问:
Debugging JavaScript with Flask and PyCharm
I just installed the professional version of PyCharm for its Flask features, but I'm having a lot of issues getting anything JavaScript related working.

Firstly, is there any way of getting the browser to open when you run the flask project? There doesn't seem to be a Flask run configuration, which means you have to use the default Python configuration, and that doesn't have the option to run a browser. I tried making a JavaScript Debug project that runs the server as a Before Launch command, but it still doesn't open the browser (either Chrome or Firefox)

Secondly, how do I get PyCharm to hit the JavaScript breakpoints? Even if I manually browse to the flask server (http://localhost:5555/), Intellij doesn't hit breakpoints in my JavaScript, even though the JetBrains plugin is installed (again, in both Firefox and Chrome). I suspect this may be related to the fact that PyCharm doesn't open the browser, which is why I mentioned that as my first point.

Can anyone with experience in PyCharm or IntelliJ help me out?

答:
Just solved this problem.

You need some setup steps.

My prerequisites:

PyCharm on my local laptop

I'm developing on remote virtual machine (droplet DO, Ubuntu)

Setup you web-server. It should be Apache, nginx whatever.

Setup you web-app. You web-app should be runned on web-server.

Setup your debug configuration:

a. Run->Edit configuration

b. Add->JavaScript debug

c. Specify you URL as real url from web-browser like:
http://YOUR_IP:YOUR_PORT/directory/category

d. Specify File/Directory of HTML template and remote URL where your template located.

e. Debug it.

f. Profit ! :)

P.S. So lovely evaluate JavaScript variables from familiar PyCharm tool :)

P.S2: Almost forgot: Need install Chrome extension: https://www.jetbrains.com/help/pycharm/2016.3/debugging-javascript.html#d615717e345


来源: stackexchange

问:
how to implement Multi-Tenant functionality in asp.net-core
I have an Asp.net Core application I want to be able to allow multiple/ different Tenant(Client)to access the same application but using different url's. I have common database for all tenant(client).
So It is the main part I want to host my application in a domain say... www.myapplication.com then allow different Tenant(client) to access the same application using

1.www.TenantOne.myapplication.com

2.www.TenanatTwo.myapplication.com.

3.www.{TENANCY_NAME}.myapplication.com

I can't find any info on how to do this and I'm stuck.
How to do it? Please provide the code. Thanks.

答:
Sorry,you have to get something to start with and then come back for the people to help you with.

I would say that this is all of a domain based wild card mapping and change in your authentication logic to get the tenant id from the URL. Once you identified the tenant, you just login and then take it forward. Like you might be having a database with the tenant details like

```<code>tenant1 | tenant1.company.com | guid-ofthe-tenant | etc...
</code>```

Once you get the URL, you lookup in the above table and get the tenant code and then you choose the login mode and then proceed.

In case you have tried something yet, we would be happy to point you if it does not work yet.

ContentLicense: CC BY-SA 3.0

Body:
Sorry,you have to get something to start with and then come back for the people to help you with.

I would say that this is all of a domain based wild card mapping and change in your authentication logic to get the tenant id from the URL. Once you identified the tenant, you just login and then take it forward. Like you might be having a database with the tenant details like

tenant1 | tenant1.company.com | guid-ofthe-tenant | etc...

Once you get the URL, you lookup in the above table and get the tenant code and then you choose the login mode and then proceed.

In case you have tried something yet, we would be happy to point you if it does not work yet.


问:
Using JQuery to hide and show text
I want to use JQuery to hide text when web page is launched and when you click on an item it will show the hidden text.

When I load the page it shows the text in h2 and the text in h3 and hides the text in ptdeats as expected. When I click on the text containing "Jason O'Reilly", it doesn't show the text "Hi there, my name is Jay......".

The classes trainers ptpics, pt, center are configured in css.

The jquery is also configured to highlight h3 and also when h3 is click it shows the text and when you click on h3 it hides it again.

This is what I have configured in html:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <link href="style.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="trainersptjavascript.js"></script>
</head>
<body>
    <div class="trainers">
            <h2 class="center">Choose your Personal Trainer</h2>
            <div class="ptpics center">
                <h3 class="pt center">Jason O'Reilly</h3>
                <p class="center"><img src="images/ptjay.jpg" alt="Westside Fitness PT Jason" width="320" height="350"></p>
                <p class="ptdeats">Hi there , my name is Jay I am a personal trainer.</p>
            </div>
            <div class="ptpics center">
                <h3 class="pt center">Jean Meehan</h3>
                <p class="center"><img src="images/ptjean.jpg" alt="Westside Fitness PT Jean" width="320" height="350"></p>
                <p class="ptdeats">I am a qualified Level 4 Personal Trainer.</p>
            </div>
            <div class="ptpics center">
                <h3 class="pt center">Aoife McIntyre</h3>
                <p class="center"><img src="images/ptaoife.jpg" alt="Westside Fitness PT Aoifendrew" width="320" height="350"></p>
                <p class="ptdeats">I am Registered Nurse with a Personal Training Qualification.</p>
            </div>
    </div>
</body>
</html>
</code>```

This is the css configuration

```<code>.trainers
    {
    width: 80%;
    background-color: #36454F;
    color: #FFFFFF;
    text-align: justify;
    height: auto;
    margin-left: 10%;
    margin-left: 10%;
    padding-left: 6px;
    padding-right: 6px;
    float: left;
    }

.pt
    {
    width: 100%;
    cursor: pointer;
    color: #FFFFFF;
    padding-left: 6px;
    padding-right: 6px;
    float: left;
    }

.ptpics
    {
    width: 33%;
    background-color: #36454F;
    color: #FFFFFF;
    border: 1px;
    border-color:#009900;
    text-align: justify;
    height: auto;
    float: left;
    padding-left: 6px;
    padding-right: 6px;
    }
</code>```

JQuery configuration:

```<code>$(document).ready(function()
{
$(".me").hide();
$(".pt").click(function(){
$(".me").show();
});
});
</code>```

答:
It might be a problem with which element the event is triggering on. try:

```<code>$(".ptpic").click(function(){
$(".me").show();
});
</code>```

If that works, then you might not be clicking in the right spot.

Title: Using JQuery to hide and show text

Body:
I want to use JQuery to hide text when web page is launched and when you click on an item it will show the hidden text.

When I load the page it shows the text in h2 and the text in h3 and hides the text in ptdeats as expected. When I click on the text containing "Jason O'Reilly", it doesn't show the text "Hi there, my name is Jay......".

The classes trainers ptpics, pt, center are configured in css.

The jquery is also configured to highlight h3 and also when h3 is click it shows the text and when you click on h3 it hides it again.

This is what I have configured in html:

<!DOCTYPE html>

    <link href="style.css" rel="stylesheet">

Choose your Personal Trainer

Jason O'Reilly

Hi there , my name is Jay I am a personal trainer.

Jean Meehan

I am a qualified Level 4 Personal Trainer.

Aoife McIntyre

I am Registered Nurse with a Personal Training Qualification.

This is the css configuration

.trainers
    {
    width: 80%;
    background-color: #36454F;
    color: #FFFFFF;
    text-align: justify;
    height: auto;
    margin-left: 10%;
    margin-left: 10%;
    padding-left: 6px;
    padding-right: 6px;
    float: left;
    }

.pt
    {
    width: 100%;
    cursor: pointer;
    color: #FFFFFF;
    padding-left: 6px;
    padding-right: 6px;
    float: left;
    }

.ptpics
    {
    width: 33%;
    background-color: #36454F;
    color: #FFFFFF;
    border: 1px;
    border-color:#009900;
    text-align: justify;
    height: auto;
    float: left;
    padding-left: 6px;
    padding-right: 6px;
    }

JQuery configuration:

$(document).ready(function()
{
$(".me").hide();
$(".pt").click(function(){
$(".me").show();
});
});

Body:
It might be a problem with which element the event is triggering on. try:

$(".ptpic").click(function(){
$(".me").show();
});

If that works, then you might not be clicking in the right spot.


问:
Handling XML response with Javascript
I'm making a request to an API for some information. I need to send some information in order to get the required information back. The response is in XML format. When I make the request I get the following error

Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.

If a GET request can't have a body how do I send the required information? Basically how do I get this to work?

Here is my code.

```<code>getResponse = () => {

  const url = 'http://api.pixelz.com/REST.svc/Templates/';

  // The data we are going to send in our request

  let data = JSON.stringify({
    "contactEmail": "myemail@gmail.com",
    "contactAPIkey": "MY-API-KEY"
  })

  // The parameters we are gonna pass to the fetch function

  let fetchData = {
    method: 'GET',
    body: data,
    headers: new Headers()
  }

  fetch(url, fetchData)
    .then(function(response) {
      // Handle response you get from the server
      response.text()
      .then(data => console.log(data))
  });
}
</code>```

答:
Indeed GET requests can't have a body, meaning you don't send data while you are getting.  There can be two things going on here.

That specific endpoint is supposed to use another method like POST

The data you want to send actually needs to be passed as querystring parameter http://api.pixelz.com/REST.svc/Templates/?contactAPIkey=....&contactEmail=...

Title: Handling XML response with Javascript

Body:
I'm making a request to an API for some information. I need to send some information in order to get the required information back. The response is in XML format. When I make the request I get the following error

Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.

If a GET request can't have a body how do I send the required information? Basically how do I get this to work?

Here is my code.

getResponse = () => {

  const url = 'http://api.pixelz.com/REST.svc/Templates/';

  // The data we are going to send in our request

  let data = JSON.stringify({
    "contactEmail": "myemail@gmail.com",
    "contactAPIkey": "MY-API-KEY"
  })

  // The parameters we are gonna pass to the fetch function

  let fetchData = {
    method: 'GET',
    body: data,
    headers: new Headers()
  }

  fetch(url, fetchData)
    .then(function(response) {
      // Handle response you get from the server
      response.text()
      .then(data => console.log(data))
  });
}


问:
Tensorflow: How to switch channels of a tensor from RGB to BGR?
Is there a quick way to convert tensors which encode an image from RGB to BGR?

In python that would be something like:

```<code>image = image[:, :, [2,1,0]]
</code>```

答:
Assuming the channel is the last dimension.</p>

```<code>channels = tf.unstack (image, axis=-1)
image    = tf.stack   ([channels[2], channels[1], channels[0]], axis=-1)
</code>```

Body:
Is there a quick way to convert tensors which encode an image from RGB to BGR?

In python that would be something like:

image = image[:, :, [2,1,0]]

Body:
Assuming the channel is the last dimension.

channels = tf.unstack (image, axis=-1)
image    = tf.stack   ([channels[2], channels[1], channels[0]], axis=-1)


问:
Create a list based on nested For loops
Assume that I am using a client computer that will not allow for pip or pandas and must use Python 2.7. Binaries and converting into an exe is not allowed. I am reading in a CSV with column headers as names with numpy.

In my dataset, I am attempting to generate a list of orders that apply to unique combinations of Facility, Destination, Program #, and other factors, where p is the read csv dataset.

CSV starting out

What it would look like if I did this in Excel. The values in the Order field are what I'd like to have as a list in a variable called my_orders.

My current code looks like:

```<code>progs = np.unique(p['Program'])
facil = np.unique(p['Facility'])
dest = np.unique(p['Destination'])
reqs = np.unique(p['Requested'])
prods = np.unique(p['Produced'])
tier1 = np.unique(p['Tier1'])
tier2 = np.unique(p['Tier2'])
</code>```

Which is followed by the following method originally written with pandas and Python3 in mind until discovering that only 2.7 and numpy were available:

```<code>for a in range(len(progs)):
    print("on Program ",a)
    ProgChild = {"name":progs[a], 'children':[]}
    for r in range(len(reqs)):
        reqChild = {"name":reqs[r], 'children':[]}
        for s in range(len(prods)):
            prodChild = {'name':prods[s], "children":[]}
            for g in range(len(progs)):
                programChild = {'name':progs[g], "children":[]}
                for i in range(len(facil)):
                    FacilChild={"name":facil[i], "children":[]}
                    for c in range(len(tier1)):
                        Tier1Child={"name":tier1[c], "children":[]}
                        for d in range(len(tier2)):
                            # here's where I'm in trouble:
                            Order_Cond = np.array[[progs[a]& reqs[r]&
                                prods[s]&progs[g]& facil[i]& tier1[c]]
                            my_orders = np.where(p['Orders'], Order_cond)
                            print my_orders
                            # do other things
</code>```

As you can see the original intent was to use the For loops to set up a routine that only returned a list of Orders that came from unique combinations of facility, destination, program, etc. The Order_cond variable obviously has the wrong syntax.

If this were in SQL I'd just say "Select Orders From My_Data Where progs=a & reqs=r;" and so on.

I also considered a list comprehension but it doesn't work yet either:

```<code>list(x for p['Orders'] in p if p['Orders'] in Order_cond)
</code>```

Again, the goal is for a list of Orders to be created and stored in my_orders, which I then use for other functions.

答:
So you want to select from a csv file, rows which correspond with certain values for certain columns? In python 2.7 no less?  Ok, this is not that difficult for 2.7

You'll find this easiest with csv.DictReader, which reads in your csv files as rows of dictionaries, where the keys correspond to your column labels for each row.   Then, given a dictionary of key and value pairs you want to select for, the below code returns an array of dictionaries that fit what you want.  If you would like to strip out the key value pairing and just have arrays of values this is trivially implemented. Since you can convert your csv file into a list of dictionaries, it becomes a matter of selecting a dictionary from an array with certain values for keys

```<code>import csv

def dict_has_key_values(dict, dict_key_values):
    for key in dict_key_values:
        if not(key in dict and dict[key] == dict_key_values[key]):
           return False
    return True

def select_from_dict(csv_dict_reader, dict_key_values):
    list_of_dict = []
    for row_dict in csv_dict_reader:
        if dict_has_key_values(dict, dict_key_values):
             list_of_dict.append(dict)
    return list_of_dict

with open('yourfile.csv') as csvfile:
    selected_key_values = {...}
    reader = csv.DictReader(csvfile)
    selected_rows = select_from_dict(reader, selected_key_values)
</code>```

selected_rows should now have every row that

A: at least has every key in selected_key_values, and

B: the values associated with those keys are the same.

Title: Create a list based on nested For loops

Body:
Assume that I am using a client computer that will not allow for pip or pandas and must use Python 2.7. Binaries and converting into an exe is not allowed. I am reading in a CSV with column headers as names with numpy.

In my dataset, I am attempting to generate a list of orders that apply to unique combinations of Facility, Destination, Program #, and other factors, where p is the read csv dataset.

CSV starting out

What it would look like if I did this in Excel. The values in the Order field are what I'd like to have as a list in a variable called my_orders.

My current code looks like:

progs = np.unique(p['Program'])
facil = np.unique(p['Facility'])
dest = np.unique(p['Destination'])
reqs = np.unique(p['Requested'])
prods = np.unique(p['Produced'])
tier1 = np.unique(p['Tier1'])
tier2 = np.unique(p['Tier2'])

Which is followed by the following method originally written with pandas and Python3 in mind until discovering that only 2.7 and numpy were available:

for a in range(len(progs)):
    print("on Program ",a)
    ProgChild = {"name":progs[a], 'children':[]}
    for r in range(len(reqs)):
        reqChild = {"name":reqs[r], 'children':[]}
        for s in range(len(prods)):
            prodChild = {'name':prods[s], "children":[]}
            for g in range(len(progs)):
                programChild = {'name':progs[g], "children":[]}
                for i in range(len(facil)):
                    FacilChild={"name":facil[i], "children":[]}
                    for c in range(len(tier1)):
                        Tier1Child={"name":tier1[c], "children":[]}
                        for d in range(len(tier2)):
                            # here's where I'm in trouble:
                            Order_Cond = np.array[[progs[a]& reqs[r]&
                                prods[s]&progs[g]& facil[i]& tier1[c]]
                            my_orders = np.where(p['Orders'], Order_cond)
                            print my_orders
                            # do other things

As you can see the original intent was to use the For loops to set up a routine that only returned a list of Orders that came from unique combinations of facility, destination, program, etc. The Order_cond variable obviously has the wrong syntax.

If this were in SQL I'd just say "Select Orders From My_Data Where progs=a & reqs=r;" and so on.

I also considered a list comprehension but it doesn't work yet either:

list(x for p['Orders'] in p if p['Orders'] in Order_cond)

Again, the goal is for a list of Orders to be created and stored in my_orders, which I then use for other functions.

Body:
So you want to select from a csv file, rows which correspond with certain values for certain columns? In python 2.7 no less?  Ok, this is not that difficult for 2.7

You'll find this easiest with csv.DictReader, which reads in your csv files as rows of dictionaries, where the keys correspond to your column labels for each row.   Then, given a dictionary of key and value pairs you want to select for, the below code returns an array of dictionaries that fit what you want.  If you would like to strip out the key value pairing and just have arrays of values this is trivially implemented. Since you can convert your csv file into a list of dictionaries, it becomes a matter of selecting a dictionary from an array with certain values for keys

import csv

def dict_has_key_values(dict, dict_key_values):
    for key in dict_key_values:
        if not(key in dict and dict[key] == dict_key_values[key]):
           return False
    return True

def select_from_dict(csv_dict_reader, dict_key_values):
    list_of_dict = []
    for row_dict in csv_dict_reader:
        if dict_has_key_values(dict, dict_key_values):
             list_of_dict.append(dict)
    return list_of_dict

with open('yourfile.csv') as csvfile:
    selected_key_values = {...}
    reader = csv.DictReader(csvfile)
    selected_rows = select_from_dict(reader, selected_key_values)

selected_rows should now have every row that

A: at least has every key in selected_key_values, and

B: the values associated with those keys are the same.


问:
Issue with graphQL in nodejs , null returned for customised type in graphQL
I am currently exploring graphQL with nodejs, I m trying to build a simple example as below:

```<code>var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');

var schema = buildSchema(`
type Query {
getUser(jid: String ): [User],
albums:[Album],
}

type User{
name:String,
image:String,
albums:[Album]
}

type Album{
name:String,
image:String
}

`);

class Album {
    constructor() { }
    name() { return 'ablum name' }
    image() { return 'image url' }
}

class User {
    constructor(jid) {
        this.jid = jid;
        console.log(this.jid);

    }
    ablums() {

        return [new Album, new Album];

    };
    name() {
        console.log(this.jid);
        return "name";
    }
    image() { return "url"; }
}

var root = {

    getUser: function ({ jid }) {
        return [new User(jid), new User(jid)];
    },

};

var app = express();
app.use('/graphql', graphqlHTTP({
    schema: schema,
    rootValue: root,
    graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');
</code>```

I m expecting a JSON result with two User Arrays , each of it contain another two albums array which contain it's name and image. However I have got null in the Album field which should show an arrays of two albums with name and image field.

```<code>{
"data": {
"getUser": [
  {
    "name": "name of abc is michael",
    "image": "url",
    "albums": null
  },
  {
    "name": "name of abc is michael",
    "image": "url",
    "albums": null
  }
 ]
}
}
</code>```

Please help! I am completely new to graphQL and I think it is a very useful technology!

答: It's a typo on your user class, your method is called ablums yet your query is looking for a method / property called albums, which doesn't exist, hence returning null.</p>

Body:
I am currently exploring graphQL with nodejs, I m trying to build a simple example as below:

var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');

var schema = buildSchema(`
type Query {
getUser(jid: String ): [User],
albums:[Album],
}

type User{
name:String,
image:String,
albums:[Album]
}

type Album{
name:String,
image:String
}

`);

class Album {
    constructor() { }
    name() { return 'ablum name' }
    image() { return 'image url' }
}

class User {
    constructor(jid) {
        this.jid = jid;
        console.log(this.jid);

    }
    ablums() {

        return [new Album, new Album];

    };
    name() {
        console.log(this.jid);
        return "name";
    }
    image() { return "url"; }
}

var root = {

    getUser: function ({ jid }) {
        return [new User(jid), new User(jid)];
    },

};

var app = express();
app.use('/graphql', graphqlHTTP({
    schema: schema,
    rootValue: root,
    graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');

I m expecting a JSON result with two User Arrays , each of it contain another two albums array which contain it's name and image. However I have got null in the Album field which should show an arrays of two albums with name and image field.

{
"data": {
"getUser": [
  {
    "name": "name of abc is michael",
    "image": "url",
    "albums": null
  },
  {
    "name": "name of abc is michael",
    "image": "url",
    "albums": null
  }
 ]
}
}

Please help! I am completely new to graphQL and I think it is a very useful technology!


问:
Is there someway to disable all firebase logging to console?
I have created some unit tests for my firebase security rules. Part of this testing is trying to do illegal operations and asserting that they fail.

My problem has to do with noise; when I run the tests using nodeunit, the firebase client spits out several logs similar to this:

FIREBASE WARNING: set at /user failed: permission_denied

I do not want this output when intentionally doing illegal operations as it just results in noise and confusion.

答:
In our testing suite, we rewrite process.stderr.write to only ignore firebase warnings like so:

Javascript

process.stderr.write = (function(write) {
  return function() {
    if (!arguments[0].includes("FIREBASE WARNING"))
      write.apply(process.stderr, arguments);
  };
}(process.stderr.write));
```

<p><strong>Typescript (including tslint fix)</strong></p>

<pre class="lang-js prettyprint-override"><code>process.stderr.write = (() => {
    // tslint:disable-next-line:no-unbound-method
    const write = process.stderr.write;

    return function () {
        if (!(arguments[0] as string).includes("FIREBASE WARNING")) {
            return write.apply(process.stderr, arguments);
        }
    };
})();
</code>```

Body:
In our testing suite, we rewrite process.stderr.write to only ignore firebase warnings like so:

Javascript

process.stderr.write = (function(write) {
  return function() {
    if (!arguments[0].includes("FIREBASE WARNING"))
      write.apply(process.stderr, arguments);
  };
}(process.stderr.write));

Typescript (including tslint fix)

process.stderr.write = (() => {
    // tslint:disable-next-line:no-unbound-method
    const write = process.stderr.write;

    return function () {
        if (!(arguments[0] as string).includes("FIREBASE WARNING")) {
            return write.apply(process.stderr, arguments);
        }
    };
})();

ContentLicense: CC BY-SA 4.0


问:
Java book for experienced programmers (PHP)
I searched on few questions earlier asked here but my context is not matching exactly to them.
I am working on LAMP from past few years. I recently learnt Java SL-314 Syllabus thinking my knowledge in PHP and other PLUS some knowledge in core Java from Oracle website can be helpful.
I saw Java document is very poor compared to PHP. In PHP, one can get everything basic from the php.net site itself. For a simple thing like showing the resultset data to servlet or JSP from plain java code, I need to search a lot and still I cannot get past ArrayList etc. I was looking for a code in Java like this in PHP:

```<code>while ($row = mysql_fetch_assoc($result)) {
    echo $row["userid"];
    echo $row["fullname"];
    echo $row["userstatus"];
}
</code>```

I mean I want to use all fields the way I want.

I have a book, Java in Nutshell but that seems too theoretical. I need small book so that I can read it soon. I want to develop web app using Java. For getting help from core java, I want simple example codes to do all normal work I used to do in PHP.

Please help me find simple Java book with example code which can help me do all normal stuff one do in PHP.

答: If you want to do the jump to Java, try getting aquainted to Project Zero or Quercus (simpler) first. Both are PHP-implementations atop Java and allow interfacing to other Java frameworks. This might allow you to more gradually transition between the two languages and environments.</p>

ContentLicense: CC BY-SA 2.5

Body:
I searched on few questions earlier asked here but my context is not matching exactly to them.
I am working on LAMP from past few years. I recently learnt Java SL-314 Syllabus thinking my knowledge in PHP and other PLUS some knowledge in core Java from Oracle website can be helpful.
I saw Java document is very poor compared to PHP. In PHP, one can get everything basic from the php.net site itself. For a simple thing like showing the resultset data to servlet or JSP from plain java code, I need to search a lot and still I cannot get past ArrayList etc. I was looking for a code in Java like this in PHP:

while ($row = mysql_fetch_assoc($result)) {
    echo $row["userid"];
    echo $row["fullname"];
    echo $row["userstatus"];
}

I mean I want to use all fields the way I want.

I have a book, Java in Nutshell but that seems too theoretical. I need small book so that I can read it soon. I want to develop web app using Java. For getting help from core java, I want simple example codes to do all normal work I used to do in PHP.

Please help me find simple Java book with example code which can help me do all normal stuff one do in PHP.


问:
Animate DatePicker hide/show in StackView
How to properly animate datePicker appearance/disappearance in stackView? Currently I tried like this:

```<code>UIView.animateWithDuration(0.3, animations: {
    self.datePickerView.hidden = !self.datePickerView.hidden
})
</code>```

This causes problems with hiding animation - it starts nicely and then in the end datePickerView flashes a little bit at the top of where datePicker was. Any suggestions?

答:
Using a container to hold the picker and setting clipsToBounds = true worked for me.

I'm using PureLayout, but it should work with IB too.

```<code>startRangePickerContainer = UIView()
startRangePickerContainer.clipsToBounds = true
startRangePickerContainer.backgroundColor = UIColor.cyan
stackView.addArrangedSubview(startRangePickerContainer)
startRangePickerContainer.autoPinEdge(toSuperviewEdge: .leading)
startRangePickerContainer.autoSetDimension(.height, toSize: 216)
startRangePickerContainer.autoPinEdge(toSuperviewEdge: .leading)
startRangePickerContainer.autoPinEdge(toSuperviewEdge: .trailing)

startRangePicker = UIDatePicker()
startRangePickerContainer.addSubview(startRangePicker)
startRangePicker.autoCenterInSuperview()
</code>```

To animate:

```<code>UIView.animate(withDuration: 0.3, animations: {
    self.startRangePickerContainer.isHidden = !self.startRangePickerContainer.isHidden
})
</code>```

Body:
How to properly animate datePicker appearance/disappearance in stackView? Currently I tried like this:

UIView.animateWithDuration(0.3, animations: {
    self.datePickerView.hidden = !self.datePickerView.hidden
})

This causes problems with hiding animation - it starts nicely and then in the end datePickerView flashes a little bit at the top of where datePicker was. Any suggestions?

Body:
Using a container to hold the picker and setting clipsToBounds = true worked for me.

I'm using PureLayout, but it should work with IB too.

startRangePickerContainer = UIView()
startRangePickerContainer.clipsToBounds = true
startRangePickerContainer.backgroundColor = UIColor.cyan
stackView.addArrangedSubview(startRangePickerContainer)
startRangePickerContainer.autoPinEdge(toSuperviewEdge: .leading)
startRangePickerContainer.autoSetDimension(.height, toSize: 216)
startRangePickerContainer.autoPinEdge(toSuperviewEdge: .leading)
startRangePickerContainer.autoPinEdge(toSuperviewEdge: .trailing)

startRangePicker = UIDatePicker()
startRangePickerContainer.addSubview(startRangePicker)
startRangePicker.autoCenterInSuperview()

To animate:

UIView.animate(withDuration: 0.3, animations: {
    self.startRangePickerContainer.isHidden = !self.startRangePickerContainer.isHidden
})


问:
matplotlib scatterplot x axis labels
When I'm adding the c option to a scatterplot in matplotlib, the x axis labels dissapear. Here's an example: https://github.com/Kornel/scatterplot-matplotlib/blob/master/Scatter%20plot%20x%20axis%20labels.ipynb (pull requests are welcome:))

Here's the same example as in the notebook:

```<code>import pandas as pd
import matplotlib.pyplot as plt

test_df = pd.DataFrame({
        "X": [1, 2, 3, 4],
        "Y": [5, 4, 2, 1],
        "C": [1, 2, 3, 4]
    })
</code>```

Now compare the result of:

```<code>test_df.plot(kind="scatter", x="X", y="Y", s=50);
</code>```

To:

```<code>test_df.plot(kind="scatter", x="X", y="Y", c="C");
</code>```

Where are the x axis labels? Is this a feature I'm missing?

Pandas version: 0.18.1
Matplotlib: 1.5.3
Python: 3.5.2

Thanks for any help,
 Kornel

EDIT: The solution as pointed out by @Kewl is to call plt.subplots and specify the axes:

```<code>fig, ax = plt.subplots()
test_df.plot(kind="scatter", x="X", y="Y", s=50, c="C", cmap="plasma", ax=ax);
</code>```

gives

P.S. It looks like a jupyter issue, the label is fine when called without a jupyter notebook

答:
That looks like a strange bug with pandas plotting to me! Here's a way around it:

```<code>fig, ax = plt.subplots()
df.plot(kind='scatter',x='X', y='Y', c='C', ax=ax)
ax.set_xlabel("X")
plt.show()
</code>```

This will give you the graph you expect:

Title: matplotlib scatterplot x axis labels

Body:
When I'm adding the c option to a scatterplot in matplotlib, the x axis labels dissapear. Here's an example: https://github.com/Kornel/scatterplot-matplotlib/blob/master/Scatter%20plot%20x%20axis%20labels.ipynb (pull requests are welcome:))

Here's the same example as in the notebook:

import pandas as pd
import matplotlib.pyplot as plt

test_df = pd.DataFrame({
        "X": [1, 2, 3, 4],
        "Y": [5, 4, 2, 1],
        "C": [1, 2, 3, 4]
    })

Now compare the result of:

test_df.plot(kind="scatter", x="X", y="Y", s=50);

To:

test_df.plot(kind="scatter", x="X", y="Y", c="C");

Where are the x axis labels? Is this a feature I'm missing?

Pandas version: 0.18.1
Matplotlib: 1.5.3
Python: 3.5.2

Thanks for any help,
 Kornel

EDIT: The solution as pointed out by @Kewl is to call plt.subplots and specify the axes:

fig, ax = plt.subplots()
test_df.plot(kind="scatter", x="X", y="Y", s=50, c="C", cmap="plasma", ax=ax);

gives

P.S. It looks like a jupyter issue, the label is fine when called without a jupyter notebook

Body:
That looks like a strange bug with pandas plotting to me! Here's a way around it:

fig, ax = plt.subplots()
df.plot(kind='scatter',x='X', y='Y', c='C', ax=ax)
ax.set_xlabel("X")
plt.show()

This will give you the graph you expect:


问:
Getting an ArrayList of ArrayLists from another ArrayList in Java
I have an ArrayList of MyClass and I need to extract multiple lists from it according to the repetition of a property of the class.

MyClass:

```<code>public class MyClass{
    private int ID;
    private String Name;
    private String Position;

    public MyClass(int ID, String name, String position){
        this.ID = ID;
        Name = name;
        Position = position;
    }
}
</code>```

Example:

In my ArrayList I have 5 objects:

```<code>ID = 0, Name = "Name 0", Position = "G1.1";
ID = 1, Name = "Name 1", Position = "G2.1";
ID = 2, Name = "Name 2", Position = "G1.1";
ID = 3, Name = "Name 3", Position = "G1.1";
ID = 4, Name = "Name 4", Position = "G2.1";
</code>```

From this list I'll create 2 ArrayLists:

```<code>ArrayList 1 (Where Position = "G1.1")
    ID = 0, Name = "Name 0", Position = "G1.1";
    ID = 2, Name = "Name 2", Position = "G1.1";
    ID = 3, Name = "Name 3", Position = "G1.1";
ArrayList 2 (Where Position = "G2.1")
    ID = 1, Name = "Name 1", Position = "G2.1";
    ID = 4, Name = "Name 4", Position = "G2.1";
</code>```

The main list is created dynamically, so I don't know what will be the positions I will need to create to get the items.

答:
Try using a HashMap.</p>

```<code>Map<String, List<MyClass>> hm = new HashMap<String, List<MyClass>>();
for(MyClass obj : OrignalList){
    if(null != hm.get(obj.Position)){
         String pos = obj.Position;
         hm.put(pos, hm.get(pos).add(obj));
    }else {
         List<MyClass> temp = new ArrayList<MyClass>();
         temp.add(obj);
         hm.put(obj.Position, temp);
    }
}
</code>```

Body:
I have an ArrayList of MyClass and I need to extract multiple lists from it according to the repetition of a property of the class.

MyClass:

public class MyClass{
    private int ID;
    private String Name;
    private String Position;

    public MyClass(int ID, String name, String position){
        this.ID = ID;
        Name = name;
        Position = position;
    }
}

Example:

In my ArrayList I have 5 objects:

ID = 0, Name = "Name 0", Position = "G1.1";
ID = 1, Name = "Name 1", Position = "G2.1";
ID = 2, Name = "Name 2", Position = "G1.1";
ID = 3, Name = "Name 3", Position = "G1.1";
ID = 4, Name = "Name 4", Position = "G2.1";

From this list I'll create 2 ArrayLists:

ArrayList 1 (Where Position = "G1.1")
    ID = 0, Name = "Name 0", Position = "G1.1";
    ID = 2, Name = "Name 2", Position = "G1.1";
    ID = 3, Name = "Name 3", Position = "G1.1";
ArrayList 2 (Where Position = "G2.1")
    ID = 1, Name = "Name 1", Position = "G2.1";
    ID = 4, Name = "Name 4", Position = "G2.1";

The main list is created dynamically, so I don't know what will be the positions I will need to create to get the items.

Body:
Try using a HashMap.

Map<String, List<MyClass>> hm = new HashMap<String, List<MyClass>>();
for(MyClass obj : OrignalList){
    if(null != hm.get(obj.Position)){
         String pos = obj.Position;
         hm.put(pos, hm.get(pos).add(obj));
    }else {
         List<MyClass> temp = new ArrayList<MyClass>();
         temp.add(obj);
         hm.put(obj.Position, temp);
    }
}


问:
@RestControllerAdvice vs @ControllerAdvice

What are the major difference between @RestControllerAdvice and @ControllerAdvice ??

Is it we should always use @RestControllerAdvice for rest services and @ControllerAdvice MVC ?

答:
@RestControllerAdvice is just a syntactic sugar for @ControllerAdvice + @ResponseBody, you can look here.

Is it we should always use @RestControllerAdvice for rest services and
  @ControllerAdvice MVC?

Again, as mentioned above, @ControllerAdvice can be used even for REST web services as well, but you need to additionally use @ResponseBody.


问:
openxlsx: read.xlsx throws an error if the sheet name contains the "&" character

Create an .xlsx file with three sheets named: "Test 1", "S&P500 TR" and "SP500 TR". Put some random content in each sheet and save it as "Book1.xlsx".

Run:

```<code>> a <- getSheetNames("Book1.xlsx")
> a
[1] "Test 1"    "S&P500 TR" "SP500 TR"
</code>```

Now try:

```<code>> read.xlsx("Book1.xlsx", a[2])
Error in read.xlsx.default("Book1.xlsx", a[2]) :
  Cannot find sheet named "S&P500 TR"
</code>```

答:
First check if you actually type the name S&P500 TR instead of using a[2] that would change anything.

Alternatively, you can use readxl package for importing;

```<code>  library(readxl)

  X1 <- read_excel("C:/1.xls", sheet = "S&P500 TR")
</code>```

This is a spreadsheet that I had and it is the result after it is imported;

```<code> head(X1)
  # A tibble: 6 × 4
  #   Year Month       Community                      ` Average Daily`
  #  <dbl> <chr>         <chr>                                   <dbl>
  # 1  2016   Jan       Arlington                              5.35
  # 2  2016   Jan       Ashland                               1.26
  # 3  2016   Jan       Bedford                                2.62
  # 4  2016   Jan       Belmont                               3.03
  # 5  2016   Jan       Boston                                 84.89
  # 6  2016   Jan       Braintree                              8.16
</code>```

Body:
Create an .xlsx file with three sheets named: "Test 1", "S&P500 TR" and "SP500 TR". Put some random content in each sheet and save it as "Book1.xlsx".

Run:

> a <- getSheetNames("Book1.xlsx")
> a
[1] "Test 1"    "S&P500 TR" "SP500 TR"

Now try:

> read.xlsx("Book1.xlsx", a[2])
Error in read.xlsx.default("Book1.xlsx", a[2]) :
  Cannot find sheet named "S&P500 TR"

Body:
First check if you actually type the name S&P500 TR instead of using a[2] that would change anything.

Alternatively, you can use readxl package for importing;

  library(readxl)

  X1 <- read_excel("C:/1.xls", sheet = "S&P500 TR")

This is a spreadsheet that I had and it is the result after it is imported;

 head(X1)
  # A tibble: 6 × 4
  #   Year Month       Community                      ` Average Daily`
  #  <dbl> <chr>         <chr>                                   <dbl>
  # 1  2016   Jan       Arlington                              5.35
  # 2  2016   Jan       Ashland                               1.26
  # 3  2016   Jan       Bedford                                2.62
  # 4  2016   Jan       Belmont                               3.03
  # 5  2016   Jan       Boston                                 84.89
  # 6  2016   Jan       Braintree                              8.16


问:
Angular2 High Charts not working on Angularcli
I have created a project added all the references and added highcharts reference in package.json. But require not found is displayed. </p>

答: Add a variable declare var require: any; in app.module.ts</p>


问:
Problem with max SQL function
I have this code in PHP

```<code>$max="SELECT MAX(num) FROM info";
$maxquery= mysql_query($max) or die (died);
while($row = mysql_fetch_array($maxquery)){
    echo "The max num is ". $row['num']."this is it";
}
$maxnum= mysql_fetch_array($maxquery);
echo "<br>".$maxnum."hh";
</code>```

then the output be:

The max num is this is it

hh

Why didn't the query get the max number?

The table is called info and it has these fields, ID, num, title, description, and answer.

After editing:

I tried my query in MySQL and it works fine!

"SELECT MAX(num) FROM info"

and this is my complete code if it can help:

```<code><?php
    $answer=$_GET["answerbox"];
    $ID=$_GET["TheID"];

    $host="localhost";
    $username="root";
    $password="";
    $db_name="game";
    mysql_connect("$host","$username","$password")or die("cannot connect");
    mysql_select_db("$db_name")or die("cannot select DB");

    $max="SELECT MAX(num) FROM info";
    $maxquery= mysql_query($max) or die (died);
    while($row = mysql_fetch_array($maxquery)) {
        echo "The max num is ". $row['num']."this is it";
    }

    $maxnum= mysql_fetch_array($maxquery);
    $sql="SELECT * FROM info  WHERE ID=".$ID;
    $query = mysql_query($sql) or die(errorquery);
    $row = mysql_fetch_array($query);
    $trueanswer = $row['Answer'];
    $num=$row['num'];
    if ($num<$maxnum)
    {
        $numto= $num +1 ;
        echo "<br>".$maxnum."hh";
    }
?>
</code>```

答:
Run your query within the MySQL query window then analyse the output.  That way you can concentrate on the query without the PHP getting in the way.

Once you've done that modify the question so that we can see the query that's actually being run.

Title: Problem with max SQL function

Body:
I have this code in PHP

$max="SELECT MAX(num) FROM info";
$maxquery= mysql_query($max) or die (died);
while($row = mysql_fetch_array($maxquery)){
    echo "The max num is ". $row['num']."this is it";
}
$maxnum= mysql_fetch_array($maxquery);
echo "
".$maxnum."hh";

then the output be:

The max num is this is it

hh

Why didn't the query get the max number?

The table is called info and it has these fields, ID, num, title, description, and answer.

After editing:

I tried my query in MySQL and it works fine!

"SELECT MAX(num) FROM info"

and this is my complete code if it can help:

<?php
    $answer=$_GET["answerbox"];
    $ID=$_GET["TheID"];

    $host="localhost";
    $username="root";
    $password="";
    $db_name="game";
    mysql_connect("$host","$username","$password")or die("cannot connect");
    mysql_select_db("$db_name")or die("cannot select DB");

    $max="SELECT MAX(num) FROM info";
    $maxquery= mysql_query($max) or die (died);
    while($row = mysql_fetch_array($maxquery)) {
        echo "The max num is ". $row['num']."this is it";
    }

    $maxnum= mysql_fetch_array($maxquery);
    $sql="SELECT * FROM info  WHERE ID=".$ID;
    $query = mysql_query($sql) or die(errorquery);
    $row = mysql_fetch_array($query);
    $trueanswer = $row['Answer'];
    $num=$row['num'];
    if ($num<$maxnum)
    {
        $numto= $num +1 ;
        echo "
".$maxnum."hh";
    }
?>


答: try npm i -S pixrem then retry your grunt command.

Title: Grunt error "task default not found"

Body:
I am create gruntfile and install all needed dependencies.
In tutorial all worked fine but not for me.
If i try to run this gruntfile i see this error message:

Error: Cannot find module 'pixrem'
      Warning: Task "default" not found. Use --force to continue.
      Aborted due to warnings.

Where is mistake? If you can please correct the mistakes in the answer.
  Gruntfile is here:

module.exports = function(grunt) {

 grunt.initConfig({
  pkg : grunt.file.readJSON('package.json'),

  watch : {

   images : {
    files : ['images/src/**/*.{png,jpg,gif}'],
    tasks : ['newer:imagemin']
   }, // watch images added to src

   deleting : {
    files : ['images/src/*.{png,jpg,gif}'],
    tasks : ['delete_sync']
   }, // end of delete sync

   scripts : {
    files : ['js/libs/*.js', 'js/custom/*.js'],
    tasks : ['concat', 'uglify'],
    options : {
     spawn : false,
    }
   }, //end of watch scripts

   css : {
    files : ['sass/**/*.scss'],
    tasks : ['sass', 'postcss', 'penthouse'],
    options : {
     spawn : false,
    }
   }, //end of sass watch

   grunt : {
    files : ['gruntfile.js']
   }
  }, //end of watch

  /* ====================================================================================================================================================
   * ====================================================================================================================================================

   Tasks

   ====================================================================================================================================================
   ====================================================================================================================================================
   */

  delete_sync : {
   dist : {
    cwd : 'images/dist',
    src : ['**'],
    syncWith : 'images/src'
   }
  }, // end of delete sync

  imagemin : {
   dynamic : {
    files : [{
     expand : true, // Enable dynamic expansion
     cwd : 'images/src/', // source images (not compressed)
     src : ['**/*.{png,jpg,gif}'], // Actual patterns to match
     dest : 'images/dist/' // Destination of compressed files
    }]
   }
  }, //end imagemin

  concat : {
   dist : {
    src : ['js/libs/*.js', 'js/custom/*.js'],
    dest : 'js/build/production.js'
   }
  }, //end concat

  uglify : {
   dist : {
    src : 'js/build/production.js',
    dest : 'js/build/production.min.js'
   }
  }, //end uglify

  sass : {
   dist : {
    options : {
     style : 'nested', //no need for config.rb
     compass : 'true'
    },
    files : {
     'css/main.css' : 'sass/main.scss'
    }
   }
  }, //end of sass

  postcss : {
   options : {
    map : true,
    processors : [require('pixrem')(), // add fallbacks for rem units
    require('autoprefixer-core')({
     browsers : 'last 2 version, IE 9'
    }), // add vendor prefixes. for more: https://github.com/ai/browserslist
    require('cssnano')() // minify the result
    ]
   },
   dist : {
    src : 'css/main.css'
   }
  },

  penthouse : {
   extract : {
    outfile : 'css/critical.css.php',
    css : 'css/main.css',
    url : 'http://localhost/grunt-boilerplate',
    width : 1200,
    height : 500
   },
  }, //end of penthouse

  browserSync : {
   dev : {
    bsFiles : {
     src : ['css/*.css', 'images/*.*', 'js/build/production.min.js', '*.php', 'includes/*.php', '!.sass-cache']
    },
    options : {
     proxy : "localhost/grunt-boilerplate",
     watchTask : true
    }
   }
  },

  ftpush : {
   build : {
    auth : {
     host : 'ftp.yourwebsite.com',
     port : 21,
     authKey : 'key1' //ftp login is in the .ftppass file
    },
    src : './', //root
    dest : '/www', //destination folder
    exclusions : ['.sass-cache', '.git', 'images/src', 'node_modules', '.gitignore', '.ftppass', 'gruntfile.js', 'README.md', 'package.json'], //remember adding '.ftppass' to the exclusions in .gitignore if you are publishing the repo to github
    // keep : ['blog','cv','projects'], // SUPER IMPORTANT! check what resources should STAY on the server, for example your wordpress installation or other subfolders you use for other projects. else they'll get wiped out
    simple : false,
    useList : false
   }
  }
 });

 // load npm tasks
 grunt.loadNpmTasks('grunt-contrib-watch');
 grunt.loadNpmTasks('grunt-browser-sync');
 grunt.loadNpmTasks('grunt-contrib-sass');
 grunt.loadNpmTasks('grunt-contrib-concat');
 grunt.loadNpmTasks('grunt-contrib-uglify');
 grunt.loadNpmTasks('grunt-postcss');
 grunt.loadNpmTasks('grunt-contrib-imagemin');
 grunt.loadNpmTasks('grunt-newer');
 grunt.loadNpmTasks('grunt-delete-sync');
 grunt.loadNpmTasks('grunt-penthouse');
 grunt.loadNpmTasks('grunt-ftpush');

 // define default task
 grunt.registerTask('default', ["browserSync", "watch"]);
};

strong text


问:
Why does NetMQ DealerSocket on Mono send no message to server on Debian Wheezy, but does on Windows?
I have some problem with NetMQ 4.0.0.1 on Mono 4.8 on Debian Wheezy.

Where Dealer socket is not sending any message until I won't stop calling it to send new message. When I will put Thread.Sleep( 1000 ) between creating a tasks with than everything is ok. I would like to admit that everything is working on Windows in .Net Framework 4.5 and on .Net Core 1.1 without any Thread.Sleep().

I have pattern like this:

I have added debug messages and I can see that I am creating 100 REQ sockets in Tasks in a loop, and Router is getting requests in a queue, than is sending them trough Dealer, and nothing is happening on the other side of TCP until I will stop call send on REQ sockets. A simple Thread.Sleep() on every 5 tasks is working. It looks like a Poller bug, or Dealer bug, or I am making something wrong.

Here is a code of middle box:

```<code>public class CollectorDevice : IDisposable
{
    private NetMQPoller _poller;
    private RouterSocket _frontendSocket;
    private DealerSocket _backendSocket;
    private readonly string _backEndAddress;
    private readonly string _frontEndAddress;
    private readonly int _expectedFrameCount;
    private readonly ManualResetEvent _startSemaphore = new ManualResetEvent(false);
    private readonly Thread _localThread;
    private static Logger _logger = LogManager.GetCurrentClassLogger();

    /// <summary>
    /// Constructor
    /// </summary>
    /// <param name="backEndAddress"></param>
    /// <param name="frontEndAddress"></param>
    /// <param name="expectedFrameCount"></param>
    public CollectorDevice(string backEndAddress, string frontEndAddress, int expectedFrameCount)
    {
        _expectedFrameCount = expectedFrameCount;

        _backEndAddress = backEndAddress;
        _frontEndAddress = frontEndAddress;

        _localThread = new Thread(DoWork) { Name = "IPC Collector Device Thread" };
    }

    public void Start()
    {
        _localThread.Start();
        _startSemaphore.WaitOne();

    }

    public void Stop()
    {
        _poller.Stop();
    }

    #region Implementation of IDisposable

    public void Dispose()
    {
        Stop();
    }

    #endregion

    #region Private Methods
    private void DoWork()
    {
        try
        {
            using (_poller = new NetMQPoller())
            using (_frontendSocket = new RouterSocket(_frontEndAddress))
            using (_backendSocket = new DealerSocket(_backEndAddress))
            {
                _backendSocket.ReceiveReady += OnBackEndReady;
                _frontendSocket.ReceiveReady += OnFrontEndReady;

                _poller.Add(_frontendSocket);
                _poller.Add(_backendSocket);

                _startSemaphore.Set();

                _poller.Run();
            }
        }
        catch (Exception e)
        {
            _logger.Error(e);
        }
    }

    private void OnBackEndReady(object sender, NetMQSocketEventArgs e)
    {
        NetMQMessage message = _backendSocket.ReceiveMultipartMessage(_expectedFrameCount);
        _frontendSocket.SendMultipartMessage(message);
    }

    private void OnFrontEndReady(object sender, NetMQSocketEventArgs e)
    {
        NetMQMessage message = _frontendSocket.ReceiveMultipartMessage(_expectedFrameCount);
        _backendSocket.SendMultipartMessage(message);
    }

    #endregion
}
</code>```

Here is a client side:

```<code>class Program
{
    private static Logger _logger = LogManager.GetCurrentClassLogger();

    private static void Main(string[] args)
    {
        Console.WriteLine("Client. Please enter message for server. Enter 'QUIT' to turn off server");
        Console.ReadKey();

        using (var collectorDevice = new CollectorDevice(">tcp://localhost:5556", "inproc://broker", 3))
        {
            collectorDevice.Start();

            List<Task> tasks = new List<Task>();
            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine(i);
                int j = i;
                Task t = Task.Factory.StartNew(() =>
                {
                    try
                    {
                        using (var req = new RequestSocket("inproc://broker"))
                        {
                            req.SendFrame(String.Format("Request client: {0} id: {1}", j, Task.CurrentId));
                            _logger.Debug(String.Format("Request client: {0} id: {1}", j, Task.CurrentId));
                            Console.WriteLine(String.Format("Request client: {0} id: {1}", j, Task.CurrentId));

                            string responseMessage = req.ReceiveFrameString();
                            _logger.Debug(String.Format("Response from server: {0} id: {1} message: {2}", j, Task.CurrentId, responseMessage));
                            Console.WriteLine(String.Format("Response from server: {0} id: {1} message: {2}", j, Task.CurrentId, responseMessage));
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        _logger.Error(e);
                    }
                });
                tasks.Add(t);
                //Thread.Sleep (100);//<- This thread sleep is fixing problem?
            }

            Task.WaitAll(tasks.ToArray());
        }

    }
}
</code>```

And server side:

```<code>class Program
{
    private static Logger _logger = LogManager.GetCurrentClassLogger();

    static void Main(string[] args)
    {
        try{
        using (var routerSocket = new RouterSocket("@tcp://*:5556"))
        {
            var poller = new NetMQPoller();
            routerSocket.ReceiveReady += RouterSocketOnReceiveReady;
            poller.Add(routerSocket);
            poller.Run();
        }
        }
        catch(Exception e)
        {
            Console.WriteLine (e);
        }

        Console.ReadKey ();
    }

    private static void RouterSocketOnReceiveReady(object sender, NetMQSocketEventArgs netMqSocketEventArgs)
    {
        NetMQMessage clientMessage = new NetMQMessage();
        bool result = netMqSocketEventArgs.Socket.TryReceiveMultipartMessage(new TimeSpan(0, 0, 0, 5),
            ref clientMessage, 5);

        if (result == false)
        {
            Console.WriteLine ("Something went wrong?!");
        }

        var address = clientMessage[0];
        var address2 = clientMessage[1];
        var clientMessageString = clientMessage[3].ConvertToString();

        //_logger.Debug("Message from client received: '{0}'", clientMessageString);
        Console.WriteLine (String.Format ("Message from client received: '{0}'", clientMessageString));

        netMqSocketEventArgs
            .Socket.SendMoreFrame(address.Buffer)
            .SendMoreFrame(address2.Buffer)
            .SendMoreFrameEmpty()
            .SendFrame("I have received your message");
    }
}
</code>```

Anybody has any idea?

I was thinking that I am maybe using socket from different threads, so I have packed it into ThreadLocal structure, but it wasnt helped.Than I have read about some problems in unity with NetMQ so I have added 'AsyncIO.ForceDotNet.Force();' before every socket constructor call, and this wasnt helped too. Than I have updated my mono to 4.8 from 4.4 and it still looks the same.

I have checked that Thread.Sleep(100) between tasks is fixing problem. It is strange

答:
I tested the code, it does take a lot of time but eventually server receives all messages (takes around a minute).

The problem is the amount of threads, all async operation which should be completed on io completion ports thread takes a lot of time when there are 100 threads. I was able to reproduce it without NetMQ with following code

```<code>    public static void Main(string[] args)
    {
        ManualResetEvent resetEvent = new ManualResetEvent(false);

        List<Task> tasks = new List<Task>();

        for (int i = 0; i < 100; i++)
        {
            tasks.Add(Task.Run(() =>
            {
                resetEvent.WaitOne();
            }));
        }

        Thread.Sleep(100);

        Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        listener.Bind(new IPEndPoint(IPAddress.Any, 5556));
        listener.Listen(1);

        SocketAsyncEventArgs args1 = new SocketAsyncEventArgs();
        args1.Completed += (sender, eventArgs) =>
        {
            Console.WriteLine($"Accepted {args1.SocketError}");
            resetEvent.Set();
        };
        listener.AcceptAsync(args1);

        SocketAsyncEventArgs args2 = new SocketAsyncEventArgs();
        args2.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, 5556);
        args2.Completed += (sender, eventArgs) => Console.WriteLine("Connected");
        Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        client.ConnectAsync(args2);

        Task.WaitAll(tasks.ToArray());

        Console.WriteLine("all tasks completed");
    }
</code>```

You can see that is also takes around a minute. With only 5 threads it completed immediately.

Anyway you might want to start less threads and/or reoort a bug in mono project.

Body:
I have some problem with NetMQ 4.0.0.1 on Mono 4.8 on Debian Wheezy.

Where Dealer socket is not sending any message until I won't stop calling it to send new message. When I will put Thread.Sleep( 1000 ) between creating a tasks with than everything is ok. I would like to admit that everything is working on Windows in .Net Framework 4.5 and on .Net Core 1.1 without any Thread.Sleep().

I have pattern like this:

I have added debug messages and I can see that I am creating 100 REQ sockets in Tasks in a loop, and Router is getting requests in a queue, than is sending them trough Dealer, and nothing is happening on the other side of TCP until I will stop call send on REQ sockets. A simple Thread.Sleep() on every 5 tasks is working. It looks like a Poller bug, or Dealer bug, or I am making something wrong.

Here is a code of middle box:

public class CollectorDevice : IDisposable
{
    private NetMQPoller _poller;
    private RouterSocket _frontendSocket;
    private DealerSocket _backendSocket;
    private readonly string _backEndAddress;
    private readonly string _frontEndAddress;
    private readonly int _expectedFrameCount;
    private readonly ManualResetEvent _startSemaphore = new ManualResetEvent(false);
    private readonly Thread _localThread;
    private static Logger _logger = LogManager.GetCurrentClassLogger();

    ///
    /// Constructor
    ///
    /// <param name="backEndAddress"></param>
    /// <param name="frontEndAddress"></param>
    /// <param name="expectedFrameCount"></param>
    public CollectorDevice(string backEndAddress, string frontEndAddress, int expectedFrameCount)
    {
        _expectedFrameCount = expectedFrameCount;

        _backEndAddress = backEndAddress;
        _frontEndAddress = frontEndAddress;

        _localThread = new Thread(DoWork) { Name = "IPC Collector Device Thread" };
    }

    public void Start()
    {
        _localThread.Start();
        _startSemaphore.WaitOne();

    }

    public void Stop()
    {
        _poller.Stop();
    }

    #region Implementation of IDisposable

    public void Dispose()
    {
        Stop();
    }

    #endregion

    #region Private Methods
    private void DoWork()
    {
        try
        {
            using (_poller = new NetMQPoller())
            using (_frontendSocket = new RouterSocket(_frontEndAddress))
            using (_backendSocket = new DealerSocket(_backEndAddress))
            {
                _backendSocket.ReceiveReady += OnBackEndReady;
                _frontendSocket.ReceiveReady += OnFrontEndReady;

                _poller.Add(_frontendSocket);
                _poller.Add(_backendSocket);

                _startSemaphore.Set();

                _poller.Run();
            }
        }
        catch (Exception e)
        {
            _logger.Error(e);
        }
    }

    private void OnBackEndReady(object sender, NetMQSocketEventArgs e)
    {
        NetMQMessage message = _backendSocket.ReceiveMultipartMessage(_expectedFrameCount);
        _frontendSocket.SendMultipartMessage(message);
    }

    private void OnFrontEndReady(object sender, NetMQSocketEventArgs e)
    {
        NetMQMessage message = _frontendSocket.ReceiveMultipartMessage(_expectedFrameCount);
        _backendSocket.SendMultipartMessage(message);
    }

    #endregion
}

Here is a client side:

class Program
{
    private static Logger _logger = LogManager.GetCurrentClassLogger();

    private static void Main(string[] args)
    {
        Console.WriteLine("Client. Please enter message for server. Enter 'QUIT' to turn off server");
        Console.ReadKey();

        using (var collectorDevice = new CollectorDevice(">tcp://localhost:5556", "inproc://broker", 3))
        {
            collectorDevice.Start();

            List<Task> tasks = new List<Task>();
            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine(i);
                int j = i;
                Task t = Task.Factory.StartNew(() =>
                {
                    try
                    {
                        using (var req = new RequestSocket("inproc://broker"))
                        {
                            req.SendFrame(String.Format("Request client: {0} id: {1}", j, Task.CurrentId));
                            _logger.Debug(String.Format("Request client: {0} id: {1}", j, Task.CurrentId));
                            Console.WriteLine(String.Format("Request client: {0} id: {1}", j, Task.CurrentId));

                            string responseMessage = req.ReceiveFrameString();
                            _logger.Debug(String.Format("Response from server: {0} id: {1} message: {2}", j, Task.CurrentId, responseMessage));
                            Console.WriteLine(String.Format("Response from server: {0} id: {1} message: {2}", j, Task.CurrentId, responseMessage));
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        _logger.Error(e);
                    }
                });
                tasks.Add(t);
                //Thread.Sleep (100);//<- This thread sleep is fixing problem?
            }

            Task.WaitAll(tasks.ToArray());
        }

    }
}

And server side:

class Program
{
    private static Logger _logger = LogManager.GetCurrentClassLogger();

    static void Main(string[] args)
    {
        try{
        using (var routerSocket = new RouterSocket("@tcp://*:5556"))
        {
            var poller = new NetMQPoller();
            routerSocket.ReceiveReady += RouterSocketOnReceiveReady;
            poller.Add(routerSocket);
            poller.Run();
        }
        }
        catch(Exception e)
        {
            Console.WriteLine (e);
        }

        Console.ReadKey ();
    }

    private static void RouterSocketOnReceiveReady(object sender, NetMQSocketEventArgs netMqSocketEventArgs)
    {
        NetMQMessage clientMessage = new NetMQMessage();
        bool result = netMqSocketEventArgs.Socket.TryReceiveMultipartMessage(new TimeSpan(0, 0, 0, 5),
            ref clientMessage, 5);

        if (result == false)
        {
            Console.WriteLine ("Something went wrong?!");
        }

        var address = clientMessage[0];
        var address2 = clientMessage[1];
        var clientMessageString = clientMessage[3].ConvertToString();

        //_logger.Debug("Message from client received: '{0}'", clientMessageString);
        Console.WriteLine (String.Format ("Message from client received: '{0}'", clientMessageString));

        netMqSocketEventArgs
            .Socket.SendMoreFrame(address.Buffer)
            .SendMoreFrame(address2.Buffer)
            .SendMoreFrameEmpty()
            .SendFrame("I have received your message");
    }
}

Anybody has any idea?

I was thinking that I am maybe using socket from different threads, so I have packed it into ThreadLocal structure, but it wasnt helped.Than I have read about some problems in unity with NetMQ so I have added 'AsyncIO.ForceDotNet.Force();' before every socket constructor call, and this wasnt helped too. Than I have updated my mono to 4.8 from 4.4 and it still looks the same.

I have checked that Thread.Sleep(100) between tasks is fixing problem. It is strange

Body:
I tested the code, it does take a lot of time but eventually server receives all messages (takes around a minute).

The problem is the amount of threads, all async operation which should be completed on io completion ports thread takes a lot of time when there are 100 threads. I was able to reproduce it without NetMQ with following code

    public static void Main(string[] args)
    {
        ManualResetEvent resetEvent = new ManualResetEvent(false);

        List<Task> tasks = new List<Task>();

        for (int i = 0; i < 100; i++)
        {
            tasks.Add(Task.Run(() =>
            {
                resetEvent.WaitOne();
            }));
        }

        Thread.Sleep(100);

        Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        listener.Bind(new IPEndPoint(IPAddress.Any, 5556));
        listener.Listen(1);

        SocketAsyncEventArgs args1 = new SocketAsyncEventArgs();
        args1.Completed += (sender, eventArgs) =>
        {
            Console.WriteLine($"Accepted {args1.SocketError}");
            resetEvent.Set();
        };
        listener.AcceptAsync(args1);

        SocketAsyncEventArgs args2 = new SocketAsyncEventArgs();
        args2.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, 5556);
        args2.Completed += (sender, eventArgs) => Console.WriteLine("Connected");
        Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        client.ConnectAsync(args2);

        Task.WaitAll(tasks.ToArray());

        Console.WriteLine("all tasks completed");
    }

You can see that is also takes around a minute. With only 5 threads it completed immediately.

Anyway you might want to start less threads and/or reoort a bug in mono project.


问:
How to format date in fatfree template?
Is it possible and how to format date in FatFree framework inside template using it's own function?</p>

```<code><repeat group="{{ @rows }}" value="{{ @row }}">
      <tr>
         <td>{{ @row.idbox }}</td>
         <td>{{ @row.code }}</td>
         <td>{{ @row.createon }}</td>//date to format
         <td>{{ @row.senton }}</td>
         <td>{{ @row.price }}</td>
      </tr>
</repeat>
</code>```

答:
Use the standard php date() function. The previous answer is a really complicated way to get to the same result:

```<code>{{  date('d M Y',strtotime(@row.createon))  }}
</code>```

The reason you need to use strtotime is because F3's ::template view renders the variables as strings even if they were timestamp/datetime in the database.

Title: How to format date in fatfree template?

Body:
Is it possible and how to format date in FatFree framework inside template using it's own function?

<repeat group="{{ @rows }}" value="{{ @row }}">

         {{ @row.idbox }}
         {{ @row.code }}
         {{ @row.createon }}	//date to format
         {{ @row.senton }}
         {{ @row.price }}

</repeat>

Body:
Use the standard php date() function. The previous answer is a really complicated way to get to the same result:

{{  date('d M Y',strtotime(@row.createon))  }}

The reason you need to use strtotime is because F3's ::template view renders the variables as strings even if they were timestamp/datetime in the database.


问:
Decorator pattern in Objective-C
I was thinking of using the decorator pattern to extend the functionality of a UIKit class. The problem that I'm facing is that from examples I've seen in other languages the pattern forces me to duplicate the decorated object's interface. Here's how I would see the pattern implemented:

```<code>// Inheritance used for compile time check only
@interface UIScrollViewDecorator : UIScrollView
{
    UIScrollview *decoratedScrollView;
}

- (id)initWithScrollView:(UISCrollView*)scrollView;

@end

@implementation UIScrollViewDecorator

- (id)initWithScrollView:(UISCrollView*)scrollView
{
    self = [super init];
    if(self != nil)
    {
        decoratedScrollView = [scrollView retain];
        // maybe set up some custom controls on decoratedScrollView
    }
}

// all methods for UIScrollView need to be manually passed to the decorated object
//   -- this is the problem
- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated
{
    // use "overwritten methods" to mess with the input for the decorated scroll view
    // most of the time though I have no need to make any adjustments here; I still need
    // to pass all these messages through so that outside users can interact with me just
    // like with a real UIScrollView
    [decoratedScrollView scrollRectToVisible:rect animated:animated];
}

@end
</code>```

So to summarize, the problem is the duplication of the decorated object's method, even when I don't need to alter anything there. Is there a simpler way to pass along those methods that I don't need to "overwrite"? Could I use something like a NSProxy for this?

EDIT: This has become mostly a theoretical problem for me since I realized the decorator pattern is not what I needed to solve my actual problem. However, since I may come to use it again in the future, I'm still very interested in your answers.

答:
I believe what you want is to create a Category. Categories allow you to add additional methods to an existing class, including to core classes.

iOS Reference Library: Category

Title: Decorator pattern in Objective-C

Body:
I was thinking of using the decorator pattern to extend the functionality of a UIKit class. The problem that I'm facing is that from examples I've seen in other languages the pattern forces me to duplicate the decorated object's interface. Here's how I would see the pattern implemented:

// Inheritance used for compile time check only
@interface UIScrollViewDecorator : UIScrollView
{
    UIScrollview *decoratedScrollView;
}

- (id)initWithScrollView:(UISCrollView*)scrollView;

@end

@implementation UIScrollViewDecorator

- (id)initWithScrollView:(UISCrollView*)scrollView
{
    self = [super init];
    if(self != nil)
    {
        decoratedScrollView = [scrollView retain];
        // maybe set up some custom controls on decoratedScrollView
    }
}

// all methods for UIScrollView need to be manually passed to the decorated object
//   -- this is the problem
- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated
{
    // use "overwritten methods" to mess with the input for the decorated scroll view
    // most of the time though I have no need to make any adjustments here; I still need
    // to pass all these messages through so that outside users can interact with me just
    // like with a real UIScrollView
    [decoratedScrollView scrollRectToVisible:rect animated:animated];
}

@end

So to summarize, the problem is the duplication of the decorated object's method, even when I don't need to alter anything there. Is there a simpler way to pass along those methods that I don't need to "overwrite"? Could I use something like a NSProxy for this?

EDIT: This has become mostly a theoretical problem for me since I realized the decorator pattern is not what I needed to solve my actual problem. However, since I may come to use it again in the future, I'm still very interested in your answers.


问:
CGAffineTransform revert the rotating direction
I'm rotating 360º a UIButton using this code:

```<code>self.btn.transform = CGAffineTransform(rotationAngle: (180.0 * CGFloat(M_PI)) / 180.0)
    self.btn.transform = CGAffineTransform(rotationAngle: (0.0 * CGFloat(M_PI)) / 180.0)
</code>```

The problem is that it rotates from left to right and i want to invert the direction.
I have tried using -M_PI, or -180 and other combinations, but without success.
What am i doing wrong?

答:
You can apply a negative transform to reverse the direction:

```<code>self.btn.transform = CGAffineTransform(rotationAngle: -0.999*CGFloat.pi)
</code>```

Undo it with:

```<code>self.btn.transform = CGAffineTransform.identity
</code>```

Remember that the transform mutates the view but not the actual object.  You don't have to "undo" it, you just replace it.

Here is some simple working playground code showing animation counter-clockwise:

```<code>import UIKit
import PlaygroundSupport

let view:UIView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
view.backgroundColor = UIColor.red
PlaygroundPage.current.liveView = view

let button = UIView(frame: CGRect(x: 50, y: 50, width: 100, height: 50))

button.backgroundColor = UIColor.white
view.addSubview(button)

UIView.animateKeyframes(withDuration: 2.0, delay: 0.0, options: .repeat, animations: {
    let rotation = -0.999*CGFloat.pi
    button.transform = CGAffineTransform(rotationAngle: rotation)
    print(rotation)
}, completion: nil)
</code>```

The result is this:

Body:
I'm rotating 360º a UIButton using this code:

self.btn.transform = CGAffineTransform(rotationAngle: (180.0 * CGFloat(M_PI)) / 180.0)
    self.btn.transform = CGAffineTransform(rotationAngle: (0.0 * CGFloat(M_PI)) / 180.0)

The problem is that it rotates from left to right and i want to invert the direction.
I have tried using -M_PI, or -180 and other combinations, but without success.
What am i doing wrong?

Body:
You can apply a negative transform to reverse the direction:

self.btn.transform = CGAffineTransform(rotationAngle: -0.999*CGFloat.pi)

Undo it with:

self.btn.transform = CGAffineTransform.identity

Remember that the transform mutates the view but not the actual object.  You don't have to "undo" it, you just replace it.

Here is some simple working playground code showing animation counter-clockwise:

import UIKit
import PlaygroundSupport

let view:UIView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
view.backgroundColor = UIColor.red
PlaygroundPage.current.liveView = view

let button = UIView(frame: CGRect(x: 50, y: 50, width: 100, height: 50))

button.backgroundColor = UIColor.white
view.addSubview(button)

UIView.animateKeyframes(withDuration: 2.0, delay: 0.0, options: .repeat, animations: {
    let rotation = -0.999*CGFloat.pi
    button.transform = CGAffineTransform(rotationAngle: rotation)
    print(rotation)
}, completion: nil)

The result is this:


问:
Python xlrd : how to convert an extracted value?
Well i have a question that i feel i've been answered several times, from what i found here. However, as a newbie, i can't really understand how to perform a really basic operation.

Here's the thing :

i have an .xls and when i use xlrd to get a value i'm just using
sh.cell(0,0) (assuming that sh is my sheet);

if what is in the cell is a string i get something like text:u'MyName' and i only want to keep the string 'MyName';

if what is in the cell is a number i get something like number:201.0 and i only want to keep the integer 201.

If anyone can indicate me what i should to only extract the value, formatted as i want, thank you.

答: The correct answer to this is to simply use the Cell.value function. This will return a number or a Unicode string depending on what the cell contains.


问:
Ambiguity Resolution
```<code>void S(){}
struct S{};

int main(){
   S();
}
</code>```

In the code above, the expression 'S()' in main is treated as a function call expression rather than an attempt to create a temporary of type 'S'.

Which portion of the C++ Standard talks about the resolution of such an expression in favour of a function declaration? For some reason I am unable to locate it.

答: It can be resolved either by using the scope resolution operator(::) or by using virtual keyword(when we are dealing with either multiple or hybrid inheritance.  </p>

Title: Ambiguity Resolution

Body:
void S(){}
struct S{};

int main(){
   S();
}

In the code above, the expression 'S()' in main is treated as a function call expression rather than an attempt to create a temporary of type 'S'.

Which portion of the C++ Standard talks about the resolution of such an expression in favour of a function declaration? For some reason I am unable to locate it.


问:
How to declare a variable and mysql update in liquibase
I want to write the following sql code in liquibase

set @value1 = "string1";
set @value2 = "string2";

update users set category = REPLACE(category, @value1, @value2);

How to write this in liquibase either in xml or in sql file?

答:
If you want to declare and set variables within a changeset's 'sql' tag you just need to remove the ";".

By default liquibase uses ";" to execute, and variables are scoped within an execution.
So while this will not work:

```<code>DECLARE @value1 varchar(10);
SET @value1 = "string1";
</code>```

This will work:

```<code>DECLARE @value1 varchar(10)
SET @value1 = "string1"
</code>```

I left off the last ";" on the initialization as I assume you want to do something with the variable

Body:
If you want to declare and set variables within a changeset's 'sql' tag you just need to remove the ";".

By default liquibase uses ";" to execute, and variables are scoped within an execution.
So while this will not work:

DECLARE @value1 varchar(10);
SET @value1 = "string1";

This will work:

DECLARE @value1 varchar(10)
SET @value1 = "string1"

I left off the last ";" on the initialization as I assume you want to do something with the variable


问:
No resource identifier found for attribute 'alpha' in package 'android.support.design'
I created a library project from

```<code>android-sdk\extras\android\m2repository\com\android\support\design\design-25.0.1.aar
</code>```

I added appcompat, recyclerview and cardview libraries.

There is an error message:

design_25.0.1\res\color\design_tint_password_toggle.xml:19: error:
  No resource identifier found for attribute 'alpha' in package 'android.support.design'

This is the code of design_tint_password_toggle.xml

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:state_checked="true" android:color="?android:attr/colorForeground" app:alpha="0.54"/>
    <item android:color="?android:attr/colorForeground" app:alpha="0.38"/>
</selector>
</code>```

How can I fix this error?

答: I found doing a clean build first fixed this issue for me. (I was trying to upgrade from 23.0.1 -> 24.2.1)</p>

Body:
I created a library project from

android-sdk\extras\android\m2repository\com\android\support\design\design-25.0.1.aar

I added appcompat, recyclerview and cardview libraries.

There is an error message:

design_25.0.1\res\color\design_tint_password_toggle.xml:19: error:
  No resource identifier found for attribute 'alpha' in package 'android.support.design'

This is the code of design_tint_password_toggle.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:state_checked="true" android:color="?android:attr/colorForeground" app:alpha="0.54"/>
    <item android:color="?android:attr/colorForeground" app:alpha="0.38"/>
</selector>

How can I fix this error?


问:
How to push and present to UIViewController programmatically without segue in iOS Swift 3
I am using this code for push SHOW and MODALLY programmatically in iOS Objective C.

And now want to know about Swift 3.

```<code>NewsDetailsViewController *vc =  instantiateViewControllerWithIdentifier:@"NewsDetailsVCID"];
vc.newsObj = newsObj;
//--this(SHOW)
[self.navigationController pushViewController:vc animated:YES];
//-- or this(MODAL)
[self presentViewController:vc animated:YES completion:nil];
</code>```

答:
With an elegant way.

Create an Navigatable protocol:

```<code>protocol Navigatable {
    /// Storyboard name where this view controller exists.
    static var storyboardName: String { get }

    /// Storyboard Id of this view controller.
    static var storyboardId: String { get }

    /// Returns a new instance created from Storyboard identifiers.
    static func instantiateFromStoryboard() -> Self
}
</code>```

Create a default instantiate controller implementation:

```<code>/**
 Extension of Navigatable protocol with default implementations.
 */
extension Navigatable {
    static func instantiateFromStoryboard() -> Self {
        let storyboard = UIStoryboard(name: self.storyboardName, bundle: nil)
        guard
            let viewController = storyboard
                .instantiateViewController(withIdentifier: self.storyboardId) as? Self else {
                    fatalError("Cannot instantiate the controller.")
        }

        return viewController
    }
}
</code>```

Extends the UIViewController to push a view controller:

```<code>extension UIViewController {
    /**
     Pushes a view controller of the provided type.

     - Parameter viewControllerType: Type of view controller to push.
     - Parameter completion: Function to be executed on completion.
     Contains the view controller that was pushed when successful and nil otherwise.
     */
    func pushViewControllerOfType<T: Navigatable>(viewControllerType: T.Type, completion: (T) -> Void) {
        let viewController = T.instantiateFromStoryboard()
        if let vc = viewController as? UIViewController {
            self.pushViewController(vc, animated: true)
        }
        completion(viewController)
    }

    /**
     Pushes a view controller of the provided type.

     - Parameter viewControllerType: Type of view controller to push.
     */
    func pushViewControllerOfType<T: Navigatable>(viewControllerType: T.Type) {
        self.pushViewControllerOfType(viewControllerType: viewControllerType) { _ in }
    }
}
</code>```

Then you can use the Navigatable protocol for a specific view controller.

```<code>class MySuperViewController {
   override func viewDidLoad() {
      ...
   }
   // ...
}
extension MySuperViewController: Navigatable {
    static var storyboardName: String {
        return "Main"
    }

    static var storyboardId: String {
        return "MySuperViewControllerId" // From your story board name Main
    }
}

// Instantiate your controller
let vc = MySuperViewController.instantiateFromStoryboard()

// Or
//
// Push your view controller

// testViewController.swift

self.pushViewControllerOfType(viewControllerType: MySuperViewController)
</code>```

Body:
I am using this code for push SHOW and MODALLY programmatically in iOS Objective C.

And now want to know about Swift 3.

NewsDetailsViewController *vc =  instantiateViewControllerWithIdentifier:@"NewsDetailsVCID"];
vc.newsObj = newsObj;
//--this(SHOW)
[self.navigationController pushViewController:vc animated:YES];
//-- or this(MODAL)
[self presentViewController:vc animated:YES completion:nil];

Body:
With an elegant way.

Create an Navigatable protocol:

protocol Navigatable {
    /// Storyboard name where this view controller exists.
    static var storyboardName: String { get }

    /// Storyboard Id of this view controller.
    static var storyboardId: String { get }

    /// Returns a new instance created from Storyboard identifiers.
    static func instantiateFromStoryboard() -> Self
}

Create a default instantiate controller implementation:

/**
 Extension of Navigatable protocol with default implementations.
 */
extension Navigatable {
    static func instantiateFromStoryboard() -> Self {
        let storyboard = UIStoryboard(name: self.storyboardName, bundle: nil)
        guard
            let viewController = storyboard
                .instantiateViewController(withIdentifier: self.storyboardId) as? Self else {
                    fatalError("Cannot instantiate the controller.")
        }

        return viewController
    }
}

Extends the UIViewController to push a view controller:

extension UIViewController {
    /**
     Pushes a view controller of the provided type.

     - Parameter viewControllerType: Type of view controller to push.
     - Parameter completion: Function to be executed on completion.
     Contains the view controller that was pushed when successful and nil otherwise.
     */
    func pushViewControllerOfType<T: Navigatable>(viewControllerType: T.Type, completion: (T) -> Void) {
        let viewController = T.instantiateFromStoryboard()
        if let vc = viewController as? UIViewController {
            self.pushViewController(vc, animated: true)
        }
        completion(viewController)
    }

    /**
     Pushes a view controller of the provided type.

     - Parameter viewControllerType: Type of view controller to push.
     */
    func pushViewControllerOfType<T: Navigatable>(viewControllerType: T.Type) {
        self.pushViewControllerOfType(viewControllerType: viewControllerType) { _ in }
    }
}

Then you can use the Navigatable protocol for a specific view controller.

class MySuperViewController {
   override func viewDidLoad() {
      ...
   }
   // ...
}
extension MySuperViewController: Navigatable {
    static var storyboardName: String {
        return "Main"
    }

    static var storyboardId: String {
        return "MySuperViewControllerId" // From your story board name Main
    }
}

// Instantiate your controller
let vc = MySuperViewController.instantiateFromStoryboard()

// Or
//
// Push your view controller

// testViewController.swift

self.pushViewControllerOfType(viewControllerType: MySuperViewController)


问:
Multidimensional Arrays Nested to Unlimited Depth
I have a multidimensional array nested to an unknown/unlimited depth.
I'd like to be able to loop through every element.
I don't want to use, foreach(){foreach(){foreach(){}}} as I don't know the depth.

I'm eventually looking for all nested arrays called "xyz".  Has anyone got any suggestions?

答:
There is a vast difference between unknown and unlimited. However, you can make use of the SPL Iterators instead of using multiple nested foreach loops.

Example:

```<code>$array_obj = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach($array_obj as $key => $value) {
   echo $value;
}
</code>```

Body:
There is a vast difference between unknown and unlimited. However, you can make use of the SPL Iterators instead of using multiple nested foreach loops.

Example:

$array_obj = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach($array_obj as $key => $value) {
   echo $value;
}