问:
Android check file error "Type mismatch: inferred type is Context but Path! was expected"
I am trying to introduce local JSON storage into an app that I am making.  I have used this method of JSON storage before, but I have never gotten these errors; Type mismatch: inferred type is Context but Path! was expected and Type mismatch: inferred type is String but LinkOption! was expected
The errors appear as follows on context and JSON_FILE:

```<code> constructor (context: Context) {
        this.context = context
        if (exists(context, JSON_FILE)) {
            deserialize()
        }
    }
</code>```

Here is the class:

```<code>package ie.wit.models

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import org.jetbrains.anko.AnkoLogger
import java.nio.file.Files.exists
import kotlin.random.Random
import ie.wit.helpers.**/
import android.content.Context
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import org.jetbrains.anko.AnkoLogger
import ie.wit.helpers.*
import java.nio.file.Files.exists
import java.util.*

val JSON_FILE = "bookings.json"
val gsonBuilder = GsonBuilder().setPrettyPrinting().create()
val listType = object: TypeToken<ArrayList<ValetModel>>(){}.type

fun generateRandomId(): Long {
    return Random().nextLong()
}

class ValetJSONStore: ValetStore, AnkoLogger{
    val context: Context
    var bookings = mutableListOf<ValetModel>()

    constructor (context: Context) {
        this.context = context
        if (exists(context, JSON_FILE)) {
            deserialize()
        }
    }

    override fun findAll(): List<ValetModel> {
        return bookings
    }

    override fun create(valet: ValetModel) {
        valet.id = generateRandomId()
        bookings.add(valet)
        serialize()
    }

    override fun update(valet: ValetModel) {
        val bookingsList = findAll() as ArrayList<ValetModel>
        var foundBooking: ValetModel? = bookingsList.find{p -> p.id == valet.id}
        if(foundBooking != null){
            foundBooking.brand = valet.brand
            foundBooking.model = valet.model
            foundBooking.numberPlate = valet.numberPlate
            foundBooking.date = valet.date
        }
        serialize()
    }

    override fun delete(valet: ValetModel) {
        bookings.remove(valet)
        serialize()
    }

    private fun serialize(){
        val jsonString = gsonBuilder.toJson(bookings, listType)
        write(context, JSON_FILE, jsonString)
    }

    private fun deserialize() {
        val jsonString = read(context, JSON_FILE)
        bookings = Gson().fromJson(jsonString, listType)
    }

}
</code>```

答:
To explain why you are getting that error: If you check the documentation for exists(..) for import java.nio.file.Files.existsit expects a Pathand not a Context:

```<code>/**
     * Tests whether a file exists.
     *
     * <p> The {@code options} parameter may be used to indicate how symbolic links
     * are handled for the case that the file is a symbolic link. By default,
     * symbolic links are followed. If the option {@link LinkOption#NOFOLLOW_LINKS
     * NOFOLLOW_LINKS} is present then symbolic links are not followed.
     *
     * <p> Note that the result of this method is immediately outdated. If this
     * method indicates the file exists then there is no guarantee that a
     * subsequence access will succeed. Care should be taken when using this
     * method in security sensitive applications.
     *
     * @param   path
     *          the path to the file to test
     * @param   options
     *          options indicating how symbolic links are handled
     * .
     * @return  {@code true} if the file exists; {@code false} if the file does
     *          not exist or its existence cannot be determined.
     *
     * @throws  SecurityException
     *          In the case of the default provider, the {@link
     *          SecurityManager#checkRead(String)} is invoked to check
     *          read access to the file.
     *
     * @see #notExists
 */
public static boolean exists(Path path, LinkOption... options) {
    try {
        if (followLinks(options)) {
            provider(path).checkAccess(path);
        } else {
            // attempt to read attributes without following links
            readAttributes(path, BasicFileAttributes.class,
                           LinkOption.NOFOLLOW_LINKS);
        }
        // file exists
        return true;
    } catch (IOException x) {
        // does not exist or unable to determine if file exists
        return false;
    }

}
</code>```

Probably in other classes where you have implemented the same thing maybe you are trying to use an exists(..) method imported from somewhere else different from java.nio.file.Files.exists?

To check if that file exists or not you have many options, but for now I can list you two options, of which one you already tried to use (exists(..) which is available from API 26):

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

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import java.io.File
import java.nio.file.Files.exists
import java.nio.file.Paths

class MainActivity : AppCompatActivity() {

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

        val JSON_FILE = "bookings.json"

        // One option to check if file exists (available from API 26)
        if (exists(Paths.get(JSON_FILE))) {
            //
        }

        // Another option to check if file exists (available from API 1)
        val file = File(JSON_FILE)
        if (file.exists()) {
            //
        }
    }
}
</code>```

Body:
I am trying to introduce local JSON storage into an app that I am making.  I have used this method of JSON storage before, but I have never gotten these errors; Type mismatch: inferred type is Context but Path! was expected and Type mismatch: inferred type is String but LinkOption! was expected
The errors appear as follows on context and JSON_FILE:

 constructor (context: Context) {
        this.context = context
        if (exists(context, JSON_FILE)) {
            deserialize()
        }
    }

Here is the class:

package ie.wit.models

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import org.jetbrains.anko.AnkoLogger
import java.nio.file.Files.exists
import kotlin.random.Random
import ie.wit.helpers.**/
import android.content.Context
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import org.jetbrains.anko.AnkoLogger
import ie.wit.helpers.*
import java.nio.file.Files.exists
import java.util.*

val JSON_FILE = "bookings.json"
val gsonBuilder = GsonBuilder().setPrettyPrinting().create()
val listType = object: TypeToken<ArrayList<ValetModel>>(){}.type

fun generateRandomId(): Long {
    return Random().nextLong()
}

class ValetJSONStore: ValetStore, AnkoLogger{
    val context: Context
    var bookings = mutableListOf<ValetModel>()

    constructor (context: Context) {
        this.context = context
        if (exists(context, JSON_FILE)) {
            deserialize()
        }
    }

    override fun findAll(): List<ValetModel> {
        return bookings
    }

    override fun create(valet: ValetModel) {
        valet.id = generateRandomId()
        bookings.add(valet)
        serialize()
    }

    override fun update(valet: ValetModel) {
        val bookingsList = findAll() as ArrayList<ValetModel>
        var foundBooking: ValetModel? = bookingsList.find{p -> p.id == valet.id}
        if(foundBooking != null){
            foundBooking.brand = valet.brand
            foundBooking.model = valet.model
            foundBooking.numberPlate = valet.numberPlate
            foundBooking.date = valet.date
        }
        serialize()
    }

    override fun delete(valet: ValetModel) {
        bookings.remove(valet)
        serialize()
    }

    private fun serialize(){
        val jsonString = gsonBuilder.toJson(bookings, listType)
        write(context, JSON_FILE, jsonString)
    }

    private fun deserialize() {
        val jsonString = read(context, JSON_FILE)
        bookings = Gson().fromJson(jsonString, listType)
    }

}

Body:
To explain why you are getting that error: If you check the documentation for exists(..) for import java.nio.file.Files.existsit expects a Pathand not a Context:

/**
     * Tests whether a file exists.
     *
     * <p> The {@code options} parameter may be used to indicate how symbolic links
     * are handled for the case that the file is a symbolic link. By default,
     * symbolic links are followed. If the option {@link LinkOption#NOFOLLOW_LINKS
     * NOFOLLOW_LINKS} is present then symbolic links are not followed.
     *
     * <p> Note that the result of this method is immediately outdated. If this
     * method indicates the file exists then there is no guarantee that a
     * subsequence access will succeed. Care should be taken when using this
     * method in security sensitive applications.
     *
     * @param   path
     *          the path to the file to test
     * @param   options
     *          options indicating how symbolic links are handled
     * .
     * @return  {@code true} if the file exists; {@code false} if the file does
     *          not exist or its existence cannot be determined.
     *
     * @throws  SecurityException
     *          In the case of the default provider, the {@link
     *          SecurityManager#checkRead(String)} is invoked to check
     *          read access to the file.
     *
     * @see #notExists
 */
public static boolean exists(Path path, LinkOption... options) {
    try {
        if (followLinks(options)) {
            provider(path).checkAccess(path);
        } else {
            // attempt to read attributes without following links
            readAttributes(path, BasicFileAttributes.class,
                           LinkOption.NOFOLLOW_LINKS);
        }
        // file exists
        return true;
    } catch (IOException x) {
        // does not exist or unable to determine if file exists
        return false;
    }

}

Probably in other classes where you have implemented the same thing maybe you are trying to use an exists(..) method imported from somewhere else different from java.nio.file.Files.exists?

To check if that file exists or not you have many options, but for now I can list you two options, of which one you already tried to use (exists(..) which is available from API 26):

package com.example.myapplication

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import java.io.File
import java.nio.file.Files.exists
import java.nio.file.Paths

class MainActivity : AppCompatActivity() {

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

        val JSON_FILE = "bookings.json"

        // One option to check if file exists (available from API 26)
        if (exists(Paths.get(JSON_FILE))) {
            //
        }

        // Another option to check if file exists (available from API 1)
        val file = File(JSON_FILE)
        if (file.exists()) {
            //
        }
    }
}


来源: stackexchange

问:
Apache Cassandra COPY FROM, datetime entered incorrectly
I can see a strange issue with COPY FROM command in Cassandra with datetime values.

My timezone and my server's timezone is same. IST (GMT+5:30)

First i tried inserting a value with INSERT query.

```<code>INSERT INTO activity (home_id, datetime, event, code_used) VALUES ('H01474777', '2014-05-21 07:32:16', 'alarm set', '5599');
</code>```

It gave me the below row.

```<code> home_id   | datetime                        | code_used | event
-----------+---------------------------------+-----------+-----------
 H01474777 | 2014-05-21 02:02:16.000000+0000 |      5599 | alarm set
</code>```

Here Cassandra is showing the time value in GMT by removing +5:30

But when i tried to insert the below via the COPY FROM command and you can see that it added +5:30 when showing the GMT value, its like when adding the row it added 11 hours to the time.
See file, query and output below respectively.

```<code>home_id|datetime|event|code_used
H02257222|2014-05-21 05:29:47|alarm set|1566
H01474777|2014-05-21 07:32:16|alarm set|5599
</code>```

Query:

```<code>COPY activity (home_id, datetime, event, code_used) FROM '/home/cass/events.csv' WITH HEADER = TRUE AND DELIMITER = '|';
</code>```

Result:

```<code> home_id   | datetime                        | code_used | event
-----------+---------------------------------+-----------+-----------
 H01474777 | 2014-05-21 13:02:16.000000+0000 |      5599 | alarm set
 H01474777 | 2014-05-21 02:02:16.000000+0000 |      5599 | alarm set --Old row from insert query.
 H02257222 | 2014-05-21 10:59:47.000000+0000 |      1566 | alarm set
</code>```

Here the first 2 rows are same data and the first 2 columns of the table are primary key but still another row has been created where as there should have been 2 rows only.

答:
I was able to replicate the scenario you have mentioned.

My server timezone EST .

I ran the insert that you provided and used the file you provided to load the data with copy command

```<code>INSERT INTO activity (home_id, datetime, event, code_used) VALUES ('H01474777', '2014-05-21 07:32:16', 'alarm set', 5599);

home_id   | datetime                        | code_used | event
-----------+---------------------------------+-----------+-----------
H01474777 | 2014-05-21 07:32:16.000000+0000 |      5599 | alarm set

COPY activity (home_id, datetime, event, code_used) FROM 'temp.csv' WITH HEADER = TRUE AND DELIMITER = '|'

 home_id   | datetime                        | code_used | event
-----------+---------------------------------+-----------+-----------
 H01474777 | 2014-05-21 02:32:16.000000+0000 |      5599 | alarm set
 H01474777 | 2014-05-21 07:32:16.000000+0000 |      5599 | alarm set
 H02257222 | 2014-05-21 00:29:47.000000+0000 |      1566 | alarm set
</code>```

In the file you did not mention any timezone for datetime column. so it considering local zone as its zone. In my case it is EST so -0500 and your case it is IST so +0530

your file will be like

```<code>home_id|datetime|event|code_used
H02257222|2014-05-21 05:29:47.000+0530|alarm set|1566
H01474777|2014-05-21 07:32:16.000+0530|alarm set|5599
</code>```

If you modify you csv file as below. Then you will only see one row for H01474777.

```<code>home_id|datetime|event|code_used
H02257222|2014-05-21 05:29:47.000+0000|alarm set|1566
H01474777|2014-05-21 07:32:16.000+0000|alarm set|5599
</code>```

Hope this helps! Let me know if you have any questions.

ContentLicense: CC BY-SA 4.0

Body:
I can see a strange issue with COPY FROM command in Cassandra with datetime values.

My timezone and my server's timezone is same. IST (GMT+5:30)

First i tried inserting a value with INSERT query.

INSERT INTO activity (home_id, datetime, event, code_used) VALUES ('H01474777', '2014-05-21 07:32:16', 'alarm set', '5599');

It gave me the below row.

 home_id   | datetime                        | code_used | event
-----------+---------------------------------+-----------+-----------
 H01474777 | 2014-05-21 02:02:16.000000+0000 |      5599 | alarm set

Here Cassandra is showing the time value in GMT by removing +5:30

But when i tried to insert the below via the COPY FROM command and you can see that it added +5:30 when showing the GMT value, its like when adding the row it added 11 hours to the time.
See file, query and output below respectively.

home_id|datetime|event|code_used
H02257222|2014-05-21 05:29:47|alarm set|1566
H01474777|2014-05-21 07:32:16|alarm set|5599

Query:

COPY activity (home_id, datetime, event, code_used) FROM '/home/cass/events.csv' WITH HEADER = TRUE AND DELIMITER = '|';

Result:

 home_id   | datetime                        | code_used | event
-----------+---------------------------------+-----------+-----------
 H01474777 | 2014-05-21 13:02:16.000000+0000 |      5599 | alarm set
 H01474777 | 2014-05-21 02:02:16.000000+0000 |      5599 | alarm set --Old row from insert query.
 H02257222 | 2014-05-21 10:59:47.000000+0000 |      1566 | alarm set

Here the first 2 rows are same data and the first 2 columns of the table are primary key but still another row has been created where as there should have been 2 rows only.

Body:
I was able to replicate the scenario you have mentioned.

My server timezone EST .

I ran the insert that you provided and used the file you provided to load the data with copy command

INSERT INTO activity (home_id, datetime, event, code_used) VALUES ('H01474777', '2014-05-21 07:32:16', 'alarm set', 5599);

home_id   | datetime                        | code_used | event
-----------+---------------------------------+-----------+-----------
H01474777 | 2014-05-21 07:32:16.000000+0000 |      5599 | alarm set

COPY activity (home_id, datetime, event, code_used) FROM 'temp.csv' WITH HEADER = TRUE AND DELIMITER = '|'

 home_id   | datetime                        | code_used | event
-----------+---------------------------------+-----------+-----------
 H01474777 | 2014-05-21 02:32:16.000000+0000 |      5599 | alarm set
 H01474777 | 2014-05-21 07:32:16.000000+0000 |      5599 | alarm set
 H02257222 | 2014-05-21 00:29:47.000000+0000 |      1566 | alarm set

In the file you did not mention any timezone for datetime column. so it considering local zone as its zone. In my case it is EST so -0500 and your case it is IST so +0530

your file will be like

home_id|datetime|event|code_used
H02257222|2014-05-21 05:29:47.000+0530|alarm set|1566
H01474777|2014-05-21 07:32:16.000+0530|alarm set|5599

If you modify you csv file as below. Then you will only see one row for H01474777.

home_id|datetime|event|code_used
H02257222|2014-05-21 05:29:47.000+0000|alarm set|1566
H01474777|2014-05-21 07:32:16.000+0000|alarm set|5599

Hope this helps! Let me know if you have any questions.


问:
Adding dictonary with static keys inside another dictonary in python 3
I wanna make a dictonary with another dictonary that have fixed keys e.g

```<code>dic1 = {'filename':'file1','namelen':'5'}
dic2 = {
"file1":dic1,
"file2":dic2,
...
...
}
</code>```

The issue with my code is adding a new dictonary overwrites all the exisitng inner dictonary.

```<code>dic1 ={}
dic2 ={}
file_list = ["file1","file2", "file3"]
for file in file_list:
 dic1["filename"] = file
 dic1["namelen"] = len(file)
 dic2[file] = dic1
print(dic2)
</code>```

My dictonary looks like this

```<code>    dic2 =
{
'file1': {'namelen': 5, 'filename': 'file3'},
'file3': {'namelen': 5, 'filename': 'file3'},
'file2': {'namelen': 5, 'filename': 'file3'}
}
</code>```

How to prevent the overwrite, without switching to list ?

答:
This might useful.

```<code>dic2 = dict()
file_list = ["file1", "file2", "file3"]
for file_name in file_list:
    dic1 = dict()
    dic1["filename"] = file_name
    dic1["namelen"] = len(file_name)
    dic2[file_name] = dic1
print(dic2)
</code>```

Output:

```<code>{
     'file1': {'filename': 'file1', 'namelen': 5},
     'file2': {'filename': 'file2', 'namelen': 5},
     'file3': {'filename': 'file3', 'namelen': 5}
}
</code>```

Body:
I wanna make a dictonary with another dictonary that have fixed keys e.g

dic1 = {'filename':'file1','namelen':'5'}
dic2 = {
"file1":dic1,
"file2":dic2,
...
...
}

The issue with my code is adding a new dictonary overwrites all the exisitng inner dictonary.

dic1 ={}
dic2 ={}
file_list = ["file1","file2", "file3"]
for file in file_list:
 dic1["filename"] = file
 dic1["namelen"] = len(file)
 dic2[file] = dic1
print(dic2)

My dictonary looks like this

    dic2 =
{
'file1': {'namelen': 5, 'filename': 'file3'},
'file3': {'namelen': 5, 'filename': 'file3'},
'file2': {'namelen': 5, 'filename': 'file3'}
}

How to prevent the overwrite, without switching to list ?

Body:
This might useful.

dic2 = dict()
file_list = ["file1", "file2", "file3"]
for file_name in file_list:
    dic1 = dict()
    dic1["filename"] = file_name
    dic1["namelen"] = len(file_name)
    dic2[file_name] = dic1
print(dic2)

Output:

{
     'file1': {'filename': 'file1', 'namelen': 5},
     'file2': {'filename': 'file2', 'namelen': 5},
     'file3': {'filename': 'file3', 'namelen': 5}
}


问:
Stackdriver custom label usage in email alerts for metric conditions
In Stackdriver, I am trying to incorporate labels, or specific data values from logs, in email alert documentation, eg error message. I have included the metric selected in Aggregation as well. But they still throw null outputs.
Are there any other settings that need to be checked. I tried following variables\labels in the formats specified while updating policy documentation of metric email alerts - ${metric.label.errortext} (errortext - label)

```<code>${metric.label.query}(query - label)
</code>```

Metric variables

```<code>${protoPayload.serviceData.jobInsertRequest.resource.jobConfiguration.query.query}

${severity}

${metric.label.severity}
</code>```

Above all are returning null value.

答:
So after multiple tries, I finally figured out the source of the issue.  Alerting with custom labels, needs to be grouped, as obviously, unless grouped you cannot be having alerts within specific time spaces with same label data.   To a certain extent its like SQL group by clause parameters, should be existing in Select as well.
Anyways, the answer was pretty much there in the previous posts-

1. Create your log based metric, and label your target parameter say X

2. Create the alerting policy

3. In conditions, add the Metric created.  Note, importantly the Group By clause needs to include label X.

4. I found using aggregate 'sum' to best suite my requirement, of receiving alerts for every occurrence of the log metric.  I am not clear on the other aggregate params, and how effective they are.

6. For configuration I have used Any time series Violation

7. In policy document, when including the said label, it should be in the form ${metric.label.X}

Add Notification channels, and let it run.  This is working perfectly for my requirement now.

Body:
In Stackdriver, I am trying to incorporate labels, or specific data values from logs, in email alert documentation, eg error message. I have included the metric selected in Aggregation as well. But they still throw null outputs.
Are there any other settings that need to be checked. I tried following variables\labels in the formats specified while updating policy documentation of metric email alerts - ${metric.label.errortext} (errortext - label)

${metric.label.query}(query - label)

Metric variables

${protoPayload.serviceData.jobInsertRequest.resource.jobConfiguration.query.query}

${severity}

${metric.label.severity}

Above all are returning null value.


问:
how to get an itemprop element value with cheerio?
I am trying for the first time cheerio library to do a little bit of web scraping from paginas amarillas, such as companies name, address etc... The address is in a span inside a span with no class, only an itemprop="streetAddres", I have tried different ways as it is a long string to get to that selector, I get data until the one right before the itemprop but I do not know how to aim the itemprop selector, the one I am having troubles with is the pathAddreses constant it returns an empty array on the console log, if I delete the last element of the string(itemprop='streetAddres') it brings me data but not exactly the one I want

Here is the code:

```<code>const cheerio = require("cheerio");
const request = require("request-promise");
//const of the classes of the paginas amarillas elements we are aiming to
const pathProfesionals1 =
  ".container .row .first-content-listado .col-lg-7.col-md-8.col-xs-12 .bloque-central .central .listado-item.item-ip .box .cabecera .row .col-xs-11.comercial-nombre a h2 span";
const pathProfesionals2 =
  ".container .row .first-content-listado .col-lg-7.col-md-8.col-xs-12 .bloque-central .central .listado-item.item-ig .box .cabecera .row .col-xs-11.comercial-nombre a h2 span";
const pathTelephones1 =
  ".container .row .first-content-listado .col-lg-7.col-md-8.col-xs-12 .bloque-central .central .listado-item.item-ip .box .pie-pastilla .row .col-xs-4 a.llama-desplegable.btn.btn-amarillo.btn-block.phone.hidden.d-none span";
const pathTelephones2 =
  ".container .row .first-content-listado .col-lg-7.col-md-8.col-xs-12 .bloque-central .central .listado-item.item-ig .box .pie-pastilla .row .col-xs-4 a.llama-desplegable.btn.btn-amarillo.btn-block.phone.hidden.d-none span";
const pathAddress1 = `.container .row .first-content-listado .col-lg-7.col-md-8.col-xs-12 .bloque-central .central .listado-item.item-ig .box .row a .location span *[itemprop = 'streetAddress']`;

const pathAddress2 = "";

init = async () => {
    const arrCompanyName = [];
    const arrTelephones = [];
    const arrAddresses = [];

    const { category, city } = this.state;

    const $ = await request({
      uri: `https://www.paginasamarillas.es/search/${category}/all-ma/${city}/all-is/malaga/all-ba/all-pu/all-nc/1?what=carpintero&where=malaga&ub=false&qc=true`,
      transform: body => cheerio.load(body) //una vez hago la peticion lo paso a cheerio para que lo analice
    });

    const profesionals1 = $(pathProfesionals1).each((i, el) =>
      arrCompanyName.push($(el).text())
    );

    const telephones1 = $(pathTelephones1).each((i, el) =>
      arrTelephones.push($(el).text())
    );

    const profesionals2 = $(pathProfesionals2).each((i, el) =>
      arrCompanyName.push($(el).text())
    );

    const telephones2 = $(pathTelephones2).each((i, el) =>
      arrTelephones.push($(el).text())
    );

    const addresses1 = $(pathAddress1).each((i, el) =>
      arrAddresses.push($(el).text())
    );

    console.log(arrAddresses);
}
</code>```

答:
If you want to select the span tag with itemprop='streetAddress' attribute only then you need to remove * from the address selector. Currently, Cheerio is trying to get all the tags with itemprop=streetAddress inside and not with span.

Also if you want to select all the addresses from that list you can run a simple query with $(".listado-item .links span[itemprop='streetAddress']") then iterate the Cheerio object array.

Body:
I am trying for the first time cheerio library to do a little bit of web scraping from paginas amarillas, such as companies name, address etc... The address is in a span inside a span with no class, only an itemprop="streetAddres", I have tried different ways as it is a long string to get to that selector, I get data until the one right before the itemprop but I do not know how to aim the itemprop selector, the one I am having troubles with is the pathAddreses constant it returns an empty array on the console log, if I delete the last element of the string(itemprop='streetAddres') it brings me data but not exactly the one I want

Here is the code:

const cheerio = require("cheerio");
const request = require("request-promise");
//const of the classes of the paginas amarillas elements we are aiming to
const pathProfesionals1 =
  ".container .row .first-content-listado .col-lg-7.col-md-8.col-xs-12 .bloque-central .central .listado-item.item-ip .box .cabecera .row .col-xs-11.comercial-nombre a h2 span";
const pathProfesionals2 =
  ".container .row .first-content-listado .col-lg-7.col-md-8.col-xs-12 .bloque-central .central .listado-item.item-ig .box .cabecera .row .col-xs-11.comercial-nombre a h2 span";
const pathTelephones1 =
  ".container .row .first-content-listado .col-lg-7.col-md-8.col-xs-12 .bloque-central .central .listado-item.item-ip .box .pie-pastilla .row .col-xs-4 a.llama-desplegable.btn.btn-amarillo.btn-block.phone.hidden.d-none span";
const pathTelephones2 =
  ".container .row .first-content-listado .col-lg-7.col-md-8.col-xs-12 .bloque-central .central .listado-item.item-ig .box .pie-pastilla .row .col-xs-4 a.llama-desplegable.btn.btn-amarillo.btn-block.phone.hidden.d-none span";
const pathAddress1 = `.container .row .first-content-listado .col-lg-7.col-md-8.col-xs-12 .bloque-central .central .listado-item.item-ig .box .row a .location span *[itemprop = 'streetAddress']`;

const pathAddress2 = "";

init = async () => {
    const arrCompanyName = [];
    const arrTelephones = [];
    const arrAddresses = [];

    const { category, city } = this.state;

    const $ = await request({
      uri: `https://www.paginasamarillas.es/search/${category}/all-ma/${city}/all-is/malaga/all-ba/all-pu/all-nc/1?what=carpintero&where=malaga&ub=false&qc=true`,
      transform: body => cheerio.load(body) //una vez hago la peticion lo paso a cheerio para que lo analice
    });

    const profesionals1 = $(pathProfesionals1).each((i, el) =>
      arrCompanyName.push($(el).text())
    );

    const telephones1 = $(pathTelephones1).each((i, el) =>
      arrTelephones.push($(el).text())
    );

    const profesionals2 = $(pathProfesionals2).each((i, el) =>
      arrCompanyName.push($(el).text())
    );

    const telephones2 = $(pathTelephones2).each((i, el) =>
      arrTelephones.push($(el).text())
    );

    const addresses1 = $(pathAddress1).each((i, el) =>
      arrAddresses.push($(el).text())
    );

    console.log(arrAddresses);
}


问:
input values does not fill correctly in FormArray
I have trouble with filling the right values into input fields of a FormArray. Here is my html:

```<code><div formArrayName="roles" *ngFor="let role of roles.controls; let i=index">
    <div [formGroupName]="i">
        <div class="form-group row">
            <label class="col-md-2 col-form-label" attr.for="{{'roleNameId' + i}}">Role Name {{i+1}}</label>
            <div class="col-md-6">
                <input class="form-control"
                        attr.id="{{'roleNameId' + i}}"
                        type="text"
                        formControlName="roleName">
            </div>
            <label class="col-md-2 col-form-label" attr.for="{{'identifierId' + i}}">
                <input
                    type="checkbox"
                    attr.id="{{'identifierId' + i}}"
                    formControlName="identifier"> identifier
            </label>
            <div class="col-md-2">
                 <button type="button" (click)="removeRole(i)" class="btn btn-danger oi oi-trash"></button>
            </div>
        </div>
    </div>
</div>
</code>```

So this html is being rendered x times depending on the number of roles i have. This works just fine and no errors are shown.

But here is the Problem: When i remove one Role which is not the last of the Array, the input fields filled with the right roles change.
Here are the roles:

When i remove role 2 for example, the form looks like this:

role2 was being removed correctly, but role3 disappeared and the last two roles have the name of the last role (role8)

Why this happens? When i look to the formArray where all roles are saved, the array has the correct values, here is the evidence:

why the correct values are not shown in the view? Thank you for your help

EDIT: Here is the relevant typescript code:

```<code>this.sourcesForm = this.fb.group({
        sourceName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(255)]],
        sourceType: ['QUERY'],
        dsl: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(255)]],
        list: [''],
        roles: this.fb.array([this.buildRole()]),
        database: [''],
});

// save roles to temporary variable to map for the roles Formarray
let roles = [];
dslStatement.roles.forEach(role => {
    let oneRole = {
        roleName: role.name,
        identifier: true
    }
    if (role.role === 'IDENTIFIER')
        oneRole.identifier = true;
    else
        oneRole.identifier = false
    roles.push(oneRole);
});
// convert the variable to FormGroups, then the FormGroups to one FormArray
// and at last set the FormArray to the roles of sourcesForm
const rolesFormGroups = roles.map(roles => this.fb.group(roles));
const rolesFormArray = this.fb.array(rolesFormGroups);
this.sourcesForm.setControl('roles', rolesFormArray);

buildRole(): FormGroup {
    return this.fb.group({
        roleName: '',
        identifier: true
    });
}

addRole() {
    this.roles.push(this.buildRole());
}

removeRole(i: number) {
    this.roles.removeAt(i);
    console.log(this.roles.value);
    console.log(this.roles.controls);
}
</code>```

答:
try this:

```<code>addRole() {
    this.roles = this.sourcesForm.get('roles') as FormArray;
    this.roles.push(this.buildRole());
}
</code>```

instead of

```<code>  addRole() {
    this.roles.push(this.buildRole());
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have trouble with filling the right values into input fields of a FormArray. Here is my html:

            Role Name {{i+1}}

                <input class="form-control"
                        attr.id="{{'roleNameId' + i}}"
                        type="text"
                        formControlName="roleName">

                <input
                    type="checkbox"
                    attr.id="{{'identifierId' + i}}"
                    formControlName="identifier"> identifier

                 <button type="button" (click)="removeRole(i)" class="btn btn-danger oi oi-trash"></button>

So this html is being rendered x times depending on the number of roles i have. This works just fine and no errors are shown.

But here is the Problem: When i remove one Role which is not the last of the Array, the input fields filled with the right roles change.
Here are the roles:

When i remove role 2 for example, the form looks like this:

role2 was being removed correctly, but role3 disappeared and the last two roles have the name of the last role (role8)

Why this happens? When i look to the formArray where all roles are saved, the array has the correct values, here is the evidence:

why the correct values are not shown in the view? Thank you for your help

EDIT: Here is the relevant typescript code:

this.sourcesForm = this.fb.group({
        sourceName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(255)]],
        sourceType: ['QUERY'],
        dsl: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(255)]],
        list: [''],
        roles: this.fb.array([this.buildRole()]),
        database: [''],
});

// save roles to temporary variable to map for the roles Formarray
let roles = [];
dslStatement.roles.forEach(role => {
    let oneRole = {
        roleName: role.name,
        identifier: true
    }
    if (role.role === 'IDENTIFIER')
        oneRole.identifier = true;
    else
        oneRole.identifier = false
    roles.push(oneRole);
});
// convert the variable to FormGroups, then the FormGroups to one FormArray
// and at last set the FormArray to the roles of sourcesForm
const rolesFormGroups = roles.map(roles => this.fb.group(roles));
const rolesFormArray = this.fb.array(rolesFormGroups);
this.sourcesForm.setControl('roles', rolesFormArray);

buildRole(): FormGroup {
    return this.fb.group({
        roleName: '',
        identifier: true
    });
}

addRole() {
    this.roles.push(this.buildRole());
}

removeRole(i: number) {
    this.roles.removeAt(i);
    console.log(this.roles.value);
    console.log(this.roles.controls);
}

Body:
try this:

addRole() {
    this.roles = this.sourcesForm.get('roles') as FormArray;
    this.roles.push(this.buildRole());
}

instead of

  addRole() {
    this.roles.push(this.buildRole());
}


问:
filter foreignkey field in django admin
I have these models:

```<code>class Entity(models.Model):
       name=models.CharField(max_length=100)

class Theme(models.Model):
   name=models.CharField(max_length=100)
   entity=models.OneToOneField(Entity)

class Company(models.Model):
    name=models.CharField(max_length=100)
    theme=models.OneToOneField(Theme,null=True,blank=True)
</code>```

I want to filter the theme field when adding a Company in the admin, something like this:

```<code>class CompanyAdmin(admin.ModelAdmin):
   def queryset(self, request):
      qs = super(CompanyAdmin, self).queryset(request)
      qs.theme.queryset = Theme.objects.filter(name__iexact='company')
      return qs

admin.site.register(Company, CompanyAdmin)
</code>```

I've tried many things, but nothing worked! How can I do this?

答:
I faced with the need to add filter to the foreignKey queryset of the parent ModelAdmin class (which all other ModelAdmins inherit from), that is, I can’t know exactly which model I need, this is my solution: db_field.related_model.objects.filter()

```<code>class TSModelAdmin(admin.ModelAdmin):
   exclude = ('site',)
    ...

      def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.related_model:
            kwargs["queryset"] =
            db_field.related_model.objects.filter(site=request.user.user_profile.site)
        return super().formfield_for_foreignkey(db_field, request, **kwargs)
</code>```

used django version 2.2.10

Title: filter foreignkey field in django admin

Body:
I have these models:

class Entity(models.Model):
       name=models.CharField(max_length=100)

class Theme(models.Model):
   name=models.CharField(max_length=100)
   entity=models.OneToOneField(Entity)

class Company(models.Model):
    name=models.CharField(max_length=100)
    theme=models.OneToOneField(Theme,null=True,blank=True)

I want to filter the theme field when adding a Company in the admin, something like this:

class CompanyAdmin(admin.ModelAdmin):
   def queryset(self, request):
      qs = super(CompanyAdmin, self).queryset(request)
      qs.theme.queryset = Theme.objects.filter(name__iexact='company')
      return qs

admin.site.register(Company, CompanyAdmin)

I've tried many things, but nothing worked! How can I do this?

Body:
I faced with the need to add filter to the foreignKey queryset of the parent ModelAdmin class (which all other ModelAdmins inherit from), that is, I can’t know exactly which model I need, this is my solution: db_field.related_model.objects.filter()

class TSModelAdmin(admin.ModelAdmin):
   exclude = ('site',)
    ...

      def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.related_model:
            kwargs["queryset"] =
            db_field.related_model.objects.filter(site=request.user.user_profile.site)
        return super().formfield_for_foreignkey(db_field, request, **kwargs)

used django version 2.2.10


问:
win32 menu item bitmap with transparent background
What I try to accomplish is really simple: adding an image to a menu item. I'm programming in C using the win32 API. The image / bitmap shows up but the background is white. What I want is to turn the white background into transparant.

I have been reading every information I could find including stackoverflow but the information seems inconsistent. Some say a bitmap cannot have any form of transparancy, whereas others say it can. See for example this question:

Simple way to show a bitmap next to a menu item in a CMenu with correct transparency

Both SetMenuItemBitmaps() and SetMenuItemInfo() give a white background. Above link says if the bitmap is in 32bpp with premultiplied alpha it should be shown correctly. So either it simply is not possible this way, or the bmp I use is in the wrong format. Can anyone give the definite answer to this problem. If it turns out it can't be done using SetMenuItemInfo(), what is then the easiest way of solving this problem? I try to avoid owner draw solutions as I feel it is a bit overkill. Besides, as far as I understand owner drawn solutions are hard to respect Windows theming.

menubitmap.rc:

```<code>#include "menubitmap.h"

ID_ICON             ICON    DISCARDABLE "menu1.ico"
ID_BITMAP_EXIT      BITMAP  DISCARDABLE "Exit-icn.bmp"

ID_MENU MENU DISCARDABLE
BEGIN
    POPUP "&File"
    BEGIN
        MENUITEM "E&xit",                       ID_FILE_EXIT
    END
END
</code>```

menubitmap.c:

```<code>#include <windows.h>
#include "menubitmap.h"

const char g_szClassName[] = "myWindowClass";

LRESULT CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)
{
    switch(Message)
    {
        case WM_CREATE:
        {
            HBITMAP btmp;
            MENUITEMINFOA miinfo;
            HMENU menu;

            btmp=LoadBitmap((HINSTANCE) GetModuleHandle (NULL), MAKEINTRESOURCE(ID_BITMAP_EXIT));
            menu=GetMenu(hwnd);
            miinfo.cbSize=sizeof(MENUITEMINFO);
            if(!GetMenuItemInfo(menu,ID_FILE_EXIT,FALSE,&miinfo)){
                    printf("getmenuiteminfo failed\r\n");
            }else{
                    miinfo.fMask |= MIIM_BITMAP;
                    miinfo.hbmpItem=btmp;
                    if(SetMenuItemInfo(menu,ID_FILE_EXIT,FALSE,&miinfo)){
                            printf("setmenuiteminfo");
                    }
            }

        }
        case WM_COMMAND:
            switch(LOWORD(wParam))
            {
                case ID_FILE_EXIT:
                    PostMessage(hwnd, WM_CLOSE, 0, 0);
                break;
            }
        break;
        case WM_CLOSE:
            DestroyWindow(hwnd);
        break;
        case WM_DESTROY:
            PostQuitMessage(0);
        break;
        default:
            return DefWindowProc(hwnd, Message, wParam, lParam);
    }
    return 0;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    LPSTR lpCmdLine, int nCmdShow)
{
    WNDCLASSEX wc;
    HWND hwnd;
    MSG Msg;

    wc.cbSize        = sizeof(WNDCLASSEX);
    wc.style         = 0;
    wc.lpfnWndProc   = WndProc;
    wc.cbClsExtra    = 0;
    wc.cbWndExtra    = 0;
    wc.hInstance     = hInstance;
    wc.hIcon         = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(ID_ICON));
    wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
    wc.lpszMenuName  = MAKEINTRESOURCE(ID_MENU);
    wc.lpszClassName = g_szClassName;
    wc.hIconSm       = (HICON)LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(ID_ICON), IMAGE_ICON, 16, 16, 0);

    if(!RegisterClassEx(&wc))
    {
        MessageBox(NULL, "Window Registration Failed!", "Error!",
            MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    hwnd = CreateWindowEx(
        WS_EX_CLIENTEDGE,
        g_szClassName,
        "A Menu",
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT, 240, 120,
        NULL, NULL, hInstance, NULL);

    if(hwnd == NULL)
    {
        MessageBox(NULL, "Window Creation Failed!", "Error!",
            MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    ShowWindow(hwnd, nCmdShow);
    UpdateWindow(hwnd);

    while(GetMessage(&Msg, NULL, 0, 0) > 0)
    {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
    }
    return Msg.wParam;
}
</code>```

Here you can find the bitmap

Here is the bitmap in bas64 format:

```<code>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
AA==
</code>```

答:
Alpha transparency in Windows' GDI is a minefield. It was added very late, and only a handful of API calls are truly capable of handling a dedicated alpha channel. LoadBitmap is not one of those that support (or at least do not break) alpha transparency. The alpha channel gets lost when you're loading the image from the application's resources.

To fix that, you'll have to use LoadImage, passing in the correct flags. LR_CREATEDIBSECTION is the important one, as that preserves the alpha channel in the source bitmap.

The fix is as simple as replacing

LoadBitmap((HINSTANCE) GetModuleHandle (NULL), MAKEINTRESOURCE(ID_BITMAP_EXIT))
```

<p>with</p>

<pre class="lang-cpp prettyprint-override"><code>(HBITMAP)LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(ID_BITMAP_EXIT),
                   IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION)
</code>```

With that in place you'll see the menu icon displayed with per-pixel alpha transparency:

Body:
What I try to accomplish is really simple: adding an image to a menu item. I'm programming in C using the win32 API. The image / bitmap shows up but the background is white. What I want is to turn the white background into transparant.

I have been reading every information I could find including stackoverflow but the information seems inconsistent. Some say a bitmap cannot have any form of transparancy, whereas others say it can. See for example this question:

Simple way to show a bitmap next to a menu item in a CMenu with correct transparency

Both SetMenuItemBitmaps() and SetMenuItemInfo() give a white background. Above link says if the bitmap is in 32bpp with premultiplied alpha it should be shown correctly. So either it simply is not possible this way, or the bmp I use is in the wrong format. Can anyone give the definite answer to this problem. If it turns out it can't be done using SetMenuItemInfo(), what is then the easiest way of solving this problem? I try to avoid owner draw solutions as I feel it is a bit overkill. Besides, as far as I understand owner drawn solutions are hard to respect Windows theming.

menubitmap.rc:

#include "menubitmap.h"

ID_ICON             ICON    DISCARDABLE "menu1.ico"
ID_BITMAP_EXIT      BITMAP  DISCARDABLE "Exit-icn.bmp"

ID_MENU MENU DISCARDABLE
BEGIN
    POPUP "&File"
    BEGIN
        MENUITEM "E&xit",                       ID_FILE_EXIT
    END
END

menubitmap.c:

#include <windows.h>
#include "menubitmap.h"

const char g_szClassName[] = "myWindowClass";

LRESULT CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)
{
    switch(Message)
    {
        case WM_CREATE:
        {
            HBITMAP btmp;
            MENUITEMINFOA miinfo;
            HMENU menu;

            btmp=LoadBitmap((HINSTANCE) GetModuleHandle (NULL), MAKEINTRESOURCE(ID_BITMAP_EXIT));
            menu=GetMenu(hwnd);
            miinfo.cbSize=sizeof(MENUITEMINFO);
            if(!GetMenuItemInfo(menu,ID_FILE_EXIT,FALSE,&miinfo)){
                    printf("getmenuiteminfo failed\r\n");
            }else{
                    miinfo.fMask |= MIIM_BITMAP;
                    miinfo.hbmpItem=btmp;
                    if(SetMenuItemInfo(menu,ID_FILE_EXIT,FALSE,&miinfo)){
                            printf("setmenuiteminfo");
                    }
            }

        }
        case WM_COMMAND:
            switch(LOWORD(wParam))
            {
                case ID_FILE_EXIT:
                    PostMessage(hwnd, WM_CLOSE, 0, 0);
                break;
            }
        break;
        case WM_CLOSE:
            DestroyWindow(hwnd);
        break;
        case WM_DESTROY:
            PostQuitMessage(0);
        break;
        default:
            return DefWindowProc(hwnd, Message, wParam, lParam);
    }
    return 0;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    LPSTR lpCmdLine, int nCmdShow)
{
    WNDCLASSEX wc;
    HWND hwnd;
    MSG Msg;

    wc.cbSize        = sizeof(WNDCLASSEX);
    wc.style         = 0;
    wc.lpfnWndProc   = WndProc;
    wc.cbClsExtra    = 0;
    wc.cbWndExtra    = 0;
    wc.hInstance     = hInstance;
    wc.hIcon         = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(ID_ICON));
    wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
    wc.lpszMenuName  = MAKEINTRESOURCE(ID_MENU);
    wc.lpszClassName = g_szClassName;
    wc.hIconSm       = (HICON)LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(ID_ICON), IMAGE_ICON, 16, 16, 0);

    if(!RegisterClassEx(&wc))
    {
        MessageBox(NULL, "Window Registration Failed!", "Error!",
            MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    hwnd = CreateWindowEx(
        WS_EX_CLIENTEDGE,
        g_szClassName,
        "A Menu",
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT, 240, 120,
        NULL, NULL, hInstance, NULL);

    if(hwnd == NULL)
    {
        MessageBox(NULL, "Window Creation Failed!", "Error!",
            MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    ShowWindow(hwnd, nCmdShow);
    UpdateWindow(hwnd);

    while(GetMessage(&Msg, NULL, 0, 0) > 0)
    {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
    }
    return Msg.wParam;
}

Here you can find the bitmap

Here is the bitmap in bas64 format:

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
AA==

Body:
Alpha transparency in Windows' GDI is a minefield. It was added very late, and only a handful of API calls are truly capable of handling a dedicated alpha channel. LoadBitmap is not one of those that support (or at least do not break) alpha transparency. The alpha channel gets lost when you're loading the image from the application's resources.

To fix that, you'll have to use LoadImage, passing in the correct flags. LR_CREATEDIBSECTION is the important one, as that preserves the alpha channel in the source bitmap.

The fix is as simple as replacing

LoadBitmap((HINSTANCE) GetModuleHandle (NULL), MAKEINTRESOURCE(ID_BITMAP_EXIT))

with

(HBITMAP)LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(ID_BITMAP_EXIT),
                   IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION)

With that in place you'll see the menu icon displayed with per-pixel alpha transparency:


问:
Synched Timer Across all Application instances
Could anyone maybe lend some advice.

I need to create a Global Timer for every instance of my application

For a Time'd Sale of sorts, The use case Is that a Product will be on a Quick sale for 10 minutes then Disappear. Now there needs to be a timer but it would have to be synched across all application regardless of what time they open the application.

Now what i've done is used a webview with a Online Reoccurring timer. The issue with this is that I realised I'd have to clear the quick sale cart when the timer is up, So that people cant checkout products for the quick sale price when the sale is over. And with the webview I cant read that value to do that

So in Essence my Question is: What are my Alternative options/Option to get a Synchronised Timer That I can read the Value from To use for Functionality later on.

Another Solution I had was that, I could check on the OnAppearing() of the quick Cart if that Product still exists under the quick products And if not remove it form the list but, I'd like to stay away from webviews

答:
You can store Timer end value in a database and get it everytime somebody enters your site to calculate time left, if the time is over then You can call your API method for orders to remove products of some ID from every not finished order.

Another way is to use the same process but with service and it's probably better way to do so. Every app could request the Timer end value from service and use it to calculate time left.


问:
Converting string of 0 and 1 characters to hexadecimal string
I am converting all binary numbers stored in a file to hexadecimal. The file is parsed through command line argument, but to convert it to hexadecimal I want it to be converted to an integer, i.e. literal integer of the string received and atoi() doesn't seem to work.

```<code>#include<stdlib.h>
#include<stdio.h>
#include<string.h>

int main ( int argc, char *argv[] )
{
    FILE *fp,*op;
    fp = fopen(argv[1],"r");
    op= fopen(argv[2],"w+");
    if( fp == NULL)
    {
       perror("An error has occurred\n");
       exit(1);
    }

    char buff[1026];
    unsigned char hexstr[1024];
    unsigned long int hexnum,hexint;
    unsigned char four[4];
    int i, j,len;
    while(fgets(buff, sizeof(buff), fp))
    {
        printf("\nString value = %s", buff);
        hexint=atoi(buff);
        printf("%ld",hexint);
    }

    fclose(fp);
    fclose(op);
    return 0;
}
</code>```

input file contains:

0000000000001010
1010000000000000
101010111100110111101111
000100100011010001010110
000100010001000100010001
011101110111011101110111
000000000000000000000000
```

<p>output file should contain:</p>

<pre class="lang-none prettyprint-override"><code>000a
a000
abcdef
123456
111111
777777
000000
</code>```

答:
For this conversion assignment, Using fgets() might pose a problem if the line length can be arbitrary.

You can convert the contents on the fly, one byte at a time and pass any non binary digits to the output unchanged:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    FILE *fp, *op;
    int c, hasnum;
    unsigned long long num;

    if (argc < 3
    ||  ((fp = fopen(argv[1], "r")) == NULL
    ||  ((op = fopen(argv[2], "w")) == NULL) {
       perror("Error opening files\n");
       return 1;
    }
    hasnum = 0;
    num = 0;

    for (;;) {
        c = getc(fp);
        if (c == '0' || c == '1') {
            num = num * 2 + (c - '0');
            hasnum++;
        } else {
            if (hasnum) {
                // output one hex digit for 4 input binary digits
                fprintf(fo, "%0*x", (hasnum + 3) / 4, num);
                hasnum = 0;
                num = 0;
            }
            if (c == EOF)
                break;
        }
    }
    fclose(fp);
    fclose(op);
    return 0;
}
```

Body:
I am converting all binary numbers stored in a file to hexadecimal. The file is parsed through command line argument, but to convert it to hexadecimal I want it to be converted to an integer, i.e. literal integer of the string received and atoi() doesn't seem to work.

#include<stdlib.h>
#include<stdio.h>
#include<string.h>

int main ( int argc, char *argv[] )
{
    FILE *fp,*op;
    fp = fopen(argv[1],"r");
    op= fopen(argv[2],"w+");
    if( fp == NULL)
    {
       perror("An error has occurred\n");
       exit(1);
    }

    char buff[1026];
    unsigned char hexstr[1024];
    unsigned long int hexnum,hexint;
    unsigned char four[4];
    int i, j,len;
    while(fgets(buff, sizeof(buff), fp))
    {
        printf("\nString value = %s", buff);
        hexint=atoi(buff);
        printf("%ld",hexint);
    }

    fclose(fp);
    fclose(op);
    return 0;
}

input file contains:

0000000000001010
1010000000000000
101010111100110111101111
000100100011010001010110
000100010001000100010001
011101110111011101110111
000000000000000000000000

output file should contain:

000a
a000
abcdef
123456
111111
777777
000000


问:
I want to use setter in kotlin to set value of document snapshot
I try to use setter in kotlin but can't set the document snapshot data </p>

```<code>
    private lateinit var document: QueryDocumentSnapshot
//intialize top
            .addOnSuccessListener { documents ->
                        for (document in documents) {
                            klog.d("#fail", document.get("question").toString())
                            setDocument(document)
                        }
                    }.addOnFailureListener { exception ->
                        klog.d("#fail", exception.message)
                    }
        }
    }

    fun setDocument(document: QueryDocumentSnapshot) {
        this.document=document
    }
</code>```

答:
try the following code, to check if the varialbe is initialised</p>

```<code>        if (::document.isInitialized){
            //variable is initialised
        }
</code>```

Body:
I try to use setter in kotlin but can't set the document snapshot data

    private lateinit var document: QueryDocumentSnapshot
//intialize top
            .addOnSuccessListener { documents ->
                        for (document in documents) {
                            klog.d("#fail", document.get("question").toString())
                            setDocument(document)
                        }
                    }.addOnFailureListener { exception ->
                        klog.d("#fail", exception.message)
                    }
        }
    }

    fun setDocument(document: QueryDocumentSnapshot) {
        this.document=document
    }

Body:
try the following code, to check if the varialbe is initialised

        if (::document.isInitialized){
            //variable is initialised
        }


问:
Java code for getting count in the sorted ArrayList for particular range
Need to find the count of the elements in the sorted ArrayList from the given range(x,y). And the count should have count of range elements also if it is in ArrayList.

So for, I have done this by traversing the whole list and getting the count.

Pseudo-code:

```<code>count = 0;
for (i=0; i<length(list); i++)
{
if (list[i]>= startrange and list[i]<=endrange)
  {
    count = count+1;
  }
}
</code>```

Current solution is taking more time because input array size is more than 1000000. Help me to optimize the solution.

Example:

Input array looks like this [1,4,5,8,9,12,16,19,23,26,28,29,30,31,33,35,37].

Input range: (12,30)

Output should be like 8

答:
You said Need to find the count of the elements in the sorted ArrayList from the given range(x,y).

So, you can make use of binary search to make your code efficient.

In binary search, we first have 2 pointers, say low and high. Now, we start our search from middle element in this range. If the middle element is smaller than required one, we move to the right side of the range (mid + 1,high), else we move to the left side of the range (low,mid-1).

In this particular case, we have to do 2 binary searches. Let's take (12,30)as an example. One is to find the lowest index which has 12 and another binary search to find the highest index which has 30. Answer for this query would be highestIndex - lowestIndex + 1.

Snippet:

```<code>public class Main{
    public static void main(String[] args) {
        int[] arr = {1,4,5,8,9,12,16,19,23,26,28,29,30,31,33,35,37};
        int[][] queries = {
            {12,30},
            {-1,37},
            {1,49}
        };

        for(int[] q : queries){
            System.out.println(binarySearch(arr,q[0],q[1]));
        }
    }

    private static int binarySearch(int[] arr,int low,int high){
        return highestIndex(arr,high) - lowestIndex(arr,low) + 1; // + 1 because of 0-based indexing
    }

    private static int highestIndex(int[] arr,int num){
        int low = 0 , high = arr.length - 1;
        while(low <= high){
            int mid = low + (high - low) / 2; // (or (low + high)/2, as it doesn't matter in this context
            if(arr[mid] <= num) low = mid + 1;
            else high = mid - 1;
        }

        return high;
    }

    private static int lowestIndex(int[] arr,int num){
        int low = 0 , high = arr.length - 1;
        while(low <= high){
            int mid = low + (high - low) / 2; // (or (low + high)/2, as it doesn't matter in this context
            if(arr[mid] >= num) high = mid - 1;
            else low = mid + 1;
        }

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

Demo: https://onlinegdb.com/BJ4g3AXXL

Space Complexity of above code is O(1).

Time complexity of above code is O(Q * (log(N) + log(N))) ~ O(Q * 2 * log(N)) ~ O(Q * log(N)) asymptotically where Q is number of queries and N is size of the array.

Body:
Need to find the count of the elements in the sorted ArrayList from the given range(x,y). And the count should have count of range elements also if it is in ArrayList.

So for, I have done this by traversing the whole list and getting the count.

Pseudo-code:

count = 0;
for (i=0; i<length(list); i++)
{
if (list[i]>= startrange and list[i]<=endrange)
  {
    count = count+1;
  }
}

Current solution is taking more time because input array size is more than 1000000. Help me to optimize the solution.

Example:

Input array looks like this [1,4,5,8,9,12,16,19,23,26,28,29,30,31,33,35,37].

Input range: (12,30)

Output should be like 8

Body:
You said Need to find the count of the elements in the sorted ArrayList from the given range(x,y).

So, you can make use of binary search to make your code efficient.

In binary search, we first have 2 pointers, say low and high. Now, we start our search from middle element in this range. If the middle element is smaller than required one, we move to the right side of the range (mid + 1,high), else we move to the left side of the range (low,mid-1).

In this particular case, we have to do 2 binary searches. Let's take (12,30)as an example. One is to find the lowest index which has 12 and another binary search to find the highest index which has 30. Answer for this query would be highestIndex - lowestIndex + 1.

Snippet:

public class Main{
    public static void main(String[] args) {
        int[] arr = {1,4,5,8,9,12,16,19,23,26,28,29,30,31,33,35,37};
        int[][] queries = {
            {12,30},
            {-1,37},
            {1,49}
        };

        for(int[] q : queries){
            System.out.println(binarySearch(arr,q[0],q[1]));
        }
    }

    private static int binarySearch(int[] arr,int low,int high){
        return highestIndex(arr,high) - lowestIndex(arr,low) + 1; // + 1 because of 0-based indexing
    }

    private static int highestIndex(int[] arr,int num){
        int low = 0 , high = arr.length - 1;
        while(low <= high){
            int mid = low + (high - low) / 2; // (or (low + high)/2, as it doesn't matter in this context
            if(arr[mid] <= num) low = mid + 1;
            else high = mid - 1;
        }

        return high;
    }

    private static int lowestIndex(int[] arr,int num){
        int low = 0 , high = arr.length - 1;
        while(low <= high){
            int mid = low + (high - low) / 2; // (or (low + high)/2, as it doesn't matter in this context
            if(arr[mid] >= num) high = mid - 1;
            else low = mid + 1;
        }

        return low;
    }
}

Demo: https://onlinegdb.com/BJ4g3AXXL

Space Complexity of above code is O(1).

Time complexity of above code is O(Q * (log(N) + log(N))) ~ O(Q * 2 * log(N)) ~ O(Q * log(N)) asymptotically where Q is number of queries and N is size of the array.


问:
Clearing localStorage in javascript?
Is there any way to reset/clear the browser's localStorage in javascript?

答:
This code here you give a list of strings of keys that you don't want to delete, then it filters those from all the keys in local storage then deletes the others.</p>

```<code>const allKeys = Object.keys(localStorage);

const toBeDeleted = allKeys.filter(value => {
  return !this.doNotDeleteList.includes(value);
});

toBeDeleted.forEach(value => {
  localStorage.removeItem(value);
});
</code>```

Title: Clearing localStorage in javascript?

Body:
This code here you give a list of strings of keys that you don't want to delete, then it filters those from all the keys in local storage then deletes the others.

const allKeys = Object.keys(localStorage);

const toBeDeleted = allKeys.filter(value => {
  return !this.doNotDeleteList.includes(value);
});

toBeDeleted.forEach(value => {
  localStorage.removeItem(value);
});


问:
Using regex to find-and-replace an arbitrary number of elements per match
My goal is to recognize bold parenthesized text in a markup language, eg.:

```<code>[B] blah blah (foo) blah [/B]
</code>```

and use regex to surround it with another tag, like so:

```<code>[B] blah blah [C](foo)[/C] blah [/B]
</code>```

Here's my attempt at this using Python:

```<code>outtext = re.sub(r'(\[B\].*?)(\(.*?\))(.*?\[/B\])', r'\1[C]\2[/C]\3', intext)
</code>```

The problem is, it doesn't work if there are multiple parenthesized strings within the block:

```<code>Input: [B] (foo) (bar) [/B]
Expected: [B] [C](foo)[/C] [C](bar)[/C] [/B]
Actual: [B] [C](foo)[/C] (bar) [/B]
</code>```

I know the reason why this is happening, but I don't know how to fix it. Is it possible to change my regex so that it's able to find-and-replace an arbitrary number of parenthesized strings within each block, as opposed to just one?

答:
Okay.. this took me some time.. I'm not sure of the specifics of the markup syntax, but I'll make some assumptions: the text inside parenthesis can be any character except parenthesis unless they are escaped. The escape character is a backslash. With that said.. here's what I came up with.

```<code>>>> expr = r"""
...    \(                            # Match left paren.
...       (
...         (?:      [^ \( \) \\] |  # Match any char not a paren or escape, OR
...              \\  [  \( \) \\] |  # Match an escaped paren or escape, OR
...              \s                  # whitespace.
...          )*
...        )
...    \)                            # Match right paren. """
...
>>> re.sub(expr, r"[C](\1)[/C]",  "[B] (foo) (bar) [/B]", flags=re.VERBOSE)
'[B] [C](foo)[/C] [C](bar)[/C] [/B]'
</code>```

This will also work with target strings that have escaped parenthesis in them. The abbreviated form of the above is this...

```<code>re.sub(r"\(((?:[^\(\)\\]|\\[\(\)\\]|\s)*)\)",
       r"[C](\1)[/C]",  "[B] (foo) (bar) [/B]")
</code>```

With the whitespace and comments taken out...

Body:
My goal is to recognize bold parenthesized text in a markup language, eg.:

[B] blah blah (foo) blah [/B]

and use regex to surround it with another tag, like so:

[B] blah blah [C](foo)[/C] blah [/B]

Here's my attempt at this using Python:

outtext = re.sub(r'(\[B\].*?)(\(.*?\))(.*?\[/B\])', r'\1[C]\2[/C]\3', intext)

The problem is, it doesn't work if there are multiple parenthesized strings within the block:

Input: [B] (foo) (bar) [/B]
Expected: [B] [C](foo)[/C] [C](bar)[/C] [/B]
Actual: [B] [C](foo)[/C] (bar) [/B]

I know the reason why this is happening, but I don't know how to fix it. Is it possible to change my regex so that it's able to find-and-replace an arbitrary number of parenthesized strings within each block, as opposed to just one?

Body:
Okay.. this took me some time.. I'm not sure of the specifics of the markup syntax, but I'll make some assumptions: the text inside parenthesis can be any character except parenthesis unless they are escaped. The escape character is a backslash. With that said.. here's what I came up with.

>>> expr = r"""
...    \(                            # Match left paren.
...       (
...         (?:      [^ \( \) \\] |  # Match any char not a paren or escape, OR
...              \\  [  \( \) \\] |  # Match an escaped paren or escape, OR
...              \s                  # whitespace.
...          )*
...        )
...    \)                            # Match right paren. """
...
>>> re.sub(expr, r"[C](\1)[/C]",  "[B] (foo) (bar) [/B]", flags=re.VERBOSE)
'[B] [C](foo)[/C] [C](bar)[/C] [/B]'

This will also work with target strings that have escaped parenthesis in them. The abbreviated form of the above is this...

re.sub(r"\(((?:[^\(\)\\]|\\[\(\)\\]|\s)*)\)",
       r"[C](\1)[/C]",  "[B] (foo) (bar) [/B]")

With the whitespace and comments taken out...


问:
SQL group by and select with condition in each column
I want to select a table, group by it into a subset and keep only 'Y' values of each column within each group.

And replace the value 'Y' with the first column ID value.

my table like this

```<code>
ID      Date        MachineNo Operator1 Operator2 Operator3 Operator4 Reporter1 Reporter2 Reporter3 Reporter4
A57611  2019-01-02   5515         Y        N          N          N        N         N         Y         N
D75451  2019-01-02   5515         N        Y          N          N        N         Y         N         N
E10758  2019-01-02   5515         N        N          Y          N        Y         N         N         N
E41020  2019-01-02   5515         N        N          N          Y        N         N         N         Y
...
F20124  2019-01-02   5405         Y        N          N          N        N         N         Y         N
A45687  2019-01-02   5405         N        N          Y          N        N         Y         N         N
B22511  2019-01-02   5405         N        Y          N          N        Y         N         N         N
C45451  2019-01-02   5405         N        N          N          Y        N         N         N         Y
...
</code>```

And I want to select a table like this:

Group by Date and MachineNo

Replace 'Y' with ID of each row and each group combines into one row

```<code>
  Date      MachineNo Operator1 Operator2 Operator3 Operator4 Reporter1 Reporter2 Reporter3 Reporter4
2019-01-02    5515      A57611    D75451    E10758    E41020    E10758    D75451   A57611    E41020
2019-01-02    5405      F20124    B22511    A45687    C45451    B22511    A45687   F20124    C45451
...
</code>```

The method that I can imagine now is "join" multiple times, but I am wondering is there any better way to do it.

Note: 'Y' only appears once in each group on operator and reporter columns.

答:
You can do it with conditional aggregation if you group by date, machineno:

```<code>select date, machineno,
  max(case when operator1 = 'Y' then ID end) operator1,
  ...........................................................
  max(case when reporter1 = 'Y' then ID end) reporter1,
  ...........................................................
from tablename
group by date, machineno
</code>```

Body:
I want to select a table, group by it into a subset and keep only 'Y' values of each column within each group.

And replace the value 'Y' with the first column ID value.

my table like this

ID      Date        MachineNo Operator1 Operator2 Operator3 Operator4 Reporter1 Reporter2 Reporter3 Reporter4
A57611  2019-01-02   5515         Y        N          N          N        N         N         Y         N
D75451  2019-01-02   5515         N        Y          N          N        N         Y         N         N
E10758  2019-01-02   5515         N        N          Y          N        Y         N         N         N
E41020  2019-01-02   5515         N        N          N          Y        N         N         N         Y
...
F20124  2019-01-02   5405         Y        N          N          N        N         N         Y         N
A45687  2019-01-02   5405         N        N          Y          N        N         Y         N         N
B22511  2019-01-02   5405         N        Y          N          N        Y         N         N         N
C45451  2019-01-02   5405         N        N          N          Y        N         N         N         Y
...

And I want to select a table like this:

Group by Date and MachineNo

Replace 'Y' with ID of each row and each group combines into one row

  Date      MachineNo Operator1 Operator2 Operator3 Operator4 Reporter1 Reporter2 Reporter3 Reporter4
2019-01-02    5515      A57611    D75451    E10758    E41020    E10758    D75451   A57611    E41020
2019-01-02    5405      F20124    B22511    A45687    C45451    B22511    A45687   F20124    C45451
...

The method that I can imagine now is "join" multiple times, but I am wondering is there any better way to do it.

Note: 'Y' only appears once in each group on operator and reporter columns.

Body:
You can do it with conditional aggregation if you group by date, machineno:

select date, machineno,
  max(case when operator1 = 'Y' then ID end) operator1,
  ...........................................................
  max(case when reporter1 = 'Y' then ID end) reporter1,
  ...........................................................
from tablename
group by date, machineno


问:
Vimeo api to wordpress posts
I have listed the vimeo videos from a channel using vimeo api using php
Now i want to upload all the videos as a post to wordpress custom postype how to do that?
each time a new video i published it should add the videos as a post to custom postype</p>

答:
To create a post in WordPress, you can use the below code.

Step1:

Look for the Vimeo webhooks option, which will let you know when a new Vimeo video is published. By doing so, you can get the details of the video and then use that information to create a post in WordPress.

Vimeo API link: https://developer.vimeo.com/help

Zapier Vimeo Integration Link: https://zapier.com/apps/vimeo/integrations/webhook

Step2:

```<code>/**
 * A function used to programmatically create a post in WordPress. The slug, author ID, and title
 * are defined within the context of the function.
 *
 * @returns -1 if the post was never created, -2 if a post with the same title exists, or the ID
 *          of the post if successful.
 */
function programmatically_create_post() {

    // Initialize the page ID to -1. This indicates no action has been taken.
    $post_id = -1;

    // Setup the author, slug, and title for the post
    $author_id = 1;
    $slug = 'example-post';
    $title = 'My Example Post';

    // If the page doesn't already exist, then create it
    if( null == get_page_by_title( $title ) ) {

        // Set the post ID so that we know the post was created successfully
        $post_id = wp_insert_post(
            array(
                'comment_status'    =>  'closed',
                'ping_status'       =>  'closed',
                'post_author'       =>  $author_id,
                'post_name'     =>  $slug,
                'post_title'        =>  $title,
                'post_status'       =>  'publish',
                'post_type'     =>  'post'
            )
        );

    // Otherwise, we'll stop
    } else {

            // Arbitrarily use -2 to indicate that the page with the title already exists
            $post_id = -2;

    } // end if

} // end programmatically_create_post
add_filter( 'after_setup_theme', 'programmatically_create_post' );
</code>```

Title: Vimeo api to wordpress posts

Body:
To create a post in WordPress, you can use the below code.

Step1:

Look for the Vimeo webhooks option, which will let you know when a new Vimeo video is published. By doing so, you can get the details of the video and then use that information to create a post in WordPress.

Vimeo API link: https://developer.vimeo.com/help

Zapier Vimeo Integration Link: https://zapier.com/apps/vimeo/integrations/webhook

Step2:

/**
 * A function used to programmatically create a post in WordPress. The slug, author ID, and title
 * are defined within the context of the function.
 *
 * @returns -1 if the post was never created, -2 if a post with the same title exists, or the ID
 *          of the post if successful.
 */
function programmatically_create_post() {

    // Initialize the page ID to -1. This indicates no action has been taken.
    $post_id = -1;

    // Setup the author, slug, and title for the post
    $author_id = 1;
    $slug = 'example-post';
    $title = 'My Example Post';

    // If the page doesn't already exist, then create it
    if( null == get_page_by_title( $title ) ) {

        // Set the post ID so that we know the post was created successfully
        $post_id = wp_insert_post(
            array(
                'comment_status'    =>  'closed',
                'ping_status'       =>  'closed',
                'post_author'       =>  $author_id,
                'post_name'     =>  $slug,
                'post_title'        =>  $title,
                'post_status'       =>  'publish',
                'post_type'     =>  'post'
            )
        );

    // Otherwise, we'll stop
    } else {

            // Arbitrarily use -2 to indicate that the page with the title already exists
            $post_id = -2;

    } // end if

} // end programmatically_create_post
add_filter( 'after_setup_theme', 'programmatically_create_post' );


问:
Display warning message after commit
I want to display a warning message after someone commits a change.

```<code>$ git commit -am "First commit"  # Or `git commit -a` and then type a message in the editor
Please, don't forget to update the production repository
</code>```

The only restriction that I have is that it can't be done to all Git repositories, it has to work only in specific directories.

Is this possible?

答:
You can do this with a post-commit hook.  The documentation for that hook says:

post-commit

This hook is invoked by git commit. It takes no parameter, and is invoked after a commit is made.  This hook is meant primarily for notification, and cannot affect the outcome of git commit.

... so you can just install a post-commit hook that echos your message you mention.  How you get your users to install this hook is a different matter, covered in other answers on Stack Overflow, e.g. Can Git hook scripts be managed along with the repository?....

Title: Display warning message after commit

Body:
I want to display a warning message after someone commits a change.

$ git commit -am "First commit"  # Or `git commit -a` and then type a message in the editor
Please, don't forget to update the production repository

The only restriction that I have is that it can't be done to all Git repositories, it has to work only in specific directories.

Is this possible?


问:
Appending to CSV file without headers
I am using opencsv to write a Java bean to a CSV file with headers. The file name contains the current date. If the user runs it for a second time in the same day, it appends to the file but adds another header line.

How do I append to the file but without the column headers.

```<code>    public class CSVExport {

final File USERHOME = new File(System.getProperty("user.home"));
final List<saleExport> listSaleExport = new ArrayList<>();
final ObjectMapper mapper = new ObjectMapper();

public void createCsvFile(String Region, Map<String, String> currentSale) throws IOException {

    mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
    // use column position mapping strategy for no headers?
    LocalDate today = LocalDate.now();

                final SaleExport saleExport = mapper.convertValue(currentSale, SaleExport.class);
                listSaleExport.add(saleExport);
                writeToFile(today +" LA.csv", listSaleExport);
}

public void writeToFile(String filename, List<listSaleExport> listSaleExport) throws IOException {

    File file = new File(PROCESSED_DIR +"\\", "filename");

    if (!file.exists()) {
        try {
            Writer writer = new FileWriter(PROCESSED_DIR +"\\" +filename, true);
            StatefulBeanToCsvBuilder<listSaleExport> beanToCsv = new StatefulBeanToCsvBuilder<>(writer);
            StatefulBeanToCsv<listSaleExport> beanWriter = beanToCsv.build();
            beanWriter.write(listSaleExport);
            writer.close();
        } catch (Exception ex) {
            System.out.println("Error : " + ex.getMessage());
        }
    } else {
        try {
            Writer writer = new FileWriter(PROCESSED_DIR +"\\" +"filename");
            StatefulBeanToCsvBuilder<listSaleExport> beanToCsv = new StatefulBeanToCsvBuilder<>(writer);
            StatefulBeanToCsv<listSaleExport> beanWriter = beanToCsv.build();
            beanWriter.write(listSaleExport);
            writer.close();
        } catch (Exception ex) {
            System.out.println("Error : " + ex.getMessage());
        }
    }
  }
}
</code>```

答:
I don't know if the feature was finally added in OpenCSV. Right now the latest version is 5.1 and I haven't read anything about it...

As I've posted in another question, I got it to work after updating to 5.1:

Needed to have CSVs with both specific field headers (@CsvBindByName) and positions (@CsvBindByPosition), so I already had to make my own MappingStrategy.

public class CustomMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
    private boolean useHeader=true;

    public CustomMappingStrategy(){
    }

    public CustomMappingStrategy(boolean useHeader) {
        this.useHeader = useHeader;
    }

    @Override
    public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
        final int numColumns = FieldUtils.getAllFields(bean.getClass()).length;
        super.setColumnMapping(new String[numColumns]);

        if (numColumns == -1) {
            return super.generateHeader(bean);
        }

        String[] header = new String[numColumns];

        if(!useHeader){
            return ArrayUtils.EMPTY_STRING_ARRAY;
        }
        BeanField<T, Integer> beanField;
        for (int i = 0; i < numColumns; i++){
            beanField = findField(i);
            String columnHeaderName = extractHeaderName(beanField);
            header[i] = columnHeaderName;
        }

        return header;
    }

    private String extractHeaderName(final BeanField<T, Integer> beanField){
        if (beanField == null || beanField.getField() == null || beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class).length == 0){
            return StringUtils.EMPTY;
        }

        //return value of CsvBindByName annotation
        final CsvBindByName bindByNameAnnotation = beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class)[0];
        return bindByNameAnnotation.column();
    }

}
```
<p>I also made a generic exporter class, to ease CSV generation:</p>
<pre class="lang-java prettyprint-override"><code>public class ExportGenericCSV<T> {
    private static final Logger logger = LoggerFactory.getLogger(ExportGenericCSV.class);
    private final char DEFAULT_QUOTE_CHARACTER = CSVWriter.NO_QUOTE_CHARACTER;
    private final char CSV_SEPARATOR = CSVWriter.DEFAULT_SEPARATOR;

    public void writeToFile(String fileName, List<T> content){
        writeList(fileName, content, true);
    }

    public void appendToFile(String fileName, List<T> content){
        writeList(fileName, content, false, StandardOpenOption.APPEND);
    }

    @SuppressWarnings("unchecked")
    private void writeList(String fileName, List<T> exports, boolean addHeader, OpenOption...openOptions){
        if(exports == null  || exports.isEmpty()) return;
        try (Writer writer = Files.newBufferedWriter(Paths.get(fileName), openOptions)){

            CustomMappingStrategy<T> mapping = new CustomMappingStrategy<T>(addHeader);
            mapping.setType((Class<? extends T>) exports.get(0).getClass());

            StatefulBeanToCsv<T> beanToCsv = new StatefulBeanToCsvBuilder<T>(writer)
                    .withQuotechar(DEFAULT_QUOTE_CHARACTER)
                    .withSeparator(CSV_SEPARATOR)
                    .withMappingStrategy(mapping)
                    .build();

            beanToCsv.write(exports);

            writer.flush();
            writer.close();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } catch (CsvDataTypeMismatchException e) {
            logger.error(e.getMessage(), e);
        } catch (CsvRequiredFieldEmptyException e) {
            logger.error(e.getMessage(), e);
        }
    }
}
</code>```

This way, when you need to export a list of items you can use:

```<code>ExportGenericCSV<ExportedClass> exporter = new ExportGenericCSV<ExportedClass>();
</code>```

and then use exporter.writeToFile(...) or exporter.appendToFile(...)

Title: Appending to CSV file without headers

Body:
I am using opencsv to write a Java bean to a CSV file with headers. The file name contains the current date. If the user runs it for a second time in the same day, it appends to the file but adds another header line.

How do I append to the file but without the column headers.

    public class CSVExport {

final File USERHOME = new File(System.getProperty("user.home"));
final List<saleExport> listSaleExport = new ArrayList<>();
final ObjectMapper mapper = new ObjectMapper();

public void createCsvFile(String Region, Map<String, String> currentSale) throws IOException {

    mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
    // use column position mapping strategy for no headers?
    LocalDate today = LocalDate.now();

                final SaleExport saleExport = mapper.convertValue(currentSale, SaleExport.class);
                listSaleExport.add(saleExport);
                writeToFile(today +" LA.csv", listSaleExport);
}

public void writeToFile(String filename, List<listSaleExport> listSaleExport) throws IOException {

    File file = new File(PROCESSED_DIR +"\\", "filename");

    if (!file.exists()) {
        try {
            Writer writer = new FileWriter(PROCESSED_DIR +"\\" +filename, true);
            StatefulBeanToCsvBuilder<listSaleExport> beanToCsv = new StatefulBeanToCsvBuilder<>(writer);
            StatefulBeanToCsv<listSaleExport> beanWriter = beanToCsv.build();
            beanWriter.write(listSaleExport);
            writer.close();
        } catch (Exception ex) {
            System.out.println("Error : " + ex.getMessage());
        }
    } else {
        try {
            Writer writer = new FileWriter(PROCESSED_DIR +"\\" +"filename");
            StatefulBeanToCsvBuilder<listSaleExport> beanToCsv = new StatefulBeanToCsvBuilder<>(writer);
            StatefulBeanToCsv<listSaleExport> beanWriter = beanToCsv.build();
            beanWriter.write(listSaleExport);
            writer.close();
        } catch (Exception ex) {
            System.out.println("Error : " + ex.getMessage());
        }
    }
  }
}

Body:
I don't know if the feature was finally added in OpenCSV. Right now the latest version is 5.1 and I haven't read anything about it...

As I've posted in another question, I got it to work after updating to 5.1:

Needed to have CSVs with both specific field headers (@CsvBindByName) and positions (@CsvBindByPosition), so I already had to make my own MappingStrategy.

public class CustomMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
    private boolean useHeader=true;

    public CustomMappingStrategy(){
    }

    public CustomMappingStrategy(boolean useHeader) {
        this.useHeader = useHeader;
    }

    @Override
    public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
        final int numColumns = FieldUtils.getAllFields(bean.getClass()).length;
        super.setColumnMapping(new String[numColumns]);

        if (numColumns == -1) {
            return super.generateHeader(bean);
        }

        String[] header = new String[numColumns];

        if(!useHeader){
            return ArrayUtils.EMPTY_STRING_ARRAY;
        }
        BeanField<T, Integer> beanField;
        for (int i = 0; i < numColumns; i++){
            beanField = findField(i);
            String columnHeaderName = extractHeaderName(beanField);
            header[i] = columnHeaderName;
        }

        return header;
    }

    private String extractHeaderName(final BeanField<T, Integer> beanField){
        if (beanField == null || beanField.getField() == null || beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class).length == 0){
            return StringUtils.EMPTY;
        }

        //return value of CsvBindByName annotation
        final CsvBindByName bindByNameAnnotation = beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class)[0];
        return bindByNameAnnotation.column();
    }

}

I also made a generic exporter class, to ease CSV generation:

public class ExportGenericCSV<T> {
    private static final Logger logger = LoggerFactory.getLogger(ExportGenericCSV.class);
    private final char DEFAULT_QUOTE_CHARACTER = CSVWriter.NO_QUOTE_CHARACTER;
    private final char CSV_SEPARATOR = CSVWriter.DEFAULT_SEPARATOR;

    public void writeToFile(String fileName, List<T> content){
        writeList(fileName, content, true);
    }

    public void appendToFile(String fileName, List<T> content){
        writeList(fileName, content, false, StandardOpenOption.APPEND);
    }

    @SuppressWarnings("unchecked")
    private void writeList(String fileName, List<T> exports, boolean addHeader, OpenOption...openOptions){
        if(exports == null  || exports.isEmpty()) return;
        try (Writer writer = Files.newBufferedWriter(Paths.get(fileName), openOptions)){

            CustomMappingStrategy<T> mapping = new CustomMappingStrategy<T>(addHeader);
            mapping.setType((Class<? extends T>) exports.get(0).getClass());

            StatefulBeanToCsv<T> beanToCsv = new StatefulBeanToCsvBuilder<T>(writer)
                    .withQuotechar(DEFAULT_QUOTE_CHARACTER)
                    .withSeparator(CSV_SEPARATOR)
                    .withMappingStrategy(mapping)
                    .build();

            beanToCsv.write(exports);

            writer.flush();
            writer.close();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } catch (CsvDataTypeMismatchException e) {
            logger.error(e.getMessage(), e);
        } catch (CsvRequiredFieldEmptyException e) {
            logger.error(e.getMessage(), e);
        }
    }
}

This way, when you need to export a list of items you can use:

ExportGenericCSV<ExportedClass> exporter = new ExportGenericCSV<ExportedClass>();

and then use exporter.writeToFile(...) or exporter.appendToFile(...)


问:
How to merge two forms into one?
I want to have these two buttons in one line, so Remove button is in the position in which it is and the Update mapping button is on the right.
So it would looks like this:

[![enter image description here][1]][1]

答:
You can use floats for forms or display:flex on forms parent.

div {display:flex;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>        <div>
            <form action="/.../delete" method="post">
                <button type="submit" name="name1" th:value="${tmpl.variable1} + '_' + ${tmpl.variable2}"
                        class="secondary">Remove
                </button>
            </form>
            <form action="/.../update" method="get">
                <button type="submit" name="name2" th:value="${tmpl.variable1} + '_' + ${tmpl.variable2}"
                        class="button primary">Update mapping
                </button>
            </form>
            <pre th:utext="${tmpl.response}"/>
        </div></code>```

Title: How to merge two forms into one?

Body:
You can use floats for forms or display:flex on forms parent.

div {display:flex;}

        <div>
            <form action="/.../delete" method="post">
                <button type="submit" name="name1" th:value="${tmpl.variable1} + '_' + ${tmpl.variable2}"
                        class="secondary">Remove
                </button>
            </form>
            <form action="/.../update" method="get">
                <button type="submit" name="name2" th:value="${tmpl.variable1} + '_' + ${tmpl.variable2}"
                        class="button primary">Update mapping
                </button>
            </form>
            <pre th:utext="${tmpl.response}"/>
        </div>