问:
Refactor for supplier classes
I'm looking to refactor two supplier classes as they both have very similar code. One provides and ArrayList and the other a Map. They are sorted in the configuration folder but I'm not sure thats the correct place. They both load data from a text file sorted in the project folder, which doesn't feel right to me.

The two supplier classes are:

```<code>@Component
public class ModulusWeightTableSupplier implements Supplier<List>{

    private static final Logger LOGGER = LogManager.getLogger(CDLBankDetailsValidator.class);

    private static final String MODULUS_WEIGHT_TABLE = "AccountModulus_Weight_Table.txt";

    @Override
    public List<ModulusWeightTableEntry> get(){

        LOGGER.debug("Attempting to load modulus weight table " + MODULUS_WEIGHT_TABLE);
        final List<ModulusWeightTableEntry> modulusWeightTable = new ArrayList<>();

        try{
            final InputStream in = new FileInputStream(MODULUS_WEIGHT_TABLE);
            final BufferedReader br = new BufferedReader(new InputStreamReader(in));

            String line;
            while ((line = br.readLine()) != null) {
                final String[] fields = line.split("\\s+");
                modulusWeightTable.add(new ModulusWeightTableEntry(fields));
            }
            LOGGER.debug("Modulus weight table loaded");
            br.close();
        }
        catch (final IOException e) {
            throw new BankDetailsValidationRuntimeException("An error occurred loading the modulus weight table or sort code substitution table", e);
        }
        return modulusWeightTable;
    }
}
</code>```

and

```<code>@Component
public class SortCodeSubstitutionTableSupplier implements Supplier<Map> {

    private static final Logger LOGGER = LogManager.getLogger(CDLBankDetailsValidator.class);

    private static final String SORT_CODE_SUBSTITUTION_TABLE = "SCSUBTAB.txt";

    @Override
    public Map<String, String> get() {

        LOGGER.debug("Attempting to load sort code substitution table " + SORT_CODE_SUBSTITUTION_TABLE);
        final Map<String, String> sortCodeSubstitutionTable = new HashMap<>();

        try {
            final InputStream in = new FileInputStream(SORT_CODE_SUBSTITUTION_TABLE);
            final BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = br.readLine()) != null) {
                final String[] fields = line.split("\\s+");
                sortCodeSubstitutionTable.put(fields[0], fields[1]);
            }
            LOGGER.debug("Sort code substitution table loaded");
            br.close();
        }
        catch (final IOException e) {
            throw new BankDetailsValidationRuntimeException("An error occurred loading the sort code substitution table", e);
        }

        return sortCodeSubstitutionTable;
    }
}
</code>```

Both classes have a lot of duplicate code. I'm trying to work out the best way to refactor them.

答:
So your current code loads some configuration from textual files. Maybe best solution for this would be to go with properties or yaml files. This is most common approach for loading configuration data from external files.

Good starting point would be Spring Boot documentation for externalized configuration which provides information on how to use both properies and yaml files for loading configuration data in your application.

Title: Refactor for supplier classes

Body:
I'm looking to refactor two supplier classes as they both have very similar code. One provides and ArrayList and the other a Map. They are sorted in the configuration folder but I'm not sure thats the correct place. They both load data from a text file sorted in the project folder, which doesn't feel right to me.

The two supplier classes are:

@Component
public class ModulusWeightTableSupplier implements Supplier<List>{

    private static final Logger LOGGER = LogManager.getLogger(CDLBankDetailsValidator.class);

    private static final String MODULUS_WEIGHT_TABLE = "AccountModulus_Weight_Table.txt";

    @Override
    public List<ModulusWeightTableEntry> get(){

        LOGGER.debug("Attempting to load modulus weight table " + MODULUS_WEIGHT_TABLE);
        final List<ModulusWeightTableEntry> modulusWeightTable = new ArrayList<>();

        try{
            final InputStream in = new FileInputStream(MODULUS_WEIGHT_TABLE);
            final BufferedReader br = new BufferedReader(new InputStreamReader(in));

            String line;
            while ((line = br.readLine()) != null) {
                final String[] fields = line.split("\\s+");
                modulusWeightTable.add(new ModulusWeightTableEntry(fields));
            }
            LOGGER.debug("Modulus weight table loaded");
            br.close();
        }
        catch (final IOException e) {
            throw new BankDetailsValidationRuntimeException("An error occurred loading the modulus weight table or sort code substitution table", e);
        }
        return modulusWeightTable;
    }
}

and

@Component
public class SortCodeSubstitutionTableSupplier implements Supplier<Map> {

    private static final Logger LOGGER = LogManager.getLogger(CDLBankDetailsValidator.class);

    private static final String SORT_CODE_SUBSTITUTION_TABLE = "SCSUBTAB.txt";

    @Override
    public Map<String, String> get() {

        LOGGER.debug("Attempting to load sort code substitution table " + SORT_CODE_SUBSTITUTION_TABLE);
        final Map<String, String> sortCodeSubstitutionTable = new HashMap<>();

        try {
            final InputStream in = new FileInputStream(SORT_CODE_SUBSTITUTION_TABLE);
            final BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = br.readLine()) != null) {
                final String[] fields = line.split("\\s+");
                sortCodeSubstitutionTable.put(fields[0], fields[1]);
            }
            LOGGER.debug("Sort code substitution table loaded");
            br.close();
        }
        catch (final IOException e) {
            throw new BankDetailsValidationRuntimeException("An error occurred loading the sort code substitution table", e);
        }

        return sortCodeSubstitutionTable;
    }
}

Both classes have a lot of duplicate code. I'm trying to work out the best way to refactor them.


来源: stackexchange

问:
Cannot find the declaration of element 'car'
First time posting here.  I'm having difficulties with some XLM and XSD.  I keep getting the following error:

Cannot find the declaration of element 'car'. [13]

I've searched the site for help, but I can't seem to make any progress without adding more errors (which may be the problem anyway I guess).  I'd appreciate any and all help.

Part of XML:

```<code><car
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="carcatalog.xsd">
    <make><h2>Make: </h2>Honda</make>
    <model><h2>Model: </h2>Accord</model>
    <year><h2>Year: </h2>2020</year>
    <color><h2>Color: </h2>Red</color>
    <engine>
        <number_of_cylinders><h2>Number of Cylinders: </h2>4</number_of_cylinders>
        <fuel_system><h2>Fuel System: </h2>Fuel Injected</fuel_system>
    </engine>
    <number_of_doors><h2>Doors: </h2>4</number_of_doors>
    <transmission_type><h2>Transmission: </h2>Automatic</transmission_type>
    <accessories>
        <radio><h2>Radio: </h2>Yes</radio>
        <air_conditioner><h2>Air Conditioner: </h2>Yes</air_conditioner>
        <power_windows><h2>Power Windows: </h2>No</power_windows>
        <power_steering><h2>Power Steering: </h2>Yes</power_steering>
        <power_brakes><h2>Power Brakes: </h2>Yes</power_brakes>
    </accessories>

    <h1></h1>

    <make><h2>Make: </h2>Chevrolet</make>
    <model><h2>Model: </h2>Corvette</model>
    <year><h2>Year: </h2>2020</year>
    <color><h2>Color: </h2>Blue</color>
    <engine>
        <number_of_cylinders><h2>Number of Cylinders: </h2>8</number_of_cylinders>
        <fuel_system><h2>Fuel System: </h2>Fuel Injected</fuel_system>
    </engine>
    <number_of_doors><h2>Doors: </h2>2</number_of_doors>
    <transmission_type><h2>Transmission: </h2>Manual</transmission_type>
    <accessories>
        <radio><h2>Radio: </h2>Yes</radio>
        <air_conditioner><h2>Air Conditioner: </h2>Yes</air_conditioner>
        <power_windows><h2>Power Windows: </h2>Yes</power_windows>
        <power_steering><h2>Power Steering: </h2>Yes</power_steering>
        <power_brakes><h2>Power Brakes: </h2>Yes</power_brakes>
    </accessories>

    <h1></h1>

    <make><h2>Make: </h2>Toyota</make>
    <model><h2>Model: </h2>Tacoma</model>
    <year><h2>Year: </h2>2017</year>
    <color><h2>Color: </h2>Cement</color>
    <engine>
        <number_of_cylinders><h2>Number of Cylinders: </h2>6</number_of_cylinders>
        <fuel_system><h2>Fuel System: </h2>Fuel Injected</fuel_system>
    </engine>
    <number_of_doors><h2>Doors: </h2>4</number_of_doors>
    <transmission_type><h2>Transmission: </h2>Automatic</transmission_type>
    <accessories>
        <radio><h2>Radio: </h2>Yes</radio>
        <air_conditioner><h2>Air Conditioner: </h2>Yes</air_conditioner>
        <power_windows><h2>Power Windows: </h2>Yes</power_windows>
        <power_steering><h2>Power Steering: </h2>Yes</power_steering>
        <power_brakes><h2>Power Brakes: </h2>Yes</power_brakes>
    </accessories>
</car>
</code>```

Part of XSD:

```<code><xs:schema
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="catalog">
    <xs:complexType>
    <xs:sequence>

    <xs:element name = "car" maxOccurs="unbounded">
        <xs:complexType>
            <xs:sequence>
                <xs:element name = "make" type="xs:string"/>
                <xs:element name = "model" type="xs:string"/>
                <xs:element name = "year" type="xs:positiveInteger"/>
                <xs:element name = "color" type="xs:string"/>
                <xs:element name="engine">
                    <xs:complexType>
                    <xs:sequence>
                        <xs:element name="number_of_cylinders" type="xs:positiveInteger"/>
                        <xs:element name="fuel_system">
                            <xs:complexType>
                            <xs:sequence>
                                <xs:choice>
                                    <xs:element name="fuel_injected"/>
                                    <xs:element name="carbureted"/>
                                </xs:choice>
                            </xs:sequence>
                            </xs:complexType>
                        </xs:element>
                    </xs:sequence>
                    </xs:complexType>
                </xs:element>

                <xs:element name = "number_of_doors" type="xs:positiveInteger"/>
                <xs:element name = "transmission_type" type="xs:string"/>

                <xs:element name = "accessories">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name = "radio" minOccurs="1">
                                <xs:simpleType>
                                    <xs:restriction base="xs:string">
                                        <xs:enumeration value="yes"/>
                                        <xs:enumeration value="no"/>
                                    </xs:restriction>
                                </xs:simpleType>
                            </xs:element>
                            <xs:element name = "air_conditioner" minOccurs="1">
                                <xs:simpleType>
                                    <xs:restriction base="xs:string">
                                        <xs:enumeration value="yes"/>
                                        <xs:enumeration value="no"/>
                                    </xs:restriction>
                                </xs:simpleType>
                            </xs:element>
                            <xs:element name = "power_windows" minOccurs="1">
                                <xs:simpleType>
                                    <xs:restriction base="xs:string">
                                        <xs:enumeration value="yes"/>
                                        <xs:enumeration value="no"/>
                                    </xs:restriction>
                                </xs:simpleType>
                            </xs:element>
                            <xs:element name = "power_steering" minOccurs="1">
                                <xs:simpleType>
                                    <xs:restriction base="xs:string">
                                        <xs:enumeration value="yes"/>
                                        <xs:enumeration value="no"/>
                                    </xs:restriction>
                                </xs:simpleType>
                            </xs:element>
                            <xs:element name = "power_brakes" minOccurs="1">
                                <xs:simpleType>
                                    <xs:restriction base="xs:string">
                                        <xs:enumeration value="yes"/>
                                        <xs:enumeration value="no"/>
                                    </xs:restriction>
                                </xs:simpleType>
                            </xs:element>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    </xs:sequence>
    </xs:complexType>
</xs:element>
</xs:schema>
</code>```

答:
Reason for the error

In your case, the reason for the error is because the root element in your XML, car, does not have a top-level declaration in your XSD.

Remedies for this issue

Either move the declaration of car to the top-level in your XSD, or wrap car in your XML with catalog, which is defined at the top level and has car in its content model.

If you opt to move the declaration of car to the top-level in the XSD, you can reference it where needed in the content model of catalog (and other elements as necessary) via

```<code><xs:element ref="car"  ... >
</code>```

rather than xs:element/@name.

Other reasons for the error

There are many other reasons for an element not to be found during validation.  See also:

How to link XML to XSD using schemaLocation or noNamespaceSchemaLocation?

How to reference a local XML Schema file correctly?

xmlns, xmlns:xsi, xsi:schemaLocation, and targetNamespace?

ContentLicense: CC BY-SA 4.0

Body:
First time posting here.  I'm having difficulties with some XLM and XSD.  I keep getting the following error:

Cannot find the declaration of element 'car'. [13]

I've searched the site for help, but I can't seem to make any progress without adding more errors (which may be the problem anyway I guess).  I'd appreciate any and all help.

Part of XML:

<car
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="carcatalog.xsd">
    <make>
Make:
Honda</make>
    <model>
Model:
Accord</model>
    <year>
Year:
2020</year>
    <color>
Color:
Red</color>
    <engine>
        <number_of_cylinders>
Number of Cylinders:
4</number_of_cylinders>
        <fuel_system>
Fuel System:
Fuel Injected</fuel_system>
    </engine>
    <number_of_doors>
Doors:
4</number_of_doors>
    <transmission_type>
Transmission:
Automatic</transmission_type>
    <accessories>
        <radio>
Radio:
Yes</radio>
        <air_conditioner>
Air Conditioner:
Yes</air_conditioner>
        <power_windows>
Power Windows:
No</power_windows>
        <power_steering>
Power Steering:
Yes</power_steering>
        <power_brakes>
Power Brakes:
Yes</power_brakes>
    </accessories>

    <make>
Make:
Chevrolet</make>
    <model>
Model:
Corvette</model>
    <year>
Year:
2020</year>
    <color>
Color:
Blue</color>
    <engine>
        <number_of_cylinders>
Number of Cylinders:
8</number_of_cylinders>
        <fuel_system>
Fuel System:
Fuel Injected</fuel_system>
    </engine>
    <number_of_doors>
Doors:
2</number_of_doors>
    <transmission_type>
Transmission:
Manual</transmission_type>
    <accessories>
        <radio>
Radio:
Yes</radio>
        <air_conditioner>
Air Conditioner:
Yes</air_conditioner>
        <power_windows>
Power Windows:
Yes</power_windows>
        <power_steering>
Power Steering:
Yes</power_steering>
        <power_brakes>
Power Brakes:
Yes</power_brakes>
    </accessories>

    <make>
Make:
Toyota</make>
    <model>
Model:
Tacoma</model>
    <year>
Year:
2017</year>
    <color>
Color:
Cement</color>
    <engine>
        <number_of_cylinders>
Number of Cylinders:
6</number_of_cylinders>
        <fuel_system>
Fuel System:
Fuel Injected</fuel_system>
    </engine>
    <number_of_doors>
Doors:
4</number_of_doors>
    <transmission_type>
Transmission:
Automatic</transmission_type>
    <accessories>
        <radio>
Radio:
Yes</radio>
        <air_conditioner>
Air Conditioner:
Yes</air_conditioner>
        <power_windows>
Power Windows:
Yes</power_windows>
        <power_steering>
Power Steering:
Yes</power_steering>
        <power_brakes>
Power Brakes:
Yes</power_brakes>
    </accessories>
</car>

Part of XSD:

<xs:schema
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="catalog">
    <xs:complexType>
    <xs:sequence>

    <xs:element name = "car" maxOccurs="unbounded">
        <xs:complexType>
            <xs:sequence>
                <xs:element name = "make" type="xs:string"/>
                <xs:element name = "model" type="xs:string"/>
                <xs:element name = "year" type="xs:positiveInteger"/>
                <xs:element name = "color" type="xs:string"/>
                <xs:element name="engine">
                    <xs:complexType>
                    <xs:sequence>
                        <xs:element name="number_of_cylinders" type="xs:positiveInteger"/>
                        <xs:element name="fuel_system">
                            <xs:complexType>
                            <xs:sequence>
                                <xs:choice>
                                    <xs:element name="fuel_injected"/>
                                    <xs:element name="carbureted"/>
                                </xs:choice>
                            </xs:sequence>
                            </xs:complexType>
                        </xs:element>
                    </xs:sequence>
                    </xs:complexType>
                </xs:element>

                <xs:element name = "number_of_doors" type="xs:positiveInteger"/>
                <xs:element name = "transmission_type" type="xs:string"/>

                <xs:element name = "accessories">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name = "radio" minOccurs="1">
                                <xs:simpleType>
                                    <xs:restriction base="xs:string">
                                        <xs:enumeration value="yes"/>
                                        <xs:enumeration value="no"/>
                                    </xs:restriction>
                                </xs:simpleType>
                            </xs:element>
                            <xs:element name = "air_conditioner" minOccurs="1">
                                <xs:simpleType>
                                    <xs:restriction base="xs:string">
                                        <xs:enumeration value="yes"/>
                                        <xs:enumeration value="no"/>
                                    </xs:restriction>
                                </xs:simpleType>
                            </xs:element>
                            <xs:element name = "power_windows" minOccurs="1">
                                <xs:simpleType>
                                    <xs:restriction base="xs:string">
                                        <xs:enumeration value="yes"/>
                                        <xs:enumeration value="no"/>
                                    </xs:restriction>
                                </xs:simpleType>
                            </xs:element>
                            <xs:element name = "power_steering" minOccurs="1">
                                <xs:simpleType>
                                    <xs:restriction base="xs:string">
                                        <xs:enumeration value="yes"/>
                                        <xs:enumeration value="no"/>
                                    </xs:restriction>
                                </xs:simpleType>
                            </xs:element>
                            <xs:element name = "power_brakes" minOccurs="1">
                                <xs:simpleType>
                                    <xs:restriction base="xs:string">
                                        <xs:enumeration value="yes"/>
                                        <xs:enumeration value="no"/>
                                    </xs:restriction>
                                </xs:simpleType>
                            </xs:element>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    </xs:sequence>
    </xs:complexType>
</xs:element>
</xs:schema>

Body:
Reason for the error

In your case, the reason for the error is because the root element in your XML, car, does not have a top-level declaration in your XSD.

Remedies for this issue

Either move the declaration of car to the top-level in your XSD, or wrap car in your XML with catalog, which is defined at the top level and has car in its content model.

If you opt to move the declaration of car to the top-level in the XSD, you can reference it where needed in the content model of catalog (and other elements as necessary) via

<xs:element ref="car"  ... >

rather than xs:element/@name.

Other reasons for the error

There are many other reasons for an element not to be found during validation.  See also:

How to link XML to XSD using schemaLocation or noNamespaceSchemaLocation?

How to reference a local XML Schema file correctly?

xmlns, xmlns:xsi, xsi:schemaLocation, and targetNamespace?


问:
I can not successfully run tensorflow-gpu on anaconda python3.6 and spyder
I am having a problem with TensorFlow-GPU when I try to run the following code

```<code>from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
</code>```

it yields this error:

And the same problem happens in here.

My CUDA version is 10.2,cudnn version is 7.6.5, and the TensorFlow-GPU version show on anaconda navigator is 2.0.0.

(I usually install the package on navigator)

could anyone help me?

Thank you...

答:
The letter I just before tensorflow/streams_executor... means that you're getting INFO-level log message, and Spyder mistreats this info message as the error. Getting this message is ok, however, your can perform additional checks on your GPU by running the following code:

```<code>import tensorflow as tf
tf.debugging.set_log_device_placement(True)
print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
# Create some tensors
a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
c = tf.matmul(a, b)
print(c)
</code>```

Body:
I am having a problem with TensorFlow-GPU when I try to run the following code

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

it yields this error:

And the same problem happens in here.

My CUDA version is 10.2,cudnn version is 7.6.5, and the TensorFlow-GPU version show on anaconda navigator is 2.0.0.

(I usually install the package on navigator)

could anyone help me?

Thank you...

Body:
The letter I just before tensorflow/streams_executor... means that you're getting INFO-level log message, and Spyder mistreats this info message as the error. Getting this message is ok, however, your can perform additional checks on your GPU by running the following code:

import tensorflow as tf
tf.debugging.set_log_device_placement(True)
print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
# Create some tensors
a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
c = tf.matmul(a, b)
print(c)


问:
@angular-cli install fails with deprecated request@2.88.2: request has been deprecated (mac)
After updating node.js and npm to current LTS:

```<code>node -v
v12.16.0
</code>```

```<code>npm -v
6.13.4
</code>```

When I'm trying to install @angular-cli following the steps in the documentation, running npm install -g @angular/cli
 in the terminal stops the installation and the console output is:

```<code>npm install -g @angular/cli
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
/Users/user/.npm-global/bin/ng -> /USERS/USER/.npm-global/lib/node_modules/@angular/cli/bin/ng

> @angular/cli@9.0.2 postinstall /USERS/USER/.npm-global/lib/node_modules/@angular/cli
> node ./bin/postinstall/script.js

+ @angular/cli@9.0.2
updated 1 package in 12.202s
</code>```

And in this case, ng new project-name yields -bash: ng: command not found. Any help would be very welcome as I have a big project coming up.
Thanks all.

答:
Unfortunately, Request package was deprecated.
and that according to Mikeal Rogers (creator of request) read this link

and for more information, you can read this article

Body:
After updating node.js and npm to current LTS:

node -v
v12.16.0

npm -v
6.13.4

When I'm trying to install @angular-cli following the steps in the documentation, running npm install -g @angular/cli
 in the terminal stops the installation and the console output is:

npm install -g @angular/cli
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
/Users/user/.npm-global/bin/ng -> /USERS/USER/.npm-global/lib/node_modules/@angular/cli/bin/ng

> @angular/cli@9.0.2 postinstall /USERS/USER/.npm-global/lib/node_modules/@angular/cli
> node ./bin/postinstall/script.js

+ @angular/cli@9.0.2
updated 1 package in 12.202s

And in this case, ng new project-name yields -bash: ng: command not found. Any help would be very welcome as I have a big project coming up.
Thanks all.


问:
Writing data from kafka to hive using pyspark - stucked
I quite new to spark and started with pyspark, I am learning to push data from kafka to hive using pyspark.

```<code>from pyspark.sql import SparkSession
from pyspark.sql.functions import explode
from pyspark.sql.functions import *
from pyspark.streaming.kafka import KafkaUtils
from os.path import abspath

warehouseLocation = abspath("spark-warehouse")

spark = SparkSession.builder.appName("sparkstreaming").getOrCreate()

df = spark.read.format("kafka").option("startingoffsets", "earliest").option("kafka.bootstrap.servers", "kafka-server1:66,kafka-server2:66").option("kafka.security.protocol", "SSL").option("kafka.ssl.keystore.location", "mykeystore.jks").option("kafka.ssl.keystore.password","mykeystorepassword").option("subscribe","json_stream").load().selectExpr("CAST(value AS STRING)")

json_schema = df.schema

df1 = df.select($"value").select(from_json,json_schema).alias("data").select("data.*")
</code>```

The above is not working, however after extracting data, I want to insert data to hive table.

As I am completely new, looking for help.
Appreciated in advance! :)

答:
```<code>from os.path import expanduser, join, abspath

from pyspark.sql import SparkSession
from pyspark.sql import Row

# warehouse_location points to the default location for managed databases and tables
warehouse_location = abspath('spark-warehouse')

spark = SparkSession \
.builder \
.appName("Python Spark SQL Hive integration example") \
.config("spark.sql.warehouse.dir", warehouse_location) \
.enableHiveSupport() \
.getOrCreate()

# spark is an existing SparkSession
spark.sql("CREATE TABLE IF NOT EXISTS src (key INT, value STRING) USING hive")
spark.sql("LOAD DATA LOCAL INPATH 'examples/src/main/resources/kv1.txt' INTO TABLE src")
</code>```

Body:
I quite new to spark and started with pyspark, I am learning to push data from kafka to hive using pyspark.

from pyspark.sql import SparkSession
from pyspark.sql.functions import explode
from pyspark.sql.functions import *
from pyspark.streaming.kafka import KafkaUtils
from os.path import abspath

warehouseLocation = abspath("spark-warehouse")

spark = SparkSession.builder.appName("sparkstreaming").getOrCreate()

df = spark.read.format("kafka").option("startingoffsets", "earliest").option("kafka.bootstrap.servers", "kafka-server1:66,kafka-server2:66").option("kafka.security.protocol", "SSL").option("kafka.ssl.keystore.location", "mykeystore.jks").option("kafka.ssl.keystore.password","mykeystorepassword").option("subscribe","json_stream").load().selectExpr("CAST(value AS STRING)")

json_schema = df.schema

df1 = df.select($"value").select(from_json,json_schema).alias("data").select("data.*")

The above is not working, however after extracting data, I want to insert data to hive table.

As I am completely new, looking for help.
Appreciated in advance! :)


问:
Is it possible to create an object on a background thread with no reference on the main thread?
Equities trading application uses a class library for getting callbacks on stock quote updates, another class library for getting callbacks on order executions or cancelations. I currently have the callbacks execute in the thread pool. I start one background thread for each callback. The threads are very short lived and the work involved includes fetching the data and notifying the observers. Once observers are notified the background thread dies. When I have strategies subscribing to over 1000 actively traded symbols I get OutOfMemory exceptions.

How can I improve this design? I was thinking of starting two threads at the start, one for quotes, the other for executions, and creating each object on its respective threads. Then just have a shared object which allows adding and removing observers to the threads. But 1) how would you keep the thread alive to receive the callbacks? 2) How can you even have a callback object which is initialized on a thread with no reference on the main thread? Is this even possible?

Any help would be appreciated.

答:
Use a producer / consumer model with a simple queue. Then you have a set number of worker threads running and you won't have this problem.

As for how to call the callback function, you could possibly use a struct like this:

```<code>struct WorkerData
{
    Data data;
    Delegate someCallback;
}
</code>```

when the worker is finished with the data it can invoke the callback itself.

ContentLicense: CC BY-SA 3.0

Body:
Use a producer / consumer model with a simple queue. Then you have a set number of worker threads running and you won't have this problem.

As for how to call the callback function, you could possibly use a struct like this:

struct WorkerData
{
    Data data;
    Delegate someCallback;
}

when the worker is finished with the data it can invoke the callback itself.


问:
search a paragraph in reverse order without array in perl
i have a log file where the errors will be mentioned as "ERROR" in the beginning of the line and next line will have the detailed text about the error. I would like to search for "ERROR" in the reverse order so i can find the last error and print the next line or copy is the line to a variable.

In shell i can try the below command which will help me to achieve the same. Can some one give me a equivalent perl code.

```<code>grep -A2 ERROR sapinst.log | tail -2
</code>```

As the log file will be huge (~5000+ lines), so I don't want to store it in an array.

答:
Your file size is rather small and perl is pretty quick, so I wouldn't worry about reverse order that much. This little program reads lines of input from the files you specify on the command line (or standard input if you specify none), skips lines until it finds ERROR, then prints that and the next line:

```<code>#!perl

while( <> ) {
    next unless /ERROR/;
    print;
    print scalar <>;
    }
</code>```

From there you can use tail if you like. This Perl does the same as the grep you posted (although since you already have that solution I wonder why you want a different one).

If you don't want to use tail, keep track of the two lines you'll output and replace them when you find a new set:

```<code>my( $error_line, $next_line );
while( <> ) {
    next unless /ERROR/;
    $error_line = $_;
    $next_line = scalar <>;
    }

print $error_line, $next_line;
</code>```

If you have a recent enough perl, you can use the safer double diamond line input operator:

```<code>use v5.22;

my( $error_line, $next_line );
while( <<>> ) {
    next unless /ERROR/;
    $error_line = $_;
    $next_line = scalar <<>>;
    }

print $error_line, $next_line;
</code>```

You can use File::ReadBackwards, but you'll have to do the same task by remembering every line then checking if the previous line had ERROR. For you data sizes, the benefit probably isn't apparent. If the simple solution isn't fast enough, it's time to get fancier (but not before then).

Body:
i have a log file where the errors will be mentioned as "ERROR" in the beginning of the line and next line will have the detailed text about the error. I would like to search for "ERROR" in the reverse order so i can find the last error and print the next line or copy is the line to a variable.

In shell i can try the below command which will help me to achieve the same. Can some one give me a equivalent perl code.

grep -A2 ERROR sapinst.log | tail -2

As the log file will be huge (~5000+ lines), so I don't want to store it in an array.

Body:
Your file size is rather small and perl is pretty quick, so I wouldn't worry about reverse order that much. This little program reads lines of input from the files you specify on the command line (or standard input if you specify none), skips lines until it finds ERROR, then prints that and the next line:

#!perl

while( <> ) {
    next unless /ERROR/;
    print;
    print scalar <>;
    }

From there you can use tail if you like. This Perl does the same as the grep you posted (although since you already have that solution I wonder why you want a different one).

If you don't want to use tail, keep track of the two lines you'll output and replace them when you find a new set:

my( $error_line, $next_line );
while( <> ) {
    next unless /ERROR/;
    $error_line = $_;
    $next_line = scalar <>;
    }

print $error_line, $next_line;

If you have a recent enough perl, you can use the safer double diamond line input operator:

use v5.22;

my( $error_line, $next_line );
while( <<>> ) {
    next unless /ERROR/;
    $error_line = $_;
    $next_line = scalar <<>>;
    }

print $error_line, $next_line;

You can use File::ReadBackwards, but you'll have to do the same task by remembering every line then checking if the previous line had ERROR. For you data sizes, the benefit probably isn't apparent. If the simple solution isn't fast enough, it's time to get fancier (but not before then).


问:
Compare Txt Files in Linux and Return Elements in File 1 for Elements in File 2
Here is the problem.

Host.txt file has only Hostnames as follows:

```
GVC-CH-ZRH-BRA-5H81-PELE
GVC-US-NYC-9TH-4C101-MEDROOM
GVC-US-NYC-9TH-4C101E-EXTRA
GVC-US-NYC-9TH-5E117-STUDIO54
```

2.HosandIp.txt has the Hostnames and Ip as follows (HostandIP has hostname,IP Address Note the Comma (,)):

```
GVC-CH-ZRH-BRA-5H81-PELE,170.16.75.101
GVC-US-NYC-9TH-4C101-MEDROOM,170.26.114.242
GVC-US-NYC-9TH-4C101E-EXTRA,170.26.108.224
GVC-US-NYC-9TH-5E117-STUDIO54,170.26.108.95
beta-gvc-personal-antoniop-526,170.26.107.180
beta-gvc-personal-antoniop-9100,170.26.106.206
beta-gvc-personal-antoniop-9100b,170.26.106.41
beta-gvc-personal-antoniop-office,170.26.107.192
```

I need to compare these two files and get only the IP Address in another text file called IPOnly.txt

IPOnly.txt has only the IP's common to both Host.txt and HostandIp.txt as follows:

```
170.16.75.101
170.26.114.242
170.26.108.224
170.26.108.95
```

It can be done in JAVA using HASH MAP. Is there a Linux Command to do this ? Please Help!

答:
```<code>sort Host.txt -o Host_sorted.txt
sort HosandIp.txt -o HosandIp_sorted.txt
join Host_sorted.txt HosandIp_sorted.txt -t, | cut -d, -f2
</code>```

The input files must be sorted. The entries aren't quite sorted in the order desired by join, therefore I've included the calls to sort to do this. Join man page

Body:
Here is the problem.

Host.txt file has only Hostnames as follows:

GVC-CH-ZRH-BRA-5H81-PELE
GVC-US-NYC-9TH-4C101-MEDROOM
GVC-US-NYC-9TH-4C101E-EXTRA
GVC-US-NYC-9TH-5E117-STUDIO54

2.HosandIp.txt has the Hostnames and Ip as follows (HostandIP has hostname,IP Address Note the Comma (,)):

GVC-CH-ZRH-BRA-5H81-PELE,170.16.75.101
GVC-US-NYC-9TH-4C101-MEDROOM,170.26.114.242
GVC-US-NYC-9TH-4C101E-EXTRA,170.26.108.224
GVC-US-NYC-9TH-5E117-STUDIO54,170.26.108.95
beta-gvc-personal-antoniop-526,170.26.107.180
beta-gvc-personal-antoniop-9100,170.26.106.206
beta-gvc-personal-antoniop-9100b,170.26.106.41
beta-gvc-personal-antoniop-office,170.26.107.192

I need to compare these two files and get only the IP Address in another text file called IPOnly.txt

IPOnly.txt has only the IP's common to both Host.txt and HostandIp.txt as follows:

170.16.75.101
170.26.114.242
170.26.108.224
170.26.108.95

It can be done in JAVA using HASH MAP. Is there a Linux Command to do this ? Please Help!

Body:
sort Host.txt -o Host_sorted.txt
sort HosandIp.txt -o HosandIp_sorted.txt
join Host_sorted.txt HosandIp_sorted.txt -t, | cut -d, -f2

The input files must be sorted. The entries aren't quite sorted in the order desired by join, therefore I've included the calls to sort to do this. Join man page


问:
linking a button to another page in SweetAlert
am i using sweet alert and i have 2 buttons; one is cancel button and the another one is continue button. i want to link the 'continue' button to another page that is 'trial.php'. how can i proceed with this? below is code i've tried:

if(m <= 2){
  swal({
    title:"dataset file is: "+  ""+size2 +"Mb",
    text: "a cluster of 1 node will be required for processing",
    buttons: {
      cancel: true,
      confirm: "continue"
    }
  })```

答: swal({ title: "test", text: "testing", buttons: { cancel: true, confirm: "continue" } }).then((value) => { if (value) { window.location.href = "trial.php"; } });```


问:
How to log mallocs
This is a bit hypothetical and grossly simplified but...

Assume a program that will be calling functions written by third parties. These parties can be assumed to be non-hostile but can't be assumed to be "competent". Each function will take some arguments, have side effects and return a value. They have no state while they are not running.

The objective is to ensure they can't cause memory leaks by logging all mallocs (and the like) and then freeing everything after the function exits.

Is this possible? Is this practical?

p.s. The important part to me is ensuring that no allocations persist so ways to remove memory leaks without doing that are not useful to me.

答:
On Linux I've successfully used mtrace(3) to log allocations and freeings. Its usage is as simple as

Modify your program to call mtrace() when you need to begin tracing (e.g. at the top of main()),

Set environment variable MALLOC_TRACE to the file path where the trace should be saved and run the program.

After that the output file will contain something like this (excerpt from the middle to show a failed allocation):

```<code>@ /usr/lib/tls/libnvidia-tls.so.390.116:[0xf44b795c] + 0x99e5e20 0x49
@ /opt/gcc-7/lib/libstdc++.so.6:(_ZdlPv+0x18)[0xf6a80f78] - 0x99beba0
@ /usr/lib/tls/libnvidia-tls.so.390.116:[0xf44b795c] + 0x9a23ec0 0x10
@ /opt/gcc-7/lib/libstdc++.so.6:(_ZdlPv+0x18)[0xf6a80f78] - 0x9a23ec0
@ /opt/Xorg/lib/video-libs/libGL.so.1:[0xf668ee49] + 0x99c67c0 0x8
@ /opt/Xorg/lib/video-libs/libGL.so.1:[0xf668f14f] - 0x99c67c0
@ /opt/Xorg/lib/video-libs/libGL.so.1:[0xf668ee49] + (nil) 0x30000000
@ /lib/libc.so.6:[0xf677f8eb] + 0x99c21f0 0x158
@ /lib/libc.so.6:(_IO_file_doallocate+0x91)[0xf677ee61] + 0xbfb00480 0x400
@ /lib/libc.so.6:(_IO_setb+0x59)[0xf678d7f9] - 0xbfb00480
</code>```

OwnerDisplayName: BCS

ContentLicense: CC BY-SA 2.5

Title: How to log mallocs

LastEditorDisplayName: Checkers

Body:
On Linux I've successfully used mtrace(3) to log allocations and freeings. Its usage is as simple as

Modify your program to call mtrace() when you need to begin tracing (e.g. at the top of main()),

Set environment variable MALLOC_TRACE to the file path where the trace should be saved and run the program.

After that the output file will contain something like this (excerpt from the middle to show a failed allocation):

@ /usr/lib/tls/libnvidia-tls.so.390.116:[0xf44b795c] + 0x99e5e20 0x49
@ /opt/gcc-7/lib/libstdc++.so.6:(_ZdlPv+0x18)[0xf6a80f78] - 0x99beba0
@ /usr/lib/tls/libnvidia-tls.so.390.116:[0xf44b795c] + 0x9a23ec0 0x10
@ /opt/gcc-7/lib/libstdc++.so.6:(_ZdlPv+0x18)[0xf6a80f78] - 0x9a23ec0
@ /opt/Xorg/lib/video-libs/libGL.so.1:[0xf668ee49] + 0x99c67c0 0x8
@ /opt/Xorg/lib/video-libs/libGL.so.1:[0xf668f14f] - 0x99c67c0
@ /opt/Xorg/lib/video-libs/libGL.so.1:[0xf668ee49] + (nil) 0x30000000
@ /lib/libc.so.6:[0xf677f8eb] + 0x99c21f0 0x158
@ /lib/libc.so.6:(_IO_file_doallocate+0x91)[0xf677ee61] + 0xbfb00480 0x400
@ /lib/libc.so.6:(_IO_setb+0x59)[0xf678d7f9] - 0xbfb00480


问:
How to properly organize the resources in the res folder?
I created a project in android studio using Kotlin

I try now to organise my files in the "res" area.
in drawable, there is a lot of png files ( icons used in my app ),
and a lot of custom controls: xml files, using shape, solid, stoke...

when I try to create a new resource directory, using "resource type" = drawable :
it does not compile : "shape" "solid", etc... are not recognized anymore during compilation.
android studio require me to put ALL my shape in drawable folder, which start to be a big mess.

how can I add several folder in res area.
I want to separate properly the icons, the xml files in separate folder ?

thanks for any help.

答:
Unfortunately, Android don't let you do that, all drawables must be in the drawable folder - and we can't create subdirectories (Can the Android drawable directory contain subdirectories?).

In order to be able to manage all this mess, I recommend prepending the drawable type to the name, so you have:

```<code>icon_my_icon_name
shape_my_shape_name
solid_my_solid_name
...
</code>```

Body:
Unfortunately, Android don't let you do that, all drawables must be in the drawable folder - and we can't create subdirectories (Can the Android drawable directory contain subdirectories?).

In order to be able to manage all this mess, I recommend prepending the drawable type to the name, so you have:

icon_my_icon_name
shape_my_shape_name
solid_my_solid_name
...


问:
How can I display a return in three columns (in Google Apps Script) that looks like an array, but (to me) doesn't behave like one?
How can I display this return in three columns on my web app, preferably with given headers?

THIS IS PROBABLY IMPORTANT!
According to the writer of the gvizQuery function, which I use to find data in a referenced Google Sheet, the return is an array of arrays.

The code runs Google Apps Script V8.

This is the simplest version of the code where I provide a serial number, which is sent to the query function, and returned along with a reference to ou and most recent user.

document.getElementById("btnserno1").addEventListener("click",fetchCBOU);
    function fetchCBOU(){
        var sernum = document.getElementById("serial").value;
        google.script.run
        .withSuccessHandler(printCBOUU)
        .queryCBOU(sernum);
    }
        window.printCBOUU = function(CBOUU) {
        console.log(CBOUU);
        var CBOU1 = CBOUU

        document.getElementById('idCB').innerHTML = CBOU1[0];
        document.getElementById('idCBOU').innerHTML = CBOU1[1];
        document.getElementById('idCBRecent').innerHTML = CBOU1[2];
  }```
</div>
</div>
</p>
<p>In the <em>Stackdriver logs</em> the return is displayed like this.</p>
<p>Feb 17, 2020, 12:07:22 AM   Info    [[[5CD725B5B0, /Grundskolor/Boras, utd8377@edu.kunskapsskolan.se]]]</p>
<p>This is what it looks like in the console.
First a perfect match.</p>
<p><img src="https://i.stack.imgur.com/9P9e9.png" alt="Perfect match" /></p>
<p>On the web app it displays the three values in one place, and leaves the other two as <em>undefined</em>.
<img src="https://i.stack.imgur.com/K6Hw7.png" alt="displays on web app" /></p>
<p>If I instead do a partial match, I get more arrays in console.</p>
<p><img src="https://i.stack.imgur.com/3eYVu.png" alt="partial match" /></p>
<p>But in the web app I get all those values in the first element and the two other elements are still <em>undefined</em>.</p>
<p>If I manipulate the incoming data after it arrives, and try split it up, I get different results depending on if it's a perfect or partial match.</p>
<p>I changed the middle part of the code to this.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>        window.printCBOUU = function(CBOUU) {
        console.log(CBOUU);

        //Creating the new variable, based off CBOUU, adding quotation marks.
        var str = CBOUU + '';
        console.log(str);

        //Creating the new array, based off CBOUU, and now, since it has quotation marks, it becomes an array.
        var CBOU1 = str.split(",");
        console.log(CBOU1);

        document.getElementById('idCB').innerHTML = CBOU1[0];
        document.getElementById('idCBOU').innerHTML = CBOU1[1];
        document.getElementById('idCBRecent').innerHTML = CBOU1[2];
  }</code>```

For a perfect match and a partial match that only has a single matching device everything still works.

But if I do a partial match and get many hits everything breaks, as it is no longer working with variables with three sets of data, but instead as many values as there are matching devices, times three values. And to display them I'd have to keep adding CBOU1[n] values for each one.

Do note that this is not static data! I'm trying to display the return from a function where I search for a partial serial number from a Google sheet.

Logs (I thought this was an array, with three values for each object, but apparently this could be an array of arrays)

[20-02-14 16:28:16:153 CET] [[[5CD9264KBW, /Grundskolor/Boras, user1@my.domain], [5CD9264K64, /Grundskolor/Boras, user2@my.domain], [5CD9264K7V, /Grundskolor/Boras, user3@my.domain], [5CD9264K6M, /Grundskolor/Boras, user4@my.domain]]

Console after I try to turn it into a usable array (here it looks to me to be a single array of only one object, with a bunch of values)

["5CD9264KBW", "/Grundskolor/Boras", "user1@my.domain", "5CD9264K64", "/Grundskolor/Boras", "user2@my.domain", "5CD9264K7V", "/Grundskolor/Boras", "user3@my.domain", "5CD9264K6M", "/Grundskolor/Boras", "user4@my.domain"]

答:
```<code>function splitItUp() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getActiveSheet();
  var data='[[[5CD9264KBW, /Grundskolor/Boras, user1@my.domain], [5CD9264K64, /Grundskolor/Boras, user2@my.domain], [5CD9264K7V, /Grundskolor/Boras, user3@my.domain], [5CD9264K6M, /Grundskolor/Boras, user4@my.domain]]';
  var a=data.slice(3,-2).trim().replace(/\], \[/g,'~~~').split('~~~');
  var b=[];
  a.forEach(function(r){b.push(r.split(', '));});
  sh.getRange(1,1,b.length,b[0].length).setValues(b);
}
</code>```

I'm guessing that you can take it from here:

```<code>function splitItUp() {
  const data='[[[5CD9264KBW, /Grundskolor/Boras, user1@my.domain], [5CD9264K64, /Grundskolor/Boras, user2@my.domain], [5CD9264K7V, /Grundskolor/Boras, user3@my.domain], [5CD9264K6M, /Grundskolor/Boras, user4@my.domain]]';
  let a=data.slice(3,-2).trim().replace(/\], \[/g,'~~~').split('~~~');
  let b=[];
  a.forEach(function(r){b.push(r.split(', '));});
  let html='<style>td,th{border:1px solid black;}</style><table>';
  b.forEach(function(r,i){html+=`<tr><td>${r[0]}</td><td>${r[1]}</td><td>${r[2]}</td></tr>`;});
  html+='</table>';
  var ui=HtmlService.createHtmlOutput(html);
  SpreadsheetApp.getUi().showModelessDialog(ui, 'Split It Up')
}
</code>```

I just put it into a dialog since I don't have a web app handy right now.

Okay maybe this is what you want.

```<code>function splitItUp() {
  const data='[[[5CD9264KBW, /Grundskolor/Boras, user1@my.domain], [5CD9264K64, /Grundskolor/Boras, user2@my.domain], [5CD9264K7V, /Grundskolor/Boras, user3@my.domain], [5CD9264K6M, /Grundskolor/Boras, user4@my.domain]]';
  let a=data.slice(3,-2).trim().replace(/\], \[/g,'~~~').split('~~~');
  let b=[];
  a.forEach(function(r){b.push(r.split(', '));});
  let html='<style>td,th{border:1px solid black;}</style><table>';
  b.forEach(function(r,i){html+=`<tr><td>${r[0]}</td><td>${r[1]}</td><td>${r[2]}</td></tr>`;});
  html+='</table>';
  //var ui=HtmlService.createHtmlOutput(html);
  //SpreadsheetApp.getUi().showModelessDialog(ui, 'Split It Up')
  document.getElementByID('iddeviceInfo').innerHTML=html;
}
</code>```

Okay here's an example of a small webapp.  I actually ran it as a dialog.

The html:(file name was ah1.html)

```<code><!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

  <script>
  $(function(){
    splitItUp();
  });
  function splitItUp() {
    const data='[[[5CD9264KBW, /Grundskolor/Boras, user1@my.domain], [5CD9264K64, /Grundskolor/Boras, user2@my.domain], [5CD9264K7V, /Grundskolor/Boras, user3@my.domain], [5CD9264K6M, /Grundskolor/Boras, user4@my.domain]]';
    let a=data.slice(3,-2).trim().replace(/\], \[/g,'~~~').split('~~~');
    let b=[];
    a.forEach(function(r){b.push(r.split(', '));});
    let html='<style>td,th{border:1px solid black;}</style><table>';
    b.forEach(function(r,i){html+=`<tr><td>${r[0]}</td><td>${r[1]}</td><td>${r[2]}</td></tr>`;});
    html+='</table>';
    document.getElementById('mydiv').innerHTML=html;
  }
  console.log('My Code');
  </script>
  </head>
  <body>
    <div id="mydiv"></div>
  </body>
</html>
</code>```

the gs: (for launching it as a dialog)

```<code>function runOne() {
  SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('ah1'), 'Data');
}
</code>```

Body:
How can I display this return in three columns on my web app, preferably with given headers?

THIS IS PROBABLY IMPORTANT!
According to the writer of the gvizQuery function, which I use to find data in a referenced Google Sheet, the return is an array of arrays.

The code runs Google Apps Script V8.

This is the simplest version of the code where I provide a serial number, which is sent to the query function, and returned along with a reference to ou and most recent user.

document.getElementById("btnserno1").addEventListener("click",fetchCBOU);
    function fetchCBOU(){
        var sernum = document.getElementById("serial").value;
        google.script.run
        .withSuccessHandler(printCBOUU)
        .queryCBOU(sernum);
    }
        window.printCBOUU = function(CBOUU) {
        console.log(CBOUU);
        var CBOU1 = CBOUU

        document.getElementById('idCB').innerHTML = CBOU1[0];
        document.getElementById('idCBOU').innerHTML = CBOU1[1];
        document.getElementById('idCBRecent').innerHTML = CBOU1[2];
  }

In the Stackdriver logs the return is displayed like this.

Feb 17, 2020, 12:07:22 AM   Info    [[[5CD725B5B0, /Grundskolor/Boras, utd8377@edu.kunskapsskolan.se]]]

This is what it looks like in the console.
First a perfect match.

On the web app it displays the three values in one place, and leaves the other two as undefined.

If I instead do a partial match, I get more arrays in console.

But in the web app I get all those values in the first element and the two other elements are still undefined.

If I manipulate the incoming data after it arrives, and try split it up, I get different results depending on if it's a perfect or partial match.

I changed the middle part of the code to this.

        window.printCBOUU = function(CBOUU) {
        console.log(CBOUU);

        //Creating the new variable, based off CBOUU, adding quotation marks.
        var str = CBOUU + '';
        console.log(str);

        //Creating the new array, based off CBOUU, and now, since it has quotation marks, it becomes an array.
        var CBOU1 = str.split(",");
        console.log(CBOU1);

        document.getElementById('idCB').innerHTML = CBOU1[0];
        document.getElementById('idCBOU').innerHTML = CBOU1[1];
        document.getElementById('idCBRecent').innerHTML = CBOU1[2];
  }

For a perfect match and a partial match that only has a single matching device everything still works.

But if I do a partial match and get many hits everything breaks, as it is no longer working with variables with three sets of data, but instead as many values as there are matching devices, times three values. And to display them I'd have to keep adding CBOU1[n] values for each one.

Do note that this is not static data! I'm trying to display the return from a function where I search for a partial serial number from a Google sheet.

Logs (I thought this was an array, with three values for each object, but apparently this could be an array of arrays)

[20-02-14 16:28:16:153 CET] [[[5CD9264KBW, /Grundskolor/Boras, user1@my.domain], [5CD9264K64, /Grundskolor/Boras, user2@my.domain], [5CD9264K7V, /Grundskolor/Boras, user3@my.domain], [5CD9264K6M, /Grundskolor/Boras, user4@my.domain]]

Console after I try to turn it into a usable array (here it looks to me to be a single array of only one object, with a bunch of values)

["5CD9264KBW", "/Grundskolor/Boras", "user1@my.domain", "5CD9264K64", "/Grundskolor/Boras", "user2@my.domain", "5CD9264K7V", "/Grundskolor/Boras", "user3@my.domain", "5CD9264K6M", "/Grundskolor/Boras", "user4@my.domain"]

Body:
function splitItUp() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getActiveSheet();
  var data='[[[5CD9264KBW, /Grundskolor/Boras, user1@my.domain], [5CD9264K64, /Grundskolor/Boras, user2@my.domain], [5CD9264K7V, /Grundskolor/Boras, user3@my.domain], [5CD9264K6M, /Grundskolor/Boras, user4@my.domain]]';
  var a=data.slice(3,-2).trim().replace(/\], \[/g,'~~~').split('~~~');
  var b=[];
  a.forEach(function(r){b.push(r.split(', '));});
  sh.getRange(1,1,b.length,b[0].length).setValues(b);
}

I'm guessing that you can take it from here:

function splitItUp() {
  const data='[[[5CD9264KBW, /Grundskolor/Boras, user1@my.domain], [5CD9264K64, /Grundskolor/Boras, user2@my.domain], [5CD9264K7V, /Grundskolor/Boras, user3@my.domain], [5CD9264K6M, /Grundskolor/Boras, user4@my.domain]]';
  let a=data.slice(3,-2).trim().replace(/\], \[/g,'~~~').split('~~~');
  let b=[];
  a.forEach(function(r){b.push(r.split(', '));});
  let html='<style>td,th{border:1px solid black;}</style><table>';
  b.forEach(function(r,i){html+=`<tr><td>${r[0]}</td><td>${r[1]}</td><td>${r[2]}</td></tr>`;});
  html+='</table>';
  var ui=HtmlService.createHtmlOutput(html);
  SpreadsheetApp.getUi().showModelessDialog(ui, 'Split It Up')
}

I just put it into a dialog since I don't have a web app handy right now.

Okay maybe this is what you want.

function splitItUp() {
  const data='[[[5CD9264KBW, /Grundskolor/Boras, user1@my.domain], [5CD9264K64, /Grundskolor/Boras, user2@my.domain], [5CD9264K7V, /Grundskolor/Boras, user3@my.domain], [5CD9264K6M, /Grundskolor/Boras, user4@my.domain]]';
  let a=data.slice(3,-2).trim().replace(/\], \[/g,'~~~').split('~~~');
  let b=[];
  a.forEach(function(r){b.push(r.split(', '));});
  let html='<style>td,th{border:1px solid black;}</style><table>';
  b.forEach(function(r,i){html+=`<tr><td>${r[0]}</td><td>${r[1]}</td><td>${r[2]}</td></tr>`;});
  html+='</table>';
  //var ui=HtmlService.createHtmlOutput(html);
  //SpreadsheetApp.getUi().showModelessDialog(ui, 'Split It Up')
  document.getElementByID('iddeviceInfo').innerHTML=html;
}

Okay here's an example of a small webapp.  I actually ran it as a dialog.

The html:(file name was ah1.html)

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

  <script>
  $(function(){
    splitItUp();
  });
  function splitItUp() {
    const data='[[[5CD9264KBW, /Grundskolor/Boras, user1@my.domain], [5CD9264K64, /Grundskolor/Boras, user2@my.domain], [5CD9264K7V, /Grundskolor/Boras, user3@my.domain], [5CD9264K6M, /Grundskolor/Boras, user4@my.domain]]';
    let a=data.slice(3,-2).trim().replace(/\], \[/g,'~~~').split('~~~');
    let b=[];
    a.forEach(function(r){b.push(r.split(', '));});
    let html='<style>td,th{border:1px solid black;}</style><table>';
    b.forEach(function(r,i){html+=`<tr><td>${r[0]}</td><td>${r[1]}</td><td>${r[2]}</td></tr>`;});
    html+='</table>';
    document.getElementById('mydiv').innerHTML=html;
  }
  console.log('My Code');
  </script>
  </head>
  <body>
    <div id="mydiv"></div>
  </body>
</html>

the gs: (for launching it as a dialog)

function runOne() {
  SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('ah1'), 'Data');
}


问:
Inline assembly multiplication "undefined reference" on inputs
Trying to multiply 400 by 2 with inline assembly, using the fact imul implicity multiplies by eax. However, i'm getting "undefined reference" compile errors to $1 and $2

```<code> int c;
 int a = 400;
 int b = 2;

 __asm__(
  ".intel_syntax;"
  "mov eax, $1;"
  "mov ebx, $2;"
  "imul %0, ebx;"
  ".att_syntax;"
  : "=r"(c)
  : "r" (a), "r" (b)
  : "eax");

std::cout << c << std::endl;
</code>```

答:
Do not use fixed registers in inline asm, especially if you have not listed them as clobbers and have not made sure inputs or outputs don't overlap them.  (This part is basically a duplicate of segmentation fault(core dumped) error while using inline assembly)

Do not switch syntax in inline assembly as the compiler will substitute wrong syntax. Use -masm=intel if you want intel syntax.

To reference arguments in an asm template string use % not $ prefix.  There's nothing special about $1; it gets treated as a symbol name just like if you'd used my_extern_int_var.  When linking, the linker doesn't find a definition for a $1 symbol.

Do not mov stuff around unnecessarily. Also remember that just because something seems to work in a certain environment, that doesn't guarantee it's correct and will work everywhere every time. Doubly so for inline asm. You have to be careful. Anyway, a fixed version could look like:

```<code>__asm__(
  "imul %0, %1"
  : "=r"(c)
  : "r" (a), "0" (b)
  : );
</code>```

Has to be compiled using -masm=intel. Notice b has been put into the same register as c.

using the fact imul implicity multiplies by eax

That's not true for the normal 2-operand form of imul.  It works the same as other instructions, doing dst *= src so you can use any register, and not waste uops writing the high half anywhere if you don't even want it.

Body:
Trying to multiply 400 by 2 with inline assembly, using the fact imul implicity multiplies by eax. However, i'm getting "undefined reference" compile errors to $1 and $2

 int c;
 int a = 400;
 int b = 2;

 __asm__(
  ".intel_syntax;"
  "mov eax, $1;"
  "mov ebx, $2;"
  "imul %0, ebx;"
  ".att_syntax;"
  : "=r"(c)
  : "r" (a), "r" (b)
  : "eax");

std::cout << c << std::endl;

Body:
Do not use fixed registers in inline asm, especially if you have not listed them as clobbers and have not made sure inputs or outputs don't overlap them.  (This part is basically a duplicate of segmentation fault(core dumped) error while using inline assembly)

Do not switch syntax in inline assembly as the compiler will substitute wrong syntax. Use -masm=intel if you want intel syntax.

To reference arguments in an asm template string use % not $ prefix.  There's nothing special about $1; it gets treated as a symbol name just like if you'd used my_extern_int_var.  When linking, the linker doesn't find a definition for a $1 symbol.

Do not mov stuff around unnecessarily. Also remember that just because something seems to work in a certain environment, that doesn't guarantee it's correct and will work everywhere every time. Doubly so for inline asm. You have to be careful. Anyway, a fixed version could look like:

__asm__(
  "imul %0, %1"
  : "=r"(c)
  : "r" (a), "0" (b)
  : );

Has to be compiled using -masm=intel. Notice b has been put into the same register as c.

using the fact imul implicity multiplies by eax

That's not true for the normal 2-operand form of imul.  It works the same as other instructions, doing dst *= src so you can use any register, and not waste uops writing the high half anywhere if you don't even want it.


问:
Basic HTML operations in Emacs
I am working with HTML in Emacs and I am looking for ways to make basics operations as:

convert list of string to HTML-list

```<code>one
two
three
</code>```

to

```<code><ul>
 <li>one</li>
 <li>two</li>
 <li>three</li>
</ul>
</code>```

add class to list of elements

```<code><a></a>
<a></a>
<a></a>
</code>```

to

```<code><a class="one"></a>
<a class="one"></a>
<a class="one"></a>
</code>```

Is there any extensions which can helps me?

答: You should take a look at zencoding , it's pretty useful. Here's a youtube video showing it with yasnippet, showing some functionality like what you want.</p>

Title: Basic HTML operations in Emacs

Body:
I am working with HTML in Emacs and I am looking for ways to make basics operations as:

convert list of string to HTML-list

one
two
three

to

one

two

three

add class to list of elements

to

Is there any extensions which can helps me?


问:
How to generate a 100x6 matrix with different values in each column in C++
I'm a newbie programmer, almost zero experience with C++, in order to translate MATLAB code manually I need to generate a 100x6 matrix. According to what I investigated so far, I should use std::vector (vector of vectors). The problem is I don't know how to add values to the matrix in this way:
100 rows, then each column should have these values:

```<code>column 1: sin(2*pi*0.05)
column 2: cos(2*pi*0.05)
column 3: sin(4*pi*0.05)
column 4: cos(4*pi*0.05)
column 5: sin(6*pi*0.05)
column 6: cos(6*pi*0.05)
</code>```

I've only found very basic examples with std:vector and nested for loops which I fail to adapt to this particular problem. Can someone give me a hint of how to solve this problem?.

答:
```<code>std::vector<std::vector<double>> matrix;
matrix.resize(100);
for (auto & line : matrix) {
    line.resize(6);
}
</code>```

And then you can do:

```<code>matrix[x1][y1] = someValue;
otherValue = matrix[x2][y2];
</code>```

etc.

But, if you know you will have a fixed size for your matrix, you can just do:

```<code>double matrix[100][6] = { 0.0 };
</code>```

instead of creating the vectors.

Body:
I'm a newbie programmer, almost zero experience with C++, in order to translate MATLAB code manually I need to generate a 100x6 matrix. According to what I investigated so far, I should use std::vector (vector of vectors). The problem is I don't know how to add values to the matrix in this way:
100 rows, then each column should have these values:

column 1: sin(2*pi*0.05)
column 2: cos(2*pi*0.05)
column 3: sin(4*pi*0.05)
column 4: cos(4*pi*0.05)
column 5: sin(6*pi*0.05)
column 6: cos(6*pi*0.05)

I've only found very basic examples with std:vector and nested for loops which I fail to adapt to this particular problem. Can someone give me a hint of how to solve this problem?.

Body:
std::vector<std::vector<double>> matrix;
matrix.resize(100);
for (auto & line : matrix) {
    line.resize(6);
}

And then you can do:

matrix[x1][y1] = someValue;
otherValue = matrix[x2][y2];

etc.

But, if you know you will have a fixed size for your matrix, you can just do:

double matrix[100][6] = { 0.0 };

instead of creating the vectors.


问:
Check if $_POST exists
I'm trying to check whether a $_POST exists and if it does, print it inside another string, if not, don't print at all.

something like this:

```<code>$fromPerson = '+from%3A'.$_POST['fromPerson'];

function fromPerson() {
    if !($_POST['fromPerson']) {
        print ''
    } else {
        print $fromPerson
    };
}

$newString = fromPerson();
</code>```

Any help would be great!

答:
I would like to add my answer even though this thread is years old and it ranked high in Google for me.

My best method is to try:

```<code>if(sizeof($_POST) !== 0){
// Code...
}
</code>```

As $_POST is an array, if the script loads and no data is present in the $_POST variable it will have an array length of 0. This can be used in an IF statement.

You may also be wondering if this throws an "undefined index" error seeing as though we're checking if $_POST is set... In fact $_POST always exists, the "undefined index" error will only appear if you try to search for a $_POST array value that doesn't exist.

$_POST always exists in itself being either empty or has array values.
$_POST['value'] may not exist, thus throwing an "undefined index" error.

Title: Check if $_POST exists

Body:
I'm trying to check whether a $_POST exists and if it does, print it inside another string, if not, don't print at all.

something like this:

$fromPerson = '+from%3A'.$_POST['fromPerson'];

function fromPerson() {
    if !($_POST['fromPerson']) {
        print ''
    } else {
        print $fromPerson
    };
}

$newString = fromPerson();

Any help would be great!

Body:
I would like to add my answer even though this thread is years old and it ranked high in Google for me.

My best method is to try:

if(sizeof($_POST) !== 0){
// Code...
}

As $_POST is an array, if the script loads and no data is present in the $_POST variable it will have an array length of 0. This can be used in an IF statement.

You may also be wondering if this throws an "undefined index" error seeing as though we're checking if $_POST is set... In fact $_POST always exists, the "undefined index" error will only appear if you try to search for a $_POST array value that doesn't exist.

$_POST always exists in itself being either empty or has array values.
$_POST['value'] may not exist, thus throwing an "undefined index" error.


问:
Can I create a Windows installer that can add the program path to the environment variables?
I have developed an application in Go that I want to create a Windows installer for. The problem is that it is a console app that would preferably be run with just a simple call from the Terminal/Cmd Prompt. For that I need to add the installation directory to the system environment variables. Is it possible to do this through a custom Windows installer of some sorts?

I already have the exe that I will want to be added to the system environment variables. I want it to be possible for the user to install the program wherever they want and then that the installer can add that directory to the environment variables. Is this possible?

答:
Maybe you can use this if you don’t do it now: Visual Studio Create Installer Package
I don’t know the exact possibilities of this myself.</p>


问:
How to create a list with actions using materialize-css?
I'm trying to create a list with checkboxes for collecting actions with materialize, but the input tag didn't get recognized by the pattern. Is this possible?</p>

```<code>              <div class="row">
                <ul class="collection with-header" v-if="listaRoles.length > 0">
                  <li class="collection-header left-align"><h4> Roles do perfil {{ perfil.descricao }}</h4></li>
                  <li v-for="r in listaRoles" :key="r.id" class="collection-item">
                    <div class="left-align">
                      <span> {{ r.descricao }} </span>
                    <input type="checkbox" />
                    </div>
                  </li>
                </ul>
              </div>
</code>```

答:
You have to use the exact same structure as the materialize docs, otherwise your components won't work correctly. So in the case of checkboxes that is <input>, followed by , and both of these wrapped in a .

```<code>  <label>
    <input type="checkbox" />
    <span>Red</span>
  </label>
</code>```

Any deviation from this will break the component.

EDIT:

Checkboxes inside li works perfectly fine, here a codepen to demonstrate:

https://codepen.io/doughballs/pen/KKpNrPy

The error is coming from somewhere else.

https://materializecss.com/checkboxes.html

Body:
I'm trying to create a list with checkboxes for collecting actions with materialize, but the input tag didn't get recognized by the pattern. Is this possible?

 0">

 Roles do perfil {{ perfil.descricao }}

                       {{ r.descricao }}
                    <input type="checkbox" />

Body:
You have to use the exact same structure as the materialize docs, otherwise your components won't work correctly. So in the case of checkboxes that is <input>, followed by <span>, and both of these wrapped in a <label>.

  <label>
    <input type="checkbox" />
    <span>Red</span>
  </label>

Any deviation from this will break the component.

EDIT:

Checkboxes inside li works perfectly fine, here a codepen to demonstrate:

https://codepen.io/doughballs/pen/KKpNrPy

The error is coming from somewhere else.

https://materializecss.com/checkboxes.html


问:
Is Pex and Moles project still active?
They used to release a two new versions a month but since October 2010 they haven't released a new one. I've found this.
But the fact they have closed its support forum on MSDN makes me suspect the project is not going forward.
We are using it for our current project, but we are thinking to replace it for another framework before it is too late.</p>

答: It is under active development, but support seems to be non-existent. Since they have made stackoverflow their default forum, a lot of questions seem to go unanswered.</p>

Title: Is Pex and Moles project still active?


问:
Trying to put a Html string to the WebView in Xamarin
I have a little strange problem with the WebView in Xamarin (Visual Studio 2017)

This scenario works:

I am putting html content to the webview in the "OnCreate" event and the webview shows "Hello"

This scenario doesn't work:

I am creating a button control in the OnCreate and assign a click event. The clickevent Do fire so this works. But "Hello2" is not put to the WebView although I use the exact same code.

What could be the problem?

<WebView xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:id="@+id/LocalWebView">
</WebView>

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.activity_main); Android.Content.Context context = ApplicationContext;
            Android.Support.V7.Widget.Toolbar toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
            SetSupportActionBar(toolbar);

            //This works and shows: "Hello"
            WebView localWebView = FindViewById<WebView>(Resource.Id.LocalWebView);
            localWebView.SetWebViewClient(new WebViewClient()); // stops request going to Web Browser
            localWebView.LoadData("Hello", "text/html", "utf-8");

            Button button = new Button(context);
            button.Click += (sender, args) =>
            {
                //The click event fires but Hello2" is not put to the webview?
                Button btn = sender as Button;

                WebView localWebView2 = FindViewById<WebView>(Resource.Id.LocalWebView);
                localWebView2.SetWebViewClient(new WebViewClient()); // stops request going to Web Browser
                localWebView2.LoadData("Hello2", "text/html", "utf-8");
            };
        }```

答:
It worked now when I did put the width and height to the WebView.
Strangely "fill_parent" or "match_parent" didn't expand the WebView.

<WebView xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="500px"
  android:layout_height="1000px"
  android:id="@+id/LocalWebView">
</WebView>```


问:
Using an object inside of a class and using the other class' object's methods isn't working
I'm trying to make a clock object by simply making an object called "boundedCounter" which has a value and a limit, the value starts at 0 and keep counting up until it reaches the limit, then it resets to 0 and continues counting. I want to have the clock object use 3 bounded counters for each seconds, minutes and hours and the rest is simple. When I did it in java, it worked pretty good. But now after learning C++, I can't seem to find why making the boundedCounter object inside of the clock class isn't working. I tried making it an inherited class, making methods and such. Here's the code:

```<code>class boundedCounter {
private:
    int value, limit;

public:

    boundedCounter(int boundLimit) {
        value = 0;
        limit = boundLimit;
    }

    void next() {
        if (++value == limit) {
            value = 0;
        }
    }

    void setLimit(int boundLimit) {
        limit = boundLimit;
    }

    int getValue() {
        return value;
    }
};

class Clock : private boundedCounter {
public:
    boundedCounter seconds(60);
    boundedCounter minutes(60);
    boundedCounter hours(24);

    seconds.setLimit(60);
};
</code>```

Errors:

```<code>E0079 expected a type specifier line 35
E0079 expected a type specifier line 36
E0079 expected a type specifier line 37
E0077 this declaration has no storage class or type specifier line 39
E0065 expected a ';'

</code>```

答:
There are several problems in this code; First of all, there is not need to inherent from the other class! Inheritance is defined as "is a" relation. Clock isn't a bounded counter, it has 3 different counters - seconds, minutes, hours (thus, we have a "has a" relation). Therefore, you should change the relation to composition. As a rule of thumb - you should prefer composition over inheritance.

Secondly, you cannot initialize non-static member variables like that, that must be done inside non-static function (and most likely in the ctor of the class). Notice that I have put it in the initializer list, and not in the body of the ctor, which is the best practice.

The following code does compile properly:

```<code>class boundedCounter {
private:
    int value, limit;

public:

    boundedCounter(int boundLimit) {
        value = 0;
        limit = boundLimit;
    }

    void next() {
        if (++value == limit) {
            value = 0;
        }
    }

    void setLimit(int boundLimit) {
        limit = boundLimit;
    }

    int getValue() {
        return value;
    }
};

class Clock {
public:
    boundedCounter seconds;
    boundedCounter minutes;
    boundedCounter hours;

    Clock() :
    seconds(60),
    minutes(60),
    hours(24)
    {
    }
};
</code>```

Body:
I'm trying to make a clock object by simply making an object called "boundedCounter" which has a value and a limit, the value starts at 0 and keep counting up until it reaches the limit, then it resets to 0 and continues counting. I want to have the clock object use 3 bounded counters for each seconds, minutes and hours and the rest is simple. When I did it in java, it worked pretty good. But now after learning C++, I can't seem to find why making the boundedCounter object inside of the clock class isn't working. I tried making it an inherited class, making methods and such. Here's the code:

class boundedCounter {
private:
    int value, limit;

public:

    boundedCounter(int boundLimit) {
        value = 0;
        limit = boundLimit;
    }

    void next() {
        if (++value == limit) {
            value = 0;
        }
    }

    void setLimit(int boundLimit) {
        limit = boundLimit;
    }

    int getValue() {
        return value;
    }
};

class Clock : private boundedCounter {
public:
    boundedCounter seconds(60);
    boundedCounter minutes(60);
    boundedCounter hours(24);

    seconds.setLimit(60);
};

Errors:

E0079 expected a type specifier line 35
E0079 expected a type specifier line 36
E0079 expected a type specifier line 37
E0077 this declaration has no storage class or type specifier line 39
E0065 expected a ';'

Body:
There are several problems in this code; First of all, there is not need to inherent from the other class! Inheritance is defined as "is a" relation. Clock isn't a bounded counter, it has 3 different counters - seconds, minutes, hours (thus, we have a "has a" relation). Therefore, you should change the relation to composition. As a rule of thumb - you should prefer composition over inheritance.

Secondly, you cannot initialize non-static member variables like that, that must be done inside non-static function (and most likely in the ctor of the class). Notice that I have put it in the initializer list, and not in the body of the ctor, which is the best practice.

The following code does compile properly:

class boundedCounter {
private:
    int value, limit;

public:

    boundedCounter(int boundLimit) {
        value = 0;
        limit = boundLimit;
    }

    void next() {
        if (++value == limit) {
            value = 0;
        }
    }

    void setLimit(int boundLimit) {
        limit = boundLimit;
    }

    int getValue() {
        return value;
    }
};

class Clock {
public:
    boundedCounter seconds;
    boundedCounter minutes;
    boundedCounter hours;

    Clock() :
    seconds(60),
    minutes(60),
    hours(24)
    {
    }
};


问:
What characters do you send to a "Generic/Text Only" printer to print bolded and underlined characters?
I need to print a report for a project I'm working on. I'm already printing it, but some formatting is missing (bold, underline) that is used to emphasize and differentiate certain areas.

The printer is installed as "Generic/Text Only" (required by the client). I've been googling for a while now, and haven't found a way to send the right characters to make the text bolded and underlined from code.

How can I print bold and underline characters in a generic text only printer by code?

答:
Often a plain text printer will respond to the BS (backspace) character, chr(8) by moving the carriage to the left and overprinting characters. So to bold a word, you could send the characters:

```<code>t h i s SP i s SP b BS b o BS o l BS l d BS d
</code>```

and to underline:

```<code>t h i s SP i s SP u BS _ n BS _ d BS _ e BS _ r BS _ l BS _ i BS _ n BS _ e BS _ d BS _
</code>```

Sometimes the printer might respond better to CR (carriage return, chr(13)) better, which moves the carriage all the way to the left so you can space over and overprint characters:

```<code>t h i s SP i s SP b o l d CR SP SP SP SP SP SP SP SP b o l d
</code>```

Body:
Often a plain text printer will respond to the BS (backspace) character, chr(8) by moving the carriage to the left and overprinting characters. So to bold a word, you could send the characters:

t h i s SP i s SP b BS b o BS o l BS l d BS d

and to underline:

t h i s SP i s SP u BS _ n BS _ d BS _ e BS _ r BS _ l BS _ i BS _ n BS _ e BS _ d BS _

Sometimes the printer might respond better to CR (carriage return, chr(13)) better, which moves the carriage all the way to the left so you can space over and overprint characters:

t h i s SP i s SP b o l d CR SP SP SP SP SP SP SP SP b o l d


问:
Undoing a git rebase
How do I easily undo a git rebase? A lengthy manual method is:

checkout the commit parent to both of the branches

create and checkout a temporary branch

cherry-pick all commits by hand

reset the faulty rebased branch to point to the temporary branch

In my current situation, this works because I can easily spot commits from both branches (one was my stuff, the other was my colleague's stuff). However, my approach strikes me as suboptimal and error-prone (let's say I had just rebased with two of my own branches).

Clarification: I am talking about a rebase during which multiple commits were replayed, not only one.

答: I tried all suggestions with reset and reflog without any success. Restoring local history of IntelliJ resolved the problem of lost files</p>

OwnerDisplayName: webmat

Title: Undoing a git rebase


问:
Count max increasing number sequence in array
I have to find the max increasing number sequence in this array.
Does anyone know why my code doesn't run?</p>

```<code>public class Array {

public static void main(String[] args) {

    int[] a = {4,7,15,3,9,22,36,24,28,14,19,27,30,31,2,9,29,30,16,19};

    int counter = 0;
    int maxCounter = 0;

    for (int i : a) {

        if (a[i] < a[i + 1]) {
            counter++;
        }

        if (a[i] > a[i + 1]) {
            maxCounter = counter;
            counter = 0;
        }

    }

    System.out.println(maxCounter);
}

}
</code>```

答:
Working code to find the max number sequence in array.</p>

```<code>public class Array {

public static void main(String[] args) {

int[] a = {4,7,15,3,9,22,36,24,28,14,19,27,30,31,2,9,29,30,16,19};

int counter = 1;
int maxCounter = 0;

for (int i = 0; i < a.length - 1 ; i++) {
    if (a[i] < a[i + 1]) {
        counter++;
    } else if (a[i] > a[i + 1]) {
        counter = 1;
    }

    if (counter > maxCounter) {
        maxCounter = counter;
    }
}

System.out.println(maxCounter);
}
}
</code>```

Body:
I have to find the max increasing number sequence in this array.
Does anyone know why my code doesn't run?

public class Array {

public static void main(String[] args) {

    int[] a = {4,7,15,3,9,22,36,24,28,14,19,27,30,31,2,9,29,30,16,19};

    int counter = 0;
    int maxCounter = 0;

    for (int i : a) {

        if (a[i]  a[i + 1]) {
            maxCounter = counter;
            counter = 0;
        }

    }

    System.out.println(maxCounter);
}

}

Body:
Working code to find the max number sequence in array.

public class Array {

public static void main(String[] args) {

int[] a = {4,7,15,3,9,22,36,24,28,14,19,27,30,31,2,9,29,30,16,19};

int counter = 1;
int maxCounter = 0;

for (int i = 0; i < a.length - 1 ; i++) {
    if (a[i] < a[i + 1]) {
        counter++;
    } else if (a[i] > a[i + 1]) {
        counter = 1;
    }

    if (counter > maxCounter) {
        maxCounter = counter;
    }
}

System.out.println(maxCounter);
}
}


问:
Grouping input fields in Javascript
I am trying to group my name/number/email field together so I can have one event listener. I want to make it so when the user leaves the input field, it plays the audio. I have tried adding an event to the parent .infofield class but it doesn't work for onblur/focus events. I was wondering how I'd approach this in Javascript?

```<code>        <section class="infofield">
            <audio id="leave" src= "blur.mp3"></audio>

            <section>
                <p class ="name">Name*</p>
                First: <br><input type="text" name="fname" required><br/>
                Last: <br><input type="text" name="lname" required><br/>
            </section>

            <section>
                <p class ="name">Phone Number*</p>
                <input type="text" name="number" required>
            </section>

            <section>
                <p>Email*</p>
                <input type="email" name="email" required>
            </section>

        </section>
</code>```

答:
I do not see any difficulties, what is the problem?

const myForm = document.getElementById('my-form')
  ;
myForm.in_fields.querySelectorAll('input').forEach(inElm=>
  {
  inElm.onfocus=focusOn;
  inElm.onblur=focusOff;
  })
function focusOn(e)
  {
  WiGo.textContent = `evt focus on ${e.target.name}`
  }
function focusOff(e)
  {
  WiGo.textContent = `evt blur on ${e.target.name}`
  }

/* previous version --------------------------------------------------
myForm.in_fields.onmouseover=e=>
  {
  WiGo.textContent = 'mouse is over Personal informations fields'
  }
myForm.in_fields.onmouseout=e=>
  {
  WiGo.textContent = 'mouse is out of Personal informations fields'
  }
----------------------------------------------------------------------*/  ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#my-form{
  font-size: 14px;
  font-family: Arial, Helvetica, sans-serif;
}
fieldset {
  width:22em;
  padding: 0 1em;
}
legend::before,
legend::after {
   content: '\00a0'
}
label,input {
  float: left;
  margin: .4em;
}
input {
  width:11em ;
  padding: .2em;
  border-width: 1px;
  padding: .3em 5px;
}
label {
  display: block;
  clear: both;
  width: 9em;
  text-align: right;
  line-height: 1.5em;
}
label::after {
   content: '* :'
}</code>```

<form id="my-form">

  <fieldset name="in_fields">
    <legend>Personal informations</legend>

     First Name
    <input type="text" name="fname" required>

    Last Name
    <input type="text" name="lname" required>

    Phone Number
    <input type="text" name="number" required>

    Email
    <input type="email" name="email" required>
  </fieldset>

What's going on ?

</form>```

Title: Grouping input fields in Javascript

Body:
I am trying to group my name/number/email field together so I can have one event listener. I want to make it so when the user leaves the input field, it plays the audio. I have tried adding an event to the parent .infofield class but it doesn't work for onblur/focus events. I was wondering how I'd approach this in Javascript?

            <audio id="leave" src= "blur.mp3"></audio>

Name*

                First:
<input type="text" name="fname" required>

                Last:
<input type="text" name="lname" required>

Phone Number*

                <input type="text" name="number" required>

Email*

                <input type="email" name="email" required>

Body:
I do not see any difficulties, what is the problem?

const myForm = document.getElementById('my-form')
  ;
myForm.in_fields.querySelectorAll('input').forEach(inElm=>
  {
  inElm.onfocus=focusOn;
  inElm.onblur=focusOff;
  })
function focusOn(e)
  {
  WiGo.textContent = `evt focus on ${e.target.name}`
  }
function focusOff(e)
  {
  WiGo.textContent = `evt blur on ${e.target.name}`
  }

/* previous version --------------------------------------------------
myForm.in_fields.onmouseover=e=>
  {
  WiGo.textContent = 'mouse is over Personal informations fields'
  }
myForm.in_fields.onmouseout=e=>
  {
  WiGo.textContent = 'mouse is out of Personal informations fields'
  }
----------------------------------------------------------------------*/

#my-form{
  font-size: 14px;
  font-family: Arial, Helvetica, sans-serif;
}
fieldset {
  width:22em;
  padding: 0 1em;
}
legend::before,
legend::after {
   content: '\00a0'
}
label,input {
  float: left;
  margin: .4em;
}
input {
  width:11em ;
  padding: .2em;
  border-width: 1px;
  padding: .3em 5px;
}
label {
  display: block;
  clear: both;
  width: 9em;
  text-align: right;
  line-height: 1.5em;
}
label::after {
   content: '* :'
}

<form id="my-form">

  <!--audio id="leave" src= "blur.mp3"></audio -->

  <fieldset name="in_fields">
    <legend>Personal informations</legend>

    <label> First Name</label>
    <input type="text" name="fname" required>

    <label>Last Name</label>
    <input type="text" name="lname" required>

    <label>Phone Number</label>
    <input type="text" name="number" required>

    <label>Email</label>
    <input type="email" name="email" required>
  </fieldset>

  <p id="WiGo" >What's going on ?</p>

</form>


问:
How do I use PDO::FETCH_CLASS with namespace?
I'm learning PHP and right now I'm displaying some articles with PDO. I have some issue using PDO::FETCH_CLASS with the usage of namespace.

my folder architecture:

```<code>class/
- Post.php
layout/
-articles/
--articles.php
public/
-index.php (contains my router)
</code>```

Post.php

```<code>namespace App\Articles;

class Post {
    private $id;
    private $name;
    private $content;
    private $date;

    public function getId()
    {
        return $this->id;
    }
    public function getName()
    {
        return $this->name;
    }
    public function getContent()
    {
        return $this->content;
    }
    public function getExcerpt()
    {
        $res = $this->content;
        return (strlen($res) > 150) ? substr($res, 0, 150) . '...' : $res;
    }
    public function getDate()
    {
        return $this->date = date('d-m-Y', $this->date);
    }
}
</code>```

data.db contains only four columns: id, name(text), content(text), created_at(int)

The part I have trouble with:

```<code>use App\Articles\Post;

$pdo = new PDO('sqlite:../data.db', null, null, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ
]);
try {
    $query = $pdo->query('SELECT * FROM posts');
    $posts = $query->fetchAll(PDO::FETCH_CLASS, 'Post');
} catch (PDOException $e) {
    $error = $e->getMessage();
}
</code>```

I tried different typing instead of 'Postlike

```<code>'App\Articles\'
'App\Articles\Post'
'App\Articles\::POST'
...
</code>```

I can't manage to make it works with namepsace.
It works with a require '../class/Post.php'.

Is there a solution for this problem or should I just use the require ?

答: I forgot to add the folder Articles in class/ so App\Articles\Post couldn't be find.</p>

Body:
I'm learning PHP and right now I'm displaying some articles with PDO. I have some issue using PDO::FETCH_CLASS with the usage of namespace.

my folder architecture:

class/
- Post.php
layout/
-articles/
--articles.php
public/
-index.php (contains my router)

Post.php

namespace App\Articles;

class Post {
    private $id;
    private $name;
    private $content;
    private $date;

    public function getId()
    {
        return $this->id;
    }
    public function getName()
    {
        return $this->name;
    }
    public function getContent()
    {
        return $this->content;
    }
    public function getExcerpt()
    {
        $res = $this->content;
        return (strlen($res) > 150) ? substr($res, 0, 150) . '...' : $res;
    }
    public function getDate()
    {
        return $this->date = date('d-m-Y', $this->date);
    }
}

data.db contains only four columns: id, name(text), content(text), created_at(int)

The part I have trouble with:

use App\Articles\Post;

$pdo = new PDO('sqlite:../data.db', null, null, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ
]);
try {
    $query = $pdo->query('SELECT * FROM posts');
    $posts = $query->fetchAll(PDO::FETCH_CLASS, 'Post');
} catch (PDOException $e) {
    $error = $e->getMessage();
}

I tried different typing instead of 'Postlike

'App\Articles\'
'App\Articles\Post'
'App\Articles\::POST'
...

I can't manage to make it works with namepsace.
It works with a require '../class/Post.php'.

Is there a solution for this problem or should I just use the require ?


问:
Changing execution stack in x86 from Rust
I am trying to manually set RSP and start execution at a custom address in Rust with inline x86_64 assembly.

I have this C code which works:

```<code>#include <stddef.h>

void __attribute ((noreturn)) jump_with_stack(size_t jump_addr, size_t *jump_stack) {
            __asm__ volatile ( \
                        "movq %[stack], %%rsp\n" \
                        "xor %%rdx, %%rdx\n" \
                        "jmp *%[entry]" \
                        : /* None  */ \
                        : [stack] "r" (jump_stack), [entry] "r" (jump_addr) \
                        : "rdx", "memory" \
                        );
}
</code>```

This is the disassembly:

```<code>jump_with_stack:
        push    rbp
        mov     rbp, rsp
        mov     QWORD PTR [rbp-8], rdi
        mov     QWORD PTR [rbp-16], rsi
        mov     rax, QWORD PTR [rbp-16]
        mov     rcx, QWORD PTR [rbp-8]
        movq rax, %rsp
        xor %rdx, %rdx
        jmp *rcx
        nop
        pop     rbp
        ret
</code>```

And this Rust code that does not:

```<code>#![feature(asm)]

pub unsafe extern fn rust_jump_with_stack(target: usize, targ_stack: *mut usize) -> ! {

    asm!("mov rsp, $0
         xor rdx, rdx
         jmp [$1]"
         :
         :"r"(targ_stack), "r"(target)
         : "rdx", "memory"
         : "intel");
    unreachable!();
}
</code>```

Here is the rust disassembly:

```<code>example::rust_jump_with_stack:
    push    rax

    mov     rsp, rsi
    xor     rdx, rdx
    jmp     qword ptr [rdi]

    lea     rdi, [rip + .L__unnamed_3]
    lea     rdx, [rip + .L__unnamed_4]
    mov     rax, qword ptr [rip + std::panicking::begin_panic@GOTPCREL]
    mov     esi, 40
    call    rax
    ud2
</code>```

(Both disassembly outputs are from Godbolt explorer)

I don't understand the difference between the two or what the difference in the generated code means.

答:
jmp [$1] is an extra level of indirection that you don't have in your AT&T version.

AT&T jmp *%1 is equivalent to Intel jmp %1.

Note that %[entry] is just a symbolic way of writing %1; the square brackets are part of the operand-name syntax and don't end up in the final asm output as an addressing-mode syntax.

(Also your question is a total mess because you use -masm=intel on Godbolt while your GNU C inline asm is written to be built with the default -masm=att.)

The other major differences are that GCC defaults to -O0 (anti-optimized debug mode), while you built your Rust code with optimization enabled.

You should probably use __builtin_unreachable() after your C asm("") statement to make sure the compiler knows that execution really doesn't come out the other side of the asm statement.  I'd worry that marking the wrapper function noreturn might not be sufficient to prevent having the compiler assume it can defer a store until after the asm statement, after inlining.  (Jumping out of an asm statement normally requires asm goto for known labels, otherwise __builtin_unreachable() is recommended.)

Body:
I am trying to manually set RSP and start execution at a custom address in Rust with inline x86_64 assembly.

I have this C code which works:

#include <stddef.h>

void __attribute ((noreturn)) jump_with_stack(size_t jump_addr, size_t *jump_stack) {
            __asm__ volatile ( \
                        "movq %[stack], %%rsp\n" \
                        "xor %%rdx, %%rdx\n" \
                        "jmp *%[entry]" \
                        : /* None  */ \
                        : [stack] "r" (jump_stack), [entry] "r" (jump_addr) \
                        : "rdx", "memory" \
                        );
}

This is the disassembly:

jump_with_stack:
        push    rbp
        mov     rbp, rsp
        mov     QWORD PTR [rbp-8], rdi
        mov     QWORD PTR [rbp-16], rsi
        mov     rax, QWORD PTR [rbp-16]
        mov     rcx, QWORD PTR [rbp-8]
        movq rax, %rsp
        xor %rdx, %rdx
        jmp *rcx
        nop
        pop     rbp
        ret

And this Rust code that does not:

#![feature(asm)]

pub unsafe extern fn rust_jump_with_stack(target: usize, targ_stack: *mut usize) -> ! {

    asm!("mov rsp, $0
         xor rdx, rdx
         jmp [$1]"
         :
         :"r"(targ_stack), "r"(target)
         : "rdx", "memory"
         : "intel");
    unreachable!();
}

Here is the rust disassembly:

example::rust_jump_with_stack:
    push    rax

    mov     rsp, rsi
    xor     rdx, rdx
    jmp     qword ptr [rdi]

    lea     rdi, [rip + .L__unnamed_3]
    lea     rdx, [rip + .L__unnamed_4]
    mov     rax, qword ptr [rip + std::panicking::begin_panic@GOTPCREL]
    mov     esi, 40
    call    rax
    ud2

(Both disassembly outputs are from Godbolt explorer)

I don't understand the difference between the two or what the difference in the generated code means.