问:
"applicationXMI parameter not set" on starting a product in Eclipse E4
The last few days I took some time to shift the build process of my Eclipse E4 plugin project to maven and tycho. After I got this working I wanted to have a look at the producr again and tried to start it via RunAs "xvy.product".
I expected that to work fine, but I received this error message:

```<code>applicationXMI parameter not set and no branding plugin defined.
java.lang.Exception
    at org.eclipse.e4.ui.internal.workbench.swt.E4Application.lambda$12(E4Application.java:397)
    at java.util.Optional.orElseGet(Optional.java:267)
    at org.eclipse.e4.ui.internal.workbench.swt.E4Application.determineApplicationModelURI(E4Application.java:391)
    at org.eclipse.e4.ui.internal.workbench.swt.E4Application.loadApplicationModel(E4Application.java:349)
    at org.eclipse.e4.ui.internal.workbench.swt.E4Application.createE4Workbench(E4Application.java:253)
    at org.eclipse.e4.ui.internal.workbench.swt.E4Application.start(E4Application.java:149)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:653)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:590)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1499)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1472)
</code>```

In the end this looks, that there seems to be nothing wrong with my own code?! After a some googling I finally found some similar errors: This one was discussed here at stackoverflow Eclipse 4 RCP Deployment applicationXMI argument missing, but I donot receive an
AssertionFailedException nor do I try to export an RCP product. The other occurence was a bug at eclipse.org Application.e4xmi should be default for "applicationXMI"
As a consequence of that, I had a look at my plugin.xml and it looks like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>

   <extension
         id="prod"
         point="org.eclipse.core.runtime.products">
      <product
            application="org.eclipse.e4.ui.workbench.swt.E4Application"
            name="FinPim">
         <property
               name="appName"
               value="FinPim">
         </property>
         <property
               name="applicationXMI"
               value="mhFinPim/Application.e4xmi">
         </property>
         <property name="lifeCycleURI" value="bundleclass://mhFinPim/de.mho.finpim.lifecycle.Manager"></property>
      </product>
   </extension>

</plugin>
</code>```

You can see here, that my applicationXMI points to mhFinPim/Application.e4xmi
, which is bundlename/Applicatione4xmi
So, now I wonder, what else might be wrong that prevents my procuct from starting?

Subsequent to this exception, I receive a further one:

```<code>java.lang.NullPointerException
    at org.eclipse.emf.common.util.URI$URIPool$PlatformAccessUnit.setValue(URI.java:865)
    at org.eclipse.emf.common.util.URI$URIPool.intern(URI.java:1949)
    at org.eclipse.emf.common.util.URI.createPlatformPluginURI(URI.java:2718)
    at org.eclipse.e4.ui.internal.workbench.swt.E4Application.determineApplicationModelURI(E4Application.java:408)
    at org.eclipse.e4.ui.internal.workbench.swt.E4Application.loadApplicationModel(E4Application.java:349)
    at org.eclipse.e4.ui.internal.workbench.swt.E4Application.createE4Workbench(E4Application.java:253)
    at org.eclipse.e4.ui.internal.workbench.swt.E4Application.start(E4Application.java:149)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:653)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:590)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1499)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1472)
</code>```

I suppose, this is just a subsequent error, caused by the first exception?

答: I got the same type of error when I accidently regenerated my eclipse.ini file after a rebuild. My problem at that occasion was that the reference (-vm) to the Java VM had been deleted in the ini file.</p>

Body:
The last few days I took some time to shift the build process of my Eclipse E4 plugin project to maven and tycho. After I got this working I wanted to have a look at the producr again and tried to start it via RunAs "xvy.product".
I expected that to work fine, but I received this error message:

applicationXMI parameter not set and no branding plugin defined.
java.lang.Exception
    at org.eclipse.e4.ui.internal.workbench.swt.E4Application.lambda$12(E4Application.java:397)
    at java.util.Optional.orElseGet(Optional.java:267)
    at org.eclipse.e4.ui.internal.workbench.swt.E4Application.determineApplicationModelURI(E4Application.java:391)
    at org.eclipse.e4.ui.internal.workbench.swt.E4Application.loadApplicationModel(E4Application.java:349)
    at org.eclipse.e4.ui.internal.workbench.swt.E4Application.createE4Workbench(E4Application.java:253)
    at org.eclipse.e4.ui.internal.workbench.swt.E4Application.start(E4Application.java:149)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:653)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:590)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1499)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1472)

In the end this looks, that there seems to be nothing wrong with my own code?! After a some googling I finally found some similar errors: This one was discussed here at stackoverflow Eclipse 4 RCP Deployment applicationXMI argument missing, but I donot receive an
AssertionFailedException nor do I try to export an RCP product. The other occurence was a bug at eclipse.org Application.e4xmi should be default for "applicationXMI"
As a consequence of that, I had a look at my plugin.xml and it looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>

   <extension
         id="prod"
         point="org.eclipse.core.runtime.products">
      <product
            application="org.eclipse.e4.ui.workbench.swt.E4Application"
            name="FinPim">
         <property
               name="appName"
               value="FinPim">
         </property>
         <property
               name="applicationXMI"
               value="mhFinPim/Application.e4xmi">
         </property>
         <property name="lifeCycleURI" value="bundleclass://mhFinPim/de.mho.finpim.lifecycle.Manager"></property>
      </product>
   </extension>

</plugin>

You can see here, that my applicationXMI points to mhFinPim/Application.e4xmi
, which is bundlename/Applicatione4xmi
So, now I wonder, what else might be wrong that prevents my procuct from starting?

Subsequent to this exception, I receive a further one:

java.lang.NullPointerException
    at org.eclipse.emf.common.util.URI$URIPool$PlatformAccessUnit.setValue(URI.java:865)
    at org.eclipse.emf.common.util.URI$URIPool.intern(URI.java:1949)
    at org.eclipse.emf.common.util.URI.createPlatformPluginURI(URI.java:2718)
    at org.eclipse.e4.ui.internal.workbench.swt.E4Application.determineApplicationModelURI(E4Application.java:408)
    at org.eclipse.e4.ui.internal.workbench.swt.E4Application.loadApplicationModel(E4Application.java:349)
    at org.eclipse.e4.ui.internal.workbench.swt.E4Application.createE4Workbench(E4Application.java:253)
    at org.eclipse.e4.ui.internal.workbench.swt.E4Application.start(E4Application.java:149)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:653)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:590)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1499)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1472)

I suppose, this is just a subsequent error, caused by the first exception?


来源: stackexchange

问:
Monitoring PVC Usage with Prometheus
I am using Prometheus 2.33 version.
The following query does not work.

kubelet_volume_stats_available_bytes

kubelet_volume_stats_capacity_bytes

The following query is used to monitor the DISK usage of the POD.

container_fs_usage_bytes

container_fs_limit_bytes

Is there a way to get the usage of PVC, Limit value?

答:
For PVC, Kubernetes exposes these metrics to Prometheus, you can use them to monitor a persistent volume's usage:

kube_persistentvolume_capacity_bytes
kube_persistentvolumeclaim_resource_requests_storage_bytes
```

EDIT:
These metrics are from kube-state-metrics - a service that produces Prometheus format metrics based on the current state of the Kubernetes native resources. It is basically listening to Kubernetes API and gathering information about its resources and objects, in particular for PV - PV metrics and PVC - PVC metrics. More information about the service is here.

ContentLicense: CC BY-SA 4.0

Title: Monitoring PVC Usage with Prometheus

Body:
For PVC, Kubernetes exposes these metrics to Prometheus, you can use them to monitor a persistent volume's usage:

kube_persistentvolume_capacity_bytes
kube_persistentvolumeclaim_resource_requests_storage_bytes

EDIT:
These metrics are from kube-state-metrics - a service that produces Prometheus format metrics based on the current state of the Kubernetes native resources. It is basically listening to Kubernetes API and gathering information about its resources and objects, in particular for PV - PV metrics and PVC - PVC metrics. More information about the service is here.


问:
Add attribute to html element with php in functions.php
I need php code for functions.php (Wordpress) to add an attribute (data-priority="2") to an element if it have attribute: data-name="cf_post_wish_count"

I have

```<code><th data-name="cf_post_wish_count"></th>
</code>```

I need

```<code><th data-name="cf_post_wish_count" data-priority="2"></th>
</code>```

Any help?

答:
Based on your description this problem is more suited for JS/JQuery. You can do this on the frontend fairly simply:</p>
```<code>$('th[data-name="cf_post_wish_count"]').each(function() {
     $(this).attr('data-priority', '2');
});
</code>```

Body:
I need php code for functions.php (Wordpress) to add an attribute (data-priority="2") to an element if it have attribute: data-name="cf_post_wish_count"

I have

I need

Any help?

Body:
Based on your description this problem is more suited for JS/JQuery. You can do this on the frontend fairly simply:

$('th[data-name="cf_post_wish_count"]').each(function() {
     $(this).attr('data-priority', '2');
});


问:
Could not successfully bind to port 2181
I'm following https://github.com/PacktPublishing/Apache-Kafka-Series---Kafka-Connect-Hands-on-Learning and I've below docker-compose file and using Mac.

```<code>version: '2'

services:
  # this is our kafka cluster.
  kafka-cluster:
    image: landoop/fast-data-dev:cp3.3.0
    environment:
      ADV_HOST: localhost         # Change to 192.168.99.100 if using Docker Toolbox
      RUNTESTS: 0                 # Disable Running tests so the cluster starts faster
    ports:
      - 2181:2181                 # Zookeeper
      - 3030:3030                 # Landoop UI
      - 8081-8083:8081-8083       # REST Proxy, Schema Registry, Kafka Connect ports
      - 9581-9585:9581-9585       # JMX Ports
      - 9092:9092                 # Kafka Broker
</code>```

and when I run

```<code>docker-compose up kafka-cluster
[+] Running 1/0
 ⠿ Container code-kafka-cluster-1  Created                                                       0.0s
Attaching to code-kafka-cluster-1
code-kafka-cluster-1  | Setting advertised host to 127.0.0.1.
code-kafka-cluster-1  | runtime: failed to create new OS thread (have 2 already; errno=22)
code-kafka-cluster-1  | fatal error: newosproc
code-kafka-cluster-1  |
code-kafka-cluster-1  | runtime stack:
code-kafka-cluster-1  | runtime.throw(0x512269, 0x9)
code-kafka-cluster-1  |         /usr/lib/go/src/runtime/panic.go:566 +0x95
code-kafka-cluster-1  | runtime.newosproc(0xc420026000, 0xc420035fc0)
code-kafka-cluster-1  |         /usr/lib/go/src/runtime/os_linux.go:160 +0x194
code-kafka-cluster-1  | runtime.newm(0x5203a0, 0x0)
code-kafka-cluster-1  |         /usr/lib/go/src/runtime/proc.go:1572 +0x132
code-kafka-cluster-1  | runtime.main.func1()
code-kafka-cluster-1  |         /usr/lib/go/src/runtime/proc.go:126 +0x36
code-kafka-cluster-1  | runtime.systemstack(0x593600)
code-kafka-cluster-1  |         /usr/lib/go/src/runtime/asm_amd64.s:298 +0x79
code-kafka-cluster-1  | runtime.mstart()
code-kafka-cluster-1  |         /usr/lib/go/src/runtime/proc.go:1079
code-kafka-cluster-1  |
code-kafka-cluster-1  | goroutine 1 [running]:
code-kafka-cluster-1  | runtime.systemstack_switch()
code-kafka-cluster-1  |         /usr/lib/go/src/runtime/asm_amd64.s:252 fp=0xc420020768 sp=0xc420020760
code-kafka-cluster-1  | runtime.main()
code-kafka-cluster-1  |         /usr/lib/go/src/runtime/proc.go:127 +0x6c fp=0xc4200207c0 sp=0xc420020768
code-kafka-cluster-1  | runtime.goexit()
code-kafka-cluster-1  |         /usr/lib/go/src/runtime/asm_amd64.s:2086 +0x1 fp=0xc4200207c8 sp=0xc4200207c0
code-kafka-cluster-1  | Could not successfully bind to port 2181. Maybe some other service
code-kafka-cluster-1  | in your system is using it? Please free the port and try again.
code-kafka-cluster-1  | Exiting.
code-kafka-cluster-1 exited with code 1
</code>```

Note: % sudo lsof -i :2181 - this command shows no output.

答:
Error suggests you're running something else on port 2181 already. So either stop that, or remove the port mapping since you shouldn't be connecting to Zookeeper anyway for using Kafka. As of latest Kafka versions (which I doubt the linked course will be using), --zookeeper flags are removed from Kafka CLI tools

Other solution would be to not use the Landoop container. Plenty of other Docker Compose files exist on the web for Kafka

Overall, I'd suggest not using Docker at all for developing a Kafka Connector.

Body:
I'm following https://github.com/PacktPublishing/Apache-Kafka-Series---Kafka-Connect-Hands-on-Learning and I've below docker-compose file and using Mac.

version: '2'

services:
  # this is our kafka cluster.
  kafka-cluster:
    image: landoop/fast-data-dev:cp3.3.0
    environment:
      ADV_HOST: localhost         # Change to 192.168.99.100 if using Docker Toolbox
      RUNTESTS: 0                 # Disable Running tests so the cluster starts faster
    ports:
      - 2181:2181                 # Zookeeper
      - 3030:3030                 # Landoop UI
      - 8081-8083:8081-8083       # REST Proxy, Schema Registry, Kafka Connect ports
      - 9581-9585:9581-9585       # JMX Ports
      - 9092:9092                 # Kafka Broker

and when I run

docker-compose up kafka-cluster
[+] Running 1/0
 ⠿ Container code-kafka-cluster-1  Created                                                       0.0s
Attaching to code-kafka-cluster-1
code-kafka-cluster-1  | Setting advertised host to 127.0.0.1.
code-kafka-cluster-1  | runtime: failed to create new OS thread (have 2 already; errno=22)
code-kafka-cluster-1  | fatal error: newosproc
code-kafka-cluster-1  |
code-kafka-cluster-1  | runtime stack:
code-kafka-cluster-1  | runtime.throw(0x512269, 0x9)
code-kafka-cluster-1  |         /usr/lib/go/src/runtime/panic.go:566 +0x95
code-kafka-cluster-1  | runtime.newosproc(0xc420026000, 0xc420035fc0)
code-kafka-cluster-1  |         /usr/lib/go/src/runtime/os_linux.go:160 +0x194
code-kafka-cluster-1  | runtime.newm(0x5203a0, 0x0)
code-kafka-cluster-1  |         /usr/lib/go/src/runtime/proc.go:1572 +0x132
code-kafka-cluster-1  | runtime.main.func1()
code-kafka-cluster-1  |         /usr/lib/go/src/runtime/proc.go:126 +0x36
code-kafka-cluster-1  | runtime.systemstack(0x593600)
code-kafka-cluster-1  |         /usr/lib/go/src/runtime/asm_amd64.s:298 +0x79
code-kafka-cluster-1  | runtime.mstart()
code-kafka-cluster-1  |         /usr/lib/go/src/runtime/proc.go:1079
code-kafka-cluster-1  |
code-kafka-cluster-1  | goroutine 1 [running]:
code-kafka-cluster-1  | runtime.systemstack_switch()
code-kafka-cluster-1  |         /usr/lib/go/src/runtime/asm_amd64.s:252 fp=0xc420020768 sp=0xc420020760
code-kafka-cluster-1  | runtime.main()
code-kafka-cluster-1  |         /usr/lib/go/src/runtime/proc.go:127 +0x6c fp=0xc4200207c0 sp=0xc420020768
code-kafka-cluster-1  | runtime.goexit()
code-kafka-cluster-1  |         /usr/lib/go/src/runtime/asm_amd64.s:2086 +0x1 fp=0xc4200207c8 sp=0xc4200207c0
code-kafka-cluster-1  | Could not successfully bind to port 2181. Maybe some other service
code-kafka-cluster-1  | in your system is using it? Please free the port and try again.
code-kafka-cluster-1  | Exiting.
code-kafka-cluster-1 exited with code 1

Note: % sudo lsof -i :2181 - this command shows no output.


问:
How to store variables in for-loop to print after loop has completed?
I am currently working on a code that determines the floor occupancy rate of a hotel with 8 floors and 30 rooms per floor. I have successfully created the loop to determine the occupancy of each floor, however, after the for loop has completed, I’m supposed to display all the floor occupancy rates and total hotel occupancy rate. Do you guys have any advice? Hopefully the description of what I’m trying to achieve is good enough. Ive attached a picture of how the desired program should run. Thank you in advance!!</p>
```<code>print("this program will calculate a hotel's occupancy rate.")

# variable initialization
roomsOccupied = 0
floorOcupancyRate = (roomsOccupied/30) * 100
totalRoomsOccupied = 0
roomsAvailable = 30
floorOccupancyList = []

# list {1, 2, 3, 4, 5, 6, 7, 8}
# range

# user Input
for floorNbr in {1, 2, 3, 4, 5, 6, 7, 8}:
    print('Current floor: ', floorNbr)
    roomsOccupied = int(input('Please enter the number of rooms occupied on this floor: '))
    if roomsOccupied == True:
        if roomsOccupied <= roomsAvailable:
            floorOccupancyList.append(roomsOccupied)
            floorOccupancyRate = round((roomsOccupied/30)*100, 2)
            totalRoomsOccupied += roomsOccupied
            totalOccupancyRate = round((totalRoomsOccupied/240)*100, 2)
            print('For floor ', str(floorNbr), 'there are a total of ', str(roomsOccupied), 'for a floor occupancy rate of ', str(floorOccupancyRate), '%')
        else:
            print('Invalid occupancy amouont. Please try again.')
    else:
        roomsOccupied =int(input('Please enter a valid room occupacy amount: '))
print('There are a total of ', totalRoomsOccupied, 'rooms occupied for a total hotel occupancy rate of ', totalOccupancyRate, '%')
print(floorOccupancyList)
# Processing
# output
print('The total number of rooms occupied is: ', totalRoomsOccupied)
</code>```

答:
So I would store this information in a dictionary, and then access it with its key.

dict_occupied = {}
for f in floors:
    occupied = input(int()) # or however you're capturing this data
    dict_occupied[f] = occupied

for d in dict_occupied:
    print(f"Floor {d}: Rooms occupied = {dict_occupied[d]}.")
```

Body:
I am currently working on a code that determines the floor occupancy rate of a hotel with 8 floors and 30 rooms per floor. I have successfully created the loop to determine the occupancy of each floor, however, after the for loop has completed, I’m supposed to display all the floor occupancy rates and total hotel occupancy rate. Do you guys have any advice? Hopefully the description of what I’m trying to achieve is good enough. Ive attached a picture of how the desired program should run. Thank you in advance!!

print("this program will calculate a hotel's occupancy rate.")

# variable initialization
roomsOccupied = 0
floorOcupancyRate = (roomsOccupied/30) * 100
totalRoomsOccupied = 0
roomsAvailable = 30
floorOccupancyList = []

# list {1, 2, 3, 4, 5, 6, 7, 8}
# range

# user Input
for floorNbr in {1, 2, 3, 4, 5, 6, 7, 8}:
    print('Current floor: ', floorNbr)
    roomsOccupied = int(input('Please enter the number of rooms occupied on this floor: '))
    if roomsOccupied == True:
        if roomsOccupied <= roomsAvailable:
            floorOccupancyList.append(roomsOccupied)
            floorOccupancyRate = round((roomsOccupied/30)*100, 2)
            totalRoomsOccupied += roomsOccupied
            totalOccupancyRate = round((totalRoomsOccupied/240)*100, 2)
            print('For floor ', str(floorNbr), 'there are a total of ', str(roomsOccupied), 'for a floor occupancy rate of ', str(floorOccupancyRate), '%')
        else:
            print('Invalid occupancy amouont. Please try again.')
    else:
        roomsOccupied =int(input('Please enter a valid room occupacy amount: '))
print('There are a total of ', totalRoomsOccupied, 'rooms occupied for a total hotel occupancy rate of ', totalOccupancyRate, '%')
print(floorOccupancyList)
# Processing
# output
print('The total number of rooms occupied is: ', totalRoomsOccupied)


问:
Running Test Suite from Command Line - MVN test - Says Zero tests ran
I have written a test suite to test my api using RestAssured, Cucumber and Java. When I run my tests from the CucumberOptions TestRunner I can see all my 5 test case features running and passing. But I I open a terminal window and navigate the test project and enter the following command (see below) the test results say "Tests run 0".

mvn test

Below is my pom.xml file:-

```<code>    <?xml version="1.0" encoding="UTF-8"?>

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>

      <groupId>Automation101</groupId>
      <artifactId>Automation101APICucumber</artifactId>
      <version>0.0.1-SNAPSHOT</version>

      <name>Automation101APICucumber</name>
      <!-- FIXME change it to the project's website -->
      <url>http://www.example.com</url>

      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
      </properties>

      <dependencies>

        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>7.2.3</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-junit -->
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>7.2.3</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured -->
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>4.5.0</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.13.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.13.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.9</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.testng/testng -->
    <!-- -->    <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>7.5</version>
            <scope>test</scope>
        </dependency>

    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.36</version>
    </dependency>

        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.7.36</version>
        <scope>test</scope>
    </dependency>

      </dependencies>

      <build>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
          <plugins>
            <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
            <plugin>
              <artifactId>maven-clean-plugin</artifactId>
              <version>3.1.0</version>
            </plugin>
            <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
            <plugin>
              <artifactId>maven-resources-plugin</artifactId>
              <version>3.0.2</version>
            </plugin>
            <plugin>
              <artifactId>maven-compiler-plugin</artifactId>
              <version>3.8.0</version>
            </plugin>
            <plugin>
              <artifactId>maven-surefire-plugin</artifactId>
              <version>2.22.1</version>
            </plugin>
            <plugin>
              <artifactId>maven-jar-plugin</artifactId>
              <version>3.0.2</version>
            </plugin>
            <plugin>
              <artifactId>maven-install-plugin</artifactId>
              <version>2.5.2</version>
            </plugin>
            <plugin>
              <artifactId>maven-deploy-plugin</artifactId>
              <version>2.8.2</version>
            </plugin>
            <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
            <plugin>
              <artifactId>maven-site-plugin</artifactId>
              <version>3.7.1</version>
            </plugin>
            <plugin>
              <artifactId>maven-project-info-reports-plugin</artifactId>
              <version>3.0.0</version>
            </plugin>
          </plugins>
        </pluginManagement>
      </build>
    </project>

This i my test runner class:-

package CucumberOptions;

import org.junit.runner.RunWith;

import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;

@RunWith(Cucumber.class)
@CucumberOptions(
        features = "src/test/java/Features",
        glue = {"StepDefinitions"}
)
public class TestRunner {

}
</code>```

I will also provide a screen shot of my project folder structuring as this may be helpful:-

Any help to why the output in the command terminal says '0' test ran, would be hugely helpful to me. Thanks

答: I found out what was causing the issue. It was because I was using JUnit and TestNG in the same project. I removed all references to TestNG (including the pom.xml file). I then re-ran the test suite from the command line and it now shows 5 tests have been ran.</p>

Body:
I have written a test suite to test my api using RestAssured, Cucumber and Java. When I run my tests from the CucumberOptions TestRunner I can see all my 5 test case features running and passing. But I I open a terminal window and navigate the test project and enter the following command (see below) the test results say "Tests run 0".

mvn test

Below is my pom.xml file:-

    <?xml version="1.0" encoding="UTF-8"?>

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>

      <groupId>Automation101</groupId>
      <artifactId>Automation101APICucumber</artifactId>
      <version>0.0.1-SNAPSHOT</version>

      <name>Automation101APICucumber</name>

      <url>http://www.example.com</url>

      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
      </properties>

      <dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>7.2.3</version>
        </dependency>

        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>7.2.3</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>4.5.0</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.1</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.13.1</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.13.1</version>
        </dependency>

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.9</version>
        </dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>7.5</version>
            <scope>test</scope>
        </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.36</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.7.36</version>
        <scope>test</scope>
    </dependency>

      </dependencies>

      <build>
        <pluginManagement>
          <plugins>

            <plugin>
              <artifactId>maven-clean-plugin</artifactId>
              <version>3.1.0</version>
            </plugin>

            <plugin>
              <artifactId>maven-resources-plugin</artifactId>
              <version>3.0.2</version>
            </plugin>
            <plugin>
              <artifactId>maven-compiler-plugin</artifactId>
              <version>3.8.0</version>
            </plugin>
            <plugin>
              <artifactId>maven-surefire-plugin</artifactId>
              <version>2.22.1</version>
            </plugin>
            <plugin>
              <artifactId>maven-jar-plugin</artifactId>
              <version>3.0.2</version>
            </plugin>
            <plugin>
              <artifactId>maven-install-plugin</artifactId>
              <version>2.5.2</version>
            </plugin>
            <plugin>
              <artifactId>maven-deploy-plugin</artifactId>
              <version>2.8.2</version>
            </plugin>

            <plugin>
              <artifactId>maven-site-plugin</artifactId>
              <version>3.7.1</version>
            </plugin>
            <plugin>
              <artifactId>maven-project-info-reports-plugin</artifactId>
              <version>3.0.0</version>
            </plugin>
          </plugins>
        </pluginManagement>
      </build>
    </project>

This i my test runner class:-

package CucumberOptions;

import org.junit.runner.RunWith;

import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;

@RunWith(Cucumber.class)
@CucumberOptions(
        features = "src/test/java/Features",
        glue = {"StepDefinitions"}
)
public class TestRunner {

}

I will also provide a screen shot of my project folder structuring as this may be helpful:-

Any help to why the output in the command terminal says '0' test ran, would be hugely helpful to me. Thanks


问:
skip an iteration of the for loop in python
I need a hand, I don't understand how to fix it.

Look at the photo to better understand my speech, where the new field is populated the value of new is subtracted from the total and I don't want it to be subtracted immediately but the next round.

How can I do?

```<code>def UserAndamentoListView(request):
    giorni = []
    mese = []
    new_user = []
    tot_user = []
    tot =  User.objects.all().count()

    for day in range(5):
        giorni.append(datetime.datetime.now() - datetime.timedelta(days=day))
        new = User.objects.filter(date_joined__contains = giorni[day].date())
        new_user.append(new)
        tot -= new.count()
        tot_user.append(tot)

    context = {'giorni': giorni, 'new_user':new_user, 'tot_user': tot_user}
    return render(request, 'andamento.html', context)
</code>```

答:
Just subtract after appending the total

```<code>for day in range(5):
    giorni.append(datetime.datetime.now() - datetime.timedelta(days=day))
    new = User.objects.filter(date_joined__contains = giorni[day].date())
    new_user.append(new)
    tot_user.append(tot)

    tot -= new.count()
</code>```

The value of tot is changed at the end of the current loop iteration but is not used until the next trip around the loop.

Body:
I need a hand, I don't understand how to fix it.

Look at the photo to better understand my speech, where the new field is populated the value of new is subtracted from the total and I don't want it to be subtracted immediately but the next round.

How can I do?

def UserAndamentoListView(request):
    giorni = []
    mese = []
    new_user = []
    tot_user = []
    tot =  User.objects.all().count()

    for day in range(5):
        giorni.append(datetime.datetime.now() - datetime.timedelta(days=day))
        new = User.objects.filter(date_joined__contains = giorni[day].date())
        new_user.append(new)
        tot -= new.count()
        tot_user.append(tot)

    context = {'giorni': giorni, 'new_user':new_user, 'tot_user': tot_user}
    return render(request, 'andamento.html', context)

Body:
Just subtract after appending the total

for day in range(5):
    giorni.append(datetime.datetime.now() - datetime.timedelta(days=day))
    new = User.objects.filter(date_joined__contains = giorni[day].date())
    new_user.append(new)
    tot_user.append(tot)

    tot -= new.count()

The value of tot is changed at the end of the current loop iteration but is not used until the next trip around the loop.


答:
You've got to initialize your variable before the loop and modify it inside the loop.

For example:

```<code>floors = []
for i range(8):
    floors.append(input("Please enter the rooms occupied for floor:"))

print (floors)
</code>```

Title: How to store variables in for-loop to print after loop has completed?

Body:
You've got to initialize your variable before the loop and modify it inside the loop.

For example:

floors = []
for i range(8):
    floors.append(input("Please enter the rooms occupied for floor:"))

print (floors)


问:
Keras : history not accessible for loss or accuracy

I am training a CNN in Keras with Tensorflow backend,

mod1=gmodel.fit(images, train_labels,
      batch_size=100,
      epochs=2,
      verbose=1,
      validation_data=(test_images, test_labels))
```

<p>and at every epoch I can see printed in the output the accuracy and loss (until here everything seems ok).</p>

<pre class="lang-python prettyprint-override"><code>Epoch 1/10
1203/1203 [==============================] - 190s - loss: 0.7600 - acc: 0.5628
- val_loss: 0.5592 - val_acc: 0.6933
Epoch 2/10
1203/1203 [==============================] - 187s - loss: 0.5490 - acc: 0.6933
- val_loss: 0.4589 - val_acc: 0.7930
Epoch 3/10
....
</code>```

At the end, I want to plot the validation loss so in previous projects I have accessed the validation loss via

mod1.history['val_loss']
```

<p>but I am getting an error as if <code>.history()</code> was empty.</p>

<pre class="lang-python prettyprint-override"><code>TypeError                                 Traceback (most recent call last)
<ipython-input-23-ecdd306e9232> in <module>()
----> 1 modl.history()
TypeError: 'History' object is not callable
</code>```

EDIT (after answer below): When I try to access the loss, for example:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-34-06fcc6efb374> in <module>()
----> 1 mod1.history['val_loss']

TypeError: 'History' object is not subscriptable
```

I haven't found anything like this problem before, so I am lost as to what could be happening or how to debug.

Any pointers or ideas are greatly appreciated.

答:
Try this, it will definitely work.</p>
```<code>Epoches = 30

Validation = (x_valid,y_valid)

model_clf.fit(x_train,y_train,epochs=Epoches, validation_data=Validation, batch_size=20 )

model_clf.history.params

model_clf.history.history

#### convert into datafarame
pd.DataFrame(model_clf.history.history)

#### if u want to draw the graph
pd.DataFrame(model_clf.history.history).plot(figsize=(15,7))

plt.grid(True)

plt.show()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am training a CNN in Keras with Tensorflow backend,

mod1=gmodel.fit(images, train_labels,
      batch_size=100,
      epochs=2,
      verbose=1,
      validation_data=(test_images, test_labels))

and at every epoch I can see printed in the output the accuracy and loss (until here everything seems ok).

Epoch 1/10
1203/1203 [==============================] - 190s - loss: 0.7600 - acc: 0.5628
- val_loss: 0.5592 - val_acc: 0.6933
Epoch 2/10
1203/1203 [==============================] - 187s - loss: 0.5490 - acc: 0.6933
- val_loss: 0.4589 - val_acc: 0.7930
Epoch 3/10
....

At the end, I want to plot the validation loss so in previous projects I have accessed the validation loss via

mod1.history['val_loss']

but I am getting an error as if .history() was empty.

TypeError                                 Traceback (most recent call last)
<ipython-input-23-ecdd306e9232> in <module>()
----> 1 modl.history()
TypeError: 'History' object is not callable

EDIT (after answer below): When I try to access the loss, for example:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-34-06fcc6efb374> in <module>()
----> 1 mod1.history['val_loss']

TypeError: 'History' object is not subscriptable

I haven't found anything like this problem before, so I am lost as to what could be happening or how to debug.

Any pointers or ideas are greatly appreciated.

Body:
Try this, it will definitely work.

Epoches = 30

Validation = (x_valid,y_valid)

model_clf.fit(x_train,y_train,epochs=Epoches, validation_data=Validation, batch_size=20 )

model_clf.history.params

model_clf.history.history

#### convert into datafarame
pd.DataFrame(model_clf.history.history)

#### if u want to draw the graph
pd.DataFrame(model_clf.history.history).plot(figsize=(15,7))

plt.grid(True)

plt.show()


问:
How to use useState to store multiple key objects?
I have a candlestick chart for a crypto and it has different timeframe for 1 minute, 30, minute, and so on. I currently have

```<code>const [data, setData] = useState[]
  useEffect(() => {

    const fetchPrice = async () => {
      const { data } = await axios.get(`/api/apii?slug=${poolName[0].pool_id}&timeframe=`${1h}``); // default is 1h

      const btcusd = data.data.results.map(
        (d) => {
          return {
            open: d.open,
            close: d.close,
            low: d.low,
            high: d.high,
            time: toDateStamp(d.datetime),
          };
        }
      );
      setData(btcusd)
    };

    fetchPrice()
  }, []);
</code>```

The above is the initial state whenever a user visits which he or she will be shown a 1-hour chart data. So there is this onClick button which will fetch and set new state according to he chosen timeframe. It works if i setData for one timeframe but then if I set another timeframe, how do I separate them?

Edit:

My bad guys, I have no issues to have the useffect runs again as i have another useeffect for that purpose whenever a user clicks on a new timeframe. My question is how can I store the chosen timeframes into a state and then re-use them again should the user chooses the timeframe that he chose before? This would be nice as I can stop outgoing network request.

答:
You need to add your dynamic values, like 1h and poolName to the dependency array like this:

useEffect(() => {
  ...
}, [1h, poolNames])
```

Body:
I have a candlestick chart for a crypto and it has different timeframe for 1 minute, 30, minute, and so on. I currently have

const [data, setData] = useState[]
  useEffect(() => {

    const fetchPrice = async () => {
      const { data } = await axios.get(`/api/apii?slug=${poolName[0].pool_id}&timeframe=`${1h}``); // default is 1h

      const btcusd = data.data.results.map(
        (d) => {
          return {
            open: d.open,
            close: d.close,
            low: d.low,
            high: d.high,
            time: toDateStamp(d.datetime),
          };
        }
      );
      setData(btcusd)
    };

    fetchPrice()
  }, []);

The above is the initial state whenever a user visits which he or she will be shown a 1-hour chart data. So there is this onClick button which will fetch and set new state according to he chosen timeframe. It works if i setData for one timeframe but then if I set another timeframe, how do I separate them?

Edit:

My bad guys, I have no issues to have the useffect runs again as i have another useeffect for that purpose whenever a user clicks on a new timeframe. My question is how can I store the chosen timeframes into a state and then re-use them again should the user chooses the timeframe that he chose before? This would be nice as I can stop outgoing network request.


问:
zsh: command not found: atom
This seems to be happening randomly, but every once in a while my "atom ." command in order to open a directory in atom won't work.

I run into the following terminal error - "zsh: command not found: atom".

Once I open up Atom manually, I can go ahead and install shell commands and the command works. However, the shell commands don't seem to be saving.

I've tried to edit my zshrc file and uncommented line two "export PATH=$HOME/bin:/usr/local/bin:$PATH". But this issue seems to still be happening.

Any help would be greatly appreciated!

Thanks!

答:
If you're using oh-my-zsh, just uncomment the first line of ~/.zshrc -

```<code># If you come from bash you might have to change your $PATH.
# export PATH=$HOME/bin:/usr/local/bin:$PATH
</code>```

That worked for me !

Title: zsh: command not found: atom

Body:
If you're using oh-my-zsh, just uncomment the first line of ~/.zshrc -

# If you come from bash you might have to change your $PATH.
# export PATH=$HOME/bin:/usr/local/bin:$PATH

That worked for me !


问:
NEAR smart-contract error: "Contract is not initialized"
I created NEAR smart-contract using Assembly Script and deployed to testnet.
When I call any function I receiving error that contract is not initialised (contract was added to workspaces in asconfig.json):

```<code>Error: {"index":0,"kind":{"ExecutionError":"Smart contract panicked: contract is not initialized, filename: \"src/token/assembly/index.ts\" line: 123 col: 3"}}
ServerTransactionError: {"index":0,"kind":{"ExecutionError":"Smart contract panicked: contract is not initialized, filename: \"src/token/assembly/index.ts\" line: 123 col: 3"}}
</code>```

First lines of my contract

答:
This error can occur when you have a Singleton style contract, and a constructor(){} in it. If you don't use the constructor, just remove it. Or, you can call it with zero arguments when you deploy the contract:

```<code>near deploy --accountId example-contract.testnet --wasmFile out/singleton.wasm --initFunction new --initArgs '{}'
</code>```

or using dev-deploy, without passing an accountId to generate a new dev-account

```<code>near dev-deploy --wasmFile out/singleton.wasm --initFunction new --initArgs '{}'
</code>```

If you have a constructor with some arguments, you need to pass the arguments when you deploy it as well

```<code>near deploy --accountId example-contract.testnet --wasmFile out/singleton.wasm --initFunction new --initArgs '{"name":"someName"}'
</code>```

@nearBindgen
export class Contract {
 name: string;
 // If the constructor is empty without any argumanets, just remove it, and you don't have to think about init.
 // constructor(){}

 // When you have some arguments in the constructor, you need to call init after it's deployed.
 constructor(name:string){
   this.name = name;
 }

}
```
<p>If the contract is already deployed, which I think is the case when you get this error in the first place, you can also call <code>init</code> afterwards</p>
```near call example-contract.testnet init '{"name":"someName"}' --accountId example-contract.testnet
```

More information can be found in NEAR's documentation

Body:
I created NEAR smart-contract using Assembly Script and deployed to testnet.
When I call any function I receiving error that contract is not initialised (contract was added to workspaces in asconfig.json):

Error: {"index":0,"kind":{"ExecutionError":"Smart contract panicked: contract is not initialized, filename: \"src/token/assembly/index.ts\" line: 123 col: 3"}}
ServerTransactionError: {"index":0,"kind":{"ExecutionError":"Smart contract panicked: contract is not initialized, filename: \"src/token/assembly/index.ts\" line: 123 col: 3"}}

First lines of my contract

Body:
This error can occur when you have a Singleton style contract, and a constructor(){} in it. If you don't use the constructor, just remove it. Or, you can call it with zero arguments when you deploy the contract:

near deploy --accountId example-contract.testnet --wasmFile out/singleton.wasm --initFunction new --initArgs '{}'

or using dev-deploy, without passing an accountId to generate a new dev-account

near dev-deploy --wasmFile out/singleton.wasm --initFunction new --initArgs '{}'

If you have a constructor with some arguments, you need to pass the arguments when you deploy it as well

near deploy --accountId example-contract.testnet --wasmFile out/singleton.wasm --initFunction new --initArgs '{"name":"someName"}'

@nearBindgen
export class Contract {
 name: string;
 // If the constructor is empty without any argumanets, just remove it, and you don't have to think about init.
 // constructor(){}

 // When you have some arguments in the constructor, you need to call init after it's deployed.
 constructor(name:string){
   this.name = name;
 }

}

If the contract is already deployed, which I think is the case when you get this error in the first place, you can also call init afterwards

near call example-contract.testnet init '{"name":"someName"}' --accountId example-contract.testnet

More information can be found in NEAR's documentation


问:
Mongoose - Version Error: No matching document found for id
Context: I have a Post Mongoose model that contains a csv_files array field to store csv strings. I make a fetch API request from a different web app to POST the csv strings for a particular Post.

The code below produces an error

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): VersionError: No matching document found for id "5966932399e969ad8013bedf"

router.js

```<code>router.post('/posts/:url/upload-csv/:csv_name', (req, res) => {
  let csv_name = req.params.csv_name;
  let csv_string = csv_name+req.body.csv_string;

  Post.findOne({url: req.params.url})
    .then((post) => {
      if (post.csv_files.length === 0) {
        post.csv_files.push(csv_string);
      } else {
        let foundExistingCSV = false;
        for (var i = 0; i < post.csv_files.length; i++) {
          if (post.csv_files[i].includes(csv_name)) {
            foundExistingCSV = true;
            post.csv_files[i] = csv_string;
            break;
          }
        }
        if (!foundExistingCSV) post.csv_files.push(csv_string);
      }

      post.markModified('csv_files');
      post.save();

      return res.status(200);
    })
    .catch((err) => {
      console.log(err);
      return res.status(400);
    });
});
</code>```

models/post.js

```<code>const mongoose    = require('mongoose');

var stringPreset = {
  type: String,
  uppercase: true
}

var Post = mongoose.model('Post', {
  name                 : stringPreset,
  url                  : String,
  password             : String,
  csv_files            : { type : Array , "default" : [] },
  updatedAt            : { type: Date, default: Date.now }
});

module.exports = { Post };
</code>```

How can I fix this so that the document saves into the csv_files array without the error?

答:
I got the same error.
I used findone.exec(). it worked for me</p>

Body:
Context: I have a Post Mongoose model that contains a csv_files array field to store csv strings. I make a fetch API request from a different web app to POST the csv strings for a particular Post.

The code below produces an error

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): VersionError: No matching document found for id "5966932399e969ad8013bedf"

router.js

router.post('/posts/:url/upload-csv/:csv_name', (req, res) => {
  let csv_name = req.params.csv_name;
  let csv_string = csv_name+req.body.csv_string;

  Post.findOne({url: req.params.url})
    .then((post) => {
      if (post.csv_files.length === 0) {
        post.csv_files.push(csv_string);
      } else {
        let foundExistingCSV = false;
        for (var i = 0; i < post.csv_files.length; i++) {
          if (post.csv_files[i].includes(csv_name)) {
            foundExistingCSV = true;
            post.csv_files[i] = csv_string;
            break;
          }
        }
        if (!foundExistingCSV) post.csv_files.push(csv_string);
      }

      post.markModified('csv_files');
      post.save();

      return res.status(200);
    })
    .catch((err) => {
      console.log(err);
      return res.status(400);
    });
});

models/post.js

const mongoose    = require('mongoose');

var stringPreset = {
  type: String,
  uppercase: true
}

var Post = mongoose.model('Post', {
  name                 : stringPreset,
  url                  : String,
  password             : String,
  csv_files            : { type : Array , "default" : [] },
  updatedAt            : { type: Date, default: Date.now }
});

module.exports = { Post };

How can I fix this so that the document saves into the csv_files array without the error?


问:
Making some of the kernel parameters of the dense layer non-trainable
Consider a simple model as follows:

```<code>input = keras.layers.Input(shape=(1,))
l1 = tf.keras.layers.Dense(units=4,activation='relu',use_bias=False)(input)
out = tf.keras.layers.Dense(units=4,activation=None,use_bias=False)(l1)
model = tf.keras.Model(inputs=input, outputs=out)
</code>```

So for the last layer, the kernel has a shape of (4,4). Although for my implementation, I would only want to keep some of the parameters in this kernel to be trainable.

For instance, in usual cases, my kernel for the last layer looks like this:

But I would like to have something like this:

I want to have only non-zero entries as trainable. Can someone please help with this?

答:
The simplest way to do this is using kernel_initializer='zeros' with a custom kernel_constraint in the last Dense.

Here is my proposal for the custom kernel_constraint. my_constraints is a matrix of 0/1 built outside that must be passed as argument.

```<code>class MyConstraint(tf.keras.constraints.Constraint):

  def __init__(self, my_constraints):
    self.my_constraints = my_constraints

  def __call__(self, w):
    assert tf.shape(w).shape == tf.shape(self.my_constraints).shape
    return w * tf.cast(self.my_constraints, dtype=tf.float32)

  def get_config(self):
    return {'my_constraints': self.my_constraints}
</code>```

Below is how to build and run the model with some dummy data:

```<code>my_constraints = tf.constant([[1,0,1,0],[0,1,0,1],[1,0,1,0],[0,1,0,1]], dtype=tf.float32)
X = np.random.uniform(-10,10, (100,1))
y = np.random.uniform(-10,10, (100,4))

input = Input(shape=(1,))
l1 = Dense(units=4, activation='relu', name='layer1', use_bias=False)(input)
out = Dense(units=4, activation=None , name='layer2', use_bias=False,
            kernel_constraint=MyConstraint(my_constraints), kernel_initializer='zeros')(l1)
model = Model(inputs=input, outputs=out)
model.compile('adam','mse')

model.fit(X,y, epochs=100)
</code>```

To inspect the results:

```<code>>>> print(model.get_weights()[-1] == 0)
[[False  True False  True]
 [ True False  True False]
 [False  True False  True]
 [ True False  True False]]

>>> print(model.get_weights()[-1])
[[-0.00230937 -0.         -0.01893261  0.        ]
 [-0.         -0.07535305 -0.         -0.01603868]
 [-0.16068968  0.          0.23261748 -0.        ]
 [-0.         -0.07739028 -0.         -0.01623872]]
</code>```

Body:
Consider a simple model as follows:

input = keras.layers.Input(shape=(1,))
l1 = tf.keras.layers.Dense(units=4,activation='relu',use_bias=False)(input)
out = tf.keras.layers.Dense(units=4,activation=None,use_bias=False)(l1)
model = tf.keras.Model(inputs=input, outputs=out)

So for the last layer, the kernel has a shape of (4,4). Although for my implementation, I would only want to keep some of the parameters in this kernel to be trainable.

For instance, in usual cases, my kernel for the last layer looks like this:

But I would like to have something like this:

I want to have only non-zero entries as trainable. Can someone please help with this?

Body:
The simplest way to do this is using kernel_initializer='zeros' with a custom kernel_constraint in the last Dense.

Here is my proposal for the custom kernel_constraint. my_constraints is a matrix of 0/1 built outside that must be passed as argument.

class MyConstraint(tf.keras.constraints.Constraint):

  def __init__(self, my_constraints):
    self.my_constraints = my_constraints

  def __call__(self, w):
    assert tf.shape(w).shape == tf.shape(self.my_constraints).shape
    return w * tf.cast(self.my_constraints, dtype=tf.float32)

  def get_config(self):
    return {'my_constraints': self.my_constraints}

Below is how to build and run the model with some dummy data:

my_constraints = tf.constant([[1,0,1,0],[0,1,0,1],[1,0,1,0],[0,1,0,1]], dtype=tf.float32)
X = np.random.uniform(-10,10, (100,1))
y = np.random.uniform(-10,10, (100,4))

input = Input(shape=(1,))
l1 = Dense(units=4, activation='relu', name='layer1', use_bias=False)(input)
out = Dense(units=4, activation=None , name='layer2', use_bias=False,
            kernel_constraint=MyConstraint(my_constraints), kernel_initializer='zeros')(l1)
model = Model(inputs=input, outputs=out)
model.compile('adam','mse')

model.fit(X,y, epochs=100)

To inspect the results:

>>> print(model.get_weights()[-1] == 0)
[[False  True False  True]
 [ True False  True False]
 [False  True False  True]
 [ True False  True False]]

>>> print(model.get_weights()[-1])
[[-0.00230937 -0.         -0.01893261  0.        ]
 [-0.         -0.07535305 -0.         -0.01603868]
 [-0.16068968  0.          0.23261748 -0.        ]
 [-0.         -0.07739028 -0.         -0.01623872]]


答:
If the timespans in df_2 are not overlapping, you can use numpy broadcasting to compare the timestamp with all of the timespans and determine which timespan it falls between. Then use argmax to figure out which 'Event' to assign (since there can only be at most 1 with non-overlapping timespans).

The where condition is used to NaN any that could have fallen outside of all timespans (since argmax won't deal with this properly)

```<code>import numpy as np

m = ((df_1['timestamp'].to_numpy() >= df_2['start'].to_numpy()[:, None])
      & (df_1['timestamp'].to_numpy() <= df_2['end'].to_numpy()[:, None]))

df_1['Event'] = df_2['event'].take(np.argmax(m, axis=0)).where(m.sum(axis=0) > 0)
</code>```

```<code>print(df_1)
            timestamp         A         B Event
0 2016-05-14 10:54:33  0.020228  0.026572    E1
1 2016-05-14 10:54:34  0.057780  0.175499    E2
2 2016-05-14 10:54:35  0.098808  0.620986    E2
3 2016-05-14 10:54:36  0.158789  1.014819    E2
4 2016-05-14 10:54:39  0.038129  2.384590    E3
</code>```

Title: How to join two dataframes for which column values are within a certain range?

Body:
Given two dataframes df_1 and df_2, how to join them such that datetime column df_1 is in between start and end  in dataframe df_2:

print df_1

  timestamp              A          B
0 2016-05-14 10:54:33    0.020228   0.026572
1 2016-05-14 10:54:34    0.057780   0.175499
2 2016-05-14 10:54:35    0.098808   0.620986
3 2016-05-14 10:54:36    0.158789   1.014819
4 2016-05-14 10:54:39    0.038129   2.384590

print df_2

  start                end                  event
0 2016-05-14 10:54:31  2016-05-14 10:54:33  E1
1 2016-05-14 10:54:34  2016-05-14 10:54:37  E2
2 2016-05-14 10:54:38  2016-05-14 10:54:42  E3

Get corresponding event where df1.timestamp is between df_2.start and df2.end

  timestamp              A          B          event
0 2016-05-14 10:54:33    0.020228   0.026572   E1
1 2016-05-14 10:54:34    0.057780   0.175499   E2
2 2016-05-14 10:54:35    0.098808   0.620986   E2
3 2016-05-14 10:54:36    0.158789   1.014819   E2
4 2016-05-14 10:54:39    0.038129   2.384590   E3

Body:
If the timespans in df_2 are not overlapping, you can use numpy broadcasting to compare the timestamp with all of the timespans and determine which timespan it falls between. Then use argmax to figure out which 'Event' to assign (since there can only be at most 1 with non-overlapping timespans).

The where condition is used to NaN any that could have fallen outside of all timespans (since argmax won't deal with this properly)

import numpy as np

m = ((df_1['timestamp'].to_numpy() >= df_2['start'].to_numpy()[:, None])
      & (df_1['timestamp'].to_numpy() <= df_2['end'].to_numpy()[:, None]))

df_1['Event'] = df_2['event'].take(np.argmax(m, axis=0)).where(m.sum(axis=0) > 0)

print(df_1)
            timestamp         A         B Event
0 2016-05-14 10:54:33  0.020228  0.026572    E1
1 2016-05-14 10:54:34  0.057780  0.175499    E2
2 2016-05-14 10:54:35  0.098808  0.620986    E2
3 2016-05-14 10:54:36  0.158789  1.014819    E2
4 2016-05-14 10:54:39  0.038129  2.384590    E3


问:
Firebase auth not successful
I've been trying so make auth with firebase and all went pretty well. But at the moment i tested it, it didn't work. The problem is that the function called createUserWithEmailAndPassowrd is not successful. I think the firebase it's connected to android studio, because the analytics works perfectly. Could you give me a hand please?

Here is the code:

```<code>package com.example.authtest

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.ktx.Firebase

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val etEmail = findViewById<EditText>(R.id.EmailEt)
        val etPwd = findViewById<EditText>(R.id.PasswordEt)
        val registerBtn = findViewById<Button>(R.id.RegisterBtn)
        val logInBtn = findViewById<Button>(R.id.LogInBtn)
        val tvMessage = findViewById<TextView>(R.id.MessageTv)

        val auth = FirebaseAuth.getInstance()

        registerBtn.setOnClickListener {
            if (etEmail.text.isNotEmpty() && etPwd.text.isNotEmpty()) {
                auth.createUserWithEmailAndPassword(etEmail.toString(),etPwd.toString()).addOnCompleteListener {
                    if (it.isSuccessful) {
                        tvMessage.text = "Registered as: " + it.result?.user?.email ?: ""
                    } else {
                        tvMessage.text = "Error registering your account!"
                    }
                }
            }
        }

        logInBtn.setOnClickListener {
            if (etEmail.text.isNotEmpty() && etPwd.text.isNotEmpty()) {
                auth.signInWithEmailAndPassword(etEmail.toString(),etPwd.toString()).addOnCompleteListener {
                    if (it.isSuccessful) {
                        tvMessage.text = "Logged in as: " + it.result?.user?.email ?: ""
                    } else {
                        tvMessage.text = "Incorrect username/password!"
                    }
                }
            }
        }
    }
}
</code>```

Thanks in advance!

答:
The auth.createUserWithEmailAndPassword call (and many other Firebase API calls) returns a Task that is marked as either being successful or as having failed. In the case where the task has failed, it contains an exception that gives the root cause of that failure.

You should log the exception, and fix the root cause:

```<code>FirebaseAuth.getInstance().signInWithEmailAndPassword(emailID,pass)
  .addOnCompleteListener{ task->
    if (task.isSuccessful) {

        ...

    } else {
        Log.e("Firebase Auth", "Sign-in failed", task.exception); //
        Toast.makeText(this@Login,task.exception!!.message.toString(),
            LENGTH_SHORT).show()
    }
}
</code>```

Title: Firebase auth not successful

Body:
I've been trying so make auth with firebase and all went pretty well. But at the moment i tested it, it didn't work. The problem is that the function called createUserWithEmailAndPassowrd is not successful. I think the firebase it's connected to android studio, because the analytics works perfectly. Could you give me a hand please?

Here is the code:

package com.example.authtest

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.ktx.Firebase

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val etEmail = findViewById<EditText>(R.id.EmailEt)
        val etPwd = findViewById<EditText>(R.id.PasswordEt)
        val registerBtn = findViewById<Button>(R.id.RegisterBtn)
        val logInBtn = findViewById<Button>(R.id.LogInBtn)
        val tvMessage = findViewById<TextView>(R.id.MessageTv)

        val auth = FirebaseAuth.getInstance()

        registerBtn.setOnClickListener {
            if (etEmail.text.isNotEmpty() && etPwd.text.isNotEmpty()) {
                auth.createUserWithEmailAndPassword(etEmail.toString(),etPwd.toString()).addOnCompleteListener {
                    if (it.isSuccessful) {
                        tvMessage.text = "Registered as: " + it.result?.user?.email ?: ""
                    } else {
                        tvMessage.text = "Error registering your account!"
                    }
                }
            }
        }

        logInBtn.setOnClickListener {
            if (etEmail.text.isNotEmpty() && etPwd.text.isNotEmpty()) {
                auth.signInWithEmailAndPassword(etEmail.toString(),etPwd.toString()).addOnCompleteListener {
                    if (it.isSuccessful) {
                        tvMessage.text = "Logged in as: " + it.result?.user?.email ?: ""
                    } else {
                        tvMessage.text = "Incorrect username/password!"
                    }
                }
            }
        }
    }
}

Thanks in advance!

Body:
The auth.createUserWithEmailAndPassword call (and many other Firebase API calls) returns a Task that is marked as either being successful or as having failed. In the case where the task has failed, it contains an exception that gives the root cause of that failure.

You should log the exception, and fix the root cause:

FirebaseAuth.getInstance().signInWithEmailAndPassword(emailID,pass)
  .addOnCompleteListener{ task->
    if (task.isSuccessful) {

        ...

    } else {
        Log.e("Firebase Auth", "Sign-in failed", task.exception); //
        Toast.makeText(this@Login,task.exception!!.message.toString(),
            LENGTH_SHORT).show()
    }
}


问:
Ethereum Web3.js returns "Cannot find module 'web3-requestManager'"
I'm trying to start using Ethereum Web3.js with node 6.11.1 on a macosx

I installed web3 with the following command:

npm install web3

Then i launch this - apparently - simple node command:

Web3 = require('web3');

Well, it returns the following error:

```<code>module.js:471
    throw err;
    ^

Error: Cannot find module 'web3-requestManager'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/fremente/Dropbox/Influx Design/Web htdocs/ethereum/node_modules/web3/packages/web3-core/src/index.js:26:22)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
</code>```

it looks like it require some module (e.g. 'web3-requestManager') that aren't installed with the package.

Here it is my package.json

```<code>{
  "name": "ethereum",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "ethereumjs-testrpc": "^4.0.1",
    "solc": "^0.4.13",
    "web3": "^1.0.0-beta2"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}
</code>```

Any Idea? Am i doing something wrong?

答: Downgrading "react-scripts" from "5.0.0" to "4.0.3" did the trick for me.</p>

Body:
I'm trying to start using Ethereum Web3.js with node 6.11.1 on a macosx

I installed web3 with the following command:

npm install web3

Then i launch this - apparently - simple node command:

Web3 = require('web3');

Well, it returns the following error:

module.js:471
    throw err;
    ^

Error: Cannot find module 'web3-requestManager'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/fremente/Dropbox/Influx Design/Web htdocs/ethereum/node_modules/web3/packages/web3-core/src/index.js:26:22)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)

it looks like it require some module (e.g. 'web3-requestManager') that aren't installed with the package.

Here it is my package.json

{
  "name": "ethereum",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "ethereumjs-testrpc": "^4.0.1",
    "solc": "^0.4.13",
    "web3": "^1.0.0-beta2"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Any Idea? Am i doing something wrong?


问:
How to make outer pane scroll instead of inner one
Firstly, as you probably noticed in tags, I use RichTextFX. CodeArea is just its text area with some features.

I have ScrollPane with inner elements:

```<code>ScrollPane
|   AnchorPane
|   |   VBox
|   |   |   HBox
|   |   |   |   Label
|   |   |   |   CodeArea
|   |   |   HBox
|   |   |   |   Label
|   |   |   |   CodeArea
|   |   |   HBox
|   |   |   |   Label
|   |   |   |   CodeArea
...........................
</code>```

When I'm trying to scroll while my cursor isn't hovering CodeArea, ScrollPane scrolling like it should do.

But if my cursor is on CodeArea, as I assume, it trying to scroll the CodeArea, even if there is nothing to scroll (content fits well).

ScrollEvent isn't being called on ScrollPane, AnchorPane nor CodeArea, but VBox.

I tried to bind properties like scrollPane.onScrollProperty().bind(vBox.onScrollProperty()) or scrollPane.onScrollProperty().bind(codeArea.onScrollProperty()) and many others but that didn't work.

This question doesn't affect classic TextArea.

How to make ScrollPane scroll instead of CodeArea when hovering CodeArea?

You can also use this example to reproduce the problem:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.scene.control.ScrollPane;
import org.fxmisc.richtext.CodeArea;

public class Main extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        ScrollPane scrollPane = new ScrollPane();
        VBox vBox = new VBox();
        scrollPane.setContent(vBox);
        CodeArea codeArea = new CodeArea();
        codeArea.setPrefHeight(2000);
        Label label = new Label("Can you scroll here while hovering code area?");
        vBox.getChildren().addAll(codeArea, label);
        for (int i = 0; i < 256; i++) {
            codeArea.appendText("Sample text\n");
        }
        Scene scene = new Scene(scrollPane, 400, 400);
        stage.setScene(scene);
        stage.show();
    }
}
```

答:
In your example do:</p>
```<code>codeArea.addEventFilter( ScrollEvent.ANY, scroll ->
{
    vBox.fireEvent( scroll );
    scroll.consume();
});
</code>```

Body:
Firstly, as you probably noticed in tags, I use RichTextFX. CodeArea is just its text area with some features.

I have ScrollPane with inner elements:

ScrollPane
|   AnchorPane
|   |   VBox
|   |   |   HBox
|   |   |   |   Label
|   |   |   |   CodeArea
|   |   |   HBox
|   |   |   |   Label
|   |   |   |   CodeArea
|   |   |   HBox
|   |   |   |   Label
|   |   |   |   CodeArea
...........................

When I'm trying to scroll while my cursor isn't hovering CodeArea, ScrollPane scrolling like it should do.

But if my cursor is on CodeArea, as I assume, it trying to scroll the CodeArea, even if there is nothing to scroll (content fits well).

ScrollEvent isn't being called on ScrollPane, AnchorPane nor CodeArea, but VBox.

I tried to bind properties like scrollPane.onScrollProperty().bind(vBox.onScrollProperty()) or scrollPane.onScrollProperty().bind(codeArea.onScrollProperty()) and many others but that didn't work.

This question doesn't affect classic TextArea.

How to make ScrollPane scroll instead of CodeArea when hovering CodeArea?

You can also use this example to reproduce the problem:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.scene.control.ScrollPane;
import org.fxmisc.richtext.CodeArea;

public class Main extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        ScrollPane scrollPane = new ScrollPane();
        VBox vBox = new VBox();
        scrollPane.setContent(vBox);
        CodeArea codeArea = new CodeArea();
        codeArea.setPrefHeight(2000);
        Label label = new Label("Can you scroll here while hovering code area?");
        vBox.getChildren().addAll(codeArea, label);
        for (int i = 0; i < 256; i++) {
            codeArea.appendText("Sample text\n");
        }
        Scene scene = new Scene(scrollPane, 400, 400);
        stage.setScene(scene);
        stage.show();
    }
}

Body:
In your example do:

codeArea.addEventFilter( ScrollEvent.ANY, scroll ->
{
    vBox.fireEvent( scroll );
    scroll.consume();
});


问:
How I get  URL from webview on click
How can I get "clicked URL" from webview on its click event??

@Override
    public void onClick(View v) {

```<code>    if( v.getId() == R.id.webview) {

        //Here i want to get clicked url
    }

}
</code>```

Thanks in advance.

答:
```<code>webView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url){
                webView.loadUrl(url);
                // Here the String url hold 'Clicked URL'
                return false;
            }
        });
</code>```

Title: How I get  URL from webview on click

Body:
How can I get "clicked URL" from webview on its click event??

@Override
    public void onClick(View v) {

    if( v.getId() == R.id.webview) {

        //Here i want to get clicked url
    }

}

Thanks in advance.


问:
What is the proper way to create a class instance with an empty dictionary and/or list?
This answer suggests I am creating my empty dictionary the correct way.

```<code>class Board:
    def __init(self):
        self.pot = 0
        self.activePlayer = 1
        self.activePlayers = 4
        self.passedPlayers = 0
        self.firstHand = True
        self.lastCardsPlayedList = []
        self.lastCardsPlayedDict = {}

    def playCard(self, cardInt, cardPic):
        self.lastCardsPlayedDict[cardInt] = cardPic
        self.lastCardsPlayedList.append(cardInt)
        self.lastCardsPlayedList.sort()
</code>```

I create an instance of my class

```<code>b = Board()
</code>```

but when I go to call it...

```<code>b.playCard(1, cardPic)
</code>```

I get the error:

```<code>AttributeError: 'Board' object has no attribute 'lastCardsPlayedDict'
</code>```

答:
Silly Mistake...your init method is not defined correctly.

Here is the corrected code.

```<code>class Board:
    def __init__(self):
        self.pot = 0
        self.activePlayer = 1
        self.activePlayers = 4
        self.passedPlayers = 0
        self.firstHand = True
        self.lastCardsPlayedList = []
        self.lastCardsPlayedDict = {}

    def playCard(self, cardInt, cardPic):
        self.lastCardsPlayedDict[cardInt] = cardPic
        self.lastCardsPlayedList.append(cardInt)
        self.lastCardsPlayedList.sort()

b = Board()
b.playCard(1, 'cardPic')

print(b)
</code>```

Body:
This answer suggests I am creating my empty dictionary the correct way.

class Board:
    def __init(self):
        self.pot = 0
        self.activePlayer = 1
        self.activePlayers = 4
        self.passedPlayers = 0
        self.firstHand = True
        self.lastCardsPlayedList = []
        self.lastCardsPlayedDict = {}

    def playCard(self, cardInt, cardPic):
        self.lastCardsPlayedDict[cardInt] = cardPic
        self.lastCardsPlayedList.append(cardInt)
        self.lastCardsPlayedList.sort()

I create an instance of my class

b = Board()

but when I go to call it...

b.playCard(1, cardPic)

I get the error:

AttributeError: 'Board' object has no attribute 'lastCardsPlayedDict'

Body:
Silly Mistake...your init method is not defined correctly.

Here is the corrected code.

class Board:
    def __init__(self):
        self.pot = 0
        self.activePlayer = 1
        self.activePlayers = 4
        self.passedPlayers = 0
        self.firstHand = True
        self.lastCardsPlayedList = []
        self.lastCardsPlayedDict = {}

    def playCard(self, cardInt, cardPic):
        self.lastCardsPlayedDict[cardInt] = cardPic
        self.lastCardsPlayedList.append(cardInt)
        self.lastCardsPlayedList.sort()

b = Board()
b.playCard(1, 'cardPic')

print(b)


问:
Support schedule for Cassandra versions
I wanted to know till when Cassandra 3.11.10 is supported.
Is there some place where this information is available for all currently supported versions of Cassandra?
https://cassandra.apache.org/_/download.html specifies the maintained until date only for the latest available versions.</p>

答:
Download the latest Apache Cassandra 3.11 release: Released on
2022-02-08 Maintained until 4.2.0 release (May-July 2023)

This section covers all 3.11.x releases.  3.11.10 should be good until mid 2023.

Title: Support schedule for Cassandra versions


问:
Authentication middleware is called for routes that don't exist
I have public and private routes in an app.

// public
router.use(publicRoute);

// After this all Routes are private
router.use(runAsyncWrapper(isAuthenticated));

// private
router.use(privateRoute);
```
<p>There is also a route that matches all possible routes, and returns a 404 error.</p>
<pre class="lang-js prettyprint-override"><code>app.all('*', (req, res, next) => {
  next(new MyError(`Route ${req.originalUrl} doesn not exist.`));
});
</code>```

In the middleware I try to authenticate the user.

const isAuthenticated = async (req, res, next) => {
  const {
    headers: { authorization },
  } = req;

  const user = await tryToAuthenticateAndReturnUser(authorization);

  if (!user) throw new MyError('Token is not valid', 401);

  req.user = user;

  next();
};
```

This middleware is run for any route that doesn't match any public route, even if the route itself doesn't exist. So if I request a route that doesn't exist, instead of 404 error it will return me the "Token is not valid", 401 error.

How do I make it return the right error, 404 if route doesn't exist, and 401 if route exists but user can't be authenticated?

答:
I had to add the middleware for every route separately, as @kmp answered in the comments to my question. I could improve it a little bit, by adding middleware to routes using first word in routes' path.

For example, if we have such routes

GET `/users` //to get all users
POST `/users` //to create a user

GET `/posts/:userId` //to get posts of a user
POST `/posts/:userId` //to create a user's post
```
<p>We can create an array like this</p>
<pre class="lang-js prettyprint-override"><code>const protectedRoutes = ['/users', '/posts'];
</code>```

and then add authentication middleware like this

protectedRoutes.forEach(route => router.use(route, runAsyncWrapper(isAuthenticated)))
```

After this every route that starts with /users or /posts will be protected.

Body:
I have public and private routes in an app.

// public
router.use(publicRoute);

// After this all Routes are private
router.use(runAsyncWrapper(isAuthenticated));

// private
router.use(privateRoute);

There is also a route that matches all possible routes, and returns a 404 error.

app.all('*', (req, res, next) => {
  next(new MyError(`Route ${req.originalUrl} doesn not exist.`));
});

In the middleware I try to authenticate the user.

const isAuthenticated = async (req, res, next) => {
  const {
    headers: { authorization },
  } = req;

  const user = await tryToAuthenticateAndReturnUser(authorization);

  if (!user) throw new MyError('Token is not valid', 401);

  req.user = user;

  next();
};

This middleware is run for any route that doesn't match any public route, even if the route itself doesn't exist. So if I request a route that doesn't exist, instead of 404 error it will return me the "Token is not valid", 401 error.

How do I make it return the right error, 404 if route doesn't exist, and 401 if route exists but user can't be authenticated?

Body:
I had to add the middleware for every route separately, as @kmp answered in the comments to my question. I could improve it a little bit, by adding middleware to routes using first word in routes' path.

For example, if we have such routes

GET `/users` //to get all users
POST `/users` //to create a user

GET `/posts/:userId` //to get posts of a user
POST `/posts/:userId` //to create a user's post

We can create an array like this

const protectedRoutes = ['/users', '/posts'];

and then add authentication middleware like this

protectedRoutes.forEach(route => router.use(route, runAsyncWrapper(isAuthenticated)))

After this every route that starts with /users or /posts will be protected.


问:
Using CollectionExpression in QueryDSL
In the QueryDSL library, the com.mysema.query.types.expr.SimpleExpression<T> class has a SimpleExpression.in(CollectionExpression<?, ? extends T>) method which is supposed to take an expression which is supposed to return a collection. But I cannot find a way to create an object of type com.mysema.query.types.CollectionExpression<?, ? extends T>.

My query expression looks like this:

```<code>QEvent.event.organization.in(expression)
</code>```

where i want the expression to be something like:

```<code>QOrganization.organization.country.in("India", "USA")
</code>```

But the second expression is of type com.mysema.query.types.expr.BooleanExpression and I am unable to find a way to convert it to com.mysema.query.types.CollectionExpression<?, ? extends T>.

I looked in the QueryDSL API docs but could not find anything relevant.

答:
I don't think you can do it like that, it wouldn't make sense on the DB side, anyway.

You have to use a SubQuery

Title: Using CollectionExpression in QueryDSL

Body:
In the QueryDSL library, the com.mysema.query.types.expr.SimpleExpression<T> class has a SimpleExpression.in(CollectionExpression<?, ? extends T>) method which is supposed to take an expression which is supposed to return a collection. But I cannot find a way to create an object of type com.mysema.query.types.CollectionExpression<?, ? extends T>.

My query expression looks like this:

QEvent.event.organization.in(expression)

where i want the expression to be something like:

QOrganization.organization.country.in("India", "USA")

But the second expression is of type com.mysema.query.types.expr.BooleanExpression and I am unable to find a way to convert it to com.mysema.query.types.CollectionExpression<?, ? extends T>.

I looked in the QueryDSL API docs but could not find anything relevant.


问:
Postgres: processes terminated after connetion break / invalidation
I don't understand some of Postgres mechanism and it makes me quite upset.
I usually use DBeaver as SQL client to query external pg base. If run create.. or insert.. queries and then connection for some reason is broken or invalidated, the pid is still running and finishes transaction.

But for some more complicated PL/pgSQL functions (with temp tables, loops, inserts, etc.) we wrote, breaking connection always causes process termination (it disappears from session list just before making next sql operation, eg. inserting a row in logtable). No matter if it's DBeaver editor or psql command.

I know that maybe disconnecting is critical problem, which should be eliminated and maybe I shouldn't expect process to successfully continue, but I do:) Or just to know why it happened and is it possible to prevent it?

答:
If the network connection fails, the database server can detect that in two ways:

if it tries to send data to the client, it will figure out pretty quickly that the connection is down

if it tries to receive data from the client, it will only notice when the kernel's TCP keepalive mechanism has determined that the connection is down

When you say that sometimes execution of a function is terminated right away, I would say that is because the function returned data to the client.

In the case where a query keeps running, it is not attempting to return any data yet.

There is no cure for the former, but in PostgreSQL v14 you can prevent the latter by setting client_connection_check_interval. In addition, you have to set the PostgreSQL keepalive parameters so that the dead connection becomes known quickly.

See my article for more.


问:
Trying to make a program with header files in C
I'm trying to make a program in C that uses header files and I'm getting an error. The program is supposed to add two numbers, add two numbers with a macro, and print a component in a typedef. There are three separate files:

functions.c

```<code>int add(int n1, int n2) {
    return n1 + n2;
}
</code>```

functions.h

```<code>#ifndef FUNCTIONS_H
#define FUNCTIONS_H

// function declaration
int add(int, int);

// macro declaration
#define ADD(n1, n2) n1 + n2

// typedef declaration
typedef struct {
    int age;
    char *name;
} person;

#endif
</code>```

main.c (This is the main program that uses everything from functions.c and functions.h and prints the result.)

```<code>#include <stdio.h>
#include "functions.h"

int main(void) {
    printf("%d\n", add(2, 6));
    printf("%d\n", ADD(3, 7));

    person engineer_man;
    engineer_man.age = 32;
    printf("engineer man's age is: %d\n", engineer_man.age);
}
</code>```

I tried compiling by doing gcc -g -std=c99 -Wall -Wvla -Werror -fsanitize=address,undefined -o main main.c, but then it gave this error:

/usr/bin/ld: /tmp/ccbVAioe.o: in function `main':
/common/home/user/folder/main.c:5: undefined reference to `add'
collect2: error: ld returned 1 exit status
```

How do I fix this error?

答:
You never compile functions.c.

You need this:

gcc -g -std=c99 -Wall -Wvla -Werror -fsanitize=address,undefined -o main main.c functions.c
                                                                 you forgot this ^
```
<p>BTW, you also need to include "functions.h" in "functions.c":</p>
```#include "functions.h"

int add(int n1, int n2) {
    return n1 + n2;
}
```

Without including "functions.h" your program will build, but if for some reason the function declaration in functions.h doesn't match the function definiton in "functions.c", your program will have undefined behaviour.

Body:
I'm trying to make a program in C that uses header files and I'm getting an error. The program is supposed to add two numbers, add two numbers with a macro, and print a component in a typedef. There are three separate files:

functions.c

int add(int n1, int n2) {
    return n1 + n2;
}

functions.h

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

// function declaration
int add(int, int);

// macro declaration
#define ADD(n1, n2) n1 + n2

// typedef declaration
typedef struct {
    int age;
    char *name;
} person;

#endif

main.c (This is the main program that uses everything from functions.c and functions.h and prints the result.)

#include <stdio.h>
#include "functions.h"

int main(void) {
    printf("%d\n", add(2, 6));
    printf("%d\n", ADD(3, 7));

    person engineer_man;
    engineer_man.age = 32;
    printf("engineer man's age is: %d\n", engineer_man.age);
}

I tried compiling by doing gcc -g -std=c99 -Wall -Wvla -Werror -fsanitize=address,undefined -o main main.c, but then it gave this error:

/usr/bin/ld: /tmp/ccbVAioe.o: in function `main':
/common/home/user/folder/main.c:5: undefined reference to `add'
collect2: error: ld returned 1 exit status

How do I fix this error?

Body:
You never compile functions.c.

You need this:

gcc -g -std=c99 -Wall -Wvla -Werror -fsanitize=address,undefined -o main main.c functions.c
                                                                 you forgot this ^

BTW, you also need to include "functions.h" in "functions.c":

#include "functions.h"

int add(int n1, int n2) {
    return n1 + n2;
}

Without including "functions.h" your program will build, but if for some reason the function declaration in functions.h doesn't match the function definiton in "functions.c", your program will have undefined behaviour.


问:
using two consecutive values from a list in each iteration
I have posted a part of my code below. Newton() function calls Bezier() function. The Bezier() function has a list from where I get p0 and p3. What I am trying to do is, in 1st iteration the program should take the first and second items from the plist as p0 and p3. Then in 2nd iteration, p0 and p3 are the second and third items and so on. With each iteration, the p0 and p3 values should change. It's like the new p0 is the old p3. I could not put this in the code properly. Thank you.  </p>

```<code>import math

w = 1.0

def Newton(poly):
    """ Returns a root of the polynomial"""
    x = 0.5  # initial guess value
    counter = 0
    epsilon = 0.000000000001
    poly_diff = poly_differentiate(poly)

    while True:
        x_n = x - (float(poly_substitute(poly, x)) / float(poly_substitute(poly_diff, x)))
        counter += 1
        if abs(x_n - x) < epsilon :
            break
        x = x_n
        print "\tIteration " , counter , " : ", x_n

    print "u: ", x_n
    Bezier(x_n)

def Bezier(x_n) :
    """ Calculating sampling points using rational bezier curve equation"""
    u = x_n
    plist = [0.5, 0.1, 0.4, 0.35, 0.8, 0.6, 1.0, 0.2, 0.7, 0.9] # list of parameter values of the phonemes

    for i in range(len(plist) - 1) :
        p0 = plist[i]
        p3 = plist[i + 1]
        p1 = p0
        p2 = p3
        print p0, p3
        p_u = math.pow(1 - u, 3) * p0 + 3 * u * math.pow(1 - u, 2) * p1 \
            + 3 * (1 - u) * math.pow(u, 2) * p2 + math.pow(u, 3) * p3
        p_u = p_u * w
        d = math.pow(1 - u, 3) * w + 3 * u * w * math.pow(1 - u, 2) + 3 * (1 - u) * w * math.pow(u, 2) + math.pow(u, 3) * w
        p_u = p_u / d

    print "p(u): ", p_u
    return plist

if __name__ == "__main__" :
</code>```

Body:
I have posted a part of my code below. Newton() function calls Bezier() function. The Bezier() function has a list from where I get p0 and p3. What I am trying to do is, in 1st iteration the program should take the first and second items from the plist as p0 and p3. Then in 2nd iteration, p0 and p3 are the second and third items and so on. With each iteration, the p0 and p3 values should change. It's like the new p0 is the old p3. I could not put this in the code properly. Thank you.

import math

w = 1.0

def Newton(poly):
    """ Returns a root of the polynomial"""
    x = 0.5  # initial guess value
    counter = 0
    epsilon = 0.000000000001
    poly_diff = poly_differentiate(poly)

    while True:
        x_n = x - (float(poly_substitute(poly, x)) / float(poly_substitute(poly_diff, x)))
        counter += 1
        if abs(x_n - x) < epsilon :
            break
        x = x_n
        print "\tIteration " , counter , " : ", x_n

    print "u: ", x_n
    Bezier(x_n)

def Bezier(x_n) :
    """ Calculating sampling points using rational bezier curve equation"""
    u = x_n
    plist = [0.5, 0.1, 0.4, 0.35, 0.8, 0.6, 1.0, 0.2, 0.7, 0.9] # list of parameter values of the phonemes

    for i in range(len(plist) - 1) :
        p0 = plist[i]
        p3 = plist[i + 1]
        p1 = p0
        p2 = p3
        print p0, p3
        p_u = math.pow(1 - u, 3) * p0 + 3 * u * math.pow(1 - u, 2) * p1 \
            + 3 * (1 - u) * math.pow(u, 2) * p2 + math.pow(u, 3) * p3
        p_u = p_u * w
        d = math.pow(1 - u, 3) * w + 3 * u * w * math.pow(1 - u, 2) + 3 * (1 - u) * w * math.pow(u, 2) + math.pow(u, 3) * w
        p_u = p_u / d

    print "p(u): ", p_u
    return plist

if __name__ == "__main__" :

Body:
>>> p = [1, 2, 3, 4, 5]
>>> for p1, p2 in zip(p, p[1:]):
...     print p1, p2
...
1 2
2 3
3 4
4 5

Does it help?


问:
Oracle - Where clause parameter change query speed
Using a query with a table and a View, however if i change the where column the speed drastically changes.
What can be the problem?
its quite hard to google "performance changes on where clause" since all exemples are not even close to this.

```<code>SELECT ADRE.*
FROM INVOICE N
INNER JOIN ENTRY_INVOICE NAF
     ON NAF.COMPANY = N.COMPANY
     AND NAF.ID_INVOICE = N.ID_INVOICE
INNER JOIN UV_ENTRY_ALL ADRE
    ON ADRE.COMPANY = NAF.COMPANY
    AND ADRE.ID_ENTRY = NAF.ID_ENTRY
WHERE
    NAF.COMPANY = 1
    /*
    AND NAF.ID_INVOICE = 113806
        => 40 SECONDS

    AND  NAF.ID_ENTRY = 387473
        => 0,6 SECONDS

    AND EXISTS (SELECT 1 FROM ENTRY_INVOICE WHERE COMPANY = 1 AND ID_INVOICE=113806)
        => 1,6 SECONDS
    */
</code>```

ENTRY_INVOICE
IT HAS AT MOST 2 RECORDS FOR EACH INVOICE.

COMPANY
ID_INVOICE
ID_ENTRY

1
113706
387224

1
113706
387225

1
113707
387226

1
113806
387473

PLAN EXPLANATION
https://exists-stack.tiiny.site/

As questioned, even if remove the table INVOICE, and select especific columns, it wont change the speed.

答:
UV_ENTRY_ALL Was a View that returned all payments from invoice
however i tought removing some tables would make it perform better, and it does, but i need to filter the exact entry.

By adding back on each Union (union all) ENTRY_INVOICE and returning "ID_INVOICE" i added it on the Join and now works like a charm.

on the other hand i lost Performance while i run UV_ENTRY_ALL standalone

```<code>SELECT ADRE.*
FROM INVOICE N
INNER JOIN ENTRY_INVOICE NAF
    ON NAF.COMPANY = N.COMPANY
    AND NAF.ID_INVOICE = N.ID_INVOICE
INNER JOIN UV_ENTRY_ALL ADRE
   ON ADRE.COMPANY = NAF.COMPANY
   AND ADRE.ID_ENTRY = NAF.ID_ENTRY
   AND ADRE.ID_INVOICE = NAF.ID_INVOICE
WHERE
   NAF.COMPANY = 1 AND NAF.ID_INVOICE = 113806
</code>```

Body:
Using a query with a table and a View, however if i change the where column the speed drastically changes.
What can be the problem?
its quite hard to google "performance changes on where clause" since all exemples are not even close to this.

SELECT ADRE.*
FROM INVOICE N
INNER JOIN ENTRY_INVOICE NAF
     ON NAF.COMPANY = N.COMPANY
     AND NAF.ID_INVOICE = N.ID_INVOICE
INNER JOIN UV_ENTRY_ALL ADRE
    ON ADRE.COMPANY = NAF.COMPANY
    AND ADRE.ID_ENTRY = NAF.ID_ENTRY
WHERE
    NAF.COMPANY = 1
    /*
    AND NAF.ID_INVOICE = 113806
        => 40 SECONDS

    AND  NAF.ID_ENTRY = 387473
        => 0,6 SECONDS

    AND EXISTS (SELECT 1 FROM ENTRY_INVOICE WHERE COMPANY = 1 AND ID_INVOICE=113806)
        => 1,6 SECONDS
    */

ENTRY_INVOICE
IT HAS AT MOST 2 RECORDS FOR EACH INVOICE.

COMPANY
ID_INVOICE
ID_ENTRY

1
113706
387224

1
113706
387225

1
113707
387226

1
113806
387473

PLAN EXPLANATION
https://exists-stack.tiiny.site/

As questioned, even if remove the table INVOICE, and select especific columns, it wont change the speed.

Body:
UV_ENTRY_ALL Was a View that returned all payments from invoice
however i tought removing some tables would make it perform better, and it does, but i need to filter the exact entry.

By adding back on each Union (union all) ENTRY_INVOICE and returning "ID_INVOICE" i added it on the Join and now works like a charm.

on the other hand i lost Performance while i run UV_ENTRY_ALL standalone

SELECT ADRE.*
FROM INVOICE N
INNER JOIN ENTRY_INVOICE NAF
    ON NAF.COMPANY = N.COMPANY
    AND NAF.ID_INVOICE = N.ID_INVOICE
INNER JOIN UV_ENTRY_ALL ADRE
   ON ADRE.COMPANY = NAF.COMPANY
   AND ADRE.ID_ENTRY = NAF.ID_ENTRY
   AND ADRE.ID_INVOICE = NAF.ID_INVOICE
WHERE
   NAF.COMPANY = 1 AND NAF.ID_INVOICE = 113806