问:
Instantiating objects in the constructor
Is there any benefit to doing the following:

```<code>public class Foo
{
    private Bar bar;

    public Foo()
    {
        bar = new Bar();
    }
}
</code>```

Instead of doing it like so:

```<code>public class Foo
{
    private Bar bar = new Bar();

    public Foo()
    {
    }
}
</code>```

Given that at instantiation, the private member variable in either example will be instantiated, I don't believe there is a difference, but I've seen it enough times to where I'm curious.

答:
In the exact case you've given, there isn't a difference - but in general there is.

Variable initializers are executed before the base class constructor is called. If that base constructor calls a virtual method which uses some of the instance variables, you can see that difference.

For spec fans, it's in section 10.11.2 of the C# 4 spec:

When an instance constructor has no constructor initializer, or it has a constructor initializer of the form base(...), that constructor implicitly performs the initializations specified by the variable-initializers of the instance fields declared in its class. This corresponds to a sequence of assignments that are executed immediately upon entry to the constructor and before the implicit invocation of the direct base class constructor.

Here's an example demonstrating this:

```<code>using System;

public class Base
{
    public Base()
    {
        Dump();
    }

    public virtual void Dump() {}
}

class Child : Base
{
    private string x = "initialized in declaration";
    private string y;

    public Child()
    {
        y = "initialized in constructor";
    }

    public override void Dump()
    {
        Console.WriteLine("x={0}; y={1}", x, y);
    }
}

class Test
{
    static void Main(string[] args)
    {
        new Child();
    }
}
</code>```

Result:

x=initialized in declaration; y=

Now having said the above, I would try hard to avoid calling virtual methods from a constructor. You're basically asking the derived class to work in a partially-initialized fashion. However, it's a difference you should be aware of.

As for where to initialize variables... I have to admit I'm not particularly consistent, and I don't find that's actually a problem. If I have any specific bias, it's probably to initialize anything which won't depend on any parameters at the point of declaration, leaving the variables which I can't initialize without extra information to the constructor.

Body:
Is there any benefit to doing the following:

public class Foo
{
    private Bar bar;

    public Foo()
    {
        bar = new Bar();
    }
}

Instead of doing it like so:

public class Foo
{
    private Bar bar = new Bar();

    public Foo()
    {
    }
}

Given that at instantiation, the private member variable in either example will be instantiated, I don't believe there is a difference, but I've seen it enough times to where I'm curious.

Body:
In the exact case you've given, there isn't a difference - but in general there is.

Variable initializers are executed before the base class constructor is called. If that base constructor calls a virtual method which uses some of the instance variables, you can see that difference.

For spec fans, it's in section 10.11.2 of the C# 4 spec:

When an instance constructor has no constructor initializer, or it has a constructor initializer of the form base(...), that constructor implicitly performs the initializations specified by the variable-initializers of the instance fields declared in its class. This corresponds to a sequence of assignments that are executed immediately upon entry to the constructor and before the implicit invocation of the direct base class constructor.

Here's an example demonstrating this:

using System;

public class Base
{
    public Base()
    {
        Dump();
    }

    public virtual void Dump() {}
}

class Child : Base
{
    private string x = "initialized in declaration";
    private string y;

    public Child()
    {
        y = "initialized in constructor";
    }

    public override void Dump()
    {
        Console.WriteLine("x={0}; y={1}", x, y);
    }
}

class Test
{
    static void Main(string[] args)
    {
        new Child();
    }
}

Result:

x=initialized in declaration; y=

Now having said the above, I would try hard to avoid calling virtual methods from a constructor. You're basically asking the derived class to work in a partially-initialized fashion. However, it's a difference you should be aware of.

As for where to initialize variables... I have to admit I'm not particularly consistent, and I don't find that's actually a problem. If I have any specific bias, it's probably to initialize anything which won't depend on any parameters at the point of declaration, leaving the variables which I can't initialize without extra information to the constructor.


来源: stackexchange

问:
Remove null values in SQL server

Hello, Does anuone knows how can I remowe the null values corresponding to the description of the same product key? So, I have one product Key and its description in each language.

I'm trying to use the coalesce function, but it doesnt return me anything.

答:
you can use GROUP BY as below.

```<code>SELECT ProductKey,
       MAX(C_ar_description) AS C_ar_description,
       MAX(C_en_description) AS C_en_description,
       MAX(C_fr_description) AS C_fr_description
FROM YourTable
GROUP BY ProductKey
</code>```

You should use the results to fix the data so you dont need to do this every time.

ContentLicense: CC BY-SA 3.0

Title: Remove null values in SQL server

Body:
you can use GROUP BY as below.

SELECT ProductKey,
       MAX(C_ar_description) AS C_ar_description,
       MAX(C_en_description) AS C_en_description,
       MAX(C_fr_description) AS C_fr_description
FROM YourTable
GROUP BY ProductKey

You should use the results to fix the data so you dont need to do this every time.


问:
How do you retrieve a google drive watcher channel id?
I want to stop a channel with that method: https://developers.google.com/drive/v3/reference/channels/stop

My issue is that I can't remember the uuid that I need to pass to stop the watcher.

I should be able to retrieve that info from the header X-GOOG-CHANNEL-ID google sends to the webhook adress I registered when I created the watcher.

But second issue is that webhook callback for the watcher is on a google standard engine.

There are stackdriver logs, I see the webhook adress getting hit, but I'm unable in those logs to see the headers sent.

There are no methods on the drive API to get a list of 'alive' watchers, so I guess my only option is to somehow log in the standard engine instance the headers of the POST request sent to the webhook adress.

From the stackdriver doc, requests header should be in the httpRequest object, but mine mentions only that for the webhook adress route declared earlier.

httpRequest: {
  status:  500

 }

Any idea ?

答:
I found a solution, once has to use the debug facility at
https://console.cloud.google.com/debug?dlv=4&project=YOURPROJECT&app=GAE:SERVICE@VERSION

You put a breakpoint called a Snapshot in the webhook adress route at the beginning with a code like this one for instance: watcherid = request.headers['X-GOOG-CHANNEL-ID'] and thus will be able to inspect variables and the watcherid variable.


问:
How to mock a generic method to return concrete type?
I'm trying to mock the return type of a generic method to match a specific concrete type but I cannot seem to get the casting to work out:

```<code>    public T Get<T>(string key)
    {
        if (typeof(T) == typeof(GenericIsAuthenticatedResponse) && key == "1234")
            return GetGenericIsAuthenticatedResponse();

        return default(T);
    }

    private static GenericIsAuthenticatedResponse GetGenericIsAuthenticatedResponse()
    {
       return new GenericIsAuthenticatedResponse
        {
            AuthCode = "1234",
            Email = "email@email.com"
        };
    }
</code>```

So my question is how can I get the mock method to return the GenericIsAuthenticatedResponse?

答:
I applied some lateral thinking in the end (or bodge depending on your POV) and serialised/deserialised Json to achieve this:</p>

```<code>   public T Get<T>(string key)
    {
        if (typeof(T) == typeof(GenericIsAuthenticatedResponse) && key == "1234")
            return JsonConvert.DeserializeObject<T>(GetGenericIsAuthenticatedResponse());

        return default(T);
    }

    private static string GetGenericIsAuthenticatedResponse()
    {
        var r = new GenericIsAuthenticatedResponse
        {
            Username = "email.email.com",
            AuthCode = "1234"
        };

        return JsonConvert.SerializeObject(r);
    }
</code>```

Body:
I'm trying to mock the return type of a generic method to match a specific concrete type but I cannot seem to get the casting to work out:

    public T Get<T>(string key)
    {
        if (typeof(T) == typeof(GenericIsAuthenticatedResponse) && key == "1234")
            return GetGenericIsAuthenticatedResponse();

        return default(T);
    }

    private static GenericIsAuthenticatedResponse GetGenericIsAuthenticatedResponse()
    {
       return new GenericIsAuthenticatedResponse
        {
            AuthCode = "1234",
            Email = "email@email.com"
        };
    }

So my question is how can I get the mock method to return the GenericIsAuthenticatedResponse?

Body:
I applied some lateral thinking in the end (or bodge depending on your POV) and serialised/deserialised Json to achieve this:

   public T Get<T>(string key)
    {
        if (typeof(T) == typeof(GenericIsAuthenticatedResponse) && key == "1234")
            return JsonConvert.DeserializeObject<T>(GetGenericIsAuthenticatedResponse());

        return default(T);
    }

    private static string GetGenericIsAuthenticatedResponse()
    {
        var r = new GenericIsAuthenticatedResponse
        {
            Username = "email.email.com",
            AuthCode = "1234"
        };

        return JsonConvert.SerializeObject(r);
    }


问:
Find maximum of 9 numbers - fast
I have 9 random integer numbers. Is there a faster way how to find maximum without explicitly compare everything?

I am performing this operation milion times per frame and this is quite slow.

```<code>function calculateMax(a, b, c,
                      d, e, f,
                      g, h, i){
    var max = (a > b) ? a : b;
    var max2 = (c > d) ? c : d;
    var max3 = (e > f) ? e : f;
    var max4 = (g > h) ? g : h;

    max = (i > max) ? i : max;
    max = (max2 > max) ? max2 : max;
    max = (max3 > max) ? max3 : max;
    max = (max4 > max) ? max4 : max;

    return max;
}
</code>```

答:
The results seem rather disappointing after running few times, but posting in case someone wants to do better test on other browsers, or improve (might be faster with SIMD instructions)

function max1(a, b, c, d, e, f, g, h, i) {                   // shortened calculateMax
    var max  = (a > b) ? a : b; var max2 = (c > d) ? c : d;
    var max3 = (e > f) ? e : f; var max4 = (g > h) ? g : h;

    max = ( i   > max) ?  i   : max; max = (max2 > max) ? max2 : max;
    max = (max3 > max) ? max3 : max; max = (max4 > max) ? max4 : max;
    return max;
}

function max2(a, b, c, d, e, f, g, h, i) {
  if (a < b) a = b; if (a < c) a = c; if (a < d) a = d; if (a < e) a = e;
  if (a < f) a = f; if (a < g) a = g; if (a < h) a = h; if (a > 31 )); }
//function max(a, b) { return (a - b >>> 31) * b | (b - a >>> 31) * a }
function max(a, b) { return (a - b >> 31) & b | (b - a >> 31) & a }

function max3(a, b, c, d, e, f, g, h, i) {
  return max(a, max(b, max(c, max(d, max(e, max(f, max(g, max(h, i))))))))
}

function max4(a, b, c, d, e, f, g, h, i) {
  a  =   (a - b >> 31) & b | (b - a >> 31) & a
  a  =   (a - c >> 31) & c | (c - a >> 31) & a
  a  =   (a - d >> 31) & d | (d - a >> 31) & a
  a  =   (a - e >> 31) & e | (e - a >> 31) & a
  a  =   (a - f >> 31) & f | (f - a >> 31) & a
  a  =   (a - g >> 31) & g | (g - a >> 31) & a
  a  =   (a - h >> 31) & h | (h - a >> 31) & a
  return (a - i >> 31) & i | (i - a >> 31) & a
}

var l = console.log, p = performance
var t = p.now(), m = max1(1,2,3,4,5,6,7,8,9); t -= p.now(); l(m, 1, -t)
var t = p.now(), m = max2(1,2,3,4,5,6,7,8,9); t -= p.now(); l(m, 2, -t)
var t = p.now(), m = max3(1,2,3,4,5,6,7,8,9); t -= p.now(); l(m, 3, -t)
var t = p.now(), m = max4(1,2,3,4,5,6,7,8,9); t -= p.now(); l(m, 4, -t)```

Title: Find maximum of 9 numbers - fast

Body:
I have 9 random integer numbers. Is there a faster way how to find maximum without explicitly compare everything?

I am performing this operation milion times per frame and this is quite slow.

function calculateMax(a, b, c,
                      d, e, f,
                      g, h, i){
    var max = (a > b) ? a : b;
    var max2 = (c > d) ? c : d;
    var max3 = (e > f) ? e : f;
    var max4 = (g > h) ? g : h;

    max = (i > max) ? i : max;
    max = (max2 > max) ? max2 : max;
    max = (max3 > max) ? max3 : max;
    max = (max4 > max) ? max4 : max;

    return max;
}

Body:
The results seem rather disappointing after running few times, but posting in case someone wants to do better test on other browsers, or improve (might be faster with SIMD instructions)

function max1(a, b, c, d, e, f, g, h, i) {                   // shortened calculateMax
    var max  = (a > b) ? a : b; var max2 = (c > d) ? c : d;
    var max3 = (e > f) ? e : f; var max4 = (g > h) ? g : h;

    max = ( i   > max) ?  i   : max; max = (max2 > max) ? max2 : max;
    max = (max3 > max) ? max3 : max; max = (max4 > max) ? max4 : max;
    return max;
}

function max2(a, b, c, d, e, f, g, h, i) {
  if (a < b) a = b; if (a < c) a = c; if (a < d) a = d; if (a < e) a = e;
  if (a < f) a = f; if (a < g) a = g; if (a < h) a = h; if (a < i) a = i;
  return a;
}

//function max(a, b) { return a - ((a -= b) & (a >> 31 )); }
//function max(a, b) { return (a - b >>> 31) * b | (b - a >>> 31) * a }
function max(a, b) { return (a - b >> 31) & b | (b - a >> 31) & a }

function max3(a, b, c, d, e, f, g, h, i) {
  return max(a, max(b, max(c, max(d, max(e, max(f, max(g, max(h, i))))))))
}

function max4(a, b, c, d, e, f, g, h, i) {
  a  =   (a - b >> 31) & b | (b - a >> 31) & a
  a  =   (a - c >> 31) & c | (c - a >> 31) & a
  a  =   (a - d >> 31) & d | (d - a >> 31) & a
  a  =   (a - e >> 31) & e | (e - a >> 31) & a
  a  =   (a - f >> 31) & f | (f - a >> 31) & a
  a  =   (a - g >> 31) & g | (g - a >> 31) & a
  a  =   (a - h >> 31) & h | (h - a >> 31) & a
  return (a - i >> 31) & i | (i - a >> 31) & a
}

var l = console.log, p = performance
var t = p.now(), m = max1(1,2,3,4,5,6,7,8,9); t -= p.now(); l(m, 1, -t)
var t = p.now(), m = max2(1,2,3,4,5,6,7,8,9); t -= p.now(); l(m, 2, -t)
var t = p.now(), m = max3(1,2,3,4,5,6,7,8,9); t -= p.now(); l(m, 3, -t)
var t = p.now(), m = max4(1,2,3,4,5,6,7,8,9); t -= p.now(); l(m, 4, -t)


问:
Gradient background with text clip for IE11 and safari
The example below:

h1 {
  background-image: linear-gradient(to right, #00b140, #bcda00 17%, #bcda00 60%, #00b140);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Text11111</h1></code>```

Lacks full cross-browser support. Any suggestions?

答:
You can try the following and adjust the colors as required!

Code:

h1 {
    background-image: rgba(21, 182, 57,1);
    background-image: -moz-linear-gradient(left, rgba(21, 182, 57,1) 0%, rgba(21, 182, 57,1) 13%, rgba(141, 208, 16,1) 10%);
    background-image: -webkit-gradient(left top, right top, color-stop(0%, rgba(21, 182, 57,1)), color-stop(100%, rgba(141, 208, 16,1)));
    background-image: -webkit-linear-gradient(left, rgb(21, 182, 57) 0%, rgba(141, 208, 16,1) 10%);
    background-image: -o-linear-gradient(left, rgba(21, 182, 57,1) 0%, rgba(141, 208, 16,1) 10%);
    background-image: -ms-linear-gradient(left, rgba(21, 182, 57,1) 0%, rgba(141, 208, 16,1) 10%);
    /* background-image: linear-gradient(to right, rgb(29, 53, 10) 0%, rgb(127, 255, 30) 13%, rgba(83,133,36,1) 30%, rgba(197,255,82,1) 58%, rgba(197,255,82,1) 100%); */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#8dd010', endColorstr='#15b639', GradientType=1 );
    background-clip: text;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Hello Gradient</h1></code>```

Body:
The example below:

h1 {
  background-image: linear-gradient(to right, #00b140, #bcda00 17%, #bcda00 60%, #00b140);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

Text11111

Lacks full cross-browser support. Any suggestions?

Body:
You can try the following and adjust the colors as required!

Code:

h1 {
    background-image: rgba(21, 182, 57,1);
    background-image: -moz-linear-gradient(left, rgba(21, 182, 57,1) 0%, rgba(21, 182, 57,1) 13%, rgba(141, 208, 16,1) 10%);
    background-image: -webkit-gradient(left top, right top, color-stop(0%, rgba(21, 182, 57,1)), color-stop(100%, rgba(141, 208, 16,1)));
    background-image: -webkit-linear-gradient(left, rgb(21, 182, 57) 0%, rgba(141, 208, 16,1) 10%);
    background-image: -o-linear-gradient(left, rgba(21, 182, 57,1) 0%, rgba(141, 208, 16,1) 10%);
    background-image: -ms-linear-gradient(left, rgba(21, 182, 57,1) 0%, rgba(141, 208, 16,1) 10%);
    /* background-image: linear-gradient(to right, rgb(29, 53, 10) 0%, rgb(127, 255, 30) 13%, rgba(83,133,36,1) 30%, rgba(197,255,82,1) 58%, rgba(197,255,82,1) 100%); */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#8dd010', endColorstr='#15b639', GradientType=1 );
    background-clip: text;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}

<h1>Hello Gradient</h1>


问:
Mule-Join two DB table results based on given condition
I need to join the output coming from two database tables based on given condition.
The condition would be :  If value for a column from first table is  same as value for a column from second table, join the rows from both tables into one or else skip the row.

My code looks something like below :

```<code>    <?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:json="http://www.mulesoft.org/schema/mule/json" xmlns:dw="http://www.mulesoft.org/schema/mule/ee/dw" xmlns:db="http://www.mulesoft.org/schema/mule/db" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
    xmlns:spring="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/db http://www.mulesoft.org/schema/mule/db/current/mule-db.xsd
http://www.mulesoft.org/schema/mule/ee/dw http://www.mulesoft.org/schema/mule/ee/dw/current/dw.xsd
http://www.mulesoft.org/schema/mule/json http://www.mulesoft.org/schema/mule/json/current/mule-json.xsd">
    <db:mysql-config name="MySQL_Configuration" host="xyz.com" port="3306" user="userXXX" password="****" database="bd" doc:name="MySQL Configuration"/>
    <expression-filter expression="#[flowVars.payload1.seatsAvailable != flowVars.payload2.seatsAvailable]" name="Expression" doc:name="Expression"/>
    <flow name="studyFlow">
        <poll doc:name="Poll">
            <fixed-frequency-scheduler frequency="1" timeUnit="HOURS"/>
            <db:select config-ref="MySQL_Configuration" doc:name="Database">
                <db:parameterized-query><![CDATA[select * from table1]]></db:parameterized-query>
            </db:select>
        </poll>
        <set-variable variableName="payload1" value="#[payload]" doc:name="resultFromTable1"/>
        <db:select config-ref="MySQL_Configuration" doc:name="Database">
            <db:parameterized-query><![CDATA[select * from table2]]></db:parameterized-query>
        </db:select>
        <logger message="payload from american #[payload[0]]" level="INFO" doc:name="Logger"/>
        <set-variable variableName="payload2" value="#[payload]" doc:name="resultFromTable2"/>
        <dw:transform-message doc:name="Transform Message">
            <dw:set-payload><![CDATA[%dw 1.0
%output application/java
%var count = 0
---
flowVars.payload1 map using (id = $.code2) {

         (flowVars.payload2 filter ($.code2 contains id)  map {

            //col1:flowVars.payload2.code2,
            col2: flowVars.payload1.toAirport

     })
  }
  ]]></dw:set-payload>
        </dw:transform-message>

        <logger message="#[payload]" level="INFO" doc:name="Logger"/>
    </flow>
</mule>
</code>```

But this doesn't give me appropriate output. Please help.

答:
Why can't you join in SQL query itself and select columns.. something like below

select  from tableA , tableB where tableA.id = tableB.id

do you have any constraints ?

Body:
I need to join the output coming from two database tables based on given condition.
The condition would be :  If value for a column from first table is  same as value for a column from second table, join the rows from both tables into one or else skip the row.

My code looks something like below :

    <?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:json="http://www.mulesoft.org/schema/mule/json" xmlns:dw="http://www.mulesoft.org/schema/mule/ee/dw" xmlns:db="http://www.mulesoft.org/schema/mule/db" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
    xmlns:spring="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/db http://www.mulesoft.org/schema/mule/db/current/mule-db.xsd
http://www.mulesoft.org/schema/mule/ee/dw http://www.mulesoft.org/schema/mule/ee/dw/current/dw.xsd
http://www.mulesoft.org/schema/mule/json http://www.mulesoft.org/schema/mule/json/current/mule-json.xsd">
    <db:mysql-config name="MySQL_Configuration" host="xyz.com" port="3306" user="userXXX" password="****" database="bd" doc:name="MySQL Configuration"/>
    <expression-filter expression="#[flowVars.payload1.seatsAvailable != flowVars.payload2.seatsAvailable]" name="Expression" doc:name="Expression"/>
    <flow name="studyFlow">
        <poll doc:name="Poll">
            <fixed-frequency-scheduler frequency="1" timeUnit="HOURS"/>
            <db:select config-ref="MySQL_Configuration" doc:name="Database">
                <db:parameterized-query><![CDATA[select * from table1]]></db:parameterized-query>
            </db:select>
        </poll>
        <set-variable variableName="payload1" value="#[payload]" doc:name="resultFromTable1"/>
        <db:select config-ref="MySQL_Configuration" doc:name="Database">
            <db:parameterized-query><![CDATA[select * from table2]]></db:parameterized-query>
        </db:select>
        <logger message="payload from american #[payload[0]]" level="INFO" doc:name="Logger"/>
        <set-variable variableName="payload2" value="#[payload]" doc:name="resultFromTable2"/>
        <dw:transform-message doc:name="Transform Message">
            <dw:set-payload><![CDATA[%dw 1.0
%output application/java
%var count = 0
---
flowVars.payload1 map using (id = $.code2) {

         (flowVars.payload2 filter ($.code2 contains id)  map {

            //col1:flowVars.payload2.code2,
            col2: flowVars.payload1.toAirport

     })
  }
  ]]></dw:set-payload>
        </dw:transform-message>

        <logger message="#[payload]" level="INFO" doc:name="Logger"/>
    </flow>
</mule>

But this doesn't give me appropriate output. Please help.


问:
How to federate AD identities of a private domain to public services?

I am trying to connect AWS Cognito to my private AD users. I installed AD FS and AD FS Proxy, but now the question: as my domain is private (domain.local), I do not have publicly trusted SSL certificate. Therefore I can not connect Cognito to my Proxy to it.

答:
Although I am not versed in AWS Cognito, I would say this is expected behavior. I believe the principles for federation between an internal Active Directory domain to AWS Cognito via ADFS would be the same as an internal Active Directory domain to the Azure cloud / Office 365 via ADFS.  And that is, only domains which are publicly routable can get a publicly trusted SSL certificate.  Private  domains (like domain.local) are only ever able to get their own internal CA to trust them - but no public trust CAs will ever trust that private domain.  There is no way around that aspect.  To federate to Azure you must prove ownership of a domain, then verify it with a public trust authority, then create a required DNS TXT record, before you can add the domain to Office 365.  Without these steps completed, you cannot federate to anything.  There is a slight workaround for private domains in this scenario, but it would involve obtaining a publicly routable DNS domain which goes against the notion of what your trying to do with a quick test.  Just in case your interested, the workaround to federate an internal namespace to federate to public services is to:

Add a routable domain UPN suffix in Active Directory Domains and Trusts

Configure particular (or all) users with that routable UserPrincipleName

Synch the users to Azure / Office 365

Federate to the other public services

This is explained at the 29:05 mark in a Microsoft Office 365 Partner video titled: Office 365: Configuring DirSync and Single Sign On with ADFS - Part 1

Note:  To get a wider audience, I would remove the proxy tag and replace it with office365.


问:
How to use confirm in JavaScript with PHP
```<code>   <?php
 mysql_connect("localhost","root","");
 mysql_select_db("lastasignment");
if(isset($_GET['act'])){
 $nid=$_GET['i']; ?>
<script type="text/javascript">
 if(confirm("you want to delete "+" <?php echo $nid ?>")){
<?php $i=$_GET['i'];
mysql_query("delete from testings where id=$i");
 ?> ;
 }else {
alert("cancelled");
}
</script>
</code>```

The data in the table is deleted whether i click ok or cancel?

答:
If you are using a form you can do something like that:

```<code><form onsubmit="if (!confirm('Are you sure you want to delete this item?')) return false;">
    <input type="hidden" name="act" value="delete" />
    <button name="i" value="1">Delete</button>
</form>
</code>```

If you are using an anchor tag, you can use onclick:

```<code><a href="YOUR_URL" onclick="if (!confirm('Are you sure you want to delete this item?')) return false;">Click Me</a>
</code>```

And BTW, you should use GET for fetching things only, you should not use it for insert/update/delete. Use POST instead. The reason? for example, you don't want the user to access that link from his browser history, then you'll have a dupliacte entery / delete again / update again.

Body:
   <?php
 mysql_connect("localhost","root","");
 mysql_select_db("lastasignment");
if(isset($_GET['act'])){
 $nid=$_GET['i']; ?>

The data in the table is deleted whether i click ok or cancel?

Body:
If you are using a form you can do something like that:

<form onsubmit="if (!confirm('Are you sure you want to delete this item?')) return false;">
    <input type="hidden" name="act" value="delete" />
    <button name="i" value="1">Delete</button>
</form>

If you are using an anchor tag, you can use onclick:

<a href="YOUR_URL" onclick="if (!confirm('Are you sure you want to delete this item?')) return false;">Click Me</a>

And BTW, you should use GET for fetching things only, you should not use it for insert/update/delete. Use POST instead. The reason? for example, you don't want the user to access that link from his browser history, then you'll have a dupliacte entery / delete again / update again.


问:
best component / example code for an Outlook-style calendar in a C# windows forms program?
Are there any existing libraries or sample programs for an Outlook-style calendar component, to be used in a C# windows form program?</p>

答: Iirc from a previos project, ILOG have a component for this. I didn't use that one, so I can't comment on it - but the one I did use (Gantt) was exceptionally good. I was a very happy customer.

ContentLicense: CC BY-SA 2.5


问:
PHP json_encode($_POST) and mySQL issue
I am trying to json_encode($_POST) in PHP, but I have one small problem.

On my $_POST sometimes I get some encoded JSON as example below:

```<code>Array
(
    [module] => {"media":true}
)
</code>```

Where module contains a JSON string. My problem is when I use json_encode($POST); I get a result like this:

```<code>{"module":"{\"petMedia\":true}"}
</code>```

Trying to insert into mySQL JSON column, I get this error

```<code>Invalid JSON text: "Missing a comma or '}' after an object member.
</code>```

It's not possible for me to decode the string before because not always I get encoded JSON.

Thanks.

答:
A variation on a theme perhaps

```<code>/* emulate POST */
$_POST=array(
    'php'=>'fantastic',
    'javascript'=>'awesome',
    'asp'=>'awful',
    'module'=>json_encode( array( 'media' => true ) )
);

/* process the POST array and decode any json data within */
array_walk( $_POST, function( &$value ){
    $tmp=json_decode( $value );
    if( json_last_error() == 0 )$value=$tmp;
});

/* encode the POST data */
$encoded=json_encode( $_POST );
</code>```

Outputs:

```<code>{"php":"fantastic","javascript":"awesome","asp":"awful","module":{"media":true}}
</code>```

Title: PHP json_encode($_POST) and mySQL issue

Body:
I am trying to json_encode($_POST) in PHP, but I have one small problem.

On my $_POST sometimes I get some encoded JSON as example below:

Array
(
    [module] => {"media":true}
)

Where module contains a JSON string. My problem is when I use json_encode($POST); I get a result like this:

{"module":"{\"petMedia\":true}"}

Trying to insert into mySQL JSON column, I get this error

Invalid JSON text: "Missing a comma or '}' after an object member.

It's not possible for me to decode the string before because not always I get encoded JSON.

Thanks.

Body:
A variation on a theme perhaps

/* emulate POST */
$_POST=array(
    'php'=>'fantastic',
    'javascript'=>'awesome',
    'asp'=>'awful',
    'module'=>json_encode( array( 'media' => true ) )
);

/* process the POST array and decode any json data within */
array_walk( $_POST, function( &$value ){
    $tmp=json_decode( $value );
    if( json_last_error() == 0 )$value=$tmp;
});

/* encode the POST data */
$encoded=json_encode( $_POST );

Outputs:

{"php":"fantastic","javascript":"awesome","asp":"awful","module":{"media":true}}


问:
Selecting columns to insert into table with where condition
I am working on a project where I need to grab the img path from a backup table and insert it in to the image path column of a new table based on if the item names match up perfectly (as the id's vary).

This is what I tried, but getting an error that the items.prod_name column is not found:

MySQL

```<code>INSERT INTO items (img_path)
SELECT img_path
FROM items_backup
WHERE items.prod_name = items_backup.prod_name
</code>```

答:
You would seem to want an update, not an insert.  The syntax in MySQL is:

```<code>update items i join
       items_backup ib
       on i.prod_name = ib.prod_name
    set i.img_path = ib.img_path;
</code>```

Body:
I am working on a project where I need to grab the img path from a backup table and insert it in to the image path column of a new table based on if the item names match up perfectly (as the id's vary).

This is what I tried, but getting an error that the items.prod_name column is not found:

MySQL

INSERT INTO items (img_path)
SELECT img_path
FROM items_backup
WHERE items.prod_name = items_backup.prod_name

Body:
You would seem to want an update, not an insert.  The syntax in MySQL is:

update items i join
       items_backup ib
       on i.prod_name = ib.prod_name
    set i.img_path = ib.img_path;


问:
Problem with ASP.NET MVC 2 Routing
I have the following URL:

http://localhost/PagingController/ShowPage?pageNumber=3

When user clicks this link he must be redirected to the following URL:

http://localhost/MyController/ MyAction?pageNumber=3

How can I create a mapping rule for these URLs? I don't understand how to get pageNumber parameter with URL templates such as .../{controller}/{action}

Thanks.

答:
You don't have to define a route for it. If you use querystring, you can just get it in the action like this:</p>

```<code>public ActionResult MyAction(int pageNumber)
</code>```

Title: Problem with ASP.NET MVC 2 Routing

Body:
You don't have to define a route for it. If you use querystring, you can just get it in the action like this:

public ActionResult MyAction(int pageNumber)


问:
MySQL Markup all records on Select with same values (first one included)
Connected with MySQL Markup Records with Duplicates on Select. The difference is I want to markup not only actually duplicated records but all records with same values including first one.

```<code>id     name
--------------
1      John    # mark this
2      Peter
3      John    # this
4      David
5      John    # and this
</code>```

The approach proposed by @m-khalid-junaid https://stackoverflow.com/a/47728321/1056384

```<code>SELECT DISTINCT a.*,
CASE WHEN b.id IS NULL THEN 0 ELSE 1 end `duplicate`
FROM tab a
LEFT JOIN tab b ON a.name = b.name AND a.id > b.id
ORDER BY a.id
</code>```

It has one or two problems for me:

It not markups first occurrence of "duplicate" record in group.

It uses order by id (not sure if it depends) but I need to sort result in real complex query by different ways.

If it makes sense for query optimization, my task is a little bit more complex. Actually, I need to markup duplicates inside groups only:

```<code>id   group  name
--------------
1    1      John    # mark this (dups in group #1)
2    1      Peter
3    1      John    # mark this (dups in group #1)
4    2      David
5    2      John    # this is not (it's in group #2)
</code>```

答:
Looks like this works for me:

```<code>SELECT DISTINCT t.*,
       IF(t2.id IS NULL, 0, 1) AS is_duplicate
FROM tab t
LEFT JOIN tab t2 ON t.name = t2.name AND t.group = t2.group AND t.id <> t2.id
</code>```

http://sqlfiddle.com/#!9/d24012/16/0

Body:
Connected with MySQL Markup Records with Duplicates on Select. The difference is I want to markup not only actually duplicated records but all records with same values including first one.

id     name
--------------
1      John    # mark this
2      Peter
3      John    # this
4      David
5      John    # and this

The approach proposed by @m-khalid-junaid https://stackoverflow.com/a/47728321/1056384

SELECT DISTINCT a.*,
CASE WHEN b.id IS NULL THEN 0 ELSE 1 end `duplicate`
FROM tab a
LEFT JOIN tab b ON a.name = b.name AND a.id > b.id
ORDER BY a.id

It has one or two problems for me:

It not markups first occurrence of "duplicate" record in group.

It uses order by id (not sure if it depends) but I need to sort result in real complex query by different ways.

If it makes sense for query optimization, my task is a little bit more complex. Actually, I need to markup duplicates inside groups only:

id   group  name
--------------
1    1      John    # mark this (dups in group #1)
2    1      Peter
3    1      John    # mark this (dups in group #1)
4    2      David
5    2      John    # this is not (it's in group #2)

Body:
Looks like this works for me:

SELECT DISTINCT t.*,
       IF(t2.id IS NULL, 0, 1) AS is_duplicate
FROM tab t
LEFT JOIN tab t2 ON t.name = t2.name AND t.group = t2.group AND t.id <> t2.id

http://sqlfiddle.com/#!9/d24012/16/0


问:
how to upside down a text in python turtle.write() method?
nowadays I'm writing a program to fetch 4 poker cards from 52 poker cards randomly and I have to draw these pokers by python turtle module. Now here's my question: cause there's an upside-down number in pokers, just like this(the bottom right corner number)

at first I want to use this code to generate the numbers:

```<code>import turtle as do
def generate_digital(number, x, y, start_angle, size):
    '''
       this function generate '2-10'
       parameters:
       number: this is number you want to write
       x and y: this is the pen's initial location
       start_angle: the pen's initial direction
       size: the number's size
    '''
    do.penup()
    do.goto(x, y)
    do.pensize(30)
    do.setheading(start_angle)
    do.write(number, font=("Arial", size, "normal"))
</code>```

I want to use
do.settheading() to set the angle of the number, but I found that it didn't work! I can get a 5 but I can't get a upside-down 5 using the do.write() method......

Now, the only way myself can think of is to use this

```<code>def generate_photo_2(x, y, start_angle, size):
    '''
       this function generate a '2'
       parameters:
       just like last function
    '''
    do.penup()
    do.goto(x, y)
    do.pensize(3)
    do.setheading(start_angle)
    do.pendown()
    do.circle(-size, 200)
    do.fd(2 * size)
    do.left(45)
    do.fd(0.6 * size)
    do.left(90)
    do.fd(2 * size)
</code>```

code to 'draw' a number, and by setting the start angle, I can 'draw' a upside-side number 2, but it causes a lot of trouble, isn't it?

Could anybody tells me how to write() a upside-down number?
Thank you very much!!!

答:
turtle doesn't have function to display text upside down.

But turtle is built on top of tkinter module and Canvas widget which has method

```<code>create_text(x, y, text=.., angle=..., ...)
</code>```

Working example

```<code>import turtle

c = turtle.getcanvas()

item_id = c.create_text(0, 0, text='5', angle=180, font=("Arial", 30, "normal"))

turtle.mainloop() # run tkinter event loop
</code>```

Later you can change angle using item_id

```<code>c.itemconfig(item_id, angle=45)
</code>```

Effbot.org: Canvas in tkinter.

BTW: I found information that only the newest tkinter with Tk 8.6 has angle=.

You can check version

```<code>import tkinter

print(tkinter.TkVersion)
</code>```

Body:
nowadays I'm writing a program to fetch 4 poker cards from 52 poker cards randomly and I have to draw these pokers by python turtle module. Now here's my question: cause there's an upside-down number in pokers, just like this(the bottom right corner number)

at first I want to use this code to generate the numbers:

import turtle as do
def generate_digital(number, x, y, start_angle, size):
    '''
       this function generate '2-10'
       parameters:
       number: this is number you want to write
       x and y: this is the pen's initial location
       start_angle: the pen's initial direction
       size: the number's size
    '''
    do.penup()
    do.goto(x, y)
    do.pensize(30)
    do.setheading(start_angle)
    do.write(number, font=("Arial", size, "normal"))

I want to use
do.settheading() to set the angle of the number, but I found that it didn't work! I can get a 5 but I can't get a upside-down 5 using the do.write() method......

Now, the only way myself can think of is to use this

def generate_photo_2(x, y, start_angle, size):
    '''
       this function generate a '2'
       parameters:
       just like last function
    '''
    do.penup()
    do.goto(x, y)
    do.pensize(3)
    do.setheading(start_angle)
    do.pendown()
    do.circle(-size, 200)
    do.fd(2 * size)
    do.left(45)
    do.fd(0.6 * size)
    do.left(90)
    do.fd(2 * size)

code to 'draw' a number, and by setting the start angle, I can 'draw' a upside-side number 2, but it causes a lot of trouble, isn't it?

Could anybody tells me how to write() a upside-down number?
Thank you very much!!!

Body:
turtle doesn't have function to display text upside down.

But turtle is built on top of tkinter module and Canvas widget which has method

create_text(x, y, text=.., angle=..., ...)

Working example

import turtle

c = turtle.getcanvas()

item_id = c.create_text(0, 0, text='5', angle=180, font=("Arial", 30, "normal"))

turtle.mainloop() # run tkinter event loop

Later you can change angle using item_id

c.itemconfig(item_id, angle=45)

Effbot.org: Canvas in tkinter.

BTW: I found information that only the newest tkinter with Tk 8.6 has angle=.

You can check version

import tkinter

print(tkinter.TkVersion)


问:
How to add space between the Flex items in ReactJs?
This is the image of the code and the page.

The justifyconent attribute in the Containerr doesn't seem to work. Why are the 3 children elements stuck together with no space?

EDIT: I tried justifyContent too. (instead of JustifyContent as in the picture..)

答:
Keys for styles in ReactJs should be lower camel case.
In your case, you are using JustifyContent. Instead, it should justifyContent.

```<code>justifyContent : 'space-between'
</code>```

This should solve your problem.

Body:
Keys for styles in ReactJs should be lower camel case.
In your case, you are using JustifyContent. Instead, it should justifyContent.

justifyContent : 'space-between'

This should solve your problem.


问:
scroll to next element with same parent class
I have several divs with the class name "fullcontent".
In each div I have 2 elements: "fullcontent--prev" and "fullcontent--next".
On click on this elements I want to scroll to the next/previous fullcontent-div.

But I don't get this working with this:

https://jsfiddle.net/whgxauyd/1/

$(".fullcontent--prev").click(function() {
  $('html, body').animate({
      scrollTop: $('.fullcontent').nextAll().offset().top
  }, 1000, 'easeInOutSine');
});

$(".fullcontent--next").click(function() {
  $('html, body').animate({
      scrollTop: $('.fullcontent').nextAll().offset().top
  }, 1000, 'easeInOutSine');
});
```

<pre class="lang-css prettyprint-override"><code>.fullcontent {
  z-index: 900;
  width: 100%;
  height: 100vh;
  opacity: 0.5;
  font-size: 60px;
  color: black;
  position: relative;
  background-color: yellow;
  margin-bottom: 100px;

  &--prev {
    height: 25%;
    width: 100%;
    top: 0;
    left: 0;
    opacity: 0.5;
    position: absolute;
    background-color: red;
    cursor: pointer;
  }

  &--next {
    height: 75%;
    width: 100%;
    bottom: 0;
    left: 0;
    opacity: 0.55;
    position: absolute;
    background-color: green;
    cursor: pointer;
    }
}
</code>```

 1

 2

 3

 4

```

Where is the error?

答:
```<code>index = 1;
$('div.fullcontent').click(function(){
  $('html, body').animate({
      scrollTop: $('div.fullcontent:eq('+index+')').offset().top
  }, 1000, 'easeInOutSine');
  index++;
  if(index>3)
  index=0;
  console.log(index);
})
</code>```

Try this code you will get expected result

https://jsfiddle.net/y10dqh4q/

Body:
I have several divs with the class name "fullcontent".
In each div I have 2 elements: "fullcontent--prev" and "fullcontent--next".
On click on this elements I want to scroll to the next/previous fullcontent-div.

But I don't get this working with this:

https://jsfiddle.net/whgxauyd/1/

$(".fullcontent--prev").click(function() {
  $('html, body').animate({
      scrollTop: $('.fullcontent').nextAll().offset().top
  }, 1000, 'easeInOutSine');
});

$(".fullcontent--next").click(function() {
  $('html, body').animate({
      scrollTop: $('.fullcontent').nextAll().offset().top
  }, 1000, 'easeInOutSine');
});

.fullcontent {
  z-index: 900;
  width: 100%;
  height: 100vh;
  opacity: 0.5;
  font-size: 60px;
  color: black;
  position: relative;
  background-color: yellow;
  margin-bottom: 100px;

  &--prev {
    height: 25%;
    width: 100%;
    top: 0;
    left: 0;
    opacity: 0.5;
    position: absolute;
    background-color: red;
    cursor: pointer;
  }

  &--next {
    height: 75%;
    width: 100%;
    bottom: 0;
    left: 0;
    opacity: 0.55;
    position: absolute;
    background-color: green;
    cursor: pointer;
    }
}

 1

 2

 3

 4

Where is the error?

Body:
index = 1;
$('div.fullcontent').click(function(){
  $('html, body').animate({
      scrollTop: $('div.fullcontent:eq('+index+')').offset().top
  }, 1000, 'easeInOutSine');
  index++;
  if(index>3)
  index=0;
  console.log(index);
})

Try this code you will get expected result

https://jsfiddle.net/y10dqh4q/


问:
Angular translate Pipe could not be found
I have a component that uses the translateService, but it's not possible to translate items with the pipe on the Component Template HTML, i get following error:

The pipe 'translate' could not be found

app.module.ts

```<code>import {BrowserModule} from "@angular/platform-browser";
import {NgModule} from "@angular/core";
import {HttpModule, Http} from "@angular/http";
import {TranslateModule, TranslateLoader, TranslateStaticLoader} from 'ng2-translate';
import {AppComponent} from "./app.component";

@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
HttpModule,
TranslateModule.forRoot({
    provide: TranslateLoader,
    useFactory: (http: Http) => new TranslateStaticLoader(http, './assets/i18n', '.json'),
    deps: [Http]
   })
],
bootstrap: [AppComponent]
})
export class AppModule {
}
</code>```

booking.component.ts

```<code>import {Component, OnInit} from '@angular/core';
import {BookingComponent} from './booking.component';
import {TranslateService} from 'ng2-translate';

@Component({
   selector: 'app-booking',
   templateUrl: './booking.component.html',
   styleUrls: ['./booking.component.css']
})

export class BookingComponent implements OnInit {
  constructor(private translate: TranslateService
  ) {
    translate.setDefaultLang('de');
    translate.use('de');
};

ngOnInit() {
}
}
</code>```

booking.component.html

```<code><p>{{'TESTKEY' | translate }}</p>
</code>```

The translation with the service on the component works fine, but i need to translate also the html with pipe

答:
For those coming across this, here are the steps you need to do in a nutshell to fix the issue

Have the translate module logic along with translate loader and translateFactory present in the app.module.ts

```<code>    TranslateModule.forRoot({
        provide: TranslateLoader,
        useFactory: (http: Http) =>
        new TranslateStaticLoader(http, './assets/i18n', '.json'),
        deps: [Http]
       })
    ],`
</code>```

In your shared.module.ts (or any other module), import and export the Translate module.

i.e.: Translate module should be a part of both the import and export arrays. Most answers in SO and github mention importing the module but not exporting it.

```<code>    @NgModule({
     imports: [
       // other imported modules here
       TranslateModule
    ],
    exports: [
    // other exported modules here
    TranslateModule]`

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a component that uses the translateService, but it's not possible to translate items with the pipe on the Component Template HTML, i get following error:

The pipe 'translate' could not be found

app.module.ts

import {BrowserModule} from "@angular/platform-browser";
import {NgModule} from "@angular/core";
import {HttpModule, Http} from "@angular/http";
import {TranslateModule, TranslateLoader, TranslateStaticLoader} from 'ng2-translate';
import {AppComponent} from "./app.component";

@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
HttpModule,
TranslateModule.forRoot({
    provide: TranslateLoader,
    useFactory: (http: Http) => new TranslateStaticLoader(http, './assets/i18n', '.json'),
    deps: [Http]
   })
],
bootstrap: [AppComponent]
})
export class AppModule {
}

booking.component.ts

import {Component, OnInit} from '@angular/core';
import {BookingComponent} from './booking.component';
import {TranslateService} from 'ng2-translate';

@Component({
   selector: 'app-booking',
   templateUrl: './booking.component.html',
   styleUrls: ['./booking.component.css']
})

export class BookingComponent implements OnInit {
  constructor(private translate: TranslateService
  ) {
    translate.setDefaultLang('de');
    translate.use('de');
};

ngOnInit() {
}
}

booking.component.html

{{'TESTKEY' | translate }}

The translation with the service on the component works fine, but i need to translate also the html with pipe

Body:
For those coming across this, here are the steps you need to do in a nutshell to fix the issue

Have the translate module logic along with translate loader and translateFactory present in the app.module.ts

    TranslateModule.forRoot({
        provide: TranslateLoader,
        useFactory: (http: Http) =>
        new TranslateStaticLoader(http, './assets/i18n', '.json'),
        deps: [Http]
       })
    ],`

In your shared.module.ts (or any other module), import and export the Translate module.

i.e.: Translate module should be a part of both the import and export arrays. Most answers in SO and github mention importing the module but not exporting it.

    @NgModule({
     imports: [
       // other imported modules here
       TranslateModule
    ],
    exports: [
    // other exported modules here
    TranslateModule]`


问:
Set type for function parameters?
Is there a way to let a javascript function know that a certain parameter is of a certain type?

Being able to do something like this would be perfect:

```<code>function myFunction(Date myDate, String myString)
{
    //do stuff
}
</code>```

Thank you!

Update: Being that the answer is a resounding "no," if I want myDate to be treated as a date (in order to call date functions on it), I have to cast it as a date inside the function or set a new variable of type Date to it?

答:
Maybe a helper function like this. But if you see yourself using such syntax regularly, you should probably switch to TypeScript.

function check(caller_args, ...types) {
    if(!types.every((type, index) => {
        if(typeof type === 'string')
            return typeof caller_args[index] === type
        return caller_args[index] instanceof type;
    })) throw Error("Illegal argument given");
}

function abc(name, id, bla) {
   check(arguments, "string", "number", MyClass)
   // code
}
```

Title: Set type for function parameters?

Body:
Is there a way to let a javascript function know that a certain parameter is of a certain type?

Being able to do something like this would be perfect:

function myFunction(Date myDate, String myString)
{
    //do stuff
}

Thank you!

Update: Being that the answer is a resounding "no," if I want myDate to be treated as a date (in order to call date functions on it), I have to cast it as a date inside the function or set a new variable of type Date to it?


问:
Creating a CLI (Shell?) in Python
I am very newbie in Python but I have to implement for school a command line interpreter in Python language, but I am kinda lost in how to do that.

I have already read some tutorials and created a simple file called functions.py where i include some simple functions like this:

```<code>def delete(loc):
    if os.path.exists(loc) == True:
        os.remove(loc)
        print "Removed"
    else:
        print "File not exists"
</code>```

Now.. here is the thing.. in order to use this I must import it inside the python command interpreter, like...

```<code>import functions
functions.delete("file to delete")
</code>```

How can I make a Shell/CLI so instead of have to write all of this I can just write like:

```<code>delete file_name
</code>```

Thanks!

答: You might want to check my personal REPL for some inspiration. I wrote it during a tutorial series. Actual source may be found here. It probably does a few things you won't need... Still it could be a good read. :)</p>

Title: Creating a CLI (Shell?) in Python

Body:
I am very newbie in Python but I have to implement for school a command line interpreter in Python language, but I am kinda lost in how to do that.

I have already read some tutorials and created a simple file called functions.py where i include some simple functions like this:

def delete(loc):
    if os.path.exists(loc) == True:
        os.remove(loc)
        print "Removed"
    else:
        print "File not exists"

Now.. here is the thing.. in order to use this I must import it inside the python command interpreter, like...

import functions
functions.delete("file to delete")

How can I make a Shell/CLI so instead of have to write all of this I can just write like:

delete file_name

Thanks!


问:
Intel SGX Error: What does the 8207 error mean when I cannot load the enclave correct
I have made the following enclave & app loading the enclave:

https://github.com/pc-magas/myFirstEnclave/tree/run_fail

As you can see I load the wrong path of the enclave therefore the app fails to run as expected, when that happens in the example it returns the error:

SGX error code: 8207

Fail to initialize enclave.

But I cannot figure tour what does the 8207 error code means as far I can see I does not get mentioned over the error codes on documentation: https://software.intel.com/en-us/node/709252

So can you explain what does this error code means?

答:
8207 (decimal) is 200F (hex), and your link shows:

0x200F | SGX_ERROR_ENCLAVE_FILE_ACCESS          | Can’t open enclave file.
```

Which is what you'd expect when passing the wrong path.

Body:
8207 (decimal) is 200F (hex), and your link shows:

0x200F | SGX_ERROR_ENCLAVE_FILE_ACCESS          | Can’t open enclave file.

Which is what you'd expect when passing the wrong path.


问:
Unbuffered bidirectional data streaming with gRPC: how to get the size of the client-side buffer?
I am streaming data from a server to a client and I would like the server not to read and send more data than the client's buffer size.

Given:

```<code>service StreamService {
  rpc Stream(stream Buffer) returns (stream Buffer);
}

message Buffer {
  bytes data = 1;
}
</code>```

My client's program basically looks like:

```<code>func ReadFromServer(stream StreamService_StreamClient, buf []byte) (n int, err error) {
  // I actually don't need more than len(buf)...
  // How could I send len(buf) while stream is bidirectional...?
  buffer, err := stream.Recv()
  if err != nil {
     return 0,  err
  }
  n = copy(buf, buffer.Data)
  // buf could also be smaller than buffer.Data...
  return n, nil
}
</code>```

So how could I send len(buf) while the RPC's stream is bidirectional, i.e. the send direction is used by another independent stream of data? Note that I don't use client or server-side buffering to avoid loosing data when one of them is terminated (my data-source is an I/O).

答:
I think there's no built-in solution for that. The use-case looks little bit weird: why server must care about client's state at all? If it really needs to, you should extend your bidirectional stream: the client must request byte slices of a particular size (according to the own buffer size and other factors).

By the way, you may find useful message size limit settings GRPC client and server:
https://godoc.org/google.golang.org/grpc#MaxMsgSize https://godoc.org/google.golang.org/grpc#WithMaxMsgSize

Body:
I am streaming data from a server to a client and I would like the server not to read and send more data than the client's buffer size.

Given:

service StreamService {
  rpc Stream(stream Buffer) returns (stream Buffer);
}

message Buffer {
  bytes data = 1;
}

My client's program basically looks like:

func ReadFromServer(stream StreamService_StreamClient, buf []byte) (n int, err error) {
  // I actually don't need more than len(buf)...
  // How could I send len(buf) while stream is bidirectional...?
  buffer, err := stream.Recv()
  if err != nil {
     return 0,  err
  }
  n = copy(buf, buffer.Data)
  // buf could also be smaller than buffer.Data...
  return n, nil
}

So how could I send len(buf) while the RPC's stream is bidirectional, i.e. the send direction is used by another independent stream of data? Note that I don't use client or server-side buffering to avoid loosing data when one of them is terminated (my data-source is an I/O).


问:
Universal make-based build system design
I am aware of tools like CMake and GNU Autotools but I'm trying to write a universal build system myself, to use for my C and C++ projects. I'll briefly explain how it works and hopefully, someone can suggest either improvements or a better design altogether.

The build system proper lives in one of the project's subdirectories (I import it as a Git submodule). The project's root directory has a wrapper makefile that defines a couple of macros and includes the main makefile from said subdirectory. That does most of the work: it follows the directory organization scheme (i.e., it outputs libraries in lib, binaries in bin, etc.), it handles automatic dependencies for the source code and the DocBook documentation, and provides the de facto standard targets: all, test, clean, install, as well as others.

Here's what a wrapper makefile that builds two binaries, foo and bar, might look like:

```<code># foo-specific macros
FOO_SRC_FILES = foo1.c foo2.c foo3.c
FOO_OBJ_FILES = $(FOO_SRC_FILES:.c=.o)
FOO_BIN_FILE = foo

# bar-specific macros
BAR_SRC_FILES = bar1.c bar2.c
BAR_OBJ_FILES = $(BAR_SRC_FILES:.c=.o)
BAR_BIN_FILE = bar

# Inform the build system about them
SRC_FILES = $(FOO_SRC_FILES) $(BAR_SRC_FILES)
OBJ_FILES = R(BAR_OBJ_FILES) $(BAR_OBJ_FILES)
BIN_FILES = $(FOO_BIN_FILE) $(BAR_BIN_FILE)

# Only install the binaries. If I were building a library, I would instead
# select the "lib" and perhaps "include" directories.
INSTALL = bin
INSTALL_DIR = /usr/share

# Use the build system
include build/build.mk
</code>```

Now here's the problem. While build.mk can use pattern rules to create dependency and object files, there's only one OBJ_FILES and only one BIN_FILES. So if I put a pattern rule like the following in the build system that looks like this:

```<code>$(BIN_DIR)/$(BIN_FILES): $(OBJ_FILES:%=$(OBJ_DIR)/%) $(LIB_FILES:%=$(LIB_DIR)/%) | $(BIN_DIR)
    $(CC) $(LDFLAGS) -o $@ $(OBJ_FILES:%=$(OBJ_DIR)/%) -L $(LIB_DIR) $(LIB_FILES:lib%.a=-l %)
</code>```

then foo would depend on and link with everything that bar does and vice versa. So what I end up doing is asking the user to put these rules in the wrapper makefile, even though they feel like they belong in build.mk:

```<code>$(BIN_DIR)/$(FOO_BIN_FILE): $(FOO_OBJ_FILES:%=$(OBJ_DIR)/%) $(FOO_LIB_FILES:%=$(LIB_DIR)/%) | $(BIN_DIR)
    $(CC) $(LDFLAGS) -o $@ $(FOO_OBJ_FILES:%=$(OBJ_DIR)/%) -L $(LIB_DIR) $(FOO_LIB_FILES:lib%.a=-l %)

$(BIN_DIR)/$(BAR_BIN_FILE): $(BAR_OBJ_FILES:%=$(OBJ_DIR)/%) $(BAR_LIB_FILES:%=$(LIB_DIR)/%) | $(BIN_DIR)
    $(CC) $(LDFLAGS) -o $@ $(BAR_OBJ_FILES:%=$(OBJ_DIR)/%) -L $(LIB_DIR) $(BAR_LIB_FILES:lib%.a=-l %)
</code>```

The same issue applies to libraries as well, of course. The upside is that these rules can be copied and pasted almost verbatim; only the prefixes need to be changed (e.g., FOO or BAR).

Ideas to fix this include:

Asking the user to have separate wrapper makefiles for separate things (e.g., one for foo and another for bar) but that is just terrible.

Changing things up a little bit and then using m4 to do some preprocessing but I don't want to go through that unless a more elegant solution doesn't exist.

I would really appreciate some ideas.

PS: I know that the pattern matching expressions in the last two code samples can be replaced with text functions but those are GNU Make-specific. The style I used is more portable and is in fact on the list of additions for the next version of the POSIX standard.

答:
I have begin to develop a similar system for my own C projects, but the logic I use does rely on some features which I believe are specific to GNU Make.

The main idea is to use a combinaison of $(eval) and $(call), by defining the logic of the build system, and then applying to the project tree.
To do so, I have in each of my directories and subdirectories a piece of Makefile of the following form, which I name Srcs.mk:

```<code>SRC := foo.c foo_bar.c bar.c
TARGET := foo_bar
SRC_DIR := src
OBJ_DIR := obj
</code>```

I define a variable, which is in fact a macro, which is expanded with $(call) and then passed to $(eval). It's defined this way:

```<code>define get_local_variables
include Srcs.mk
$1SRC := $(SRC)
$1SRC_DIR := $(SRC_DIR)
$1OBJ_DIR := $(OBJ_DIR)
$1TARGET := $(TARGET)
TARGET :=
SRC :=
SRC_DIR :=
OBJ_DIR :=
</code>```

$(call get_local_variables, $(DIR)) will expand to the above, with $1 replaced by the content of $(DIR). Then it will be treated as a Makefile fragment by $(eval)

This way, I fill per-directory variables for each of my directory.
I have then a handful or other rules which use this variables, using the same principles.

```<code>### Macros ###
obj = $(patsubst %.c,$($1OBJ_DIR)/%.o,$($1SRC))

define standard_rules
$($1TARGET): $(obj)
    $$(LINK)

$(obj): $($1OBJ_DIR)/%.o:$($1SRC_DIR)/%.c | $($1OBJ_DIR)
    $$(COMPILE)

endef
</code>```

The variable are computed $(call), then expanded and read as makefile fragments by $(eval).

(I use static pattern rules but that it not intrinsic to the idea).

The whole idea is basically to define directories as a kind of namespace, with data attached to them, and then run function over them.
My actual system is a bit more complicated, but that the whole idea.

If you have a way to emulate $(eval) and $(call) (I think these are specific to GNU make, but not sure), you could try that approach.

You can also implement non recursive make this way, by adding a SUBDIRS variables in each directory and running recursively the same macro which is run on the current one. But it should been done carefully, not to mess it up with the order of expansion and evaluation in make.
So get_local_variables need to be evaluated before the rest of the macros are expanded.

(My project is visible on my Github account if you want to take a look, under make-build-system. But it is far from be complete enough^).

Be aware, though, that this is quite painful to debug when things go wrong. Make (at least, GNU) basically catch the error (when there is one) on the higher $(call) or $(eval) expansion.

Body:
I am aware of tools like CMake and GNU Autotools but I'm trying to write a universal build system myself, to use for my C and C++ projects. I'll briefly explain how it works and hopefully, someone can suggest either improvements or a better design altogether.

The build system proper lives in one of the project's subdirectories (I import it as a Git submodule). The project's root directory has a wrapper makefile that defines a couple of macros and includes the main makefile from said subdirectory. That does most of the work: it follows the directory organization scheme (i.e., it outputs libraries in lib, binaries in bin, etc.), it handles automatic dependencies for the source code and the DocBook documentation, and provides the de facto standard targets: all, test, clean, install, as well as others.

Here's what a wrapper makefile that builds two binaries, foo and bar, might look like:

# foo-specific macros
FOO_SRC_FILES = foo1.c foo2.c foo3.c
FOO_OBJ_FILES = $(FOO_SRC_FILES:.c=.o)
FOO_BIN_FILE = foo

# bar-specific macros
BAR_SRC_FILES = bar1.c bar2.c
BAR_OBJ_FILES = $(BAR_SRC_FILES:.c=.o)
BAR_BIN_FILE = bar

# Inform the build system about them
SRC_FILES = $(FOO_SRC_FILES) $(BAR_SRC_FILES)
OBJ_FILES = R(BAR_OBJ_FILES) $(BAR_OBJ_FILES)
BIN_FILES = $(FOO_BIN_FILE) $(BAR_BIN_FILE)

# Only install the binaries. If I were building a library, I would instead
# select the "lib" and perhaps "include" directories.
INSTALL = bin
INSTALL_DIR = /usr/share

# Use the build system
include build/build.mk

Now here's the problem. While build.mk can use pattern rules to create dependency and object files, there's only one OBJ_FILES and only one BIN_FILES. So if I put a pattern rule like the following in the build system that looks like this:

$(BIN_DIR)/$(BIN_FILES): $(OBJ_FILES:%=$(OBJ_DIR)/%) $(LIB_FILES:%=$(LIB_DIR)/%) | $(BIN_DIR)
    $(CC) $(LDFLAGS) -o $@ $(OBJ_FILES:%=$(OBJ_DIR)/%) -L $(LIB_DIR) $(LIB_FILES:lib%.a=-l %)

then foo would depend on and link with everything that bar does and vice versa. So what I end up doing is asking the user to put these rules in the wrapper makefile, even though they feel like they belong in build.mk:

$(BIN_DIR)/$(FOO_BIN_FILE): $(FOO_OBJ_FILES:%=$(OBJ_DIR)/%) $(FOO_LIB_FILES:%=$(LIB_DIR)/%) | $(BIN_DIR)
    $(CC) $(LDFLAGS) -o $@ $(FOO_OBJ_FILES:%=$(OBJ_DIR)/%) -L $(LIB_DIR) $(FOO_LIB_FILES:lib%.a=-l %)

$(BIN_DIR)/$(BAR_BIN_FILE): $(BAR_OBJ_FILES:%=$(OBJ_DIR)/%) $(BAR_LIB_FILES:%=$(LIB_DIR)/%) | $(BIN_DIR)
    $(CC) $(LDFLAGS) -o $@ $(BAR_OBJ_FILES:%=$(OBJ_DIR)/%) -L $(LIB_DIR) $(BAR_LIB_FILES:lib%.a=-l %)

The same issue applies to libraries as well, of course. The upside is that these rules can be copied and pasted almost verbatim; only the prefixes need to be changed (e.g., FOO or BAR).

Ideas to fix this include:

Asking the user to have separate wrapper makefiles for separate things (e.g., one for foo and another for bar) but that is just terrible.

Changing things up a little bit and then using m4 to do some preprocessing but I don't want to go through that unless a more elegant solution doesn't exist.

I would really appreciate some ideas.

PS: I know that the pattern matching expressions in the last two code samples can be replaced with text functions but those are GNU Make-specific. The style I used is more portable and is in fact on the list of additions for the next version of the POSIX standard.

Body:
I have begin to develop a similar system for my own C projects, but the logic I use does rely on some features which I believe are specific to GNU Make.

The main idea is to use a combinaison of $(eval) and $(call), by defining the logic of the build system, and then applying to the project tree.
To do so, I have in each of my directories and subdirectories a piece of Makefile of the following form, which I name Srcs.mk:

SRC := foo.c foo_bar.c bar.c
TARGET := foo_bar
SRC_DIR := src
OBJ_DIR := obj

I define a variable, which is in fact a macro, which is expanded with $(call) and then passed to $(eval). It's defined this way:

define get_local_variables
include Srcs.mk
$1SRC := $(SRC)
$1SRC_DIR := $(SRC_DIR)
$1OBJ_DIR := $(OBJ_DIR)
$1TARGET := $(TARGET)
TARGET :=
SRC :=
SRC_DIR :=
OBJ_DIR :=

$(call get_local_variables, $(DIR)) will expand to the above, with $1 replaced by the content of $(DIR). Then it will be treated as a Makefile fragment by $(eval)

This way, I fill per-directory variables for each of my directory.
I have then a handful or other rules which use this variables, using the same principles.

### Macros ###
obj = $(patsubst %.c,$($1OBJ_DIR)/%.o,$($1SRC))

define standard_rules
$($1TARGET): $(obj)
    $$(LINK)

$(obj): $($1OBJ_DIR)/%.o:$($1SRC_DIR)/%.c | $($1OBJ_DIR)
    $$(COMPILE)

endef

The variable are computed $(call), then expanded and read as makefile fragments by $(eval).

(I use static pattern rules but that it not intrinsic to the idea).

The whole idea is basically to define directories as a kind of namespace, with data attached to them, and then run function over them.
My actual system is a bit more complicated, but that the whole idea.

If you have a way to emulate $(eval) and $(call) (I think these are specific to GNU make, but not sure), you could try that approach.

You can also implement non recursive make this way, by adding a SUBDIRS variables in each directory and running recursively the same macro which is run on the current one. But it should been done carefully, not to mess it up with the order of expansion and evaluation in make.
So get_local_variables need to be evaluated before the rest of the macros are expanded.

(My project is visible on my Github account if you want to take a look, under make-build-system. But it is far from be complete enough^).

Be aware, though, that this is quite painful to debug when things go wrong. Make (at least, GNU) basically catch the error (when there is one) on the higher $(call) or $(eval) expansion.


问:
How to use create-react-app to develop multiple pages?
When creating an app with create-react-app,there is only one index.html,does that means React can only handle one SPA at a time? What if I want to develop multiple pages? Should I create another SPA with create-react-app and then put them together after building each of them? </p>

答:
Update:

Parceljs can do that. here is docs.

You can use Parcel instead of Webpack (which being used in create-react-app) and it provide you zero config environment to develop web apps (using react or anything else).

Having multiple pages (instead of SPA) is not what most React environments had in mind [before - see update above].

You can have different page URL's using react-router or similar client side routing solutions.

If the concern is bundle size, there are solutions using webpack or parcel to lazy load each bundle whenever they needed or cache bundle (using service workers) and so on (Tree shaking, ...). (check Code Splitting in React Docs)

Other concern I might have in my brain is SEO, in this case you may find Isomorphic app (react server side rendering) useful which initialize first view of requested URL HTML and sends it to client, then client will load react and react will take control of UI. This will help Google (or other search engines) find your URLs fast and user experience in transitions between pages will remain seamless.


问:
JPA: Unidirectional one-to-many relationship with composite semi-shared primary key without join table
JPA:

How can I model the following in JPA:

a uni-directional one-to-many relationship

where the owning entity has a single-column application-determined primary key AND

where the child entity has a composite primary key AND

where one part of the child's primary key is the parent's primary key AND

avoiding JPA generating a join table.

Any ideas?

答:
I figured out myself how to do this.

You need to annotate the foreign key in the owning entity with

```<code>@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "myId", referencedColumnName = "parentId")
private List<ChildEntity> childEntity;
</code>```

The primary key part in the child entity that is also the foreign key referencing the owning entity must not be annotated as being a foreign key, so e.g.:

```<code>@Id
private String parentId;
</code>```

The usual rules concerning composite primary keys apply for the child class (primary key class annotated with @Embeddable etc.)

As user DN1 commented, the @JoinColumn annotation must be used, but it must be specified at the foreign reference in the owning class.

For some reason, you also must not use @PrimaryKeyJoinColumn instead of @JoinColumn, otherwise JPA will generate join tables.

Another challenge would be that the owning class's primary is also composite, but I haven't tried that.

Body:
I figured out myself how to do this.

You need to annotate the foreign key in the owning entity with

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "myId", referencedColumnName = "parentId")
private List<ChildEntity> childEntity;

The primary key part in the child entity that is also the foreign key referencing the owning entity must not be annotated as being a foreign key, so e.g.:

@Id
private String parentId;

The usual rules concerning composite primary keys apply for the child class (primary key class annotated with @Embeddable etc.)

As user DN1 commented, the @JoinColumn annotation must be used, but it must be specified at the foreign reference in the owning class.

For some reason, you also must not use @PrimaryKeyJoinColumn instead of @JoinColumn, otherwise JPA will generate join tables.

Another challenge would be that the owning class's primary is also composite, but I haven't tried that.


问:
https PHP/MySql webservice with ios instagram login
I'm trying to wrap my mind around something. I want to create a web service that accesses a database from an ios/ android app. Now I want the user to be able to log into the app through the Instagram API.

I'm a bit confused as in how they tie together. Obviously step one is to login with Instagram. What do I do then? I would like to save this user information I receive (let's say at least the username/ID) to the database with some other info that don't come from Instagram, like the location. All that in a secure way. can i use the instagram token for this? I'm a bit stuck on this process...

答:
After you complete the step 3 Instagram Autorization, which is pretty simple and i wont talk about it since you question is how to integrate Instagram data with you database, you should receive the following json:

```<code>{
    "access_token": "fb2e77d.47a0479900504cb3ab4a1f626d174d2d",
    "user": {
        "id": "1574083",
        "username": "snoopdogg",
        "full_name": "Snoop Dogg",
        "profile_picture": "..."
    }
}
</code>```

What you do with the data is a matter of architeture:

1) You user may authorize through instagram or regular username/password

Create a user table that has both password field and instagram user_id:

Your user table might be like:

```<code>CREATE TABLE users (
    id INT AUTO_INCREMENT NOT NULL ,
    username VARCHAR(255) NOT NULL,
    password VARCHAR(255) DEFAULT NULL,
    instagram_userid INT DEFAULT NULL,
    instagram_accesstoken VARCHAR(255) DEFAULT NULL,
    PRIMARY KEY(id)
);
</code>```

Anytime a user authenticates through Instagram you should:

Look for you uses table for a row with the same instagram_userid returned by instagram api.

If the instagram_userid already exists, you should authenticate you user in YOUR application now (for example, using SESSIONS/COOKIES, i.e. the usual way you have done your whole life).

If the instagram_userid doesnt exist, you should create a user row, with the username returned by Instagram API. Also authenticate this user with SESSION.

2)Instagram is your only user choice for authenticating

You should then just create a user table that is only a mirror for instagram api return. You can treat instagram_userid as your primary key:

```<code>CREATE TABLE users (
    username VARCHAR(255) NOT NULL,
    instagram_userid INT DEFAULT NULL,
    instagram_accesstoken VARCHAR(255) DEFAULT NULL,
    PRIMARY KEY(instagram_userid)
 );
</code>```

Anytime a user authenticates throught Instagram API, you should search in you user table for a row with the same id as returned by Instagram API.

If the row exists, authenticate that user in your application.

If the row doesnt exist, create it and authenticate the user.

Account merging

If your application handles both username/passoword authentication and  maybe others authentication providers , you should expect that a user might forget that he registered through you app with lets way Instagram Auth, and try to autenticate through username/password. If this happens, you might provide a way to merge the accounts, instead of duplicating it. For example, if the user Instagram email exists in your database as a username, you should update this row with instagram api data, instead of assuming its a new account. In this way, now your user can authenticate both with usuername/password and Instagram.

Access token

The instagram access token is stored, but not used. Why? Because it would be used for fetching instagram data, like user's posts, friends list, etc. If you want to do it, you should not assume the token is valid, because it might expire, so you should handle token expiration and provide a way to the user authenticate again.

Body:
After you complete the step 3 Instagram Autorization, which is pretty simple and i wont talk about it since you question is how to integrate Instagram data with you database, you should receive the following json:

{
    "access_token": "fb2e77d.47a0479900504cb3ab4a1f626d174d2d",
    "user": {
        "id": "1574083",
        "username": "snoopdogg",
        "full_name": "Snoop Dogg",
        "profile_picture": "..."
    }
}

What you do with the data is a matter of architeture:

1) You user may authorize through instagram or regular username/password

Create a user table that has both password field and instagram user_id:

Your user table might be like:

CREATE TABLE users (
    id INT AUTO_INCREMENT NOT NULL ,
    username VARCHAR(255) NOT NULL,
    password VARCHAR(255) DEFAULT NULL,
    instagram_userid INT DEFAULT NULL,
    instagram_accesstoken VARCHAR(255) DEFAULT NULL,
    PRIMARY KEY(id)
);

Anytime a user authenticates through Instagram you should:

Look for you uses table for a row with the same instagram_userid returned by instagram api.

If the instagram_userid already exists, you should authenticate you user in YOUR application now (for example, using SESSIONS/COOKIES, i.e. the usual way you have done your whole life).

If the instagram_userid doesnt exist, you should create a user row, with the username returned by Instagram API. Also authenticate this user with SESSION.

2)Instagram is your only user choice for authenticating

You should then just create a user table that is only a mirror for instagram api return. You can treat instagram_userid as your primary key:

CREATE TABLE users (
    username VARCHAR(255) NOT NULL,
    instagram_userid INT DEFAULT NULL,
    instagram_accesstoken VARCHAR(255) DEFAULT NULL,
    PRIMARY KEY(instagram_userid)
 );

Anytime a user authenticates throught Instagram API, you should search in you user table for a row with the same id as returned by Instagram API.

If the row exists, authenticate that user in your application.

If the row doesnt exist, create it and authenticate the user.

Account merging

If your application handles both username/passoword authentication and  maybe others authentication providers , you should expect that a user might forget that he registered through you app with lets way Instagram Auth, and try to autenticate through username/password. If this happens, you might provide a way to merge the accounts, instead of duplicating it. For example, if the user Instagram email exists in your database as a username, you should update this row with instagram api data, instead of assuming its a new account. In this way, now your user can authenticate both with usuername/password and Instagram.

Access token

The instagram access token is stored, but not used. Why? Because it would be used for fetching instagram data, like user's posts, friends list, etc. If you want to do it, you should not assume the token is valid, because it might expire, so you should handle token expiration and provide a way to the user authenticate again.


问:
Use pipl with Node.js
I am trying to use pipl with Node.js. I have written the following code:

```<code>router.post('/httpOnly/enrich/pipl', (req, res) => {
    var pipl = require('pipl')('BUSINESS-PREMIUM-DEMO-xyozhmgkc57085z7...');
    pipl.search.query('json', {"email": "softtimur@gmail.com"}, function(err, data) {
        console.log(data);
        res.json(data)
    });
})
</code>```

However, it gave an error:

```<code>index.js POST /httpOnly/enrich/pipl
http://api.pipl.com/search/v4/
/.../node_modules/pipl/lib/inherits.js:32
                    return callback(err, JSON.parse(body) || body);
                           ^

TypeError: callback is not a function
    at Request._callback (/.../node_modules/pipl/lib/inherits.js:32:28)
    at Request.self.callback (/.../node_modules/request/request.js:123:22)
    at emitTwo (events.js:125:13)
    at Request.emit (events.js:213:7)
    at Request.<anonymous> (/.../node_modules/request/request.js:893:14)
    at emitOne (events.js:120:20)
    at Request.emit (events.js:210:7)
    at IncomingMessage.<anonymous> (/.../node_modules/request/request.js:844:12)
    at emitNone (events.js:110:20)
    at IncomingMessage.emit (events.js:207:7)
    at endReadableNT (_stream_readable.js:1059:12)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)
</code>```

Does anyone know what's wrong?

答:
From the documentation it looks like the syntax is:

```<code>pipl.search.query({"email": "softtimur@gmail.com"}, function(err, data) {
    console.log(data);
    res.json(data)
});
</code>```

Without the 'json' string at the beginning. I think the signature was changed without the documentation on npm being updated.

Check this commit too.

Title: Use pipl with Node.js

Body:
I am trying to use pipl with Node.js. I have written the following code:

router.post('/httpOnly/enrich/pipl', (req, res) => {
    var pipl = require('pipl')('BUSINESS-PREMIUM-DEMO-xyozhmgkc57085z7...');
    pipl.search.query('json', {"email": "softtimur@gmail.com"}, function(err, data) {
        console.log(data);
        res.json(data)
    });
})

However, it gave an error:

index.js POST /httpOnly/enrich/pipl
http://api.pipl.com/search/v4/
/.../node_modules/pipl/lib/inherits.js:32
                    return callback(err, JSON.parse(body) || body);
                           ^

TypeError: callback is not a function
    at Request._callback (/.../node_modules/pipl/lib/inherits.js:32:28)
    at Request.self.callback (/.../node_modules/request/request.js:123:22)
    at emitTwo (events.js:125:13)
    at Request.emit (events.js:213:7)
    at Request.<anonymous> (/.../node_modules/request/request.js:893:14)
    at emitOne (events.js:120:20)
    at Request.emit (events.js:210:7)
    at IncomingMessage.<anonymous> (/.../node_modules/request/request.js:844:12)
    at emitNone (events.js:110:20)
    at IncomingMessage.emit (events.js:207:7)
    at endReadableNT (_stream_readable.js:1059:12)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)

Does anyone know what's wrong?

Body:
From the documentation it looks like the syntax is:

pipl.search.query({"email": "softtimur@gmail.com"}, function(err, data) {
    console.log(data);
    res.json(data)
});

Without the 'json' string at the beginning. I think the signature was changed without the documentation on npm being updated.

Check this commit too.


问:
Binding project inconsistent accessibility on inner classes but can't get transform syntax right
I've been trying to create a binding project for this token auto complete text view project on GitHub (https://github.com/mattwhetton/TokenAutoComplete). I'm basically trying to port it to us in Xamarin / Mono (C#)

I've been immediately getting the following error:

```<code>Inconsistent accessibility: parameter type 'Com.Tokenautocomplete.TokenCompleteTextView.TokenImageSpan' is less accessible than method 'Com.Tokenautocomplete.TokenCompleteTextView.TokenTextWatcher.RemoveToken(Com.Tokenautocomplete.TokenCompleteTextView.TokenImageSpan, Android.Text.IEditable)'
</code>```

I understand the error and tried to add a transform to make the TokenImageSpan inner class more accessible, but I just cant seem to get the syntax rioght. I've tried the 2 variations below:

```<code><attr path="/api/package[@name='Com.Tokenautocomplete']/class[@name='TokenImageSpan']/class[@name='TokenImageSpan']"
                name="visibility">public</attr>

<attr path="/api/package[@name='Com.Tokenautocomplete.TokenCompleteTextView']/class[@name='TokenImageSpan']"
                name="visibility">public</attr>
</code>```

But neither seems to work, both just give me the following errors:

```<code>BINDINGSGENERATOR : warning BG8A04: <attr path="/api/package[@name='Com.Tokenautocomplete.TokenCompleteTextView']/class[@name='TokenImageSpan']"/> matched no nodes.

BINDINGSGENERATOR : warning BG8A04: <attr path="/api/package[@name='Com.Tokenautocomplete']/class[@name='TokenImageSpan']/class[@name='TokenImageSpan']"/> matched no nodes.
</code>```

I'm guessing (probably incorrectly) that its something to do with them being nested classes?!

答:
Solution:

add in Metadata.xml string

```<code><attr path="/api/package[@name='com.tokenautocomplete']/class[@name='TokenCompleteTextV ew.TokenImageSpan']" name="visibility">public</attr>
</code>```

Body:
I've been trying to create a binding project for this token auto complete text view project on GitHub (https://github.com/mattwhetton/TokenAutoComplete). I'm basically trying to port it to us in Xamarin / Mono (C#)

I've been immediately getting the following error:

Inconsistent accessibility: parameter type 'Com.Tokenautocomplete.TokenCompleteTextView.TokenImageSpan' is less accessible than method 'Com.Tokenautocomplete.TokenCompleteTextView.TokenTextWatcher.RemoveToken(Com.Tokenautocomplete.TokenCompleteTextView.TokenImageSpan, Android.Text.IEditable)'

I understand the error and tried to add a transform to make the TokenImageSpan inner class more accessible, but I just cant seem to get the syntax rioght. I've tried the 2 variations below:

<attr path="/api/package[@name='Com.Tokenautocomplete']/class[@name='TokenImageSpan']/class[@name='TokenImageSpan']"
                name="visibility">public</attr>

<attr path="/api/package[@name='Com.Tokenautocomplete.TokenCompleteTextView']/class[@name='TokenImageSpan']"
                name="visibility">public</attr>

But neither seems to work, both just give me the following errors:

BINDINGSGENERATOR : warning BG8A04: <attr path="/api/package[@name='Com.Tokenautocomplete.TokenCompleteTextView']/class[@name='TokenImageSpan']"/> matched no nodes.

BINDINGSGENERATOR : warning BG8A04: <attr path="/api/package[@name='Com.Tokenautocomplete']/class[@name='TokenImageSpan']/class[@name='TokenImageSpan']"/> matched no nodes.

I'm guessing (probably incorrectly) that its something to do with them being nested classes?!

Body:
Solution:

add in Metadata.xml string

<attr path="/api/package[@name='com.tokenautocomplete']/class[@name='TokenCompleteTextV ew.TokenImageSpan']" name="visibility">public</attr>


问:
Select returning empty query
I'm trying to select data where by acc_id

What I get in my localhost: []

However, when I set a specific acc_id i get the correct row is there something in my syntax?

```<code><?php

header('Access-Control-Allow-Origin: *');

// Define database connection parameters
$hn      = 'localhost';
$un      = 'root';
$pwd     = '';
$db      = 'ringabell';
$cs      = 'utf8';

// Set up the PDO parameters
$dsn  = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
$opt  = array(
                    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
                    PDO::ATTR_EMULATE_PREPARES   => false,
                   );
// Create a PDO instance (connect to the database)
$pdo  = new PDO($dsn, $un, $pwd, $opt);
$data = array();

// Attempt to query database table and retrieve data
try {
        $acc_id = $pdo->prepare('SELECT acc_id FROM account_info');
        $stmt = $pdo->prepare('SELECT p_fname, p_lname, p_condition FROM patient_info WHERE acc_id = "$acc_id"');
        $stmt->execute([$acc_id]);
        while($row = $stmt->fetch(PDO::FETCH_ASSOC))
        {
            // Assign each row of data to associative array
            $data[] = $row;
        }

  // Return data as JSON
  echo json_encode($data);
  }
 catch(PDOException $e)
{
  echo $e->getMessage();
}
?>
</code>```

答:
It seems like you want to use the prepared statement but instead executing your query instantly. If you want to bind the value to your query use something like this:

```<code>$acc_id = // get the $acc_id value from somewhere you want
$stmt = $pdo->prepare('SELECT p_fname, p_lname, p_condition FROM patient_info WHERE acc_id = ?');
$stmt->execute([$acc_id]);
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
     // Assign each row of data to associative array
     $data[] = $row;
}
</code>```

Example with using a placeholder

Instead of executing your statement with the array of params, you could also use the bindValue() or the bindParam() method:

```<code>$stmt = $pdo->prepare('SELECT p_fname, p_lname, p_condition FROM patient_info WHERE acc_id = :acc_id');
$stmt->bindValue(':acc_id', $acc_id);
$stmt->execute();
// everything else works as previous
</code>```

The difference between these two methods is written in docs:

bindValue():

Binds a value to a corresponding named or question mark placeholder in the SQL statement that was used to prepare the statement.

bindParam():

Binds a PHP variable to a corresponding named or question mark placeholder in the SQL statement that was used to prepare the statement. Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.

Title: Select returning empty query

Body:
I'm trying to select data where by acc_id

What I get in my localhost: []

However, when I set a specific acc_id i get the correct row is there something in my syntax?

<?php

header('Access-Control-Allow-Origin: *');

// Define database connection parameters
$hn      = 'localhost';
$un      = 'root';
$pwd     = '';
$db      = 'ringabell';
$cs      = 'utf8';

// Set up the PDO parameters
$dsn  = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
$opt  = array(
                    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
                    PDO::ATTR_EMULATE_PREPARES   => false,
                   );
// Create a PDO instance (connect to the database)
$pdo  = new PDO($dsn, $un, $pwd, $opt);
$data = array();

// Attempt to query database table and retrieve data
try {
        $acc_id = $pdo->prepare('SELECT acc_id FROM account_info');
        $stmt = $pdo->prepare('SELECT p_fname, p_lname, p_condition FROM patient_info WHERE acc_id = "$acc_id"');
        $stmt->execute([$acc_id]);
        while($row = $stmt->fetch(PDO::FETCH_ASSOC))
        {
            // Assign each row of data to associative array
            $data[] = $row;
        }

  // Return data as JSON
  echo json_encode($data);
  }
 catch(PDOException $e)
{
  echo $e->getMessage();
}
?>

Body:
It seems like you want to use the prepared statement but instead executing your query instantly. If you want to bind the value to your query use something like this:

$acc_id = // get the $acc_id value from somewhere you want
$stmt = $pdo->prepare('SELECT p_fname, p_lname, p_condition FROM patient_info WHERE acc_id = ?');
$stmt->execute([$acc_id]);
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
     // Assign each row of data to associative array
     $data[] = $row;
}

Example with using a placeholder

Instead of executing your statement with the array of params, you could also use the bindValue() or the bindParam() method:

$stmt = $pdo->prepare('SELECT p_fname, p_lname, p_condition FROM patient_info WHERE acc_id = :acc_id');
$stmt->bindValue(':acc_id', $acc_id);
$stmt->execute();
// everything else works as previous

The difference between these two methods is written in docs:

bindValue():

Binds a value to a corresponding named or question mark placeholder in the SQL statement that was used to prepare the statement.

bindParam():

Binds a PHP variable to a corresponding named or question mark placeholder in the SQL statement that was used to prepare the statement. Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.


问:
How to restart Java method after termination
I'm new to Java and thought I would make one of the classic Username and Password validation programs which I have successfully made with no obvious bugs, however I would like the program to essentially restart the input if the user enters the in-correct information. How would I go about restarting the program successfully each time the users enters wrong information?

Code below:

```<code>import java.util.Scanner;
public class UserPass {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        String user; //Creating user-name variable.
        String pass; //Creating password variable.

        System.out.println("Enter username here: "); //Message to tell user to input the user-name.
        user = input.nextLine(); //Taking the users user-name input.

        System.out.println("Enter the password here: "); //Message to tell user to input the password.
        pass = input.nextLine(); //Taking the users password input.

        //Validating the users User-name and password input.
        if(user.equals("Shane") && (pass.equals("Temple"))) {
            System.out.println("Correct!"); //If the User-name and password are both correct then a message will tell the user that they are correct.
        }

        else {
            System.out.println("The Usernname or Password that you have entered was in-correct"); //If above conditions are not met then message will tell the user that they have entered the wrong user-name or password
        }
    }

}
</code>```

I know this is extremely basic as I said I'm very new to Java (2 hours ago new).

I thought of calling the "main" method inside the else condition statement however I heard It's bas practice to use the "main" method any more times than when the program first starts.

Thanks in advance :)

答:
I hope this is what you wanted.</p>

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

public class UserPass {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        String user; //Creating user-name variable.
        String pass; //Creating password variable.
        boolean isValidUser = false;

        while(!isValidUser) {
            System.out.println("Enter username here: "); //Message to tell user to input the user-name.
            user = input.nextLine(); //Taking the users user-name input.

            System.out.println("Enter the password here: "); //Message to tell user to input the password.
            pass = input.nextLine(); //Taking the users password input.

            //Validating the users User-name and password input.
            if(user.equals("Shane") && (pass.equals("Temple"))) {
                System.out.println("Correct!");
                isValidUser = true;
            }
            else {
                System.out.println("The Usernname or Password that you have entered was in-correct");
                isValidUser = false;
            }
        }
    }
}
</code>```

Body:
I'm new to Java and thought I would make one of the classic Username and Password validation programs which I have successfully made with no obvious bugs, however I would like the program to essentially restart the input if the user enters the in-correct information. How would I go about restarting the program successfully each time the users enters wrong information?

Code below:

import java.util.Scanner;
public class UserPass {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        String user; //Creating user-name variable.
        String pass; //Creating password variable.

        System.out.println("Enter username here: "); //Message to tell user to input the user-name.
        user = input.nextLine(); //Taking the users user-name input.

        System.out.println("Enter the password here: "); //Message to tell user to input the password.
        pass = input.nextLine(); //Taking the users password input.

        //Validating the users User-name and password input.
        if(user.equals("Shane") && (pass.equals("Temple"))) {
            System.out.println("Correct!"); //If the User-name and password are both correct then a message will tell the user that they are correct.
        }

        else {
            System.out.println("The Usernname or Password that you have entered was in-correct"); //If above conditions are not met then message will tell the user that they have entered the wrong user-name or password
        }
    }

}

I know this is extremely basic as I said I'm very new to Java (2 hours ago new).

I thought of calling the "main" method inside the else condition statement however I heard It's bas practice to use the "main" method any more times than when the program first starts.

Thanks in advance :)

Body:
I hope this is what you wanted.

import java.util.Scanner;

public class UserPass {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        String user; //Creating user-name variable.
        String pass; //Creating password variable.
        boolean isValidUser = false;

        while(!isValidUser) {
            System.out.println("Enter username here: "); //Message to tell user to input the user-name.
            user = input.nextLine(); //Taking the users user-name input.

            System.out.println("Enter the password here: "); //Message to tell user to input the password.
            pass = input.nextLine(); //Taking the users password input.

            //Validating the users User-name and password input.
            if(user.equals("Shane") && (pass.equals("Temple"))) {
                System.out.println("Correct!");
                isValidUser = true;
            }
            else {
                System.out.println("The Usernname or Password that you have entered was in-correct");
                isValidUser = false;
            }
        }
    }
}


问:
Find the position of a specific number that appear first in the list [python]
So I want to find a number that appears more than once in the list. I want the position of the first one.

Example: Say I want 3

```<code>     s = [1,2,3,4,5,3,9,8]  => s[2] appears first
</code>```

答:
Yet another way of doing it:</p>

```<code>from operator import countOf

def multindex(seq):
    """ find index of first value occurring more than once
        in a sequence, else raise ValueError if there aren't any
    """
    for i,v in enumerate(seq):
        if countOf(seq, v) > 1:
            return i
    else:
        raise ValueError

print 's[{}] is first value in the list occurring more than once'.format(multindex(s))
# s[2] is first value in the list occurring more than once
</code>```

Body:
So I want to find a number that appears more than once in the list. I want the position of the first one.

Example: Say I want 3

     s = [1,2,3,4,5,3,9,8]  => s[2] appears first

Body:
Yet another way of doing it:

from operator import countOf

def multindex(seq):
    """ find index of first value occurring more than once
        in a sequence, else raise ValueError if there aren't any
    """
    for i,v in enumerate(seq):
        if countOf(seq, v) > 1:
            return i
    else:
        raise ValueError

print 's[{}] is first value in the list occurring more than once'.format(multindex(s))
# s[2] is first value in the list occurring more than once