问:
Triggering a long process by a user in a website
I want to create a web page where users can initiate a process, this process will take several minutes to complete.

My question is:

  When the user clicks on a button, should I start the process on a different thread and send him to a different page? I don't want the process to end in case he closes the window or the connection is lost.

Also how can I prevent other users from initiating this process.

I thought about putting a variable in the application state that indicates whether the process is currently running or not.

Thanks for your advices

答:
You could spawn a thread that is going to do the work and periodically checks whether it should still continue with his work. For the work you generate a certain ID (that you may or not couple to the user for extra security) that will be used to distinguish the work job. On the redirected page you could use some javascript to tell the server that the user is still waiting for job with ID X. Should this time-out expire you can drop the work.

Create your job with a specific ID

Share somewhere a timeout variable accessible by both the server and the job-thread

Redirect the user to the landing page, where you have javascript polling the server
for the result

Once the job completes you store the result with the id and on the next poll from
the client you can pass the information to the client.

Update: If you want only one person to activate the process then you could still use the still system if you want to keep a history of some kind. You would only need to change the landing page to always look at the latest process and prevent other from starting one if there is still a process running.

Otherwise you could do the same as in the above system but use a single store point for the process results. If the store point consists a placeholder it indicates that the process already has been started and that no-one should start a new process. The display page could then poll against this store point for the info to show the users.

In the event you want everyone to be able to see the current results while a new process is being executed use two locations to store the result, one to store the finished one and one to store the busy one.


来源: stackexchange

问:
JavaScript updating value of array element
I have below JSON Array and I am trying to add new object to one of the array element, but problem that I am facing is:

If I push new object for an array array1 at index 0 of arrayHolder then all the array1 elements are getting updated with new object.

```<code>{
  "arrayHolder": [
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    }
 ]
}
</code>```

I am using below code to push to array1:

```<code>var jsonStr = "{\"arrayHolder\":[{\"array1\": [],\"....."; // Json String
var jsonObj = JSON.parse(jsonStr); // String To object

var newObj = {"value": 1}; // New object that I want to push
jsonObj.arrayHolder[0].array1.push(newObj);

// Even below code has same output
jsonObj.arrayHolder[0]["array1"][0] = newObj;

</code>```

I get below output:

```<code>{
  "arrayHolder": [
    {
      "array1": [{"value": 1}],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [{"value": 1}],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [{"value": 1}],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [{"value": 1}],
      "array2": [],
      "array3": [],
      "array4": []
    }
 ]
}
</code>```

I want to update value of array1 only for the 0th element in the arrayHolder array not for all the array1 elements in the main array.

答:
Try:</p>

```<code>jsonObj.['arrayHolder'][0]['array1'].push(newObj);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have below JSON Array and I am trying to add new object to one of the array element, but problem that I am facing is:

If I push new object for an array array1 at index 0 of arrayHolder then all the array1 elements are getting updated with new object.

{
  "arrayHolder": [
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    }
 ]
}

I am using below code to push to array1:

var jsonStr = "{\"arrayHolder\":[{\"array1\": [],\"....."; // Json String
var jsonObj = JSON.parse(jsonStr); // String To object

var newObj = {"value": 1}; // New object that I want to push
jsonObj.arrayHolder[0].array1.push(newObj);

// Even below code has same output
jsonObj.arrayHolder[0]["array1"][0] = newObj;

I get below output:

{
  "arrayHolder": [
    {
      "array1": [{"value": 1}],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [{"value": 1}],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [{"value": 1}],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [{"value": 1}],
      "array2": [],
      "array3": [],
      "array4": []
    }
 ]
}

I want to update value of array1 only for the 0th element in the arrayHolder array not for all the array1 elements in the main array.

Body:
Try:

jsonObj.['arrayHolder'][0]['array1'].push(newObj);


问:
How to change my Git username in terminal?
I was pushing and pulling from git in Terminal then I changed my username on github.com.  I went to push some changes and it couldn't push because it was still recognizing my old username.. How do I change/update my username on git in terminal?</p>

答:
Firstly you need to change credentials from your local machine

remove generic credentials if there is any

configure new user and email (you can make it globally if you want)

```<code>git config [--global] user.name "Your Name"
git config [--global] user.email "email@address.com"
</code>```

now upload or update your repo it will ask your username and password to get access to github

Body:
Firstly you need to change credentials from your local machine

remove generic credentials if there is any

configure new user and email (you can make it globally if you want)

git config [--global] user.name "Your Name"
git config [--global] user.email "email@address.com"

now upload or update your repo it will ask your username and password to get access to github


答: The issue is with the array holder, it seems that the array holder is using the same object, and so modifying it in one place will cause the change to be reflected in all places.</p>

Title: JavaScript updating value of array element


问:
Populating Tables from Database in Angular. Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed
Although i have seen similar questions, none have solved my problem. any sort of help would be appreciated. I am trying to populate my table with information from my db. i can log the information but when i try to iterate i get this error.

Admin.HTML

```<code>    <div class="col">
      <button class="btn btn-primary" (click)="getData()">Customer Data</button>
    </div>
    <div class="col-sm-8 col-md-8">
      <table class="col table table-striped">
        <thead>
          <tr>
            <th scope="col-2">Name</th>
            <th scope="">Phone Number</th>
            <th scope="col-2">Email</th>
          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let customer of customers">
            <th scope="row">{{ customer.name }}</th>
            <td>{{ customer.number }}</td>
            <td>{{ customer.email }}</td>
          </tr>
        </tbody>
      </table>
    </div>
</code>```

admin.ts

```<code>import { Component, OnInit } from '@angular/core';
import { Response } from '@angular/http';

import { CustomerData } from '../customer.service';

@Component({
  selector: 'app-admin',
  templateUrl: './admin.component.html',
  styleUrls: ['./admin.component.css']
})
export class AdminComponent implements OnInit {
  customers = [];

  constructor(private customerData: CustomerData) { }

  ngOnInit() {
  }

  getData() {
    this.customerData.getData()
    .subscribe(
      (customers: any[]) => this.customers = customers,
      (error) => console.log(error)
    )
  }
}
</code>```

service.ts

```<code>import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { FormGroup } from '@angular/forms';
import { map } from 'rxjs/operators';

@Injectable()
export class CustomerData {
    constructor(private http: Http) {}
    getData() {
        return this.http.get('link yo database')
        .pipe(map(
            (response: Response) => {
                const data = response.json();
                return data.result || data || [];
            }
        ));
    }
}
</code>```

答:
I assume the data you get from your DB is not an Array(). That will not be iterable by *ngFor. The response seems to be an object or something else.

I created a small Stackblitz: https://stackblitz.com/edit/angular-ivy-ap58xs?file=src%2Fapp%2Fcustomer.service.ts

It may help.

Body:
Although i have seen similar questions, none have solved my problem. any sort of help would be appreciated. I am trying to populate my table with information from my db. i can log the information but when i try to iterate i get this error.

Admin.HTML

      <button class="btn btn-primary" (click)="getData()">Customer Data</button>

            Name
            Phone Number
            Email

            {{ customer.name }}
            {{ customer.number }}
            {{ customer.email }}

admin.ts

import { Component, OnInit } from '@angular/core';
import { Response } from '@angular/http';

import { CustomerData } from '../customer.service';

@Component({
  selector: 'app-admin',
  templateUrl: './admin.component.html',
  styleUrls: ['./admin.component.css']
})
export class AdminComponent implements OnInit {
  customers = [];

  constructor(private customerData: CustomerData) { }

  ngOnInit() {
  }

  getData() {
    this.customerData.getData()
    .subscribe(
      (customers: any[]) => this.customers = customers,
      (error) => console.log(error)
    )
  }
}

service.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { FormGroup } from '@angular/forms';
import { map } from 'rxjs/operators';

@Injectable()
export class CustomerData {
    constructor(private http: Http) {}
    getData() {
        return this.http.get('link yo database')
        .pipe(map(
            (response: Response) => {
                const data = response.json();
                return data.result || data || [];
            }
        ));
    }
}


问:
Why am i getting this error from getSource method in MouseAdapter?
I was trying to change the text "Java" to "Love Java" by using MouseAdapter. The text "Java" comes out when mouseEntered and "Love Java" comes out when mouseExited. So I created class MyMouse extends MouseAdapter and trying to use the methods.

But there is the error message "The method getSource() is undefined for the type MouseEvent". When I searched it, this code is nothing wrong with it but I don't know why I'm getting this error message, and also of course the result is not working.

```<code>import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MouseEvent extends JFrame{

    MouseEvent(){
        setTitle("Practicing mouse event");
        setLayout(new FlowLayout());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLabel lb = new JLabel("Java");
        MyMouse mym = new MyMouse();
        lb.addMouseListener(mym);

        lb.setSize(300,100);
        add(lb);
        setSize(400,200);
        setVisible(true);
    }
    public static void main(String[] args) {
        new MouseEvent();
    }
}

class MyMouse extends MouseAdapter{
    public void mouseEntered(MouseEvent e) {
        JLabel lb = (JLabel)e.getSource();
        lb.setText("Love Java");
    }
    public void mouseExited(MouseEvent e) {
        JLabel lb = (JLabel)e.getSource();
        lb.setText("Java");
    }
}
</code>```

答:
The problem can be solved through these changes to the code:

Rename the main class of the program so that its name does not conflict with that of the class (java.awt.event.MouseEvent) imported from Java library.

Add @Override annotations to mouseEntered and mouseExited methods to avoid compiler warnings

Call setVisible(true) on the frame to display after instantiation

Here is the working example with the above mentioned changes:

```<code>// File name: Demo.java
// This name was chosen to avoid conflict with java.awt.event.MouseEvent

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class MyMouse extends MouseAdapter{

    // Add @Override annotation to overridden methods
    @Override
    public void mouseEntered(MouseEvent e) {
        JLabel lb = (JLabel)e.getSource();
        lb.setText("Love Java");
    }

    // Add @Override annotation to overridden methods
    @Override
    public void mouseExited(MouseEvent e) {
        JLabel lb = (JLabel)e.getSource();
        lb.setText("Java");
    }
}

public class Demo extends JFrame{
    Demo() {
        setTitle("Practicing mouse event");
        setLayout(new FlowLayout());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLabel lb = new JLabel("Java");
        MyMouse mym = new MyMouse();
        lb.addMouseListener(mym);

        lb.setSize(300,100);
        add(lb);
        setSize(400,200);
    }

    public static void main(String[] args) {
        Demo demo = new Demo();
        // Display the frame
        demo.setVisible(true);
    }
}
</code>```

Output:

```<code>> javac Demo.java

> java Demo
</code>```

Body:
I was trying to change the text "Java" to "Love Java" by using MouseAdapter. The text "Java" comes out when mouseEntered and "Love Java" comes out when mouseExited. So I created class MyMouse extends MouseAdapter and trying to use the methods.

But there is the error message "The method getSource() is undefined for the type MouseEvent". When I searched it, this code is nothing wrong with it but I don't know why I'm getting this error message, and also of course the result is not working.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MouseEvent extends JFrame{

    MouseEvent(){
        setTitle("Practicing mouse event");
        setLayout(new FlowLayout());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLabel lb = new JLabel("Java");
        MyMouse mym = new MyMouse();
        lb.addMouseListener(mym);

        lb.setSize(300,100);
        add(lb);
        setSize(400,200);
        setVisible(true);
    }
    public static void main(String[] args) {
        new MouseEvent();
    }
}

class MyMouse extends MouseAdapter{
    public void mouseEntered(MouseEvent e) {
        JLabel lb = (JLabel)e.getSource();
        lb.setText("Love Java");
    }
    public void mouseExited(MouseEvent e) {
        JLabel lb = (JLabel)e.getSource();
        lb.setText("Java");
    }
}

Body:
The problem can be solved through these changes to the code:

Rename the main class of the program so that its name does not conflict with that of the class (java.awt.event.MouseEvent) imported from Java library.

Add @Override annotations to mouseEntered and mouseExited methods to avoid compiler warnings

Call setVisible(true) on the frame to display after instantiation

Here is the working example with the above mentioned changes:

// File name: Demo.java
// This name was chosen to avoid conflict with java.awt.event.MouseEvent

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class MyMouse extends MouseAdapter{

    // Add @Override annotation to overridden methods
    @Override
    public void mouseEntered(MouseEvent e) {
        JLabel lb = (JLabel)e.getSource();
        lb.setText("Love Java");
    }

    // Add @Override annotation to overridden methods
    @Override
    public void mouseExited(MouseEvent e) {
        JLabel lb = (JLabel)e.getSource();
        lb.setText("Java");
    }
}

public class Demo extends JFrame{
    Demo() {
        setTitle("Practicing mouse event");
        setLayout(new FlowLayout());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLabel lb = new JLabel("Java");
        MyMouse mym = new MyMouse();
        lb.addMouseListener(mym);

        lb.setSize(300,100);
        add(lb);
        setSize(400,200);
    }

    public static void main(String[] args) {
        Demo demo = new Demo();
        // Display the frame
        demo.setVisible(true);
    }
}

Output:

> javac Demo.java

> java Demo


问:
Does pthread_once_t variable need a mutex?
we use One-Time initialization for pthreads like this:

```<code>/* define a statically initialized pthread_once_t variable */
pthread_once_t once_var = PTHREAD_ONCE_INIT;

/* we call pthread_once function in threads */
int pthread_once(pthread_once_t *once_control, void (*init)(void));
</code>```

when more than one thread is going to change the state of pthread_once_t variable, do we need a mutex for protecting it?

答: pthread_once is thread safe. You can think of the pthread_once_t variable as the mutex in this case.</p>

ContentLicense: CC BY-SA 3.0

Body:
we use One-Time initialization for pthreads like this:

/* define a statically initialized pthread_once_t variable */
pthread_once_t once_var = PTHREAD_ONCE_INIT;

/* we call pthread_once function in threads */
int pthread_once(pthread_once_t *once_control, void (*init)(void));

when more than one thread is going to change the state of pthread_once_t variable, do we need a mutex for protecting it?


问:
Windows Azure Virtual Machine - Opening a port
I am trying to open a port in a Windows Azure virtual machine. I have a game listening on that port, and I am able to access it via localhost, so the game is running.

I have also opened the port in the firewall and created an endpoint in the virtual machine, but the port doesn't seem to be open to the outside world. I have tried accessing it both via the IP address and the DNS with the same results.

Is there anything else I should do? I have looked up several tutorials online and can't figure out what I am doing wrong.

答:
This is a two step process:

Configure the port rule in the Azure Portal (No need of any restarts. The effect takes place in a few minutes.)
Here are the steps (at the time of writing): Click on the VM -> Click on 'Networking' -> Click 'Allow inbound port rule'

Configure the port rule in the VM's own Firewall - this depends on the Operating  System your VM has got (OR disable this firewall)
Here are the steps for Windows 10:
Open 'Windows Firewall with Advanced Security' Desktop App -> Click on 'Inbound Rules' on the left panel -> Click on 'New Rule' in the Actions panel on the right. The following screenshots explain the rest.

Now the application listening to the port can be reached over the internet.


问:
Trimming GPS information with awk
In a little bash script I simply try to trim GPS input data so that I have longitude and latitude values in separate variables:

```<code>  echo $geo_data
  GPS_latitude=$( echo $geo_data | awk -F"+|-" '{print substr($0,index($0,$2-1),1) $2}' )
  GPS_longitude=$( echo $geo_data | awk -F"+|-" '{print substr($0,index($0,$3-1),1) $3}' )
  echo $GPS_latitude
  echo $GPS_longitude
</code>```

But what I get out seems to confuse the +/- signs in front of each component:

```<code>-04.7367+055.5230
-04.7367
-055.5230
</code>```

I thought the index()-parameters would exactly avoid this situation, but obviously I did something wrong. Any idea how to fix this?

Title: Trimming GPS information with awk

Body:
In a little bash script I simply try to trim GPS input data so that I have longitude and latitude values in separate variables:

  echo $geo_data
  GPS_latitude=$( echo $geo_data | awk -F"+|-" '{print substr($0,index($0,$2-1),1) $2}' )
  GPS_longitude=$( echo $geo_data | awk -F"+|-" '{print substr($0,index($0,$3-1),1) $3}' )
  echo $GPS_latitude
  echo $GPS_longitude

But what I get out seems to confuse the +/- signs in front of each component:

-04.7367+055.5230
-04.7367
-055.5230

I thought the index()-parameters would exactly avoid this situation, but obviously I did something wrong. Any idea how to fix this?

Body:
You need to subtract 1 from the output of index not the field value

$ echo '-04.7367+055.5230' | awk -F"+|-" '{print substr($0,index($0,$2)-1,1) $2}'
-04.7367
$ echo '-04.7367+055.5230' | awk -F"+|-" '{print substr($0,index($0,$3)-1,1) $3}'
+055.5230

You can also use bash parameter expansion

$ s='-04.7367+055.5230'
$ a="${s%+*}"
$ b="${s#${s%+*}}"
$ echo "$a"
-04.7367
$ echo "$b"
+055.5230

$ # or, use the value of variable 'a'
$ c="${s#$a}"
$ echo "$c"
+055.5230


问:
Write a bash function/script that takes 2 parameters, filename and increment, and then increments the number of the filename by the increment
I have a folder with files that have the exact structure, that is file01.txt, file02.txt and so on..
i need to write a function that takes the filename, for example file08.txt, and increment, lets say 4, and then renames file08.txt to file12.txt.

Thank you in advance.

答:
```<code>#!/bin/bash
function inc {
        incrementor=$2
        filename=$(basename -- "$1")
        extention="${filename##*.}"
        filename="${filename%.*}"
        number=$(echo "$filename" | tr -dc '0-9')
        let " number+=incrementor "
        filename=$(echo "$filename" | tr -d '0-9')
        mv $1 "$filename$number.$extention"
        echo "$filename $number $extention"
}
filename=$1
increment=$2
inc $filename $increment
</code>```

Got it!

Body:
#!/bin/bash
function inc {
        incrementor=$2
        filename=$(basename -- "$1")
        extention="${filename##*.}"
        filename="${filename%.*}"
        number=$(echo "$filename" | tr -dc '0-9')
        let " number+=incrementor "
        filename=$(echo "$filename" | tr -d '0-9')
        mv $1 "$filename$number.$extention"
        echo "$filename $number $extention"
}
filename=$1
increment=$2
inc $filename $increment

Got it!


问:
get array values in python
I have the values arr1  as 25,26 and arr2 values as A,B

Its always that the number of values in arr1 and arr2 are equal

My question is that

```<code>          for i in arr1.split(","):
                print i //prints 25 and 26
</code>```

is it not possible to get the values of arr2 in the same loop or should  another loop be written only for this purpose.Basically the idea is that map the values of arr1 and arr2

答: You can't do it on only one loop, it isn't possible. You would have to do each loop individually. Theres not really a way around it. Sorry.</p>

Title: get array values in python

Body:
I have the values arr1  as 25,26 and arr2 values as A,B

Its always that the number of values in arr1 and arr2 are equal

My question is that

          for i in arr1.split(","):
                print i //prints 25 and 26

is it not possible to get the values of arr2 in the same loop or should  another loop be written only for this purpose.Basically the idea is that map the values of arr1 and arr2


问:
Flutter - How to play a Google Drive video preview using webview_flutter package
I have an app that needs to play a Google Drive Video from my account, I'm using this webview_flutter plugin also tried with this too flutter_webview_plugin, The thumbnail appears but when I tap play I get the errors below:

```<code>String url = 'https://drive.google.com/file/d/1O8WF2MsdyoKpQZE2973IFPRpqwKUjm_q/preview';

           WebView(
                onWebViewCreated: (WebViewController controller){

                  webViewController = controller;

                },
                initialUrl: url,
                javascriptMode: JavascriptMode.unrestricted,
                initialMediaPlaybackPolicy: AutoMediaPlaybackPolicy.always_allow,
              ),
</code>```

Errors:

```<code> "The deviceorientation events are blocked by feature policy. See https://github.com/WICG/feature-policy/blo
b/master/features.md#sensor-features", source: https://youtube.googleapis.com/s/player/64dddad9/player_ias.vflset/pt_BR/base.js (263)
</code>```

The second time I tap play:

```<code>I/chromium(29212): [INFO:CONSOLE(1472)] "Uncaught (in promise) Error: Untrusted URL: https://youtube.googleapis.com/videoplayback?expire=158836583
1&ei=x1GsXtyWNuzPj-8Px_eH2Aw&ip=2804:431:c7da:c52b:854e:e83e:e7c5:eb3e&cp=QVNNWkRfVFhRQlhOOk5mQ0FhT0J5Y0k2T3ZDdjJLa0UzQVRiaHNoQlVHeXpjV3BtYW9YT2Rk
YUM&id=eb79141269cc6ad3&itag=18&source=webdrive&requiressl=yes&mh=F-&mm=32&mn=sn-bg0eznll&ms=su&mv=m&mvi=4&pl=47&ttl=transient&susc=dr&driveid=1O8
WF2MsdyoKpQZE2973IFPRpqwKUjm_q&app=explorer&mime=video/mp4&dur=2.043&lmt=1551969798109476&mt=1588351334&sparams=expire,ei,ip,cp,id,itag,source,req
uiressl,ttl,susc,driveid,app,mime,dur,lmt&sig=AOq0QJ8wRAIgEzxYGpS8RI0CRVPdZrMxdDGfkYfCezdOkiJ7iUcl5XMCIHiDsmbGel8tWT6XIU8dWdfjLJWdOlI_WHNtDNwYszU9
&lsparams=mh,mm,mn,ms,mv,mvi,pl&lsig=AG3C_xAwRAIgTq3W38roufwBwSPXe4fxB25kANk3s42N5x2oBvVWonoCIDaYJVrPpmNzcoU6q4bqogHP6W-Mw4p_5CRrwh59kZM4&cpn=bCev
241Hx8eXmwyo&c=WEB_EMBEDDED_PLAYER&cver=20200429", source: https://youtube.googleapis.com/s/player/64dddad9/player_ias.vflset/pt_BR/base.js (1472)
</code>```

答:
You can try my plugin flutter_inappwebview, which is a Flutter plugin that allows you to add inline WebViews or open an in-app browser window and has a lot of events, methods, and options to control WebViews.

Here is the code example using your Google Drive URL and it is working properly:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  InAppWebViewController webView;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('InAppWebView Example'),
        ),
        body: Container(
            child: Column(children: <Widget>[
          Expanded(
              child: InAppWebView(
            initialUrl: "https://drive.google.com/file/d/1O8WF2MsdyoKpQZE2973IFPRpqwKUjm_q/preview",
            initialHeaders: {},
            initialOptions: InAppWebViewGroupOptions(
              crossPlatform: InAppWebViewOptions(
                debuggingEnabled: true,
              ),
            ),
            onWebViewCreated: (InAppWebViewController controller) {
              webView = controller;
            },
            onLoadStart: (InAppWebViewController controller, String url) {},
            onLoadStop: (InAppWebViewController controller, String url) {},
          ))
        ])),
      ),
    );
  }
}
```

Screenshot (.gif):

Body:
I have an app that needs to play a Google Drive Video from my account, I'm using this webview_flutter plugin also tried with this too flutter_webview_plugin, The thumbnail appears but when I tap play I get the errors below:

String url = 'https://drive.google.com/file/d/1O8WF2MsdyoKpQZE2973IFPRpqwKUjm_q/preview';

           WebView(
                onWebViewCreated: (WebViewController controller){

                  webViewController = controller;

                },
                initialUrl: url,
                javascriptMode: JavascriptMode.unrestricted,
                initialMediaPlaybackPolicy: AutoMediaPlaybackPolicy.always_allow,
              ),

Errors:

 "The deviceorientation events are blocked by feature policy. See https://github.com/WICG/feature-policy/blo
b/master/features.md#sensor-features", source: https://youtube.googleapis.com/s/player/64dddad9/player_ias.vflset/pt_BR/base.js (263)

The second time I tap play:

I/chromium(29212): [INFO:CONSOLE(1472)] "Uncaught (in promise) Error: Untrusted URL: https://youtube.googleapis.com/videoplayback?expire=158836583
1&ei=x1GsXtyWNuzPj-8Px_eH2Aw&ip=2804:431:c7da:c52b:854e:e83e:e7c5:eb3e&cp=QVNNWkRfVFhRQlhOOk5mQ0FhT0J5Y0k2T3ZDdjJLa0UzQVRiaHNoQlVHeXpjV3BtYW9YT2Rk
YUM&id=eb79141269cc6ad3&itag=18&source=webdrive&requiressl=yes&mh=F-&mm=32&mn=sn-bg0eznll&ms=su&mv=m&mvi=4&pl=47&ttl=transient&susc=dr&driveid=1O8
WF2MsdyoKpQZE2973IFPRpqwKUjm_q&app=explorer&mime=video/mp4&dur=2.043&lmt=1551969798109476&mt=1588351334&sparams=expire,ei,ip,cp,id,itag,source,req
uiressl,ttl,susc,driveid,app,mime,dur,lmt&sig=AOq0QJ8wRAIgEzxYGpS8RI0CRVPdZrMxdDGfkYfCezdOkiJ7iUcl5XMCIHiDsmbGel8tWT6XIU8dWdfjLJWdOlI_WHNtDNwYszU9
&lsparams=mh,mm,mn,ms,mv,mvi,pl&lsig=AG3C_xAwRAIgTq3W38roufwBwSPXe4fxB25kANk3s42N5x2oBvVWonoCIDaYJVrPpmNzcoU6q4bqogHP6W-Mw4p_5CRrwh59kZM4&cpn=bCev
241Hx8eXmwyo&c=WEB_EMBEDDED_PLAYER&cver=20200429", source: https://youtube.googleapis.com/s/player/64dddad9/player_ias.vflset/pt_BR/base.js (1472)

Body:
You can try my plugin flutter_inappwebview, which is a Flutter plugin that allows you to add inline WebViews or open an in-app browser window and has a lot of events, methods, and options to control WebViews.

Here is the code example using your Google Drive URL and it is working properly:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  InAppWebViewController webView;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('InAppWebView Example'),
        ),
        body: Container(
            child: Column(children: <Widget>[
          Expanded(
              child: InAppWebView(
            initialUrl: "https://drive.google.com/file/d/1O8WF2MsdyoKpQZE2973IFPRpqwKUjm_q/preview",
            initialHeaders: {},
            initialOptions: InAppWebViewGroupOptions(
              crossPlatform: InAppWebViewOptions(
                debuggingEnabled: true,
              ),
            ),
            onWebViewCreated: (InAppWebViewController controller) {
              webView = controller;
            },
            onLoadStart: (InAppWebViewController controller, String url) {},
            onLoadStop: (InAppWebViewController controller, String url) {},
          ))
        ])),
      ),
    );
  }
}

Screenshot (.gif):


答:
You may use sed to extract these values:

```<code>geo_data='-04.7367+055.5230'
GPS_latitude=$(sed 's/\(.*\)[-+].*/\1/' <<< "$geo_data")
GPS_longitude=$(sed 's/.*\([-+].*\)/\1/' <<< "$geo_data")
echo "GPS Latitude: ${GPS_latitude} and GPS longitude: ${GPS_longitude}"
# => GPS Latitude: -04.7367 and GPS longitude: +055.5230
</code>```

See the online demo

The latitude pattern is \(.*\)[-+].*, it captures all chars up to the last + or - into Group 1 and then matches the rest. The match is replaced with group 1 contents, so you get all before the last + or -.

POSIX BRE regex details

\( - start of a capturing group #1 (\1 refers this value from the replacement pattern)

.* - any 0 or more chars

\) - end of the capturing group

[-+] - a bracket expression matching either - or +

.* - - any 0 or more chars.

The GPS_longitude pattern is identical, but captures all after last - or + including the plus or hyphen.

Title: Trimming GPS information with awk

Body:
You may use sed to extract these values:

geo_data='-04.7367+055.5230'
GPS_latitude=$(sed 's/\(.*\)[-+].*/\1/' <<< "$geo_data")
GPS_longitude=$(sed 's/.*\([-+].*\)/\1/' <<< "$geo_data")
echo "GPS Latitude: ${GPS_latitude} and GPS longitude: ${GPS_longitude}"
# => GPS Latitude: -04.7367 and GPS longitude: +055.5230

See the online demo

The latitude pattern is \(.*\)[-+].*, it captures all chars up to the last + or - into Group 1 and then matches the rest. The match is replaced with group 1 contents, so you get all before the last + or -.

POSIX BRE regex details

\( - start of a capturing group #1 (\1 refers this value from the replacement pattern)

.* - any 0 or more chars

\) - end of the capturing group

[-+] - a bracket expression matching either - or +

.* - - any 0 or more chars.

The GPS_longitude pattern is identical, but captures all after last - or + including the plus or hyphen.


问:
Builds fail: https://apt.puppetlabs.com, certificate chain uses expired certificate
My builds started failing this afternoon, with this:

```<code>Notice: /Stage[main]/Server_init::Apt_get_update/Exec[apt-get-update]/returns:
Err:16 https://apt.puppetlabs.com bionic Release

Notice: /Stage[main]/Server_init::Apt_get_update/Exec[apt-get-update]/returns:
Certificate verification failed: The certificate is NOT trusted.
The certificate chain uses expired certificate.  Could not handshake:
Error in the certificate verification. [IP: 13.33.171.122 443]
</code>```

I assume the expired certificate expired this morning, since an earlier successful build.

How do I sort out which cert it is which has failed?  And what I can do to get it updated.  This says it is some cert in the chain, which I assume means that it is not necessarily the one for apt.puppetlabs.com.

Is there some way for me to tell apt to ignore the certs on this repo, for the time being, so I can resume work on my ticket, instead of this new bug?

答:
There may be a more convenient way to do this, but here is how I found the broken link in the certificate chain:

```<code>openssl s_client </dev/null -showcerts -connect apt.puppetlabs.com:443 -servername apt.puppetlabs.com | awk 'BEGIN { pem_to_text = "openssl x509 -noout -text" }; /BEGIN CERTIFICATE/ { on = 1 }; on == 1 { print $0 | pem_to_text }; /END CERTIFICATE/ { on = 0; close(pem_to_text) }'
</code>```

At the time of writing, one of the certificates in the chain (CN = USERTrust RSA Certification Authority) had expired as of May 30 10:48:38 2020 GMT.

Note, however, that on newer operating system versions (like Ubuntu 20.04) the problem does not cause an error, because the ca-certificates package contains an updated CA certificate for the same entity and public key, that is valid through Jan 18 23:59:59 2038 GMT, and newer versions of libssl (OpenSSL) take advantage of that fact (it seems) to verify the leaf certificate.

Body:
My builds started failing this afternoon, with this:

Notice: /Stage[main]/Server_init::Apt_get_update/Exec[apt-get-update]/returns:
Err:16 https://apt.puppetlabs.com bionic Release

Notice: /Stage[main]/Server_init::Apt_get_update/Exec[apt-get-update]/returns:
Certificate verification failed: The certificate is NOT trusted.
The certificate chain uses expired certificate.  Could not handshake:
Error in the certificate verification. [IP: 13.33.171.122 443]

I assume the expired certificate expired this morning, since an earlier successful build.

How do I sort out which cert it is which has failed?  And what I can do to get it updated.  This says it is some cert in the chain, which I assume means that it is not necessarily the one for apt.puppetlabs.com.

Is there some way for me to tell apt to ignore the certs on this repo, for the time being, so I can resume work on my ticket, instead of this new bug?

Body:
There may be a more convenient way to do this, but here is how I found the broken link in the certificate chain:

openssl s_client </dev/null -showcerts -connect apt.puppetlabs.com:443 -servername apt.puppetlabs.com | awk 'BEGIN { pem_to_text = "openssl x509 -noout -text" }; /BEGIN CERTIFICATE/ { on = 1 }; on == 1 { print $0 | pem_to_text }; /END CERTIFICATE/ { on = 0; close(pem_to_text) }'

At the time of writing, one of the certificates in the chain (CN = USERTrust RSA Certification Authority) had expired as of May 30 10:48:38 2020 GMT.

Note, however, that on newer operating system versions (like Ubuntu 20.04) the problem does not cause an error, because the ca-certificates package contains an updated CA certificate for the same entity and public key, that is valid through Jan 18 23:59:59 2038 GMT, and newer versions of libssl (OpenSSL) take advantage of that fact (it seems) to verify the leaf certificate.


问:
Insert selective columns into collection using mongodb
Wrote a trigger function that inserts  full documents to my collection new_list when ever there is an insert into listingsAndReviews collection.

```<code>exports = function(changeEvent) {

    const fullDocument = changeEvent.fullDocument;

    const collection = context.services.get('Cluster0').db("sample_airbnb").collection("new_list");

    return collection.insertMany([fullDocument])
  .then(result => {
    console.log(`Successfully inserted ${result.insertedIds.length} items!`);
    return result;
  })
  .catch(err => console.error(`Failed to insert documents: ${err}`));

};
</code>```

Is there a way to select only particular required columns while inserting data into new_list collection.
In this case i need to insert only name and cart_id and ignore others.

My sample collection column names :

```<code>name     - string
cart_id   - objectid
number - string
address - string
</code>```

答:
You can extract your required properties from fullDocument and just insert this new object:

```<code>return collection.insertMany([{name: fullDocument.name, cart_id: fullDocument.cart_id }])
</code>```

Afaik there's no other way to "filter" properties on the insert-methods.
Also note that you can use insertOne here instead of insertMany as you're only inserting one document.

Body:
Wrote a trigger function that inserts  full documents to my collection new_list when ever there is an insert into listingsAndReviews collection.

exports = function(changeEvent) {

    const fullDocument = changeEvent.fullDocument;

    const collection = context.services.get('Cluster0').db("sample_airbnb").collection("new_list");

    return collection.insertMany([fullDocument])
  .then(result => {
    console.log(`Successfully inserted ${result.insertedIds.length} items!`);
    return result;
  })
  .catch(err => console.error(`Failed to insert documents: ${err}`));

};

Is there a way to select only particular required columns while inserting data into new_list collection.
In this case i need to insert only name and cart_id and ignore others.

My sample collection column names :

name     - string
cart_id   - objectid
number - string
address - string

Body:
You can extract your required properties from fullDocument and just insert this new object:

return collection.insertMany([{name: fullDocument.name, cart_id: fullDocument.cart_id }])

Afaik there's no other way to "filter" properties on the insert-methods.
Also note that you can use insertOne here instead of insertMany as you're only inserting one document.


问:
Is it possible to use classical converter with parameters in MultiBinding QuickConverter in WPF?
Is it possible to use classical converter with parameters with QuickConverter MultiBinding in WPF ?

More clearly, I want to bind the Text property of a TextBlock to display a text like this :

```<code><MyApplication> + ' v' + <1.0>
</code>```

MyApplication comes from a string resource Resources.String225 and 1.0 might comes from an IValueConverter class type to which I may pass the parameter myParameter .
I tried the XAML code below,

```<code><TextBlock Text="{qc:MultiBinding '$V0 + \' v\' + $V1',
 V0={x:Static resx:Resources.String225},
 V1={Binding Converter={StaticResource ProgramVersionConverter}, ConverterParameter='myParameter'}}"/>
</code>```

With the following Converter :

```<code>public class ProgramVersionConverter : IValueConverter
{
    public static Func<string, string> GetApplicationExeVersion;

    /// <summary>
    /// Returns version of the executable
    /// </summary>
    /// <param name="value"></param>
    /// <param name="targetType"></param>
    /// <param name="parameter"></param>
    /// <param name="culture"></param>
    /// <returns></returns>
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return GetApplicationExeVersion?.Invoke((string)parameter);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException("ProgramVersion converter ConvertBack not supported.");
    }
}
</code>```

GetApplicationExeVersion is set to a method in another part of code, not needed there.

But I'm getting this Exception at runtime :

```<code>System.Windows.Markup.XamlParseException:
'Unable to set' Binding 'on property' V1 'of type' MultiBinding '.
A 'Binding' can only be defined on a DependencyProperty of a DependencyObject. '
</code>```

Am I in the rigth way or it is not possible to do it ?

Thank you for your attention.

答:
Of course, you can.

If you want to add a value as a result of a System.Windows.Data.Binding (or System.Windows.Data.MultiBinding etc.), you have to use one of the P0...P9 properties of the QuickConverter.MultiBinding, as they only accept binding expressions. The V0...V9 properties only accept constant values, no binding expressions.

```<code><TextBlock Text="{qc:MultiBinding '$V0 + \' v\' + $P0',
 V0={x:Static resx:Resources.String225},
 P0={Binding Converter={StaticResource ProgramVersionConverter}, ConverterParameter='myParameter'}}"/>
</code>```

Body:
Is it possible to use classical converter with parameters with QuickConverter MultiBinding in WPF ?

More clearly, I want to bind the Text property of a TextBlock to display a text like this :

<MyApplication> + ' v' + <1.0>

MyApplication comes from a string resource Resources.String225 and 1.0 might comes from an IValueConverter class type to which I may pass the parameter myParameter .
I tried the XAML code below,

<TextBlock Text="{qc:MultiBinding '$V0 + \' v\' + $V1',
 V0={x:Static resx:Resources.String225},
 V1={Binding Converter={StaticResource ProgramVersionConverter}, ConverterParameter='myParameter'}}"/>

With the following Converter :

public class ProgramVersionConverter : IValueConverter
{
    public static Func<string, string> GetApplicationExeVersion;

    ///
    /// Returns version of the executable
    ///
    /// <param name="value"></param>
    /// <param name="targetType"></param>
    /// <param name="parameter"></param>
    /// <param name="culture"></param>
    /// <returns></returns>
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return GetApplicationExeVersion?.Invoke((string)parameter);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException("ProgramVersion converter ConvertBack not supported.");
    }
}

GetApplicationExeVersion is set to a method in another part of code, not needed there.

But I'm getting this Exception at runtime :

System.Windows.Markup.XamlParseException:
'Unable to set' Binding 'on property' V1 'of type' MultiBinding '.
A 'Binding' can only be defined on a DependencyProperty of a DependencyObject. '

Am I in the rigth way or it is not possible to do it ?

Thank you for your attention.

Body:
Of course, you can.

If you want to add a value as a result of a System.Windows.Data.Binding (or System.Windows.Data.MultiBinding etc.), you have to use one of the P0...P9 properties of the QuickConverter.MultiBinding, as they only accept binding expressions. The V0...V9 properties only accept constant values, no binding expressions.

<TextBlock Text="{qc:MultiBinding '$V0 + \' v\' + $P0',
 V0={x:Static resx:Resources.String225},
 P0={Binding Converter={StaticResource ProgramVersionConverter}, ConverterParameter='myParameter'}}"/>


问:
How to get parameter from view in onclick function in kotlin?
I have an Android app developed in Kotlin(in AndroidStudio). In each element of RecyclerView I have a button with onclickFunction and I want to use a value from that element's view (precisely: "id" column of database table row, which give data to that element of RecycleView, which I already put in invisible textView) but how can I access it in onclick function?

So for example, I have RecyclerView element for data from database with Id=0, so for it's button I want to pass this 0 as parameter.

答:
If you set a new click listener in onBindViewHolder, you can simply reference the id from the item for that row in the listener. But this allocates new near-identical listeners for every item, which can potentially cause little GC stutters when scrolling a list fast. You could instead set the view’s tag value to the ID. Then you can have a common listener for all list items.

```<code>// Can set this same listener instance for every view:
val listener = OnClickListener { view ->
    val id = view.tag as Int
    //...
}

// In onBindViewHolder
val id = //...
holder.myView.apply {
    tag = id
    setOnClickListener(listener)
}
</code>```

Body:
If you set a new click listener in onBindViewHolder, you can simply reference the id from the item for that row in the listener. But this allocates new near-identical listeners for every item, which can potentially cause little GC stutters when scrolling a list fast. You could instead set the view’s tag value to the ID. Then you can have a common listener for all list items.

// Can set this same listener instance for every view:
val listener = OnClickListener { view ->
    val id = view.tag as Int
    //...
}

// In onBindViewHolder
val id = //...
holder.myView.apply {
    tag = id
    setOnClickListener(listener)
}


问:
VS code is showing me +5000 files that supposedly have changed on my "macbook" repository, i don't know how this happened
This is why i think it has created a git repo on my main drive:

Not sure how this happened:

I think, I mistakenly added my macbook drive as a repository from Github desktop and i don't know how to get rid of this.

答:
Based on answer from Mkasberg.

You can navigate to the folder. and press Cmd + shift + .

This will allow you to see in finder the hidden folder such as .git


问:
Is there any reason to use enum params over bit flags in c#?
Lets say, for example, I have two implementations, one with bit flags and one with simple enum:

1) bit flags

```<code>[Flags]
public enum LettersBitFlags
{
    A = 1,
    B = 2,
    C = 4,
    D = 8
}
</code>```

```<code>public static bool IsLetterBBitFlags(LettersBitFlags letters)
{
    return (letters & LettersBitFlags.B) != 0;
}

</code>```

2) simple enum

```<code>public enum Letters
{
    A,
    B,
    C,
    D
}
</code>```

```<code>public static bool IsLetterBParams(params Letters[] letters)
{
    return letters.Any(x => x == Letters.B);
}
</code>```

They obviously can be used like this:

```<code>Console.WriteLine(IsLetterBBitFlags(LettersBitFlags.A | LettersBitFlags.D)); //false
Console.WriteLine(IsLetterBBitFlags(LettersBitFlags.B | LettersBitFlags.C)); //true

Console.WriteLine(IsLetterBParams(Letters.A, Letters.D)); //false
Console.WriteLine(IsLetterBParams(Letters.B, Letters.C)); //true
</code>```

Is there any practical reason to choose one over the other? As I see, they give the same result, but maybe some performance or anything else should make me use one and did not use the other?

答: The 1st option is good when you represent data in some byte/ int bits, and the data may contain 1 or more of the enum values and then you ca check if data has flag or not.</p>

Body:
Lets say, for example, I have two implementations, one with bit flags and one with simple enum:

1) bit flags

[Flags]
public enum LettersBitFlags
{
    A = 1,
    B = 2,
    C = 4,
    D = 8
}

public static bool IsLetterBBitFlags(LettersBitFlags letters)
{
    return (letters & LettersBitFlags.B) != 0;
}

2) simple enum

public enum Letters
{
    A,
    B,
    C,
    D
}

public static bool IsLetterBParams(params Letters[] letters)
{
    return letters.Any(x => x == Letters.B);
}

They obviously can be used like this:

Console.WriteLine(IsLetterBBitFlags(LettersBitFlags.A | LettersBitFlags.D)); //false
Console.WriteLine(IsLetterBBitFlags(LettersBitFlags.B | LettersBitFlags.C)); //true

Console.WriteLine(IsLetterBParams(Letters.A, Letters.D)); //false
Console.WriteLine(IsLetterBParams(Letters.B, Letters.C)); //true

Is there any practical reason to choose one over the other? As I see, they give the same result, but maybe some performance or anything else should make me use one and did not use the other?


问:
Remove Angular Material Theme
I started building the front end of my web application using the angular material "Indigo-Pink" theme. Now I want to switch to a custom theme but am not sure how to do that. In particular I don't know how to remove the old theme. I was able to install the custom theme without removing the other theme, but this does not seem like particularly clean solution and I fear it might lead to problems later on.
How would I remove the old "Indigo Pink" theme the right way?

Thank you very much in advance!
Any help is highly appreciated!

Best regards,
Sam

答: Search for "indigo-pink." in any of your project files and follow the official tutorial on customizing themes: https://material.angular.io/guide/theming</p>

Title: Remove Angular Material Theme


问:
How to set targets in prometheus kubernetes?
I am trying to setup Prometheus for my Kubernetes cluster. I am using https://github.com/coreos/kube-prometheus . I am using default namespace only. When I apply resources from manifests (https://github.com/coreos/kube-prometheus/tree/master/manifests) folder, It creates resources but in targets, it doesn't show my pod service.

I am new to Kubernetes so I need help with this. How do I configure my pod to show up in Prometheus targets?
I tried https://github.com/coreos/kube-prometheus#quickstart

答:
For better manageability use Prometheus Operator.

You need to define ServiceMonitor or PodMonitor

ServiceMonitor which declaratively specifies how groups of services should be monitored. The Operator automatically generates Prometheus scrape configuration based on the definition and the targets will have the  IPs of all the pods behind the service.

PodMonitor, which declaratively specifies how groups of pods should be monitored. The Operator automatically generates Prometheus scrape configuration based on the definition and targets will have the Pod IP

Refer to the examples here


问:
Waiting for data to be retrieved from local storage
When the gallery is loaded in my gallery app, a functioned is called to check whether the current user has liked an image in an array of images. If the user has liked the image, a solid heart icon is displayed on top of the image. If the hasn't liked the image, a heart outline icon is displayed.

Within the function, we get the current users index in an array of users. This information is retrieved from a user object which is stored in the browsers local storage. The problem I am having is that the function is called before the user data is retrieved from the local storage and I'm not sure how to get around this problem?

Here is the relevant html from the gallery-list component:

```<code><div class="gallery-container">
    <div
      class="image-container"
      *ngFor="let image of galleryList">
      <div *ngIf="checkLike(image.imagePath)" class="heart-icon-container">
        <ion-icon name="heart" class="heart-icon" (click)="updateLike(image.imagePath)"></ion-icon>
      </div>
      <div *ngIf="!checkLike(image.imagePath)" class="heart-icon-container">
        <ion-icon name="heart-outline" class="heart-icon" (click)="updateLike(image.imagePath)"></ion-icon>
      </div>
    </div>
</div>
</code>```

Here is the relevant code from the gallery-list ts file:

```<code>  currUsersIndex: number;

ngOnInit() {

    this.currUsersIndex = this.usersService.getCurrUserArrIndex();

}

 checkLike(imageUrl: string): boolean {
    const users = this.usersService.getUsers();

    if(this.isLoggedIn) {
      const FavouritesList = users[this.currUsersIndex].likes;

      if(FavouritesList.includes(imageUrl)) {
          return true;
      } else {
          return false;
      }
  }
    }
</code>```

Finally, this is where the users index is retrieved from the users.service file:

```<code>private users: User[] = [];
 getCurrUserArrIndex() {

        const usersEmail = this.getCurrentUser().email;

        const users = this.getUsers();

        const usersIndex = users.findIndex(user => user.email === usersEmail);

        return usersIndex;

        }

 getCurrentUser() {

    const userData: {

         email: string,
         id: string,
         _token: string,
         _tokenExpirationDate: string

     } = JSON.parse(localStorage.getItem('authUserData'));

 return userData;

 }

    getUsers() {
        return this.users.slice();
    }
</code>```

Please note, the users array is initially set to empty but it is set with the users from a firebase database when the app initializes.

The error message I am receiving in the console is: "can't access property "likes", users[this.currUsersIndex] is undefined"

答:
You don't need to separate things IMO. You can update your code to this, this will be error-proof.</p>

```<code>checkLike(imageUrl: string): boolean {
    const user = this.usersService.getCurrentUser();

    if(user && user.likes) {
      const FavouritesList = user.likes;
      return FavouritesList.includes(imageUrl);
    }

    return false
}

getCurrentUser() {
  const userData: {
        email: string,
        id: string,
        _token: string,
        _tokenExpirationDate: string
    } = JSON.parse(localStorage.getItem('authUserData'));

  const userEmail = userData.email;

  const users = this.getUsers();
  return users.find(user => user.email === usersEmail);
}
</code>```

Body:
When the gallery is loaded in my gallery app, a functioned is called to check whether the current user has liked an image in an array of images. If the user has liked the image, a solid heart icon is displayed on top of the image. If the hasn't liked the image, a heart outline icon is displayed.

Within the function, we get the current users index in an array of users. This information is retrieved from a user object which is stored in the browsers local storage. The problem I am having is that the function is called before the user data is retrieved from the local storage and I'm not sure how to get around this problem?

Here is the relevant html from the gallery-list component:

        <ion-icon name="heart" class="heart-icon" (click)="updateLike(image.imagePath)"></ion-icon>

        <ion-icon name="heart-outline" class="heart-icon" (click)="updateLike(image.imagePath)"></ion-icon>

Here is the relevant code from the gallery-list ts file:

  currUsersIndex: number;

ngOnInit() {

    this.currUsersIndex = this.usersService.getCurrUserArrIndex();

}

 checkLike(imageUrl: string): boolean {
    const users = this.usersService.getUsers();

    if(this.isLoggedIn) {
      const FavouritesList = users[this.currUsersIndex].likes;

      if(FavouritesList.includes(imageUrl)) {
          return true;
      } else {
          return false;
      }
  }
    }

Finally, this is where the users index is retrieved from the users.service file:

private users: User[] = [];
 getCurrUserArrIndex() {

        const usersEmail = this.getCurrentUser().email;

        const users = this.getUsers();

        const usersIndex = users.findIndex(user => user.email === usersEmail);

        return usersIndex;

        }

 getCurrentUser() {

    const userData: {

         email: string,
         id: string,
         _token: string,
         _tokenExpirationDate: string

     } = JSON.parse(localStorage.getItem('authUserData'));

 return userData;

 }

    getUsers() {
        return this.users.slice();
    }

Please note, the users array is initially set to empty but it is set with the users from a firebase database when the app initializes.

The error message I am receiving in the console is: "can't access property "likes", users[this.currUsersIndex] is undefined"

Body:
You don't need to separate things IMO. You can update your code to this, this will be error-proof.

checkLike(imageUrl: string): boolean {
    const user = this.usersService.getCurrentUser();

    if(user && user.likes) {
      const FavouritesList = user.likes;
      return FavouritesList.includes(imageUrl);
    }

    return false
}

getCurrentUser() {
  const userData: {
        email: string,
        id: string,
        _token: string,
        _tokenExpirationDate: string
    } = JSON.parse(localStorage.getItem('authUserData'));

  const userEmail = userData.email;

  const users = this.getUsers();
  return users.find(user => user.email === usersEmail);
}


问:
AWS SSH access key generation procedure and putting on EC2
I wonder how does AWS EC2 puts the SSH public key on the instance and provides private key to end user. I mean to know how this process of creating an SSH key and putting it on EC2 instance is automated.

答: This process is actually carried out when the instance boots as part of the user data.</p>


问:
Which file(s) do I use for an Android app built with Android Studio
I have followed this tutorial  on how to upload an app to Google Play

I have built my app in Android Studio, tested it and it works. I now want to upload the app to Google Play, Amazon App store, Samsung Apps, my own website etc..

After following the instructions down to the bottom on how to sign my app, I click locate file which takes me to 'build\outputs\apk\debug' and the files are app-debug.apk and output.json.

Are these the files for my app and if I want someone to install my app from my website do they download both?

Edit-

After running build again I found another link further down which takes me to app-release.aab, this looks more accurate.

Is this file my app, does it just need to be downloaded on to an android device to run?

答:
.apk file is the file used for the app.
.aab is a bundle file it is used by app stores to distibute diffierent versions of the same app based on device. </p>

<p>I uploaded .apk file to my server. I can then download that file on my android device from my server and it will run the app. </p>

Body:
.apk file is the file used for the app.
.aab is a bundle file it is used by app stores to distibute diffierent versions of the same app based on device.

I uploaded .apk file to my server. I can then download that file on my android device from my server and it will run the app.


问:
Is there a way to bring all definitions in a C++ struct/class into scope without deriving from it?
Musing on a Sunday...

Deriving from a class brings all names from the base class into the scope of the derived class. However, it also adds the base class non-static data members to every instance of the derived class.

Is there a way to achieve the former without the latter? I'm asking in the interest of concise notation.

Obviously, when the base class doesn't have any data members, I get what I want. There are quite a few empty classes or class templates in the standard library defined to do just that - inject names summarily into a class scope through inheritance. There's even the empty base class optimization to make this as cheap as possible.

But if I wanted to do the same with a non-empty base class, I would be tempted to employ something like:

struct Bar {
    using struct Foo;
};
```

<p>But, alas, that's not supported by C++. My question is, is there another way to achieve the same which I overlooked?</p>

<p>To provide a more complete example:</p>

<pre class="lang-cpp prettyprint-override"><code>struct Foo {
    enum { some_constant=42 };

    // data members follow here ...
};

struct Bar {
    using class Foo;   // this doesn't compile

    int f();
};

int Bar::f() {
    return some_constant;   // I want to use the constant directly, without Foo::
}
</code>```

One clumsy way could be to split the definitions in Foo into two classes, one with the constants (which would be an empty class I could derive from without penalty) and the other with the data members, but that looks rather like an inelegant hack to me.

If there isn't a clean way to achieve this, maybe someone can provide a rationale for why it doesn't exist, or perhaps shouldn't exist.

答: In reference to your specific example you could make the constants you want to access static, which will allow you to access them from the second class by fully qualifying with the "base" class</p>

Body:
Musing on a Sunday...

Deriving from a class brings all names from the base class into the scope of the derived class. However, it also adds the base class non-static data members to every instance of the derived class.

Is there a way to achieve the former without the latter? I'm asking in the interest of concise notation.

Obviously, when the base class doesn't have any data members, I get what I want. There are quite a few empty classes or class templates in the standard library defined to do just that - inject names summarily into a class scope through inheritance. There's even the empty base class optimization to make this as cheap as possible.

But if I wanted to do the same with a non-empty base class, I would be tempted to employ something like:

struct Bar {
    using struct Foo;
};

But, alas, that's not supported by C++. My question is, is there another way to achieve the same which I overlooked?

To provide a more complete example:

struct Foo {
    enum { some_constant=42 };

    // data members follow here ...
};

struct Bar {
    using class Foo;   // this doesn't compile

    int f();
};

int Bar::f() {
    return some_constant;   // I want to use the constant directly, without Foo::
}

One clumsy way could be to split the definitions in Foo into two classes, one with the constants (which would be an empty class I could derive from without penalty) and the other with the data members, but that looks rather like an inelegant hack to me.

If there isn't a clean way to achieve this, maybe someone can provide a rationale for why it doesn't exist, or perhaps shouldn't exist.


问:
how to extaract data from file starting from 2nd line in c
Im very new to this language, can you help me:

Instead of making the user input col, row, and direction(scanf). I want to extract the data from file(format below)

From the file format i do not want to extract the first line(5,6), i only want to extract the remaining lines.

Below is a code of how to extract data from a file(using command line arguments), but this code extract the first line also, and only prints the lines.I do not want to print the line but to extract the data from a file instead of making the user input it.

File format:
colrow direction(starting from 2nd line)

```<code>5,6
A0 H
D0 V
C1 V
A4 H
F0 v
</code>```

code of scanf

```<code>
yourcolumn = getchar();
col = charToNum(yourcolumn);    //function to input column

printf("enter row");
scanf("%d",&row);

printf("h: horizontally or v: vertically?\n");
scanf(" %c",&direction);
</code>```

Code for extracting data from file:

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

int main(int argc, char* argv[])
{
    char const* const fileName = argv[1]; /* should check that argc > 1 */
    FILE* file = fopen(fileName, "r"); /* should check the result */
    char line[256];

    while (fgets(line, sizeof(line), file)) {
        /* note that fgets don't strip the terminating \n, checking its
           presence would allow to handle lines longer that sizeof(line) */
        printf("%s", line);
    }
    /* may check feof here to make a difference between eof and io failure -- network
       timeout for instance */

    fclose(file);

    return 0;
}

</code>```

答:
Since you are reading line-by-line, I suggest you restructure you file reading to match your logic

```<code>while (EOF != fscanf(file, "%[^\n]\n", line)) {
     printf("> %s\n", line);
}
</code>```

Is a way that one can read every line, one at a time.  You can lookup the caveats of using fscanf and how to adjust the code to safely read without overflowing your line buffer.

Then, if you want to skip the first line, your code could look like this

```<code>if (EOF != fscanf(file, "%[^\n]\n", line)) {
    // skip the first line
}
while (EOF != fscanf(file, "%[^\n]\n", line)) {
     printf("> %s\n", line);
}
</code>```

And your processing logic will look a lot like your mental process.

Yes, you could use a line counter, and only process if the counter is high enough; but, it is generally better to avoid introducing variables, if you can live without them.  This is because an extra added variable doesn't make the code too hard to reason about; but, after you've repeated that "extra variable" rationale five or six times, the code quickly turns into something that's harder to maintain and harder to reason about.  By the time you hit twenty or more extra variables, the odds of maintaining the code quickly without breaking it are lower.

Body:
Im very new to this language, can you help me:

Instead of making the user input col, row, and direction(scanf). I want to extract the data from file(format below)

From the file format i do not want to extract the first line(5,6), i only want to extract the remaining lines.

Below is a code of how to extract data from a file(using command line arguments), but this code extract the first line also, and only prints the lines.I do not want to print the line but to extract the data from a file instead of making the user input it.

File format:
colrow direction(starting from 2nd line)

5,6
A0 H
D0 V
C1 V
A4 H
F0 v

code of scanf

yourcolumn = getchar();
col = charToNum(yourcolumn);    //function to input column

printf("enter row");
scanf("%d",&row);

printf("h: horizontally or v: vertically?\n");
scanf(" %c",&direction);

Code for extracting data from file:

#include <stdio.h>

int main(int argc, char* argv[])
{
    char const* const fileName = argv[1]; /* should check that argc > 1 */
    FILE* file = fopen(fileName, "r"); /* should check the result */
    char line[256];

    while (fgets(line, sizeof(line), file)) {
        /* note that fgets don't strip the terminating \n, checking its
           presence would allow to handle lines longer that sizeof(line) */
        printf("%s", line);
    }
    /* may check feof here to make a difference between eof and io failure -- network
       timeout for instance */

    fclose(file);

    return 0;
}

Body:
Since you are reading line-by-line, I suggest you restructure you file reading to match your logic

while (EOF != fscanf(file, "%[^\n]\n", line)) {
     printf("> %s\n", line);
}

Is a way that one can read every line, one at a time.  You can lookup the caveats of using fscanf and how to adjust the code to safely read without overflowing your line buffer.

Then, if you want to skip the first line, your code could look like this

if (EOF != fscanf(file, "%[^\n]\n", line)) {
    // skip the first line
}
while (EOF != fscanf(file, "%[^\n]\n", line)) {
     printf("> %s\n", line);
}

And your processing logic will look a lot like your mental process.

Yes, you could use a line counter, and only process if the counter is high enough; but, it is generally better to avoid introducing variables, if you can live without them.  This is because an extra added variable doesn't make the code too hard to reason about; but, after you've repeated that "extra variable" rationale five or six times, the code quickly turns into something that's harder to maintain and harder to reason about.  By the time you hit twenty or more extra variables, the odds of maintaining the code quickly without breaking it are lower.


问:
TypeError: Object(...) is not a function React.js
[![enter image description here][1]][1]Filename : productScreen.js

Error     : line 6 - TypeError: Object(...) is not a function

Path     :src/Screens/ProductScreen.js

Code as follows:

```<code>  3 | import { Link } from "react-router-dom";
  4 | import { detailsProduct } from "../actions/productActions";
  5 | function ProductScreen(props){
  >6|     const productDetails= useSelector(state => state.productDetails);
  7 |     const {product , loading , error} = productDetails;
  8 |     const dispatch = useDispatch();
  9 |     useEffect(()=>{
  10|          dispatch(detailsProduct(props.match.params.id));
  11|         return () => {
  12|        };
  13|    } , [])
</code>```

Filename : store.js

Path     : src/store.js

Code as follows:

```<code>    1|const initialState = {}
    2|const reducer = combineReducers({
    3|productList: productListReducer,
    4|productDetails: productDetailsReducer
    5| })
    6|const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
    7|const store = createStore(reducer , initialState , composeEnhancer(applyMiddleware(thunk)));
    8|export default store;
</code>```

Filename : index.js

Path     :src/index.js

Code as follows:

```<code>    ReactDOM.render(
    <Provider store = {store}>
    <App />
    </Provider>,
    document.getElementById('root')
    );
    serviceWorker.unregister();
</code>```

All imports are made correctly

答:
It seems that you're missing useSelector import statement.

Add import { useSelector } from "react-redux"; in your ProductScreen.js file.

Body:
[![enter image description here][1]][1]Filename : productScreen.js

Error     : line 6 - TypeError: Object(...) is not a function

Path     :src/Screens/ProductScreen.js

Code as follows:

  3 | import { Link } from "react-router-dom";
  4 | import { detailsProduct } from "../actions/productActions";
  5 | function ProductScreen(props){
  >6|     const productDetails= useSelector(state => state.productDetails);
  7 |     const {product , loading , error} = productDetails;
  8 |     const dispatch = useDispatch();
  9 |     useEffect(()=>{
  10|          dispatch(detailsProduct(props.match.params.id));
  11|         return () => {
  12|        };
  13|    } , [])

Filename : store.js

Path     : src/store.js

Code as follows:

    1|const initialState = {}
    2|const reducer = combineReducers({
    3|productList: productListReducer,
    4|productDetails: productDetailsReducer
    5| })
    6|const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
    7|const store = createStore(reducer , initialState , composeEnhancer(applyMiddleware(thunk)));
    8|export default store;

Filename : index.js

Path     :src/index.js

Code as follows:

    ReactDOM.render(
    <Provider store = {store}>
    <App />
    </Provider>,
    document.getElementById('root')
    );
    serviceWorker.unregister();

All imports are made correctly


问:
Problem with inserting unique value into SQL Server in C#
My code doesn't catch the exception when I try to add the same user to the database and I don't really know how to change it.</p>

```<code>try
{
    SqlConnection.Open();
    string sqlZapytanie = "INSERT INTO Host Values('" + host.Name + "','" +
         host.Surname + "'," + host.PESEL + ",'" + host.City + "','" + host.Street + "', '" + host.House_number + "','" + host.Apartament_number + "','" + host.e_mail + "'," + host.Phone_number + ",'"+host.Login+"')";

    try
    {
        SqlCommand.Connection = SqlConnection;
        SqlCommand.CommandText = sqlZapytanie;
        SqlCommand.ExecuteNonQuery();
    }
    catch(SqlException sqlex)
    {
        MessageBox.Show(sqlex.Message, "Zduplikowany użytkownik.", MessageBoxButton.OK);
    }
</code>```

答: Perhaps the error to be returned is not type SqlException  but type Exception.</p>

Body:
My code doesn't catch the exception when I try to add the same user to the database and I don't really know how to change it.

try
{
    SqlConnection.Open();
    string sqlZapytanie = "INSERT INTO Host Values('" + host.Name + "','" +
         host.Surname + "'," + host.PESEL + ",'" + host.City + "','" + host.Street + "', '" + host.House_number + "','" + host.Apartament_number + "','" + host.e_mail + "'," + host.Phone_number + ",'"+host.Login+"')";

    try
    {
        SqlCommand.Connection = SqlConnection;
        SqlCommand.CommandText = sqlZapytanie;
        SqlCommand.ExecuteNonQuery();
    }
    catch(SqlException sqlex)
    {
        MessageBox.Show(sqlex.Message, "Zduplikowany użytkownik.", MessageBoxButton.OK);
    }


问:
Defold, scale making sprites dissapear
I'm trying to scale my sprite, but it keeps dissapearing. I used go.set_scale(4) which makes it dissapear. There doesn't seem to be anything on the defold page and I have even tried using manuel scaling with the properties options. Why can't I scale the sprite?

Do I need to make them tiles? Those scale fine.

答: I'm betting that the game object/sprite isn't positioned at z-value 0 and when scaled 4 times it probably ends up outside the default -1 to 1 range that is visible in the render script: https://defold.com/manuals/components/#component-z-value</p>

Title: Defold, scale making sprites dissapear


问:
How do I convert an Int to a String in C# without using ToString()?

Convert the following int argument into a string without using any native toString functionality.

```<code>public string integerToString(int integerPassedIn){
    //Your code here
}
</code>```

Since everything inherits from Object and Object has a ToString() method how would you convert an int to a string without using the native ToString() method?

The problem with string concatenation is that it will call ToString() up the chain until it hits one or hits the Object class.

How do you convert an integer to a string in C# without using ToString()?

答:
easy peasy: </p>

```<code>string s = 5 + ""
//s = "5"
</code>```

Body:
Convert the following int argument into a string without using any native toString functionality.

public string integerToString(int integerPassedIn){
    //Your code here
}

Since everything inherits from Object and Object has a ToString() method how would you convert an int to a string without using the native ToString() method?

The problem with string concatenation is that it will call ToString() up the chain until it hits one or hits the Object class.

How do you convert an integer to a string in C# without using ToString()?

Body:
easy peasy:

string s = 5 + ""
//s = "5"


问:
Java equivalent of c++ equal_range (or lower_bound & upper_bound)
I have a List of object sorted and I want to find the first occurrence and the last occurrence of an object. In C++, I can easily use std::equal_range (or just one lower_bound and one upper_bound).

For example:

```<code>bool mygreater (int i,int j) { return (i>j); }

int main () {
  int myints[] = {10,20,30,30,20,10,10,20};
  std::vector<int> v(myints,myints+8);                         // 10 20 30 30 20 10 10 20
  std::pair<std::vector<int>::iterator,std::vector<int>::iterator> bounds;

  // using default comparison:
  std::sort (v.begin(), v.end());                              // 10 10 10 20 20 20 30 30
  bounds=std::equal_range (v.begin(), v.end(), 20);            //          ^        ^

  // using "mygreater" as comp:
  std::sort (v.begin(), v.end(), mygreater);                   // 30 30 20 20 20 10 10 10
  bounds=std::equal_range (v.begin(), v.end(), 20, mygreater); //       ^        ^

  std::cout << "bounds at positions " << (bounds.first - v.begin());
  std::cout << " and " << (bounds.second - v.begin()) << '\n';

  return 0;
}
</code>```

In Java, there seems to be no simple equivalence? How should I do with the equal range with

```<code>List<MyClass> myList;
</code>```

By the way, I am using a standard import java.util.List;

答:
Java equivalent of lower_bound in cpp is

```<code>public static int lower(int arr[],int key){
    int low = 0;
    int high = arr.length-1;
    while(low < high){
        int mid = low + (high - low)/2;
        if(arr[mid] >= key){
            high = mid;
        }
        else{
            low = mid+1;
        }
    }
    return low;
}
</code>```

But the above snippet will give the lower bound if the key is not present in the array

Java equivalent of upper_bound in cpp is

```<code>public static int upper(int arr[],int key){
    int low = 0;
    int high = arr.length-1;
    while(low < high){
        int mid = low + (high - low+1)/2;
        if(arr[mid] <= key){
            low = mid;
        }
        else{
            high = mid-1;
        }
    }
    return low;
}
</code>```

But the above snippet will give the lower bound of key if the key is not present in the array

Body:
I have a List of object sorted and I want to find the first occurrence and the last occurrence of an object. In C++, I can easily use std::equal_range (or just one lower_bound and one upper_bound).

For example:

bool mygreater (int i,int j) { return (i>j); }

int main () {
  int myints[] = {10,20,30,30,20,10,10,20};
  std::vector<int> v(myints,myints+8);                         // 10 20 30 30 20 10 10 20
  std::pair<std::vector<int>::iterator,std::vector<int>::iterator> bounds;

  // using default comparison:
  std::sort (v.begin(), v.end());                              // 10 10 10 20 20 20 30 30
  bounds=std::equal_range (v.begin(), v.end(), 20);            //          ^        ^

  // using "mygreater" as comp:
  std::sort (v.begin(), v.end(), mygreater);                   // 30 30 20 20 20 10 10 10
  bounds=std::equal_range (v.begin(), v.end(), 20, mygreater); //       ^        ^

  std::cout << "bounds at positions " << (bounds.first - v.begin());
  std::cout << " and " << (bounds.second - v.begin()) << '\n';

  return 0;
}

In Java, there seems to be no simple equivalence? How should I do with the equal range with

List<MyClass> myList;

By the way, I am using a standard import java.util.List;

Body:
Java equivalent of lower_bound in cpp is

public static int lower(int arr[],int key){
    int low = 0;
    int high = arr.length-1;
    while(low < high){
        int mid = low + (high - low)/2;
        if(arr[mid] >= key){
            high = mid;
        }
        else{
            low = mid+1;
        }
    }
    return low;
}

But the above snippet will give the lower bound if the key is not present in the array

Java equivalent of upper_bound in cpp is

public static int upper(int arr[],int key){
    int low = 0;
    int high = arr.length-1;
    while(low < high){
        int mid = low + (high - low+1)/2;
        if(arr[mid] <= key){
            low = mid;
        }
        else{
            high = mid-1;
        }
    }
    return low;
}

But the above snippet will give the lower bound of key if the key is not present in the array


问:
How do I install hunspell on windows10?
I'm new to python and need help with getting hunspell installed on my windows 10. The tool is PyCharm.

First I tried to install CyHunspell: pip install CyHunspell and got the following error msg:

RuntimeError: 'pkg-config' is not recognized as an internal or external command,operable program or batch file.
```

<p>Then I tried installing PyHunspell instead and got the following error msg:</p>

<pre class="lang-none prettyprint-override"><code>ERROR: Could not find a version that satisfies the requirement PyHunspell (from versions: none)
ERROR: No matching distribution found for PyHunspell
</code>```

Then I tried installing hunspell directly and got the following error msg:

hunspell.cpp
    hunspell.cpp(20): fatal error C1083: Cannot open include file: 'hunspell.hxx': No such file or directory
    error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe' failed with exit status 2
```

<p>In my test code:</p>

<pre class="lang-py prettyprint-override"><code>import hunspell
</code>```

Result:

spellchecker = hunspell.HunSpell() failed with the following error msg:
AttributeError: module 'hunspell' has no attribute 'HunSpell'
```

I would think I'm not the first one who uses hunspell on windows 10, but somehow I can't seem to find info needed to get this to work.

答:
The GNU Emacs documentation states here (underlined by me):

The EZWinPorts project provides many useful ports of recent versions of GNU and Unix software. This includes all the optional libraries used by Emacs (image libraries, libxml2, GnuTLS), RCS, Texinfo, a clone of man command, Grep, xz, bzip2, bsdtar, ID Utils, Findutils, Hunspell, Gawk, GNU Make, Groff, GDB.

You will indeed find Hunspell in the list of files of the EZWinPorts project on sourceforge.

Once unzipped, you shall find the executable hunspell.exe inside the bin folder. No installation required. The tool is to be used on the command-line. You probably should add it to your Windows Path.

Tested on my Windows 10 PC.

Title: How do I install hunspell on windows10?

Body:
I'm new to python and need help with getting hunspell installed on my windows 10. The tool is PyCharm.

First I tried to install CyHunspell: pip install CyHunspell and got the following error msg:

RuntimeError: 'pkg-config' is not recognized as an internal or external command,operable program or batch file.

Then I tried installing PyHunspell instead and got the following error msg:

ERROR: Could not find a version that satisfies the requirement PyHunspell (from versions: none)
ERROR: No matching distribution found for PyHunspell

Then I tried installing hunspell directly and got the following error msg:

hunspell.cpp
    hunspell.cpp(20): fatal error C1083: Cannot open include file: 'hunspell.hxx': No such file or directory
    error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe' failed with exit status 2

In my test code:

import hunspell

Result:

spellchecker = hunspell.HunSpell() failed with the following error msg:
AttributeError: module 'hunspell' has no attribute 'HunSpell'

I would think I'm not the first one who uses hunspell on windows 10, but somehow I can't seem to find info needed to get this to work.


问:
How to remove multple ceph nodes slowly
In a 20 node cluster with 10 OSDs per node, how would you remove nodes 1-5.
If I reweight the OSDs on node1 then data will move to node2-node20.
Then do the same for node2 through node5.

Is there a way to put the OSDs in node2-node5 in a read-only state so data doesn't have to move twice?

答:
So you want to evict all data from node 1 to 5. This is possible if the remaining nodes can fit all the data with retaining all copies for redundancy.

If this is the case you can reweight all OSDs on node 1 to 5 to zero weight at the same time. With every reweight commond given ceph will recalculate the needed movement. This way the whole data movement is done in one step. Then just sit and wait until the re-balance is finished.

The speed of re-balance is the same like only re-balancing one node, because the objects are re-weighted with the same batch size in the re-balance operation regardless of how many re-weight parameters are changed. Every change results in a new crush map. The cluster will converge towards this new crush map. There are ceph setting to control how much data is moved in parallel.

Alternatively there is also a script that will drain the OSDs at a even slower rate.

After re-balancing you have to remove the OSDs and any remaining ceph services from the evicted nodes. Then you can decommission the old nodes. done.

As a side node: You write, that by re-weighting all OSDs on node 1, data will be moved to node 2. This is not completely correct. Correct is: Data will move to all remaining nodes.

Here is example how I drain OSDs:

First check the OSD tree:

```<code>root@odroid1:~# ceph osd tree
ID   CLASS  WEIGHT    TYPE NAME           STATUS  REWEIGHT  PRI-AFF
 -1         51.93213  root default
 -7         12.73340      host miniceph1
  3    hdd  12.73340          osd.3           up   1.00000  1.00000
 -5         12.73340      host miniceph2
  1    hdd  12.73340          osd.1           up   1.00000  1.00000
 -3         12.73340      host miniceph3
  0    hdd  12.73340          osd.0           up   1.00000  1.00000
-13          2.72899      host miniceph4
  4    hdd   2.72899          osd.4           up   1.00000  1.00000
-11          2.72899      host miniceph5
  5    hdd   2.72899          osd.5           up   1.00000  1.00000
 -9          2.72899      host miniceph6
  2    hdd   2.72899          osd.2           up   1.00000  1.00000
-25          1.86299      host odroid1
  7    ssd   1.86299          osd.7           up   1.00000  1.00000
-22          1.81898      host odroid2
  6    ssd   1.81898          osd.6           up   1.00000  1.00000
-28          1.86299      host odroid3
  8    ssd   1.86299          osd.8           up   1.00000  1.00000
</code>```

In this example the miniceph OSDs contain HDDs and odroid OSDs SSDs.

I like to remove miniceph 2, 4 and 5. These contain smaller disks I'd like to replace. But before removing the the OSDs I'd like to move the data to the remaining miniceph OSDs. That way all data will stay fully replicated. Just removing an OSD will result in a fail scenario.

For this I issue:

```<code>root@odroid1:~# ceph osd reweight osd.4 0
reweighted osd.4 to 0 (0)
root@odroid1:~# ceph osd reweight osd.5 0
reweighted osd.5 to 0 (0)
root@odroid1:~# ceph osd reweight osd.2 0
reweighted osd.2 to 0 (0)
</code>```

And now the data is moved to the remaining OSDs.

```<code>root@odroid1:~# ceph -s
  cluster:
    id:     51c02ed5-2025-4ae7-91d6-fb5450c4b4d7
    health: HEALTH_WARN
            mons are allowing insecure global_id reclaim
            Degraded data redundancy: 4/4707252 objects degraded (0.000%), 1 pg degraded, 2 pgs undersized

  services:
    mon: 3 daemons, quorum odroid2,odroid3,odroid1 (age 24h)
    mgr: odroid1(active, since 24h), standbys: odroid2
    mds: cephfs:1 {0=odroid1=up:active} 1 up:standby
    osd: 9 osds: 9 up (since 24h), 6 in (since 4m); 168 remapped pgs
    rgw: 2 daemons active (odroid1.rgw0, odroid2.rgw0)

  task status:

  data:
    pools:   12 pools, 401 pgs
    objects: 1.57M objects, 1.8 TiB
    usage:   4.2 TiB used, 40 TiB / 44 TiB avail
    pgs:     4/4707252 objects degraded (0.000%)
             1156448/4707252 objects misplaced (24.567%)
             232 active+clean
             165 active+remapped+backfill_wait
             1   active+recovering
             1   active+remapped+backfilling
             1   active+recovery_wait+undersized+degraded+remapped
             1   active+recovering+undersized+remapped

  io:
    recovery: 9.8 MiB/s, 2 objects/s

  progress:
    Rebalancing after osd.4 marked out (7m)
      [===========.................] (remaining: 9m)
    Rebalancing after osd.5 marked out (6m)
      [=========...................] (remaining: 13m)
    Rebalancing after osd.2 marked out (4m)
      [===========.................] (remaining: 6m)
</code>```

Title: How to remove multple ceph nodes slowly

Body:
So you want to evict all data from node 1 to 5. This is possible if the remaining nodes can fit all the data with retaining all copies for redundancy.

If this is the case you can reweight all OSDs on node 1 to 5 to zero weight at the same time. With every reweight commond given ceph will recalculate the needed movement. This way the whole data movement is done in one step. Then just sit and wait until the re-balance is finished.

The speed of re-balance is the same like only re-balancing one node, because the objects are re-weighted with the same batch size in the re-balance operation regardless of how many re-weight parameters are changed. Every change results in a new crush map. The cluster will converge towards this new crush map. There are ceph setting to control how much data is moved in parallel.

Alternatively there is also a script that will drain the OSDs at a even slower rate.

After re-balancing you have to remove the OSDs and any remaining ceph services from the evicted nodes. Then you can decommission the old nodes. done.

As a side node: You write, that by re-weighting all OSDs on node 1, data will be moved to node 2. This is not completely correct. Correct is: Data will move to all remaining nodes.

Here is example how I drain OSDs:

First check the OSD tree:

root@odroid1:~# ceph osd tree
ID   CLASS  WEIGHT    TYPE NAME           STATUS  REWEIGHT  PRI-AFF
 -1         51.93213  root default
 -7         12.73340      host miniceph1
  3    hdd  12.73340          osd.3           up   1.00000  1.00000
 -5         12.73340      host miniceph2
  1    hdd  12.73340          osd.1           up   1.00000  1.00000
 -3         12.73340      host miniceph3
  0    hdd  12.73340          osd.0           up   1.00000  1.00000
-13          2.72899      host miniceph4
  4    hdd   2.72899          osd.4           up   1.00000  1.00000
-11          2.72899      host miniceph5
  5    hdd   2.72899          osd.5           up   1.00000  1.00000
 -9          2.72899      host miniceph6
  2    hdd   2.72899          osd.2           up   1.00000  1.00000
-25          1.86299      host odroid1
  7    ssd   1.86299          osd.7           up   1.00000  1.00000
-22          1.81898      host odroid2
  6    ssd   1.81898          osd.6           up   1.00000  1.00000
-28          1.86299      host odroid3
  8    ssd   1.86299          osd.8           up   1.00000  1.00000

In this example the miniceph OSDs contain HDDs and odroid OSDs SSDs.

I like to remove miniceph 2, 4 and 5. These contain smaller disks I'd like to replace. But before removing the the OSDs I'd like to move the data to the remaining miniceph OSDs. That way all data will stay fully replicated. Just removing an OSD will result in a fail scenario.

For this I issue:

root@odroid1:~# ceph osd reweight osd.4 0
reweighted osd.4 to 0 (0)
root@odroid1:~# ceph osd reweight osd.5 0
reweighted osd.5 to 0 (0)
root@odroid1:~# ceph osd reweight osd.2 0
reweighted osd.2 to 0 (0)

And now the data is moved to the remaining OSDs.

root@odroid1:~# ceph -s
  cluster:
    id:     51c02ed5-2025-4ae7-91d6-fb5450c4b4d7
    health: HEALTH_WARN
            mons are allowing insecure global_id reclaim
            Degraded data redundancy: 4/4707252 objects degraded (0.000%), 1 pg degraded, 2 pgs undersized

  services:
    mon: 3 daemons, quorum odroid2,odroid3,odroid1 (age 24h)
    mgr: odroid1(active, since 24h), standbys: odroid2
    mds: cephfs:1 {0=odroid1=up:active} 1 up:standby
    osd: 9 osds: 9 up (since 24h), 6 in (since 4m); 168 remapped pgs
    rgw: 2 daemons active (odroid1.rgw0, odroid2.rgw0)

  task status:

  data:
    pools:   12 pools, 401 pgs
    objects: 1.57M objects, 1.8 TiB
    usage:   4.2 TiB used, 40 TiB / 44 TiB avail
    pgs:     4/4707252 objects degraded (0.000%)
             1156448/4707252 objects misplaced (24.567%)
             232 active+clean
             165 active+remapped+backfill_wait
             1   active+recovering
             1   active+remapped+backfilling
             1   active+recovery_wait+undersized+degraded+remapped
             1   active+recovering+undersized+remapped

  io:
    recovery: 9.8 MiB/s, 2 objects/s

  progress:
    Rebalancing after osd.4 marked out (7m)
      [===========.................] (remaining: 9m)
    Rebalancing after osd.5 marked out (6m)
      [=========...................] (remaining: 13m)
    Rebalancing after osd.2 marked out (4m)
      [===========.................] (remaining: 6m)


问:
Trying to make sequential executing of futures. What is wrong?
I am trying to execute function which returns Future sequentially

So, I have a collection

```<code>  val in = Seq(1, 1, -1, -2, 3, -4, 5, 6, 7, -1, -2, -9, 1, 2, 2)
</code>```

and function to process every int in this collection

```<code>  def intToFuture(int: Int): Future[Int] = {
    Future {
      println(s"Running function $int")
      Thread.sleep(1500)
      int * 100
    }
  }
</code>```

I need to implement logic that process collection by portions of parallel processing.
Get first n elements, multiply each to 100 in parallel, then get next n elements and do the same... etc.

What I have done(after I read some posts on this site) is, I implement two functions

1)to process a batch of calculations

```<code>  def processBatch(ints: Seq[Int])(f: Int => Future[Int]): Future[Seq[Int]] = {
    Future.sequence(ints.map(f))
  }
</code>```

2)and second, which apply to process iteratively

```<code>  def batchTraverse(in: Seq[Int], size: Int)(f: Int => Future[Int]): Future[Seq[Int]] = {
    val grs = in.grouped(size).toList
    def loop(l: Seq[Seq[Int]]): Future[Seq[Int]] = {
      l match {
        case Nil =>
          Future.successful(l.flatten)//? flatten
        case head :: tail =>
          println("head="+head)
          processBatch(head)(f).flatMap{
            s => loop(tail).map{ t =>
              s.appendedAll(t)
            }
          }
      }
    }
    loop(grs)
  }
</code>```

And start this by

```<code>  val fs: Future[Seq[Int]] = batchTraverse(in, 3)(intToFuture)

  fs.onComplete{
    f => println(f)
  }
</code>```

As a result, it makes only one iteration, where have I mistaken?

答:
Your function actually seems to works fine, what is likely happening is your program is terminating before the future gets a chance to complete, thus you're only seeing the first iteration. By adding an await to your code I was able to get things to work.

```<code>import scala.concurrent._
import scala.concurrent.duration._

val fs: Future[Seq[Int]] = batchTraverse(in, 3)(intToFuture)

fs.onComplete{
  f => println(f)
}

Await.result(fs, Duration.Inf)
</code>```

You'll likely want a duration that smaller than Duration.Inf as this will wait forever for the future to complete. Doing this I was able to get the following output:

```<code>head=List(1, 1, -1)
Running function 1
Running function 1
Running function -1
head=List(-2, 3, -4)
Running function -4
Running function 3
Running function -2
head=List(5, 6, 7)
Running function 7
Running function 6
Running function 5
head=List(-1, -2, -9)
Running function -9
Running function -2
Running function -1
head=List(1, 2, 2)
Running function 2
Running function 2
Running function 1
Success(List(100, 100, -100, -200, 300, -400, 500, 600, 700, -100, -200, -900, 100, 200, 200))
</code>```

Body:
I am trying to execute function which returns Future sequentially

So, I have a collection

  val in = Seq(1, 1, -1, -2, 3, -4, 5, 6, 7, -1, -2, -9, 1, 2, 2)

and function to process every int in this collection

  def intToFuture(int: Int): Future[Int] = {
    Future {
      println(s"Running function $int")
      Thread.sleep(1500)
      int * 100
    }
  }

I need to implement logic that process collection by portions of parallel processing.
Get first n elements, multiply each to 100 in parallel, then get next n elements and do the same... etc.

What I have done(after I read some posts on this site) is, I implement two functions

1)to process a batch of calculations

  def processBatch(ints: Seq[Int])(f: Int => Future[Int]): Future[Seq[Int]] = {
    Future.sequence(ints.map(f))
  }

2)and second, which apply to process iteratively

  def batchTraverse(in: Seq[Int], size: Int)(f: Int => Future[Int]): Future[Seq[Int]] = {
    val grs = in.grouped(size).toList
    def loop(l: Seq[Seq[Int]]): Future[Seq[Int]] = {
      l match {
        case Nil =>
          Future.successful(l.flatten)//? flatten
        case head :: tail =>
          println("head="+head)
          processBatch(head)(f).flatMap{
            s => loop(tail).map{ t =>
              s.appendedAll(t)
            }
          }
      }
    }
    loop(grs)
  }

And start this by

  val fs: Future[Seq[Int]] = batchTraverse(in, 3)(intToFuture)

  fs.onComplete{
    f => println(f)
  }

As a result, it makes only one iteration, where have I mistaken?

Body:
Your function actually seems to works fine, what is likely happening is your program is terminating before the future gets a chance to complete, thus you're only seeing the first iteration. By adding an await to your code I was able to get things to work.

import scala.concurrent._
import scala.concurrent.duration._

val fs: Future[Seq[Int]] = batchTraverse(in, 3)(intToFuture)

fs.onComplete{
  f => println(f)
}

Await.result(fs, Duration.Inf)

You'll likely want a duration that smaller than Duration.Inf as this will wait forever for the future to complete. Doing this I was able to get the following output:

head=List(1, 1, -1)
Running function 1
Running function 1
Running function -1
head=List(-2, 3, -4)
Running function -4
Running function 3
Running function -2
head=List(5, 6, 7)
Running function 7
Running function 6
Running function 5
head=List(-1, -2, -9)
Running function -9
Running function -2
Running function -1
head=List(1, 2, 2)
Running function 2
Running function 2
Running function 1
Success(List(100, 100, -100, -200, 300, -400, 500, 600, 700, -100, -200, -900, 100, 200, 200))


问:
Intersection Observer API not working with hidden elements
I am trying to observe a hidden element. I have an element which has style set to display: none. I want when my element intersect it will perform my action i.e: Play the video. I am sharing my sample code below

```<code> var options = {threshold: 0.5 }

 var circle = document.getElementById('content_video');

 var observer = new IntersectionObserver(entries => {
     var [{ isIntersecting }] = entries
     if (isIntersecting) {
         player.play();
         player.ima.getAdsManager().resume();
     } else {
         player.ima.getAdsManager().pause();
     }
 }, options);

 window.addEventListener('load', () => {
     if ('IntersectionObserver' in window) observer.observe(circle);
 }, false);
</code>```

答:
This is normal behaviour, because element with display:none cannot be reached and ignoring by browser

Try set other styles instead display:none. Example, use opacity or width and height 0 with overflow: hidden

Body:
I am trying to observe a hidden element. I have an element which has style set to display: none. I want when my element intersect it will perform my action i.e: Play the video. I am sharing my sample code below

 var options = {threshold: 0.5 }

 var circle = document.getElementById('content_video');

 var observer = new IntersectionObserver(entries => {
     var [{ isIntersecting }] = entries
     if (isIntersecting) {
         player.play();
         player.ima.getAdsManager().resume();
     } else {
         player.ima.getAdsManager().pause();
     }
 }, options);

 window.addEventListener('load', () => {
     if ('IntersectionObserver' in window) observer.observe(circle);
 }, false);