问:
How to convert Top Row google sheet to index dataframe
sample not have ,header=0

```<code>dfGetMoniter = pd.DataFrame(data=gc.open("Data").worksheet("Moniter").get_all_values())

for index, row in dfGetMoniter.iterrows():

    print(index)
</code>```

out put

```<code>0
1
2
3
</code>```

but i want to show header Top Row of google sheet like this

```<code>A
B
C
D
</code>```

and i try put ,header=0 like pd.read_csv and got error

```<code>dfGetMoniter = pd.DataFrame(data=gc.open("Data").worksheet("Moniter").get_all_values(),header=0)

for index, row in dfGetMoniter.iterrows():

    print(index)
</code>```

```<code>E:\PycharmProjects\exsample\venv\Scripts\python.exe E:/PycharmProjects/exsample/BinanceTutorialVideo-master/now/sheetManager.py
Traceback (most recent call last):
  File "E:/PycharmProjects/exsample/BinanceTutorialVideo-master/now/sheetManager.py", line 16, in <module>
    dfGetMoniter = pd.DataFrame(data=gc.open("Data").worksheet("Moniter").get_all_values(),header=0)
TypeError: __init__() got an unexpected keyword argument 'header'

Process finished with exit code 1
</code>```

edit change

```<code>for col in dfGetMoniter.columns:
    print(col)
</code>```

not work

答:
A dataframe's columns are available from the columns attribute:

```<code>dfGetMoniter.columns

Index(['A', 'B', 'C', 'D'], dtype='object')
</code>```

```<code>for col in dfGetMoniter.columns:
    print(col)

A
B
C
D
</code>```

Take a look at the introductory tutorials.

Body:
sample not have ,header=0

dfGetMoniter = pd.DataFrame(data=gc.open("Data").worksheet("Moniter").get_all_values())

for index, row in dfGetMoniter.iterrows():

    print(index)

out put

0
1
2
3

but i want to show header Top Row of google sheet like this

A
B
C
D

and i try put ,header=0 like pd.read_csv and got error

dfGetMoniter = pd.DataFrame(data=gc.open("Data").worksheet("Moniter").get_all_values(),header=0)

for index, row in dfGetMoniter.iterrows():

    print(index)

E:\PycharmProjects\exsample\venv\Scripts\python.exe E:/PycharmProjects/exsample/BinanceTutorialVideo-master/now/sheetManager.py
Traceback (most recent call last):
  File "E:/PycharmProjects/exsample/BinanceTutorialVideo-master/now/sheetManager.py", line 16, in <module>
    dfGetMoniter = pd.DataFrame(data=gc.open("Data").worksheet("Moniter").get_all_values(),header=0)
TypeError: __init__() got an unexpected keyword argument 'header'

Process finished with exit code 1

edit change

for col in dfGetMoniter.columns:
    print(col)

not work

Body:
A dataframe's columns are available from the columns attribute:

dfGetMoniter.columns

Index(['A', 'B', 'C', 'D'], dtype='object')

for col in dfGetMoniter.columns:
    print(col)

A
B
C
D

Take a look at the introductory tutorials.


来源: stackexchange

问:
SingleTickerProviderStateMixin and custom mixin
I'm a bit of a newb with Flutter and Dart, and Google couldn't help me with this question.

Say I have this:

class _MapPageState extends BaseState<MapPage> with SingleTickerProviderStateMixin

I want to add another mixin (BasePage) on top of this that contains a reusable appbar, drawer, etc. The layout is described in this article.

I know this is not possible, and my IDE throws an error that tells me to integrate them, but I do not know how. Is there a solution? I need SingleTickerProviderStateMixin because it is required by an AnimationController I am using.

Here is the custom mixin code, if needed:

```<code>abstract class Base extends StatefulWidget {
  Base({Key key}) : super(key: key);
}

abstract class BaseState<Page extends Base> extends State<Page> {
  String screenName();
}

mixin BasePage<Page extends Base> on BaseState<Page> {

  MapFunctions functions = MapFunctions();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Guidey'),
          backgroundColor: Colors.deepOrangeAccent,
          centerTitle: true,
        ),
        drawer: Theme(
          data: Theme.of(context).copyWith(
            canvasColor: Colors.black.withOpacity(0.5)
          ),
          child: Drawer(
            child: ListView(
              padding: EdgeInsets.fromLTRB(40.0, 10.0, 40.0, 10.0),
              children: <Widget>[
                DrawerHeader(
                  child: Padding(
                    padding: EdgeInsets.fromLTRB(0, 35, 0, 0),
                    child: Text('Navigation', textAlign: TextAlign.center, style: TextStyle(fontSize: 20, color: Colors.white))
                  )
                ),
                ListTile(
                  title: Text('Profile', style: TextStyle(color: Colors.white)),
                  trailing: Icon(Icons.account_circle, color: Colors.white70),
                  onTap: (){
                    Navigator.of(context).pop();
                  },
                ),
                ListTile(
                  title: Text('Map', style: TextStyle(color: Colors.white)),
                  trailing: Icon(Icons.drive_eta, color: Colors.white70),
                  onTap: (){
                    Navigator.of(context).pop();
                  },
                ),
                ListTile(
                  title: Text('My Location', style: TextStyle(color: Colors.white)),
                  trailing: Icon(Icons.store, color: Colors.white70),
                  onTap: (){
                  },
                )
              ],
            )
          ),
        ),
    );
  }

  Widget body();
}
</code>```

答:
It turns out I was thinking too big, combining mixins can be done with a simple comma.

... with SingleTickProviderMixin, BasePageMixin

ContentLicense: CC BY-SA 4.0

Body:
I'm a bit of a newb with Flutter and Dart, and Google couldn't help me with this question.

Say I have this:

class _MapPageState extends BaseState<MapPage> with SingleTickerProviderStateMixin

I want to add another mixin (BasePage) on top of this that contains a reusable appbar, drawer, etc. The layout is described in this article.

I know this is not possible, and my IDE throws an error that tells me to integrate them, but I do not know how. Is there a solution? I need SingleTickerProviderStateMixin because it is required by an AnimationController I am using.

Here is the custom mixin code, if needed:

abstract class Base extends StatefulWidget {
  Base({Key key}) : super(key: key);
}

abstract class BaseState<Page extends Base> extends State<Page> {
  String screenName();
}

mixin BasePage<Page extends Base> on BaseState<Page> {

  MapFunctions functions = MapFunctions();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Guidey'),
          backgroundColor: Colors.deepOrangeAccent,
          centerTitle: true,
        ),
        drawer: Theme(
          data: Theme.of(context).copyWith(
            canvasColor: Colors.black.withOpacity(0.5)
          ),
          child: Drawer(
            child: ListView(
              padding: EdgeInsets.fromLTRB(40.0, 10.0, 40.0, 10.0),
              children: <Widget>[
                DrawerHeader(
                  child: Padding(
                    padding: EdgeInsets.fromLTRB(0, 35, 0, 0),
                    child: Text('Navigation', textAlign: TextAlign.center, style: TextStyle(fontSize: 20, color: Colors.white))
                  )
                ),
                ListTile(
                  title: Text('Profile', style: TextStyle(color: Colors.white)),
                  trailing: Icon(Icons.account_circle, color: Colors.white70),
                  onTap: (){
                    Navigator.of(context).pop();
                  },
                ),
                ListTile(
                  title: Text('Map', style: TextStyle(color: Colors.white)),
                  trailing: Icon(Icons.drive_eta, color: Colors.white70),
                  onTap: (){
                    Navigator.of(context).pop();
                  },
                ),
                ListTile(
                  title: Text('My Location', style: TextStyle(color: Colors.white)),
                  trailing: Icon(Icons.store, color: Colors.white70),
                  onTap: (){
                  },
                )
              ],
            )
          ),
        ),
    );
  }

  Widget body();
}


问:
Printing number of rows in Laravel
I am trying to print number of rows in Laravel from MySQL but i get this error:
htmlspecialchars() expects parameter 1 to be string, object given (View: C:\wamp64\www\kont\resources\views\profile.blade.php)

I have two function inside my model. First function returns information about user from one table and another function counts number of friends for that user from another table. Please view my code below:

HomeController.php

```<code>public function profile(Request $request,$id){
        $model = new UserModel();
 $podaciIzBaze = $model->userdata($id);
 $data = array();
 $data['dt'] = $podaciIzBaze;

$model2 = new UserModel();
 $podaciIzBaze2 = $model2->countfriends($id);

 $data['dt2'] = $podaciIzBaze2;

         return view('profile',$data);

    }
</code>```

UserModel.php

```<code>  class UserModel extends Model
    {
        //
        public function userdata($id){
            $query = DB::select("SELECT first_name,last_name,email,website,birth_date FROM users where id = $id");
            return $query;
        }

        public function countfriends($id){

            $query=DB::SELECT("SELECT count(user_id) from user_friend where user_id = $id");
            return $query;

        }
</code>```

profile.blade.php

```<code> @foreach($dt as $d)
                                 <tr>
                                    <td>Ime:</td>
                                    <td>{{ $d->first_name }}</td>
                                 </tr>
                                 <tr>
                                    <td>Prezime</td>
                                    <td>{{ $d->last_name }}</td>
                                 </tr>
                                 <tr>
                                    <td>Datum Rodjenja</td>
                                    <td>{{ $d->birth_date }}</td>
                                 </tr>
                                 <tr>
                                 <tr>
                                    <td>Pol</td>
                                    <td>Musko</td>
                                 </tr>
                                 <tr>
                                    <td>Email</td>
                                    <td><a href="mailto:info@support.com">{{ $d->email }}</a></td>
                                 </tr>
                                 <td>Website</td>
                                 <td>
                                   {{ $d->website }}
                                 </td>
                                 </tr>
                                     @endforeach

                       @foreach($dt2 as $d2)
                     Number of friends: {{ $d }}
                     @endforeach
</code>```

答:
In the second line

```<code>@foreach($dt2 as $d2)
    Number of friends: {{ $d }}  // Here it should be $d2
@endforeach
</code>```

It should be $d2 instead of $d.

Edit 1

Problem is with your second function countfriends($id). Use following code

```<code>$query=\DB::select("SELECT count(user_id) as friends from user_friend where user_id = $id");
</code>```

Then in view file use:

```<code>@foreach($dt2 as $d2)
    Number of friends: {{ $d2->friends }}
@endforeach
</code>```

When you were using select query it was returning the key "count(user_id)" which could not be used with standard object to print.

But you should start using Eloquent for queries instead of writing manual SQL queries.

Title: Printing number of rows in Laravel

Body:
I am trying to print number of rows in Laravel from MySQL but i get this error:
htmlspecialchars() expects parameter 1 to be string, object given (View: C:\wamp64\www\kont\resources\views\profile.blade.php)

I have two function inside my model. First function returns information about user from one table and another function counts number of friends for that user from another table. Please view my code below:

HomeController.php

public function profile(Request $request,$id){
        $model = new UserModel();
 $podaciIzBaze = $model->userdata($id);
 $data = array();
 $data['dt'] = $podaciIzBaze;

$model2 = new UserModel();
 $podaciIzBaze2 = $model2->countfriends($id);

 $data['dt2'] = $podaciIzBaze2;

         return view('profile',$data);

    }

UserModel.php

  class UserModel extends Model
    {
        //
        public function userdata($id){
            $query = DB::select("SELECT first_name,last_name,email,website,birth_date FROM users where id = $id");
            return $query;
        }

        public function countfriends($id){

            $query=DB::SELECT("SELECT count(user_id) from user_friend where user_id = $id");
            return $query;

        }

profile.blade.php

 @foreach($dt as $d)

                                    Ime:
                                    {{ $d->first_name }}

                                    Prezime
                                    {{ $d->last_name }}

                                    Datum Rodjenja
                                    {{ $d->birth_date }}

                                    Pol
                                    Musko

                                    Email
                                    {{ $d->email }}

                                 Website

                                   {{ $d->website }}

                                     @endforeach

                       @foreach($dt2 as $d2)
                     Number of friends: {{ $d }}
                     @endforeach

Body:
In the second line

@foreach($dt2 as $d2)
    Number of friends: {{ $d }}  // Here it should be $d2
@endforeach

It should be $d2 instead of $d.

Edit 1

Problem is with your second function countfriends($id). Use following code

$query=\DB::select("SELECT count(user_id) as friends from user_friend where user_id = $id");

Then in view file use:

@foreach($dt2 as $d2)
    Number of friends: {{ $d2->friends }}
@endforeach

When you were using select query it was returning the key "count(user_id)" which could not be used with standard object to print.

But you should start using Eloquent for queries instead of writing manual SQL queries.


问:
how to send data from angular to node.js
i need to pass some data from angular to node.js server. this is my angular postlist component:
    import { Component, OnInit } from '@angular/core';
    import { HttpClient } from "@angular/common/http";

```<code>@Component({
  selector: 'app-postlist',
  templateUrl: './postlist.component.html',
  styleUrls: ['./postlist.component.css']
})
export class PostlistComponent implements OnInit {

  constructor(private http: HttpClient) { }
  public data="test";
  ngOnInit(): void {
      this.http
        .post("http://localhost:3000/api/book",this.data);
  }

}
</code>```

my node.js server:

```<code>const express=require('express');
var app = express();
app.post('/api/book', function(req, res, next){
    var data = req.body.params;
    console.log(data);
 });
 app.listen(3000);
</code>```

i'm trying to console.log the data but nothing happens.

答:
you are missing .subscribe in your call. Change your code to  :-

```<code>  ngOnInit(): void {
      this.http
        .post("http://localhost:3000/api/book",this.data).subscribe();
  }
</code>```

and in nodejs just print req.body

Body:
i need to pass some data from angular to node.js server. this is my angular postlist component:
    import { Component, OnInit } from '@angular/core';
    import { HttpClient } from "@angular/common/http";

@Component({
  selector: 'app-postlist',
  templateUrl: './postlist.component.html',
  styleUrls: ['./postlist.component.css']
})
export class PostlistComponent implements OnInit {

  constructor(private http: HttpClient) { }
  public data="test";
  ngOnInit(): void {
      this.http
        .post("http://localhost:3000/api/book",this.data);
  }

}

my node.js server:

const express=require('express');
var app = express();
app.post('/api/book', function(req, res, next){
    var data = req.body.params;
    console.log(data);
 });
 app.listen(3000);

i'm trying to console.log the data but nothing happens.

Body:
you are missing .subscribe in your call. Change your code to  :-

  ngOnInit(): void {
      this.http
        .post("http://localhost:3000/api/book",this.data).subscribe();
  }

and in nodejs just print req.body


问:
Regex - how to exclude 4 digit number from wider numeric pattern
Really tried to browse and search if this specific question has been posted previously, so I hope I'm not asking an obvious one here.

My problem: I have a regex expression, with few different possible criteria for pattern matching separated by pipes. I'm OK with all of them except one, where I basically want to:

Find any expression which would be number between 4 and 6 digits (regardless of position in the string)

Exclude from this pattern expressions which would relate to years in this century (so starting with 20 and followed by two digits)

So for example, I would like to match: 4149, 20259, 202046, but would like to exclude 2019 as it will refer to a year and not the code I'm searching for.

Currently, I tried applying this one (only last part of the expression): |\d{4,6}?!20\d{2}) , but it's not working properly. I know that the expressions preceeding pipe are fine and was able to notice that \d{4,6} stops to work once I add the "exclusion" in this case, so I assume I'm not using the ?! properly. Could I ask you for an advice on this one?

Edit: Solved! Thank you very much for immediate answers (I was really positively surprised how fast there were few alternative solutions). Sorry I had to pick just one, all of others would be adjustable and viable for my needs, I just found this one most appealing and tailored for my needs.

答:
Where I'm not sure if word-boundaries are your best bet to indicate boundaries (maybe \D is better?), you could try:

```<code>\b(?!20\d\d\b)\d{4,6}\b
</code>```

See the Online Demo

\b - Word boundary.

(?!20\d\d\b) - Negative lookahead: No literal 20 followed by two digits and a word boundary.

\d{4,6} - Four to six digits.

\b - Word boundary.

Body:
Where I'm not sure if word-boundaries are your best bet to indicate boundaries (maybe \D is better?), you could try:

\b(?!20\d\d\b)\d{4,6}\b

See the Online Demo

\b - Word boundary.

(?!20\d\d\b) - Negative lookahead: No literal 20 followed by two digits and a word boundary.

\d{4,6} - Four to six digits.

\b - Word boundary.


问:
A very big sum - Hacker Rank
I am trying to solve "A very big sum" challenge on Hacker Rank: https://www.hackerrank.com/challenges/a-very-big-sum/problem

In there I have to sum all the numbers in the array given so I came up with two solutions:

First solution

```<code>function aVeryBigSum(ar){
  let sum = 0;
  for(let i = 0; i < ar.length; i++){
     sum += i;
   }
}
</code>```

Second Solution

```<code>function(ar){
 let sum = ar.reduce((accumulator, currentValue) => {
  accumulator + currentValue;
    });
}
</code>```

But none of them work and I don´t know why, I am thiniking maybe I am not writing it as Hacker Rank wants me to but I am not sure

答:
sum += i; should be sum += ar[i];

Also return sum

```<code>function aVeryBigSum(ar){
  let sum = 0;
  for(let i = 0; i < ar.length; i++){
     sum += ar[i];
  }
  return sum;
}
</code>```

Also reducer function should be like

```<code>function a(ar){
  let sum = (accumulator, currentValue) => accumulator + currentValue;
  return ar.reduce(sum);
}
</code>```

Title: A very big sum - Hacker Rank

Body:
I am trying to solve "A very big sum" challenge on Hacker Rank: https://www.hackerrank.com/challenges/a-very-big-sum/problem

In there I have to sum all the numbers in the array given so I came up with two solutions:

First solution

function aVeryBigSum(ar){
  let sum = 0;
  for(let i = 0; i < ar.length; i++){
     sum += i;
   }
}

Second Solution

function(ar){
 let sum = ar.reduce((accumulator, currentValue) => {
  accumulator + currentValue;
    });
}

But none of them work and I don´t know why, I am thiniking maybe I am not writing it as Hacker Rank wants me to but I am not sure

Body:
sum += i; should be sum += ar[i];

Also return sum

function aVeryBigSum(ar){
  let sum = 0;
  for(let i = 0; i < ar.length; i++){
     sum += ar[i];
  }
  return sum;
}

Also reducer function should be like

function a(ar){
  let sum = (accumulator, currentValue) => accumulator + currentValue;
  return ar.reduce(sum);
}


问:
CryptoStream: Why CryptoStreamMode.Write to encrypt and CryptoStreamMode.Read to decrypt?
Let e = 'password' and I am transforming it to 'as9kio0736' in a CryptoStream.

Let d = 'as9kio0736' and I am transforming it to 'password in a CryptoStream.

When I am transforming d back to 'password' why is it not considered writing in a CryptoStream?

```<code>using (MemoryStream msEncrypt = new MemoryStream()) {
    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) {
        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) {
            swEncrypt.Write(plainText);
        }
    }
}

using (MemoryStream msDecrypt = new MemoryStream(cipherText)) {
    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) {
        using (StreamReader srDecrypt = new StreamReader(csDecrypt)) {
            plaintext = srDecrypt.ReadToEnd();
        }
    }
}
</code>```

答:
CryptoStream gives the flexibility to read/write for both Encrypt and Decrypt.  For the case where the direction is fixed  it can be changed to move in either direction regardless of the implementation.

Here's a way to do it:

https://github.com/djpai/StreamConduit

ContentLicense: CC BY-SA 3.0

Body:
Let e = 'password' and I am transforming it to 'as9kio0736' in a CryptoStream.

Let d = 'as9kio0736' and I am transforming it to 'password in a CryptoStream.

When I am transforming d back to 'password' why is it not considered writing in a CryptoStream?

using (MemoryStream msEncrypt = new MemoryStream()) {
    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) {
        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) {
            swEncrypt.Write(plainText);
        }
    }
}

using (MemoryStream msDecrypt = new MemoryStream(cipherText)) {
    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) {
        using (StreamReader srDecrypt = new StreamReader(csDecrypt)) {
            plaintext = srDecrypt.ReadToEnd();
        }
    }
}


问:
Changing the logo in rails_admin
I'm loving the rails_admin plugin from https://github.com/sferik/rails_admin but I cant for the life of me get my custom logo to replace the installed one.

Anyone have any insight as to how to achieve this? I've tried overriding the css and rails_admin directory/fil structure but it doesnt pick my changes up.

Anyone got any insight as to how to get this resolved?

答:
You can copy the /app/views/layouts/rails_admin folder, located in the gem installation folder (bundle show rails_admin), into your project's app/views/layouts folder. Then you can modify the _header.html.erb partial, on the line:

```<code>span class="image_replacement"><%= @plugin_name %>
</code>```

Hope this helps

ContentLicense: CC BY-SA 2.5

Title: Changing the logo in rails_admin

Body:
You can copy the /app/views/layouts/rails_admin folder, located in the gem installation folder (bundle show rails_admin), into your project's app/views/layouts folder. Then you can modify the _header.html.erb partial, on the line:

span class="image_replacement"><%= @plugin_name %>

Hope this helps


问:
SSL context in mongo:client attribute using spring xml config
How to add SSL key store and trust store file path and password in mongo:client options using spring xml to connect mongo db on TLS . Also need to know how to add ssl invalid host name allowed in mongo:client attribute in xml. I am using spring data mongo db 2.2.3 .</p>

答:
This is not XML solution, but via Bean.
This is what I did for 2.2.5.RELEASE. Note that for 2.3.0, there is no MongoClientOptions</p>

```<code>    @Value("classpath:truststore/mongoserver-truststore.p12")
    private Resource trustStore;

    @Value("${ssl.truststore.mongodb.password}")
    private String mongoTrustStorePassword;

    @Bean
    public MongoClientOptions mongoClientOptions() throws Exception {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(trustStore.getInputStream(), mongoTrustStorePassword.toCharArray());

        trustManagerFactory.init(keyStore);

        SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
        return MongoClientOptions.builder()
                .sslEnabled(true)
                .sslContext(sslContext)
                .sslInvalidHostNameAllowed(true)
                .build();
    }
</code>```

Body:
This is not XML solution, but via Bean.
This is what I did for 2.2.5.RELEASE. Note that for 2.3.0, there is no MongoClientOptions

    @Value("classpath:truststore/mongoserver-truststore.p12")
    private Resource trustStore;

    @Value("${ssl.truststore.mongodb.password}")
    private String mongoTrustStorePassword;

    @Bean
    public MongoClientOptions mongoClientOptions() throws Exception {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(trustStore.getInputStream(), mongoTrustStorePassword.toCharArray());

        trustManagerFactory.init(keyStore);

        SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
        return MongoClientOptions.builder()
                .sslEnabled(true)
                .sslContext(sslContext)
                .sslInvalidHostNameAllowed(true)
                .build();
    }


问:
Parsing JSON Data Swift "Thread 4: Fatal error: Unexpectedly found nil while unwrapping an Optional value"
I am trying to parse some JSON data returned from an API call. The path I want to navigate is media > faces > points. I can navigate to faces but getting points is the issue.

here is code

```<code>
let dictionary = try JSONSerialization.jsonObject(with: data!, options:.mutableContainers) as? [String:Any]

let media = dictionary!["media"] as? [String: Any]
print(media!["faces"]) // Works see the returned data below
let faces = media!["faces"] as? [String: Any]
print(faces!["points"]) // Thread 4: Fatal error: Unexpectedly found nil while unwrapping an Optional value

</code>```

API returned data for print(media!["faces"])

```<code>{
    angle = "1.2222";
    "appearance_id" = 0;
    "detection_score" = 1;
    duration = "00:00:00";
    "face_uuid" = "78338d20-9ced-11ea-b153-0cc47a6c4dbd";
    height = "74.31999999999999";
    "media_uuid" = "fec83ac3-de00-44f0-ad5b-e1e990a29a8c";
    "person_id" = "";
    points =     (
                {
            name = "basic eye left";
            type = 512;
            x = "85.16";
            y = "86.62";
        },
                {
            name = "basic eye right";
            type = 768;
            x = "110.92";
            y = "86.66";
        }
</code>```

答:
Since you are a beginner I'm helping you out. These questions have been asked many times (There is a high chance you get duplicate flag). Here is how you avoid these kinds of errors, try not to use force-unwraps (this symbol !) anywhere without any exception to avoid these errors. Instead of if let you can use guard let, it's a personal choice.

if let data = data,
    let dictionary = try JSONSerialization.jsonObject(with: data, options:.mutableContainers) as? [String: Any],
    let media = dictionary["media"] as? [String: Any],
    let faces = media["faces"] as? [[String: Any]],
    let points = faces[0]["points"] {
    print(points)
}
```

<p>Edit: Since <code>"faces"</code> parameter is an array you need to parse them as an <code>Array</code> and not as <code>Dictionary</code>. The above example shows how to get to the first set of <code>"points"</code>.</p>

<p>Update: Better approach would be to use <code>JSONDecoder</code>. Here's how:
Create this struct outside the class:</p>

<pre class="lang-swift prettyprint-override"><code>struct Response: Codable { var media: Media }
struct Media: Codable { var faces: [Face] }
struct Face: Codable { var points: [Point] }
struct Point: Codable { }
</code>```

And then decode like this:

if let data = data,
    let response = try JSONDecoder().decode(Response.self, from: data) {
    print(response.media.faces[0].points)
}
```

Body:
I am trying to parse some JSON data returned from an API call. The path I want to navigate is media > faces > points. I can navigate to faces but getting points is the issue.

here is code

let dictionary = try JSONSerialization.jsonObject(with: data!, options:.mutableContainers) as? [String:Any]

let media = dictionary!["media"] as? [String: Any]
print(media!["faces"]) // Works see the returned data below
let faces = media!["faces"] as? [String: Any]
print(faces!["points"]) // Thread 4: Fatal error: Unexpectedly found nil while unwrapping an Optional value

API returned data for print(media!["faces"])

{
    angle = "1.2222";
    "appearance_id" = 0;
    "detection_score" = 1;
    duration = "00:00:00";
    "face_uuid" = "78338d20-9ced-11ea-b153-0cc47a6c4dbd";
    height = "74.31999999999999";
    "media_uuid" = "fec83ac3-de00-44f0-ad5b-e1e990a29a8c";
    "person_id" = "";
    points =     (
                {
            name = "basic eye left";
            type = 512;
            x = "85.16";
            y = "86.62";
        },
                {
            name = "basic eye right";
            type = 768;
            x = "110.92";
            y = "86.66";
        }

Body:
Since you are a beginner I'm helping you out. These questions have been asked many times (There is a high chance you get duplicate flag). Here is how you avoid these kinds of errors, try not to use force-unwraps (this symbol !) anywhere without any exception to avoid these errors. Instead of if let you can use guard let, it's a personal choice.

if let data = data,
    let dictionary = try JSONSerialization.jsonObject(with: data, options:.mutableContainers) as? [String: Any],
    let media = dictionary["media"] as? [String: Any],
    let faces = media["faces"] as? [[String: Any]],
    let points = faces[0]["points"] {
    print(points)
}

Edit: Since "faces" parameter is an array you need to parse them as an Array and not as Dictionary. The above example shows how to get to the first set of "points".

Update: Better approach would be to use JSONDecoder. Here's how:
Create this struct outside the class:

struct Response: Codable { var media: Media }
struct Media: Codable { var faces: [Face] }
struct Face: Codable { var points: [Point] }
struct Point: Codable { }

And then decode like this:

if let data = data,
    let response = try JSONDecoder().decode(Response.self, from: data) {
    print(response.media.faces[0].points)
}


问:
How can i read this type of json objects in a my sql table

I have this type of json data in a mysql table. how can i read them

[
    {
        "price": "1000",
        "itemcode": "1",
        "itemname": "Break Pads",
        "quantity": "1"
    },
    {
        "price": "800",
        "itemcode": "3",
        "itemname": "Break Oil",
        "quantity": "1"
    }
]
```

答:
A workaround emulating JSON_TABLE(), which exists in version 8.0, might be given for DB 5.7 as

```<code>SELECT JSON_UNQUOTE(JSON_EXTRACT(jsdata, CONCAT('$[',@rn+1,'].price'))) AS price,
       JSON_UNQUOTE(JSON_EXTRACT(jsdata, CONCAT('$[',@rn+1,'].itemcode'))) AS itemcode,
       JSON_UNQUOTE(JSON_EXTRACT(jsdata, CONCAT('$[',@rn+1,'].itemname'))) AS itemname,
       JSON_UNQUOTE(JSON_EXTRACT(jsdata, CONCAT('$[',@rn+1,'].quantity'))) AS quantity,
       @rn :=  @rn + 1 as rn
  FROM tab
 CROSS JOIN (SELECT @rn := -1
               FROM information_schema.tables) AS iter
 WHERE @rn < JSON_LENGTH(JSON_EXTRACT(jsdata, '$[*]')) - 1
</code>```

Demo

Body:
A workaround emulating JSON_TABLE(), which exists in version 8.0, might be given for DB 5.7 as

SELECT JSON_UNQUOTE(JSON_EXTRACT(jsdata, CONCAT('$[',@rn+1,'].price'))) AS price,
       JSON_UNQUOTE(JSON_EXTRACT(jsdata, CONCAT('$[',@rn+1,'].itemcode'))) AS itemcode,
       JSON_UNQUOTE(JSON_EXTRACT(jsdata, CONCAT('$[',@rn+1,'].itemname'))) AS itemname,
       JSON_UNQUOTE(JSON_EXTRACT(jsdata, CONCAT('$[',@rn+1,'].quantity'))) AS quantity,
       @rn :=  @rn + 1 as rn
  FROM tab
 CROSS JOIN (SELECT @rn := -1
               FROM information_schema.tables) AS iter
 WHERE @rn < JSON_LENGTH(JSON_EXTRACT(jsdata, '$[*]')) - 1

Demo


问:
Preventing SQL Injection for online SQL querying
I have a small Python project site where a visitor can practice writing SQL code.  This code actually runs and returns values.  I know that I need to prevent SQL injection, but I'm not sure the best approach since the purpose of the site is that users should be able to write and execute  arbitrary SQL code against a real database.

What should I look to do to prevent malicious behavior?  I want to prevent statements such as DROP xyz;, but users should still be able to execute code.  I think maybe the ideal solution is that users can only "read" from the database, ie. they can only run SELECT statements (or variations).  But I'm not sure if "read only" captures all edge cases of malicious behavior.

Need to prevent malicious SQL querying, but also need to allow users to execute code

Using SQLite now but will probably move to postgres

I'm strictly using SQL at this point but may want to add Python and other languages in the future

The site is built with Python (Flask)

Any ideas or suggestions would be helpful

答:
There is no way to prevent SQL injection for a site that takes SQL statements as user input and runs them verbatim. The purpose of the site is SQL injection. The only way you can prevent SQL injection is to not develop this site.

If you do develop the site, how can you prevent malicious SQL? Answer: don't let malicious users have access to this site. Only allow trusted users to use it.

Okay, I assume you do want to develop the site and you do want to allow all users, without doing a lot of work to screen them.

Then it becomes a task of limiting the potential damage they can do. Restrict their privileges carefully, so they only have access to create objects and run queries in a specific schema.

Or better yet, launch a Docker container for each individual to have their own private database instance, and restrict the CPU and memory the container can use.


问:
Google Maps API GroundOverlay Complete Event
is there a way to, w/ google maps v3, listen to an event that will indicate a groundoverlay asset has been loaded?  I'm loading an image onto the map and would like to be notified when the asset has completed downloading and has been presented to the client.  Any ideas?</p>

Body:
A straight reading of the Google Maps API v3 documentation would seem to suggest that this wouldn't work, but I've managed to do this using the idle event with addListenerOnce().  (If that doesn't work for you, edit your question to show the code you tried and we'll see if we can get it working.)

The idle event seems to fire exactly once as a way of sort of saying "map is loaded and ready to go" even though the documentation seems to suggest that a pan or zoom needs to happen to trigger it.

Since this is (to my knowledge) undocumented behavior (at least in any official documentation), it runs the risk of suddenly not working one day when the API is updated.  You can make the choice to either live with that risk or try to guard against it by specifying the version of the API that you want in your <script> tag that loads the API.


问:
How to connect IKS environment using external Rundeck?
I'm using external Rundeck present outside  IKS usually  we login to ibmcloud and then access IKS. But I need to access IKS environment with service account (cert & token). Is that possible?
if yes how I can store this kubeconfig temporarily without storing it in .kube/config </p>

答:
Create a 'Service ID' and within the service id create an 'API Key'
- Login to the ibmcloud console and choose Manage > Access (IAM)
- Create a Service ID
- Add the Access polices, by clicking the associated panel and then add policies
- Choose the API keys panel and click on create

I do not know what you mean to 'store temporarily'. But then the script can login using this api key in your script and config kubectl:

ibmcloud login --aipkey 6JaR7NOTAREALKEYPc-E01i-mlwc7_8zd29foobar2NA -g yourgroup
ibmcloud ks cluster config --cluster yourcluster
kubectl ...


问:
How to remove user mentions and urls in a tweet/string using python
So I want to remove all user mentions and urls in a tweet/string.

For example, if I have a tweet like this:

```<code>@username1: some tweet here, http://www.url.com, aaaaa @username2
</code>```

I want to get something like this:

```<code>some tweet here, aaaaa
</code>```

I want to user regular expression but I'm really new to python and don't know how to do it.

Also, tweets are stored in a JSON file (a list of dictionaries), and each tweet (a dictionary) has a key called "entities" which stores information about "user_mentions", "urls", and "hashtags" in a format like the following:

```<code>{u'user_mentions': [{u'indices': [3, 18],
                     u'screen_name': u'username1',
                     u'id': 1234567,
                     u'name': u'user name 1',
                     u'id_str': u'1234567'},

                    {u'indices': [108, 116],
                     u'screen_name': u'username2',
                     u'id': 112233,
                     u'name': u'user name 2',
                     u'id_str': u'112233'}],

 u'hashtags': [],
 u'urls': [{u'url': u'http://www.url.com',
            u'indices': [83, 103],
            u'expanded_url': u'http://www.url.com',
            u'display_url': u'http://www.url.com'}]
}
</code>```

Does anyone know how to remove user mentions and urls?
Thanks so much!

答:
You can combine this onto a one-liner as well but here is a the break-down of the steps:

```<code>text = '@username1: some tweet here, http://www.url.com, aaaaa @username2'
processed_text = re.sub(r"(?:\@|http?\://|https?\://|www)\S+", "", text)
processed_text = " ".join(processed_text.split())
print(processed_text)
</code>```

Output:

```<code>some tweet here, aaaaa
</code>```

Body:
So I want to remove all user mentions and urls in a tweet/string.

For example, if I have a tweet like this:

@username1: some tweet here, http://www.url.com, aaaaa @username2

I want to get something like this:

some tweet here, aaaaa

I want to user regular expression but I'm really new to python and don't know how to do it.

Also, tweets are stored in a JSON file (a list of dictionaries), and each tweet (a dictionary) has a key called "entities" which stores information about "user_mentions", "urls", and "hashtags" in a format like the following:

{u'user_mentions': [{u'indices': [3, 18],
                     u'screen_name': u'username1',
                     u'id': 1234567,
                     u'name': u'user name 1',
                     u'id_str': u'1234567'},

                    {u'indices': [108, 116],
                     u'screen_name': u'username2',
                     u'id': 112233,
                     u'name': u'user name 2',
                     u'id_str': u'112233'}],

 u'hashtags': [],
 u'urls': [{u'url': u'http://www.url.com',
            u'indices': [83, 103],
            u'expanded_url': u'http://www.url.com',
            u'display_url': u'http://www.url.com'}]
}

Does anyone know how to remove user mentions and urls?
Thanks so much!

Body:
You can combine this onto a one-liner as well but here is a the break-down of the steps:

text = '@username1: some tweet here, http://www.url.com, aaaaa @username2'
processed_text = re.sub(r"(?:\@|http?\://|https?\://|www)\S+", "", text)
processed_text = " ".join(processed_text.split())
print(processed_text)

Output:

some tweet here, aaaaa


问:
Error in Postman: Error: write EPROTO 8768:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:
During request GET in Postman (https://localhost:9001/test)
I've received an error:

Error: write EPROTO 8768:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:c:\users\administrator\buildkite-agent\builds\pm-electron\postman\electron-release\vendor\node\deps\openssl\openssl\ssl\record\ssl3_record.c:252:

Warning: This request did not get sent completely and might not have all the required system headers.

Postman Configuration:

SSL certificate verification is disabled;

Proxy configuration - Default Proxy Configuration and Proxy configurations for sending requests are disabled;

Request timeout in ms - 0.

答: For Localhost we don't really need https, please try with http://localhost:9001/test</p>


问:
Hashcat | md5(md5($salt).md5($pass))
I have a problem with hashcat, I was looking for Hash-Mode for a hash type

```<code>MD5(MD5($Salt).MD5($Password))
</code>```

and I didn't find that Hash-Mode, I found only Hash-Mode 3910

```<code>md5(md5($pass).md5($salt))
</code>```

but this is not what I need, there is a hash-mode that is suitable for cracking this type of hash what I mentioned?

答:
You could try filing a Github issue to get the format supported.

Or you could try adding the format on your own? As suggested by another forum post which links to this git commit as an example. But this may be more effort that you planned to put into cracking your hash.

Title: Hashcat | md5(md5($salt).md5($pass))

Body:
I have a problem with hashcat, I was looking for Hash-Mode for a hash type

MD5(MD5($Salt).MD5($Password))

and I didn't find that Hash-Mode, I found only Hash-Mode 3910

md5(md5($pass).md5($salt))

but this is not what I need, there is a hash-mode that is suitable for cracking this type of hash what I mentioned?


问:
Help Evaluating Build Tools
I'm already familiar with and use Ant & Maven, at this point I'd like to branch out to another tool and I'm deciding between 'Buildr' and 'Gradle'. I'd appreciate insight/feedback from those that have either used one or both of these tools, because quite frankly at this point the only real difference to me seems to be ruby vs groovy (and I am comfortable with and enjoy both). I'd also appreciate answers to the following:

I understand that Buildr allows for downloading and extracting dependencies that are NOT in a maven type repo, does Gradle offer the same feature?

Can Buildr/Gradle be used to build other language source code -- i.e. groovy, ruby, actionscript/flex, c family, etc.?

How well integrated are Buildr/Gradle with Hudson or Jenkins?

答:
We recently evaluated Gradle, Buildr and Maven 2 as alternatives to our current mix of Ant and homegrown Ant-wrappers and ended up settling on Gradle. Technically speaking we found them (Buildr and Gradle) to be very similar and the reasons for our decision ended up being non-technical:

Gradle = Groovy = Java! If you have a team of java developers the argument for being able to express build logic in a language anyone can contribute to is hard to beat... which is not a judgement on Ruby - just a consideration of what development resources are available. Groovy Closures require some getting used to but I have found it pretty fun to learn.

Commercial support - this may or may not be important to your case, but in ours it was a defining factor. Gradle is commercially supported by Gradleware

User adoption / popularity (mainstreamness) - for the issues that we ran into, it was easier to find answers to questions about Gradle than Buildr.

That said... I am still pretty confident either one would have supported our multi-project builds. Maven 2 would have been acceptable if we were starting from scratch, but we have a lot of quirks and odd project structures to manage which make it hard to be productive from day 1... the transition requirements made Maven 2 prohibitively expensive.

Hope that helps and good luck!

Title: Help Evaluating Build Tools


问:
How to add the connected SQL Server database to the solution folder?
I've created a small ASP.NET MVC application and used a SQL Server database. I saw that the database was not moved to the Solution folder, so if understood correctly, the application won't work on other computers/servers.

Is it possible to move somehow the database to the project without losing the connection with the application?

Please help! Thanks in advance!

Answer:

The problem was solved with the solution from

https://www.codeproject.com/Questions/441590/How-to-add-existing-database-in-app-data-folder-in

答:
No. Seriously. ANY serious setup will have a database server and somone will apply a backup of the database you provide there. Unless you write toy applications, you NEVER employ the databsae on the same machine and "in the folder" - this works for development, it is not how SQL is deployed in the real world of larger controlled applications.

And get used on how to make upgrades to that database via some sort of change script mechanism.


问:
AWS cannot signed CloudFront urls PEM error
I'm using NodeJS to get a signed URL from Cloudfront... I have the credentials to get them but I'm always getting an error, it tells me the credentials are wrong, I'm using this library.

aws-cloudfront-sign

```<code>var cfsign = require('aws-cloudfront-sign');

var signingParams = {
  keypairId: process.env.PUBLIC_KEY,
  privateKeyString: process.env.PRIVATE_KEY,
  expireTime: 1426625464599
}

// Generating a signed URL
var signedUrl = cfsign.getSignedUrl(
  'http://example.cloudfront.net/image.png',
  signingParams
);
</code>```

Obviously I have replaced example.cloudfront with the name of my distribution

答:
Solved.. you must add the break lines with \n in a variable</p>

```<code>const pk = "-----BEGIN RSA PRIVATE KEY-----\nABDECASFAFSAS\n
</code>```

Body:
I'm using NodeJS to get a signed URL from Cloudfront... I have the credentials to get them but I'm always getting an error, it tells me the credentials are wrong, I'm using this library.

aws-cloudfront-sign

var cfsign = require('aws-cloudfront-sign');

var signingParams = {
  keypairId: process.env.PUBLIC_KEY,
  privateKeyString: process.env.PRIVATE_KEY,
  expireTime: 1426625464599
}

// Generating a signed URL
var signedUrl = cfsign.getSignedUrl(
  'http://example.cloudfront.net/image.png',
  signingParams
);

Obviously I have replaced example.cloudfront with the name of my distribution

Body:
Solved.. you must add the break lines with \n in a variable

const pk = "-----BEGIN RSA PRIVATE KEY-----\nABDECASFAFSAS\n


问:
Access to fetch at 'https://randomuser.me/api/?results=4' from origin 'http://localhost:3000' has been blocked by CORS policy:
I keep getting this in my console and i don't understand, please can somebody help me and explain.
Access to fetch at 'https://randomuser.me/api/?results=4' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.</p>

答:
To be able to allow API Proxy within a react app - You need to edit the package.json with the following

```<code>"proxy": "https://randomuser.me",
</code>```

More details can be found on the create-react-dev docs

Body:
To be able to allow API Proxy within a react app - You need to edit the package.json with the following

"proxy": "https://randomuser.me",

More details can be found on the create-react-dev docs


问:
Perl: match against a large array
Say I have $sentence = "The quick brown fox jumps over the lazy dog" and an array @targets = qw(brown red black lazy quick);.

The goal is to find out all words in @targets that contains in the $sentence, in this case, it's this three words: brown lazy quick.

Note: The @targets array could be very large, like there could be 10,000 elements in it. And there could be 10,000 $sentences to deal with.

Is there an efficient and elegant way to do it?

答:
Using Algorithm::AhoCorasick::XS, which does very efficient searches for multiple strings:

```<code>#!/usr/bin/env perl
use strict;
use warnings;
use feature qw/say/;
use Algorithm::AhoCorasick::XS;

my @targets = qw(brown red black lazy quick);
my $matcher = Algorithm::AhoCorasick::XS->new(\@targets);

my @sentences = (
    "The quick brown fox jumps over the lazy dog",
    "The man in black fled across the desert and the gunslinger followed."
);

for my $sentence (@sentences) {
    my @matches = $matcher->matches($sentence); # Or unique_matches
    say "@matches" if @matches;
}
</code>```

Example:

```<code>$ perl demo.pl
quick brown lazy
black
</code>```

Title: Perl: match against a large array

Body:
Using Algorithm::AhoCorasick::XS, which does very efficient searches for multiple strings:

#!/usr/bin/env perl
use strict;
use warnings;
use feature qw/say/;
use Algorithm::AhoCorasick::XS;

my @targets = qw(brown red black lazy quick);
my $matcher = Algorithm::AhoCorasick::XS->new(\@targets);

my @sentences = (
    "The quick brown fox jumps over the lazy dog",
    "The man in black fled across the desert and the gunslinger followed."
);

for my $sentence (@sentences) {
    my @matches = $matcher->matches($sentence); # Or unique_matches
    say "@matches" if @matches;
}

Example:

$ perl demo.pl
quick brown lazy
black


问:
Google Apps Script: Multiple recipients in GmailApp?
Can I email multiple recipients through GmailApp.sendEmail()? I've tried storing the recipient addresses as an array, but it doesn't seem to send any of them.

Thanks!

答:
When I have multiple addresses, I just reference the list via a range.  The below script sample would send to 5 email addresses pulled from C2:C6 on the sheet/tab named Email.  </p>

```<code>    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var emailRange = ss.getSheetByName("Email").getRange(2,3,5,1);
    var emailAddress = emailRange.getValues();
      Logger.log(emailAddress);
    var message = 'Message you wish to enter';
    var subject = 'Verbiage for Subject Line';
   GmailApp.sendEmail(emailAddress, subject, message)
</code>```

Body:
When I have multiple addresses, I just reference the list via a range.  The below script sample would send to 5 email addresses pulled from C2:C6 on the sheet/tab named Email.

    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var emailRange = ss.getSheetByName("Email").getRange(2,3,5,1);
    var emailAddress = emailRange.getValues();
      Logger.log(emailAddress);
    var message = 'Message you wish to enter';
    var subject = 'Verbiage for Subject Line';
   GmailApp.sendEmail(emailAddress, subject, message)


问:
Get CPU load in python on Raspberry Pi doesn't work
I have googled for code to get the CPU load on RPi3. I found this code:

```<code>import os

def getCPUuse():
    return str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip())
</code>```

For me it only returns an empty string.

Where is the problem in this code?

EDIT:

I call it like this:

```<code>while True:
    time.sleep(0.2)
    use = getCPUuse()
    print(use)
</code>```

答: Take off the strip() and just do readline. That worked for me.

Body:
I have googled for code to get the CPU load on RPi3. I found this code:

import os

def getCPUuse():
    return str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip())

For me it only returns an empty string.

Where is the problem in this code?

EDIT:

I call it like this:

while True:
    time.sleep(0.2)
    use = getCPUuse()
    print(use)


问:
Is it undefined behaviour to have a reference to freed memory?
In C++, is it undefined behaviour to free memory that is still referred to by a reference, even if that reference is not used again? For example, does the following function invoke undefined behaviour?</p>

```<code>void foo() {
    std::map<std::string, int> mymap;
    {
        int& val = mymap["eight"];
        val = 8;
        mymap.erase("eight"); // Oops! val still refers to mymap["eight"]
        // val is not used again
    }
    std::cout << "Entry count: " << mymap.size() << "\n";
}
</code>```

答:
Is it undefined behaviour to have a reference to freed memory?

The standard doesn't define any behaviour for "having" any value of any type.

```<code>mymap.erase("eight"); // Oops! val still refers to mymap["eight"]
</code>```

This is what the standard says about behaviour of erase:

[associative.reqmts] ... The erase members shall invalidate ... references to the erased elements ...

Note that the rule does not say that behaviour is undefined if those references exist. In fact, it would be rather pointless to describe that those references are invalidated if the existence of the reference would always imply undefined behaviour.

As for definition of what an invalid reference is... the standard appears to be lacking. There is a definition for invalid pointer, but I cannot find any for invalid reference. This lack of definition could be considered to be a defect in the standard.

Body:
In C++, is it undefined behaviour to free memory that is still referred to by a reference, even if that reference is not used again? For example, does the following function invoke undefined behaviour?

void foo() {
    std::map<std::string, int> mymap;
    {
        int& val = mymap["eight"];
        val = 8;
        mymap.erase("eight"); // Oops! val still refers to mymap["eight"]
        // val is not used again
    }
    std::cout << "Entry count: " << mymap.size() << "\n";
}

Body:
Is it undefined behaviour to have a reference to freed memory?

The standard doesn't define any behaviour for "having" any value of any type.

mymap.erase("eight"); // Oops! val still refers to mymap["eight"]

This is what the standard says about behaviour of erase:

[associative.reqmts] ... The erase members shall invalidate ... references to the erased elements ...

Note that the rule does not say that behaviour is undefined if those references exist. In fact, it would be rather pointless to describe that those references are invalidated if the existence of the reference would always imply undefined behaviour.

As for definition of what an invalid reference is... the standard appears to be lacking. There is a definition for invalid pointer, but I cannot find any for invalid reference. This lack of definition could be considered to be a defect in the standard.


问:
Xcode/Swift 'filename used twice' build error
I'm new to Swift and am struggling with an error after I have (possibly) correctly installed a 3rd party framework via CocoaPods.

The error is as follows.

```<code><unknown>:0: error: filename "MainController.swift" used twice: '/Users/myname/Desktop/ProjectName/ProjectName/Controllers/MainController.swift' and '/Users/myname/Desktop/ProjectName/ProjectName/Controllers/MainController.swift'
<unknown>:0: note: filenames are used to distinguish private declarations with the same name
Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1
</code>```

As far as I can gather from other forums and seemingly obvious is that I have to remove one of the files being used twice. However I can't see where they would be installed twice. If I remove the file from the /Controllers folder the error becomes 'file not found' etc.

So my question is, where would these conflicting files be located and how do I safely remove one of them? Or is it more that there is only one file but it is being used twice - in which case how do I stop that?

Many thanks.

Ok I feel that comments are getting lost so am clarifying here to see if can trigger an answer as not been able to build and run this since yesterday.

I now have only the swift files in the Pods->Pods/MainController folder.

When I build I get a file not found. However the file it is looking for is in App->Controllers folder which is where I deleted it from. If I put the file in there I get the 'used twice' error.

So how do I stop it trying to find the file in the Controllers and look for it in the Pods?

Thanks

答:
I just ran into this issue myself. It was the first time that I was adding a new target to a project.

When you're adding a new target you should click on an existing target and attempt to DUPLICATE it.

You shouldn't create the target from the same template. As that would add a new AppDelegate, ViewController, SceneDelegate, plist, Main.Storyboard and Assets. It would basically add everything that template gives and your project now has 2 of each of those fails. If you then go and add the target to the existing AppDelegate then you'll get the error mentioned. The fix is to:

Delete all duplicate files

As Franck said: Check the file is not included twice in the target's "Build Phases" "Compile Sources" settings. It can happen when you merge project.pbxproj.

If you duplicate, then all you get is a new target and a plist. Once you get those then for every existing file you need to go in its file inspector and add the new target to the list of its targets.

Body:
I'm new to Swift and am struggling with an error after I have (possibly) correctly installed a 3rd party framework via CocoaPods.

The error is as follows.

<unknown>:0: error: filename "MainController.swift" used twice: '/Users/myname/Desktop/ProjectName/ProjectName/Controllers/MainController.swift' and '/Users/myname/Desktop/ProjectName/ProjectName/Controllers/MainController.swift'
<unknown>:0: note: filenames are used to distinguish private declarations with the same name
Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1

As far as I can gather from other forums and seemingly obvious is that I have to remove one of the files being used twice. However I can't see where they would be installed twice. If I remove the file from the /Controllers folder the error becomes 'file not found' etc.

So my question is, where would these conflicting files be located and how do I safely remove one of them? Or is it more that there is only one file but it is being used twice - in which case how do I stop that?

Many thanks.

Ok I feel that comments are getting lost so am clarifying here to see if can trigger an answer as not been able to build and run this since yesterday.

I now have only the swift files in the Pods->Pods/MainController folder.

When I build I get a file not found. However the file it is looking for is in App->Controllers folder which is where I deleted it from. If I put the file in there I get the 'used twice' error.

So how do I stop it trying to find the file in the Controllers and look for it in the Pods?

Thanks


问:
Terraform and AWS: modify an existing policy
I have an existing IAM policy attached to a role. Each time a new secret is created in the Secrets Manager, I need to append the new ARN to the policy. Can this be done with Terraform? I've managed to import the policy into the terraform.state file, but I don't know how to:
1) Append a new ARN inside the "Resources" list
2) Push the change to AWS

This is how the policy looks now:

```<code>{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Action": "secretsmanager:GetSecretValue",
        "Resource": [
            "SECRET_ARN_1",
            "SECRET_ARN_2",
            "SECRET_ARN_3"
        ]
    },
    {
        "Effect": "Allow",
        "Action": "kms:Decrypt",
        "Resource": "KMS_ARN"
    }
]
</code>```

}

And this is how I need it to look:

```<code>{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Action": "secretsmanager:GetSecretValue",
        "Resource": [
            "SECRET_ARN_1",
            "SECRET_ARN_2",
            "SECRET_ARN_3",
            "MY_BRAND_NEW_SECRET_ARN"
        ]
    },
    {
        "Effect": "Allow",
        "Action": "kms:Decrypt",
        "Resource": "KMS_ARN"
    }
]
</code>```

}

The following import is working by importing the existing policy to the object aws_iam_policy.mysimplepolicy, but I don't know how to proceed from here.

```<code>terraform import aws_iam_policy.mysimplepolicy <MY_POLICY_ARN>
</code>```

答:
It sounds like you've already figured out how to import the policy in to your state. Now you need to define the resource in your Terraform code so it matches the policy.

First, define variables for the ARNs:

```<code>variable "secret_arns" {
    description = "A list of secret manager ARNs that the IAM policy should permit access to."
    type        = list(string)
}

variable "kms_key_arns" {
    description = "A list of KMS Key ARNs that the IAM policy should permit access to."
    type        = list(string)
}
</code>```

Next, define the policy document as a data source, using the variables:

```<code>data "aws_iam_policy_document" "secret_access" {
    statement {
        sid       = "SecretsAccess"
        actions   = ["secretsmanager:GetSecretValue"]
        resources = var.secret_arns
        effect    = "Allow"
    }
    statement {
        sid       = "KMSAccess"
        actions   = "kms:Decrypt"
        resources = var.kms_key_arns
        effect    = "Allow"
    }
}
</code>```

Now create a policy using the data source:

```<code>resource "aws_iam_policy" "mysimplepolicy" {
  name   = "MySimplePolicy"  # Make sure this has the name you want
  policy = data.aws_iam_policy_document.secret_access.json
}
</code>```

Finally, when you call the code, pass in the ARNs in your variables using whatever method you prefer. It could be from a terraform.tfvars file or on the command line using the -var syntax or as output from another Terraform module that creates the secrets. For example:

```<code>terraform apply -var='secret_arns=["arn1", "arn2", <etc>]' -var='kms_key_arns=["key-arn1", "key-arn2"]'
</code>```

Every time you append a new item to one of the variables and run terraform apply, Terraform will update the policy accordingly.

Body:
I have an existing IAM policy attached to a role. Each time a new secret is created in the Secrets Manager, I need to append the new ARN to the policy. Can this be done with Terraform? I've managed to import the policy into the terraform.state file, but I don't know how to:
1) Append a new ARN inside the "Resources" list
2) Push the change to AWS

This is how the policy looks now:

{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Action": "secretsmanager:GetSecretValue",
        "Resource": [
            "SECRET_ARN_1",
            "SECRET_ARN_2",
            "SECRET_ARN_3"
        ]
    },
    {
        "Effect": "Allow",
        "Action": "kms:Decrypt",
        "Resource": "KMS_ARN"
    }
]

}

And this is how I need it to look:

{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Action": "secretsmanager:GetSecretValue",
        "Resource": [
            "SECRET_ARN_1",
            "SECRET_ARN_2",
            "SECRET_ARN_3",
            "MY_BRAND_NEW_SECRET_ARN"
        ]
    },
    {
        "Effect": "Allow",
        "Action": "kms:Decrypt",
        "Resource": "KMS_ARN"
    }
]

}

The following import is working by importing the existing policy to the object aws_iam_policy.mysimplepolicy, but I don't know how to proceed from here.

terraform import aws_iam_policy.mysimplepolicy <MY_POLICY_ARN>

Body:
It sounds like you've already figured out how to import the policy in to your state. Now you need to define the resource in your Terraform code so it matches the policy.

First, define variables for the ARNs:

variable "secret_arns" {
    description = "A list of secret manager ARNs that the IAM policy should permit access to."
    type        = list(string)
}

variable "kms_key_arns" {
    description = "A list of KMS Key ARNs that the IAM policy should permit access to."
    type        = list(string)
}

Next, define the policy document as a data source, using the variables:

data "aws_iam_policy_document" "secret_access" {
    statement {
        sid       = "SecretsAccess"
        actions   = ["secretsmanager:GetSecretValue"]
        resources = var.secret_arns
        effect    = "Allow"
    }
    statement {
        sid       = "KMSAccess"
        actions   = "kms:Decrypt"
        resources = var.kms_key_arns
        effect    = "Allow"
    }
}

Now create a policy using the data source:

resource "aws_iam_policy" "mysimplepolicy" {
  name   = "MySimplePolicy"  # Make sure this has the name you want
  policy = data.aws_iam_policy_document.secret_access.json
}

Finally, when you call the code, pass in the ARNs in your variables using whatever method you prefer. It could be from a terraform.tfvars file or on the command line using the -var syntax or as output from another Terraform module that creates the secrets. For example:

terraform apply -var='secret_arns=["arn1", "arn2", <etc>]' -var='kms_key_arns=["key-arn1", "key-arn2"]'

Every time you append a new item to one of the variables and run terraform apply, Terraform will update the policy accordingly.


问:
form data not saving to chrome local storage
I'm pretty new coder and only touched on JavaScript, but I'm trying to submit a form and get back the data as part of my school work, but according to google's DevTool its not saving into google's local storage, any help?

```<code>    function submit() {
    var name = document.getElementById("name").value;
    var email = document.getElementById("email").value;
    var feedback = document.getElementById("feedback").value;

    localStorage.setItem("name", name);
    localStorage.setItem("email", email);
    localStorage.setItem("feedback", feedback);

    return true;
}

function init() {
    var name = localStorage.getItem("name");
    var email = localStorage.getItem("email");
    var feedback = localStorage.getItem("feedback");

        document.write("passed value = " + name);
        document.write("passed value = " + email);
        document.write("passed value = " + feedback);

}
</code>```

HTML

```<code><form action="form.html" method="get" onsubmit="submit()">
            <fieldset style="width: 80%; margin: auto;">
                <legend>Feedback:</legend>
                <label for="name">Name:</label><br />
                <input type="text" id="name" name="name"><br><br>
                <label for="email">Email:</label><br />
                <input type="email" id="email" name="email"><br><br>
                <label for="feedback">Feedback:</label><br />
                <textarea id="feedback" name="feedback"></textarea><br>
                <input type="submit" value="Submit" onclick="submit()">
            </fieldset>
        </form>
    </section>
    <script src="form.js" type="text/javascript"></script>
</code>```

答:
The thing is that localstorage cannot store objects, but you could always store json formatted objects as a string and parse it later whenever you want to you the data!

And also the form submission should be stopped before it refreshes the page! just by adding the return false on the onsubmit event.

<form action="form.html" method="get" id="myForm">
  <fieldset style="width: 80%; margin: auto;">
    <legend>Feedback:</legend>
    Name:

    <input type="text" id="name" name="name">

    Email:

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

    Feedback:

    <textarea id="feedback" name="feedback"></textarea>

    <input type="submit" value="Submit">
  </fieldset>
</form>

```

Body:
I'm pretty new coder and only touched on JavaScript, but I'm trying to submit a form and get back the data as part of my school work, but according to google's DevTool its not saving into google's local storage, any help?

    function submit() {
    var name = document.getElementById("name").value;
    var email = document.getElementById("email").value;
    var feedback = document.getElementById("feedback").value;

    localStorage.setItem("name", name);
    localStorage.setItem("email", email);
    localStorage.setItem("feedback", feedback);

    return true;
}

function init() {
    var name = localStorage.getItem("name");
    var email = localStorage.getItem("email");
    var feedback = localStorage.getItem("feedback");

        document.write("passed value = " + name);
        document.write("passed value = " + email);
        document.write("passed value = " + feedback);

}

HTML

<form action="form.html" method="get" onsubmit="submit()">
            <fieldset style="width: 80%; margin: auto;">
                <legend>Feedback:</legend>
                Name:

                <input type="text" id="name" name="name">

                Email:

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

                Feedback:

                <textarea id="feedback" name="feedback"></textarea>

                <input type="submit" value="Submit" onclick="submit()">
            </fieldset>
        </form>

Body:
The thing is that localstorage cannot store objects, but you could always store json formatted objects as a string and parse it later whenever you want to you the data!

And also the form submission should be stopped before it refreshes the page! just by adding the return false on the onsubmit event.

<form action="form.html" method="get" id="myForm">
  <fieldset style="width: 80%; margin: auto;">
    <legend>Feedback:</legend>
    <label for="name">Name:</label><br />
    <input type="text" id="name" name="name"><br><br>
    <label for="email">Email:</label><br />
    <input type="email" id="email" name="email"><br><br>
    <label for="feedback">Feedback:</label><br />
    <textarea id="feedback" name="feedback"></textarea><br>
    <input type="submit" value="Submit">
  </fieldset>
</form>

<script>

  var myForm = document.querySelector("form#myForm");

  myForm.onsubmit = function(){
    const data = {};
    const dataToFetch = this.querySelectorAll("input, textarea, button, select");

    for(let element of dataToFetch){

      if( element && element.tagName && element.name )
        data[element.name] = element.value;

    }

    let jsonData = JSON.stringify( data );

    localStorage.setItem("formData", jsonData);

    alert("Data stored to localStorage itemName:'formData'");

    return false;
  }

</script>


问:
Decimal rounding issues
I have a scenario in which some variable values have decimal values, the values can have leading .0, .234, .124, .125, numbers like this, and so on. If the number has leading decimal and zero it should ignore and if a number has leading 3 or more numbers it should round off to two.
Let's say the code is as follows:

```<code>var anone    = "23"
var antwo    = "23.0"
var anthree  = "23.467"
var anfour   = "23.125"
</code>```

In order to remove the leading decimal and zero I have used the following method:

```<code> var removingzero = antwo.Replace(".0", "");
 // The result will be = 23
</code>```

In order to round off and limit the number to two decimal points I have used the following method:

```<code> var convertodecimal = Decimal.Parse(anthree);
 var roundtotwo      = Math.Round(convertodecimal, 2);
 // The result will be = 23.47
</code>```

similarly in order to convert the last one I follow the same method:

```<code> var convertodecimal = Decimal.Parse(anfour);
 var roundtotwo      = Math.Round(convertodecimal, 2);
 // The result will be = 23.12
 // But the Result should be = 23.13
</code>```

So, the problem is when I am trying to round off any number like the last example it does not do it, how can I fix it.

答:
It sounds like your question is a long way of asking "How can I force rounding UP when a decimal number ends in 5?"

If that's the case, then you can use the overload of Math.Round that takes a MidpointRounding argument, and specify either MidpointRounding.AwayFromZero or MidpointRounding.ToPositiveInfinity.

The behavior of these is the same for positive numbers, but difference is seen with negative numbers, where -23.125 will round to -23.13 if AwayFromZero is specified, or -23.12 if ToPositiveInfinity is specified.

So your code might look like this instead:

```<code>var roundtotwo = Math.Round(convertodecimal, 2, MidpointRounding.AwayFromZero);
</code>```

Title: Decimal rounding issues

Body:
I have a scenario in which some variable values have decimal values, the values can have leading .0, .234, .124, .125, numbers like this, and so on. If the number has leading decimal and zero it should ignore and if a number has leading 3 or more numbers it should round off to two.
Let's say the code is as follows:

var anone    = "23"
var antwo    = "23.0"
var anthree  = "23.467"
var anfour   = "23.125"

In order to remove the leading decimal and zero I have used the following method:

 var removingzero = antwo.Replace(".0", "");
 // The result will be = 23

In order to round off and limit the number to two decimal points I have used the following method:

 var convertodecimal = Decimal.Parse(anthree);
 var roundtotwo      = Math.Round(convertodecimal, 2);
 // The result will be = 23.47

similarly in order to convert the last one I follow the same method:

 var convertodecimal = Decimal.Parse(anfour);
 var roundtotwo      = Math.Round(convertodecimal, 2);
 // The result will be = 23.12
 // But the Result should be = 23.13

So, the problem is when I am trying to round off any number like the last example it does not do it, how can I fix it.

Body:
It sounds like your question is a long way of asking "How can I force rounding UP when a decimal number ends in 5?"

If that's the case, then you can use the overload of Math.Round that takes a MidpointRounding argument, and specify either MidpointRounding.AwayFromZero or MidpointRounding.ToPositiveInfinity.

The behavior of these is the same for positive numbers, but difference is seen with negative numbers, where -23.125 will round to -23.13 if AwayFromZero is specified, or -23.12 if ToPositiveInfinity is specified.

So your code might look like this instead:

var roundtotwo = Math.Round(convertodecimal, 2, MidpointRounding.AwayFromZero);


问:
How do I get sum of two different columns from two diffrent tables and group them
I have two tables which I wanna perform join between two tables and group them by date

Table one is fb_data

```<code>id  name created_at           revenue
1   as   2020-05-29 19:30:54  5
2   as   2020-05-28 19:30:54  10
3   ad   2020-05-29 19:31:42  6
4  ad    2020-05-28 19:31:54 65
5  as    2020-05-29 19:32:10 7
6  ad    2020-05-28 19:31:54 5
</code>```

Table two is google_data

```<code>id name   created_at           sessions
1  as     2020-05-29 19:38:32    5
2  ad     2020-05-29 19:38:41    10
3  as      2020-05-29 19:38:49   7
4  as      2020-05-28 19:39:02   6
5  ad     2020-05-28 19:39:13   8
6  ad    2020-05-28 19:41:41   13
</code>```

Now what I want is to join two columns by name then group them by created_at . Something like this

```<code>Name , date(created_at) as date , sum(fb_data.revenue) , sum(google_data.revenue)
</code>```

I have one sql query but that doesn't gives result as I expected

```<code>select gd.name,fb.total_revenue,fb.created_at,gd.total_sessions
from (select date(fb_data.created_at) as created_at, sum(fb_data.revenue) as total_revenue, name
      from fb_data
      group by date(fb_data.created_at), name) fb,
     (select date(google_data.created_at) as created_at, sum(google_data.session) as total_sessions, name
      from google_data
      group by name, date(google_data.created_at)) as gd
      where fb.name = gd.name
      group by  gd.name,fb.name,fb.created_at,gd.total_sessions
</code>```

The result I get is

```<code>Name total_revenue   created_at     total_sessions
as   12              2020-05-29     12
as   12              2020-05-29     6
as   10              2020-05-28     12
as   10              2020-05-28     6
ad   6               2020-05-29     10
ad   6              2020-05-29      21
ad  70             2020-05-28       10
ad  70             2020-05-28      21
</code>```

The result that I am expecting is

```<code>name  total_revenue   created_at total_sessions
as    12              2020-05-29   12
as    10              2020-05-28   6
ad    6               2020-05-29   10
ad    70              2020-05-28   21
</code>```

答:
You can use below simple Query. It gives the desired result :

```<code>select aa.name,aa.created, sum(ses), sum(rev)
from
    (select fb_data.name, date(created_at) as created, sum(revenue) as rev, 0 as ses
    from fb_data group by fb_data.name,date(created_at)
    UNION
    select google_data.name, date(created_at) as created, 0 as rev, sum(sessions) as ses
    from google_data group by google_data.name,date(created_at)
    ) as aa
group by name,created;
</code>```

Check Results :
https://www.db-fiddle.com/f/7wpGKon7SH58HNF7Q4SuFH/1

Body:
I have two tables which I wanna perform join between two tables and group them by date

Table one is fb_data

id  name created_at           revenue
1   as   2020-05-29 19:30:54  5
2   as   2020-05-28 19:30:54  10
3   ad   2020-05-29 19:31:42  6
4  ad    2020-05-28 19:31:54 65
5  as    2020-05-29 19:32:10 7
6  ad    2020-05-28 19:31:54 5

Table two is google_data

id name   created_at           sessions
1  as     2020-05-29 19:38:32    5
2  ad     2020-05-29 19:38:41    10
3  as      2020-05-29 19:38:49   7
4  as      2020-05-28 19:39:02   6
5  ad     2020-05-28 19:39:13   8
6  ad    2020-05-28 19:41:41   13

Now what I want is to join two columns by name then group them by created_at . Something like this

Name , date(created_at) as date , sum(fb_data.revenue) , sum(google_data.revenue)

I have one sql query but that doesn't gives result as I expected

select gd.name,fb.total_revenue,fb.created_at,gd.total_sessions
from (select date(fb_data.created_at) as created_at, sum(fb_data.revenue) as total_revenue, name
      from fb_data
      group by date(fb_data.created_at), name) fb,
     (select date(google_data.created_at) as created_at, sum(google_data.session) as total_sessions, name
      from google_data
      group by name, date(google_data.created_at)) as gd
      where fb.name = gd.name
      group by  gd.name,fb.name,fb.created_at,gd.total_sessions

The result I get is

Name total_revenue   created_at     total_sessions
as   12              2020-05-29     12
as   12              2020-05-29     6
as   10              2020-05-28     12
as   10              2020-05-28     6
ad   6               2020-05-29     10
ad   6              2020-05-29      21
ad  70             2020-05-28       10
ad  70             2020-05-28      21

The result that I am expecting is

name  total_revenue   created_at total_sessions
as    12              2020-05-29   12
as    10              2020-05-28   6
ad    6               2020-05-29   10
ad    70              2020-05-28   21

Body:
You can use below simple Query. It gives the desired result :

select aa.name,aa.created, sum(ses), sum(rev)
from
    (select fb_data.name, date(created_at) as created, sum(revenue) as rev, 0 as ses
    from fb_data group by fb_data.name,date(created_at)
    UNION
    select google_data.name, date(created_at) as created, 0 as rev, sum(sessions) as ses
    from google_data group by google_data.name,date(created_at)
    ) as aa
group by name,created;

Check Results :
https://www.db-fiddle.com/f/7wpGKon7SH58HNF7Q4SuFH/1


问:
Sorting a list of RGB triplets into a spectrum
I have a list of RGB triplets, and I'd like to plot them in such a way that they form something like a spectrum.

I've converted them to HSV, which people seem to recommend.

```<code>from PIL import Image, ImageDraw
import colorsys

def make_rainbow_rgb(colors, width, height):
    """colors is an array of RGB tuples, with values between 0 and 255"""

    img = Image.new("RGBA", (width, height))
    canvas = ImageDraw.Draw(img)

    def hsl(x):
        to_float = lambda x : x / 255.0
        (r, g, b) = map(to_float, x)
        h, s, l = colorsys.rgb_to_hsv(r,g,b)
        h = h if 0 < h else 1 # 0 -> 1
        return h, s, l

    rainbow = sorted(colors, key=hsl)

    dx = width / float(len(colors))
    x = 0
    y = height / 2.0
    for rgb in rainbow:
        canvas.line((x, y, x + dx, y), width=height, fill=rgb)
        x += dx
    img.show()
</code>```

However, the result doesn't look very much like a nice rainbow-y spectrum. I suspect I need to either convert to a different color space or handle the HSL triplet differently.

Does anyone know what I need to do to make this data look roughly like a rainbow?

Update:

I was playing around with Hilbert curves and revisited this problem. Sorting the RGB values (same colors in both images) by their position along a Hilbert curve yields an interesting (if still not entirely satisfying) result:

答: Presumably you are sorting by hue (i.e. H)?  That will give a nice result if S and L (or V) are constant, but if they are varying independently, then you will get a bit of a mess!

Body:
I have a list of RGB triplets, and I'd like to plot them in such a way that they form something like a spectrum.

I've converted them to HSV, which people seem to recommend.

from PIL import Image, ImageDraw
import colorsys

def make_rainbow_rgb(colors, width, height):
    """colors is an array of RGB tuples, with values between 0 and 255"""

    img = Image.new("RGBA", (width, height))
    canvas = ImageDraw.Draw(img)

    def hsl(x):
        to_float = lambda x : x / 255.0
        (r, g, b) = map(to_float, x)
        h, s, l = colorsys.rgb_to_hsv(r,g,b)
        h = h if 0 < h else 1 # 0 -> 1
        return h, s, l

    rainbow = sorted(colors, key=hsl)

    dx = width / float(len(colors))
    x = 0
    y = height / 2.0
    for rgb in rainbow:
        canvas.line((x, y, x + dx, y), width=height, fill=rgb)
        x += dx
    img.show()

However, the result doesn't look very much like a nice rainbow-y spectrum. I suspect I need to either convert to a different color space or handle the HSL triplet differently.

Does anyone know what I need to do to make this data look roughly like a rainbow?

Update:

I was playing around with Hilbert curves and revisited this problem. Sorting the RGB values (same colors in both images) by their position along a Hilbert curve yields an interesting (if still not entirely satisfying) result:


问:
best way to get tab delimited text file into MongoDB collection
I have a product data table given to me in text file and the format of the data is like below:

**START

IB 1107518415

BI Paperback

BC JHBC

BC JFDD

CO United Kingdom

ED Alvarez, R. Michael

IU 46 b/w illus.  2 maps  18 tables

MP No

PD 20160307

I3 9781107518414

**

Basically, a TAG system is followed where each TAG has a unique 2-digit identifier followed by the relevant data itself. A
CR/LF will be at the end of each field.

** Markers is used to indicate the beginning of a new record.

The file is 3 GB and it has 6 million such record, each record having upto 43 fields and some fields having multiple values like the "BC" field in the above sample, I'd need both the values.

What would be the best way to get this file into a collection?

Thanks
Mohamed

答:
This could be done two steps:

Step 1. Convert the file to a usable format (CSV or JSON)

You could use a regular expression to get all the fields such as

```<code>/^\*\* START IB (.+) BI (.+) BC (.+) BC (.+) CO (.+) ED (.+) MP (.+) PD (.+) PA (.+) NP (.+) RP (.+) RI (.+) RE (.+) DI (.+) PU (.+) YP (.+) DE (.+) EA (.+) RF (.+) WE (.+) SG (.+) GC (.+) I3 (.+)/
</code>```

You can see it working here

Step 2. Import the file using mongoimport which is answered here

Body:
This could be done two steps:

Step 1. Convert the file to a usable format (CSV or JSON)

You could use a regular expression to get all the fields such as

/^\*\* START IB (.+) BI (.+) BC (.+) BC (.+) CO (.+) ED (.+) MP (.+) PD (.+) PA (.+) NP (.+) RP (.+) RI (.+) RE (.+) DI (.+) PU (.+) YP (.+) DE (.+) EA (.+) RF (.+) WE (.+) SG (.+) GC (.+) I3 (.+)/

You can see it working here

Step 2. Import the file using mongoimport which is answered here


问:
NodeJS Express encodes the URL - how to decode
I'm using NodeJS with Express, and when I use foreign characters in the URL, they automatically get encoded.

How do I decode it back to the original string?

Before calling NodeJS, I escape characters.

So the string: אובמה

Becomes %u05D0%u05D5%u05D1%u05DE%u05D4

The entire URL now looks like: http://localhost:32323/?query=%u05D0%u05D5%u05D1%u05DE%u05D4

Now in my NodeJS, I get the escaped string %u05D0%u05D5%u05D1%u05DE%u05D4.

This is the relevant code:

```<code>var url_parts = url.parse(req.url, true);
var params = url_parts.query;
var query = params.query; // '%u05D0%u05D5%u05D1%u05DE%u05D4'
</code>```

I've tried url and querystring libraries but nothing seems to fit my case.

```<code>querystring.unescape(query); // still '%u05D0%u05D5%u05D1%u05DE%u05D4'
</code>```

答:
```<code>#**update may-2020**
# how to use an encoder/decoder on node js
### I am writing my answer due to I have noisy data I spend 4 hour to fixed

data email   input = myemail@gmail.com
data URL input = /us/home

```
decodeURI function that only decodes a URL special character

  email output =>myemail%40gmail.com
  url output => %2Fus%2F

using decodeURIComponent
  email output = > myemail@gmail.com
  url output => /us/
```
here some clarification where you can use decodeURI and  decodeURIComponent   a fucntion
</code>```

Body:
I'm using NodeJS with Express, and when I use foreign characters in the URL, they automatically get encoded.

How do I decode it back to the original string?

Before calling NodeJS, I escape characters.

So the string: אובמה

Becomes %u05D0%u05D5%u05D1%u05DE%u05D4

The entire URL now looks like: http://localhost:32323/?query=%u05D0%u05D5%u05D1%u05DE%u05D4

Now in my NodeJS, I get the escaped string %u05D0%u05D5%u05D1%u05DE%u05D4.

This is the relevant code:

var url_parts = url.parse(req.url, true);
var params = url_parts.query;
var query = params.query; // '%u05D0%u05D5%u05D1%u05DE%u05D4'

I've tried url and querystring libraries but nothing seems to fit my case.

querystring.unescape(query); // still '%u05D0%u05D5%u05D1%u05DE%u05D4'


问:
Python generic with union
I have a Document and Page types, both containing data and metadata parts. They are looking the same:

```<code>class Document:
    __data: DocumentData
    __meta: DocumentMeta

    def __init__(self, part: Union[DocumentData, DocumentMeta, None] = None, data: Optional[DocumentData] = None,
             meta: Optional[DocumentMeta] = None):
        super().__init__()
        self.data: Optional[DocumentData] = data
        self.meta: Optional[DocumentMeta] = meta

        if part is not None:
            if type(part) == DocumentData:
                data = part
                meta = DocumentMeta()
            elif type(part) == DocumentMeta:
                meta = part
                data = DocumentData()

class Page:
    __data: PageData
    __meta: PageMeta

    def __init__(self, part: Union[PageData, PageMeta, None] = None, data: Optional[PageData] = None,
             meta: Optional[PageMeta] = None):
        super().__init__()
        self.data: Optional[PageData] = data
        self.meta: Optional[PageMeta] = meta

        if part is not None:
            if type(part) == PageData:
                data = part
                meta = PageMeta()
            elif type(part) == PageMeta:
                meta = part
                data = PageData()
</code>```

I would like now to refactor these 2 types to use a generic type. I did it that way:

```<code>from typing import Generic, Optional, TypeVar, Union

DataStruct = TypeVar('DataStruct')
MetaStruct = TypeVar('MetaStruct')

class MetaDataStruct(Generic[DataStruct, MetaStruct]):
    __data: DataStruct
    __meta: MetaStruct

    def __init__(
        self,
        part: Union[DataStruct, MetaStruct, None] = None,
        data: Optional[DataStruct] = None,
        meta: Optional[MetaStruct] = None
    ):
        super().__init__()
        self.data: Optional[DataStruct] = data
        self.meta: Optional[MetaStruct] = meta

        if part is not None:
            if type(part) == DataStruct:
                data = part
                meta = MetaStruct()
            elif type(part) == MetaStruct:
                meta = part
                data = DataStruct()

class DocumentData:
    pass

class DocumentMeta:
    pass

class PageData:
    pass

class PageMeta:
    pass

class Document(MetaDataStruct[DocumentData, DocumentMeta]):
    pass

class Page(MetaDataStruct[PageData, PageMeta]):
    pass
</code>```

Now there's few problems with type checking.

if type(part) == DataStruct: returns False all the time. In runtime a type(part) is one of: DocumentData, DocumentMeta, PageData, PageMeta. I understand that I have to compare type(part) with actual type of DataStruct. What is the right way to resolve the runtime type of DataStruct?

In python hints manual it's written: At runtime, isinstance(x, T) will raise TypeError. In general, isinstance() and issubclass() should not be used with types. I believe the same issue is here.

I can use type(self).orig_bases[0].args[0] to infer DataStruct, but it is conceptually incorrect. It will retrieve the first generic argument instead DataStruct. So, if a MetaDataStruct base class signature will change to class MergedStruct(Struct, Generic[MetaStruct, DataStruct]) (swapped TypeVar arguments), MetaStruct will be retrieved instead DataStruct.

For some reason, when I tried to intialize Document(part=1), it passed. In practice I expected the code to raise TypeError.

答:
Python doesn't do type checking at runtime; you need to use a static analysis tool like mypy.  Running mypy over the code you've given shows these errors:

```<code>22: error: 'DataStruct' is a type variable and only valid in type context
23: error: Incompatible types in assignment (expression has type "Union[DataStruct, MetaStruct]", variable has type "Optional[DataStruct]")
24: error: 'MetaStruct' is a type variable and only valid in type context
25: error: 'MetaStruct' is a type variable and only valid in type context
26: error: Incompatible types in assignment (expression has type "Union[DataStruct, MetaStruct]", variable has type "Optional[MetaStruct]")
27: error: 'DataStruct' is a type variable and only valid in type context
</code>```

If you add a line trying to initialize Document(part=1), you won't get a runtime error (there's nothing in your code that would raise an error; your if/elif will just be a no-op), but you will get a typechecking error from mypy that looks like:

```<code>54: error: Argument "part" to "Document" has incompatible type "int"; expected "Union[DocumentData, DocumentMeta, None]"
</code>```

The problem with the type() check you're trying to do (and with an equivalent isinstance) is that a TypeVar has no runtime value, so you can't invoke it as a constructor.  See: Instantiate a type that is a TypeVar

One way to fix this is to require that the subclass provide the actual types:

```<code>from abc import ABC, abstractclassmethod
from typing import Generic, Optional, Type, TypeVar, Union

DataStruct = TypeVar('DataStruct')
MetaStruct = TypeVar('MetaStruct')

class MetaDataStruct(Generic[DataStruct, MetaStruct], ABC):

    @abstractclassmethod
    def _data_type(cls) -> Type[DataStruct]:
        pass

    @abstractclassmethod
    def _meta_type(cls) -> Type[MetaStruct]:
        pass

    def __init__(
        self,
        part: Union[DataStruct, MetaStruct, None] = None,
        data: Optional[DataStruct] = None,
        meta: Optional[MetaStruct] = None
    ):
        super().__init__()
        self.data: Optional[DataStruct] = data
        self.meta: Optional[MetaStruct] = meta

        if part is not None:
            if isinstance(part, self._data_type()):
                data = part
                meta = self._meta_type()()
            elif isinstance(part, self._meta_type()):
                meta = part
                data = self._data_type()()

class DocumentData:
    pass

class DocumentMeta:
    pass

class Document(MetaDataStruct[DocumentData, DocumentMeta]):
    @classmethod
    def _data_type(cls) -> Type[DocumentData]:
        return DocumentData

    @classmethod
    def _meta_type(cls) -> Type[DocumentMeta]:
        return DocumentMeta
</code>```

The above typechecks correctly (you'll get mypy errors if you don't implement the _data_type and _meta_type methods correctly in the subclass), and is able to use the class methods to call the appropriate constructors at runtime.

Title: Python generic with union

Body:
I have a Document and Page types, both containing data and metadata parts. They are looking the same:

class Document:
    __data: DocumentData
    __meta: DocumentMeta

    def __init__(self, part: Union[DocumentData, DocumentMeta, None] = None, data: Optional[DocumentData] = None,
             meta: Optional[DocumentMeta] = None):
        super().__init__()
        self.data: Optional[DocumentData] = data
        self.meta: Optional[DocumentMeta] = meta

        if part is not None:
            if type(part) == DocumentData:
                data = part
                meta = DocumentMeta()
            elif type(part) == DocumentMeta:
                meta = part
                data = DocumentData()

class Page:
    __data: PageData
    __meta: PageMeta

    def __init__(self, part: Union[PageData, PageMeta, None] = None, data: Optional[PageData] = None,
             meta: Optional[PageMeta] = None):
        super().__init__()
        self.data: Optional[PageData] = data
        self.meta: Optional[PageMeta] = meta

        if part is not None:
            if type(part) == PageData:
                data = part
                meta = PageMeta()
            elif type(part) == PageMeta:
                meta = part
                data = PageData()

I would like now to refactor these 2 types to use a generic type. I did it that way:

from typing import Generic, Optional, TypeVar, Union

DataStruct = TypeVar('DataStruct')
MetaStruct = TypeVar('MetaStruct')

class MetaDataStruct(Generic[DataStruct, MetaStruct]):
    __data: DataStruct
    __meta: MetaStruct

    def __init__(
        self,
        part: Union[DataStruct, MetaStruct, None] = None,
        data: Optional[DataStruct] = None,
        meta: Optional[MetaStruct] = None
    ):
        super().__init__()
        self.data: Optional[DataStruct] = data
        self.meta: Optional[MetaStruct] = meta

        if part is not None:
            if type(part) == DataStruct:
                data = part
                meta = MetaStruct()
            elif type(part) == MetaStruct:
                meta = part
                data = DataStruct()

class DocumentData:
    pass

class DocumentMeta:
    pass

class PageData:
    pass

class PageMeta:
    pass

class Document(MetaDataStruct[DocumentData, DocumentMeta]):
    pass

class Page(MetaDataStruct[PageData, PageMeta]):
    pass

Now there's few problems with type checking.

if type(part) == DataStruct: returns False all the time. In runtime a type(part) is one of: DocumentData, DocumentMeta, PageData, PageMeta. I understand that I have to compare type(part) with actual type of DataStruct. What is the right way to resolve the runtime type of DataStruct?

In python hints manual it's written: At runtime, isinstance(x, T) will raise TypeError. In general, isinstance() and issubclass() should not be used with types. I believe the same issue is here.

I can use type(self).orig_bases[0].args[0] to infer DataStruct, but it is conceptually incorrect. It will retrieve the first generic argument instead DataStruct. So, if a MetaDataStruct base class signature will change to class MergedStruct(Struct, Generic[MetaStruct, DataStruct]) (swapped TypeVar arguments), MetaStruct will be retrieved instead DataStruct.

For some reason, when I tried to intialize Document(part=1), it passed. In practice I expected the code to raise TypeError.

Body:
Python doesn't do type checking at runtime; you need to use a static analysis tool like mypy.  Running mypy over the code you've given shows these errors:

22: error: 'DataStruct' is a type variable and only valid in type context
23: error: Incompatible types in assignment (expression has type "Union[DataStruct, MetaStruct]", variable has type "Optional[DataStruct]")
24: error: 'MetaStruct' is a type variable and only valid in type context
25: error: 'MetaStruct' is a type variable and only valid in type context
26: error: Incompatible types in assignment (expression has type "Union[DataStruct, MetaStruct]", variable has type "Optional[MetaStruct]")
27: error: 'DataStruct' is a type variable and only valid in type context

If you add a line trying to initialize Document(part=1), you won't get a runtime error (there's nothing in your code that would raise an error; your if/elif will just be a no-op), but you will get a typechecking error from mypy that looks like:

54: error: Argument "part" to "Document" has incompatible type "int"; expected "Union[DocumentData, DocumentMeta, None]"

The problem with the type() check you're trying to do (and with an equivalent isinstance) is that a TypeVar has no runtime value, so you can't invoke it as a constructor.  See: Instantiate a type that is a TypeVar

One way to fix this is to require that the subclass provide the actual types:

from abc import ABC, abstractclassmethod
from typing import Generic, Optional, Type, TypeVar, Union

DataStruct = TypeVar('DataStruct')
MetaStruct = TypeVar('MetaStruct')

class MetaDataStruct(Generic[DataStruct, MetaStruct], ABC):

    @abstractclassmethod
    def _data_type(cls) -> Type[DataStruct]:
        pass

    @abstractclassmethod
    def _meta_type(cls) -> Type[MetaStruct]:
        pass

    def __init__(
        self,
        part: Union[DataStruct, MetaStruct, None] = None,
        data: Optional[DataStruct] = None,
        meta: Optional[MetaStruct] = None
    ):
        super().__init__()
        self.data: Optional[DataStruct] = data
        self.meta: Optional[MetaStruct] = meta

        if part is not None:
            if isinstance(part, self._data_type()):
                data = part
                meta = self._meta_type()()
            elif isinstance(part, self._meta_type()):
                meta = part
                data = self._data_type()()

class DocumentData:
    pass

class DocumentMeta:
    pass

class Document(MetaDataStruct[DocumentData, DocumentMeta]):
    @classmethod
    def _data_type(cls) -> Type[DocumentData]:
        return DocumentData

    @classmethod
    def _meta_type(cls) -> Type[DocumentMeta]:
        return DocumentMeta

The above typechecks correctly (you'll get mypy errors if you don't implement the _data_type and _meta_type methods correctly in the subclass), and is able to use the class methods to call the appropriate constructors at runtime.