问:
Accepting a list of integers as an input, and insert them, one by one, into an empty Binary Search Tree in python
I want to accept a list of integers as input, and insert them, one by one, into an empty BST. The lecturer provided some code for me to modify.

I was trying to modify the code and got stuck. I have accepted a list of integers and separated with the spaces and inserted it in to a list. Now I need to add the elements in the list to the binary tree and get the preorder, postorder traversals. Here is the code:

```<code>class BinaryTree:
    def __init__(self):
        self.root = None
        self.size = 0

    # Return True if the element is in the tree
    def search(self, e):
        current = self.root # Start from the root

        while current != None:
            if e < current.element:
                current = current.left
            elif e > current.element:
                current = current.right
            else: # element matches current.element
                return True # Element is found

        return False

    # Insert element e into the binary search tree
    # Return True if the element is inserted successfully
    def insert(self, e):
        if self.root == None:
          self.root = self.createNewNode(e) # Create a new root
        else:
          # Locate the parent node
          parent = None
          current = self.root
          while current != None:
            if e < current.element:
              parent = current
              current = current.left
            elif e > current.element:
              parent = current
              current = current.right
            else:
              return False # Duplicate node not inserted

          # Create the new node and attach it to the parent node
          if e < parent.element:
            parent.left = self.createNewNode(e)
          else:
            parent.right = self.createNewNode(e)

        self.size += 1 # Increase tree size
        return True # Element inserted

    # Create a new TreeNode for element e
    def createNewNode(self, e):
      return TreeNode(e)
    """
    # Return the size of the tree
    def getSize(self):
      return self.size"""

    # Inorder traversal from the root
    def inorder(self):
      self.inorderHelper(self.root)

    # Inorder traversal from a subtree
    def inorderHelper(self, r):
      if r != None:
        self.inorderHelper(r.left)
        print(r.element, end = " ")
        self.inorderHelper(r.right)

    # Postorder traversal from the root
    def postorder(self):
      self.postorderHelper(self.root)

    # Postorder traversal from a subtree
    def postorderHelper(self, root):
      if root != None:
        self.postorderHelper(root.left)
        self.postorderHelper(root.right)
        print(root.element, end = " ")

    # Preorder traversal from the root
    def preorder(self):
      self.preorderHelper(self.root)

    # Preorder traversal from a subtree
    def preorderHelper(self, root):
      if root != None:
        print(root.element, end = " ")
        self.preorderHelper(root.left)
        self.preorderHelper(root.right)

    # Return true if the tree is empty
    def isEmpty(self):
      return self.size == 0

    # Remove all elements from the tree
    def clear(self):
      self.root == None
      self.size == 0

    # Return the root of the tree
    def getRoot(self):
      return self.root

class TreeNode:
    def __init__(self, e):
      self.element = e
      self.left = None # Point to the left node, default None
      self.right = None # Point to the right node, default None

    ####################### Main test binary tree

def main(size = 7):
    int_list=input('Enter a list of integers seperated by spaces: ')

    numbers =[int_list]

    print ("\n\nInserting the following values:")
    intTree = BinaryTree()
    for e in numbers:
      intTree.insert(e)
    print("\nPreorder traversal:")
    intTree.preorder()
    print("\n\nInorder traversal:")
    intTree.inorder()
    print("\n\nPostorder traversal:")
    intTree.postorder()

if __name__ == "__main__":
    main()
</code>```

答: From what I understand you have a list and you want to insert all the elements in a binary search tree. You can write a new function that takes as parameter an array, your list, and the you can iterate with a for loop and call the function insert(self, e) for every element that belongs to the array. Then outside the loop you can call whatever function you need (postorder, ...).

Body:
I want to accept a list of integers as input, and insert them, one by one, into an empty BST. The lecturer provided some code for me to modify.

I was trying to modify the code and got stuck. I have accepted a list of integers and separated with the spaces and inserted it in to a list. Now I need to add the elements in the list to the binary tree and get the preorder, postorder traversals. Here is the code:

class BinaryTree:
    def __init__(self):
        self.root = None
        self.size = 0

    # Return True if the element is in the tree
    def search(self, e):
        current = self.root # Start from the root

        while current != None:
            if e < current.element:
                current = current.left
            elif e > current.element:
                current = current.right
            else: # element matches current.element
                return True # Element is found

        return False

    # Insert element e into the binary search tree
    # Return True if the element is inserted successfully
    def insert(self, e):
        if self.root == None:
          self.root = self.createNewNode(e) # Create a new root
        else:
          # Locate the parent node
          parent = None
          current = self.root
          while current != None:
            if e < current.element:
              parent = current
              current = current.left
            elif e > current.element:
              parent = current
              current = current.right
            else:
              return False # Duplicate node not inserted

          # Create the new node and attach it to the parent node
          if e < parent.element:
            parent.left = self.createNewNode(e)
          else:
            parent.right = self.createNewNode(e)

        self.size += 1 # Increase tree size
        return True # Element inserted

    # Create a new TreeNode for element e
    def createNewNode(self, e):
      return TreeNode(e)
    """
    # Return the size of the tree
    def getSize(self):
      return self.size"""

    # Inorder traversal from the root
    def inorder(self):
      self.inorderHelper(self.root)

    # Inorder traversal from a subtree
    def inorderHelper(self, r):
      if r != None:
        self.inorderHelper(r.left)
        print(r.element, end = " ")
        self.inorderHelper(r.right)

    # Postorder traversal from the root
    def postorder(self):
      self.postorderHelper(self.root)

    # Postorder traversal from a subtree
    def postorderHelper(self, root):
      if root != None:
        self.postorderHelper(root.left)
        self.postorderHelper(root.right)
        print(root.element, end = " ")

    # Preorder traversal from the root
    def preorder(self):
      self.preorderHelper(self.root)

    # Preorder traversal from a subtree
    def preorderHelper(self, root):
      if root != None:
        print(root.element, end = " ")
        self.preorderHelper(root.left)
        self.preorderHelper(root.right)

    # Return true if the tree is empty
    def isEmpty(self):
      return self.size == 0

    # Remove all elements from the tree
    def clear(self):
      self.root == None
      self.size == 0

    # Return the root of the tree
    def getRoot(self):
      return self.root

class TreeNode:
    def __init__(self, e):
      self.element = e
      self.left = None # Point to the left node, default None
      self.right = None # Point to the right node, default None

    ####################### Main test binary tree

def main(size = 7):
    int_list=input('Enter a list of integers seperated by spaces: ')

    numbers =[int_list]

    print ("\n\nInserting the following values:")
    intTree = BinaryTree()
    for e in numbers:
      intTree.insert(e)
    print("\nPreorder traversal:")
    intTree.preorder()
    print("\n\nInorder traversal:")
    intTree.inorder()
    print("\n\nPostorder traversal:")
    intTree.postorder()

if __name__ == "__main__":
    main()


来源: stackexchange

问:
org.hibernate.MappingException: Could not determine type for: java.util.Map
I have a problem with mapping a property in hibernate. I just want to map Device (1 to many) to DeviceData (many to 1) and vice versa.

My output should be:

Table: Device =
id,
device (a device number),

Table: DeviceData =
id,
device_id (forgein key),
...

Everything has been generated by json2ojo generator.

```<code>@Entity(name = "Device")
@Table(name = "device_devices")
public class Device {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @JsonProperty
    private Long id;

    @JsonProperty("device")
    @Column(unique = true)
    private String device;

    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "device", cascade = CascadeType.ALL, orphanRemoval = true, targetEntity = DeviceData.class)
    private List<DeviceData> deviceData = new ArrayList<>();
...
}

@Entity(name = "DeviceData")
@Table(name = "device_data")
public class DeviceData {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @JsonProperty
    private Long id;
...
    @JsonIgnore
    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, targetEntity = Device.class)
    @JoinColumn(name = "device_id", referencedColumnName = "id")
    private Device device;

    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

   @JsonProperty("id")
    public Long getId(){
        return id;
    }

    @JsonIgnore
    public Device getDevice(){
        return device;
    }

    @JsonIgnore
    public void setDevice(Device device){
        this.device = device;
    }
...

...
    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }
}
</code>```

Error:

```<code>org.hibernate.MappingException: Could not determine type for:
   java.util.Map, at table: device_data, for columns:
   [org.hibernate.mapping.Column(additionalProperties)]     at
   org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:456)  at
   org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:423)  at
   org.hibernate.mapping.Property.isValid(Property.java:226)    at
   org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:597)
    at org.hibernate.mapping.RootClass.validate(RootClass.java:265)     at
   org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:329)
    at
   org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:461)
    at
   org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:710)
    at
   io.dropwizard.hibernate.SessionFactoryFactory.buildSessionFactory(SessionFactoryFactory.java:96)
    at
   io.dropwizard.hibernate.SessionFactoryFactory.build(SessionFactoryFactory.java:49)
    at
   io.dropwizard.hibernate.SessionFactoryFactory.build(SessionFactoryFactory.java:39)
    at
   io.dropwizard.hibernate.HibernateBundle.run(HibernateBundle.java:67)
    at
   io.dropwizard.hibernate.HibernateBundle.run(HibernateBundle.java:19)
    at io.dropwizard.setup.Bootstrap.run(Bootstrap.java:200)    at
   io.dropwizard.cli.EnvironmentCommand.run(EnvironmentCommand.java:42)
    at
   io.dropwizard.cli.ConfiguredCommand.run(ConfiguredCommand.java:87)
    at io.dropwizard.cli.Cli.run(Cli.java:78)   at
   io.dropwizard.Application.run(Application.java:93)
</code>```

答:
By default, JPA tries to persist all the properties of @Entity class, but you can ignore some properties using @Transient annotation. In your case, if you don't want to persist additionalProperties field in both classes, you should mark their as @Transient:

```<code>@JsonIgnore
@Transient
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a problem with mapping a property in hibernate. I just want to map Device (1 to many) to DeviceData (many to 1) and vice versa.

My output should be:

Table: Device =
id,
device (a device number),

Table: DeviceData =
id,
device_id (forgein key),
...

Everything has been generated by json2ojo generator.

@Entity(name = "Device")
@Table(name = "device_devices")
public class Device {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @JsonProperty
    private Long id;

    @JsonProperty("device")
    @Column(unique = true)
    private String device;

    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "device", cascade = CascadeType.ALL, orphanRemoval = true, targetEntity = DeviceData.class)
    private List<DeviceData> deviceData = new ArrayList<>();
...
}

@Entity(name = "DeviceData")
@Table(name = "device_data")
public class DeviceData {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @JsonProperty
    private Long id;
...
    @JsonIgnore
    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, targetEntity = Device.class)
    @JoinColumn(name = "device_id", referencedColumnName = "id")
    private Device device;

    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

   @JsonProperty("id")
    public Long getId(){
        return id;
    }

    @JsonIgnore
    public Device getDevice(){
        return device;
    }

    @JsonIgnore
    public void setDevice(Device device){
        this.device = device;
    }
...

...
    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }
}

Error:

org.hibernate.MappingException: Could not determine type for:
   java.util.Map, at table: device_data, for columns:
   [org.hibernate.mapping.Column(additionalProperties)]     at
   org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:456)  at
   org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:423)  at
   org.hibernate.mapping.Property.isValid(Property.java:226)    at
   org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:597)
    at org.hibernate.mapping.RootClass.validate(RootClass.java:265)     at
   org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:329)
    at
   org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:461)
    at
   org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:710)
    at
   io.dropwizard.hibernate.SessionFactoryFactory.buildSessionFactory(SessionFactoryFactory.java:96)
    at
   io.dropwizard.hibernate.SessionFactoryFactory.build(SessionFactoryFactory.java:49)
    at
   io.dropwizard.hibernate.SessionFactoryFactory.build(SessionFactoryFactory.java:39)
    at
   io.dropwizard.hibernate.HibernateBundle.run(HibernateBundle.java:67)
    at
   io.dropwizard.hibernate.HibernateBundle.run(HibernateBundle.java:19)
    at io.dropwizard.setup.Bootstrap.run(Bootstrap.java:200)    at
   io.dropwizard.cli.EnvironmentCommand.run(EnvironmentCommand.java:42)
    at
   io.dropwizard.cli.ConfiguredCommand.run(ConfiguredCommand.java:87)
    at io.dropwizard.cli.Cli.run(Cli.java:78)   at
   io.dropwizard.Application.run(Application.java:93)

Body:
By default, JPA tries to persist all the properties of @Entity class, but you can ignore some properties using @Transient annotation. In your case, if you don't want to persist additionalProperties field in both classes, you should mark their as @Transient:

@JsonIgnore
@Transient
private Map<String, Object> additionalProperties = new HashMap<String, Object>();


问:
Is there a way to put php inside of a IE conditional comments
I have a php section that loads jquery through wordpress from google's api. I dont want to load jquery on IE browsers. Long story short, it doesn't work for whatever reason (you can read through my other posted questions).

Or if this is not possible is there another way to NOT use this code when its an IE browser, maybe a php solution.

```<code><?php
    if( !is_admin()){
        wp_deregister_script('jquery');
        wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js', false, '1.5.2', true);
        wp_enqueue_script('jquery');
    }

?>
</code>```

Targets everything except IE (what i was trying to use, but it didnt work):

```<code><!--[if !IE]><!-->
<!--<![endif]-->
</code>```

答: You have the global $is_IE in Wordpress.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a php section that loads jquery through wordpress from google's api. I dont want to load jquery on IE browsers. Long story short, it doesn't work for whatever reason (you can read through my other posted questions).

Or if this is not possible is there another way to NOT use this code when its an IE browser, maybe a php solution.

<?php
    if( !is_admin()){
        wp_deregister_script('jquery');
        wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js', false, '1.5.2', true);
        wp_enqueue_script('jquery');
    }

?>

Targets everything except IE (what i was trying to use, but it didnt work):


问:
Expand the possibility to put offline a post after an event
I'm trying to expand the function that I've showed in this question using this code:

```<code>@property
def is_expired(self):
    print(self.publishing_date)
    if self.membership == "One Month":
        if self.publishing_date + datetime.timedelta(days=30) < datetime.datetime.now():
            message = 'Scaduto'
            return message
        else:
            expiring_date = self.publishing_date + datetime.timedelta(days=30)
            delta = expiring_date - datetime.datetime.now()
            return delta
    else:
        if self.publishing_date + datetime.timedelta(days=365) < datetime.datetime.now():
            message = 'Scaduto'
            return message
        else:
            expiring_date = self.publishing_date + datetime.timedelta(days=365)
            delta = expiring_date - datetime.datetime.now()
            return delta
    return False
</code>```

I want to use this new template:

```<code>  {% for asset in user_details.authorized_user_set.all %}
    {% if not asset.is_expired %}
    <tr>
      <td class="text-left"><p><strong><a class="text-info" href="{{ asset.get_absolute_url }}">{{ asset.title }}</a></strong></p></td>
      <td class="text-center">
        {% if asset.type == "3D Region" %}
          <p class="badge badge-pill badge-primary">{{ asset.type }}</p>
        {% elif asset.type == "3D Village" %}
          <p class="badge badge-pill badge-secondary">{{ asset.type }}</p>
        {% else %}
          <p class="badge badge-pill badge-success">{{ asset.type }}</p>
        {% endif %}
      </td>
      <td class="text-right"><p>{{ asset.publishing_date }}</p></td>
      <td class="text-center">
        {% if asset.membership == "One Month" %}
          <p class="badge badge-pill badge-warning">{{ asset.membership }}</p>
        {% else %}
          <p class="badge badge-pill badge-danger">{{ asset.membership }}</p>
        {% endif %}
      </td>
      <td class="text-right"><p>{{ asset.delta }}</p></td>
    </tr>
    {% endif %}
  {% endfor %}
</code>```

Inside Django administration panel I can see all that I want corrctly, as you can see on the image below, but the template  give me an empty table. If I erase the else condition that return delta everything works fine, then the problem is here but I don't know why everything works fine inside Django administration panel if I use the full code.

答:
It returns an empty table because your property is_expired always return a non-false value. Your asset.is_expired check should check if asset.is_expired == 'Scaduto'.

However, I recommend you to have this logic inside your model:

@property
def expiration_date(self):
    if self.membership == "One Month":
        return self.publishing_date + datetime.timedelta(days=30)
    else:
        return self.publishing_date + datetime.timedelta(days=365)

@property
def is_expired(self):
    return self.expiration_date < datetime.datetime.now()

@property
def delta(self):
    return self.expiration_date - datetime.datetime.now() if not self.is_expired else 'Scaduto'
```

<p>Then, you can use it as you want in the template. If what you want is to have it as you have in the admin panel:</p>

```  {% for asset in user_details.authorized_user_set.all %}

{{ asset.title }}

        {% if asset.type == "3D Region" %}

{{ asset.type }}

        {% elif asset.type == "3D Village" %}

{{ asset.type }}

        {% else %}

{{ asset.type }}

        {% endif %}

{{ asset.publishing_date }}

        {% if asset.membership == "One Month" %}

{{ asset.membership }}

        {% else %}

{{ asset.membership }}

        {% endif %}

{{ asset.delta }}

  {% endfor %}
```

Body:
I'm trying to expand the function that I've showed in this question using this code:

@property
def is_expired(self):
    print(self.publishing_date)
    if self.membership == "One Month":
        if self.publishing_date + datetime.timedelta(days=30) < datetime.datetime.now():
            message = 'Scaduto'
            return message
        else:
            expiring_date = self.publishing_date + datetime.timedelta(days=30)
            delta = expiring_date - datetime.datetime.now()
            return delta
    else:
        if self.publishing_date + datetime.timedelta(days=365) < datetime.datetime.now():
            message = 'Scaduto'
            return message
        else:
            expiring_date = self.publishing_date + datetime.timedelta(days=365)
            delta = expiring_date - datetime.datetime.now()
            return delta
    return False

I want to use this new template:

  {% for asset in user_details.authorized_user_set.all %}
    {% if not asset.is_expired %}

{{ asset.title }}

        {% if asset.type == "3D Region" %}

{{ asset.type }}

        {% elif asset.type == "3D Village" %}

{{ asset.type }}

        {% else %}

{{ asset.type }}

        {% endif %}

{{ asset.publishing_date }}

        {% if asset.membership == "One Month" %}

{{ asset.membership }}

        {% else %}

{{ asset.membership }}

        {% endif %}

{{ asset.delta }}

    {% endif %}
  {% endfor %}

Inside Django administration panel I can see all that I want corrctly, as you can see on the image below, but the template  give me an empty table. If I erase the else condition that return delta everything works fine, then the problem is here but I don't know why everything works fine inside Django administration panel if I use the full code.

Body:
It returns an empty table because your property is_expired always return a non-false value. Your asset.is_expired check should check if asset.is_expired == 'Scaduto'.

However, I recommend you to have this logic inside your model:

@property
def expiration_date(self):
    if self.membership == "One Month":
        return self.publishing_date + datetime.timedelta(days=30)
    else:
        return self.publishing_date + datetime.timedelta(days=365)

@property
def is_expired(self):
    return self.expiration_date < datetime.datetime.now()

@property
def delta(self):
    return self.expiration_date - datetime.datetime.now() if not self.is_expired else 'Scaduto'

Then, you can use it as you want in the template. If what you want is to have it as you have in the admin panel:

  {% for asset in user_details.authorized_user_set.all %}
    <tr>
      <td class="text-left"><p><strong><a class="text-info" href="{{ asset.get_absolute_url }}">{{ asset.title }}</a></strong></p></td>
      <td class="text-center">
        {% if asset.type == "3D Region" %}
          <p class="badge badge-pill badge-primary">{{ asset.type }}</p>
        {% elif asset.type == "3D Village" %}
          <p class="badge badge-pill badge-secondary">{{ asset.type }}</p>
        {% else %}
          <p class="badge badge-pill badge-success">{{ asset.type }}</p>
        {% endif %}
      </td>
      <td class="text-right"><p>{{ asset.publishing_date }}</p></td>
      <td class="text-center">
        {% if asset.membership == "One Month" %}
          <p class="badge badge-pill badge-warning">{{ asset.membership }}</p>
        {% else %}
          <p class="badge badge-pill badge-danger">{{ asset.membership }}</p>
        {% endif %}
      </td>
      <td class="text-right"><p>{{ asset.delta }}</p></td>
    </tr>
  {% endfor %}


问:
Java Error: cannot resolve method split()
I am trying to get user input into a String array and wanted to use the string.split() method but for some reason, my IntelliJ is telling me, that it cannot resolve the method 'split()'.

package com.Practice;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();

        String[] splittedString = input.split();
    }
}
```

<p>I dont think, that there is a problem with my code, mayby with my IDE or Java version, but im no expert at this stuff.
When I try to run the program it throws me this error:</p>

```Error:(10, 40) java: no suitable method found for split(no arguments)
    method java.lang.String.split(java.lang.String,int) is not applicable
      (actual and formal argument lists differ in length)
    method java.lang.String.split(java.lang.String) is not applicable
      (actual and formal argument lists differ in length)
```

答:
You need to add an argument in split method. check split method here

```<code>public class Main {

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String input = sc.nextLine();

    String[] splittedString = input.split(" ");

}
}
</code>```

Body:
I am trying to get user input into a String array and wanted to use the string.split() method but for some reason, my IntelliJ is telling me, that it cannot resolve the method 'split()'.

package com.Practice;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();

        String[] splittedString = input.split();
    }
}

I dont think, that there is a problem with my code, mayby with my IDE or Java version, but im no expert at this stuff.
When I try to run the program it throws me this error:

Error:(10, 40) java: no suitable method found for split(no arguments)
    method java.lang.String.split(java.lang.String,int) is not applicable
      (actual and formal argument lists differ in length)
    method java.lang.String.split(java.lang.String) is not applicable
      (actual and formal argument lists differ in length)

Body:
You need to add an argument in split method. check split method here

public class Main {

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String input = sc.nextLine();

    String[] splittedString = input.split(" ");

}
}


问:
what is the postgresql query to find the timestamp without time zone

select now();
               now
----------------------------------
 2019-06-01 16:10:19.893354+05:30
```

I want only date and time without timezone.What is the query to get today's date and time.eg: 2019-06-01 16:10:19

答:
You can cast to timestamp in this way of current time :

```<code>select now()::timestamp() without time zone
</code>```

And you can use timestamp(0) if you do now want miliseconds. The number in timestamp('number') is miliseconds after dot of seconds

You need that query :

```<code>select now()::timestamp(0) without time zone
</code>```

Body:
select now();
               now
----------------------------------
 2019-06-01 16:10:19.893354+05:30

I want only date and time without timezone.What is the query to get today's date and time.eg: 2019-06-01 16:10:19

Body:
You can cast to timestamp in this way of current time :

select now()::timestamp() without time zone

And you can use timestamp(0) if you do now want miliseconds. The number in timestamp('number') is miliseconds after dot of seconds

You need that query :

select now()::timestamp(0) without time zone


问:
What is the error in this code?The javascript code is not working
I am trying to change the background color of my div element onclick.But it's not working.

```<code><html>

     <head>
         <title>Event handling5</title>
         <meta charset="UTF-8">
         <style type="text/css">
         .styleClass{
             display: table-cell;
             border: 5px solid black;
             padding: 20px;
             text-align: center;
         }
         </style>
         </head>
         <body>
             <div id="DIV1" class="styleClass">DIV1
            <div id="DIV2" class="styleClass">DIV2
                <div id="DIV3" class="styleClass">DIV3

                </div>
            </div>
            </div>
            <script type="text/javascript">
            var divElements=document.getElementsByTagName('div');
            for(var i=0;i<divElements;i++){
                divElements[i].onclick=function(){
                    this.style.borderColor='red';
                    alert(this.getAttribute("id")+"Border color changed");
                }
            }
            </script>
         </body>
 </html>
</code>```

Only css functions are working and javascript function is not working.

答:
You need to go until the length of the results is reached and move the script tag into head.

```<code><html>

     <head>
         <title>Event handling5</title>
         <meta charset="UTF-8">
         <style type="text/css">
         .styleClass{
             display: table-cell;
             border: 5px solid black;
             padding: 20px;
             text-align: center;
         }
         </style>
            <script type="text/javascript">
            function load() {
                var divElements=document.getElementsByTagName('div');
                for(var i=0;i<divElements.length;i++){
                    divElements[i].onclick=function(){
                        this.style.borderColor='red';
                        alert(this.getAttribute("id")+"Border color changed");
                    }
                }
            }
            </script>
         </head>
         <body onload="load();">
             <div id="DIV1" class="styleClass">DIV1
            <div id="DIV2" class="styleClass">DIV2
                <div id="DIV3" class="styleClass">DIV3

                </div>
            </div>
            </div>
         </body>
 </html>
</code>```

Body:
I am trying to change the background color of my div element onclick.But it's not working.

         <title>Event handling5</title>
         <meta charset="UTF-8">

DIV1

DIV2

DIV3

Only css functions are working and javascript function is not working.

Body:
You need to go until the length of the results is reached and move the script tag into head.

<html>

     <head>
         <title>Event handling5</title>
         <meta charset="UTF-8">
         <style type="text/css">
         .styleClass{
             display: table-cell;
             border: 5px solid black;
             padding: 20px;
             text-align: center;
         }
         </style>
            <script type="text/javascript">
            function load() {
                var divElements=document.getElementsByTagName('div');
                for(var i=0;i<divElements.length;i++){
                    divElements[i].onclick=function(){
                        this.style.borderColor='red';
                        alert(this.getAttribute("id")+"Border color changed");
                    }
                }
            }
            </script>
         </head>
         <body onload="load();">
             <div id="DIV1" class="styleClass">DIV1
            <div id="DIV2" class="styleClass">DIV2
                <div id="DIV3" class="styleClass">DIV3

                </div>
            </div>
            </div>
         </body>
 </html>


问:
What to do when findViewById cannot find a GUI resource while debugging in Eclipse
Spent about an hour on this so I thought I'd save somebody else the trouble. Using Eclipse 3.6.2.

My call to findViewById a GUI widget keep returning null. Check the code and xml over and over and over, no problems. Finally exited and restarted Eclipse and suddenly findViewById worked.

答: The next time you can just delete the R.java file, and let Eclipse regenerate it, then it should work too.</p>


问:
is it possible to train spacy to identify any random organization name
is it possible to identify in spacy as an entity any random organization name in any language

i tried the pretrained model of spacy to identify the organization names but  but it fails on some places eg Rama works at Remote software

答:
Yes, you can update an existing statistical model with more data, or train a new model from scratch. You can find more details and documentation here:

Training basics: https://spacy.io/usage/training#basics

Training the named entity recognizer: https://spacy.io/usage/training#ner

Training code examples: https://github.com/explosion/spaCy/tree/master/examples/training

spacy train command: https://spacy.io/api/cli#train


问:
Need help understanding this lisp function
I am having trouble understanding the return line in this function.

I'm creating a parser in C# and found this tutorial (http://lisperator.net/pltut/parser/the-parser) which was written in Javascript. I can't understand the return line of the function

```<code>function is_punc(ch) {
    var tok = input.peek();
    return tok && tok.type == "punc" && (!ch || tok.value == ch) && tok;
}
</code>```

I believe it will return true if: tok is not null AND its type is punc AND (the char ch is not null OR the value of tok equals ch) AND tok is not null.

If I am reading this right why is he evaluating tok is not null twice.

答:
It's not meaningful in this context, but the logical operators in JavaScript work like those in Python and Lisp (the only connection to Lisp in this question).

That is, a && b returns a if it is "false-y", otherwise it returns b.

Similarly, a || b returns a if it is "truth-y", otherwise it returns b.

Examples (from my Firefox console):

```<code>> "" && 23
< ""
> 0 && 23
< 0
> 1 && 23
< 23
> 1 && "hello"
< "hello"
> "hello" || "world"
< "hello"
> 0 || "world"
< "world"
</code>```

This means that the final tok makes the function return the token itself if all the other conditions are truth-y.

Body:
I am having trouble understanding the return line in this function.

I'm creating a parser in C# and found this tutorial (http://lisperator.net/pltut/parser/the-parser) which was written in Javascript. I can't understand the return line of the function

function is_punc(ch) {
    var tok = input.peek();
    return tok && tok.type == "punc" && (!ch || tok.value == ch) && tok;
}

I believe it will return true if: tok is not null AND its type is punc AND (the char ch is not null OR the value of tok equals ch) AND tok is not null.

If I am reading this right why is he evaluating tok is not null twice.

Body:
It's not meaningful in this context, but the logical operators in JavaScript work like those in Python and Lisp (the only connection to Lisp in this question).

That is, a && b returns a if it is "false-y", otherwise it returns b.

Similarly, a || b returns a if it is "truth-y", otherwise it returns b.

Examples (from my Firefox console):

> "" && 23
< ""
> 0 && 23
< 0
> 1 && 23
< 23
> 1 && "hello"
< "hello"
> "hello" || "world"
< "hello"
> 0 || "world"
< "world"

This means that the final tok makes the function return the token itself if all the other conditions are truth-y.


问:
How to createElement on a different page?
How to createElement on a different page?

I am very new to JavaScript / jQuery. I am trying to find a way to create an element on different page (please check the chart).

The functioning I am looking for:

Click the "ADD SECTION" button located on Page_1.html

The visitor will be redirected to a new page (Page_2.html) where the new div will be created

enter image description here

function add_section_1() {
    var section_1 = document.createElement('div');
        section_1.className = 'new_section';
        section_1.id = 'section_1';
        document.getElementById('wrapper').appendChild(section_1);
}```

答:
Your code on Page_1 stops running when that page is unloaded to make room for Page_2. There is nothing Page_1 can do directly to change Page_2 when it's loaded.

What Page_1 can do is tell Page_2 that it should create the div. It can do that in various ways:

Setting a value in sessionStorage that Page_2 looks for (and then removes).

Adding a query parameter to the query string when redirecting to Page_2 (e.g., Page_2.html?creatediv=blah) that Page_2 looks for on location.search (see location, search).

There are probably others, but the fundamental point is: Page_1's code can't do it, but it can pass along informaton to Page_2 telling it to do it.


答:
You can express boolean logic with more than true/false, and some languages exploit this to return more information from boolean operators. For example, in a JS console, you can write the following:

```<code>> x = 10
10
> (x < 100) && x
10
</code>```

An integer like 10 belongs to the set of True values when used in a boolean context. The result is thus 10.
The same happens in Lisp, where (or (try-first-this) (maybe-that)) evaluates to the first expression that holds true.

In your case the last term is necessary for the function to return the token.

Title: Need help understanding this lisp function

Body:
You can express boolean logic with more than true/false, and some languages exploit this to return more information from boolean operators. For example, in a JS console, you can write the following:

> x = 10
10
> (x < 100) && x
10

An integer like 10 belongs to the set of True values when used in a boolean context. The result is thus 10.
The same happens in Lisp, where (or (try-first-this) (maybe-that)) evaluates to the first expression that holds true.

In your case the last term is necessary for the function to return the token.


问:
Mailslots in Python
Hello is there any good tutorial / doc. for using the Win MailSlots in Python ?</p>

Title: Mailslots in Python


问:
How to add missing dates and populate values inside groups with 'data.table'
Let see the following example in dplyr style.

```<code># 1. Data set
df <- data.table(
  g1 = c(1, 1, 2, 1, 2, 2, 1),
  g2 = c(2, 1, 3, 3, 1, 1, 2),
  status = c(1, 0, 1, 0, 0, 1, 1),
  date_obs = as.Date(c("2019-01-01", "2019-01-02", "2019-01-12", "2019-01-15",
           "2019-01-20", "2019-01-24", "2019-01-30")))

# 2. Arrange data
df <- df %>%
  arrange(g1, g2, date_obs)

# 3. Populate missing 'date_obs' and 'status' values
df_filled <- df %>%
  group_by(g1, g2) %>%
  complete(date_obs = seq.Date(min(date_obs), max(date_obs), by = "day")) %>%
  fill(status) %>%
  arrange(g1, g2, date_obs) %>%
  ungroup()
</code>```

How can I make the same operations by using data.table R syntax?

Thanks!

答:
The method is to generate a "complete" data.table with all of the date ranges by variables g1 and g2. Then we do a left join to the original data.table and then fill in the NA status.

This still relies on another package to do the fill method. I couldn't get tidyr::fill to work but zoo::na.locf worked like a charm. There are a lot of other options for filling NA values.

Replace NA with last non-NA in data.table by using only data.table

R data.table join/ subsetting/ match by group and by a condition

Replacing NAs with latest non-NA value

```<code>setorder(dt, g1, g2, date_obs)

dt_complete <- dt[, .(date_obs = seq.Date(min(date_obs), max(date_obs), by = "day")), by = .(g1, g2)]

dt[dt_complete
    , on = c('date_obs', 'g1', 'g2')
    , .(g1, g2, date_obs, status = zoo::na.locf(status))
    ]

    g1 g2   date_obs status
 1:  1  1 2019-01-02      0
 2:  1  2 2019-01-01      1
 3:  1  2 2019-01-02      1
 4:  1  2 2019-01-03      1
 5:  1  2 2019-01-04      1
 6:  1  2 2019-01-05      1
 7:  1  2 2019-01-06      1
 8:  1  2 2019-01-07      1
 9:  1  2 2019-01-08      1
... 38 total rows...
</code>```

Data which is simply OP:

```<code>library(data.table)
library(tidyverse)
# 1. Data set
dt <- data.table(
  g1 = c(1, 1, 2, 1, 2, 2, 1),
  g2 = c(2, 1, 3, 3, 1, 1, 2),
  status = c(1, 0, 1, 0, 0, 1, 1),
  date_obs = as.Date(c("2019-01-01", "2019-01-02", "2019-01-12", "2019-01-15",
                       "2019-01-20", "2019-01-24", "2019-01-30")))
</code>```

Body:
Let see the following example in dplyr style.

# 1. Data set
df <- data.table(
  g1 = c(1, 1, 2, 1, 2, 2, 1),
  g2 = c(2, 1, 3, 3, 1, 1, 2),
  status = c(1, 0, 1, 0, 0, 1, 1),
  date_obs = as.Date(c("2019-01-01", "2019-01-02", "2019-01-12", "2019-01-15",
           "2019-01-20", "2019-01-24", "2019-01-30")))

# 2. Arrange data
df <- df %>%
  arrange(g1, g2, date_obs)

# 3. Populate missing 'date_obs' and 'status' values
df_filled <- df %>%
  group_by(g1, g2) %>%
  complete(date_obs = seq.Date(min(date_obs), max(date_obs), by = "day")) %>%
  fill(status) %>%
  arrange(g1, g2, date_obs) %>%
  ungroup()

How can I make the same operations by using data.table R syntax?

Thanks!

Body:
The method is to generate a "complete" data.table with all of the date ranges by variables g1 and g2. Then we do a left join to the original data.table and then fill in the NA status.

This still relies on another package to do the fill method. I couldn't get tidyr::fill to work but zoo::na.locf worked like a charm. There are a lot of other options for filling NA values.

Replace NA with last non-NA in data.table by using only data.table

R data.table join/ subsetting/ match by group and by a condition

Replacing NAs with latest non-NA value

setorder(dt, g1, g2, date_obs)

dt_complete <- dt[, .(date_obs = seq.Date(min(date_obs), max(date_obs), by = "day")), by = .(g1, g2)]

dt[dt_complete
    , on = c('date_obs', 'g1', 'g2')
    , .(g1, g2, date_obs, status = zoo::na.locf(status))
    ]

    g1 g2   date_obs status
 1:  1  1 2019-01-02      0
 2:  1  2 2019-01-01      1
 3:  1  2 2019-01-02      1
 4:  1  2 2019-01-03      1
 5:  1  2 2019-01-04      1
 6:  1  2 2019-01-05      1
 7:  1  2 2019-01-06      1
 8:  1  2 2019-01-07      1
 9:  1  2 2019-01-08      1
... 38 total rows...

Data which is simply OP:

library(data.table)
library(tidyverse)
# 1. Data set
dt <- data.table(
  g1 = c(1, 1, 2, 1, 2, 2, 1),
  g2 = c(2, 1, 3, 3, 1, 1, 2),
  status = c(1, 0, 1, 0, 0, 1, 1),
  date_obs = as.Date(c("2019-01-01", "2019-01-02", "2019-01-12", "2019-01-15",
                       "2019-01-20", "2019-01-24", "2019-01-30")))


问:
How to resolve LazyInitializationException in Spring data rest @RepositoryEventHandler @HandleAfterLinkSave?
I have a spring data rest application with relation between types Match and Round

```<code>@Entity
public class Match {

    @OneToMany
    private List<Round> rounds;
    ...
}
</code>```

When a link is created between a match and a round, e.g. like this

```<code>curl -X PUT -d "http://localhost:8080/rounds/2" -H "Content-Type:text/uri-list" http://localhost:8080/matches/1/rounds;
</code>```

i capture this with an EventHandler to do some updates on my domain model:

```<code>public class MatchEventHandler

    @HandleAfterLinkSave
    public void handleLinkSave(Match match, List<Round> rounds) {
        ...
}
</code>```

I need to access the second argument in order to do my update but doing so, e.g. with rounds.get(0), returns

org.hibernate.LazyInitializationException: failed to lazily initialize a collection, could not initialize proxy - no Session

Reading other threads about Hibernates LazyInitializationExceptions i see mainly three approaches that are suggested:

Use Hibernate.initialize() - i don't see on which method i could call this and it would add an ugly dependency to Hibernate framework

Put controller method into a transaction - i understand that spring data already puts everything into a transaction. Also as this is a spring data rest application i'm not using any controller or service layer and therfore i would not know what exactly to put into a transaction.

Set FetchType.EAGER on the relation - although not really a valid solution i did try it. In that case the second argument of the @HandleAfterLinkSave method is an empty list, so it also does not deliver the expected result.

答:
The property references are handled in the following Spring class:

org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController

Although it works quite well most of the time, it's buggy here or there. Or let's say this way: It has some interesting behaviours... (I've spent months during the last two years for creating an improved version of Spring Data Rest).

If the request method was POST or PATCH then the 2nd parameter contains the updated collection. But if you use a PUT method, it contains the original collection.

(Also, there is no way to decide which collection was modified, if you have multiple property-collections in your main entity. And there are those questionable results for map-type properties, but that's an other story.)

So the best solution IMHO if you create a repository method in RoundRepository, and use it to reload the collection:

```<code>@RestResource(exported = false)
List<Round> findAllByMatch(Match match);
</code>```

By the way!
In regards of your Option 2, please read this topic!

Body:
I have a spring data rest application with relation between types Match and Round

@Entity
public class Match {

    @OneToMany
    private List<Round> rounds;
    ...
}

When a link is created between a match and a round, e.g. like this

curl -X PUT -d "http://localhost:8080/rounds/2" -H "Content-Type:text/uri-list" http://localhost:8080/matches/1/rounds;

i capture this with an EventHandler to do some updates on my domain model:

public class MatchEventHandler

    @HandleAfterLinkSave
    public void handleLinkSave(Match match, List<Round> rounds) {
        ...
}

I need to access the second argument in order to do my update but doing so, e.g. with rounds.get(0), returns

org.hibernate.LazyInitializationException: failed to lazily initialize a collection, could not initialize proxy - no Session

Reading other threads about Hibernates LazyInitializationExceptions i see mainly three approaches that are suggested:

Use Hibernate.initialize() - i don't see on which method i could call this and it would add an ugly dependency to Hibernate framework

Put controller method into a transaction - i understand that spring data already puts everything into a transaction. Also as this is a spring data rest application i'm not using any controller or service layer and therfore i would not know what exactly to put into a transaction.

Set FetchType.EAGER on the relation - although not really a valid solution i did try it. In that case the second argument of the @HandleAfterLinkSave method is an empty list, so it also does not deliver the expected result.

Body:
The property references are handled in the following Spring class:

org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController

Although it works quite well most of the time, it's buggy here or there. Or let's say this way: It has some interesting behaviours... (I've spent months during the last two years for creating an improved version of Spring Data Rest).

If the request method was POST or PATCH then the 2nd parameter contains the updated collection. But if you use a PUT method, it contains the original collection.

(Also, there is no way to decide which collection was modified, if you have multiple property-collections in your main entity. And there are those questionable results for map-type properties, but that's an other story.)

So the best solution IMHO if you create a repository method in RoundRepository, and use it to reload the collection:

@RestResource(exported = false)
List<Round> findAllByMatch(Match match);

By the way!
In regards of your Option 2, please read this topic!


问:
How to use onActivityResult twice in one Activity
error:method onActivityResult(int,int, Intent) is already defined in class scan.

So I'm trying to build an app where u snap a photo and than the app detects text on the photo. Sadly I use the method onActivityResult twice.
Since I'm new to coding and in general a bit stupid, I don't know how to solve this.

adding the number 1 behind the ints where I first used them, but well that didn't do it

```<code>private void camera(){
    Intent intent2 = new Intent (MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent2, 0);
}
@Override
protected void onActivityResult (int requestCode1, int resultCode1 , Intent data1) {
    super.onActivityResult(requestCode1,resultCode1,data1);
    if (resultCode1==RESULT_OK){
        Bitmap btp = (Bitmap) data1.getExtras().get("data");
        imageView.setImageBitmap(btp);
    }
}

public void detect (View v){
    if (bitmap == null){
        Toast.makeText(getApplicationContext(),"Bitmap is null",Toast.LENGTH_SHORT).show();
    }
    else {
        FirebaseVisionImage firebaseVisionImage = FirebaseVisionImage.fromBitmap(bitmap);
        FirebaseVisionTextRecognizer firebaseVisionTextRecognizer = FirebaseVision.getInstance().getOnDeviceTextRecognizer();
        firebaseVisionTextRecognizer.processImage(firebaseVisionImage)
                .addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
                    @Override
                    public void onSuccess(FirebaseVisionText firebaseVisionText) {
                        process_text(firebaseVisionText);
                    }
                });

    }

}

private void process_text(FirebaseVisionText firebaseVisionText) {
    List<FirebaseVisionText.TextBlock> blocks = firebaseVisionText.getTextBlocks();
    if (blocks.size() == 0){
        Toast.makeText(getApplicationContext(),"no text detected",Toast.LENGTH_LONG).show();
    }
    else {
        for (FirebaseVisionText.TextBlock block:firebaseVisionText.getTextBlocks()){
            String text = block.getText();
            textView.setText(text);
        }
    }
}

public void pick_image(View v){
    Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
    startActivityForResult(i,1);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == 1 && resultCode == RESULT_OK)
    {
        Uri uri = data.getData();
        try {
            bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),uri);
            imageView.setImageBitmap(bitmap);
        }catch (IOException e){
            e.printStackTrace();
        }

    }
}
</code>```

error: method onActivityResult(int,int,Intent) is already defined in class scan

答:
You just have to put it in one onActivityResult.

```<code>    @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == 1 && resultCode == RESULT_OK)
    {
        Uri uri = data.getData();
        try {
            bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),uri);
            imageView.setImageBitmap(bitmap);
        }catch (IOException e){
            e.printStackTrace();
        }

    }
if (resultCode==RESULT_OK){
        Bitmap btp = (Bitmap) data.getExtras().get("data");
        imageView.setImageBitmap(btp);
    }
}
</code>```

Body:
error:method onActivityResult(int,int, Intent) is already defined in class scan.

So I'm trying to build an app where u snap a photo and than the app detects text on the photo. Sadly I use the method onActivityResult twice.
Since I'm new to coding and in general a bit stupid, I don't know how to solve this.

adding the number 1 behind the ints where I first used them, but well that didn't do it

private void camera(){
    Intent intent2 = new Intent (MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent2, 0);
}
@Override
protected void onActivityResult (int requestCode1, int resultCode1 , Intent data1) {
    super.onActivityResult(requestCode1,resultCode1,data1);
    if (resultCode1==RESULT_OK){
        Bitmap btp = (Bitmap) data1.getExtras().get("data");
        imageView.setImageBitmap(btp);
    }
}

public void detect (View v){
    if (bitmap == null){
        Toast.makeText(getApplicationContext(),"Bitmap is null",Toast.LENGTH_SHORT).show();
    }
    else {
        FirebaseVisionImage firebaseVisionImage = FirebaseVisionImage.fromBitmap(bitmap);
        FirebaseVisionTextRecognizer firebaseVisionTextRecognizer = FirebaseVision.getInstance().getOnDeviceTextRecognizer();
        firebaseVisionTextRecognizer.processImage(firebaseVisionImage)
                .addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
                    @Override
                    public void onSuccess(FirebaseVisionText firebaseVisionText) {
                        process_text(firebaseVisionText);
                    }
                });

    }

}

private void process_text(FirebaseVisionText firebaseVisionText) {
    List<FirebaseVisionText.TextBlock> blocks = firebaseVisionText.getTextBlocks();
    if (blocks.size() == 0){
        Toast.makeText(getApplicationContext(),"no text detected",Toast.LENGTH_LONG).show();
    }
    else {
        for (FirebaseVisionText.TextBlock block:firebaseVisionText.getTextBlocks()){
            String text = block.getText();
            textView.setText(text);
        }
    }
}

public void pick_image(View v){
    Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
    startActivityForResult(i,1);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == 1 && resultCode == RESULT_OK)
    {
        Uri uri = data.getData();
        try {
            bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),uri);
            imageView.setImageBitmap(bitmap);
        }catch (IOException e){
            e.printStackTrace();
        }

    }
}

error: method onActivityResult(int,int,Intent) is already defined in class scan

Body:
You just have to put it in one onActivityResult.

    @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == 1 && resultCode == RESULT_OK)
    {
        Uri uri = data.getData();
        try {
            bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),uri);
            imageView.setImageBitmap(bitmap);
        }catch (IOException e){
            e.printStackTrace();
        }

    }
if (resultCode==RESULT_OK){
        Bitmap btp = (Bitmap) data.getExtras().get("data");
        imageView.setImageBitmap(btp);
    }
}


问:
Has anyone experience with new deploys on Heroku crashing, after building a new local directory to house the app locally?
I recently have cloned my github repo of a working (first release) web app to a new directory and a new user on my computer. The web app is hosted at Heroku.

I have made some changes, push them to origin, and then pushed them to Heroku and the web app crashes. The changes are exceedingly minor and will not affect anything backend or complicated.

Heroku says the build was successful, there there did exist a perculiar warning:

```<code>###### WARNING:
       Detecting rails configuration failed
       set HEROKU_DEBUG_RAILS_RUNNER=1 to debug
###### WARNING:
       We detected that some binary dependencies required to
       use all the preview features of Active Storage are not
       present on this system.

       For more information please see:
         https://devcenter.heroku.com/articles/active-storage-on-heroku
</code>```

No idea on what and where they mean by set HEROKU_DEBUG_RAILS_RUNNER=1 to debug

The error logs I get during the crash are:

```<code>...
2019-06-01T07:14:31.564617+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/training_sessions/345" host=www.trainingrepo.com request_id=ed87114f-a296-4a84-adba-57f7249d3ea9 fwd="81.226.11.112" dyno= connect= service= status=503 bytes= protocol=http
2019-06-01T07:14:32.159379+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=www.trainingrepo.com request_id=990ffa88-1d6b-4e38-af9b-521b2dff6fa8 fwd="81.226.11.112" dyno= connect= service= status=503 bytes= protocol=http
2019-06-01T07:14:41.170353+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=www.trainingrepo.com request_id=14e1d219-30e5-4b87-96cf-3ea9378c13e1 fwd="81.226.11.112" dyno= connect= service= status=503 bytes= protocol=http
2019-06-01T07:14:41.642669+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=www.trainingrepo.com request_id=54ad17ed-5e6c-44ff-818a-f7e4fcd6720a fwd="81.226.11.112" dyno= connect= service= status=503 bytes= protocol=http
2019-06-01T07:14:44.421786+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/training_sessions/345" host=www.trainingrepo.com request_id=418bea73-f5b8-44bf-8233-6751b481d671 fwd="81.226.11.112" dyno= connect= service= status=503 bytes= protocol=http
2019-06-01T07:14:44.724359+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=www.trainingrepo.com request_id=a6226248-404a-4a25-8144-7bf923c362d1 fwd="81.226.11.112" dyno= connect= service= status=503 bytes= protocol=http
2019-06-01T07:16:15.084500+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=training-repo.herokuapp.com request_id=aeb650e9-57bb-4d60-b095-cc426a2f7a48 fwd="81.226.11.112" dyno= connect= service= status=503 bytes= protocol=https
2019-06-01T07:16:15.468246+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=training-repo.herokuapp.com request_id=17442b02-84a1-4e2d-a3d2-04f26e2bd8ef fwd="81.226.11.112" dyno= connect= service= status=503 bytes= protocol=https
</code>```

You'll notice that the dyno= connect= service= are all empty. When I rant the production check, it was a blood bath:

```<code>PASSED Heroku-18 Stack
FAILED Hobby Dynos
You're running on Hobby dynos. Upgrading to Standard tier dynos will provide a higher level of performance and access to important features such as metrics and faster builds. Upgrading to Performance will provide single tenant isolation for highest performance. Visit your app's resources tab to upgrade.
FAILED Dyno Redundancy
You're only running on 1 web dyno. A second dyno will provide instant fallback if one dyno fails for any reason. Scale your dynos to 2 or more on the Resources tab.
FAILED Production Postgres Database
Using a Hobby Tier Postgres database. Upgrade to a Standard or Premium Tier database for production-grade availability.
WARNING Postgres High Availability
Using a Hobby Tier Postgres database. Upgrade to a Premium Tier database for High Availability.
FAILED App monitoring
Not using an app monitoring add-on. Install a monitoring add-on such as New Relic or Librato to monitor your app's performance.
FAILED Log monitoring
No logging add-on found. Install a logging add-on such as Papertrail,or Logentriesto monitor and search your logs.
WARNING Custom Maintenance Pages
Configure customized error and maintenance pages to match your app's branding.
PASSED Heroku SSL
</code>```

Also of note: I cannot connect to my DB locally - I am guessing it has something to do with me trying to access it from a new user account on my computer - but I am an imbecile

答:
Very hard to say what's going on without looking at your code, but this line is very telling: Detecting rails configuration failed. For a normal Rails app that should never happen. The other stuff in semi-optional configuration.

You could try checking if you've pushed the wrong folder level - either one step too high or low. Make sure you push the RAILS_ROOT folder - the one with the Gemfile in it. If you open your project on Github you should see the Gemfile listed directly in the first screen.

Body:
I recently have cloned my github repo of a working (first release) web app to a new directory and a new user on my computer. The web app is hosted at Heroku.

I have made some changes, push them to origin, and then pushed them to Heroku and the web app crashes. The changes are exceedingly minor and will not affect anything backend or complicated.

Heroku says the build was successful, there there did exist a perculiar warning:

###### WARNING:
       Detecting rails configuration failed
       set HEROKU_DEBUG_RAILS_RUNNER=1 to debug
###### WARNING:
       We detected that some binary dependencies required to
       use all the preview features of Active Storage are not
       present on this system.

       For more information please see:
         https://devcenter.heroku.com/articles/active-storage-on-heroku

No idea on what and where they mean by set HEROKU_DEBUG_RAILS_RUNNER=1 to debug

The error logs I get during the crash are:

...
2019-06-01T07:14:31.564617+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/training_sessions/345" host=www.trainingrepo.com request_id=ed87114f-a296-4a84-adba-57f7249d3ea9 fwd="81.226.11.112" dyno= connect= service= status=503 bytes= protocol=http
2019-06-01T07:14:32.159379+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=www.trainingrepo.com request_id=990ffa88-1d6b-4e38-af9b-521b2dff6fa8 fwd="81.226.11.112" dyno= connect= service= status=503 bytes= protocol=http
2019-06-01T07:14:41.170353+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=www.trainingrepo.com request_id=14e1d219-30e5-4b87-96cf-3ea9378c13e1 fwd="81.226.11.112" dyno= connect= service= status=503 bytes= protocol=http
2019-06-01T07:14:41.642669+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=www.trainingrepo.com request_id=54ad17ed-5e6c-44ff-818a-f7e4fcd6720a fwd="81.226.11.112" dyno= connect= service= status=503 bytes= protocol=http
2019-06-01T07:14:44.421786+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/training_sessions/345" host=www.trainingrepo.com request_id=418bea73-f5b8-44bf-8233-6751b481d671 fwd="81.226.11.112" dyno= connect= service= status=503 bytes= protocol=http
2019-06-01T07:14:44.724359+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=www.trainingrepo.com request_id=a6226248-404a-4a25-8144-7bf923c362d1 fwd="81.226.11.112" dyno= connect= service= status=503 bytes= protocol=http
2019-06-01T07:16:15.084500+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=training-repo.herokuapp.com request_id=aeb650e9-57bb-4d60-b095-cc426a2f7a48 fwd="81.226.11.112" dyno= connect= service= status=503 bytes= protocol=https
2019-06-01T07:16:15.468246+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=training-repo.herokuapp.com request_id=17442b02-84a1-4e2d-a3d2-04f26e2bd8ef fwd="81.226.11.112" dyno= connect= service= status=503 bytes= protocol=https

You'll notice that the dyno= connect= service= are all empty. When I rant the production check, it was a blood bath:

PASSED Heroku-18 Stack
FAILED Hobby Dynos
You're running on Hobby dynos. Upgrading to Standard tier dynos will provide a higher level of performance and access to important features such as metrics and faster builds. Upgrading to Performance will provide single tenant isolation for highest performance. Visit your app's resources tab to upgrade.
FAILED Dyno Redundancy
You're only running on 1 web dyno. A second dyno will provide instant fallback if one dyno fails for any reason. Scale your dynos to 2 or more on the Resources tab.
FAILED Production Postgres Database
Using a Hobby Tier Postgres database. Upgrade to a Standard or Premium Tier database for production-grade availability.
WARNING Postgres High Availability
Using a Hobby Tier Postgres database. Upgrade to a Premium Tier database for High Availability.
FAILED App monitoring
Not using an app monitoring add-on. Install a monitoring add-on such as New Relic or Librato to monitor your app's performance.
FAILED Log monitoring
No logging add-on found. Install a logging add-on such as Papertrail,or Logentriesto monitor and search your logs.
WARNING Custom Maintenance Pages
Configure customized error and maintenance pages to match your app's branding.
PASSED Heroku SSL

Also of note: I cannot connect to my DB locally - I am guessing it has something to do with me trying to access it from a new user account on my computer - but I am an imbecile


问:
Need working C# code to find neighbors of an element in a 2-dimentional array
say array with 12 rows and 10 columns

```<code>int[,] array = new int[12,10];
</code>```

and I select 0,0 it must return all neighbors of 0,0
which will be

```<code>0,1
1,1
1,0
</code>```

say I want neighbors of 2,3 it must return an array of neighbors

```<code>1,2
1,3
1,4
2,2
2,4
3,1
3,2
3,3
</code>```

答:
```<code>element [x, y]

neighbor1 = x + 1, y;
neighbor2 = x - 1, y;
neighbor3 = x, y + 1;
neighbor4 = x, y - 1;
neighbor5 = x + 1, y + 1;
neighbor6 = x + 1, y - 1;
neighbor7 = x - 1, y + 1;
neighbor8 = x - 1, y - 1;
</code>```

Obviously you need to check if those elements coordinates exists just in case the element is in a "border" of the matrix. Hard? I say no.

Body:
say array with 12 rows and 10 columns

int[,] array = new int[12,10];

and I select 0,0 it must return all neighbors of 0,0
which will be

0,1
1,1
1,0

say I want neighbors of 2,3 it must return an array of neighbors

1,2
1,3
1,4
2,2
2,4
3,1
3,2
3,3

Body:
element [x, y]

neighbor1 = x + 1, y;
neighbor2 = x - 1, y;
neighbor3 = x, y + 1;
neighbor4 = x, y - 1;
neighbor5 = x + 1, y + 1;
neighbor6 = x + 1, y - 1;
neighbor7 = x - 1, y + 1;
neighbor8 = x - 1, y - 1;

Obviously you need to check if those elements coordinates exists just in case the element is in a "border" of the matrix. Hard? I say no.


问:
Android device monitor emulator 5554 - offline
Good afternoon! Not so long ago I began to develop an application for android. The application creates a database and write data through want Android Device Monitor pull database and view, but when you start, emulator-5554 switches to offline mode. I tried to solve the problem using the adb kill-server and adb start-server, to no avail. Prompt how to solve the problem? Used to develop Android Studio 2.3.</p>

答:
I had the same problem, the easiest working way is
First, Open Android Studio
Go to Tools -> Android -> AVD Manager - Find the emulator which has problem -> Right click on it and click COLD BOOT NOW .

This will restart the android system, it's just like you hold the power button of your Smartphone and choose Restart.


问:
How to remove _id when I print fields using printjson()?
```<code>db.events.find().forEach(function(doc)
{
    var iso_date = new Date(doc.starts_at);
    if(iso_date>= new Date() && iso_date<= new Date(new Date().setDate(new
     Date().getDate()+4))){
        printjson(doc);
    }
})
</code>```

I am unable to remove _id field using printjson() in MongoDB. I am printing fields based on a particular condition which I have handled using JavaScript. While printing using printjson(), I can't remove _id field. Is there a way to remove _id while printing using printjson()?

答:
As JME pointed out in the comment to your question, you can delete the _id field before printing the document. On the other hand, the comparison of dates could be something simpler and, more importantly, you should do it in the query to treat only the documents you want instead of looping through all the documents in the database, so I think your code could look like this:</p>

```<code>db.events.find({starts_at: {$gte: Date.now(), $lte: new Date().setDate(4)}}).forEach(function(doc)
{
    delete doc._id;
    printjson(doc);
});
</code>```

Body:
db.events.find().forEach(function(doc)
{
    var iso_date = new Date(doc.starts_at);
    if(iso_date>= new Date() && iso_date<= new Date(new Date().setDate(new
     Date().getDate()+4))){
        printjson(doc);
    }
})

I am unable to remove _id field using printjson() in MongoDB. I am printing fields based on a particular condition which I have handled using JavaScript. While printing using printjson(), I can't remove _id field. Is there a way to remove _id while printing using printjson()?

Body:
As JME pointed out in the comment to your question, you can delete the _id field before printing the document. On the other hand, the comparison of dates could be something simpler and, more importantly, you should do it in the query to treat only the documents you want instead of looping through all the documents in the database, so I think your code could look like this:

db.events.find({starts_at: {$gte: Date.now(), $lte: new Date().setDate(4)}}).forEach(function(doc)
{
    delete doc._id;
    printjson(doc);
});


问:
In SQL, why do we need a primary key if we can use NOT NULL and UNIQUE constraints in place of a primary key?
A primary key in SQL is a combination of both NOT NULL and UNIQUE constraints, with the only difference that only one primary key constraint can exist within a table.

Why can't we only manage with the NOT NULL and UNIQUE constraints? Even they both do the same thing.

答:
The definition of a primary key is:

A primary key is unique.

A primary key is not null.

Table has only one primary key.

You are asking about the third condition.  Well, that is the definition.  The "primary key" is a single set of keys that have been explicitly chosen to uniquely identify each row in the table.  The word "primary" implies that there is only one per table.  Other keys or combinations of keys that meet the first two conditions are called candidate primary keys.

Although not strictly enforced, primary keys are the best method for referencing individual rows.  They should be used for foreign key constraints, for instance (and any database that I come into contact with does enforce primary keys for foreign key constraints).  Having multiple different keys refer to a single table confuses the data model.  Think about Entity-Relationship modeling.  The links should be primary keys.

To give a flavor of the use of primary keys, some databases (such as MySQL using the InnoDB storage engine) by default cluster tables based on the primary key.  A table can only be clustered once, hence the use of a single key.


问:
Reshaping database using reshape package-part 2
Following the interaction in the previous post Reshaping database using reshape package I create this one to ask other question.
Briefly: I have a database with some rows that it replicate for Id column, I would like to transpose it. The following cose show a little example of my database.

```<code>test<-data.frame(Id=c(1,1,2,3),
                 St=c(20,80,80,20),
                 gap=seq(0.02,0.08,by=0.02),
                 gip=c(0.23,0.60,0.86,2.09),
                 gat=c(0.0107,0.989,0.337,0.663))
</code>```

I would like a final database like this figure that I attached:

With one row for each Id value and the different columns attached.

Can you give me any suggestions?

答:
A dplyr/tidyr alternative is to first gather to long format, group_by Id and key and create a sequential row identifier for each group (new_key) and finally spread it back to wide form.

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

test %>%
  gather(key, value, -Id) %>%
  group_by(Id, key) %>%
  mutate(new_key = paste0(key, row_number())) %>%
  ungroup() %>%
  select(-key) %>%
  spread(new_key, value, fill = 0)

#     Id  gap1  gap2   gat1  gat2  gip1  gip2   St1   St2
#  <dbl> <dbl> <dbl>  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1     1  0.02  0.04 0.0107 0.989  0.23   0.6    20    80
#2     2  0.06  0    0.337  0      0.86   0      80     0
#3     3  0.08  0    0.663  0      2.09   0      20     0
</code>```

Body:
Following the interaction in the previous post Reshaping database using reshape package I create this one to ask other question.
Briefly: I have a database with some rows that it replicate for Id column, I would like to transpose it. The following cose show a little example of my database.

test<-data.frame(Id=c(1,1,2,3),
                 St=c(20,80,80,20),
                 gap=seq(0.02,0.08,by=0.02),
                 gip=c(0.23,0.60,0.86,2.09),
                 gat=c(0.0107,0.989,0.337,0.663))

I would like a final database like this figure that I attached:

With one row for each Id value and the different columns attached.

Can you give me any suggestions?

Body:
A dplyr/tidyr alternative is to first gather to long format, group_by Id and key and create a sequential row identifier for each group (new_key) and finally spread it back to wide form.

library(dplyr)
library(tidyr)

test %>%
  gather(key, value, -Id) %>%
  group_by(Id, key) %>%
  mutate(new_key = paste0(key, row_number())) %>%
  ungroup() %>%
  select(-key) %>%
  spread(new_key, value, fill = 0)

#     Id  gap1  gap2   gat1  gat2  gip1  gip2   St1   St2
#  <dbl> <dbl> <dbl>  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1     1  0.02  0.04 0.0107 0.989  0.23   0.6    20    80
#2     2  0.06  0    0.337  0      0.86   0      80     0
#3     3  0.08  0    0.663  0      2.09   0      20     0


问:
Why I keep getting an error of MAX_ELEMENTS_EXCEEDED when I don't overpass the daily free number of requests?
So I developed a code where I read a file with some locations (15 to be more precise), where the first one is the depot and the other 14 locations are the places where a bus needs to pass to collect patients. In order to do that, I use Google Maps API key in order to collect the real distances and write them in a .txt file in the end.

```<code>import pandas as pd
import googlemaps
from itertools import tee
import numpy as np

#Read CSV file into data frame named 'df'
#change seperator (sep e.g. ',') type if necessary
df = pd.read_csv("D:/Utilizadores/Documents/FEUP/2018-2019/1º Semestre/PDI/Relatório/locais2.txt", sep='\\t',
                       engine='python', skiprows=[0], names=["address", "latitude", "longitude"])

lat = np.expand_dims(np.array(df["latitude"]), 1)
lon = np.expand_dims(np.array(df["longitude"]), 1)
coordinates = np.concatenate((lat, lon), axis=1)

coordinates = list(coordinates)
coordinates = [list(coor) for coor in coordinates]

#Perform request to use the Google Maps API web service
#API_key = 'AIzaSyCi8DDz_CCiVwW2JtvT6i-XpJYiEwxFryI'
API_key = 'AIzaSyCpumDcRbbteV64xlGOUQ5_Bah8Ja5gdJ4'
gmaps = googlemaps.Client(key=API_key)

result = gmaps.distance_matrix(coordinates, coordinates, mode='driving')["rows"]
distance_matrix = np.zeros((len(result), len(result)))

for i in range(len(result)):
    for j in range(len(result)):
        distance_matrix[i, j] = result[i]["elements"][j]["distance"]["value"]

np.savetxt("D:/Utilizadores/Documents/FEUP/2018-2019/1º Semestre/PDI/Relatório/locais_output.txt", distance_matrix, delimiter=",", fmt='%d')
print(distance_matrix)
</code>```

The distances I want are from one place to every place, so the result I want is a matrix of 15x15 where the diagonal is filled with 0's. But it keeps printing this error:

```<code>"googlemaps.exceptions.ApiError: MAX_ELEMENTS_EXCEEDED".
</code>```

The only way to not have an error is to put a limit on the reading of the file of 10 locations, including the depot:

```<code>result = gmaps.distance_matrix(coordinates[0:10], coordinates[0:10], mode='driving')["rows"]
</code>```

Why is that? Anyone?

答:
from the documentation

MAX_ELEMENTS_EXCEEDED indicates that the product of origins and destinations exceeds the per-query limit.

from "usage and billing":

Each query sent to the Distance Matrix API generates elements, where the number of origins times the number of destinations equals the number of elements.

Other Usage Limits

  While you are no longer limited to a maximum number of elements per day (EPD), the following usage limits are still in place for the Distance Matrix API:

Maximum of 25 origins or 25 destinations per request.

  Maximum 100 elements per server-side request.

  Maximum 100 elements per client-side request.

  1000 elements per second (EPS), calculated as the sum of client-side and server-side queries.

15 x 15 = 225 which is greater than the maximum allowed (100)

That you don't want or need some of the responses is not relevant.

Body:
So I developed a code where I read a file with some locations (15 to be more precise), where the first one is the depot and the other 14 locations are the places where a bus needs to pass to collect patients. In order to do that, I use Google Maps API key in order to collect the real distances and write them in a .txt file in the end.

import pandas as pd
import googlemaps
from itertools import tee
import numpy as np

#Read CSV file into data frame named 'df'
#change seperator (sep e.g. ',') type if necessary
df = pd.read_csv("D:/Utilizadores/Documents/FEUP/2018-2019/1º Semestre/PDI/Relatório/locais2.txt", sep='\\t',
                       engine='python', skiprows=[0], names=["address", "latitude", "longitude"])

lat = np.expand_dims(np.array(df["latitude"]), 1)
lon = np.expand_dims(np.array(df["longitude"]), 1)
coordinates = np.concatenate((lat, lon), axis=1)

coordinates = list(coordinates)
coordinates = [list(coor) for coor in coordinates]

#Perform request to use the Google Maps API web service
#API_key = 'AIzaSyCi8DDz_CCiVwW2JtvT6i-XpJYiEwxFryI'
API_key = 'AIzaSyCpumDcRbbteV64xlGOUQ5_Bah8Ja5gdJ4'
gmaps = googlemaps.Client(key=API_key)

result = gmaps.distance_matrix(coordinates, coordinates, mode='driving')["rows"]
distance_matrix = np.zeros((len(result), len(result)))

for i in range(len(result)):
    for j in range(len(result)):
        distance_matrix[i, j] = result[i]["elements"][j]["distance"]["value"]

np.savetxt("D:/Utilizadores/Documents/FEUP/2018-2019/1º Semestre/PDI/Relatório/locais_output.txt", distance_matrix, delimiter=",", fmt='%d')
print(distance_matrix)

The distances I want are from one place to every place, so the result I want is a matrix of 15x15 where the diagonal is filled with 0's. But it keeps printing this error:

"googlemaps.exceptions.ApiError: MAX_ELEMENTS_EXCEEDED".

The only way to not have an error is to put a limit on the reading of the file of 10 locations, including the depot:

result = gmaps.distance_matrix(coordinates[0:10], coordinates[0:10], mode='driving')["rows"]

Why is that? Anyone?


问:
How to verify element displays in new window after clicking a link on the main window
I am using Cypress to click a link on the Homepage which opens the respective page in the new window. I am not able to identify any element on this page. I am doing this to verify that the click opens the correct page.

I saw the link: Access a new window - cypress.io which didn't help much to answer the problem.

Please suggest if there is some way to test this.

I have tried few things like:

```<code>cy.window().contains('.div.trItem')
cy.window().its('.trValue).should('eq','SomeHeading')
cy.url().should('include', '/theLink1.html/')
</code>```

Expected:
- Clicking link open the correct page in new window
- Identify URL in new window includes some text
- Certain text displays on the new window

答:
First of all, you can't access to another tab or window with Cypress. Consider to separate your test cases. For example, in one test you could check that a element contains href attribute with expected url and target attribute with _blank.
Like this:

it('contains valid a element', () => {
  cy.visit('https://example.cypress.io/')
  cy.contains('Cypress.io').should('have.attr', 'href', 'https://www.cypress.io').should('have.attr', 'target', '_blank')
})
```

And in second test check that your other page contains expected text.

Body:
I am using Cypress to click a link on the Homepage which opens the respective page in the new window. I am not able to identify any element on this page. I am doing this to verify that the click opens the correct page.

I saw the link: Access a new window - cypress.io which didn't help much to answer the problem.

Please suggest if there is some way to test this.

I have tried few things like:

cy.window().contains('.div.trItem')
cy.window().its('.trValue).should('eq','SomeHeading')
cy.url().should('include', '/theLink1.html/')

Expected:
- Clicking link open the correct page in new window
- Identify URL in new window includes some text
- Certain text displays on the new window

Body:
First of all, you can't access to another tab or window with Cypress. Consider to separate your test cases. For example, in one test you could check that a element contains href attribute with expected url and target attribute with _blank.
Like this:

it('contains valid a element', () => {
  cy.visit('https://example.cypress.io/')
  cy.contains('Cypress.io').should('have.attr', 'href', 'https://www.cypress.io').should('have.attr', 'target', '_blank')
})

And in second test check that your other page contains expected text.


问:
Is there a way to put php inside of a IE conditional comments
I have a php section that loads jquery through wordpress from google's api. I dont want to load jquery on IE browsers. Long story short, it doesn't work for whatever reason (you can read through my other posted questions).

Or if this is not possible is there another way to NOT use this code when its an IE browser, maybe a php solution.

```<code><?php
    if( !is_admin()){
        wp_deregister_script('jquery');
        wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js', false, '1.5.2', true);
        wp_enqueue_script('jquery');
    }

?>
</code>```

Targets everything except IE (what i was trying to use, but it didnt work):

```<code><!--[if !IE]><!-->
<!--<![endif]-->
</code>```

答:
No. You'd probably want to detect the browser in a PHP block as an alternative solution. Something like:

```<code>$browser = get_browser();
if ($browser->browser == 'MSIE') {
    if (!is_admin()) {
        wp_deregister_script('jquery');
        wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js', false, '1.5.2', true);
        wp_enqueue_script('jquery');
    }
}
</code>```

Or using the $is_IE global variable as in Nikolay Yordanov's answer:

```<code>if ($is_IE) {
    if (!is_admin()) {
        wp_deregister_script('jquery');
        wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js', false, '1.5.2', true);
        wp_enqueue_script('jquery');
    }
}
</code>```

Body:
I have a php section that loads jquery through wordpress from google's api. I dont want to load jquery on IE browsers. Long story short, it doesn't work for whatever reason (you can read through my other posted questions).

Or if this is not possible is there another way to NOT use this code when its an IE browser, maybe a php solution.

<?php
    if( !is_admin()){
        wp_deregister_script('jquery');
        wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js', false, '1.5.2', true);
        wp_enqueue_script('jquery');
    }

?>

Targets everything except IE (what i was trying to use, but it didnt work):

Body:
No. You'd probably want to detect the browser in a PHP block as an alternative solution. Something like:

$browser = get_browser();
if ($browser->browser == 'MSIE') {
    if (!is_admin()) {
        wp_deregister_script('jquery');
        wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js', false, '1.5.2', true);
        wp_enqueue_script('jquery');
    }
}

Or using the $is_IE global variable as in Nikolay Yordanov's answer:

if ($is_IE) {
    if (!is_admin()) {
        wp_deregister_script('jquery');
        wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js', false, '1.5.2', true);
        wp_enqueue_script('jquery');
    }
}


问:
How to re-initialize a vector in a while-loop?
I am doing some exercises in c++. I am trying to make a simple game which requires continuous input in a vector from the user.

I tried to reinitialize the vector. I used in the while(1) loop and tried to clear() it too.

```<code>vector<int> user;                 // initialize vector
while (1)
{
    for (int guess; cin >> guess;)// looping
    {                             // user input
        user.push_back(guess);
    }
    if (user.size() != 4)         // check if user put exactly 4 numbers
    {
        cerr << "Invalid input";
        return 1;
    }
    //...                        // doing some stuff with "int bulls"
    if (bulls == 4)
    {
        break;
    }
}    // now need to go back with emty vector, so that the user can input guesses again
</code>```

In my terminal, it is looping forever or it is stopping in a condition I put for invalid input.

答:
You have an infinite loop because of

```<code>for(int guess; cin >> guess;)
</code>```

where you push_back to user vector until std::cin fails.

You probably want to have 4 user input. If so try the following, by which you do not need to clear the vector as in each while loop you create a new one.

```<code>while (true)
{
    std::vector<int> user;
    user.reserve(4); // reserve memory which helps not to have unwanted reallocations
    int guess;
    while(cin >> guess &&  user.size() != 4)
        user.emplace_back(guess);

    // doing some stuff with "int bulls"
    if (bulls == 4) {
        break;
    }
}
</code>```

Body:
I am doing some exercises in c++. I am trying to make a simple game which requires continuous input in a vector from the user.

I tried to reinitialize the vector. I used in the while(1) loop and tried to clear() it too.

vector<int> user;                 // initialize vector
while (1)
{
    for (int guess; cin >> guess;)// looping
    {                             // user input
        user.push_back(guess);
    }
    if (user.size() != 4)         // check if user put exactly 4 numbers
    {
        cerr << "Invalid input";
        return 1;
    }
    //...                        // doing some stuff with "int bulls"
    if (bulls == 4)
    {
        break;
    }
}    // now need to go back with emty vector, so that the user can input guesses again

In my terminal, it is looping forever or it is stopping in a condition I put for invalid input.

Body:
You have an infinite loop because of

for(int guess; cin >> guess;)

where you push_back to user vector until std::cin fails.

You probably want to have 4 user input. If so try the following, by which you do not need to clear the vector as in each while loop you create a new one.

while (true)
{
    std::vector<int> user;
    user.reserve(4); // reserve memory which helps not to have unwanted reallocations
    int guess;
    while(cin >> guess &&  user.size() != 4)
        user.emplace_back(guess);

    // doing some stuff with "int bulls"
    if (bulls == 4) {
        break;
    }
}