问:
How can I enable Flutter/Dart language experiments?
I want to use the new spread syntax in Dart.

I'm using Android Studio for Flutter development and I receive this error.

This requires the --spread-collections experiment to be enabled

```<code>ListView(children: [...listTiles, MyWidget()])
</code>```

However, I didn't find anywhere where I could specify this option.

I couldn't even make it work on the command line. flutter --spread-collections run gives Could not find an option named "spread-collections"..

```<code>flutter --version
Flutter 1.3.8 • channel beta • https://github.com/flutter/flutter.git
Framework • revision e5b1ed7a7f (4 weeks ago) • 2019-03-06 14:23:37 -0800
Engine • revision f4951df193
Tools • Dart 2.2.1 (build 2.2.1-dev.0.0 571ea80e11)
</code>```

答:
With the new version of flutter it became an error - but it can easily be fixed by updating the sdk version:

```<code>environment:
  sdk: ">=2.7.0 <3.0.0"
</code>```

Just don't forget to restart VisualStudio Code or whatever IDE you're using.

Body:
I want to use the new spread syntax in Dart.

I'm using Android Studio for Flutter development and I receive this error.

This requires the --spread-collections experiment to be enabled

ListView(children: [...listTiles, MyWidget()])

However, I didn't find anywhere where I could specify this option.

I couldn't even make it work on the command line. flutter --spread-collections run gives Could not find an option named "spread-collections"..

flutter --version
Flutter 1.3.8 • channel beta • https://github.com/flutter/flutter.git
Framework • revision e5b1ed7a7f (4 weeks ago) • 2019-03-06 14:23:37 -0800
Engine • revision f4951df193
Tools • Dart 2.2.1 (build 2.2.1-dev.0.0 571ea80e11)

Body:
With the new version of flutter it became an error - but it can easily be fixed by updating the sdk version:

environment:
  sdk: ">=2.7.0 <3.0.0"

Just don't forget to restart VisualStudio Code or whatever IDE you're using.


来源: stackexchange

问:
Flutter Buttons which updates the body
Hello how can I make 2 buttons which will update the body content like tabs. When you click on 1st button it will be shown as selected and the content will change (appBar title, body, slider etc.). When you click to another one It will be shown as selected and will change the content again. But the buttons will appear in both contents. like in this example below

There are look like tabs but the difference is they are changing state and updating the page

答:
Simplest way is to create a global variable which holds the value of the button selected.

Put it out of the main() method.

You can access it from every class and file in your project.

Other ways would require a Provider and state management architecture.

Working sample:

```<code>import 'package:flutter/material.dart';

int selectedButton = 0;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Page1(),
    );
  }
}

class Page1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
            body: Column(children: <Widget>[
          Text('Page1'),
          MyWidget(selectedButton),
        ])));
  }
}

class Page2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
            body: Column(children: <Widget>[
          Text('Page2'),
          MyWidget(selectedButton),
        ])));
  }
}

class MyWidget extends StatelessWidget {
  final int selected;

  MyWidget(this.selected);

  @override
  Widget build(BuildContext context) {
    return Row(children: <Widget>[
      RawMaterialButton(
          child: Text("Go to page1"),
          fillColor: selected == 0 ? Colors.red : Colors.grey,
          onPressed: () {
            selectedButton = 0;
            Navigator.push(
                context, MaterialPageRoute(builder: (context) => Page1()));
          }),
      RawMaterialButton(
          child: Text("Go to page2"),
          fillColor: selected == 1 ? Colors.red : Colors.grey,
          onPressed: () {
            selectedButton = 1;
            Navigator.push(
                context, MaterialPageRoute(builder: (context) => Page2()));
          })
    ]);
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Flutter Buttons which updates the body

Body:
Simplest way is to create a global variable which holds the value of the button selected.

Put it out of the main() method.

You can access it from every class and file in your project.

Other ways would require a Provider and state management architecture.

Working sample:

import 'package:flutter/material.dart';

int selectedButton = 0;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Page1(),
    );
  }
}

class Page1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
            body: Column(children: <Widget>[
          Text('Page1'),
          MyWidget(selectedButton),
        ])));
  }
}

class Page2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
            body: Column(children: <Widget>[
          Text('Page2'),
          MyWidget(selectedButton),
        ])));
  }
}

class MyWidget extends StatelessWidget {
  final int selected;

  MyWidget(this.selected);

  @override
  Widget build(BuildContext context) {
    return Row(children: <Widget>[
      RawMaterialButton(
          child: Text("Go to page1"),
          fillColor: selected == 0 ? Colors.red : Colors.grey,
          onPressed: () {
            selectedButton = 0;
            Navigator.push(
                context, MaterialPageRoute(builder: (context) => Page1()));
          }),
      RawMaterialButton(
          child: Text("Go to page2"),
          fillColor: selected == 1 ? Colors.red : Colors.grey,
          onPressed: () {
            selectedButton = 1;
            Navigator.push(
                context, MaterialPageRoute(builder: (context) => Page2()));
          })
    ]);
  }
}


问:
SSL Enabling Problem: Tomcat in Windows 7
I downloaded Tomcat 7.08 Windows Service Installer and installed it.
I edited the server.xml to enable https connector port @ 8443

I already created the certificate and key pair using the keytool.

keytool -genkey -alias techtracer -keypass ttadmin -keystore techtracer.bin -storepass ttadmin

i started the server then, and tried https://localhost:8443/ but it was not showing anything. Firefox had shown "connected to localhost..." and nothing more.
I cant load any pages in https.

My System: Windows 7 64-bits / 4GB RAM /JDK_JRE 6/ Tomcat 7.08/ Firefox 3.6

Can Any one tell me what is the problem with the SSL in my system.?.Any way to fix this?
Thanks

Mr.k

答: Same system, same configuration, same problem but with Tomcat 6. My solution was to switch to 32bit version of Tomcat. I think this is an issue related to 64bit distributions.</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Create table with values from one column and another column without intersection
I have a table like so:

```<code>userid | clothesid
-------|-----------
  1    |   1
  1    |   3
  2    |   1
  2    |   4
  2    |   5
</code>```

What I want from this table is a table like so:

```<code>userid | clothesid
-------|-----------
  1    |   4
  1    |   5
  2    |   3
</code>```

How can I do this?

I've tried it with one entry as:

```<code>select distinct r.clothesid from table r where r.clothes not in (select r1.clothes from table r1 where r1.userid=1);
</code>```

and this returns 4,5, but I'm not sure where to proceed from here

答:
I think you want:

```<code>select (case when t1.clothesid is not null then 2 else 1 end),
       coalesce(t1.clothesid, t2.clothesid)
from (select t.*
      from t
      where t.userid = 1
     ) t1 full join
     (select t.*
      from t
      where t.userid = 2
     ) t2
     on t1.clothesid = t2.clothesid
where t1.clothesid is null or t2.clothesid is null;
</code>```

Actually, I think I have a simpler solution:

```<code>select (case when min(t.userid) = 1 then 2 else 1 end), clothesid
from t
group by clothesid
having count(*) = 1;
</code>```

Here is a db<>fiddle.

Body:
I have a table like so:

userid | clothesid
-------|-----------
  1    |   1
  1    |   3
  2    |   1
  2    |   4
  2    |   5

What I want from this table is a table like so:

userid | clothesid
-------|-----------
  1    |   4
  1    |   5
  2    |   3

How can I do this?

I've tried it with one entry as:

select distinct r.clothesid from table r where r.clothes not in (select r1.clothes from table r1 where r1.userid=1);

and this returns 4,5, but I'm not sure where to proceed from here

Body:
I think you want:

select (case when t1.clothesid is not null then 2 else 1 end),
       coalesce(t1.clothesid, t2.clothesid)
from (select t.*
      from t
      where t.userid = 1
     ) t1 full join
     (select t.*
      from t
      where t.userid = 2
     ) t2
     on t1.clothesid = t2.clothesid
where t1.clothesid is null or t2.clothesid is null;

Actually, I think I have a simpler solution:

select (case when min(t.userid) = 1 then 2 else 1 end), clothesid
from t
group by clothesid
having count(*) = 1;

Here is a db<>fiddle.


问:
How can I return a specific element out of an array in Javascript?
Im trying to implement a Network discovery search which returns all devices that are linked with my local network.
My code so far looks like this:

```<code>const find = require('local-devices');

// Find all local network devices.
find().then(devices => {
  console.log(devices);
})
</code>```

And the returned array in the console looks like this:

```<code>[
  { name: '?', ip: '192.168.0.174', mac: '00:17:88:65:f4:4d' },
  { name: '?', ip: '192.168.0.222', mac: '80:be:05:73:bc:g5' },
  { name: '?', ip: '192.168.0.190', mac: '0c:fe:45:4d:b8:28' }
]
</code>```

So, I know the Mac Adress of the device im looking for already, my problem is, how can I search for the mac adress in the Array, and return the specific ip Adress of this device?
For example, I pass the mac adress "00:17:88:65:f4:4d" into a function, and the function should return "192.168.0.174" which I can save in a variable and work with in the following code.

I might be able to solve this with the find() function, but how can I tell the code, that I only want the ip adress, and not the full element of the array saved?
I thought about something like:

```<code>const ip = devices.find('00:17:88:65:f4:4d');
</code>```

But this would only return the full element, if the syntax was correct.

Body:
Im trying to implement a Network discovery search which returns all devices that are linked with my local network.
My code so far looks like this:

const find = require('local-devices');

// Find all local network devices.
find().then(devices => {
  console.log(devices);
})

And the returned array in the console looks like this:

[
  { name: '?', ip: '192.168.0.174', mac: '00:17:88:65:f4:4d' },
  { name: '?', ip: '192.168.0.222', mac: '80:be:05:73:bc:g5' },
  { name: '?', ip: '192.168.0.190', mac: '0c:fe:45:4d:b8:28' }
]

So, I know the Mac Adress of the device im looking for already, my problem is, how can I search for the mac adress in the Array, and return the specific ip Adress of this device?
For example, I pass the mac adress "00:17:88:65:f4:4d" into a function, and the function should return "192.168.0.174" which I can save in a variable and work with in the following code.

I might be able to solve this with the find() function, but how can I tell the code, that I only want the ip adress, and not the full element of the array saved?
I thought about something like:

const ip = devices.find('00:17:88:65:f4:4d');

But this would only return the full element, if the syntax was correct.

Body:
var devices = [
  { name: '?', ip: '192.168.0.174', mac: '00:17:88:65:f4:4d' },
  { name: '?', ip: '192.168.0.222', mac: '80:be:05:73:bc:g5' },
  { name: '?', ip: '192.168.0.190', mac: '0c:fe:45:4d:b8:28' }
];

const getIpFromMacAddress = macAddress => {
  for (let i = 0; i < devices.length; i++) {
    if (devices[i].mac === macAddress){
      return devices[i].ip
    }
  }
  return 'device not found'
}

getIpFromMacAddress('00:17:88:65:f4:4d') // "192.168.0.174"


问:
OpenSSL Error messages: error:14095126 unexpected eof while reading
Description

This error:

```<code>file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages: error:14095126:SSL routines:ssl3_read_n:unexpected eof while reading
</code>```

returns when:

```<code>$file = file_get_contents($url['url'], false, stream_context_create($arrContextOptions));
</code>```

Steps to Reproduce

Video to download:

https://www.youtube.com/watch?v=r5NzAksjfDI

Extract the video id:

```<code>$video_id = $yt->extractVideoId(implode($url));
</code>```

Get the downloadable url

```<code>$links = $yt->getDownloadLinks($video_id, $selector = 'video');
</code>```

Get the array key for the specified video quality etc.

```<code>$arrayindex = array_search('mp4, video, 1080p, audio', array_column($links, 'format'));
</code>```

Set $url to array

```<code>$url = $links[$arrayindex];
</code>```

Disable SSL

```<code>$arrContextOptions=array( "ssl"=>array( "verify_peer"=>false, "verify_peer_name"=>false, ), );
</code>```

Get the file from the url

```<code>$video = file_get_contents($url['url'], false, stream_context_create($arrContextOptions));
</code>```

Send the video back to front end

```<code>return view('convert', [ 'url' => $url['url'], 'quality' => $url['format'], ]);
</code>```

Expected behavior:

The video gets downloaded

Actual behavior:

I get this error:

```<code>file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages: error:14095126:SSL routines:ssl3_read_n:unexpected eof while reading
</code>```

The code stops.

Version

The latest version of:

https://github.com/Athlon1600/youtube-downloader/blob/master/src/YouTubeDownloader.php

Additional Information

This code is in the laravel framework, the code here is in the UrlController. This is a local development server, this error also shows up when the firewall is disabled. All the functions used in my code are in the YouTubeDownloader.php file

答:
I had a similar problem.I suspect you are using Xampp-Windows-7.4.5.In that case file_get_contents() function gives the SSL error on laravel.It works on simple(core) php on my side though.

Things You Can Try.

Use Curl instead of file_get_contents().You can create a custom function that would work in the same manner(with SSL enabled) like so.

```<code>function file_get_content_curl ($url)
{
    // Throw Error if the curl function does'nt exist.
    if (!function_exists('curl_init'))
    {
        die('CURL is not installed!');
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $Url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}
</code>```

Then you can call the function like this.

```<code>$data = file_get_content_curl($url);
$save = file_put_contents($path, $data);
</code>```

Disable/Uninstall Skpye.As skpye uses port 80/443(https) ,if you are using apache on port 80 try switching to port 8080 or uninstalling skpye if you dont use it.That might also solve your issue.

Downgrade to Xampp-Windows-7.2.3 if you want to use file_get_contents() function.This also solved the issue for me.

Body:
Description

This error:

file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages: error:14095126:SSL routines:ssl3_read_n:unexpected eof while reading

returns when:

$file = file_get_contents($url['url'], false, stream_context_create($arrContextOptions));

Steps to Reproduce

Video to download:

https://www.youtube.com/watch?v=r5NzAksjfDI

Extract the video id:

$video_id = $yt->extractVideoId(implode($url));

Get the downloadable url

$links = $yt->getDownloadLinks($video_id, $selector = 'video');

Get the array key for the specified video quality etc.

$arrayindex = array_search('mp4, video, 1080p, audio', array_column($links, 'format'));

Set $url to array

$url = $links[$arrayindex];

Disable SSL

$arrContextOptions=array( "ssl"=>array( "verify_peer"=>false, "verify_peer_name"=>false, ), );

Get the file from the url

$video = file_get_contents($url['url'], false, stream_context_create($arrContextOptions));

Send the video back to front end

return view('convert', [ 'url' => $url['url'], 'quality' => $url['format'], ]);

Expected behavior:

The video gets downloaded

Actual behavior:

I get this error:

file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages: error:14095126:SSL routines:ssl3_read_n:unexpected eof while reading

The code stops.

Version

The latest version of:

https://github.com/Athlon1600/youtube-downloader/blob/master/src/YouTubeDownloader.php

Additional Information

This code is in the laravel framework, the code here is in the UrlController. This is a local development server, this error also shows up when the firewall is disabled. All the functions used in my code are in the YouTubeDownloader.php file

Body:
I had a similar problem.I suspect you are using Xampp-Windows-7.4.5.In that case file_get_contents() function gives the SSL error on laravel.It works on simple(core) php on my side though.

Things You Can Try.

Use Curl instead of file_get_contents().You can create a custom function that would work in the same manner(with SSL enabled) like so.

function file_get_content_curl ($url)
{
    // Throw Error if the curl function does'nt exist.
    if (!function_exists('curl_init'))
    {
        die('CURL is not installed!');
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $Url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

Then you can call the function like this.

$data = file_get_content_curl($url);
$save = file_put_contents($path, $data);

Disable/Uninstall Skpye.As skpye uses port 80/443(https) ,if you are using apache on port 80 try switching to port 8080 or uninstalling skpye if you dont use it.That might also solve your issue.

Downgrade to Xampp-Windows-7.2.3 if you want to use file_get_contents() function.This also solved the issue for me.


问:
Pipeline creation on AWS with GitHub repository
When we create a pipeline on AWS we can provide a Github repo, let's say the repo name is: "RepoName/exampleProject" and in this repo, we have many folders. So can we provide a subfolder from this repo like "RepoName/exampleProject/subFolder" to repo section in add source stage in AWS?

Since we could have two Folders in this repo like Laravel for the backend and a separate project Vue Js for the frontend.

答:
No. Not for GitHub or AWS CodeCommit. Basically, its a no for any git provider.
What your are providing here is a / and the you provide branch.

These details are required to git clone the source code which will be transition to next stage. When you do a git clone, you clone the entire repository and not any specific folder.

If your source files are on S3, it will be a different case. S3 is not a git based version control. You can download specific folder from S3.


问:
Laravel and scopes hate me - Sorry - I don't know how else to phase it
So we have all been there - you are doing something simple that is giving you very odd results and you try everything to understand the issue but you can only conclude that the code hates you! (You know you are overlooking something)

That is me right now...

I have a game with many user and users have to be approved to be actually playing so I have created a playing scope on the User object so I can write statements like:

```<code>$game->players()->playing()->count();
</code>```

This returns a count of the players who are actually approved to play.

The scope is:

```<code>public function scopePlaying($query){
    return $query->where('status', Self::APPROVED)
                    ->orderBy('position', 'asc');
}
</code>```

This scope works well, however being approved is not the only condition so I extended the scope to include this other condition:

```<code>public function scopePlaying($query){
    return $query->where('status', Self::APPROVED)
                    ->where('action', '<>', Self::ACTION_FOLD)
                    ->orderBy('position', 'asc');
}
</code>```

And suddenly the scope returns nothing. Ever. If I change the name of the "action" column to something that does not exist on the table instead of it throwing an error it starts working as it did before adding the new where clause.

Is my computer possessed and is just doing this to make me give up programming forever? What am I missing?

Output from the query log:

```<code>[2020-06-02 12:29:04] testing.DEBUG: array (
  0 =>
   array (
     'query' => 'select count(*) as aggregate from "users" where "users"."game_id" = ? and "users"."game_id" is not null and "status" = ? and "action" <> ?',
'bindings' =>
array (
  0 => 'c1f666c7-dc6c-47c1-9abc-8decba505ac5',
  1 => 'approved',
  2 => 'fold',
),
'time' => 0.13,
</code>```

),
)

My Migration for the table:

```<code>Schema::create('users', function (Blueprint $table) {
        $table->uuid('id')->primary();
        $table->string('game_id');
        $table->string('name');
        $table->string('status', 10)->default('online');
        $table->string('action', 10)->nullable();
        $table->smallInteger('position')->nullable();
        $table->timestamps();
    });
</code>```

答:
The issue appears to be the fact that my "action" property had the default values of NULL in the database.

```<code>Schema::create('users', function (Blueprint $table) {
    $table->uuid('id')->primary();
    $table->string('game_id');
    $table->string('name');
    $table->string('status', 10)->default('online');
    $table->string('action', 10)->nullable();
    $table->smallInteger('position')->nullable();
    $table->timestamps();
});
</code>```

I changed this to have some value and it started working as expected.

It must be the handling of NULL with comparisons and I should have included

```<code>where action is null OR action <> "fold"
</code>```

I kept the null default and updated the scope.

```<code>public function scopePlaying($query){
    return $query->where('status', Self::APPROVED)
                    ->whereNull('action')
                    ->orWhere('action', '<>', Self::ACTION_FOLD)
                    ->orderBy('position', 'asc');
}
</code>```

It's pretty scary because I have been using MySQL for nearly 20 years and I can't remember encountering this before.

Or maybe I have and I am so old I have forgotten....

Body:
So we have all been there - you are doing something simple that is giving you very odd results and you try everything to understand the issue but you can only conclude that the code hates you! (You know you are overlooking something)

That is me right now...

I have a game with many user and users have to be approved to be actually playing so I have created a playing scope on the User object so I can write statements like:

$game->players()->playing()->count();

This returns a count of the players who are actually approved to play.

The scope is:

public function scopePlaying($query){
    return $query->where('status', Self::APPROVED)
                    ->orderBy('position', 'asc');
}

This scope works well, however being approved is not the only condition so I extended the scope to include this other condition:

public function scopePlaying($query){
    return $query->where('status', Self::APPROVED)
                    ->where('action', '<>', Self::ACTION_FOLD)
                    ->orderBy('position', 'asc');
}

And suddenly the scope returns nothing. Ever. If I change the name of the "action" column to something that does not exist on the table instead of it throwing an error it starts working as it did before adding the new where clause.

Is my computer possessed and is just doing this to make me give up programming forever? What am I missing?

Output from the query log:

[2020-06-02 12:29:04] testing.DEBUG: array (
  0 =>
   array (
     'query' => 'select count(*) as aggregate from "users" where "users"."game_id" = ? and "users"."game_id" is not null and "status" = ? and "action" <> ?',
'bindings' =>
array (
  0 => 'c1f666c7-dc6c-47c1-9abc-8decba505ac5',
  1 => 'approved',
  2 => 'fold',
),
'time' => 0.13,

),
)

My Migration for the table:

Schema::create('users', function (Blueprint $table) {
        $table->uuid('id')->primary();
        $table->string('game_id');
        $table->string('name');
        $table->string('status', 10)->default('online');
        $table->string('action', 10)->nullable();
        $table->smallInteger('position')->nullable();
        $table->timestamps();
    });

Body:
The issue appears to be the fact that my "action" property had the default values of NULL in the database.

Schema::create('users', function (Blueprint $table) {
    $table->uuid('id')->primary();
    $table->string('game_id');
    $table->string('name');
    $table->string('status', 10)->default('online');
    $table->string('action', 10)->nullable();
    $table->smallInteger('position')->nullable();
    $table->timestamps();
});

I changed this to have some value and it started working as expected.

It must be the handling of NULL with comparisons and I should have included

where action is null OR action <> "fold"

I kept the null default and updated the scope.

public function scopePlaying($query){
    return $query->where('status', Self::APPROVED)
                    ->whereNull('action')
                    ->orWhere('action', '<>', Self::ACTION_FOLD)
                    ->orderBy('position', 'asc');
}

It's pretty scary because I have been using MySQL for nearly 20 years and I can't remember encountering this before.

Or maybe I have and I am so old I have forgotten....


答:
Left join all the combinations of userid and clothesid to the table and return only the unmatched rows:

```<code>select t1.userid, t2.clothesid
from (select distinct userid from tablename) t1
cross join (select distinct clothesid from tablename) t2
left join tablename t on t.userid = t1.userid and t.clothesid = t2.clothesid
where t.userid is null
</code>```

Or with the operator EXCEPT:

```<code>select t1.userid, t2.clothesid
from (select distinct userid from tablename) t1
cross join (select distinct clothesid from tablename) t2
except
select userid, clothesid
from tablename
</code>```

See the demo.

Results:

```<code>> userid | clothesid
> -----: | --------:
>      1 |         4
>      1 |         5
>      2 |         3
</code>```

Title: Create table with values from one column and another column without intersection

Body:
Left join all the combinations of userid and clothesid to the table and return only the unmatched rows:

select t1.userid, t2.clothesid
from (select distinct userid from tablename) t1
cross join (select distinct clothesid from tablename) t2
left join tablename t on t.userid = t1.userid and t.clothesid = t2.clothesid
where t.userid is null

Or with the operator EXCEPT:

select t1.userid, t2.clothesid
from (select distinct userid from tablename) t1
cross join (select distinct clothesid from tablename) t2
except
select userid, clothesid
from tablename

See the demo.

Results:

> userid | clothesid
> -----: | --------:
>      1 |         4
>      1 |         5
>      2 |         3


问:
difference between ftp -iv internet and ftp -ivn $server commands
I am having the below shell script which tries to connect to the ftp server and puts a jar file in that ftp server from the linux application server

```<code>#ftp -iv internet << ! >> /home/abc.log
ftp -ivn $server << ! >>   /home/abc.log
user $2 p
binary
quit
</code>```

I want to know what is the difference between ftp -iv internet and ftp -ivn $server?

答:
The -n switch of ftp is for:

Restrains ftp from attempting ''auto-login'' upon initial connection.

Without -n, ftp would prompt for username and password.

With -n this does not happen. Instead, your script explicitly logs in using the user command.

Body:
I am having the below shell script which tries to connect to the ftp server and puts a jar file in that ftp server from the linux application server

#ftp -iv internet << ! >> /home/abc.log
ftp -ivn $server << ! >>   /home/abc.log
user $2 p
binary
quit

I want to know what is the difference between ftp -iv internet and ftp -ivn $server?


问:
How to know port number in jenkins?
I downloaded the Jenkins.war file and ran the command java -jar jenkins.war in my war file directory. It started Jenkins on the default port 8080 but now I want to change the Jenkins default port as I am running tomcat on port 8080. I did not found any Jenkins.xml file in my C:/User/Username/.jenkins folder. How to change the default port for Jenkins in this case?</p>

答:
If you need to run Jenkins on another port, just use the following syntax: java -jar jenkins.war -httpPort=<port-number>

For example, java -jar jenkins.war -httpPort=9090

I would suggest you run Jenkins as a service instead of running it using command line. This will ensure Jenkins keeps running when you restart your system.

Note: Regarding missing jenkins.xml file, i too don't have it in my installation dir. However, if you install Jenkins as a service using the steps provided here, it will then generate the jenkins.xml file. FYI, i am using Jenkins version 2.222.4

Title: How to know port number in jenkins?


问:
Empty flutter project after creation with Android studio
I am experiencing a problem with flutter creation using Android Studio.

I have flutter SDK in place:

```<code>Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, v1.12.13+hotfix.8, on Microsoft Windows [Version 10.0.18363.592], locale en-NZ)
[!] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
    X Android license status unknown.
      Try re-installing or updating your Android SDK Manager.
      See https://developer.android.com/studio/#downloads or visit https://flutter.dev/setup/#android-setup for detailed
      instructions.
[√] Android Studio (version 3.6)
[!] VS Code, 64-bit edition (version 1.36.0)
    X Flutter extension not installed; install from
      https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter
[!] Connected device
    ! No devices available
</code>```

Nevertheless, Android studio does nothing after creation. So I manually open the project and it is empty.

The project structure shows NO SDK.

Don't know how to fix this. Please help!

答:
I had the same issue.

As it turned out my Dart SDK settings got erased.

What should help:

Go to Settings -> Language & Frameworks -> Dart;

Enter your path to Dart SDK. It is located at %your_flutter_sdk%/bin/cache/dart-sdk. Make sure that proper version is displayed under this path;

Enable Dart support for this project by checking it;

Save changes and restart Android Studio.

Body:
I am experiencing a problem with flutter creation using Android Studio.

I have flutter SDK in place:

Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, v1.12.13+hotfix.8, on Microsoft Windows [Version 10.0.18363.592], locale en-NZ)
[!] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
    X Android license status unknown.
      Try re-installing or updating your Android SDK Manager.
      See https://developer.android.com/studio/#downloads or visit https://flutter.dev/setup/#android-setup for detailed
      instructions.
[√] Android Studio (version 3.6)
[!] VS Code, 64-bit edition (version 1.36.0)
    X Flutter extension not installed; install from
      https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter
[!] Connected device
    ! No devices available

Nevertheless, Android studio does nothing after creation. So I manually open the project and it is empty.

The project structure shows NO SDK.

Don't know how to fix this. Please help!


问:
dumb-init npm install: No such file or directory when running in docker-compose
dockerfile

    FROM node:${NODE_VERSION}-buster-slim

    ENTRYPOINT ["/usr/bin/dumb-init", "--"]

    RUN apt-get update && \
        apt-get install -qqy --no-install-recommends \
        ca-certificates \
        dumb-init \
        build-essential && \
        rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

    ENV HOME=/home/node
    WORKDIR $HOME/app

    COPY --chown=node:node . .

    RUN set -xe && \
        chown -R node /usr/local/lib /usr/local/include /usr/local/share /usr/local/bin && \
        npm install && npm cache clean --force

    EXPOSE 4200

    CMD ["node"]
```

<p><strong>docker-compose</strong></p>

<pre class="lang-sh prettyprint-override"><code>    webapp            :
    container_name    : webapp
    hostname          : webapp
    build             :
      dockerfile      : Dockerfile
      context         : ${PWD}/app
    image             : webapp:development
    command           :
                      - npm install
                      - npm run start
    volumes           :
                      - ${PWD}/webapp:/app
    networks          :
                      - backend
    ports             :
                      - 4200:4200
    restart           : on-failure
    tty               : true
    stdin_open        : true
    env_file          :
                      - variables.env
</code>```

I can run the image with
     docker run webapp bash -c "npm install; npm run start"
but when I run the compose file it says
     webapp  | [dumb-init] npm install: No such file or directory

I tried to replace the docker-compose command to prefix "node" but the same error but with node npm install: no such file or directory

Can someone tell me where things are going wrong ?

答:
When you use the list form of command: in the docker-compose.yml file (or the JSON-array form of Dockerfile CMD) you are providing a list of words in a single command, not a list of separate commands.  Once this gets combined with the ENTRYPOINT in the Dockerfile, the container command is

/usr/bin/dumb-init -- 'npm install' 'npm run start'
```

<p>and when there isn't a <code>/usr/bin/npm\ install</code> file (including the space in the file name) you get that error.</p>

<p>Since you <code>COPY</code> the application code in the Dockerfile and run <code>npm install</code> there, you don't need to repeat this step at application start time.  You should be able to delete the <code>volumes:</code> and <code>command:</code> part of the <code>docker-compose.yml</code> file to use what's built in to the image.</p>

<p>If you really need to repeat this <code>command:</code>, do it in exactly the form you specified in the <code>docker run</code> command, without list syntax</p>

<pre class="lang-yaml prettyprint-override"><code>command: bash -c 'npm install; npm run start'
</code>```

Body:
dockerfile

    FROM node:${NODE_VERSION}-buster-slim

    ENTRYPOINT ["/usr/bin/dumb-init", "--"]

    RUN apt-get update && \
        apt-get install -qqy --no-install-recommends \
        ca-certificates \
        dumb-init \
        build-essential && \
        rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

    ENV HOME=/home/node
    WORKDIR $HOME/app

    COPY --chown=node:node . .

    RUN set -xe && \
        chown -R node /usr/local/lib /usr/local/include /usr/local/share /usr/local/bin && \
        npm install && npm cache clean --force

    EXPOSE 4200

    CMD ["node"]

docker-compose

    webapp            :
    container_name    : webapp
    hostname          : webapp
    build             :
      dockerfile      : Dockerfile
      context         : ${PWD}/app
    image             : webapp:development
    command           :
                      - npm install
                      - npm run start
    volumes           :
                      - ${PWD}/webapp:/app
    networks          :
                      - backend
    ports             :
                      - 4200:4200
    restart           : on-failure
    tty               : true
    stdin_open        : true
    env_file          :
                      - variables.env

I can run the image with
     docker run webapp bash -c "npm install; npm run start"
but when I run the compose file it says
     webapp  | [dumb-init] npm install: No such file or directory

I tried to replace the docker-compose command to prefix "node" but the same error but with node npm install: no such file or directory

Can someone tell me where things are going wrong ?

Body:
When you use the list form of command: in the docker-compose.yml file (or the JSON-array form of Dockerfile CMD) you are providing a list of words in a single command, not a list of separate commands.  Once this gets combined with the ENTRYPOINT in the Dockerfile, the container command is

/usr/bin/dumb-init -- 'npm install' 'npm run start'

and when there isn't a /usr/bin/npm\ install file (including the space in the file name) you get that error.

Since you COPY the application code in the Dockerfile and run npm install there, you don't need to repeat this step at application start time.  You should be able to delete the volumes: and command: part of the docker-compose.yml file to use what's built in to the image.

If you really need to repeat this command:, do it in exactly the form you specified in the docker run command, without list syntax

command: bash -c 'npm install; npm run start'


问:
How to loop over an ArrayList using the index value of an Array (Processing)
The second loop (for (int j = years[i].xrateValue.size ()-1; j >= 0; j--)) is retrieving all the xrate values for each Year from the array (years[i]). Please do you have any ideas of how I can only return the xrate values for each year in the array. For example, Year 1990 has Xrate 2,5,6,5.6 and Year 1991 has Xrate 3,6.7,5,8,1.4. The loop should only return the Xrate values for 1990 and then 1991 and so on.</p>

```<code>for (int i=0; i<years.length; i++)
  {
    //code to display each year

    for (int j = years[i].xrateValue.size ()-1; j >= 0; j--)
    {
      float xrate = (float)(years[i].xrateValue.get(j));
      float barHeight = map(xrate, 0, mathMax, 0, 80); //adjust rect size
      float bX = sX+2;
      float bY = sY + 105 - barHeight;
      float bW = 105 / years.length;
      strokeWeight(0.9);
      stroke(10);
      fill(255, 8, 8);
      if (xrate >= 71)
      {
        fill(2, 152, 48);
      } else if ((xrate >= 51) && (xrate <= 70))
      {
        fill(255, 217, 19);
      }
      rect(i+i+i+bX, bY, bW, barHeight);
    }
}
</code>```

答:
```<code>for(int i : [listname]){
    for(int j = i; j > 0; j--){
        // your code
    }
}
</code>```

This repeats a repitition that repeats 1 extra time each time the repitition repeats (Wow that's confusing. just read it over untill it makes sense.).

Body:
The second loop (for (int j = years[i].xrateValue.size ()-1; j >= 0; j--)) is retrieving all the xrate values for each Year from the array (years[i]). Please do you have any ideas of how I can only return the xrate values for each year in the array. For example, Year 1990 has Xrate 2,5,6,5.6 and Year 1991 has Xrate 3,6.7,5,8,1.4. The loop should only return the Xrate values for 1990 and then 1991 and so on.

for (int i=0; i<years.length; i++)
  {
    //code to display each year

    for (int j = years[i].xrateValue.size ()-1; j >= 0; j--)
    {
      float xrate = (float)(years[i].xrateValue.get(j));
      float barHeight = map(xrate, 0, mathMax, 0, 80); //adjust rect size
      float bX = sX+2;
      float bY = sY + 105 - barHeight;
      float bW = 105 / years.length;
      strokeWeight(0.9);
      stroke(10);
      fill(255, 8, 8);
      if (xrate >= 71)
      {
        fill(2, 152, 48);
      } else if ((xrate >= 51) && (xrate <= 70))
      {
        fill(255, 217, 19);
      }
      rect(i+i+i+bX, bY, bW, barHeight);
    }
}

Body:
for(int i : [listname]){
    for(int j = i; j > 0; j--){
        // your code
    }
}

This repeats a repitition that repeats 1 extra time each time the repitition repeats (Wow that's confusing. just read it over untill it makes sense.).


问:
Possible to modify @ModelAttribute before @Validated is run
Is is possible to modify a @ModelAttribute before it is validated via @Validated.

ie

```<code>@RequestMapping(value = "/doSomething", method = RequestMethod.POST)
public final ModelAndView save(
        @Validated(value = {myGroup.class}) @ModelAttribute("myObject") MyObject myObject)
</code>```

I need to change the state of myObject before @Validated is executed

答:
There are 2 ways to modify the model attribute object before the @Validated will trigger:

Remove @Validated and autowire the validator and manually trigger the validator:

```<code>class MyController {

  private final Validator validator;

  class MyController(Validator validator) {
    this.validator = validator;
  }

  @PostMapping("/doSomething")
  public final ModelAndView save(
        @ModelAttribute("myObject") MyObject myObject, BindingResult result) {
    // edit MyObject here

    validator.validate(myObject, result)

    // original method body here
}

</code>```

Decorate the default validator and pre-process the myObject object inside the decorated validator.

```<code>class MyController {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.setValidator(new PreProcessMyObjectValidator(binder.getValidator()));
    }

@PostMapping("/doSomething")
  public final ModelAndView save(
        @Validated(value = {myGroup.class}) @ModelAttribute("myObject") MyObject myObject, BindingResult result) {
    ...
  }

private static class PreProcessMyObjectValidator implements Validator {
        private final Validator validator;

        public PreProcessMyObjectValidator(Validator validator) {
            this.validator = validator;
        }

        @Override
        public boolean supports(@Nonnull Class<?> clazz) {
            return validator.supports(clazz);
        }

        @Override
        public void validate(@Nonnull Object target, @Nonnull Errors errors) {
            if (target instanceof MyObject) {
                MyObject myObject = (MyObject) target;
                // manipulate myObject here

            }

            validator.validate(target, errors);
        }
    }

}
</code>```

(This second tip is what I picked up from https://github.com/spring-projects/spring-framework/issues/11103)

Body:
Is is possible to modify a @ModelAttribute before it is validated via @Validated.

ie

@RequestMapping(value = "/doSomething", method = RequestMethod.POST)
public final ModelAndView save(
        @Validated(value = {myGroup.class}) @ModelAttribute("myObject") MyObject myObject)

I need to change the state of myObject before @Validated is executed

Body:
There are 2 ways to modify the model attribute object before the @Validated will trigger:

Remove @Validated and autowire the validator and manually trigger the validator:

class MyController {

  private final Validator validator;

  class MyController(Validator validator) {
    this.validator = validator;
  }

  @PostMapping("/doSomething")
  public final ModelAndView save(
        @ModelAttribute("myObject") MyObject myObject, BindingResult result) {
    // edit MyObject here

    validator.validate(myObject, result)

    // original method body here
}

Decorate the default validator and pre-process the myObject object inside the decorated validator.

class MyController {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.setValidator(new PreProcessMyObjectValidator(binder.getValidator()));
    }

@PostMapping("/doSomething")
  public final ModelAndView save(
        @Validated(value = {myGroup.class}) @ModelAttribute("myObject") MyObject myObject, BindingResult result) {
    ...
  }

private static class PreProcessMyObjectValidator implements Validator {
        private final Validator validator;

        public PreProcessMyObjectValidator(Validator validator) {
            this.validator = validator;
        }

        @Override
        public boolean supports(@Nonnull Class<?> clazz) {
            return validator.supports(clazz);
        }

        @Override
        public void validate(@Nonnull Object target, @Nonnull Errors errors) {
            if (target instanceof MyObject) {
                MyObject myObject = (MyObject) target;
                // manipulate myObject here

            }

            validator.validate(target, errors);
        }
    }

}

(This second tip is what I picked up from https://github.com/spring-projects/spring-framework/issues/11103)


问:
Piecing together meshes in ThreeJS causes visible seam
I'm trying to piece together a sphere with individual slices. Basically, I have multiple SphereGeoemtery slices that form a sphere and used to project a panorama. Slices are used for lazy loading very large panoramas.

With the default texture wrapping mode (THREE.ClampToEdgeWrapping) on these slices, from far away the panorama looks fine but if you zoom in it's very clear the edges of the meshes are stretching, causing visible seams. It make sense since it's stretching the last pixel at the edge..

I also tried changing wrapping mode to THREE.RepeatWrapping, however, the seam becomes completely visible:

So my question is, what's the best method here for piecing together meshes? Or is this just unavoidable?

答:
Off the top of my head you'd have to make each texture contain one border row and border column in each direction that's a repeat of the its neighbor, then adjust the UV coordinates appropriately

For example if the big image is 8 pixels wide and 6 pixels tall

```<code>ABCDEFGH
IJKLMNOP
QRSTUVWX
YZ123456
789abcde
fghijklm
</code>```

And you want to divide it into into 4 parts (each 4, 3)
then you'd need these 4 parts

```<code>ABCDE DEFGH
IJKLM LMNOP
QRSTU TUVWX
YZ123 23456

QRSTU TUVWX
YZ123 23456
789ab abcde
fghij ijklm
</code>```

Also to make it easy repeat the edges so

```<code>AABCDE DEFGHH
AABCDE DEFGHH
IIJKLM LMNOPP
QQRSTU TUVWXX
YYZ123 234566

QQRSTU TUVWXX
YYZ123 234566
7789ab abcdee
ffghij ijklmm
ffghij ijklmm
</code>```

Repeating the edges is because I'm assuming you're splitting into more than 2x2 so technically if you were going to split something 50 pixels wide into 5 parts you could do parts that are 11, 12, 12, 12, 11 in width. The edges being only 11 pixels instead of 12 would need a different UV adjustment. But, by repeating the edges we can make them all 12, 12, 12, 12, 12 so everything is consistant.

testing, left is normal split showing the seam. Right is the fixed one, no seam.

body {
  margin: 0;
}
#c {
  width: 100vw;
  height: 100vh;
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="c"></canvas>
<script type="module">
import * as THREE from 'https://threejsfundamentals.org/threejs/resources/threejs/r115/build/three.module.js';

function main() {
  const canvas = document.querySelector('#c');
  const renderer = new THREE.WebGLRenderer({canvas});

  const fov = 75;
  const aspect = 2;  // the canvas default
  const near = 0.1;
  const far = 5;
  const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  camera.position.z = 1;

  const scene = new THREE.Scene();

  // make our texture using a canvas to test
  const bigImage = document.createElement('canvas');
  {
    const ctx = bigImage.getContext('2d');
    const width = 32;
    const height = 16;
    ctx.canvas.width = width;
    ctx.canvas.height = height;
    const gradient = ctx.createLinearGradient(0, 0, width, height);
    gradient.addColorStop(0, 'red');
    gradient.addColorStop(0.5, 'yellow');
    gradient.addColorStop(1, 'blue');
    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, width, height);
  }

  const forceTextureInitialization = function() {
    const material = new THREE.MeshBasicMaterial();
    const geometry = new THREE.PlaneBufferGeometry();
    const scene = new THREE.Scene();
    scene.add(new THREE.Mesh(geometry, material));
    const camera = new THREE.Camera();

    return function forceTextureInitialization(texture) {
      material.map = texture;
      renderer.render(scene, camera);
    };
  }();

  // bad
  {
    const ctx = document.createElement('canvas').getContext('2d');

    // split the texture into 4 parts across 4 planes
    const across = 2;
    const down = 2;
    const pixelsAcross = bigImage.width / across;
    const pixelsDown = bigImage.height / down;
    ctx.canvas.width = pixelsAcross;
    ctx.canvas.height = pixelsDown;

    for (let y = 0; y < down; ++y) {
      for (let x = 0; x < across; ++x) {
        ctx.clearRect(0, 0, pixelsAcross, pixelsDown);
        ctx.drawImage(bigImage,
                      x * pixelsAcross, (down - 1 - y) * pixelsDown, pixelsAcross, pixelsDown,
                      0, 0, pixelsAcross, pixelsDown);
        const texture = new THREE.CanvasTexture(ctx.canvas);
        // see https://threejsfundamentals.org/threejs/lessons/threejs-canvas-textures.html
        forceTextureInitialization(texture);
        const geometry = new THREE.PlaneBufferGeometry(1 / across, 1 / down);
        const material = new THREE.MeshBasicMaterial({map: texture});
        const plane = new THREE.Mesh(geometry, material);
        scene.add(plane);
        plane.position.set(-1 + x / across, y / down - 0.25, 0);
      }
    }
  }

  // good
  {
    const ctx = document.createElement('canvas').getContext('2d');

    // split the texture into 4 parts across 4 planes
    const across = 2;
    const down = 2;
    const pixelsAcross = bigImage.width / across;
    const pixelsDown = bigImage.height / down;
    ctx.canvas.width = pixelsAcross + 2;
    ctx.canvas.height = pixelsDown + 2;

    // just draw the image at all these offsets.
    // it would be more efficient to draw the edges
    // 1 pixel wide but I'm lazy
    const offsets = [
      [ 0,  0],
      [ 1,  0],
      [ 2,  0],
      [ 0,  1],
      [ 2,  1],
      [ 0,  2],
      [ 1,  2],
      [ 2,  2],
      [ 1,  1],
    ];

    for (let y = 0; y < down; ++y) {
      for (let x = 0; x < across; ++x) {
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        let srcX = x * pixelsAcross - 1;
        let srcY = (down - 1 - y) * pixelsDown - 1;
        let dstX = 0;
        let dstY = 0;
        let width = pixelsAcross + 2;
        let height = pixelsDown + 2;
        ctx.drawImage(bigImage,
                      srcX, srcY, width, height,
                      dstX, dstY, width, height);
        // handle edges
        if (srcX < 0) {
          // repeat left edge
          ctx.drawImage(bigImage,
                        0, srcY, 1, height,
                        0, dstY, 1, height);
        }
        if (srcY < 0) {
          // repeat top edge
          ctx.drawImage(bigImage,
                        srcX, 0, width, 1,
                        dstX, 0, width, 1);
        }
        if (srcX + width > bigImage.width) {
          // repeat right edge
          ctx.drawImage(bigImage,
                        bigImage.width - 1, srcY, 1, height,
                        ctx.canvas.width - 1, dstY, 1, height);
        }
        if (srcY + height > bigImage.height) {
          // repeat bottom edge
          ctx.drawImage(bigImage,
                        srcX, bigImage.height - 1, width, 1,
                        dstX, ctx.canvas.height - 1, width, 1);
        }
        // TODO: handle corners
        const texture = new THREE.CanvasTexture(ctx.canvas);
        texture.minFilter = THREE.LinearFilter;
        // offset UV coords 1 pixel to skip the edge pixel
        texture.offset.set(1 / ctx.canvas.width, 1 / ctx.canvas.height);
        // only textureSize - 2 of the pixels in the texture
        texture.repeat.set(pixelsAcross / ctx.canvas.width, pixelsDown / ctx.canvas.height);
        // see https://threejsfundamentals.org/threejs/lessons/threejs-canvas-textures.html
        forceTextureInitialization(texture);
        const geometry = new THREE.PlaneBufferGeometry(1 / across, 1 / down);
        const material = new THREE.MeshBasicMaterial({map: texture});
        const plane = new THREE.Mesh(geometry, material);
        scene.add(plane);
        plane.position.set(1 + x / across - 0.5, y / down - 0.25, 0);
      }
    }
  }

  function resizeRendererToDisplaySize(renderer) {
    const canvas = renderer.domElement;
    const width = canvas.clientWidth;
    const height = canvas.clientHeight;
    const needResize = canvas.width !== width || canvas.height !== height;
    if (needResize) {
      renderer.setSize(width, height, false);
    }
    return needResize;
  }

  function render(time) {
    time *= 0.001;

    if (resizeRendererToDisplaySize(renderer)) {
      const canvas = renderer.domElement;
      camera.aspect = canvas.clientWidth / canvas.clientHeight;
      camera.updateProjectionMatrix();
    }

    renderer.render(scene, camera);

    requestAnimationFrame(render);
  }

  requestAnimationFrame(render);
}

main();
</script></code>```

Body:
Off the top of my head you'd have to make each texture contain one border row and border column in each direction that's a repeat of the its neighbor, then adjust the UV coordinates appropriately

For example if the big image is 8 pixels wide and 6 pixels tall

ABCDEFGH
IJKLMNOP
QRSTUVWX
YZ123456
789abcde
fghijklm

And you want to divide it into into 4 parts (each 4, 3)
then you'd need these 4 parts

ABCDE DEFGH
IJKLM LMNOP
QRSTU TUVWX
YZ123 23456

QRSTU TUVWX
YZ123 23456
789ab abcde
fghij ijklm

Also to make it easy repeat the edges so

AABCDE DEFGHH
AABCDE DEFGHH
IIJKLM LMNOPP
QQRSTU TUVWXX
YYZ123 234566

QQRSTU TUVWXX
YYZ123 234566
7789ab abcdee
ffghij ijklmm
ffghij ijklmm

Repeating the edges is because I'm assuming you're splitting into more than 2x2 so technically if you were going to split something 50 pixels wide into 5 parts you could do parts that are 11, 12, 12, 12, 11 in width. The edges being only 11 pixels instead of 12 would need a different UV adjustment. But, by repeating the edges we can make them all 12, 12, 12, 12, 12 so everything is consistant.

testing, left is normal split showing the seam. Right is the fixed one, no seam.

body {
  margin: 0;
}
#c {
  width: 100vw;
  height: 100vh;
  display: block;
}

<canvas id="c"></canvas>
<script type="module">
import * as THREE from 'https://threejsfundamentals.org/threejs/resources/threejs/r115/build/three.module.js';

function main() {
  const canvas = document.querySelector('#c');
  const renderer = new THREE.WebGLRenderer({canvas});

  const fov = 75;
  const aspect = 2;  // the canvas default
  const near = 0.1;
  const far = 5;
  const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  camera.position.z = 1;

  const scene = new THREE.Scene();

  // make our texture using a canvas to test
  const bigImage = document.createElement('canvas');
  {
    const ctx = bigImage.getContext('2d');
    const width = 32;
    const height = 16;
    ctx.canvas.width = width;
    ctx.canvas.height = height;
    const gradient = ctx.createLinearGradient(0, 0, width, height);
    gradient.addColorStop(0, 'red');
    gradient.addColorStop(0.5, 'yellow');
    gradient.addColorStop(1, 'blue');
    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, width, height);
  }

  const forceTextureInitialization = function() {
    const material = new THREE.MeshBasicMaterial();
    const geometry = new THREE.PlaneBufferGeometry();
    const scene = new THREE.Scene();
    scene.add(new THREE.Mesh(geometry, material));
    const camera = new THREE.Camera();

    return function forceTextureInitialization(texture) {
      material.map = texture;
      renderer.render(scene, camera);
    };
  }();

  // bad
  {
    const ctx = document.createElement('canvas').getContext('2d');

    // split the texture into 4 parts across 4 planes
    const across = 2;
    const down = 2;
    const pixelsAcross = bigImage.width / across;
    const pixelsDown = bigImage.height / down;
    ctx.canvas.width = pixelsAcross;
    ctx.canvas.height = pixelsDown;

    for (let y = 0; y < down; ++y) {
      for (let x = 0; x < across; ++x) {
        ctx.clearRect(0, 0, pixelsAcross, pixelsDown);
        ctx.drawImage(bigImage,
                      x * pixelsAcross, (down - 1 - y) * pixelsDown, pixelsAcross, pixelsDown,
                      0, 0, pixelsAcross, pixelsDown);
        const texture = new THREE.CanvasTexture(ctx.canvas);
        // see https://threejsfundamentals.org/threejs/lessons/threejs-canvas-textures.html
        forceTextureInitialization(texture);
        const geometry = new THREE.PlaneBufferGeometry(1 / across, 1 / down);
        const material = new THREE.MeshBasicMaterial({map: texture});
        const plane = new THREE.Mesh(geometry, material);
        scene.add(plane);
        plane.position.set(-1 + x / across, y / down - 0.25, 0);
      }
    }
  }

  // good
  {
    const ctx = document.createElement('canvas').getContext('2d');

    // split the texture into 4 parts across 4 planes
    const across = 2;
    const down = 2;
    const pixelsAcross = bigImage.width / across;
    const pixelsDown = bigImage.height / down;
    ctx.canvas.width = pixelsAcross + 2;
    ctx.canvas.height = pixelsDown + 2;

    // just draw the image at all these offsets.
    // it would be more efficient to draw the edges
    // 1 pixel wide but I'm lazy
    const offsets = [
      [ 0,  0],
      [ 1,  0],
      [ 2,  0],
      [ 0,  1],
      [ 2,  1],
      [ 0,  2],
      [ 1,  2],
      [ 2,  2],
      [ 1,  1],
    ];

    for (let y = 0; y < down; ++y) {
      for (let x = 0; x < across; ++x) {
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        let srcX = x * pixelsAcross - 1;
        let srcY = (down - 1 - y) * pixelsDown - 1;
        let dstX = 0;
        let dstY = 0;
        let width = pixelsAcross + 2;
        let height = pixelsDown + 2;
        ctx.drawImage(bigImage,
                      srcX, srcY, width, height,
                      dstX, dstY, width, height);
        // handle edges
        if (srcX < 0) {
          // repeat left edge
          ctx.drawImage(bigImage,
                        0, srcY, 1, height,
                        0, dstY, 1, height);
        }
        if (srcY < 0) {
          // repeat top edge
          ctx.drawImage(bigImage,
                        srcX, 0, width, 1,
                        dstX, 0, width, 1);
        }
        if (srcX + width > bigImage.width) {
          // repeat right edge
          ctx.drawImage(bigImage,
                        bigImage.width - 1, srcY, 1, height,
                        ctx.canvas.width - 1, dstY, 1, height);
        }
        if (srcY + height > bigImage.height) {
          // repeat bottom edge
          ctx.drawImage(bigImage,
                        srcX, bigImage.height - 1, width, 1,
                        dstX, ctx.canvas.height - 1, width, 1);
        }
        // TODO: handle corners
        const texture = new THREE.CanvasTexture(ctx.canvas);
        texture.minFilter = THREE.LinearFilter;
        // offset UV coords 1 pixel to skip the edge pixel
        texture.offset.set(1 / ctx.canvas.width, 1 / ctx.canvas.height);
        // only textureSize - 2 of the pixels in the texture
        texture.repeat.set(pixelsAcross / ctx.canvas.width, pixelsDown / ctx.canvas.height);
        // see https://threejsfundamentals.org/threejs/lessons/threejs-canvas-textures.html
        forceTextureInitialization(texture);
        const geometry = new THREE.PlaneBufferGeometry(1 / across, 1 / down);
        const material = new THREE.MeshBasicMaterial({map: texture});
        const plane = new THREE.Mesh(geometry, material);
        scene.add(plane);
        plane.position.set(1 + x / across - 0.5, y / down - 0.25, 0);
      }
    }
  }

  function resizeRendererToDisplaySize(renderer) {
    const canvas = renderer.domElement;
    const width = canvas.clientWidth;
    const height = canvas.clientHeight;
    const needResize = canvas.width !== width || canvas.height !== height;
    if (needResize) {
      renderer.setSize(width, height, false);
    }
    return needResize;
  }

  function render(time) {
    time *= 0.001;

    if (resizeRendererToDisplaySize(renderer)) {
      const canvas = renderer.domElement;
      camera.aspect = canvas.clientWidth / canvas.clientHeight;
      camera.updateProjectionMatrix();
    }

    renderer.render(scene, camera);

    requestAnimationFrame(render);
  }

  requestAnimationFrame(render);
}

main();
</script>


问:
Converting string of strings to list in dataframe
I have a dataframe as following:

```<code>id|words
1|ant,bat,cat
2|mat,rat,pat
</code>```

I want the words column to be as follows:

```<code>id|words
1|['ant','bat','cat']
2|['mat','rat','pat']
</code>```

How could I do it?
I tried with literaleval but it shows exception

答:
Use Series.str.split:

```<code>df['words'] = df['words'].str.split(',')
</code>```

Body:
I have a dataframe as following:

id|words
1|ant,bat,cat
2|mat,rat,pat

I want the words column to be as follows:

id|words
1|['ant','bat','cat']
2|['mat','rat','pat']

How could I do it?
I tried with literaleval but it shows exception

Body:
Use Series.str.split:

df['words'] = df['words'].str.split(',')


问:
Can't redirect after login?
Getting a TypeError: Cannot read property '$router' of undefined when trying to redirect after login. I have tried various methods on the router instance but it is undefined according to the console?

Login action (inside store):

```<code>login({ commit, dispatch }, { username, password }) {
    const querystring = require('querystring');

    this.$axios.$post('connect/token', querystring.stringify({
        client_id: process.env.CLIENT_ID,
        client_secret: process.env.CLIENT_SECRET,
        username,
        password,
        grant_type: 'password'
    }))
    .then(function (response) {
        dispatch('setToken', {
            token: response.access_token,
            expiresIn: response.expires_in
        });

        this.$router.push({name: 'home' }); // this line is the issue
    })
    .catch(errors => {
      console.dir(errors);
    });
},
</code>```

答:
You just need to preserve this before calling it again inside .then(...) like:

```<code>login({ commit, dispatch }, { username, password }) {

    // Store `this` inside variable vm here
    const vm = this;
    const querystring = require('querystring');

    vm.$axios.$post('connect/token', querystring.stringify({
        client_id: process.env.CLIENT_ID,
        client_secret: process.env.CLIENT_SECRET,
        username,
        password,
        grant_type: 'password'
    }))
    .then(function (response) {
        dispatch('setToken', {
            token: response.access_token,
            expiresIn: response.expires_in
        });

        // Use this for debugging purpose only
        console.log( vm.$router )

        // You can now access `$router` safely here now
        vm.$router.push({name: 'home' });
    })
    .catch(errors => console.dir(errors));
},
</code>```

Title: Can't redirect after login?

Body:
Getting a TypeError: Cannot read property '$router' of undefined when trying to redirect after login. I have tried various methods on the router instance but it is undefined according to the console?

Login action (inside store):

login({ commit, dispatch }, { username, password }) {
    const querystring = require('querystring');

    this.$axios.$post('connect/token', querystring.stringify({
        client_id: process.env.CLIENT_ID,
        client_secret: process.env.CLIENT_SECRET,
        username,
        password,
        grant_type: 'password'
    }))
    .then(function (response) {
        dispatch('setToken', {
            token: response.access_token,
            expiresIn: response.expires_in
        });

        this.$router.push({name: 'home' }); // this line is the issue
    })
    .catch(errors => {
      console.dir(errors);
    });
},

Body:
You just need to preserve this before calling it again inside .then(...) like:

login({ commit, dispatch }, { username, password }) {

    // Store `this` inside variable vm here
    const vm = this;
    const querystring = require('querystring');

    vm.$axios.$post('connect/token', querystring.stringify({
        client_id: process.env.CLIENT_ID,
        client_secret: process.env.CLIENT_SECRET,
        username,
        password,
        grant_type: 'password'
    }))
    .then(function (response) {
        dispatch('setToken', {
            token: response.access_token,
            expiresIn: response.expires_in
        });

        // Use this for debugging purpose only
        console.log( vm.$router )

        // You can now access `$router` safely here now
        vm.$router.push({name: 'home' });
    })
    .catch(errors => console.dir(errors));
},


问:
Why basic_ifstream show me wrong results?
I have a binary file. There are 2288*2288 longitude float values stored in top half section, and the same number of latitude float values occupied the bottom half. I used the following code to load them into a float vector. It can run like a charm, but gave me incorrect results. With regard to my binary file, the float vector should be filled with a total of 2288*2288*2=10469888 elements, but only 159005, all their values are the same 200.0000. Would you please explain what's wrong with my code?

Thank you in advance!

```<code>bool LoadData(const char* pszDataFile)
{
    typedef char_traits<float> traits_type;
    typedef std::codecvt<float, char, mbstate_t> cvt;

    std::basic_ifstream<float, traits_type> input( pszDataFile, std::ios::binary );
    std::locale loc(std::locale(), new cvt());
    input.imbue(loc);

    std::vector<float> fvBuffer;

    // Copies all data into buffer
    std::copy(std::istreambuf_iterator<float>(input),
              std::istreambuf_iterator<float>( ),
              std::back_inserter(fvBuffer));

    long nSzie = fvBuffer.size();  // Wrong vector size (159005)

    return true;
}
</code>```

答:
To make std::basic_ifstream works, you have to define your trait_type so that it provides everything expected by input stream, and I'm not sure that it will be possible.  That will be far more than just a codecvt<float, char, mbstate_t> (which you seem to think is already present while the standard demand only the wchar_t, char and char, char specializations).

If you want a binary input iterator, you'll have to write one yourself to work with basic_ifstream,  something like this (run and give the expected result, but not debugged further):

```<code>#include <fstream>
#include <algorithm>
#include <vector>
#include <iterator>
#include <iostream>

template <typename T>
class BinaryInputIterator
    : public std::iterator<std::input_iterator_tag, T, std::ptrdiff_t,
                           const T*, const T&>
{
public:
    BinaryInputIterator();
    BinaryInputIterator(std::istream&);
    // Compiler generated version OK:
    // BinaryInputIterator(BinaryInputIterator const& other);
    // BinaryInputIterator& operator=(BinaryInputIterator const& other);
    ~BinaryInputIterator();

    T const& operator*() const;
    T const* operator->() const;
    BinaryInputIterator& operator++();
    BinaryInputIterator operator++(int);

private:
    std::istream* myStream;
    T myValue;

    friend bool operator==
       (BinaryInputIterator const& l, BinaryInputIterator const& r)
    {
        return ((l.myStream == NULL && (r.myStream == NULL || !*r.myStream))
                || (r.myStream == NULL && (l.myStream == NULL || !*l.myStream)));
    }
    friend bool operator!=
       (BinaryInputIterator const& l, BinaryInputIterator const& r)
    {
        return !(l == r);
    }
};

template <typename T>
BinaryInputIterator<T>::BinaryInputIterator()
    : myStream(0)
{}

template <typename T>
BinaryInputIterator<T>::BinaryInputIterator(std::istream& is)
    : myStream(&is)
{
    myStream->read(reinterpret_cast<char*>(&myValue), sizeof myValue);
}

template <typename T>
BinaryInputIterator<T>::~BinaryInputIterator()
{}

template <typename T>
T const& BinaryInputIterator<T>::operator*() const
{
    return myValue;
}

template <typename T>
T const* BinaryInputIterator<T>::operator->() const
{
    return &myValue;
}

template <typename T>
BinaryInputIterator<T>& BinaryInputIterator<T>::operator++()
{
    myStream->read(reinterpret_cast<char*>(&myValue), sizeof myValue);
    return *this;
}

template <typename T>
BinaryInputIterator<T> BinaryInputIterator<T>::operator++(int)
{
    BinaryInputIterator result(this);
    ++*this;
    return result;
}

int main()
{
 {
    std::ofstream os("foo.dta");
    std::vector<float> vect1;
    vect1.push_back(4.2);
    vect1.push_back(3.14);
    os.write(reinterpret_cast<char*>(&vect1[0]), sizeof(float)*vect1.size());
 }
 {
    std::ifstream is("foo.dta");
    std::vector<float> vect2;
    std::copy(BinaryInputIterator<float>(is),
              BinaryInputIterator<float>(),
              std::back_inserter(vect2));
    std::copy(vect2.begin(), vect2.end(), std::ostream_iterator<float>(std::cout, "\n"));
 }
}
</code>```

Body:
I have a binary file. There are 2288*2288 longitude float values stored in top half section, and the same number of latitude float values occupied the bottom half. I used the following code to load them into a float vector. It can run like a charm, but gave me incorrect results. With regard to my binary file, the float vector should be filled with a total of 2288*2288*2=10469888 elements, but only 159005, all their values are the same 200.0000. Would you please explain what's wrong with my code?

Thank you in advance!

bool LoadData(const char* pszDataFile)
{
    typedef char_traits<float> traits_type;
    typedef std::codecvt<float, char, mbstate_t> cvt;

    std::basic_ifstream<float, traits_type> input( pszDataFile, std::ios::binary );
    std::locale loc(std::locale(), new cvt());
    input.imbue(loc);

    std::vector<float> fvBuffer;

    // Copies all data into buffer
    std::copy(std::istreambuf_iterator<float>(input),
              std::istreambuf_iterator<float>( ),
              std::back_inserter(fvBuffer));

    long nSzie = fvBuffer.size();  // Wrong vector size (159005)

    return true;
}

Body:
To make std::basic_ifstream works, you have to define your trait_type so that it provides everything expected by input stream, and I'm not sure that it will be possible.  That will be far more than just a codecvt<float, char, mbstate_t> (which you seem to think is already present while the standard demand only the wchar_t, char and char, char specializations).

If you want a binary input iterator, you'll have to write one yourself to work with basic_ifstream,  something like this (run and give the expected result, but not debugged further):

#include <fstream>
#include <algorithm>
#include <vector>
#include <iterator>
#include <iostream>

template <typename T>
class BinaryInputIterator
    : public std::iterator<std::input_iterator_tag, T, std::ptrdiff_t,
                           const T*, const T&>
{
public:
    BinaryInputIterator();
    BinaryInputIterator(std::istream&);
    // Compiler generated version OK:
    // BinaryInputIterator(BinaryInputIterator const& other);
    // BinaryInputIterator& operator=(BinaryInputIterator const& other);
    ~BinaryInputIterator();

    T const& operator*() const;
    T const* operator->() const;
    BinaryInputIterator& operator++();
    BinaryInputIterator operator++(int);

private:
    std::istream* myStream;
    T myValue;

    friend bool operator==
       (BinaryInputIterator const& l, BinaryInputIterator const& r)
    {
        return ((l.myStream == NULL && (r.myStream == NULL || !*r.myStream))
                || (r.myStream == NULL && (l.myStream == NULL || !*l.myStream)));
    }
    friend bool operator!=
       (BinaryInputIterator const& l, BinaryInputIterator const& r)
    {
        return !(l == r);
    }
};

template <typename T>
BinaryInputIterator<T>::BinaryInputIterator()
    : myStream(0)
{}

template <typename T>
BinaryInputIterator<T>::BinaryInputIterator(std::istream& is)
    : myStream(&is)
{
    myStream->read(reinterpret_cast<char*>(&myValue), sizeof myValue);
}

template <typename T>
BinaryInputIterator<T>::~BinaryInputIterator()
{}

template <typename T>
T const& BinaryInputIterator<T>::operator*() const
{
    return myValue;
}

template <typename T>
T const* BinaryInputIterator<T>::operator->() const
{
    return &myValue;
}

template <typename T>
BinaryInputIterator<T>& BinaryInputIterator<T>::operator++()
{
    myStream->read(reinterpret_cast<char*>(&myValue), sizeof myValue);
    return *this;
}

template <typename T>
BinaryInputIterator<T> BinaryInputIterator<T>::operator++(int)
{
    BinaryInputIterator result(this);
    ++*this;
    return result;
}

int main()
{
 {
    std::ofstream os("foo.dta");
    std::vector<float> vect1;
    vect1.push_back(4.2);
    vect1.push_back(3.14);
    os.write(reinterpret_cast<char*>(&vect1[0]), sizeof(float)*vect1.size());
 }
 {
    std::ifstream is("foo.dta");
    std::vector<float> vect2;
    std::copy(BinaryInputIterator<float>(is),
              BinaryInputIterator<float>(),
              std::back_inserter(vect2));
    std::copy(vect2.begin(), vect2.end(), std::ostream_iterator<float>(std::cout, "\n"));
 }
}


答:
Your problem is that you use this inside an regular function, that means that this is binded to the function and not the vue instance, change it to an arrow function:

```<code>.then((response) => {
        dispatch('setToken', {
            token: response.access_token,
            expiresIn: response.expires_in
        });

        this.$router.push({name: 'home' }); // this line is the issue
    })
</code>```

Other solution is to .bind() it:

```<code>.then(function (response) {
        dispatch('setToken', {
            token: response.access_token,
            expiresIn: response.expires_in
        });

        this.$router.push({name: 'home' }); // this line is the issue
    }.bind(this))
</code>```

Title: Can't redirect after login?

Body:
Your problem is that you use this inside an regular function, that means that this is binded to the function and not the vue instance, change it to an arrow function:

.then((response) => {
        dispatch('setToken', {
            token: response.access_token,
            expiresIn: response.expires_in
        });

        this.$router.push({name: 'home' }); // this line is the issue
    })

Other solution is to .bind() it:

.then(function (response) {
        dispatch('setToken', {
            token: response.access_token,
            expiresIn: response.expires_in
        });

        this.$router.push({name: 'home' }); // this line is the issue
    }.bind(this))


问:
How to get associative array from url query string, javascript
I have url query string

```<code>?filter%5B%22customer_rating_heading%22%5D=customer_rating_6_up%2Ccustomer_rating_7_up%2Ccustomer_rating_9_up&map=1
</code>```

which is

```<code>?filter["customer_rating_heading"]=customer_rating_6_up,customer_rating_7_up,customer_rating_9_up&map=1
</code>```

I want to ask for filter like params.get('filter) and get

```<code>[customer_rating_heading => 'customer_rating_6_up,customer_rating_7_up,customer_rating_9_up' //(later I'll make array from this string)
</code>```

But I don't know how to do this, I tried let query = Object.fromEntries(new URLSearchParams(location.search) but it gives me:

```<code>{filter["customer_rating_heading"]: "customer_rating_6_up,customer_rating_7_up,customer_rating_9_up"
map: "1"}
</code>```

but I can't get filter like query.filter it's always undefined

does anyone know a solution for such problem?

答:
You can use URLSearchParams.entries. Here is an example:

```<code>let query = new URLSearchParams(location.search);

for(var pair of query.entries()) {
  console.log("Filter:",pair[0]); // "filter['customer_rating_heading']"
  console.log("Result:",pair[1]) // "customer_rating_6_up,customer_rating_7_up,customer_rating_9_up"
}
</code>```

Here is a codepen for you to try.

Body:
I have url query string

?filter%5B%22customer_rating_heading%22%5D=customer_rating_6_up%2Ccustomer_rating_7_up%2Ccustomer_rating_9_up&map=1

which is

?filter["customer_rating_heading"]=customer_rating_6_up,customer_rating_7_up,customer_rating_9_up&map=1

I want to ask for filter like params.get('filter) and get

[customer_rating_heading => 'customer_rating_6_up,customer_rating_7_up,customer_rating_9_up' //(later I'll make array from this string)

But I don't know how to do this, I tried let query = Object.fromEntries(new URLSearchParams(location.search) but it gives me:

{filter["customer_rating_heading"]: "customer_rating_6_up,customer_rating_7_up,customer_rating_9_up"
map: "1"}

but I can't get filter like query.filter it's always undefined

does anyone know a solution for such problem?

Body:
You can use URLSearchParams.entries. Here is an example:

let query = new URLSearchParams(location.search);

for(var pair of query.entries()) {
  console.log("Filter:",pair[0]); // "filter['customer_rating_heading']"
  console.log("Result:",pair[1]) // "customer_rating_6_up,customer_rating_7_up,customer_rating_9_up"
}

Here is a codepen for you to try.


问:
Will Python open a file before it's finished writing?
I am writing a script that will be polling a directory looking for new files.

In this scenario, is it necessary to do some sort of error checking to make sure the files are completely written prior to accessing them?

I don't want to work with a file before it has been written completely to disk, but because the info I want from the file is near the beginning, it seems like it could be possible to pull the data I need without realizing the file isn't done being written.

Is that something I should worry about, or will the file be locked because the OS is writing to the hard drive?

This is on a Linux system.

答:
On Unix, unless the writing application goes out of its way, the file won't be locked and you'll be able to read from it.

The reader will, of course, have to be prepared to deal with an incomplete file (bearing in mind that there may be I/O buffering happening on the writer's side).

If that's a non-starter, you'll have to think of some scheme to synchronize the writer and the reader, for example:

explicitly lock the file;

write the data to a temporary location and only move it into its final place when the file is complete (the move operation can be done atomically, provided both the source and the destination reside on the same file system).


问:
Exploding only some part of an object in Blender 2.82a (using Explode modifier with Vertex Group?)
I am trying to explode/destroy only some part of an object.

Following Blender 2.82 manual page

     https://docs.blender.org/manual/en/2.82/physics/particles/emitter/emission.html

says "You may use vertex groups to confine the emission, that is done in the Vertex Groups panel."

So, it must be possible.

As a test, I created a Blender file, attempting to explode/destroy only the left ear of Suzanne, using Explode modifier.
I tried the following:

Added a monkey object ("Suzanne").

Applied "Subdivision Modifier" with "Simple" subdivision algorithm.

Created a vertex group named "VtxGroup_Suzanne__All_vertices_in_left_ear", which contains all vertices in Suzanne's left ear.

enter image description here

Created particle system setting.

  Enabled Rotation.

  In "Density" field under "Vertex Groups", entered "VtxGroup_Suzanne__All_vertices_in_left_ear".

  In "Render As" filed under "Render", chose "Object".

Added "Explode" modifier.

  This modifier has "Vertex Group" field, but it seems it does not make any difference in the result (probably because I do not know how to use it properly???)

At this point, when I play the animation, particles erupt out of Suzanne's left ear, breaking down Suzanne little by little.
However, the destruction is not limited to the left year.  Entire Suzanne starts breaking down.

Some destruction pieces are really big or unnaturally long, such as almost half of Suzanne's face shown in the screenshot.

enter image description here

Is there any way I can limit the destruction only to the left ear (which is vertex group "VtxGroup_Suzanne__All_vertices_in_left_ear".
Also, can I adjust the sizes of destruction particles, so that some of them would not be too big, nor too long?
I tried setting a whole bunch of settings, but I could not find the solution.  Maybe I am attempting this completely wrong?  Is there some way to accomplish this in a completely different way?
This test file is found here (zipped):
Test file for Explode modifier with Vertex Group
Thank you in advance for help.

答:
Try splitting the object? If you want to animate the object beforehand, construct the object out of two separate objects grouped, and then ungroup them at or before the keyframe you want them to explode. I hope this helps!
:)</p>


问:
VS Studio - Method color gone to white after update to 16.6.0
Well, after I updated my vs studio community 2019 to latest version 16.6.0, all my method color turn white.

I found Tools > Options > Fonts and Colors > User Members - Methods are able to change color, but I not sure the custom RGB color. I using dark theme, I remember the method color was kind a yellow.

If anyone know the RGB color for the method or there is other way to fix this, please leave your comment. Thanks

答:
Not completely sure but it was something like this:

R: 250

G: 238

B: 190

H: 32

S: 206

L: 207


问:
onActivityResult() never called
I have a problem with onActivityResult() and setResult().

I started android development 1 week ago so sorry.

Could you help me?

here is a snippet of my code :

ListActivity function Click

```<code>    val myadapter = ItemAdapter();
    list_recycler_view.layoutManager = LinearLayoutManager(this)
    list_recycler_view.adapter = myadapter
    val me = this;
        myadapter.setOnItemClickListener(object : ItemAdapter.OnItemClickListener {
            override fun onItemClick(item: Item) {
                val intent = Intent(me, DetailActivity::class.java)
                intent.putExtra("item", item)
                startActivityForResult(intent, 2)
            }
        })
</code>```

List activity function onActivityResult

```<code>    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Log.d("reponse","coucou5");
        Log.d("reponse",requestCode.toString());
        Log.d("reponse",resultCode.toString());
        if (requestCode == 2 && resultCode == RESULT_OK) {

            val item = data?.getParcelableExtra<Item>("item") as Item
            Log.d("reponse-update",item.toString());
            if (item == null) {
                Toast.makeText(this, "Could not update! Error!", Toast.LENGTH_SHORT).show()
            }

            //ItemListViewModel.update(item);

        } else {
            Toast.makeText(this, "Note not saved!", Toast.LENGTH_SHORT).show()
        }
    }
</code>```

DetailActivity function on click

```<code>     btnSave.setOnClickListener{
            //other props
            item.gid = gid;
            item.distance = distance
            Log.d("reponse",item.toString());
            Log.d("reponse","coucou4");
            val returnIntent = intent
            returnIntent.putExtra("item", item)
            setResult(Activity.RESULT_OK, returnIntent)
            finish()
        }
</code>```

it seems that the onActivityResult() is never called

答:
I think it is because you are not creating another intent to send the info back, please do this and check if that works for you.

Do this in your detail activity instead of your code just paste this.

```<code>btnSave.setOnClickListener{
        //other props
        item.gid = gid;
        item.distance = distance
        Log.d("reponse",item.toString());
        Log.d("reponse","coucou4");
        Intent returnIntent = Intent();
        returnIntent.putExtra("item", item)
        setResult(2, returnIntent)
        finish()
    }
</code>```

you are passing RESULT_OK which isn't required and it's processed by the Android framework itself.

Title: onActivityResult() never called

Body:
I have a problem with onActivityResult() and setResult().

I started android development 1 week ago so sorry.

Could you help me?

here is a snippet of my code :

ListActivity function Click

    val myadapter = ItemAdapter();
    list_recycler_view.layoutManager = LinearLayoutManager(this)
    list_recycler_view.adapter = myadapter
    val me = this;
        myadapter.setOnItemClickListener(object : ItemAdapter.OnItemClickListener {
            override fun onItemClick(item: Item) {
                val intent = Intent(me, DetailActivity::class.java)
                intent.putExtra("item", item)
                startActivityForResult(intent, 2)
            }
        })

List activity function onActivityResult

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Log.d("reponse","coucou5");
        Log.d("reponse",requestCode.toString());
        Log.d("reponse",resultCode.toString());
        if (requestCode == 2 && resultCode == RESULT_OK) {

            val item = data?.getParcelableExtra<Item>("item") as Item
            Log.d("reponse-update",item.toString());
            if (item == null) {
                Toast.makeText(this, "Could not update! Error!", Toast.LENGTH_SHORT).show()
            }

            //ItemListViewModel.update(item);

        } else {
            Toast.makeText(this, "Note not saved!", Toast.LENGTH_SHORT).show()
        }
    }

DetailActivity function on click

     btnSave.setOnClickListener{
            //other props
            item.gid = gid;
            item.distance = distance
            Log.d("reponse",item.toString());
            Log.d("reponse","coucou4");
            val returnIntent = intent
            returnIntent.putExtra("item", item)
            setResult(Activity.RESULT_OK, returnIntent)
            finish()
        }

it seems that the onActivityResult() is never called

Body:
I think it is because you are not creating another intent to send the info back, please do this and check if that works for you.

Do this in your detail activity instead of your code just paste this.

btnSave.setOnClickListener{
        //other props
        item.gid = gid;
        item.distance = distance
        Log.d("reponse",item.toString());
        Log.d("reponse","coucou4");
        Intent returnIntent = Intent();
        returnIntent.putExtra("item", item)
        setResult(2, returnIntent)
        finish()
    }

you are passing RESULT_OK which isn't required and it's processed by the Android framework itself.


问:
Best practices for loading page content via AJAX request in Rails3?
Suppose you have a page with two columns of content. For whatever reason, you wish to retrieve the HTML content of one of those columns after the page has loaded, via an AJAX request.  The user does not need to take an action to make the content load (no link clicking or form submissions), it just happens automatically.

I can easily do this by returning an empty placeholder div in the main response

```<code><div id="pink-dancing-elephants"></div>
</code>```

and then add a little jQuery to the page

```<code>$.ajax({
    url: "/elephants/dancing/pink",
    cache: false,
    success: function(html){
      $("#pink-dancing-elephants").append(html);
    }
});
</code>```

and have the action that responses to /elephants/dancing/pink return the corresponding blob of HTML.

This all works fine, but I'm wondering if I'm missing some Rails3 feature that would make this easier.  E.g. I'm searching for the ability to be able to just put something like the following in the main view and have the rest of it happen by "magic"

```<code><%= render :url=>"/elephants/dancing/pink", :remote => true %>
</code>```

Am I missing something?

答:
There is a simple way ofcource, just add respond_to :html, :js to your controller and create *.js.erb views in your app/views/ directory. Your controller will then be able to respond to javascript format and you can write javascript with ruby code in *.js.erb files.

Check this out: Unobtrusive javascript in Rails 3

Body:
Suppose you have a page with two columns of content. For whatever reason, you wish to retrieve the HTML content of one of those columns after the page has loaded, via an AJAX request.  The user does not need to take an action to make the content load (no link clicking or form submissions), it just happens automatically.

I can easily do this by returning an empty placeholder div in the main response

and then add a little jQuery to the page

$.ajax({
    url: "/elephants/dancing/pink",
    cache: false,
    success: function(html){
      $("#pink-dancing-elephants").append(html);
    }
});

and have the action that responses to /elephants/dancing/pink return the corresponding blob of HTML.

This all works fine, but I'm wondering if I'm missing some Rails3 feature that would make this easier.  E.g. I'm searching for the ability to be able to just put something like the following in the main view and have the rest of it happen by "magic"

<%= render :url=>"/elephants/dancing/pink", :remote => true %>

Am I missing something?


问:
Not able to run ansible playbook in ec2(host machine) to Mac(target machine)
My mac machine is communicating with an ec2 instance, SSH connection is established and when it's pinged ,I am getting a response as "pong", but when I run playbook facing below issue.

but when I run playbook getting below error:

```<code>PLAY [macserver] ***************************************************************

TASK [Gathering Facts] *********************************************************
fatal: [X.X.X.X]: FAILED! => {"msg": "Missing sudo password"}

PLAY RECAP *********************************************************************
X.X.X.X : ok=0 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
</code>```

running the playbook as ec2-user, also just to check if issue is with ec2-user added new user as "ansible" in my linux ec2 instance and started running playbook, but still same issue is persisting.
Also I have added ec2-user in sudoers file.

I tried alternative method to run playbook as specified below:

"ansible-playbook paybook.yml -k -K"

command to give password and run playbook,
in that scenario facing incorrect sudo password error. Whereas the password created for root, ec2-user and ansible all are same.
I am not able to figure out what and where I am missing, Can anyone help me with this?

答:
You are connecting your Mac from EC2. "Missing sudo password" is not of root/ec2-user of EC2 server but of the Mac. You need to provide username/password/sudo access etc of target machine

Regarding use of "ec2-user".
You can continue with ec2-user or ubuntu user, which is a default user for EC2 instance. However, it is always a good practice to create a new user(s) with restricted accesses and delete the default user.

Body:
My mac machine is communicating with an ec2 instance, SSH connection is established and when it's pinged ,I am getting a response as "pong", but when I run playbook facing below issue.

but when I run playbook getting below error:

PLAY [macserver] ***************************************************************

TASK [Gathering Facts] *********************************************************
fatal: [X.X.X.X]: FAILED! => {"msg": "Missing sudo password"}

PLAY RECAP *********************************************************************
X.X.X.X : ok=0 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0

running the playbook as ec2-user, also just to check if issue is with ec2-user added new user as "ansible" in my linux ec2 instance and started running playbook, but still same issue is persisting.
Also I have added ec2-user in sudoers file.

I tried alternative method to run playbook as specified below:

"ansible-playbook paybook.yml -k -K"

command to give password and run playbook,
in that scenario facing incorrect sudo password error. Whereas the password created for root, ec2-user and ansible all are same.
I am not able to figure out what and where I am missing, Can anyone help me with this?