问:
Angular 6 project with libraries using rxjs5
I'm trying to my project to newer Angular version. Newer Angular use rxjs 6, but my project uses some third party's libraries which still use rxjs5. How to deal with this case?

Many thanks!

答:
I recommend you that when update your angular version you also do it with the rxjs version separately to see if that works.

```<code>npm update rxjs@version
</code>```

In version, you should choose any version, for example:

```<code>npm update rxjs@6.0.0
</code>```

Let me know if its work

Body:
I recommend you that when update your angular version you also do it with the rxjs version separately to see if that works.

npm update rxjs@version

In version, you should choose any version, for example:

npm update rxjs@6.0.0

Let me know if its work


来源: stackexchange

问:
Android: How to show a spinner while performing a long-running operation?
I have a ProgressBar in .xml that I want to show when a long-running operation. I use

```<code>ProgressBar progressSpinner = (ProgressBar)findViewById(R.id.progressSpinner);
progressSpinner.setVisibility(View.VISIBLE);
</code>```

to set its visibility in some onButtonClick method. If the above code is all that is in the method, it works just fine. The problem is when I have a method like this:

```<code>public void onButtonClick (android.view.View view){
    ProgressBar progressSpinner = (ProgressBar)findViewById(R.id.progressSpinner);
    progressSpinner.setVisibility(View.VISIBLE);

    longRunningMethod(); // This method takes 5-10 seconds to run

    progressSpinner.setVisibility(View.GONE);
}
</code>```

The UI just locks up until longRunningMethod is done. That method works just fine, but the spinner never shows.

I tried running everything on a different thread with this:

```<code>public void onButtonClick (android.view.View view){
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    executorService.submit(this::longRunningMethod);
}
</code>```

And I added the spinner visibility changing stuff to longRunningMethod:

```<code>private void longRunningMethod(){
    ProgressBar progressSpinner = (ProgressBar)findViewById(R.id.progressSpinner);
    progressSpinner.setVisibility(View.VISIBLE);

    // Logic that takes 5-10 seconds to run.

    progressSpinner.setVisibility(View.GONE);
}
</code>```

When I do this, the UI doesn't lock up, but nothing in longRunningMethod works. The spinner won't show and the logic also doesn't seem to work, although this may just be a problem with that logic not playing nice on not-the-UI-thread. I am very confused that the spinner visibility won't update from here though.

答:
For running long task operations, you should use Worker Thread.
You must run your task in worker thread and then return task results to UI.

First method is using AsyncTask:

AsyncTask was intended to enable proper and easy use of the UI thread. However, the most common use case was for integrating into UI, and that would cause Context leaks, missed callbacks, or crashes on configuration changes. It also has inconsistent behavior on different versions of the platform, swallows exceptions from doInBackground, and does not provide much utility over using Executors directly.

Second one is using Pure Thread

All Android apps use a main thread to handle UI operations. Calling long-running operations from this main thread can lead to freezes and unresponsiveness. For example, if your app makes a network request from the main thread, your app's UI is frozen until it receives the network response. You can create additional background threads to handle long-running operations while the main thread continues to handle UI updates.

official document

and the last method is using Coroutine (just for kotlin)

if you are using kotlin i suggest this one otherwise use AsyncTask

Just try to run your tasks in other Thread and return results by using a callback like interface

ContentLicense: CC BY-SA 4.0

Body:
I have a ProgressBar in .xml that I want to show when a long-running operation. I use

ProgressBar progressSpinner = (ProgressBar)findViewById(R.id.progressSpinner);
progressSpinner.setVisibility(View.VISIBLE);

to set its visibility in some onButtonClick method. If the above code is all that is in the method, it works just fine. The problem is when I have a method like this:

public void onButtonClick (android.view.View view){
    ProgressBar progressSpinner = (ProgressBar)findViewById(R.id.progressSpinner);
    progressSpinner.setVisibility(View.VISIBLE);

    longRunningMethod(); // This method takes 5-10 seconds to run

    progressSpinner.setVisibility(View.GONE);
}

The UI just locks up until longRunningMethod is done. That method works just fine, but the spinner never shows.

I tried running everything on a different thread with this:

public void onButtonClick (android.view.View view){
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    executorService.submit(this::longRunningMethod);
}

And I added the spinner visibility changing stuff to longRunningMethod:

private void longRunningMethod(){
    ProgressBar progressSpinner = (ProgressBar)findViewById(R.id.progressSpinner);
    progressSpinner.setVisibility(View.VISIBLE);

    // Logic that takes 5-10 seconds to run.

    progressSpinner.setVisibility(View.GONE);
}

When I do this, the UI doesn't lock up, but nothing in longRunningMethod works. The spinner won't show and the logic also doesn't seem to work, although this may just be a problem with that logic not playing nice on not-the-UI-thread. I am very confused that the spinner visibility won't update from here though.


问:
Incremental BR tag counter isn´t working, something is missing
I have the following code, in order to add an incremental counter next to each BR tag, as a per line counter for a lyric song, but it isn´t working. Help is apreciated!</p>
```<code><?php $lyrics = "<p>Every time when I look in the mirror <br />All these lines on my face getting clearer <br /> The past is gone <br /> And it went by, like dusk to dawn <br /> Isn't that the way? <br /> Everybody's got their dues in life to pay <br /> Yeah, I know nobody knows <br /> Where it comes and where it goes <br /> I know it's everybody's sin <br /> You got to lose to know how to win <br /></p>";

$arr=explode(PHP_EOL, $lyrics);
foreach($arr as $index=>$ele)
{
echo $ele . $index+1 . "<br />";
} ?>
</code>```

答:
You are trying to split the string $lyrics on the PHP_EOL constant (This is a platform dependent constant which refers to the line ending your operating system uses). Instead you should try to split the string by
.

Body:
I have the following code, in order to add an incremental counter next to each BR tag, as a per line counter for a lyric song, but it isn´t working. Help is apreciated!

<?php $lyrics = "
Every time when I look in the mirror
All these lines on my face getting clearer
 The past is gone
 And it went by, like dusk to dawn
 Isn't that the way?
 Everybody's got their dues in life to pay
 Yeah, I know nobody knows
 Where it comes and where it goes
 I know it's everybody's sin
 You got to lose to know how to win

";

$arr=explode(PHP_EOL, $lyrics);
foreach($arr as $index=>$ele)
{
echo $ele . $index+1 . "
";
} ?>

Body: You are trying to split the string $lyrics on the PHP_EOL constant (This is a platform dependent constant which refers to the line ending your operating system uses). Instead you should try to split the string by <br />.


问:
Changed data-type in room, how to do a migration?
I have changed a column type from Float to Int, how can I migrate the change so I won't lost old entries, instead just to convert all of them to the Int.</p>

答:
You need to add a Migration that will create the table in it's new form and copy the data from it's old form.

The SQL for the new form can be ascertained by looking at the generated java (visible from the Android View of Android Studio). Look at the class that is named the same as the class that is annotated with @Database but suffixed with _Impl, and then  find the SQL in the method named createAllTables

You could then use the following

:-

DROP, just in case the intermediate old table e.g. DROP TABLE IF EXISTS table_old;

RENAME the original table using SQL based upon ALTER TABLE the_table RENAME TO the_table_old;

Create the new table using the SQL as obtained above

Copy the data using SQL based upon INSERT INTO the_table SELECT * FROM the_table_old;

DROP the now defunct old table e.g. DROP TABLE IF EXISTS table_old;;

Demo

As an example where the entity is (was commented out) :-

```<code>@Entity(tableName = "jourTable")
class Note(
    @ColumnInfo(name = "title") val jourTitle:String,
    @ColumnInfo(name = "description") val jourDescription:String,
    @ColumnInfo(name = "date") val jourDate:String,
    @ColumnInfo(name = "image", typeAffinity = ColumnInfo.BLOB) val jourImage: Bitmap?, //<<<<< will use the TypeConverter
    //@ColumnInfo(name = "altImage") val jourAltImage: ByteArray //<<<<< will not use the TypeConverter
    @ColumnInfo(name = "altImage") val jourAltImage: Int
) {
    @PrimaryKey(autoGenerate = true)var id=0
}
</code>```

i.e. commented out jourAltImage was ByteArray now to be Int (INTEGER type in SQL)

and the generated java is obtained via :-

The the @Database annotated class (TheDatabase) has :-

```<code>@TypeConverters(ImageConverter::class)
@Database(entities = [Note::class], version = 2 /*<<<<<<<<<< INCREASE FROM 1 to 2 (or as required)*/, exportSchema = false)
abstract class TheDatabase: RoomDatabase() {
    abstract fun getAllDao(): AllDao

    companion object {
        @Volatile
        private var instance: TheDatabase ? = null
        fun getInstance(context: Context): TheDatabase {
            if (instance == null) {
                instance = Room.databaseBuilder(context,TheDatabase::class.java,"the_database.db")
                    .allowMainThreadQueries()
                    .addMigrations(MIG_1_2) //<<<<<<<<<< ADD the migration
                    .build()
            }
            return instance as TheDatabase
        }
        /*<<<<<<<<<< The Migration >>>>>>>>>> */
        val MIG_1_2 = object: Migration(1,2){
            override fun migrate(db: SupportSQLiteDatabase) {
                db.execSQL("DROP TABLE IF EXISTS jourTable_old;")
                db.execSQL("ALTER TABLE jourTable RENAME TO jourTable_old ")
                /* SQL ON NEXT LINE COPIED FROM GENERATED JAVA */
                db.execSQL("CREATE TABLE IF NOT EXISTS `jourTable` (`title` TEXT NOT NULL, `description` TEXT NOT NULL, `date` TEXT NOT NULL, `image` BLOB, `altImage` INTEGER NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)")
                db.execSQL("INSERT INTO jourTable SELECT * FROM jourTable_old")
                db.execSQL("DROP TABLE IF EXISTS jourTable_old")
            }
        }
    }
}
</code>```

The when run App Inspection shows (it had 1 row) and the app adds 1 new row when run :-

as cab seen the altimage column is now INTEGER (was BLOB) and the 1 row has been retained.

Body:
You need to add a Migration that will create the table in it's new form and copy the data from it's old form.

The SQL for the new form can be ascertained by looking at the generated java (visible from the Android View of Android Studio). Look at the class that is named the same as the class that is annotated with @Database but suffixed with _Impl, and then  find the SQL in the method named createAllTables

You could then use the following

:-

DROP, just in case the intermediate old table e.g. DROP TABLE IF EXISTS table_old;

RENAME the original table using SQL based upon ALTER TABLE the_table RENAME TO the_table_old;

Create the new table using the SQL as obtained above

Copy the data using SQL based upon INSERT INTO the_table SELECT * FROM the_table_old;

DROP the now defunct old table e.g. DROP TABLE IF EXISTS table_old;;

Demo

As an example where the entity is (was commented out) :-

@Entity(tableName = "jourTable")
class Note(
    @ColumnInfo(name = "title") val jourTitle:String,
    @ColumnInfo(name = "description") val jourDescription:String,
    @ColumnInfo(name = "date") val jourDate:String,
    @ColumnInfo(name = "image", typeAffinity = ColumnInfo.BLOB) val jourImage: Bitmap?, //<<<<< will use the TypeConverter
    //@ColumnInfo(name = "altImage") val jourAltImage: ByteArray //<<<<< will not use the TypeConverter
    @ColumnInfo(name = "altImage") val jourAltImage: Int
) {
    @PrimaryKey(autoGenerate = true)var id=0
}

i.e. commented out jourAltImage was ByteArray now to be Int (INTEGER type in SQL)

and the generated java is obtained via :-

The the @Database annotated class (TheDatabase) has :-

@TypeConverters(ImageConverter::class)
@Database(entities = [Note::class], version = 2 /*<<<<<<<<<< INCREASE FROM 1 to 2 (or as required)*/, exportSchema = false)
abstract class TheDatabase: RoomDatabase() {
    abstract fun getAllDao(): AllDao

    companion object {
        @Volatile
        private var instance: TheDatabase ? = null
        fun getInstance(context: Context): TheDatabase {
            if (instance == null) {
                instance = Room.databaseBuilder(context,TheDatabase::class.java,"the_database.db")
                    .allowMainThreadQueries()
                    .addMigrations(MIG_1_2) //<<<<<<<<<< ADD the migration
                    .build()
            }
            return instance as TheDatabase
        }
        /*<<<<<<<<<< The Migration >>>>>>>>>> */
        val MIG_1_2 = object: Migration(1,2){
            override fun migrate(db: SupportSQLiteDatabase) {
                db.execSQL("DROP TABLE IF EXISTS jourTable_old;")
                db.execSQL("ALTER TABLE jourTable RENAME TO jourTable_old ")
                /* SQL ON NEXT LINE COPIED FROM GENERATED JAVA */
                db.execSQL("CREATE TABLE IF NOT EXISTS `jourTable` (`title` TEXT NOT NULL, `description` TEXT NOT NULL, `date` TEXT NOT NULL, `image` BLOB, `altImage` INTEGER NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)")
                db.execSQL("INSERT INTO jourTable SELECT * FROM jourTable_old")
                db.execSQL("DROP TABLE IF EXISTS jourTable_old")
            }
        }
    }
}

The when run App Inspection shows (it had 1 row) and the app adds 1 new row when run :-

as cab seen the altimage column is now INTEGER (was BLOB) and the 1 row has been retained.


问:
Why is maven looking for artifact in the wrong repo?
I'm defining a dependency in pom.xml in a Maven 3 project. Dependency is as follows:

```<code><dependency>
    <groupId>org.glassfish.web</groupId>
    <artifactId>el-impl</artifactId>
    <scope>runtime</scope>
    <version>2.2</version>
</dependency>
</code>```

Repostory is described in pom as follows:

```<code><repository>
    <id>java.net</id>
    <name>java.net</name>
    <url>http://download.java.net/maven/2</url>
</repository>
</code>```

Artifact is indeed present in the repository. It's easy to check. Despite that, Maven is trying to obtain the artifact from repo1.maven.org. What could be the reason of this? Maybe I make some crucial mistake in defining repository access? Other dependencies seem to do fine.

```<code>Plugin org.mortbay.jetty:maven-jetty-plugin:6.1.26 or one of its
dependencies could not be resolved: Could not find artifact
org.glassfish.web:el-impl:jar:2.2
in central (http://repo1.maven.org/maven2)
</code>```

答: In addition to the above mentioned answers, make sure your settings.xml is saved as an xml file not a text file i.e. its not saved settings.xml.txt.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm defining a dependency in pom.xml in a Maven 3 project. Dependency is as follows:

<dependency>
    <groupId>org.glassfish.web</groupId>
    <artifactId>el-impl</artifactId>
    <scope>runtime</scope>
    <version>2.2</version>
</dependency>

Repostory is described in pom as follows:

<repository>
    <id>java.net</id>
    <name>java.net</name>
    <url>http://download.java.net/maven/2</url>
</repository>

Artifact is indeed present in the repository. It's easy to check. Despite that, Maven is trying to obtain the artifact from repo1.maven.org. What could be the reason of this? Maybe I make some crucial mistake in defining repository access? Other dependencies seem to do fine.

Plugin org.mortbay.jetty:maven-jetty-plugin:6.1.26 or one of its
dependencies could not be resolved: Could not find artifact
org.glassfish.web:el-impl:jar:2.2
in central (http://repo1.maven.org/maven2)


问:
Derivative not ignoring fields for comparison
I have the following data structure. When I do a binary search on it, and pass in a &limit_price, it only matches if the values in size and orders matches as well. Because I am ignoring PartialEq I would assume it should only match on the price field.

Am I missing something?

```<code>#[derive(Derivative)]
#[derivative(Hash, PartialEq, Eq, PartialOrd, Ord, Debug)]
struct LimitPrice {
    price: OrderedFloat<f32>,

    #[derivative(Hash="ignore", PartialEq = "ignore", PartialOrd = "ignore")]
    size: OrderedFloat<f32>,
    #[derivative(Hash="ignore", PartialEq = "ignore", PartialOrd = "ignore")]
    orders: Vec<Order>,
}
</code>```

答:
A reproducible example shows that only Ord is incorrect.

Any time you implement Ord and PartialOrd, you need to ensure that the implementations agree. With #[derive] this is automatic, but because derivative allows you to skip fields it also makes it possible to get Ord and PartialOrd that don't agree with each other. In this code, it would make sense for them to both have the same "ignore" annotation.

```<code>#[derivative(Hash="ignore", PartialEq = "ignore", PartialOrd = "ignore", Ord = "ignore")]
                                                                      // ^^^^^^^^^^^^^^
</code>```

(playground)

Ord and PartialOrd have a different relationship than Eq and PartialEq. Eq is a marker trait – it has no behavior of its own, only a contract about the behavior of PartialEq. Ord, on the other hand, carries both a promise about the behavior of PartialOrd (that partial_cmp always returns Some) and its own behavior (a function that returns an Ordering directly). This is why you don't need an "ignore" annotation for Eq but you do need one for Ord.

Body:
I have the following data structure. When I do a binary search on it, and pass in a &limit_price, it only matches if the values in size and orders matches as well. Because I am ignoring PartialEq I would assume it should only match on the price field.

Am I missing something?

#[derive(Derivative)]
#[derivative(Hash, PartialEq, Eq, PartialOrd, Ord, Debug)]
struct LimitPrice {
    price: OrderedFloat<f32>,

    #[derivative(Hash="ignore", PartialEq = "ignore", PartialOrd = "ignore")]
    size: OrderedFloat<f32>,
    #[derivative(Hash="ignore", PartialEq = "ignore", PartialOrd = "ignore")]
    orders: Vec<Order>,
}

Body:
A reproducible example shows that only Ord is incorrect.

Any time you implement Ord and PartialOrd, you need to ensure that the implementations agree. With #[derive] this is automatic, but because derivative allows you to skip fields it also makes it possible to get Ord and PartialOrd that don't agree with each other. In this code, it would make sense for them to both have the same "ignore" annotation.

#[derivative(Hash="ignore", PartialEq = "ignore", PartialOrd = "ignore", Ord = "ignore")]
                                                                      // ^^^^^^^^^^^^^^

(playground)

Ord and PartialOrd have a different relationship than Eq and PartialEq. Eq is a marker trait – it has no behavior of its own, only a contract about the behavior of PartialEq. Ord, on the other hand, carries both a promise about the behavior of PartialOrd (that partial_cmp always returns Some) and its own behavior (a function that returns an Ordering directly). This is why you don't need an "ignore" annotation for Eq but you do need one for Ord.


问:
Python web requests: Accessing json data from web response
I have a question with probably a well-known answer. However I couldnt articulate it well enough to find answers on google.

Lets say you are using the developer interface of Chrome browser (Press F12). If you click on the network tab and go to any website, a lot of files will be queried there for example images, stylesheets and JSON-responses.

I want to parse these JSON-responses using python now.

Thanks in advance!

答:
You can save the network requests to a .har file (JSON format) and analyze that.

In your network tools panel, there is a download button to export as HAR format.

import json
with open('myrequests.har') as f:
    network_data = json.load(f)

print(network_data)
```

Or, as Jack Deeth answered you can make the requests using Python instead of your browser and get the response JSON data that way.

Though, this can sometimes be difficult depending on the website and nature of the request(s) (for example, needing to login and/or figuring out how to get all the proper arguments to make the request)

Body:
You can save the network requests to a .har file (JSON format) and analyze that.

In your network tools panel, there is a download button to export as HAR format.

import json
with open('myrequests.har') as f:
    network_data = json.load(f)

print(network_data)

Or, as Jack Deeth answered you can make the requests using Python instead of your browser and get the response JSON data that way.

Though, this can sometimes be difficult depending on the website and nature of the request(s) (for example, needing to login and/or figuring out how to get all the proper arguments to make the request)


问:
Compare folder size and run script if the size changed
I am trying to write a code which will carry out something with the newly added file to the folder. So, the way I see it is to calculate the folder size, compare it with the one calculated ±10 mins ago, and then to do something with the newly added file if the size of the folder did change.

```<code>while (True):
    def get_size(start_path='/Users/.../Desktop/files'):
        total_size = 0
        for dirpath, dirnames, filenames in os.walk(start_path):
            for f in filenames:
                fp = os.path.join(dirpath, f)
                # skip if it is symbolic link
                if not os.path.islink(fp):
                    total_size += os.path.getsize(fp)

        return total_size

    print(get_size(), 'bytes')
    time.sleep(10)
</code>```

The code above calculates the size of the folder every 10 seconds. I don't know how to compare it to the previous size though :(

Please, help..

答:
You can try something like that:</p>
```<code>before = 0
while (True):
    def get_size(start_path='.'):
        total_size = 0
        # use variable defined outside loop
        global before
        for dirpath, dirnames, filenames in os.walk(start_path):
            for f in filenames:
                fp = os.path.join(dirpath, f)
                # skip if it is symbolic link
                if not os.path.islink(fp):
                    total_size += os.path.getsize(fp)

        # Your logic
        if total_size > before:
            print("New: "+str(total_size - before))
        else:
            print("No changes")
        before = total_size
        return total_size

    print(get_size(), 'bytes')
    time.sleep(10)
</code>```

Body:
I am trying to write a code which will carry out something with the newly added file to the folder. So, the way I see it is to calculate the folder size, compare it with the one calculated ±10 mins ago, and then to do something with the newly added file if the size of the folder did change.

while (True):
    def get_size(start_path='/Users/.../Desktop/files'):
        total_size = 0
        for dirpath, dirnames, filenames in os.walk(start_path):
            for f in filenames:
                fp = os.path.join(dirpath, f)
                # skip if it is symbolic link
                if not os.path.islink(fp):
                    total_size += os.path.getsize(fp)

        return total_size

    print(get_size(), 'bytes')
    time.sleep(10)

The code above calculates the size of the folder every 10 seconds. I don't know how to compare it to the previous size though :(

Please, help..

Body:
You can try something like that:

before = 0
while (True):
    def get_size(start_path='.'):
        total_size = 0
        # use variable defined outside loop
        global before
        for dirpath, dirnames, filenames in os.walk(start_path):
            for f in filenames:
                fp = os.path.join(dirpath, f)
                # skip if it is symbolic link
                if not os.path.islink(fp):
                    total_size += os.path.getsize(fp)

        # Your logic
        if total_size > before:
            print("New: "+str(total_size - before))
        else:
            print("No changes")
        before = total_size
        return total_size

    print(get_size(), 'bytes')
    time.sleep(10)


问:
Disable double-tap "zoom" option in browser on touch devices
I want to disable the double-tap zoom functionality on specified elements in the browser (on touch devices), without disabling all the zoom functionality.

For example: One element can be tapped multiple times for something to happen. This works fine on desktop browsers (as expected), but on touch device browsers, it will zoom in.

答:
Here's a variation that currently, as of 2022, does the trick on most device versions; Android / iOS.
Note that for example iOS 14+ zooms in on any text input fields that has a font-size of less than 1rem 16px, which also quite senior pros seem to have missed.

A vanilla javascript example - that can be improved further - for example with logic to allow normal behavior scenarios too - so for your experimentation.

```<code>document.getElementById('selectorid').addEventListener('touchend' || 'dblclick', event => {
event.preventDefault();
event.stopImmediatePropagation();
    }, {
    passive: false
    });
</code>```

Here's a more covering example for testing purposes to see if it achieves wished results. This one affects all the elements on the page inherited in the DOM.

```<code> /* For testing purposes, overrides events that may trigger a "zoom"; note that this may cause other unexpected behavior */
 window.addEventListener('touchmove' || 'touchdowm' || 'touchend' || 'mousedown' || 'dblclick', event => {
            event.preventDefault();
            event.stopImmediatePropagation();

        }, {
            passive: false
        });
</code>```

Here's some simple CSS, for overriding test purposes - try it out on the page and you may expect a remedy clue if form fields are what's bugging. Although the minimum size of 16px is actually quite wishfully intentional for accesibillity concerns. Note that the "!important" flag isn't considered good practice to manifest in a production deploy.

```<code>/* CSS to test prevention of zoom when interacting with input fields */
input[type=text] {
   font-size: 1rem !important;
}
</code>```

Body:
Here's a variation that currently, as of 2022, does the trick on most device versions; Android / iOS.
Note that for example iOS 14+ zooms in on any text input fields that has a font-size of less than 1rem 16px, which also quite senior pros seem to have missed.

A vanilla javascript example - that can be improved further - for example with logic to allow normal behavior scenarios too - so for your experimentation.

document.getElementById('selectorid').addEventListener('touchend' || 'dblclick', event => {
event.preventDefault();
event.stopImmediatePropagation();
    }, {
    passive: false
    });

Here's a more covering example for testing purposes to see if it achieves wished results. This one affects all the elements on the page inherited in the DOM.

 /* For testing purposes, overrides events that may trigger a "zoom"; note that this may cause other unexpected behavior */
 window.addEventListener('touchmove' || 'touchdowm' || 'touchend' || 'mousedown' || 'dblclick', event => {
            event.preventDefault();
            event.stopImmediatePropagation();

        }, {
            passive: false
        });

Here's some simple CSS, for overriding test purposes - try it out on the page and you may expect a remedy clue if form fields are what's bugging. Although the minimum size of 16px is actually quite wishfully intentional for accesibillity concerns. Note that the "!important" flag isn't considered good practice to manifest in a production deploy.

/* CSS to test prevention of zoom when interacting with input fields */
input[type=text] {
   font-size: 1rem !important;
}


问:
How to take screen shot of current webpage using Javascript/JQuery?
I was trying to take screen shot of a web page using JavaScript/JQuery. Could you please explain me the code steps I need to follow?</p>

答:
If you want real screenshot and not to convert html to image then you can try my new JS library: screenshot.js.

It's enable to take real screenshot.

You load the script:

```
<p>and take screenshot:</p>
<pre class="lang-js prettyprint-override"><code>new Screenshot({success: img => {
        // callback function
        myimage = img;
    }});
</code>```

You can read more options in project page.

Body:
If you want real screenshot and not to convert html to image then you can try my new JS library: screenshot.js.

It's enable to take real screenshot.

You load the script:

<script src="https://raw.githubusercontent.com/amiad/screenshot.js/master/screenshot.js"></script>

and take screenshot:

new Screenshot({success: img => {
        // callback function
        myimage = img;
    }});

You can read more options in project page.


问:
bad request while using google index api in javascript
Hello evrey one i want to make a script that update my new urls of my website by using google indexing api from http://localhost:8000/test.html
i add http://localhost:8000 to Authorised JavaScript origins in the client ID
but i have error 400 :

```<code>Sign-in successful

cb=gapi.loaded_0:228 GET https://content.googleapis.com/discovery/v1/apis/indexing/v3/rest?pp=0&fields=kind%2Cname%2Cversion%2CrootUrl%2CservicePath%2Cresources%2Cparameters%2Cmethods%2CbatchPath%2Cid&key='my api' 400
wh @ cb=gapi.loaded_0:228
g @ cb=gapi.loaded_0:228
xh @ cb=gapi.loaded_0:229
(anonymous) @ cb=gapi.loaded_0:229
d @ cb=gapi.loaded_0:186
b @ cb=gapi.loaded_0:181

Error loading GAPI client for API
{error: {…}}
error:
code: 400
message: "Request contains an invalid argument."
status: "INVALID_ARGUMENT"
__proto__: Object
__proto__: Object
</code>```

i change the browser from chrome to edge it work one time then i shutdown my pc but day after the problem apear again.
i am using the api expoler script : link
i put the script and the console log as image

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

  <button onclick="authenticate().then(loadClient)">authorize and load</button>
  <button onclick="execute()">execute</button>

```

here the console log

答:
```<code><script src="https://apis.google.com/js/api.js"></script>
<script>
  /**
   * Sample JavaScript code for indexing.urlNotifications.publish
   * See instructions for running APIs Explorer code samples locally:
   * https://developers.google.com/explorer-help/code-samples#javascript
   */

  function authenticate() {
    return gapi.auth2.getAuthInstance()
        .signIn({scope: "https://www.googleapis.com/auth/indexing"})
        .then(function() { console.log("Sign-in successful"); },
              function(err) { console.error("Error signing in", err); });
  }
  function loadClient() {
    gapi.client.setApiKey("xxxxxxxxxxxxxxxxxxxx");
    return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/indexing/v3/rest")
        .then(function() { console.log("GAPI client loaded for API"); },
              function(err) { console.error("Error loading GAPI client for API", err); });
  }
  // Make sure the client is loaded and sign-in is complete before calling this method.
  function execute() {
    return gapi.client.indexing.urlNotifications.publish({
      "resource": {}
    })
        .then(function(response) {
                // Handle the results here (response.result has the parsed body).
                console.log("Response", response);
              },
              function(err) { console.error("Execute error", err); });
  }
  gapi.load("client:auth2", function() {
    gapi.auth2.init({client_id: "samplexxxxxxxxxxxxxxxxxx.apps.googleusercontent.com"});
  });
</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>
</code>```

not working and

```<code><script src="https://apis.google.com/js/api.js"></script>
    <script>
      /**
       * Sample JavaScript code for indexing.urlNotifications.publish
       * See instructions for running APIs Explorer code samples locally:
       * https://developers.google.com/explorer-help/code-samples#javascript
       */

      function authenticate() {
        return gapi.auth2.getAuthInstance()
            .signIn({scope: "https://www.googleapis.com/auth/indexing"})
            .then(function() { console.log("Sign-in successful"); },
                  function(err) { console.error("Error signing in", err); });
      }
      function loadClient() {
        gapi.client.setApiKey("xxxxxxxxxxxxxxxxxxxx");
        return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/indexing/v3/rest")
            .then(function() { console.log("GAPI client loaded for API"); },
                  function(err) { console.error("Error loading GAPI client for API", err); });
      }
      // Make sure the client is loaded and sign-in is complete before calling this method.
      function execute() {
        return gapi.client.indexing.urlNotifications.publish({
          "resource": {}
        })
            .then(function(response) {
                    // Handle the results here (response.result has the parsed body).
                    console.log("Response", response);
                  },
                  function(err) { console.error("Execute error", err); });
      }
      gapi.load("client:auth2", function() {
        gapi.auth2.init({client_id: "samplexxxxxxxxxxxxxxxxxx.apps.googleusercontent.com"});
      });
    </script>
    <button onclick="loadClient().then(authenticate)">authorize and load</button>
    <button onclick="execute()">execute</button>
</code>```

not working all error;
code code: 400
message: "Request contains an invalid argument."
status: "INVALID_ARGUMENT"

Body:
Hello evrey one i want to make a script that update my new urls of my website by using google indexing api from http://localhost:8000/test.html
i add http://localhost:8000 to Authorised JavaScript origins in the client ID
but i have error 400 :

Sign-in successful

cb=gapi.loaded_0:228 GET https://content.googleapis.com/discovery/v1/apis/indexing/v3/rest?pp=0&fields=kind%2Cname%2Cversion%2CrootUrl%2CservicePath%2Cresources%2Cparameters%2Cmethods%2CbatchPath%2Cid&key='my api' 400
wh @ cb=gapi.loaded_0:228
g @ cb=gapi.loaded_0:228
xh @ cb=gapi.loaded_0:229
(anonymous) @ cb=gapi.loaded_0:229
d @ cb=gapi.loaded_0:186
b @ cb=gapi.loaded_0:181

Error loading GAPI client for API
{error: {…}}
error:
code: 400
message: "Request contains an invalid argument."
status: "INVALID_ARGUMENT"
__proto__: Object
__proto__: Object

i change the browser from chrome to edge it work one time then i shutdown my pc but day after the problem apear again.
i am using the api expoler script : link
i put the script and the console log as image

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

  <button onclick="authenticate().then(loadClient)">authorize and load</button>
  <button onclick="execute()">execute</button>

here the console log

Body:
<script src="https://apis.google.com/js/api.js"></script>
<script>
  /**
   * Sample JavaScript code for indexing.urlNotifications.publish
   * See instructions for running APIs Explorer code samples locally:
   * https://developers.google.com/explorer-help/code-samples#javascript
   */

  function authenticate() {
    return gapi.auth2.getAuthInstance()
        .signIn({scope: "https://www.googleapis.com/auth/indexing"})
        .then(function() { console.log("Sign-in successful"); },
              function(err) { console.error("Error signing in", err); });
  }
  function loadClient() {
    gapi.client.setApiKey("xxxxxxxxxxxxxxxxxxxx");
    return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/indexing/v3/rest")
        .then(function() { console.log("GAPI client loaded for API"); },
              function(err) { console.error("Error loading GAPI client for API", err); });
  }
  // Make sure the client is loaded and sign-in is complete before calling this method.
  function execute() {
    return gapi.client.indexing.urlNotifications.publish({
      "resource": {}
    })
        .then(function(response) {
                // Handle the results here (response.result has the parsed body).
                console.log("Response", response);
              },
              function(err) { console.error("Execute error", err); });
  }
  gapi.load("client:auth2", function() {
    gapi.auth2.init({client_id: "samplexxxxxxxxxxxxxxxxxx.apps.googleusercontent.com"});
  });
</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>

not working and

<script src="https://apis.google.com/js/api.js"></script>
    <script>
      /**
       * Sample JavaScript code for indexing.urlNotifications.publish
       * See instructions for running APIs Explorer code samples locally:
       * https://developers.google.com/explorer-help/code-samples#javascript
       */

      function authenticate() {
        return gapi.auth2.getAuthInstance()
            .signIn({scope: "https://www.googleapis.com/auth/indexing"})
            .then(function() { console.log("Sign-in successful"); },
                  function(err) { console.error("Error signing in", err); });
      }
      function loadClient() {
        gapi.client.setApiKey("xxxxxxxxxxxxxxxxxxxx");
        return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/indexing/v3/rest")
            .then(function() { console.log("GAPI client loaded for API"); },
                  function(err) { console.error("Error loading GAPI client for API", err); });
      }
      // Make sure the client is loaded and sign-in is complete before calling this method.
      function execute() {
        return gapi.client.indexing.urlNotifications.publish({
          "resource": {}
        })
            .then(function(response) {
                    // Handle the results here (response.result has the parsed body).
                    console.log("Response", response);
                  },
                  function(err) { console.error("Execute error", err); });
      }
      gapi.load("client:auth2", function() {
        gapi.auth2.init({client_id: "samplexxxxxxxxxxxxxxxxxx.apps.googleusercontent.com"});
      });
    </script>
    <button onclick="loadClient().then(authenticate)">authorize and load</button>
    <button onclick="execute()">execute</button>

not working all error;
code code: 400
message: "Request contains an invalid argument."
status: "INVALID_ARGUMENT"


问:
Prettier vscode extension ignoring config files
I can't get the prettier extension to use my config files. It keeps using the global settings (as defined in the config path setting in vscode). I made an example project:

https://github.com/Supperhero1/prettierTest

I set tabWidth to 1 in the .prettierrc file. When I run "npx prettier --write ." the prettier package properly formats the test.ts document to have an indentation of one, but if i save the file (I have format on save turned on) it gets formatted back to the global setting (4 spaces). I deleted all settings in the global setting but then it defaults to a tab with of two spaces. The extension seems to ignore the config file completely. A collegue has the extension and it works fine with config files.

I'm trying to figure out what could be overriding the setting, the exension description says the precedence for figuring out settings is:

```<code>Prettier configuration file
.editorconfig
Visual Studio Code Settings (Ignored if any other configuration is present)
</code>```

And in the official docs, the config file resolution precedence is:

```<code>A "prettier" key in your package.json file.
A .prettierrc file written in JSON or YAML.
...
</code>```

Seeing how I don't have a prettier key in my package.json file, there should be nothing that can override my .prettierrc file. I tried restarting vscode but that didn't help. Has anyone else had this issue, I'm not sure where to look to solve this problem...

答:
The only way that worked with me was uninstalling and then re-installing the Prettier - Code formatter in VS Code.

I tried many different ways that other people recommended, but nothing worked.

FYI, my repository currently has formatting rules in .editorconfig, .eslintrc.json, .prettierrc.html.json, .prettierrc.ts.json, .prettierrc.scss.json locally.

Body:
I can't get the prettier extension to use my config files. It keeps using the global settings (as defined in the config path setting in vscode). I made an example project:

https://github.com/Supperhero1/prettierTest

I set tabWidth to 1 in the .prettierrc file. When I run "npx prettier --write ." the prettier package properly formats the test.ts document to have an indentation of one, but if i save the file (I have format on save turned on) it gets formatted back to the global setting (4 spaces). I deleted all settings in the global setting but then it defaults to a tab with of two spaces. The extension seems to ignore the config file completely. A collegue has the extension and it works fine with config files.

I'm trying to figure out what could be overriding the setting, the exension description says the precedence for figuring out settings is:

Prettier configuration file
.editorconfig
Visual Studio Code Settings (Ignored if any other configuration is present)

And in the official docs, the config file resolution precedence is:

A "prettier" key in your package.json file.
A .prettierrc file written in JSON or YAML.
...

Seeing how I don't have a prettier key in my package.json file, there should be nothing that can override my .prettierrc file. I tried restarting vscode but that didn't help. Has anyone else had this issue, I'm not sure where to look to solve this problem...


问:
Recommended way of parsing a Form into an URLSearchParam object in Typescript
I'm learning typescript translating an old project from JS to TS. I'm having problems with this function that is called when a submit button is pressed in a login form with the default behaviour prevented. When called, the event is passed as parameter.

In the body of the function I'm trying to parse the content of the <form> into an URLSearchParam object.

```<code>function sendLogin(e: SubmitEvent) {
    let URLSP: URLSearchParams;
    if (e.target instanceof HTMLFormElement) {
        URLSP = new URLSearchParams(new FormData(e.target));
...
</code>```

This approach (the one of the original JS app) is clean but doesn't work because TS complains about: URLsearchParams doesn't accept FormData datatype as argument.

```<code>function sendLogin(e: SubmitEvent) {
    let URLSP: URLSearchParams;
    if (e.target instanceof HTMLFormElement) {
        let A = new FormData(e.target);
        let B = [...A.entries()];
        let URLSP = new URLSearchParams(B);
    }
...
</code>```

This second approach also doesn't work because B has [String,FormDataEntryValue][] datatype. URLSearchParams accepted datatypes are string | URLSearchParams | string[][] | Record<string, string>.

Which would be the cleanest way to parse my <form> into an URLSearchParam object in TS?

答:
FormData is actually not full compatible with URLSearchParams contructor, sadly. See Typescript #30584 for more info.

That issue thread has a few workarounds, such as:

```<code>const convertedFormEntries = Array.from(
  formData,
  ([key, value]) => (
    [key, typeof value === 'string' ? value : value.name]
  ),
);
</code>```

Which seems to work, as far as I can tell.

Playground

Body:
I'm learning typescript translating an old project from JS to TS. I'm having problems with this function that is called when a submit button is pressed in a login form with the default behaviour prevented. When called, the event is passed as parameter.

In the body of the function I'm trying to parse the content of the <form> into an URLSearchParam object.

function sendLogin(e: SubmitEvent) {
    let URLSP: URLSearchParams;
    if (e.target instanceof HTMLFormElement) {
        URLSP = new URLSearchParams(new FormData(e.target));
...

This approach (the one of the original JS app) is clean but doesn't work because TS complains about: URLsearchParams doesn't accept FormData datatype as argument.

function sendLogin(e: SubmitEvent) {
    let URLSP: URLSearchParams;
    if (e.target instanceof HTMLFormElement) {
        let A = new FormData(e.target);
        let B = [...A.entries()];
        let URLSP = new URLSearchParams(B);
    }
...

This second approach also doesn't work because B has [String,FormDataEntryValue][] datatype. URLSearchParams accepted datatypes are string | URLSearchParams | string[][] | Record<string, string>.

Which would be the cleanest way to parse my <form> into an URLSearchParam object in TS?

Body:
FormData is actually not full compatible with URLSearchParams contructor, sadly. See Typescript #30584 for more info.

That issue thread has a few workarounds, such as:

const convertedFormEntries = Array.from(
  formData,
  ([key, value]) => (
    [key, typeof value === 'string' ? value : value.name]
  ),
);

Which seems to work, as far as I can tell.

Playground


问:
Remove file location from document print using Javascript
I am using Javascript to print a div contents it works fine but it also prints the file location on top-right position which gives an odd impression on the output. here i attached the snap of it.

Thanks.

答:
This link has nothing to do with your code. It is put there by the browsers printing engine.

In most browsers, the user can change that, in others (e.g. Chrome) they can't.

Either way, there's nothing you can do from your end.


问:
Got TypeError: got an unexpected keyword argument 'dim_order' when calculating Temperature advection with Metpy?
I was recreating the code from Metpy Case Study

using ERA5 data. But calculating advection I got this error:
 TypeError: got an unexpected keyword argument 'dim_order'

Here is my full code using colab link: https://colab.research.google.com/drive/1UlYPoT6rF7BkHCIta8t7DlnTeq8Mu8wr?usp=sharing

答:
The linked example is unfortunately out-of-date with recent versions of MetPy. As noted in this StackOverflow answer, the signature for metpy.calc.advection as of v1.0 has changed to (scalar, u, v), and dim_order is no longer valid as an argument, but instead dimension order is automatically inferred (or manually specified with y_dim and x_dim). In your example, using the updated API could look something like

import metpy.calc as mpcalc
from metpy.units import units
import xarray as xr

data = xr.open_dataset(file).metpy.parse_cf()

level = 850 * units.hPa  # units.Quantity([ 250,  300,  500,  750,  850,
                         # 925, 1000], 'hPa')

temp = data['t'].isel(time=0).metpy.sel(vertical=level)
u_wind = data['u'].isel(time=0).metpy.sel(vertical=level)
v_wind = data['v'].isel(time=0).metpy.sel(vertical=level)

temp_adv = mpcalc.advection(temp, u_wind, v_wind)
```


问:
AWS EKS - Dead container cleanup
I am using Terraform to create infrastructure on AWS environment. Out of many services, we are also creating AWS EKS using terraform-aws-modules/eks/aws module. The EKS is primarily used for spinning dynamic containers to handle asynchronous job execution. Once a given task is completed the container releases resources and terminates.

What I have noticed is that, the dead containers lying on the EKS cluster forever. This is causing too many dead containers just sitting on EKS and consuming storage. I came across few blogs which mention that Kubernetes has garbage collection process, but none describes how it can be specified using Terraform or explicitly for AWS EKS.

Hence I am looking for a solution, which will help to specify garbage collection policy for dead containers on AWS EKS. If not achievable via Terraform, I am ok with using kubectl with AWS EKS.

答:
These two kubelet flags will cause the node to clean up docker images when the filesystem reaches those percentages. https://kubernetes.io/docs/concepts/architecture/garbage-collection/#container-image-lifecycle

```<code>--image-gc-high-threshold="85"
--image-gc-low-threshold="80"
</code>```

But you also probably want to set --maximum-dead-containers 1 so that running multiple (same) images doesn't leave dead containers around.

In EKS you can add these flags to the UserData section of your EC2 instance/Autoscaling group.

```<code>#!/bin/bash
set -o xtrace
/etc/eks/bootstrap.sh --apiserver-endpoint ..... --kubelet-extra-args '<here>'
</code>```

Title: AWS EKS - Dead container cleanup

Body:
These two kubelet flags will cause the node to clean up docker images when the filesystem reaches those percentages. https://kubernetes.io/docs/concepts/architecture/garbage-collection/#container-image-lifecycle

--image-gc-high-threshold="85"
--image-gc-low-threshold="80"

But you also probably want to set --maximum-dead-containers 1 so that running multiple (same) images doesn't leave dead containers around.

In EKS you can add these flags to the UserData section of your EC2 instance/Autoscaling group.

#!/bin/bash
set -o xtrace
/etc/eks/bootstrap.sh --apiserver-endpoint ..... --kubelet-extra-args '<here>'


答:
Try it this way: use "
" to separate and make each echo single:

```<code>$lyrics = "<p>Every time when I look in the mirror <br />All these lines on my face getting clearer <br /> The past is gone <br /> And it went by, like dusk to dawn <br /> Isn't that the way? <br /> Everybody's got their dues in life to pay <br /> Yeah, I know nobody knows <br /> Where it comes and where it goes <br /> I know it's everybody's sin <br /> You got to lose to know how to win <br /></p>";

$arr=explode("<br />", $lyrics);
foreach($arr as $index=>$ele)
{
    echo $ele;
    echo $index+1;
    echo "<br />";
}
</code>```

Title: Incremental BR tag counter isn´t working, something is missing

Body:
I have the following code, in order to add an incremental counter next to each BR tag, as a per line counter for a lyric song, but it isn´t working. Help is apreciated!

<?php $lyrics = "
Every time when I look in the mirror
All these lines on my face getting clearer
 The past is gone
 And it went by, like dusk to dawn
 Isn't that the way?
 Everybody's got their dues in life to pay
 Yeah, I know nobody knows
 Where it comes and where it goes
 I know it's everybody's sin
 You got to lose to know how to win

";

$arr=explode(PHP_EOL, $lyrics);
foreach($arr as $index=>$ele)
{
echo $ele . $index+1 . "
";
} ?>

Body:
Try it this way: use "<br />" to separate and make each echo single:

$lyrics = "<p>Every time when I look in the mirror <br />All these lines on my face getting clearer <br /> The past is gone <br /> And it went by, like dusk to dawn <br /> Isn't that the way? <br /> Everybody's got their dues in life to pay <br /> Yeah, I know nobody knows <br /> Where it comes and where it goes <br /> I know it's everybody's sin <br /> You got to lose to know how to win <br /></p>";

$arr=explode("<br />", $lyrics);
foreach($arr as $index=>$ele)
{
    echo $ele;
    echo $index+1;
    echo "<br />";
}


问:
Merging Object and List with Lambdas
I have a situation similar to the follows:

```<code>List<ObjectA> all = repository.findAll(Sort.by(Sort.Direction.ASC, "status"));
</code>```

This find a list of object with three possible states: OPEN, CLOSED, PROGRAMMED

Now I must return a List that shows to the user the last PROGRAMMED object, the first OPEN object and all closed objects. I have writing something like that:

```<code>ObjectA programmed = all.stream().filter(isPROGRAMMED()).reduce((x,y) -> y).orElse(null);
ObjectA open = all.stream().filter(isOPEN()).findFirst().get();
List<ObjectA> closed = all.stream().filter(isCLOSED()).collect(Collectors.toList());
</code>```

isOPEN(), isPROGRAMMED() and isCLOSED() are Predicate I have written as follows:

```<code>private static Predicate<ObjectA> isPROGRAMMED() {
    return x -> x.getStatus().equals(Stato.PROGRAMMED);
}

private static Predicate<ObjectA> isOPEN() {
    return x -> x.getStatus().equals(Stato.OPEN);
}

private static Predicate<ObjectA> isCLOSED() {
    return x -> x.getStatus().equals(Stato.CLOSED);
}
</code>```

Now I want just to merge the two object and the third list into one. List should contain programmed item (if present) open object (if present) and after that all closed items. I jave tried with Stream.of, Stream.concat but I always obtain some compilation errors..

Are there some way to do it with Lambdas and with few code?

答:
If you want to avoid mutation of the closed list, then Stream IPA is one of the possible choices for this task.

It could be done like this:

```<code>    public static List<ObjectA> merge(List<ObjectA> closed, ObjectA programmed, ObjectA open) {
        return Stream.concat(Stream.of(programmed, open),
                             closed.stream())
                .collect(Collectors.toList());
    }
</code>```

And as I've already mentioned in the comment if are not concerned about preserving the initial state of the closed list, then these objects can be added directly to the list. Since adding a new element at the beginning of the list is costly (if it's backed by the array), a better option will be make use of addAll() and add both values in one operation as Holger suggested :

```<code>        closed.addAll(0, Arrays.asList(programmed, open));
</code>```

Side note:

There's an inconsistency in how you are obtaining a programmed object and open object. If a programmed object doesn't exist your decided to return null. But if there's no open object, method get() will raise NoSuchElementException.

```<code>ObjectA programmed = all.stream().filter(isPROGRAMMED()).reduce((x,y) -> y).orElse(null);
ObjectA open = all.stream().filter(isOPEN()).findFirst().get();
</code>```

Title: Merging Object and List with Lambdas

Body:
I have a situation similar to the follows:

List<ObjectA> all = repository.findAll(Sort.by(Sort.Direction.ASC, "status"));

This find a list of object with three possible states: OPEN, CLOSED, PROGRAMMED

Now I must return a List that shows to the user the last PROGRAMMED object, the first OPEN object and all closed objects. I have writing something like that:

ObjectA programmed = all.stream().filter(isPROGRAMMED()).reduce((x,y) -> y).orElse(null);
ObjectA open = all.stream().filter(isOPEN()).findFirst().get();
List<ObjectA> closed = all.stream().filter(isCLOSED()).collect(Collectors.toList());

isOPEN(), isPROGRAMMED() and isCLOSED() are Predicate I have written as follows:

private static Predicate<ObjectA> isPROGRAMMED() {
    return x -> x.getStatus().equals(Stato.PROGRAMMED);
}

private static Predicate<ObjectA> isOPEN() {
    return x -> x.getStatus().equals(Stato.OPEN);
}

private static Predicate<ObjectA> isCLOSED() {
    return x -> x.getStatus().equals(Stato.CLOSED);
}

Now I want just to merge the two object and the third list into one. List should contain programmed item (if present) open object (if present) and after that all closed items. I jave tried with Stream.of, Stream.concat but I always obtain some compilation errors..

Are there some way to do it with Lambdas and with few code?

Body:
If you want to avoid mutation of the closed list, then Stream IPA is one of the possible choices for this task.

It could be done like this:

    public static List<ObjectA> merge(List<ObjectA> closed, ObjectA programmed, ObjectA open) {
        return Stream.concat(Stream.of(programmed, open),
                             closed.stream())
                .collect(Collectors.toList());
    }

And as I've already mentioned in the comment if are not concerned about preserving the initial state of the closed list, then these objects can be added directly to the list. Since adding a new element at the beginning of the list is costly (if it's backed by the array), a better option will be make use of addAll() and add both values in one operation as Holger suggested :

        closed.addAll(0, Arrays.asList(programmed, open));

Side note:

There's an inconsistency in how you are obtaining a programmed object and open object. If a programmed object doesn't exist your decided to return null. But if there's no open object, method get() will raise NoSuchElementException.

ObjectA programmed = all.stream().filter(isPROGRAMMED()).reduce((x,y) -> y).orElse(null);
ObjectA open = all.stream().filter(isOPEN()).findFirst().get();


问:
Django rest framework create-only serializer field
I'm have a Django model that serves as a request description. It is created to issue a request by a REST client, serves to record the tasks current status, and record historical requests received by clients.

This model has a few fields that are used to fine-tune and control the requested task (say, a target object and the type of action). Obviously, I'd like the client to control those fields on object creation but not afterwards (you can't change the object once the task started running).

I was hoping for something similar to serializers.ReadOnlyField, so I could have something similar to this:

```<code>class TaskSerializer(serializers.ModelSerializer):
    owner = serializers.ReadOnlyField(source='owner.username')
    task_id = serializers.ReadOnlyField()
    target_object = serializers.CreateOnlyField()
</code>```

but couldn't find it in the documentation or google.

答:
This can be achieved with one serializer by using to_internal_value method

```<code>class TaskSerializer(serializers.ModelSerializer):
    # Field settings here

    def to_internal_value(self, data):
        data = super().to_internal_value(data)
        # Remove target_object if serializer is updating object
        if self.instance:
            data.pop('target_object', None)
        return data

    class Meta:
        model = Task
        fields = ('owner', 'task_id', 'target_object')
</code>```

Body:
I'm have a Django model that serves as a request description. It is created to issue a request by a REST client, serves to record the tasks current status, and record historical requests received by clients.

This model has a few fields that are used to fine-tune and control the requested task (say, a target object and the type of action). Obviously, I'd like the client to control those fields on object creation but not afterwards (you can't change the object once the task started running).

I was hoping for something similar to serializers.ReadOnlyField, so I could have something similar to this:

class TaskSerializer(serializers.ModelSerializer):
    owner = serializers.ReadOnlyField(source='owner.username')
    task_id = serializers.ReadOnlyField()
    target_object = serializers.CreateOnlyField()

but couldn't find it in the documentation or google.

Body:
This can be achieved with one serializer by using to_internal_value method

class TaskSerializer(serializers.ModelSerializer):
    # Field settings here

    def to_internal_value(self, data):
        data = super().to_internal_value(data)
        # Remove target_object if serializer is updating object
        if self.instance:
            data.pop('target_object', None)
        return data

    class Meta:
        model = Task
        fields = ('owner', 'task_id', 'target_object')


问:
$JAVA_HOME path not sourced correctly in ~/bash_profile at login
Upon logging into my CentOS 7 VM, my $JAVA_HOME is always set to :
/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.131-11.b12.el7.x86_64/jre, which is incorrect.

My ~/.bash_profile reads:

```<code>#  .bash_profile

#  Get the aliases and functions
if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

# User specific environment and startup programs
JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.144-0.b01.el7_4.x86_64/jre
export JAVA_HOME

PYCHARM_HOME=/opt/pycharm-community-2017.2.3/
export PYCHARM_HOME

ECLIPSE_HOME=/opt/eclipse
export ECLIPSE_HOME

export SPARK_HOME=/opt/spark

PATH=$PATH:$HOME/.local/bin:$HOME/bin:$JAVA_HOME/bin:$SPARK_HOME/bin:$PYCHARM_HOME/bin:$ECLIPSE_HOME

export PATH
</code>```

Sourcing .bash_profile each time I open a new terminal appears to correct the issue, but why is my $JAVA_HOME path defaulting to an old version on startup and not being set to the directory specified in .bash_profile?

答:
It worked for me!

In my case, The follwing caused the error:

export JAVA_HOME = /Library/Java/JavaVirtualMachines/jdk1.8.0_101.jdk/Contents/Home

The error was that there were spaces before and after the = . The error disappeared after those spaces were removed.

So the correct command is as follows:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_101.jdk/Contents/Home

Body:
Upon logging into my CentOS 7 VM, my $JAVA_HOME is always set to :
/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.131-11.b12.el7.x86_64/jre, which is incorrect.

My ~/.bash_profile reads:

#  .bash_profile

#  Get the aliases and functions
if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

# User specific environment and startup programs
JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.144-0.b01.el7_4.x86_64/jre
export JAVA_HOME

PYCHARM_HOME=/opt/pycharm-community-2017.2.3/
export PYCHARM_HOME

ECLIPSE_HOME=/opt/eclipse
export ECLIPSE_HOME

export SPARK_HOME=/opt/spark

PATH=$PATH:$HOME/.local/bin:$HOME/bin:$JAVA_HOME/bin:$SPARK_HOME/bin:$PYCHARM_HOME/bin:$ECLIPSE_HOME

export PATH

Sourcing .bash_profile each time I open a new terminal appears to correct the issue, but why is my $JAVA_HOME path defaulting to an old version on startup and not being set to the directory specified in .bash_profile?


问:
HttpURLConnection send variables along with multipart data
I am trying to upload a file to web server,and also send two variables along with it. The file uploads correctly but the variables are not available at server side .Here is my code

```<code> URL url = new URL(upLoadServerUri);

            // Open a HTTP connection to the URL
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true); // Allow Inputs
            conn.setDoOutput(true); // Allow Outputs
            conn.setUseCaches(false); // Don't use a Cached Copy
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("uploaded_file", fileName);
            conn.setRequestProperty("from", phone);//here
            conn.setRequestProperty("contact", contact);//here
            dos = new DataOutputStream(conn.getOutputStream());
            String urlParameters = "from=" + phone + "&contact=" + contact;
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                    + fileName + "\"" + lineEnd);

            dos.writeBytes(lineEnd);
</code>```

At server side which is PHP i am accessing the variables from and contact using $_SERVER['from'];

Can you point out what am i doing wrong or a new approach to it?

I also tried dos.writeBytes("contact=a&from=b");

答:
I found the solution on this thread:
Sending files using POST with HttpURLConnection

This is what i end typing:

```<code>    String boundary =  "*****";
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    HttpsURLConnection conn = null;
    DataOutputStream dos = null;
    BufferedReader inStream = null;
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 10*1024*1024;
    String urlString = "https://yoururl.com/phpfile.php";
    try{
        File f = new File("filepath");
        String filename = "filename";
        FileInputStream fileInputStream = new FileInputStream(f);

        // open a URL connection to the Servlet
        URL url = new URL(urlString);
        // Open a HTTP connection to the URL
        conn = (HttpsURLConnection) url.openConnection();
        // Allow Inputs
        conn.setDoInput(true);
        // Allow Outputs
        conn.setDoOutput(true);
        // Don't use a cached copy.
        conn.setUseCaches(false);
        // Use a post method.
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("enctype", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
        conn.setRequestProperty("upfile", filename);

        dos = new DataOutputStream( conn.getOutputStream() );

        String name = "myvariable";
        String value = "123456";

        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"" + name + "\""+ lineEnd);
        dos.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
        dos.writeBytes(lineEnd);
        dos.writeBytes(value+ lineEnd);

        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"upfile\"; filename='"+ filename+"'" + lineEnd);
        dos.writeBytes(lineEnd);
        // create a buffer of maximum size
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];
        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        while (bytesRead > 0)
        {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }
        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        // Responses from the server (code and message)
        int serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();

        Log.i("upfile", "HTTP Response is : "
                + serverResponseMessage + ": " + serverResponseCode);

        // close streams
        fileInputStream.close();
        dos.flush();
        dos.close();
    }
    catch (MalformedURLException ex)
    {
        Log.e("Debug", "erro: " + ex.getMessage(), ex);
    }
    catch (IOException ioe)
    {
        Log.e("Debug", "erro: " + ioe.getMessage(), ioe);
    }
</code>```

And this is my php relevant code:

```<code>try {

if (
    !isset($_FILES['upfile']['error']) ||
    is_array($_FILES['upfile']['error'])
) {
    throw new RuntimeException('Invalid parameters.');
}

switch ($_FILES['upfile']['error']) {
    case UPLOAD_ERR_OK:
        break;
    case UPLOAD_ERR_NO_FILE:
        throw new RuntimeException('No file sent.');
    case UPLOAD_ERR_INI_SIZE:
    case UPLOAD_ERR_FORM_SIZE:
        throw new RuntimeException('Exceeded filesize limit.');
    default:
        throw new RuntimeException('Unknown errors.');
}

if ($_FILES['upfile']['size'] > 100000) {
    throw new RuntimeException('Exceeded filesize limit.');
}

$variable = $_REQUEST["myvariable"];
//do what you want with the variable you send

if (!move_uploaded_file(
    $_FILES['upfile']['tmp_name'],
    sprintf('myfolder/%s',
        $_FILES['upfile']['name']
    )
)) {
    throw new RuntimeException('Failed to move uploaded file.');
}

echo 'File is uploaded successfully.';

} catch (RuntimeException $e) {

    echo $e->getMessage();

}
</code>```

Body:
I am trying to upload a file to web server,and also send two variables along with it. The file uploads correctly but the variables are not available at server side .Here is my code

 URL url = new URL(upLoadServerUri);

            // Open a HTTP connection to the URL
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true); // Allow Inputs
            conn.setDoOutput(true); // Allow Outputs
            conn.setUseCaches(false); // Don't use a Cached Copy
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("uploaded_file", fileName);
            conn.setRequestProperty("from", phone);//here
            conn.setRequestProperty("contact", contact);//here
            dos = new DataOutputStream(conn.getOutputStream());
            String urlParameters = "from=" + phone + "&contact=" + contact;
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                    + fileName + "\"" + lineEnd);

            dos.writeBytes(lineEnd);

At server side which is PHP i am accessing the variables from and contact using $_SERVER['from'];

Can you point out what am i doing wrong or a new approach to it?

I also tried dos.writeBytes("contact=a&from=b");

Body:
I found the solution on this thread:
Sending files using POST with HttpURLConnection

This is what i end typing:

    String boundary =  "*****";
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    HttpsURLConnection conn = null;
    DataOutputStream dos = null;
    BufferedReader inStream = null;
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 10*1024*1024;
    String urlString = "https://yoururl.com/phpfile.php";
    try{
        File f = new File("filepath");
        String filename = "filename";
        FileInputStream fileInputStream = new FileInputStream(f);

        // open a URL connection to the Servlet
        URL url = new URL(urlString);
        // Open a HTTP connection to the URL
        conn = (HttpsURLConnection) url.openConnection();
        // Allow Inputs
        conn.setDoInput(true);
        // Allow Outputs
        conn.setDoOutput(true);
        // Don't use a cached copy.
        conn.setUseCaches(false);
        // Use a post method.
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("enctype", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
        conn.setRequestProperty("upfile", filename);

        dos = new DataOutputStream( conn.getOutputStream() );

        String name = "myvariable";
        String value = "123456";

        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"" + name + "\""+ lineEnd);
        dos.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
        dos.writeBytes(lineEnd);
        dos.writeBytes(value+ lineEnd);

        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"upfile\"; filename='"+ filename+"'" + lineEnd);
        dos.writeBytes(lineEnd);
        // create a buffer of maximum size
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];
        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        while (bytesRead > 0)
        {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }
        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        // Responses from the server (code and message)
        int serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();

        Log.i("upfile", "HTTP Response is : "
                + serverResponseMessage + ": " + serverResponseCode);

        // close streams
        fileInputStream.close();
        dos.flush();
        dos.close();
    }
    catch (MalformedURLException ex)
    {
        Log.e("Debug", "erro: " + ex.getMessage(), ex);
    }
    catch (IOException ioe)
    {
        Log.e("Debug", "erro: " + ioe.getMessage(), ioe);
    }

And this is my php relevant code:

try {

if (
    !isset($_FILES['upfile']['error']) ||
    is_array($_FILES['upfile']['error'])
) {
    throw new RuntimeException('Invalid parameters.');
}

switch ($_FILES['upfile']['error']) {
    case UPLOAD_ERR_OK:
        break;
    case UPLOAD_ERR_NO_FILE:
        throw new RuntimeException('No file sent.');
    case UPLOAD_ERR_INI_SIZE:
    case UPLOAD_ERR_FORM_SIZE:
        throw new RuntimeException('Exceeded filesize limit.');
    default:
        throw new RuntimeException('Unknown errors.');
}

if ($_FILES['upfile']['size'] > 100000) {
    throw new RuntimeException('Exceeded filesize limit.');
}

$variable = $_REQUEST["myvariable"];
//do what you want with the variable you send

if (!move_uploaded_file(
    $_FILES['upfile']['tmp_name'],
    sprintf('myfolder/%s',
        $_FILES['upfile']['name']
    )
)) {
    throw new RuntimeException('Failed to move uploaded file.');
}

echo 'File is uploaded successfully.';

} catch (RuntimeException $e) {

    echo $e->getMessage();

}


问:
Development Language IT on Xcode
Hello everyone I wanted to have information ...
I changed the development language on Xcode EN -> IT
Now I wanted to know if these changes will remain even when I publish the app on the app store or if they remain only during development

My app is for Italy only and I wanted to know if I can avoid entering Locale(identifier: "it") for each date display, now that I have set the development language to Italian.

答:
You will want to go to File > New File > Strings File, name it Localizable.strings, this is important.
Open the attribute inspector. Click Localize..., select your language.

In your file, for each piece of text you want to show in your app, come up with an identifier/key for it, then write as follows:

"welcome_message" = "Welcome to my app!"; // This would be in your English file.
```

Then do the same thing for each language you want to support, but just change the phrase itself in each file, and keep the same key/identifier.
Then when you want to use that phrase in your app, replace whichever String with NSLocalizedString("welcome_message", comment: "")

No need to set Locale(identifier:String) in your files. The app will look for the device's set language and use the corresponding Localizable.strings file.

Title: Development Language IT on Xcode

Body:
You will want to go to File > New File > Strings File, name it Localizable.strings, this is important.
Open the attribute inspector. Click Localize..., select your language.

In your file, for each piece of text you want to show in your app, come up with an identifier/key for it, then write as follows:

"welcome_message" = "Welcome to my app!"; // This would be in your English file.

Then do the same thing for each language you want to support, but just change the phrase itself in each file, and keep the same key/identifier.
Then when you want to use that phrase in your app, replace whichever String with NSLocalizedString("welcome_message", comment: "")

No need to set Locale(identifier:String) in your files. The app will look for the device's set language and use the corresponding Localizable.strings file.


问:
build constraints exclude all Go files in
when import     "golang.org/x/net/route"

it tells
"build constraints exclude all Go files in go/src/golang.org/x/net/routego"

I am using VSCode editor on Windows/Linux

I searched online and didn't see a solution to the similar problem

```<code>package main

import (
    "golang.org/x/net/route"
)

{
    rib, _ := route.FetchRIB(0, route.RIBTypeRoute, 0)
    messages, err := route.ParseRIB(route.RIBTypeRoute, rib)
}
</code>```

答:
In my case I just by an accident replaced original code by test file, it was containing the following comments:</p>
```<code>//go:build unittest
// +build unittest
</code>```

Body:
when import     "golang.org/x/net/route"

it tells
"build constraints exclude all Go files in go/src/golang.org/x/net/routego"

I am using VSCode editor on Windows/Linux

I searched online and didn't see a solution to the similar problem

package main

import (
    "golang.org/x/net/route"
)

{
    rib, _ := route.FetchRIB(0, route.RIBTypeRoute, 0)
    messages, err := route.ParseRIB(route.RIBTypeRoute, rib)
}

Body:
In my case I just by an accident replaced original code by test file, it was containing the following comments:

//go:build unittest
// +build unittest


问:
What would be the best way to transmit data from one python script to another, without them being on the same computer?
I am attempting to create a basic chatroom in python, and I would like to know how I could transmit data from one script to another, preferably without using google drive. If needed to, I could create a webserver on Replit, but I don't do well with HTML or PHP.

Side note: I can't port forward, as my google wifi doesn't accept any level of port forwarding.

I would send messages of about 50 characters every couple seconds

答:
Since you mention port forwarding, I assume you want two chat clients that run on different local networks to talk to each other, for example your own and the chat client of a friend in a remote location, over the internet.

If you (or your counterpart) cannot set up port forwarding, then direct communication between the script on your computer and theirs is hard, if not impossible. The solution is to set up a third computer or service on the internet that can be reached by both clients and use it for relaying messages between them.

A network is typically protected by a firewall of sorts and will typically be behind a router that performs network address translation (NAT) to help multiple devices on a network to simultaneously access services on the internet, whilst all using the same IP address on the internet. Port forwarding fits into that by connecting a specific port from the outside directly to a port on a machine on the inside - without that, an outside computer might be able to reach your IP address, but they could never connect to a computer or program on the inside of the network, as the router wouldn't know what computer to contact, also the firewall might disallow the connection to begin with.

But if your computer on the inside establishes a connection with an accessible server on the internet, expecting a response, that creates a temporary conduit through the router and firewall that can be used by the server to send messages (look up 'hole punching' for more information). And if both computers do this, the server can relay message between both clients. Only the server then needs to run in an environment that doesn't have firewall restrictions or NAT that prevent this.

You could write a simple Python server, that accepts incoming connections and can send several responses and a simple client that connects to it, identifying itself and joining a chatroom, or having a direct conversation with another connected client. There are many techniques that would allow you to do this, but I think web sockets might be a good starting point, as long as you don't plan to do advanced fast or high volume stuff that would require something like a UDP connection.

A library like websockets could be a good starting point, but you may want to start out by figuring out where you would have this service hosted first, since there may be limitations on what you're able and allowed to do.

Also, if all you're looking to do is send simple messages, you may want to stay away from writing your own server an protocols at all - have a look around for open source message servers written in a language you are comfortable with, or that just work out of the box without any development, in which case the language doesn't even really matter, as long as you can connect to it and exchange messages from Python.


问:
Get values from ID HTML and save in array
I'm doing a view where once I click I'm displaying

For Loop

I am having a view that captures a QR code and displays it on the screen, what I want to do next is take these values by iterating the elements with a for loop and save it in an array, in this case my ID is id="scanned-result" and I want to iterate each  containing values and saving to an array.

I am doing this but for some reason it is not performing the operation correctly. I would like to know what I should correct?

```<code>      function SubmitCodes() {
             var QRCodeval= document.querySelectorAll('scanned-result');
             var arr = [];
             for (var i in QRCodeval) {
                 alert(QRCodeval[i]);
                 arr.push( QRCodeval[i]);
             }
             alert(arr.val);
         }
</code>```

VIEW

```<code>    <div class="container">
        <div class="row">
            <div class="col-md-12" style="text-align: center;margin-bottom: 20px;">
                <div id="reader" style="display: inline-block;"></div>
                <div class="empty"></div>

                <div id="scanned-result">
                   <div>[1] - https://www.investopedia.com/terms/q/quick-response-qr-code.asp</div>
                   <div>[2] - https://www.dropbox.com/s/705b6p4a2ydvayx/EN-Poster.pdf?dl=0</div></div>
            </div>

        </div>
    </div>
</code>```

答:
Since there is no <scanned-result></scanned-result> element on your page, as charlietfl pointed out, you won't get any results.

Since your HTML markup is the following:

```
<p>You are looking for an ID.</p>
<p>And the valid ID query in a CSS selector is a <code>#</code>, because of that you should query like:</p>
<pre class="lang-js prettyprint-override"><code>var QRCodeval = document.querySelectorAll('#scanned-result')
</code>```

Body:
I'm doing a view where once I click I'm displaying

For Loop

I am having a view that captures a QR code and displays it on the screen, what I want to do next is take these values by iterating the elements with a for loop and save it in an array, in this case my ID is id="scanned-result" and I want to iterate each  containing values and saving to an array.

I am doing this but for some reason it is not performing the operation correctly. I would like to know what I should correct?

      function SubmitCodes() {
             var QRCodeval= document.querySelectorAll('scanned-result');
             var arr = [];
             for (var i in QRCodeval) {
                 alert(QRCodeval[i]);
                 arr.push( QRCodeval[i]);
             }
             alert(arr.val);
         }

VIEW

[1] - https://www.investopedia.com/terms/q/quick-response-qr-code.asp

[2] - https://www.dropbox.com/s/705b6p4a2ydvayx/EN-Poster.pdf?dl=0

Body:
Since there is no <scanned-result></scanned-result> element on your page, as charlietfl pointed out, you won't get any results.

Since your HTML markup is the following:

<div id="scanned-result">
    <!-- … -->
</div>

You are looking for an ID.

And the valid ID query in a CSS selector is a #, because of that you should query like:

var QRCodeval = document.querySelectorAll('#scanned-result')


问:
Android: How to show a spinner while performing a long-running operation?
I have a ProgressBar in .xml that I want to show when a long-running operation. I use

```<code>ProgressBar progressSpinner = (ProgressBar)findViewById(R.id.progressSpinner);
progressSpinner.setVisibility(View.VISIBLE);
</code>```

to set its visibility in some onButtonClick method. If the above code is all that is in the method, it works just fine. The problem is when I have a method like this:

```<code>public void onButtonClick (android.view.View view){
    ProgressBar progressSpinner = (ProgressBar)findViewById(R.id.progressSpinner);
    progressSpinner.setVisibility(View.VISIBLE);

    longRunningMethod(); // This method takes 5-10 seconds to run

    progressSpinner.setVisibility(View.GONE);
}
</code>```

The UI just locks up until longRunningMethod is done. That method works just fine, but the spinner never shows.

I tried running everything on a different thread with this:

```<code>public void onButtonClick (android.view.View view){
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    executorService.submit(this::longRunningMethod);
}
</code>```

And I added the spinner visibility changing stuff to longRunningMethod:

```<code>private void longRunningMethod(){
    ProgressBar progressSpinner = (ProgressBar)findViewById(R.id.progressSpinner);
    progressSpinner.setVisibility(View.VISIBLE);

    // Logic that takes 5-10 seconds to run.

    progressSpinner.setVisibility(View.GONE);
}
</code>```

When I do this, the UI doesn't lock up, but nothing in longRunningMethod works. The spinner won't show and the logic also doesn't seem to work, although this may just be a problem with that logic not playing nice on not-the-UI-thread. I am very confused that the spinner visibility won't update from here though.

答:
first of all I recommend that get familiar with threads in android :

https://developer.android.com/guide/components/processes-and-threads

then , there is some lib to manage threads

AsyncTask , Couroutin , Rxjava  . . .

Body:
I have a ProgressBar in .xml that I want to show when a long-running operation. I use

ProgressBar progressSpinner = (ProgressBar)findViewById(R.id.progressSpinner);
progressSpinner.setVisibility(View.VISIBLE);

to set its visibility in some onButtonClick method. If the above code is all that is in the method, it works just fine. The problem is when I have a method like this:

public void onButtonClick (android.view.View view){
    ProgressBar progressSpinner = (ProgressBar)findViewById(R.id.progressSpinner);
    progressSpinner.setVisibility(View.VISIBLE);

    longRunningMethod(); // This method takes 5-10 seconds to run

    progressSpinner.setVisibility(View.GONE);
}

The UI just locks up until longRunningMethod is done. That method works just fine, but the spinner never shows.

I tried running everything on a different thread with this:

public void onButtonClick (android.view.View view){
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    executorService.submit(this::longRunningMethod);
}

And I added the spinner visibility changing stuff to longRunningMethod:

private void longRunningMethod(){
    ProgressBar progressSpinner = (ProgressBar)findViewById(R.id.progressSpinner);
    progressSpinner.setVisibility(View.VISIBLE);

    // Logic that takes 5-10 seconds to run.

    progressSpinner.setVisibility(View.GONE);
}

When I do this, the UI doesn't lock up, but nothing in longRunningMethod works. The spinner won't show and the logic also doesn't seem to work, although this may just be a problem with that logic not playing nice on not-the-UI-thread. I am very confused that the spinner visibility won't update from here though.


问:
Hibernate: How to fix "identifier of an instance altered from X to Y"?
```<code>org.hibernate.HibernateException: identifier of an instance
of org.cometd.hibernate.User altered from 12 to 3
</code>```

in fact, my user table is really must dynamically change its value, my Java app is multithreaded.
Any ideas how to fix it?

答:
I got the issue when i tried fetching an existing DB entity, modified few fields and executed

```<code>session.save(entity)
</code>```

instead of

```<code>session.merge(entity)
</code>```

Since it is existing in the DB, when we should merge() instead of save()

ContentLicense: CC BY-SA 2.5

Body:
org.hibernate.HibernateException: identifier of an instance
of org.cometd.hibernate.User altered from 12 to 3

in fact, my user table is really must dynamically change its value, my Java app is multithreaded.
Any ideas how to fix it?

Body:
I got the issue when i tried fetching an existing DB entity, modified few fields and executed

session.save(entity)

instead of

session.merge(entity)

Since it is existing in the DB, when we should merge() instead of save()


问:
Pandas dataframe group by 10 min intervals with different actions on other columns
I have a pandas dataframe which includes a timestamp and 71 other columns, something like this:

```<code>              timestamp           |close_price|highest_price|volume| ...
              2018-09-29 00:00:20 |1809       |1811         |  ... |
              2018-09-29 00:00:34 |1823       |1832         |
              2018-09-29 00:00:59 |1832       |1863         |
              2018-09-29 00:01:09 |1800       |1802         |
              2018-09-29 00:01:28 |1832       |1845         |
              .
              .
              .
</code>```

I want to put the data into 10 min intervals and I want to do separate operations on each column, for example I want the 10 min intervals of close_price column to show the last value of the corresponding range in the real table, or for the highest_price column, I want the max value of the corresponding range, or for volume I want the mean of the values in that range. I already tried

```<code>dataTable = datefram.resample("10min").agg({'first_price':'first',
                                       'close_price':'last',
                                       'highest_price': 'max',
                                       'volume':'mean',
                                        #other attributes...
                                        })
</code>```

but the result seems to be incorrect.
Is there any other ways to do what I want to do?
I will appreciate any comments or thoughts.

Note that there is no specific pattern in timestamp values. In 1 minute, we can have 0 to 60 rows.

答: If your data spans multiple days or periods where you don't have any data points, calling resample() can result in lots of additional rows with NaN values. I think your code is actually correct, you just got the wrong impression from seeing all the extra rows.

Body:
I have a pandas dataframe which includes a timestamp and 71 other columns, something like this:

              timestamp           |close_price|highest_price|volume| ...
              2018-09-29 00:00:20 |1809       |1811         |  ... |
              2018-09-29 00:00:34 |1823       |1832         |
              2018-09-29 00:00:59 |1832       |1863         |
              2018-09-29 00:01:09 |1800       |1802         |
              2018-09-29 00:01:28 |1832       |1845         |
              .
              .
              .

I want to put the data into 10 min intervals and I want to do separate operations on each column, for example I want the 10 min intervals of close_price column to show the last value of the corresponding range in the real table, or for the highest_price column, I want the max value of the corresponding range, or for volume I want the mean of the values in that range. I already tried

dataTable = datefram.resample("10min").agg({'first_price':'first',
                                       'close_price':'last',
                                       'highest_price': 'max',
                                       'volume':'mean',
                                        #other attributes...
                                        })

but the result seems to be incorrect.
Is there any other ways to do what I want to do?
I will appreciate any comments or thoughts.

Note that there is no specific pattern in timestamp values. In 1 minute, we can have 0 to 60 rows.


问:
ImageMagick: Combine two images into R/G channels and create a white B channel
I have a set of normal maps that were separated into their red and green channels for upscaling. Now I want to recombine them with an solid white blue channel, but I'm struggling to find an efficient way to make that white blue channel.

My current code does actually work:

magick "file_r.png"  "file_g.png" ( -size 2048x2048 xc:white ) -combine "file.png"

But having to create that image for the blue channel doesn't seem ideal. Is there a better way?

(Also the size isn't static, so it would have to be retrieved each time -- entirely doable since it's being run by a powershell script and I can at the very least run an identify command (magick identify -ping -format "%[w]x%[h]" "file_r.png", which I fear may be legacy code but can't work out how to convert it to v7) beforehand to generate the dimensions, but it seems like more overhead. (I also tried putting an identify command after -size to put the dimensions in the command dynamically, but I couldn't get the syntax right. It also doesn't necessarily solve the efficiency issue, but if there's a way to do it I would love to know!))

This thread on the legacy ImageMagick forums seemed like a better solution: it says that any channels undefined by -channel would become the -background colour, which seems to me like it would be more efficient since it wouldn't have to create an image (I could be wrong, it could be doing the exact same thing internally). This is their code:

convert r.jpg g.jpg -background black -channel RG -combine combined.jpg

But when I tried, the red and green channels were perfect but the blue channel had the red file's image as well rather than pure white:

magick "file_r.png" "file_g.png" -background white -channel RG -combine "file.png"

Has this behaviour changed in version 7, or (more likely) am I doing it wrong? The input files are sRGB rather than grey since that's what the upscaler outputs; perhaps the blue channel of the red channel's image (which is identical to its other channels since it was originally grey) is being put there instead? I've played around with that command by trying to specify individual channels of the two images for the inputs but I couldn't get it to work (which may be my syntax; I'm new to ImageMagick and I've been struggling with its commands even with the documentation).

Thank you!

答:
Perhaps this is what you want in ImageMagick.</p>
```<code>magick r.png g.png g.png -combine -channel b -evaluate set 100% +channel result.png
</code>```

Body:
Perhaps this is what you want in ImageMagick.

magick r.png g.png g.png -combine -channel b -evaluate set 100% +channel result.png