问:
How to give a python script limited access to azure blob container
I want my python script to be able to append new blobs to my container in azure. Using Shared Access Signatures (SAS) seems to be the way to go.

But I can't figure out how to use them. I don't want to give the script full access to the azure account by giving it the storage account key so using a SAS and limiting the abilities of the script to create and removing delete, get and list seems to be ok.
But how to I use the token in the script?

Here is my test code:

```<code>#!/usr/bin/env python3

import requests
from azure.storage.blob import BlockBlobService, ContainerPermissions, ContentSettings

# this is only for testing, account key will be removed later

account_name = 'myaccountname'
account_key = 'myaccountkey'
container_name = 'mycontainer'
existing_file = 'existing_file.jpg'
new_file = 'test.jpg'

service = BlockBlobService(
    account_name=account_name,
    account_key=account_key
)
# There are two ways to create a permission
# 1. Assign boolean values to `read`/`add`/`create`/`write`/`delete` operation
# permission = BlobPermissions(read=True, add=True, create=True, write=True, delete=True)
# 2. Just simply assign a string to `_str`(A string representing the permissions) like `racwd` which means assign True to all operation
permission = ContainerPermissions(write=True)
sas = service.generate_container_shared_access_signature(
    container_name=container_name,
    permission=permission,
    protocol='https'
)
print(sas)

# Here begins the real script

service = BlockBlobService(
    account_name=account_name,
    sas_token=sas
)

assert service.exists(container_name=container_name, blob_name=existing_file)

service.create_blob_from_path(
        container_name=container_name,
        blob_name=new_file,
        file_path='./%s' % new_file,
        content_settings=ContentSettings(content_type=mimetypes.guess_type('./%s' % new_file)[0]),
        validate_content=True
)

r = requests.head('https://%s.blob.core.windows.net/%s/%s' % (account_name, container_name, new_file), timeout=2)
assert r.status_code == 200
</code>```

This fails service.exists() call with: azure.common.AzureHttpError: Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.

答:
I solved it. For anyone who is interested, here is the working script:

```<code>#!/usr/bin/env python3

import mimetypes
mimetypes.init()
from datetime import datetime, timedelta

import requests
from azure.storage.blob import BlockBlobService, ContainerPermissions, ContentSettings

account_name = 'myaccount'
account_key = 'mykey'
container_name = 'mycontainer'
new_file = 'new_pic.jpg'
existing_file = 'old_pic.jpg'

service = BlockBlobService(account_name=account_name, account_key=account_key)
permission = ContainerPermissions(read=True, write=True)
sas = service.generate_container_shared_access_signature(container_name=container_name, permission=permission,
        protocol='https', start=datetime.now(), expiry=datetime.now() + timedelta(days=1))
print(sas)

service = BlockBlobService(account_name=account_name, sas_token=sas)

assert service.exists(container_name=container_name, blob_name=existing_file)

service.create_blob_from_path(
        container_name=container_name,
        blob_name=new_file,
        file_path=new_file,
        content_settings=ContentSettings(content_type=mimetypes.guess_type(new_file)[0]),
        validate_content=True
)

r = requests.head('https://%s.blob.core.windows.net/%s/%s' % (account_name, container_name, new_file), timeout=2)
assert r.status_code == 200
</code>```

The important stuff is using ContainerPermissions and getting the datetimes right. Timezones are your worst nightmare!

Body:
I want my python script to be able to append new blobs to my container in azure. Using Shared Access Signatures (SAS) seems to be the way to go.

But I can't figure out how to use them. I don't want to give the script full access to the azure account by giving it the storage account key so using a SAS and limiting the abilities of the script to create and removing delete, get and list seems to be ok.
But how to I use the token in the script?

Here is my test code:

#!/usr/bin/env python3

import requests
from azure.storage.blob import BlockBlobService, ContainerPermissions, ContentSettings

# this is only for testing, account key will be removed later

account_name = 'myaccountname'
account_key = 'myaccountkey'
container_name = 'mycontainer'
existing_file = 'existing_file.jpg'
new_file = 'test.jpg'

service = BlockBlobService(
    account_name=account_name,
    account_key=account_key
)
# There are two ways to create a permission
# 1. Assign boolean values to `read`/`add`/`create`/`write`/`delete` operation
# permission = BlobPermissions(read=True, add=True, create=True, write=True, delete=True)
# 2. Just simply assign a string to `_str`(A string representing the permissions) like `racwd` which means assign True to all operation
permission = ContainerPermissions(write=True)
sas = service.generate_container_shared_access_signature(
    container_name=container_name,
    permission=permission,
    protocol='https'
)
print(sas)

# Here begins the real script

service = BlockBlobService(
    account_name=account_name,
    sas_token=sas
)

assert service.exists(container_name=container_name, blob_name=existing_file)

service.create_blob_from_path(
        container_name=container_name,
        blob_name=new_file,
        file_path='./%s' % new_file,
        content_settings=ContentSettings(content_type=mimetypes.guess_type('./%s' % new_file)[0]),
        validate_content=True
)

r = requests.head('https://%s.blob.core.windows.net/%s/%s' % (account_name, container_name, new_file), timeout=2)
assert r.status_code == 200

This fails service.exists() call with: azure.common.AzureHttpError: Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.

Body:
I solved it. For anyone who is interested, here is the working script:

#!/usr/bin/env python3

import mimetypes
mimetypes.init()
from datetime import datetime, timedelta

import requests
from azure.storage.blob import BlockBlobService, ContainerPermissions, ContentSettings

account_name = 'myaccount'
account_key = 'mykey'
container_name = 'mycontainer'
new_file = 'new_pic.jpg'
existing_file = 'old_pic.jpg'

service = BlockBlobService(account_name=account_name, account_key=account_key)
permission = ContainerPermissions(read=True, write=True)
sas = service.generate_container_shared_access_signature(container_name=container_name, permission=permission,
        protocol='https', start=datetime.now(), expiry=datetime.now() + timedelta(days=1))
print(sas)

service = BlockBlobService(account_name=account_name, sas_token=sas)

assert service.exists(container_name=container_name, blob_name=existing_file)

service.create_blob_from_path(
        container_name=container_name,
        blob_name=new_file,
        file_path=new_file,
        content_settings=ContentSettings(content_type=mimetypes.guess_type(new_file)[0]),
        validate_content=True
)

r = requests.head('https://%s.blob.core.windows.net/%s/%s' % (account_name, container_name, new_file), timeout=2)
assert r.status_code == 200

The important stuff is using ContainerPermissions and getting the datetimes right. Timezones are your worst nightmare!


来源: stackexchange

问:
Angular-jwplayer issue
Hi I am using angular Jwplayer https://github.com/ds62987/angular-jwplayer to play HLS(live streaming).
I have the html

```<code> <jwplayer player-id="{{cameradetails.id}}" camera="cameradetails"
    setup="liveStreamCtrl.options"></jwplayer>
</code>```

And the Controller looks like

```<code>var cameraObject = {
image: "../../assets/images/main/live-streaming/video-default.jpg",
    width: "100%",
    height: "100%",
    androidhls: true,
    playlist: [{
        sources: [{
            //Desktop: Use RTMP protocol and played by flash.
    file: "//52.2.142.67:1935/58d385775914156fc85a2795/" + window.localStorage.getItem('token') + "/58d65451555c6d75e3b7c51f.stream"
                       }, {
    //Mobile: Use HLS protocol and played by HTML5
    file: "//52.2.142.67:1935/58d385775914156fc85a2795/" + window.localStorage.getItem('token') + "/58d65451555c6d75e3b7c51f.stream/playlist.m3u8"
                        }, ]
                    }],
                    primary: "flash"
             };
    var dahuaCameraObject = cameraObject;
    self.options[value.id] = dahuaCameraObject;
</code>```

When I an running setup it is giving me the  following error and returns player timeout err.

```<code>Uncaught DOMException: Failed to execute 'querySelector' on 'Element': '#58d3ba2dfc21ab4b4dc7199f-ade55c26e70e4' is not a valid selector.
at http://localhost:8585/client/dev/assets/js/clientAccount/directives/player.js:5:12043 (anonymous) @ player.js:5 player.js:5 Uncaught DOMException: Failed to execute 'querySelector' on 'Element':  #58d5fa103f2bba6af0327842-85fa6e4830107' is not a valid selector. at http://localhost:8585/client/dev/assets/js/clientAccount/directives/player.js:5:12043
</code>```

http://imgur.com/a/KCmOa

答:
```<code>androidhls: true,
primary: "flash"
</code>```

I changes this to

```<code>  "primary": "html5",
  "hlshtml": true,
</code>```

i.e playing the videos by html5 instead of flash is woking fine

ContentLicense: CC BY-SA 3.0

Title: Angular-jwplayer issue

Body:
Hi I am using angular Jwplayer https://github.com/ds62987/angular-jwplayer to play HLS(live streaming).
I have the html

 <jwplayer player-id="{{cameradetails.id}}" camera="cameradetails"
    setup="liveStreamCtrl.options"></jwplayer>

And the Controller looks like

var cameraObject = {
image: "../../assets/images/main/live-streaming/video-default.jpg",
    width: "100%",
    height: "100%",
    androidhls: true,
    playlist: [{
        sources: [{
            //Desktop: Use RTMP protocol and played by flash.
    file: "//52.2.142.67:1935/58d385775914156fc85a2795/" + window.localStorage.getItem('token') + "/58d65451555c6d75e3b7c51f.stream"
                       }, {
    //Mobile: Use HLS protocol and played by HTML5
    file: "//52.2.142.67:1935/58d385775914156fc85a2795/" + window.localStorage.getItem('token') + "/58d65451555c6d75e3b7c51f.stream/playlist.m3u8"
                        }, ]
                    }],
                    primary: "flash"
             };
    var dahuaCameraObject = cameraObject;
    self.options[value.id] = dahuaCameraObject;

When I an running setup it is giving me the  following error and returns player timeout err.

Uncaught DOMException: Failed to execute 'querySelector' on 'Element': '#58d3ba2dfc21ab4b4dc7199f-ade55c26e70e4' is not a valid selector.
at http://localhost:8585/client/dev/assets/js/clientAccount/directives/player.js:5:12043 (anonymous) @ player.js:5 player.js:5 Uncaught DOMException: Failed to execute 'querySelector' on 'Element':  #58d5fa103f2bba6af0327842-85fa6e4830107' is not a valid selector. at http://localhost:8585/client/dev/assets/js/clientAccount/directives/player.js:5:12043

http://imgur.com/a/KCmOa

Body:
androidhls: true,
primary: "flash"

I changes this to

  "primary": "html5",
  "hlshtml": true,

i.e playing the videos by html5 instead of flash is woking fine


问:
Should I use std::list or is there a better method?
I am currently coding in a 2D geometry editor in c++. I am having the user place nodes. Lines and arcs can be drawn by selecting 2 nodes.

Right now, I am storing the nodes in a std::deque container (same thing for the lines and arcs) because I would like to store the address of the node into each line/arc. This makes things very convenient coding wise when I implement a feature to move the node. If I were to store the actual node inside of each line/arc, then when I want to move a node, then I would have to iterate through the entire line and arc stucture to find the node that I just moved and update the parameters. This option isn't an option on the table. Hence, the need to be able to store the address of the node inside each line/arc.

However, I am running into some issue where I need to delete the node. Looking on the reference manual, it seems that for all pointer, these are invalidated when you erase an element from the deque (unless that element is at the beginning or the end. For the sake of discussion, I will not be considering this case). This causes issue with the erasing because now, all of my lines/arc reconnect themselves to different nodes or are not drawn at all when a node is erased and the program eventually crashes.

Continuing to look online, I come across std::list which (from my understanding of reading the documentation) does not invalidate any pointers or references when one of the elements is erased. This seems to be a very nice solution to my problem.

However, I have been looking a little bit on stack overflow to see what are the benefits/disadvantages of using a list vs a deque. And it seems like there is more of a preference to use a deque then a list. It seems as though the list is slower to access then the deque. This is not good because I am not sure how many nodes a user would like to draw. For all I know, there could be 10,000+ nodes in the geometry and if the user wants to move a node, I don't want the user have to wait 30 sec for the program to iterate through all of the elements to find the node(s) to erase.

So on one hand, deque are alot faster but as soon as an element is removed, all of the pointers and references are invalidated. On the other hand, std::list allows me to erase whatever element I want without invalidating any of the pointers and references but is slower compared to a deque.

I am considering to switch to a list because even if the list is slower, if I can't erase an element without invalidating the pointers and references, then there isn't much of a benefit speed wise if the program doesn't work.

However, is using a list the best choice in my situation? Is there any way to use a deque? Or is there a third option that I haven't considered?

Edit:

I forgot to mention. One thing that I am not to fond of with lists is the inability to get an element's data directly (in std::deque and vector, I can use the at function to access elements). This isn't a huge deal breaker with my code. But it does makes things convenient. For example, when a user selects a node when they want to create a line/arc, the code iterates over the entire node list to find out which one was selected and then, for the first selection, stores the index into a variable (called firstNodeIndex). For the second node, it does the same thing but when both variables (firstNodeIndex and secondNodeIndex) are viable numbers, then the function for creating the line/arc is called and the function uses the two stored indexes to re-access the node list to grab an address to the node. If I were to use the list, I would have to store the address of the two nodes in variables and then create some additional logic to make sure that the two variables containing the addresses to the two nodes are viable options.

Another alternate solution would be to reiterate through the entire node list again to grab the nodes that are selected (I would have a variable inside each node to indicate that it is selected). But I am afraid that this might not be a good idea given std::list limitations.

I am kind of in favor of my first way but I am open to change if need be or if there is a better method

答:
So your problem is that you don't want your iterators invalidated when you insert or erase element, but you want your data structure to be fast.

Linked list is only slow when you have to iterate all elements frequently. In does not take advantage of continuous data access like vector or deque. Also linear search in list is slow.

I had similar situations. Here are some options:

Use list and try to avoid linear searches. See if memory access speed of linked list affect your performance significantly and if it doesn't - use it.

Use map or set. Same cons as list except search, which is O(logn). Or you can use unordered versions if you don't care about sorting elements.

Use non-standard data structure like plf::colony. If you don't care about order of insertion, this is probably your best option.

Create your own deque-like data structure that does not invalidate iterators (using skipfields or storing free elements somewhere). I wouldn't recommend it since you will probably end up writing something like plf::colony anyway.


问:
AngularJS txn.price is non-assignable
I am using AngularJS and trying to format float in input text as below.

```<code><input ng-model="txn.price | number:3" name="price" ng-pattern="/^\d+([,.]\d+)?$/" md-maxlength="30" required ng-change="calcUnits()">
</code>```

but i am getting below error.

```<code>Error: ngModel:nonassign
Non-Assignable Expression
Expression 'txn.price' is non-assignable. Element: {1}
</code>```

答:
It is non assignable because you are running the model through a filter.  This means the data can't be set because you are modeling a return value instead of the original item.  You need to change your model to ng-model="txn.price"

Alternatively you may want to use $filter('number')(txn.price, 3) in your controller function.

$filter('number')(number, fractionSize)

Title: AngularJS txn.price is non-assignable

Body:
I am using AngularJS and trying to format float in input text as below.

<input ng-model="txn.price | number:3" name="price" ng-pattern="/^\d+([,.]\d+)?$/" md-maxlength="30" required ng-change="calcUnits()">

but i am getting below error.

Error: ngModel:nonassign
Non-Assignable Expression
Expression 'txn.price' is non-assignable. Element: {1}


问:
How to post raw data in swift 3?
If I post raw data using Postman, response is coming. I am using this code

```<code> var dict = Dictionary<String, Any>()
 dict = ["user_id" :userid as AnyObject, "type" :type as AnyObject, "complaint_id" :complaintId as AnyObject,  "auth_code" : authCode as AnyObject, "isSkip" :isSkip as AnyObject]

 let url:URL = URL(string: "http://development.easystartup.org/prigovo/Backend/detailed_complaint/index.php")!
    let session = URLSession.shared

   var postData = NSData()
    do{

    postData = try JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions.prettyPrinted) as NSData!
    }catch {
        print("error")
    }

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
   // request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
    request.setValue("\(postData.length)", forHTTPHeaderField: "Content-Length")
    request.setValue("text/html", forHTTPHeaderField: "Content-Type")
    request.setValue("json/application", forHTTPHeaderField: "Accept")

    request.httpBody = postData as Data

    let task = session.dataTask(with: request as URLRequest) {
        (
        data, response, error) in

        guard let data = data, let _:URLResponse = response, error == nil else {
            print("error")
            return
        }
        let dataString =  String(data: data, encoding: String.Encoding.utf8)
        print(dataString ?? "no data")
    }
    task.resume()
</code>```

Getting data of 0 bytes everyTime. Already tried with Alamofire but no response.

Also I tried in Objective C where I am getting response, code is :

```<code>  NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)postData.length] forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"text/html" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];

    NSError *error = nil;
    NSHTTPURLResponse *response = nil;

    [[NSURLConnection alloc] initWithRequest:request delegate:self];

    NSData *retData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    if (error)
    {
        //error
        NSLog(@"error");
        return @"";
    }
    else
    {
        NSLog(@"No error");
        NSString *charlieSendString = [[NSString alloc] initWithData:retData encoding:NSUTF8StringEncoding];
        NSLog(@"data come : %@",charlieSendString);
        return charlieSendString;
    }
</code>```

Posted "dict" in Log :

["complaint_id": COMBRD1, "user_id": USR9, "type": complaint_brand, "auth_code": KL1hwYrAhNVnSgT, "is_skip": 2]

答:
```<code>var dict = Dictionary<String, Any>()

    dict = ["user_id" :userid, "type" :type, "complaint_id" :complaintId,"auth_code" : authCode, "is_skip" :isSkip]
    var  jsonData = NSData()

   // var dataString2 :String = ""
    do {
         jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) as NSData
        // you can now cast it with the right type
    } catch {
        print(error.localizedDescription)
    }

    let url:URL = URL(string: "http://Backend/detailed_complaint/index.php")!
    let session = URLSession.shared

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("\(jsonData.length)", forHTTPHeaderField: "Content-Length")
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpBody = jsonData as Data

    let task = session.dataTask(with: request as URLRequest) {
        (
        data, response, error) in

        guard let data = data, let _:URLResponse = response, error == nil else {
            print("error")
            return
        }
        let dataString =  String(data: data, encoding: String.Encoding.utf8)
        print("no data",dataString ?? "no data")
    }
    task.resume()
</code>```

Title: How to post raw data in swift 3?

Body:
If I post raw data using Postman, response is coming. I am using this code

 var dict = Dictionary<String, Any>()
 dict = ["user_id" :userid as AnyObject, "type" :type as AnyObject, "complaint_id" :complaintId as AnyObject,  "auth_code" : authCode as AnyObject, "isSkip" :isSkip as AnyObject]

 let url:URL = URL(string: "http://development.easystartup.org/prigovo/Backend/detailed_complaint/index.php")!
    let session = URLSession.shared

   var postData = NSData()
    do{

    postData = try JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions.prettyPrinted) as NSData!
    }catch {
        print("error")
    }

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
   // request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
    request.setValue("\(postData.length)", forHTTPHeaderField: "Content-Length")
    request.setValue("text/html", forHTTPHeaderField: "Content-Type")
    request.setValue("json/application", forHTTPHeaderField: "Accept")

    request.httpBody = postData as Data

    let task = session.dataTask(with: request as URLRequest) {
        (
        data, response, error) in

        guard let data = data, let _:URLResponse = response, error == nil else {
            print("error")
            return
        }
        let dataString =  String(data: data, encoding: String.Encoding.utf8)
        print(dataString ?? "no data")
    }
    task.resume()

Getting data of 0 bytes everyTime. Already tried with Alamofire but no response.

Also I tried in Objective C where I am getting response, code is :

  NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)postData.length] forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"text/html" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];

    NSError *error = nil;
    NSHTTPURLResponse *response = nil;

    [[NSURLConnection alloc] initWithRequest:request delegate:self];

    NSData *retData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    if (error)
    {
        //error
        NSLog(@"error");
        return @"";
    }
    else
    {
        NSLog(@"No error");
        NSString *charlieSendString = [[NSString alloc] initWithData:retData encoding:NSUTF8StringEncoding];
        NSLog(@"data come : %@",charlieSendString);
        return charlieSendString;
    }

Posted "dict" in Log :

["complaint_id": COMBRD1, "user_id": USR9, "type": complaint_brand, "auth_code": KL1hwYrAhNVnSgT, "is_skip": 2]


问:
How do I create FIX partyID group?
I am trying to add a PartyID group to a FIX4.4 message.

I cannot find a "group" for PartyID. So I am adding them sequentially.

NoPartyIDs, PartyRole, PartyIDSource, PartyID

However, whichever way I add them, the fix engine appears to reorder them.

How should I do this, or is there a way to specify order?

```<code>    public QuickFix.FIX44.MarketDataRequest QueryMarketDataRequest44(string symbol)
    {
        MDReqID mdReqID = new MDReqID("RqID"+symbol);
        SubscriptionRequestType subType = new SubscriptionRequestType(SubscriptionRequestType.SNAPSHOT_PLUS_UPDATES);
        MarketDepth marketDepth = new MarketDepth(1);

        QuickFix.FIX44.MarketDataRequest.NoMDEntryTypesGroup marketDataEntryGroup = new QuickFix.FIX44.MarketDataRequest.NoMDEntryTypesGroup();

        QuickFix.FIX44.MarketDataRequest.NoRelatedSymGroup symbolGroup = new QuickFix.FIX44.MarketDataRequest.NoRelatedSymGroup();
        symbolGroup.Set(new Symbol(symbol));

        QuickFix.FIX44.MarketDataRequest message = new QuickFix.FIX44.MarketDataRequest(mdReqID, subType, marketDepth);
        message.Set(new MDUpdateType(0));
        message.AddGroup(symbolGroup);

        QuickFix.Fields.NoPartyIDs noPartyIDs = new QuickFix.Fields.NoPartyIDs(1);
        QuickFix.Fields.PartyID partyID = new QuickFix.Fields.PartyID("XXXX");
        QuickFix.Fields.PartyIDSource partyIDSource = new QuickFix.Fields.PartyIDSource('D');
        QuickFix.Fields.PartyRole partyRole = new QuickFix.Fields.PartyRole(35);

        message.SetField(noPartyIDs);
        message.SetField(partyRole);
        message.SetField(partyIDSource);
        message.SetField(partyID);

        return message;
    }
</code>```

答:
This worked for me. I used Quote.NoPartyIDsGroup. Odd that there isn't such a group in MarketDataRequest.</p>

```<code>QuickFix.Fields.NoPartyIDs noPartyIDs = new QuickFix.Fields.NoPartyIDs(1);
            QuickFix.Fields.PartyID partyID = new QuickFix.Fields.PartyID(lp);
            QuickFix.Fields.PartyIDSource partyIDSource = new QuickFix.Fields.PartyIDSource('D');
            QuickFix.Fields.PartyRole partyRole = new QuickFix.Fields.PartyRole(35);

          QuickFix.FIX44.Quote.NoPartyIDsGroup group = new Quote.NoPartyIDsGroup();

            group.SetField(noPartyIDs);
            group.SetField(partyRole);
            group.SetField(partyIDSource);
            group.SetField(partyID);

            message.AddGroup(group);
</code>```

Title: How do I create FIX partyID group?

Body:
I am trying to add a PartyID group to a FIX4.4 message.

I cannot find a "group" for PartyID. So I am adding them sequentially.

NoPartyIDs, PartyRole, PartyIDSource, PartyID

However, whichever way I add them, the fix engine appears to reorder them.

How should I do this, or is there a way to specify order?

    public QuickFix.FIX44.MarketDataRequest QueryMarketDataRequest44(string symbol)
    {
        MDReqID mdReqID = new MDReqID("RqID"+symbol);
        SubscriptionRequestType subType = new SubscriptionRequestType(SubscriptionRequestType.SNAPSHOT_PLUS_UPDATES);
        MarketDepth marketDepth = new MarketDepth(1);

        QuickFix.FIX44.MarketDataRequest.NoMDEntryTypesGroup marketDataEntryGroup = new QuickFix.FIX44.MarketDataRequest.NoMDEntryTypesGroup();

        QuickFix.FIX44.MarketDataRequest.NoRelatedSymGroup symbolGroup = new QuickFix.FIX44.MarketDataRequest.NoRelatedSymGroup();
        symbolGroup.Set(new Symbol(symbol));

        QuickFix.FIX44.MarketDataRequest message = new QuickFix.FIX44.MarketDataRequest(mdReqID, subType, marketDepth);
        message.Set(new MDUpdateType(0));
        message.AddGroup(symbolGroup);

        QuickFix.Fields.NoPartyIDs noPartyIDs = new QuickFix.Fields.NoPartyIDs(1);
        QuickFix.Fields.PartyID partyID = new QuickFix.Fields.PartyID("XXXX");
        QuickFix.Fields.PartyIDSource partyIDSource = new QuickFix.Fields.PartyIDSource('D');
        QuickFix.Fields.PartyRole partyRole = new QuickFix.Fields.PartyRole(35);

        message.SetField(noPartyIDs);
        message.SetField(partyRole);
        message.SetField(partyIDSource);
        message.SetField(partyID);

        return message;
    }

Body:
This worked for me. I used Quote.NoPartyIDsGroup. Odd that there isn't such a group in MarketDataRequest.

QuickFix.Fields.NoPartyIDs noPartyIDs = new QuickFix.Fields.NoPartyIDs(1);
            QuickFix.Fields.PartyID partyID = new QuickFix.Fields.PartyID(lp);
            QuickFix.Fields.PartyIDSource partyIDSource = new QuickFix.Fields.PartyIDSource('D');
            QuickFix.Fields.PartyRole partyRole = new QuickFix.Fields.PartyRole(35);

          QuickFix.FIX44.Quote.NoPartyIDsGroup group = new Quote.NoPartyIDsGroup();

            group.SetField(noPartyIDs);
            group.SetField(partyRole);
            group.SetField(partyIDSource);
            group.SetField(partyID);

            message.AddGroup(group);


问:
Segmentation Fault in linkedlist and debugging options for Linux
full code: ( https://github.com/martin-varbanov96/fmi_summer_2017/tree/master/daa/bfs )

So I have to do a graph BFS, but first I have to make a fully working linkedList and I have a problem with the segmentation fault.

The real problem here is that I am using Linux and trying to learn vim and so I have no good way of debugging and I have to use gdb.

The general problem is that I have a node struct and I want to assign it a value but it gives a Segmentation fault. Here is the node:

```<code>struct node{
        int value;
        node* next;
};
</code>```

and than in the main function, program crashes in the assigment:

```<code>int main(){
        node* b;
        b->value=1;
        linkedList a;
         ...
</code>```

this is the gdb result:

```<code>Wed Mar 29; 15:59:29; marton;~/documents/github/fmi_summer_2017/daa/bfs ;  $  gdb a.out
GNU gdb (GDB; openSUSE Leap 42.1) 7.11.1
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-suse-linux".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://bugs.opensuse.org/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from a.out...done.
(gdb) start
Temporary breakpoint 1 at 0x4008f5: file main.cpp, line 5.
Starting program: /home/marton/documents/github/fmi_summer_2017/daa/bfs/a.out
step
Temporary breakpoint 1, main () at main.cpp:5
5               b->value=1;
(gdb) step

Program received signal SIGSEGV, Segmentation fault.
0x00000000004008f9 in main () at main.cpp:5
5               b->value=1;
(gdb)

Program terminated with signal SIGSEGV, Segmentation fault.
The program no longer exists.
(gdb)
</code>```

So my question is what is the problem with my code and what do I need to do to fix it and is there a better way to debug my things in the future?

EDIT:

changes main, as said:

```<code>int main(){
        node* b=new node();
        b->value=1;
</code>```

gdb:

```<code>Temporary breakpoint 1, main () at main.cpp:4
4               node* b=new node();
(gdb) step
operator new (sz=16) at ../../../../libstdc++-v3/libsupc++/new_op.cc:43
43      ../../../../libstdc++-v3/libsupc++/new_op.cc: No such file or directory.
(gdb)
48      in ../../../../libstdc++-v3/libsupc++/new_op.cc
(gdb)
43      in ../../../../libstdc++-v3/libsupc++/new_op.cc
(gdb)
48      in ../../../../libstdc++-v3/libsupc++/new_op.cc
(gdb)
50      in ../../../../libstdc++-v3/libsupc++/new_op.cc
(gdb)

__GI___libc_malloc (bytes=16) at malloc.c:2897
2897    malloc.c: No such file or directory.
(gdb)
2902    in malloc.c
(gdb)
2903    in malloc.c
(gdb)
2906    in malloc.c
(gdb)
2908    in malloc.c
(gdb)
_int_malloc (av=av@entry=0x7ffff753a620 <main_arena>, bytes=bytes@entry=16) at malloc.c:3325
3325    in malloc.c
(gdb)
3355    in malloc.c
(gdb)
3359    in malloc.c
(gdb)
3373    in malloc.c
(gdb)
3375    in malloc.c
</code>```

Real problem is how to debug properly with vim and linux

答:
```<code>int main(){
    node* b;
    b->value=1;
    linkedList a;
</code>```

Problem is pointer b, you declared a pointer type of node, but it points null(nowhere),then you try assign  b->value, therefore throw  a segmentation fault.
You must assign  a address your pointer b ,like below,

```<code>b=new node;
b->value=1;
</code>```

then you can assign any value

Body:
full code: ( https://github.com/martin-varbanov96/fmi_summer_2017/tree/master/daa/bfs )

So I have to do a graph BFS, but first I have to make a fully working linkedList and I have a problem with the segmentation fault.

The real problem here is that I am using Linux and trying to learn vim and so I have no good way of debugging and I have to use gdb.

The general problem is that I have a node struct and I want to assign it a value but it gives a Segmentation fault. Here is the node:

struct node{
        int value;
        node* next;
};

and than in the main function, program crashes in the assigment:

int main(){
        node* b;
        b->value=1;
        linkedList a;
         ...

this is the gdb result:

Wed Mar 29; 15:59:29; marton;~/documents/github/fmi_summer_2017/daa/bfs ;  $  gdb a.out
GNU gdb (GDB; openSUSE Leap 42.1) 7.11.1
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-suse-linux".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://bugs.opensuse.org/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from a.out...done.
(gdb) start
Temporary breakpoint 1 at 0x4008f5: file main.cpp, line 5.
Starting program: /home/marton/documents/github/fmi_summer_2017/daa/bfs/a.out
step
Temporary breakpoint 1, main () at main.cpp:5
5               b->value=1;
(gdb) step

Program received signal SIGSEGV, Segmentation fault.
0x00000000004008f9 in main () at main.cpp:5
5               b->value=1;
(gdb)

Program terminated with signal SIGSEGV, Segmentation fault.
The program no longer exists.
(gdb)

So my question is what is the problem with my code and what do I need to do to fix it and is there a better way to debug my things in the future?

EDIT:

changes main, as said:

int main(){
        node* b=new node();
        b->value=1;

gdb:

Temporary breakpoint 1, main () at main.cpp:4
4               node* b=new node();
(gdb) step
operator new (sz=16) at ../../../../libstdc++-v3/libsupc++/new_op.cc:43
43      ../../../../libstdc++-v3/libsupc++/new_op.cc: No such file or directory.
(gdb)
48      in ../../../../libstdc++-v3/libsupc++/new_op.cc
(gdb)
43      in ../../../../libstdc++-v3/libsupc++/new_op.cc
(gdb)
48      in ../../../../libstdc++-v3/libsupc++/new_op.cc
(gdb)
50      in ../../../../libstdc++-v3/libsupc++/new_op.cc
(gdb)

__GI___libc_malloc (bytes=16) at malloc.c:2897
2897    malloc.c: No such file or directory.
(gdb)
2902    in malloc.c
(gdb)
2903    in malloc.c
(gdb)
2906    in malloc.c
(gdb)
2908    in malloc.c
(gdb)
_int_malloc (av=av@entry=0x7ffff753a620 <main_arena>, bytes=bytes@entry=16) at malloc.c:3325
3325    in malloc.c
(gdb)
3355    in malloc.c
(gdb)
3359    in malloc.c
(gdb)
3373    in malloc.c
(gdb)
3375    in malloc.c

Real problem is how to debug properly with vim and linux

Body:
int main(){
    node* b;
    b->value=1;
    linkedList a;

Problem is pointer b, you declared a pointer type of node, but it points null(nowhere),then you try assign  b->value, therefore throw  a segmentation fault.
You must assign  a address your pointer b ,like below,

b=new node;
b->value=1;

then you can assign any value


问:
Order of arguments and pipe-right operator
Is there a way to simplify the following, so I won't need a runWithTimeout function?

```<code>let runWithTimeout timeout computation =
   Async.RunSynchronously(computation, timeout)

let processOneItem item =  fetchAction item
                           |> runWithTimeout 2000
</code>```

Edit:
Here's why i needed the extra method:

```<code>let processOneItem item =  fetchAction item
                           |> Async.Catch
                           |> runWithTimeout 2000
                           |> handleExceptions
</code>```

答:
I'm not very keen on using fun x -> ... as part of a pipeline.

I think that the pipelining style of writing code is nice when it is supported by the API (e.g. lists), but when the API doesn't fit the style, it is just better to follow the usual "C#-like" style. Of coures, this is just a personal preference, but I'd just write:

```<code>let processOneItem item =
  let work = Async.Catch(fetchAction item)
  let result = Async.RunSynchronously(work, 30000)
  handleExceptions result
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Is there a way to simplify the following, so I won't need a runWithTimeout function?

let runWithTimeout timeout computation =
   Async.RunSynchronously(computation, timeout)

let processOneItem item =  fetchAction item
                           |> runWithTimeout 2000

Edit:
Here's why i needed the extra method:

let processOneItem item =  fetchAction item
                           |> Async.Catch
                           |> runWithTimeout 2000
                           |> handleExceptions

Body:
I'm not very keen on using fun x -> ... as part of a pipeline.

I think that the pipelining style of writing code is nice when it is supported by the API (e.g. lists), but when the API doesn't fit the style, it is just better to follow the usual "C#-like" style. Of coures, this is just a personal preference, but I'd just write:

let processOneItem item =
  let work = Async.Catch(fetchAction item)
  let result = Async.RunSynchronously(work, 30000)
  handleExceptions result


问:
A bug because of the accuracy of double type in C++
I have wrote a class to calculate the amount of money for me. Below is the code in brief.

```<code>class RMB
{
private:
    int yuan;
    int jiao;
    int fen;
    bool mark;
public:
RMB(int yu, int ji, int fe, bool mar = true)
    {
        yuan = yu;
        jiao = ji;
        fen = fe;
        mark = mar;
    }
    RMB(double money)
    {
        int money1 = int(money * 100);
        yuan = money1 / 100;
        fen = money1 % 10;
        jiao = (money1 - yuan * 100 - fen)/10;
        if (money < 0) mark = 0;
        else mark = 1;
    }
    operator double()
    {
        double money = yuan + double(jiao) / 10 + double(fen) / 100;
        if (mark == false) return -money;
        return money;
    }
};
int main()
{
    RMB a(1,2,3);RMB b(2,3,4);
cout << "a + c = " << RMB(a + c) << endl;//assume I have override "<<" and ">>"

cout << "a - b = " << RMB(a - b) << endl;
}
</code>```

But when I test my code,it happened that:

```<code>a + c = 2 yuan 4 jiao 5 fen

a - b = -1 yuan -1 jiao 0 fen
</code>```

I test it in VS2015,I have debugged it, and I see exact value of double(a-b） is -1.199999998. So how can I fix this bug and what can I do to avoid bug like this kind?

答:
RMB(double money)
{
    int money1 = int(money * 100);
```

<p>If money is negative, money1 is too!</p>

<pre class="lang-cpp prettyprint-override"><code>    yuan = money1 / 100;
    fen = money1 % 10;
    jiao = (money1 - yuan * 100 - fen)/10;
</code>```

So will be your members!

    if (money < 0)
        mark = 0;
    else
        mark = 1;
```

<p>And you store the sign additionally (to be used in <code>operator double</code>):</p>

<pre class="lang-cpp prettyprint-override"><code>return mark ? money : -money;
</code>```

Suppose you should make your members positive instead (and I'd prefer unsigned members then):

RMB(double money)
    : mark(money >= 0)
{
    unsigned int money1 = (int)((mark ? money : -money) * 100);
    // ...
}
```

Body:
I have wrote a class to calculate the amount of money for me. Below is the code in brief.

class RMB
{
private:
    int yuan;
    int jiao;
    int fen;
    bool mark;
public:
RMB(int yu, int ji, int fe, bool mar = true)
    {
        yuan = yu;
        jiao = ji;
        fen = fe;
        mark = mar;
    }
    RMB(double money)
    {
        int money1 = int(money * 100);
        yuan = money1 / 100;
        fen = money1 % 10;
        jiao = (money1 - yuan * 100 - fen)/10;
        if (money < 0) mark = 0;
        else mark = 1;
    }
    operator double()
    {
        double money = yuan + double(jiao) / 10 + double(fen) / 100;
        if (mark == false) return -money;
        return money;
    }
};
int main()
{
    RMB a(1,2,3);RMB b(2,3,4);
cout << "a + c = " << RMB(a + c) << endl;//assume I have override "<<" and ">>"

cout << "a - b = " << RMB(a - b) << endl;
}

But when I test my code,it happened that:

a + c = 2 yuan 4 jiao 5 fen

a - b = -1 yuan -1 jiao 0 fen

I test it in VS2015,I have debugged it, and I see exact value of double(a-b） is -1.199999998. So how can I fix this bug and what can I do to avoid bug like this kind?

Body:
RMB(double money)
{
    int money1 = int(money * 100);

If money is negative, money1 is too!

    yuan = money1 / 100;
    fen = money1 % 10;
    jiao = (money1 - yuan * 100 - fen)/10;

So will be your members!

    if (money < 0)
        mark = 0;
    else
        mark = 1;

And you store the sign additionally (to be used in operator double):

return mark ? money : -money;

Suppose you should make your members positive instead (and I'd prefer unsigned members then):

RMB(double money)
    : mark(money >= 0)
{
    unsigned int money1 = (int)((mark ? money : -money) * 100);
    // ...
}


问:
Javascript Nested Function - Need help returning result
I am trying to create a function to return a lat/long array from the Google Maps JS API (v3). I am able to write the data out that I retrieve from the API, but I am not able to pass the data along to a variable. I am wanting to do something like this:

```<code>var latLong = getLatLong(Address);
</code>```

The function that I have created is here:

```<code>function getLatLong(loc, callback) {
  var geocoder = new google.maps.Geocoder();
  var array = new Array();

  if (geocoder) {
    geocoder.geocode({ 'address': loc }, function (results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var latLng = results[0].geometry.location;;
        $.each(latLng, function(k, v) {
          if (k == 'va' || k == 'wa') {
            array.push(v);
          }
        });
        var ret = array;
        callback(ret);
      } else {
        console.log("Geocoding failed: " + status);
      }
    });
  }
}
</code>```

I then am assigning the function to a variable and calling it to give me the lat/long.

```<code>var geo = getLatLong('Dallas, TX', function(result) {
  return result;
});
</code>```

Unfortunately this produces an 'undefined' result. I can access the result in the function, I just can't pass it along. How can I pass the result of the function to a variable to be accessed?

答:
Unfortunately this produces an 'undefined' result

Do you mean in the 'geo' variable? If so, you are missing the point of callbacks. The function you pass in will be called later after the getLatLong() call returns. Callbacks are asynchronous functions, and you will want to use the callback to take an action (e.g. change state, tweak a display, etc.) of your choice.

Try changing it to

```<code>function(result) { alert('callback result: '+result); }
</code>```

to check if it gets called properly. If you get an alert() properly, then you might want to do something like this:

```<code>var geo = null;
getLatLong('Dallas, TX', function(result) {
   // cache state
   geo = result;
   // do something with it
   showResultInSomeSpotOnThePage(result);
});
/* We can't use the "geo" variable contents immediately
 * after getLatLong returns; it will be set at some time later.
 * But there may be some use for keeping the result around indefinitely,
 * we just have to be prepared for "geo" to be null if we check it
 * before the callback is called.
 */
</code>```

Body:
I am trying to create a function to return a lat/long array from the Google Maps JS API (v3). I am able to write the data out that I retrieve from the API, but I am not able to pass the data along to a variable. I am wanting to do something like this:

var latLong = getLatLong(Address);

The function that I have created is here:

function getLatLong(loc, callback) {
  var geocoder = new google.maps.Geocoder();
  var array = new Array();

  if (geocoder) {
    geocoder.geocode({ 'address': loc }, function (results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var latLng = results[0].geometry.location;;
        $.each(latLng, function(k, v) {
          if (k == 'va' || k == 'wa') {
            array.push(v);
          }
        });
        var ret = array;
        callback(ret);
      } else {
        console.log("Geocoding failed: " + status);
      }
    });
  }
}

I then am assigning the function to a variable and calling it to give me the lat/long.

var geo = getLatLong('Dallas, TX', function(result) {
  return result;
});

Unfortunately this produces an 'undefined' result. I can access the result in the function, I just can't pass it along. How can I pass the result of the function to a variable to be accessed?

Body:
Unfortunately this produces an 'undefined' result

Do you mean in the 'geo' variable? If so, you are missing the point of callbacks. The function you pass in will be called later after the getLatLong() call returns. Callbacks are asynchronous functions, and you will want to use the callback to take an action (e.g. change state, tweak a display, etc.) of your choice.

Try changing it to

function(result) { alert('callback result: '+result); }

to check if it gets called properly. If you get an alert() properly, then you might want to do something like this:

var geo = null;
getLatLong('Dallas, TX', function(result) {
   // cache state
   geo = result;
   // do something with it
   showResultInSomeSpotOnThePage(result);
});
/* We can't use the "geo" variable contents immediately
 * after getLatLong returns; it will be set at some time later.
 * But there may be some use for keeping the result around indefinitely,
 * we just have to be prepared for "geo" to be null if we check it
 * before the callback is called.
 */


问:
How to change "Choose File" or "Browse" button text and "No file selected" text. Example:
I have following HTML code for displaying "Browse" or "Choose File" button:</p>

```<code><input type="file" name="file" id="file">
</code>```

答: You may increase the width of .file > label { width: 113px; } and drop the opacity: 0; in  .file > input[type="file"].

Body:
I have following HTML code for displaying "Browse" or "Choose File" button:

<input type="file" name="file" id="file">


问:
Elasticsearch script - variable not defined
I'm following an Elasticsearch tutorial, but ran into a problem when trying to use parameters in a script.

Step 1: Create a new document - OK (index = website; type = blog; id = 1)

```<code>curl -XPUT localhost:9200/website/blog/1?pretty -d '{
  "title":"my first post",
  "tags" : [ "tag1" ]
}'
</code>```

Step 2: Use script to append an extra value to tags array - ERROR

```<code>curl -XPOST localhost:9200/website/blog/1/_update?pretty -d '{
   "script" : "ctx._source.tags+=new_tag",
   "params" : {
      "new_tag" : "tag2"
   }
}'
</code>```

The error message is this, mentioning "reason" : "Variable [new_tag] is not defined." But I have defined the variable new_tag as described on the tutorial page. What am I doing wrong?

```<code>  "error" : {
    "root_cause" : [
      {
        "type" : "remote_transport_exception",
        "reason" : "[mrukUvA][127.0.0.1:9300][indices:data/write/update[s]]"
      }
    ],
    "type" : "illegal_argument_exception",
    "reason" : "failed to execute script",
    "caused_by" : {
      "type" : "script_exception",
      "reason" : "compile error",
      "caused_by" : {
        "type" : "illegal_argument_exception",
        "reason" : "Variable [new_tag] is not defined."
      },
      "script_stack" : [
        "ctx._source.tags+=new_tag",
        "                  ^---- HERE"
      ],
      "script" : "ctx._source.tags+=new_tag",
      "lang" : "painless"
    }
  },
  "status" : 400
}
</code>```

Step 2 (retry) Qualifying new_tag with params - ERROR

```<code>curl -XPOST localhost:9200/website/blog/1/_update?pretty -d '{
   "script" : {
       "inline": "ctx._source.tags+=params.new_tag",
       "params" : {
          "new_tag" : "tag2"
       }
   }
}'
</code>```

Gives error

```<code>{
  "error" : {
    "root_cause" : [
      {
        "type" : "remote_transport_exception",
        "reason" : "[mrukUvA][127.0.0.1:9300][indices:data/write/update[s]]"
      }
    ],
    "type" : "illegal_argument_exception",
    "reason" : "failed to execute script",
    "caused_by" : {
      "type" : "script_exception",
      "reason" : "runtime error",
      "caused_by" : {
        "type" : "class_cast_exception",
        "reason" : "Cannot cast java.lang.String to java.util.ArrayList"
      },
      "script_stack" : [
        "ctx._source.tags+=params.new_tag",
        "                        ^---- HERE"
      ],
      "script" : "ctx._source.tags+=params.new_tag",
      "lang" : "painless"
    }
  },
  "status" : 400
}
</code>```

As a sanity check to make sure the document is valid

```<code>$ curl -XGET localhost:9200/website/blog/1?pretty
{
  "_index" : "website",
  "_type" : "blog",
  "_id" : "1",
  "_version" : 27,
  "found" : true,
  "_source" : {
    "title" : "my first post",
    "tags" : [
      "tag1"
    ]
  }
}
</code>```

So the document does have the valid field tag which is an array.

答:
Your syntax is slightly off, if you have parameters you need to inline the script. Try this:

```<code>curl -XPOST localhost:9200/website/blog/1/_update?pretty -d '{
   "script" : {
       "inline": "ctx._source.tags.add(params.new_tag)",
       "params" : {
          "new_tag" : "tag2"
       }
   }
}'
</code>```

Body:
I'm following an Elasticsearch tutorial, but ran into a problem when trying to use parameters in a script.

Step 1: Create a new document - OK (index = website; type = blog; id = 1)

curl -XPUT localhost:9200/website/blog/1?pretty -d '{
  "title":"my first post",
  "tags" : [ "tag1" ]
}'

Step 2: Use script to append an extra value to tags array - ERROR

curl -XPOST localhost:9200/website/blog/1/_update?pretty -d '{
   "script" : "ctx._source.tags+=new_tag",
   "params" : {
      "new_tag" : "tag2"
   }
}'

The error message is this, mentioning "reason" : "Variable [new_tag] is not defined." But I have defined the variable new_tag as described on the tutorial page. What am I doing wrong?

  "error" : {
    "root_cause" : [
      {
        "type" : "remote_transport_exception",
        "reason" : "[mrukUvA][127.0.0.1:9300][indices:data/write/update[s]]"
      }
    ],
    "type" : "illegal_argument_exception",
    "reason" : "failed to execute script",
    "caused_by" : {
      "type" : "script_exception",
      "reason" : "compile error",
      "caused_by" : {
        "type" : "illegal_argument_exception",
        "reason" : "Variable [new_tag] is not defined."
      },
      "script_stack" : [
        "ctx._source.tags+=new_tag",
        "                  ^---- HERE"
      ],
      "script" : "ctx._source.tags+=new_tag",
      "lang" : "painless"
    }
  },
  "status" : 400
}

Step 2 (retry) Qualifying new_tag with params - ERROR

curl -XPOST localhost:9200/website/blog/1/_update?pretty -d '{
   "script" : {
       "inline": "ctx._source.tags+=params.new_tag",
       "params" : {
          "new_tag" : "tag2"
       }
   }
}'

Gives error

{
  "error" : {
    "root_cause" : [
      {
        "type" : "remote_transport_exception",
        "reason" : "[mrukUvA][127.0.0.1:9300][indices:data/write/update[s]]"
      }
    ],
    "type" : "illegal_argument_exception",
    "reason" : "failed to execute script",
    "caused_by" : {
      "type" : "script_exception",
      "reason" : "runtime error",
      "caused_by" : {
        "type" : "class_cast_exception",
        "reason" : "Cannot cast java.lang.String to java.util.ArrayList"
      },
      "script_stack" : [
        "ctx._source.tags+=params.new_tag",
        "                        ^---- HERE"
      ],
      "script" : "ctx._source.tags+=params.new_tag",
      "lang" : "painless"
    }
  },
  "status" : 400
}

As a sanity check to make sure the document is valid

$ curl -XGET localhost:9200/website/blog/1?pretty
{
  "_index" : "website",
  "_type" : "blog",
  "_id" : "1",
  "_version" : 27,
  "found" : true,
  "_source" : {
    "title" : "my first post",
    "tags" : [
      "tag1"
    ]
  }
}

So the document does have the valid field tag which is an array.

Body:
Your syntax is slightly off, if you have parameters you need to inline the script. Try this:

curl -XPOST localhost:9200/website/blog/1/_update?pretty -d '{
   "script" : {
       "inline": "ctx._source.tags.add(params.new_tag)",
       "params" : {
          "new_tag" : "tag2"
       }
   }
}'


问:
sql connection error 000webhost
I am using 000 webhost to store a sql database.
Every time I want to connect to it I recieve this error message

```<code>Warning: mysqli::__construct(): (HY000/2002): Connection refused in /storage/h10/804/1186804/public_html/Handy_Help_PHP_files/conexiune.php on line 7
Connection failed: Connection refused
</code>```

This is the php I use to connect

```<code><?php
$servername = "localhost:3306";
$username = "id1186804_admin";
$password = "12345";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
</code>```

Can somebody help me to find the error?

答:
with mysqli need add database name too

```<code><?php
$servername = "localhost:3306";
$username = "id1186804_admin";
$password = "12345";

// Create connection
$conn = new mysqli($servername, $username, $password,$yourdbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
</code>```

such:

```<code><?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?>
</code>```

Title: sql connection error 000webhost

Body:
I am using 000 webhost to store a sql database.
Every time I want to connect to it I recieve this error message

Warning: mysqli::__construct(): (HY000/2002): Connection refused in /storage/h10/804/1186804/public_html/Handy_Help_PHP_files/conexiune.php on line 7
Connection failed: Connection refused

This is the php I use to connect

<?php
$servername = "localhost:3306";
$username = "id1186804_admin";
$password = "12345";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

Can somebody help me to find the error?

Body:
with mysqli need add database name too

<?php
$servername = "localhost:3306";
$username = "id1186804_admin";
$password = "12345";

// Create connection
$conn = new mysqli($servername, $username, $password,$yourdbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

such:

<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?>


问:
Joomla intro image with hover-overlay and showing intro text
I'm stuck. Any help is appreciated.

Goal...
When in a Joomla content blog view I show an intro image, I want, on hover, to fade it to 20% and show the intro text, in black, on top of the intro image.

What I've done so far...
Alter the Joomla core file blog_item.php from

```<code><?php echo JLayoutHelper::render('joomla.content.intro_image', $this->item); ?>
</code>```

to

```<code><?php echo '<div id="box">'; ?>
<?php echo JLayoutHelper::render('joomla.content.intro_image', $this->item); ?>
    <?php echo '<div id="overlay">'; ?>
        <?php echo $this->item->introtext; ?>
    <?php echo '</div>'; ?>
<?php echo '</div>'; ?>
</code>```

and added CSS for opacity and positioning.

The problem is... The div overlay hovers over the introduction-image-link. So it's no longer clickable.

My question... How can I give the div overlay the same href as the introduction-image?

Thanks for your help.

答: The simplest way that I can think of right away is to implement a click listener on the overlay div and take the user to the desired url using window.location

Body:
I'm stuck. Any help is appreciated.

Goal...
When in a Joomla content blog view I show an intro image, I want, on hover, to fade it to 20% and show the intro text, in black, on top of the intro image.

What I've done so far...
Alter the Joomla core file blog_item.php from

<?php echo JLayoutHelper::render('joomla.content.intro_image', $this->item); ?>

to

<?php echo '
'; ?>
<?php echo JLayoutHelper::render('joomla.content.intro_image', $this->item); ?>
    <?php echo '
'; ?>
        <?php echo $this->item->introtext; ?>
    <?php echo '
'; ?>
<?php echo '
'; ?>

and added CSS for opacity and positioning.

The problem is... The div overlay hovers over the introduction-image-link. So it's no longer clickable.

My question... How can I give the div overlay the same href as the introduction-image?

Thanks for your help.


答:
Use this

http://sympy.org/

Title: String manipulation of type String substitution in mathematical expression

Body:
Imagine something like

exp(49/200)+(x-49/200)

I want to pass as argument of the function "roundn" whatever operation that is not a addtion or a subtraction
So my expression became

roundn(exp(roundn(49/200, n)), n) + (x - roundn(49/200, n)

Well the expression I want to manipulate is this:

exp(49/200)+exp(49/200)*(x-49/200)+1/2*exp(49/200)*(x-49/200)^2+1/6*exp(49/200)*(x-49/200)^3+1/24*exp(49/200)*(x-49/200)^4+1/120*exp(49/200)*(x-49/200)^5+1/720*exp(49/200)*(x-49/200)^6+1/5040*exp(49/200)*(x-49/200)^7+1/40320*exp(49/200)*(x-49/200)^8+1/362880*exp(49/200)*(x-49/200)^9+1/3628800*exp(49/200)*(x-49/200)^10+1/39916800*exp(49/200)*(x-49/200)^11

Body:
Use this

http://sympy.org/


问:
Retrieving String from JAX-RS Response
In short terms, I simplified the problem a lot. I am calling this code, and the response is received with status 200 (OK):

Receiver.java:

```<code>Response response = componentInstanceService.getResource(componentResourceType);
</code>```

However, I don't know how can I retrieve the String contained in the body from this method:

Sender.java:

```<code>  @Override
    public Response getResource(ComponentResourceType resourceType) {
        String path = getPath();
        return Response.ok(this.getClass().getResourceAsStream(path)).build();
    }
</code>```

Please note that the communication between classes is working fine, as long as the Response is OK, however, how can I retrieve the String that Response contains?

This is what I would like to do roughly:

Receiver:

```<code>String result = componentInstanceService.getResource(componentResourceType);
</code>```

答:
If you want to read the string from the body simply use</p>

```<code>String result = componentInstanceService.getResource(componentResourceType).readEntity(String.class);
</code>```

Title: Retrieving String from JAX-RS Response

Body:
In short terms, I simplified the problem a lot. I am calling this code, and the response is received with status 200 (OK):

Receiver.java:

Response response = componentInstanceService.getResource(componentResourceType);

However, I don't know how can I retrieve the String contained in the body from this method:

Sender.java:

  @Override
    public Response getResource(ComponentResourceType resourceType) {
        String path = getPath();
        return Response.ok(this.getClass().getResourceAsStream(path)).build();
    }

Please note that the communication between classes is working fine, as long as the Response is OK, however, how can I retrieve the String that Response contains?

This is what I would like to do roughly:

Receiver:

String result = componentInstanceService.getResource(componentResourceType);

Body:
If you want to read the string from the body simply use

String result = componentInstanceService.getResource(componentResourceType).readEntity(String.class);


问:
How to mount django app at root of site on Apache?
I'm following the documentation here:

https://modwsgi.readthedocs.io/en/develop/user-guides/quick-configuration-guide.html

I'm using apache2 on Debian

I change the settings by editing apache2.conf

When I mount my app like this,

```<code>WSGIScriptAlias /app /path/to/mysite
</code>```

and it works when I browse 127.0.0.1/app/.

However, when I try to mount my app at root like this:

```<code>WSGIScriptAlias / /path/to/mysite
</code>```

and I browse 127.0.0.1/ , the default page "It works!" is shown by apache

The option

```<code>DocumentRoot /path/to/mysite
</code>```

in apache2.conf doesn't work, too.

答:
You have to provide the location of the wsgi script.</p>

```<code>WSGIScriptAlias / /var/www/html/myproj/src/myproj/wsgi.py process-group=myproj
</code>```

Body:
I'm following the documentation here:

https://modwsgi.readthedocs.io/en/develop/user-guides/quick-configuration-guide.html

I'm using apache2 on Debian

I change the settings by editing apache2.conf

When I mount my app like this,

WSGIScriptAlias /app /path/to/mysite

and it works when I browse 127.0.0.1/app/.

However, when I try to mount my app at root like this:

WSGIScriptAlias / /path/to/mysite

and I browse 127.0.0.1/ , the default page "It works!" is shown by apache

The option

DocumentRoot /path/to/mysite

in apache2.conf doesn't work, too.

Body:
You have to provide the location of the wsgi script.

WSGIScriptAlias / /var/www/html/myproj/src/myproj/wsgi.py process-group=myproj


问:
Cookie doesn't work properly in webview in android
Needed datas is not written to cookies immediately in WebView. But when I wait for 10-15 seconds everything is ok.
To explain the situation, this example would be good as for me:

I open the app and login. After login, I close the app immediately. Then after  I open the app again, it shows me to logout. But if I open the app after 1 minute, it shows again as logged in. For me cookies are written lately. But I cannot find solution. Please help me if you know.

I used CookieManager class but it doesn't help either.

```<code>CookieManager.getInstance().setAcceptCookie(true);
</code>```

答:
I had similar issue and I added the below code and worked.

```<code>String myURL = "https://www.yourWebPage.com";

android.webkit.CookieManager cookieManager = android.webkit.CookieManager.getInstance();

cookieManager.setAcceptCookie(true);
cookieManager.acceptCookie();
cookieManager.setAcceptFileSchemeCookies(true);
cookieManager.getInstance().setAcceptCookie(true);
cookieManager.getCookie(myURL);
</code>```

Hope it helps.

Body:
Needed datas is not written to cookies immediately in WebView. But when I wait for 10-15 seconds everything is ok.
To explain the situation, this example would be good as for me:

I open the app and login. After login, I close the app immediately. Then after  I open the app again, it shows me to logout. But if I open the app after 1 minute, it shows again as logged in. For me cookies are written lately. But I cannot find solution. Please help me if you know.

I used CookieManager class but it doesn't help either.

CookieManager.getInstance().setAcceptCookie(true);

Body:
I had similar issue and I added the below code and worked.

String myURL = "https://www.yourWebPage.com";

android.webkit.CookieManager cookieManager = android.webkit.CookieManager.getInstance();

cookieManager.setAcceptCookie(true);
cookieManager.acceptCookie();
cookieManager.setAcceptFileSchemeCookies(true);
cookieManager.getInstance().setAcceptCookie(true);
cookieManager.getCookie(myURL);

Hope it helps.


问:
yum local install to install a package with its dependency
I have downloaded a package with it's dependency and want to install a package with dependency. Even though i have download in local folder it's checking for online.

sudo yum -y --disablerepo=* localinstall autoconf-2.69-11.el7.noarch.rpm

I am trying above command but failed to load it's dependency that is there in same folder.

Thanks,
Hare

答:
Inside the local directory where you have all the downloaded RPMs, do this:

```<code> sudo yum --disablerepo=* localinstall *.rpm
</code>```

OR

```<code> sudo yum --disablerepo=* localinstall foo.rpm bar.rpm baz.rpm
</code>```

Since you have downloaded all the dependencies to a single directory, you can also use rpm to install those:

```<code> sudo rpm -Uvvh *.rpm --test
</code>```

--test does a dry-run. Remove it to install on disk.

ContentLicense: CC BY-SA 4.0

Body:
Inside the local directory where you have all the downloaded RPMs, do this:

 sudo yum --disablerepo=* localinstall *.rpm

OR

 sudo yum --disablerepo=* localinstall foo.rpm bar.rpm baz.rpm

Since you have downloaded all the dependencies to a single directory, you can also use rpm to install those:

 sudo rpm -Uvvh *.rpm --test

--test does a dry-run. Remove it to install on disk.


问:
adfs authentication invalid request exception msis7042 mvc
I have a MVC site deployed on a web server. Some users get a InvalidRequestException MSIS7042 and other users are able to access the site without a problem. I am having this problem on safari and iOS. I have other MVC sites deployed that use ADFS that work fine. I have checked that the endpoints and the identifiers have trailing slashes. The permissions are set up the same for users that can and can't access the site. If a user that is having an issue accesses one of the other sites, and authenticates with adfs, then goes back to the url that they were having an issues with, they can access the site fine. I have added my web.config below, Any help would be greatly appreciated. </p>

```<code><configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  <sectionGroup name="elmah">
      <section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah" />
      <section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah" />
      <section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah" />
      <section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah" />
    </sectionGroup>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
      <section name="Specbook.Web.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </sectionGroup>
  </configSections>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="ida:ADFSMetadata" value="adfs medadata url" />
    <add key="ida:Wtrealm" value="http://apps/SpecbookDev" />
    <add key="ida:Wreply" value="reply url" />
  <add key="elmah.mvc.disableHandler" value="false" /><add key="elmah.mvc.disableHandleErrorFilter" value="false" /><add key="elmah.mvc.requiresAuthentication" value="false" /><add key="elmah.mvc.IgnoreDefaultRoute" value="false" /><add key="elmah.mvc.allowedRoles" value="*" /><add key="elmah.mvc.allowedUsers" value="*" /><add key="elmah.mvc.route" value="elmah" /><add key="elmah.mvc.UserAuthCaseSensitive" value="true" /></appSettings>
  <system.web>
    <customErrors mode="Off" />
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
  <httpModules>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules></system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
    </compilers>
  </system.codedom>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
<system.webServer>
</configuration>
</code>```

答: We upgraded our ADFS server, and this has seemed to fix the issue. If we get the multiple redirects, we restart the app pool and that resolves that issue as well. </p>

Body:
I have a MVC site deployed on a web server. Some users get a InvalidRequestException MSIS7042 and other users are able to access the site without a problem. I am having this problem on safari and iOS. I have other MVC sites deployed that use ADFS that work fine. I have checked that the endpoints and the identifiers have trailing slashes. The permissions are set up the same for users that can and can't access the site. If a user that is having an issue accesses one of the other sites, and authenticates with adfs, then goes back to the url that they were having an issues with, they can access the site fine. I have added my web.config below, Any help would be greatly appreciated.

<configuration>
  <configSections>

  <sectionGroup name="elmah">

    </sectionGroup>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >

    </sectionGroup>
  </configSections>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="ida:ADFSMetadata" value="adfs medadata url" />
    <add key="ida:Wtrealm" value="http://apps/SpecbookDev" />
    <add key="ida:Wreply" value="reply url" />
  <add key="elmah.mvc.disableHandler" value="false" /><add key="elmah.mvc.disableHandleErrorFilter" value="false" /><add key="elmah.mvc.requiresAuthentication" value="false" /><add key="elmah.mvc.IgnoreDefaultRoute" value="false" /><add key="elmah.mvc.allowedRoles" value="*" /><add key="elmah.mvc.allowedUsers" value="*" /><add key="elmah.mvc.route" value="elmah" /><add key="elmah.mvc.UserAuthCaseSensitive" value="true" /></appSettings>
  <system.web>
    <customErrors mode="Off" />
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
  <httpModules>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules></system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
    </compilers>
  </system.codedom>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
<system.webServer>
</configuration>


问:
How to get all custom post types in wordpress?
I am trying to make a shortcode for Visual Composer. I have to get all the custom post types as dropdown. I am using the get_post_types() function, but it returns an empty array.

Here is my code:

```<code> /*Post type shortcode*/
 add_action( 'vc_before_init', 'post_type_shortcode');
function post_type_shortcode(){
$args = array( 'public' => true, '_builtin' => false );
$output = 'names'; //'names'; // names or objects, note names is the default
$operator = 'and'; // 'and' or 'or'
$custom_post_types = get_post_types( $args, $output, $operator );
vc_map( array(
    "name" => __( "Display Post Type", "saue" ),
    "description" => "Display post type",
    "base" => "display_post_type",
    "class" => "",
    "category" => __( "Saue Theme", "saue"),
    "params" => array(
        array(
            "type"          => "dropdown",
                    //"holder"        => "div",
            "heading"       => __( "Post Type", "saue" ),
            "admin_label" => true,
            "param_name"    => "post_type",
            "value"         => $custom_post_types,
            ),
        )
    ) );
</code>```

}

I have also tried to get it in the functions.php but result is same.

I also used add_action('init',"function_name');, it works within the hook but not outside of the hook.

Can any one help me please?

答:
I have modified your code around the line where you are calling $custom_post_types for your shortcode values.

```<code>/*Post type shortcode*/
add_action( 'vc_before_init', 'post_type_shortcode');
function post_type_shortcode(){
$args = array( 'public' => true, '_builtin' => false );
$output = 'names'; //'names'; // names or objects, note names is the default
$operator = 'and'; // 'and' or 'or'
$custom_post_types = get_post_types( $args, $output, $operator );
vc_map( array(
    "name" => __( "Display Post Type", "saue" ),
    "description" => "Display post type",
    "base" => "display_post_type",
    "class" => "",
    "category" => __( "Saue Theme", "saue"),
    "params" => array(
        array(
            "type"          => "dropdown",
            //"holder"      => "div",
            "heading"       => __( "Post Type", "saue" ),
            "admin_label"   => true,
            "param_name"    => "post_type",
            "value"         => $custom_post_types->name,//see this line
            ),
        )
    ) );
}
</code>```

This line should return the names of the post types registered. Hope this works for you!

Body:
I am trying to make a shortcode for Visual Composer. I have to get all the custom post types as dropdown. I am using the get_post_types() function, but it returns an empty array.

Here is my code:

 /*Post type shortcode*/
 add_action( 'vc_before_init', 'post_type_shortcode');
function post_type_shortcode(){
$args = array( 'public' => true, '_builtin' => false );
$output = 'names'; //'names'; // names or objects, note names is the default
$operator = 'and'; // 'and' or 'or'
$custom_post_types = get_post_types( $args, $output, $operator );
vc_map( array(
    "name" => __( "Display Post Type", "saue" ),
    "description" => "Display post type",
    "base" => "display_post_type",
    "class" => "",
    "category" => __( "Saue Theme", "saue"),
    "params" => array(
        array(
            "type"          => "dropdown",
                    //"holder"        => "div",
            "heading"       => __( "Post Type", "saue" ),
            "admin_label" => true,
            "param_name"    => "post_type",
            "value"         => $custom_post_types,
            ),
        )
    ) );

}

I have also tried to get it in the functions.php but result is same.

I also used add_action('init',"function_name');, it works within the hook but not outside of the hook.

Can any one help me please?

Body:
I have modified your code around the line where you are calling $custom_post_types for your shortcode values.

/*Post type shortcode*/
add_action( 'vc_before_init', 'post_type_shortcode');
function post_type_shortcode(){
$args = array( 'public' => true, '_builtin' => false );
$output = 'names'; //'names'; // names or objects, note names is the default
$operator = 'and'; // 'and' or 'or'
$custom_post_types = get_post_types( $args, $output, $operator );
vc_map( array(
    "name" => __( "Display Post Type", "saue" ),
    "description" => "Display post type",
    "base" => "display_post_type",
    "class" => "",
    "category" => __( "Saue Theme", "saue"),
    "params" => array(
        array(
            "type"          => "dropdown",
            //"holder"      => "div",
            "heading"       => __( "Post Type", "saue" ),
            "admin_label"   => true,
            "param_name"    => "post_type",
            "value"         => $custom_post_types->name,//see this line
            ),
        )
    ) );
}

This line should return the names of the post types registered. Hope this works for you!


问:
Nodejs -- Cannot read property 'findAll' of undefined
I'm using nodejs with sequelize and connecting to a postgres database.

I have created a model and inside one of my routes I'm trying to return all of the users within the database.

The code:

routes.js

```<code>var models = require('../server/models/index');
router.get('/users', function(req, res, next) {

    models.Users.findAll({}).then(function(user) {

    });
});
</code>```

/server/models/index

```<code>'use strict';

var fs        = require('fs');
var path      = require('path');
var Sequelize = require('sequelize');
var basename  = path.basename(module.filename);
var env       = process.env.NODE_ENV || 'development';
var config    = require(__dirname + '/../config.json')[env];
var db        = {};

if (config.use_env_variable) {
  var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
  var sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(function(file) {
    return (file.indexOf('.') !== 0) && (file !== basename);
  })
  .forEach(function(file) {
    if (file.slice(-3) !== '.js') return;
    var model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(function(modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
</code>```

I am getting the following when running the server and navigating to it:

Cannot read property 'findAll' of undefined

I have tested the connection and it's all working fine. I cannot seem to figure out what is going wrong here. Any ideas to what I'm missing?

EDIT:

users.js

```<code>'use strict';
module.exports = function(sequelize, DataTypes) {
  var Users = sequelize.define('users', {
    email: DataTypes.STRING
  }, {
    classMethods: {
      associate: function(models) {
        // associations can be defined here
      }
    }
  });
  return Users;
};
</code>```

答:
Instead of sequelize.define('users');

Try var Users = sequelize.define('Users'); or var Users = sequelize.define('User');

Body:
I'm using nodejs with sequelize and connecting to a postgres database.

I have created a model and inside one of my routes I'm trying to return all of the users within the database.

The code:

routes.js

var models = require('../server/models/index');
router.get('/users', function(req, res, next) {

    models.Users.findAll({}).then(function(user) {

    });
});

/server/models/index

'use strict';

var fs        = require('fs');
var path      = require('path');
var Sequelize = require('sequelize');
var basename  = path.basename(module.filename);
var env       = process.env.NODE_ENV || 'development';
var config    = require(__dirname + '/../config.json')[env];
var db        = {};

if (config.use_env_variable) {
  var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
  var sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(function(file) {
    return (file.indexOf('.') !== 0) && (file !== basename);
  })
  .forEach(function(file) {
    if (file.slice(-3) !== '.js') return;
    var model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(function(modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

I am getting the following when running the server and navigating to it:

Cannot read property 'findAll' of undefined

I have tested the connection and it's all working fine. I cannot seem to figure out what is going wrong here. Any ideas to what I'm missing?

EDIT:

users.js

'use strict';
module.exports = function(sequelize, DataTypes) {
  var Users = sequelize.define('users', {
    email: DataTypes.STRING
  }, {
    classMethods: {
      associate: function(models) {
        // associations can be defined here
      }
    }
  });
  return Users;
};


问:
How to migrate a realm database to an app group?
Really excited about the recent addition of sharing Realm data between apps and extensions. The documentation details how to set the default realm to the app group directory, I've got that working. </p>

<p>Here's what I'm stuck on -- what's the best way to transfer the old database to the new location in the app group? </p>

答:
Hope this will help other reader.

As discussed in https://github.com/realm/realm-cocoa/issues/4490, you can set app group path with below code and use File Manager to move existing db as mention above.

```<code>var config = Realm.Configuration()
config.fileURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupIdentifier)!.appendingPathComponent(dbFilename)
Realm.Configuration.defaultConfiguration = config
</code>```

Body:
Really excited about the recent addition of sharing Realm data between apps and extensions. The documentation details how to set the default realm to the app group directory, I've got that working.

Here's what I'm stuck on -- what's the best way to transfer the old database to the new location in the app group?

Body:
Hope this will help other reader.

As discussed in https://github.com/realm/realm-cocoa/issues/4490, you can set app group path with below code and use File Manager to move existing db as mention above.

var config = Realm.Configuration()
config.fileURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupIdentifier)!.appendingPathComponent(dbFilename)
Realm.Configuration.defaultConfiguration = config


问:
mysql query - accessing field without affecting output
I have 2 tables in mysql: tableA and tableB

```<code>tableA: idA
tableB: idB, name
</code>```

Now i want to fire following query:

```<code>SELECT * FROM tableA WHERE idA in (1, 2, 3, 4);
</code>```

idA and idB are exactly same. I want to access "name" field of tableB in the above query.

How do i do this???

Thanks alot for help
Regards

答:
Why select from TableA if you only need the id which is already in tableB?

```<code>SELECT idB, name FROM tableB where idB in (1, 2, 3, 4)
</code>```

If you need to refer to the id field as idA, you can write

```<code>SELECT idB as idA, name FROM tableB where idB in (1, 2, 3, 4)
</code>```

Body:
I have 2 tables in mysql: tableA and tableB

tableA: idA
tableB: idB, name

Now i want to fire following query:

SELECT * FROM tableA WHERE idA in (1, 2, 3, 4);

idA and idB are exactly same. I want to access "name" field of tableB in the above query.

How do i do this???

Thanks alot for help
Regards

Body:
Why select from TableA if you only need the id which is already in tableB?

SELECT idB, name FROM tableB where idB in (1, 2, 3, 4)

If you need to refer to the id field as idA, you can write

SELECT idB as idA, name FROM tableB where idB in (1, 2, 3, 4)


问:
In a static library, Xcode 8.1 does not detect when an objective-c method is not implemented
My objective-c project uses a static library and recently I just discovered that Xcode 8.1 does not give some warnings for the library.
When a method implementation is missing in the app itself, I get a warning. But if a method implementation is missing in the library, I get no warning. It just crashes at run time.

Same for the switch statement with an enum. If a case is missing, Xcode would signal a warning, but not in the static library.

In previous versions of Xcode, I am sure I received those warnings in my library. And I never changed any Build Settings, I just keep all the default values.

More info:

When I open the static library itself as a project, I get all warnings. But when I open another project that includes the library (I dropped the mylibrary.xcodeproj file in my project and add it in the Link phase), I don't have the library warnings

答: It was a bug in Xcode. It is now working well in Xcode Version 8.3 (8E162)</p>


问:
How to fix Syntax error, insert "... VariableDeclaratorId..."
I am following a question but I am getting this error. I am not sure how to fix it, I have looked up this error but i can't relate it to my code. Would appreciate it any help given!

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

public class Employee {

    private static String name;
    private static String job;
    private static float salary;
    private static int id;

public Employee() {

    Scanner scan = new Scanner(System.in);
    name = scan.nextLine();
    job = scan.nextLine();
    salary = scan.nextFloat();
    id = scan.nextInt();
}
public Employee(String name, String job, float salary, int id) {
    name = name;
    job = job;
    salary = salary;
    id = id;
}
public String getName(name) {
    return name;
}
public String getJobTitle(job) {
    return job;
}
public float salary(salary){
    return salary;
}
public static void showEmp() {
    System.out.println("Employee is called: " + name);
    System.out.println("They are a " +job);
    System.out.println("Their salary is " + salary);
    System.out.println("Their Employee ID number is " + id);
}
</code>```

}

答:
Your getter should not have a paramter:

```<code> public String getName() {
        return name;
    }
</code>```

The variables should not be static also the showEmp method.
Full code should look like:

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

public class Employee {

    private String name;
    private String job;
    private float salary;
    private int id;

    public Employee() {

        Scanner scan = new Scanner(System.in);
        name = scan.nextLine();
        job = scan.nextLine();
        salary = scan.nextFloat();
        id = scan.nextInt();
    }

    public Employee(String name, String job, float salary, int id) {
        this.name = name;
        this.job = job;
        this.salary = salary;
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public String getJobTitle() {
        return job;
    }

    public float salary() {
        return salary;
    }

    public void showEmp() {
        System.out.println("Employee is called: " + name);
        System.out.println("They are a " + job);
        System.out.println("Their salary is " + salary);
        System.out.println("Their Employee ID number is " + id);
    }
}
</code>```

Body:
I am following a question but I am getting this error. I am not sure how to fix it, I have looked up this error but i can't relate it to my code. Would appreciate it any help given!

import java.util.Scanner;

public class Employee {

    private static String name;
    private static String job;
    private static float salary;
    private static int id;

public Employee() {

    Scanner scan = new Scanner(System.in);
    name = scan.nextLine();
    job = scan.nextLine();
    salary = scan.nextFloat();
    id = scan.nextInt();
}
public Employee(String name, String job, float salary, int id) {
    name = name;
    job = job;
    salary = salary;
    id = id;
}
public String getName(name) {
    return name;
}
public String getJobTitle(job) {
    return job;
}
public float salary(salary){
    return salary;
}
public static void showEmp() {
    System.out.println("Employee is called: " + name);
    System.out.println("They are a " +job);
    System.out.println("Their salary is " + salary);
    System.out.println("Their Employee ID number is " + id);
}

}

Body:
Your getter should not have a paramter:

 public String getName() {
        return name;
    }

The variables should not be static also the showEmp method.
Full code should look like:

import java.util.Scanner;

public class Employee {

    private String name;
    private String job;
    private float salary;
    private int id;

    public Employee() {

        Scanner scan = new Scanner(System.in);
        name = scan.nextLine();
        job = scan.nextLine();
        salary = scan.nextFloat();
        id = scan.nextInt();
    }

    public Employee(String name, String job, float salary, int id) {
        this.name = name;
        this.job = job;
        this.salary = salary;
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public String getJobTitle() {
        return job;
    }

    public float salary() {
        return salary;
    }

    public void showEmp() {
        System.out.println("Employee is called: " + name);
        System.out.println("They are a " + job);
        System.out.println("Their salary is " + salary);
        System.out.println("Their Employee ID number is " + id);
    }
}


问:
Disqus in Angular 2 application: Showing same discussion.
I have Angular 2 app in there I use ng2-awesome-disqus component.

On the page I have several items and for each item I have one discussion component :

```<code><disqus [shortname]="shortname" [identifier]="identifier"></disqus>
</code>```

shortname is same for each item

identifier is unique for each item

I would expect unique discussion for each item, but there are all the same.

答:
For exam</p>

```<code><ng-container *ngFor="let item of items;let i=index">
   <disqus [shortname]="item.shortname" [identifier]="i"></disqus>
</ng-container>
</code>```

Body:
I have Angular 2 app in there I use ng2-awesome-disqus component.

On the page I have several items and for each item I have one discussion component :

<disqus [shortname]="shortname" [identifier]="identifier"></disqus>

shortname is same for each item

identifier is unique for each item

I would expect unique discussion for each item, but there are all the same.

Body:
For exam

<ng-container *ngFor="let item of items;let i=index">
   <disqus [shortname]="item.shortname" [identifier]="i"></disqus>
</ng-container>