问:
Displaying images from firebase to my android application in recyclerview
Firebase Database----------

I've been trying to show all the images stored in firebase in an android application using recyclerview. Is there a way to do so?
I uploaded the photos I want to show in firebase storage and its download URL in firebase database. Each image has a primary ID. I don't know how I can get access to all the child elements of all the primary ID.

Please help me solve this problem.

答:
if using a fragment you can do I like below on your on create method

```<code>@Override
    public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        databaseReference = FirebaseDatabase.getInstance().getReference().child("users");
        databaseReference.keepSynced(true);

        firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<AllUsers, AllUsersViewHolder>
                (AllUsers.class, R.layout.all_users_display_layout, AllUsersViewHolder.class, databaseReference) {
            @Override
            protected void populateViewHolder(AllUsersViewHolder viewHolder, AllUsers model, final int position) {

                viewHolder.setThumbImage(getContext(), model.getThumbImage());

            }
        };
        all_user_list.setAdapter(firebaseRecyclerAdapter);
    }
</code>```

and create a static class that extends from RecyclerView.ViewHolder like below

```<code>public static class AllUsersViewHolder extends RecyclerView.ViewHolder {

        View view;

        public AllUsersViewHolder(View itemView) {
            super(itemView);
            view = itemView;
        }

        public void setThumbImage(final Context context, final String thumb_image) {
            final CircleImageView all_user_image = (CircleImageView) view.findViewById(R.id.all_user_image);

            if(!thumb_image.equals("default_image")) {
                Picasso.with(context).load(thumb_image).networkPolicy(NetworkPolicy.OFFLINE)
                        .placeholder(R.drawable.default_image).into(all_user_image, new Callback() {
                    @Override
                    public void onSuccess() {

                    }

                    @Override
                    public void onError() {
                        Picasso.with(context).load(thumb_image).placeholder(R.drawable.default_image).into(all_user_image);
                    }
                });
            }
        }
    }
</code>```

and create a helper class like below

```<code>public class AllUsers {

    public String thumb_image;

    public AllUsers() {

    }

    public AllUsers(String thumb_image) {

        this.thumb_image = thumb_image;
    }

    public String getThumbImage() {
        return thumb_image;
    }

    public void setThumbImage(String thumb_image) {
        this.thumb_image = thumb_image;
    }

}
</code>```

after that you can retrieve your images to your recycler view

Body:
if using a fragment you can do I like below on your on create method

@Override
    public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        databaseReference = FirebaseDatabase.getInstance().getReference().child("users");
        databaseReference.keepSynced(true);

        firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<AllUsers, AllUsersViewHolder>
                (AllUsers.class, R.layout.all_users_display_layout, AllUsersViewHolder.class, databaseReference) {
            @Override
            protected void populateViewHolder(AllUsersViewHolder viewHolder, AllUsers model, final int position) {

                viewHolder.setThumbImage(getContext(), model.getThumbImage());

            }
        };
        all_user_list.setAdapter(firebaseRecyclerAdapter);
    }

and create a static class that extends from RecyclerView.ViewHolder like below

public static class AllUsersViewHolder extends RecyclerView.ViewHolder {

        View view;

        public AllUsersViewHolder(View itemView) {
            super(itemView);
            view = itemView;
        }

        public void setThumbImage(final Context context, final String thumb_image) {
            final CircleImageView all_user_image = (CircleImageView) view.findViewById(R.id.all_user_image);

            if(!thumb_image.equals("default_image")) {
                Picasso.with(context).load(thumb_image).networkPolicy(NetworkPolicy.OFFLINE)
                        .placeholder(R.drawable.default_image).into(all_user_image, new Callback() {
                    @Override
                    public void onSuccess() {

                    }

                    @Override
                    public void onError() {
                        Picasso.with(context).load(thumb_image).placeholder(R.drawable.default_image).into(all_user_image);
                    }
                });
            }
        }
    }

and create a helper class like below

public class AllUsers {

    public String thumb_image;

    public AllUsers() {

    }

    public AllUsers(String thumb_image) {

        this.thumb_image = thumb_image;
    }

    public String getThumbImage() {
        return thumb_image;
    }

    public void setThumbImage(String thumb_image) {
        this.thumb_image = thumb_image;
    }

}

after that you can retrieve your images to your recycler view


来源: stackexchange

问:
Jsoup, parse html loaded ajax table
I have a problem with the table parsing, which is loaded with ajax:

```<code>Document doc = Jsoup.connect("http://lfl.ru/club553").get();
</code>```

That's what i get:

```<code><div class="tournament_stats_table_tournament_3442 tournament-stats-table" style="display: block;" url="/?ajax=1&method=tournament_stats_table&tournament_id=3442&club_id=553">
                        подождите...                    </div>
</code>```

Tell me please what can be done in this situation.
Thx.

答:
First: you need get Cookies ,just using

```<code> Connection.Response = Jsoup.connect.method(get).excute
</code>```

Then: make request with cookies and headers

```<code>document=Jsoup.connect.header.data.post
</code>```

e.g.

```<code>Connection.Response loginForm=Jsoup.connect("http://www.a5.cn").
        method(Connection.Method.GET).execute();

Document document=Jsoup.connect("http://www.a5.cn/login.html").
        data("formhash","97bfbf").data("hdn_refer","http://www.a5.cn/")
        data("account","userID").data("autoLogin","1").data("password","your password").
        cookies(loginForm.cookies()).header("Accept","application/json, text/javascript, */*; q=0.01").header("X-Requested-With","XMLHttpRequest").post();

System.out.println(document.body().text());
</code>```

ContentLicense: CC BY-SA 3.0

Title: Jsoup, parse html loaded ajax table

Body:
I have a problem with the table parsing, which is loaded with ajax:

Document doc = Jsoup.connect("http://lfl.ru/club553").get();

That's what i get:

                        подождите...

Tell me please what can be done in this situation.
Thx.

Body:
First: you need get Cookies ,just using

 Connection.Response = Jsoup.connect.method(get).excute

Then: make request with cookies and headers

document=Jsoup.connect.header.data.post

e.g.

Connection.Response loginForm=Jsoup.connect("http://www.a5.cn").
        method(Connection.Method.GET).execute();

Document document=Jsoup.connect("http://www.a5.cn/login.html").
        data("formhash","97bfbf").data("hdn_refer","http://www.a5.cn/")
        data("account","userID").data("autoLogin","1").data("password","your password").
        cookies(loginForm.cookies()).header("Accept","application/json, text/javascript, */*; q=0.01").header("X-Requested-With","XMLHttpRequest").post();

System.out.println(document.body().text());


问:
Why is my django urlpattern not resolving?
So I'm creating a small ecommerce website for a friend and cannot work out why the url won't resolve itself.

For the sake of simplicity whilst making the website I'm using a product called "number 1". It has a slug field of "number-1" and on the product page clicking on the product takes a user to "/shop/number-1"

My url pattern for this is:

```<code>url(r'^<slug:url>', views.item, name='products')
</code>```

with the view:

```<code>def item(request, url=""):
    products = product.objects.get(url=url)
    return render(request, 'shop\product.html', {'products', products})
</code>```

As far as I can tell this should render my product.html template but instead it returns a 404 and I'm not sure why?

If it helps I have other views, such as product types set within the same views and they work fine so as far as I can tell its that the slug:url isn't being used in the views.item, or the view isn't getting the context properly.

Also I'm on django 1.11.7 for this project.

答:
The url pattern you are trying to use (slug:url) is only valid in Django 2.

If you are on Django 1.11 then you need to use a regular expression - something like this:

```<code>url(r'^?P<url>[\w-]+', views.item, name='products')
</code>```

Always make sure you're looking at the documentation for your version of Django ;-).

Body:
So I'm creating a small ecommerce website for a friend and cannot work out why the url won't resolve itself.

For the sake of simplicity whilst making the website I'm using a product called "number 1". It has a slug field of "number-1" and on the product page clicking on the product takes a user to "/shop/number-1"

My url pattern for this is:

url(r'^<slug:url>', views.item, name='products')

with the view:

def item(request, url=""):
    products = product.objects.get(url=url)
    return render(request, 'shop\product.html', {'products', products})

As far as I can tell this should render my product.html template but instead it returns a 404 and I'm not sure why?

If it helps I have other views, such as product types set within the same views and they work fine so as far as I can tell its that the slug:url isn't being used in the views.item, or the view isn't getting the context properly.

Also I'm on django 1.11.7 for this project.

Body:
The url pattern you are trying to use (slug:url) is only valid in Django 2.

If you are on Django 1.11 then you need to use a regular expression - something like this:

url(r'^?P<url>[\w-]+', views.item, name='products')

Always make sure you're looking at the documentation for your version of Django ;-).


问:
How to put JSON data into a HTML div?
Here is my problem: I want to put JSON data that I catch with an Ajax call in an HTML div.

function showEspece(espece, categorie, object) {
  $.ajax({
    type: 'POST',
    url: 'getespece.php',
    data: {
      espece: espece,
      categorie: categorie
    },
    dataType: 'json',
    success: function(data) {
      console.log(data);
      $('#output').html(data); //what i try to do but don't work
    },
    error: function(xhr, status, error) {
      console.log(error);
    }
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="output"></div></code>```

And here is what the variable data contains:

How can I show the variable's content in an HTML div - in a table particularly?

答:
```<code>var data = {
    DATENAISSANCE: [...],
    ...
}

var root = document.getElementById("output");
var table = element("table");
root.appendChild(table);

var dataName;
for (dataName in data) {
    if (data.hasOwnProperty(dataName)) {
        var row = element("tr", element("th", dataName));
        data[dataName].forEach(function (dataValue) {
            row.appendChild(element("td", dataValue));
        });
        table.appendChild(row);
    }
}

// Create a convenient function `element` which creates an element and sets its content
function element(nodeName, content, attributes, eventListeners) {
    var node = document.createElement(nodeName);
    appendChildren(node, content);
    return node;
}

function appendChildren(node, content) {
    var append = function (t) {
        if (/string|number/.test(typeof t)) {
            node.innerHTML += t;
        } else if (t instanceof HTMLElement) {
            node.appendChild(t);
        }
    };
    if (content instanceof Array) {
        content.forEach(function (item) {
            append(item);
        });
    } else {
        append(content);
    }
}
</code>```

Title: How to put JSON data into a HTML div?

Body:
Here is my problem: I want to put JSON data that I catch with an Ajax call in an HTML div.

function showEspece(espece, categorie, object) {
  $.ajax({
    type: 'POST',
    url: 'getespece.php',
    data: {
      espece: espece,
      categorie: categorie
    },
    dataType: 'json',
    success: function(data) {
      console.log(data);
      $('#output').html(data); //what i try to do but don't work
    },
    error: function(xhr, status, error) {
      console.log(error);
    }
  });
}

And here is what the variable data contains:

How can I show the variable's content in an HTML div - in a table particularly?


问:
How can I select only rows with multiple hits for a specific column?
I am not sure how to phrase this question so I'll give an example:

Suppose there is a table called tagged that has two columns: tagger and taggee. What would the SQL query look like to return the taggee(s) that are in multiple rows? That is to say, they have been tagged 2 or more times by any tagger.

I would like a 'generic' SQL query and not something that only works on a specific DBMS.

EDIT: Added "tagged 2 or more times by any tagger."

答:
HAVING can operate on the result of aggregate functions.  So if you have data like this:

```<code>Row    tagger  |  taggee
       --------+----------
1.     Joe     |  Cat
2.     Fred    |  Cat
3.     Denise  |  Dog
4.     Joe     |  Horse
5.     Denise  |  Horse
</code>```

It sounds like you want Cat, Horse.

To get the taggee's that are in multiple rows, you would execute:

```<code>SELECT taggee, count(*) FROM tagged GROUP BY taggee HAVING count(*) > 1
</code>```

That being said, when you say "select only rows with multiple hits for a specific column", which row do you want?  Do you want row 1 for Cat, or row 2?

ContentLicense: CC BY-SA 2.5

Body:
HAVING can operate on the result of aggregate functions.  So if you have data like this:

Row    tagger  |  taggee
       --------+----------
1.     Joe     |  Cat
2.     Fred    |  Cat
3.     Denise  |  Dog
4.     Joe     |  Horse
5.     Denise  |  Horse

It sounds like you want Cat, Horse.

To get the taggee's that are in multiple rows, you would execute:

SELECT taggee, count(*) FROM tagged GROUP BY taggee HAVING count(*) > 1

That being said, when you say "select only rows with multiple hits for a specific column", which row do you want?  Do you want row 1 for Cat, or row 2?


问:
Python / Spark cast multiple variables - columns as double type
I am translating Scala / Spark deep learning model into Python / PySpark. After reading the df all variables are interpreted as strings type. I need to cast them as float.
Doing this one by one is easy, I think it would be like this:

```<code>format_number(result['V1'].cast('float'),2).alias('V1')
</code>```

, but there is 31 columns
How to do it all at once.
The columns are "V1" to "V28" and "Time", "Amount", "Class"

Scala solution to it is this:

```<code>// cast all the column to Double type.
val df = raw.select(((1 to 28).map(i => "V" + i) ++ Array("Time", "Amount", "Class")).map(s => col(s).cast("Double")): _*)
</code>```

https://github.com/intel-analytics/analytics-zoo/blob/master/apps/fraudDetection/Fraud%20Detction.ipynb

How to do the same in PySpark?

答:
Use comprehensions:</p>

```<code>result.select([
    format_number(result[c].cast('float'),2).alias(c) for c in result.columns
])
</code>```

Body:
I am translating Scala / Spark deep learning model into Python / PySpark. After reading the df all variables are interpreted as strings type. I need to cast them as float.
Doing this one by one is easy, I think it would be like this:

format_number(result['V1'].cast('float'),2).alias('V1')

, but there is 31 columns
How to do it all at once.
The columns are "V1" to "V28" and "Time", "Amount", "Class"

Scala solution to it is this:

// cast all the column to Double type.
val df = raw.select(((1 to 28).map(i => "V" + i) ++ Array("Time", "Amount", "Class")).map(s => col(s).cast("Double")): _*)

https://github.com/intel-analytics/analytics-zoo/blob/master/apps/fraudDetection/Fraud%20Detction.ipynb

How to do the same in PySpark?

Body:
Use comprehensions:

result.select([
    format_number(result[c].cast('float'),2).alias(c) for c in result.columns
])


问:
Python how to calcualate average of individual list of a list
I have a list in a list with a lot of data:

```<code>data =  [ [4,25,1,6,3,1,6,...],[45,2,1,5,6,20,29],[491,5,195,239,194,09]
         ..[2,1,5,6,1,95] ]
</code>```

and what I've been trying to figure out how to do is calculate the mean of each individual list and turn it into a column of data looking like this:

```<code>List# average
1     (Mean value of the first list)
2     (Mean value of the second list)
....
15    (mean value of the 15th list)
</code>```

I've tried to put in to loop of iteration like this:

```<code>def average(data)
    for i in range(16):
        total = 0.0
        for x in data[i]:
            total = total + x
    return total / len(data[i])
</code>```

but it only calculate the mean of the first list so far. I also want to calculate the mean of the each of those individual list with the first piece of data sliced off but I don't know how to do that with list in a list.

Edit: changed as suggested but I still have only 1 result from the function, not the average from every sublist.

Body:
I have a list in a list with a lot of data:

data =  [ [4,25,1,6,3,1,6,...],[45,2,1,5,6,20,29],[491,5,195,239,194,09]
         ..[2,1,5,6,1,95] ]

and what I've been trying to figure out how to do is calculate the mean of each individual list and turn it into a column of data looking like this:

List# average
1     (Mean value of the first list)
2     (Mean value of the second list)
....
15    (mean value of the 15th list)

I've tried to put in to loop of iteration like this:

def average(data)
    for i in range(16):
        total = 0.0
        for x in data[i]:
            total = total + x
    return total / len(data[i])

but it only calculate the mean of the first list so far. I also want to calculate the mean of the each of those individual list with the first piece of data sliced off but I don't know how to do that with list in a list.

Edit: changed as suggested but I still have only 1 result from the function, not the average from every sublist.

Body:
You can use the builtin sum and len functions:

l = [ [4,25,1,6,3,1,6],[45,2,1,5,6,20,29],[491,5,195,239,194,9],[2,1,5,6,1,95]]
new_l = {'List {}'.format(i):sum(a)/float(len(a)) for i, a in enumerate(l, start=1)}

Output:

{'List 4': 18.333333333333332, 'List 2': 15.428571428571429, 'List 3': 188.83333333333334, 'List 1': 6.571428571428571}

Edit: to remove the first value in each list:

l = [ [4,25,1,6,3,1,6],[45,2,1,5,6,20,29],[491,5,195,239,194,9],[2,1,5,6,1,95]]
new_l = [i[1:] for i in l]

Output:

[[25, 1, 6, 3, 1, 6], [2, 1, 5, 6, 20, 29], [5, 195, 239, 194, 9], [1, 5, 6, 1, 95]]

Edit: Rounding the dictionary values:

l = [ [4,25,1,6,3,1,6],[45,2,1,5,6,20,29],[491,5,195,239,194,9],[2,1,5,6,1,95]]
new_l = {'List {}'.format(i):round(sum(a)/float(len(a)), 2) for i, a in enumerate(l, start=1)}

Output:

{'List 4': 18.33, 'List 2': 15.43, 'List 3': 188.83, 'List 1': 6.57}


问:
How to run blender on webserver?
I have a small script (model convertation), and this script works perfectly on local Win7 x64. I run it from command line

```<code>C:\SOFT\blender-2.79-windows64\blender.exe --debug-all --background --python myscript.py
</code>```

Script takes one file, then converts it to another format.
I want to run this script on webserver.
I mean, i want to put blender on webhosting, and execute script directly on webhosting.

Questions:

Which version of Blender i should use(Linux?)?

What will be my syntax on hosting?

答:
First you need to arrange some hosting, the cheaper host-managed shared web hosting options will rarely install non-web related software such as blender. This means you will need to look at having a linux server that you setup and manage yourself (or you pay someone to do it for you). The most common option these days is using the cloud. Most cloud providers offer pre-installed linux systems, so you just have to install the specific software you use, such as apache, php, blender. depending on which linux flavour you use it will be something like sudo apt-get install apache2 php blender

Once you have a server setup, get the path for blender -

```<code>% where blender
/usr/local/bin/blender
</code>```

You then use that path instead of the windows C:\SOFT\blender-2.79-windows64\blender.exe.

In your script you may need to adjust the use of paths in a similar way, os.path.join() is an easy way to join paths in a cross-platform way, the newer pathlib can also be used.

The linux equivelant of your example would be something like -

```<code>/usr/local/bin/blender --debug-all --background --python /home/joe/myscript.py
</code>```

Title: How to run blender on webserver?

Body:
I have a small script (model convertation), and this script works perfectly on local Win7 x64. I run it from command line

C:\SOFT\blender-2.79-windows64\blender.exe --debug-all --background --python myscript.py

Script takes one file, then converts it to another format.
I want to run this script on webserver.
I mean, i want to put blender on webhosting, and execute script directly on webhosting.

Questions:

Which version of Blender i should use(Linux?)?

What will be my syntax on hosting?

Body:
First you need to arrange some hosting, the cheaper host-managed shared web hosting options will rarely install non-web related software such as blender. This means you will need to look at having a linux server that you setup and manage yourself (or you pay someone to do it for you). The most common option these days is using the cloud. Most cloud providers offer pre-installed linux systems, so you just have to install the specific software you use, such as apache, php, blender. depending on which linux flavour you use it will be something like sudo apt-get install apache2 php blender

Once you have a server setup, get the path for blender -

% where blender
/usr/local/bin/blender

You then use that path instead of the windows C:\SOFT\blender-2.79-windows64\blender.exe.

In your script you may need to adjust the use of paths in a similar way, os.path.join() is an easy way to join paths in a cross-platform way, the newer pathlib can also be used.

The linux equivelant of your example would be something like -

/usr/local/bin/blender --debug-all --background --python /home/joe/myscript.py


问:
Got some issues in Java
I'm still new in Java and I have a problem here. I'm currently learning how to use methods with parameters. Here's the code:

```<code>import java.util.Scanner;
class TEST2 {
    public static void main(String [] args){
        Scanner input = new Scanner(System.in);
        tuna tunaObject = new tuna ();
        System.out.println("Enter your name here: ");
        String name = input.nextLine();
        tunaObject.simpleMessage(name);
    }
}
</code>```

And another one :

```<code>public class tuna {
    public void simpleMessage(String name){
    System.out.println("Hello" + name);
    }
}
</code>```

*The problem is, the result is turned out like this:

Enter your name here:

Eddy

HelloEddy

"HelloEddy" supposed to be "Hello Eddy"
*Why there's no space? What is the mistake I made in this code, can anyone help? Thank you.

答:
In java Strings are concat by '+' symbol or concat, to get space in your program you can do something like this:

```<code>  System.out.println("Hello "+name);
</code>```

or

```<code>  System.out.println("Hello ".concat(name));
</code>```

Title: Got some issues in Java

Body:
I'm still new in Java and I have a problem here. I'm currently learning how to use methods with parameters. Here's the code:

import java.util.Scanner;
class TEST2 {
    public static void main(String [] args){
        Scanner input = new Scanner(System.in);
        tuna tunaObject = new tuna ();
        System.out.println("Enter your name here: ");
        String name = input.nextLine();
        tunaObject.simpleMessage(name);
    }
}

And another one :

public class tuna {
    public void simpleMessage(String name){
    System.out.println("Hello" + name);
    }
}

*The problem is, the result is turned out like this:

Enter your name here:

Eddy

HelloEddy

"HelloEddy" supposed to be "Hello Eddy"
*Why there's no space? What is the mistake I made in this code, can anyone help? Thank you.

Body:
In java Strings are concat by '+' symbol or concat, to get space in your program you can do something like this:

  System.out.println("Hello "+name);

or

  System.out.println("Hello ".concat(name));


问:
PDO insert parameter key instead parameter value
Here I have a form:

```<code> <form action="includes/Payment.inc.php" method="get" class="px-4 py-4" >
    <div class="form-group">
        <div class="d-inline py-1"><h5>Payment Type</h5></div>
        <select class="bg-white text-dark" name="payment_type">
            <option value="Type">Type</option>
            <option value="Food">Food</option>
            <option value="House-Rent">House-Rent</option>
            <option value="Other">Other</option>
        </select>
        <h5 class="py-1">Amount of Money</h5>
        <div class="input-group">
            <span class="input-group-addon">$</span>
            <input type="text" class="form-control" name="amount" aria-label="Text input with checkbox">
            <span class="input-group-addon">JPY</span>
        </div>
        <h5 class="py-1">Detail</h5>
        <textarea placeholder="Enter The Detail in here" name="detail"></textarea><br>
        <label><h5 class="py-1">Date: </h5></label>
        <input type="date" name="date"><br>
        <button type="submit" name="submit" class="btn btn-primary m-4 border rounded">Submit</button>
    </div>
</form>
</code>```

When clicked simply put all the information into database with following PHP code:

```<code><?php
if (isset($_GET['submit'])) {
    include_once  'dbh.inc.php';
    $payment_type = $_GET['payment'];
    $amount_money = filter_input(INPUT_GET,'amount',FILTER_SANITIZE_NUMBER_INT);
    $detail = filter_input(INPUT_GET,'detail',FILTER_SANITIZE_STRING);
    $date = $_GET['date'];
    if (empty($amount_money)) {
        header('Location: ../Data.php?money_empty');
        exit();
    }
    else {
        $sql = "INSERT INTO payment(payment_type,amount,detail,payment_date)
            VALUES (':payment_type',':amount',':detail',':payment_date')";
        $result = $conn->prepare($sql);
        $result->bindParam(':payment_type',$payment_type,PDO::PARAM_STR);
        $result->bindParam(':amount',$amount_money,PDO::PARAM_INT);
        $result->bindParam(':detail',$detail,PDO::PARAM_STR);
        $result->bindParam(':payment_date',$date,PDO::PARAM_STR);
        $result->execute();

        header("Location: ../Data.php?payment_success");
        exit();
    }
}
</code>```

Then when I test the form, the execution is completed but when I checked the "payment" table, here's what i got:

payment_type(varchar) = ":payment_type"

amount(int) = 0

detail(varchar) = ":detail"

payment_date(date) = "0000-00-00".
What's wrong  with my code ??

答:
You are quoting your parameter markers, eg ':payment_type', which makes them look like plain strings to PDO, so those strings are what show up in the DB.  As the docs show, you should not quote them:

```<code>$sql = "INSERT INTO payment(payment_type,amount,detail,payment_date)
        VALUES (:payment_type, :amount, :detail, :payment_date)";
</code>```

Body:
Here I have a form:

 <form action="includes/Payment.inc.php" method="get" class="px-4 py-4" >

Payment Type

        <select class="bg-white text-dark" name="payment_type">
            <option value="Type">Type</option>
            <option value="Food">Food</option>
            <option value="House-Rent">House-Rent</option>
            <option value="Other">Other</option>
        </select>

Amount of Money

            $
            <input type="text" class="form-control" name="amount" aria-label="Text input with checkbox">
            JPY

Detail

        <textarea placeholder="Enter The Detail in here" name="detail"></textarea>

Date:

        <input type="date" name="date">

        <button type="submit" name="submit" class="btn btn-primary m-4 border rounded">Submit</button>

</form>

When clicked simply put all the information into database with following PHP code:

<?php
if (isset($_GET['submit'])) {
    include_once  'dbh.inc.php';
    $payment_type = $_GET['payment'];
    $amount_money = filter_input(INPUT_GET,'amount',FILTER_SANITIZE_NUMBER_INT);
    $detail = filter_input(INPUT_GET,'detail',FILTER_SANITIZE_STRING);
    $date = $_GET['date'];
    if (empty($amount_money)) {
        header('Location: ../Data.php?money_empty');
        exit();
    }
    else {
        $sql = "INSERT INTO payment(payment_type,amount,detail,payment_date)
            VALUES (':payment_type',':amount',':detail',':payment_date')";
        $result = $conn->prepare($sql);
        $result->bindParam(':payment_type',$payment_type,PDO::PARAM_STR);
        $result->bindParam(':amount',$amount_money,PDO::PARAM_INT);
        $result->bindParam(':detail',$detail,PDO::PARAM_STR);
        $result->bindParam(':payment_date',$date,PDO::PARAM_STR);
        $result->execute();

        header("Location: ../Data.php?payment_success");
        exit();
    }
}

Then when I test the form, the execution is completed but when I checked the "payment" table, here's what i got:

payment_type(varchar) = ":payment_type"

amount(int) = 0

detail(varchar) = ":detail"

payment_date(date) = "0000-00-00".
What's wrong  with my code ??

Body:
You are quoting your parameter markers, eg ':payment_type', which makes them look like plain strings to PDO, so those strings are what show up in the DB.  As the docs show, you should not quote them:

$sql = "INSERT INTO payment(payment_type,amount,detail,payment_date)
        VALUES (:payment_type, :amount, :detail, :payment_date)";


问:
How to tell TalkBack a custom view is being used as a button
I’m using a custom view as a button on Android, which doesn't inherit from android.widget.Button. What is the best way of telling the accessibility services it's a button?

Is it enough to just call setClickable(true) on the view?

With a standard Button, TalkBack appends the word "button" as a hint, but with a custom view it doesn’t do that. Should I be adding the word "button" as a hint somewhere?

On iOS, I’d add a button "trait" to the view, and VoiceOver annonces it as a button. Is there anything similar on Android?

答:
If you dig through the TalkBack project, in Role.java, you will see that the hint text "button" is applied in the following circumstances:

The element has a class of android.widget.Button

OR

The element has a class of android.widget.ImageView

The element isClickable()

HOWEVER, anything that isClickable() will have the hint text "Double tap to ...." applied to it. So, the answer is NO, you should not. "Button" means something very specific to TalkBack users, and it is best to allow the Android Operating System and TalkBack to work together to figure out what that is.

Would it be better if TalkBack just announced all Trivially clickable things as buttons, instead of putting that information in the delayed hint text: "Double tap to..." (... = Expand, activate, etc, depending on control) Yes, it probably would.

Would it be better if Android allowed you to say: "Yes this thing I've subclassed is a button", like iOS traits. Yes, it probably would.

In fact, I would argue that given the: "Double tap to ...." announcement, that the announcement of "button" in this scenario is additional information. "Button" means nothing more than the thing can be double tapped to be actioned. If "button" announcement only applied to "buttons" this wouldn't be the case, as "android.widget.Button" objects are styled certain ways (typically). But, since this is also applied to IMAGE_VIEWS, without being applied to other simple "clickable" views, its purpose is muddy, and ultimately useless and confusing.  AND NO, you should not attempt to rectify this. It is absolutely TalkBack's job to get this right, which it does... just in other ways.  Let me explain:

The announcement of button has essentially been deprecated, and replaced by the delayed announcement "double tap to ...". The "button" announcement was left in as legacy support for users that were accustomed to that announcement.

To summarize: ensure that "Double tap to ...." is announced AFTER your control. Though, just ensuring that your node has a click listener and "isClickable" should be enough for this. This delayed hint announcement is the important bit. The announcement of "button" is unimportant, legacy garbage leftover from unfortunate decisions made early on in the development of the TalkBack project. THAT, or it will be fixed to be applied to all clickable things (like custom controls) in a future release. Either way, adding the word "button" to your content description would be ill advised.


问:
(Beginner) How to call Outlook RESTful APIs in Outlook VSTO Add-In
I'm looking to develop an Outlook Add-In, in which I receive a meeting room request and propose another room based upon conditions relating number of participants and size of the other rooms. I'm attempting to do this using a VSTO Add-In in C#.

My problem comes in the algorithm to determine the list of rooms and which room is smaller. From research, I can see that Outlook incorporates a number of RESTful APIs (https://msdn.microsoft.com/en-us/office/office365/api/calendar-rest-operations). However, I'm running into roadblocks in terms of how to call the APIs and how to get their data.

Is this possible in a VSTO add-in? If so, how could I get and store a list of the meeting rooms in Outlook using the REST APIs? I know there are other types of add-ins but I'm unfamiliar with Javascript and thus I'd like to stay with C#.

答:
We recommend using the web add-in framework, instead of COM, for writing an Outlook add-in. The web add-in framework enables developers to:

Write once and have their add-in run across supported Outlook
clients enabling the add-in to reach millions of Outlook Desktop,
Outlook for Web, Outlook for Mac, and Outlook Mobile users.

Simplified deployment through the Office store, enabling users to acquire your add-in with a single click.

Access to user mailbox data via a rich REST based API set.

In addition to the benefits of the web add-in framework, Microsoft is not investing in new functionality on the COM platform. We understand COM add-ins may support different scenarios than the web add-in framework and thus are continually investing in the web add-in framework.

If you have any feedback or new functionality you would like to see available in the web add-in framework please let us know.

We track Outlook add-in feature requests on our user-voice page. Please add your request there.

[Outlook Add-ins Engineering Team]


问:
Run subscription only once
I need to run userProfiles$.subscribe(async res => { only once. But it works infinitely. Can you tell me how to avoid it?

This is the video of that issue:

.ts

```<code>async loginWithGoogle(): Promise<void> {
    try {
      const result = await this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
      const userId: string = result.additionalUserInfo.profile.id;
      const userProfile: AngularFirestoreDocument<UserProfile> = this.fireStore.doc(`userProfile/${userId}`);
      const userProfiles: AngularFirestoreCollection<UserProfile> = this.fireStore.collection('userProfile/', ref => ref.where('email', '==', result.additionalUserInfo.profile.email));
      const userProfiles$: Observable<UserProfile[]> = userProfiles.valueChanges();

      userProfiles$.subscribe(async res => { //problem is here
        if (res.length == 0) {
          await userProfile.set({
            id: userId,
            email: result.additionalUserInfo.profile.email,
            creationTime: moment().format(),
            lastSignInTime: moment().format()
          });
        } else {
          await userProfile.update({
            lastSignInTime: moment().format()
          });
        }
      });
    }
    catch (err) {
      console.log(err);
    }
  }
</code>```

I have tried to convert it to promise like below. But no difference. Maybe I did it wrong?

```<code> userProfiles$.map(async res => {
        if (res.length == 0) {
          await userProfile.set({
            id: userId, email: result.additionalUserInfo.profile.email,
            creationTime: moment().format(),
            lastSignInTime: moment().format()
          });
        }
      }).toPromise();
</code>```

Versions:

```<code> "typescript": "2.4.2"
 "rxjs": "5.5.2",
</code>```

答:
I have found a solution here using both mix of Angularfire2 and firebase native API.

I got this solution from Michael here.

Firestore native API

```<code>get
get() returns firebase.firestore.QuerySnapshot

Executes the query and returns the results as a QuerySnapshot.

Returns
non-null firebase.firestore.QuerySnapshot A promise that will be resolved with the results of the query.
</code>```

.ts

```<code> constructor() {
     this.db = firebase.firestore();
  }

   async loginWithGoogle(): Promise<string> {
        try {
          const response = await this.afAuth.auth.signInWithRedirect(new firebase.auth.GoogleAuthProvider());
          const result = await this.afAuth.auth.getRedirectResult();
          this.user = result.user;
          const userId: string = result.user.uid;
          const userProfile: AngularFirestoreDocument<UserProfile> = this.fireStore.doc(`userProfile/${userId}`);
          const res = await this.db.collection("userProfiles").where("email", "==", data).get();
          if (res.docs.length === 0) {
            await userProfile.set({
              id: userId,
              email: result.additionalUserInfo.profile.email,
              creationTime: moment().format(),
              lastSignInTime: moment().format()
            });
          } else {
            await userProfile.update({
              lastSignInTime: moment().format()
            });
          }
          return result.additionalUserInfo.profile.email;
        }
        catch (err) {
          console.log(err);
        }
      }
</code>```

Title: Run subscription only once

Body:
I need to run userProfiles$.subscribe(async res => { only once. But it works infinitely. Can you tell me how to avoid it?

This is the video of that issue:

.ts

async loginWithGoogle(): Promise<void> {
    try {
      const result = await this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
      const userId: string = result.additionalUserInfo.profile.id;
      const userProfile: AngularFirestoreDocument<UserProfile> = this.fireStore.doc(`userProfile/${userId}`);
      const userProfiles: AngularFirestoreCollection<UserProfile> = this.fireStore.collection('userProfile/', ref => ref.where('email', '==', result.additionalUserInfo.profile.email));
      const userProfiles$: Observable<UserProfile[]> = userProfiles.valueChanges();

      userProfiles$.subscribe(async res => { //problem is here
        if (res.length == 0) {
          await userProfile.set({
            id: userId,
            email: result.additionalUserInfo.profile.email,
            creationTime: moment().format(),
            lastSignInTime: moment().format()
          });
        } else {
          await userProfile.update({
            lastSignInTime: moment().format()
          });
        }
      });
    }
    catch (err) {
      console.log(err);
    }
  }

I have tried to convert it to promise like below. But no difference. Maybe I did it wrong?

 userProfiles$.map(async res => {
        if (res.length == 0) {
          await userProfile.set({
            id: userId, email: result.additionalUserInfo.profile.email,
            creationTime: moment().format(),
            lastSignInTime: moment().format()
          });
        }
      }).toPromise();

Versions:

 "typescript": "2.4.2"
 "rxjs": "5.5.2",

Body:
I have found a solution here using both mix of Angularfire2 and firebase native API.

I got this solution from Michael here.

Firestore native API

get
get() returns firebase.firestore.QuerySnapshot

Executes the query and returns the results as a QuerySnapshot.

Returns
non-null firebase.firestore.QuerySnapshot A promise that will be resolved with the results of the query.

.ts

 constructor() {
     this.db = firebase.firestore();
  }

   async loginWithGoogle(): Promise<string> {
        try {
          const response = await this.afAuth.auth.signInWithRedirect(new firebase.auth.GoogleAuthProvider());
          const result = await this.afAuth.auth.getRedirectResult();
          this.user = result.user;
          const userId: string = result.user.uid;
          const userProfile: AngularFirestoreDocument<UserProfile> = this.fireStore.doc(`userProfile/${userId}`);
          const res = await this.db.collection("userProfiles").where("email", "==", data).get();
          if (res.docs.length === 0) {
            await userProfile.set({
              id: userId,
              email: result.additionalUserInfo.profile.email,
              creationTime: moment().format(),
              lastSignInTime: moment().format()
            });
          } else {
            await userProfile.update({
              lastSignInTime: moment().format()
            });
          }
          return result.additionalUserInfo.profile.email;
        }
        catch (err) {
          console.log(err);
        }
      }


问:
Using radar/polar graphs to depict individual datapoints
This is following my previous post: How to measure the area of a polygon in ggplot2?

What I would like now to do is to use the resulting radar charts as data points in a totally separate scatterplot or maybe save the object and use it later on graphs to depict the shape of the actual data.

I have many files and they typically look like this. They range from 1 to many in col number and the fractions are always in descending format. ie #1 always contributes most in any given file.

```<code>myfile
01 0.31707317
02 0.12195122
03 0.09756098
04 0.07317073
05 0.07317073
06 0.07317073
07 0.07317073
08 0.07317073
09 0.04878049
10 0.04878049
</code>```

Here, I would like to plot a radar chart for each of these files individually and just get the shape with no grid around it. ggradar is the closest and the nicest I have found.

```<code>ggradar(as.matrix(t(radar)), group.point.size = 2, grid.line.width = 0, grid.max = 1.0, grid.mid = 0,
    grid.min = 0, axis.line.colour = "white", axis.label.size = 0, grid.label.size = 0,
    centre.y = 0, background.circle.colour = "white", group.colours = "black", group.line.width = 1)
</code>```

Now the problem starts when I want to use these shapes as data points.

@brian kindly commented and hinted as to how to approach this.

R::ggplot2::geom_points: how to swap points with pie charts?

Small ggplot2 plots placed on coordinates on a ggmap

Inspired by these comments, I can now save plots as one column along with the filename and keep adding the new files using the same pipeline.

```<code>  for (file in file_list){
#eliminate the empty files (they contain only the header)
if (file.size(file) > 420){
  # if the merged dataset does exist, append to it
  if (exists("dfradar")){
    radarfile <-read.table(file, header=TRUE, sep="\t")
    radarfile1 <- as.data.frame(as.numeric(radarfile[,3]))
    rownames(radarfile1) <- c(1:nrow(radarfile))
    dfradar1 <- ggradar(t(radarfile1), group.point.size = 1, grid.line.width = 0, grid.max = 1, grid.mid = 0,
                        grid.min = 0, axis.line.colour = "white", axis.label.size = 0, grid.label.size = 0,
                        centre.y = 0, background.circle.colour = "white", group.colours = "black", group.line.width = 0.5) +
                    theme(legend.position = "none")
    dfradar1 <- cbind(substring(file,11), dfradar1)
    dfradar <- rbind(dfradar, dfradar1)
  }
  # if the merged dataset doesn't exist, create it
  if (!exists("dfradar")){
    radarfile <- read.table(file, header=TRUE, sep="\t")
    radarfile1 <- as.data.frame(as.numeric(radarfile[,3]))
    rownames(radarfile1) <- c(1:nrow(radarfile))
    dfradar <- ggradar(t(radarfile1), group.point.size = 1, grid.line.width = 0, grid.max = 1, grid.mid = 0,
                        grid.min = 0, axis.line.colour = "white", axis.label.size = 0, grid.label.size = 0,
                        centre.y = 0, background.circle.colour = "white", group.colours = "black", group.line.width = 0.5) +
                theme(legend.position = "none")
    dfradar <- cbind(substring(file,11), dfradar)
    rm(radarfile)
    rm(radarfile1)
  }
} }
</code>```

Now when I want to save the grobs, I can't; I get:

"Error in mutate_impl(.data, dots) :    Evaluation error: attempt to
  apply non-function."

or:

"Error in plot_clone(plot) : attempt to apply non-function"

```<code># merge the df with another df containing all other
# variables that I wanna use in my scatterplot
dfradar_merge <- merge(dfradar, Cases, all=FALSE)
dfradar_merge <-  dfradar_merge %>% mutate(radargrobs = list(annotation_custom(ggplotGrob(radarplots)),
xmin = as.numeric(Gender), xmax = as.numeric(Gender)*1.2,
ymin = as.numeric(Age) , ymax = as.numeric(Age)*1.2)))
</code>```

I think if I can get this part straight and pass the variables as xmin and ymin, I should be able to do what I need...

Any ideas are really appreciated. It has been a headache for me.

答:
I came up with the following idea. I used the ggradar package to create a graphic. Then, I looked into the data frames staying behind the graphic with ggplot_build(). It seems that there are 13 lists behind the graphic. I needed to investigate which list is the right one containing polygon data. I found that the 6th list is the one you want to extract and save for your future use. Let me show you what I have done.

```<code>library(dplyr)
library(ggradar)
library(scales)

# I modified the code from https://github.com/ricardo-bion/ggradar to get a graphic.

mtcars %>%
mutate_all(rescale) %>%
mutate(group = rownames(mtcars)) %>%
slice(5:9) %>%
select(1:4) -> mtcars_radar

g <- ggradar(mtcars_radar)
</code>```

The code above generates the following graphic. There is something wrong with my computer or something else, and I do not see a complete graphic. But this is not an issue for this question.

Now, we want to get the data staying behind the graphic and look for the right data.

```<code>foo <- ggplot_build(g)$data

# This is the 6th list in foo.

 $ :'data.frame':   20 obs. of  8 variables:
  ..$ colour  : chr [1:20] "#FF5A5F" "#FF5A5F" "#FF5A5F" "#FF5A5F" ...
  ..$ x       : num [1:20] 0 0.72 -0.687 0 0 ...
  ..$ y       : num [1:20] 1.111 -0.416 -0.397 1.111 0.611 ...
  ..$ group   : atomic [1:20] 1 1 1 1 2 2 2 2 3 3 ...
  .. ..- attr(*, "n")= int 5
  ..$ PANEL   : Factor w/ 1 level "1": 1 1 1 1 1 1 1 1 1 1 ...
  ..$ size    : num [1:20] 1.5 1.5 1.5 1.5 1.5 1.5 1.5 1.5 1.5 1.5 ...
  ..$ linetype: num [1:20] 1 1 1 1 1 1 1 1 1 1 ...
  ..$ alpha   : logi [1:20] NA NA NA NA NA NA ...
</code>```

You want to extract this list as a data frame. The reason why I could spot this list is that I was paying attention to color information (e.g., FF5A5F).

```<code>mydf <- foo[[6]]

    colour          x          y group PANEL size linetype alpha
1  #FF5A5F  0.0000000  1.1111111     1     1  1.5        1    NA
2  #FF5A5F  0.7203077 -0.4158698     1     1  1.5        1    NA
3  #FF5A5F -0.6868360 -0.3965450     1     1  1.5        1    NA
4  #FF5A5F  0.0000000  1.1111111     1     1  1.5        1    NA
5  #FFB400  0.0000000  0.6111111     2     1  1.5        1    NA
6  #FFB400  0.4286803 -0.2474987     2     1  1.5        1    NA
7  #FFB400 -0.2584135 -0.1491951     2     1  1.5        1    NA
8  #FFB400  0.0000000  0.6111111     2     1  1.5        1    NA
9  #007A87  0.0000000  1.1111111     3     1  1.5        1    NA
10 #007A87  0.7203077 -0.4158698     3     1  1.5        1    NA
11 #007A87 -0.4726248 -0.2728700     3     1  1.5        1    NA
12 #007A87  0.0000000  1.1111111     3     1  1.5        1    NA
13 #8CE071  0.0000000  0.1111111     4     1  1.5        1    NA
14 #8CE071  0.2467912 -0.1424850     4     1  1.5        1    NA
15 #8CE071 -0.2278119 -0.1315273     4     1  1.5        1    NA
16 #8CE071  0.0000000  0.1111111     4     1  1.5        1    NA
17 #7B0051  0.0000000  0.1111111     5     1  1.5        1    NA
18 #7B0051  0.2595364 -0.1498434     5     1  1.5        1    NA
19 #7B0051 -0.1268266 -0.0732234     5     1  1.5        1    NA
20 #7B0051  0.0000000  0.1111111     5     1  1.5        1    NA
</code>```

Let's confirm if this data reproduces the five triangles in the ggradar graphic.

```<code>gg <- ggplot(data = mydf, aes(x = x, y = y, group = group, color = factor(group))) +
      geom_path(show.legend = FALSE) +
      theme_bw()
</code>```

In summary, you want to hack ggplot data to extract the data you want. This method allows you to save data for the "shape" that you want. I hope this is what you are after.

Body:
This is following my previous post: How to measure the area of a polygon in ggplot2?

What I would like now to do is to use the resulting radar charts as data points in a totally separate scatterplot or maybe save the object and use it later on graphs to depict the shape of the actual data.

I have many files and they typically look like this. They range from 1 to many in col number and the fractions are always in descending format. ie #1 always contributes most in any given file.

myfile
01 0.31707317
02 0.12195122
03 0.09756098
04 0.07317073
05 0.07317073
06 0.07317073
07 0.07317073
08 0.07317073
09 0.04878049
10 0.04878049

Here, I would like to plot a radar chart for each of these files individually and just get the shape with no grid around it. ggradar is the closest and the nicest I have found.

ggradar(as.matrix(t(radar)), group.point.size = 2, grid.line.width = 0, grid.max = 1.0, grid.mid = 0,
    grid.min = 0, axis.line.colour = "white", axis.label.size = 0, grid.label.size = 0,
    centre.y = 0, background.circle.colour = "white", group.colours = "black", group.line.width = 1)

Now the problem starts when I want to use these shapes as data points.

@brian kindly commented and hinted as to how to approach this.

R::ggplot2::geom_points: how to swap points with pie charts?

Small ggplot2 plots placed on coordinates on a ggmap

Inspired by these comments, I can now save plots as one column along with the filename and keep adding the new files using the same pipeline.

  for (file in file_list){
#eliminate the empty files (they contain only the header)
if (file.size(file) > 420){
  # if the merged dataset does exist, append to it
  if (exists("dfradar")){
    radarfile <-read.table(file, header=TRUE, sep="\t")
    radarfile1 <- as.data.frame(as.numeric(radarfile[,3]))
    rownames(radarfile1) <- c(1:nrow(radarfile))
    dfradar1 <- ggradar(t(radarfile1), group.point.size = 1, grid.line.width = 0, grid.max = 1, grid.mid = 0,
                        grid.min = 0, axis.line.colour = "white", axis.label.size = 0, grid.label.size = 0,
                        centre.y = 0, background.circle.colour = "white", group.colours = "black", group.line.width = 0.5) +
                    theme(legend.position = "none")
    dfradar1 <- cbind(substring(file,11), dfradar1)
    dfradar <- rbind(dfradar, dfradar1)
  }
  # if the merged dataset doesn't exist, create it
  if (!exists("dfradar")){
    radarfile <- read.table(file, header=TRUE, sep="\t")
    radarfile1 <- as.data.frame(as.numeric(radarfile[,3]))
    rownames(radarfile1) <- c(1:nrow(radarfile))
    dfradar <- ggradar(t(radarfile1), group.point.size = 1, grid.line.width = 0, grid.max = 1, grid.mid = 0,
                        grid.min = 0, axis.line.colour = "white", axis.label.size = 0, grid.label.size = 0,
                        centre.y = 0, background.circle.colour = "white", group.colours = "black", group.line.width = 0.5) +
                theme(legend.position = "none")
    dfradar <- cbind(substring(file,11), dfradar)
    rm(radarfile)
    rm(radarfile1)
  }
} }

Now when I want to save the grobs, I can't; I get:

"Error in mutate_impl(.data, dots) :    Evaluation error: attempt to
  apply non-function."

or:

"Error in plot_clone(plot) : attempt to apply non-function"

# merge the df with another df containing all other
# variables that I wanna use in my scatterplot
dfradar_merge <- merge(dfradar, Cases, all=FALSE)
dfradar_merge <-  dfradar_merge %>% mutate(radargrobs = list(annotation_custom(ggplotGrob(radarplots)),
xmin = as.numeric(Gender), xmax = as.numeric(Gender)*1.2,
ymin = as.numeric(Age) , ymax = as.numeric(Age)*1.2)))

I think if I can get this part straight and pass the variables as xmin and ymin, I should be able to do what I need...

Any ideas are really appreciated. It has been a headache for me.

Body:
I came up with the following idea. I used the ggradar package to create a graphic. Then, I looked into the data frames staying behind the graphic with ggplot_build(). It seems that there are 13 lists behind the graphic. I needed to investigate which list is the right one containing polygon data. I found that the 6th list is the one you want to extract and save for your future use. Let me show you what I have done.

library(dplyr)
library(ggradar)
library(scales)

# I modified the code from https://github.com/ricardo-bion/ggradar to get a graphic.

mtcars %>%
mutate_all(rescale) %>%
mutate(group = rownames(mtcars)) %>%
slice(5:9) %>%
select(1:4) -> mtcars_radar

g <- ggradar(mtcars_radar)

The code above generates the following graphic. There is something wrong with my computer or something else, and I do not see a complete graphic. But this is not an issue for this question.

Now, we want to get the data staying behind the graphic and look for the right data.

foo <- ggplot_build(g)$data

# This is the 6th list in foo.

 $ :'data.frame':   20 obs. of  8 variables:
  ..$ colour  : chr [1:20] "#FF5A5F" "#FF5A5F" "#FF5A5F" "#FF5A5F" ...
  ..$ x       : num [1:20] 0 0.72 -0.687 0 0 ...
  ..$ y       : num [1:20] 1.111 -0.416 -0.397 1.111 0.611 ...
  ..$ group   : atomic [1:20] 1 1 1 1 2 2 2 2 3 3 ...
  .. ..- attr(*, "n")= int 5
  ..$ PANEL   : Factor w/ 1 level "1": 1 1 1 1 1 1 1 1 1 1 ...
  ..$ size    : num [1:20] 1.5 1.5 1.5 1.5 1.5 1.5 1.5 1.5 1.5 1.5 ...
  ..$ linetype: num [1:20] 1 1 1 1 1 1 1 1 1 1 ...
  ..$ alpha   : logi [1:20] NA NA NA NA NA NA ...

You want to extract this list as a data frame. The reason why I could spot this list is that I was paying attention to color information (e.g., FF5A5F).

mydf <- foo[[6]]

    colour          x          y group PANEL size linetype alpha
1  #FF5A5F  0.0000000  1.1111111     1     1  1.5        1    NA
2  #FF5A5F  0.7203077 -0.4158698     1     1  1.5        1    NA
3  #FF5A5F -0.6868360 -0.3965450     1     1  1.5        1    NA
4  #FF5A5F  0.0000000  1.1111111     1     1  1.5        1    NA
5  #FFB400  0.0000000  0.6111111     2     1  1.5        1    NA
6  #FFB400  0.4286803 -0.2474987     2     1  1.5        1    NA
7  #FFB400 -0.2584135 -0.1491951     2     1  1.5        1    NA
8  #FFB400  0.0000000  0.6111111     2     1  1.5        1    NA
9  #007A87  0.0000000  1.1111111     3     1  1.5        1    NA
10 #007A87  0.7203077 -0.4158698     3     1  1.5        1    NA
11 #007A87 -0.4726248 -0.2728700     3     1  1.5        1    NA
12 #007A87  0.0000000  1.1111111     3     1  1.5        1    NA
13 #8CE071  0.0000000  0.1111111     4     1  1.5        1    NA
14 #8CE071  0.2467912 -0.1424850     4     1  1.5        1    NA
15 #8CE071 -0.2278119 -0.1315273     4     1  1.5        1    NA
16 #8CE071  0.0000000  0.1111111     4     1  1.5        1    NA
17 #7B0051  0.0000000  0.1111111     5     1  1.5        1    NA
18 #7B0051  0.2595364 -0.1498434     5     1  1.5        1    NA
19 #7B0051 -0.1268266 -0.0732234     5     1  1.5        1    NA
20 #7B0051  0.0000000  0.1111111     5     1  1.5        1    NA

Let's confirm if this data reproduces the five triangles in the ggradar graphic.

gg <- ggplot(data = mydf, aes(x = x, y = y, group = group, color = factor(group))) +
      geom_path(show.legend = FALSE) +
      theme_bw()

In summary, you want to hack ggplot data to extract the data you want. This method allows you to save data for the "shape" that you want. I hope this is what you are after.


问:
how to stop centered css dropdown menu from twitching (chrome only)
I have a css driven dropdown menu, and in Chrome when I hover over the last option the whole thing jumps to the left slightly. I assume it's because the dropdown menu is adding to the overall width of the main list even though it's styled to float. Is there any way to fix this? (it's not doing it in firefox interestingly)

I've noticed by using webdeveloper to outline elements that the last li appears to get wider when it's hovered, but none of the others do.

the applicable sourcecode is here:
http://jsfiddle.net/WsAEW/

答:
Here is a modified jsfiddle. I think the issue is fixed. Give it a try.

http://jsfiddle.net/WsAEW/5/

BTW, I only changed the following style. The 'float left' gets the elements to line up horizontally and the 'display: block' gets the top element to size to include the drop down menu.

```<code>#menu ul li {
    float: left;
    display: block;
    position: relative;
}
</code>```

Body:
Here is a modified jsfiddle. I think the issue is fixed. Give it a try.

http://jsfiddle.net/WsAEW/5/

BTW, I only changed the following style. The 'float left' gets the elements to line up horizontally and the 'display: block' gets the top element to size to include the drop down menu.

#menu ul li {
    float: left;
    display: block;
    position: relative;
}


答:
In your code, you use '' to eclosed the string part in insert parameters this not need with PDO. Use the following instead...

```<code><?php
if (isset($_GET['submit'])) {
include_once  'dbh.inc.php';
$payment_type = $_GET['payment'];
$amount_money = filter_input(INPUT_GET,'amount',FILTER_SANITIZE_NUMBER_INT);
$detail = filter_input(INPUT_GET,'detail',FILTER_SANITIZE_STRING);
$date = $_GET['date'];
if (empty($amount_money)) {
    header('Location: ../Data.php?money_empty');
    exit();
}
else {
    $sql = "INSERT INTO payment(payment_type,amount,detail,payment_date)
            VALUES (:payment_type,:amount,:detail,:payment_date)";
    $result = $conn->prepare($sql);
    $result->bindParam(':payment_type',$payment_type,PDO::PARAM_STR);
    $result->bindParam(':amount',$amount_money,PDO::PARAM_INT);
    $result->bindParam(':detail',$detail,PDO::PARAM_STR);
    $result->bindParam(':payment_date',$date,PDO::PARAM_STR);
    $result->execute();

    header("Location: ../Data.php?payment_success");
    exit();
}
}
</code>```

Title: PDO insert parameter key instead parameter value

Body:
In your code, you use '' to eclosed the string part in insert parameters this not need with PDO. Use the following instead...

<?php
if (isset($_GET['submit'])) {
include_once  'dbh.inc.php';
$payment_type = $_GET['payment'];
$amount_money = filter_input(INPUT_GET,'amount',FILTER_SANITIZE_NUMBER_INT);
$detail = filter_input(INPUT_GET,'detail',FILTER_SANITIZE_STRING);
$date = $_GET['date'];
if (empty($amount_money)) {
    header('Location: ../Data.php?money_empty');
    exit();
}
else {
    $sql = "INSERT INTO payment(payment_type,amount,detail,payment_date)
            VALUES (:payment_type,:amount,:detail,:payment_date)";
    $result = $conn->prepare($sql);
    $result->bindParam(':payment_type',$payment_type,PDO::PARAM_STR);
    $result->bindParam(':amount',$amount_money,PDO::PARAM_INT);
    $result->bindParam(':detail',$detail,PDO::PARAM_STR);
    $result->bindParam(':payment_date',$date,PDO::PARAM_STR);
    $result->execute();

    header("Location: ../Data.php?payment_success");
    exit();
}
}


问:
Passing an argument from HTML Form to PHP
Here is the HTML Form:

```<code><form action="imagematch.php" method="get">
Input Route Number: <input type="text" name="N" />
<input type="submit" />
</form>
</code>```

And here is the PHP file:

```<code><?php
if(isset($_GET[’N’]))
{
$N = $_GET[’N’];
}
?>
</code>```

Right now, it is reading the PHP file but it isn't reading the "N" argument correctly.

答:
As best we can tell, the issue seems to be the type of quotes you are using around the letter 'N'. This is very common when copying code from webpages. The angled/curly quotes used in webpages aren't interpreted the same as quotes expected and accepted in most programming languages. If you look at this article, you can see the difference. Note you want to do the opposite of what they recommend as they are making recommendations for publications and not code. You want to use straight quotes only in code.

As a separate recommendation, as mentioned by joeDaigle, you should use the GET method for when you are GETting (or reading) information, and use PUT when PUTting (or writing/updating) information. You can read this RFC for more details, but the main reason is that browsers treat GET and POST requests differently (note when you refresh a regular webpage, versus when you refresh a page after submitting a POST form and your browser prompts asking if you're sure).

Body:
Here is the HTML Form:

<form action="imagematch.php" method="get">
Input Route Number: <input type="text" name="N" />
<input type="submit" />
</form>

And here is the PHP file:

<?php
if(isset($_GET[’N’]))
{
$N = $_GET[’N’];
}
?>

Right now, it is reading the PHP file but it isn't reading the "N" argument correctly.


问:
Java- executor service shutdown at class level field
I have ExecutorService at class level.

There is a rest point 'url'. So, user will call this API 'n' number of times per day.

How to shutdown the executor service if I define it class level?

CLASS LEVEL: (not sure how to shutdown executor service)

```<code>public class A {
    private final ExecutorService executorService = Executors.newFixedThreadPool(3);

    @GET("/url")
    public void executeParallelTask() {
        try {
            executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                    }
            });
        }
        finally {
            executorService.shutdown();
            executorService.awaitTermination(12,TIMEUNIT.HOURS)
        }
</code>```

If I shutdown executor service in finally block, when next request comes at rest point, I’m getting Thread Pool size is empty and couldn’t handle the request.

I’m aware of method level like below.

```<code>public void executeParallelTask() {
    executorService.submit(new Runnable() {
        @Override
        public void run() {
        }
    });
    executorService.shutdown();
    executorService.awaitTermination(12, TimeUnit.HOURS)
</code>```

答:
You can do it in a shutdown hook.</p>

```<code>static {
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                if (executorService.isShutdown()) {
                    return;
                }
                log.debug("executorService shutting down...");
                executorService.shutdown();
                executorService.awaitTermination(10, TimeUnit.SECONDS);
                executorService.shutdownNow();
                log.debug("executorService shutdown");
            } catch (Throwable e) {
                log.error(e, e);
            }
        }
    });
}
</code>```

Body:
I have ExecutorService at class level.

There is a rest point 'url'. So, user will call this API 'n' number of times per day.

How to shutdown the executor service if I define it class level?

CLASS LEVEL: (not sure how to shutdown executor service)

public class A {
    private final ExecutorService executorService = Executors.newFixedThreadPool(3);

    @GET("/url")
    public void executeParallelTask() {
        try {
            executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                    }
            });
        }
        finally {
            executorService.shutdown();
            executorService.awaitTermination(12,TIMEUNIT.HOURS)
        }

If I shutdown executor service in finally block, when next request comes at rest point, I’m getting Thread Pool size is empty and couldn’t handle the request.

I’m aware of method level like below.

public void executeParallelTask() {
    executorService.submit(new Runnable() {
        @Override
        public void run() {
        }
    });
    executorService.shutdown();
    executorService.awaitTermination(12, TimeUnit.HOURS)

Body:
You can do it in a shutdown hook.

static {
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                if (executorService.isShutdown()) {
                    return;
                }
                log.debug("executorService shutting down...");
                executorService.shutdown();
                executorService.awaitTermination(10, TimeUnit.SECONDS);
                executorService.shutdownNow();
                log.debug("executorService shutdown");
            } catch (Throwable e) {
                log.error(e, e);
            }
        }
    });
}


问:
Show a div tag only if a person is logged in
I was trying to incorporate a functionality in my ASP.NET such that  a DIV tag which contains the Profile Navigation Menu  should only be visible if a person is logged in.
I know the condition on how to if the person is logged in or not but wanted to know the method to toggle the div tag on/off based on person's logged in status.

```<code>if(loggedin==yes)
{
//?
}
</code>```

Thanks

答:
If you div is having runat=server attribute. You can take the instance of it as follows:

```<code><div id="myDiv"></div>

HtmlGenericControl div=Page.FindControl("myDiv");
div.Visible=false;
</code>```

Body:
I was trying to incorporate a functionality in my ASP.NET such that  a DIV tag which contains the Profile Navigation Menu  should only be visible if a person is logged in.
I know the condition on how to if the person is logged in or not but wanted to know the method to toggle the div tag on/off based on person's logged in status.

if(loggedin==yes)
{
//?
}

Thanks

Body:
If you div is having runat=server attribute. You can take the instance of it as follows:

<div id="myDiv"></div>

HtmlGenericControl div=Page.FindControl("myDiv");
div.Visible=false;


问:
Getting a data from mongodb
```<code>router.get('/channels', isLoggedIn, function(req, res) {
    channel.find({}, function(err, channeldata) {
        var channelMap = {};
        console.log('channelMap:');
        console.log(channelMap);
        channeldata.forEach((chn)=> {
            console.log(chn)
            var arr = chn
        });

        if(err || channeldata === null){
                res.status(404).send({
                    message: 'Channel Not Found',
                    data: []
                })
        }
        else {
                res.status(200).json({
                    message: "channel success",
                    data: arr
                })
        }
        console.log(channelMap);
        // res.send(userMap);
    });
});
</code>```

here is how I implemented my GET and I am trying the get the chn which looks like

from my DB. Above is the result from console.log(chn)

I try to get this by doing

```<code>axios.get('/channels').then( (res) => {
            console.log(res);
        }).catch( (err) => {
            console.log(err);
        });
</code>```

in my frontend, but the app crashes and give me an error message saying

```<code>events.js:160
      throw er; // Unhandled 'error' event
      ^

ReferenceError: arr is not defined
</code>```

What did I do wrong?

答:
Your issue is in the lines

```<code>channeldata.forEach((chn)=> {
            console.log(chn)
            var arr = chn
        });
</code>```

You are defining arr in the for each loop, which means arr can only be used inside the loop.

if you swap arr for chn in the code

```<code>res.status(200).json({
                    message: "channel success",
                    data: arr
                })
</code>```

Then that should work

Title: Getting a data from mongodb

Body:
router.get('/channels', isLoggedIn, function(req, res) {
    channel.find({}, function(err, channeldata) {
        var channelMap = {};
        console.log('channelMap:');
        console.log(channelMap);
        channeldata.forEach((chn)=> {
            console.log(chn)
            var arr = chn
        });

        if(err || channeldata === null){
                res.status(404).send({
                    message: 'Channel Not Found',
                    data: []
                })
        }
        else {
                res.status(200).json({
                    message: "channel success",
                    data: arr
                })
        }
        console.log(channelMap);
        // res.send(userMap);
    });
});

here is how I implemented my GET and I am trying the get the chn which looks like

from my DB. Above is the result from console.log(chn)

I try to get this by doing

axios.get('/channels').then( (res) => {
            console.log(res);
        }).catch( (err) => {
            console.log(err);
        });

in my frontend, but the app crashes and give me an error message saying

events.js:160
      throw er; // Unhandled 'error' event
      ^

ReferenceError: arr is not defined

What did I do wrong?

Body:
Your issue is in the lines

channeldata.forEach((chn)=> {
            console.log(chn)
            var arr = chn
        });

You are defining arr in the for each loop, which means arr can only be used inside the loop.

if you swap arr for chn in the code

res.status(200).json({
                    message: "channel success",
                    data: arr
                })

Then that should work


问:
Scraping data from a website with Simple HTML Dom
I work to finish an API for a website (https://rushwallet.com/) for github.

I am using PHP and attempting to retrieve the wallet address from this URL: https://rushwallet.com/#n3GjsndjdCURphhsqJ4mQH7AjiXlGI.
Can anyone can help me?

My code so far:

```<code>$url = "https://rushwallet.com/#n3GjsndjdCURphhsqJ4mQH7AjiXlGI";

$open_url = str_get_html(file_get_contents($url));

$content_url = $open_url->find('span[id=btcBalance]', 0)->innertext;
die(var_dump($content_url));
</code>```

答:
You cannot read the correct content in this case. You are trying to access the non-rendered page content. Therefore, you always read the empty string. The content is loaded after the page is fully loaded. The page source is shown as:

```<code>฿<span id="btcBalance"></span>
</code>```

If you want to scrape the data in this case, you need to use rendering engine which is possible to render javascript. One possible engine is phantomJS, which is a headless browser and able to scrape the data after rendering.

Body:
I work to finish an API for a website (https://rushwallet.com/) for github.

I am using PHP and attempting to retrieve the wallet address from this URL: https://rushwallet.com/#n3GjsndjdCURphhsqJ4mQH7AjiXlGI.
Can anyone can help me?

My code so far:

$url = "https://rushwallet.com/#n3GjsndjdCURphhsqJ4mQH7AjiXlGI";

$open_url = str_get_html(file_get_contents($url));

$content_url = $open_url->find('span[id=btcBalance]', 0)->innertext;
die(var_dump($content_url));

Body:
You cannot read the correct content in this case. You are trying to access the non-rendered page content. Therefore, you always read the empty string. The content is loaded after the page is fully loaded. The page source is shown as:

฿<span id="btcBalance"></span>

If you want to scrape the data in this case, you need to use rendering engine which is possible to render javascript. One possible engine is phantomJS, which is a headless browser and able to scrape the data after rendering.


问:
How to build an incomplete binary tree from array representation
if the input is an array, where null means no node.

input:

[1, 2, 3, null, 5, null, 7]

Please assume that I have already checked the input.

For each array[i], its parents array[i / 2] will not be null (recursively, so root can not be null).

How to build a tree with such logic relation:

```<code>   1
 /    \
2      3
 \      \
  5      7
</code>```

each node should be represented by a TreeNode object:

```<code>class TreeNode {
public:
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
</code>```

I found a blog here where a complete tree was built

but if the tree is incomplete as mentioned above, how to do it neatly and efficiently ?

Test data:

[input array]

[-64,12,18,-4,-53,null,76,null,-51,null,null,-93,3,null,-31,47,null,3,53,-81,33,4,null,-51,-44,-60,11,null,null,null,null,78,null,-35,-64,26,-81,-31,27,60,74,null,null,8,-38,47,12,-24,null,-59,-49,-11,-51,67,null,null,null,null,null,null,null,-67,null,-37,-19,10,-55,72,null,null,null,-70,17,-4,null,null,null,null,null,null,null,3,80,44,-88,-91,null,48,-90,-30,null,null,90,-34,37,null,null,73,-38,-31,-85,-31,-96,null,null,-18,67,34,72,null,-17,-77,null,56,-65,-88,-53,null,null,null,-33,86,null,81,-42,null,null,98,-40,70,-26,24,null,null,null,null,92,72,-27,null,null,null,null,null,null,-67,null,null,null,null,null,null,null,-54,-66,-36,null,-72,null,null,43,null,null,null,-92,-1,-98,null,null,null,null,null,null,null,39,-84,null,null,null,null,null,null,null,null,null,null,null,null,null,-93,null,null,null,98]

答:
Just use recursion to traverse the nodes using the index of the array and use Integer to allow null.</p>

```<code>private TreeNode array2Tree(Integer[] data,TreeNode root, int index){

    if(index >= data.length){
      return root;
    }

    if(data[index] != null){
      TreeNode temp =  new TreeNode(data[index]);
      root = temp;
      root.left = array2Tree(data,root.left,2*index+1);
      root.right = array2Tree(data,root.right,2*index+2);
    }

    return root;
}
</code>```

Body:
if the input is an array, where null means no node.

input:

[1, 2, 3, null, 5, null, 7]

Please assume that I have already checked the input.

For each array[i], its parents array[i / 2] will not be null (recursively, so root can not be null).

How to build a tree with such logic relation:

   1
 /    \
2      3
 \      \
  5      7

each node should be represented by a TreeNode object:

class TreeNode {
public:
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

I found a blog here where a complete tree was built

but if the tree is incomplete as mentioned above, how to do it neatly and efficiently ?

Test data:

[input array]

[-64,12,18,-4,-53,null,76,null,-51,null,null,-93,3,null,-31,47,null,3,53,-81,33,4,null,-51,-44,-60,11,null,null,null,null,78,null,-35,-64,26,-81,-31,27,60,74,null,null,8,-38,47,12,-24,null,-59,-49,-11,-51,67,null,null,null,null,null,null,null,-67,null,-37,-19,10,-55,72,null,null,null,-70,17,-4,null,null,null,null,null,null,null,3,80,44,-88,-91,null,48,-90,-30,null,null,90,-34,37,null,null,73,-38,-31,-85,-31,-96,null,null,-18,67,34,72,null,-17,-77,null,56,-65,-88,-53,null,null,null,-33,86,null,81,-42,null,null,98,-40,70,-26,24,null,null,null,null,92,72,-27,null,null,null,null,null,null,-67,null,null,null,null,null,null,null,-54,-66,-36,null,-72,null,null,43,null,null,null,-92,-1,-98,null,null,null,null,null,null,null,39,-84,null,null,null,null,null,null,null,null,null,null,null,null,null,-93,null,null,null,98]

Body:
Just use recursion to traverse the nodes using the index of the array and use Integer to allow null.

private TreeNode array2Tree(Integer[] data,TreeNode root, int index){

    if(index >= data.length){
      return root;
    }

    if(data[index] != null){
      TreeNode temp =  new TreeNode(data[index]);
      root = temp;
      root.left = array2Tree(data,root.left,2*index+1);
      root.right = array2Tree(data,root.right,2*index+2);
    }

    return root;
}


问:
CAShapeLayer cutout in UIView
My goal is to create a pretty opaque background with a clear rounded rect inset

```<code>    let shape = CGRect(x: 0, y: 0, width: 200, height: 200)

    let maskLayer = CAShapeLayer()
    maskLayer.path = UIBezierPath(roundedRect: shape, cornerRadius: 16).cgPath
    maskLayer.fillColor = UIColor.clear.cgColor
    maskLayer.fillRule = kCAFillRuleEvenOdd

    let background = UIView()
    background.backgroundColor = UIColor.black.withAlphaComponent(0.8)
    view.addSubview(background)
    constrain(background) {
        $0.edges == $0.superview!.edges
    }

    background.layer.addSublayer(maskLayer)
//        background.layer.mask = maskLayer
</code>```

When I uncomment background.layer.mask = maskLayer, the view is totally clear. When I have it commented out, I see the semi-opaque background color but no mask cutout

Any idea what I'm doing wrong here? Thanks!

答:
Here is a playground that I think implements your intended effect (minus .edges and constrain - that appear to be your own extensions).

a) used a red background instead of black with alpha (just to make the effect stand out)

b) set maskLayer.backgroundColor instead of maskLayer.fillColor

Adding the maskLayer as another layer to uiview is superfluous (as indicated by @Ken) but seems to do no harm.

```<code>    import UIKit
    import PlaygroundSupport

    let bounds = CGRect(x: 0, y: 0, width: 400, height: 200)

    let uiview = UIView(frame: bounds)
    uiview.backgroundColor = UIColor.red.withAlphaComponent(0.8)

    PlaygroundPage.current.liveView = uiview

    let shape = CGRect(x: 100, y: 50, width: 200, height: 100)

    let maskLayer = CAShapeLayer()
    maskLayer.path = UIBezierPath(roundedRect: shape, cornerRadius: 16).cgPath
    maskLayer.backgroundColor = UIColor.clear.cgColor
    maskLayer.fillRule = kCAFillRuleEvenOdd
    uiview.layer.mask = maskLayer
</code>```

image of clear inset

On the other hand, if you intended a picture frame / colored-envelope-with-transparent-window effect like below, then see gist

image of picture frame

Title: CAShapeLayer cutout in UIView

Body:
My goal is to create a pretty opaque background with a clear rounded rect inset

    let shape = CGRect(x: 0, y: 0, width: 200, height: 200)

    let maskLayer = CAShapeLayer()
    maskLayer.path = UIBezierPath(roundedRect: shape, cornerRadius: 16).cgPath
    maskLayer.fillColor = UIColor.clear.cgColor
    maskLayer.fillRule = kCAFillRuleEvenOdd

    let background = UIView()
    background.backgroundColor = UIColor.black.withAlphaComponent(0.8)
    view.addSubview(background)
    constrain(background) {
        $0.edges == $0.superview!.edges
    }

    background.layer.addSublayer(maskLayer)
//        background.layer.mask = maskLayer

When I uncomment background.layer.mask = maskLayer, the view is totally clear. When I have it commented out, I see the semi-opaque background color but no mask cutout

Any idea what I'm doing wrong here? Thanks!

Body:
Here is a playground that I think implements your intended effect (minus .edges and constrain - that appear to be your own extensions).

a) used a red background instead of black with alpha (just to make the effect stand out)

b) set maskLayer.backgroundColor instead of maskLayer.fillColor

Adding the maskLayer as another layer to uiview is superfluous (as indicated by @Ken) but seems to do no harm.

    import UIKit
    import PlaygroundSupport

    let bounds = CGRect(x: 0, y: 0, width: 400, height: 200)

    let uiview = UIView(frame: bounds)
    uiview.backgroundColor = UIColor.red.withAlphaComponent(0.8)

    PlaygroundPage.current.liveView = uiview

    let shape = CGRect(x: 100, y: 50, width: 200, height: 100)

    let maskLayer = CAShapeLayer()
    maskLayer.path = UIBezierPath(roundedRect: shape, cornerRadius: 16).cgPath
    maskLayer.backgroundColor = UIColor.clear.cgColor
    maskLayer.fillRule = kCAFillRuleEvenOdd
    uiview.layer.mask = maskLayer

image of clear inset

On the other hand, if you intended a picture frame / colored-envelope-with-transparent-window effect like below, then see gist

image of picture frame


问:
Invalid JSON Text - SQL (Java JSON Object)

I'm putting in JSON into an SQL table (type: json) and it claims something is wrong - but I can't tell what it's pointing out directly.

Current json I'm trying to input:

```<code>'{"{\"type\":\"HUMAN\"}":"1.0"}'
</code>```

Yes, it is "json within json" but the code I'm writing is kind of dependent on it being that way. I'm not willing to really change that part.

Here's the error:

```<code>#3140 - Invalid JSON text: "Missing a colon after a name of object member." at position 5 in value for column 'mines.materials'.
</code>```

If you need code, I have it. I really need to know whats wrong with the JSON, if it requires a fundamental change to the code I can provide what I have.

答:
You should really try validating some basic assumptions.

'{"{\"type\":\"HUMAN\"}":"1.0"}' is not a valid JSON string as you can see below

"use strict";
(function () {
  try {
    JSON.parse('{"{\"type\":\"HUMAN\"}":"1.0"}');
  } catch (e) {
    console.error(e);
  }
}());```
</div>
</div>
</p>
<p>You are using attempting to use a JSON encoded string as a property key in another JSON encoded string but have not escaped it correctly.</p>
<p>You need to use <code>\\"</code> instead of <code>\"</code> to escape the quotes</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>"use strict";
(function() {
  try {
    console.log(JSON.parse('{"{\\"type\\":\\"HUMAN\\"}":"1.0"}'));
  } catch (e) {
    console.error(e);
  }
}());</code>```

Body:
I'm putting in JSON into an SQL table (type: json) and it claims something is wrong - but I can't tell what it's pointing out directly.

Current json I'm trying to input:

'{"{\"type\":\"HUMAN\"}":"1.0"}'

Yes, it is "json within json" but the code I'm writing is kind of dependent on it being that way. I'm not willing to really change that part.

Here's the error:

#3140 - Invalid JSON text: "Missing a colon after a name of object member." at position 5 in value for column 'mines.materials'.

If you need code, I have it. I really need to know whats wrong with the JSON, if it requires a fundamental change to the code I can provide what I have.

Body:
You should really try validating some basic assumptions.

'{"{\"type\":\"HUMAN\"}":"1.0"}' is not a valid JSON string as you can see below

"use strict";
(function () {
  try {
    JSON.parse('{"{\"type\":\"HUMAN\"}":"1.0"}');
  } catch (e) {
    console.error(e);
  }
}());

You are using attempting to use a JSON encoded string as a property key in another JSON encoded string but have not escaped it correctly.

You need to use \\" instead of \" to escape the quotes

"use strict";
(function() {
  try {
    console.log(JSON.parse('{"{\\"type\\":\\"HUMAN\\"}":"1.0"}'));
  } catch (e) {
    console.error(e);
  }
}());

ContentLicense: CC BY-SA 4.0


问:
pyspark split csv with spaces in string - jupyter notebook
I do not want to read a text file, I want to perform the action over an existing Dataframe

my DataFrame has only one column text, like a file, "tabSeparator".

It is a structured file, with 3 columns, separator is a tab.
In case the column has an embedded tab, it is enclosed in double quotes ("xxx xx")

Example:

```<code>-------------------------
col_0
-------------------------
c11   c12    c13
c21 c22 c23
"c 31" "c 32" c33
</code>```

I am using this regular expression:
I am using pyspark with Jupyter Notebook

```<code>myre = '([\\t ]?(\\".*?\\"|[^\\t ]+))'

df = textDF.withColumn("tmp", split( col("_c0"), myre))\
      .select(\
        col("tmp").getItem(0).alias("col_1"),\
        col("tmp").getItem(1).alias("col_2"),\
        col("tmp").getItem(2).alias("col_3")
      )
</code>```

Not sure if the problem is with the regular expression or my way to parse the file but I cannot create a new DataFrame with the 3 columns parsed, resulting on:

```<code>-------------------
|col_1|col_2|col_3|
------+-----+------
| c11 | c12 | c13 |
| c21 | c22 | c23 |
| c 31| c 32| c 33|
-------------------
</code>```

答:
This is nothing that csv reader cannot handle:

```<code>spark.read.option("delimiter", "\t").csv(path_to_file)
</code>```

In Spark 2.3 you can done on existing distribute data structure:

```<code>df = spark.createDataFrame([
    'c11\tc12\tc13', 'c21\tc22\tc23', '"c\t31"\t"c\t32"\t"c\t33"'
], "string").toDF("col_0")

spark.read.option('delimiter', '\t').csv(df.rdd.map(lambda x: x.col_0)).show()

# +----+----+----+
# | _c0| _c1| _c2|
# +----+----+----+
# | c11| c12| c13|
# | c21| c22| c23|
# |c    31|c    32|c    33|
# +----+----+----+
</code>```

UDF with csv might work in 2.2 with Python 3 but it will be slow:

```<code>from pyspark.sql.functions import udf
import csv

@udf("struct<c0:string,c1:string,c2:string>")
def csv_(s):
    try:
        return next(csv.reader([s], delimiter="\t"))
    except: pass

df.select(csv_("col_0").alias("tmp")).select("tmp.*").show()

# +----+----+----+
# |  c0|  c1|  c2|
# +----+----+----+
# | c11| c12| c13|
# | c21| c22| c23|
# |c    31|c    32|c    33|
# +----+----+----+
</code>```

Body:
I do not want to read a text file, I want to perform the action over an existing Dataframe

my DataFrame has only one column text, like a file, "tabSeparator".

It is a structured file, with 3 columns, separator is a tab.
In case the column has an embedded tab, it is enclosed in double quotes ("xxx xx")

Example:

-------------------------
col_0
-------------------------
c11   c12    c13
c21 c22 c23
"c 31" "c 32" c33

I am using this regular expression:
I am using pyspark with Jupyter Notebook

myre = '([\\t ]?(\\".*?\\"|[^\\t ]+))'

df = textDF.withColumn("tmp", split( col("_c0"), myre))\
      .select(\
        col("tmp").getItem(0).alias("col_1"),\
        col("tmp").getItem(1).alias("col_2"),\
        col("tmp").getItem(2).alias("col_3")
      )

Not sure if the problem is with the regular expression or my way to parse the file but I cannot create a new DataFrame with the 3 columns parsed, resulting on:

-------------------
|col_1|col_2|col_3|
------+-----+------
| c11 | c12 | c13 |
| c21 | c22 | c23 |
| c 31| c 32| c 33|
-------------------

Body:
This is nothing that csv reader cannot handle:

spark.read.option("delimiter", "\t").csv(path_to_file)

In Spark 2.3 you can done on existing distribute data structure:

df = spark.createDataFrame([
    'c11\tc12\tc13', 'c21\tc22\tc23', '"c\t31"\t"c\t32"\t"c\t33"'
], "string").toDF("col_0")

spark.read.option('delimiter', '\t').csv(df.rdd.map(lambda x: x.col_0)).show()

# +----+----+----+
# | _c0| _c1| _c2|
# +----+----+----+
# | c11| c12| c13|
# | c21| c22| c23|
# |c    31|c    32|c    33|
# +----+----+----+

UDF with csv might work in 2.2 with Python 3 but it will be slow:

from pyspark.sql.functions import udf
import csv

@udf("struct<c0:string,c1:string,c2:string>")
def csv_(s):
    try:
        return next(csv.reader([s], delimiter="\t"))
    except: pass

df.select(csv_("col_0").alias("tmp")).select("tmp.*").show()

# +----+----+----+
# |  c0|  c1|  c2|
# +----+----+----+
# | c11| c12| c13|
# | c21| c22| c23|
# |c    31|c    32|c    33|
# +----+----+----+


问:
How to suppress fputs, fsockopen etc warnings without disabling error reporting?
I use fsockopen, fgets and fputs to implement communication protocol with other machine. NetBeans give warning to all '@' before fsockopen, fputs, fgets etc. The solution works but without '@' after disconnection of remote device there are warnings (not errors).

I don't want to use error_reporting because it is not more kosher solution. Additionally more code, longer execution time...

Is there any better solution for this?

BTW. the warnings occurs if the destination machine will drop connection. It is possible if device is overload.

```<code>$answer=@fgets($socket, $negotiatedMaxLength);
</code>```

BTW. The solution should work without ini_set - blocked on server and without error_reporting().

答:
One way instead of @ which is obvious way to do it, is to use set_error_handler

https://www.w3schools.com/php/func_error_set_error_handler.asp

This lets you pipe the errors into the ErrorException class and then you have exceptions instead of errors. That's allows you to use try/catch blocks for the errors.

```<code>set_error_handler(function($severity, $message, $file = 'Unknown', $line = 'Unknown'){
     //typically I set a constant for PHP_ERRORS for the exception code.
     if (error_reporting() != -1 && !(error_reporting() & $severity)) {
         //we'll let this error go to the next error handler
         return; //return null
     }else{
          //convert the error into an exception
         throw new ErrorExcption($message, 0, $severity, $file, $line );
         //we don't have to return anything because the exception throwing kicks us out of the error handler.
     }
 });

 try{
     $answer=fgets($socket, $negotiatedMaxLength);
 }catch(ErrorException $e ){

 }
</code>```

Note the & single ampersand is intentional for checking severity level -vs- error reporting level you do bitwise And

Also the $file and $line are optional, so we set a default for them.

Body:
I use fsockopen, fgets and fputs to implement communication protocol with other machine. NetBeans give warning to all '@' before fsockopen, fputs, fgets etc. The solution works but without '@' after disconnection of remote device there are warnings (not errors).

I don't want to use error_reporting because it is not more kosher solution. Additionally more code, longer execution time...

Is there any better solution for this?

BTW. the warnings occurs if the destination machine will drop connection. It is possible if device is overload.

$answer=@fgets($socket, $negotiatedMaxLength);

BTW. The solution should work without ini_set - blocked on server and without error_reporting().

Body:
One way instead of @ which is obvious way to do it, is to use set_error_handler

https://www.w3schools.com/php/func_error_set_error_handler.asp

This lets you pipe the errors into the ErrorException class and then you have exceptions instead of errors. That's allows you to use try/catch blocks for the errors.

set_error_handler(function($severity, $message, $file = 'Unknown', $line = 'Unknown'){
     //typically I set a constant for PHP_ERRORS for the exception code.
     if (error_reporting() != -1 && !(error_reporting() & $severity)) {
         //we'll let this error go to the next error handler
         return; //return null
     }else{
          //convert the error into an exception
         throw new ErrorExcption($message, 0, $severity, $file, $line );
         //we don't have to return anything because the exception throwing kicks us out of the error handler.
     }
 });

 try{
     $answer=fgets($socket, $negotiatedMaxLength);
 }catch(ErrorException $e ){

 }

Note the & single ampersand is intentional for checking severity level -vs- error reporting level you do bitwise And

Also the $file and $line are optional, so we set a default for them.


问:
Django queryset attach or annotate related object field
It is needed to attach to queryset results related object field.

Models:

```<code>class User(models.Model):
    name = models.CharField(max_length=50)
    friends = models.ManyToManyField('self', through='Membership',
        blank=True, null=True, symmetrical=False)

class Membership(models.Model):
    status = models.CharField(choices=SOME_CHOICES, max_length=50)
    from_user = models.ForeignKey(User, related_name="member_from")
    to_user = models.ForeignKey(User, related_name="member_to")
</code>```

I can do this:

```<code>>>> User.objects.all().values('name', 'member_from__status')
[{'member_from__status': u'accepted', 'name': 'Ann'}, {'member_from__status': u'thinking', 'name': 'John'}]
</code>```

'member_from__status' contains information, that i need. But together with it, i need a model instance also.

What i want is:

```<code>>>> users_with_status = User.objects.all().do_something('member_from__status')
>>> users_with_status
[<User 1>, <User 2>]

>>> users_with_status[0] # <-- this is an object, so i can access to all its methods
</code>```

Every instance in queryset has a 'member_from__status' field with corresponding value:

```<code>>>> users_with_status[0].member_from__status
u'accepted'
</code>```

How this could be achieved?

答:
You can use annotate and F

```<code>>>> from django.db.models import F
>>> users = User.objects.all().annotate(member_from__status=F('member_from__status'))
>>> users[0].member_from__status
'accepted'
</code>```

Tested with Django versions 1.11 and 2.2

In answer to comments

Here I guess we are rather interested by member_to__status than member_from__status (we want the user being requested to accept the friendship, not the other way around)

Here's the content of my membership table:

```<code>status   |  from|   to
---------+------+-----
accepted |     1|    2
accepted |     2|    3
 refused |     3|    1
</code>```

Since "it's not possible to have a symmetrical, recursive ManyToManyField" (e.g. user 1 accepted user 2 so user 1 is now in user 2's friend list but user 2 is also in user 1's friends), this is how I would retrieve all actual friends:

```<code>>>> for user in User.objects.all():
...     friends = user.friends.filter(member_to__status='accepted')
...     print(str(user.id) + ': ' + ','.join([str(friend.id) for friend in friends]))
1: 2
2: 3
3:
</code>```

If you want to have <User 1> in <User 2>'s friends, I'd suggest to add another Membership when the friendship from 1 to 2 has been accepted.

Here we assume that a Membership can only be accepted once, so it could be a good idea to add the unique-together option. Nonetheless, if we have several Membership with same from_user, this is what happens:

```<code>>>> # <Insert several Membership from one to another User>
>>> Membership.objects.filter(from_user__id=1, to_user__id=2).count()
3
>>> users = User.objects.annotate(member_from__id=F('member_from__id'))
>>> print('User Membership')
... for user in users:
...    print("%4d %10d" % (user.id, user.member_from__id))
User Membership
   1          1
   2          2
   1          3  # User 1 again
   1          4  # User 1 again
   3          None
</code>```

Body:
It is needed to attach to queryset results related object field.

Models:

class User(models.Model):
    name = models.CharField(max_length=50)
    friends = models.ManyToManyField('self', through='Membership',
        blank=True, null=True, symmetrical=False)

class Membership(models.Model):
    status = models.CharField(choices=SOME_CHOICES, max_length=50)
    from_user = models.ForeignKey(User, related_name="member_from")
    to_user = models.ForeignKey(User, related_name="member_to")

I can do this:

>>> User.objects.all().values('name', 'member_from__status')
[{'member_from__status': u'accepted', 'name': 'Ann'}, {'member_from__status': u'thinking', 'name': 'John'}]

'member_from__status' contains information, that i need. But together with it, i need a model instance also.

What i want is:

>>> users_with_status = User.objects.all().do_something('member_from__status')
>>> users_with_status
[<User 1>, <User 2>]

>>> users_with_status[0] # <-- this is an object, so i can access to all its methods

Every instance in queryset has a 'member_from__status' field with corresponding value:

>>> users_with_status[0].member_from__status
u'accepted'

How this could be achieved?

Body:
You can use annotate and F

>>> from django.db.models import F
>>> users = User.objects.all().annotate(member_from__status=F('member_from__status'))
>>> users[0].member_from__status
'accepted'

Tested with Django versions 1.11 and 2.2

In answer to comments

Here I guess we are rather interested by member_to__status than member_from__status (we want the user being requested to accept the friendship, not the other way around)

Here's the content of my membership table:

status   |  from|   to
---------+------+-----
accepted |     1|    2
accepted |     2|    3
 refused |     3|    1

Since "it's not possible to have a symmetrical, recursive ManyToManyField" (e.g. user 1 accepted user 2 so user 1 is now in user 2's friend list but user 2 is also in user 1's friends), this is how I would retrieve all actual friends:

>>> for user in User.objects.all():
...     friends = user.friends.filter(member_to__status='accepted')
...     print(str(user.id) + ': ' + ','.join([str(friend.id) for friend in friends]))
1: 2
2: 3
3:

If you want to have <User 1> in <User 2>'s friends, I'd suggest to add another Membership when the friendship from 1 to 2 has been accepted.

Here we assume that a Membership can only be accepted once, so it could be a good idea to add the unique-together option. Nonetheless, if we have several Membership with same from_user, this is what happens:

>>> # <Insert several Membership from one to another User>
>>> Membership.objects.filter(from_user__id=1, to_user__id=2).count()
3
>>> users = User.objects.annotate(member_from__id=F('member_from__id'))
>>> print('User Membership')
... for user in users:
...    print("%4d %10d" % (user.id, user.member_from__id))
User Membership
   1          1
   2          2
   1          3  # User 1 again
   1          4  # User 1 again
   3          None