问:
What are the `'UnreadVariable'` in Tensorflow 2.0?
In Tensorflow 2.0, some variables can be described as 'UnreadVariable'

For ex:

```<code>b = tf.Variable([4,5], name="test")
print(b.assign([7, 9]))
# Will print
# <tf.Variable 'UnreadVariable' shape=(2,) dtype=int32, numpy=array([7, 9], dtype=int32)>
</code>```

What does it mean?

答:
UnreadVariable basically Represents a future for a read of a variable. Pretends to be the tensor if anyone looks.

This is because of the eager execution enabled during assign operation.

TensorFlow's eager execution is an imperative programming environment that evaluates operations immediately, without building graphs: operations return concrete values instead of constructing a computational graph to run later.

In Tensorflow 2.0 eager execution is enabled by default. So the operation which you are performing does it without constructing a graph.

Anyways if you want you can change the type to AssignVariableOp by disabling eager execution as follows.

```<code>import tensorflow as tf
tf.compat.v1.disable_eager_execution()

b = tf.Variable([4,5], name="test")
print(b.assign([7, 9]))

Returns:

<tf.Variable 'AssignVariableOp' shape=(2,) dtype=int32>
</code>```

Body:
In Tensorflow 2.0, some variables can be described as 'UnreadVariable'

For ex:

b = tf.Variable([4,5], name="test")
print(b.assign([7, 9]))
# Will print
# <tf.Variable 'UnreadVariable' shape=(2,) dtype=int32, numpy=array([7, 9], dtype=int32)>

What does it mean?

Body:
UnreadVariable basically Represents a future for a read of a variable. Pretends to be the tensor if anyone looks.

This is because of the eager execution enabled during assign operation.

TensorFlow's eager execution is an imperative programming environment that evaluates operations immediately, without building graphs: operations return concrete values instead of constructing a computational graph to run later.

In Tensorflow 2.0 eager execution is enabled by default. So the operation which you are performing does it without constructing a graph.

Anyways if you want you can change the type to AssignVariableOp by disabling eager execution as follows.

import tensorflow as tf
tf.compat.v1.disable_eager_execution()

b = tf.Variable([4,5], name="test")
print(b.assign([7, 9]))

Returns:

<tf.Variable 'AssignVariableOp' shape=(2,) dtype=int32>


来源: stackexchange

问:
Beautiful Soup Can't Redact Phone Number with Parentheses
I'm trying to redact phone number information from an html file ... and while I can identify all of the phone numbers easily enough I can't figure out why I am unable to replace the phone numbers that have parentheses in them.  Sample below:

```<code>import re
from bs4 import BeautifulSoup

text = '''<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<title>Big Title</title>
<style type="text/css">
.parsed {font-size: 75%; color: #474747;}
</style>
</head>
<body>
<div class="parsed">
<h1>Redacted Redacted</h1>
<h2> Contact Info</h2>
<ul>
<li>Position Title: My Fake Title</li>
<li>Email: Redacted@gmail.com</li>
<li>Phones: (555) 555-5555</li>
</ul><b>Category:</b> <ul><li>Title 2    </li><li>Fake Info</li></ul>

 City, MO 11111 | (555) 111-1111 | myemail@gmail.com

 Some Category / Some Name: 555-222-2222 | Record Number#:

 </html>'''

soup = BeautifulSoup(text, 'html.parser')

def find_phone_numbers(text):
    phones = re.findall(r"((?:\d{3}|\(\d{3}\))?(?:\s|-|\.)?\d{3}(?:\s|-|\.)\d{4})", text)
    return phones

phones = find_phone_numbers(str(soup))

print(phones)

for i in phones:
    target = soup.find_all(text=re.compile(i, re.I))
    try:
        for v in target:
            v.replace_with(v.replace(i,'(XXX) XXX-XXXX'))
    except TypeError:
        pass;

print(soup)
</code>```

These are my results from running the above:

```<code>['(555) 555-5555', '(555) 111-1111', '555-222-2222']
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<title>Big Title</title>
<style type="text/css">
.parsed {font-size: 75%; color: #474747;}
</style>
</head>
<body>
<div class="parsed">
<h1>Redacted Redacted</h1>
<h2> Contact Info</h2>
<ul>
<li>Position Title: My Fake Title</li>
<li>Email: Redacted@gmail.com</li>
<li>Phones: (555) 555-5555</li>
</ul><b>Category:</b> <ul><li>Title 2    </li><li>Fake Info</li></ul>

 City, MO 11111 | (555) 111-1111 | myemail@gmail.com

 Some Category / Some Name: (XXX) XXX-XXXX | Record Number#:

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

答:
You can use .find_all(text=True) to obtain all text content from the HTML soup, and then replace it with re.sub (that way, you preserve all tags, including
):

```<code>for content in soup.find_all(text=True):
    s = re.sub(r'(\(?\d{3}\)?)([\s.-]*)(\d{3})([\s.-]*)(\d{4})', '(XXX) XXX-XXXX', content)
    content.replace_with(s)

print(soup)
</code>```

Prints:

```<code><html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<title>Big Title</title>
<style type="text/css">
.parsed {font-size: 75%; color: #474747;}
</style>
</head>
<body>
<div class="parsed">
<h1>Redacted Redacted</h1>
<h2> Contact Info</h2>
<ul>
<li>Position Title: My Fake Title</li>
<li>Email: Redacted@gmail.com</li>
<li>Phones: (XXX) XXX-XXXX</li>
</ul><b>Category:</b> <ul><li>Title 2    </li><li>Fake Info</li></ul>

 City, MO 11111 | (XXX) XXX-XXXX | myemail@gmail.com

 Some Category / Some Name: (XXX) XXX-XXXX | Record Number#:

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

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to redact phone number information from an html file ... and while I can identify all of the phone numbers easily enough I can't figure out why I am unable to replace the phone numbers that have parentheses in them.  Sample below:

import re
from bs4 import BeautifulSoup

text = '''

<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<title>Big Title</title>

Redacted Redacted

 Contact Info

Position Title: My Fake Title

Email: Redacted@gmail.com

Phones: (555) 555-5555

Category:

Title 2

Fake Info

 City, MO 11111 | (555) 111-1111 | myemail@gmail.com

 Some Category / Some Name: 555-222-2222 | Record Number#:

 '''

soup = BeautifulSoup(text, 'html.parser')

def find_phone_numbers(text):
    phones = re.findall(r"((?:\d{3}|\(\d{3}\))?(?:\s|-|\.)?\d{3}(?:\s|-|\.)\d{4})", text)
    return phones

phones = find_phone_numbers(str(soup))

print(phones)

for i in phones:
    target = soup.find_all(text=re.compile(i, re.I))
    try:
        for v in target:
            v.replace_with(v.replace(i,'(XXX) XXX-XXXX'))
    except TypeError:
        pass;

print(soup)

These are my results from running the above:

['(555) 555-5555', '(555) 111-1111', '555-222-2222']

<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<title>Big Title</title>

Redacted Redacted

 Contact Info

Position Title: My Fake Title

Email: Redacted@gmail.com

Phones: (555) 555-5555

Category:

Title 2

Fake Info

 City, MO 11111 | (555) 111-1111 | myemail@gmail.com

 Some Category / Some Name: (XXX) XXX-XXXX | Record Number#:

Body:
You can use .find_all(text=True) to obtain all text content from the HTML soup, and then replace it with re.sub (that way, you preserve all tags, including <li>):

for content in soup.find_all(text=True):
    s = re.sub(r'(\(?\d{3}\)?)([\s.-]*)(\d{3})([\s.-]*)(\d{4})', '(XXX) XXX-XXXX', content)
    content.replace_with(s)

print(soup)

Prints:

<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<title>Big Title</title>
<style type="text/css">
.parsed {font-size: 75%; color: #474747;}
</style>
</head>
<body>
<div class="parsed">
<h1>Redacted Redacted</h1>
<h2> Contact Info</h2>
<ul>
<li>Position Title: My Fake Title</li>
<li>Email: Redacted@gmail.com</li>
<li>Phones: (XXX) XXX-XXXX</li>
</ul><b>Category:</b> <ul><li>Title 2    </li><li>Fake Info</li></ul>

 City, MO 11111 | (XXX) XXX-XXXX | myemail@gmail.com

 Some Category / Some Name: (XXX) XXX-XXXX | Record Number#:

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


问:
Query-string encoding of a JavaScript object
Is there a fast and simple way to encode a JavaScript object into a string that I can pass via a GET request?

No jQuery, no other frameworks—just plain JavaScript :)

答:
With Ramda:

    R.pipe(R.toPairs, R.map(R.join('=')), R.join('&'))({a: 'b', b: 'a'})
```


问:
unable to compare strings in mongodb collection
I'm a beginner in mongodb and pymongo and I have a mongodb movie database where I store the users
with fields(name,surname,email,category).I am trying to insert a user in my mongodb data using a pymongo and the user key must be a string that is either "Admin" or "Simple". However I am a complete beginner and I do not know how to compare a mongodb collection instance with a string .
I have my code down below :

```<code>from pymongo import MongoClient
from flask import Flask , request , Response , jsonify , redirect
from pymongo.errors import DuplicateKeyError
import json

client = MongoClient('mongodb://localhost:27017/')
db = client['MovieFlixDB']

users = db['Users']
movies = db['Movies']

app = Flask(__name__)

@app.route('/insertuser' , methods = ['POST'])
def insert_user():
    data = None
    try:
       data=json.loads(request.data)
    except Exception as e:
        return Response("Bad json content" , status = 500 , mimetype='application/json')
    if data==None:
        return Response("no data has been added" , status = 500 , mimetype='application/json')
    if not "name" in data or not "surname" in data or not "email" in data or not "category" in data:
        return Response("Information incompleted" , status = 500 , mimetype='application/json')
    if data['category']!="admin" and data['category']!="simple":
    return Response("Invalid category." ,status = 500 , mimetype='application/json')
</code>```

EDIT : I realised that I cannot compare something that has not been inserted in my database and I actually have to compare data["category"] not users.find(...) and I updated my code

I would appreciate your help with this task . Thank you in advance

答:
I think you need to use below:

db_data = users.find_one({"email":data["email"]})
if db_data["category"] == data['category']:
    # Do something
else:
    # Do something else
```

I suggest you to use find_one, instead of find, since you need to find only one document, matching the condition.

Body:
I'm a beginner in mongodb and pymongo and I have a mongodb movie database where I store the users
with fields(name,surname,email,category).I am trying to insert a user in my mongodb data using a pymongo and the user key must be a string that is either "Admin" or "Simple". However I am a complete beginner and I do not know how to compare a mongodb collection instance with a string .
I have my code down below :

from pymongo import MongoClient
from flask import Flask , request , Response , jsonify , redirect
from pymongo.errors import DuplicateKeyError
import json

client = MongoClient('mongodb://localhost:27017/')
db = client['MovieFlixDB']

users = db['Users']
movies = db['Movies']

app = Flask(__name__)

@app.route('/insertuser' , methods = ['POST'])
def insert_user():
    data = None
    try:
       data=json.loads(request.data)
    except Exception as e:
        return Response("Bad json content" , status = 500 , mimetype='application/json')
    if data==None:
        return Response("no data has been added" , status = 500 , mimetype='application/json')
    if not "name" in data or not "surname" in data or not "email" in data or not "category" in data:
        return Response("Information incompleted" , status = 500 , mimetype='application/json')
    if data['category']!="admin" and data['category']!="simple":
    return Response("Invalid category." ,status = 500 , mimetype='application/json')

EDIT : I realised that I cannot compare something that has not been inserted in my database and I actually have to compare data["category"] not users.find(...) and I updated my code

I would appreciate your help with this task . Thank you in advance

Body:
I think you need to use below:

db_data = users.find_one({"email":data["email"]})
if db_data["category"] == data['category']:
    # Do something
else:
    # Do something else

I suggest you to use find_one, instead of find, since you need to find only one document, matching the condition.


问:
Check data update in redux store
I have two audio players (mini and main) and when I dispatch pause or play in the mini player I must call the function in the main player. For this, I need to check if the isplaying parameter changes.

Does anyone have any idea on how can I achieve this?

In the mini player code:

store.dispatch({type: "PAUSE"})
```

<p>Then in the main player I call the pause function :</p>

<pre class="lang-js prettyprint-override"><code>const pause = () => {
audio.stop()
}
pause()
</code>```

How do I check if this parameter is changing?

答:
I do stop/play on Enter and mainplayer buttons .
and in mini player i write simulate function that on miniplayer buttons click simulate pressing Enter</p>

Title: Check data update in redux store

Body:
I have two audio players (mini and main) and when I dispatch pause or play in the mini player I must call the function in the main player. For this, I need to check if the isplaying parameter changes.

Does anyone have any idea on how can I achieve this?

In the mini player code:

store.dispatch({type: "PAUSE"})

Then in the main player I call the pause function :

const pause = () => {
audio.stop()
}
pause()

How do I check if this parameter is changing?


问:
Which free version of Java can I use for production environments and or commercial purposes?
While I was in a dockerization project in my current job, I got this doubt: Which Java can I use?

This doubt is due to :

So after some researches I got these conclusions:

Since the Java 8 update at April 16, 2019 8u221, all versions and updates for (Java 8, 9, 10, 11 and 13) has no cost just for personal use and development purposes. Any other use, needs a Commercial License

Legacy versions prior to 7, does not have and will not have any update. Maybe a sales contact could be a solution if an update in these versions are required for Legacy Systems Support.

If I want to use Java 8 oracle version for commercials purposes and FREE, I need to use a previous version of April 16, 2019 8u221 update

Questions

According to my conclusions:

If my development strictly needs or was developed with JDK 8, Can I only use Oracle Java SE 8 JDK 8u202 and earlier versions for FREE and commercial purposes accepting issues and security problems?

If I can change my development and I want still FREE, and I want to have improvements and security updates, I must use one of these  java open implementations?

References

End of Public Updates for Oracle JDK 8

The Oracle JDK License has changed for releases starting April 16, 2019.

Official List of updates and release versions

Java official supported versions

Oracle Java 8 download alert

Oracle Java 8 unsupported but free version

Java 4 legacy official download page

Java 5 legacy official download page

Java 6 legacy official download page

Java 7 legacy official download page

答:
Summary

If you need to have java in your production servers for free, your have two options

#1 OpenJdk

The OpenJDK is the open source reference implementation of the Java SE Specification, but it is only the source code https://github.com/openjdk

Binary distributions are provided by different vendors for a number of supported platforms.

One of them is https://jdk.java.net/java-se-ri/19 which is maintained by Oracle:

Source: https://whichjdk.com

#2 JDK Customized by Third Parties

Amazon Corretto

https://docs.aws.amazon.com/corretto/latest/corretto-11-ug/downloads-list.html

Zulu

https://www.azul.com/downloads/zulu-community/?architecture=x86-64-bit&package=jdk

Licences OTN vs BCL

Oracle JDK 8 (aka 1.8) no longer uses BCL (Binary Code License). From April 16, 2019, Oracle JDK 8 uses the OTN (Oracle Technology Network) license, which requires you to create an Oracle account to download JDK 8 and payment!!

BCL = Oracle Binary Code License

You can use it, but you can't modify it

You agree not to sue Oracle if anything goes wrong

You can redistribute/publish it (so that you can sell products with Java embedded), but if you do, you agree to indemnify Oracle; so if someone sues you, you can't drag Oracle into it.

It's really just there to protect Oracle's intellectual property and to shield them from being sued when bugs are found.

source: https://www.quora.com/In-short-what-does-the-Oracle-Binary-Code-License-Agreement-for-Java-SE-actually-say-or-prohibit/answer/Jon-Harley

As a summary: FREE with risks and without any fault of Oracle

OTN = Oracle Technology Network License

As a summary: Opposite to BCL and FREE just for development in your laptop. For enterprises, you must PAY

OpenJDK and Oracle JDK

Both OpenJDK and Oracle JDK are created and maintained currently by Oracle only.

OpenJDK and Oracle JDK are implementations of the same Java specification passed the TCK (Java Technology Certification Kit).

Most of the vendors of JDK are written on top of OpenJDK by doing a few tweaks to [mostly to replace licensed proprietary parts / replace with more high-performance items that only work on specific OS] components without breaking the TCK compatibility.

Source: Differences between Oracle JDK and OpenJDK

Free official options

Here I will list and keep updated the official links, ready to download the most used java versions

Oracle Java 1.4, 5, 6 and 7 (Deprecated)

Oracle does not show any message related to license changes for Java 1.4, 5, 6 and 7 downloads. So we can use them for development and production deployment, accepting issues and security problems because these versions are so ancient!!

Oracle downloads:

https://www.oracle.com/java/technologies/java-archive-javase-v14-downloads.html

https://www.oracle.com/java/technologies/java-archive-javase5-downloads.html

https://www.oracle.com/java/technologies/javase-java-archive-javase6-downloads.html

https://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html

Legacy versions prior to 7, does not have and will not have any update. Maybe a sales contact could be a solution if your have a Legacy Systems running over this java old versions.

Oracle Java 8 update 202

Just Java SE 8 JDK 8u202 and earlier versions are free for development and production deployment. You can download it from:

https://www.oracle.com/java/technologies/javase/javase8-archive-downloads.html

Openjdk 8 (Deprecated)

OpenJDK is a ORACLE initiative. More details here: https://adoptopenjdk.net/

compressed mode

You can download the latest v8 release from here. Latest version:

https://github.com/AdoptOpenJDK/openjdk8-upstream-binaries/releases/download/jdk8u292-b10/OpenJDK8U-jdk_x64_windows_8u292b10.zip

https://github.com/AdoptOpenJDK/openjdk8-upstream-binaries/releases/download/jdk8u292-b10/OpenJDK8U-jdk_x64_linux_8u292b10.tar.gz

I can't find the version for osx :(

Follow this to download using curl

install mode

```<code>apt-get install openjdk-8-jre (just run apps)
apt-get install openjdk-8-jdk (develop and run)
</code>```

From https://openjdk.java.net/install/

Openjdk 11

https://jdk.java.net/java-se-ri/11

https://github.com/AdoptOpenJDK/openjdk11-binaries/releases

```<code>apt-get update
apt-get install openjdk-11-jdk
</code>```

Openjdk 17

https://jdk.java.net/java-se-ri/17

Openjdk 19

https://jdk.java.net/java-se-ri/19

Free From Trusted Third Parties

Zulu Community (Java 6,7,8,11,13,14,15)

https://www.azul.com/downloads/zulu-community/?architecture=x86-64-bit&package=jdk

Amazon Corretto (Java 11)

https://docs.aws.amazon.com/corretto/latest/corretto-11-ug/downloads-list.html

Eclipse OpenJ9

https://www.eclipse.org/openj9/

More third parties

The following implementations, listed in alphabetical order, are open source and free to use:

AdoptOpenJDK

Azul Zulu

Bck2Brwsr

CACAO

Codename One

DoppioJVM

GraalVM CE

HaikuVM

HotSpot

Jamiga

JamVM

Jelatine JVM

Jikes RVM (Jikes Research Virtual Machine)

JVM.go

leJOS

Maxine

Multi-OS Engine

RopeVM

uJVM

NON-FREE options

You should pay for these versions but in return you will have a lot of features suported by Oracle or another third parties

Oracle Java

https://www.oracle.com/java/technologies/downloads/

Java 19

https://www.oracle.com/java/technologies/downloads/#java19

Java 17

https://www.oracle.com/java/technologies/downloads/#java17

Java 11

https://www.oracle.com/java/technologies/downloads/#java11

Oracle Java 8 update 221

Since the java 8 update at April 16, 2019 8u221, all versions and updates for (java 8,9,10,11,14) has no cost just for personal use and development purposes. Any other use, needs a Commercial License.

https://www.oracle.com/java/technologies/javase/javase-jdk8-downloads.html latest update 251

https://www.oracle.com/java/technologies/javase/javase8u211-later-archive-downloads.html previous updates (241,231,221,212,211)

Source: https://www.baeldung.com/oracle-jdk-vs-openjdk

Proprietary Implementations

There are also other private or commercial implementations:

Azul Zing JVM

CEE-J

Excelsior JET (Discontinued)

GraalVM EE

Imsys AB

JamaicaVM (aicas)

JBlend (Aplix)

MicroJvm (IS2T – Industrial Smart Software Technology)

OJVM

PTC Perc

SAP JVM

Waratek CloudVM for Java

Source: https://www.baeldung.com/oracle-jdk-vs-openjdk

Notes

Oracle Java 9 and 10 has reached end of support.

https://stackoverflow.com/a/50333498/3957754

More References

Differences between Oracle JDK and OpenJDK

https://whichjdk.com/

https://www.openlogic.com/blog/java-experts-openjdk-vs-oracle-jdk

https://www.oracle.com/technetwork/java/javase/overview/faqs-jsp-136696.html

https://www.oracle.com/downloads/licenses/javase-license1.html

https://openjdk.java.net/projects/jdk8/

https://www.oracle.com/java/technologies/javase/8u-relnotes.html

https://gist.github.com/jrichardsz/83db09163ca9a0db4c9cd4f91cbf0598/

https://jdk.java.net/archive

Body:
Summary

If you need to have java in your production servers for free, your have two options

#1 OpenJdk

The OpenJDK is the open source reference implementation of the Java SE Specification, but it is only the source code https://github.com/openjdk

Binary distributions are provided by different vendors for a number of supported platforms.

One of them is https://jdk.java.net/java-se-ri/19 which is maintained by Oracle:

Source: https://whichjdk.com

#2 JDK Customized by Third Parties

Amazon Corretto

https://docs.aws.amazon.com/corretto/latest/corretto-11-ug/downloads-list.html

Zulu

https://www.azul.com/downloads/zulu-community/?architecture=x86-64-bit&package=jdk

Licences OTN vs BCL

Oracle JDK 8 (aka 1.8) no longer uses BCL (Binary Code License). From April 16, 2019, Oracle JDK 8 uses the OTN (Oracle Technology Network) license, which requires you to create an Oracle account to download JDK 8 and payment!!

BCL = Oracle Binary Code License

You can use it, but you can't modify it

You agree not to sue Oracle if anything goes wrong

You can redistribute/publish it (so that you can sell products with Java embedded), but if you do, you agree to indemnify Oracle; so if someone sues you, you can't drag Oracle into it.

It's really just there to protect Oracle's intellectual property and to shield them from being sued when bugs are found.

source: https://www.quora.com/In-short-what-does-the-Oracle-Binary-Code-License-Agreement-for-Java-SE-actually-say-or-prohibit/answer/Jon-Harley

As a summary: FREE with risks and without any fault of Oracle

OTN = Oracle Technology Network License

As a summary: Opposite to BCL and FREE just for development in your laptop. For enterprises, you must PAY

OpenJDK and Oracle JDK

Both OpenJDK and Oracle JDK are created and maintained currently by Oracle only.

OpenJDK and Oracle JDK are implementations of the same Java specification passed the TCK (Java Technology Certification Kit).

Most of the vendors of JDK are written on top of OpenJDK by doing a few tweaks to [mostly to replace licensed proprietary parts / replace with more high-performance items that only work on specific OS] components without breaking the TCK compatibility.

Source: Differences between Oracle JDK and OpenJDK

Free official options

Here I will list and keep updated the official links, ready to download the most used java versions

Oracle Java 1.4, 5, 6 and 7 (Deprecated)

Oracle does not show any message related to license changes for Java 1.4, 5, 6 and 7 downloads. So we can use them for development and production deployment, accepting issues and security problems because these versions are so ancient!!

Oracle downloads:

https://www.oracle.com/java/technologies/java-archive-javase-v14-downloads.html

https://www.oracle.com/java/technologies/java-archive-javase5-downloads.html

https://www.oracle.com/java/technologies/javase-java-archive-javase6-downloads.html

https://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html

Legacy versions prior to 7, does not have and will not have any update. Maybe a sales contact could be a solution if your have a Legacy Systems running over this java old versions.

Oracle Java 8 update 202

Just Java SE 8 JDK 8u202 and earlier versions are free for development and production deployment. You can download it from:

https://www.oracle.com/java/technologies/javase/javase8-archive-downloads.html

Openjdk 8 (Deprecated)

OpenJDK is a ORACLE initiative. More details here: https://adoptopenjdk.net/

compressed mode

You can download the latest v8 release from here. Latest version:

https://github.com/AdoptOpenJDK/openjdk8-upstream-binaries/releases/download/jdk8u292-b10/OpenJDK8U-jdk_x64_windows_8u292b10.zip

https://github.com/AdoptOpenJDK/openjdk8-upstream-binaries/releases/download/jdk8u292-b10/OpenJDK8U-jdk_x64_linux_8u292b10.tar.gz

I can't find the version for osx :(

Follow this to download using curl

install mode

apt-get install openjdk-8-jre (just run apps)
apt-get install openjdk-8-jdk (develop and run)

From https://openjdk.java.net/install/

Openjdk 11

https://jdk.java.net/java-se-ri/11

https://github.com/AdoptOpenJDK/openjdk11-binaries/releases

apt-get update
apt-get install openjdk-11-jdk

Openjdk 17

https://jdk.java.net/java-se-ri/17

Openjdk 19

https://jdk.java.net/java-se-ri/19

Free From Trusted Third Parties

Zulu Community (Java 6,7,8,11,13,14,15)

https://www.azul.com/downloads/zulu-community/?architecture=x86-64-bit&package=jdk

Amazon Corretto (Java 11)

https://docs.aws.amazon.com/corretto/latest/corretto-11-ug/downloads-list.html

Eclipse OpenJ9

https://www.eclipse.org/openj9/

More third parties

The following implementations, listed in alphabetical order, are open source and free to use:

AdoptOpenJDK

Azul Zulu

Bck2Brwsr

CACAO

Codename One

DoppioJVM

GraalVM CE

HaikuVM

HotSpot

Jamiga

JamVM

Jelatine JVM

Jikes RVM (Jikes Research Virtual Machine)

JVM.go

leJOS

Maxine

Multi-OS Engine

RopeVM

uJVM

NON-FREE options

You should pay for these versions but in return you will have a lot of features suported by Oracle or another third parties

Oracle Java

https://www.oracle.com/java/technologies/downloads/

Java 19

https://www.oracle.com/java/technologies/downloads/#java19

Java 17

https://www.oracle.com/java/technologies/downloads/#java17

Java 11

https://www.oracle.com/java/technologies/downloads/#java11

Oracle Java 8 update 221

Since the java 8 update at April 16, 2019 8u221, all versions and updates for (java 8,9,10,11,14) has no cost just for personal use and development purposes. Any other use, needs a Commercial License.

https://www.oracle.com/java/technologies/javase/javase-jdk8-downloads.html latest update 251

https://www.oracle.com/java/technologies/javase/javase8u211-later-archive-downloads.html previous updates (241,231,221,212,211)

Source: https://www.baeldung.com/oracle-jdk-vs-openjdk

Proprietary Implementations

There are also other private or commercial implementations:

Azul Zing JVM

CEE-J

Excelsior JET (Discontinued)

GraalVM EE

Imsys AB

JamaicaVM (aicas)

JBlend (Aplix)

MicroJvm (IS2T – Industrial Smart Software Technology)

OJVM

PTC Perc

SAP JVM

Waratek CloudVM for Java

Source: https://www.baeldung.com/oracle-jdk-vs-openjdk

Notes

Oracle Java 9 and 10 has reached end of support.

https://stackoverflow.com/a/50333498/3957754

More References

Differences between Oracle JDK and OpenJDK

https://whichjdk.com/

https://www.openlogic.com/blog/java-experts-openjdk-vs-oracle-jdk

https://www.oracle.com/technetwork/java/javase/overview/faqs-jsp-136696.html

https://www.oracle.com/downloads/licenses/javase-license1.html

https://openjdk.java.net/projects/jdk8/

https://www.oracle.com/java/technologies/javase/8u-relnotes.html

https://gist.github.com/jrichardsz/83db09163ca9a0db4c9cd4f91cbf0598/

https://jdk.java.net/archive


问:
Make socket class available to entire app
I have the following class which I will use to display an alert regardless of which page the user is on within the app.

What is the best way to make this class accessible to all pages with in the app? Do I need to include it in every page and then call it in the init method of that page?

```<code>class SocketHelper{

  connect(){
SocketIO socketIO = SocketIOManager().createSocketIO("http://someurl", "/", query: "userId=123",socketStatusCallback: _socketStatus);
socketIO.init();
socketIO.subscribe("somealert", _onReceiveAlert);
socketIO.connect();
  }

  _onReceiveAlert(){
    // todo
  }

  _socketStatus(){
    // todo
  }

}
</code>```

答: You need to follow the singleton pattern for that. You can use dependency injections to that. They make it available everywhere in the app. You can use Provider but the problem with Provider is that you will need context to do that. If you think accessing context will be a problem then use get_it package to do that.</p>

Body:
I have the following class which I will use to display an alert regardless of which page the user is on within the app.

What is the best way to make this class accessible to all pages with in the app? Do I need to include it in every page and then call it in the init method of that page?

class SocketHelper{

  connect(){
SocketIO socketIO = SocketIOManager().createSocketIO("http://someurl", "/", query: "userId=123",socketStatusCallback: _socketStatus);
socketIO.init();
socketIO.subscribe("somealert", _onReceiveAlert);
socketIO.connect();
  }

  _onReceiveAlert(){
    // todo
  }

  _socketStatus(){
    // todo
  }

}


问:
anchoring an absolute path to parent directory in shared repo
I'm working on a shared repo and am using pytest through pycharm and have a test directory structure looking something like this:

```<code>├── data
│   ├── sample_data.json
│   ├── real_data.json
│   └── __init__.py
├── my_project
│   ├── __init__.py
│   └── main.py
└── tests
    ├── conftest.py
    ├── test0.py
    ├── test_class1
    │   ├── __init__.py
    │   ├── test1.py
    │   ├── test2.py
    │   └── test3.py
    └── test_class2
        ├── __init__.py
        ├── test4.py
        ├── test5.py
        └── test6.py
</code>```

My conftest propagates the sample data using something like this:

```<code># conftest.py
from pathlib import Path

data_path = Path("/home/myusername/projects/my_project/data") # the problem line
sample_data = data_path.joinpath("sample_data.json") # json filetype is irrelevant

propagate_data(sample_data)
</code>```

This works great and allows me to call pytest from any level of the test directory and the tests find the data properly. However it's not acceptable in a shared repo because the absolute path is unique to my system.  I've tried using relative paths, but the way Pycharm invokes pytest I get a FileNotFound unless I only run tests from the top-level test/ directory.

What is the preferred way to use the Path or os.pathlib.abspath modules to always be able to find sample_data.json regardless of from which directory python3 was called?  Or, to put it another way, can you dynamically create absolute paths that are relative a project root?

答:
You could just use your conftest.py location as the base for the path calculation (provided its location is fixed relative to the project root):

conftest_path = Path(__file__)
data_path = conftest_path.parent.parent / 'data'
```

Body:
I'm working on a shared repo and am using pytest through pycharm and have a test directory structure looking something like this:

├── data
│   ├── sample_data.json
│   ├── real_data.json
│   └── __init__.py
├── my_project
│   ├── __init__.py
│   └── main.py
└── tests
    ├── conftest.py
    ├── test0.py
    ├── test_class1
    │   ├── __init__.py
    │   ├── test1.py
    │   ├── test2.py
    │   └── test3.py
    └── test_class2
        ├── __init__.py
        ├── test4.py
        ├── test5.py
        └── test6.py

My conftest propagates the sample data using something like this:

# conftest.py
from pathlib import Path

data_path = Path("/home/myusername/projects/my_project/data") # the problem line
sample_data = data_path.joinpath("sample_data.json") # json filetype is irrelevant

propagate_data(sample_data)

This works great and allows me to call pytest from any level of the test directory and the tests find the data properly. However it's not acceptable in a shared repo because the absolute path is unique to my system.  I've tried using relative paths, but the way Pycharm invokes pytest I get a FileNotFound unless I only run tests from the top-level test/ directory.

What is the preferred way to use the Path or os.pathlib.abspath modules to always be able to find sample_data.json regardless of from which directory python3 was called?  Or, to put it another way, can you dynamically create absolute paths that are relative a project root?


问:
Identifying Page Calling a Modal Page
I have a navigation bar menu button 'About' which should display the information about the page from where user has clicked on the menu bar button.

How can I pass the current :APP_PAGE_ID to this modal page, so that it shows the Page number from which page throughout the whole application the click has been made?

答:
Found the answer to my own question:

Populate Request as &APP_PAGE_ID. in Navigation Menu List Entry, like shown below:

Title: Identifying Page Calling a Modal Page


问:
How can I use custom expressions in DevArt LINQ to Entities and also use query comprehension syntax?
I've got a situation where I need to use a custom expression in a LINQ to Entities query (because I want to have custom logic that L2E wouldn't otherwise understand:

```<code>var query = db.MyTable.Where(MyPredicateExpression)
</code>```

But I'd rather use query comprehension syntax:

```<code>var query = from x in db.MyTable where [x matches the predicate of MyPredicateExpression]
</code>```

I know this is possible, because L2E supports it in other places:

```<code>var query = from x in db.MyTable where x.Length > 10
</code>```

How do they make that work?

Edit: I'm using devart's LinqConnect for Oracle, which may behave somewhat differently than Microsoft L2E.

答:
Entity Framework and LINQ to SQL do not support this scenario, because the translation of MyPredicateExpression should be added to expression tree translator.

I recommend you to create a stored function performing the predicate check and add this function to DataContext. You will be able to use a query like the following in this case:

var query = from x in db.MyTable where context.MyPredicateFunction(x.Field) select x;

Update. Here is the updated query that takes into account your comments:

```<code>int[] values = new int[] { 1, 2, 3 };
var query = from x in db.MyTable where values.Contains(x.AuditState) select x;
</code>```

Update 2. You can add a Queryable property to your context that will be obtaining the necessary set of MyTable objects as shown in the following example:

```<code>
public partial class MyDataContext {
  IQueryable<MyTable> GetSpecialTables {
    get {
      int[] values = new int[] { 1, 2, 3 };
      return this.MyTables.Where(x => values.Contains(x.AuditState));
    }
  }
}</code>```

Replace MyDataContext with the actual name of your context.

ContentLicense: CC BY-SA 3.0

Body:
I've got a situation where I need to use a custom expression in a LINQ to Entities query (because I want to have custom logic that L2E wouldn't otherwise understand:

var query = db.MyTable.Where(MyPredicateExpression)

But I'd rather use query comprehension syntax:

var query = from x in db.MyTable where [x matches the predicate of MyPredicateExpression]

I know this is possible, because L2E supports it in other places:

var query = from x in db.MyTable where x.Length > 10

How do they make that work?

Edit: I'm using devart's LinqConnect for Oracle, which may behave somewhat differently than Microsoft L2E.

Body:
Entity Framework and LINQ to SQL do not support this scenario, because the translation of MyPredicateExpression should be added to expression tree translator.

I recommend you to create a stored function performing the predicate check and add this function to DataContext. You will be able to use a query like the following in this case:

var query = from x in db.MyTable where context.MyPredicateFunction(x.Field) select x;

Update. Here is the updated query that takes into account your comments:

int[] values = new int[] { 1, 2, 3 };
var query = from x in db.MyTable where values.Contains(x.AuditState) select x;

Update 2. You can add a Queryable property to your context that will be obtaining the necessary set of MyTable objects as shown in the following example:

public partial class MyDataContext {
  IQueryable<MyTable> GetSpecialTables {
    get {
      int[] values = new int[] { 1, 2, 3 };
      return this.MyTables.Where(x => values.Contains(x.AuditState));
    }
  }
}

Replace MyDataContext with the actual name of your context.


问:
Retrieving the key for the entry from material-ui autocomplete at onSelect, instead of value
I'm using React with Material-ui and the Autocomplete component documented here - https://material-ui.com/components/autocomplete/ with downshift.

```<code>                <Downshift id="downshift-options">
                {({
                      clearSelection,
                      getInputProps,
                      getItemProps,
                      getLabelProps,
                      getMenuProps,
                      highlightedIndex,
                      inputValue,
                      isOpen,
                      openMenu,
                      selectedItem,
                  }) => {
                    const {onSelect, onBlur, onChange, onFocus, ...inputProps} = getInputProps({
                        onChange: event => {
                            if (event.target.value === '') {
                                clearSelection();
                            }
                        },
                        onSelect: event => {
                            if (event.target.id) {
                                this.props.onSelect(event.target.value);
                            }

                        },
                        onFocus: openMenu,
                        placeholder: 'Type to search',
                    });

                    return (
                        <div className={classes.container}>
                            {renderInput({
                                fullWidth: true,
                                classes,
                                label: "Assigned Rider",
                                InputLabelProps: getLabelProps({shrink: true}),
                                InputProps: {onBlur, onChange, onFocus, onSelect},
                                inputProps,
                            })}

                            <div {...getMenuProps()}>
                                {isOpen ? (
                                    <Paper className={classes.paper} square>
                                        {getSuggestions(this.props.suggestions, inputValue, {showEmpty: true}).map((suggestion, index) =>
                                            renderSuggestion({
                                                suggestion,
                                                index,
                                                itemProps: getItemProps({item: suggestion.label}),
                                                highlightedIndex,
                                                selectedItem,
                                            }),
                                        )}
                                    </Paper>
                                ) : null}
                            </div>
                        </div>
                    );
                }}
            </Downshift>
</code>```

With onSelect, I can retrieve the value of the selection. I'd like to be able to retrieve the key instead.

```<code>function renderSuggestion(suggestionProps) {
    const { suggestion, index, itemProps, highlightedIndex, selectedItem } = suggestionProps;
    const isHighlighted = highlightedIndex === index;
    const isSelected = (selectedItem || '').indexOf(suggestion.label) > -1;

    return (
        <MenuItem
            {...itemProps}
            key={suggestion.uuid}
            value={suggestion.uuid}
            selected={isHighlighted}
            component="div"
            style={{
                fontWeight: isSelected ? 500 : 400,
            }}
        >
            {suggestion.label}
        </MenuItem>
    );
}
</code>```

Here I set the uuid as the key for each selection.

My ultimate aim is to be able to make a selection and retrieve a uuid instead of the value itself.

Although I can use the value returned to match against a list of items, I want to be sure that if there end up being any duplicate entries, it doesn't cause problems.

Link to my full code for the component is here - https://github.com/theocranmore/bloodbike/blob/master/react_app/src/components/UsersSelect.js#L143

Thank you!

答:
You can retrieve the entire value and then access your desired key (option.id):</p>

```<code>const options = [
      { id: 0, value: "foo" },
      { id: 1, value: "goo" },
    ];

<Autocomplete
  options={options}
  onChange={(event, option) => {
    console.log(option.id); // 1
  }}
  renderInput={(params) => <TextField {...params} />}
/>;
</code>```

Body:
I'm using React with Material-ui and the Autocomplete component documented here - https://material-ui.com/components/autocomplete/ with downshift.

                <Downshift id="downshift-options">
                {({
                      clearSelection,
                      getInputProps,
                      getItemProps,
                      getLabelProps,
                      getMenuProps,
                      highlightedIndex,
                      inputValue,
                      isOpen,
                      openMenu,
                      selectedItem,
                  }) => {
                    const {onSelect, onBlur, onChange, onFocus, ...inputProps} = getInputProps({
                        onChange: event => {
                            if (event.target.value === '') {
                                clearSelection();
                            }
                        },
                        onSelect: event => {
                            if (event.target.id) {
                                this.props.onSelect(event.target.value);
                            }

                        },
                        onFocus: openMenu,
                        placeholder: 'Type to search',
                    });

                    return (

                            {renderInput({
                                fullWidth: true,
                                classes,
                                label: "Assigned Rider",
                                InputLabelProps: getLabelProps({shrink: true}),
                                InputProps: {onBlur, onChange, onFocus, onSelect},
                                inputProps,
                            })}

                                {isOpen ? (
                                    <Paper className={classes.paper} square>
                                        {getSuggestions(this.props.suggestions, inputValue, {showEmpty: true}).map((suggestion, index) =>
                                            renderSuggestion({
                                                suggestion,
                                                index,
                                                itemProps: getItemProps({item: suggestion.label}),
                                                highlightedIndex,
                                                selectedItem,
                                            }),
                                        )}
                                    </Paper>
                                ) : null}

                    );
                }}
            </Downshift>

With onSelect, I can retrieve the value of the selection. I'd like to be able to retrieve the key instead.

function renderSuggestion(suggestionProps) {
    const { suggestion, index, itemProps, highlightedIndex, selectedItem } = suggestionProps;
    const isHighlighted = highlightedIndex === index;
    const isSelected = (selectedItem || '').indexOf(suggestion.label) > -1;

    return (
        <MenuItem
            {...itemProps}
            key={suggestion.uuid}
            value={suggestion.uuid}
            selected={isHighlighted}
            component="div"
            style={{
                fontWeight: isSelected ? 500 : 400,
            }}
        >
            {suggestion.label}
        </MenuItem>
    );
}

Here I set the uuid as the key for each selection.

My ultimate aim is to be able to make a selection and retrieve a uuid instead of the value itself.

Although I can use the value returned to match against a list of items, I want to be sure that if there end up being any duplicate entries, it doesn't cause problems.

Link to my full code for the component is here - https://github.com/theocranmore/bloodbike/blob/master/react_app/src/components/UsersSelect.js#L143

Thank you!

Body:
You can retrieve the entire value and then access your desired key (option.id):

const options = [
      { id: 0, value: "foo" },
      { id: 1, value: "goo" },
    ];

<Autocomplete
  options={options}
  onChange={(event, option) => {
    console.log(option.id); // 1
  }}
  renderInput={(params) => <TextField {...params} />}
/>;


问:
Take data from List<class> and put it in to String object
I'm making an java simple app for better code learning that combine some gui on intellji.

I already have a main page and I'm just trying to make a popup Table That have all the data on my product this is my tableView CODE:

```<code>public class ProductTable extends JFrame
{
    private Model.product product;
    private List<product> list;

    public ProductTable() {
        list = product.ProductList();

        // headers for the table
        String[] columns = {"Product Name",
                "Quantity",
                "Expiration day",
                "Need fridge"};
        Object[][] data = new Object[][] {
        };

        // create table with data
        JTable table = new JTable(data, columns);

        // add the table to the frame
        this.add(new JScrollPane(table));
        this.setTitle("ProductList");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.pack();
        this.setVisible(true);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ProductTable();
            }
        });
    }
}
</code>```

In the Product class I have:

```<code>product.name = String
product.quantity = int
Product.Expiration_day = String
product.fridge = boolean
</code>```

I want to load into the String Object

```<code>Data={ {product.name, product.quantity, Product.Expiration_day, Product.fridge} ,{.....,....,....,...}{..............}};
</code>```

till i put in all off my data now i know how to know the size but i need load it one by one into the data object please can anyone guide through it?!

My Product code:

```<code>package Model;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class product
{
    private String product_name;
    private Integer product_quantity;
    private String experation_day;
    private boolean fridge = false;
    private boolean matched= false;
    private Connection connection;

    public product()
    {
        this.product_name = "";
        this.product_quantity = 0;
        this.experation_day = "";
    }

    public product(String product_name, Integer product_quantity, String experation_day) {
        this.product_name = product_name;
        this.product_quantity = product_quantity;
        this.experation_day = experation_day;
    }

    public Integer getProduct_quantity() {
        return product_quantity;
    }

    public String getExperation_day() {
        return experation_day;
    }

    public String getProduct_name()
    {
        return product_name;
    }

    public void setProduct_quantity(Integer product_quantity) {
        this.product_quantity = product_quantity;
    }

    public void setExperation_day(String experation_day) {
        this.experation_day = experation_day;
    }

    public void setProduct_name(String product_name)
    {
        this.product_name = product_name;
    }

    public List<product> ProductList() {

        String windownsUserName = System.getProperty("user.name");
        try
        {
            System.out.println("Connecting to a selected database...");
            Connection connection = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\"+windownsUserName+"\\IdeaProjects\\Software-engineer-final-project\\untitled\\src\\DButills\\account.db");
            System.out.println("Connected database successfully...");
            String sqlQuery = "SELECT product_name, product_amount, product_expration_date FROM products";
            PreparedStatement ps = connection.prepareStatement(sqlQuery);
            ResultSet rs = ps.executeQuery();
            {

            }
            List<product> products = new ArrayList<>();
            while (rs.next()) {
                product product = new product();
                product.setProduct_quantity(rs.getInt("product_amount"));
                product.setProduct_name(rs.getString("product_name"));
                product.setExperation_day(rs.getString("product_expration_date"));
                products.add(product);
            }
            return products;

        } catch (SQLException e) {
            System.out.println("Query failed: " + e.getMessage());
            return null;
        }
    }
}
</code>```

答:
```<code>'package viewer;
</code>```

import Model.product;

import javax.swing.*;

import java.awt.*;

import java.util.List;

public class ProductTable extends JFrame

{
    private Model.product product;

```<code>private Container c;

private JTable table;

Object[] mdata;

private List<product> list;

String[] columns = {"Product Name", "Quantity", "Expiration day"};  //headers for the table
int i=1;
</code>```

private Object[][] data = new Object[][] { };

```<code>public ProductTable()
{
    list=product.ProductList();
   while(i<=list.size()) {

       mdata = new Object[]{list.get(i).getProduct_name(), list.get(i).getExperation_day(), list.get(i).getProduct_quantity().toString()};

       data[0][i]=mdata[0];

       data[1][i]=mdata[1];

       data[2][i]=mdata[2];

       i++;
   }

    //create table with data

    JTable table = new JTable(data, columns);

  //add the table to the frame

    this.setTitle("ProductList");

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    setVisible(true);
}
</code>```

}'

Body:
I'm making an java simple app for better code learning that combine some gui on intellji.

I already have a main page and I'm just trying to make a popup Table That have all the data on my product this is my tableView CODE:

public class ProductTable extends JFrame
{
    private Model.product product;
    private List<product> list;

    public ProductTable() {
        list = product.ProductList();

        // headers for the table
        String[] columns = {"Product Name",
                "Quantity",
                "Expiration day",
                "Need fridge"};
        Object[][] data = new Object[][] {
        };

        // create table with data
        JTable table = new JTable(data, columns);

        // add the table to the frame
        this.add(new JScrollPane(table));
        this.setTitle("ProductList");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.pack();
        this.setVisible(true);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ProductTable();
            }
        });
    }
}

In the Product class I have:

product.name = String
product.quantity = int
Product.Expiration_day = String
product.fridge = boolean

I want to load into the String Object

Data={ {product.name, product.quantity, Product.Expiration_day, Product.fridge} ,{.....,....,....,...}{..............}};

till i put in all off my data now i know how to know the size but i need load it one by one into the data object please can anyone guide through it?!

My Product code:

package Model;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class product
{
    private String product_name;
    private Integer product_quantity;
    private String experation_day;
    private boolean fridge = false;
    private boolean matched= false;
    private Connection connection;

    public product()
    {
        this.product_name = "";
        this.product_quantity = 0;
        this.experation_day = "";
    }

    public product(String product_name, Integer product_quantity, String experation_day) {
        this.product_name = product_name;
        this.product_quantity = product_quantity;
        this.experation_day = experation_day;
    }

    public Integer getProduct_quantity() {
        return product_quantity;
    }

    public String getExperation_day() {
        return experation_day;
    }

    public String getProduct_name()
    {
        return product_name;
    }

    public void setProduct_quantity(Integer product_quantity) {
        this.product_quantity = product_quantity;
    }

    public void setExperation_day(String experation_day) {
        this.experation_day = experation_day;
    }

    public void setProduct_name(String product_name)
    {
        this.product_name = product_name;
    }

    public List<product> ProductList() {

        String windownsUserName = System.getProperty("user.name");
        try
        {
            System.out.println("Connecting to a selected database...");
            Connection connection = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\"+windownsUserName+"\\IdeaProjects\\Software-engineer-final-project\\untitled\\src\\DButills\\account.db");
            System.out.println("Connected database successfully...");
            String sqlQuery = "SELECT product_name, product_amount, product_expration_date FROM products";
            PreparedStatement ps = connection.prepareStatement(sqlQuery);
            ResultSet rs = ps.executeQuery();
            {

            }
            List<product> products = new ArrayList<>();
            while (rs.next()) {
                product product = new product();
                product.setProduct_quantity(rs.getInt("product_amount"));
                product.setProduct_name(rs.getString("product_name"));
                product.setExperation_day(rs.getString("product_expration_date"));
                products.add(product);
            }
            return products;

        } catch (SQLException e) {
            System.out.println("Query failed: " + e.getMessage());
            return null;
        }
    }
}

Body:
'package viewer;

import Model.product;

import javax.swing.*;

import java.awt.*;

import java.util.List;

public class ProductTable extends JFrame

{
    private Model.product product;

private Container c;

private JTable table;

Object[] mdata;

private List<product> list;

String[] columns = {"Product Name", "Quantity", "Expiration day"};  //headers for the table
int i=1;

private Object[][] data = new Object[][] { };

public ProductTable()
{
    list=product.ProductList();
   while(i<=list.size()) {

       mdata = new Object[]{list.get(i).getProduct_name(), list.get(i).getExperation_day(), list.get(i).getProduct_quantity().toString()};

       data[0][i]=mdata[0];

       data[1][i]=mdata[1];

       data[2][i]=mdata[2];

       i++;
   }

    //create table with data

    JTable table = new JTable(data, columns);

  //add the table to the frame

    this.setTitle("ProductList");

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    setVisible(true);
}

}'


问:
Multithread celery worker for task division
Im currently building an application that, based on some input, runs some scans.

The issue i'm encountering is that a bottleneck is being creating on some of the scans, I was wondering if there was a way to implement a different thread/worker for these tasks.

I'll ellaborate a little bit more.

I start my worker with the command

pipenv run celery -A proj worker -B -l info

```<code>### Tasks.py ###

@shared_task
def short_task_1():
    return

@shared_task
def short_task_2():
    return

@shared_task
def long_task_1():
    return
</code>```

```<code>### handler.py ###
def handle_scan():
    short_task_1.delay()
    short_task_2.delay()
    long_task_1.delay()
</code>```

A possible solution I find is assigning the short tasks to one worker and the longer ones to the other. But I cant find in the docs how to define which worker the task is assigned to with the delay() command.

Will having another worker for handling this tasks help? If another thread is the solution, whats the best way of doing it?

答:
I ended up doing the following

delay() does not work if you are trying to use multiple task queues. Mainly because delay() is only used if the "default" queue is used. For using multiple queues, apply_async() must be used.

For example, if a task was called with .delay(arg1, arg2)
Now (With multiple queues in mind) it needs to be called with .apply_async(args=[arg1,arg2], queue='queue_name')

So, here is how I did it finally, thanks to @DejanLekic
tasks.py

```<code>@shared_task
def short_task_1():
    return

@shared_task
def short_task_2():
    return

@shared_task
def long_task_1():
    return
</code>```

Same as before. But here is the new handler

```<code>def handle_scan():
    # Fast queue with args if required
    short_task_1.apply_async(args=[arg1, arg2], queue='fast_queue')
    short_task_2.apply_async(args=[arg1, arg2], queue='fast_queue')
    # slow queue
    long_task_1.apply_async(args=[arg1, arg2], queue='slow_queue')
</code>```

I start the workers by doing the following (mind the pipenv):

```<code>pipenv run celery -A proj worker -B --loglevel=info -Q slow_queue,fast_queue
</code>```

Body:
Im currently building an application that, based on some input, runs some scans.

The issue i'm encountering is that a bottleneck is being creating on some of the scans, I was wondering if there was a way to implement a different thread/worker for these tasks.

I'll ellaborate a little bit more.

I start my worker with the command

pipenv run celery -A proj worker -B -l info

### Tasks.py ###

@shared_task
def short_task_1():
    return

@shared_task
def short_task_2():
    return

@shared_task
def long_task_1():
    return

### handler.py ###
def handle_scan():
    short_task_1.delay()
    short_task_2.delay()
    long_task_1.delay()

A possible solution I find is assigning the short tasks to one worker and the longer ones to the other. But I cant find in the docs how to define which worker the task is assigned to with the delay() command.

Will having another worker for handling this tasks help? If another thread is the solution, whats the best way of doing it?

Body:
I ended up doing the following

delay() does not work if you are trying to use multiple task queues. Mainly because delay() is only used if the "default" queue is used. For using multiple queues, apply_async() must be used.

For example, if a task was called with .delay(arg1, arg2)
Now (With multiple queues in mind) it needs to be called with .apply_async(args=[arg1,arg2], queue='queue_name')

So, here is how I did it finally, thanks to @DejanLekic
tasks.py

@shared_task
def short_task_1():
    return

@shared_task
def short_task_2():
    return

@shared_task
def long_task_1():
    return

Same as before. But here is the new handler

def handle_scan():
    # Fast queue with args if required
    short_task_1.apply_async(args=[arg1, arg2], queue='fast_queue')
    short_task_2.apply_async(args=[arg1, arg2], queue='fast_queue')
    # slow queue
    long_task_1.apply_async(args=[arg1, arg2], queue='slow_queue')

I start the workers by doing the following (mind the pipenv):

pipenv run celery -A proj worker -B --loglevel=info -Q slow_queue,fast_queue


问:
C# UML diagram interpretation
i dot an understanding question, im new in programming c# and dont know if i interpreted the uml right.

My suggestion for class Tree:

```<code>public class Tree<T>:Elements{

public int create(){
   //code
   return 1;
}

public int invicible(){
    return 1;
    //code

}

}

</code>```

Am i on the right way?

Thanks for help

答:
The diagram does not follow UML notation, so it is difficult to say how to implement it in C#.

You consider Tree to be a generic class, but this is not the case in the diagram. The UML notation for class Tree<T> ... {...} is  :

Also the used arrow does not represent a generalization/realization, and this enforced by the presence of the multiplicity "*" even it is strangely placed.

Even that does not follow UML notation note also in diagram there is <T extends Element> not compatible with your inheritance, but specifying a restriction to T

Title: C# UML diagram interpretation

Body:
i dot an understanding question, im new in programming c# and dont know if i interpreted the uml right.

My suggestion for class Tree:

public class Tree<T>:Elements{

public int create(){
   //code
   return 1;
}

public int invicible(){
    return 1;
    //code

}

}

Am i on the right way?

Thanks for help


问:
Require Input.Toggle's to be Checked True Before Submitting?
I have the following adaptive card JSON code that has three Input.Toggle's. Is there a way to throw an error when the user clicks "Submit" and all three Input.Toggle's are not set to true? I saw in the Schema Explorer (Schema Explorer Input.Toggle) that they have Inherited properties called "fallback" and "requires", is that what I need? If so, how do I implement "fallback" and "requires" into this JSON code?</p>

```<code>{
    "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
    "type": "AdaptiveCard",
    "version": "1.2",
    "body": [
        {
            "placeholder": "1.1 Business Office Coordinator - RFQ Receipt",
            "type": "Input.Text",
            "id": "Title"
        },
        {
            "text": "Quote #@{body('Get_response_details')?['b194cde8837234ccc80fu5017c1b0f869']} ",
            "type": "TextBlock",
            "id": "textBlock1"
        },
        {
            "type": "Input.Toggle",
            "title": "Customer Acknowledgement",
            "valueOn": "custYes",
            "valueOff": "custNo",
            "id": "Customer"
        },
        {
            "type": "Input.Toggle",
            "title": "Create RFQ Log Number and Enter Information into RFQ Log",
            "valueOn": "RFQYes",
            "valueOff": "RFQNo",
            "id": "RFQ"
        },
        {
            "type": "Input.Toggle",
            "title": "Populate Quote Folder with Customer Data",
            "valueOn": "PopulateYes",
            "valueOff": "PopulateNo",
            "id": "Populate"
        }
    ],
    "actions": [
        {
            "type": "Action.Submit",
            "title": "Submit",
            "data": {
                "id": "9876543210"
            }
        }
    ]
}
</code>```

答:
this is part of input validation which as of today is not available yet.

I'm afraid what you're asking for is not possible right now but will hopefully be soon.

You can follow the feature request here: https://portal.productboard.com/adaptivecards/1-adaptive-cards-features/c/21-input-validation-and-evolution , add your own vote to it aswell if you want to.

Depending on where you use the card however, you can get this working. In MS Teams you could verify the card submission in your own code and return an error. Its not client side but that way you can still do the check.

Body:
I have the following adaptive card JSON code that has three Input.Toggle's. Is there a way to throw an error when the user clicks "Submit" and all three Input.Toggle's are not set to true? I saw in the Schema Explorer (Schema Explorer Input.Toggle) that they have Inherited properties called "fallback" and "requires", is that what I need? If so, how do I implement "fallback" and "requires" into this JSON code?

{
    "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
    "type": "AdaptiveCard",
    "version": "1.2",
    "body": [
        {
            "placeholder": "1.1 Business Office Coordinator - RFQ Receipt",
            "type": "Input.Text",
            "id": "Title"
        },
        {
            "text": "Quote #@{body('Get_response_details')?['b194cde8837234ccc80fu5017c1b0f869']} ",
            "type": "TextBlock",
            "id": "textBlock1"
        },
        {
            "type": "Input.Toggle",
            "title": "Customer Acknowledgement",
            "valueOn": "custYes",
            "valueOff": "custNo",
            "id": "Customer"
        },
        {
            "type": "Input.Toggle",
            "title": "Create RFQ Log Number and Enter Information into RFQ Log",
            "valueOn": "RFQYes",
            "valueOff": "RFQNo",
            "id": "RFQ"
        },
        {
            "type": "Input.Toggle",
            "title": "Populate Quote Folder with Customer Data",
            "valueOn": "PopulateYes",
            "valueOff": "PopulateNo",
            "id": "Populate"
        }
    ],
    "actions": [
        {
            "type": "Action.Submit",
            "title": "Submit",
            "data": {
                "id": "9876543210"
            }
        }
    ]
}


问:
Error converting html to pdf with dompdf: Fatal error: Uncaught ImagickException: NoDecodeDelegateForThisImageFormat
I have a script that convert an html code with jpg and png images in PDF. Until this morning all worked right. After, without doing anything to the script or to the server it stop working and return this error:

```<code>Fatal error: Uncaught ImagickException: NoDecodeDelegateForThisImageFormat `/tmp/ca_dompdf_img_AFNf9n' @ error/constitute.c/ReadImage/544 in /var/www/vhosts/mysite.it/httpdocs/ldv/dompdf/lib/Cpdf.php:4862 Stack trace: #0 /var/www/vhosts/mysite.it/httpdocs/ldv/dompdf/lib/Cpdf.php(4862): Imagick->__construct('/tmp/ca_dompdf_...') #1 /var/www/vhosts/mysite.it/httpdocs/ldv/dompdf/lib/Cpdf.php(4984): Cpdf->addImagePngAlpha('/tmp/ca_dompdf_...', 499.0142519685, 739.6242519685, 75, 75, 3) #2 /var/www/vhosts/mysite.it/httpdocs/ldv/dompdf/src/Adapter/CPDF.php(845): Cpdf->addPngFromFile('/tmp/ca_dompdf_...', 499.0142519685, 739.6242519685, 75, 75) #3 /var/www/vhosts/mysite.it/httpdocs/ldv/dompdf/src/Renderer/Image.php(110): Dompdf\Adapter\CPDF->image('/tmp/ca_dompdf_...', 499.0142519685, 27.265748031496, 75, 75, 'normal') #4 /var/www/vhosts/mysite.it/httpdocs/ldv/dompdf/src/Renderer.php(293): Dompdf\Renderer\Image->render(Object(Dompdf\FrameDecorator\Image)) #5 /var/www/vhosts/mysite.it/httpdocs/ldv/dompdf/src/ in /var/www/vhosts/mysite.it/httpdocs/ldv/dompdf/lib/Cpdf.php on line 4862
</code>```

What may have happened?

答:
Restart php. Make sure you restart the exact php version you run the project with. For example in Laravel you can find it on composer.json file. Then restart Apache.

It should solve this.

Body:
I have a script that convert an html code with jpg and png images in PDF. Until this morning all worked right. After, without doing anything to the script or to the server it stop working and return this error:

Fatal error: Uncaught ImagickException: NoDecodeDelegateForThisImageFormat `/tmp/ca_dompdf_img_AFNf9n' @ error/constitute.c/ReadImage/544 in /var/www/vhosts/mysite.it/httpdocs/ldv/dompdf/lib/Cpdf.php:4862 Stack trace: #0 /var/www/vhosts/mysite.it/httpdocs/ldv/dompdf/lib/Cpdf.php(4862): Imagick->__construct('/tmp/ca_dompdf_...') #1 /var/www/vhosts/mysite.it/httpdocs/ldv/dompdf/lib/Cpdf.php(4984): Cpdf->addImagePngAlpha('/tmp/ca_dompdf_...', 499.0142519685, 739.6242519685, 75, 75, 3) #2 /var/www/vhosts/mysite.it/httpdocs/ldv/dompdf/src/Adapter/CPDF.php(845): Cpdf->addPngFromFile('/tmp/ca_dompdf_...', 499.0142519685, 739.6242519685, 75, 75) #3 /var/www/vhosts/mysite.it/httpdocs/ldv/dompdf/src/Renderer/Image.php(110): Dompdf\Adapter\CPDF->image('/tmp/ca_dompdf_...', 499.0142519685, 27.265748031496, 75, 75, 'normal') #4 /var/www/vhosts/mysite.it/httpdocs/ldv/dompdf/src/Renderer.php(293): Dompdf\Renderer\Image->render(Object(Dompdf\FrameDecorator\Image)) #5 /var/www/vhosts/mysite.it/httpdocs/ldv/dompdf/src/ in /var/www/vhosts/mysite.it/httpdocs/ldv/dompdf/lib/Cpdf.php on line 4862

What may have happened?


问:
How to make Google OR Tools Deploy More Vehicle
I am working on a VRP project using Google OR-Tools with Python.

Currently, I have a tight time windows constraints, high demands, and the capacity of the vehicles.
When I run the solver, the solver always chooses to deploy the vehicle that has the biggest capacity.
Can I make the solver deploy the smaller vehicle even though it will deploy more vehicles? Because in reality deploying bigger vehicles will cost higher.

And is there any function inside that can allow re-departure of vehicle?

Thank you!

答:
1) You can set a fixed cost for each vehicle.

ref: https://github.com/google/or-tools/blob/5ff76b487a6c2006326765d6417964599eedc8c9/ortools/constraint_solver/routing.h#L844-L848

2) to "redeploy" you can duplicate the depot and use "reload".

see: https://github.com/google/or-tools/blob/master/ortools/constraint_solver/samples/cvrp_reload.py


问:
Class constructor in C#
I am somewhat of a C# noob, and have been looking around in documentation but have been unable to understand how to create a constructor method for my class as I would in python.

Say I have a class named Vehicle, and when I create an instance of vehicle, I need to input the number of wheels and the number of axles the vehicles has. I want the constructor to divide the total wheels by the total axles to set the property wheelsPerAxle:

```<code>public class Vehicle
{
    public int numWheels;
    public int numAxles;
    public int wheelsPerAxle;

    public Vehicle()
    {
        wheelsPerAxle = Mathf.CeilToInt(numWheels/numAxles);
    }

}
</code>```

My code example is a little ridiculous but hopefully you get the idea that I want to call the method when the object is instantiated. How can I do this?

答:
You mentioned Property, but what you have there are fields. Please read this answer to understand the difference.
So I assumed that you really need property in my code:

The first solution is assuming that WheelsPerAxle is readonly property.

```<code>public class Vehicle
{
    public int NumWheels { get; set; }
    public int NumAxles { get; set; }

    //if you want to have it as readonly
   public int WheelsPerAxle => Mathf.CeilToInt(NumWheels / NumAxles);

    public Vehicle(int numWheels, int numAxles)
    {
        NumWheels = numWheels;
        NumAxles = numAxles;
    }

}
</code>```

and second solution is assuming WheelsPerAxle has a setter

```<code>public class Vehicle
{
    public int NumWheels { get; set; }
    public int NumAxles { get; set; }

    //if you want to set it later on and change its value
    public int WheelsPerAxle { get; set; }

    public Vehicle(int numWheels, int numAxles)
    {
        NumWheels = numWheels;
        NumAxles = numAxles;
        WheelsPerAxle = Mathf.CeilToInt(NumWheels / NumAxles);
    }

}
</code>```

Make sure to add some validations.

Title: Class constructor in C#

Body:
I am somewhat of a C# noob, and have been looking around in documentation but have been unable to understand how to create a constructor method for my class as I would in python.

Say I have a class named Vehicle, and when I create an instance of vehicle, I need to input the number of wheels and the number of axles the vehicles has. I want the constructor to divide the total wheels by the total axles to set the property wheelsPerAxle:

public class Vehicle
{
    public int numWheels;
    public int numAxles;
    public int wheelsPerAxle;

    public Vehicle()
    {
        wheelsPerAxle = Mathf.CeilToInt(numWheels/numAxles);
    }

}

My code example is a little ridiculous but hopefully you get the idea that I want to call the method when the object is instantiated. How can I do this?

Body:
You mentioned Property, but what you have there are fields. Please read this answer to understand the difference.
So I assumed that you really need property in my code:

The first solution is assuming that WheelsPerAxle is readonly property.

public class Vehicle
{
    public int NumWheels { get; set; }
    public int NumAxles { get; set; }

    //if you want to have it as readonly
   public int WheelsPerAxle => Mathf.CeilToInt(NumWheels / NumAxles);

    public Vehicle(int numWheels, int numAxles)
    {
        NumWheels = numWheels;
        NumAxles = numAxles;
    }

}

and second solution is assuming WheelsPerAxle has a setter

public class Vehicle
{
    public int NumWheels { get; set; }
    public int NumAxles { get; set; }

    //if you want to set it later on and change its value
    public int WheelsPerAxle { get; set; }

    public Vehicle(int numWheels, int numAxles)
    {
        NumWheels = numWheels;
        NumAxles = numAxles;
        WheelsPerAxle = Mathf.CeilToInt(NumWheels / NumAxles);
    }

}

Make sure to add some validations.


问:
How do I add to a section in a line in JSON (python)?
I was wondering how I would add to a certain parameter of a JSON line with python. For example, here is my python:

import json

file = open('jsonusers.json', 'r+')
read = file.read()
y = json.loads(read)
users = y["people"]
lines = [person for person in users if person["id"] == 457775659998248960]
for i in lines:
    print(i)
```

<p>and here is my JSON file: </p>

```{"people": [{"id": 580040383883378710, "coins": 0}, {"id": 457775659998248960, "coins": 0}, {"id": 630506515484377099, "coins": 0}]}
```

If I wanted to add 1 to the coins of 457775659998248960, how would I do that then update it to the JSON file?

答:
You can open the file in a context manager, load it into a variable, then iterate through the list, increment the value of a given key, and then write it back in:

with open("jsonusers.json", "r") as fp:
    data = json.load(fp)

for person in data["people"]:
    if person["id"] == 457775659998248960:
        person["coins"] += 1

with open("jsonusers.json", "w+") as fp:
    json.dump(data, fp, sort_keys=True, indent=4) # kwargs are for beautification
```

References:

File context managers

Body:
I was wondering how I would add to a certain parameter of a JSON line with python. For example, here is my python:

import json

file = open('jsonusers.json', 'r+')
read = file.read()
y = json.loads(read)
users = y["people"]
lines = [person for person in users if person["id"] == 457775659998248960]
for i in lines:
    print(i)

and here is my JSON file:

{"people": [{"id": 580040383883378710, "coins": 0}, {"id": 457775659998248960, "coins": 0}, {"id": 630506515484377099, "coins": 0}]}

If I wanted to add 1 to the coins of 457775659998248960, how would I do that then update it to the JSON file?

Body:
You can open the file in a context manager, load it into a variable, then iterate through the list, increment the value of a given key, and then write it back in:

with open("jsonusers.json", "r") as fp:
    data = json.load(fp)

for person in data["people"]:
    if person["id"] == 457775659998248960:
        person["coins"] += 1

with open("jsonusers.json", "w+") as fp:
    json.dump(data, fp, sort_keys=True, indent=4) # kwargs are for beautification

References:

File context managers


问:
Kafka producing message key as STRING even though the REST program has INT?
I am using following program to produce records in kafka:

```<code>import java.io.IOException;
import java.security.SecureRandom;

public class SensorStatusProducer {
  private final static String TOPIC = "SENSOR_STATUS_DETAILS";
  private final static String PRODUCER_URI = "http://xxx.xxx.xxx.xxx:8082/topics/" + TOPIC;
  private final static SecureRandom randomNumber = new SecureRandom();
  private final static SensorDetails sensorDetails = new SensorDetails();

  public static void main(String[] args) {
    int[] sensorid = sensorDetails.getSensorid(); //this will return [1001,1002,1003,1004,1005]
    try {
      HttpRestProxyUtil rest = new HttpRestProxyUtil(); //this is defined in another class
      for (int sid : sensorid) {
        rest.produceRecords(PRODUCER_URI, String.format("{\"records\":[{\"key\": %d," +
          "\"value\":{" +
          "\"sensorid\":%d," +
          "\"status\":%s," +
          "\"lastconnectedtime\":%s}}]}", sid, sid, "\"CONNECTED\"", String.format("\"%s\"", sensorDetails.currentTimestamp()))); //currentTimestamp() function in defined in another class
      }
    } catch (InterruptedException | IOException me) {
      me.printStackTrace();
    }
  }
}
</code>```

The key has format specifier as %d but the record produced has key of STRING type.

This is evident by following:

When trying to make table:

```<code>CREATE TABLE STATUS_IB_TABLE (ROWKEY INT KEY,
  sensorid INTEGER,
  status VARCHAR,
  lastconnectedtime STRING)
WITH (TIMESTAMP='lastconnectedtime', TIMESTAMP_FORMAT='yyyy-MM-dd HH:mm:ss', KAFKA_TOPIC='SENSOR_STATUS_DETAILS', VALUE_FORMAT='JSON', KEY='sensorid');
</code>```

The KEY is serialized as STRING as pointed out by @Andrew Coates

I don't know how's that possible.

can someone please clarify this for me, what am I doing wrong?

PS:

=> this is a follow up question for my earlier question ksqlDB not taking rowkey properly

=> Confluent Platform version: 5.5

=> This is the main class of the program.

答:
The REST Proxy supports various content types, but not including the primitive type to write a serialized 32-bit integer.

Your code is thus producing data to the topic with a string key. For an example of how to produce an INT see the example here which uses kafkacat.

Since you're using Java, you could use the native Java Producer API to control exactly how the data is produced to Kafka (which is also more performant and flexible than the REST API).

Body:
I am using following program to produce records in kafka:

import java.io.IOException;
import java.security.SecureRandom;

public class SensorStatusProducer {
  private final static String TOPIC = "SENSOR_STATUS_DETAILS";
  private final static String PRODUCER_URI = "http://xxx.xxx.xxx.xxx:8082/topics/" + TOPIC;
  private final static SecureRandom randomNumber = new SecureRandom();
  private final static SensorDetails sensorDetails = new SensorDetails();

  public static void main(String[] args) {
    int[] sensorid = sensorDetails.getSensorid(); //this will return [1001,1002,1003,1004,1005]
    try {
      HttpRestProxyUtil rest = new HttpRestProxyUtil(); //this is defined in another class
      for (int sid : sensorid) {
        rest.produceRecords(PRODUCER_URI, String.format("{\"records\":[{\"key\": %d," +
          "\"value\":{" +
          "\"sensorid\":%d," +
          "\"status\":%s," +
          "\"lastconnectedtime\":%s}}]}", sid, sid, "\"CONNECTED\"", String.format("\"%s\"", sensorDetails.currentTimestamp()))); //currentTimestamp() function in defined in another class
      }
    } catch (InterruptedException | IOException me) {
      me.printStackTrace();
    }
  }
}

The key has format specifier as %d but the record produced has key of STRING type.

This is evident by following:

When trying to make table:

CREATE TABLE STATUS_IB_TABLE (ROWKEY INT KEY,
  sensorid INTEGER,
  status VARCHAR,
  lastconnectedtime STRING)
WITH (TIMESTAMP='lastconnectedtime', TIMESTAMP_FORMAT='yyyy-MM-dd HH:mm:ss', KAFKA_TOPIC='SENSOR_STATUS_DETAILS', VALUE_FORMAT='JSON', KEY='sensorid');

The KEY is serialized as STRING as pointed out by @Andrew Coates

I don't know how's that possible.

can someone please clarify this for me, what am I doing wrong?

PS:

=> this is a follow up question for my earlier question ksqlDB not taking rowkey properly

=> Confluent Platform version: 5.5

=> This is the main class of the program.


问:
why consumer has to register with eureka server?
I am currenly learning microservices. I have two services Service A and Service B. Service A registered with Eureka server. Service B is calling Service B via Eureka server to get the response. My question is
why Service B has to register with Eureka service in order to call Service A?

Service B can get the Service A url and portno through service discovery from Eureka server. What is the significance of Service B to register with Eureka server?

答:
Typically in Microservices architecture,  we have a lot of small applications running independently together, and ofcourse they will all have their own URLs and ports.

In that scenario, it would be very cumbersome to maintain all these microservices to run in synchronization, and more importantly, with monitoring. This problem will increase manifold when we start implementing load balancers.

To solve this issue, we need a tool that will monitor and maintain the registry of all the microservices in the ecosystem.

That's why Eureka server acts as directory and service discovery system to make sure they is no direct binding between services and it make sure to have health check for those services.


答: Based on your output, it seems that antecedent and consequent are arrays or python lists. These are converted to BigQuery's arrays.

Title: Comma is generating separate rows for a particular value in a column while exporting table from pyspark cluster to BigQuery

Body:
I was exporting a spark df to bigquery by using the code below

gcs_bucket = 'main'
bq_dataset = 'table'
bq_table = 'user'

Rules.write \
  .format("bigquery") \
  .option("table","{}.{}".format(bq_dataset, bq_table)) \
  .option("temporaryGcsBucket", gcs_bucket) \
  .mode('overwrite') \
  .save()

Below is the output i was getting within the cluster

+-----------+----------+-------------------+------------------+
| antecedent|consequent|         confidence|              lift|
+-----------+----------+-------------------+------------------+
|[19, 6, 39]|      [44]|  0.418945963975984|10.602038775664845|
|[19, 6, 39]|      [35]|0.47298198799199465| 7.423073393311932|
|[19, 6, 39]|     [322]|   0.47631754503002|4.6520592549063995|
|[19, 6, 39]|     [308]| 0.4496330887258172| 5.856259667533207|
|[19, 6, 39]|     [345]| 0.5196797865243495|5.4970336458402285|

when exported the above df to bigquery, i am getting the table in the below format. Why is that? and how can i fix it?


问:
Turning an ASP.NET Website into an AJAX-Enabled one
I have successfully downloaded and installed AJAX framework, and the control toolkit.

While trying to insert any AJAX controls such as UpdatePanels or ScriptManagers into an existent ASP.NET Web Site (which currently has no AJAX functionalities) I get the following error:

"Attempret do read or write protected memory. This is often an indicator that other memory is corrupt."

So as a test, I've created a brand new project, as an ASP.NET AJAX-Enabled Web Site, as follows:

And in the default page of this project there is an ScriptManager already, and I've been able to insert an UpdatePanel, do a little test with a label and a button updating its content to the current time.

The question is: What does an "ASP.NET AJAX-Enabled Web Site" have that an "ASP.NET Web Site" does not that prevents me from adding AJAX controls ?

答:
Do you have more than one version of the AJAX libraries. Often times, the versions can be different between what you have set to use in the configuration file and the controls you are slapping on the page. That is the first place I would check.

You also need to make sure you have the correct version of both AJAX and the control library. This can be you downloaded an old control kit and are using the latest .NET framework, as much of the AJAX functionality has been included in .NET 4.0. Or it can be downloading newer bits and trying to use them with 2.0.


问:
Shared variables in TypeScripts just like in JS
In JS I am able to connect scripts inside HTML. Assume I have two scripts first.js and second.js, so I can make this:

```<code><script src=".../first.js"></script>
<script src=".../second.js"></script>
</code>```

and then I am able to use any variable of first.js in second.js
How to reach such a result via TypeScript keeping those scripts as separated files?

答:
As pointed out in a comment, you don't want to rely on implicitly declared shared variables. This can have some nasty side-effects and often is really hard to debug. However there are situations where there is no other way. You can use the globalThis object to share variables between different modules, as globalThis is everywhere the same object.

// module A
globalThis.myVar = 17;

// module B
console.log(globalThis.myVar);
```

You can learn more about globalThis here: MDN:globalThis

Body:
In JS I am able to connect scripts inside HTML. Assume I have two scripts first.js and second.js, so I can make this:

and then I am able to use any variable of first.js in second.js
How to reach such a result via TypeScript keeping those scripts as separated files?

Body:
As pointed out in a comment, you don't want to rely on implicitly declared shared variables. This can have some nasty side-effects and often is really hard to debug. However there are situations where there is no other way. You can use the globalThis object to share variables between different modules, as globalThis is everywhere the same object.

// module A
globalThis.myVar = 17;

// module B
console.log(globalThis.myVar);

You can learn more about globalThis here: MDN:globalThis


问:
Using flask, ajax - get response header value
I'm sending request through ajax,
sending response through Flask.

This is my code

ajax

'''

```<code>$.ajax({
    url:'/get',
    type: "post",
    data: {"hi":"hello"},
    success(function(data, textStatus, jqXHR){
        console.log(jqXHR.getResponseHeader('token'));
    })
})
</code>```

'''

Flask
'''

```<code>@app.route('/get', methods=['POST'])
def hello():
    data = {'result': 0}
    resp = make_response(data)
    resp.headers['hi'] = 123
    return resp'''
</code>```

If I run this, I can see response header ('hi', 123) in chrome inspection. But NO CONSOLE LOG.

Is there anything wrong with my code?

答:
There's no token response header in your server response, try reading hi header:

```<code>$.ajax({
    url:'/get',
    type: "post",
    data: {"hi":"hello"},
    success(function(data, textStatus, jqXHR){
        // this line:
        console.log(jqXHR.getResponseHeader('hi'));
    })
})
</code>```

Body:
I'm sending request through ajax,
sending response through Flask.

This is my code

ajax

'''

$.ajax({
    url:'/get',
    type: "post",
    data: {"hi":"hello"},
    success(function(data, textStatus, jqXHR){
        console.log(jqXHR.getResponseHeader('token'));
    })
})

'''

Flask
'''

@app.route('/get', methods=['POST'])
def hello():
    data = {'result': 0}
    resp = make_response(data)
    resp.headers['hi'] = 123
    return resp'''

If I run this, I can see response header ('hi', 123) in chrome inspection. But NO CONSOLE LOG.

Is there anything wrong with my code?

Body:
There's no token response header in your server response, try reading hi header:

$.ajax({
    url:'/get',
    type: "post",
    data: {"hi":"hello"},
    success(function(data, textStatus, jqXHR){
        // this line:
        console.log(jqXHR.getResponseHeader('hi'));
    })
})


问:
How do I call variables with similar names using a for loop?
I have the following code:

```<code>var projectNumbers = [];
projectNumbers.push(project0[0]);
projectNumbers.push(project1[0]);
projectNumbers.push(project2[0]);
projectNumbers.push(project3[0]);
projectNumbers.push(project4[0]);
projectNumbers.push(project5[0]);
</code>```

This adds 6 different numbers from other arrays to the projectNumbers array.

However, I want the code to automatically add numbers to the projectNumbers array based off the number of projects. I tried doing this using:

```<code>var projectNumbers = [];
for (var i=0;i<projects.length+1;i++{
projectNumbers.push("project"+i+"[0]")
}
</code>```

but this ended up displaying project0[0], project1[0], project2[0] etc. instead of getting the values of these and displaying 0,1,2 etc.

How can I fix this?

答:
You can use eval like this.

eval(`projectNumbers.push(project${i}[0])`);
```

<p><strong>Don't do that.</strong> You already have a projects array. Does that contain the information from project1, project2... ? If it does then you can just do</p>

```projectNumbers = projects.map((item) => {return item[0]});
```

If it doesn't you should make an array to contain your projects, then do the same thing.

Body:
I have the following code:

var projectNumbers = [];
projectNumbers.push(project0[0]);
projectNumbers.push(project1[0]);
projectNumbers.push(project2[0]);
projectNumbers.push(project3[0]);
projectNumbers.push(project4[0]);
projectNumbers.push(project5[0]);

This adds 6 different numbers from other arrays to the projectNumbers array.

However, I want the code to automatically add numbers to the projectNumbers array based off the number of projects. I tried doing this using:

var projectNumbers = [];
for (var i=0;i<projects.length+1;i++{
projectNumbers.push("project"+i+"[0]")
}

but this ended up displaying project0[0], project1[0], project2[0] etc. instead of getting the values of these and displaying 0,1,2 etc.

How can I fix this?

Body:
You can use eval like this.

eval(`projectNumbers.push(project${i}[0])`);

Don't do that. You already have a projects array. Does that contain the information from project1, project2... ? If it does then you can just do

projectNumbers = projects.map((item) => {return item[0]});

If it doesn't you should make an array to contain your projects, then do the same thing.


问:
Need assistance with if statement in Python code for SQL
If I want to filter my table using an if statement how would I go about doing this.

I have an example of what I am wanting to do but not sure how to achieve this.

I want to pull a few values based off of the fact that a customer order is active/inactive.

With my sql column being a bit value type I want to only show "orders" based off of active (column value of 0) orders.

Below is my line of code to pull part numbers, customer number, order numbers:

for row in cur:
    custOrders = CST.OrderLog(row[22], row[23], row[39])
    listofCustOrders.append(custOrders)
return listofcustOrders
```

row22 is my part number
row23 is my cust number
row39 is my cust order number

I need to sort my customer order number based off the active/inactive column (row[2]) which consists of just 0,1,NULL values.

Any ideas, I have not worked with if statements regarding a SQL connection before.

Thanks

答:
Why don't you try
cur.execute('SELECT column_name FROM table_name WHERE row[2]_column_name = ?',(variable, ))
You can set variable as 0, 1 or NULL as per your requirement. this 'cur' you can use in for loop too.

Body:
If I want to filter my table using an if statement how would I go about doing this.

I have an example of what I am wanting to do but not sure how to achieve this.

I want to pull a few values based off of the fact that a customer order is active/inactive.

With my sql column being a bit value type I want to only show "orders" based off of active (column value of 0) orders.

Below is my line of code to pull part numbers, customer number, order numbers:

for row in cur:
    custOrders = CST.OrderLog(row[22], row[23], row[39])
    listofCustOrders.append(custOrders)
return listofcustOrders

row22 is my part number
row23 is my cust number
row39 is my cust order number

I need to sort my customer order number based off the active/inactive column (row[2]) which consists of just 0,1,NULL values.

Any ideas, I have not worked with if statements regarding a SQL connection before.

Thanks


问:
How to show a TPopupMenu when you click a TButton?
I want to show a popupmenu when click a button, but this procedure has error in Delphi XE.

```<code>procedure ShowPopupMenuEx(var mb1:TMouseButton;var X:integer;var Y:integer;var pPopUP:TPopupMenu);
var
  popupPoint : TPoint;
begin
  if (mb1 = mbLeft) then begin
    popupPoint.X := x ;
    popupPoint.Y := y ;
    popupPoint := ClientToScreen(popupPoint);   //Error Here
    pPopUP.Popup(popupPoint.X, popupPoint.Y) ;
  end;
end;

procedure TForm1.Button1MouseUp(Sender: TObject; Button: TMouseButton;Shift: TShiftState; X, Y: Integer);
begin
  ShowPopupMenuEx(button,Button1.Left,Button1.Top,PopupMenu1); //Error Here
end;
</code>```

when click button show this error :

[DCC Error] Form1.pas(205): E2010 Incompatible types: 'HWND' and 'TPoint'

  [DCC Error] Form1.pas(398): E2197 Constant object cannot be passed as var parameter

  [DCC Error] Form1.pas(398): E2197 Constant object cannot be passed as var parameter

Is there any better way for show popupmenu, when click a button?

答:
Similarly for TToolButton

(Assuming TToolButton Style is tbsDropDown...)

In my experience, I find more often than not, I'd rather the drop down menu displayed when the entire button is clicked, not just the drop down arrow (⯆).

To achieve this, based on the code by @Andreas under An Alternative above,
 simply add Down := True property, as in:

procedure TForm1.ToolButton1Click(Sender: TObject);
begin
  with ToolButton1, ClientToScreen(Point(0, Height)) do
  begin
    Down := True;
    DropdownMenu.Popup(X, Y);
  end;
end;
```

This also simulates the button background display behavior.

Body:
I want to show a popupmenu when click a button, but this procedure has error in Delphi XE.

procedure ShowPopupMenuEx(var mb1:TMouseButton;var X:integer;var Y:integer;var pPopUP:TPopupMenu);
var
  popupPoint : TPoint;
begin
  if (mb1 = mbLeft) then begin
    popupPoint.X := x ;
    popupPoint.Y := y ;
    popupPoint := ClientToScreen(popupPoint);   //Error Here
    pPopUP.Popup(popupPoint.X, popupPoint.Y) ;
  end;
end;

procedure TForm1.Button1MouseUp(Sender: TObject; Button: TMouseButton;Shift: TShiftState; X, Y: Integer);
begin
  ShowPopupMenuEx(button,Button1.Left,Button1.Top,PopupMenu1); //Error Here
end;

when click button show this error :

[DCC Error] Form1.pas(205): E2010 Incompatible types: 'HWND' and 'TPoint'

  [DCC Error] Form1.pas(398): E2197 Constant object cannot be passed as var parameter

  [DCC Error] Form1.pas(398): E2197 Constant object cannot be passed as var parameter

Is there any better way for show popupmenu, when click a button?

Body:
Similarly for TToolButton

(Assuming TToolButton Style is tbsDropDown...)

In my experience, I find more often than not, I'd rather the drop down menu displayed when the entire button is clicked, not just the drop down arrow (⯆).

To achieve this, based on the code by @Andreas under An Alternative above,
 simply add Down := True property, as in:

procedure TForm1.ToolButton1Click(Sender: TObject);
begin
  with ToolButton1, ClientToScreen(Point(0, Height)) do
  begin
    Down := True;
    DropdownMenu.Popup(X, Y);
  end;
end;

This also simulates the button background display behavior.


问:
My inserts in SQL Server are slow for few tables
I have an application which inserts data into tables. I found that for 3 tables the insert of data is really slow. The schema, no. Of records etc are same in stage and my prod environment. But, the slowness is observed in prod.

I checked that index fragmentation is low and stats are up-to-date.

Schema and constraints are the same in stage and prod. But inserts are performing well in stage, but slow in prod.

It's a client's prod so I don't have access to the machine. What should I be checking now? I am planning to observe IO/ disk is good. Any ideas on what queries I should be given to the client to get to the root cause of the slowness?

答:
Any ideas on what queries I shd be given to client to get to root cause of the slowness.

Typical cause of "slow inserts in prod" is that the log volume has higher latency and you're not batching inserts into transactions.  Without a transaction, each insert statement requires a physical log flush.

The Session Wait Stats should allow you (or the DBA) to pinpoint the cause of the slowness.  Waits to flush the log file are tracked as WRITELOG waits.  This can also be caused by having a remote synchronous replica using Mirroring or Availibility Groups, which have their own wait types.


问:
IF with parameter inside native query
I have a question. If I happen to do a native query, and need to do an if within it using a parameter that will come in the call, something like this:

```<code>   case
      when :var=1 then
      inner join" +
     primeiroInnerJoin
     else " +
   inner join
   segundoInnerJoin
end
</code>```

The ":var" is a variable that will come in the call of my native query, how do I check the value of this variable and change the query depending on the value of the variable?

答: You would need to make this a stored procedure call and use dynamic SQL in the database to build the query conditionally. I don't think you can have different conditional join conditions like that in SQL.</p>

Title: IF with parameter inside native query

Body:
I have a question. If I happen to do a native query, and need to do an if within it using a parameter that will come in the call, something like this:

   case
      when :var=1 then
      inner join" +
     primeiroInnerJoin
     else " +
   inner join
   segundoInnerJoin
end

The ":var" is a variable that will come in the call of my native query, how do I check the value of this variable and change the query depending on the value of the variable?