问:
Setting template parameter default value
I have written this class :

```<code>class Queue<T> {
    var value: T
    var next: Queue<T>?

    init(_ items: Any...)
    {
        self.value = items[0]
    }

</code>```

However I was wondering is there a way to implement the constructor  by setting some default value for the parameter "value".I know if I decalre it as "  var value: T?" it will be ok , but is there any "hacky" solution with the current code in the constructor to set some default value, it doesn't matter what it is , cause I want to make object like this : var obj = Queue() , cause currently Queue() crashes

答:
The design mistake you're making here is that you're exposing the nodes in your linked list as public API. Your Queue<T> class models a node, and naturally, a link list node must contain a value. Otherwise, it's not really a node of the list, is it?

Instead, you should have a parent LinkedList (or Queue, in your case) struct, which encapsulates a reference to the head/tail LinkedListNode. That way, an empty list can be modeled with a nil value for the LinkedList.head.

Here's how I would do this:

```<code>struct LinkedList<T> {
    class Node {
        let value: T
        let next: Node?

        init(value: T, next: Node?) {
            self.value = value
            self.next = next
        }

        convenience init?(head: T?, tail: ArraySlice<T>) {
            guard let head = head else { return nil }
            self.init(
                value: head,
                next: Node(head: tail.first, tail: tail.dropFirst())
            )
        }
    }

    var head: Node?

    init(_ elements: T...) {
        self.init(elements)
    }

    // ugh, you can't forward a vararg in Swift, so you need to have this overload >_>
    init(_ elements: [T]) {
        self.head = Node(head: elements.first, tail: elements.dropFirst())
    }
}

extension LinkedList: CustomStringConvertible {
    var description: String {
        guard let head = self.head else { return "LinkedList[empty]"}

        let allNodes = sequence(first: head, next: { $0.next })

        let body = allNodes
            .map { String(describing: $0.value) }
            .joined(separator: ", ")

        return "LinkedList[\(body)]"
    }
}

print(LinkedList(1, 2, 3)) // => LinkedList[1, 2, 3]
</code>```

Then I would implement Queue<T> as just a basic wrapper around a LinkedList<T>

```<code>struct Queue<T> {
    var list: LinkedList<T>

    init(_ initialElements: T...) {
        self.list = LinkedList(initialElements)
    }

    mutating func push(_ newElement: T) {
        let newHead = LinkedList.Node(value: newElement, next: self.list.head)
        self.list.head = newHead
    }

    mutating func pop() -> T? {
        guard let head = self.list.head else { return nil }

        self.list.head = head.next

        return head.value
    }
}

var q = Queue(3, 2, 1)
print(q) // => Queue<Int>(list: LinkedList[3, 2, 1])

q.push(4); print(q) // => Queue<Int>(list: LinkedList[4, 3, 2, 1])
q.push(5); print(q) // => Queue<Int>(list: LinkedList[5, 4, 3, 2, 1])

print(q.pop(), q) // => Optional(5) Queue<Int>(list: LinkedList[4, 3, 2, 1])
print(q.pop(), q) // => Optional(4) Queue<Int>(list: LinkedList[3, 2, 1])
print(q.pop(), q) // => Optional(3) Queue<Int>(list: LinkedList[2, 1])
print(q.pop(), q) // => Optional(2) Queue<Int>(list: LinkedList[1])
print(q.pop(), q) // => Optional(1) Queue<Int>(list: LinkedList[empty])
print(q.pop(), q) // => nil Queue<Int>(list: LinkedList[empty])
</code>```

Body:
I have written this class :

class Queue<T> {
    var value: T
    var next: Queue<T>?

    init(_ items: Any...)
    {
        self.value = items[0]
    }

However I was wondering is there a way to implement the constructor  by setting some default value for the parameter "value".I know if I decalre it as "  var value: T?" it will be ok , but is there any "hacky" solution with the current code in the constructor to set some default value, it doesn't matter what it is , cause I want to make object like this : var obj = Queue() , cause currently Queue() crashes

Body:
The design mistake you're making here is that you're exposing the nodes in your linked list as public API. Your Queue<T> class models a node, and naturally, a link list node must contain a value. Otherwise, it's not really a node of the list, is it?

Instead, you should have a parent LinkedList (or Queue, in your case) struct, which encapsulates a reference to the head/tail LinkedListNode. That way, an empty list can be modeled with a nil value for the LinkedList.head.

Here's how I would do this:

struct LinkedList<T> {
    class Node {
        let value: T
        let next: Node?

        init(value: T, next: Node?) {
            self.value = value
            self.next = next
        }

        convenience init?(head: T?, tail: ArraySlice<T>) {
            guard let head = head else { return nil }
            self.init(
                value: head,
                next: Node(head: tail.first, tail: tail.dropFirst())
            )
        }
    }

    var head: Node?

    init(_ elements: T...) {
        self.init(elements)
    }

    // ugh, you can't forward a vararg in Swift, so you need to have this overload >_>
    init(_ elements: [T]) {
        self.head = Node(head: elements.first, tail: elements.dropFirst())
    }
}

extension LinkedList: CustomStringConvertible {
    var description: String {
        guard let head = self.head else { return "LinkedList[empty]"}

        let allNodes = sequence(first: head, next: { $0.next })

        let body = allNodes
            .map { String(describing: $0.value) }
            .joined(separator: ", ")

        return "LinkedList[\(body)]"
    }
}

print(LinkedList(1, 2, 3)) // => LinkedList[1, 2, 3]

Then I would implement Queue<T> as just a basic wrapper around a LinkedList<T>

struct Queue<T> {
    var list: LinkedList<T>

    init(_ initialElements: T...) {
        self.list = LinkedList(initialElements)
    }

    mutating func push(_ newElement: T) {
        let newHead = LinkedList.Node(value: newElement, next: self.list.head)
        self.list.head = newHead
    }

    mutating func pop() -> T? {
        guard let head = self.list.head else { return nil }

        self.list.head = head.next

        return head.value
    }
}

var q = Queue(3, 2, 1)
print(q) // => Queue<Int>(list: LinkedList[3, 2, 1])

q.push(4); print(q) // => Queue<Int>(list: LinkedList[4, 3, 2, 1])
q.push(5); print(q) // => Queue<Int>(list: LinkedList[5, 4, 3, 2, 1])

print(q.pop(), q) // => Optional(5) Queue<Int>(list: LinkedList[4, 3, 2, 1])
print(q.pop(), q) // => Optional(4) Queue<Int>(list: LinkedList[3, 2, 1])
print(q.pop(), q) // => Optional(3) Queue<Int>(list: LinkedList[2, 1])
print(q.pop(), q) // => Optional(2) Queue<Int>(list: LinkedList[1])
print(q.pop(), q) // => Optional(1) Queue<Int>(list: LinkedList[empty])
print(q.pop(), q) // => nil Queue<Int>(list: LinkedList[empty])


来源: stackexchange

问:
Numpy array how to get index of row minimum
I have a numpy array like this one

```<code># [[0.64809866 1.4297429  1.76778859]
#  [0.98994126 0.60583935 1.07312068]
#  [0.47607127 0.58659789 1.52184562]
#  [0.6905903  0.33424117 1.50113122]
#  [0.66848235 1.5608329  2.02750987]

</code>```

I'd like to find the min of each row, but knowing by index. Like this

```<code># [[0]
#  [1]
#  [0]
#  [1]
#  [0]]
</code>```

i used np.min(dist, axis=1).reshape(-1, 1) in order to generate a matrix with the min of results, but no idea how to follow from here.

ContentLicense: CC BY-SA 4.0

Body:
I have a numpy array like this one

# [[0.64809866 1.4297429  1.76778859]
#  [0.98994126 0.60583935 1.07312068]
#  [0.47607127 0.58659789 1.52184562]
#  [0.6905903  0.33424117 1.50113122]
#  [0.66848235 1.5608329  2.02750987]

I'd like to find the min of each row, but knowing by index. Like this

# [[0]
#  [1]
#  [0]
#  [1]
#  [0]]

i used np.min(dist, axis=1).reshape(-1, 1) in order to generate a matrix with the min of results, but no idea how to follow from here.

Body:
Try with argmin

a.argmin(axis=1).reshape(-1,1)
array([[0],
       [1],
       [0],
       [1],
       [0]])


问:
Group Django queryset into separate sections depending on choice
I've got the following Django model:

```<code>class Product(models.Model):

    HARDWARE = 'H'
    SOFTWARE = 'S'
    CATEGORY_CHOICES = (
        (HARDWARE, 'Hardware'),
        (SOFTWARE, 'Software'),
    )

    name = models.CharField(max_length=100)
    category = models.CharField(max_length=1, choices=CATEGORY_CHOICES, default=HARDWARE)
</code>```

I'd like to display all products in a template, separated into Hardware and Software.

```<code>{% for category in grouped_by_category %}
    <h1>{{category.name}}</h1>
    <ul>
    {% for product in category.products %}
        <li>{{product.name}}</li>
    {% endfor %}
    </ul>
{% endfor %}
</code>```

This is what I have, but it just seems inefficient.

```<code>def grouped_by_category():
    grouped_products = []
    all_products = Product.objects.all()
    for key, name in Product.CATEGORY_CHOICES:
        category_products = []
        for product in all_products:
            if product.category == key:
                category_products.append(product)
        grouped_products.append({'name': name, 'products':category_products})
    return grouped_products
</code>```

答:
You can use different queries based on category</p>

```<code>def grouped_by_category():
    grouped_products = []
    for key, name in Product.CATEGORY_CHOICES:
        grouped_products.append({'name':name,'products':Product.objects.filter(category=key)})
    return grouped_products
</code>```

Body:
I've got the following Django model:

class Product(models.Model):

    HARDWARE = 'H'
    SOFTWARE = 'S'
    CATEGORY_CHOICES = (
        (HARDWARE, 'Hardware'),
        (SOFTWARE, 'Software'),
    )

    name = models.CharField(max_length=100)
    category = models.CharField(max_length=1, choices=CATEGORY_CHOICES, default=HARDWARE)

I'd like to display all products in a template, separated into Hardware and Software.

{% for category in grouped_by_category %}

{{category.name}}

    {% for product in category.products %}

{{product.name}}

    {% endfor %}

{% endfor %}

This is what I have, but it just seems inefficient.

def grouped_by_category():
    grouped_products = []
    all_products = Product.objects.all()
    for key, name in Product.CATEGORY_CHOICES:
        category_products = []
        for product in all_products:
            if product.category == key:
                category_products.append(product)
        grouped_products.append({'name': name, 'products':category_products})
    return grouped_products

Body:
You can use different queries based on category

def grouped_by_category():
    grouped_products = []
    for key, name in Product.CATEGORY_CHOICES:
        grouped_products.append({'name':name,'products':Product.objects.filter(category=key)})
    return grouped_products


问:
Changing Font Size of Japanese (Unicode) characters
I have a NSPopUpButton which contains either English or Japanese Strings read from a plist file according to the System's Language. Now when the Language is English I am able to change the font size by using code such as -

```<code> [auxStatePopup setFont: [NSFont fontWithName:@"Helvetica-BoldOblique" size:10.0]];
</code>```

but Using such technique I am not able to change Japanese font size even if I tried by setting some Japanese font name which I googled and found out.
I want to do that because Japanese characters move slightly up when used. I intend to manipulate that upward movement by decreasing font size.
Thanks for any help..

OR

any way to move text in NSPopupButton downwards?

答:
My impression is that the two samples are not using the same font. Please try to put a text with characters from both sets and see what happens.

Also try not to customize the font size and even the font face.

I also suspect that the text rendering engine may had overridden some of your changes due to the text length. iOS text rendering may try to change the font size of letter spacing if the text does not fit the control. So make some tests with shorter texts.

BTW, I think that you were mean to say that you want bigger font size for Japanese not smaller. In the screenshots the Japanese text is already too small to be properly read by anyone.

ContentLicense: CC BY-SA 3.0

Body:
I have a NSPopUpButton which contains either English or Japanese Strings read from a plist file according to the System's Language. Now when the Language is English I am able to change the font size by using code such as -

 [auxStatePopup setFont: [NSFont fontWithName:@"Helvetica-BoldOblique" size:10.0]];

but Using such technique I am not able to change Japanese font size even if I tried by setting some Japanese font name which I googled and found out.
I want to do that because Japanese characters move slightly up when used. I intend to manipulate that upward movement by decreasing font size.
Thanks for any help..

OR

any way to move text in NSPopupButton downwards?


问:
A function uses an object to initiate and destroy a resource. How can I rewrite this as HOF that provides a resource?
Here is what I am starting with. convert uses svgInjector to initiate and destroy a resource.

```<code>export async function convert(
  serializedSvg: string,
  svgSourceId: string,
  containerId: string
): Promise<string> {
  const svgInjector = new SvgInjector(serializedSvg, containerId).inject();
  if (!svgInjector.injectedElement) {
    throw new Error("Svg not injected");
  }

  const doc = new TargetDocument({});
  const xml = convertRecursively(
    svgInjector.injectedElement,
    doc,
    {
      svgSourceId,
    }
  );

  svgInjector.remove();

  return doc.saveXML();
}
</code>```

How can I rewrite this to instead have a higher order function initiate, provide and destroy the resource svgInjector.injectedElement to the convert function?

EDIT:

Here is a minimal reproducible example:

var svg = '<svg xmlns="http://www.w3.org/2000/svg"><text x="20" y="20">I am made available in DOM</text></svg>'

function convert(
  serializedSvg,
  containerId
) {
  // make resource available (cross-cutting convern)
  var container = document.getElementById(containerId);
  var resource = new DOMParser().parseFromString(serializedSvg, "image/svg+xml").documentElement;
  container.appendChild(resource);

  // core convert functionality does things with resource
  console.log(resource.getBBox())

  // clean up resource (cross-cutting concern)
  resource.remove()
}

convert(svg, "container")```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <title>Minimal</title>
</head>
<body>
<div id="container">
</div>
</body>
</html></code>```

EDIT 2

Here is a TypeScript version of the JavaScript in the previous edit

```<code>var svg = '<svg xmlns="http://www.w3.org/2000/svg"><text x="20" y="20">I am made available in DOM</text></svg>'

function convert(
  serializedSvg: string,
  containerId: string
) {
  // make resource available (cross-cutting convern)
  var container = document.getElementById(containerId);
  if (!(container instanceof HTMLDivElement)) {
    throw new Error("Extpected a div element")
  }
  var resource = new DOMParser().parseFromString(serializedSvg, "image/svg+xml").documentElement;
  if (!(resource instanceof SVGSVGElement)) {
    throw new Error("Extpected a svg element")
  }
  container.appendChild(resource);

  // core convert functionality does things with resource
  console.log(resource.getBBox())

  // clean up resource (cross-cutting concern)
  resource.remove()
}

convert(svg, "container")
</code>```

答:
I'm not sure if this is the sort of thing you're looking for exactly, but I'd be inclined to invert the control flow so that convert() uses or is passed a "resource manager" which takes care of the creation, furnishing, and deletion of the resource.  A ResourceManager could simply be a function like:

```<code>type ResourceManager<T, I> = <R>(initProps: I, cb: (resource: T) => R) => R;
</code>```

So a ResourceManager<T, I> is a function that takes some initial property bag of type I to specify which resource of type T is needed, and a callback function that does the actual work after the resource is available and before it is destroyed.  If the callback function returns a result, then so does the resource manager.

This ResourceManager<T, I> is the generic contract that can be reused for different types of resource.  Of course different types of resource need their own implementations.  For example, I'd pull out of your convert() function a ResourceManager<SVGSVGElement, { serializedSvg: string, containerId: string }> like this:

```<code>const svgManager: ResourceManager<SVGSVGElement, { serializedSvg: string, containerId: string }> =
  (initProps, cb) => {

    // make resource available)
    var container = document.getElementById(initProps.containerId);
    if (!(container instanceof HTMLDivElement)) {
      throw new Error("Extpected a div element");
    }
    var resource = new DOMParser().parseFromString(initProps.serializedSvg, "image/svg+xml").documentElement;
    if (!(resource instanceof SVGSVGElement)) {
      throw new Error("Extpected a svg element")
    }
    container.appendChild(resource);

    // core functionality
    const ret = cb(resource);

    // clean up resource
    resource.remove()

    // return returned value if we have one
    return ret;
  }
</code>```

Notice how the "core functionality" is just deferred to the callback, whose return value is held onto in case it is needed.  Then convert() is simplified to:

```<code>function convert(
  serializedSvg: string,
  containerId: string
) {
  svgManager({ serializedSvg, containerId }, (resource => console.log(resource.getBBox())));
}
</code>```

Where resource => console.log(resource.getBBox()) is the function that does the work without caring about how to get or dispose of resource.

Hope that helps or gives you some ideas.  Good luck!

Playground link to code

Body:
Here is what I am starting with. convert uses svgInjector to initiate and destroy a resource.

export async function convert(
  serializedSvg: string,
  svgSourceId: string,
  containerId: string
): Promise<string> {
  const svgInjector = new SvgInjector(serializedSvg, containerId).inject();
  if (!svgInjector.injectedElement) {
    throw new Error("Svg not injected");
  }

  const doc = new TargetDocument({});
  const xml = convertRecursively(
    svgInjector.injectedElement,
    doc,
    {
      svgSourceId,
    }
  );

  svgInjector.remove();

  return doc.saveXML();
}

How can I rewrite this to instead have a higher order function initiate, provide and destroy the resource svgInjector.injectedElement to the convert function?

EDIT:

Here is a minimal reproducible example:

var svg = '<svg xmlns="http://www.w3.org/2000/svg"><text x="20" y="20">I am made available in DOM</text></svg>'

function convert(
  serializedSvg,
  containerId
) {
  // make resource available (cross-cutting convern)
  var container = document.getElementById(containerId);
  var resource = new DOMParser().parseFromString(serializedSvg, "image/svg+xml").documentElement;
  container.appendChild(resource);

  // core convert functionality does things with resource
  console.log(resource.getBBox())

  // clean up resource (cross-cutting concern)
  resource.remove()
}

convert(svg, "container")

<!DOCTYPE html>

  <title>Minimal</title>

EDIT 2

Here is a TypeScript version of the JavaScript in the previous edit

var svg = '<svg xmlns="http://www.w3.org/2000/svg"><text x="20" y="20">I am made available in DOM</text></svg>'

function convert(
  serializedSvg: string,
  containerId: string
) {
  // make resource available (cross-cutting convern)
  var container = document.getElementById(containerId);
  if (!(container instanceof HTMLDivElement)) {
    throw new Error("Extpected a div element")
  }
  var resource = new DOMParser().parseFromString(serializedSvg, "image/svg+xml").documentElement;
  if (!(resource instanceof SVGSVGElement)) {
    throw new Error("Extpected a svg element")
  }
  container.appendChild(resource);

  // core convert functionality does things with resource
  console.log(resource.getBBox())

  // clean up resource (cross-cutting concern)
  resource.remove()
}

convert(svg, "container")

Body:
I'm not sure if this is the sort of thing you're looking for exactly, but I'd be inclined to invert the control flow so that convert() uses or is passed a "resource manager" which takes care of the creation, furnishing, and deletion of the resource.  A ResourceManager could simply be a function like:

type ResourceManager<T, I> = <R>(initProps: I, cb: (resource: T) => R) => R;

So a ResourceManager<T, I> is a function that takes some initial property bag of type I to specify which resource of type T is needed, and a callback function that does the actual work after the resource is available and before it is destroyed.  If the callback function returns a result, then so does the resource manager.

This ResourceManager<T, I> is the generic contract that can be reused for different types of resource.  Of course different types of resource need their own implementations.  For example, I'd pull out of your convert() function a ResourceManager<SVGSVGElement, { serializedSvg: string, containerId: string }> like this:

const svgManager: ResourceManager<SVGSVGElement, { serializedSvg: string, containerId: string }> =
  (initProps, cb) => {

    // make resource available)
    var container = document.getElementById(initProps.containerId);
    if (!(container instanceof HTMLDivElement)) {
      throw new Error("Extpected a div element");
    }
    var resource = new DOMParser().parseFromString(initProps.serializedSvg, "image/svg+xml").documentElement;
    if (!(resource instanceof SVGSVGElement)) {
      throw new Error("Extpected a svg element")
    }
    container.appendChild(resource);

    // core functionality
    const ret = cb(resource);

    // clean up resource
    resource.remove()

    // return returned value if we have one
    return ret;
  }

Notice how the "core functionality" is just deferred to the callback, whose return value is held onto in case it is needed.  Then convert() is simplified to:

function convert(
  serializedSvg: string,
  containerId: string
) {
  svgManager({ serializedSvg, containerId }, (resource => console.log(resource.getBBox())));
}

Where resource => console.log(resource.getBBox()) is the function that does the work without caring about how to get or dispose of resource.

Hope that helps or gives you some ideas.  Good luck!

<a href="https://www.typescriptlang.org/play?#code/G4QwTgBAzsDmEF4IHIA8N4A8C2AbAdlAgEQAWALuQA4BcA9HQO7MB0jAzCwPZix0BMABmF0MxAHypyAU0zkImEkOIQAnksESAkhBDYI2EABNpu0AEtcIAEa5T5-BAAiAeQCyqOjLmTRcccgAUIHkqlSmAErSUFwArmAAxtJuIPggsNJgqAAqADQQWuKIEKgR4gAUDubkAApgXFRQNAX5CdbN5WDRcYnSzdkAlIhFEUMIIwDcwQlchPIYKWkZYM1RMfFJi+mZqADKAGoA4geHAKJ22NL45PkA3tCZ5iC45gBe0ka7cM1Q5GAOsFas3IIAcmS0Rh+fwBEAAvkUEIEIBBKvhqnUGlBWtYxkVbsFkciGAYQABrUxdda9Mygqy2aQDJGE0CQGbXUH4TLFIxcBKxS7XFgZcjnaQC8gAIVUENR6PqjRYbJBYLAEIGU0JEHMADMUQBCcpKjlchy-VJJLi6gAS2TcABknOZgKLxQMhvjNcjyKR6owIJy-acwPUwOViKc5OEEjIjLoIEYnRBpBcruRiOqmcjYZmICyIJSekligHnO4auAoJlygMWFQK9IAGL1bC7aH4WCy2ryqAsSv-Z5vD5fQEQYjmQwZPywADUOFw6ZYPL54pdqY1hJ1+s63Q29jm5uklogJxOq+ubogHs93t9-ukgeDPDDEeo0mjHzjGCTKeu6Zz2c1I0VRYEAqHCfAjAAYVISwjG3KkkgzHNiRmLoIG1WJ8GjcxZgHUIczZX582keQkDaeDCwZKZkLoCAEjsVIIFiKhiIQ6QcwLXcWC6bAuGAaRqwJQliS6ch4kcUTxI-UBcFiexdUYUxSBAfiIFmdjNUksAJJI9ds0CDCsPIHDHDZfiwHIcomT7J4XneT5vmgNtASZIDOVVSEnP+dtAnday4C2ZZynuGyB3s4cgXZFUIThfIKN3YY6NmGI7BYXAuA7TjeiFEiJQlLhMGrN0M30szMksjB8mINzMnTajgkCIA" rel="nofollow noreferrer">Playground link to code


答:
You can use the regroup templatetag in the template:

```<code>{% regroup all_products by category as grouped_by_category %}

{% for category in grouped_by_category %}
    <h1>{{ category.grouper }}</h1>
    <ul>
    {% for product in category.list %}
        <li>{{product.name}}</li>
    {% endfor %}
    </ul>
{% endfor %}
</code>```

See https://docs.djangoproject.com/en/2.2/ref/templates/builtins/#regroup for the documentation.

Title: Group Django queryset into separate sections depending on choice

Body:
You can use the regroup templatetag in the template:

{% regroup all_products by category as grouped_by_category %}

{% for category in grouped_by_category %}
    <h1>{{ category.grouper }}</h1>
    <ul>
    {% for product in category.list %}
        <li>{{product.name}}</li>
    {% endfor %}
    </ul>
{% endfor %}

See https://docs.djangoproject.com/en/2.2/ref/templates/builtins/#regroup for the documentation.


问:
How to add or condition using sequelize in Reactjs
I would like to add the below query condition in my “service/players” get userModel.findAll()...

select * from user where privilege =‘ADMIN’ or privilege = ‘PLAYER’

The below query just returns only PLAYER.

```<code>app.get('/service/players', async (req, res) => {
  try {
    const players = await UserModel.findAll({ where: { privilege: 'PLAYER' } });
    res.status(200).json({ players });
  } catch (e) {
    res.status(500).json({ message: e.message });
  }

});
</code>```

答:
You can use Op.or or Op.in

Like this

app.get('/service/players', async (req, res) => {
    try {
      const players = await UserModel.findAll({
        where: {
          privilege: {
            [Op.or]: ['ADMIN', 'PLAYER']
          }
        }
      })
      res.status(200).json({ players });
    } catch (e) {
      res.status(500).json({ message: e.message });
    }
}

```

<p><strong>or simply like this</strong></p>

<pre class="lang-js prettyprint-override"><code>where: {
    privilege: ['ADMIN', 'PLAYER']
  }
</code>```

Body:
I would like to add the below query condition in my “service/players” get userModel.findAll()...

select * from user where privilege =‘ADMIN’ or privilege = ‘PLAYER’

The below query just returns only PLAYER.

app.get('/service/players', async (req, res) => {
  try {
    const players = await UserModel.findAll({ where: { privilege: 'PLAYER' } });
    res.status(200).json({ players });
  } catch (e) {
    res.status(500).json({ message: e.message });
  }

});

Body:
You can use Op.or or Op.in

Like this

app.get('/service/players', async (req, res) => {
    try {
      const players = await UserModel.findAll({
        where: {
          privilege: {
            [Op.or]: ['ADMIN', 'PLAYER']
          }
        }
      })
      res.status(200).json({ players });
    } catch (e) {
      res.status(500).json({ message: e.message });
    }
}

or simply like this

where: {
    privilege: ['ADMIN', 'PLAYER']
  }


问:
How to separate or draw some independent legends in a linear plot?
I have been struggling to visually separate the legends. My data only has time vs amount of different growth values, but I need to separate the Raw Data (colored lines) from the geometric mean (black smooth curve).

Growth curves A

Growth Curves B

I have "successfully" plotted them, but I either get a plot with the 'geometric mean' without it appearing in the legend, or all four curves in the same legend.

I would love to separate them, so that the three lines have the title "Fluorescence excitation at" title, and the geometric mean of these lines, just the name "60 mM Mean". The reason I want that data to be separated is because I will be creating other graphs that will compare the mean fluorescence excitation at different concentrations (60, 30, 15, so on).

Data: Small file with the data frame (28 observations of 11 numerical variables)

Here is my code for A:

```<code>GraphChl60mM <- ggplot(data = Combined60mM, mapping = aes(Tiempo)) +
  geom_smooth(aes(y=Mean.excitation.at.335, colour= "335 nm"), method = "loess", alpha = 0.35) +
  geom_point(aes(y=Mean.excitation.at.335, colour= "335 nm")) +
  geom_line(aes(y=Mean.excitation.at.335, colour= "335 nm")) +

  geom_smooth(aes(y=Mean.excitation.at.440, colour= "440 nm"), method = "loess", alpha = 0.35) +
  geom_point(aes(y=Mean.excitation.at.440, colour= "440 nm")) +
  geom_line(aes(y=Mean.excitation.at.440, colour= "440 nm")) +

  geom_smooth(aes(y=Mean.excitation.at.480, colour= "480 nm"), method = "loess", alpha = 0.35) +
  geom_point(aes(y=Mean.excitation.at.480, colour= "480 nm")) +
  geom_line(aes(y=Mean.excitation.at.480, colour= "480 nm")) +

  #Geometric mean
  geom_smooth(aes(y=Mean.60.mM, colour= "60 mM"), method = "loess", alpha = 0.5) +
  #colour= "Black"
  theme_minimal() +
  #theme(legend.position="none") +
  labs(y = "Fluorescence intensity", x = "Time (days)", title = expression(paste("Growth curve of ",
   italic("Chlorella vulgaris "), "UTEX 2714 at 60 mM"))) +
#  guides(colour = guide_legend(override.aes = list(pch = c(16,17,18,21), fill = c('gray', 'grey', 'gray', "gray")))) +
#  guides(color=guide_legend("Mean excitation at")) +
    scale_color_manual(name =bquote(paste("Mean excitation at ", lambda)),
                       values = c( "335 nm" = "blue", "440 nm" = "red", "480 nm" = "orange", "60 mM" = "black"),
                       labels = c("335 nm", "440 nm", "480 nm", "Geometric mean values")) +
  coord_cartesian(ylim=c(0, 10000))
</code>```

And the code for graph B

```<code>
GraphChl60mM <- ggplot(data = Combined60mM, mapping = aes(Tiempo)) +
  geom_smooth(aes(y=Mean.excitation.at.335, colour= "335 nm"), method = "loess") +
  geom_point(aes(y=Mean.excitation.at.335, colour= "335 nm")) +
  geom_line(aes(y=Mean.excitation.at.335, colour= "335 nm")) +

  geom_smooth(aes(y=Mean.excitation.at.440, colour= "440 nm"), method = "loess") +
  geom_point(aes(y=Mean.excitation.at.440, colour= "440 nm")) +
  geom_line(aes(y=Mean.excitation.at.440, colour= "440 nm")) +

  geom_smooth(aes(y=Mean.excitation.at.480, colour= "480 nm"), method = "loess") +
  geom_point(aes(y=Mean.excitation.at.480, colour= "480 nm")) +
  geom_line(aes(y=Mean.excitation.at.480, colour= "480 nm")) +

  #Promedio
  geom_smooth(aes(y= df_Comparative_Chlorella$`Mean.60.mM`, colour= "30 mM"), color= "Black", method = "loess") +

  theme_minimal() +
  #theme(legend.position="none") +
  labs(y = "Fluorescence intensity", x = "Time (h)", title = expression(paste(italic("C. vulgaris "), "UTEX 2714 at 60 mM"))) +
  coord_cartesian(ylim=c(0, 10000))

</code>```

答:
For multiple series, always try to "tidy" your data. That means gathering the names into one column and the values into another.

```<code>library(tidyr)
library(dplyr)
library(ggplot2)

geom.mean <- function(x) exp(mean(log(x)))

select(Combined60mM, Tiempo, starts_with("Mean.Exc")) %>%
  pivot_longer(cols=-Tiempo) %>%
  ggplot(mapping = aes(x=Tiempo, y=value, col=factor(name))) +
  geom_point() +
  geom_line() +
  geom_smooth(method = "loess", alpha = 0.35) +
  theme_minimal() +
  scale_color_manual(
    name =bquote(paste("Mean excitation at ", lambda)),
    values = c("blue", "red", "orange"),
    labels = c("335 nm", "440 nm", "480 nm")) +
  coord_cartesian(ylim=c(0, 10000)) +
  stat_summary(aes(lwd="Geometric mean values"), fun=geom.mean, geom="line", col="black") +
  guides(col = guide_legend(order = 1)) +
  labs(y = "Fluorescence intensity", x = "Time (days)",
       title = expression(paste("Growth curve of ", italic("Chlorella vulgaris "), "UTEX 2714 at 60 mM")),
       size=NULL)
</code>```

Body:
I have been struggling to visually separate the legends. My data only has time vs amount of different growth values, but I need to separate the Raw Data (colored lines) from the geometric mean (black smooth curve).

Growth curves A

Growth Curves B

I have "successfully" plotted them, but I either get a plot with the 'geometric mean' without it appearing in the legend, or all four curves in the same legend.

I would love to separate them, so that the three lines have the title "Fluorescence excitation at" title, and the geometric mean of these lines, just the name "60 mM Mean". The reason I want that data to be separated is because I will be creating other graphs that will compare the mean fluorescence excitation at different concentrations (60, 30, 15, so on).

Data: Small file with the data frame (28 observations of 11 numerical variables)

Here is my code for A:

GraphChl60mM <- ggplot(data = Combined60mM, mapping = aes(Tiempo)) +
  geom_smooth(aes(y=Mean.excitation.at.335, colour= "335 nm"), method = "loess", alpha = 0.35) +
  geom_point(aes(y=Mean.excitation.at.335, colour= "335 nm")) +
  geom_line(aes(y=Mean.excitation.at.335, colour= "335 nm")) +

  geom_smooth(aes(y=Mean.excitation.at.440, colour= "440 nm"), method = "loess", alpha = 0.35) +
  geom_point(aes(y=Mean.excitation.at.440, colour= "440 nm")) +
  geom_line(aes(y=Mean.excitation.at.440, colour= "440 nm")) +

  geom_smooth(aes(y=Mean.excitation.at.480, colour= "480 nm"), method = "loess", alpha = 0.35) +
  geom_point(aes(y=Mean.excitation.at.480, colour= "480 nm")) +
  geom_line(aes(y=Mean.excitation.at.480, colour= "480 nm")) +

  #Geometric mean
  geom_smooth(aes(y=Mean.60.mM, colour= "60 mM"), method = "loess", alpha = 0.5) +
  #colour= "Black"
  theme_minimal() +
  #theme(legend.position="none") +
  labs(y = "Fluorescence intensity", x = "Time (days)", title = expression(paste("Growth curve of ",
   italic("Chlorella vulgaris "), "UTEX 2714 at 60 mM"))) +
#  guides(colour = guide_legend(override.aes = list(pch = c(16,17,18,21), fill = c('gray', 'grey', 'gray', "gray")))) +
#  guides(color=guide_legend("Mean excitation at")) +
    scale_color_manual(name =bquote(paste("Mean excitation at ", lambda)),
                       values = c( "335 nm" = "blue", "440 nm" = "red", "480 nm" = "orange", "60 mM" = "black"),
                       labels = c("335 nm", "440 nm", "480 nm", "Geometric mean values")) +
  coord_cartesian(ylim=c(0, 10000))

And the code for graph B

GraphChl60mM <- ggplot(data = Combined60mM, mapping = aes(Tiempo)) +
  geom_smooth(aes(y=Mean.excitation.at.335, colour= "335 nm"), method = "loess") +
  geom_point(aes(y=Mean.excitation.at.335, colour= "335 nm")) +
  geom_line(aes(y=Mean.excitation.at.335, colour= "335 nm")) +

  geom_smooth(aes(y=Mean.excitation.at.440, colour= "440 nm"), method = "loess") +
  geom_point(aes(y=Mean.excitation.at.440, colour= "440 nm")) +
  geom_line(aes(y=Mean.excitation.at.440, colour= "440 nm")) +

  geom_smooth(aes(y=Mean.excitation.at.480, colour= "480 nm"), method = "loess") +
  geom_point(aes(y=Mean.excitation.at.480, colour= "480 nm")) +
  geom_line(aes(y=Mean.excitation.at.480, colour= "480 nm")) +

  #Promedio
  geom_smooth(aes(y= df_Comparative_Chlorella$`Mean.60.mM`, colour= "30 mM"), color= "Black", method = "loess") +

  theme_minimal() +
  #theme(legend.position="none") +
  labs(y = "Fluorescence intensity", x = "Time (h)", title = expression(paste(italic("C. vulgaris "), "UTEX 2714 at 60 mM"))) +
  coord_cartesian(ylim=c(0, 10000))

Body:
For multiple series, always try to "tidy" your data. That means gathering the names into one column and the values into another.

library(tidyr)
library(dplyr)
library(ggplot2)

geom.mean <- function(x) exp(mean(log(x)))

select(Combined60mM, Tiempo, starts_with("Mean.Exc")) %>%
  pivot_longer(cols=-Tiempo) %>%
  ggplot(mapping = aes(x=Tiempo, y=value, col=factor(name))) +
  geom_point() +
  geom_line() +
  geom_smooth(method = "loess", alpha = 0.35) +
  theme_minimal() +
  scale_color_manual(
    name =bquote(paste("Mean excitation at ", lambda)),
    values = c("blue", "red", "orange"),
    labels = c("335 nm", "440 nm", "480 nm")) +
  coord_cartesian(ylim=c(0, 10000)) +
  stat_summary(aes(lwd="Geometric mean values"), fun=geom.mean, geom="line", col="black") +
  guides(col = guide_legend(order = 1)) +
  labs(y = "Fluorescence intensity", x = "Time (days)",
       title = expression(paste("Growth curve of ", italic("Chlorella vulgaris "), "UTEX 2714 at 60 mM")),
       size=NULL)


问:
smtp error while setting up phpmailer
i'm having difficulty setting up phpmailer on my local web server and would appreciate any help

i am running xamppp 1.7.4 and php 5.3.5 - i keep receiving the following error message whenever trying to send mail

```<code>SMTP Error: Could not connect to SMTP host.
</code>```

here is the code i am using right now

```<code>require("resources/phpmailer/class.phpmailer.php");
    //send the email with an email containing the activation link to the supplied email address

   $mailer = new PHPMailer();
   $mailer->IsSMTP();  // telling the class to use SMTP
   $mailer->Mailer = "smtp";
   $mailer->Host = "ssl://smtp.gmail.com";
   $mailer->Port = 587;
   $mailer->SMTPAuth = true; // turn on SMTP authentication
   $mailer->Username = $email_kite;
   $mailer->Password = $emailpass_kite;
   $mailer->From = $email_kite;
   $mailer->FromName = 'Kite';
   $mailer->Body = 'Testing';
   $mailer->Subject = 'Get started with Kite';
   $mailer->AddAddress($email);
   if(!$mailer->Send())
   {
       // message not sent
  echo '<p class="c7">Unfortunately the <b>activation</b> email could not be sent and user registration has failed. Please go <a href="register.php">back</a> and try again.</p>';
      echo '<br><img src="resources/img/spacer.gif" alt="" width="1" height="10">';
  include_once ("resources/php/footer.php");
  exit;
   }
   else
   {
       // message sent
       "Email sent successfully!";
   }
    }
</code>```

thanks!

答:
Try using

```<code>$mailer->Port = 465;
</code>```

Port 587 is for TLS, the SSL port is 465.

Title: smtp error while setting up phpmailer

Body:
i'm having difficulty setting up phpmailer on my local web server and would appreciate any help

i am running xamppp 1.7.4 and php 5.3.5 - i keep receiving the following error message whenever trying to send mail

SMTP Error: Could not connect to SMTP host.

here is the code i am using right now

require("resources/phpmailer/class.phpmailer.php");
    //send the email with an email containing the activation link to the supplied email address

   $mailer = new PHPMailer();
   $mailer->IsSMTP();  // telling the class to use SMTP
   $mailer->Mailer = "smtp";
   $mailer->Host = "ssl://smtp.gmail.com";
   $mailer->Port = 587;
   $mailer->SMTPAuth = true; // turn on SMTP authentication
   $mailer->Username = $email_kite;
   $mailer->Password = $emailpass_kite;
   $mailer->From = $email_kite;
   $mailer->FromName = 'Kite';
   $mailer->Body = 'Testing';
   $mailer->Subject = 'Get started with Kite';
   $mailer->AddAddress($email);
   if(!$mailer->Send())
   {
       // message not sent
  echo '
Unfortunately the activation email could not be sent and user registration has failed. Please go back and try again.
';
      echo '
';
  include_once ("resources/php/footer.php");
  exit;
   }
   else
   {
       // message sent
       "Email sent successfully!";
   }
    }

thanks!

Body:
Try using

$mailer->Port = 465;

Port 587 is for TLS, the SSL port is 465.


问:
Best way to group filename based on filename in Bash?
I have a folder with the following files:

```<code>DA-001-car.jpg
DA-001-dog.jpg
DA-001-coffee.jpg
DA-002-house.jpg
DA-003-coffee.jpg
DA-003-cat.jpg
...
</code>```

I want to generate this (CSV) output:

```<code>SKU, IMAGE
DA-001, "DA-001-car.jpg, DA-001-dog.jpg, DA-001-coffee.jpg"
DA-002, "DA-001-house.jpg"
DA-003, "DA-001-coffee.jpg, DA-001-cat.jpg"
</code>```

I tried to program this in Bash:

```<code>#!/bin/bash
echo "SKU, FILE" >> tmp.csv
for file in /home/calvin/test/*.jpg
do
    SKU_NAME="${file##*/}"
    echo ${SKU_NAME:0:6}, \"inner for-loop?, ?, ?\" >> tmp.csv
done
uniq tmp.csv output.csv
</code>```

As you can see I'm a noob as for programming :)
Please help me out, thanks in advance!

答:
```<code>awk '
    BEGIN {
        OFS = ", "
        print "SKU", "IMAGE"
        for (i=1; i<ARGC; i++) {
            curr = fname = ARGV[i]
            sub(/-[^-]+$/,"",curr)
            if ( curr != prev ) {
                if ( i > 1 ) {
                    print prev, "\"" fnames "\""
                }
                prev = curr
                fnames = ""
            }
            fnames = (fnames == "" ? "" : fnames OFS) fname
        }
        print prev, "\"" fnames "\""
        exit
    }
' /home/calvin/test/*.jpg
SKU, IMAGE
DA-001, "DA-001-car.jpg, DA-001-coffee.jpg, DA-001-dog.jpg"
DA-002, "DA-002-house.jpg"
DA-003, "DA-003-cat.jpg, DA-003-coffee.jpg"
</code>```

Body:
I have a folder with the following files:

DA-001-car.jpg
DA-001-dog.jpg
DA-001-coffee.jpg
DA-002-house.jpg
DA-003-coffee.jpg
DA-003-cat.jpg
...

I want to generate this (CSV) output:

SKU, IMAGE
DA-001, "DA-001-car.jpg, DA-001-dog.jpg, DA-001-coffee.jpg"
DA-002, "DA-001-house.jpg"
DA-003, "DA-001-coffee.jpg, DA-001-cat.jpg"

I tried to program this in Bash:

#!/bin/bash
echo "SKU, FILE" >> tmp.csv
for file in /home/calvin/test/*.jpg
do
    SKU_NAME="${file##*/}"
    echo ${SKU_NAME:0:6}, \"inner for-loop?, ?, ?\" >> tmp.csv
done
uniq tmp.csv output.csv

As you can see I'm a noob as for programming :)
Please help me out, thanks in advance!


问:
Conversion from not equal to equal in nat
I have function,whose output is some natural number.I have proved a lemma,that output of this function cannot be zero. It means output is equal to some natural number S m.I want to convert the above lemma.</p>

```<code>Theorem greater:forall (m :nat)(l:list nat),
 m=?0=false ->
 0=? (f1 + m)=false->
 (f1 + m)= S m.
</code>```

答:
The statement you entered does not type check. Regardless, I don't see how it could hold -- for instance, if by l you mean f1 : nat, then the statement would imply that 3 = 2.

```<code>Require Import Coq.Arith.Arith.

Theorem greater:forall (m :nat)(f1:nat),
 m=?0=false ->
 0=? (f1 + m)=false->
 (f1 + m)= S m.
Admitted.

Lemma contra : False.
Proof.
pose proof (greater 1 2 eq_refl eq_refl).
easy.
Qed.
</code>```

Proving that something that is not zero is a successor can be done as follows:

```<code>Require Import Coq.Arith.Arith.

Lemma not_zero_succ :
  forall n, n <> 0 ->
  exists m, n = S m.
Proof. destruct n as [|n]; eauto; easy. Qed.
</code>```

Edit The complete statement you wrote below is also contradictory:

```<code>Require Import Coq.Arith.Arith.
Require Import Coq.Lists.List.
Import ListNotations.

Fixpoint lt_numb (n: nat) (l: list nat) : nat :=
  match l with
  | nil => 0
  | h::tl =>
    if h <? n then S (lt_numb n tl) else lt_numb n tl
  end.

Fixpoint greatest (large: nat) (l: list nat) : nat :=
  match large with
  | O => 0
  | S m' => (lt_numb large l) + (greatest m' l)
  end.

Definition change (n: nat) (l: list nat) : list nat :=
  match l with
  | nil => l
  | h::tl => if n <? h then l else n::tl
  end.

Fixpoint g_value (elements: nat) (l: list nat) : nat :=
  match l with
  | nil => 0
  | [n] => n
  | h :: l =>
    match elements with
    | O => h
    | S elements' => g_value elements' (change h l)
    end
  end.

Theorem no_elements : forall (m n z :nat)(l:list nat),
    m=?0=false -> greatest(g_value (length (n :: l)) (n :: l) + m) (n :: l) = (S z).
Proof. Admitted.

Goal False.
pose proof (no_elements 1 0 1 [] eq_refl).
simpl in H.
discriminate.
Qed.
</code>```

Body:
I have function,whose output is some natural number.I have proved a lemma,that output of this function cannot be zero. It means output is equal to some natural number S m.I want to convert the above lemma.

Theorem greater:forall (m :nat)(l:list nat),
 m=?0=false ->
 0=? (f1 + m)=false->
 (f1 + m)= S m.

Body:
The statement you entered does not type check. Regardless, I don't see how it could hold -- for instance, if by l you mean f1 : nat, then the statement would imply that 3 = 2.

Require Import Coq.Arith.Arith.

Theorem greater:forall (m :nat)(f1:nat),
 m=?0=false ->
 0=? (f1 + m)=false->
 (f1 + m)= S m.
Admitted.

Lemma contra : False.
Proof.
pose proof (greater 1 2 eq_refl eq_refl).
easy.
Qed.

Proving that something that is not zero is a successor can be done as follows:

Require Import Coq.Arith.Arith.

Lemma not_zero_succ :
  forall n, n <> 0 ->
  exists m, n = S m.
Proof. destruct n as [|n]; eauto; easy. Qed.

Edit The complete statement you wrote below is also contradictory:

Require Import Coq.Arith.Arith.
Require Import Coq.Lists.List.
Import ListNotations.

Fixpoint lt_numb (n: nat) (l: list nat) : nat :=
  match l with
  | nil => 0
  | h::tl =>
    if h <? n then S (lt_numb n tl) else lt_numb n tl
  end.

Fixpoint greatest (large: nat) (l: list nat) : nat :=
  match large with
  | O => 0
  | S m' => (lt_numb large l) + (greatest m' l)
  end.

Definition change (n: nat) (l: list nat) : list nat :=
  match l with
  | nil => l
  | h::tl => if n <? h then l else n::tl
  end.

Fixpoint g_value (elements: nat) (l: list nat) : nat :=
  match l with
  | nil => 0
  | [n] => n
  | h :: l =>
    match elements with
    | O => h
    | S elements' => g_value elements' (change h l)
    end
  end.

Theorem no_elements : forall (m n z :nat)(l:list nat),
    m=?0=false -> greatest(g_value (length (n :: l)) (n :: l) + m) (n :: l) = (S z).
Proof. Admitted.

Goal False.
pose proof (no_elements 1 0 1 [] eq_refl).
simpl in H.
discriminate.
Qed.


问:
split integer, float and Chinese character with Python
Here is the raw data.

```<code>[['9河北36010.27'],
 ['10福建35804.04'],
 ...
 ['23黑龙江16361.62']]
</code>```

Each string consists of 3 parts which are id, province name and GDP value.

This code is to extract data from the raw

```<code>provc_list = []
gdp_list = []
for i in raw:
    match_1 = re.match('\d{1,9}', i[0])
    stw_provc = i[0][match_1.end():]
    match_2 = re.search('\d{1,9}', stw_provc)
    provc_list.append(stw_provc[:match_2.start()])
    gdp_list.append(stw_provc[match_2.start():])
</code>```

then I got

```<code>['广东', '江苏', '山东']
['97277.77', '92595.4', '76469.67']
</code>```

the code works well as expected. Is there more elegant/graceful/refined code to do the job?

Body:
Here is the raw data.

[['9河北36010.27'],
 ['10福建35804.04'],
 ...
 ['23黑龙江16361.62']]

Each string consists of 3 parts which are id, province name and GDP value.

This code is to extract data from the raw

provc_list = []
gdp_list = []
for i in raw:
    match_1 = re.match('\d{1,9}', i[0])
    stw_provc = i[0][match_1.end():]
    match_2 = re.search('\d{1,9}', stw_provc)
    provc_list.append(stw_provc[:match_2.start()])
    gdp_list.append(stw_provc[match_2.start():])

then I got

['广东', '江苏', '山东']
['97277.77', '92595.4', '76469.67']

the code works well as expected. Is there more elegant/graceful/refined code to do the job?

Body:
You may try this:

>>> a = [['9河北36010.27'],
...   ['10福建35804.04'],]
>>>
>>> import re
>>> re.findall( r'(\d+)([^\d]+)([0-9.]+)', a[0][0])
[('9', '河北', '36010.27')]
>>>


问:
problem implementing simple linked list in c++, no output
For my C++ programming course, my task is to implement a simple linked list using my own functions of addElement(), printList() and deleteList().

When I compile and run the following program, nothing happens. I get no warnings and using valgrind I couldn't find anything wrong.

The program code I am working with is as follows:

```<code>#include <iostream>
using namespace std;

struct Node {
  int data;
  Node *next;
  Node(int i) : data(i), next(nullptr) {}
  friend ostream &operator<<(ostream &os, const Node &n) {
    os << "Node\n"
       << "\tdata: " << n.data << "\n\tthis: " << &n << "\n\tnext: " << n.next;
    return os;
  }
};

void addElement(Node **head, int data);
void printList(Node *head);
void deleteList(Node *head);

void deleteList(Node *head) {
  Node *next = head;
  while (next) {
    Node *deleteMe = next;
    next = next->next;
    delete deleteMe;
  }
}

void addElement(Node **head, int data) {
  Node *n = new Node(data);
  n->next = *head;
  head = &n;
}

void printList(Node *head) {
  Node *next = head;
  while(next) {
    cout << next->data;
    next = next->next;
  }
}

int main() {
  Node *list = nullptr;
  addElement(&list, 1);
  addElement(&list, 2);
  addElement(&list, 3);
  addElement(&list, 4);
  printList(list);
  deleteList(list);
  return 0;
}
</code>```

I have no idea why my code does not work and produce output.
Please help and kind regards

答:
```<code>void addElement(Node **head, int data) {
  Node *n = new Node(data);
  n->next = *head;
  head = &n;
}
</code>```

Wrong in a couple of ways:

head is a local variable in this function, changing it will have no effect on the outside world, you should be changing *head; and

n is already a pointer to a node, you should use it directly, rather than using the address of it.

In other words, that final line of code should be:

```<code>*head = n;
</code>```

And, a few other points. First, you can avoid all those double-pointer issues prevalent in C if you just learn to use references in C++, that's one of the great advantages of the latter language. Your code then becomes:

```<code>void addElement(Node *&head, int data) {
  Node *n = new Node(data);
  n->next = head;
  head = n;
}

// Call with: "addElement(list, 1)".
</code>```

Second, if you want your items appended to the end of the list (a more usual requirement), you can do that in a couple of ways. The first is the search for the final one then append it after there:

```<code>void addElement(Node *&head, int data) {
  Node *n = new Node(data);
    if (head == nullptr) {
        head = n;
    } else {
        Node *curr = head;
        while (curr->next != nullptr) {
            curr = curr->next;
        }
        curr->next = n;
    }
}
</code>```

The second (more efficient) is to maintain the tail element as well so that it is always available and you don't have to search for it on every insertion. That's best done with a split of functionality into separate List and Node classes, such as with:

```<code>#include <iostream>

using namespace std;

struct Node {
    int data;
    Node *next;
    Node(int i) : data(i), next(nullptr) {}
};

struct List {
    Node *head;
    Node *tail;
    List() : head(nullptr), tail(nullptr) {}
};

void deleteList(List *&list) {
    Node *curr = list->head;
    while (curr != nullptr) {
        Node *deleteMe = curr;
        curr = curr->next;
        delete deleteMe;
    }
    delete list;
    list = nullptr;
}

void addElement(List *list, int data) {
    Node *n = new Node(data);
    if (list->head == nullptr) {
        list->head = list->tail = n;
    } else {
        list->tail->next = n;
        list->tail = n;
    }
}

void printList(List *list) {
    Node *curr = list->head;
    while (curr != nullptr) {
        cout << curr->data;
        curr = curr->next;
    }
    cout << '\n';
}

int main() {
    List *list = new List();

    addElement(list, 1);
    addElement(list, 2);
    addElement(list, 3);
    addElement(list, 4);

    printList(list);

    deleteList(list);

    return 0;
}
</code>```

And, finally, though I realise you're still a relative beginner, you should at least be aware of the benefits of encapsulation (information hiding). A proper implementation would have the data in each class as private members, modifiable only by functions within the class itself (although at the request of outside callers, of course).

As it stands at the moment, I could write code that could easily modify the internal data of your class (data and next), causing serious issues. If the internal data was private, you could better protect against that.

Although I wouldn't suggest using this code for your assignment (assuming this is educational work), I'll include it anyway for your examination:

```<code>#include <iostream>
#include <functional>

using namespace std;

// Only used within List and private there so leave as public.

struct Node {
    Node(int value) : m_data(value), m_next(nullptr) {}
    int m_data;
    Node *m_next;
};

// Properly encapsulae to protect memebrs.

class List {
public:
    List() : m_head(nullptr), m_tail(nullptr) {}
    ~List() { clearAll(); }
    void clearAll();
    void addElement(int data);
    void traverse(const std::function<void(int)> &callback);
private:
    Node *m_head;
    Node *m_tail;
};

// Clear all items in list.

void List::clearAll() {
    Node *curr = m_head;
    while (curr != nullptr) {
        Node *deleteMe = curr;
        curr = curr->m_next;
        delete deleteMe;
    }
    m_head = m_tail = nullptr;
}

// Add an item to list.

void List::addElement(int data) {
    Node *node = new Node(data);
    if (m_head == nullptr) {
        m_head = m_tail = node;
    } else {
        m_tail->m_next = node;
        m_tail = node;
    }
}

// Traverse list, calling a callback for each item.

void List::traverse(const std::function<void(int)> &callback) {
    Node *curr = m_head;
    while (curr != nullptr) {
        callback(curr->m_data);
        curr = curr->m_next;
    }
}

// Test harness for the code above.

int main() {
    List list; // could also 'new' this but not needed.

    list.addElement(1);
    list.addElement(2);
    list.addElement(3);
    list.addElement(4);

     // Advanced lambda stuff for callback.

    std::cout << "Items are:";
    list.traverse([](int i) -> void {
        std::cout << " " << i;
    });
    std::cout << "\n";

    return 0;
}
</code>```

Body:
For my C++ programming course, my task is to implement a simple linked list using my own functions of addElement(), printList() and deleteList().

When I compile and run the following program, nothing happens. I get no warnings and using valgrind I couldn't find anything wrong.

The program code I am working with is as follows:

#include <iostream>
using namespace std;

struct Node {
  int data;
  Node *next;
  Node(int i) : data(i), next(nullptr) {}
  friend ostream &operator<<(ostream &os, const Node &n) {
    os << "Node\n"
       << "\tdata: " << n.data << "\n\tthis: " << &n << "\n\tnext: " << n.next;
    return os;
  }
};

void addElement(Node **head, int data);
void printList(Node *head);
void deleteList(Node *head);

void deleteList(Node *head) {
  Node *next = head;
  while (next) {
    Node *deleteMe = next;
    next = next->next;
    delete deleteMe;
  }
}

void addElement(Node **head, int data) {
  Node *n = new Node(data);
  n->next = *head;
  head = &n;
}

void printList(Node *head) {
  Node *next = head;
  while(next) {
    cout << next->data;
    next = next->next;
  }
}

int main() {
  Node *list = nullptr;
  addElement(&list, 1);
  addElement(&list, 2);
  addElement(&list, 3);
  addElement(&list, 4);
  printList(list);
  deleteList(list);
  return 0;
}

I have no idea why my code does not work and produce output.
Please help and kind regards

Body:
void addElement(Node **head, int data) {
  Node *n = new Node(data);
  n->next = *head;
  head = &n;
}

Wrong in a couple of ways:

head is a local variable in this function, changing it will have no effect on the outside world, you should be changing *head; and

n is already a pointer to a node, you should use it directly, rather than using the address of it.

In other words, that final line of code should be:

*head = n;

And, a few other points. First, you can avoid all those double-pointer issues prevalent in C if you just learn to use references in C++, that's one of the great advantages of the latter language. Your code then becomes:

void addElement(Node *&head, int data) {
  Node *n = new Node(data);
  n->next = head;
  head = n;
}

// Call with: "addElement(list, 1)".

Second, if you want your items appended to the end of the list (a more usual requirement), you can do that in a couple of ways. The first is the search for the final one then append it after there:

void addElement(Node *&head, int data) {
  Node *n = new Node(data);
    if (head == nullptr) {
        head = n;
    } else {
        Node *curr = head;
        while (curr->next != nullptr) {
            curr = curr->next;
        }
        curr->next = n;
    }
}

The second (more efficient) is to maintain the tail element as well so that it is always available and you don't have to search for it on every insertion. That's best done with a split of functionality into separate List and Node classes, such as with:

#include <iostream>

using namespace std;

struct Node {
    int data;
    Node *next;
    Node(int i) : data(i), next(nullptr) {}
};

struct List {
    Node *head;
    Node *tail;
    List() : head(nullptr), tail(nullptr) {}
};

void deleteList(List *&list) {
    Node *curr = list->head;
    while (curr != nullptr) {
        Node *deleteMe = curr;
        curr = curr->next;
        delete deleteMe;
    }
    delete list;
    list = nullptr;
}

void addElement(List *list, int data) {
    Node *n = new Node(data);
    if (list->head == nullptr) {
        list->head = list->tail = n;
    } else {
        list->tail->next = n;
        list->tail = n;
    }
}

void printList(List *list) {
    Node *curr = list->head;
    while (curr != nullptr) {
        cout << curr->data;
        curr = curr->next;
    }
    cout << '\n';
}

int main() {
    List *list = new List();

    addElement(list, 1);
    addElement(list, 2);
    addElement(list, 3);
    addElement(list, 4);

    printList(list);

    deleteList(list);

    return 0;
}

And, finally, though I realise you're still a relative beginner, you should at least be aware of the benefits of encapsulation (information hiding). A proper implementation would have the data in each class as private members, modifiable only by functions within the class itself (although at the request of outside callers, of course).

As it stands at the moment, I could write code that could easily modify the internal data of your class (data and next), causing serious issues. If the internal data was private, you could better protect against that.

Although I wouldn't suggest using this code for your assignment (assuming this is educational work), I'll include it anyway for your examination:

#include <iostream>
#include <functional>

using namespace std;

// Only used within List and private there so leave as public.

struct Node {
    Node(int value) : m_data(value), m_next(nullptr) {}
    int m_data;
    Node *m_next;
};

// Properly encapsulae to protect memebrs.

class List {
public:
    List() : m_head(nullptr), m_tail(nullptr) {}
    ~List() { clearAll(); }
    void clearAll();
    void addElement(int data);
    void traverse(const std::function<void(int)> &callback);
private:
    Node *m_head;
    Node *m_tail;
};

// Clear all items in list.

void List::clearAll() {
    Node *curr = m_head;
    while (curr != nullptr) {
        Node *deleteMe = curr;
        curr = curr->m_next;
        delete deleteMe;
    }
    m_head = m_tail = nullptr;
}

// Add an item to list.

void List::addElement(int data) {
    Node *node = new Node(data);
    if (m_head == nullptr) {
        m_head = m_tail = node;
    } else {
        m_tail->m_next = node;
        m_tail = node;
    }
}

// Traverse list, calling a callback for each item.

void List::traverse(const std::function<void(int)> &callback) {
    Node *curr = m_head;
    while (curr != nullptr) {
        callback(curr->m_data);
        curr = curr->m_next;
    }
}

// Test harness for the code above.

int main() {
    List list; // could also 'new' this but not needed.

    list.addElement(1);
    list.addElement(2);
    list.addElement(3);
    list.addElement(4);

     // Advanced lambda stuff for callback.

    std::cout << "Items are:";
    list.traverse([](int i) -> void {
        std::cout << " " << i;
    });
    std::cout << "\n";

    return 0;
}


问:
How can i check if the login credentials are valid using praw
So im trying to make a bot that fetch random post url's from a subreddit and want it to check if the login credentials are valid so heres what i came up with:</p>

```<code>import praw
import pandas as pd
import datetime as dt

username = input("Your user name:\n")
password = input("Your Password:\n")

reddit = praw.Reddit(client_id='xxxxxxxxxxxxx', \
                     client_secret='xxxxxxxxxxxxxxxxxxxxxxxx', \
                     user_agent='Fetch', \
                     username=username, \
                     password=password)

if reddit == thats where i dont know what to type
    submission = reddit.subreddit("gtaonline").random()
    print(submission.url)

else:
    print("Enter valid credentials")
    quit()
</code>```

答:
You can use reddit.user.me(). This method gives you the authenticated user, which as a side effect causes the Reddit instance to use the credentials.

If the credentials are valid, this returns a Redditor instance. If your credentials are invalid, calling it will result in a prawcore.ResponseException.

You can use this fact to test your credentials:

from prawcore import ResponseException

def authenticated(reddit):
    """Determine whether the given Reddit instance has valid credentials."""
    try:
        reddit.user.me()
    except ResponseException:
        return False
    else:
        return True
```

<p>If you define this function in your script, your condition becomes</p>

<pre class="lang-py prettyprint-override"><code>if authenticated(reddit):
</code>```

Body:
So im trying to make a bot that fetch random post url's from a subreddit and want it to check if the login credentials are valid so heres what i came up with:

import praw
import pandas as pd
import datetime as dt

username = input("Your user name:\n")
password = input("Your Password:\n")

reddit = praw.Reddit(client_id='xxxxxxxxxxxxx', \
                     client_secret='xxxxxxxxxxxxxxxxxxxxxxxx', \
                     user_agent='Fetch', \
                     username=username, \
                     password=password)

if reddit == thats where i dont know what to type
    submission = reddit.subreddit("gtaonline").random()
    print(submission.url)

else:
    print("Enter valid credentials")
    quit()

Body:
You can use reddit.user.me(). This method gives you the authenticated user, which as a side effect causes the Reddit instance to use the credentials.

If the credentials are valid, this returns a Redditor instance. If your credentials are invalid, calling it will result in a prawcore.ResponseException.

You can use this fact to test your credentials:

from prawcore import ResponseException

def authenticated(reddit):
    """Determine whether the given Reddit instance has valid credentials."""
    try:
        reddit.user.me()
    except ResponseException:
        return False
    else:
        return True

If you define this function in your script, your condition becomes

if authenticated(reddit):


问:
Restore database .bak file to azure elastic pool database from VM
Restore database .bak file to azure elastic pool database from VM

How to restore database .bak file to azure elastic pool databases directly, I used the option "Deploy Database to Microsoft Azure SQL Database"  but every time creates a new database outside of the elastic pool.

We are looking for a solution to create a new database in an elastic pool only, any alternative methods we can achieve.

答:
Azure SQL Database does not currently support that customers use bak file as a restore to generate a new database on Azure SQL Database. The only method used to restore in Azure SQL Database is to import from BACPAC files by following this document :  https://learn.microsoft.com/en-us/azure/azure-sql/database/database-import?tabs=azure-powershell.

So according to the situation, you use  the option "Deploy Database to Microsoft Azure SQL Database" then migrate the database to  azure elastic pool. Regarding how to migrate it, please refer to  https://www.fmsinc.com/microsoft-azure/sql-server/pooled/index.htm


问:
Konva doesn't seem to take width into account
When I set a width for my Konva stage, it doesn't seem to be taken into account:

https://codesandbox.io/s/vue-template-4g1b7?file=/src/App.vue

When you change the height, everything works fine, but the width seems stuck to the width of the page. Is there away to force the stage to fit the width we want?

Thanks in advance.

答:
Thanks to Anton Lavrenov (https://github.com/konvajs/konva/issues/915), I had the explanation:

That is because your container has display: block in styles (default
  for div). You may set it to display: inline-block.

I updated the sandbox.


问:
BigQuery SQL for 28-day sliding window aggregate (without writing 28 lines of SQL)
I'm trying to compute a 28 day moving sum in BigQuery using the LAG function.

The top answer to this question

Bigquery SQL for sliding window aggregate

from Felipe Hoffa indicates that that you can use the LAG function. An example of this would be:

```<code>SELECT
    spend + spend_lagged_1day + spend_lagged_2day + spend_lagged_3day + ... +  spend_lagged_27day as spend_28_day_sum,
    user,
    date
FROM (
  SELECT spend,
         LAG(spend, 1) OVER (PARTITION BY user ORDER BY date) spend_lagged_1day,
         LAG(spend, 2) OVER (PARTITION BY user ORDER BY date) spend_lagged_2day,
         LAG(spend, 3) OVER (PARTITION BY user ORDER BY date) spend_lagged_3day,
         ...
         LAG(spend, 28) OVER (PARTITION BY user ORDER BY date) spend_lagged_day,
         user,
         date
  FROM user_spend
)
</code>```

Is there a way to do this without having to write out 28 lines of SQL!

答:
Here is an alternate take that I found to be flexible and effective:

WITH users AS
 (SELECT 'Isabella' as user, 1 as spend, DATE(2020, 03, 28) as date
  UNION ALL SELECT 'Isabella', 2, DATE(2020, 03, 29)
  UNION ALL SELECT 'Daniel', 3, DATE(2020, 03, 24)
  UNION ALL SELECT 'Andrew', 4, DATE(2020, 03, 23)
  UNION ALL SELECT 'Daniel', 5, DATE(2020, 03, 11)
  UNION ALL SELECT 'Jose', 6, DATE(2020, 03, 17))
SELECT
user,
max(sum(case date_diff(date(2020,04,15), date, day) between 0 and 28
        when true then spend else 0 end)) over(partition by user) as spend_28_day_sum
FROM users
group by user
```

```+------------------------------+
| user      | spend_28_day_sum |
+------------------------------+
| Andrew    | 4                |
| Daniel    | 3                |
| Isabella  | 3                |
| Jose      | 0                |
+------------------------------+
```

You could change the specified date for the "window function" to current_date() or cross join with a generated date array to see how users change over time.

Body:
I'm trying to compute a 28 day moving sum in BigQuery using the LAG function.

The top answer to this question

Bigquery SQL for sliding window aggregate

from Felipe Hoffa indicates that that you can use the LAG function. An example of this would be:

SELECT
    spend + spend_lagged_1day + spend_lagged_2day + spend_lagged_3day + ... +  spend_lagged_27day as spend_28_day_sum,
    user,
    date
FROM (
  SELECT spend,
         LAG(spend, 1) OVER (PARTITION BY user ORDER BY date) spend_lagged_1day,
         LAG(spend, 2) OVER (PARTITION BY user ORDER BY date) spend_lagged_2day,
         LAG(spend, 3) OVER (PARTITION BY user ORDER BY date) spend_lagged_3day,
         ...
         LAG(spend, 28) OVER (PARTITION BY user ORDER BY date) spend_lagged_day,
         user,
         date
  FROM user_spend
)

Is there a way to do this without having to write out 28 lines of SQL!

Body:
Here is an alternate take that I found to be flexible and effective:

WITH users AS
 (SELECT 'Isabella' as user, 1 as spend, DATE(2020, 03, 28) as date
  UNION ALL SELECT 'Isabella', 2, DATE(2020, 03, 29)
  UNION ALL SELECT 'Daniel', 3, DATE(2020, 03, 24)
  UNION ALL SELECT 'Andrew', 4, DATE(2020, 03, 23)
  UNION ALL SELECT 'Daniel', 5, DATE(2020, 03, 11)
  UNION ALL SELECT 'Jose', 6, DATE(2020, 03, 17))
SELECT
user,
max(sum(case date_diff(date(2020,04,15), date, day) between 0 and 28
        when true then spend else 0 end)) over(partition by user) as spend_28_day_sum
FROM users
group by user

+------------------------------+
| user      | spend_28_day_sum |
+------------------------------+
| Andrew    | 4                |
| Daniel    | 3                |
| Isabella  | 3                |
| Jose      | 0                |
+------------------------------+

You could change the specified date for the "window function" to current_date() or cross join with a generated date array to see how users change over time.


问:
SQL query to remove consecutive duplicates in table
I have a table in the format below:

```<code>|name |visited_property|visit_date_time    |
|Marry|Residence_inn   |05-25-2020 15:00:01|
|Marry|Residence_inn   |05-25-2020 15:15:01|
|Marry|Residence_inn   |05-25-2020 15:30:01|
|Marry|Hilton_garden   |05-25-2020 17:10:01|
|Marry|Marriott_hotel  |05-25-2020 18:10:01|

|Harry|Hilton_garden   |05-26-2020 10:10:01|
|Harry|Residence_inn   |05-26-2020 12:10:01|
|Harry|Hilton_garden   |05-26-2020 15:10:01|

</code>```

I want to write a query to get the list of distinct properties (and order of visit) they visit. If they visit the same property consecutively, I'd like to count that as 1 visit. If they visit the same property non-consecutively, I'd like to count the visits separately.

Ideally I would like to replicate the table and get rid of the consecutive duplicates to have something that looks like this (getting rid of Marry's 2nd and 3rd visit to Residence Inn since it's 3 visits to that property in a row, while keeping Harry's both visits to Hilton garden since they are non-consecutive):

```<code>|name |visited_property|visit_date_time    |
|Marry|Residence_inn   |05-25-2020 15:00:01|
|Marry|Hilton_garden   |05-25-2020 17:10:01|
|Marry|Marriott_hotel  |05-25-2020 18:10:01|

|Harry|Hilton_garden   |05-26-2020 10:10:01|
|Harry|Residence_inn   |05-26-2020 12:10:01|
|Harry|Hilton_garden   |05-26-2020 15:10:01|
</code>```

What SQL statement can I use? Appreciate your help.

答:
How about adding a unique constraint. Something like following:

```<code># remove duplicate rows
-- create a new temporary table
CREATE TABLE tmp_table_name LIKE existing_table_name;
-- add a unique constraint
ALTER TABLE tmp_table_name ADD UNIQUE(column_name);
-- scan over the existing table to insert entries in the temporary table
INSERT IGNORE INTO tmp_table_name SELECT * FROM existing_table_name ORDER BY column_name;
select * from tmp_table_name;
-- rename tables
RENAME TABLE existing_table_name TO existing_table_name_backup, tmp_table_name TO existing_table_name;
-- drop the backup table
drop table existing_table_name_backup;
select * from existing_table_name;
</code>```

Body:
I have a table in the format below:

|name |visited_property|visit_date_time    |
|Marry|Residence_inn   |05-25-2020 15:00:01|
|Marry|Residence_inn   |05-25-2020 15:15:01|
|Marry|Residence_inn   |05-25-2020 15:30:01|
|Marry|Hilton_garden   |05-25-2020 17:10:01|
|Marry|Marriott_hotel  |05-25-2020 18:10:01|

|Harry|Hilton_garden   |05-26-2020 10:10:01|
|Harry|Residence_inn   |05-26-2020 12:10:01|
|Harry|Hilton_garden   |05-26-2020 15:10:01|

I want to write a query to get the list of distinct properties (and order of visit) they visit. If they visit the same property consecutively, I'd like to count that as 1 visit. If they visit the same property non-consecutively, I'd like to count the visits separately.

Ideally I would like to replicate the table and get rid of the consecutive duplicates to have something that looks like this (getting rid of Marry's 2nd and 3rd visit to Residence Inn since it's 3 visits to that property in a row, while keeping Harry's both visits to Hilton garden since they are non-consecutive):

|name |visited_property|visit_date_time    |
|Marry|Residence_inn   |05-25-2020 15:00:01|
|Marry|Hilton_garden   |05-25-2020 17:10:01|
|Marry|Marriott_hotel  |05-25-2020 18:10:01|

|Harry|Hilton_garden   |05-26-2020 10:10:01|
|Harry|Residence_inn   |05-26-2020 12:10:01|
|Harry|Hilton_garden   |05-26-2020 15:10:01|

What SQL statement can I use? Appreciate your help.

Body:
How about adding a unique constraint. Something like following:

# remove duplicate rows
-- create a new temporary table
CREATE TABLE tmp_table_name LIKE existing_table_name;
-- add a unique constraint
ALTER TABLE tmp_table_name ADD UNIQUE(column_name);
-- scan over the existing table to insert entries in the temporary table
INSERT IGNORE INTO tmp_table_name SELECT * FROM existing_table_name ORDER BY column_name;
select * from tmp_table_name;
-- rename tables
RENAME TABLE existing_table_name TO existing_table_name_backup, tmp_table_name TO existing_table_name;
-- drop the backup table
drop table existing_table_name_backup;
select * from existing_table_name;


问:
Calls to lstrlenA or lstrlenW are returning unexpected values
Summary: In Excel VBA, I've got a function that gets CF_TEXT from the clipboard, and another function for CF_UNICODETEXT. I use lstrlenA / lstrlenW to get the length of the string, but I'm getting unexpected results from those calls. I'd like help to understand why.

Details:

Within my functions, I use CopyMemory after opening the clipboard to get a byte array that I can then turn into a string. I'm in the process of adapting the project for 64-bit Office, and wanted to make sure everything involving CopyMemory is working correctly. That got me testing these clipboard functions, which is how I encountered this issue.

Before calling CopyMemory, I'm calling lstrlenA(pMem) / lstrlenW(pMem) to determine how much to copy. But these calls are returning unexpected lengths.

Here's one of the functions (ignoring locales):

```<code>Function GetANSITextFromClipboard() As String
    Dim hClip As LongPtr, pMem As LongPtr
    Dim cbText As Integer
    Dim abRetString() As Byte
    Dim RetString As String

    If IsClipboardFormatAvailable(CF_TEXT) Then
        If OpenClipboard(0) Then
            hClip = GetClipboardData(CF_TEXT)
            Dim clipSize As LongPtr         'added to check on mem size vs what's reported by lstrlenW
            clipSize = GlobalSize(hClip)
            pMem = GlobalLock(hClip)
            cbText = lstrlenA(pMem)

            If cbText > 0 Then
                ReDim abRetString(0 To cbText)
                CopyMemory abRetString(0), ByVal pMem, cbText '64-bit: should be good if cbText is right
                'strip terminating null
                If abRetString(UBound(abRetString)) = 0 Then
                    ReDim Preserve abRetString(0 To UBound(abRetString) - 1)
                End If
                RetString = StrConv(abRetString, vbUnicode)
            End If
            GlobalUnlock (hClip)
            CloseClipboard
            GetANSITextFromClipboard = RetString
        End If
    End If
End Function
</code>```

These are relevant declares for that function:

```<code>Declare PtrSafe Function OpenClipboard Lib "user32" (ByVal hwnd As LongPtr) As Long 'returns BOOL
Declare PtrSafe Function GetClipboardData Lib "user32" (ByVal wFormat As Long) As LongPtr 'returns HANDLE
Declare PtrSafe Function CloseClipboard Lib "user32" () As Long 'returns BOOL

Declare PtrSafe Function GlobalSize Lib "kernel32" (ByVal hMem As LongPtr) As LongPtr 'returns SIZE_T
Declare PtrSafe Function GlobalLock Lib "kernel32" (ByVal hMem As LongPtr) As LongPtr 'returns LPVOID
Declare PtrSafe Function GlobalUnlock Lib "kernel32" (ByVal hMem As LongPtr) As Long  'returns BOOL

Declare PtrSafe Function lstrlenA Lib "kernel32" (ByVal lpString As String) As Long 'returns int

Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" ( _
    Destination As Any, _
    Source As Any, _
    ByVal length As LongPtr)
</code>```

To test, I copy something to the clipboard then run this:

```<code>Private Sub TestReadClipboard()
    Dim acbfFormats() As CBFormat
    Dim i As Integer
    Dim strPrompt As String
    Dim strBuffer As String

    If GetClipboardFormats(acbfFormats()) Then
        strPrompt = UBound(acbfFormats()) - LBound(acbfFormats()) + 1 & " formats:" & vbCrLf & vbCrLf
        For i = LBound(acbfFormats()) To UBound(acbfFormats())
            strPrompt = strPrompt & acbfFormats(i).uFormat & " = " & acbfFormats(i).name _
                        & " (" & acbfFormats(i).Size & " bytes)" & vbCrLf
        Next
    Else
        strPrompt = "Formats not available."
    End If
    MsgBox strPrompt

    strPrompt = "Plain text: " & GetANSITextFromClipboard & vbCrLf & vbCrLf
    strPrompt = strPrompt & "Unicode text: " & GetUnicodeTextFromClipboard & vbCrLf & vbCrLf
    strPrompt = strPrompt & "Locale: " & Right("00000000" & Hex(GetClipboardLocale), 8)
    MsgBox strPrompt
End Sub
</code>```

CBFormat is a custom type, and GetClipboardFormats is a custom function that collects details about the formats in a CBFormat array. In particular, CBFormat.size for each format is set by calling GlobalSize().

At the first MsgBox strPrompt call, the formats I see are as expected. And the size of data for each format is as expected: at least as long as the text I copied. Then when I call into GetANSITextFromClipboard, the size seen earlier is the same as clipSize.

But cbText is consistently wrong. I've tried copying to the clipboard multiple times from different sources, and lstrlenA is always returning 13. In the Unicode function, lstrlenW is always returning 7.

(I don't use clipSize as the length to copy because then I end up with null and following garbage in the string. I could walk the byte array looking for null and then redim to that, but I shouldn't need to.)

Question: Why don't my calls to lstrlenA/lstrlenW work?

答: Your declaration of lstrlenA() is wrong. Don't use String, that is not an 8bit string in VBA, it is a 16bit COM BSTR string. Since you are passing a LongPtr from GlobalLock() to lstrlenA(), use LongPtr as the parameter type instead of String. Otherwise, you will just have to scan the byte array manually.

Body:
Summary: In Excel VBA, I've got a function that gets CF_TEXT from the clipboard, and another function for CF_UNICODETEXT. I use lstrlenA / lstrlenW to get the length of the string, but I'm getting unexpected results from those calls. I'd like help to understand why.

Details:

Within my functions, I use CopyMemory after opening the clipboard to get a byte array that I can then turn into a string. I'm in the process of adapting the project for 64-bit Office, and wanted to make sure everything involving CopyMemory is working correctly. That got me testing these clipboard functions, which is how I encountered this issue.

Before calling CopyMemory, I'm calling lstrlenA(pMem) / lstrlenW(pMem) to determine how much to copy. But these calls are returning unexpected lengths.

Here's one of the functions (ignoring locales):

Function GetANSITextFromClipboard() As String
    Dim hClip As LongPtr, pMem As LongPtr
    Dim cbText As Integer
    Dim abRetString() As Byte
    Dim RetString As String

    If IsClipboardFormatAvailable(CF_TEXT) Then
        If OpenClipboard(0) Then
            hClip = GetClipboardData(CF_TEXT)
            Dim clipSize As LongPtr         'added to check on mem size vs what's reported by lstrlenW
            clipSize = GlobalSize(hClip)
            pMem = GlobalLock(hClip)
            cbText = lstrlenA(pMem)

            If cbText > 0 Then
                ReDim abRetString(0 To cbText)
                CopyMemory abRetString(0), ByVal pMem, cbText '64-bit: should be good if cbText is right
                'strip terminating null
                If abRetString(UBound(abRetString)) = 0 Then
                    ReDim Preserve abRetString(0 To UBound(abRetString) - 1)
                End If
                RetString = StrConv(abRetString, vbUnicode)
            End If
            GlobalUnlock (hClip)
            CloseClipboard
            GetANSITextFromClipboard = RetString
        End If
    End If
End Function

These are relevant declares for that function:

Declare PtrSafe Function OpenClipboard Lib "user32" (ByVal hwnd As LongPtr) As Long 'returns BOOL
Declare PtrSafe Function GetClipboardData Lib "user32" (ByVal wFormat As Long) As LongPtr 'returns HANDLE
Declare PtrSafe Function CloseClipboard Lib "user32" () As Long 'returns BOOL

Declare PtrSafe Function GlobalSize Lib "kernel32" (ByVal hMem As LongPtr) As LongPtr 'returns SIZE_T
Declare PtrSafe Function GlobalLock Lib "kernel32" (ByVal hMem As LongPtr) As LongPtr 'returns LPVOID
Declare PtrSafe Function GlobalUnlock Lib "kernel32" (ByVal hMem As LongPtr) As Long  'returns BOOL

Declare PtrSafe Function lstrlenA Lib "kernel32" (ByVal lpString As String) As Long 'returns int

Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" ( _
    Destination As Any, _
    Source As Any, _
    ByVal length As LongPtr)

To test, I copy something to the clipboard then run this:

Private Sub TestReadClipboard()
    Dim acbfFormats() As CBFormat
    Dim i As Integer
    Dim strPrompt As String
    Dim strBuffer As String

    If GetClipboardFormats(acbfFormats()) Then
        strPrompt = UBound(acbfFormats()) - LBound(acbfFormats()) + 1 & " formats:" & vbCrLf & vbCrLf
        For i = LBound(acbfFormats()) To UBound(acbfFormats())
            strPrompt = strPrompt & acbfFormats(i).uFormat & " = " & acbfFormats(i).name _
                        & " (" & acbfFormats(i).Size & " bytes)" & vbCrLf
        Next
    Else
        strPrompt = "Formats not available."
    End If
    MsgBox strPrompt

    strPrompt = "Plain text: " & GetANSITextFromClipboard & vbCrLf & vbCrLf
    strPrompt = strPrompt & "Unicode text: " & GetUnicodeTextFromClipboard & vbCrLf & vbCrLf
    strPrompt = strPrompt & "Locale: " & Right("00000000" & Hex(GetClipboardLocale), 8)
    MsgBox strPrompt
End Sub

CBFormat is a custom type, and GetClipboardFormats is a custom function that collects details about the formats in a CBFormat array. In particular, CBFormat.size for each format is set by calling GlobalSize().

At the first MsgBox strPrompt call, the formats I see are as expected. And the size of data for each format is as expected: at least as long as the text I copied. Then when I call into GetANSITextFromClipboard, the size seen earlier is the same as clipSize.

But cbText is consistently wrong. I've tried copying to the clipboard multiple times from different sources, and lstrlenA is always returning 13. In the Unicode function, lstrlenW is always returning 7.

(I don't use clipSize as the length to copy because then I end up with null and following garbage in the string. I could walk the byte array looking for null and then redim to that, but I shouldn't need to.)

Question: Why don't my calls to lstrlenA/lstrlenW work?


问:
MISSING-INPUT-RESPONSE recaptcha error in codeigniter php
i have created recaptcha for my form in codeigniter, the recaptcha function is like below in my controller:

public function validate_captcha() {
          $recaptcha = trim($this->input->post('g-recaptcha-response'));
          $userIp= $this->input->ip_address();
          $secret='6LcuEP4UAAAAAGa1zwXxGTV0r1fNHMZqnTGeN-c_';

          $secretdata = array(
              'secret' => "$secret",
              'response' => "$recaptcha",
              'remoteip' =>"$userIp"
          );

          $verify = curl_init();
          curl_setopt($verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
          curl_setopt($verify, CURLOPT_POST, true);
          curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($secretdata));
          curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false);
          curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
          $response = curl_exec($verify);
          $status= json_decode($response, true);

          if(empty($status['success'])){
              return FALSE;
          }else{
              return TRUE;
          }
      }```

now the problem is this is giving me the following error:

{"SUCCESS":FALSE,"ERROR-CODES":["MISSING-INPUT-RESPONSE"]}

can anyone please tell me what i did wrong in my code, thanks in advance

答:
I think Method should be GET instead of POST.

Please use below code to verify Google captcha.

```<code><?php

public function validate_captcha() {
  $recaptcha = trim($this->input->post('g-recaptcha-response'));
  $userIp= $this->input->ip_address();
  $secret='6LcuEP4UAAAAAGa1zwXxGTV0r1fNHMZqnTGeN-c_';

  $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$recaptcha.'&remoteip='.$userIp);
  $responseData = json_decode($verifyResponse);
    if(!$responseData->success){
        echo "failed";
    }else{
        echo "success";
    }

}
</code>```

Body:
i have created recaptcha for my form in codeigniter, the recaptcha function is like below in my controller:

public function validate_captcha() {
          $recaptcha = trim($this->input->post('g-recaptcha-response'));
          $userIp= $this->input->ip_address();
          $secret='6LcuEP4UAAAAAGa1zwXxGTV0r1fNHMZqnTGeN-c_';

          $secretdata = array(
              'secret' => "$secret",
              'response' => "$recaptcha",
              'remoteip' =>"$userIp"
          );

          $verify = curl_init();
          curl_setopt($verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
          curl_setopt($verify, CURLOPT_POST, true);
          curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($secretdata));
          curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false);
          curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
          $response = curl_exec($verify);
          $status= json_decode($response, true);

          if(empty($status['success'])){
              return FALSE;
          }else{
              return TRUE;
          }
      }

now the problem is this is giving me the following error:

{"SUCCESS":FALSE,"ERROR-CODES":["MISSING-INPUT-RESPONSE"]}

can anyone please tell me what i did wrong in my code, thanks in advance

Body:
I think Method should be GET instead of POST.

Please use below code to verify Google captcha.

<?php

public function validate_captcha() {
  $recaptcha = trim($this->input->post('g-recaptcha-response'));
  $userIp= $this->input->ip_address();
  $secret='6LcuEP4UAAAAAGa1zwXxGTV0r1fNHMZqnTGeN-c_';

  $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$recaptcha.'&remoteip='.$userIp);
  $responseData = json_decode($verifyResponse);
    if(!$responseData->success){
        echo "failed";
    }else{
        echo "success";
    }

}


问:
How to easily move comma on a long number
I have this number 0.020928116469517644
And I want to get the percentage, e.g. 2% in this case.
How can I do this? Thanks in advance.</p>

答:
```<code>function percentage(x) {
   return Math.round(100*x) + '%'
}

answer = percentage(0.020928116469517644)
</code>```

Also note that in this example, the percentage is 2% and not 20%

Body:
function percentage(x) {
   return Math.round(100*x) + '%'
}

answer = percentage(0.020928116469517644)

Also note that in this example, the percentage is 2% and not 20%


问:
securing twilio fax mediaUrl
I am using Twilio programmable Fax api to send fax messages from my application.
I am not facing any issue while sending faxes when I provide a public url with out any authentication as mediaUrl for sending the fax. But when I pass a url secured with basic authentication as the mediaUrl for the send fax api, the fax sending is getting failed.

```<code>"status": "failed",
</code>```

I have debugged the code on the server on which the mediaUrl accesses, and could find that Twilio is not at all sending a request with "Authorization" header.

As per Twilio documentation,

```<code>You may provide a username and password via the following URL format.
</code>```

https://username:password@www.myserver.com/my_secure_document

Twilio will authenticate to your web server using the provided
  username and password and will remain logged in for the duration of
  the call. We highly recommend that you use HTTP Authentication in
  conjunction with encryption. For more information on Basic and Digest
  Authentication, refer to your web server documentation.

If you specify a password-protected URL, Twilio will first send a
  request with no Authorization header. After your server responds with
  a 401 Unauthorized status code, a WWW-Authenticate header and a realm
  in the response, Twilio will make the same request with an
  Authorization header

I am giving the mediaUrl in the same format as required by Twilio. But the fax is getting response as failed. Kindly provide your valuable suggestions to help me resolve the issue.

My server is sending the 401 response as given below when Twilio accesses the mediaUrl without Authorization header,

Http response header for 401

```<code>  Status Code: 401 Unauthorized
    Content-Length: 34
    Content-Type: application/xml
    Date: Wed, 30 Aug 2017 12:38:41 GMT
    Server: Apache-Coyote/1.1
    WWW-Authenticate: Basic realm="My Realm"
</code>```

Response body

```<code><message>Invalid credentials</message>
</code>```

答:
To answer this question differently, I'm just using Signed URLs on Google Cloud, which provide a long token that grants temporary access for a specific file.  You can set this to grant access for 10 minutes, which should be more than enough time.

AWS appears to offer a similar solution.

Title: securing twilio fax mediaUrl

Body:
I am using Twilio programmable Fax api to send fax messages from my application.
I am not facing any issue while sending faxes when I provide a public url with out any authentication as mediaUrl for sending the fax. But when I pass a url secured with basic authentication as the mediaUrl for the send fax api, the fax sending is getting failed.

"status": "failed",

I have debugged the code on the server on which the mediaUrl accesses, and could find that Twilio is not at all sending a request with "Authorization" header.

As per Twilio documentation,

You may provide a username and password via the following URL format.

https://username:password@www.myserver.com/my_secure_document

Twilio will authenticate to your web server using the provided
  username and password and will remain logged in for the duration of
  the call. We highly recommend that you use HTTP Authentication in
  conjunction with encryption. For more information on Basic and Digest
  Authentication, refer to your web server documentation.

If you specify a password-protected URL, Twilio will first send a
  request with no Authorization header. After your server responds with
  a 401 Unauthorized status code, a WWW-Authenticate header and a realm
  in the response, Twilio will make the same request with an
  Authorization header

I am giving the mediaUrl in the same format as required by Twilio. But the fax is getting response as failed. Kindly provide your valuable suggestions to help me resolve the issue.

My server is sending the 401 response as given below when Twilio accesses the mediaUrl without Authorization header,

Http response header for 401

  Status Code: 401 Unauthorized
    Content-Length: 34
    Content-Type: application/xml
    Date: Wed, 30 Aug 2017 12:38:41 GMT
    Server: Apache-Coyote/1.1
    WWW-Authenticate: Basic realm="My Realm"

Response body

<message>Invalid credentials</message>