问:
How can I initialize array of structs to global in c?

I want to make struct global I tried something but I got an error.

```<code>struct data{
    int barcode;
    char product_name[50];
    char category[50];
    float price;
};

void printer(){
    struct data *data1=(struct data*)malloc(sizeof(struct data));
}

int main()
{
    struct data *data1=(struct data*)malloc(sizeof(struct data));
    return 0;
}
</code>```

"error:initializer element is not constant"

```<code>struct data{
    int barcode;
    char product_name[50];
    char category[50];
    float price;
};
struct data *data1=(struct data*)malloc(sizeof(struct data));
</code>```

答:
You can't call malloc outside a function context. If you want a single structure, declare it as a global variable. If you want multiple structures, make an array.

```<code>struct data data1;
struct data dataN[12];
</code>```

Body:
I want to make struct global I tried something but I got an error.

struct data{
    int barcode;
    char product_name[50];
    char category[50];
    float price;
};

void printer(){
    struct data *data1=(struct data*)malloc(sizeof(struct data));
}

int main()
{
    struct data *data1=(struct data*)malloc(sizeof(struct data));
    return 0;
}

"error:initializer element is not constant"

struct data{
    int barcode;
    char product_name[50];
    char category[50];
    float price;
};
struct data *data1=(struct data*)malloc(sizeof(struct data));

Body:
You can't call malloc outside a function context. If you want a single structure, declare it as a global variable. If you want multiple structures, make an array.

struct data data1;
struct data dataN[12];


来源: stackexchange

问:
Generate K matrix for 2-way ANOVA with interaction Tukey analysis with multcomp::glht()
I am trying to figure out how to implement a simultaneous inference for generalised linear models via the multcomp::glht() function. Specifically, I'd like to run a complete Tukey analysis for the 2-way ANOVA example from here. They carry out a Tukey's posthoc analysis for the model with interaction.

mod <- lm(breaks ~ wool * tension, data = warpbreaks)

wool is a 2-level factor (A, B)

tension is a 3-level factor (L, M, H)

In the vignette's example they check the differences in means for the tension levels within each wool level. However I am interested in learning how to look for differences between every possible combination of levels.
Following the example, with a code like this:

```<code>tmp <- expand.grid(tension = unique(warpbreaks$tension),
                    wool = unique(warpbreaks$wool))
X <- model.matrix(~ wool * tension, data = tmp)
glht(mod, linfct = X)
Tukey <- contrMat(table(warpbreaks$tension), "Tukey")
K1 <- cbind(Tukey, matrix(0, nrow = nrow(Tukey), ncol = ncol(Tukey)))
rownames(K1) <- paste(levels(warpbreaks$wool)[1], rownames(K1), sep = ":")
K2 <- cbind(matrix(0, nrow = nrow(Tukey), ncol = ncol(Tukey)), Tukey)
rownames(K2) <- paste(levels(warpbreaks$wool)[2], rownames(K2), sep = ":")
K <- rbind(K1, K2)
colnames(K) <- c(colnames(Tukey), colnames(Tukey))
summary(glht(mod, linfct = K %*% X))
</code>```

they get something like bellow:

```<code>Simultaneous Tests for General Linear Hypotheses

Fit: lm(formula = breaks ~ wool * tension, data = warpbreaks)

Linear Hypotheses:
             Estimate Std. Error t value Pr(>|t|)
A:M - L == 0 -20.5556     5.1573  -3.986  0.00131 **
A:H - L == 0 -20.0000     5.1573  -3.878  0.00187 **
A:H - M == 0   0.5556     5.1573   0.108  0.99996
B:M - L == 0   0.5556     5.1573   0.108  0.99996
B:H - L == 0  -9.4444     5.1573  -1.831  0.30795
B:H - M == 0 -10.0000     5.1573  -1.939  0.25535
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
(Adjusted p values reported -- single-step method)
</code>```

So, how could I get the right contrast matrix so that I make comparisons like:

A:M - B:M == 0

A:M - B:H == 0

I know how the contrast matrix K should be, so I could work it out manually. However this is just an example to grow familiar with the package. My real ANOVA has a 5 level factor and another 10 level factor, so doing it manually would be such a pain.
Thanks

答:
I have found a solution by means of emmeans package. The function lsm appears to do what I was looking for. In particular:

```<code>library(emmeans)        # for lsm
model_glht <- glht(mod1, lsm(pairwise ~ wool : tension), by = NULL)
summary(model_glht)
</code>```

I finally get the wanted comparisons:

```<code>     Simultaneous Tests for General Linear Hypotheses

Fit: lm(formula = breaks ~ wool * tension, data = warpbreaks)

Linear Hypotheses:
               Estimate Std. Error t value Pr(>|t|)
A,L - B,L == 0  16.3333     6.4767   2.522   0.1285
A,L - A,M == 0  20.5556     6.3052   3.260   0.0216 *
A,L - B,M == 0  15.7778     6.4135   2.460   0.1465
A,L - A,H == 0  20.0000     6.5399   3.058   0.0369 *
A,L - B,H == 0  25.7778     5.8918   4.375   <0.001 ***
B,L - A,M == 0   4.2222     4.1239   1.024   0.9002
B,L - B,M == 0  -0.5556     4.2877  -0.130   1.0000
B,L - A,H == 0   3.6667     4.4746   0.819   0.9591
B,L - B,H == 0   9.4444     3.4589   2.730   0.0809 .
A,M - B,M == 0  -4.7778     4.0239  -1.187   0.8294
A,M - A,H == 0  -0.5556     4.2225  -0.132   1.0000
A,M - B,H == 0   5.2222     3.1261   1.671   0.5384
B,M - A,H == 0   4.2222     4.3826   0.963   0.9210
B,M - B,H == 0  10.0000     3.3391   2.995   0.0431 *
A,H - B,H == 0   5.7778     3.5759   1.616   0.5738
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
(Adjusted p values reported -- single-step method)
</code>```

Yet, after so much working on the vignettes I am still curious about finding a K matrix by  means of base or glht tools. Anyone knows how to?

Thank you

ContentLicense: CC BY-SA 4.0

Body:
I am trying to figure out how to implement a simultaneous inference for generalised linear models via the multcomp::glht() function. Specifically, I'd like to run a complete Tukey analysis for the 2-way ANOVA example from here. They carry out a Tukey's posthoc analysis for the model with interaction.

mod <- lm(breaks ~ wool * tension, data = warpbreaks)

wool is a 2-level factor (A, B)

tension is a 3-level factor (L, M, H)

In the vignette's example they check the differences in means for the tension levels within each wool level. However I am interested in learning how to look for differences between every possible combination of levels.
Following the example, with a code like this:

tmp <- expand.grid(tension = unique(warpbreaks$tension),
                    wool = unique(warpbreaks$wool))
X <- model.matrix(~ wool * tension, data = tmp)
glht(mod, linfct = X)
Tukey <- contrMat(table(warpbreaks$tension), "Tukey")
K1 <- cbind(Tukey, matrix(0, nrow = nrow(Tukey), ncol = ncol(Tukey)))
rownames(K1) <- paste(levels(warpbreaks$wool)[1], rownames(K1), sep = ":")
K2 <- cbind(matrix(0, nrow = nrow(Tukey), ncol = ncol(Tukey)), Tukey)
rownames(K2) <- paste(levels(warpbreaks$wool)[2], rownames(K2), sep = ":")
K <- rbind(K1, K2)
colnames(K) <- c(colnames(Tukey), colnames(Tukey))
summary(glht(mod, linfct = K %*% X))

they get something like bellow:

Simultaneous Tests for General Linear Hypotheses

Fit: lm(formula = breaks ~ wool * tension, data = warpbreaks)

Linear Hypotheses:
             Estimate Std. Error t value Pr(>|t|)
A:M - L == 0 -20.5556     5.1573  -3.986  0.00131 **
A:H - L == 0 -20.0000     5.1573  -3.878  0.00187 **
A:H - M == 0   0.5556     5.1573   0.108  0.99996
B:M - L == 0   0.5556     5.1573   0.108  0.99996
B:H - L == 0  -9.4444     5.1573  -1.831  0.30795
B:H - M == 0 -10.0000     5.1573  -1.939  0.25535
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
(Adjusted p values reported -- single-step method)

So, how could I get the right contrast matrix so that I make comparisons like:

A:M - B:M == 0

A:M - B:H == 0

I know how the contrast matrix K should be, so I could work it out manually. However this is just an example to grow familiar with the package. My real ANOVA has a 5 level factor and another 10 level factor, so doing it manually would be such a pain.
Thanks

Body:
I have found a solution by means of emmeans package. The function lsm appears to do what I was looking for. In particular:

library(emmeans)        # for lsm
model_glht <- glht(mod1, lsm(pairwise ~ wool : tension), by = NULL)
summary(model_glht)

I finally get the wanted comparisons:

     Simultaneous Tests for General Linear Hypotheses

Fit: lm(formula = breaks ~ wool * tension, data = warpbreaks)

Linear Hypotheses:
               Estimate Std. Error t value Pr(>|t|)
A,L - B,L == 0  16.3333     6.4767   2.522   0.1285
A,L - A,M == 0  20.5556     6.3052   3.260   0.0216 *
A,L - B,M == 0  15.7778     6.4135   2.460   0.1465
A,L - A,H == 0  20.0000     6.5399   3.058   0.0369 *
A,L - B,H == 0  25.7778     5.8918   4.375   <0.001 ***
B,L - A,M == 0   4.2222     4.1239   1.024   0.9002
B,L - B,M == 0  -0.5556     4.2877  -0.130   1.0000
B,L - A,H == 0   3.6667     4.4746   0.819   0.9591
B,L - B,H == 0   9.4444     3.4589   2.730   0.0809 .
A,M - B,M == 0  -4.7778     4.0239  -1.187   0.8294
A,M - A,H == 0  -0.5556     4.2225  -0.132   1.0000
A,M - B,H == 0   5.2222     3.1261   1.671   0.5384
B,M - A,H == 0   4.2222     4.3826   0.963   0.9210
B,M - B,H == 0  10.0000     3.3391   2.995   0.0431 *
A,H - B,H == 0   5.7778     3.5759   1.616   0.5738
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
(Adjusted p values reported -- single-step method)

Yet, after so much working on the vignettes I am still curious about finding a K matrix by  means of base or glht tools. Anyone knows how to?

Thank you


问:
How to allow visitors to add new markers in Openlayers or Leaflet
I'm working on an open mapping project and am trying to create a map that would enable website visitors to add markers to the map with some info input fields (markers would be visible by all after approved).

I discovered OpenLayers and Leaflet which both seem promising, and spent some time putting together basic maps, but after a lot of searching I've been unable to find anything on allowing visitors to add new markers to maps made with these two tools. Anyone know if this is possible ~~ or if there's another open source tool that would work better for this application? I'm solid in HTML//CSS and know basics of JQUERY - but am not well versed in javascript so if there are more plug-n-play tools thats preferred, but if not I'm willing to do the work to learn...

Thanks!

答:
you need in LEAFLET but this solution is in NUXTjs add this to you code:

@dblclick to you event method and get new lat al lng points to store in database o do something:

```<code><div id="map-wrap" style="height: 100vh">
    <no-ssr>
      <l-map :zoom="13" :center="[-16.5002, -68.1493]" @dblclick="newMarkerbyClient">
        <l-tile-layer
          url="https://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png"
        ></l-tile-layer>
        <l-marker :lat-lng="[xPosition, yPosition]"></l-marker>
      </l-map>
    </no-ssr>
  </div>
</code>```

and you script

```<code>data() {
  return {
    xPosition: -16.5002,
    yPosition: -68.1493,
  }
},
methods: {
  newMarkerbyClient(e) {
    console.log("x: " + e.latlng.lat + " y:" + e.latlng.lng);
    this.xPosition = e.latlng.lat;
    this.yPosition = e.latlng.lng;
    //xPosition and yPosition are you new point provided by client and you can do anything with this
  }
}
</code>```

Regards from BOLIVIA

ContentLicense: CC BY-SA 3.0

Body:
you need in LEAFLET but this solution is in NUXTjs add this to you code:

@dblclick to you event method and get new lat al lng points to store in database o do something:

<div id="map-wrap" style="height: 100vh">
    <no-ssr>
      <l-map :zoom="13" :center="[-16.5002, -68.1493]" @dblclick="newMarkerbyClient">
        <l-tile-layer
          url="https://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png"
        ></l-tile-layer>
        <l-marker :lat-lng="[xPosition, yPosition]"></l-marker>
      </l-map>
    </no-ssr>
  </div>

and you script

data() {
  return {
    xPosition: -16.5002,
    yPosition: -68.1493,
  }
},
methods: {
  newMarkerbyClient(e) {
    console.log("x: " + e.latlng.lat + " y:" + e.latlng.lng);
    this.xPosition = e.latlng.lat;
    this.yPosition = e.latlng.lng;
    //xPosition and yPosition are you new point provided by client and you can do anything with this
  }
}

Regards from BOLIVIA


问:
AttributeError: 'NoneType' object has no attribute 'next' and Function missing 2 required positional arguments: 'x' and 'y'
I am trying to write a program to insert a node at a specific position and the errors I am getting are,

```<code>AttributeError: 'NoneType' object has no attribute 'next'
</code>```

and also

```<code>Function missing 2 required positional arguments: 'x' and 'y'
</code>```

Code:

class SinglyLinkedListNode:
    def __init__(self, data):
        self.data = data
        self.next = None

class SinglyLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None

    def insertnode_end(self, data):
        node = SinglyLinkedListNode(data)

        if not self.head:
            self.head = node
        else:
            self.tail.next = node

        self.tail = node

    def print_ll(self):

        temp = self.head
        while temp is not None:
            print(temp.data, end=" ")
            temp = temp.next

    def insertNode_pos(self, data, pos):
        new_node = SinglyLinkedListNode(data)
        if (pos == 0):
            new_node.next = self.head
            self.head = new_node

        temp = self.head
        while temp.next is not None:
            for _ in range(pos - 1):
                temp = temp.next
            new_node.next = temp.next
            temp.next = new_node

llist_count = int(input())
llist = SinglyLinkedList()

for _ in range(llist_count):
    llist_item = int(input())
    llist.insertnode_end(llist_item)

data = int(input())
pos = int(input())

llist.insertNode_pos(data, pos)

llist.print_ll()
```

答:
I don't see x and y in your code. It is helpful if you include the full traceback. It seems that your function is hitting the last node in the list, whose next item is None. Obviously, None doesn't have the next and data attributes.

Meanwhile, I modified your insertNode_pos function. One important line here is return if pos == 0. Your function doesn't need to continue in that case.

```<code> def insertNode_pos(self, data, pos):
    new_node = SinglyLinkedListNode(data)
    if pos == 0:
        new_node.next = self.head
        self.head = new_node
        return

    temp = self.head
    for iter in range(pos):
        if iter == 0:
            temp = self.head
        else:
            temp = temp.next
    new_node.next = temp.next
    temp.next = new_node
</code>```

One more note is that implementing __str__ is a more common practice for printing content of your data:

```<code>def __str__(self):
    output = []
    temp = self.head
    while temp is not None:
        output.append(str(temp.data))
        temp = temp.next
    return ",".join(output)
</code>```

Then you can simply say print(llist)

Body:
I am trying to write a program to insert a node at a specific position and the errors I am getting are,

AttributeError: 'NoneType' object has no attribute 'next'

and also

Function missing 2 required positional arguments: 'x' and 'y'

Code:

class SinglyLinkedListNode:
    def __init__(self, data):
        self.data = data
        self.next = None

class SinglyLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None

    def insertnode_end(self, data):
        node = SinglyLinkedListNode(data)

        if not self.head:
            self.head = node
        else:
            self.tail.next = node

        self.tail = node

    def print_ll(self):

        temp = self.head
        while temp is not None:
            print(temp.data, end=" ")
            temp = temp.next

    def insertNode_pos(self, data, pos):
        new_node = SinglyLinkedListNode(data)
        if (pos == 0):
            new_node.next = self.head
            self.head = new_node

        temp = self.head
        while temp.next is not None:
            for _ in range(pos - 1):
                temp = temp.next
            new_node.next = temp.next
            temp.next = new_node

llist_count = int(input())
llist = SinglyLinkedList()

for _ in range(llist_count):
    llist_item = int(input())
    llist.insertnode_end(llist_item)

data = int(input())
pos = int(input())

llist.insertNode_pos(data, pos)

llist.print_ll()

Body:
I don't see x and y in your code. It is helpful if you include the full traceback. It seems that your function is hitting the last node in the list, whose next item is None. Obviously, None doesn't have the next and data attributes.

Meanwhile, I modified your insertNode_pos function. One important line here is return if pos == 0. Your function doesn't need to continue in that case.

 def insertNode_pos(self, data, pos):
    new_node = SinglyLinkedListNode(data)
    if pos == 0:
        new_node.next = self.head
        self.head = new_node
        return

    temp = self.head
    for iter in range(pos):
        if iter == 0:
            temp = self.head
        else:
            temp = temp.next
    new_node.next = temp.next
    temp.next = new_node

One more note is that implementing __str__ is a more common practice for printing content of your data:

def __str__(self):
    output = []
    temp = self.head
    while temp is not None:
        output.append(str(temp.data))
        temp = temp.next
    return ",".join(output)

Then you can simply say print(llist)


问:
call() is not working with getter and setter in javascript

let Name = {
   get fullname() {
        return this.fname + this.last
    }
}

function pension() {
    return this.age > 60
}
let firstclass_employee = [{
    fname: "sangeth",
    last: "AV",
    age: 21,
    address: {
        housename: "good house",
        place: "goodplace",
        city: "goodtwon",
        postcode: 121212
    },
    hobbies: ["driving", "travelling", "sports"]
}, {
    fname: "ramu",
    last: "kv",
    age: 29,
    address: {
        housename: "etho veedu",
        place: "vayadi",
        city: "kalur",
        postcode: 11111
    },
    hobbies: ["travelling", "sports"]
}]
console.log(" objects::\t", Name, "\n", firstclass_employee)
    //calling a out side function for an object(out side function may be inside an object oe not)
console.log("Fullname of first employee::", Name.fullname.call(firstclass_employee[0]))
console.log("Pension status of of first emlpoyee::", pension.call(firstclass_employee[0]))
console.log("Fullname of 2nd employee::", Name.fullname.call(firstclass_employee[1]))
console.log("Pension status of of 2nd emlpoyee::", pension.call(firstclass_employee[1]))```

AND getting error--->
console.log("Fullname of first employee::", Name.fullname.call(firstclass_employee[0]))
                                                          ^

TypeError: Name.fullname.call is not a function

答:
As far as why the call() is invalid is that Name.fullname is not exposed as a function. It is exposed the same way as a field would be, e.g.

```<code>const Name = {
  fullname: 'Bob'
};
</code>```

With that structure, you wouldn't expect to be able to call Name.fullname.call, right? But for the purposes of getting the value, that's what the prior code exposed to the outside world (the difference with the field being that you can set the value, whereas with a getter and no setter, the property is read only).

The get essentially tells the JavaScript engine that, whenever someone asks for the value of fullname, give them the value of the fname and last properties concatenated together.

Thus, when you ask for Name.fullname.call(firstclass_employee[0]) it first finds Name. Then it asks for the value of fullname. It gets back NaN, because this is the Name object and it doesn't have fname or last properties, and it tries to coerce the first undefined (from this.fname) to a Number for the addition operator, and gets NaN. Then it tries to get the call function on NaN, and there is no such thing, so it throws an error.

It appears as though you want to be able to get a full name from any object that has fname and last properties. I would suggest using static method for that rather than an instance property getter.

Similarly, a static method would work for determining employees who get a pension.

Personally, I would just create a class or series of classes that I could compose together to bring this functionality together, rather than trying to use call, but that's me.

const Name = {
  fullName(obj) {
    return `${obj.fname} ${obj.last}`;
  }
};

const Pay = {
  getsPension(obj) {
    return obj.age > 60;
  }
}

let firstclass_employee = [{
   fname: "sangeth",
   last: "AV",
   age: 21,
   address: {
       housename: "good house",
       place: "goodplace",
       city: "goodtwon",
       postcode: 121212
   },
   hobbies: ["driving", "travelling", "sports"]
}, {
   fname: "ramu",
   last: "kv",
   age: 29,
   address: {
       housename: "etho veedu",
       place: "vayadi",
       city: "kalur",
       postcode: 11111
   },
   hobbies: ["travelling", "sports"]
}]
console.log('should be sangeth AV: ', Name.fullName(firstclass_employee[0]));
console.log('should be false:      ', Pay.getsPension(firstclass_employee[0]));```

Body:
let Name = {
   get fullname() {
        return this.fname + this.last
    }
}

function pension() {
    return this.age > 60
}
let firstclass_employee = [{
    fname: "sangeth",
    last: "AV",
    age: 21,
    address: {
        housename: "good house",
        place: "goodplace",
        city: "goodtwon",
        postcode: 121212
    },
    hobbies: ["driving", "travelling", "sports"]
}, {
    fname: "ramu",
    last: "kv",
    age: 29,
    address: {
        housename: "etho veedu",
        place: "vayadi",
        city: "kalur",
        postcode: 11111
    },
    hobbies: ["travelling", "sports"]
}]
console.log(" objects::\t", Name, "\n", firstclass_employee)
    //calling a out side function for an object(out side function may be inside an object oe not)
console.log("Fullname of first employee::", Name.fullname.call(firstclass_employee[0]))
console.log("Pension status of of first emlpoyee::", pension.call(firstclass_employee[0]))
console.log("Fullname of 2nd employee::", Name.fullname.call(firstclass_employee[1]))
console.log("Pension status of of 2nd emlpoyee::", pension.call(firstclass_employee[1]))

AND getting error--->
console.log("Fullname of first employee::", Name.fullname.call(firstclass_employee[0]))
                                                          ^

TypeError: Name.fullname.call is not a function

Body:
As far as why the call() is invalid is that Name.fullname is not exposed as a function. It is exposed the same way as a field would be, e.g.

const Name = {
  fullname: 'Bob'
};

With that structure, you wouldn't expect to be able to call Name.fullname.call, right? But for the purposes of getting the value, that's what the prior code exposed to the outside world (the difference with the field being that you can set the value, whereas with a getter and no setter, the property is read only).

The get essentially tells the JavaScript engine that, whenever someone asks for the value of fullname, give them the value of the fname and last properties concatenated together.

Thus, when you ask for Name.fullname.call(firstclass_employee[0]) it first finds Name. Then it asks for the value of fullname. It gets back NaN, because this is the Name object and it doesn't have fname or last properties, and it tries to coerce the first undefined (from this.fname) to a Number for the addition operator, and gets NaN. Then it tries to get the call function on NaN, and there is no such thing, so it throws an error.

It appears as though you want to be able to get a full name from any object that has fname and last properties. I would suggest using static method for that rather than an instance property getter.

Similarly, a static method would work for determining employees who get a pension.

Personally, I would just create a class or series of classes that I could compose together to bring this functionality together, rather than trying to use call, but that's me.

const Name = {
  fullName(obj) {
    return `${obj.fname} ${obj.last}`;
  }
};

const Pay = {
  getsPension(obj) {
    return obj.age > 60;
  }
}

let firstclass_employee = [{
   fname: "sangeth",
   last: "AV",
   age: 21,
   address: {
       housename: "good house",
       place: "goodplace",
       city: "goodtwon",
       postcode: 121212
   },
   hobbies: ["driving", "travelling", "sports"]
}, {
   fname: "ramu",
   last: "kv",
   age: 29,
   address: {
       housename: "etho veedu",
       place: "vayadi",
       city: "kalur",
       postcode: 11111
   },
   hobbies: ["travelling", "sports"]
}]
console.log('should be sangeth AV: ', Name.fullName(firstclass_employee[0]));
console.log('should be false:      ', Pay.getsPension(firstclass_employee[0]));


问:
My C++ class is having trouble linking to a function in another .cpp file
I asked the same question yesterday and the answer was not applicable.

https://stackoverflow.com/questions/6194578/breaking-up-class-functions-into-multiple-cpp-files

If I go into the class header, right click on the function and click "Go to Definition" and it takes me right to my function in my other .CPP file. It sees it, can link to it and still I get errors that indicate I cannot see it.

Anyone have any suggestions? I'll try anything.

Here is the error again.

zdll.lib(d000050.o) : warning LNK4078: multiple '.text' sections found with different     attributes (E0300020)

WLD.obj : error LNK2019: unresolved external symbol "public: void __thiscall  WLD::fragment_03(unsigned char *,int)" (?fragment_03@WLD@@QAEXPAEH@Z) referenced in function "public: bool __thiscall WLD::init(unsigned char *)" (?init@WLD@@QAE_NPAE@Z)

Edit: Also, I am using MSVC++. Should I try creating a new solution and importing the files? May help as I feel I am out of options...

Edit: Here is the code:

```<code>#include "WLD.h"

inline void WLD::fragment_03(uchar* location, int frag_num)
{
    // Read the struct into memory and create a temporary pointer
    struct_frag03 temp03;
    memcpy(&temp03, location, sizeof(struct_frag03));
    uchar* temp_p = location;

    // Advance the pointer to the encoded bytes (filename)
    temp_p += sizeof(long) + sizeof(short);

    // Grab the encoded filename and decode it
    uchar* f_filename = new uchar [sizeof(temp03.nameLen + 1)];
    memcpy(f_filename, temp_p, temp03.nameLen + 1);
    decode(f_filename, temp03.nameLen);

    // Add the details about this bitmap to the array
    bmp_array[current_bmp].filename = f_filename;
    bmp_array[current_bmp].nameLength = temp03.nameLen;
    bmp_array[current_bmp].reference03 = frag_num;

    // 0x03 Debug
    //errorLog.OutputSuccess("0x03 Filename: %s", bmp_array[current_bmp].filename);
    //errorLog.OutputSuccess("0x03 Name length: %i",bmp_array[current_bmp].nameLength);
    //errorLog.OutputSuccess("0x03 Reference: %i", bmp_array[current_bmp].reference03);

    // Add the bitmap to the count
    current_bmp++;
}
</code>```

And here is where the code is called in the WLD class:

```<code>case 0x03:
    fragment_03(wld + file_pos + sizeof(struct_wld_basic_frag), i);
    break;
</code>```

Here is the header file declaration: in (WLD.h):

```<code>public:
    inline void fragment_03(uchar* location, int frag_num);
</code>```

答:
inline means that the function effectively has internal linkage (that is, it must exist inside the translation unit where it is used). Either move the definition of the function into the header, or remove inline.

(inline for modern compilers really means "use internal linkage" -- compilers will inline where it makes sense to by themselves, and they typically make better decisions than humans)

EDIT: Technically speaking, the language the standard uses here says that inline functions have external linkage; however, it also says An inline function shall be defined in every translation unit in which it is used. in section 3.2 paragraph #3 of the standard, and also There can be more than one definition of a ... inline function
with external linkage (7.1.2) ... Given such an entity named D defined in more than one translation unit ... each definition of D shall consist of the same sequence of tokens in paragraph 5. So while technically speaking the name you declared inline is accessible from outside a given translation unit, to do so is to cause undefined behavior from C++.

Body:
I asked the same question yesterday and the answer was not applicable.

https://stackoverflow.com/questions/6194578/breaking-up-class-functions-into-multiple-cpp-files

If I go into the class header, right click on the function and click "Go to Definition" and it takes me right to my function in my other .CPP file. It sees it, can link to it and still I get errors that indicate I cannot see it.

Anyone have any suggestions? I'll try anything.

Here is the error again.

zdll.lib(d000050.o) : warning LNK4078: multiple '.text' sections found with different     attributes (E0300020)

WLD.obj : error LNK2019: unresolved external symbol "public: void __thiscall  WLD::fragment_03(unsigned char *,int)" (?fragment_03@WLD@@QAEXPAEH@Z) referenced in function "public: bool __thiscall WLD::init(unsigned char *)" (?init@WLD@@QAE_NPAE@Z)

Edit: Also, I am using MSVC++. Should I try creating a new solution and importing the files? May help as I feel I am out of options...

Edit: Here is the code:

#include "WLD.h"

inline void WLD::fragment_03(uchar* location, int frag_num)
{
    // Read the struct into memory and create a temporary pointer
    struct_frag03 temp03;
    memcpy(&temp03, location, sizeof(struct_frag03));
    uchar* temp_p = location;

    // Advance the pointer to the encoded bytes (filename)
    temp_p += sizeof(long) + sizeof(short);

    // Grab the encoded filename and decode it
    uchar* f_filename = new uchar [sizeof(temp03.nameLen + 1)];
    memcpy(f_filename, temp_p, temp03.nameLen + 1);
    decode(f_filename, temp03.nameLen);

    // Add the details about this bitmap to the array
    bmp_array[current_bmp].filename = f_filename;
    bmp_array[current_bmp].nameLength = temp03.nameLen;
    bmp_array[current_bmp].reference03 = frag_num;

    // 0x03 Debug
    //errorLog.OutputSuccess("0x03 Filename: %s", bmp_array[current_bmp].filename);
    //errorLog.OutputSuccess("0x03 Name length: %i",bmp_array[current_bmp].nameLength);
    //errorLog.OutputSuccess("0x03 Reference: %i", bmp_array[current_bmp].reference03);

    // Add the bitmap to the count
    current_bmp++;
}

And here is where the code is called in the WLD class:

case 0x03:
    fragment_03(wld + file_pos + sizeof(struct_wld_basic_frag), i);
    break;

Here is the header file declaration: in (WLD.h):

public:
    inline void fragment_03(uchar* location, int frag_num);


问:
I made my own custom stack and want to know how is there a way to iterate through the stack in reverse
This is the interface file

```<code>#ifndef STACK_H
#define STACH_H
#include<iostream>
using namespace std;

class Stack
{
    struct StackFrame{
        char data;
        StackFrame* next;
    };
    StackFrame* head;
public:
    Stack();
    void push(char);
    char pop();
    void empty();
    bool check_empty();
    void print();
    //Note:This code prints the data in stack format !!!
    ~Stack();
};

#endif // !STACK_H
</code>```

This is the implementation file

```<code>#include "Stack.h"

Stack::Stack():head(nullptr){}

void Stack::push(char c)
{
    StackFrame* temp = new  StackFrame;
    temp->data = c;
    temp->next = nullptr;

    if (head == nullptr)
    {
        head = temp;
        return;
    }

    temp->next = head;
    head = temp;
}

char Stack::pop()
{
    if (head == nullptr)
    {
        cerr << "There is nothing in the stack to pop at the moment!!!" << endl;
        return '\0';
    }

    StackFrame* holder = head;
    char temp_chr = holder->data;

    head = head->next;
    free(holder);
    holder = nullptr;

    return temp_chr;
}

void Stack::empty()
{
    StackFrame* holder;
    while(head!=nullptr)
    {
        holder = head;
        head = head->next;
        free(holder);
    }
    holder = nullptr;
    head = nullptr;
}

bool Stack::check_empty()
{
    return head==nullptr;
}

void Stack::print() {
    if (head == nullptr)
    {
        cerr << "Nothing in stack at the moment :( " << endl;
        return;
    }

    StackFrame* holder = head;
    while (holder != nullptr)
    {
        cout << holder->data;
        holder = holder->next;
    }
    cout << endl;
}

Stack::~Stack()
{
    empty();
}
</code>```

This is the application file

```<code>#include"Stack.h"
#include<string>

int main()
{
    int num;
    string push;
    Stack st;
    cout << "Enter your name = ";
    getline(cin, push);
    for (int i = 0; i < push.length(); i++)
    {
        st.push(push[i]);
    }
    st.print();

    cout << "How many times do you want to pop? = ";
    cin >> num;
    for (int i = 0; i < num; i++)
    {
        st.pop();
    }
    st.print();
    return EXIT_SUCCESS;
}

</code>```

Can someone help me out on how to reverse iterate in this stack class which i made myself using the concept of linked list, i googled a bit and got the gist of things to use tail , Can someone elaborate another way if possible please or share a link to a site. It will help me out later a lot when i start working on binary trees and if i ever need to reverse iterate in the binary tree nodes.

答:
Recursive algorithm would have worked fine (use the recursive call stack as your "reverse" stack).</p>

```<code>void Stack::print(StackFrame *pCurr) {
    if (pCurr != nullptr)
        {
        print(pCurr->Next);
        cout << pCurr->ch;
        }
    }

void Stack::print() {
    if (head == nullptr)
        {
        cerr << "Nothing in stack at the moment :( " << endl;
        return;
        }
    print(head);
    cout << endl;
    }
</code>```

Body:
This is the interface file

#ifndef STACK_H
#define STACH_H
#include<iostream>
using namespace std;

class Stack
{
    struct StackFrame{
        char data;
        StackFrame* next;
    };
    StackFrame* head;
public:
    Stack();
    void push(char);
    char pop();
    void empty();
    bool check_empty();
    void print();
    //Note:This code prints the data in stack format !!!
    ~Stack();
};

#endif // !STACK_H

This is the implementation file

#include "Stack.h"

Stack::Stack():head(nullptr){}

void Stack::push(char c)
{
    StackFrame* temp = new  StackFrame;
    temp->data = c;
    temp->next = nullptr;

    if (head == nullptr)
    {
        head = temp;
        return;
    }

    temp->next = head;
    head = temp;
}

char Stack::pop()
{
    if (head == nullptr)
    {
        cerr << "There is nothing in the stack to pop at the moment!!!" << endl;
        return '\0';
    }

    StackFrame* holder = head;
    char temp_chr = holder->data;

    head = head->next;
    free(holder);
    holder = nullptr;

    return temp_chr;
}

void Stack::empty()
{
    StackFrame* holder;
    while(head!=nullptr)
    {
        holder = head;
        head = head->next;
        free(holder);
    }
    holder = nullptr;
    head = nullptr;
}

bool Stack::check_empty()
{
    return head==nullptr;
}

void Stack::print() {
    if (head == nullptr)
    {
        cerr << "Nothing in stack at the moment :( " << endl;
        return;
    }

    StackFrame* holder = head;
    while (holder != nullptr)
    {
        cout << holder->data;
        holder = holder->next;
    }
    cout << endl;
}

Stack::~Stack()
{
    empty();
}

This is the application file

#include"Stack.h"
#include<string>

int main()
{
    int num;
    string push;
    Stack st;
    cout << "Enter your name = ";
    getline(cin, push);
    for (int i = 0; i < push.length(); i++)
    {
        st.push(push[i]);
    }
    st.print();

    cout << "How many times do you want to pop? = ";
    cin >> num;
    for (int i = 0; i < num; i++)
    {
        st.pop();
    }
    st.print();
    return EXIT_SUCCESS;
}

Can someone help me out on how to reverse iterate in this stack class which i made myself using the concept of linked list, i googled a bit and got the gist of things to use tail , Can someone elaborate another way if possible please or share a link to a site. It will help me out later a lot when i start working on binary trees and if i ever need to reverse iterate in the binary tree nodes.

Body:
Recursive algorithm would have worked fine (use the recursive call stack as your "reverse" stack).

void Stack::print(StackFrame *pCurr) {
    if (pCurr != nullptr)
        {
        print(pCurr->Next);
        cout << pCurr->ch;
        }
    }

void Stack::print() {
    if (head == nullptr)
        {
        cerr << "Nothing in stack at the moment :( " << endl;
        return;
        }
    print(head);
    cout << endl;
    }


问:
How to make setState take effect immediately?
There is an input element in my code:

```<code><input id="input" className="ml-2" type="number" name="Qty" min="1" max="999" value={qty} onChange={(e) => {changeQty(e)}}/>
</code>```

And the onChange handler is:

```<code>    const changeQty = (e) => {
        setQty(e.target.value);
        console.log(qty);
    }
</code>```

So I suppose that whatever I enter in the input field will be printed out in the console, but the fact is there is delay.

For example, the default value is 1, then I type 2, then 1 will be printed out. Then I type 3, then 2 will be printed out. The number printed out is the previous one I entered instead of the current one, as shown below:

Could anyone tell me how to remove the delay?

I read useState set method not reflecting change immediately, but still cannot solve it.

I tried the code below as the answer indicates,

```<code>useEffect(() => {
    setQty(document.getElementById("input").value)
}, [qty]);
</code>```

but an error ReferenceError: Cannot access 'qty' before initialization occurred.

Thanks!

答:
It's hard to say from the current question, but I'm going to assume that you're writing a function component and are using a useState hook. That is, somewhere above the changeQty you have something like:

```<code>const [qty, setQty] = useState(0);
</code>```

If that's the case, then the answer is directly in the assignment of qty above. qty is set when you call the useState hook and will not change for the duration of the execution.

setQty does not update the value of qty. It updates the internal state, which will trigger a re-render. That means the next time your render function is invoked, qty will have the value you used.

But for the rest of the execution of the function, qty will remain whatever value it was when useState was called.

If you need the new value of qty in the same iteration of your function, you can capture that as a new variable.

```<code>const [qty, setQty] = useState(0);
let updatedQty = qty;

const changeQty = (e) => {
  updatedQty = e.target.value;
  setQty(updatedQty);
  console.log(updatedQty);
}
</code>```

Body:
There is an input element in my code:

<input id="input" className="ml-2" type="number" name="Qty" min="1" max="999" value={qty} onChange={(e) => {changeQty(e)}}/>

And the onChange handler is:

    const changeQty = (e) => {
        setQty(e.target.value);
        console.log(qty);
    }

So I suppose that whatever I enter in the input field will be printed out in the console, but the fact is there is delay.

For example, the default value is 1, then I type 2, then 1 will be printed out. Then I type 3, then 2 will be printed out. The number printed out is the previous one I entered instead of the current one, as shown below:

Could anyone tell me how to remove the delay?

I read useState set method not reflecting change immediately, but still cannot solve it.

I tried the code below as the answer indicates,

useEffect(() => {
    setQty(document.getElementById("input").value)
}, [qty]);

but an error ReferenceError: Cannot access 'qty' before initialization occurred.

Thanks!

Body:
It's hard to say from the current question, but I'm going to assume that you're writing a function component and are using a useState hook. That is, somewhere above the changeQty you have something like:

const [qty, setQty] = useState(0);

If that's the case, then the answer is directly in the assignment of qty above. qty is set when you call the useState hook and will not change for the duration of the execution.

setQty does not update the value of qty. It updates the internal state, which will trigger a re-render. That means the next time your render function is invoked, qty will have the value you used.

But for the rest of the execution of the function, qty will remain whatever value it was when useState was called.

If you need the new value of qty in the same iteration of your function, you can capture that as a new variable.

const [qty, setQty] = useState(0);
let updatedQty = qty;

const changeQty = (e) => {
  updatedQty = e.target.value;
  setQty(updatedQty);
  console.log(updatedQty);
}


问:
Can i save a screenshot taken from netbeans to Mysql
I am doing a project in which i decided to save screenshot of the bill to mysql database. But the ImageIcon used to take the screenshot does not provide the length of file so, the setBinaryStream() isn't working, i have tried pstmt.setBlob (1, (BLOB)icon), still not working.

Can you save the taken screenshot directly to database, if so please tell me.
Or can i create and save custom bills in netbeans.

```<code>try
{
    Rectangle screen = new Rectangle (Toolkit.getDefaultToolkit().getScreenSize());
    BufferedImage capture = new Robot().createScreenCapture(screen);
    ImageIcon icon = new ImageIcon(capture);
    int len = icon.getWidth();
    ImageIO.write(capture,"jpg",new File("screenshot.jpg"));

        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Sign_up.class.getName()).log(Level.SEVERE, null, ex);
        }
        try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/webapp","root","")) {
            Statement at = con.createStatement();
            String qt = "insert into picture (Pictures) values (?)";
            PreparedStatement pstmt = con.prepareStatement(qt);
            pstmt.setBinaryStream (icon,);

}
</code>```

答: Maybe instead of saving the image data directly to the database (not recommended) save the file somewhere (like a remote file hosting service). Then in the SQL statement save the link of the file. </p>

Body:
I am doing a project in which i decided to save screenshot of the bill to mysql database. But the ImageIcon used to take the screenshot does not provide the length of file so, the setBinaryStream() isn't working, i have tried pstmt.setBlob (1, (BLOB)icon), still not working.

Can you save the taken screenshot directly to database, if so please tell me.
Or can i create and save custom bills in netbeans.

try
{
    Rectangle screen = new Rectangle (Toolkit.getDefaultToolkit().getScreenSize());
    BufferedImage capture = new Robot().createScreenCapture(screen);
    ImageIcon icon = new ImageIcon(capture);
    int len = icon.getWidth();
    ImageIO.write(capture,"jpg",new File("screenshot.jpg"));

        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Sign_up.class.getName()).log(Level.SEVERE, null, ex);
        }
        try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/webapp","root","")) {
            Statement at = con.createStatement();
            String qt = "insert into picture (Pictures) values (?)";
            PreparedStatement pstmt = con.prepareStatement(qt);
            pstmt.setBinaryStream (icon,);

}


问:
How can I create a new variable for seasons from a date-variable?
I have a dataframe of comments where one column df$date corresponds to the dates when the comment was made, expressed as shown below:

```<code>[1] "2019-06-01" "2019-07-01" "2019-10-01" "2019-10-01" "2019-09-01" "2019-04-01" "2019-04-01" "2019-04-01" "2019-04-01"
 [10] "2019-04-01" "2018-08-01" "2018-08-01" "2018-08-01" "2018-07-01" "2018-08-01" "2018-07-01" "2018-07-01" "2018-06-01"
</code>```

I want to add a new column with the seasons. Basically, I want to say that if the date was made between December and February, then the corresponding season would be winter. I have tried the following, but it gives me: "Error: Not compatible with requested type: [type=character; target=double]."

```<code> df$season = ifelse(between(df$date,"2018-11-30", "2019-03-01"), "Invierno"
ifelse(between(df$date,"2019-02-28", "2019-06-01"),"Spring", ifelse(between(df$date,"2019-06-30", "2019-07-01"),"Summer",
"Fall")))
</code>```

Does this mean I have to reformat the date to character or is there any way I could create the seasons column using the date format?

Thanks in advance!

答:
Two things happening here. First you need to tell R that you want a date string to actually be a date using as.Date. But then once that vector is a date, you can't use ifelse anymore because that (very useful!) function doesn't play well with dates. So it is a good opportunity to introduce dplyr's case_when syntax which accomplishes the same thing but in a more readable way:

library(dplyr, warn.conflicts = FALSE)
date <- c("2019-06-01","2019-07-01","2019-10-01","2019-10-01","2019-09-01","2019-04-01","2019-04-01","2019-04-01","2019-04-01",
"2019-04-01","2018-08-01","2018-08-01","2018-08-01","2018-07-01","2018-08-01","2018-07-01","2018-07-01","2018-06-01")

df <- data.frame(date)

## first need to tell R that date is actually a date
df$date <- as.Date(df$date)

## Turns out that ifelse doesn't actually work well for dates so I'll introduce the glorious case_when function
df$season <- case_when(
  between(df$date, as.Date("2018-11-30"), as.Date("2019-03-01")) ~ "Invierno",
  between(df$date, as.Date("2019-02-28"), as.Date("2019-06-01")) ~ "Spring",
  between(df$date, as.Date("2019-06-30"), as.Date("2019-07-01")) ~ "Summer",
  TRUE ~ "Fall"
)

df
#>          date season
#> 1  2019-06-01 Spring
#> 2  2019-07-01 Summer
#> 3  2019-10-01   Fall
#> 4  2019-10-01   Fall
#> 5  2019-09-01   Fall
#> 6  2019-04-01 Spring
#> 7  2019-04-01 Spring
#> 8  2019-04-01 Spring
#> 9  2019-04-01 Spring
#> 10 2019-04-01 Spring
#> 11 2018-08-01   Fall
#> 12 2018-08-01   Fall
#> 13 2018-08-01   Fall
#> 14 2018-07-01   Fall
#> 15 2018-08-01   Fall
#> 16 2018-07-01   Fall
#> 17 2018-07-01   Fall
#> 18 2018-06-01   Fall
```

Created on 2020-05-29 by the reprex package (v0.3.0)

Body:
I have a dataframe of comments where one column df$date corresponds to the dates when the comment was made, expressed as shown below:

[1] "2019-06-01" "2019-07-01" "2019-10-01" "2019-10-01" "2019-09-01" "2019-04-01" "2019-04-01" "2019-04-01" "2019-04-01"
 [10] "2019-04-01" "2018-08-01" "2018-08-01" "2018-08-01" "2018-07-01" "2018-08-01" "2018-07-01" "2018-07-01" "2018-06-01"

I want to add a new column with the seasons. Basically, I want to say that if the date was made between December and February, then the corresponding season would be winter. I have tried the following, but it gives me: "Error: Not compatible with requested type: [type=character; target=double]."

 df$season = ifelse(between(df$date,"2018-11-30", "2019-03-01"), "Invierno"
ifelse(between(df$date,"2019-02-28", "2019-06-01"),"Spring", ifelse(between(df$date,"2019-06-30", "2019-07-01"),"Summer",
"Fall")))

Does this mean I have to reformat the date to character or is there any way I could create the seasons column using the date format?

Thanks in advance!

Body:
Two things happening here. First you need to tell R that you want a date string to actually be a date using as.Date. But then once that vector is a date, you can't use ifelse anymore because that (very useful!) function doesn't play well with dates. So it is a good opportunity to introduce dplyr's case_when syntax which accomplishes the same thing but in a more readable way:

library(dplyr, warn.conflicts = FALSE)
date <- c("2019-06-01","2019-07-01","2019-10-01","2019-10-01","2019-09-01","2019-04-01","2019-04-01","2019-04-01","2019-04-01",
"2019-04-01","2018-08-01","2018-08-01","2018-08-01","2018-07-01","2018-08-01","2018-07-01","2018-07-01","2018-06-01")

df <- data.frame(date)

## first need to tell R that date is actually a date
df$date <- as.Date(df$date)

## Turns out that ifelse doesn't actually work well for dates so I'll introduce the glorious case_when function
df$season <- case_when(
  between(df$date, as.Date("2018-11-30"), as.Date("2019-03-01")) ~ "Invierno",
  between(df$date, as.Date("2019-02-28"), as.Date("2019-06-01")) ~ "Spring",
  between(df$date, as.Date("2019-06-30"), as.Date("2019-07-01")) ~ "Summer",
  TRUE ~ "Fall"
)

df
#>          date season
#> 1  2019-06-01 Spring
#> 2  2019-07-01 Summer
#> 3  2019-10-01   Fall
#> 4  2019-10-01   Fall
#> 5  2019-09-01   Fall
#> 6  2019-04-01 Spring
#> 7  2019-04-01 Spring
#> 8  2019-04-01 Spring
#> 9  2019-04-01 Spring
#> 10 2019-04-01 Spring
#> 11 2018-08-01   Fall
#> 12 2018-08-01   Fall
#> 13 2018-08-01   Fall
#> 14 2018-07-01   Fall
#> 15 2018-08-01   Fall
#> 16 2018-07-01   Fall
#> 17 2018-07-01   Fall
#> 18 2018-06-01   Fall

Created on 2020-05-29 by the reprex package (v0.3.0)


问:
How to scroll both ways simultaneously in pageview widget in flutter?
I am using PageView for my application.
PageView has a property of scrollDirection which sets the scroll either horizontal or vertical.
code example:

```<code> Widget build(BuildContext context) {
    return PageView.builder(
        scrollDirection: Axis.horizontal,
        itemBuilder: (context, position) {
          return Container(
            color: Colors.black,
            child: Stack(
              children: <Widget>[AppVideoPlayer(), onScreenControls()],
            ),
          );
        },
        itemCount: 20);
  }
</code>```

Is there a way where PageView can be set to scroll both ways (horizontal and vertical) at the same time.
If not, then is there any way in which this can be achieved?

答:
```<code>  Widget build(BuildContext context) {
    return PageView.builder(
        scrollDirection: Axis.vertical,
        itemBuilder: (context, position) {
          return PageView.builder(
        scrollDirection: Axis.horizontal,
        itemBuilder: (context, position) {
          return Container(
            color: Colors.black,
            child: Stack(
              children: <Widget>[AppVideoPlayer(), onScreenControls()],
            ),
          );
        },
        itemCount: 20);
        },
        itemCount: 20);
  }
</code>```

Body:
I am using PageView for my application.
PageView has a property of scrollDirection which sets the scroll either horizontal or vertical.
code example:

 Widget build(BuildContext context) {
    return PageView.builder(
        scrollDirection: Axis.horizontal,
        itemBuilder: (context, position) {
          return Container(
            color: Colors.black,
            child: Stack(
              children: <Widget>[AppVideoPlayer(), onScreenControls()],
            ),
          );
        },
        itemCount: 20);
  }

Is there a way where PageView can be set to scroll both ways (horizontal and vertical) at the same time.
If not, then is there any way in which this can be achieved?


问:
Checking if float is equivalent to an integer value in python
In Python 3, I am checking whether a given value is triangular, that is, it can be represented as n * (n + 1) / 2 for some positive integer n.

Can I just write:

```<code>import math

def is_triangular1(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return int(num) == num
</code>```

Or do I need to do check within a tolerance instead?

```<code>epsilon = 0.000000000001
def is_triangular2(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return abs(int(num) - num) < epsilon
</code>```

I checked that both of the functions return same results for x up to 1,000,000. But I am not sure if generally speaking int(x) == x will always correctly determine whether a number is integer, because of the cases when for example 5 is represented as 4.99999999999997 etc.

As far as I know, the second way is the correct one if I do it in C, but I am not sure about Python 3.

答:
You can round your number to e.g. 14 decimal places or less:

```<code> >>> round(4.999999999999997, 14)
 5.0
</code>```

PS: double precision is about 15 decimal places

Body:
In Python 3, I am checking whether a given value is triangular, that is, it can be represented as n * (n + 1) / 2 for some positive integer n.

Can I just write:

import math

def is_triangular1(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return int(num) == num

Or do I need to do check within a tolerance instead?

epsilon = 0.000000000001
def is_triangular2(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return abs(int(num) - num) < epsilon

I checked that both of the functions return same results for x up to 1,000,000. But I am not sure if generally speaking int(x) == x will always correctly determine whether a number is integer, because of the cases when for example 5 is represented as 4.99999999999997 etc.

As far as I know, the second way is the correct one if I do it in C, but I am not sure about Python 3.

Body:
You can round your number to e.g. 14 decimal places or less:

 >>> round(4.999999999999997, 14)
 5.0

PS: double precision is about 15 decimal places


问:
Retrieve data between certain hours of day
I am trying to write a query to retrieve data between midnight and 7am of the current day.  I know I am on the right track but cannot get the syntax correct...</p>

```<code>SELECT * FROM `monthly`
WHERE LogDateTime >= date_sub(curdate('07:00:00'),INTERVAL 1 hour)
</code>```

答:
I think you should try this one:</p>

```<code>SELECT
*
FROM
    monthly
WHERE
    LogDateTime <= DATE_ADD(CURDATE(), INTERVAL 9 HOUR)
AND
    LogDateTime >= CURDATE()
</code>```

Body:
I am trying to write a query to retrieve data between midnight and 7am of the current day.  I know I am on the right track but cannot get the syntax correct...

SELECT * FROM `monthly`
WHERE LogDateTime >= date_sub(curdate('07:00:00'),INTERVAL 1 hour)

Body:
I think you should try this one:

SELECT
*
FROM
    monthly
WHERE
    LogDateTime <= DATE_ADD(CURDATE(), INTERVAL 9 HOUR)
AND
    LogDateTime >= CURDATE()


问:
History goBack not working at function component
I can't make a button that send de user to the previous page and I don´t know why, I've already done it at a class component and works, but know I'm trying to do it at a function component and it crashes

See the code:

```<code>import React, { Fragment } from "react";
import { connect } from "react-redux";
import { withRouter } from "react-router-dom";
import Header from "../components/recursableComponents/Header";
import { BASE_URL } from "../consts";

    function Collections(props) {
  const { classes } = props;
  const [collections, setCollection] = useState([]);
  const [choosedCollection, setChoosedCollection] = useState("");

  const getCollections = () => {
    const user = new User();
    const id_marca_estilo = user.user.id_marca_estilo;

  return (
    <Fragment>
      <Header
        title="Coleções"
        rightIcon={null}
        leftIcon={
          <IconButton
            aria-label="upload picture"
            component="span"
            className={classes.whiteButton}
            onClick={() => props.history.goBack()}
          >
            <ArrowBack></ArrowBack>
          </IconButton>
        }
      />
</code>```

答:
If you're using react-router you can have access to history using a hook:

```<code>import { useHistory } from "react-router-dom";

// (...)

function Collections(props) {
  const history = useHistory(); // <=============

  const { classes } = props;
  const [collections, setCollection] = useState([]);
  const [choosedCollection, setChoosedCollection] = useState("");

  const getCollections = () => {
    const user = new User();
    const id_marca_estilo = user.user.id_marca_estilo;

  return (
    <Fragment>
      <Header
        title="Coleções"
        rightIcon={null}
        leftIcon={
          <IconButton
            aria-label="upload picture"
            component="span"
            className={classes.whiteButton}
            onClick={() => history.goBack()}
          >
            <ArrowBack></ArrowBack>
          </IconButton>
        }
      />
</code>```

Check docs for more details:
https://reacttraining.com/react-router/web/api/Hooks/usehistory

Body:
I can't make a button that send de user to the previous page and I don´t know why, I've already done it at a class component and works, but know I'm trying to do it at a function component and it crashes

See the code:

import React, { Fragment } from "react";
import { connect } from "react-redux";
import { withRouter } from "react-router-dom";
import Header from "../components/recursableComponents/Header";
import { BASE_URL } from "../consts";

    function Collections(props) {
  const { classes } = props;
  const [collections, setCollection] = useState([]);
  const [choosedCollection, setChoosedCollection] = useState("");

  const getCollections = () => {
    const user = new User();
    const id_marca_estilo = user.user.id_marca_estilo;

  return (
    <Fragment>
      <Header
        title="Coleções"
        rightIcon={null}
        leftIcon={
          <IconButton
            aria-label="upload picture"
            component="span"
            className={classes.whiteButton}
            onClick={() => props.history.goBack()}
          >
            <ArrowBack></ArrowBack>
          </IconButton>
        }
      />

Body:
If you're using react-router you can have access to history using a hook:

import { useHistory } from "react-router-dom";

// (...)

function Collections(props) {
  const history = useHistory(); // <=============

  const { classes } = props;
  const [collections, setCollection] = useState([]);
  const [choosedCollection, setChoosedCollection] = useState("");

  const getCollections = () => {
    const user = new User();
    const id_marca_estilo = user.user.id_marca_estilo;

  return (
    <Fragment>
      <Header
        title="Coleções"
        rightIcon={null}
        leftIcon={
          <IconButton
            aria-label="upload picture"
            component="span"
            className={classes.whiteButton}
            onClick={() => history.goBack()}
          >
            <ArrowBack></ArrowBack>
          </IconButton>
        }
      />

Check docs for more details:
https://reacttraining.com/react-router/web/api/Hooks/usehistory


答:
I am assuming you are on v5+ of react-router-dom

You have to use the useHistory hook as follows

import { useHistory } from 'react-router-dom';

Then in your functional component

const history = useHistory();

Finally
onClick={() => history.goBack()}

Title: History goBack not working at function component


问:
Run single python method many times simultaneously
I have a method which takes one argument, and post to a host.

```<code>def fts(searchstring):
    search_string="\""+searchstring+"\""
    headers = {'Content-Type': 'application/json',}
    data = '{ "explain": true,"fields": ["*"],"highlight": {},"query": { "query": '+search_string+'},"size":0}'
    response = requests.post('hostname', headers=headers, data=data, auth=('uname', 'password'))
    if response.status_code != 200:
        raise Exception("{} - {}".format(response.status_code, response.text))
    print(response.json())
</code>```

I want to run this method in several processes at a time with different arguments. Is this possible? I tried to use multiprocessing but couldn't able to get it.
Thanks

答:
Code pool.map(fts, searchstring) will run simultaneously but it will treat searchstring as list of chars and send every single char to different fts

You need list with all strings

```<code>all_results = pool.map(fts, [searchstring1, searchstring2, searchstring3, ...])
</code>```

BTW: If you will need to send more arguments then you will need list with tuples or sublists.

```<code>all_results = pool.map(fts, [(searchstring1, param1), (searchstring2, param2), ...])
</code>```

and define function as

```<code>def fts(args):
    searchstring, param = args
</code>```

Body:
I have a method which takes one argument, and post to a host.

def fts(searchstring):
    search_string="\""+searchstring+"\""
    headers = {'Content-Type': 'application/json',}
    data = '{ "explain": true,"fields": ["*"],"highlight": {},"query": { "query": '+search_string+'},"size":0}'
    response = requests.post('hostname', headers=headers, data=data, auth=('uname', 'password'))
    if response.status_code != 200:
        raise Exception("{} - {}".format(response.status_code, response.text))
    print(response.json())

I want to run this method in several processes at a time with different arguments. Is this possible? I tried to use multiprocessing but couldn't able to get it.
Thanks

Body:
Code pool.map(fts, searchstring) will run simultaneously but it will treat searchstring as list of chars and send every single char to different fts

You need list with all strings

all_results = pool.map(fts, [searchstring1, searchstring2, searchstring3, ...])

BTW: If you will need to send more arguments then you will need list with tuples or sublists.

all_results = pool.map(fts, [(searchstring1, param1), (searchstring2, param2), ...])

and define function as

def fts(args):
    searchstring, param = args


问:
Apollo Server + Lambda + Subscriptions
Is it possible to run an Apollo GraphQL Lambda backend with subscriptions? As I understand, GraphQL subscriptions use websockets, so I suppose it won't be possible unless you use Redis as message broker but I want to validate it this as it's not stated in any part of Apollo Docs.</p>

答:
Someone developed this solution you can find it here aws-lambda-graphql

Edit: you should consider Appsync, it handles subscription

Title: Apollo Server + Lambda + Subscriptions


问:
Mysql error: Column count doesn't match value count at row 1; code appears to match suggestions of guides,
I'm working on the website for a mmo-rpg game-based group, and I'm having trouble on the insert form for their 'hitlist'; my code is as follows:

function check_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}

$Pri = check_input($_GET['Pri']);
$Pir = check_input($_GET['Pir']);
$Lvl = check_input($_GET['Lvl']);
$XCd = check_input($_GET['XCd']);
$YCd = check_input($_GET['YCd']);
$Nts = mysql_real_escape_string(check_input($_GET['Nts']));
$Opl = check_input($_GET['Opl']);
$Kwl = check_input($_GET['Kwl']);
$Ktl = check_input($_GET['Ktl']);
$Tty = mysql_real_escape_string(check_input($_GET['Tty']));
$Grp = check_input($_GET['Grp']);

$sql="INSERT INTO modattacklist (`Id`, `Priority`, `Pirate`, `Level`, `KnownFltLvl`, `XCoord`, `YCoord`, `Notes`, `BaseLevel`, `KnownWallLvl`, `KnownTurretLvl`, `TurretTypes`, `BasePicture`, `Group`)
VALUES ('','$Pri','$Pir','$Lvl','$XCd','$YCd','$Nts','$Opl','$Kwl','$Ktl','$Tty','Coming Soon.','$Grp')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error() . ' ' . $sql);
  }
```

<p>Yes, I've looked elsewhere, and yes, here is a printout of the query:</p>

<pre class="lang-php prettyprint-override"><code>INSERT INTO modattacklist (`Id`, `Priority`, `Pirate`, `Level`, `KnownFltLvl`, `XCoord`, `YCoord`, `Notes`, `BaseLevel`, `KnownWallLvl`, `KnownTurretLvl`, `TurretTypes`, `BasePicture`, `Group`) VALUES ('','1','Eri','13','13751','408','?','?','?','?','?','Coming Soon.','Sector 23')
</code>```

I really don't understand what I'm doing wrong.  The Id is auto-incremented, and this query works in phpMyAdmin

A new set of eyes would really be appreciated here.

答:
You are only inserting 13 values, there are 14 columns.  The 'KnownFltLvl' variable is missing.

```<code>INSERT INTO modattacklist (`Id`, `Priority`, `Pirate`, `Level`, `KnownFltLvl`, `XCoord`, `YCoord`, `Notes`, `BaseLevel`, `KnownWallLvl`, `KnownTurretLvl`, `TurretTypes`, `BasePicture`, `Group`)
VALUES ('','$Pri','$Pir','$Lvl','$KnownFltLvl','$XCd','$YCd','$Nts','$Opl','$Kwl','$Ktl','$Tty','Coming Soon.','$Grp')
</code>```

If your table accepts nulls for this column, you can remove it from the INSERT all together.

Body:
I'm working on the website for a mmo-rpg game-based group, and I'm having trouble on the insert form for their 'hitlist'; my code is as follows:

function check_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}

$Pri = check_input($_GET['Pri']);
$Pir = check_input($_GET['Pir']);
$Lvl = check_input($_GET['Lvl']);
$XCd = check_input($_GET['XCd']);
$YCd = check_input($_GET['YCd']);
$Nts = mysql_real_escape_string(check_input($_GET['Nts']));
$Opl = check_input($_GET['Opl']);
$Kwl = check_input($_GET['Kwl']);
$Ktl = check_input($_GET['Ktl']);
$Tty = mysql_real_escape_string(check_input($_GET['Tty']));
$Grp = check_input($_GET['Grp']);

$sql="INSERT INTO modattacklist (`Id`, `Priority`, `Pirate`, `Level`, `KnownFltLvl`, `XCoord`, `YCoord`, `Notes`, `BaseLevel`, `KnownWallLvl`, `KnownTurretLvl`, `TurretTypes`, `BasePicture`, `Group`)
VALUES ('','$Pri','$Pir','$Lvl','$XCd','$YCd','$Nts','$Opl','$Kwl','$Ktl','$Tty','Coming Soon.','$Grp')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error() . ' ' . $sql);
  }

Yes, I've looked elsewhere, and yes, here is a printout of the query:

INSERT INTO modattacklist (`Id`, `Priority`, `Pirate`, `Level`, `KnownFltLvl`, `XCoord`, `YCoord`, `Notes`, `BaseLevel`, `KnownWallLvl`, `KnownTurretLvl`, `TurretTypes`, `BasePicture`, `Group`) VALUES ('','1','Eri','13','13751','408','?','?','?','?','?','Coming Soon.','Sector 23')

I really don't understand what I'm doing wrong.  The Id is auto-incremented, and this query works in phpMyAdmin

A new set of eyes would really be appreciated here.

Body:
You are only inserting 13 values, there are 14 columns.  The 'KnownFltLvl' variable is missing.

INSERT INTO modattacklist (`Id`, `Priority`, `Pirate`, `Level`, `KnownFltLvl`, `XCoord`, `YCoord`, `Notes`, `BaseLevel`, `KnownWallLvl`, `KnownTurretLvl`, `TurretTypes`, `BasePicture`, `Group`)
VALUES ('','$Pri','$Pir','$Lvl','$KnownFltLvl','$XCd','$YCd','$Nts','$Opl','$Kwl','$Ktl','$Tty','Coming Soon.','$Grp')

If your table accepts nulls for this column, you can remove it from the INSERT all together.


问:
Consider the following function:
```<code>int unknown(int n){

int i, j, k=0;
for (i=n/2; i<=n; i++)
    for (j=2; j<=n; j=j*2)
        k = k + n/2;
 return (k);

}
</code>```

The return value of the function is Θ(n^2logn).

My doubt: The time complexity of the function is Θ(nlogn) which i don't understand how it can be Θ(nlogn) because outer loop will execute exactly n/2 times and inner loop will execute logn times.

How time complexity is different than return value of this function, can someone explain me in simple language so i can visualize it.

答:
The function is having 2 loops i and j. i is being incremented from n/2 to n.So i will execute n-n/2+1 times.
For j the loop starts from 2 and ends at n,and it is being incremented exponentially ,ie 2 then 4,8...upto logn times.So for this the no of iterations are logn+1 times.
For every iteration in j there is an increment in k of n/2,so overall sum ie its return value.,which O(n^2logn).
and overall time complexity is O(nlogn),for it has to execute the statement this many times.</p>

Title: Consider the following function:

Body:
int unknown(int n){

int i, j, k=0;
for (i=n/2; i<=n; i++)
    for (j=2; j<=n; j=j*2)
        k = k + n/2;
 return (k);

}

The return value of the function is Θ(n^2logn).

My doubt: The time complexity of the function is Θ(nlogn) which i don't understand how it can be Θ(nlogn) because outer loop will execute exactly n/2 times and inner loop will execute logn times.

How time complexity is different than return value of this function, can someone explain me in simple language so i can visualize it.


问:
Create program to retype a block of text
I found this JavaScript code that retypes a piece of text that was pasted in (in the retypePhrases list). But when you paste in a large amount of text, with multiple lines, regardless of adding in apostrophes and commas to each line at the front and end of the line, the code seems to break. I'm betting there's an easy change I can make to this code, that will retype text on multiple lines. I just don't know JavaScript very well and not good enough at Python to do it myself (nor did I find anything like this in Python).

How can I modify this code to:

a) keep the text and not delete it and

b) allow adding in a lot of text on multiple lines (a small program basically)

```<code>    // OBJECT: 'retype' controls the deletion and creation of new words
var retype = {
    // ARRAY: 'retypePhrases' contains the words that will be switched
    //        The tool replaces the word contained within the element with the ID of 'retype'
    //        It works cleaner if neighboring words have different first letters.
    //        Spaces in phrases can cause a hiccup. Best practice to keep phrases as single words.
    retypePhrases: [
        'Quick.',
        'Fun.',
        'Easy.',
        'Fast.',
        'Simple.',
        'Awesome.'
    ],
    index       : -1,
    elem        : document.getElementById('retype'),
    start       : function(){
        var _this = this;
        setTimeout( function(){
            _this.deleteLetter();
        }, 3000 ); // Delay the start of a new word by 3 seconds
    },// END retype.start()
    deleteRepeat: function(){
        this.deleteLetter();
    },// END retype.deleteRepeat()
    deleteLetter: function(){
        var newWord = this.elem.innerHTML;
        if( newWord.length > 0 ){
            newWord = newWord.substring(0, newWord.length - 1);
            var _this = this;
            setTimeout( function(){
                _this.elem.innerHTML = newWord;
                _this.deleteRepeat();
            }, 75 );
        }else{
            this.newLetter();
        }// END if( newWord.length > 0 )
    },// END retype.deleteLetter()
    newRepeat   : function(){
        this.newLetter();
    },// END retype.newRepeat()
    newLetter   : function(){
        var newWord = this.elem.innerHTML;
        if( newWord.length === 0 ){
            this.index++;
            if( this.index >= this.retypePhrases.length ){
                this.index = 0;
            }
        }// END if( newWord.length === 0 )
        var newLetters = this.retypePhrases[ this.index ];
        if( newLetters.length > newWord.length ){
            newLetters = newLetters.substring(0, ( newWord.length + 1 ) );
            var _this = this;
            // Add a slight random variation in retype time to make the letter typing seem more 'human'
            var time = Math.round( Math.random() * 100 ) + 100;
            setTimeout( function(){
                _this.elem.innerHTML = newLetters;
                _this.newLetter();
            }, time );
        }else{
            this.start();
            // Yep, this makes the retype an infinite loop
        }// END if( newLetters.length > newWord.length )
    }// END retype.newLetter()
};

retype.start();
</code>```

答:
Found a better way to do this just with printing in python:

```<code>import time
import sys
from random import randrange

text = "This is the introduction \n text.This is the introduction \n This is the introduction \n This is the introduction"

for c in text:
    sys.stdout.write(c)
    sys.stdout.flush()
    seconds = "0.0" + str(randrange(5, 9, 1))
    seconds = float(seconds)
    time.sleep(seconds)

print(text)
</code>```

Adjust the speed with the 5,9 line; which is the random range of time the characters get printed.

Body:
I found this JavaScript code that retypes a piece of text that was pasted in (in the retypePhrases list). But when you paste in a large amount of text, with multiple lines, regardless of adding in apostrophes and commas to each line at the front and end of the line, the code seems to break. I'm betting there's an easy change I can make to this code, that will retype text on multiple lines. I just don't know JavaScript very well and not good enough at Python to do it myself (nor did I find anything like this in Python).

How can I modify this code to:

a) keep the text and not delete it and

b) allow adding in a lot of text on multiple lines (a small program basically)

    // OBJECT: 'retype' controls the deletion and creation of new words
var retype = {
    // ARRAY: 'retypePhrases' contains the words that will be switched
    //        The tool replaces the word contained within the element with the ID of 'retype'
    //        It works cleaner if neighboring words have different first letters.
    //        Spaces in phrases can cause a hiccup. Best practice to keep phrases as single words.
    retypePhrases: [
        'Quick.',
        'Fun.',
        'Easy.',
        'Fast.',
        'Simple.',
        'Awesome.'
    ],
    index       : -1,
    elem        : document.getElementById('retype'),
    start       : function(){
        var _this = this;
        setTimeout( function(){
            _this.deleteLetter();
        }, 3000 ); // Delay the start of a new word by 3 seconds
    },// END retype.start()
    deleteRepeat: function(){
        this.deleteLetter();
    },// END retype.deleteRepeat()
    deleteLetter: function(){
        var newWord = this.elem.innerHTML;
        if( newWord.length > 0 ){
            newWord = newWord.substring(0, newWord.length - 1);
            var _this = this;
            setTimeout( function(){
                _this.elem.innerHTML = newWord;
                _this.deleteRepeat();
            }, 75 );
        }else{
            this.newLetter();
        }// END if( newWord.length > 0 )
    },// END retype.deleteLetter()
    newRepeat   : function(){
        this.newLetter();
    },// END retype.newRepeat()
    newLetter   : function(){
        var newWord = this.elem.innerHTML;
        if( newWord.length === 0 ){
            this.index++;
            if( this.index >= this.retypePhrases.length ){
                this.index = 0;
            }
        }// END if( newWord.length === 0 )
        var newLetters = this.retypePhrases[ this.index ];
        if( newLetters.length > newWord.length ){
            newLetters = newLetters.substring(0, ( newWord.length + 1 ) );
            var _this = this;
            // Add a slight random variation in retype time to make the letter typing seem more 'human'
            var time = Math.round( Math.random() * 100 ) + 100;
            setTimeout( function(){
                _this.elem.innerHTML = newLetters;
                _this.newLetter();
            }, time );
        }else{
            this.start();
            // Yep, this makes the retype an infinite loop
        }// END if( newLetters.length > newWord.length )
    }// END retype.newLetter()
};

retype.start();

Body:
Found a better way to do this just with printing in python:

import time
import sys
from random import randrange

text = "This is the introduction \n text.This is the introduction \n This is the introduction \n This is the introduction"

for c in text:
    sys.stdout.write(c)
    sys.stdout.flush()
    seconds = "0.0" + str(randrange(5, 9, 1))
    seconds = float(seconds)
    time.sleep(seconds)

print(text)

Adjust the speed with the 5,9 line; which is the random range of time the characters get printed.


问:
How can I check if the array of objects have duplicate property values?
I need some help with iterating through array, I keep getting stuck or reinventing the wheel.

```<code>values = [
    { name: 'someName1' },
    { name: 'someName2' },
    { name: 'someName1' },
    { name: 'someName1' }
]
</code>```

How could I check if there are two (or more) same name value in array? I do not need a counter, just setting some variable if array values are not unique. Have in mind that array length is dynamic, also array values.

答:
In TS and ES6 you can create a new Set with the property to be unique and compare it's size to the original array.

const values = [
  { name: 'someName1' },
  { name: 'someName2' },
  { name: 'someName3' },
  { name: 'someName1' }
]

const uniqueValues = new Set(values.map(v => v.name));

if (uniqueValues.size < values.length) {
  console.log('duplicates found')
}```

Body:
I need some help with iterating through array, I keep getting stuck or reinventing the wheel.

values = [
    { name: 'someName1' },
    { name: 'someName2' },
    { name: 'someName1' },
    { name: 'someName1' }
]

How could I check if there are two (or more) same name value in array? I do not need a counter, just setting some variable if array values are not unique. Have in mind that array length is dynamic, also array values.


问:
How do I check if a Python script is running in PHP?
I'm trying to check if a Python script is running in PHP, but I've no idea how.
I've tried using a database: I added an entry "request" with value response "0" and the Python script had to change that value to "1" if it was online. I couldn't get that to work so now I'm asking here</p>

答:
Assuming tasklist is available, this could potentially work: (this example using Windows 10)

I first launched a test2.py script:

The test2.py code is simply running:

```<code>from time import sleep

while True:
    print('running');
    sleep(3);
</code>```

Then using this bit of php code: (I named procCheck.php)

```<code><?php
$tasks = [];

// Use -v to include the window title info:
exec('tasklist -v 2>NUL', $tasks);

// Check the tasks array for the script we seek:
$entry = preg_grep('/(test2\.py)/', $tasks);

if (!empty($entry)) {
    foreach($entry as $value) {
        echo $value . PHP_EOL;
    }
}
</code>```

Gives this output: (one wrapped line in my console window)

Know that if there are other windows open with same script name within the window title will be found too. For example, I had the test2.py open as the active tab in Notepad++ and that entry was found as well:

Changing to some other file tab in Notepad++ only found the first entry.

Body:
Assuming tasklist is available, this could potentially work: (this example using Windows 10)

I first launched a test2.py script:

The test2.py code is simply running:

from time import sleep

while True:
    print('running');
    sleep(3);

Then using this bit of php code: (I named procCheck.php)

<?php
$tasks = [];

// Use -v to include the window title info:
exec('tasklist -v 2>NUL', $tasks);

// Check the tasks array for the script we seek:
$entry = preg_grep('/(test2\.py)/', $tasks);

if (!empty($entry)) {
    foreach($entry as $value) {
        echo $value . PHP_EOL;
    }
}

Gives this output: (one wrapped line in my console window)

Know that if there are other windows open with same script name within the window title will be found too. For example, I had the test2.py open as the active tab in Notepad++ and that entry was found as well:

Changing to some other file tab in Notepad++ only found the first entry.


问:
SIGPIPE crash when switching background task
I'm experiencing a weird crash when sending my app into the background, loading a new app, switching the device into sleep mode, waking up the device, closing the new app and then opening my app from the background tasks. A black screen will appear and I cannot exit this black screen with the home button, and in the debugger I am shown this message:

Program received signal:  “SIGPIPE”.
  Data Formatters unavailable (Error
  calling dlopen for:
  "/Developer/usr/lib/libXcodeDebuggerSupport.dylib":
  "dlopen(/Developer/usr/lib/libXcodeDebuggerSupport.dylib,
  10): no suitable image found.  Did
  find:
  /Developer/usr/lib/libXcodeDebuggerSupport.dylib:
  out of address space
  /Developer/usr/lib/libXcodeDebuggerSupport.dylib:
  stat() failed with errno=868226285

How do I fix this?

答:
Set SO_NOSIGPIPE on your socket via setsockopt(), or ignore all SIGPIPE signals with:
signal(SIGPIPE, SIG_IGN).


问:
Unable to generate an explicit migration because the following explicit migrations are pending
I'm using EF 6.1 and I enabled code first migration in my project by

```<code>Enable-Migrations
Add-Migration InitializeDb -ConnectionProviderName System.Data.SqlClient -ConnectionString "Data Source=myServer;Initial Catalog=myDb;Persist Security Info=True;User ID=sa;password=******;application name = L4"
Update-Database  -ConnectionProviderName System.Data.SqlClient -ConnectionString "Data Source=myServer;Initial Catalog=myDb;Persist Security Info=True;User ID=sa;password=******;application name = L4" -verbose -script
</code>```

When I specify my ConnectionString, ConnectionProviderName  explicitly with Add-Migration and Update-database in package manager console
it work correctly:

```<code>Add-migration updateXtable -ConnectionProviderName System.Data.SqlClient -ConnectionString "Data Source=myServer;Initial Catalog=myDb;Persist Security Info=True;User ID=sa;password=******;application name = L4"
</code>```

but when I use Add-Migrationwithout extra informations:

```<code>add-migration updateXtable
</code>```

I get following error:

Unable to generate an explicit migration because the following explicit migrations are pending: [201408300955376_InitializeDb, 201408311028404_Test]. Apply the pending explicit migrations before attempting to generate a new explicit migration.

So, I have to use following command each time I need update my Database:

```<code>Add-Migration UpdateXTable -ConnectionProviderName System.Data.SqlClient -ConnectionString "Data Source=myServer;Initial Catalog=myDb;Persist Security Info=True;User ID=sa;password=******;application name = L4"
Update-Database  -ConnectionProviderName System.Data.SqlClient -ConnectionString "Data Source=myServer;Initial Catalog=myDb;Persist Security Info=True;User ID=sa;password=******;application name = L4" -verbose -script
</code>```

It's my project(that contains my DbContext) app.config file:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
 <entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory,  EntityFramework" />
 <providers>
  <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
 </providers>
 </entityFramework>
 <connectionStrings>
 <add name="ERPContext" connectionString="Data Source=myServer;Initial Catalog=myDb;Persist Security Info=True;User ID=sa;password=******;application name = L4" providerName="System.Data.SqlClient" />
 </connectionStrings>

 <startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
 </startup>
</configuration>
</code>```

Does anyone know where is the problem?

答:
Just delete the migration that you have Error
it worked for me </p>

Body:
I'm using EF 6.1 and I enabled code first migration in my project by

Enable-Migrations
Add-Migration InitializeDb -ConnectionProviderName System.Data.SqlClient -ConnectionString "Data Source=myServer;Initial Catalog=myDb;Persist Security Info=True;User ID=sa;password=******;application name = L4"
Update-Database  -ConnectionProviderName System.Data.SqlClient -ConnectionString "Data Source=myServer;Initial Catalog=myDb;Persist Security Info=True;User ID=sa;password=******;application name = L4" -verbose -script

When I specify my ConnectionString, ConnectionProviderName  explicitly with Add-Migration and Update-database in package manager console
it work correctly:

Add-migration updateXtable -ConnectionProviderName System.Data.SqlClient -ConnectionString "Data Source=myServer;Initial Catalog=myDb;Persist Security Info=True;User ID=sa;password=******;application name = L4"

but when I use Add-Migrationwithout extra informations:

add-migration updateXtable

I get following error:

Unable to generate an explicit migration because the following explicit migrations are pending: [201408300955376_InitializeDb, 201408311028404_Test]. Apply the pending explicit migrations before attempting to generate a new explicit migration.

So, I have to use following command each time I need update my Database:

Add-Migration UpdateXTable -ConnectionProviderName System.Data.SqlClient -ConnectionString "Data Source=myServer;Initial Catalog=myDb;Persist Security Info=True;User ID=sa;password=******;application name = L4"
Update-Database  -ConnectionProviderName System.Data.SqlClient -ConnectionString "Data Source=myServer;Initial Catalog=myDb;Persist Security Info=True;User ID=sa;password=******;application name = L4" -verbose -script

It's my project(that contains my DbContext) app.config file:

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

  </configSections>
 <entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory,  EntityFramework" />
 <providers>
  <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
 </providers>
 </entityFramework>
 <connectionStrings>
 <add name="ERPContext" connectionString="Data Source=myServer;Initial Catalog=myDb;Persist Security Info=True;User ID=sa;password=******;application name = L4" providerName="System.Data.SqlClient" />
 </connectionStrings>

 <startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
 </startup>
</configuration>

Does anyone know where is the problem?


问:
Splitting a string using a next line regex followed by a digit (JAVA)
I have the following string which I need to split on space, commas, and next line character.
Sample string: "./homework2 3,phone3,desc3,brand4\n4,phone4,desc4,brand4\n5,phone5,desc5,brand5"

I am using split function as: .split("[,\\s+\\n+]"); but I am unable to get the required out put. The program keeps reading brand4\n4 as one substring.

Help would be appreciated.

答:
Check the below link to validate regex

https://regex101.com/r/2ZkRBp/1/


问:
Yii2, find records that match with UNIX timestamps from today
I'am trying to find records that match with UNIX timestamps that are from today. Tried some things but cant seem to match it.</p>

```<code> $query = (new \yii\db\Query())
        ->select(['a.id' ])
        ->from(['a'=>'shopping_cart'])
        ->andWhere(['>=',new \yii\db\Expression(gmdate("Y-m-d",'updated_at')),new \yii\db\Expression(date('Y-m-d'))])
        ->distinct()
        ->all();
</code>```

答:
You could try  </p>

```<code> ->andWhere(['>=',new \yii\db\Expression('UNIX_TIMESTAMP(date(now()))')])
</code>```

Body:
I'am trying to find records that match with UNIX timestamps that are from today. Tried some things but cant seem to match it.

 $query = (new \yii\db\Query())
        ->select(['a.id' ])
        ->from(['a'=>'shopping_cart'])
        ->andWhere(['>=',new \yii\db\Expression(gmdate("Y-m-d",'updated_at')),new \yii\db\Expression(date('Y-m-d'))])
        ->distinct()
        ->all();

Body:
You could try

 ->andWhere(['>=',new \yii\db\Expression('UNIX_TIMESTAMP(date(now()))')])


问:
ImportError: No module named selenium using import selenium even after installing Selenium in Python
I am trying to run tests with selenium in python, but it can not be recognized.

I have tried uninstalling with pip uninstall selenium and reinstalling, and it has not worked.

When i run import selenium i get this error:

```<code>import selenium
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named selenium
</code>```

But, when I run pip install selenium, I get:

```<code>Requirement already satisfied: selenium in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (3.141.0)
Requirement already satisfied: urllib3 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from selenium) (1.25.9)
</code>```

I am not sure if Selenium is just in the wrong place on my machine so it can not be recognized, or what is going on.

Thanks

答:
There are a number of reasons this may fail. The easiest to validate is if it is available in the environment you are working?

Check by running pip list from terminal while in the environment you are running your python module or notebook from.

Can you say if you’re using a venv?

Also, I think you typically
from selenium import webdriver
not selenium alone.

Check out this question

Body:
I am trying to run tests with selenium in python, but it can not be recognized.

I have tried uninstalling with pip uninstall selenium and reinstalling, and it has not worked.

When i run import selenium i get this error:

import selenium
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named selenium

But, when I run pip install selenium, I get:

Requirement already satisfied: selenium in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (3.141.0)
Requirement already satisfied: urllib3 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from selenium) (1.25.9)

I am not sure if Selenium is just in the wrong place on my machine so it can not be recognized, or what is going on.

Thanks


问:
Azure Application Insights doesn't show live metrics when using Java 8 and application insights SDK version 1.0.8
I am using azure application insights for logging in my application, It is a spring boot application with gradle. I am using application insights as an appender in my logback-spring.xml. I am using Java 8 and Appinsights version 1.0.8. I do not see live metrics. I see the message as App is Offline or update to newer version of SDK. I tried updating build.gradle to use new appinsights version 2.14.0 and the build fails. The build runs fine when using older version 1.0.8. I am new to Gradle. Can someone help me with this?</p>

答:
There is an issue about live metrics in the Java application insights SDK : https://github.com/microsoft/ApplicationInsights-Java/issues/1212#issuecomment-594784792

According to this post, live metrics are not fully supported by the Java SDK :(

The table in the link https://learn.microsoft.com/fr-fr/azure/azure-monitor/app/live-stream#supported-features-table says that the supported feature requires Java application insights SDK version V2.0.0+


问:
Is javax.crypto.spec.SecretKeySpec thread safe?
I intend to use it in a spring bean as a static field, and init it inside a post construct method.
A service class will inject this encryption bean and call a method exposed by it to encrypt a string using a cipher (javax.crypto.Cipher) (cipher will be initalized using the SecretKeySpec ).

Note: A new cipher instance will be fetched each time within the encrypt string method.

Edit:
As @Savior noted, the field (SecretKeySpec) should not be denoted as static. If SecretKeySpec is thread safe then I will make it a bean in a configuration class and inject it into the encryption bean (marking it as a private final field and injecting it via constructor)

答:
Yes, it is. It's pretty easy to see why: there are no methods (bar one, see below) that change the state of a SecretKeySpec instance. In other words, the class is usually immutable, even if this is not specifically mentioned in the class description. Immutable classes are by definition thread safe. Actually, most if not all Key implementations are generally immutable.

There is one method that breaks the immutability (which I forgot about), and that's the newer Key.destroy() method. Don't worry though, that's not called by Cipher or any other function to my knowledge. Furthermore, the method is not implemented by SecretKeySpec (checked in the OpenJDK up to version 14).

As also noted in the comments, you should never put any dynamic information into static fields. Instead just share a reference otherwise.


问:
Dismiss keyboard on drag with TableView and UITextView doesn't work
I've a setup as shown in the screenshot below. I've set Keyboard to Dismiss on drag in IB for scroll view. It doesn't dismiss keyboard on drag in my project.

However it does work on a dummy test project so it seems there is something in my project which is causing it not to work. I can't figure out what that thing is.

Any help or insights on how to find out the issue and fix?

P.S. It's lot of code so I may not be able to paste all the code here for this VC. If you need any specific section code to see then let me know.

答: Setting Dismiss Interactively on UITableView worked for me.


问:
Foreign key returning empty result set
I've created a foreign key to link two tables:

The addresses of my users (foreign key)

User login details (primary key).

However, when I create the foreign key no details that the user enters are saved in the address table. Whereas when the address table doesn't have a foreign key, it inserts the input into the address table just fine.

I don't have much experience with MySQL so the error could be something trivial, however I cannot find the solution myself. I am using PHP procedural.

Here is a sample of my database:

Address Table containing foreign key:

```<code>1   id Primary          int(11)         No  None        AUTO_INCREMENT
2   address_fk Index    int(11)         No  None
3   address_line_one    varchar(25) utf8_general_ci     No  None
4   address_line_two    varchar(25) utf8_general_ci     No  None
</code>```

User details with primary key:

```<code>1   id Primary      int(11)         No             None     AUTO_INCREMENT
2   user_email      varchar(320)    utf8_general_ci     No  None
3   user_password   char(60)        utf8_general_ci     No  None
</code>```

Any guidance would be appreciated.

答:
A foreign key in a child table has to reference an existing primary key column in the parent table. If your primary key is the ID column in your User Details table, your foreign key will be an ID column in the Addresses table, as it will point to the ID column in your parent table.

Your current setup indicates an address_fk column as the foreign key; however, there is no such column in the User Details table to which it can point.

Title: Foreign key returning empty result set

Body:
I've created a foreign key to link two tables:

The addresses of my users (foreign key)

User login details (primary key).

However, when I create the foreign key no details that the user enters are saved in the address table. Whereas when the address table doesn't have a foreign key, it inserts the input into the address table just fine.

I don't have much experience with MySQL so the error could be something trivial, however I cannot find the solution myself. I am using PHP procedural.

Here is a sample of my database:

Address Table containing foreign key:

1   id Primary          int(11)         No  None        AUTO_INCREMENT
2   address_fk Index    int(11)         No  None
3   address_line_one    varchar(25) utf8_general_ci     No  None
4   address_line_two    varchar(25) utf8_general_ci     No  None

User details with primary key:

1   id Primary      int(11)         No             None     AUTO_INCREMENT
2   user_email      varchar(320)    utf8_general_ci     No  None
3   user_password   char(60)        utf8_general_ci     No  None

Any guidance would be appreciated.