问:
Using the Gson library to parse unknown data dynamically
I want to parse following JSON data in Android Studio using Gson library. But the data is generic..dont know what keys(objects) are come in data..

under school object - there is number 1103 which is object.

and under that object we have shoolname, shortname, students
  again under students - there are id's like 2201, 2202...
  these objects are dynamic dont know what comes in response..

so question is how to parse this json string in android using Gson?

or any other solution for that is welcome

```<code>{
"schools": {
    "home": "1103",
    "statelevel": "1348"
},
"school": {
    "1103": {
        "schoolname": "Indira School",
        "nameshort": "ind",
        "students": {
            "2201": {
                "name": "Ritesh",
                "isCR": true,
                "maths": {
                    "score": 95,
                    "lastscore": 86
                }
            },
            "2202": {
                "name": "Sanket",
                "maths": {
                    "score": 98,
                    "lastscore": 90
                }
            },
            "2203": {
                "name": "Ajit",
                "maths": {
                    "score": 94,
                    "lastscore": 87
                }
            }
        }
    },
    "1348": {
        "schoolname": "Patil School",
        "nameshort": "pat",
        "students": {
            "3201": {
                "name": "Ravi",
                "maths": {
                    "score": 95,
                    "lastscore": 86
                }
            },
            "3202": {
                "name": "Raj",
                "isCR": true,
                "maths": {
                    "score": 98,
                    "lastscore": 90
                }
            },
            "3203": {
                "name": "Ram",
                "maths": {
                    "score": 94,
                    "lastscore": 87
                }
            }
        }
    }
}
</code>```

}

I have refered the How to parse dynamic JSON fields with GSON?.. but not worked in my case..i have inner generic classes too.

I have found the solution here https://stackoverflow.com/a/23473650/7790252.
implements deserializer to model classes like school and students.

答:
Create model object which implements JsonDeserializer

then you have this method to override:

```<code>@Override
public ActivityEvents deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
    JsonObject jObject = jsonElement.getAsJsonObject();
    for (Map.Entry<String, JsonElement> entry : jObject.entrySet()) {
    entry.getKey(); //here you can get your key
    gson.fromJson(entry.getValue(), StudebtInfo.class);; //here you can get value for key
    }
}
</code>```

Body:
I want to parse following JSON data in Android Studio using Gson library. But the data is generic..dont know what keys(objects) are come in data..

under school object - there is number 1103 which is object.

and under that object we have shoolname, shortname, students
  again under students - there are id's like 2201, 2202...
  these objects are dynamic dont know what comes in response..

so question is how to parse this json string in android using Gson?

or any other solution for that is welcome

{
"schools": {
    "home": "1103",
    "statelevel": "1348"
},
"school": {
    "1103": {
        "schoolname": "Indira School",
        "nameshort": "ind",
        "students": {
            "2201": {
                "name": "Ritesh",
                "isCR": true,
                "maths": {
                    "score": 95,
                    "lastscore": 86
                }
            },
            "2202": {
                "name": "Sanket",
                "maths": {
                    "score": 98,
                    "lastscore": 90
                }
            },
            "2203": {
                "name": "Ajit",
                "maths": {
                    "score": 94,
                    "lastscore": 87
                }
            }
        }
    },
    "1348": {
        "schoolname": "Patil School",
        "nameshort": "pat",
        "students": {
            "3201": {
                "name": "Ravi",
                "maths": {
                    "score": 95,
                    "lastscore": 86
                }
            },
            "3202": {
                "name": "Raj",
                "isCR": true,
                "maths": {
                    "score": 98,
                    "lastscore": 90
                }
            },
            "3203": {
                "name": "Ram",
                "maths": {
                    "score": 94,
                    "lastscore": 87
                }
            }
        }
    }
}

}

I have refered the How to parse dynamic JSON fields with GSON?.. but not worked in my case..i have inner generic classes too.

I have found the solution here https://stackoverflow.com/a/23473650/7790252.
implements deserializer to model classes like school and students.

Body:
Create model object which implements JsonDeserializer

then you have this method to override:

@Override
public ActivityEvents deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
    JsonObject jObject = jsonElement.getAsJsonObject();
    for (Map.Entry<String, JsonElement> entry : jObject.entrySet()) {
    entry.getKey(); //here you can get your key
    gson.fromJson(entry.getValue(), StudebtInfo.class);; //here you can get value for key
    }
}


来源: stackexchange

问:
Fastest way to convert Image to Byte array
I am making Remote Desktop sharing application in which I capture an image of the Desktop and Compress it and Send it to the receiver. To compress the image I need to convert it to a byte[].

Currently I am using this:

```<code>public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
    MemoryStream ms = new MemoryStream();
    imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
    return  ms.ToArray();
}

public Image byteArrayToImage(byte[] byteArrayIn)
{
     MemoryStream ms = new MemoryStream(byteArrayIn);
     Image returnImage = Image.FromStream(ms);
     return returnImage;
}
</code>```

But I don't like it because I have to save it in a ImageFormat and that may also use up resources (Slow Down) as well as produce different compression results.I have read on using Marshal.Copy and memcpy but I am unable to understand them.

So is there any other method to achieve this goal?

答:
```<code>public static class HelperExtensions
{
    //Convert Image to byte[] array:
    public static byte[] ToByteArray(this Image imageIn)
    {
        var ms = new MemoryStream();
        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        return ms.ToArray();
    }

    //Convert byte[] array to Image:
    public static Image ToImage(this byte[] byteArrayIn)
    {
        var ms = new MemoryStream(byteArrayIn);
        var returnImage = Image.FromStream(ms);
        return returnImage;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am making Remote Desktop sharing application in which I capture an image of the Desktop and Compress it and Send it to the receiver. To compress the image I need to convert it to a byte[].

Currently I am using this:

public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
    MemoryStream ms = new MemoryStream();
    imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
    return  ms.ToArray();
}

public Image byteArrayToImage(byte[] byteArrayIn)
{
     MemoryStream ms = new MemoryStream(byteArrayIn);
     Image returnImage = Image.FromStream(ms);
     return returnImage;
}

But I don't like it because I have to save it in a ImageFormat and that may also use up resources (Slow Down) as well as produce different compression results.I have read on using Marshal.Copy and memcpy but I am unable to understand them.

So is there any other method to achieve this goal?


问:
jquery hover div and show another div then keep that div open
I'd really appreciate if someone can help me.

i just want to hover a div and show another div then i want to hover that div but that div still open

Code snippet:

$(function(){
 $('.navigation li').hover(
   function(){
     $('.navigation-dropdown').toggleClass('visible');
    }
    );
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.navigation{
  color: #ffffff;
  background-color: #000000;
  height: 20px;
  width: 100%;
}
.navigation li{
  display: inline-block;
}
.navigation-dropdown{
  background-color:red;
  display: none;
}
.visible{
  display: block;
}</code>```

home

about

contact

```

https://jsfiddle.net/7okx2Lrx/7/

答:
Change .toggleClass('visible') to .addClass('visible'):

$(function(){
 $('.navigation li').hover(
   function(){
     $('.navigation-dropdown').addClass('visible');
    }
    );
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.navigation{
  color: #ffffff;
  background-color: #000000;
  height: 20px;
  width: 100%;
}
.navigation li{
  display: inline-block;
}
.navigation-dropdown{
  background-color:red;
  display: none;
}
.visible{
  display: block;
}</code>```

home

about

contact

```

Body:
I'd really appreciate if someone can help me.

i just want to hover a div and show another div then i want to hover that div but that div still open

Code snippet:

$(function(){
 $('.navigation li').hover(
   function(){
     $('.navigation-dropdown').toggleClass('visible');
    }
    );
});

.navigation{
  color: #ffffff;
  background-color: #000000;
  height: 20px;
  width: 100%;
}
.navigation li{
  display: inline-block;
}
.navigation-dropdown{
  background-color:red;
  display: none;
}
.visible{
  display: block;
}

home

about

contact

https://jsfiddle.net/7okx2Lrx/7/

Body:
Change .toggleClass('visible') to .addClass('visible'):

$(function(){
 $('.navigation li').hover(
   function(){
     $('.navigation-dropdown').addClass('visible');
    }
    );
});

.navigation{
  color: #ffffff;
  background-color: #000000;
  height: 20px;
  width: 100%;
}
.navigation li{
  display: inline-block;
}
.navigation-dropdown{
  background-color:red;
  display: none;
}
.visible{
  display: block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="navigation">
  <ul>
    <a href=""><li>home</li></a>
    <a href=""><li>about</li></a>
    <a href=""><li>contact</li></a>
  </ul>
</div>
<div class="navigation-dropdown">
  <ul>
    <li><img src="" alt=""></li>
    <li><img src="" alt=""></li>
    <li><img src="" alt=""></li>
  </ul>
</div>


问:
How can I connect to a hosted Parse-Server over Parse4J?
I would like to be able to use the Parse4J library (https://github.com/thiagolocatelli/parse4j/) to connect to a hosted Parse-Server. I want to use https://parseapi.back4app.com as an API endpoint. They provide a solid Parse hosting solution.

Code:

```<code>import org.parse4j.Parse;
import org.parse4j.ParseException;
import org.parse4j.ParseObject;
import org.parse4j.ParseQuery;
import org.parse4j.callback.GetCallback;

/**
 * Created by Martin on 3/27/2017.
 */
public class Parse4JStarter {

    public static void main(String[] args) {

        Parse.initialize("applicationId","restAPIKey");

        if (Parse.getApplicationId() != null) {
            System.out.println("ParseConnection successful! " + Parse.getApplicationId());

            try {
                queryPost();
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static void queryPost() throws Exception {
        ParseQuery<ParseObject> query = ParseQuery.getQuery("Post");
        query.getInBackground("4tD9TIIIhv", new GetCallback<ParseObject>() {
            public void done(ParseObject object, ParseException e) {
                if (e == null) {
                    System.out.println("ParseObject printed successfully! " + object);
                } else {
                    e.printStackTrace();
                }
            }
        });
    }
}
</code>```

Dependencies:

```<code><dependencies>
        <dependency>
            <groupId>com.github.thiagolocatelli</groupId>
            <artifactId>parse4j</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.6.4</version>
        </dependency>
    </dependencies>
</code>```

I tried overriding the Maven repository by supplying a local version, i.e. 1.4-FIXED and changing the API_ENDPOINT value in ParseConstants.java to point to https://parseapi.back4app.com, which is where my database is hosted:

```<code>public class ParseConstants {

    public static final String API_ENDPOINT = "https://parseapi.back4app.com";
    public static final String API_VERSION = "1";

    public static final String HEADER_CONTENT_TYPE = "Content-Type";
    public static final String HEADER_APPLICATION_ID = "X-Parse-Application-Id";
    public static final String HEADER_REST_API_KEY = "X-Parse-REST-API-Key";
    public static final String HEADER_MASTER_KEY = "X-Parse-Master-Key";
    public static final String HEADER_SESSION_TOKEN = "X-Parse-Session-Token";

    public static final String CONTENT_TYPE_JSON = "application/json";

    public static final String FIELD_OBJECT_ID = "objectId";
    public static final String FIELD_CREATED_AT = "createdAt";
    public static final String FIELD_UPDATED_AT = "updatedAt";
    public static final String FIELD_SESSION_TOKEN = "sessionToken";

    public static int MAX_PARSE_FILE_SIZE = 10485760;

}
</code>```

I received an ParseException:

```<code>ParseException [code=109, error=unauthorized]
    at org.parse4j.command.ParseResponse.getParseError(ParseResponse.java:122)
    at org.parse4j.command.ParseResponse.getException(ParseResponse.java:78)
    at org.parse4j.ParseQuery.find(ParseQuery.java:598)
    at org.parse4j.ParseQuery.find(ParseQuery.java:469)
    at org.parse4j.ParseQuery.get(ParseQuery.java:377)
    at org.parse4j.ParseQuery$GetInBackgroundThread.run(ParseQuery.java:452)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
</code>```

This means that my connection was not properly initialized:

```<code>   /**
   * You must call Parse.initialize before using the Parse library.
   */
  public static final int NOT_INITIALIZED = 109;
</code>```

There is probably more that I can do by investigating the Parse4J library more thoroughly. At this point, however, I'm lost. What can I do?

答:
Thanks to the developers at Parse4J, I was able to solve my problem by updating my dependency to the latest snapshot version 1.5-SNAPSHOT and then updating my initialization method to include a third parameter that holds the custom API endpoint. This was possible some 8 months ago but the documentation does not mention anything about using the latest build, since it's not an official release yet. I got this working using https://parseapi.back4app.com. They provide a solid Parse hosting solution but you can replace this with your own URI. A new release should be around the corner I assume...

```<code><dependencies>
        <dependency>
            <groupId>com.github.thiagolocatelli</groupId>
            <artifactId>parse4j</artifactId>
            <version>1.5-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.6.4</version>
        </dependency>
    </dependencies>
</code>```

Initialization method:

```<code>Parse.initialize(applicationId, restAPIKey, "https://parseapi.back4app.com");
</code>```

See documentation here: https://github.com/thiagolocatelli/parse4j/commit/4113b422631c364488bc51152da8b071542e8159

Body:
I would like to be able to use the Parse4J library (https://github.com/thiagolocatelli/parse4j/) to connect to a hosted Parse-Server. I want to use https://parseapi.back4app.com as an API endpoint. They provide a solid Parse hosting solution.

Code:

import org.parse4j.Parse;
import org.parse4j.ParseException;
import org.parse4j.ParseObject;
import org.parse4j.ParseQuery;
import org.parse4j.callback.GetCallback;

/**
 * Created by Martin on 3/27/2017.
 */
public class Parse4JStarter {

    public static void main(String[] args) {

        Parse.initialize("applicationId","restAPIKey");

        if (Parse.getApplicationId() != null) {
            System.out.println("ParseConnection successful! " + Parse.getApplicationId());

            try {
                queryPost();
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static void queryPost() throws Exception {
        ParseQuery<ParseObject> query = ParseQuery.getQuery("Post");
        query.getInBackground("4tD9TIIIhv", new GetCallback<ParseObject>() {
            public void done(ParseObject object, ParseException e) {
                if (e == null) {
                    System.out.println("ParseObject printed successfully! " + object);
                } else {
                    e.printStackTrace();
                }
            }
        });
    }
}

Dependencies:

<dependencies>
        <dependency>
            <groupId>com.github.thiagolocatelli</groupId>
            <artifactId>parse4j</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.6.4</version>
        </dependency>
    </dependencies>

I tried overriding the Maven repository by supplying a local version, i.e. 1.4-FIXED and changing the API_ENDPOINT value in ParseConstants.java to point to https://parseapi.back4app.com, which is where my database is hosted:

public class ParseConstants {

    public static final String API_ENDPOINT = "https://parseapi.back4app.com";
    public static final String API_VERSION = "1";

    public static final String HEADER_CONTENT_TYPE = "Content-Type";
    public static final String HEADER_APPLICATION_ID = "X-Parse-Application-Id";
    public static final String HEADER_REST_API_KEY = "X-Parse-REST-API-Key";
    public static final String HEADER_MASTER_KEY = "X-Parse-Master-Key";
    public static final String HEADER_SESSION_TOKEN = "X-Parse-Session-Token";

    public static final String CONTENT_TYPE_JSON = "application/json";

    public static final String FIELD_OBJECT_ID = "objectId";
    public static final String FIELD_CREATED_AT = "createdAt";
    public static final String FIELD_UPDATED_AT = "updatedAt";
    public static final String FIELD_SESSION_TOKEN = "sessionToken";

    public static int MAX_PARSE_FILE_SIZE = 10485760;

}

I received an ParseException:

ParseException [code=109, error=unauthorized]
    at org.parse4j.command.ParseResponse.getParseError(ParseResponse.java:122)
    at org.parse4j.command.ParseResponse.getException(ParseResponse.java:78)
    at org.parse4j.ParseQuery.find(ParseQuery.java:598)
    at org.parse4j.ParseQuery.find(ParseQuery.java:469)
    at org.parse4j.ParseQuery.get(ParseQuery.java:377)
    at org.parse4j.ParseQuery$GetInBackgroundThread.run(ParseQuery.java:452)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

This means that my connection was not properly initialized:

   /**
   * You must call Parse.initialize before using the Parse library.
   */
  public static final int NOT_INITIALIZED = 109;

There is probably more that I can do by investigating the Parse4J library more thoroughly. At this point, however, I'm lost. What can I do?

Body:
Thanks to the developers at Parse4J, I was able to solve my problem by updating my dependency to the latest snapshot version 1.5-SNAPSHOT and then updating my initialization method to include a third parameter that holds the custom API endpoint. This was possible some 8 months ago but the documentation does not mention anything about using the latest build, since it's not an official release yet. I got this working using https://parseapi.back4app.com. They provide a solid Parse hosting solution but you can replace this with your own URI. A new release should be around the corner I assume...

<dependencies>
        <dependency>
            <groupId>com.github.thiagolocatelli</groupId>
            <artifactId>parse4j</artifactId>
            <version>1.5-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.6.4</version>
        </dependency>
    </dependencies>

Initialization method:

Parse.initialize(applicationId, restAPIKey, "https://parseapi.back4app.com");

See documentation here: https://github.com/thiagolocatelli/parse4j/commit/4113b422631c364488bc51152da8b071542e8159


问:
Can't add VS command prompt as a tool in VS15 Community

Arguments: /k "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\VsDevCmd.bat"

I want to add visual studio command prompt as a tool. I try with all kind of ways, but still can't able to open vs cmd.

[![enter image description here][2]][2]

This is what cmd shows when i run CMD tool.
Framework: .NET Framework 4.6

Can anyone tell me where i am doing mistake?

答: Check the double quote at the end of your argument. It seems like you didnt put it.</p>


问:
how to perform addition of items in two different lists in robot framework?
list1 = [ 1, 2, 3]

list2 = [4, 5, 6]

I want to perform addition on these lists in this way: 1+4, 2+5, 3+6.. and so on.

Any help would be really appreciated.

Thanks.

答:
In Robot Framework there aren't many calculation keyword options in the BuiltIn Library. There are certainly no native ones and we often resort to using Evaluate to evaluate a python expression. This python expression is further explained in the already mentioned  Element-wise addition of 2 lists. Combining both the the below code:

```<code>*** Test Cases ***
Map Lamda Calc
    ${list1}    Create List    ${1}    ${2}    ${3}
    ${list2}    Create List    ${1}    ${2}    ${3}
    ${CalcList}    Evaluate    map(lambda x, y: x + y, $list1, $list2)
    Log To Console    \n${CalcList}
</code>```

Which will then result in the following console response:

```<code>==============================================================================
Test
==============================================================================
Test.calcLists
==============================================================================
Map Lamda Calc
[2, 4, 6]
| PASS |
------------------------------------------------------------------------------
Test.calcLists                                                        | PASS |
1 critical test, 1 passed, 0 failed
1 test total, 1 passed, 0 failed
============================================================================
</code>```

In the code the ${1} construct is used to ensure that the value stored is indeed an robot framework integer. Otherwise a string is provided and then a concatenation is performed.

Body:
In Robot Framework there aren't many calculation keyword options in the BuiltIn Library. There are certainly no native ones and we often resort to using Evaluate to evaluate a python expression. This python expression is further explained in the already mentioned  Element-wise addition of 2 lists. Combining both the the below code:

*** Test Cases ***
Map Lamda Calc
    ${list1}    Create List    ${1}    ${2}    ${3}
    ${list2}    Create List    ${1}    ${2}    ${3}
    ${CalcList}    Evaluate    map(lambda x, y: x + y, $list1, $list2)
    Log To Console    \n${CalcList}

Which will then result in the following console response:

==============================================================================
Test
==============================================================================
Test.calcLists
==============================================================================
Map Lamda Calc
[2, 4, 6]
| PASS |
------------------------------------------------------------------------------
Test.calcLists                                                        | PASS |
1 critical test, 1 passed, 0 failed
1 test total, 1 passed, 0 failed
============================================================================

In the code the ${1} construct is used to ensure that the value stored is indeed an robot framework integer. Otherwise a string is provided and then a concatenation is performed.


问:
Setting an Image Buttons's image Xcode Applescript
This is what I am trying to do: `on changeSomeImage_(newImage, targetObjectOutlet)

```<code>set localTarget to current application's NSImage's imageNamed_(newImage)
targetObjectOutlet's setImage_(localTarget)
targetLableOutlet's setStringValue_(newLableText)

end changeSomeImage_
</code>```

I have an IBOutlet connected already.

答:
figured it out</p>

```<code>on changeSomeImage_(newImage, targetObjectOutlet, newText, targetLableOutlet)

set newImage1 to current application's NSImage's imageNamed_(newImage)
targetObjectOutlet's setImage_(newImage1)
targetLableOutlet's setStringValue_(newText)

end changeSomeImage_
</code>```

Body:
This is what I am trying to do: `on changeSomeImage_(newImage, targetObjectOutlet)

set localTarget to current application's NSImage's imageNamed_(newImage)
targetObjectOutlet's setImage_(localTarget)
targetLableOutlet's setStringValue_(newLableText)

end changeSomeImage_

I have an IBOutlet connected already.

Body:
figured it out

on changeSomeImage_(newImage, targetObjectOutlet, newText, targetLableOutlet)

set newImage1 to current application's NSImage's imageNamed_(newImage)
targetObjectOutlet's setImage_(newImage1)
targetLableOutlet's setStringValue_(newText)

end changeSomeImage_


问:
What is the best jQuery deep linking / history plug-in?
I am looking to implement deep linking / back button functionality on a web site that uses jQuery and jQuery UI (tabs, dialogs...). I a new to this so I lack the knowledge to evaluate the different offerings in deep. So far, from what I read on the web, I have narrowed my choice down to jQuery BBQ and the Asual address plugin.

Is there any other plugin that competes with those 2 ? Which one is the best ?

答:
Asual address is easier to use than BBQ, and is very fully featured.

According to this question SO says address. Though it might be a little unfair because that answer is almost a year older.

https://stackoverflow.com/questions/116446/what-is-the-best-back-button-jquery-plugin

ContentLicense: CC BY-SA 2.5


问:
Why does my Base64 encoded hash only contain 28 characters?
The inverse question exists with no answer and a comment that I don't understand.

I am attempting to create a Base64 encoded HMAC-SHA1 signature for a pseudo OAuth authentication header for an API. I found a support document (requires authenticated access) that takes you through the evolution of creating the signature. I'm able to create the same data up until the final step which is to Base64 encode the hash.

The support document states that the HMAC-SHA1 signature is:

```<code>cb5acd2d3ef689a8fbec4d06c576371834689673
</code>```

And I get:

```<code>CB5ACD2D3EF689A8FBEC4D06C576371834689673
</code>```

The support document then states

From the hex result string in step 3, encode the value using Base64

and provides the following Base64 encoded result (58 characters):

```<code>Y2I1YWNkMmQzZWY2ODlhOGZiZWM0ZDA2YzU3NjM3MTgzNDY4OTY3Mw==
</code>```

When I use Convert.ToBase64String() to convert my signature I get (28 characters):

```<code>y1rNLT72iaj77E0GxXY3GDRolnM=
</code>```

I'm stumped, I don't know if the support document is incorrect or if I'm doing something wrong. The fact that I'm generating a string that is 28 characters and the example is 56 is too interesting to ignore.

The comment in the aforementioned semi-duplicate question also stumps me. I don't see how the string "MDY" translates to any ascii or unicode digits that make sense to me - I don't understand how the comment author came to that conclusion.

The hex value is being encoded as text ("062..." == 0x30, 0x36, 0x32,
  ...) rather than as the large number it represents.

答:
I came up with the same problem here. You have to convert sha1sum result to a Hex format. For example, when your sha1sum result is dfe5ec35f9c9f144d3814821a558bcfa23ab1a58, the console outputs it in string format.

You may use UltraEdit or another text editor, edit it as hex.

And then save it as a file.
The right answer 3+XsNfnJ8UTTgUghpVi8+iOrGlg= comes out after you base64 encode the file.

Have a try. Hope it helps.

Body:
The inverse question exists with no answer and a comment that I don't understand.

I am attempting to create a Base64 encoded HMAC-SHA1 signature for a pseudo OAuth authentication header for an API. I found a support document (requires authenticated access) that takes you through the evolution of creating the signature. I'm able to create the same data up until the final step which is to Base64 encode the hash.

The support document states that the HMAC-SHA1 signature is:

cb5acd2d3ef689a8fbec4d06c576371834689673

And I get:

CB5ACD2D3EF689A8FBEC4D06C576371834689673

The support document then states

From the hex result string in step 3, encode the value using Base64

and provides the following Base64 encoded result (58 characters):

Y2I1YWNkMmQzZWY2ODlhOGZiZWM0ZDA2YzU3NjM3MTgzNDY4OTY3Mw==

When I use Convert.ToBase64String() to convert my signature I get (28 characters):

y1rNLT72iaj77E0GxXY3GDRolnM=

I'm stumped, I don't know if the support document is incorrect or if I'm doing something wrong. The fact that I'm generating a string that is 28 characters and the example is 56 is too interesting to ignore.

The comment in the aforementioned semi-duplicate question also stumps me. I don't see how the string "MDY" translates to any ascii or unicode digits that make sense to me - I don't understand how the comment author came to that conclusion.

The hex value is being encoded as text ("062..." == 0x30, 0x36, 0x32,
  ...) rather than as the large number it represents.

ContentLicense: CC BY-SA 4.0


问:
Angular 1.5 - UI-Router, Resolve Object returning undefined values
I am unable to get resolved data (via resolve object) from ui router pre-loaded into a component controller. the properties are showing up in the component's this object, but all properties are undefined. Why is this happening? I have been stuck on this for a while now...

here is the component:

```<code>  .component('wLoans', {
    template: require('./loans.html'),
    controller: LoansController,
    bindings: {
      settings: '<',
      labels: '<'
    }
  });
</code>```

this.settings and this.labels appear, but they are undefined. when I console.log inside resolve.settings below, I can see the promise itself. in the promise below, value contains the return data I want:

below is the state I am working on with UI router:

```<code>{
      name: 'loans',
      parent: 'app',
      url: '/loans',
      data: {
        authRequired: true
      },
      views: {
        content: {
          template: '<w-loans></w-loans>'
        }
      },
      resolve: {
        labels(LabelService) {
          'ngInject';
          return LabelService.fetch();
        },
        settings(SettingsService) {
          'ngInject';
          console.log(SettingsService.fetch());
          return SettingsService.fetch()
        },
        module($q, $ocLazyLoad, LabelService) {
          'ngInject';
          return $q((resolve) => {
            require.ensure([], (require) => {
              let mod = require('pages/loans');
              $ocLazyLoad.load({ name: mod.name });
              resolve(mod.name, LabelService.fetch());
            }, 'loans');
          });
        }
      }
    }
</code>```

here is the fetch function from the service that's being called in the route:

```<code>function fetch() {
        // return $http.get(require('!!file!mocks/settings.json'), {
    return $http.get(`${DEV_API_URL}/settings`, {
      cache: settingsCache,
      transformResponse: [
        ...$http.defaults.transformResponse,
        transformResponse
      ]
    })
      .then(({ data }) => {
        angular.extend(model, data);
        settingsCache.put('store', model);
        return model;
      });
  }
</code>```

Any help is appreciated!

UPDATE: using ui router 1.0.0-beta.1

答:
I had a similar problem with Angular 1.6 and it looks like a different  behavior of this version. My view is rendered after the promise is resolved, but the controller is called before, I think. It works for me using $onInit like the angular docs suggests:

```<code>.component('myComponent', {
  bindings: {value: '<'},
  controller: function() {
    this.$onInit = function() {
      // do somthing with this.value
    };
  }
})
</code>```

https://github.com/angular/angular.js/issues/15545

Body:
I am unable to get resolved data (via resolve object) from ui router pre-loaded into a component controller. the properties are showing up in the component's this object, but all properties are undefined. Why is this happening? I have been stuck on this for a while now...

here is the component:

  .component('wLoans', {
    template: require('./loans.html'),
    controller: LoansController,
    bindings: {
      settings: '<',
      labels: '<'
    }
  });

this.settings and this.labels appear, but they are undefined. when I console.log inside resolve.settings below, I can see the promise itself. in the promise below, value contains the return data I want:

below is the state I am working on with UI router:

{
      name: 'loans',
      parent: 'app',
      url: '/loans',
      data: {
        authRequired: true
      },
      views: {
        content: {
          template: '<w-loans></w-loans>'
        }
      },
      resolve: {
        labels(LabelService) {
          'ngInject';
          return LabelService.fetch();
        },
        settings(SettingsService) {
          'ngInject';
          console.log(SettingsService.fetch());
          return SettingsService.fetch()
        },
        module($q, $ocLazyLoad, LabelService) {
          'ngInject';
          return $q((resolve) => {
            require.ensure([], (require) => {
              let mod = require('pages/loans');
              $ocLazyLoad.load({ name: mod.name });
              resolve(mod.name, LabelService.fetch());
            }, 'loans');
          });
        }
      }
    }

here is the fetch function from the service that's being called in the route:

function fetch() {
        // return $http.get(require('!!file!mocks/settings.json'), {
    return $http.get(`${DEV_API_URL}/settings`, {
      cache: settingsCache,
      transformResponse: [
        ...$http.defaults.transformResponse,
        transformResponse
      ]
    })
      .then(({ data }) => {
        angular.extend(model, data);
        settingsCache.put('store', model);
        return model;
      });
  }

Any help is appreciated!

UPDATE: using ui router 1.0.0-beta.1

Body:
I had a similar problem with Angular 1.6 and it looks like a different  behavior of this version. My view is rendered after the promise is resolved, but the controller is called before, I think. It works for me using $onInit like the angular docs suggests:

.component('myComponent', {
  bindings: {value: '<'},
  controller: function() {
    this.$onInit = function() {
      // do somthing with this.value
    };
  }
})

https://github.com/angular/angular.js/issues/15545


问:
Smallest Sum Algorithm
I feel like I may not have been clear enough about the requirements so let me try to make things more clear.

You are provided a dictionary that contains keys that are either single letters or multiple letters. Each key has an associated value. Given an input, you must find the keys that contain the input letters. Return the lowest key values that satisfy this requirement.

Here are a few examples:

Input Dictionary

Key -> Value

a -> 4

b -> 6

e -> 5

abc -> 8

Input: 'a'
Output: 4

Input: 'c'
Output: 8

Input: 'ab'
Output: 8

Input: 'ac'
Output: 8

Input: 'ce'
Output: 13

Input: 'd'
Output: null

Note on the third example, the input is ab. So here, we can either get the letter 'a' from the key 'a' or the key 'abc'. We can either get the letter 'b' from the key 'b' or the key 'abc'. In order to get both keys with the lowest total value, 'abc' with a value of 8 is the correct output.

Note on the fifth example, the input is ce. The letter 'c' is only available in the key 'abc'. The letter 'e' is only available in the key 'e'. The correct output in this situation is 13.

UPDATE: I was able to solve this recursively by starting off with the first letter in the input sequence, finding all keys that contain that letter, and for each key, building a list of all the possible combinations. I was able to track the lowest sum by recursively moving through one letter of the input sequence at a time.

答:
```<code>  #!/usr/bin/python3
  import operator

    def smallest_sum(dic):
        a_dic = {}
        b_dic = {}
        # get a list of all keys containing a and b
        for key in dic:
            if "a" in key:
                a_dic[key] = dic[key]
            elif "b" in key:
                b_dic[key] = dic[key]

        a_dic = sorted(a_dic.items(), key=operator.itemgetter(1))
        b_dic = sorted(b_dic.items(), key=operator.itemgetter(1))

        if "ab" in a_dic[0]:
            return a_dic[0][1]
        else:
            a_sum_b = a_dic[0][1] + b_dic[0][1]
            return a_sum_b

    if __name__ == "__main__":
        dic = {"a":2, "b":3, "abc":10, "ab": 15, "bcd": 2}
        sum = smallest_sum(dic)
        print(sum)
</code>```

Title: Smallest Sum Algorithm


问:
Hiveconf/hivevar: possible to have a dot ('.') in a variable name?
Is it possible to use a dot in a name of hiveconf variable?

All examples in a documentation show simple variable names like a.

If yes:

How do I reference it in HQL script? select ${hiveconf:airflow.ctx.dag.dag_id} as dag_id; produces syntax error (while ${hiveconf:abcd} is ok).

If no:

Why does airflow or azkaban pass variables to hive scripts like this? Wouldn't the authors know that it's not possible to reference these variables?

hive -hiveconf airflow.ctx.dag.dag_id=video-plays-adverts -f test-hiveconf.hql

Thanks!

答:
It turns out there were several compound problems:

1) Hivevars work as a C macro system - when you assign set a = concat('-', ${hiveconf:var_name}), content of ${hiveconf:a} isn't a string, but really a command concat('-', ${hiveconf:var_name}) which gets evaluated every time you use it.

2) I was using it in static partitions, which only accept literals, so this:

```<code>INSERT OVERWRITE TABLE xyz
PARTITION (year=${hiveconf:y}, month=${hiveconf:m}, week=${hiveconf:w}, day=${hiveconf:d})
</code>```

got translated to this:

```<code>INSERT OVERWRITE TABLE xyz
PARTITION (year=<complex expression>, month=<complex expression>, week=<complex expression>, day=<complex expression>)
</code>```

Which is not supported - static partition need literals.

End of story. Seems like there is no way to use 'computed' (set a = concat(${b}, ${c})) hiveconf variables in places of constant.

Body:
It turns out there were several compound problems:

1) Hivevars work as a C macro system - when you assign set a = concat('-', ${hiveconf:var_name}), content of ${hiveconf:a} isn't a string, but really a command concat('-', ${hiveconf:var_name}) which gets evaluated every time you use it.

2) I was using it in static partitions, which only accept literals, so this:

INSERT OVERWRITE TABLE xyz
PARTITION (year=${hiveconf:y}, month=${hiveconf:m}, week=${hiveconf:w}, day=${hiveconf:d})

got translated to this:

INSERT OVERWRITE TABLE xyz
PARTITION (year=<complex expression>, month=<complex expression>, week=<complex expression>, day=<complex expression>)

Which is not supported - static partition need literals.

End of story. Seems like there is no way to use 'computed' (set a = concat(${b}, ${c})) hiveconf variables in places of constant.


问:
OpenCV Error: Assertion failed (size.width>0 && size.height>0) in cv::imshow (Python)
I went trough many similar topics like mine, but found no solution for my code.
First of all I simply want to run my webcam and see a picture.

```<code>import numpy as np
import cv2

cap = cv2.VideoCapture(1)

while True:
  re,img=cap.read()
  cv2.imshow("video output", img)
  k = cv2.waitKey(10)&0xFF
  if k==27:
     break
cap.release()
cv2.destroyAllWindows()
</code>```

I also tried it with:

```<code>if img is not None:
</code>```

I still get this error:

```<code>OpenCV Error: Assertion failed (size.width>0 && size.height>0) in cv::imshow
</code>```

I have to say that I am not using my laptop webcam so its id is not 0, but it should be 1. I read about solutions like in c++: frame=cvQueryFrame(capture);
     if (frame.empty()) break;
But how to do it in Python? I do not think that this will fix my problem?
Has anybody a solution?

Best regards

答:
According to the OpenCV docs:

cap.read() returns a bool (True/False). If frame is read correctly, it
  will be True.

...

Sometimes, cap may not have initialized the capture. In that case,
  this code shows error. You can check whether it is initialized or not
  by the method cap.isOpened(). If it is True, OK. Otherwise open it
  using cap.open().

Thus your code becomes:

```<code>import numpy as np
import cv2

device = 1
cap = cv2.VideoCapture(device)
# if capture failed to open, try again
if not cap.isOpened():
    cap.open(device)

# only attempt to read if it is opened
if cap.isOpened:
    while True:
        re, img = cap.read()
        # Only display the image if it is not empty
        if re:
            cv2.imshow("video output", img)
        # if it is empty abort
        else:
            print "Error reading capture device"
            break
        k = cv2.waitKey(10) & 0xFF
        if k == 27:
            break
    cap.release()
    cv2.destroyAllWindows()
else:
    print "Failed to open capture device"
</code>```

If you still have errors try changing device to -1, 0 or 2. Otherwise, it may be an issue unrelated to OpenCV such as driver issues.

Body:
I went trough many similar topics like mine, but found no solution for my code.
First of all I simply want to run my webcam and see a picture.

import numpy as np
import cv2

cap = cv2.VideoCapture(1)

while True:
  re,img=cap.read()
  cv2.imshow("video output", img)
  k = cv2.waitKey(10)&0xFF
  if k==27:
     break
cap.release()
cv2.destroyAllWindows()

I also tried it with:

if img is not None:

I still get this error:

OpenCV Error: Assertion failed (size.width>0 && size.height>0) in cv::imshow

I have to say that I am not using my laptop webcam so its id is not 0, but it should be 1. I read about solutions like in c++: frame=cvQueryFrame(capture);
     if (frame.empty()) break;
But how to do it in Python? I do not think that this will fix my problem?
Has anybody a solution?

Best regards

Body:
According to the OpenCV docs:

cap.read() returns a bool (True/False). If frame is read correctly, it
  will be True.

...

Sometimes, cap may not have initialized the capture. In that case,
  this code shows error. You can check whether it is initialized or not
  by the method cap.isOpened(). If it is True, OK. Otherwise open it
  using cap.open().

Thus your code becomes:

import numpy as np
import cv2

device = 1
cap = cv2.VideoCapture(device)
# if capture failed to open, try again
if not cap.isOpened():
    cap.open(device)

# only attempt to read if it is opened
if cap.isOpened:
    while True:
        re, img = cap.read()
        # Only display the image if it is not empty
        if re:
            cv2.imshow("video output", img)
        # if it is empty abort
        else:
            print "Error reading capture device"
            break
        k = cv2.waitKey(10) & 0xFF
        if k == 27:
            break
    cap.release()
    cv2.destroyAllWindows()
else:
    print "Failed to open capture device"

If you still have errors try changing device to -1, 0 or 2. Otherwise, it may be an issue unrelated to OpenCV such as driver issues.


问:
Sharing data between two input fields by ngModel
I have 2 input fileds lets say input1 and input2. I have event such that  everything  I type in input1 it shows in input2.
Now the condition is if i manually change or type something in input2 , the event i had created above should not work.

I guess need to use count loop but I am confused.

html code:

```<code><input placeholder="Organization Name" [(ngModel)] = "orgName" (ngModelChange)="setdomain($event)">

<input placeholder="Business + Sub Domain" [(ngModel)] = "subdomain">
</code>```

fragment of TypeScript file:

```<code>subdomain : string;

setdomain(name) {
    this.subdomain = name.toLowerCase().replace(/ /g ,'');
}
</code>```

答:
I guess that the simplest way is creating temporary variable, which will store unique subdomain name and create method, which will be passing to the variable appropriate value. For example:

in *.component.ts :

```<code>  defaultSubdomain: string;
  uniqueSubdomain: string;

  setdomain(name) {
    let expectedResult = name.toLowerCase().replace(/ /g ,'');
    this.defaultSubdomain = expectedResult;
  }

  setUniqueDomain(name) {
    this.uniqueSubdomain = expectedResult;
  }
</code>```

and in *.component.html :

```<code><input type="text" placeholder="Organization Name" [ngModel] = "orgName" (ngModelChange)="setdomain($event)">
<input type="text" placeholder="Business + Sub Domain" [ngModel] = "uniqueSubdomain || defaultSubdomain" (ngModelChange)="setUniqueDomain($event)">
</code>```

I created Plunker for you. Tell me if that's what you meant.

Body:
I have 2 input fileds lets say input1 and input2. I have event such that  everything  I type in input1 it shows in input2.
Now the condition is if i manually change or type something in input2 , the event i had created above should not work.

I guess need to use count loop but I am confused.

html code:

<input placeholder="Organization Name" [(ngModel)] = "orgName" (ngModelChange)="setdomain($event)">

<input placeholder="Business + Sub Domain" [(ngModel)] = "subdomain">

fragment of TypeScript file:

subdomain : string;

setdomain(name) {
    this.subdomain = name.toLowerCase().replace(/ /g ,'');
}

Body:
I guess that the simplest way is creating temporary variable, which will store unique subdomain name and create method, which will be passing to the variable appropriate value. For example:

in *.component.ts :

  defaultSubdomain: string;
  uniqueSubdomain: string;

  setdomain(name) {
    let expectedResult = name.toLowerCase().replace(/ /g ,'');
    this.defaultSubdomain = expectedResult;
  }

  setUniqueDomain(name) {
    this.uniqueSubdomain = expectedResult;
  }

and in *.component.html :

<input type="text" placeholder="Organization Name" [ngModel] = "orgName" (ngModelChange)="setdomain($event)">
<input type="text" placeholder="Business + Sub Domain" [ngModel] = "uniqueSubdomain || defaultSubdomain" (ngModelChange)="setUniqueDomain($event)">

I created Plunker for you. Tell me if that's what you meant.


答:
Do you mean something like this?

I did it without javascript.

With the "+" you can select the next element on the same level.

```<code>.navigation:hover + .navigation-dropdown, .navigation-dropdown:hover{
    display: block;
}
</code>```

And removed the margin from the ul

```<code>ul{margin: 0;}
</code>```

https://jsfiddle.net/7okx2Lrx/10/

Title: jquery hover div and show another div then keep that div open

Body:
Do you mean something like this?

I did it without javascript.

With the "+" you can select the next element on the same level.

.navigation:hover + .navigation-dropdown, .navigation-dropdown:hover{
    display: block;
}

And removed the margin from the ul

ul{margin: 0;}

https://jsfiddle.net/7okx2Lrx/10/


问:
What is meant by `compile dependencies in the console`
I'm trying to install a C++ framework which has a pretty complicated installation process since a binary installer is not provided. Here is the link that shows the steps to take to install this framework. http://fw4spl.readthedocs.io/en/dev/Installation/src/WindowsInstall.html. I'm using Windows 10 if that helps.

I've been able to successfully follow the instructions (hopefully) until this part: Compile the FW4SPL dependencies with jom in the console (e.g. jom all, jom qt, etc). I don't really understand what I am expected to do and what cmd commands I am supposed to use to complete the installation. Also, I don't really understand why there are separate instructions for dependencies and source since they look exactly the same to me. Am I supposed to do both? Any help would be appreciated.

答:
Compiling dependencies and source files are not the same since the instructions say that the fw4spl-deps folder must be built and compiled in the dependencies section, while the fw4spl folder must be built and compiled in the source section. You must have missed that the folder names were different: fw4spl-deps vs fw4spl. So you must do both.

"Compile dependencies in the console" means use the command prompt to compile the folder that was generated during the fw4spl-deps build. The building may be done with CMake for example as explained in the instructions.


问:
Mongodb aggregation retrieving document from inside of document
I have problems with MongoDB's aggregation.

In my "Job" document, it has creatorParent(single value) and Children(array of mongodb object id). In the "User" document, user has children array with child details.

When user request for retrieving this document I want aggregate child details, if array contains id of child.

I wrote an aggregation with some help, It worked for creatorParent but whatever I've tried, it didn't worked for children.

```<code>db.getCollection('Jobs').aggregate([
    {
        $unwind: {
            path : "$children"
        }
    },
    {
        $lookup: {
            "from" : "Users",
            "localField" : "creatorparent",
            "foreignField" : "_id",
            "as" : "creatorparent"
        }
    },
    {
        $lookup: {
            "from" : "Users",
            "localField" : "children",
            "foreignField" : "children",
            "as" : "children"
        }
    }
])
</code>```

Users document:

```<code>{
    "_id" : ObjectId("58daf84877733645eaa9b44f"),
    "email" : "meto93@gmail.com",
    "password" : "vpGl+Fjnef616cRgNbCkwaFDpSI=",
    "passwordsalt" : "99397F4A9D3A499D96694547667E74595CE994D2E83345D6953EF866303E8B65",
    "children" : [
        {
            "_id" : ObjectId("58daf84977733645eaa9b450"),
            "name" : "Mert",
            "age" : 5,
            "additionalinformation" : "ilk cocuk",
            "creationtime" : ISODate("2017-03-28T23:56:56.952Z"),
            "userid" : ObjectId("58daf84877733645eaa9b44f"),
            "gender" : null
        },
        {
            "_id" : ObjectId("58daf84977733645eaa9b451"),
            "name" : "Sencer",
            "age" : 7,
            "additionalinformation" : "ikinci cocuk",
            "creationtime" : ISODate("2017-03-28T23:56:56.952Z"),
            "userid" : ObjectId("58daf84877733645eaa9b44f"),
            "gender" : null
        }
    ]
}
</code>```

Job

```<code>{
    "_id" : ObjectId("58db0a2d77733645eaa9b453"),
    "creationtime" : ISODate("2017-03-29T01:13:17.509Z"),
    "startingtime" : ISODate("2017-04-03T13:00:00.000Z"),
    "endingtime" : ISODate("2017-04-03T17:00:00.000Z"),
    "children" : [
        ObjectId("58daf84977733645eaa9b450"),
        ObjectId("58daf84977733645eaa9b451")
    ],
    "creatorparent" : ObjectId("58daf84877733645eaa9b44f"),
    "applicants" : []
}
</code>```

答:
Try this:</p>

```<code>db.jobs.aggregate(
    [
        {
            $unwind: {
                path : "$children",
            }
        },
        {
            $lookup: {
                "from" : "users",
                "localField" : "creatorparent",
                "foreignField" : "_id",
                "as" : "creatorparent"
            }
        },
        {
            $lookup: {
                "from" : "users",
                "localField" : "children",
                "foreignField" : "children._id",
                "as" : "children"
            }
        },
        {
            $addFields: {
                children : {$arrayElemAt : ["$children",0]}
            }
        },
        {
            $addFields: {
              "children":"$children.children"
            }
        },
        {
            $unwind: {
                path : "$children",
            }
        },
        {
            $group: {
                "_id": "$_id",
                "name": { "$first": "$name" },
                "jobstatus" : { "$first": "$jobstatus" },
                "hourlyrate" : { "$first": "$hourlyrate" },
                "creatorparent" : { "$first" : "$creatorparent" },
                "children": { "$addToSet": "$children"  }
            }
        },

    ]
);
</code>```

Body:
I have problems with MongoDB's aggregation.

In my "Job" document, it has creatorParent(single value) and Children(array of mongodb object id). In the "User" document, user has children array with child details.

When user request for retrieving this document I want aggregate child details, if array contains id of child.

I wrote an aggregation with some help, It worked for creatorParent but whatever I've tried, it didn't worked for children.

db.getCollection('Jobs').aggregate([
    {
        $unwind: {
            path : "$children"
        }
    },
    {
        $lookup: {
            "from" : "Users",
            "localField" : "creatorparent",
            "foreignField" : "_id",
            "as" : "creatorparent"
        }
    },
    {
        $lookup: {
            "from" : "Users",
            "localField" : "children",
            "foreignField" : "children",
            "as" : "children"
        }
    }
])

Users document:

{
    "_id" : ObjectId("58daf84877733645eaa9b44f"),
    "email" : "meto93@gmail.com",
    "password" : "vpGl+Fjnef616cRgNbCkwaFDpSI=",
    "passwordsalt" : "99397F4A9D3A499D96694547667E74595CE994D2E83345D6953EF866303E8B65",
    "children" : [
        {
            "_id" : ObjectId("58daf84977733645eaa9b450"),
            "name" : "Mert",
            "age" : 5,
            "additionalinformation" : "ilk cocuk",
            "creationtime" : ISODate("2017-03-28T23:56:56.952Z"),
            "userid" : ObjectId("58daf84877733645eaa9b44f"),
            "gender" : null
        },
        {
            "_id" : ObjectId("58daf84977733645eaa9b451"),
            "name" : "Sencer",
            "age" : 7,
            "additionalinformation" : "ikinci cocuk",
            "creationtime" : ISODate("2017-03-28T23:56:56.952Z"),
            "userid" : ObjectId("58daf84877733645eaa9b44f"),
            "gender" : null
        }
    ]
}

Job

{
    "_id" : ObjectId("58db0a2d77733645eaa9b453"),
    "creationtime" : ISODate("2017-03-29T01:13:17.509Z"),
    "startingtime" : ISODate("2017-04-03T13:00:00.000Z"),
    "endingtime" : ISODate("2017-04-03T17:00:00.000Z"),
    "children" : [
        ObjectId("58daf84977733645eaa9b450"),
        ObjectId("58daf84977733645eaa9b451")
    ],
    "creatorparent" : ObjectId("58daf84877733645eaa9b44f"),
    "applicants" : []
}

Body:
Try this:

db.jobs.aggregate(
    [
        {
            $unwind: {
                path : "$children",
            }
        },
        {
            $lookup: {
                "from" : "users",
                "localField" : "creatorparent",
                "foreignField" : "_id",
                "as" : "creatorparent"
            }
        },
        {
            $lookup: {
                "from" : "users",
                "localField" : "children",
                "foreignField" : "children._id",
                "as" : "children"
            }
        },
        {
            $addFields: {
                children : {$arrayElemAt : ["$children",0]}
            }
        },
        {
            $addFields: {
              "children":"$children.children"
            }
        },
        {
            $unwind: {
                path : "$children",
            }
        },
        {
            $group: {
                "_id": "$_id",
                "name": { "$first": "$name" },
                "jobstatus" : { "$first": "$jobstatus" },
                "hourlyrate" : { "$first": "$hourlyrate" },
                "creatorparent" : { "$first" : "$creatorparent" },
                "children": { "$addToSet": "$children"  }
            }
        },

    ]
);


问:
Max pool operation in Matlab?
Is there a function that allows to compute a 2d max-pooling with predefined, kernel size and window stride in Matlab?

I was looking around but couldn't find anything so far...

Say I have a 3D cube of data [HxWxC], I'd like to run a 2d max-pooling on every channel separately (similar to the max-pool operation known from neural networks).

A similar opencv function would also help me out...

答:
Here's another solution that doesn't require the neural network function.

You could do a convolution with your kernel on each channel and then select the slices of the resulting  matrix that you want to keep (which corresponds to the stride). Here's a code sample for a generic case of linear average pooling.

```<code>% pool
kernel = ones(k)/k^2;
temp = conv2(padarray(data, [p p]), kernel, 'valid');
% downsample
pooled_data = temp(1:stride:end, 1:stride:end);
</code>```

You could, of course, use an order statistic filter instead of the linear averaging in this example, or any other pooling function. You can also play around with the padarray value parameter to get the padding behavior you desire.

Title: Max pool operation in Matlab?

Body:
Here's another solution that doesn't require the neural network function.

You could do a convolution with your kernel on each channel and then select the slices of the resulting  matrix that you want to keep (which corresponds to the stride). Here's a code sample for a generic case of linear average pooling.

% pool
kernel = ones(k)/k^2;
temp = conv2(padarray(data, [p p]), kernel, 'valid');
% downsample
pooled_data = temp(1:stride:end, 1:stride:end);

You could, of course, use an order statistic filter instead of the linear averaging in this example, or any other pooling function. You can also play around with the padarray value parameter to get the padding behavior you desire.


问:
How to create a WCF service
I want to learn step by step how to create a WCF service, starting from something very simple.

Can anyone help me?

答:
See this series of web casts by Michelle Bustamonte.

If you are a beginner, this is one of the best sources to learn WCF.

You can also start with the book Learning WCF.

Also take a look at these SO posts -

Learning the basics of WCF

What is the best way to learn WCF?

Good and easy books/tutorials to learn WCF latest stuff

Title: How to create a WCF service


问:
Why PostgreSQL does not like UPPERCASE table names?
I have recently tried to create some tables in PostgreSQL all in uppercase names. However in order to query them I need to put the table name inside the quotation  "TABLE_NAME". Is there any way to avoid this and tell the postgres to work with uppercase name as normal ?

UPDATE

this query create a table with lowercase table_name

```<code>create table TABLE_NAME
(
id integer,
name varchar(255)
)
</code>```

However, this query creates a table with uppercase name "TABLE_NAME"

```<code>create table "TABLE_NAME"
(
id integer,
name varchar(255)
)
</code>```

the problem is the quotations are part of the name now!!
in my case I do not create the tables manually, another Application creates the table and the names are in capital letters. this cause problems when I want to use CQL filters via Geoserver.

答:
put table name into double quotes if you want postgres to preserve case for relation names.

Quoting an identifier also makes it case-sensitive, whereas unquoted
  names are always folded to lower case. For example, the identifiers
  FOO, foo, and "foo" are considered the same by PostgreSQL, but "Foo"
  and "FOO" are different from these three and each other. (The folding
  of unquoted names to lower case in PostgreSQL is incompatible with the
  SQL standard, which says that unquoted names should be folded to upper
  case. Thus, foo should be equivalent to "FOO" not "foo" according to
  the standard. If you want to write portable applications you are
  advised to always quote a particular name or never quote it.)

from docs (emphasis mine)

example with quoting:

```<code>t=# create table "UC_TNAME" (i int);
CREATE TABLE
t=# \dt+ UC

t=# \dt+ "UC_TNAME"
                      List of relations
 Schema |   Name   | Type  |  Owner   |  Size   | Description
--------+----------+-------+----------+---------+-------------
 public | UC_TNAME | table | postgres | 0 bytes |
(1 row)
</code>```

example without quoting:

```<code>t=# create table UC_TNAME (i int);
CREATE TABLE
t=# \dt+ UC_TNAME
                      List of relations
 Schema |   Name   | Type  |  Owner   |  Size   | Description
--------+----------+-------+----------+---------+-------------
 public | uc_tname | table | postgres | 0 bytes |
(1 row)
</code>```

So if you created table with quotes, you should not skip quotes querying it. But if you skipped quotes creating object, the name was folded to lowercase and so will be with uppercase name in query - this way you "won't notice" it.

Body:
I have recently tried to create some tables in PostgreSQL all in uppercase names. However in order to query them I need to put the table name inside the quotation  "TABLE_NAME". Is there any way to avoid this and tell the postgres to work with uppercase name as normal ?

UPDATE

this query create a table with lowercase table_name

create table TABLE_NAME
(
id integer,
name varchar(255)
)

However, this query creates a table with uppercase name "TABLE_NAME"

create table "TABLE_NAME"
(
id integer,
name varchar(255)
)

the problem is the quotations are part of the name now!!
in my case I do not create the tables manually, another Application creates the table and the names are in capital letters. this cause problems when I want to use CQL filters via Geoserver.

Body:
put table name into double quotes if you want postgres to preserve case for relation names.

Quoting an identifier also makes it case-sensitive, whereas unquoted
  names are always folded to lower case. For example, the identifiers
  FOO, foo, and "foo" are considered the same by PostgreSQL, but "Foo"
  and "FOO" are different from these three and each other. (The folding
  of unquoted names to lower case in PostgreSQL is incompatible with the
  SQL standard, which says that unquoted names should be folded to upper
  case. Thus, foo should be equivalent to "FOO" not "foo" according to
  the standard. If you want to write portable applications you are
  advised to always quote a particular name or never quote it.)

from docs (emphasis mine)

example with quoting:

t=# create table "UC_TNAME" (i int);
CREATE TABLE
t=# \dt+ UC

t=# \dt+ "UC_TNAME"
                      List of relations
 Schema |   Name   | Type  |  Owner   |  Size   | Description
--------+----------+-------+----------+---------+-------------
 public | UC_TNAME | table | postgres | 0 bytes |
(1 row)

example without quoting:

t=# create table UC_TNAME (i int);
CREATE TABLE
t=# \dt+ UC_TNAME
                      List of relations
 Schema |   Name   | Type  |  Owner   |  Size   | Description
--------+----------+-------+----------+---------+-------------
 public | uc_tname | table | postgres | 0 bytes |
(1 row)

So if you created table with quotes, you should not skip quotes querying it. But if you skipped quotes creating object, the name was folded to lowercase and so will be with uppercase name in query - this way you "won't notice" it.


问:
Prevent border clipping my image
Okay so I have an image and I want a border outline around it (which I can get). But even if the border is 'x' far away from my image, the image still gets clipped. ONLY HAPPENS WHEN BORDER-RADIUS PROPERTY IS SET. Hopefully, that made some sense but here's some images to show what I mean. Btw sorry if this is anywhere else it's hard to think of good keywords when there's a border-image-outset property and other crap.

   .slideshow {
   display: none;
   margin-top: -50px;
   font-size: 25px;
   }

.slideshow table {
  width: 100%;
}

.slideshow table tr td {
  text-align: center;
}

.icon_circle {
  overflow: hidden;
}

td span {
  display: block;
  border-radius: 90px;
  padding: 30px;
  border: #000 5px solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="slideshow">
    <table>
      <tr>
        <td><img class="icon_circle" width="90px" src="https://i.stack.imgur.com/N2SF1.png" alt=""></td>
        <td><img class="icon_circle" width="90px" src="https://i.stack.imgur.com/N2SF1.png" alt=""></td>
        <td><img class="icon_circle" width="90px"  src="https://i.stack.imgur.com/N2SF1.png" alt=""></td>
      </tr>
    </table>
    <p>Lorem ipdrepnt occaecqui officia deserunt mollit anim id est laborum.</p>
  </div></code>```

Images:

No-Clipping

Clipping

Winrar logo

答:
Give those css properties to td tag, instead of

For example
https://jsfiddle.net/kqogcLk4/

Title: Prevent border clipping my image

Body:
Okay so I have an image and I want a border outline around it (which I can get). But even if the border is 'x' far away from my image, the image still gets clipped. ONLY HAPPENS WHEN BORDER-RADIUS PROPERTY IS SET. Hopefully, that made some sense but here's some images to show what I mean. Btw sorry if this is anywhere else it's hard to think of good keywords when there's a border-image-outset property and other crap.

   .slideshow {
   display: none;
   margin-top: -50px;
   font-size: 25px;
   }

.slideshow table {
  width: 100%;
}

.slideshow table tr td {
  text-align: center;
}

.icon_circle {
  overflow: hidden;
}

td span {
  display: block;
  border-radius: 90px;
  padding: 30px;
  border: #000 5px solid;
}

Lorem ipdrepnt occaecqui officia deserunt mollit anim id est laborum.

Images:

No-Clipping

Clipping

Winrar logo

Body:
Give those css properties to td tag, instead of <img>

For example
https://jsfiddle.net/kqogcLk4/


问:
Access and Display Returned data from Directive
I've searched much but did'nt find any answer for my problem.

I am new to angularJs so please explain in easy way...

i am using a library for social media login ...everything is working fine.. but i want to access and store the returned data from directive in a variable and also want to display that data in div accordingly.

following is code of directive:

```<code>socialLogin.directive("fbLogin", function($rootScope, fbService, social, socialLoginService){
return {
    restrict: 'A',
    scope: {},
    replace: true,
    link: function(scope, ele, attr){
        ele.on('click', function(){
            fbService.login().then(function(res){
                if(res.status == "connected"){
                    fbService.getUserDetails().then(function(user){
                        socialLoginService.setProvider("facebook");
                        var userDetails = {name: user.name, email: user.email, uid: user.id, provider: "facebook", imageUrl: user.picture.data.url}
                        $rootScope.$broadcast('event:social-sign-in-success', userDetails);
                        console.log(userDetails);
                    }, function(err){
                        console.log(err);
                    })
                }
            }, function(err){
                console.log(err);
            });
        });
    }
}
</code>```

})

in console, console.log(userDetails) is display as object now i want to display the data of object in div accordingly and also want to store all data in variables accordingly in variables to send in database...

Please help me in easy way i am new in angular js.
Thanks

答:
Change  scope: {} to  scope: false
This is the default value of scope in the directive definition. In this case, the directive has the same scope as its parent controller.
Now create a userDetails object in your controller scope which will get initialized after FB login.

socialLogin.directive("fbLogin", function($rootScope, fbService, social, socialLoginService){
return {
    restrict: 'A',
    scope: false,
    replace: true,
    link: function(scope, ele, attr){
        ele.on('click', function(){
            fbService.login().then(function(res){
                if(res.status == "connected"){
                    fbService.getUserDetails().then(function(user){
                        socialLoginService.setProvider("facebook");
                        scope.userDetails = {name: user.name, email: user.email, uid: user.id, provider: "facebook", imageUrl: user.picture.data.url}
                        $rootScope.$broadcast('event:social-sign-in-success', userDetails);
                        console.log(scope.userDetails);
                    }, function(err){
                        console.log(err);
                    })
                }
            }, function(err){
                console.log(err);
            });
        });
    }
}```

Now you can use $scope.userDetails.

Body:
I've searched much but did'nt find any answer for my problem.

I am new to angularJs so please explain in easy way...

i am using a library for social media login ...everything is working fine.. but i want to access and store the returned data from directive in a variable and also want to display that data in div accordingly.

following is code of directive:

socialLogin.directive("fbLogin", function($rootScope, fbService, social, socialLoginService){
return {
    restrict: 'A',
    scope: {},
    replace: true,
    link: function(scope, ele, attr){
        ele.on('click', function(){
            fbService.login().then(function(res){
                if(res.status == "connected"){
                    fbService.getUserDetails().then(function(user){
                        socialLoginService.setProvider("facebook");
                        var userDetails = {name: user.name, email: user.email, uid: user.id, provider: "facebook", imageUrl: user.picture.data.url}
                        $rootScope.$broadcast('event:social-sign-in-success', userDetails);
                        console.log(userDetails);
                    }, function(err){
                        console.log(err);
                    })
                }
            }, function(err){
                console.log(err);
            });
        });
    }
}

})

in console, console.log(userDetails) is display as object now i want to display the data of object in div accordingly and also want to store all data in variables accordingly in variables to send in database...

Please help me in easy way i am new in angular js.
Thanks

Body:
Change  scope: {} to  scope: false
This is the default value of scope in the directive definition. In this case, the directive has the same scope as its parent controller.
Now create a userDetails object in your controller scope which will get initialized after FB login.

socialLogin.directive("fbLogin", function($rootScope, fbService, social, socialLoginService){
return {
    restrict: 'A',
    scope: false,
    replace: true,
    link: function(scope, ele, attr){
        ele.on('click', function(){
            fbService.login().then(function(res){
                if(res.status == "connected"){
                    fbService.getUserDetails().then(function(user){
                        socialLoginService.setProvider("facebook");
                        scope.userDetails = {name: user.name, email: user.email, uid: user.id, provider: "facebook", imageUrl: user.picture.data.url}
                        $rootScope.$broadcast('event:social-sign-in-success', userDetails);
                        console.log(scope.userDetails);
                    }, function(err){
                        console.log(err);
                    })
                }
            }, function(err){
                console.log(err);
            });
        });
    }
}

Now you can use $scope.userDetails.


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答:
Making the computer obey me. Awesome.

I also love (love to hate) that the computer will obey even when I'm wrong.

But seriously folks.

I was hooked when:

I saw that you can do rich and dynamic things with code.

That the machine is generally consistent.

That programming is like math in the sense that for all the "it depends" out there, we still have more than our fair share of questions with actual, provable answers.

That I could automate menial tasks with logic and loops.

OwnerDisplayName: Michael Buen

LastEditorDisplayName: Triptych

OwnerDisplayName: Michael Haren


问:
How do I find the closest values in a Pandas series to an input number?
I have seen:

how do I find the closest value to a given number in an array?

How do I find the closest array element to an arbitrary (non-member) number?.

These relate to vanilla python and not pandas.

If I have the series:

```<code>ix   num
0    1
1    6
2    4
3    5
4    2
</code>```

And I input 3, how can I (efficiently) find?

The index of 3 if it is found in the series

The index of the value below and above 3 if it is not found in the series.

Ie. With the above series {1,6,4,5,2}, and input 3, I should get values (4,2) with indexes (2,4).

答:
I recommend using iloc in addition to John Galt's answer since this will work even with unsorted integer index, since .ix first looks at the index labels

```<code>df.iloc[(df['num']-input).abs().argsort()[:2]]
</code>```

Body:
I have seen:

how do I find the closest value to a given number in an array?

How do I find the closest array element to an arbitrary (non-member) number?.

These relate to vanilla python and not pandas.

If I have the series:

ix   num
0    1
1    6
2    4
3    5
4    2

And I input 3, how can I (efficiently) find?

The index of 3 if it is found in the series

The index of the value below and above 3 if it is not found in the series.

Ie. With the above series {1,6,4,5,2}, and input 3, I should get values (4,2) with indexes (2,4).

Body:
I recommend using iloc in addition to John Galt's answer since this will work even with unsorted integer index, since .ix first looks at the index labels

df.iloc[(df['num']-input).abs().argsort()[:2]]


问:
XCode How to Archive and Export without a paid Dev Account
I have Xcode Version 8.2.1 (8C1002). I do not have a paid for developer account yet, so this may be the reason for my problem. However, my questions is, is it possible to export an ipa if you don't have a paid for dev account?

I am able to Archive my project:

However, when I go to, Window -> Organizer, there are no archives:

Questions

Are there no Archives because I don't have a paid for developers account? You can see there are no Provisioning Profiles, which I guess you need a paid for dev account to create?

Is there a way to create an ipa file without the paid for account?

(I am on a limited budget, and need to send an ipa to someone's iPhone who will help me with the look and feel of the app, before I sign up to a 1 years subscription with Apple. I don't want to waste subscription time on development.)

答: Unfortunately, it's impossible. what's more, that app has an In-app purchase feature.</p>


问:
ML Annotator on WKS showing error
I have been trying to launch a ML annotator on WKS however each time I run it fails. All documents are complete and submitted. I am attaching a screenshot of the error too. Any help would be greatenter image description here</p>

答:
You have not accepted the annotation.
Navigate to Human Annotation --> select annotation set --> Accept
Now run the ML model.</p>

Title: ML Annotator on WKS showing error


问:
SQL how to replace string which contains only new lines?
My situation is that in some cases my field contain several (multiple) new lines and nothing else.

I can't use this:

```<code>  SELECT REPLACE(REPLACE(fielddata, CHAR(13), ''), CHAR(10), '')
</code>```

because I also have a normal ones, and as I understand this will replace all new lines.

As I understand, I need somehow check if string contains only new lines, and if it does, replace them with ''.

How can I accomplish that?

答:
One way to solve it is to use case, len, and trim to figure out if the column have data in that specific row:</p>

```<code>SELECT CASE WHEN LEN(
                     LTRIM(
                           RTRIM(
                             REPLACE(
                                     REPLACE(
                                             fielddata, CHAR(13), ''
                                             ), CHAR(10), ''
                                    )
                                )
                          )
                    ) = 0 THEN
           ''
       ELSE
           fielddata
       END as fielddata
</code>```

Body:
My situation is that in some cases my field contain several (multiple) new lines and nothing else.

I can't use this:

  SELECT REPLACE(REPLACE(fielddata, CHAR(13), ''), CHAR(10), '')

because I also have a normal ones, and as I understand this will replace all new lines.

As I understand, I need somehow check if string contains only new lines, and if it does, replace them with ''.

How can I accomplish that?

Body:
One way to solve it is to use case, len, and trim to figure out if the column have data in that specific row:

SELECT CASE WHEN LEN(
                     LTRIM(
                           RTRIM(
                             REPLACE(
                                     REPLACE(
                                             fielddata, CHAR(13), ''
                                             ), CHAR(10), ''
                                    )
                                )
                          )
                    ) = 0 THEN
           ''
       ELSE
           fielddata
       END as fielddata


问:
Video is not showing on VideoView but I can hear its sound

On my button click I wrote the following code for playing video from
my SDCARD (mp4).

```<code>video_view = (VideoView)findViewById(R.id.video_view);
video_view.setVideoPath("/sdcard/myvideo.mp4");
video_view.setMediaController(new MediaController(this));
video_view.start();
</code>```

I can play recorded video from SDCARD in player.

But when I run it on my application in videoview I can hear only sound.

Problem : I am not able to see the video.

---- I tried following SO link but still no luck ----

link 1

link 2

Is anybody ever faced this kind of problem ? If yes then how can it solve it ?

答:
SOLUTION 1:

```<code>videoView.setZOrderOnTop(true);
</code>```

this will set the videoview to the top layer; In other words: block everything under it.

SOLUTION 2:

```<code>videoView.setBackgroundColor(Color.TRANSPARENT);
</code>```

SOLUTION 3:

sometimes this is related about your apptheme; In my case, I changed the apptheme from @style/AppTheme to @android:style/Theme.NoTitleBar.Fullscreen fix my problem.

Body:
On my button click I wrote the following code for playing video from
my SDCARD (mp4).

video_view = (VideoView)findViewById(R.id.video_view);
video_view.setVideoPath("/sdcard/myvideo.mp4");
video_view.setMediaController(new MediaController(this));
video_view.start();

I can play recorded video from SDCARD in player.

But when I run it on my application in videoview I can hear only sound.

Problem : I am not able to see the video.

---- I tried following SO link but still no luck ----

link 1

link 2

Is anybody ever faced this kind of problem ? If yes then how can it solve it ?

Body:
SOLUTION 1:

videoView.setZOrderOnTop(true);

this will set the videoview to the top layer; In other words: block everything under it.

SOLUTION 2:

videoView.setBackgroundColor(Color.TRANSPARENT);

SOLUTION 3:

sometimes this is related about your apptheme; In my case, I changed the apptheme from @style/AppTheme to @android:style/Theme.NoTitleBar.Fullscreen fix my problem.


问:
Must EOT be at the bebinning in the line?
```<code>if(...) {
    if(...) {
        echo <<<EOT
        xxxxxx
EOT;
    }
}
</code>```

or

```<code>if(...) {
    if(...) {
        echo <<<EOT
        xxxxx
        EOT;
    }
}
</code>```

I prefer the latter, because it won't break the structure of code.

But it seems that the latter will cause highlight error in most editors.

Are there any standard stipulate that we must write as the former one? If so, why they make such a unsatisfying standard?

And are there any alternatives for writing block strings in php that won't break the code structure as the former one does? It is really unsatisfying...

答:
Direct from PHP:

Warning It is very important to note that the line with the closing
  identifier must contain no other characters, except a semicolon (;).
  That means especially that the identifier may not be indented, and
  there may not be any spaces or tabs before or after the semicolon.

PHP Manual's reference

Body:
if(...) {
    if(...) {
        echo <<<EOT
        xxxxxx
EOT;
    }
}

or

if(...) {
    if(...) {
        echo <<<EOT
        xxxxx
        EOT;
    }
}

I prefer the latter, because it won't break the structure of code.

But it seems that the latter will cause highlight error in most editors.

Are there any standard stipulate that we must write as the former one? If so, why they make such a unsatisfying standard?

And are there any alternatives for writing block strings in php that won't break the code structure as the former one does? It is really unsatisfying...


问:
IF EXISTS statement alternative in HANA
I want looked for "if exists", but HANA SQL was not understand for "if exists". whether I was created SQL-command wrong.

If 'Y' for the record exists in table from ZZZ_Exercise_3, else 'N' for the record not exists in table from ZZZ_Exercise_3. If old record for 'N' then this record delete should.

```<code> CREATE COLUMN TABLE ers.ZZZ_EXERCISE_5(
    ID INT NOT NULL PRIMARY KEY generated by default as IDENTITY,
    Orig_ID INT,
    COMPANY nvarchar(251),
    VALID char(1)
);

COMMIT;

IF EXISTS(
    INSERT INTO ZZZ_EXERCISE_5(Orig_ID, COMPANY, VALID)
    SELECT ID, COMPANY, 'Y' FROM ZZZ_EXERCISE_3
)
ELSE(
    INSERT INTO ZZZ_EXERCISE_5(Orig_ID, COMPANY, VALID)
    SELECT ID, COMPANY, 'N' FROM ZZZ_EXERCISE_3
)

COMMIT;

UPDATE ZZZ_EXERCISE_3
SET COMPANY = (SELECT COMPANY FROM ERS.ZZZ_EXERCISE_5)
WHERE NOT EXISTS (SELECT COMPANY FROM ZZZ_EXERCISE_5 WHERE ZZZ_EXERCISE_5.VALID = 'N')

COMMIT;

DELETE FROM ZZZ_EXERCISE_3
WHERE ERS.ZZZ_EXERCISE_5.VALID = 'N'

SELECT * FROM ZZZ_EXERCISE_3
WHERE NOT EXISTS (SELECT COMPANY FROM ZZZ_EXERCISE_5 WHERE ZZZ_EXERCISE_5.ID = ZZZ_EXERCISE_3.ID)
</code>```

答:
Not sure which SQL dialect would accept your statement, but IF-THEN-ELSE is typically part of the procedural extension like PL/SQL, T-SQL or SQLScript in SAP HANA.

If you explain more about what you want to achieve (instead of just posting some non-standard syntax that does not work), there are likely options to do it in SAP HANA.

If 'Y' for the record exists in table from ZZZ_Exercise_3, else 'N' for the record not exists in table from ZZZ_Exercise_3. If old record for 'N' then this record delete should.

Based on the revised description, my understanding is that you want

For every record in ZZZ_EXERCISE_5:
check if it exists in ZZZ_EXERCISE_3 and if so, set the VALID field in ZZZ_EXERCISE_5 to Y.

If the records exist in ZZZ_EXERCISE_3 but not in ZZZ_EXERCISE_5, insert that record into ZZZ_EXERCISE_5.

If the records don't exist in ZZZ_EXERCISE_3 but in ZZZ_EXERCISE_5, set VALID to N.

After that, you want to delete all records from ZZZ_EXERCISE_3 for which a matching record in ZZZ_EXERCISE_5 has VALID = N

For step 1, you want to look into the

Step 2 is the easier one, so let's start with that:

```<code>   DELETE FROM ZZZ_EXERCISE_3
   WHERE ID IN (SELECT DISTINCT ID
                FROM ZZZ_EXERCISE_5
                WHERE VALID ='N');
</code>```

Step 1 is a bit more complicated as it shall combine UPDATEs and INSERTS. For this, SAP HANA provides the MERGE command (also called REPLACE). MERGE|REPLACE DOCU

With SAP HANA 2, there also a new command MERGE INTO that is closer to the commonly used MERGE command in other DBMS. MERGE INTO DOCU.

Title: IF EXISTS statement alternative in HANA

Body:
I want looked for "if exists", but HANA SQL was not understand for "if exists". whether I was created SQL-command wrong.

If 'Y' for the record exists in table from ZZZ_Exercise_3, else 'N' for the record not exists in table from ZZZ_Exercise_3. If old record for 'N' then this record delete should.

 CREATE COLUMN TABLE ers.ZZZ_EXERCISE_5(
    ID INT NOT NULL PRIMARY KEY generated by default as IDENTITY,
    Orig_ID INT,
    COMPANY nvarchar(251),
    VALID char(1)
);

COMMIT;

IF EXISTS(
    INSERT INTO ZZZ_EXERCISE_5(Orig_ID, COMPANY, VALID)
    SELECT ID, COMPANY, 'Y' FROM ZZZ_EXERCISE_3
)
ELSE(
    INSERT INTO ZZZ_EXERCISE_5(Orig_ID, COMPANY, VALID)
    SELECT ID, COMPANY, 'N' FROM ZZZ_EXERCISE_3
)

COMMIT;

UPDATE ZZZ_EXERCISE_3
SET COMPANY = (SELECT COMPANY FROM ERS.ZZZ_EXERCISE_5)
WHERE NOT EXISTS (SELECT COMPANY FROM ZZZ_EXERCISE_5 WHERE ZZZ_EXERCISE_5.VALID = 'N')

COMMIT;

DELETE FROM ZZZ_EXERCISE_3
WHERE ERS.ZZZ_EXERCISE_5.VALID = 'N'

SELECT * FROM ZZZ_EXERCISE_3
WHERE NOT EXISTS (SELECT COMPANY FROM ZZZ_EXERCISE_5 WHERE ZZZ_EXERCISE_5.ID = ZZZ_EXERCISE_3.ID)

Body:
Not sure which SQL dialect would accept your statement, but IF-THEN-ELSE is typically part of the procedural extension like PL/SQL, T-SQL or SQLScript in SAP HANA.

If you explain more about what you want to achieve (instead of just posting some non-standard syntax that does not work), there are likely options to do it in SAP HANA.

If 'Y' for the record exists in table from ZZZ_Exercise_3, else 'N' for the record not exists in table from ZZZ_Exercise_3. If old record for 'N' then this record delete should.

Based on the revised description, my understanding is that you want

For every record in ZZZ_EXERCISE_5:
check if it exists in ZZZ_EXERCISE_3 and if so, set the VALID field in ZZZ_EXERCISE_5 to Y.

If the records exist in ZZZ_EXERCISE_3 but not in ZZZ_EXERCISE_5, insert that record into ZZZ_EXERCISE_5.

If the records don't exist in ZZZ_EXERCISE_3 but in ZZZ_EXERCISE_5, set VALID to N.

After that, you want to delete all records from ZZZ_EXERCISE_3 for which a matching record in ZZZ_EXERCISE_5 has VALID = N

For step 1, you want to look into the

Step 2 is the easier one, so let's start with that:

   DELETE FROM ZZZ_EXERCISE_3
   WHERE ID IN (SELECT DISTINCT ID
                FROM ZZZ_EXERCISE_5
                WHERE VALID ='N');

Step 1 is a bit more complicated as it shall combine UPDATEs and INSERTS. For this, SAP HANA provides the MERGE command (also called REPLACE). MERGE|REPLACE DOCU

With SAP HANA 2, there also a new command MERGE INTO that is closer to the commonly used MERGE command in other DBMS. MERGE INTO DOCU.


问:
How can I add condition in array on vue.js 2?
My vue component is like this :

```<code><a :href="baseUrl+'/message/inbox'"
   :class="{ 'active': currentPath === '/message/inbox' }"
 >
    Message
</a>
</code>```

If they meet the conditions then the message menu will be active

But, I want to make it like this :

```<code><a :href="baseUrl+'/message/inbox'"
   :class="{ 'active': currentPath in array ('/message/inbox', '/message/inbox/detail') }"
 >
    Message
</a>
</code>```

So it will check currentPath in the array

How can I do it?

Update :

If I have menu again like this :

```<code><a :href="baseUrl+'/store/sale'"
   :class="{ 'active': currentPath in array ('/store/sale', '/store/sale/detail') }"
 >
    Sale
</a>
</code>```

Or more menu

How to implement it?

Update 2

```<code><a :href="baseUrl+'/message/inbox'"
   :class="{ 'active': isActive }"
 >
    Message
</a>

<a :href="baseUrl+'/store/sale'"
   :class="{ 'active': isActiveSale }"
 >
    Message
</a>

computed: {
  isActive () {
    return ['/message/inbox', '/message/inbox/detail'].indexOf(this.currentPath) > -1
  },
  isActiveSale () {
    return ['/store/sale', '/store/sale/detail'].indexOf(this.currentPath) > -1
  }
}
</code>```

答:
You can use computed properties :

```<code>computed: {
    currentPathInInbox: function() {
        var arrayInbox = ['/message/inbox', '/message/inbox/detail'];
        return arrayInbox.indexOf(this.currentPath) > -1;
    }
}
</code>```

and in template :

```<code>:class="{ 'active': currentPathInInbox }"
</code>```

or with no computed properties :

```<code>:class="{ 'active': (currentPath === '/message/inbox' || (currentPath === '/message/inbox/detail')  }"
</code>```

UPDATED :

I think you need component :

Vue.component( 'linkWithPath', {
 template: '
' +
   '<slot>Link name</slot>
',
  props: {
   baseUrl: { type: String },
    currentPath: { type: String, default: '' },
    relativeUrl: { type: String }
  },
  computed: {
   isActive: function() {
     return [ this.relativeUrl, this.relativeUrl + '/detail'].indexOf(this.currentPath) > -1;
    }
  }
});

Vue.component( 'listOfLinksWithPath', {
 template: '
<link-with-path v-for="menuItem in menuArray"' +
  ':key="menuItem" :base-url="baseUrl" :current-path="currentPath"' +
  ':relative-url="menuItem.url">{{ menuItem.name }}</link-with-path>
',
  props: {
   baseUrl: { type: String },
    currentPath: { type: String },
    menuArray: { type: Array }
  }
});

new Vue({
 el: "#app",
  data: function() {
   return {
     baseUrl: 'http://www.CHANGETHISURL.com',
      currentPath: '/message/inbox',
     menuArray: [ { name: 'Message', url: '/message/inbox' },
              { name: 'Sale', url: '/store/sale' } ]
    }
  },
  methods: {
   changeCurrentPath: function() {
     this.currentPath = '/store/sale'
    }
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a.active{
  color: red;
}</code>```

Link is active when it is red.

  <list-of-links-with-path :base-url="baseUrl" :menu-array="menuArray" :current-path="currentPath"></list-of-links-with-path>

  <button @click="changeCurrentPath" type="button">Change current path</button>

  currentPath : {{ currentPath }}

```

Body:
My vue component is like this :

    Message

If they meet the conditions then the message menu will be active

But, I want to make it like this :

    Message

So it will check currentPath in the array

How can I do it?

Update :

If I have menu again like this :

    Sale

Or more menu

How to implement it?

Update 2

    Message

    Message

computed: {
  isActive () {
    return ['/message/inbox', '/message/inbox/detail'].indexOf(this.currentPath) > -1
  },
  isActiveSale () {
    return ['/store/sale', '/store/sale/detail'].indexOf(this.currentPath) > -1
  }
}

Body:
You can use computed properties :

computed: {
    currentPathInInbox: function() {
        var arrayInbox = ['/message/inbox', '/message/inbox/detail'];
        return arrayInbox.indexOf(this.currentPath) > -1;
    }
}

and in template :

:class="{ 'active': currentPathInInbox }"

or with no computed properties :

:class="{ 'active': (currentPath === '/message/inbox' || (currentPath === '/message/inbox/detail')  }"

UPDATED :

I think you need component :

Vue.component( 'linkWithPath', {
 template: '<div><a :href="baseUrl + relativeUrl"' +
   ':class="{ \'active\': isActive }">' +
   '<slot>Link name</slot></a></div>',
  props: {
   baseUrl: { type: String },
    currentPath: { type: String, default: '' },
    relativeUrl: { type: String }
  },
  computed: {
   isActive: function() {
     return [ this.relativeUrl, this.relativeUrl + '/detail'].indexOf(this.currentPath) > -1;
    }
  }
});

Vue.component( 'listOfLinksWithPath', {
 template: '<div><link-with-path v-for="menuItem in menuArray"' +
  ':key="menuItem" :base-url="baseUrl" :current-path="currentPath"' +
  ':relative-url="menuItem.url">{{ menuItem.name }}</link-with-path></div>',
  props: {
   baseUrl: { type: String },
    currentPath: { type: String },
    menuArray: { type: Array }
  }
});

new Vue({
 el: "#app",
  data: function() {
   return {
     baseUrl: 'http://www.CHANGETHISURL.com',
      currentPath: '/message/inbox',
     menuArray: [ { name: 'Message', url: '/message/inbox' },
              { name: 'Sale', url: '/store/sale' } ]
    }
  },
  methods: {
   changeCurrentPath: function() {
     this.currentPath = '/store/sale'
    }
  }
});

a.active{
  color: red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.5/vue.js"></script>

<div id="app">

  <p>Link is active when it is red.</p>

  <list-of-links-with-path :base-url="baseUrl" :menu-array="menuArray" :current-path="currentPath"></list-of-links-with-path>

  <br />
  <button @click="changeCurrentPath" type="button">Change current path</button>
  <br />
  currentPath : {{ currentPath }}

</div>