问:
What's the difference between URL.standardized and URL.absoluteURL?
In Swift's URL class, there are .standardized and .absoluteURL properties (.standardizedURL and .absoluteURL, and .URLByStandardizingPath in Objective-C's NSURL). There's also .standardizedFileURL.

I have no idea what the difference is between all these, but there must be one since they provide all of them, right? I mean clearly the .standardizedFileURL is meant to only deal with file URLs, but other than that (for instance, if all are called on a file URL), what's the difference?

From the above-linked docs:

Swift

standardized

Returns a URL with any instances of “..” or “.” removed from its path.

absoluteURL

Returns the absolute URL.

Discussion

If the URL is itself absolute, this will return self.

standardizedFileURL

Standardizes the path of a file URL.

Discussion

If the isFileURL is false, this method returns self.

Objective-C

standardizedURL

A copy of the URL with any instances of ".." or "." removed from its path. (read-only)

Discussion

This property contains a new NSURL object, initialized using the receiver’s path with any instances of ".." or "." removed. If the receiver does not conform to RFC 1808, this property contains nil.

absoluteURL

An absolute URL that refers to the same resource as the receiver. (read-only)

Discussion

If the URL is already absolute, this property contains a copy of the receiver. Resolution is performed per RFC 1808.

URLByStandardizingPath

A URL that points to the same resource as the original URL using an absolute path. (read-only)

Discussion

This property only works on URLs with the file: path scheme. For all other URLs, it returns a copy of the original URL.

Like stringByStandardizingPath, this property can make the following changes in the provided URL:

Expand an initial tilde expression using stringByExpandingTildeInPath.
  Reduce empty components and references to the current directory (that is, the sequences “//” and “/./”) to single path separators.
  In absolute paths only, resolve references to the parent directory (that is, the component “..”) to the real parent directory if possible using stringByResolvingSymlinksInPath, which consults the file system to resolve each potential symbolic link.

In relative paths, because symbolic links can’t be resolved, references to the parent directory are left in place.
  Remove an initial component of “/private” from the path if the result still indicates an existing file or directory (checked by consulting the file system).

Note that the path contained by this property may still have symbolic link components in it. Note also that this property only works with file paths (not, for example, string representations of URLs).

答:
If url is an absolute URL, url.absoluteURL == url.

If url is a relative URL and has a non-nil baseURL, then url.absoluteURL returns an absolute URL by resolving the relativity of url in the context of baseURL (and thus url.absoluteURL != url).

If url is a relative URL, url.standardized does not return an absolute URL, and may in fact return a URL that does not resolve the same way as url (!) because url.standardized removes any leading .. components of the path.

Example:

```<code>let base = URL(string: "https://stackoverflow.com/q/43258046/77567")!
// output: "https://stackoverflow.com/q/43258046/77567"

let rel = URL(string: "../16176911", relativeTo: base)!
// output: "../../16176911 -- ttps://stackoverflow.com/q/43258046/77567"

rel.absoluteURL
// output: "https://stackoverflow.com/q/16176911"

rel.standardized
// output: "16176911 -- ttps://stackoverflow.com/q/43258046/77567"

rel.standardized.absoluteURL
// output: "https://stackoverflow.com/q/43258046/16176911"
</code>```

Body:
If url is an absolute URL, url.absoluteURL == url.

If url is a relative URL and has a non-nil baseURL, then url.absoluteURL returns an absolute URL by resolving the relativity of url in the context of baseURL (and thus url.absoluteURL != url).

If url is a relative URL, url.standardized does not return an absolute URL, and may in fact return a URL that does not resolve the same way as url (!) because url.standardized removes any leading .. components of the path.

Example:

let base = URL(string: "https://stackoverflow.com/q/43258046/77567")!
// output: "https://stackoverflow.com/q/43258046/77567"

let rel = URL(string: "../16176911", relativeTo: base)!
// output: "../../16176911 -- ttps://stackoverflow.com/q/43258046/77567"

rel.absoluteURL
// output: "https://stackoverflow.com/q/16176911"

rel.standardized
// output: "16176911 -- ttps://stackoverflow.com/q/43258046/77567"

rel.standardized.absoluteURL
// output: "https://stackoverflow.com/q/43258046/16176911"


来源: stackexchange

问:
When I try to know if there is an annotation in my method, it returns null (even when there is one)
In a bukkit project, something to simplify the creation of commands, I did something that worked but I want to try new things (to learn how to use these things: Annotations!!) but in my code when I look in my code if there is an annotation "Command" on my method it returns "null" and I do not understand why

My code that looks for the annotation "Order" in my class :

for(Method method : clazz.getMethods()) {
    Command ann = method.getAnnotation(Command.class);
    if(ann != null) {
         // Creates the command
    }
}
```

<p>My annotation class :</p>

<pre class="lang-java prettyprint-override"><code>import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
public @interface Command {
    String command();
    String name();
    String desc() default "";
    String[] aliases() default {};
    boolean admin() default true;
}
</code>```

I hope you'll help me find out where my mistake is.
And I want to apologize for my English because I am a kind of French and I know that my English is not very good:/

PS: I am a young developer so don't blame me if the answer is obvious, I try to learn by myself, everything I have learned is not with a teacher or another....

答:
You need to mark your annotation with @Retention(RetentionPolicy.RUNTIME) in order to be available for query in runtime.

```<code>@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Command {
    String command();
    String name();
    String desc() default "";
    String[] aliases() default {};
    boolean admin() default true;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In a bukkit project, something to simplify the creation of commands, I did something that worked but I want to try new things (to learn how to use these things: Annotations!!) but in my code when I look in my code if there is an annotation "Command" on my method it returns "null" and I do not understand why

My code that looks for the annotation "Order" in my class :

for(Method method : clazz.getMethods()) {
    Command ann = method.getAnnotation(Command.class);
    if(ann != null) {
         // Creates the command
    }
}

My annotation class :

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
public @interface Command {
    String command();
    String name();
    String desc() default "";
    String[] aliases() default {};
    boolean admin() default true;
}

I hope you'll help me find out where my mistake is.
And I want to apologize for my English because I am a kind of French and I know that my English is not very good:/

PS: I am a young developer so don't blame me if the answer is obvious, I try to learn by myself, everything I have learned is not with a teacher or another....

Body:
You need to mark your annotation with @Retention(RetentionPolicy.RUNTIME) in order to be available for query in runtime.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Command {
    String command();
    String name();
    String desc() default "";
    String[] aliases() default {};
    boolean admin() default true;
}


问:
How to decide how many convolutions e deconvolutions apply to a GAN?
I'm trying to understand how the adversarial generative network works: I found an example in the book by François Chollet (Deep learning with Python) in which there is an example of a GAN he uses CIFAR10 dataset, using the 'frog' class which contains 32x32 RGB images.

I can't understand why:

In (1) the input is transformed into 16 × 16 128-channel (why 128-channel?) feature map

In (2) when a convolution is performed, with which filter? It is not specified

Next, run another Conv2DTranspose and then another 3 Conv2d. Why?!

At the end, I have a 32 × 32 1-channel feature map.

```<code>from keras import layers
import numpy as np
latent_dim = 32
height = 32
width = 32
channels = 3

generator_input = keras.Input(shape=(latent_dim,))

(1)
x = layers.Dense(128 * 16 * 16)(generator_input)
x = layers.LeakyReLU()(x)
x = layers.Reshape((16, 16, 128))(x)

(2)
x = layers.Conv2D(256, 5, padding='same')(x)
x = layers.LeakyReLU()(x)

x = layers.Conv2DTranspose(256, 4, strides=2, padding='same')(x)
x = layers.LeakyReLU()(x)

x = layers.Conv2D(256, 5, padding='same')(x)
x = layers.LeakyReLU()(x)
x = layers.Conv2D(256, 5, padding='same')(x)
x = layers.LeakyReLU()(x)

x = layers.Conv2D(channels, 7, activation='tanh', padding='same')(x)
generator = keras.models.Model(generator_input, x)
generator.summary()
</code>```

答:
1)
It's an arbitrary choice, you could have chosen any number of channels for the Dense layer.

16x16 is picked since a stride of 2 is set to the Conv2DTranspose and you want to upsample your width and height to get an output of 32x32.

Strides are used to influence output size of convolution layers. In normal convolutions, outputs are downsampled by the same factor as strides, where in transposed convolutions they are upsampled by the same factor as strides.

For instance, you could change your first layer output to 8x8x128 and then use a stride of 4 in your Conv2DTranspose, this way you would get the same result in terms of dimensionality.

Also keep in mind that, as stated by François Chollet in his book, when using strided transposed convolutions, in order to avoid checkerboard artifacts caused by unequal coverage of the pixel space, kernel size should be divisible by its number of strides.

2) The first argument you set in Conv2D or Conv2DTranspose is the number of filters generated by a convolution layer.

As said before, the strided Conv2DTranspose is used exactly to upsample width and height by a factor equal to the number of strides.

The other 3 Conv2D are also arbitrary, you should determine them by experimentation and fine tuning your model.

Body:
I'm trying to understand how the adversarial generative network works: I found an example in the book by François Chollet (Deep learning with Python) in which there is an example of a GAN he uses CIFAR10 dataset, using the 'frog' class which contains 32x32 RGB images.

I can't understand why:

In (1) the input is transformed into 16 × 16 128-channel (why 128-channel?) feature map

In (2) when a convolution is performed, with which filter? It is not specified

Next, run another Conv2DTranspose and then another 3 Conv2d. Why?!

At the end, I have a 32 × 32 1-channel feature map.

from keras import layers
import numpy as np
latent_dim = 32
height = 32
width = 32
channels = 3

generator_input = keras.Input(shape=(latent_dim,))

(1)
x = layers.Dense(128 * 16 * 16)(generator_input)
x = layers.LeakyReLU()(x)
x = layers.Reshape((16, 16, 128))(x)

(2)
x = layers.Conv2D(256, 5, padding='same')(x)
x = layers.LeakyReLU()(x)

x = layers.Conv2DTranspose(256, 4, strides=2, padding='same')(x)
x = layers.LeakyReLU()(x)

x = layers.Conv2D(256, 5, padding='same')(x)
x = layers.LeakyReLU()(x)
x = layers.Conv2D(256, 5, padding='same')(x)
x = layers.LeakyReLU()(x)

x = layers.Conv2D(channels, 7, activation='tanh', padding='same')(x)
generator = keras.models.Model(generator_input, x)
generator.summary()


问:
Msgbox not closing when WSH.Popup waits for certain time
I have an Excel file that opens automatically with Windows Scheduler. Also I have an Auto_Open sub to run a macro immediately. To avoid that every time it opens it starts running without a chance to modify it, I set up a msgbox that let me choose if the macro runs or not. However, I want Excel to automatically choose "Yes" after 10 seconds have passed, and I'm not able to get it. This is my code:

I have tried to place the seconds directly without a variable, I have also tried Case -1 alone, yet nothing works.

```<code>Sub Auto_Open()

Set WSH = CreateObject("WScript.Shell")
'cTime = 10
BtnCode = WSH.Popup("¿Desea generar la consulta de vacaciones?", cTime, "Consulta", vbYesNo)

Select Case BtnCode
    Case vbYes
    Call consulta

    Case vbNo

    Case 1, -1
    Call consulta

    End Select

End Sub
</code>```

答: I think has to do with the "Call consulta" procedure, try use megbox to test it.</p>

Body:
I have an Excel file that opens automatically with Windows Scheduler. Also I have an Auto_Open sub to run a macro immediately. To avoid that every time it opens it starts running without a chance to modify it, I set up a msgbox that let me choose if the macro runs or not. However, I want Excel to automatically choose "Yes" after 10 seconds have passed, and I'm not able to get it. This is my code:

I have tried to place the seconds directly without a variable, I have also tried Case -1 alone, yet nothing works.

Sub Auto_Open()

Set WSH = CreateObject("WScript.Shell")
'cTime = 10
BtnCode = WSH.Popup("¿Desea generar la consulta de vacaciones?", cTime, "Consulta", vbYesNo)

Select Case BtnCode
    Case vbYes
    Call consulta

    Case vbNo

    Case 1, -1
    Call consulta

    End Select

End Sub


问:
Duplicati and Backup of live Pervasive Database Missing Data
We have recently started using Duplicati for backup of some of our data systems. We run an ERP solution that uses Pervasive (v10).

When Duplicati begins its backup process, to the best of my understanding, it's using either the file date, and or the file byte size to determine what to back up.

The problem that I see with that solution is that some of the data is missing from the table. For example, the workorders module we are certain had new rows of data on the server (source machine) that were NOT copied over to the new file.

Last night we backed up our ERP platform then restored to a new location so as to do a compare of what was backed up during the evening against what the source machine had. We noticed that there are rows missing from one table in the restored backup, that are there in the source table.

The backup is being created from the data directory. We are NOT using the integrated backup that came with the ERP suite.

What I personally believe is happening is that the database isn't writing out the data to the table until the last client disconnects from the ERP software. Also, the byte size of the file missing data and the source machine are the same, even though the source file holds more data.

Last week we did the same test that we did last night and I noticed when I closed the ERP suite, the file updates its modified stamp and the new rows are added to the table, but not before the client disconnects.

Can someone shed some light on why this is happening?

答:
With Duplicati, you can set --disable-filetime-check=true to ignore the timestamps and sizes, and scan each file for changes.

This option is not active by default, because it may take a long time to fully read the file contents. For normal file operations, the OS should set the timestamp, but some applications, like TrueCrypt, will revert the timestamp.


问:
After adding @ComponentScan to load beans from a jar my controllers isn't scan and i get 404
I have a spring-boot application (Java8, spring-boot 2.1.4-RELEASE).

One of the services in the business layer need to @Autowire a bean from a certain jars in my classpath. In order to achieve that i had to add @ComponentScan({"package.to.my.bean.inside.the.jar"}) and it was magically scanned and wired successfully (this was added to the main spring-boot class which declare the main method).

However, since then my controllers aren't scanned hence the DispatcherServlet is returning 404 for every request i trigger (default dispatcher).
Actually my entire spring-boot app annotations is being ignored - no scan is performed.
Just to emphasis - the application worked perfectly before adding the @ComponentScan.

Main spring-boot app class:

```<code>package com.liav.ezer;

// This is the problematic addition that cause the endpoints to stop
// inside a jar in the classpath, in com.internal.jar package resides an
// object which i need to wire at run time
@ComponentScan({"com.internal.jar"})
@SpringBootApplication
public class JobsApplication {
    public static void main(String[] args) {
        SpringApplication.run(JobsApplication .class, args);
        }
}
</code>```

Controller example:

```<code>package com.liav.ezer.controller;

@RestController
@EnableAutoConfiguration
@RequestMapping(path = "/jobs")
public class JobController {

    @GetMapping(path="/create", produces = "application/json")
    @ResponseStatus(HttpStatus.OK)
    String createJob(@RequestParam() String jobName) String jobName){
        return "job created...";
    }
}
</code>```

I tried adding my spring-boot app base package to the list of packages in the @ComponentScan with no luck.
I tried narrowing down the scope of the package declaration to be only on the class which i need with no luck.
Here is the code

答:
According to Spring documentation

Configures component scanning directives for use with @Configuration
  classes. Provides support parallel with Spring XML's
   element. Either basePackageClasses() or
  basePackages() (or its alias value()) may be specified to define
  specific packages to scan. If specific packages are not defined,
  scanning will occur from the package of the class that declares this
  annotation.

In your case when you are adding

@ComponentScan({"com.internal.jar"})
  you are disabling scanning of
  com.liav.ezer.controller

To fix it you can do the following configuration

@ComponentScan(basePackages = {"com.internal.jar", "com.liav.ezer.controller"})

Body:
I have a spring-boot application (Java8, spring-boot 2.1.4-RELEASE).

One of the services in the business layer need to @Autowire a bean from a certain jars in my classpath. In order to achieve that i had to add @ComponentScan({"package.to.my.bean.inside.the.jar"}) and it was magically scanned and wired successfully (this was added to the main spring-boot class which declare the main method).

However, since then my controllers aren't scanned hence the DispatcherServlet is returning 404 for every request i trigger (default dispatcher).
Actually my entire spring-boot app annotations is being ignored - no scan is performed.
Just to emphasis - the application worked perfectly before adding the @ComponentScan.

Main spring-boot app class:

package com.liav.ezer;

// This is the problematic addition that cause the endpoints to stop
// inside a jar in the classpath, in com.internal.jar package resides an
// object which i need to wire at run time
@ComponentScan({"com.internal.jar"})
@SpringBootApplication
public class JobsApplication {
    public static void main(String[] args) {
        SpringApplication.run(JobsApplication .class, args);
        }
}

Controller example:

package com.liav.ezer.controller;

@RestController
@EnableAutoConfiguration
@RequestMapping(path = "/jobs")
public class JobController {

    @GetMapping(path="/create", produces = "application/json")
    @ResponseStatus(HttpStatus.OK)
    String createJob(@RequestParam() String jobName) String jobName){
        return "job created...";
    }
}

I tried adding my spring-boot app base package to the list of packages in the @ComponentScan with no luck.
I tried narrowing down the scope of the package declaration to be only on the class which i need with no luck.
Here is the code


问:
How to rotate camera around player in unity c#
I need to rotate the camera around my player gameobject while holding the left mouse button. How would I approach this?

Also, I've read a bit on Vector 3, but I don't have a full understanding of it. Anybody who could explain it would be greatly appreciated.

I've looked at youtube videos and this one is exactly the concept I was looking for. I  was just having trouble applying it to my code.

I'm on a bit of a time crunch, exams are nearing and my teacher hasn't explained most things that are explained in the video.

// This is my code inside the camera which follows the ball/player

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScriptBallCam : MonoBehaviour
{
public GameObject player;

private Vector3 offset;

void Start()
{
    offset = transform.position - player.transform.position;
}

void LateUpdate()
{
    transform.position = player.transform.position + offset;
}
</code>```

//End of code inside camera

//Code inside of player/ball

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScriptBall : MonoBehaviour
{

public float speed;

private Rigidbody rb;

void Start()
{
    rb = GetComponent<Rigidbody>();
}

void FixedUpdate()
{
    float moveHorizontal = Input.GetAxis("Horizontal");
    float moveVertical = Input.GetAxis("Vertical");

    Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);

    rb.AddForce(movement * speed);
}
</code>```

// end code

Results I'm expecting are exactly shown at 1:22 in

https://www.youtube.com/watch?v=xcn7hz7J7sI

答:
Try this. The script goes on your camera.

Basically this script works by first getting the direction your mouse has moved in. In this case the X axis Mouse X (left/right direction). Then we take our rotation speed turnSpeed, and use it to rotate around the player by that amount of degrees using Quaternion.AngleAxis. Finally we make sure that the camera is always looking at the player by using transform.LookAt

```<code> using UnityEngine;
 using System.Collections;

public class OrbitPlayer : MonoBehaviour {

     public float turnSpeed = 5.0f;
     public GameObject player;

     private Transform playerTransform;
     private Vector3 offset;
     private float yOffset = 10.0f;
     private float zOffset = 10.0f;

     void Start () {
         playerTransform = player.transform;
         offset = new Vector3(playerTransform.position.x, playerTransform.position.y + yOffset, playerTransform.position.z + zOffset);
     }

     void FixedUpdate()
     {
         offset = Quaternion.AngleAxis (Input.GetAxis("Mouse X") * turnSpeed, Vector3.up) * offset;
         transform.position = playerTransform.position + offset;
         transform.LookAt(playerTransform.position);
     }
}
</code>```

There is a lot of information on this topic over here:
https://answers.unity.com/questions/600577/camera-rotation-around-player-while-following.html

Body:
I need to rotate the camera around my player gameobject while holding the left mouse button. How would I approach this?

Also, I've read a bit on Vector 3, but I don't have a full understanding of it. Anybody who could explain it would be greatly appreciated.

I've looked at youtube videos and this one is exactly the concept I was looking for. I  was just having trouble applying it to my code.

I'm on a bit of a time crunch, exams are nearing and my teacher hasn't explained most things that are explained in the video.

// This is my code inside the camera which follows the ball/player

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScriptBallCam : MonoBehaviour
{
public GameObject player;

private Vector3 offset;

void Start()
{
    offset = transform.position - player.transform.position;
}

void LateUpdate()
{
    transform.position = player.transform.position + offset;
}

//End of code inside camera

//Code inside of player/ball

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScriptBall : MonoBehaviour
{

public float speed;

private Rigidbody rb;

void Start()
{
    rb = GetComponent<Rigidbody>();
}

void FixedUpdate()
{
    float moveHorizontal = Input.GetAxis("Horizontal");
    float moveVertical = Input.GetAxis("Vertical");

    Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);

    rb.AddForce(movement * speed);
}

// end code

Results I'm expecting are exactly shown at 1:22 in

https://www.youtube.com/watch?v=xcn7hz7J7sI

Body:
Try this. The script goes on your camera.

Basically this script works by first getting the direction your mouse has moved in. In this case the X axis Mouse X (left/right direction). Then we take our rotation speed turnSpeed, and use it to rotate around the player by that amount of degrees using Quaternion.AngleAxis. Finally we make sure that the camera is always looking at the player by using transform.LookAt

 using UnityEngine;
 using System.Collections;

public class OrbitPlayer : MonoBehaviour {

     public float turnSpeed = 5.0f;
     public GameObject player;

     private Transform playerTransform;
     private Vector3 offset;
     private float yOffset = 10.0f;
     private float zOffset = 10.0f;

     void Start () {
         playerTransform = player.transform;
         offset = new Vector3(playerTransform.position.x, playerTransform.position.y + yOffset, playerTransform.position.z + zOffset);
     }

     void FixedUpdate()
     {
         offset = Quaternion.AngleAxis (Input.GetAxis("Mouse X") * turnSpeed, Vector3.up) * offset;
         transform.position = playerTransform.position + offset;
         transform.LookAt(playerTransform.position);
     }
}

There is a lot of information on this topic over here:
https://answers.unity.com/questions/600577/camera-rotation-around-player-while-following.html


问:
Make materialize labels move out of input box when input box is filled via javascript
Normally, with Materialize, the labels for text input boxes show up inside the input boxes until a user enter selects the box and enters text in it. However, when a box's value is filled via javascript, the label does not move out of the way. It stays in the box and overlaps with the text entered. Is there a way to trigger the label transition with javascript as well, so this doesn't happen?</p>

答: Add class="active"into the label tag associated with the input field.

ContentLicense: CC BY-SA 3.0


问:
Coping the value that does not exist
I was wondering if we copy a value that does not exist what will be the typeof copied value ?
Is it null or undefined ?

```<code>const args = [1]
console.log(...args.slice(1))
</code>```

Here is a concrete example

```<code>const compose = fns => (...args) =>
  fns.reduceRight((acc, fn) => fn(acc, ...args.slice(1)), args[0]);

const func3 = (x, y) => (y > 0 ? x + 3 : x - 3);

const func2 = x => x ** 2;

const func1 = x => x - 8;

const fnOne = compose([func1, func2, func3])('3', 1);
console.log(fnOne); // should be 1081

const fnTwo = compose([func1, func2, func3])('3', -1);
console.log(fnTwo); //should be -8
</code>```

答:
A spreaded empty array returns no parameter.

console.log('>', ...[], '<');```

Title: Coping the value that does not exist

Body:
I was wondering if we copy a value that does not exist what will be the typeof copied value ?
Is it null or undefined ?

const args = [1]
console.log(...args.slice(1))

Here is a concrete example

const compose = fns => (...args) =>
  fns.reduceRight((acc, fn) => fn(acc, ...args.slice(1)), args[0]);

const func3 = (x, y) => (y > 0 ? x + 3 : x - 3);

const func2 = x => x ** 2;

const func1 = x => x - 8;

const fnOne = compose([func1, func2, func3])('3', 1);
console.log(fnOne); // should be 1081

const fnTwo = compose([func1, func2, func3])('3', -1);
console.log(fnTwo); //should be -8


问:
ReactJS not rendering my API call results
In React, I have a state called views_res which is a list. I make an API call in viewsList(), which is supposed to map the results of the API call to this state variable. However, when I debug using console.log(), I see the "start" and "WHAT UP DOE," but the views is empty :(

I know that the API end point is correct, as Postman shows me the correct JSON response. However, my state variable is simply not receiving the data. I'm not sure where I am going wrong with this!

For privacy, I redacted the exact API end point.

```<code>componentDidMount() {
    this.ViewsList();
  }

  // Gets views from Wistia API
   ViewsList() {
    console.log("start", this.state.views);
// API call
$.getJSON(
  "url"
)
  // JSON format
  .then(response => {
    response.json();
  })
  .then(data => {
    // Map over data
    let views_res = data.response.map(item => (
      <div>
        console.log("play_count", {item.play_count})
        <h1>{item.play_count}</h1> */}
      </div>
    ));
    // Set the state
    this.setState({ views: views_res });
  });
console.log("WHAT UP DOE", this.state.views);
  }
</code>```

答:
I'm not sure what kind of library you're using for $.getJson (is it jQuery?) but note that setState is an asynchronous operation. Meaning, you want "see" the changes if you console.log after you called setState.

There is a second argument though for setState which is a callback function that will get triggered after the actual update of the state.

```<code>this.setState({ views: views_res }, () => {
    // this is a callback function for setState.
  // this coode will run just after the state actually updated
  console.log("WHAT UP DOE", this.state.views)
})
</code>```

From the DOCS:

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied

Edit

Note that this part:

```<code><div>
  console.log("play_count", {item.play_count})
  <h1>{item.play_count}</h1> */}
</div>
</code>```

Will not log anything, as

```<code>console.log("play_count", {item.play_count})
</code>```

Is just a string inside a JSX block. If you want to write JavaScript expressions inside a JSX block, you should wrap it with curly braces ({}):

See a running example:

function App() {
  return (

        console.log("i am just a string")
        {console.log('I will show in the console')}

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></code>```

Body:
In React, I have a state called views_res which is a list. I make an API call in viewsList(), which is supposed to map the results of the API call to this state variable. However, when I debug using console.log(), I see the "start" and "WHAT UP DOE," but the views is empty :(

I know that the API end point is correct, as Postman shows me the correct JSON response. However, my state variable is simply not receiving the data. I'm not sure where I am going wrong with this!

For privacy, I redacted the exact API end point.

componentDidMount() {
    this.ViewsList();
  }

  // Gets views from Wistia API
   ViewsList() {
    console.log("start", this.state.views);
// API call
$.getJSON(
  "url"
)
  // JSON format
  .then(response => {
    response.json();
  })
  .then(data => {
    // Map over data
    let views_res = data.response.map(item => (

        console.log("play_count", {item.play_count})

{item.play_count}
 */}

    ));
    // Set the state
    this.setState({ views: views_res });
  });
console.log("WHAT UP DOE", this.state.views);
  }

Body:
I'm not sure what kind of library you're using for $.getJson (is it jQuery?) but note that setState is an asynchronous operation. Meaning, you want "see" the changes if you console.log after you called setState.

There is a second argument though for setState which is a callback function that will get triggered after the actual update of the state.

this.setState({ views: views_res }, () => {
    // this is a callback function for setState.
  // this coode will run just after the state actually updated
  console.log("WHAT UP DOE", this.state.views)
})

From the DOCS:

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied

Edit

Note that this part:

<div>
  console.log("play_count", {item.play_count})
  <h1>{item.play_count}</h1> */}
</div>

Will not log anything, as

console.log("play_count", {item.play_count})

Is just a string inside a JSX block. If you want to write JavaScript expressions inside a JSX block, you should wrap it with curly braces ({}):

See a running example:

function App() {
  return (
    <div>
     <div>
        console.log("i am just a string")
        {console.log('I will show in the console')}
      </div>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root">


问:
Select rows by comparing with next row
I have the following table,

```<code>value   caseid    version
-----   ------    -------
2.6     1         A
2.7     1         B
4.8     2         A
5.4     2         B
2.9     3         A
3.0     3         B
</code>```

and I want to compare the value in rows with version A with those in version B with the same caseid, and only display rows that have a difference of greater than 0.1.

So, in the above example, the result should be:

```<code>value   caseid    version
-----   ------    -------
4.8     2         A
5.4     2         B
</code>```

I've tried with a join, but then both rows get displayed in the same row.
Is there a way to do this where values get displayed on different rows?

Thank you.

答:
You can use lag() window analytic function :

```<code>with t1( value, caseid, version ) as
(
 select 2.6, 1, 'A' from dual union all
 select 2.7, 1, 'B' from dual union all
 select 4.8, 2, 'A' from dual union all
 select 5.4, 2, 'B' from dual union all
 select 2.9, 3, 'A' from dual union all
 select 3.0, 3, 'B' from dual
), t2 as
(
select t1.value - lag(t1.value,1,t1.value) over
       (partition by t1.caseid order by t1.version ) as diff,
       t1.*
  from t1
)
select value, caseid, version
  from t2
 where t2.caseid in ( select caseid
                        from t2
                       where caseid = t2.caseid
                         and diff > .1 )
 order by version;

VALUE   CASEID  VERSION
-----   ------  -------
4,80    2       A
5,40    2       B
</code>```

Demo

Title: Select rows by comparing with next row

Body:
I have the following table,

value   caseid    version
-----   ------    -------
2.6     1         A
2.7     1         B
4.8     2         A
5.4     2         B
2.9     3         A
3.0     3         B

and I want to compare the value in rows with version A with those in version B with the same caseid, and only display rows that have a difference of greater than 0.1.

So, in the above example, the result should be:

value   caseid    version
-----   ------    -------
4.8     2         A
5.4     2         B

I've tried with a join, but then both rows get displayed in the same row.
Is there a way to do this where values get displayed on different rows?

Thank you.

Body:
You can use lag() window analytic function :

with t1( value, caseid, version ) as
(
 select 2.6, 1, 'A' from dual union all
 select 2.7, 1, 'B' from dual union all
 select 4.8, 2, 'A' from dual union all
 select 5.4, 2, 'B' from dual union all
 select 2.9, 3, 'A' from dual union all
 select 3.0, 3, 'B' from dual
), t2 as
(
select t1.value - lag(t1.value,1,t1.value) over
       (partition by t1.caseid order by t1.version ) as diff,
       t1.*
  from t1
)
select value, caseid, version
  from t2
 where t2.caseid in ( select caseid
                        from t2
                       where caseid = t2.caseid
                         and diff > .1 )
 order by version;

VALUE   CASEID  VERSION
-----   ------  -------
4,80    2       A
5,40    2       B

Demo


问:
addEventListener for multiple pages and buttons
I'm way too used to working in react and components so doing this all in vanilla JS makes my brain go blank some times.

I have a website with multiple pages/URLs. Certain pages have unique styles that users interact with.

I have a single file script.js. I get elements with document.getElementsByClassName, I then use an addEventListener for 'clicks' and what not. When I only worked on one page I never noticed that when I started building out the second page the script breaks because it can't find the element (which was on the previous page).

This does make sense but how do you work around this? My entire script is encapulslated with window.onload.

For example,

Page1.html

```<code><button class="first"> Click me </button>
</code>```

Page2.html

```<code><button class="second"> Click me </div>
</code>```

Scrip.js

```<code>var buttonOne = document.getElementsByClassName("first")[0];
var buttonTwo = document.getElementsByClassName("second")[0];

buttonOne.addEventListener('click',function(){
        firstFun();
})

buttonTwo.addEventListener('click',function(){
        secondFun();
})

function firstFun () { .. }
function secondFun () { .. }
</code>```

In which this script wouldn't work because it would break trying to find the element and adding the event listener.

答:
As @epascarello mentioned the solution is simple.

Wrap the event listeners in an if (element) statement.

Body:
I'm way too used to working in react and components so doing this all in vanilla JS makes my brain go blank some times.

I have a website with multiple pages/URLs. Certain pages have unique styles that users interact with.

I have a single file script.js. I get elements with document.getElementsByClassName, I then use an addEventListener for 'clicks' and what not. When I only worked on one page I never noticed that when I started building out the second page the script breaks because it can't find the element (which was on the previous page).

This does make sense but how do you work around this? My entire script is encapulslated with window.onload.

For example,

Page1.html

<button class="first"> Click me </button>

Page2.html

<button class="second"> Click me

Scrip.js

var buttonOne = document.getElementsByClassName("first")[0];
var buttonTwo = document.getElementsByClassName("second")[0];

buttonOne.addEventListener('click',function(){
        firstFun();
})

buttonTwo.addEventListener('click',function(){
        secondFun();
})

function firstFun () { .. }
function secondFun () { .. }

In which this script wouldn't work because it would break trying to find the element and adding the event listener.


问:
Convert word doc to pdf and send as attachment in Outlook
I would like to convert my Word Doc to a pdf and send it as an attachment as part of my constructed Outlook email.

I have tried adding ,".pdf" at the end of my SaveAs2 line, which changed and attached the file format as pdf, however, when attempting to open the file it does not display and gives me a message that the file did not have all it's code when sent as an attachment.

```<code>Private Sub emailbutton_Click()
        'No-option email sending
        Dim OL              As Object
        Dim EmailItem       As Object
        Dim Doc             As Document

        Application.ScreenUpdating = False
        Set OL = CreateObject("Outlook.Application")
        Set EmailItem = OL.CreateItem(olMailItem)
        Set Doc = ActiveDocument

        If VName.Value = "" Then
            Doc.SaveAs ("Quotation_Blank 2016")
        Else
           Doc.SaveAs2 ("QFORM" & "_" & JNumber.Value & "_" & VName.Value)

        End If

       With EmailItem
        .Display
        End With
    '        Signature = EmailItem.body

        With EmailItem
            .Subject = "QFORM" & "_" & JNumber.Value & "_" & VName.Value

            'HTMLbody
            msg = "<b><font face=""Times New Roman"" size=""4"" color=""blue"">INTEGRATED ASSEMBLY </font></b><br>" _
            & "   1200 Woodruff Rd.<br>" _
            & "   Suite A12<br>" _
            & "   Greenville, SC 29607<br><br>" _
            & "We have recently released subject project, which will contain assemblies to be outsourced. You have been selected to build these assemblies according to the attachment. <br><br>" _
            & "As part of this process, please review the quotation form attached and indicate your acceptance. If adjustments and-or corrections are required, please feel free to contact us for quick resolution. <br><br>" _
            & "<b><font face=""Times New Roman"" size=""4"" color=""Red"">NOTE: </font></b>" _
            & "The information on attached quotation form is not a contract and only an estimate of predetermined costs per hourly rate for outsource assemblies. <br><br>" _
            & "*******For your records you may wish to print out the completed quote form. <br><br>" _
            & "Thank you, <br><br>" _
            & "<b>HARTNESS INTERNATIONAL </b><br>" _
            & "H1 Production Control <br>" _
            & vbNewLine & Signature

            .HTMLBody = msg & .HTMLBody

            If VName.Value = "INTEGRATED ASSEMBLY" Then
                .To = "Email1.com;"
                .CC = "Email2.com;" & "Email3.com;"
                .Importance = olImportanceNormal 'Or olImportanceHigh Or         olImportanceLow
                .Attachments.Add Doc.FullName
                .Display
             ElseIf VName.Value = "LEWALLEN" Then
                .To = "Email1.com;"
                .CC = "Email2.com;" & "Email3.com;"
                .Importance = olImportanceNormal 'Or olImportanceHigh Or         olImportanceLow
                .Attachments.Add Doc.FullName
                .Display

             End If
        End With

        Application.ScreenUpdating = True

        Set Doc = Nothing
        Set OL = Nothing
        Set EmailItem = Nothing

    End Sub
</code>```

答: I was wondering if you could post all your code for this solution. I have been looking for something like this for a while and all my experience is on powershell. I know this i generally frowned upon but i am running out of options</p>

Body:
I would like to convert my Word Doc to a pdf and send it as an attachment as part of my constructed Outlook email.

I have tried adding ,".pdf" at the end of my SaveAs2 line, which changed and attached the file format as pdf, however, when attempting to open the file it does not display and gives me a message that the file did not have all it's code when sent as an attachment.

Private Sub emailbutton_Click()
        'No-option email sending
        Dim OL              As Object
        Dim EmailItem       As Object
        Dim Doc             As Document

        Application.ScreenUpdating = False
        Set OL = CreateObject("Outlook.Application")
        Set EmailItem = OL.CreateItem(olMailItem)
        Set Doc = ActiveDocument

        If VName.Value = "" Then
            Doc.SaveAs ("Quotation_Blank 2016")
        Else
           Doc.SaveAs2 ("QFORM" & "_" & JNumber.Value & "_" & VName.Value)

        End If

       With EmailItem
        .Display
        End With
    '        Signature = EmailItem.body

        With EmailItem
            .Subject = "QFORM" & "_" & JNumber.Value & "_" & VName.Value

            'HTMLbody
            msg = "INTEGRATED ASSEMBLY
" _
            & "   1200 Woodruff Rd.
" _
            & "   Suite A12
" _
            & "   Greenville, SC 29607

" _
            & "We have recently released subject project, which will contain assemblies to be outsourced. You have been selected to build these assemblies according to the attachment.

" _
            & "As part of this process, please review the quotation form attached and indicate your acceptance. If adjustments and-or corrections are required, please feel free to contact us for quick resolution.

" _
            & "NOTE: " _
            & "The information on attached quotation form is not a contract and only an estimate of predetermined costs per hourly rate for outsource assemblies.

" _
            & "*******For your records you may wish to print out the completed quote form.

" _
            & "Thank you,

" _
            & "HARTNESS INTERNATIONAL
" _
            & "H1 Production Control
" _
            & vbNewLine & Signature

            .HTMLBody = msg & .HTMLBody

            If VName.Value = "INTEGRATED ASSEMBLY" Then
                .To = "Email1.com;"
                .CC = "Email2.com;" & "Email3.com;"
                .Importance = olImportanceNormal 'Or olImportanceHigh Or         olImportanceLow
                .Attachments.Add Doc.FullName
                .Display
             ElseIf VName.Value = "LEWALLEN" Then
                .To = "Email1.com;"
                .CC = "Email2.com;" & "Email3.com;"
                .Importance = olImportanceNormal 'Or olImportanceHigh Or         olImportanceLow
                .Attachments.Add Doc.FullName
                .Display

             End If
        End With

        Application.ScreenUpdating = True

        Set Doc = Nothing
        Set OL = Nothing
        Set EmailItem = Nothing

    End Sub


问:
Make a simple get request in javascript
I am trying to do some simple webscraping in javascript to get the html code from either delish or tasty sites to store recipes.  one example would be this site: https://www.delish.com/cooking/recipe-ideas/a27469586/baked-zucchini-recipe/
However when I use fetch I am not able to get it to work.

I actually wrote the equivalent code in python that I want to be able to translate into javascript.  This is pasted here:

```<code>import requests
url = "https://www.delish.com/cooking/recipe-ideas/a27469586/baked-zucchini-recipe/"
r = requests.get(url)
text = str(r.content)
</code>```

I am able to get the javascript code to work when I use a different site.  For example this worked for me

```<code>fetch('https://api.github.com/users/maecapozzi')
   .then(res => console.log('response: ', res))
   .catch(console.error)
</code>```

but when trying for my site I got an error:

Access to fetch at 'https://www.delish.com/cooking/recipe-ideas/a27469586/baked-zucchini-recipe' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
index.js:1375
TypeError: Failed to fetch

I am not sure what exactly this means as I am pretty new to all this, so any help at all would be greatly appreciated!

答:
Browsers implement CORS for security reasons, and to prevent websites from scraping other websites client-side.

https://api.github.com explicitly allows contact from other websites by specifying the Access-Control-Allow-Origin: * header.

If you want to write web-scraping in Javascript for yourself and no one else, you might be able to disable CORS in your browser. If your website needs to scrape another website, you can write a Python (or similar) server to scrape the website for you and then re-host the content on a domain you control (sketchy, probably a bad idea).

Title: Make a simple get request in javascript

Body:
I am trying to do some simple webscraping in javascript to get the html code from either delish or tasty sites to store recipes.  one example would be this site: https://www.delish.com/cooking/recipe-ideas/a27469586/baked-zucchini-recipe/
However when I use fetch I am not able to get it to work.

I actually wrote the equivalent code in python that I want to be able to translate into javascript.  This is pasted here:

import requests
url = "https://www.delish.com/cooking/recipe-ideas/a27469586/baked-zucchini-recipe/"
r = requests.get(url)
text = str(r.content)

I am able to get the javascript code to work when I use a different site.  For example this worked for me

fetch('https://api.github.com/users/maecapozzi')
   .then(res => console.log('response: ', res))
   .catch(console.error)

but when trying for my site I got an error:

Access to fetch at 'https://www.delish.com/cooking/recipe-ideas/a27469586/baked-zucchini-recipe' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
index.js:1375
TypeError: Failed to fetch

I am not sure what exactly this means as I am pretty new to all this, so any help at all would be greatly appreciated!


问:
How to determine if a child is a single child in a PROLOG family tree?
I am currently writing a PROLOG program that represents Family Relationships.

Right now I have implemented the following functions that work.

```<code>male(X). Returns true if X is male.
female(X). Returns true if X is female.
mother_of(X,Y). Returns true if X is the mother of Y.
father_of(X,Y). Returns true if X is the father of Y.
sister_of(X,Y).  Returns true if X is the sister of Y.
brother_of(X,Y). Returns true if X is the brother of Y.
</code>```

Now I want to implement a function to check if someone is a single child/has no sister/brother.
I have tried the following functions but none of them is working:

```<code>single_child(X) :- (\+ sister_of(X,Y)),(\+ brother_of(X,Y)).
single_child(X) :- not(sister_of(X,Y)), not(brother_of(X,Y)).
single_child(X) :- \+ (sister_of(X,Y),\+ brother_of(X,Y)).
single_child(X) :- not(sister_of(X,Y),brother_of(X,Y)).
</code>```

Does anyone know how I could implement such a function correctly?

Kind Regards
David J.

答:
I found a Solution myself:</p>

```<code>single_child(X) :- \+ has_sibling(X),(parent(P,X)).
parent(X,Y) :- father_of(X,Y);mother_of(X,Y).
sibling(X,Y):- parent(Z,X), parent(Z,Y), X\=Y.
has_sibling(X) :- sibling(X,_).
</code>```

Body:
I am currently writing a PROLOG program that represents Family Relationships.

Right now I have implemented the following functions that work.

male(X). Returns true if X is male.
female(X). Returns true if X is female.
mother_of(X,Y). Returns true if X is the mother of Y.
father_of(X,Y). Returns true if X is the father of Y.
sister_of(X,Y).  Returns true if X is the sister of Y.
brother_of(X,Y). Returns true if X is the brother of Y.

Now I want to implement a function to check if someone is a single child/has no sister/brother.
I have tried the following functions but none of them is working:

single_child(X) :- (\+ sister_of(X,Y)),(\+ brother_of(X,Y)).
single_child(X) :- not(sister_of(X,Y)), not(brother_of(X,Y)).
single_child(X) :- \+ (sister_of(X,Y),\+ brother_of(X,Y)).
single_child(X) :- not(sister_of(X,Y),brother_of(X,Y)).

Does anyone know how I could implement such a function correctly?

Kind Regards
David J.

Body:
I found a Solution myself:

single_child(X) :- \+ has_sibling(X),(parent(P,X)).
parent(X,Y) :- father_of(X,Y);mother_of(X,Y).
sibling(X,Y):- parent(Z,X), parent(Z,Y), X\=Y.
has_sibling(X) :- sibling(X,_).


问:
MonoDevelop build error "The search could not be finished"
I am currently developing a C# application to be cross compatible in Windows and Ubuntu. I am developing the software in Visual Studio 2010 on Windows and copying the project to ubuntu and make any modifications that are required using MonoDevelop.

This has been working perfectly all the time but now for some reason it isn't.

When I try to do a search and replace across the entire project which has always worked is now coming up with an that says 'The search could not be finished. Could not find file /myproject/myproject/Microsoft.Net.Client.3.5.

Also when I run the project it says that it builds successfully but when run it looks as if it is running the previous build instead of the latest build.

答: When I experienced issues with searching for files it was the MonoDevelop parser information files that was out of sync. Try deleting all .pidb files and do a rebuild.</p>


问:
Using the Eclipse remote debugger throws com.sun.jdi.InternalException
The following error is being thrown:

```<code>com.sun.jdi.InternalException: Got error code in reply:35 occurred while retrieving value. for all expressions
</code>```

I am getting this error for all expressions and cant find anything on it.  My guess is that the debugger isn't correctly connecting to the remote version, but I am not sure.

答:
If you have the "Logical Structures" turned on in the Expressions tab while debugging, this seems to still cause issues even in Eclipse IDE version 4.11.0. Turning it off helped me. It is not a "solution" per se rather a work-a-around.

See the Eclipse Bug 48815

OwnerDisplayName: Terry Caines

Body:
The following error is being thrown:

com.sun.jdi.InternalException: Got error code in reply:35 occurred while retrieving value. for all expressions

I am getting this error for all expressions and cant find anything on it.  My guess is that the debugger isn't correctly connecting to the remote version, but I am not sure.


问:
How to configure c++ Zbar scanner to decode only QR-Code data type?
I am using Zbar C++ library to decode QRCode,using this tutorial:
https://www.learnopencv.com/barcode-and-qr-code-scanner-using-zbar-and-opencv/

Here I have to decode only QRCode from an image however using this tutorial it decodes both QRcode and barcodes from an Image.

In tutorial it says to decode only QRCode we have to Configure Zbar Imagescanner properly.

In tutorial they are using following configuration to decode both QRCode and Barcodes

ImageScanner scanner;
scanner.set_config(ZBAR_NONE, ZBAR_CFG_ENABLE, 1);

So to decode only QRCode I am using following configuration:

ImageScanner scanner;
scanner.set_config(ZBAR_QRCODE, ZBAR_CFG_ENABLE, 1);

But using this Zbar configuration still it decodes both QRCode and barcodes data.I am getting Decoded Data type as EAN-13 and QR-Code.

How I can configure Zbar sccanner properly so it decodes only QR-Code Data type?

```<code>//Reference:https://www.learnopencv.com/opencv-qr-code-scanner-c-and-python/

#include <iostream>
#include <algorithm>
#include <vector>
#include <zbar.h>

#include <opencv2/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

using namespace std;
using namespace cv;
using namespace zbar;

typedef struct
{
  string type;
  string data;
  vector <Point> location;
}decodedObject;

// Find and decode barcodes and QR codes
void decode(Mat &im, vector<decodedObject>&decodedObjects)
{

  // Create zbar scanner
  ImageScanner scanner;

  // Configure scanner
  scanner.set_config(ZBAR_QRCODE, ZBAR_CFG_ENABLE, 1);

  // Convert image to grayscale
  Mat imGray;
  cvtColor(im, imGray,CV_BGR2GRAY);

  // Wrap image data in a zbar image
  Image image(im.cols, im.rows, "Y800", (uchar *)imGray.data, im.cols * im.rows);

  // Scan the image for barcodes and QRCodes
  int n = scanner.scan(image);

  // Print results
  for(Image::SymbolIterator symbol = image.symbol_begin(); symbol != image.symbol_end(); ++symbol)
  {
    decodedObject obj;

    obj.type = symbol->get_type_name();
    obj.data = symbol->get_data();

    // Print type and data
    cout << "Type : " << obj.type << endl;
    cout << "Data : " << obj.data << endl << endl;
    decodedObjects.push_back(obj);
  }
}

int main(int argc, char *argv[])
{

  // Read image
  string imagepath = argv[1];
  Mat im = imread(imagepath);

   // Variable for decoded objects
   vector<decodedObject> decodedObjects;

   // Find and decode barcodes and QR codes
   decode(im, decodedObjects);

   return 0;
 }
</code>```

```<code>Resulted Output:
Type : QR-Code
Data : http://LearnOpenCV.com

Type : EAN-13
Data : 0036000291452
</code>```

```<code>Expected Output:
Type : QR-Code
Data : http://LearnOpenCV.com
</code>```

答:
I assume you need to disable all first with
</p>

<pre class="lang-cpp prettyprint-override"><code>    // disable all
    scanner.set_config(ZBAR_NONE, ZBAR_CFG_ENABLE, 0);

    // enable qr
    scanner.set_config(ZBAR_QRCODE, ZBAR_CFG_ENABLE, 1);
</code>```

Body:
I am using Zbar C++ library to decode QRCode,using this tutorial:
https://www.learnopencv.com/barcode-and-qr-code-scanner-using-zbar-and-opencv/

Here I have to decode only QRCode from an image however using this tutorial it decodes both QRcode and barcodes from an Image.

In tutorial it says to decode only QRCode we have to Configure Zbar Imagescanner properly.

In tutorial they are using following configuration to decode both QRCode and Barcodes

ImageScanner scanner;
scanner.set_config(ZBAR_NONE, ZBAR_CFG_ENABLE, 1);

So to decode only QRCode I am using following configuration:

ImageScanner scanner;
scanner.set_config(ZBAR_QRCODE, ZBAR_CFG_ENABLE, 1);

But using this Zbar configuration still it decodes both QRCode and barcodes data.I am getting Decoded Data type as EAN-13 and QR-Code.

How I can configure Zbar sccanner properly so it decodes only QR-Code Data type?

//Reference:https://www.learnopencv.com/opencv-qr-code-scanner-c-and-python/

#include <iostream>
#include <algorithm>
#include <vector>
#include <zbar.h>

#include <opencv2/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

using namespace std;
using namespace cv;
using namespace zbar;

typedef struct
{
  string type;
  string data;
  vector <Point> location;
}decodedObject;

// Find and decode barcodes and QR codes
void decode(Mat &im, vector<decodedObject>&decodedObjects)
{

  // Create zbar scanner
  ImageScanner scanner;

  // Configure scanner
  scanner.set_config(ZBAR_QRCODE, ZBAR_CFG_ENABLE, 1);

  // Convert image to grayscale
  Mat imGray;
  cvtColor(im, imGray,CV_BGR2GRAY);

  // Wrap image data in a zbar image
  Image image(im.cols, im.rows, "Y800", (uchar *)imGray.data, im.cols * im.rows);

  // Scan the image for barcodes and QRCodes
  int n = scanner.scan(image);

  // Print results
  for(Image::SymbolIterator symbol = image.symbol_begin(); symbol != image.symbol_end(); ++symbol)
  {
    decodedObject obj;

    obj.type = symbol->get_type_name();
    obj.data = symbol->get_data();

    // Print type and data
    cout << "Type : " << obj.type << endl;
    cout << "Data : " << obj.data << endl << endl;
    decodedObjects.push_back(obj);
  }
}

int main(int argc, char *argv[])
{

  // Read image
  string imagepath = argv[1];
  Mat im = imread(imagepath);

   // Variable for decoded objects
   vector<decodedObject> decodedObjects;

   // Find and decode barcodes and QR codes
   decode(im, decodedObjects);

   return 0;
 }

Resulted Output:
Type : QR-Code
Data : http://LearnOpenCV.com

Type : EAN-13
Data : 0036000291452

Expected Output:
Type : QR-Code
Data : http://LearnOpenCV.com

Body:
I assume you need to disable all first with

    // disable all
    scanner.set_config(ZBAR_NONE, ZBAR_CFG_ENABLE, 0);

    // enable qr
    scanner.set_config(ZBAR_QRCODE, ZBAR_CFG_ENABLE, 1);


问:
Twig equality if..else in symfony 2 gives both results
I'm using Symfony2 with Twig and when trying to determine the class that should be a div Twig says that all 4 classes are active even beeing in an if..else clause.
Redirect has only 1 value. I checked the syntax and I think it's correct so maybe I'm missing something.

It's correct my code or is something wrong in the Twig comparision (equality or if..else clause)?

Here is the Twig code:

```<code>{% if redirect == 'a' %}
    {% block classA 'active' %}
{% elseif redirect == 'b' %}
    {% block classB 'active' %}
{% elseif redirect == 'c' %}
    {% block classC 'active' %}
{% else %}
    {% block classD 'active' %}
{% endif %}
</code>```

And the controller code:

```<code>[...]
$redirect = "a";

return $this->render('FrontendBundle:Default:delete.html.twig', array(
    'id' => $id,
    'redirect' => $redirect,
    'text' => $text)
);
</code>```

Edited.

Solution

I found that it's not possible to use if clauses out of a block, so the solution goes ahead using one block for each class.

I've also thought that a better solution would be to use a dynamic name block, but i read that's not possible.

Finally I found this that solve my problem in a different way: http://peter-hoffmann.com/2012/highlight-active-menu-item-with-twig-and-silex.html

Kind regards.

答:
Even though this question is old, I want to clarify a few things, since there is no real answer provided.

The underlying problem here is that block is evaluated during compile time, while if is evaluated during run-time. This means that blocks are always defined, one cannot define blocks conditionally. That is also the reason why blocks cannot have dynamic names.

With the template from the question, this is not a problem:

classes.html.twig:

```<code>{% if redirect == 'a' %}
    {% block classA %}active{% endblock %}
{% elseif redirect == 'b' %}
    {% block classB %}active{% endblock %}
{% elseif redirect == 'c' %}
    {% block classC %}active{% endblock %}
{% else %}
    {% block classD %}active{% endblock %}
{% endif %}
</code>```

If we render this, we get 'active', i.e. the expected output. While each block is defined, only one of them is rendered, because of the if. The problem is only revealed if we have inheritance. So let's say we have the following parent template (I assume something like that was used by the poster):

parent.html.twig:

```<code>{% block classA %}{% endblock %}
{% block classB %}{% endblock %}
{% block classC %}{% endblock %}
{% block classD %}{% endblock %}
</code>```

And change our extending template to extend this (also added classE for demonstration purposes):

classes.html.twig:

```<code>{% extends "parent.html.twig" %}

{% if redirect == 'a' %}
    {% block classA %}active{% endblock %}
{% elseif redirect == 'b' %}
    {% block classB %}active{% endblock %}
{% elseif redirect == 'c' %}
    {% block classC %}active{% endblock %}
{% else %}
    {% block classD %}active{% endblock %}
{% endif %}

{% block classE %}undefined{% endblock %}
</code>```

Now, if we render classes.html.twig, we get 'activeactiveactiveactive'. As before, the blocks are all defined with 'active', but the parent template has no conditional rendering, so all of them are shown. Block 'classE' is not rendered, because it is not defined in the parent template.

To fix this, one needs to essentially swap the if and block statements.

```<code>{% extends "parent.html.twig" %}

{% block classA %}
    {% if redirect == 'a' %}
        active
    {% endif %}
{% endblock %}
{% block classB %}
    {% if redirect != 'a' and redirect == 'b' %}
        active
    {% endif %}
{% endblock %}
{% block classC %}
    {% if redirect != 'a' and redirect != 'b' and redirect == 'c' %}
        active
    {% endif %}
{% endblock %}
{% block classD %}
    {% if redirect != 'a' and redirect != 'b' and redirect != 'c' %}
        active
    {% endif %}
{% endblock %}
</code>```

Sadly, we lose the if/else structure when we do this, so we have to write more conditions. To fix this, we can add an intermediate step using a variable.

```<code>{% extends "classes.html.twig" %}

{% if redirect == 'a' %}
    {% set render = 'a' %}
{% elseif redirect == 'b' %}
    {% set render = 'b' %}
{% elseif redirect == 'c' %}
    {% set render = 'c' %}
{% else %}
    {% set render = 'd' %}
{% endif %}

{% block classA %}
    {% if render == 'a' %}
        active
    {% endif %}
{% endblock %}
{% block classB %}
    {% if render == 'b' %}
        active
    {% endif %}
{% endblock %}
{% block classC %}
    {% if render == 'c' %}
        active
    {% endif %}
{% endblock %}
{% block classD %}
    {% if render == 'd' %}
        active
    {% endif %}
{% endblock %}
</code>```

Body:
I'm using Symfony2 with Twig and when trying to determine the class that should be a div Twig says that all 4 classes are active even beeing in an if..else clause.
Redirect has only 1 value. I checked the syntax and I think it's correct so maybe I'm missing something.

It's correct my code or is something wrong in the Twig comparision (equality or if..else clause)?

Here is the Twig code:

{% if redirect == 'a' %}
    {% block classA 'active' %}
{% elseif redirect == 'b' %}
    {% block classB 'active' %}
{% elseif redirect == 'c' %}
    {% block classC 'active' %}
{% else %}
    {% block classD 'active' %}
{% endif %}

And the controller code:

[...]
$redirect = "a";

return $this->render('FrontendBundle:Default:delete.html.twig', array(
    'id' => $id,
    'redirect' => $redirect,
    'text' => $text)
);

Edited.

Solution

I found that it's not possible to use if clauses out of a block, so the solution goes ahead using one block for each class.

I've also thought that a better solution would be to use a dynamic name block, but i read that's not possible.

Finally I found this that solve my problem in a different way: http://peter-hoffmann.com/2012/highlight-active-menu-item-with-twig-and-silex.html

Kind regards.

Body:
Even though this question is old, I want to clarify a few things, since there is no real answer provided.

The underlying problem here is that block is evaluated during compile time, while if is evaluated during run-time. This means that blocks are always defined, one cannot define blocks conditionally. That is also the reason why blocks cannot have dynamic names.

With the template from the question, this is not a problem:

classes.html.twig:

{% if redirect == 'a' %}
    {% block classA %}active{% endblock %}
{% elseif redirect == 'b' %}
    {% block classB %}active{% endblock %}
{% elseif redirect == 'c' %}
    {% block classC %}active{% endblock %}
{% else %}
    {% block classD %}active{% endblock %}
{% endif %}

If we render this, we get 'active', i.e. the expected output. While each block is defined, only one of them is rendered, because of the if. The problem is only revealed if we have inheritance. So let's say we have the following parent template (I assume something like that was used by the poster):

parent.html.twig:

{% block classA %}{% endblock %}
{% block classB %}{% endblock %}
{% block classC %}{% endblock %}
{% block classD %}{% endblock %}

And change our extending template to extend this (also added classE for demonstration purposes):

classes.html.twig:

{% extends "parent.html.twig" %}

{% if redirect == 'a' %}
    {% block classA %}active{% endblock %}
{% elseif redirect == 'b' %}
    {% block classB %}active{% endblock %}
{% elseif redirect == 'c' %}
    {% block classC %}active{% endblock %}
{% else %}
    {% block classD %}active{% endblock %}
{% endif %}

{% block classE %}undefined{% endblock %}

Now, if we render classes.html.twig, we get 'activeactiveactiveactive'. As before, the blocks are all defined with 'active', but the parent template has no conditional rendering, so all of them are shown. Block 'classE' is not rendered, because it is not defined in the parent template.

To fix this, one needs to essentially swap the if and block statements.

{% extends "parent.html.twig" %}

{% block classA %}
    {% if redirect == 'a' %}
        active
    {% endif %}
{% endblock %}
{% block classB %}
    {% if redirect != 'a' and redirect == 'b' %}
        active
    {% endif %}
{% endblock %}
{% block classC %}
    {% if redirect != 'a' and redirect != 'b' and redirect == 'c' %}
        active
    {% endif %}
{% endblock %}
{% block classD %}
    {% if redirect != 'a' and redirect != 'b' and redirect != 'c' %}
        active
    {% endif %}
{% endblock %}

Sadly, we lose the if/else structure when we do this, so we have to write more conditions. To fix this, we can add an intermediate step using a variable.

{% extends "classes.html.twig" %}

{% if redirect == 'a' %}
    {% set render = 'a' %}
{% elseif redirect == 'b' %}
    {% set render = 'b' %}
{% elseif redirect == 'c' %}
    {% set render = 'c' %}
{% else %}
    {% set render = 'd' %}
{% endif %}

{% block classA %}
    {% if render == 'a' %}
        active
    {% endif %}
{% endblock %}
{% block classB %}
    {% if render == 'b' %}
        active
    {% endif %}
{% endblock %}
{% block classC %}
    {% if render == 'c' %}
        active
    {% endif %}
{% endblock %}
{% block classD %}
    {% if render == 'd' %}
        active
    {% endif %}
{% endblock %}


问:
What does float *a[]; declare in c?
Suppose float *a[]; is declared in the main method n c. I'm trying to learn about pointers and understand what the above means.

I'm guessing it declares a pointer to the first element of that array a[].
But a[] doesn't have any elements..
I am really confused.

Thanks anyone who helps.

答:
```<code>float *a[];
</code>```

is an incomplete declaration of an array of pointers to float since it has no size.  At some point there also needs to be a defining declaration that specifies the number of elements, either explicitly or using an initializer:

```<code>float *a[];
...
float *a[N];
</code>```

or

```<code>float *a[];
...
float *a[] = {&a, &b, &c, ...};  // where a, b, c, ..., are objects of type float
</code>```

As a member of a struct type, such as

```<code>struct foo {
  int something;
  int something_else;
  float *a[];
};
</code>```

it's a flexible array member - if you just declare an instance of struct foo like

```<code>struct foo bar;
</code>```

then it isn't part of the object (you can't acess bar.a[i]).  However, if you allocate the object dynamically, you can specify extra space for the array:

```<code>struct foo *p = malloc( sizeof *p + sizeof *(p->a) * N );
</code>```

which is equivalent to defining the struct type as

```<code>struct foo {
  int something;
  int something_else;
  float *a[N];
};
</code>```

Title: What does float *a[]; declare in c?

Body:
float *a[];

is an incomplete declaration of an array of pointers to float since it has no size.  At some point there also needs to be a defining declaration that specifies the number of elements, either explicitly or using an initializer:

float *a[];
...
float *a[N];

or

float *a[];
...
float *a[] = {&a, &b, &c, ...};  // where a, b, c, ..., are objects of type float

As a member of a struct type, such as

struct foo {
  int something;
  int something_else;
  float *a[];
};

it's a flexible array member - if you just declare an instance of struct foo like

struct foo bar;

then it isn't part of the object (you can't acess bar.a[i]).  However, if you allocate the object dynamically, you can specify extra space for the array:

struct foo *p = malloc( sizeof *p + sizeof *(p->a) * N );

which is equivalent to defining the struct type as

struct foo {
  int something;
  int something_else;
  float *a[N];
};


问:
With If statement Page load error works, but page load success does not
When running If statement, upon page element not being present, page load fails and produces a correct error message, but when the element is present, both conditions run, success code operation as well as failure operation.

Tried await page.waitForSelector and await page.$(selector) both did not work and

```<code>await page.waitForSelector('#example').then(() => {
  console.log('SUCCESS');
}).catch(e => {
  console.log('FAIL');
});
</code>```

```<code>if (await page.$('.SELECTOR') !== null)
console.log(success(await page.title() + ' SUCCESS LOAD 1 - URL Page Load'));  // console log
// on success continue below
else
console.log(error(await page.title() + ' FAIL LOAD 1 - URL Page Load'));  // console log
await page.screenshot({path: './screenshots/Fail_Load_1_PageDidNotLoad.jpeg'}); // screenshot
await page.evaluate(() => alert('FAIL LOAD 1 - URL Page Did Not Load'));  // pop up alert
await browser.close();  // release memory
return process.exit(1); // exit process
</code>```

How to correctly incorporate a THEN.

答:
RESOLVED, if anyone has the same challenge.</p>

```<code>try {
await page.waitForSelector('.smallText', { timeout: 5000 })
console.log(success(await page.title() + ' SUCCESS LOAD 1 - URL Page Load'));  // console log
await page.screenshot({path: './screenshots/Success_Load_1_PageLoad.jpeg'}); // screenshot

} catch (err) {
console.log(error(await page.title() + ' FAIL LOAD 1 - URL Page Load'));  // console log
await page.screenshot({path: './screenshots/Fail_Load_1_PageDidNotLoad.jpeg'}); // screenshot
await page.evaluate(() => alert('FAIL LOAD 1 - URL Page Did Not Load'));  // pop up alert
await browser.close();  // release memory
return process.exit(1); // exit process
//return false
}
</code>```

Body:
When running If statement, upon page element not being present, page load fails and produces a correct error message, but when the element is present, both conditions run, success code operation as well as failure operation.

Tried await page.waitForSelector and await page.$(selector) both did not work and

await page.waitForSelector('#example').then(() => {
  console.log('SUCCESS');
}).catch(e => {
  console.log('FAIL');
});

if (await page.$('.SELECTOR') !== null)
console.log(success(await page.title() + ' SUCCESS LOAD 1 - URL Page Load'));  // console log
// on success continue below
else
console.log(error(await page.title() + ' FAIL LOAD 1 - URL Page Load'));  // console log
await page.screenshot({path: './screenshots/Fail_Load_1_PageDidNotLoad.jpeg'}); // screenshot
await page.evaluate(() => alert('FAIL LOAD 1 - URL Page Did Not Load'));  // pop up alert
await browser.close();  // release memory
return process.exit(1); // exit process

How to correctly incorporate a THEN.

Body:
RESOLVED, if anyone has the same challenge.

try {
await page.waitForSelector('.smallText', { timeout: 5000 })
console.log(success(await page.title() + ' SUCCESS LOAD 1 - URL Page Load'));  // console log
await page.screenshot({path: './screenshots/Success_Load_1_PageLoad.jpeg'}); // screenshot

} catch (err) {
console.log(error(await page.title() + ' FAIL LOAD 1 - URL Page Load'));  // console log
await page.screenshot({path: './screenshots/Fail_Load_1_PageDidNotLoad.jpeg'}); // screenshot
await page.evaluate(() => alert('FAIL LOAD 1 - URL Page Did Not Load'));  // pop up alert
await browser.close();  // release memory
return process.exit(1); // exit process
//return false
}


问:
“Deleted” from array still exists
I am trying to delete some information from an array, however when I go to search for the deleted thing it still shows up.

I have tried this code:

```<code>function removeperson() {

    var search = prompt("Type in someone's name to remove them.");
    while(!found && i < people.names.length) {
        if(people.names[i] == search){
            found = true;
        } else {
            i++;
        }
    }
    if(found){
            people.names.splice[i, 1];
            people.emails.splice[i, 1];
            people.phonenums.splice[i, 1];
            alert("Person successfully removed!");
            found = false;
    } else {
            alert("That person is not here or has already been deleted.");
            found = false;
    }
    i = 0;

}
</code>```

However, when I use my search function to search for the deleted thing, it still appears. The full code is available here: https://js.do/nioiluc/321017

答:
The main issue is that you are using slice with square brackets. That doesn't invoke the function. You need to use round brackets.
Second, in findperson, you must assign found to false before the while loop.

Please see the improved version at https://js.do/code/323115

Regards.

Title: “Deleted” from array still exists

Body:
I am trying to delete some information from an array, however when I go to search for the deleted thing it still shows up.

I have tried this code:

function removeperson() {

    var search = prompt("Type in someone's name to remove them.");
    while(!found && i < people.names.length) {
        if(people.names[i] == search){
            found = true;
        } else {
            i++;
        }
    }
    if(found){
            people.names.splice[i, 1];
            people.emails.splice[i, 1];
            people.phonenums.splice[i, 1];
            alert("Person successfully removed!");
            found = false;
    } else {
            alert("That person is not here or has already been deleted.");
            found = false;
    }
    i = 0;

}

However, when I use my search function to search for the deleted thing, it still appears. The full code is available here: https://js.do/nioiluc/321017


问:
PowerShell module - pass a parameter while importing module
In the below sample module file, is there a way to pass the myvar value while importing the module.

For example,

```<code>import-module -name .\test.psm1 -?? pass a parameter? e.g value of myvar

#test.psm1
$script:myvar = "hi"
function Show-MyVar {Write-Host $script:myvar}
function Set-MyVar ($Value) {$script:myvar = $Value}
#end test.psm1
</code>```

(This snippet was copied from another question.)

答:
The -ArgumentList parameter of Import-Module unfortunately does not accept a [hashtable] or [psobject] or something. A list with fixed postitions is way too static for my liking so I prefer to use a single [hashtable]-argument which has to be "manually dispatched" like this:

param( [parameter(Mandatory=$false)][hashtable]$passedVariables )
# this module uses the following variables that need to be set and passed as [hashtable]:
#  BeQuiet, URL, LotsaMore...
$passedVariables.GetEnumerator() |
  ForEach-Object { Set-Variable -Name $_.Key -Value $_.Value }
...
```

<p>The importing module or script does something like this:</p>

<pre class="lang-bsh prettyprint-override"><code>...
# variables have been defined at this point
$variablesToPass = @{}
'BeQuiet,URL,LotsaMore' -split ',' |
    ForEach-Object { $variablesToPass[$_] = Get-Variable $_ -ValueOnly }
Import-Module TheModule -ArgumentList $variablesToPass
</code>```

The above code uses the same names in both modules but you could of course easily map the variable names of the importing script arbitrarily to the names that are used in the imported module.

Body:
In the below sample module file, is there a way to pass the myvar value while importing the module.

For example,

import-module -name .\test.psm1 -?? pass a parameter? e.g value of myvar

#test.psm1
$script:myvar = "hi"
function Show-MyVar {Write-Host $script:myvar}
function Set-MyVar ($Value) {$script:myvar = $Value}
#end test.psm1

(This snippet was copied from another question.)

Body:
The -ArgumentList parameter of Import-Module unfortunately does not accept a [hashtable] or [psobject] or something. A list with fixed postitions is way too static for my liking so I prefer to use a single [hashtable]-argument which has to be "manually dispatched" like this:

param( [parameter(Mandatory=$false)][hashtable]$passedVariables )
# this module uses the following variables that need to be set and passed as [hashtable]:
#  BeQuiet, URL, LotsaMore...
$passedVariables.GetEnumerator() |
  ForEach-Object { Set-Variable -Name $_.Key -Value $_.Value }
...

The importing module or script does something like this:

...
# variables have been defined at this point
$variablesToPass = @{}
'BeQuiet,URL,LotsaMore' -split ',' |
    ForEach-Object { $variablesToPass[$_] = Get-Variable $_ -ValueOnly }
Import-Module TheModule -ArgumentList $variablesToPass

The above code uses the same names in both modules but you could of course easily map the variable names of the importing script arbitrarily to the names that are used in the imported module.


问:
How do I get an internal SVG element's position relative to the viewport of an outer SVG element?
Say I have an SVG element containing some stuff:

```<code><div style="margin-left:50px; width: 100%; min-height: 400px;">
  <svg>
    <g transform="translate(34.34,47.5) scale(0.345)" height="100%" width="100%">
      <svg x="20" y ="50" style="overflow: visible">
        <circle cx="0" cy="0" r="35" stroke="red" fill="blue">
        <text>a bunch of text</text>
      </svg>
      <line />
    </g>
  <svg>
<div>
</code>```

I'm trying to find the center position of the <g> relative to the viewport of the outer <svg> element, so that I can translate the <g> to be centered within the outer <svg>, and scale it to fit.

I was able to get it working using getBoundingClientRect() and adjusting for the transform scale, but this does not work in Firefox because the <svg> elements inside the <g> container are not constrained to the bounding box of the displayed section of their contents (rather it's the same size as the outer <svg>, with some scaling).

There is probably a solution using createSVGPoint() and getScreenCTM() or getCTM() but frankly I'm not sure what I should be using.

答:
I managed to figure out a solution using one of the d3.zoom transform methods (we're using d3.zoom to manage the translate/scale transform), and  SVGElement.getBBox(). I originally was using this method but had messed up the calculation; this way it works though.

const selection = d3.select(group);
const zoomBehavior = d3.zoom().on('zoom', () => {
  selectionTransform = d3.event.transform;
});
selection.call(zoomBehavior);

const scaleAndTransformTo = () => {
  selection.call(zoomBehavior.translateBy, Math.random() * 100, Math.random() * 150);

  group.setAttribute("transform", selectionTransform.toString());
}
scaleAndTransformTo();

reset.addEventListener('click', scaleAndTransformTo);
run.addEventListener('click', () => {
  const { width: containerWidth, height: containerHeight } = container.getBoundingClientRect();
  const containerCenter = [containerWidth / 2, containerHeight / 2];

  const { height, width, x, y } = group.getBBox();
  const nodeBBoxCenter = [x + (width / 2), y + (height / 2)];

  // Apply the current interpolated translate/scale to the BBox center to get the actual position
  const groupCenterCoords = selectionTransform.apply(nodeBBoxCenter);

  const translationOffset = [
    (containerCenter[0] - groupCenterCoords[0]) / selectionTransform.k,
    (containerCenter[1] - groupCenterCoords[1]) / selectionTransform.k,
  ];

  selection.call(zoomBehavior.translateBy, ...translationOffset);

  group.setAttribute("transform", selectionTransform.toString());
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#page {
  display: flex;
  flex-direction: column;
  position: relative;
  align-items: stretch;
  margin-left: 100px;
}

#container {
  background-color: grey;
  flex-grow: 1;
  flex-shrink: 0;
  min-height: 500px;
  border: 1px solid red;
}

#group > svg {
  overflow: visible;
}

#group > svg > circle {
  overflow: visible;
}

text {
  fill: black;
}</code>```

    <button id="run">Run</button>
    <button id="reset">Reset</button>

  <svg id="container">
    <g x="0" y="0" id="group" width="100%" height="100%">
      <line x1="20" y1="50" x2="150" y2="150" stroke="brown" />
      <svg x="20" y ="50">
        <circle cx="0" cy="0" r="35" stroke="red" fill="blue">
        <text x="35" y="0" height="100%" width="100%">a bunch of text</text>
      </svg>
      <line x1="100" y1="350" x2="160" y2="340" stroke="brown" />
      <svg x="100" y ="350">
        <circle cx="0" cy="0" r="35" stroke="red" fill="blue">
        <text x="35" y="0" height="100%" width="100%">a bunch of text 3</text>
      </svg>
    </g>
  <svg>

```

Body:
Say I have an SVG element containing some stuff:

  <svg>
    <g transform="translate(34.34,47.5) scale(0.345)" height="100%" width="100%">
      <svg x="20" y ="50" style="overflow: visible">
        <circle cx="0" cy="0" r="35" stroke="red" fill="blue">
        <text>a bunch of text</text>
      </svg>
      <line />
    </g>
  <svg>

I'm trying to find the center position of the <g> relative to the viewport of the outer <svg> element, so that I can translate the <g> to be centered within the outer <svg>, and scale it to fit.

I was able to get it working using getBoundingClientRect() and adjusting for the transform scale, but this does not work in Firefox because the <svg> elements inside the <g> container are not constrained to the bounding box of the displayed section of their contents (rather it's the same size as the outer <svg>, with some scaling).

There is probably a solution using createSVGPoint() and getScreenCTM() or getCTM() but frankly I'm not sure what I should be using.

Body:
I managed to figure out a solution using one of the d3.zoom transform methods (we're using d3.zoom to manage the translate/scale transform), and  SVGElement.getBBox(). I originally was using this method but had messed up the calculation; this way it works though.

const selection = d3.select(group);
const zoomBehavior = d3.zoom().on('zoom', () => {
  selectionTransform = d3.event.transform;
});
selection.call(zoomBehavior);

const scaleAndTransformTo = () => {
  selection.call(zoomBehavior.translateBy, Math.random() * 100, Math.random() * 150);

  group.setAttribute("transform", selectionTransform.toString());
}
scaleAndTransformTo();

reset.addEventListener('click', scaleAndTransformTo);
run.addEventListener('click', () => {
  const { width: containerWidth, height: containerHeight } = container.getBoundingClientRect();
  const containerCenter = [containerWidth / 2, containerHeight / 2];

  const { height, width, x, y } = group.getBBox();
  const nodeBBoxCenter = [x + (width / 2), y + (height / 2)];

  // Apply the current interpolated translate/scale to the BBox center to get the actual position
  const groupCenterCoords = selectionTransform.apply(nodeBBoxCenter);

  const translationOffset = [
    (containerCenter[0] - groupCenterCoords[0]) / selectionTransform.k,
    (containerCenter[1] - groupCenterCoords[1]) / selectionTransform.k,
  ];

  selection.call(zoomBehavior.translateBy, ...translationOffset);

  group.setAttribute("transform", selectionTransform.toString());
});

#page {
  display: flex;
  flex-direction: column;
  position: relative;
  align-items: stretch;
  margin-left: 100px;
}

#container {
  background-color: grey;
  flex-grow: 1;
  flex-shrink: 0;
  min-height: 500px;
  border: 1px solid red;
}

#group > svg {
  overflow: visible;
}

#group > svg > circle {
  overflow: visible;
}

text {
  fill: black;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div id="page">
  <div>
    <button id="run">Run</button>
    <button id="reset">Reset</button>
  </div>
  <svg id="container">
    <g x="0" y="0" id="group" width="100%" height="100%">
      <line x1="20" y1="50" x2="150" y2="150" stroke="brown" />
      <svg x="20" y ="50">
        <circle cx="0" cy="0" r="35" stroke="red" fill="blue">
        <text x="35" y="0" height="100%" width="100%">a bunch of text</text>
      </svg>
      <line x1="100" y1="350" x2="160" y2="340" stroke="brown" />
      <svg x="100" y ="350">
        <circle cx="0" cy="0" r="35" stroke="red" fill="blue">
        <text x="35" y="0" height="100%" width="100%">a bunch of text 3</text>
      </svg>
    </g>
  <svg>
<div>


问:
how to retrieve the child of the parent in n1ql query
I am planning to retrieve the child elements of the parent based on some condition. How can i retrieve it, being inside the array of array objects.

```<code>SELECT ARRAY {s.name,s.id} FOR s IN t.countryDetails.stateInfo END AS stateDetails
FROM test AS t
WHERE t.type = "countries" and t.countryDetails.name = 'US';
</code>```

this is the actual json document i am trying to query:

```<code>{
   "type":"countries",
   "docName":"CountryData",
   "countryDetails":[
      {
         "name":"US",
         "code":"+1",
         "stateInfo":[
            {
               "name":"Florida",
               "id":"1212"
            },
            {
               "name":"NewYork",
               "id":"1214"
            }
         ]
      },
       {
         "name":"France",
         "code":"+33",
         "stateInfo":[
            {
               "name":"Grand Est",
               "id":"5212"
            },
            {
               "name":"Brittany",
               "id":"5214"
            }
         ]
      }
   ]
}
</code>```

I am expecting the following output to bring out the country state details of US only:

```<code>[
            {
               "name":"Florida",
               "id":"1212"
            },
            {
               "name":"NewYork",
               "id":"1214"
            }
         ]
</code>```

答:
If you your ConutryDetails has single entry per country use the following

```<code>SELECT FIRST s.stateInfo FOR IN t.countryDetails WHEN s.name = "US" END AS stateDetails
FROM test AS t
WHERE t.type = "countries"
      AND ANY v IN t.countryDetails SATISFIES v.name = 'US' END;
</code>```

OR

```<code>SELECT cd.stateInfo AS stateDetails
FROM test AS t
UNNEST t.countryDetails AS cd
WHERE t.type = "countries" AND cd.name = 'US';
</code>```

Body:
I am planning to retrieve the child elements of the parent based on some condition. How can i retrieve it, being inside the array of array objects.

SELECT ARRAY {s.name,s.id} FOR s IN t.countryDetails.stateInfo END AS stateDetails
FROM test AS t
WHERE t.type = "countries" and t.countryDetails.name = 'US';

this is the actual json document i am trying to query:

{
   "type":"countries",
   "docName":"CountryData",
   "countryDetails":[
      {
         "name":"US",
         "code":"+1",
         "stateInfo":[
            {
               "name":"Florida",
               "id":"1212"
            },
            {
               "name":"NewYork",
               "id":"1214"
            }
         ]
      },
       {
         "name":"France",
         "code":"+33",
         "stateInfo":[
            {
               "name":"Grand Est",
               "id":"5212"
            },
            {
               "name":"Brittany",
               "id":"5214"
            }
         ]
      }
   ]
}

I am expecting the following output to bring out the country state details of US only:

[
            {
               "name":"Florida",
               "id":"1212"
            },
            {
               "name":"NewYork",
               "id":"1214"
            }
         ]

Body:
If you your ConutryDetails has single entry per country use the following

SELECT FIRST s.stateInfo FOR IN t.countryDetails WHEN s.name = "US" END AS stateDetails
FROM test AS t
WHERE t.type = "countries"
      AND ANY v IN t.countryDetails SATISFIES v.name = 'US' END;

OR

SELECT cd.stateInfo AS stateDetails
FROM test AS t
UNNEST t.countryDetails AS cd
WHERE t.type = "countries" AND cd.name = 'US';