问:
TypeScript adding type support for a specific key in interface and matching value of the same
Take below example.

```<code>interface MyObj = {
   name: string;
   id: number;
   isMandatory?: boolean;
}
</code>```

I have a function as below which takes one of key and value from 'MyObj'.

```<code>function sampleFn(key, value) {
   // do something
}
</code>```

How can I add type checking in sampleFn function. eg.if I pass key as "id", it should first check that id is allowed and then value should be of "number" type.

答:
You can use lookup types:

```<code>interface MyObj {
   name: string;
   id: number;
   isMandatory?: boolean;
}

function sampleFn<K extends keyof MyObj>(key: K, value: MyObj[K]) {}

sampleFn('name', 'X'); // OK
sampleFn('number', 0); // Error, key does not exist
sampleFn('name', 0);   // Error, value is of incorrect type
</code>```

In the example above, the key parameter is defined as having to be a key of the MyObj interface, and the value parameter as having to be of the type that corresponds to the property defined by key.

Body:
Take below example.

interface MyObj = {
   name: string;
   id: number;
   isMandatory?: boolean;
}

I have a function as below which takes one of key and value from 'MyObj'.

function sampleFn(key, value) {
   // do something
}

How can I add type checking in sampleFn function. eg.if I pass key as "id", it should first check that id is allowed and then value should be of "number" type.

Body:
You can use lookup types:

interface MyObj {
   name: string;
   id: number;
   isMandatory?: boolean;
}

function sampleFn<K extends keyof MyObj>(key: K, value: MyObj[K]) {}

sampleFn('name', 'X'); // OK
sampleFn('number', 0); // Error, key does not exist
sampleFn('name', 0);   // Error, value is of incorrect type

In the example above, the key parameter is defined as having to be a key of the MyObj interface, and the value parameter as having to be of the type that corresponds to the property defined by key.


来源: stackexchange

问:
What is the difference between ListView and SingleChildScrollView in Flutter?
I have seen few examples using ListView as the main body element of Scaffold and in few tutorials, it's SingleChildScrollView. All that I understood is both allow some axis of scrolling based on the direction that is configured but cannot figure out when to use one over the other?

ListView:

```<code>Scaffold
  body : ListView
    children : Padding/Container
</code>```

SingleChildScrollView:

```<code>Scaffold
  body : SingleChildScrollView
    child : Column
</code>```

答:
You could consider ListView as an optimisation to the combination of SingleChildScrollView + Column.

By using ListView, only the items that are visible are mounted and painted.

On the other hand, by using SingleChildScrollView+Column, the entire item list is mounted+painted, even if only a few items are visible.

The tradeoff is that ListView is less flexible. So for complex layouts with a small number of items, the performance gain may not be worth the trouble, in which case we can use SingleChildScrollView.

ContentLicense: CC BY-SA 4.0

Body:
I have seen few examples using ListView as the main body element of Scaffold and in few tutorials, it's SingleChildScrollView. All that I understood is both allow some axis of scrolling based on the direction that is configured but cannot figure out when to use one over the other?

ListView:

Scaffold
  body : ListView
    children : Padding/Container

SingleChildScrollView:

Scaffold
  body : SingleChildScrollView
    child : Column


问:
Use Wordpress or another CMS within a web application?
Apologies for the broad question, but I don't know where to start. I have a php web application for members with various functions and features. On the dashboard, I need to implement some dynamic news - the kind of news that that non-developer can write and publish without any interference with the source code.

Can I implement Wordpress into my existing app so that authors can login, write then publish so that my dashboard can display the latest posts?

At its most basic level, I'm thinking:

a new subfolder for Wordpress with its own separate database.

a plugin to display the latest posts content only

an iframe on my dashboard to display the output of that plugin

But all that seems like a very hacky workaround. Is there a more native way of doing this? Or is there another CMS library that could achieve the same result?

答:
I have a solution that I am running with. It's a separate Wordpress site with the latest posts accessed via the built-in API (https://developer.wordpress.org/rest-api/reference/posts/)

I will be getting all the posts in a category with:

```<code>curl https://example.com/wp-json/wp/v2/posts
</code>```

Then storing the posts in array before looping through that array to display the title and content on my dashboard with:

```<code>curl https://example.com/wp-json/wp/v2/posts/<id>
</code>```

where <id> is from the first call.

This is clean, native and serves the exact purpose I need. The member info, while secured doesn't need to be top-secret, so we're just using the Wordpress password-protection with the same password for all posts so as long as the API calls are server-side with https, the security works too :)

Body:
I have a solution that I am running with. It's a separate Wordpress site with the latest posts accessed via the built-in API (https://developer.wordpress.org/rest-api/reference/posts/)

I will be getting all the posts in a category with:

curl https://example.com/wp-json/wp/v2/posts

Then storing the posts in array before looping through that array to display the title and content on my dashboard with:

curl https://example.com/wp-json/wp/v2/posts/<id>

where <id> is from the first call.

This is clean, native and serves the exact purpose I need. The member info, while secured doesn't need to be top-secret, so we're just using the Wordpress password-protection with the same password for all posts so as long as the API calls are server-side with https, the security works too :)


问:
linux g++ regular expressions not working
I'm trying to find sub string using regular expressions on linux g++.

For example :

```<code>    std::string logline = "Apr 19 00:55:32 localhost kernel: usb 2-2.1: SerialNumber: ABCDEFGHIJKLMNOP\n";

    std::string sn = "";
    std::regex re("SerialNumber\: (.*)\n");
    std::smatch match;
    if (std::regex_search(logline, match, re) && match.size() > 1) {
        sn = match.str(1);
    }
    else
    {
        sn = std::string("");
    }
</code>```

it works in windows c++ as well.
but linux g++ not work.
what's is the problem?

答:
<regex> was implemented and released in GCC 4.9.0 so please check your gcc version and see below example:

```<code>#include <regex> //header  file for regex
#include <iostream>

int main(int argc, const char * argv[]){
    std::regex r("ab|bc|cd");
    std::cerr << "ab|bc|cd" << " matches ab? " << std::regex_match("sab", r) << std::endl;
    return 0;
}
</code>```

Output:

```<code>ab|bc|cd matches ab? 1
</code>```

Body:
I'm trying to find sub string using regular expressions on linux g++.

For example :

    std::string logline = "Apr 19 00:55:32 localhost kernel: usb 2-2.1: SerialNumber: ABCDEFGHIJKLMNOP\n";

    std::string sn = "";
    std::regex re("SerialNumber\: (.*)\n");
    std::smatch match;
    if (std::regex_search(logline, match, re) && match.size() > 1) {
        sn = match.str(1);
    }
    else
    {
        sn = std::string("");
    }

it works in windows c++ as well.
but linux g++ not work.
what's is the problem?

Body:
<regex> was implemented and released in GCC 4.9.0 so please check your gcc version and see below example:

#include <regex> //header  file for regex
#include <iostream>

int main(int argc, const char * argv[]){
    std::regex r("ab|bc|cd");
    std::cerr << "ab|bc|cd" << " matches ab? " << std::regex_match("sab", r) << std::endl;
    return 0;
}

Output:

ab|bc|cd matches ab? 1


问:
iOS UICollectionView Horizontal Scrolling Rectangular Layout with different size of items?
iOS UICollectionView how to Create Horizontal Scrolling rectangular layout with different size of items inside.

I want to create a Rectangular layout using UICollectionView like below. how can i achieve?

When i scroll horizontally using CollectionView 1,2,3,4,5,6 grid will scroll together to bring 7.

The Below are the dimensions of 320*480 iPhone Resolution. Updated Screen below.

First 6 items have below dimensions for iPhone 5s.

```<code>Item 1 Size is - (213*148)
Item 2 Size is - (106*75)
Item 3 Size is - (106*74)
Item 4 Size is - (106*88)
Item 5 Size is - (106*88)
Item 6 Size is - (106*88)
</code>```

After item6 have same dimensions as collection View width and height like below.

```<code>Item 7 Size is - (320*237)
Item 8 Size is - (320*237)
Item 9 Size is - (320*237)
</code>```

How to create a simple custom Layout Using collection view, that has horizontal scrolling?

Must appreciate for a quick solution. Thanks in advance.

答:
I would suggest using a StackView inside CollectionViewCell(of fixed dimension) to create a grid layout as shown in your post.

Below GridStackView creates a dynamic grid layout based on the number of views added using method addCell(view: UIView).

Add this GridStackView as the only subview of your CollectionViewCell pinning all the edges to the sides so that it fills the CollectionViewCell completely.

while preparing your CollectionViewCell, add tile views to it using the method addCell(view: UIView).

If only one view added, then it will show a single view occupying whole GridStackView and so as whole CollectionViewCell.
If there is more than one view added, it will automatically layout them in the inside the CollectionViewCell.

You can tweak the code below to get the desired layout calculating the row and column. Current implementation needed rowSize to be supplied while initializing which I used for one of my project, you need to modify it a bit to get your desired layout.

class GridStackView: UIStackView {
    private var cells: [UIView] = []
    private var currentRow: UIStackView?
    var rowSize: Int = 3
    var defaultSpacing: CGFloat = 5

    init(rowSize: Int) {
        self.rowSize = rowSize
        super.init(frame: .zero)
        translatesAutoresizingMaskIntoConstraints = false
        axis = .vertical
        spacing = defaultSpacing
        distribution = .fillEqually
    }

    required init(coder: NSCoder) {
        super.init(coder: coder)
        translatesAutoresizingMaskIntoConstraints = false
        axis = .vertical
        spacing = defaultSpacing
        distribution = .fillEqually
    }

    private func preapreRow() -> UIStackView {
        let row = UIStackView(arrangedSubviews: [])
        row.spacing = defaultSpacing
        row.translatesAutoresizingMaskIntoConstraints = false
        row.axis = .horizontal
        row.distribution = .fillEqually
        return row
    }

    func removeAllCell() {
        for item in arrangedSubviews {
            item.removeFromSuperview()
        }
        cells.removeAll()
        currentRow = nil
    }

    func addCell(view: UIView) {
        let firstCellInRow = cells.count % rowSize == 0
        if currentRow == nil || firstCellInRow {
            currentRow = preapreRow()
            addArrangedSubview(currentRow!)
        }
        view.translatesAutoresizingMaskIntoConstraints = false
        cells.append(view)
        currentRow?.addArrangedSubview(view)
        setNeedsLayout()
    }
}
```

Body:
iOS UICollectionView how to Create Horizontal Scrolling rectangular layout with different size of items inside.

I want to create a Rectangular layout using UICollectionView like below. how can i achieve?

When i scroll horizontally using CollectionView 1,2,3,4,5,6 grid will scroll together to bring 7.

The Below are the dimensions of 320*480 iPhone Resolution. Updated Screen below.

First 6 items have below dimensions for iPhone 5s.

Item 1 Size is - (213*148)
Item 2 Size is - (106*75)
Item 3 Size is - (106*74)
Item 4 Size is - (106*88)
Item 5 Size is - (106*88)
Item 6 Size is - (106*88)

After item6 have same dimensions as collection View width and height like below.

Item 7 Size is - (320*237)
Item 8 Size is - (320*237)
Item 9 Size is - (320*237)

How to create a simple custom Layout Using collection view, that has horizontal scrolling?

Must appreciate for a quick solution. Thanks in advance.


问:
Dynamic query in LINQ
How do I write a dynamic query for Linq, if I have say Customer class which holds the fields:

```<code>string name
string address
int phoneno
</code>```

I have to query based on information given similar to

```<code>query = string.Empty;

if(!string.IsNullorEmpty(name))
{
   query += "@name = name";
}

if(!string.IsNullorEmpty(address))
{
   query += "@address = address";
}

if(!string.IsNullorEmpty(phoneno))
{
   query += "@phoneno = phoneno";
}

var result = from condition in customer
    where(query)
    select condition;
</code>```

Edit #1:

the items are changeable at run time like

```<code>private Customer[] GetCustomers(Dictionary<string,string> attributes)
{
   here the attribute may be, name alone, or name and address, or name address and phoneno

      foreach(string field in attributes.key)
      {
           query += field == attributes[key];

      }

         Customers[] =ExecuteQuery(query);

}
</code>```

Is this kind of query supported by LINQ?

Edit #2:

Hi Mouk,

As I am new to C#, I am still struggling, this is not working for me.

```<code>var query = _ConfigFile.ConnectionMasterSection;

for(int i = 0; i < filter.count; i++)
{
    query = result.Where(p => typeof(ConnectionMaster).GetProperty(filter[i].Attribute).Name == filter[i].Value);
}
</code>```

This yeilds Empty, where as i used this

```<code>var query = _ConfigFile.ConnectionMasterSection;

//Hard coded
res.Where(q => q.category == filter[0].Value);
</code>```

And it worked as I expected.

Hi Bryan Watts,

I tried your code also and I getting this error: "Lambda Parameter not in scope".

```<code>for(int i = 0; i < filter.count; i++)
{
    Field item = filter[i];

    MemberExpression param = Expression.MakeMemberAccess(Expression.Parameter(typeof(Connection), "p"), typeof(Connection).GetProperty(item.Attribute));

    MemberExpression constant = Expression.MakeMemberAccess(Expression.Constant(item), typeof(Field).GetProperty("Value"));
}

try
{
    var myquery = Queryable.Where(coll, Expression.Lambda<Func<Connection, bool>>(
    Expression.Equal(param, constant), Expression.Parameter(typeof(Connection),"p")));
}
</code>```

What is the mistake here?

答:
Here you go:

```<code>var result = from customer in Customers
             where string.IsNullOrEmpty(phoneNo) || customer.PhoneNo == phoneNo
             where string.IsNullOrEmpty(address) || customer.Address == address
             select customer;
</code>```

If you're concerned that this generate the optimal SQL query underneath, as always you should attach a SQL Query Analyzer and check.  But I believe the expression parser in Linq To Sql will collapse down the where clauses as appropriate based on the value of the arguments.

OwnerDisplayName: Mohanavel

LastEditorDisplayName: Quintin Robinson

ContentLicense: CC BY-SA 2.5

Title: Dynamic query in LINQ

Body:
How do I write a dynamic query for Linq, if I have say Customer class which holds the fields:

string name
string address
int phoneno

I have to query based on information given similar to

query = string.Empty;

if(!string.IsNullorEmpty(name))
{
   query += "@name = name";
}

if(!string.IsNullorEmpty(address))
{
   query += "@address = address";
}

if(!string.IsNullorEmpty(phoneno))
{
   query += "@phoneno = phoneno";
}

var result = from condition in customer
    where(query)
    select condition;

Edit #1:

the items are changeable at run time like

private Customer[] GetCustomers(Dictionary<string,string> attributes)
{
   here the attribute may be, name alone, or name and address, or name address and phoneno

      foreach(string field in attributes.key)
      {
           query += field == attributes[key];

      }

         Customers[] =ExecuteQuery(query);

}

Is this kind of query supported by LINQ?

Edit #2:

Hi Mouk,

As I am new to C#, I am still struggling, this is not working for me.

var query = _ConfigFile.ConnectionMasterSection;

for(int i = 0; i < filter.count; i++)
{
    query = result.Where(p => typeof(ConnectionMaster).GetProperty(filter[i].Attribute).Name == filter[i].Value);
}

This yeilds Empty, where as i used this

var query = _ConfigFile.ConnectionMasterSection;

//Hard coded
res.Where(q => q.category == filter[0].Value);

And it worked as I expected.

Hi Bryan Watts,

I tried your code also and I getting this error: "Lambda Parameter not in scope".

for(int i = 0; i < filter.count; i++)
{
    Field item = filter[i];

    MemberExpression param = Expression.MakeMemberAccess(Expression.Parameter(typeof(Connection), "p"), typeof(Connection).GetProperty(item.Attribute));

    MemberExpression constant = Expression.MakeMemberAccess(Expression.Constant(item), typeof(Field).GetProperty("Value"));
}

try
{
    var myquery = Queryable.Where(coll, Expression.Lambda<Func<Connection, bool>>(
    Expression.Equal(param, constant), Expression.Parameter(typeof(Connection),"p")));
}

What is the mistake here?

Body:
Here you go:

var result = from customer in Customers
             where string.IsNullOrEmpty(phoneNo) || customer.PhoneNo == phoneNo
             where string.IsNullOrEmpty(address) || customer.Address == address
             select customer;

If you're concerned that this generate the optimal SQL query underneath, as always you should attach a SQL Query Analyzer and check.  But I believe the expression parser in Linq To Sql will collapse down the where clauses as appropriate based on the value of the arguments.

OwnerDisplayName: Andrew Arnott


问:
How to pass textbox value to java script on button click event

Possible Duplicate:

  How to pass text in a textbox to javascript function?

I need to pass the text box value as parameter of javascript method which will be fired on button click.

```<code><asp:TextBox ID="rowID" runat="server"> </asp:TextBox>
        <asp:Button runat="server" ID="Click" OnClientClick="PassValue(Textboxvaluehere)"/>
</code>```

PassValue is JavaScript method.

Thanks in Advance.

答:
```<code><asp:Button runat="server" ID="Click" OnClientClick="GetTextBoxValue('<%= rowID.ClientID %>'.value)"/>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Possible Duplicate:

  How to pass text in a textbox to javascript function?

I need to pass the text box value as parameter of javascript method which will be fired on button click.

<asp:TextBox ID="rowID" runat="server"> </asp:TextBox>
        <asp:Button runat="server" ID="Click" OnClientClick="PassValue(Textboxvaluehere)"/>

PassValue is JavaScript method.

Thanks in Advance.


问:
Reversing vowels in string in javaScript
This is my code for reversing vowel in a string. I couldnt find what mistake i have done in this..
example:
ip: mobile
op: mebilo

but..
for me..whatever Input i gave, its only being displayed as output.
whats my mistake?
Thank you.

```<code>const readline = require('readline');
const inp = readline.createInterface({
  input: process.stdin
});
const userInput = [];
  inp.on("line", (data) => {
  userInput.push(data);
});
inp.on("close", () => {
  a= userInput[0];
  b=[];
  n=0;
  for(i=0; i<a.length; i++){
    if(a[i]=="a"||a[i]=="e"||a[i]=="i"||a[i]=="o"||a[i]=="u"){
      b[n]=a[i];
      n+=1;
    }
  }

  last = b.length-1;
  for(j=0; j<a.length; j++){
    if(a[j]=="a"||a[j]=="e"||a[j]=="i"||a[j]=="o"||a[j]=="u"){
      a[j]=b[last];
      last-=1;
    }
  }
  console.log(a);
})
</code>```

答:
a= userInput[0]; & then you do a[j] = b[last] this was the issue, you cannot mutate strings in JS.

So change it to a= userInput[0].split('') and change console.log to console.log(a.join(''))

Example:

function reverseVowels(userInput) {
  a= userInput[0].split('');
  b=[];
  n=0;
  for(i=0; i<a.length; i++){
    if(a[i]=="a"||a[i]=="e"||a[i]=="i"||a[i]=="o"||a[i]=="u"){
      b[n]=a[i];
      n+=1;
    }
  }

  last = b.length-1;
  for(j=0; j<a.length; j++){
    if(a[j]=="a"||a[j]=="e"||a[j]=="i"||a[j]=="o"||a[j]=="u"){
      a[j]=b[last];
      last-=1;
    }
  }
  console.log(a.join(''));
}

reverseVowels(['hello']);```

Body:
This is my code for reversing vowel in a string. I couldnt find what mistake i have done in this..
example:
ip: mobile
op: mebilo

but..
for me..whatever Input i gave, its only being displayed as output.
whats my mistake?
Thank you.

const readline = require('readline');
const inp = readline.createInterface({
  input: process.stdin
});
const userInput = [];
  inp.on("line", (data) => {
  userInput.push(data);
});
inp.on("close", () => {
  a= userInput[0];
  b=[];
  n=0;
  for(i=0; i<a.length; i++){
    if(a[i]=="a"||a[i]=="e"||a[i]=="i"||a[i]=="o"||a[i]=="u"){
      b[n]=a[i];
      n+=1;
    }
  }

  last = b.length-1;
  for(j=0; j<a.length; j++){
    if(a[j]=="a"||a[j]=="e"||a[j]=="i"||a[j]=="o"||a[j]=="u"){
      a[j]=b[last];
      last-=1;
    }
  }
  console.log(a);
})


问:
Python Socket Server and parallel timed Tasks
I'm quite new to python and just hanging at the following problem.

I'm trying to build a plant-watering-automation. As a base a use a tornado socket server which listen to client polls and deliveres the data for visualisation.

For the watering automation I created a ContinuousCallback (every 30 minutes) in which I want to check for humidity and control the pumps (GPIO out).

The task: if the Callback starts and it measures to low humidity, it should start to pump by switching the GPIO pins for a defined amount of time. (the time is defined in a SQLITE DB)

The problem: how can I do it, that I enter the Callback and start the pump action (I have 4 pumps) and make it end after the defined time? (Timer?, Timer Interrupt?) without influencing the Socket Server IOloop?

.

.

Thank you and best wishes

Sebastian

答:
I guess</p>

```<code>def on_button_or_whatever():
    setGPIO_HIGH()
    timer = threading.Timer(target=setGPIO_LOW,5.0)
    timer.start()
</code>```

Body:
I guess

def on_button_or_whatever():
    setGPIO_HIGH()
    timer = threading.Timer(target=setGPIO_LOW,5.0)
    timer.start()


问:
webView don't work in flutter [ERROR:flutter/lib/ui/ui_dart_state.cc(157)]
I add in pubspec.yaml webview_flutter: ^0.3.19+8
i use  Flutter version 1.12.13+hotfix.8

and it's my code

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

void main() => runApp(MaterialApp(
  home: app(),
));

class app extends StatefulWidget {
  @override
  _appState createState() => _appState();
}

class _appState extends State<app> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('App mobile'),
      ),
      body: Container(
        constraints: BoxConstraints(maxHeight: 500),
        child: WebView(
          initialUrl: "https://google.com",
        ),
      )
    );
  }
}
</code>```

but after Run and click in white emulator screen, in tab Run i have this...

```<code>E/flutter ( 9570): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: PlatformException(error, java.lang.IllegalStateException: Sending touch to an unknown view with id: 1
E/flutter ( 9570):  at io.flutter.plugin.platform.PlatformViewsController$1.onTouch(PlatformViewsController.java:206)
E/flutter ( 9570):  at io.flutter.embedding.engine.systemchannels.PlatformViewsChannel$1.touch(PlatformViewsChannel.java:168)
...
</code>```

I will appreciate any help...

答:
I used this and works fine with me, I think you missed to use the controller

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

class WebViewScreen extends StatefulWidget {
  final String title;
  final String selectedUrl;

  WebViewScreen({@required this.title, @required this.selectedUrl});

  @override
  _WebViewScreenState createState() => _WebViewScreenState();
}

class _WebViewScreenState extends State<WebViewScreen> {
  Completer<WebViewController> _controller = Completer<WebViewController>();
  bool isLoading = true;

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: WebView(
        initialUrl: widget.selectedUrl,
        onWebViewCreated: (WebViewController webViewController) {
          _controller.complete(webViewController);
        },
      ),
    );
  }
}

</code>```

Body:
I add in pubspec.yaml webview_flutter: ^0.3.19+8
i use  Flutter version 1.12.13+hotfix.8

and it's my code

import 'package:webview_flutter/webview_flutter.dart';

void main() => runApp(MaterialApp(
  home: app(),
));

class app extends StatefulWidget {
  @override
  _appState createState() => _appState();
}

class _appState extends State<app> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('App mobile'),
      ),
      body: Container(
        constraints: BoxConstraints(maxHeight: 500),
        child: WebView(
          initialUrl: "https://google.com",
        ),
      )
    );
  }
}

but after Run and click in white emulator screen, in tab Run i have this...

E/flutter ( 9570): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: PlatformException(error, java.lang.IllegalStateException: Sending touch to an unknown view with id: 1
E/flutter ( 9570):  at io.flutter.plugin.platform.PlatformViewsController$1.onTouch(PlatformViewsController.java:206)
E/flutter ( 9570):  at io.flutter.embedding.engine.systemchannels.PlatformViewsChannel$1.touch(PlatformViewsChannel.java:168)
...

I will appreciate any help...

Body:
I used this and works fine with me, I think you missed to use the controller

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

class WebViewScreen extends StatefulWidget {
  final String title;
  final String selectedUrl;

  WebViewScreen({@required this.title, @required this.selectedUrl});

  @override
  _WebViewScreenState createState() => _WebViewScreenState();
}

class _WebViewScreenState extends State<WebViewScreen> {
  Completer<WebViewController> _controller = Completer<WebViewController>();
  bool isLoading = true;

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: WebView(
        initialUrl: widget.selectedUrl,
        onWebViewCreated: (WebViewController webViewController) {
          _controller.complete(webViewController);
        },
      ),
    );
  }
}


问:
Why does this code compile fine in java 11?
Here's the code:

```<code>import java.util.*;

public class Main {
    public static <T> T defaultIfNull(T object, T defaultValue) {
        return object != null ? object : defaultValue;
    }

    public static void main(String[] args) {
        List<String> ls = Collections.emptyList();
        List<String> lo = defaultIfNull(ls, Collections.emptyList());
    }
}
</code>```

With openjdk 11, it compiles fine:

```<code>root@debian:~/tmp# java -version
openjdk version "11.0.6" 2020-01-14
OpenJDK Runtime Environment (build 11.0.6+10-post-Debian-1deb10u1)
OpenJDK 64-Bit Server VM (build 11.0.6+10-post-Debian-1deb10u1, mixed mode, sharing)

root@debian:~/tmp# javac ./Main.java
</code>```

But, that's not the case with openjdk 1.8:

```<code>root@debian:~/tmp# /usr/local/java-se-8u41-ri/bin/java -version
openjdk version "1.8.0_41"
OpenJDK Runtime Environment (build 1.8.0_41-b04)
OpenJDK 64-Bit Server VM (build 25.40-b25, mixed mode)
root@debian:~/tmp# /usr/local/java-se-8u41-ri/bin/javac ./Main.java
./Main.java:12: error: incompatible types: inferred type does not conform to upper bound(s)
        List<String> lo = defaultIfNull(ls, Collections.emptyList());
                                       ^
    inferred: List<? extends Object>
    upper bound(s): List<String>,Object
1 error
</code>```

The problem here is that, Collections.emptyList returns List<Object> if no type parameter is supplied. Then, what makes it okay to openjdk 11 to do the same thing?

答:
This is a bug in the javac tool (as listed here) that has been fixed in a later version. You should update your jdk to a newer version to fix this problem (and to also apply the security patches).

Also, if can't update your jdk version you might be able to help the compiler by specifying the type, like so:

List<String> lo = Main.<List<String>>defaultIfNull(ls, Collections.<String>emptyList());
```

I haven't tested this though, because I don't use your version, but it might work in this case.

Body:
Here's the code:

import java.util.*;

public class Main {
    public static <T> T defaultIfNull(T object, T defaultValue) {
        return object != null ? object : defaultValue;
    }

    public static void main(String[] args) {
        List<String> ls = Collections.emptyList();
        List<String> lo = defaultIfNull(ls, Collections.emptyList());
    }
}

With openjdk 11, it compiles fine:

root@debian:~/tmp# java -version
openjdk version "11.0.6" 2020-01-14
OpenJDK Runtime Environment (build 11.0.6+10-post-Debian-1deb10u1)
OpenJDK 64-Bit Server VM (build 11.0.6+10-post-Debian-1deb10u1, mixed mode, sharing)

root@debian:~/tmp# javac ./Main.java

But, that's not the case with openjdk 1.8:

root@debian:~/tmp# /usr/local/java-se-8u41-ri/bin/java -version
openjdk version "1.8.0_41"
OpenJDK Runtime Environment (build 1.8.0_41-b04)
OpenJDK 64-Bit Server VM (build 25.40-b25, mixed mode)
root@debian:~/tmp# /usr/local/java-se-8u41-ri/bin/javac ./Main.java
./Main.java:12: error: incompatible types: inferred type does not conform to upper bound(s)
        List<String> lo = defaultIfNull(ls, Collections.emptyList());
                                       ^
    inferred: List<? extends Object>
    upper bound(s): List<String>,Object
1 error

The problem here is that, Collections.emptyList returns List<Object> if no type parameter is supplied. Then, what makes it okay to openjdk 11 to do the same thing?

Body:
This is a bug in the javac tool (as listed here) that has been fixed in a later version. You should update your jdk to a newer version to fix this problem (and to also apply the security patches).

Also, if can't update your jdk version you might be able to help the compiler by specifying the type, like so:

List<String> lo = Main.<List<String>>defaultIfNull(ls, Collections.<String>emptyList());

I haven't tested this though, because I don't use your version, but it might work in this case.


问:
Trying to implement Redigo ScanStruct but limited examples to follow
I have a code:

```<code>values, err := redis.Values(c.Do("hgetall", value))
if err != nil {
    fmt.Println("HGETALL", err)
}

/*
type UD struct {
    created_at  string
    B           time.Time
    ended_at    string
    data        string
    status      string
}
*/
if err := redis.ScanStruct(values, &UD); err != nil {
    fmt.Println(err)
}
</code>```

The error I got is

redigo.ScanStruct: cannot assign field B: cannot convert from Redis
  bulk string to time.Time

How do I resolve this? Any examples of ScanStruct in detail for a variety of field types for Struct for reference?

答:
You can simply add an ignore tag to make time field avoid being marshaled.

type UD struct {
    created_at  string
    B           time.Time `redis:"-"`
    ended_at    string
    data        string
    status      string
}
```

Body:
I have a code:

values, err := redis.Values(c.Do("hgetall", value))
if err != nil {
    fmt.Println("HGETALL", err)
}

/*
type UD struct {
    created_at  string
    B           time.Time
    ended_at    string
    data        string
    status      string
}
*/
if err := redis.ScanStruct(values, &UD); err != nil {
    fmt.Println(err)
}

The error I got is

redigo.ScanStruct: cannot assign field B: cannot convert from Redis
  bulk string to time.Time

How do I resolve this? Any examples of ScanStruct in detail for a variety of field types for Struct for reference?


问:
Laravel 6.x Backpack NewsCrud Plugin
What I want to do is allow the admin panel to post news using newscrud. I am confused in how would I grab the information from the database and show the user the articles.

I am having trouble using the newscrud plugin for laravel. I quite don't understand how to use this plugin. I have installed it using composer. All the controllers, models etc. are in the vendor folder in my Laravel project.

Attempts:
What I tried to do is make a function in the
laravel-project/vendor/backpack/newscrud/src/app/Http/Controllers/Admin/ArticleCrudController.php file:

```<code>public function index()
{
    # Pass the article database information in articles var
    $articles = Articles::all();

    # Return this variable to blog page
    return view ('blog')->with('articles', $articles);
}
</code>```

And in the routes/web.php file:

```<code>Route::get('/blog', 'ArticleCrudController@index')->name('blog');
</code>```

Front-end code

```<code>                      @foreach($articles as $article)

                          <div class="col-md-12 d-flex ftco-animate">

                            <div class="blog-entry align-self-stretch d-md-flex">

                              <a href="blog-single.html" class="block-20" style="background-image: url('images/image_6.jpg');">

                              </a>

                              <div class="text d-block pl-md-4">

                                <div class="meta mb-3">

                                  <div><a href="#">July 20, 2019</a></div>

                                  <div><a href="#">Admin</a></div>

                                  <div><a href="#" class="meta-chat"><span class="icon-chat"></span> 3</a></div>

                                </div>

                                <h3 class="heading"><a href="#">Even the all-powerful Pointing has no control about the blind texts</a></h3>

                                <p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.</p>

                                <p><a href="blog-single.html" class="btn btn-primary py-2 px-3">Read more</a></p>

                              </div>

                            </div>

                          </div>

                    @endforeach
</code>```

Error
The error message I get is:

```<code>Target class [App\Http\Controllers\ArticleCrudController] does not exist.
</code>```

If you need information/screenshots I am willing to provide them.

答:
When using composer in PHP, you should never make modifications to files inside the /vendor/ folder. Because as soon as you run composer update, they will get overwritten.

If I understand correctly, What you’re trying to do has little to do with Backpack. You should not overwrite the package in the vendor folder. You should create a controller in your app folder, with a routes in your routes folder, line you would normally do in Laravel. Just make sure that, when you reference the model, you reference Backpack\NewsCRUD\app\Models\Article instead of App\Models\Article.

Hope it helps!

Title: Laravel 6.x Backpack NewsCrud Plugin

Body:
What I want to do is allow the admin panel to post news using newscrud. I am confused in how would I grab the information from the database and show the user the articles.

I am having trouble using the newscrud plugin for laravel. I quite don't understand how to use this plugin. I have installed it using composer. All the controllers, models etc. are in the vendor folder in my Laravel project.

Attempts:
What I tried to do is make a function in the
laravel-project/vendor/backpack/newscrud/src/app/Http/Controllers/Admin/ArticleCrudController.php file:

public function index()
{
    # Pass the article database information in articles var
    $articles = Articles::all();

    # Return this variable to blog page
    return view ('blog')->with('articles', $articles);
}

And in the routes/web.php file:

Route::get('/blog', 'ArticleCrudController@index')->name('blog');

Front-end code

                      @foreach($articles as $article)

July 20, 2019

Admin

 3

Even the all-powerful Pointing has no control about the blind texts

Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.

Read more

                    @endforeach

Error
The error message I get is:

Target class [App\Http\Controllers\ArticleCrudController] does not exist.

If you need information/screenshots I am willing to provide them.


问:
IOS SDK Ebook app
i want to make a EbookApp . The Book has 400 pages.
I tried with UIScrollView + UIPageControl , but pagecontrol shows just peak 20 pages.
I heard that it can be done with UILabel and three Views.
How can i realize it?</p>

答:
You shouldn't load all the pages at time. You should automatically load only 10, for example.

Assume user opens 1st page. So you have to load 1-10 pages, when user is on 5th page you should load 11-15 pages, when user is on 10th page you have to unload 1-5 pages, etc.

Theoretically, it could be done with three views (pages).

Good luck

Title: IOS SDK Ebook app


问:
Not redirecting to desired page
How can I get the loginState in Navigation, so after successful login system should redirect to Profile screen. Now after successful login, it is not Redirecting to profile screen.
I have read few tutorials but all with complex details, I would like to have some simple way of implementing this, as I have only 4 screens.

I have added a demo below:

https://codesandbox.io/s/amazing-ellis-2h3pd?file=/src/components/Home.js

答:
To use props.history in a component, you should wrap your component with withRouter

```<code> import { withRouter } from 'react-router-dom'

 ....rest code...

 export default withRouter(Login)
</code>```

Another way to achieve your desired behavior is at route declaration itself do

```<code>  <Route path="/login" render={()=> loginstate ? < Redirect to= 'profile' /> : <Login/>} />
</code>```

What more adapt to a real scenario usage, while loginstate isn't live just a Login component but at some root place at your project

Title: Not redirecting to desired page

Body:
To use props.history in a component, you should wrap your component with withRouter

 import { withRouter } from 'react-router-dom'

 ....rest code...

 export default withRouter(Login)

Another way to achieve your desired behavior is at route declaration itself do

  <Route path="/login" render={()=> loginstate ? < Redirect to= 'profile' /> : <Login/>} />

What more adapt to a real scenario usage, while loginstate isn't live just a Login component but at some root place at your project


问:
how to covert a java class type to its base type?
I am trying to figure out how to convert a class type to its base type so that the java program can be compiled. In detail, we have code as follows. The code is similar to  https://github.com/twitter/chill/blob/develop/chill-thrift/src/main/java/com/twitter/chill/thrift/TBaseSerializer.java#L56

```<code>  interface TBase {.... }

  class Deserializer {
      public TBase read(Kryo kryo, Input input, Class<TBase> tBaseClass) {...}
      ...
  }

  class Event implements TBase {.... }

  Deserializer = new Deserializer(...)
  deserializer.read(kryo, input, Event.class);
</code>```

I got the following errors with java8:

```<code>incompatible types: Class<Event> cannot be converted to Class<TBase>
</code>```

We cannot change TBase interface to a class. With that constaint, how shall I resolve this type compatibility issue? Is  Class<Event> also Class<TBase> ?

I have also tried to declare Class<? extends TBase> as the parameter type. with this approach, I got "'read(Kryo, Input, Class)' in 'TBaseSerializer' clashes with 'read(Kryo, Input, Class)' in 'com.twitter.chill.thrift.TBaseSerializer'; both methods have the same erasure, yet neither override the other.

答:
you should use wildcards here

```<code>public TBase read(Kryo kryo, Input input, Class<? extends TBase> tBaseClass) {...}
</code>```

it means that anything that is derived from TBase can be passed as an argument. you can read more here

Body:
I am trying to figure out how to convert a class type to its base type so that the java program can be compiled. In detail, we have code as follows. The code is similar to  https://github.com/twitter/chill/blob/develop/chill-thrift/src/main/java/com/twitter/chill/thrift/TBaseSerializer.java#L56

  interface TBase {.... }

  class Deserializer {
      public TBase read(Kryo kryo, Input input, Class<TBase> tBaseClass) {...}
      ...
  }

  class Event implements TBase {.... }

  Deserializer = new Deserializer(...)
  deserializer.read(kryo, input, Event.class);

I got the following errors with java8:

incompatible types: Class<Event> cannot be converted to Class<TBase>

We cannot change TBase interface to a class. With that constaint, how shall I resolve this type compatibility issue? Is  Class<Event> also Class<TBase> ?

I have also tried to declare Class<? extends TBase> as the parameter type. with this approach, I got "'read(Kryo, Input, Class)' in 'TBaseSerializer' clashes with 'read(Kryo, Input, Class)' in 'com.twitter.chill.thrift.TBaseSerializer'; both methods have the same erasure, yet neither override the other.

Body:
you should use wildcards here

public TBase read(Kryo kryo, Input input, Class<? extends TBase> tBaseClass) {...}

it means that anything that is derived from TBase can be passed as an argument. you can read more here


问:
sql.DB.Query "expected 0 arguments" when using "?" placeholder
I am interacting with a MySQL database in golang using database/sql with the github.com/go-sql-driver/mysql driver

I associate tags to articles with a table article_to_tag which associates an article ID with a tag ID, and find articles with certain tags using a Toxi solution found toward the bottom of this article

This snippet is supposed to query my database for all articles associated with all tags in the array itags

```<code>    s := "SELECT a.* " +
        "FROM article_to_tag at, articles a, tags t " +
        "WHERE t.ID = at.TagID " +
        "AND a.ID = at.ArticleID " +
        "AND (t.Name IN ('?'" + strings.Repeat(",'?'", len(itags)-1) + ")) " +
        "GROUP BY a.ID " +
        "HAVING COUNT(a.ID)=" + strconv.Itoa(len(itags)) + ";"
    fmt.Println(s)
    rows, err := db.Query(s, itags...)
</code>```

This builds the following string when querying for 2 tags, but querying with that string returns an error: sql: expected 0 arguments, got 2

```<code>SELECT a.*
FROM article_to_tag at, articles a, tags t
WHERE t.ID = at.TagID
AND a.ID = at.ArticleID
AND (t.Name IN ('?','?'))
GROUP BY a.ID HAVING COUNT(a.ID)=2;
</code>```

Why is the query ignoring the ? placeholder, and how else should I go about building the query safely?

答: Omit the single quotes. When you use a placeholder, place it unquoted. With the quotes it's just a string.</p>

Body:
I am interacting with a MySQL database in golang using database/sql with the github.com/go-sql-driver/mysql driver

I associate tags to articles with a table article_to_tag which associates an article ID with a tag ID, and find articles with certain tags using a Toxi solution found toward the bottom of this article

This snippet is supposed to query my database for all articles associated with all tags in the array itags

    s := "SELECT a.* " +
        "FROM article_to_tag at, articles a, tags t " +
        "WHERE t.ID = at.TagID " +
        "AND a.ID = at.ArticleID " +
        "AND (t.Name IN ('?'" + strings.Repeat(",'?'", len(itags)-1) + ")) " +
        "GROUP BY a.ID " +
        "HAVING COUNT(a.ID)=" + strconv.Itoa(len(itags)) + ";"
    fmt.Println(s)
    rows, err := db.Query(s, itags...)

This builds the following string when querying for 2 tags, but querying with that string returns an error: sql: expected 0 arguments, got 2

SELECT a.*
FROM article_to_tag at, articles a, tags t
WHERE t.ID = at.TagID
AND a.ID = at.ArticleID
AND (t.Name IN ('?','?'))
GROUP BY a.ID HAVING COUNT(a.ID)=2;

Why is the query ignoring the ? placeholder, and how else should I go about building the query safely?


问:
Spring IoC: Reasons to have null checks with constructor autowiring
What are the reasons to use null checks in spring autowring?

For instance, I often see code like this:

```<code>@Component
public class MyComponent {
    private final MyService myService;

    @Autowired
    public MyComponent(MyService myService) {
        Assert.notNull(myService, "myService must not be null");
        this.myService = myService;
    }
}
</code>```

What is the point of Assert.notNull() call here?

If I forget to declare MyService as a Bean Spring will fail with:

NoSuchBeanDefinitionException: No qualifying bean of type 'com.company.MyService' available: expected at least 1 bean which qualifies as autowire candidate.

Of course there are some corner cases in which under certain specific conditions it is possible to autowire null bean. But how important are these cases in real well designed code?

答: It is useful when any developer does object creation in plain Java way something like "new Bean(null)" Or it is also possible to pass null as the value in XML based injection using the "null" tag. In both these cases, this assert will shout while bean creation itself.

Body:
What are the reasons to use null checks in spring autowring?

For instance, I often see code like this:

@Component
public class MyComponent {
    private final MyService myService;

    @Autowired
    public MyComponent(MyService myService) {
        Assert.notNull(myService, "myService must not be null");
        this.myService = myService;
    }
}

What is the point of Assert.notNull() call here?

If I forget to declare MyService as a Bean Spring will fail with:

NoSuchBeanDefinitionException: No qualifying bean of type 'com.company.MyService' available: expected at least 1 bean which qualifies as autowire candidate.

Of course there are some corner cases in which under certain specific conditions it is possible to autowire null bean. But how important are these cases in real well designed code?


问:
my code for remove @user and punctuation does not work
I wrote the code below for tweets data set, I want to do preprocessing, I have removed #, website  but my code for remove @user and punctuation does not work ,im new to python can any one help me? </p>

```<code>from nltk.corpus import stopwords
import spacy, re

nlp = spacy.load('en')

stop_words = [w.lower() for w in stopwords.words()]

def sanitize(input_string):
    """ Sanitize one string """

    # normalize to lowercase
    string = input_string.lower()

    # spacy tokenizer
    string_split = [token.text for token in nlp(string)]

    # in case the string is empty
    if not string_split:
        return ''

    names = re.compile('@[A-Za-z0-9_][A-Za-z0-9_]+')
    string = [re.sub(names, '@USER', tweet) for tweet in input_string()]

    #remove # and @
    for punc in '":!#':
       string = string.replace(punc, '')

    # remove 't.co/' links
    string = re.sub(r'http//t.co\/[^\s]+', '', string, flags=re.MULTILINE)

    # removing stop words
    string = ' '.join([w for w in string.split() if w not in stop_words])

#punctuation
   # string = [''.join(w for w in string.split() if w not in #string.punctuation) for w in string]

    return string

list = ['@Jeff_Atwood Thank you for #stackoverflow', 'All hail @Joel_Spolsky t.co/Gsb7V1oVLU #stackoverflow' ]

list_sanitized = [sanitize(string) for string in tweets[:300]]
list_sanitized[:50]
</code>```

答:
Try this:
string = [names.sub('@USER', tweet) for tweet in input_string()]</p>

Body:
I wrote the code below for tweets data set, I want to do preprocessing, I have removed #, website  but my code for remove @user and punctuation does not work ,im new to python can any one help me?

from nltk.corpus import stopwords
import spacy, re

nlp = spacy.load('en')

stop_words = [w.lower() for w in stopwords.words()]

def sanitize(input_string):
    """ Sanitize one string """

    # normalize to lowercase
    string = input_string.lower()

    # spacy tokenizer
    string_split = [token.text for token in nlp(string)]

    # in case the string is empty
    if not string_split:
        return ''

    names = re.compile('@[A-Za-z0-9_][A-Za-z0-9_]+')
    string = [re.sub(names, '@USER', tweet) for tweet in input_string()]

    #remove # and @
    for punc in '":!#':
       string = string.replace(punc, '')

    # remove 't.co/' links
    string = re.sub(r'http//t.co\/[^\s]+', '', string, flags=re.MULTILINE)

    # removing stop words
    string = ' '.join([w for w in string.split() if w not in stop_words])

#punctuation
   # string = [''.join(w for w in string.split() if w not in #string.punctuation) for w in string]

    return string

list = ['@Jeff_Atwood Thank you for #stackoverflow', 'All hail @Joel_Spolsky t.co/Gsb7V1oVLU #stackoverflow' ]

list_sanitized = [sanitize(string) for string in tweets[:300]]
list_sanitized[:50]


问:
Receiving OTP SMS Via AT+CMGL Command (e.g. Whatsapp)
I'm new to GSM AT Commands and I'm using ZTE MF190S USB 3G USB Modem with Modem Nodejs Module also tried with MS Hyperterminal.

The problem I'm facing that when I receive SMS using AT+CMGL="ALL" from Whatsapp (as example) I got in sender number field 81084326797126204 which is an invalid phone number and should be "Whatsapp" instead although the manufacture's software is showing message from Whatsapp normally.

Note: I tried to decode it as a Hexadecimal string but not done.

```<code>> AT+CSCS="GSM"
> AT+CPMS="ME"
> AT+CMGL="ALL"
//Result
+CMGL: 0,"REC UNREAD","81084326797126204",,"20/05/30,14:53:55+08"
        FEFF000000000000000000000000000000000000020
</code>```

As described in this link

+CMGL: index,message_status,address,[address_text],[service_center_time_stamp][,address_type,sms_message_body_length]sms_message_body[+CMGL:
  ...]

The address Field

The third field of the information response of the +CMGL AT command,
  address, is a string that contains the address/phone number stored in
  the SMS message header. If the SMS message read is an incoming SMS
  message, the address field contains the originator address. If the SMS
  message read is an outgoing SMS message, the address field contains
  the recipient address. Usually the address field value is a phone
  number formatted using the typical ISDN / telephony numbering plan
  (ITU E.164/E.163). For example, "+85291234567".

The address_text Field

The fourth field of the information response of the +CMGL AT command,
  address_text, is a string that contains the text associated to address
  in the phonebook. For example, if the text "Alice" is associated to
  the phone number "91234567" in the phonebook, address_text will be
  "Alice". The AT command +CSCS (command name in text: Select TE
  Character Set) can be used to specify the character set for displaying
  address_text. Note that address_text is an optional field. Some
  GSM/GPRS modems and mobile phones (examples: most Nokia products,
  including my Nokia 6021) leave this field empty.

How can I identify the message is from Whatsapp or any other services providers names?

答:
You wrote

The fourth field of the information response of the +CMGL AT command, address_text, is a string that contains the text associated to address in the phonebook

If your device used to recognize that number, it probably was in one of device's phonebooks, and maybe it got deleted.

What you can try to do is to store again the number using AT+CPBW command:

AT+CPBW=[<index>][,<number>[,<type>[,<text>]]]

where

index is the record position in the phonebook. If omitted the record is stored in the first free position

number is the number to be stored in phonebook, in string format

type is the number type; 129 for national scheme, 145 for international scheme

text is the name of the entry in the phonebook

So, in your case:

```<code>AT+CPBW=,"81084326797126204",129,"WhatsApp"
</code>```

And after it you should see the name appearing in +CGML list. You might need a device reboot after the PB write in order to see the change making effect.

The change is done in the current phonebook, usually the SIM card. It can be queried with command AT+CPBS? (it also allows to change it; see the guide for further explanation).

I suggest exploring the content of every phonebook, in order to discover any device (and SIM) default contents. The command to read phonebook entries is **AT+CPBR**. Providing

```<code>AT+CPBR=1,N
</code>```

all index between 1  and N are shown. If you set N to the size of the phonebook, you can list all the entries in it.

Body:
I'm new to GSM AT Commands and I'm using ZTE MF190S USB 3G USB Modem with Modem Nodejs Module also tried with MS Hyperterminal.

The problem I'm facing that when I receive SMS using AT+CMGL="ALL" from Whatsapp (as example) I got in sender number field 81084326797126204 which is an invalid phone number and should be "Whatsapp" instead although the manufacture's software is showing message from Whatsapp normally.

Note: I tried to decode it as a Hexadecimal string but not done.

> AT+CSCS="GSM"
> AT+CPMS="ME"
> AT+CMGL="ALL"
//Result
+CMGL: 0,"REC UNREAD","81084326797126204",,"20/05/30,14:53:55+08"
        FEFF000000000000000000000000000000000000020

As described in this link

+CMGL: index,message_status,address,[address_text],[service_center_time_stamp][,address_type,sms_message_body_length]sms_message_body[+CMGL:
  ...]

The address Field

The third field of the information response of the +CMGL AT command,
  address, is a string that contains the address/phone number stored in
  the SMS message header. If the SMS message read is an incoming SMS
  message, the address field contains the originator address. If the SMS
  message read is an outgoing SMS message, the address field contains
  the recipient address. Usually the address field value is a phone
  number formatted using the typical ISDN / telephony numbering plan
  (ITU E.164/E.163). For example, "+85291234567".

The address_text Field

The fourth field of the information response of the +CMGL AT command,
  address_text, is a string that contains the text associated to address
  in the phonebook. For example, if the text "Alice" is associated to
  the phone number "91234567" in the phonebook, address_text will be
  "Alice". The AT command +CSCS (command name in text: Select TE
  Character Set) can be used to specify the character set for displaying
  address_text. Note that address_text is an optional field. Some
  GSM/GPRS modems and mobile phones (examples: most Nokia products,
  including my Nokia 6021) leave this field empty.

How can I identify the message is from Whatsapp or any other services providers names?

Body:
You wrote

The fourth field of the information response of the +CMGL AT command, address_text, is a string that contains the text associated to address in the phonebook

If your device used to recognize that number, it probably was in one of device's phonebooks, and maybe it got deleted.

What you can try to do is to store again the number using AT+CPBW command:

AT+CPBW=[<index>][,<number>[,<type>[,<text>]]]

where

index is the record position in the phonebook. If omitted the record is stored in the first free position

number is the number to be stored in phonebook, in string format

type is the number type; 129 for national scheme, 145 for international scheme

text is the name of the entry in the phonebook

So, in your case:

AT+CPBW=,"81084326797126204",129,"WhatsApp"

And after it you should see the name appearing in +CGML list. You might need a device reboot after the PB write in order to see the change making effect.

The change is done in the current phonebook, usually the SIM card. It can be queried with command AT+CPBS? (it also allows to change it; see the guide for further explanation).

I suggest exploring the content of every phonebook, in order to discover any device (and SIM) default contents. The command to read phonebook entries is **AT+CPBR**. Providing

AT+CPBR=1,N

all index between 1  and N are shown. If you set N to the size of the phonebook, you can list all the entries in it.


问:
iOS view change with gesture problem
here is my problem: In mainviewcontroller I added to swipe down gesture to switch down another view, but inside  other views added to mainviewcontroller with swipe down gesture opens that specific view. However, I dont want swipe down gesture in other views rather than main view.

```<code>//---gesture recognizer

- (IBAction) handleSwipes:(UIGestureRecognizer *) sender {
    UISwipeGestureRecognizerDirection direction = [(UISwipeGestureRecognizer *) sender direction];

    if (direction == UISwipeGestureRecognizerDirectionDown) {
        shakeController = [[ShakeViewController alloc]
                           initWithNibName:@"ShakeViewController" bundle:nil];

        CATransition *transition = [CATransition animation];
        transition.duration = 0.5;

        transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

        transition.type = kCATransitionMoveIn;
        transition.subtype = kCATransitionFromBottom;

        transition.delegate = self;

        // Next add it to the containerView's layer. This will perform the transition based on how we change its contents.
        [self.view.layer addAnimation:transition forKey:nil];

        [self.view addSubview:shakeController.view];

    }
}

- (void)viewDidLoad {
    [super viewDidLoad];

    //gesture recognizer
    UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc]
                                              initWithTarget:self
                                              action:@selector(handleSwipes:)];
    swipeGesture.direction = UISwipeGestureRecognizerDirectionDown;
    [self.view addGestureRecognizer:swipeGesture];

    [swipeGesture release];
}
</code>```

Thanks

答:
You should adopt the UIGestureRecognizerDelegate protocol and implement gestureRecognizer:shouldReceiveTouch: method to signal whether the gesture recognizer should respond or not.

```<code>- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    for ( UIView *subview in self.view.subviews ) {
        CGPoint point = [touch locationInView:subview];
        UIView *hitView = [subview hitTest:point withEvent:nil];
        if ( hitView != nil ) {
            return NO; // Touching one of the subviews so we will not accept the gesture.
        }
    }
    return YES;
}
</code>```

Title: iOS view change with gesture problem

Body:
here is my problem: In mainviewcontroller I added to swipe down gesture to switch down another view, but inside  other views added to mainviewcontroller with swipe down gesture opens that specific view. However, I dont want swipe down gesture in other views rather than main view.

//---gesture recognizer

- (IBAction) handleSwipes:(UIGestureRecognizer *) sender {
    UISwipeGestureRecognizerDirection direction = [(UISwipeGestureRecognizer *) sender direction];

    if (direction == UISwipeGestureRecognizerDirectionDown) {
        shakeController = [[ShakeViewController alloc]
                           initWithNibName:@"ShakeViewController" bundle:nil];

        CATransition *transition = [CATransition animation];
        transition.duration = 0.5;

        transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

        transition.type = kCATransitionMoveIn;
        transition.subtype = kCATransitionFromBottom;

        transition.delegate = self;

        // Next add it to the containerView's layer. This will perform the transition based on how we change its contents.
        [self.view.layer addAnimation:transition forKey:nil];

        [self.view addSubview:shakeController.view];

    }
}

- (void)viewDidLoad {
    [super viewDidLoad];

    //gesture recognizer
    UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc]
                                              initWithTarget:self
                                              action:@selector(handleSwipes:)];
    swipeGesture.direction = UISwipeGestureRecognizerDirectionDown;
    [self.view addGestureRecognizer:swipeGesture];

    [swipeGesture release];
}

Thanks

Body:
You should adopt the UIGestureRecognizerDelegate protocol and implement gestureRecognizer:shouldReceiveTouch: method to signal whether the gesture recognizer should respond or not.

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    for ( UIView *subview in self.view.subviews ) {
        CGPoint point = [touch locationInView:subview];
        UIView *hitView = [subview hitTest:point withEvent:nil];
        if ( hitView != nil ) {
            return NO; // Touching one of the subviews so we will not accept the gesture.
        }
    }
    return YES;
}


问:
Required String parameter 'querycontent' is not present while sending multiple parameters Ajax stringify request with Jquery in Spring MVC Application
when press submit button, #dbresult will display value in select option and textarea.

error message in Console:

org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver logException

Warn: Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'querycontent' is not present]

query.jsp

```<code><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript"
    src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<title>Query DB</title>
</head>
<body>
    db:
    <select name="dbname" id="dbname">
        <option value="ibop_test">ibop_test</option>
        <option value="ibop">ibop</option>
    </select>
    <br>
    <textarea class="boxsizingBorder" id="sqlstr"></textarea>
    <br>
    <button onclick="showresult()">submit</button>
    <div id="dbresult"></div>
</body>
<script type="text/javascript">
    function showresult() {
        document.getElementById("dbresult").innerHTML = "querying...";
        var dbname = document.getElementById('dbname').value;
        var sqlstr = document.getElementById('sqlstr').value;
        var querycontent = JSON.stringify({
            "dbname" : dbname,
            "sqlstr" : sqlstr
        });
        console.log(querycontent); //In Chrome's developer tools window, we will see the logs
        $
                .ajax({
                    type : 'POST',
                    url : 'showresult',
                    contentType : 'application/json',
                    data : querycontent,
                    dataType : 'html',
                    success : function(msg) {
                        document.getElementById("dbresult").innerHTML = msg;
                    },
                    error : function() {
                        document.getElementById("dbresult").innerHTML = "querying failed!";
                    }
                })
    }
</script>
</html>
</code>```

DBQueryController.java

```<code>@Controller
public class DBQueryController {

    @RequestMapping(value = "/showresult", method = RequestMethod.POST)
    public @ResponseBody String showResult(@RequestParam String querycontent){
        String message = "db query result content.</br>";
        return message;
    }
}
</code>```

答:
Since you are sending data in body in your AJAX call, hence @RequestParam will not work. You needs to use @RequestBody instead like following:

```<code>@Controller
public class DBQueryController {

    @RequestMapping(value = "/showresult", method = RequestMethod.POST)
    public @ResponseBody String showResult(@RequestBody Map<String, String> querycontent){
        String message = "db query result content.</br>";
        return message;
    }
}
</code>```

Or simply you can create a POJO class DBQuery like following and use it in controller.

```<code>public class DBQuery {
    private String dbname;
    private String sqlstr;
    // Getters and setters
}

 @Controller
    public class DBQueryController {
        @RequestMapping(value = "/showresult", method = RequestMethod.POST)
        public @ResponseBody String showResult(@RequestBody DBQuery querycontent){
            String message = "db query result content.</br>";
            return message;
        }
   }
</code>```

Coming back to error, since you are not passing querycontent in request as parameter that's why it its throwing

```<code>Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'querycontent' is not present]
</code>```

Body:
when press submit button, #dbresult will display value in select option and textarea.

error message in Console:

org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver logException

Warn: Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'querycontent' is not present]

query.jsp

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<title>Query DB</title>

    db:
    <select name="dbname" id="dbname">
        <option value="ibop_test">ibop_test</option>
        <option value="ibop">ibop</option>
    </select>

    <textarea class="boxsizingBorder" id="sqlstr"></textarea>

    <button onclick="showresult()">submit</button>

DBQueryController.java

@Controller
public class DBQueryController {

    @RequestMapping(value = "/showresult", method = RequestMethod.POST)
    public @ResponseBody String showResult(@RequestParam String querycontent){
        String message = "db query result content.
";
        return message;
    }
}

Body:
Since you are sending data in body in your AJAX call, hence @RequestParam will not work. You needs to use @RequestBody instead like following:

@Controller
public class DBQueryController {

    @RequestMapping(value = "/showresult", method = RequestMethod.POST)
    public @ResponseBody String showResult(@RequestBody Map<String, String> querycontent){
        String message = "db query result content.</br>";
        return message;
    }
}

Or simply you can create a POJO class DBQuery like following and use it in controller.

public class DBQuery {
    private String dbname;
    private String sqlstr;
    // Getters and setters
}

 @Controller
    public class DBQueryController {
        @RequestMapping(value = "/showresult", method = RequestMethod.POST)
        public @ResponseBody String showResult(@RequestBody DBQuery querycontent){
            String message = "db query result content.</br>";
            return message;
        }
   }

Coming back to error, since you are not passing querycontent in request as parameter that's why it its throwing

Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'querycontent' is not present]


问:
Props not passing to function
The props aren't getting passed to the child component. It is showing an empty object when printed. The issue is in the News.js file. All other functionalities are working except the passage of props.
The props are passed in App.js to News.js. Issue is with passing props to the child component.

App.js:

```<code>import React, {useState} from 'react';
import Axios from'axios';
import {v4 as uuidv4} from "uuid";
import './App.css';
import News from './components/News';

const App = () => {
    const [query, setQuery] = useState("");
    const [news, setNews] = useState([]);

    const APP_KEY = "hidden due to privacy issues";
    // const content = "kerala";
    const url =  `https://gnews.io/api/v3/search?q=${query}&token=${APP_KEY}`;
    // GET https://gnews.io/api/v3/search?q=example&token=API-Token

    const getData = async () => {
        const result = await Axios.get(url)
        .then(result=>{
            console.log('inside getdata');

            setNews(result.data.articles);
            console.log(result);
            setQuery(" ");

        })
        .catch(error => {
            console.log(error);
        })

    };

    const onChange = e => {
        setQuery(e.target.value);

    };

    const onSubmit = e => {
        e.preventDefault();
        getData();
    };

    return (
        <div className="App">
          <header className="App-header">
             <h1>NEWSPAPER</h1>
           </header>
           <form className="search-form" onSubmit={onSubmit}>
                 <input
                 type="text"
                 placeholder="Search News!"
                 onChange={onChange}
                 value={query}
                 />
                 <input type="submit" value="Search"/>
            </form>
            <div className="news">
                {news !== [] && news.map(newsItem =>
                    <News key={uuidv4()} props={newsItem}/>
                    // console.log(newsItem)

                    )}
            </div>
        </div>
    )
}

export default App
</code>```

The props are passed in App.js to News.js. Issue is with passing props to the child component.

答: If you’re passing it as props = newsItem, you’ll get this in the child component with props.props.newsItem

Title: Props not passing to function

Body:
The props aren't getting passed to the child component. It is showing an empty object when printed. The issue is in the News.js file. All other functionalities are working except the passage of props.
The props are passed in App.js to News.js. Issue is with passing props to the child component.

App.js:

import React, {useState} from 'react';
import Axios from'axios';
import {v4 as uuidv4} from "uuid";
import './App.css';
import News from './components/News';

const App = () => {
    const [query, setQuery] = useState("");
    const [news, setNews] = useState([]);

    const APP_KEY = "hidden due to privacy issues";
    // const content = "kerala";
    const url =  `https://gnews.io/api/v3/search?q=${query}&token=${APP_KEY}`;
    // GET https://gnews.io/api/v3/search?q=example&token=API-Token

    const getData = async () => {
        const result = await Axios.get(url)
        .then(result=>{
            console.log('inside getdata');

            setNews(result.data.articles);
            console.log(result);
            setQuery(" ");

        })
        .catch(error => {
            console.log(error);
        })

    };

    const onChange = e => {
        setQuery(e.target.value);

    };

    const onSubmit = e => {
        e.preventDefault();
        getData();
    };

    return (

NEWSPAPER

           <form className="search-form" onSubmit={onSubmit}>
                 <input
                 type="text"
                 placeholder="Search News!"
                 onChange={onChange}
                 value={query}
                 />
                 <input type="submit" value="Search"/>
            </form>

                {news !== [] && news.map(newsItem =>
                    <News key={uuidv4()} props={newsItem}/>
                    // console.log(newsItem)

                    )}

    )
}

export default App

The props are passed in App.js to News.js. Issue is with passing props to the child component.


问:
Test Explorer (VS) shows '<Unknown project>'
Everthing below is made in VS2019, using .NET Framework 4.7 and NUnit + NUnit3TestAdapter

I created an assembly called Exitus.Tests, and added a few unit tests. However, do to some issues with Nuget, that I could not solve, I made another project called Exitus.UnitTests and removed the once file I had in the old project (including changing the namespace).

Now the new test project showed op correctly in the explorer, but a "ghost" of the old project remained:

If I try to run the test, the output window shows the following error:

System.InvalidOperationException: The following TestContainer was not found 'C:\Users\xxx\Source\Repositories\Expire\Exitus.Tests\bin\Debug\Exitus.Tests.dll'
     at Microsoft.VisualStudio.TestWindow.Client.TestContainer.TestContainerProvider.d__46.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at Microsoft.VisualStudio.TestWindow.Controller.TestContainerConfigurationQueryByTestsBase.d__6.MoveNext()
     (...)

The stack trace is a lot longer, but the curious thing is the second line, stating that it could not find the test container at \Exitus.Tests\bin\Debug\Exitus.Tests.dll. This is the name of the old test project, which I removed and deleted. I have searched my entire project for the term Exitus.Tests and it returns no results.

Is there anyway to forcefully remove this 'ghost' project?

答:
Steps as below

Close Visual Studio

Go to the project folder

Find the ".vs" folder. (Make sure you are also checking hidden item)

Delete ".vs" folder.

Good to go, Open visual studio, build and run project.


问:
C++ Implementing class function with nested struct outside
So, I want to make the code a bit more pretty in that I want the class def to contain just function declarations. Here is my code:

```<code>template <typename T>
class splay_tree
{
    struct node
    {
        T data;
        node* parent;
        node* left;
        node* right;
     };

     node* grandp(node* x)
     {
         return NULL;
     }

     node* error();
};

node* splay_tree<T>::error()
{
    return NULL;
}
</code>```

My question then is how to move the grandp implementation below the splay tree definition. Note that its return type is node*, so gcc is giving me a hard time with this. Is it possible?

答:
Like this

```<code>template <class T>
typename splay_tree<T>::node* splay_tree<T>::error()
</code>```

The return type of a method is not the the scope of method so splay_tree<T>:: must be specified separately.

Plus since this is a template, you need template <class T>

Body:
So, I want to make the code a bit more pretty in that I want the class def to contain just function declarations. Here is my code:

template <typename T>
class splay_tree
{
    struct node
    {
        T data;
        node* parent;
        node* left;
        node* right;
     };

     node* grandp(node* x)
     {
         return NULL;
     }

     node* error();
};

node* splay_tree<T>::error()
{
    return NULL;
}

My question then is how to move the grandp implementation below the splay tree definition. Note that its return type is node*, so gcc is giving me a hard time with this. Is it possible?

Body:
Like this

template <class T>
typename splay_tree<T>::node* splay_tree<T>::error()

The return type of a method is not the the scope of method so splay_tree<T>:: must be specified separately.

Plus since this is a template, you need template <class T>


问:
Kofax Java wrapper on Linux
Currently I am using .net application and kofax scan.exe to virtually scan my documents into kofax, but i want to switch from .net to java (Linux) and still achieve the virtual scan functionality in kofax.

Anyone has idea if kofax has any API or Java wrapper ?

答:
Writing as answer since I cant comment yet. I would not advise to use the AXCMLAI.exe that @Wolfgang Radl mentioned.

It is marked as obsolete, and may be removed in a next future version.

KIC is more to use in this case, but If you bought KC before the license bundle it might be to expensive.

I would not recommend the migration of KC to a linux environment unless you want to do extensive testing.

Be aware their support will probably dismiss any ticket you may have due to not having a prerequisite server.

Title: Kofax Java wrapper on Linux


问:
Meteor user accounts issue - Duplicate account being created with OAuth service (accounts-google)
I am working with Meteor User accounts to create users. I have implemented two ways of creating users.

By using accounts-password to create (default one ).

OAuth Services (accounts-google and accounts-facebook)

A user account generated with accounts-password have the document shown below

```<code>{
  "_id": "DQnDpEag2kPevSdJY",
  "createdAt": "2015-12-10T22:34:17.610Z",
  "services": {
    "password": {
      "bcrypt": "XXX"
    },
    "resume": {
      "loginTokens": [
        {
          "when": "2015-12-10T22:34:17.615Z",
          "hashedToken": "XXX"
        }
      ]
    }
  },
 -----
----
}
</code>```

Where as a user account generated with accounts-google or account-facebook have the document shown below.

```<code>{
  "_id": "Ap85ac4r6Xe3paeAh",
  "createdAt": "2015-12-10T22:29:46.854Z",
  "services": {
    "facebook": {
      "accessToken": "XXX",
      "expiresAt": 1454970581716,
      "id": "XXX",
      "email": "myname@gmail.com",
      "name": "Ada Lovelace",
      "first_name": "Ada",
      "last_name": "Lovelace",
      "link": "https://www.facebook.com/app_scoped_user_id/XXX/",
      "gender": "female",
      "locale": "en_US",
      "age_range": {
        "min": 21
      }
    },
---
---
---
</code>```

Now the real issue is, Although the email address used is same for both accounts-password and accounts-google (in my case email is myname@gmail.com), two different user accounts are being created.

I am looking for solution Something like below. (Note: Services has both "Password" and "Facebook" sections under single account)

```<code>{
  "_id": "DQnDpEag2kPevSdJY",
  "createdAt": "2015-12-10T22:34:17.610Z",
  "services": {
    "password": {
      "bcrypt": "XXX"
    },
    "facebook": {
      "accessToken": "XXX",
      "expiresAt": 1454970581716,
      "id": "XXX",
      "email": "myname@gmail.com",
      "name": "Ada Lovelace",
      "first_name": "Ada",
      "last_name": "Lovelace",
      "link": "https://www.facebook.com/app_scoped_user_id/XXX/",
      "gender": "female",
      "locale": "en_US",
      "age_range": {
        "min": 21
      }
    },
  },
 -----
----
}
</code>```

Is there a way where only one account is being generated in both cases, means if a user is already existed and the same is trying with OAuth service, first account should be used to accommodate the service ?

答:
I have solved the above issue with a hack.

In imports/startup/server/accounts.js I have added the below validation logic which always validates the newly created account.

The idea is, this process checks if user is already existed in database. If the user exists, further checks if its created from accounts-password or accounts-google/facebook .

Based on the existing type modify the existing fields with new fields and throw an error with a fancy message (This actually prevents the new account to be created).

```<code>Accounts.validateNewUser(function (user) {

// first check what is the newly creating service
  var service =
    user.services.google || user.services.facebook || user.services.password;

  if (!service) return true;

  var existingUser = null;
// due to some issues both `Meteor.users.findOne(email)` as well `Account.findUserByEmail(email)` methods have been used to find the existing user status

  if (user.services.password) {
    var email = user.emails[0].address;
    existingUser = Meteor.users.findOne({
      $or: [
        { "registered_emails[0].address": email },
        { "services.google.email": email },
        { "services.facebook.email": email },
      ],
    });

  } else {
    var email = service.email;
    //console.log(" retrieved email ", email);
    existingUser = Accounts.findUserByEmail(email);
  }

  //console.log(" existingUser  : ", existingUser);
  if (!existingUser) return true;

  if (user.services.google) {
    Meteor.users.update(
      { _id: existingUser._id },
      {
        $set: {
          profile: user.profile,
          "services.google": user.services.google,
        },

      }
    );
  } else if (user.services.facebook) {
    Meteor.users.update(
      { _id: existingUser._id },
      {
        $set: {
          profile: user.profile,
          "services.facebook": user.services.facebook,
        },

      }
    );
  } else {
    Meteor.users.update(
      { _id: existingUser._id },
      {
        $set: {
          profile: user.profile,
          "services.password": user.services.password,
          "services.email": user.services.email,
          emails: user.emails,
        },

      }
    );
  }

  throw new Meteor.Error(
    205,
    "Merged with your existing Social Login accounts now. Try refresh the page and sign in again. That should work !!"
  );
});
</code>```

Body:
I am working with Meteor User accounts to create users. I have implemented two ways of creating users.

By using accounts-password to create (default one ).

OAuth Services (accounts-google and accounts-facebook)

A user account generated with accounts-password have the document shown below

{
  "_id": "DQnDpEag2kPevSdJY",
  "createdAt": "2015-12-10T22:34:17.610Z",
  "services": {
    "password": {
      "bcrypt": "XXX"
    },
    "resume": {
      "loginTokens": [
        {
          "when": "2015-12-10T22:34:17.615Z",
          "hashedToken": "XXX"
        }
      ]
    }
  },
 -----
----
}

Where as a user account generated with accounts-google or account-facebook have the document shown below.

{
  "_id": "Ap85ac4r6Xe3paeAh",
  "createdAt": "2015-12-10T22:29:46.854Z",
  "services": {
    "facebook": {
      "accessToken": "XXX",
      "expiresAt": 1454970581716,
      "id": "XXX",
      "email": "myname@gmail.com",
      "name": "Ada Lovelace",
      "first_name": "Ada",
      "last_name": "Lovelace",
      "link": "https://www.facebook.com/app_scoped_user_id/XXX/",
      "gender": "female",
      "locale": "en_US",
      "age_range": {
        "min": 21
      }
    },
---
---
---

Now the real issue is, Although the email address used is same for both accounts-password and accounts-google (in my case email is myname@gmail.com), two different user accounts are being created.

I am looking for solution Something like below. (Note: Services has both "Password" and "Facebook" sections under single account)

{
  "_id": "DQnDpEag2kPevSdJY",
  "createdAt": "2015-12-10T22:34:17.610Z",
  "services": {
    "password": {
      "bcrypt": "XXX"
    },
    "facebook": {
      "accessToken": "XXX",
      "expiresAt": 1454970581716,
      "id": "XXX",
      "email": "myname@gmail.com",
      "name": "Ada Lovelace",
      "first_name": "Ada",
      "last_name": "Lovelace",
      "link": "https://www.facebook.com/app_scoped_user_id/XXX/",
      "gender": "female",
      "locale": "en_US",
      "age_range": {
        "min": 21
      }
    },
  },
 -----
----
}

Is there a way where only one account is being generated in both cases, means if a user is already existed and the same is trying with OAuth service, first account should be used to accommodate the service ?

Body:
I have solved the above issue with a hack.

In imports/startup/server/accounts.js I have added the below validation logic which always validates the newly created account.

The idea is, this process checks if user is already existed in database. If the user exists, further checks if its created from accounts-password or accounts-google/facebook .

Based on the existing type modify the existing fields with new fields and throw an error with a fancy message (This actually prevents the new account to be created).

Accounts.validateNewUser(function (user) {

// first check what is the newly creating service
  var service =
    user.services.google || user.services.facebook || user.services.password;

  if (!service) return true;

  var existingUser = null;
// due to some issues both `Meteor.users.findOne(email)` as well `Account.findUserByEmail(email)` methods have been used to find the existing user status

  if (user.services.password) {
    var email = user.emails[0].address;
    existingUser = Meteor.users.findOne({
      $or: [
        { "registered_emails[0].address": email },
        { "services.google.email": email },
        { "services.facebook.email": email },
      ],
    });

  } else {
    var email = service.email;
    //console.log(" retrieved email ", email);
    existingUser = Accounts.findUserByEmail(email);
  }

  //console.log(" existingUser  : ", existingUser);
  if (!existingUser) return true;

  if (user.services.google) {
    Meteor.users.update(
      { _id: existingUser._id },
      {
        $set: {
          profile: user.profile,
          "services.google": user.services.google,
        },

      }
    );
  } else if (user.services.facebook) {
    Meteor.users.update(
      { _id: existingUser._id },
      {
        $set: {
          profile: user.profile,
          "services.facebook": user.services.facebook,
        },

      }
    );
  } else {
    Meteor.users.update(
      { _id: existingUser._id },
      {
        $set: {
          profile: user.profile,
          "services.password": user.services.password,
          "services.email": user.services.email,
          emails: user.emails,
        },

      }
    );
  }

  throw new Meteor.Error(
    205,
    "Merged with your existing Social Login accounts now. Try refresh the page and sign in again. That should work !!"
  );
});


问:
style react component on click
so i have this simple divs of names:

i just want to press on one of them and get a background color of green and when pressing on another one the first one will be canceled so just one will be colored at a time. what i simply need is inline style or i don't know i'm stuck.

first.js:

import React from 'react';

```<code>function SidebarComponents({name,title,selected,onSelect}) {

    const style={
        cursor: "pointer"
    };

    const classes = {
        selected: {
          backgroundColor: '#00ff00'
        }
      }

    return (
        <div
            name={name}
            title = {title}
            style={style}
        >
           {name}
        </div>
    )

}
export default SidebarComponents;
</code>```

second.js:

```<code>import React, { useEffect, useState } from "react";
import SidebarComponents from "../SidebarComponents/SidebarComponents";
import 'bootstrap/dist/css/bootstrap.min.css';
import '../Sidebar1/Sidebar.css';

function Sidebar({ onChange }) {
  const [selectedComponent, setSelectedComponent] = useState({
    componentsName: [
      { name: "John Smith", title: "John Smith" },
      { name: "Male, 26 years old", title: "Gender and age" },
      { name: "john", title: "Alerts" },
      { name: "claude", title: "Recent" },
      { name: "edward", title: "Blood pressure" },
      { name: "mira", title: "Body weight" },
      { name: "alex", title: "Glucose" },
      { name: "zac", title: "SPO2" }
    ]
  });

  return (
    <div>
      {selectedComponent.componentsName.map(component => {
        return (
            <div className="row align-items-start sidebar-components">
                <div className="col">
                    <SidebarComponents
                    name={component.name}
                    title={component.title}
                    />
                </div>
          </div>
        );
      })}
    </div>
  );
}

export default Sidebar;
</code>```

答:
Add key attribute to div, inside the map.

Handel onClick event, to store the selected element index/value in your state.

Apply style using conditional rendering of className.

second.js

  {selectedComponent.componentsName.map((component, index) => {
    return (

 handelOnClick(index)} className="row align-items-start sidebar-components">

          <SidebarComponents
            name={component.name}
            title={component.title}
            className={selectedIndex === index ? 'highlight' : ''}
          />

    );
  })}

```

As you are rendering text in first.js no need to use div wrapper, use 'p', 'span' tag

In second.js instead of iterating entire div block, use ul li

Title: style react component on click

Body:
so i have this simple divs of names:

i just want to press on one of them and get a background color of green and when pressing on another one the first one will be canceled so just one will be colored at a time. what i simply need is inline style or i don't know i'm stuck.

first.js:

import React from 'react';

function SidebarComponents({name,title,selected,onSelect}) {

    const style={
        cursor: "pointer"
    };

    const classes = {
        selected: {
          backgroundColor: '#00ff00'
        }
      }

    return (

           {name}

    )

}
export default SidebarComponents;

second.js:

import React, { useEffect, useState } from "react";
import SidebarComponents from "../SidebarComponents/SidebarComponents";
import 'bootstrap/dist/css/bootstrap.min.css';
import '../Sidebar1/Sidebar.css';

function Sidebar({ onChange }) {
  const [selectedComponent, setSelectedComponent] = useState({
    componentsName: [
      { name: "John Smith", title: "John Smith" },
      { name: "Male, 26 years old", title: "Gender and age" },
      { name: "john", title: "Alerts" },
      { name: "claude", title: "Recent" },
      { name: "edward", title: "Blood pressure" },
      { name: "mira", title: "Body weight" },
      { name: "alex", title: "Glucose" },
      { name: "zac", title: "SPO2" }
    ]
  });

  return (

      {selectedComponent.componentsName.map(component => {
        return (

                    <SidebarComponents
                    name={component.name}
                    title={component.title}
                    />

        );
      })}

  );
}

export default Sidebar;

Body:
Add key attribute to div, inside the map.

Handel onClick event, to store the selected element index/value in your state.

Apply style using conditional rendering of className.

second.js

<div>
  {selectedComponent.componentsName.map((component, index) => {
    return (
      <div key={index} onClick={() => handelOnClick(index)} className="row align-items-start sidebar-components">
        <div className="col">
          <SidebarComponents
            name={component.name}
            title={component.title}
            className={selectedIndex === index ? 'highlight' : ''}
          />
        </div>
      </div>
    );
  })}
</div>

As you are rendering text in first.js no need to use div wrapper, use 'p', 'span' tag

In second.js instead of iterating entire div block, use ul li


问:
How can i add Signature to a specific place in XMLdocument?
I have XML document:

```<code>    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Header/>
    <soapenv:Body>
        <saml2p:ArtifactResolve xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol" Version="2.0"
                                IssueInstant="2020-06-01T10:25:15+02:00">
            <saml2:Issuer xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion">TEST</saml2:Issuer>
            <saml2p:Artifact>AAQAAKFbFR94fxqmioAqjJUwfHTFVHTDBTVHdBwwTW+ehcM19zsk=</saml2p:Artifact>
        </saml2p:ArtifactResolve>
    </soapenv:Body>
</soapenv:Envelope>
</code>```

I try to do this in this way:

```<code>$results = array();
$filename = 'cert.p12';
$password = 'certpass';
$priv_key = openssl_pkcs12_read(file_get_contents($filename), $results, $password);

$doc = new DOMDocument();
$doc->loadXML($xml);
$xp = new DOMXPath($doc);
$xp->registerNamespace('soapenv', 'http://schemas.xmlsoap.org/soap/envelope/');
$xp->registerNamespace('saml2p','urn:oasis:names:tc:SAML:2.0:protocol');
$xp->registerNamespace('saml2','urn:oasis:names:tc:SAML:2.0:assertion');
$xp->registerNamespace('ds',XMLSecurityDSig::XMLDSIGNS);

$artifactResolveNode = $xp->query('/*[local-name()=\'Envelope\']/*[local-name()=\'Body\']/*[local-name()=\'ArtifactResolve\']')->item(0);

if($artifactResolveNode){

    $objDSig = new XMLSecurityDSig();
    $objDSig->setCanonicalMethod(XMLSecurityDSig::EXC_C14N);
    $objDSig->addReference(
        $artifactResolveNode,
        XMLSecurityDSig::SHA256,
        array('http://www.w3.org/2000/09/xmldsig#enveloped-signature', 'http://www.w3.org/2001/10/xml-exc-c14n#'),
        array('force_uri' => true)
    );
    $objKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA256, array('type' => 'private'));
    $objKey->loadKey($results['pkey'], FALSE);
    $objDSig->sign($objKey);
    $objDSig->add509Cert($results['cert']);
    $objDSig->appendSignature($doc->documentElement());
    echo $doc->saveXML();
}
</code>```

Output with Singnature in wrong location is:

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Header/>
    <soapenv:Body>
    <saml2p:ArtifactResolve xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol" Version="2.0" IssueInstant="2020-06-01T10:25:15+02:00" Id="pfx97783ab1-0339-0f2e-b759-9e9c07e347b0">
    <saml2:Issuer xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion">TEST</saml2:Issuer><saml2p:Artifact>AAQAAKFbFR94fxqmioAqjJUwfyUtjJbv0uEPB7ooopodBwwTW+ehcM19zsk=</saml2p:Artifact></saml2p:ArtifactResolve>
    </soapenv:Body>
    <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">

  <ds:SignedInfo>
(...)
</soapenv:Envelope>
</code>```

I want to put Signature node between ISSUER and ARTIFACT. This location is very important to correct send SOAP Envelope.
It is possible?

答:
I found!
I need add code below:

```<code>$artifactNode = $xp->query('/*[local-name()=\'Envelope\']/*[local-name()=\'Body\']/*[local-name()=\'ArtifactResolve\']/*[local-name()=\'Artifact\']')->item(0);
</code>```

and append Signature like this:

```<code>    $objDSig->insertSignature($artifactResolveNode,$artifactNode);
</code>```

Body:
I have XML document:

    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Header/>
    <soapenv:Body>
        <saml2p:ArtifactResolve xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol" Version="2.0"
                                IssueInstant="2020-06-01T10:25:15+02:00">
            <saml2:Issuer xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion">TEST</saml2:Issuer>
            <saml2p:Artifact>AAQAAKFbFR94fxqmioAqjJUwfHTFVHTDBTVHdBwwTW+ehcM19zsk=</saml2p:Artifact>
        </saml2p:ArtifactResolve>
    </soapenv:Body>
</soapenv:Envelope>

I try to do this in this way:

$results = array();
$filename = 'cert.p12';
$password = 'certpass';
$priv_key = openssl_pkcs12_read(file_get_contents($filename), $results, $password);

$doc = new DOMDocument();
$doc->loadXML($xml);
$xp = new DOMXPath($doc);
$xp->registerNamespace('soapenv', 'http://schemas.xmlsoap.org/soap/envelope/');
$xp->registerNamespace('saml2p','urn:oasis:names:tc:SAML:2.0:protocol');
$xp->registerNamespace('saml2','urn:oasis:names:tc:SAML:2.0:assertion');
$xp->registerNamespace('ds',XMLSecurityDSig::XMLDSIGNS);

$artifactResolveNode = $xp->query('/*[local-name()=\'Envelope\']/*[local-name()=\'Body\']/*[local-name()=\'ArtifactResolve\']')->item(0);

if($artifactResolveNode){

    $objDSig = new XMLSecurityDSig();
    $objDSig->setCanonicalMethod(XMLSecurityDSig::EXC_C14N);
    $objDSig->addReference(
        $artifactResolveNode,
        XMLSecurityDSig::SHA256,
        array('http://www.w3.org/2000/09/xmldsig#enveloped-signature', 'http://www.w3.org/2001/10/xml-exc-c14n#'),
        array('force_uri' => true)
    );
    $objKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA256, array('type' => 'private'));
    $objKey->loadKey($results['pkey'], FALSE);
    $objDSig->sign($objKey);
    $objDSig->add509Cert($results['cert']);
    $objDSig->appendSignature($doc->documentElement());
    echo $doc->saveXML();
}

Output with Singnature in wrong location is:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Header/>
    <soapenv:Body>
    <saml2p:ArtifactResolve xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol" Version="2.0" IssueInstant="2020-06-01T10:25:15+02:00" Id="pfx97783ab1-0339-0f2e-b759-9e9c07e347b0">
    <saml2:Issuer xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion">TEST</saml2:Issuer><saml2p:Artifact>AAQAAKFbFR94fxqmioAqjJUwfyUtjJbv0uEPB7ooopodBwwTW+ehcM19zsk=</saml2p:Artifact></saml2p:ArtifactResolve>
    </soapenv:Body>
    <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">

  <ds:SignedInfo>
(...)
</soapenv:Envelope>

I want to put Signature node between ISSUER and ARTIFACT. This location is very important to correct send SOAP Envelope.
It is possible?

Body:
I found!
I need add code below:

$artifactNode = $xp->query('/*[local-name()=\'Envelope\']/*[local-name()=\'Body\']/*[local-name()=\'ArtifactResolve\']/*[local-name()=\'Artifact\']')->item(0);

and append Signature like this:

    $objDSig->insertSignature($artifactResolveNode,$artifactNode);


答:
You're creating News with no props at the very end of News.js:

```<code>export default function Facebook() {
  return <News />  // <=========================== here
}
</code>```

That's why you're seeing a News component created without any props.

See also Rahul Dwivedi's answer, you probably want newsItem={newsItem}, not props={newsItem}.

A side note regarding:

```<code><div className="news">
    {news !== [] && news.map(newsItem =>
        <News key={uuidv4()} props={newsItem}/>
        // console.log(newsItem)

        )}
</div>
</code>```

news !== [] is always true. No two objects are ever equal to each other. If you wanted a guard there to prevent teh call to map when news is empty, you'd use news.length !== 0:

```<code><div className="news">
    {news.length !== 0 && news.map(newsItem =>
        <News key={uuidv4()} props={newsItem}/>
    )}
</div>
</code>```

but you don't need one; calling map on an empty array is harmless, it produces an empty array:

```<code><div className="news">
    {news.map(newsItem =>
        <News key={uuidv4()} props={newsItem}/>
    )}
</div>
</code>```

Title: Props not passing to function

Body:
You're creating News with no props at the very end of News.js:

export default function Facebook() {
  return <News />  // <=========================== here
}

That's why you're seeing a News component created without any props.

See also Rahul Dwivedi's answer, you probably want newsItem={newsItem}, not props={newsItem}.

A side note regarding:

<div className="news">
    {news !== [] && news.map(newsItem =>
        <News key={uuidv4()} props={newsItem}/>
        // console.log(newsItem)

        )}
</div>

news !== [] is always true. No two objects are ever equal to each other. If you wanted a guard there to prevent teh call to map when news is empty, you'd use news.length !== 0:

<div className="news">
    {news.length !== 0 && news.map(newsItem =>
        <News key={uuidv4()} props={newsItem}/>
    )}
</div>

but you don't need one; calling map on an empty array is harmless, it produces an empty array:

<div className="news">
    {news.map(newsItem =>
        <News key={uuidv4()} props={newsItem}/>
    )}
</div>