mardi 5 mai 2015

Grab data from Yahoo Finance using Meteor Package, some work some do not

I am using the following package for Meteor http://ift.tt/1Ich9ON

I cant seem to get a specified field to work, here is a link that contains a list of all the available fields, however 'j2' and some others I tested don't work, in the sense there is no response in the result object, or no json key pair values.

Heres is my client side code.

Template.stock.rendered = function (){
    if ( _.isEmpty(Session.get('ENW.V')) ) {
        Meteor.call('getQuote', 'ENW.V', function(err, result) {
            Session.set('ENW.V', result['ENW.V']);
            console.log(result)
        });
    }
}


Template.stock.helpers({
    stock: function() {
        return Session.get('ENW.V');
    }
})

Server side Method

Meteor.methods({
  getQuote: function( stockname ) {
    return YahooFinance.snapshot({symbols: [stockname] , fields:['n','a','b','j2'] });
  }
});

Thanks for any Help in Advance. Happy to add any additional info if needed.

having problems parsing gson

I am trying to parse data from here http://ift.tt/1GJqrvW

in particular this part

RATES: {
 RS: [
      {
          BEG: "12:00 AM",
          END: "2:00 AM",
          RATE: "0",
          RQ: "No charge"
      },
      {
          BEG: "2:00 AM",
          END: "6:00 AM",
          RATE: "0",
          RQ: "Str sweep"
      },
      {
          BEG: "6:00 AM",
          END: "12:00 AM",
          RATE: "0",
          RQ: "No charge"
      }
  ]
},

and I have this code

if (dataObject.getAsJsonObject("RATES").isJsonObject()){
  JsonObject rates = dataObject.getAsJsonObject("RATES");
  if (rates.getAsJsonArray("RS").isJsonArray()){
      //parse stuff
  }
}

I get com.google.gson.JsonObject cannot be cast to com.google.gson.JsonArray in here

 if (rates.getAsJsonArray("RS").isJsonArray())

and If I change that to

if (rates.getAsJsonObject("RS").isJsonObject())

I get com.google.gson.JsonArray cannot be cast to com.google.gson.JsonObject

Deserialize JSON with Numeric Rows

I am trying to deserialize some JSON into a list using JSON.NET; however, there is a number in the way:

Here is the JSON:

"payment_info": {
    "fb_id": "",
    "order_items": {
      "0": {
        "product_id": "4534",
        "type": "product",
        "shipping_cost_per_item": "1.00",
        "quantity": "3",
        "price_each": "10.00",
        "price_total": "30.00"
      }
    },

Here is my class:

    public class OrderItem
    {
        public string product_id { get; set; }
        public string type { get; set; }
        public string shipping_cost_per_item { get; set; }
        public string quantity { get; set; }
        public string price_each { get; set; }
        public string price_total { get; set; }
    }

    public class OrderItems
    {
        public List<OrderItem> Items { get; set; }
    }

How do I tell the converter to ignore the 0? There will be a 1,2,3 for each order item.

How to cancel a scheduled email in mandrill?

I am using http://ift.tt/1DRHqds package to handle my emails in mandrill. The package has a method to schedule an email like this.

$timestamp = new DateTime('+1 hour');
$mandrill = MailTo::Mandrill();
$mandrill->addRecipient($email, $name)
         ->setFrom($email, $name)
         ->setHtml($html)
         ->setText($text)
         ->setSubject($subject)
         ->send($timestamp);

But I can't find a way to cancel a scheduled email. I read this docs http://ift.tt/1dMiZt6

Request JSON

 {
    "key": "example key",
    "id": null
} 

but I don't know how to implement this. Does anyone can help me with this?

How to read latitude and longitude from json and plot it on google maps

I want to read latitude and longitude from json, the json file looks like this, and get plot the latitude and longitude on the google map in android. The latitude is name and longitude is country.

[{"name":"13.0714562","country":"77.55946348","twitter":"Current Location"},{"name":"13.0714562","country":"77.55946348","twitter":"Current Location"},{"name":"13.0714562","country":"77.55946348","twitter":"Current Location"},{"name":"13.0714562","country":"77.55946348","twitter":"Current Location"},{"name":"13.0714562","country":"77.55946348","twitter":"Current Location"},{"name":"13.0714562","country":"77.55946348","twitter":"Current Location"},{"name":"13.0714562","country":"77.55946348","twitter":"Current Location"},{"name":"13.0714562","country":"77.55946348","twitter":"Current Location"},{"name":"13.0714562","country":"77.55946348","twitter":"Current Location"},{"name":"13.0714562","country":"77.55946348","twitter":"Current Location"},{"name":"13.0714562","country":"77.55946348","twitter":"Current Location"},{"name":"13.0714562","country":"77.55946348","twitter":"Current Location"},{"name":"13.0714562","country":"77.55946348","twitter":"Current Location"},{"name":"13.0714562","country":"77.55946348","twitter":"Current Location"},{"name":"13.0714562","country":"77.55946348","twitter":"Current Location"},{"name":"13.0714562","country":"77.55946348","twitter":"Current Location"},{"name":"13.0714562","country":"77.55946348","twitter":"Current Location"},{"name":"13.0714562","country":"77.55946348","twitter":"Current Location"},{"name":"13.0714562","country":"77.55946348","twitter":"Current Location"},{"name":"13.0714562","country":"77.55946348","twitter":"Current Location"},{"name":"13.0714562","country":"77.55946348","twitter":"Current Location"}]

Here is my android maps code.

public class Maps extends Activity {
      private static String url = "http://ift.tt/1kpxaCr";
       static final LatLng College = new LatLng(13.1172245 , 77.6341758);

       private GoogleMap googleMap;
       float lat,lon;

       @Override
       protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.maps);
          try { 


                if (googleMap == null) {
                   googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
                    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(College, 15));

                }

             googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

             @SuppressWarnings("unused")
            Marker TP = googleMap.addMarker(new MarkerOptions().position(College).title("Revamp 15,click on the arrow below for directions"));


          } catch (Exception e) {
             e.printStackTrace();
          }

       }

    }

How should i replace the static final LatLng College = new LatLng(13.1172245 , 77.6341758); witht the json data ?

How to return an array instead of object in JSON response?

I've one working REST API developed using Slim PHP framework.

It's working absolutely fine.

The only issue is when there is no error present i.e. an array $errors is empty it comes as an array in JSON response but when the array $errors contains any error like $errors['user_name'] then it comes as an object in JSON response.

Actually I want to return the array when error is present. How should I do this? Can someone please help me in this regard?

Thanks in advance.

access anonymous property from object

I have a set of nesting json object like this:

var obj = {
  name: "student",
  contact: {
     phone: "22222",
     fax: "33333",
     ...
  },
  ...
}

And I have these text fields:

<input type="text" name="name" />
<input type="text" name="contact_phone" />
<input type="text" name="contact_fax" />
...

Now I want to fill these fields with appropriate property from above object. My question is how can I access anonymous property from that object? For example suppose I have this jquery code:

 $("#formID").find("input").each(function(index) {
    fieldName = $(this).attr("name");
    var namePart = fieldName.split("_");
    //I want something like this: console.log(obj.namePart[0].namePart[1])
});

Encoding issue when parsing JSON data from server... (Arabic)

I am developing an android app with both English and Arabic language support. In this, I am parsing Json data from server which contain both English and Arabic. I have to display English or Arabic text which is parsed from Json, according to user language selection. I can display the English string successfully. But while trying to display the arabic string it showing some weird characters.

Please note that I don't have much knowledge in Character Encoding. So please don’t blame me if it is a wrong question.

getjsondata function

 private class GetJsondata extends AsyncTask<Void, Void, ArrayList<ArrayList<String>>> {

    @Override
    protected void onPreExecute() {
        dialog = ProgressDialog.show(getActivity(), "", getActivity().getResources().getString(R.string.pleasewait), true);
    }

    @Override
    protected ArrayList<ArrayList<String>> doInBackground(Void... arg0) {
        // Creating service handler class instance
        ConnectivityManager conMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
        if (activeNetwork != null && activeNetwork.isConnected()) {
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    jsonObj = new JSONObject(jsonStr);
                    ObjectOutput out = new ObjectOutputStream(new FileOutputStream
                            (new File(getActivity().getCacheDir(), "") + File.separator + "cacheFile.srl"));
                    out.writeObject(jsonObj.toString());
                    out.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }
        }
        else{
            try {
                ObjectInputStream in = new ObjectInputStream(new FileInputStream
                        (new File(getActivity().getCacheDir() + File.separator + "cacheFile.srl")));
                jsonObj = new JSONObject((String) in.readObject());
                in.close();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (OptionalDataException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (StreamCorruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
            if(jsonObj!=null) {
                try {
                    ofrList = new ArrayList<ArrayList<String>>();
                    // Getting JSON Array node
                    contacts = jsonObj.getJSONArray("offers");

                    shoplistarray = new ArrayList<ArrayList<String>>();


                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);

                        String url = c.getString("url");
                        if (userPrefs.getString("locale",null)==null || userPrefs.getString("locale",null).equals("en")) {
                            desc = c.getString("desc");
                        }
                        else{
                            String s= c.getString("desc_ar");
                            try {
                                byte[] b= s.getBytes("UTF-8");
                                desc = new String(b, "UTF-16");
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }

                        }
                        String expdate = c.getString("expdate");
                        String ofrdate = c.getString("date");
                        ArrayList<String> ofrData = new ArrayList<String>();
                        ofrData.add(url);
                        ofrData.add(desc);
                        ofrData.add(expdate);
                        ofrData.add(ofrdate);
                        ofrList.add(ofrData);
                        shoplist = new ArrayList<String>();
                        shopsarray = c.getJSONArray("shops");
                        for (int n = 0; n < shopsarray.length(); n++) {

                            JSONObject jobj = shopsarray.getJSONObject(n);
                            String shopid = jobj.getString("shopid");
                            shoplist.add(shopid);
                        }
                        shoplistarray.add(shoplist);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }



        return ofrList;
    }

servicehandler.java

package com.alsafeer.xpressions;

 import org.apache.http.HttpEntity;
 import org.apache.http.HttpResponse;
 import org.apache.http.NameValuePair;
 import org.apache.http.client.ClientProtocolException;
 import org.apache.http.client.entity.UrlEncodedFormEntity;
 import org.apache.http.client.methods.HttpGet;
 import org.apache.http.client.methods.HttpPost;
 import org.apache.http.client.utils.URLEncodedUtils;
 import org.apache.http.impl.client.DefaultHttpClient;
 import org.apache.http.protocol.HTTP;
 import org.apache.http.util.EntityUtils;

 import java.io.IOException;
 import java.io.UnsupportedEncodingException;
 import java.util.List;

 public class ServiceHandler {

static String response = null;
public final static int GET = 1;
public final static int POST = 2;

public ServiceHandler() {

}

/*
 * Making service call
 * @url - url to make request
 * @method - http request method
 * */
public String makeServiceCall(String url, int method) {
    return this.makeServiceCall(url, method, null);
}

/*
 * Making service call
 * @url - url to make request
 * @method - http request method
 * @params - http request params
 * */
public String makeServiceCall(String url, int method,
        List<NameValuePair> params) {
    try {
        // http client
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        // Checking http request method type
        if (method == POST) {
            HttpPost httpPost = new HttpPost(url);
            // adding post params
            if (params != null) {
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            }

            httpResponse = httpClient.execute(httpPost);

        } else if (method == GET) {
            // appending params to url
            if (params != null) {
                String paramString = URLEncodedUtils
                        .format(params, "UTF-8");
                url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);

            httpResponse = httpClient.execute(httpGet);

        }
        httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity, HTTP.UTF_8);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return response;
   }
}

Webview throws "Uncaught SyntaxError: Unexpected identifier",while sending JSon object from native code to webview

I want to upload a file in a webview. I'm able to upload the files in devices till Android 4.3 & above Android 4.4.3. using openFileChoser() & showFileChoser(for lollypop). But openFileChoser() doesn't get called in Android 4.4.1 & Android 4.4.2. So I implemented a custom file choser dialog. And I'm able to select the file. But problem is, I'm not able to inform the webview that user has selected the file. So that it informs the tag that file is chosen and show the file name in the webview. I tried by calling javascript of the html page through code,. But nothing happens and in the console I can see this message:

"Uncaught SyntaxError: Unexpected identifier", in the html file.

Here is my onActivity Result code, where I'm calling javascript of the html page:

/****Activity Class****/

    public class MainActivity extends Activity {

  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intentData) {
        super.onActivityResult(requestCode, resultCode, intentData);
  if (kitkat()) {
            String realPathFromURI = "";
            String fullPathUri = null;
            if (intentData != null) {
                Uri uri = intentData.getData();
                if (uri != null) {


                    Uri uri1 = Uri.parse(uri.toString());

                    realPathFromURI = Utility.getRealPathFromURI(this, uri1);

                    if (null != realPathFromURI) {

                        File file = new File(Utility.getRealPathFromURI(this, uri1));

                        boolean isMaxSize = Utility.isMaxFileSize(file.length());

                        if (isMaxSize) {
                            if (this != null)
                                Toast.makeText(this.getApplicationContext(), "File Size too large",
                                        Toast.LENGTH_SHORT).show();
                            return;
                        }


                        fullPathUri = file.toString();


                    } else {
                        if (this != null)
                            Toast.makeText(this.getApplicationContext(), "Invalid File Format", Toast.LENGTH_SHORT)
                                    .show();
                    }

                }
            } else {
                realPathFromURI = "";

                fullPathUri = mCameraPhotoPath;
            }

    Bitmap bm = null;
    ;

    BitmapFactory.Options op = new BitmapFactory.Options();
    op.inSampleSize = 4;

    bm = BitmapFactory.decodeFile(fullPathUri);


    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] b = baos.toByteArray();
    String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
    ImagePath oPath = new ImagePath(fullPathUri, encodedImage);


   String sJSON = new com.google.gson.Gson().toJson(oPath);

            String msgToSend = realPathFromURI;
//            browser.loadUrl("javascript:KitKatWebviewChooseImgResult(\"" + msgToSend + "\")");
            browser.loadUrl("javascript:ShowImageResult(\"" + sJSON + "\")");


        }
else{
        // code for all versions 
}
           }

/fileupload.html/

 <form>

   <input type="file" name="file" id="files" style="width:195px;font-size:12px;" onclick="showFileChoser()" />
        <p id="path">No File chosen</p>

        <input type="button" id="mySubmit" value="submit" style="height:100px;width:200px;" onclick="this.disabled = true;form1.submit();" disabled="true" />

    ////
    ///
    </form>


 <script>
     function KitKatWebviewChooseImgResult(msg) {
            document.getElementById("path").innerHTML = msg;


        }
 function showFileChoser(){
    choser.choseImage();
    }

    function ShowImageResult(obj){
    var image= document.getElementById("files");
    image.value=obj.Base64;



    }
    </script>

Is it a right method to convert a class to json object. " String sJSON = new com.google.gson.Gson().toJson(oPath);" I'm I doing anything wrong.. . Thanks Advance..

Rails: Tips for parsing JSON [on hold]

I'm relatively new to rails. Was curious if I'm parsing JSON the 'right/best' way. So I'm trying to get a list of subreddits from Reddit so I used the subreddits JSON from Reddit.

Here is what I first did to convert the JSON to hash -

require 'open-uri'

hash = JSON.load(open('http://ift.tt/1k5Yusm'));

I then, got the list display_name (subreddit names) from my hash the following way -

subreddit_arr = hash["data"]["children"].map { |c| c["data"]["display_name"]}

which gave me -

["funny", "pics", "AdviceAnimals", "aww", "todayilearned", "videos", "gaming", "gifs", "BlackPeopleTwitter", "WTF", "fatpeoplehate", "leagueoflegends", "AskReddit", "pcmasterrace", "me_irl", "worldnews", "news", "Showerthoughts", "DotA2", "4chan", "mildlyinteresting", "TrollXChromosomes", "nba", "politics", "trees"]

How can I get a list of all subreddits (not just 25) in the most efficient manner?

Getting all existing skins name of items from Steam game CSGO

I'm trying to extract information on all existing items/skins of a specific Steam game available on the Steam market; example with CSGO: http://ift.tt/1nGoxJ4

I succeeded in getting all items info as long as I have the specific classid using ISteamEconomy, but is there a way to get all items' classid from the market page (in json, to the extent available)?

Thanks!

My codes are not working (json, arrays)

$wiki_img = "http://ift.tt/1ckD1KK";

$json2 = file_get_contents($wiki_img);
$data2 = json_decode($json2, TRUE);

foreach ($data2['query']['pages'] as $pages) {
print_r($pages['source']);
}

My codes are not working. But I can't find what is error.I got this error "Notice: Undefined index: source in C:\xampp\htdocs\"

file_get_contents did not return the complete data in PHP

While parsing the below code, file_get_contents(url) returns only part of the data instead of the complete data. After clearing the browsing history and run the same code some more data is avaiable in $data3, but the complete data from the URL is still not retrieved.

Can you please suggest how to resolve this issue to retrieve all the data from the URL?

PHP code:

$results = file_get_contents('urllink');
$json_array = json_decode($results, true);

foreach ($json_array as $value) {

    $key1 = $value["LineageId"];
    $url = "urllink.$key1.apikey";
    echo $url;
    $data3 = file_get_contents($url);
    echo $data3;
}

iOS push notifications doesn't work if "aps" informed in JSON

If I've my app closed and I send a push notification like this:

{
     "alert" : "Hello, world!",
     "sound" : "default"
}

My app receives push notification correctly. But if I send this:

{
    "aps" : {
        "alert" : "Hello, world!",
        "sound" : "default"
    }
}

My app never show the notification.

If my app is opened I received this last notification correctly in delegate didReceiveRemoteNotification userInfo: [NSObject : AnyObject]

Why iOS 8 is not parsing this last notification and showing it like a notification?

When using an $.each statement on my json object I get an error

When using an $.each statement on my json object I get an 'Uncaught TypeError: Cannot read property 'length' of undefined'. I know my $.each statement is causing it because when I comment it out the console.log returns [Object, Object, Object] as expected. What I'm trying to do is iterate through the object and return the value of title.

$(function () {
var MENU = [
    {
        'title': 'Item 1',
        'submenu': null
    },
    {
        'title': 'Item 2',
        'submenu': null
    },
    {
        'title': 'Item 3',
        'submenu': [
            {
                'title': 'Sub 1',
                'submenu': null
            },
            {
                'title': 'Sub 2',
                'submenu': null
            },
            {
                'title': 'Sub 3',
                'submenu': [
                    {
                        'title': 'SubSub 1',
                        'submenu': null
                    },
                    {
                        'title': 'SubSub 2',
                        'submenu': null
                    },
                    {
                        'title': 'SubSub 3',
                        'submenu': null
                    }
                ]
            }
        ]
    }
];

var getMenuItem = function (MENU) {
    $.each(MENU, function (key, value) {
        var title = value.title;
        $('#myMenu').append('<ul>' +'<li>' + title +'</li>' + '</ul>' );


    });
    console.log(MENU);

};
getMenuItem();



console.log(MENU);

});

jQuery autocomplete - assigning one JSON PHP array to multiple HTML ID tags

I have successfully setup a jQuery autocomplete call from a PHP file using JSON encode. I am successfully sending a KVP (Key Value Pair) array back to my HTML.

The issue I have, is that I wish to send part of the array items to one id="sometag1" and the other array items to id="sometag2" and id="sometag3".

Here is my javascript jquery code:

jQuery(document).ready(function(data) {
    $('#edit-ad-location').autocomplete({
        source: '/postcodes-latlong.php',
        minLength: 2
    });
});

The file "postcodes-latlong.php" contains the following code:

$rs = mysql_query('select p.ID, p.post_title, m.* FROM wp_posts p, wp_postmeta m WHERE p.ID = m.post_id AND p.post_title like "' . mysql_real_escape_string($_REQUEST['term']) . '%" AND meta_value is NOT NULL AND meta_value !="" AND (meta_key = "_aphs_FYN_latitude" OR meta_key = "_aphs_FYN_longitude") order by post_title limit 0,25', $dblink);
$this_row = "";
// loop through each postcode returned and format the response for jQuery
$data = array();
if ($rs && mysql_num_rows($rs)) {
    while ($row = mysql_fetch_array($rs, MYSQL_ASSOC)) {
        $new_row = $row['post_title'];
        if ($new_row != $this_row) {
            $data[] = array(
                'id' => $row['meta_id'],
                'label' => $row['post_title'],
                'value' => $row['post_title']
            );
        }
        if ($row['meta_key'] == "_aphs_FYN_latitude") {
            $data[] = array_push($data, array(
                'id' => 'geo-search-lat',
                'value' => $row['meta_value']
            ));
        }
        if ($row['meta_key'] == "_aphs_FYN_longitude") {
            $data[] = array_push($data, array(
                'id' => 'geo-search-lng',
                'value' => $row['meta_value']
            ));
        }
        $this_row = $row['post_title'];
    }
}
// jQuery wants JSON data
echo json_encode($data);
flush();

And if the term 4503 is passed, we get the following returning array:

[{
    "id": "384047",
    "label": "4503, DAKABIN",
    "value": "4503, DAKABIN"
}, {
    "id": "geo-search-lat",
    "value": "-27.226474"
}, 2, {
    "id": "geo-search-lng",
    "value": "152.980732"
}, 4, {
    "id": "384062",
    "label": "4503, GRIFFIN",
    "value": "4503, GRIFFIN"
}, {
    "id": "geo-search-lat",
    "value": "-27.272654"
}, 7, {
    "id": "geo-search-lng",
    "value": "153.025911"
}, 9, {
    "id": "384077",
    "label": "4503, KALLANGUR",
    "value": "4503, KALLANGUR"
}, {
    "id": "geo-search-lat",
    "value": "-27.25075"
}, 12, {
    "id": "geo-search-lng",
    "value": "152.992606"
}, 14, {
    "id": "384092",
    "label": "4503, KURWONGBAH",
    "value": "4503, KURWONGBAH"
}, {
    "id": "geo-search-lat",
    "value": "-27.225828"
}, 17, {
    "id": "geo-search-lng",
    "value": "152.947552"
}, 19, {
    "id": "384107",
    "label": "4503, MURRUMBA DOWNS",
    "value": "4503, MURRUMBA DOWNS"
}, {
    "id": "geo-search-lat",
    "value": "-27.258672"
}, 22, {
    "id": "geo-search-lng",
    "value": "153.006916"
}, 24, {
    "id": "384122",
    "label": "4503, WHITESIDE",
    "value": "4503, WHITESIDE"
}, {
    "id": "geo-search-lat",
    "value": "-27.255364"
}, 27, {
    "id": "geo-search-lng",
    "value": "152.929729"
}, 29]

What I am trying to achieve, is send the ID, label and value (i.e. post_id, postcode, and suburb name) to the autocomplete field with id: "#edit-ad-location" and this works fine. But, I wish to send the latitude and longitude values to two other id tags #geo-search-lat and #geo-search-lng as shown below:

<div .... id="geo-search-lat" value=""> </div>

and

<div .... id="geo-search-lng" value=""> </div>

I have tried a number of approaches including converting the PHP JSON array to a Javascript array also trying to pass the JSON array as PHP array rather than JSON...

But I am struggling to glue all this together.

Is there a simple way to parse the array so that part of the KVP's go to one ID tag, and the rest goes to two other ID tags?

Something along the lines of:

jQuery(document).ready(function(data){
    $('#edit-ad-location', '#geo-search-lat', '#geo-search-lng').autocomplete({source:'/postcodes-latlong.php', minLength:2});
});

But if I try this approach returns an error.

You can try sending australian postcodes to the following URL and test it for yourslef:

http://ift.tt/1ckqpn9

Where XXXX is any integer from 0 to 9999.

Any help is appreciated.

Cheers, Henry

Need help accessing JSON array object

Objective: This code collects an array JSONAPIS and passes the APIS into a $.each() loop. Then JSON data field are evaluated in if statements and used to calculate precip. How do I access the JSONAPIS from the obj. Main issue: obj.daily.data.length is undefined on the daily array member. The obj should contain one of the API calls and the JSON dataset to use. Instead it contains keyword like abort, always, promise which I am not familiar how to use. What would access the result JSON object property?

var listAPIs = "";
    var darkForecastAPI = [];
    var result = [];
    var JSONAPIS = [];
$.each(numDaysAPITimes, function(a, time) {
    var darkForecastAPI = /*"http://ift.tt/1eU3pXU" + currentAPIKey + "/history_" + time + "/q/" + state + "/" + city +".json?callback=?"; */
        "http://ift.tt/1JmMFqC" + currentAPIKey + "/" + city + time + "?callback=?";
    //http://ift.tt/1iYC1hI
    JSONAPIS.push($.getJSON(darkForecastAPI, {
        tags: "WxAPI[" + i + "]", //Is this tag the name of each JSON page? I tried to index it incase this is how to refer to the JSON formatted code from the APIs.
        tagmode: "any",
        format: "json"
    }));
});
$.when(JSONAPIS).then(function(result) { /*no log simply an array */
    var eachPrecipSum = 0.0;
    var totalPrecipSinceDate = 0.0;
    alert(result);

    $.each(result, function(d, obj) {
        for (var c = 0; c <= obj.daily.data.length - 1; c++) {
            if (obj.daily.data[c].precipIntensity >= 0.0000 && obj.daily.data[c].precipType == "rain") /*Number(result.history.dailysummary.precipm, result.history.dailysummary.rain*/ {
                eachPrecipSum = result[d].daily.data[c].precipIntensity;
                totalPrecipSinceDate = eachPrecipSum + totalPrecipSinceDate; ///Write mean precip
                alert(Math.round(eachPrecipSum * 10000) / 10000);
                $("body").append("p").text("There has been as least a total of " + Math.round(totalPrecipSinceDate * 10000) / 10000 + " inches per hour of rain at the location in the last " + userDataDatePick + " days")

            } else if (obj.daily.data[c].precipIntensity >= 0.0000 && obj.daily.data[c].precipType != "rain") {
                alert("There is was no rain on ____" /*+ result.history.dailysummary.mon + "/" + result.history.dailysummary.mday + "/" + result.history.dailysummary.year*/ );
            }
        }
    });
});
numDaysAPITimes = 0;

}

How to store data for my complex web app, similar to JS Fiddle

I'm designing a web app and I'd like to make sure that my data model will work and can grow. If anyone knows any resources or standards I should follow, I'd appreciate that too. Basically, it's a complex note application with the following pieces:

I have things called chapters, the user can only see one chapter at a time. A chapter consists of 2 parts : pages and comments.

The left half of the window houses the pages (there can be multiple pages). For sake of simplicity, a page is just a string of text.

The right half will contain the comments. In other words, when a user selects a certain sentence in a page, a comment will pop up.

I'd like to have as many of these chapters as necessary, and I haven't come up with a navigational structure but I suspect I'll need to be able to group chapters together.

Right now, how I was thinking about it was having an array for each chapter so it looks like this:

[
    {
        "page": "asd",
        "comments": another array
    },
    {
        "page": "random string, will include html elements"
        "comments": another array
    }
]

I'm using angular JS and using ng-repeat to loop through this array and display all the pages. Then depending on which comment the user clicks on, the selected comment will show up on the right side.

So I don't have a unique id for each chapter- is there a standard way? I also think I need some kind of id for comments, since there can be many comments per page. I was looking into guid's but I've never used them before.

I was thinking of having this comments array:

"comments": [ {"id": "guid", "comment":"asfasfd"}, {"id": "guid", "comment":"asfasfd"}]

I also wanted to assign a guid for each chapter. For testing, I was going to keep all the chapters in one json file.

What is generally done for stuff like this? For example, how does JS Fiddle store it's data? I assume there are chunks for the html, the JS and the CSS, along with metadata, but I'm not sure how their data model actually looks like.

Parse JSON array to matrix using map

I'm using swiftyJSON.

The data looks like the following but not really, there are about 700,000 elements.

{
    "data": [
        [
            "one",
            "steak",
            -0.234
        ],
        [
            "cat",
            "pizza",
            1.9812
        ]
    ]
}

Currently I'm using this

let jsonArray:[JSON] = json["data"].arrayValue
for ( i=0; i<jsonArray.count; i++ )//number of data points
{
  A.append(jsonArray[i][0].string! )
  B.append(jsonArray[i][1].string! )
  X.append(jsonArray[i][2].float! )
}

but it is slow, I'd like to use map to speed things up to create individual arrays like shown or a M x N matrix. Or how would I put this into a struct?

Error with Json http request iOS

I am trying to work on Livelink restful services and get data in iOS Application. The documentation link for api is:

http://ift.tt/1OY65sS

Code I am using for getting response data is:

NSDictionary *authDict = [[NSDictionary alloc] initWithObjectsAndKeys:
                              @"XYZ",@"username",
                              @"ABC",@"password",
                              nil];
NSError *error;
NSData *requestData = [NSJSONSerialization dataWithJSONObject:authDict options:0 error:&error];
NSURL *url = [NSURL URLWithString:@"http://ift.tt/1EOCLwR"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];                                              
[request setHTTPMethod:@"POST"]; 
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];

NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil];

NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding]; 

But in request reply I am not getting authentication result.When I log request reply,the log is:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://ift.tt/mOIMeg">
<html xmlns="http://ift.tt/lH0Osb">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>500 - Internal server error.</title>
<style type="text/css">
<!--
body{margin:0;font-size:.7em;font-family:Verdana, Arial, Helvetica, sans-serif;background:#EEEEEE;}
fieldset{padding:0 15px 10px 15px;} 
h1{font-size:2.4em;margin:0;color:#FFF;}
h2{font-size:1.7em;margin:0;color:#CC0000;} 
h3{font-size:1.2em;margin:10px 0 0 0;color:#000000;} 
#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS", Verdana, sans-serif;color:#FFF;
background-color:#555555;}
#content{margin:0 0 0 2%;position:relative;}
.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;}
-->
</style>
</head>
<body>
<div id="header"><h1>Server Error</h1></div>
<div id="content">
 <div class="content-container"><fieldset>
  <h2>500 - Internal server error.</h2>
  <h3>There is a problem with the resource you are looking for, and it cannot be displayed.</h3>
 </fieldset></div>
</div>
</body>
</html>

Could you please help me to get the Authentication ticket. Thanks in advance.

Trying to Parse JSON in C# using JSON.NET

I'm trying to parse some JSON using JSON.NET but whenever I try to get the value from any of the values, it returns 0. I just want to get the values from the first set of data. Here is my code:

        string text = listBox1.SelectedItem.ToString();
        text = text.Substring(text.LastIndexOf(": ") + 2);
        string url = "http://ift.tt/1xI1UJB" + text + "/1";
        var json = new WebClient().DownloadString(url);

        Result itemPrices = JsonConvert.DeserializeObject<Result>(json);

        int buyPrice = itemPrices.min_sale_unit_price;
        int sellPrice = itemPrices.max_offer_unit_price;

        sellPriceLabel.Content = "Highest Sell Price: " + sellPrice;
        buyPriceLabel.Content = "Lowest Buy Price: " + buyPrice;

And here is my JSON objects class:

public class Result
{
    public int data_id { get; set; }
    public string name { get; set; }
    public int rarity { get; set; }
    public int restriction_level { get; set; }
    public string img { get; set; }
    public int type_id { get; set; }
    public int sub_type_id { get; set; }
    public string price_last_changed { get; set; }
    public int max_offer_unit_price { get; set; }
    public int min_sale_unit_price { get; set; }
    public int offer_availability { get; set; }
    public int sale_availability { get; set; }
    public int sale_price_change_last_hour { get; set; }
    public int offer_price_change_last_hour { get; set; }
}

public class RootObject
{
    public int count { get; set; }
    public int page { get; set; }
    public int last_page { get; set; }
    public int total { get; set; }
    public List<Result> results { get; set; }
}

Here is the JSON I am trying to parse:

{
"count": 3,
"page": 1,
"last_page": 1,
"total": 3,
"results": [
    {
        "data_id": 12223,
        "name": "Apple Pie",
        "rarity": 2,
        "restriction_level": 10,
        "img": "http://ift.tt/1OZ5XZX",
        "type_id": 3,
        "sub_type_id": 1,
        "price_last_changed": "2015-05-05 20:58:24 UTC",
        "max_offer_unit_price": 136,
        "min_sale_unit_price": 226,
        "offer_availability": 22161,
        "sale_availability": 4007,
        "sale_price_change_last_hour": 0,
        "offer_price_change_last_hour": 0
    },
    {
        "data_id": 12150,
        "name": "Eda's Apple Pie",
        "rarity": 1,
        "restriction_level": 5,
        "img": "http://ift.tt/1bwFUXL",
        "type_id": 3,
        "sub_type_id": 1,
        "price_last_changed": "2015-05-05 23:31:06 UTC",
        "max_offer_unit_price": 160,
        "min_sale_unit_price": 313,
        "offer_availability": 3596,
        "sale_availability": 2744,
        "sale_price_change_last_hour": 0,
        "offer_price_change_last_hour": 0
    },
    {
        "data_id": 9497,
        "name": "Eda's Apple Pie Recipe",
        "rarity": 1,
        "restriction_level": 0,
        "img": "http://ift.tt/1OZ5XZZ",
        "type_id": 3,
        "sub_type_id": 6,
        "price_last_changed": "2014-09-11 10:12:00 UTC",
        "max_offer_unit_price": 10101,
        "min_sale_unit_price": 0,
        "offer_availability": 0,
        "sale_availability": 0,
        "sale_price_change_last_hour": 0,
        "offer_price_change_last_hour": 0
    }
]

}

Attempting to Display Array on to UITableView

I am attempting to display an array which I receive from a JSON Dictionary onto a UITableView but I keep getting an error. I am trying to display all the comments for a given Instagram Picture onto a Table. Here is how I am attempting to display the cells:

  MessageTableViewCell *cell = (MessageTableViewCell *)[self.tableView dequeueReusableCellWithIdentifier:MessengerCellIdentifier];

  NSDictionary *instaPics = self.instagramData;
  NSArray *commentArray =  instaPics[@"comments"][@"data"];
  NSString *commentText = [commentArray valueForKey:@"text"]; // Error occurs here

  Message *message = self.messages[indexPath.row];

  cell.titleLabel.text = message.username;
  cell.bodyLabel.text = commentText;

Here is the error I receive:

 -[__NSArrayI length]: unrecognized selector sent to instance 0x7f913052db10
2015-05-05 22:16:08.848 Floadt[6061:514032] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI length]: unrecognized selector sent to instance 0x7f913052db10'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000107d60c65 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x000000010763cbb7 objc_exception_throw + 45
    2   CoreFoundation                      0x0000000107d680ad -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
    3   CoreFoundation                      0x0000000107cbe13c ___forwarding___ + 988
    4   CoreFoundation                      0x0000000107cbdcd8 _CF_forwarding_prep_0 + 120
    5   UIKit                               0x0000000106543ab4 -[UILabel _textRectForBounds:limitedToNumberOfLines:includingShadow:] + 65
    6   UIKit                               0x000000010654390f -[UILabel textRectForBounds:limitedToNumberOfLines:] + 76
    7   UIKit                               0x00000001065473b9 -[UILabel _intrinsicSizeWithinSize:] + 170
    8   UIKit                               0x0000000106547499 -[UILabel intrinsicContentSize] + 76
    9   UIKit                               0x00000001069e5b6c -[UIView(UIConstraintBasedLayout) _generateContentSizeConstraints] + 33
    10  UIKit                               0x00000001069e5930 -[UIView(UIConstraintBasedLayout) _updateContentSizeConstraints] + 422
    11  UIKit                               0x00000001069ecd25 -[UIView(AdditionalLayoutSupport) updateConstraints] + 162
    12  UIKit                               0x0000000106547304 -[UILabel updateConstraints] + 274
    13  UIKit                               0x00000001069ec346 -[UIView(AdditionalLayoutSupport) _internalUpdateConstraintsIfNeededAccumulatingViewsNeedingSecondPassAndViewsNeedingBaselineUpdate:] + 242
    14  UIKit                               0x00000001069ec53e -[UIView(AdditionalLayoutSupport) _updateConstraintsIfNeededAccumulatingViewsNeedingSecondPassAndViewsNeedingBaselineUpdate:] + 124
    15  CoreFoundation                      0x0000000107c67354 CFArrayApplyFunction + 68
    16  UIKit                               0x00000001069ec2ed -[UIView(AdditionalLayoutSupport) _internalUpdateConstraintsIfNeededAccumulatingViewsNeedingSecondPassAndViewsNeedingBaselineUpdate:] + 153
    17  Foundation                          0x0000000105b021be -[NSISEngine withBehaviors:performModifications:] + 155
    18  UIKit                               0x00000001069ec53e -[UIView(AdditionalLayoutSupport) _updateConstraintsIfNeededAccumulatingViewsNeedingSecondPassAndViewsNeedingBaselineUpdate:] + 124
    19  CoreFoundation                      0x0000000107c67354 CFArrayApplyFunction + 68
    20  UIKit                               0x00000001069ec2ed -[UIView(AdditionalLayoutSupport) _internalUpdateConstraintsIfNeededAccumulatingViewsNeedingSecondPassAndViewsNeedingBaselineUpdate:] + 153
    21  UIKit                               0x00000001069ec53e -[UIView(AdditionalLayoutSupport) _updateConstraintsIfNeededAccumulatingViewsNeedingSecondPassAndViewsNeedingBaselineUpdate:] + 124
    22  UIKit                               0x00000001069eca0e __60-[UIView(AdditionalLayoutSupport) updateConstraintsIfNeeded]_block_invoke + 96
    23  UIKit                               0x00000001069ec6d6 -[UIView(AdditionalLayoutSupport) updateConstraintsIfNeeded] + 231
    24  UIKit                               0x00000001067d7531 -[UITableViewCellContentView updateConstraintsIfNeeded] + 94
    25  UIKit                               0x00000001069ecdde -[UIView(AdditionalLayoutSupport) _updateConstraintsAtEngineLevelIfNeeded] + 146
    26  UIKit                               0x00000001063e4a3d -[UIView(Hierarchy) _updateConstraintsAsNecessaryAndApplyLayoutFromEngine] + 114
    27  UIKit                               0x00000001063f0a2b -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 536
    28  QuartzCore                          0x00000001061b4ec2 -[CALayer layoutSublayers] + 146
    29  QuartzCore                          0x00000001061a96d6 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
    30  UIKit                               0x00000001063e4675 -[UIView(Hierarchy) layoutBelowIfNeeded] + 607
    31  Floadt                              0x0000000104195848 -[SLKTextViewController viewWillAppear:] + 296
    32  UIKit                               0x00000001064a4fa1 -[UIViewController _setViewAppearState:isAnimating:] + 487
    33  UIKit                               0x00000001064c6395 -[UINavigationController _startCustomTransition:] + 887
    34  UIKit                               0x00000001064d23bf -[UINavigationController _startDeferredTransitionIfNeeded:] + 386
    35  UIKit                               0x00000001064d2f0e -[UINavigationController __viewWillLayoutSubviews] + 43
    36  UIKit                               0x000000010661d715 -[UILayoutContainerView layoutSubviews] + 202
    37  UIKit                               0x00000001063f0a2b -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 536
    38  QuartzCore                          0x00000001061b4ec2 -[CALayer layoutSublayers] + 146
    39  QuartzCore                          0x00000001061a96d6 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
    40  QuartzCore                          0x00000001061a9546 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
    41  QuartzCore                          0x0000000106115886 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 242
    42  QuartzCore                          0x0000000106116a3a _ZN2CA11Transaction6commitEv + 462
    43  UIKit                               0x000000010636d626 _UIApplicationHandleEventQueue + 2140
    44  CoreFoundation                      0x0000000107c94431 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    45  CoreFoundation                      0x0000000107c8a2fd __CFRunLoopDoSources0 + 269
    46  CoreFoundation                      0x0000000107c89934 __CFRunLoopRun + 868
    47  CoreFoundation                      0x0000000107c89366 CFRunLoopRunSpecific + 470
    48  GraphicsServices                    0x0000000109716a3e GSEventRunModal + 161
    49  UIKit                               0x0000000106370900 UIApplicationMain + 1282
    50  Floadt                              0x0000000104218c5f main + 111
    51  libdyld.dylib                       0x0000000109f2b145 start + 1
    52  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

Here is an example copy of the JSON:

{
    attribution = "<null>";
    caption =     {
        "created_time" = 1430877943;
        from =         {
            "full_name" = "Shreya M.";
            id = 25085898;
            "profile_picture" = "http://ift.tt/1KfELiO";
            username = "shreya_mandava";
        };
        id = 978597576956579585;
        text = "9+10????";
    };
    comments =     {
        count = 2;
        data =         (
                        {
                "created_time" = 1430878007;
                from =                 {
                    "full_name" = "Aleesha Toteja";
                    id = 17117902;
                    "profile_picture" = "http://ift.tt/1GZNFDM";
                    username = leeshtotes;
                };
                id = 978598112887967529;
                text = "DIRT \Ud83d\Ude3b";
            },
                        {
                "created_time" = 1430878307;
                from =                 {
                    "full_name" = "Shritha M.";
                    id = 375799796;
                    "profile_picture" = "http://ift.tt/1KfEHQl";
                    username = "shritha_m";
                };
                id = 978600630846098439;
                text = sigh;
            }
        );
    };
    "created_time" = 1430877943;
    filter = Normal;
    id = "978597574314167442_25085898";
    images =     {
        "low_resolution" =         {
            height = 306;
            url = "http://ift.tt/1GZNDvD";
            width = 306;
        };
        "standard_resolution" =         {
            height = 640;
            url = "http://ift.tt/1KfELiQ";
            width = 640;
        };
        thumbnail =         {
            height = 150;
            url = "http://ift.tt/1GZNFU0";
            width = 150;
        };
    };
    likes =     {
        count = 22;
        data =         (
                        {
                "full_name" = "Ronak Chopra";
                id = 347652824;
                "profile_picture" = "http://ift.tt/1KfELiU";
                username = "conak_rhopra";
            },
                        {
                "full_name" = "emily bach";
                id = 292615252;
                "profile_picture" = "http://ift.tt/1GZNDvF";
                username = "emily_bach_";
            },
                        {
                "full_name" = "\Ud83c\Udf38Trisha\Ud83c\Udf38";
                id = 303629882;
                "profile_picture" = "http://ift.tt/1KfELiW";
                username = trishddishh;
            },
                        {
                "full_name" = "Shritha M.";
                id = 375799796;
                "profile_picture" = "http://ift.tt/1KfEHQl";
                username = "shritha_m";
            }
        );
    };
    link = "http://ift.tt/1KfELiZ";
    location =     {
        id = 772010926;
        latitude = "38.913782928";
        longitude = "-77.383238738";
        name = "ft. dirt";
    };
    tags =     (
    );
    type = image;
    user =     {
        "full_name" = "Shreya M.";
        id = 25085898;
        "profile_picture" = "http://ift.tt/1KfELiO";
        username = "shreya_mandava";
    };
    "user_has_liked" = 0;
    "users_in_photo" =     (
                {
            position =             {
                x = "0.6703125";
                y = "0.246875";
            };
            user =             {
                "full_name" = "John Nguyen";
                id = 1477626916;
                "profile_picture" = "http://ift.tt/1GZNDLZ";
                username = bumbonguyen;
            };
        }
    );
}

My fix for my uitableview with sections

I figured it out. whole code below. remember im using alamofire and swiftyjson for simplicity..

Basicly my mechanism is :

1st : get the section name, data and append the section object to sections array. 2nd: while holding that instance of the section object and going thru the menu items array with the json , create the menutiem objects for each menu and use the section object function addItems to add each menuitem to that section. 3rd: check my table functions and see how i call the data of each section...

class MenuViewCell: UITableViewCell {


    @IBOutlet var lbl_nombre : UILabel!
    @IBOutlet var lbl_desc : UILabel!
    @IBOutlet var lbl_precio : UILabel!

}

class VCviendorest: UIViewController, UITableViewDelegate ,UITableViewDataSource, UIWebViewDelegate , UIScrollViewDelegate {

    required init(coder aDecoder: NSCoder) {
        self.DETAILURL = "";
        self.NOMBRERESTAURANT = "";
        self.IDREST = "";
        self.checks = [];

        super.init(coder: aDecoder)
    }


    // Array holders for menu items
    //var items:[MenuItem] = []
    var sections = [Section]()


    class Section  {
        var items: [MenuItem] = []
        var name:String = ""

        func addItem(item: MenuItem) {
            self.items.append(item)
        }

        init(name:String) {
            self.name = name
        }


    }

        class MenuItem : Printable {
            let name:String!
            let desc:String!
            let price:Float!
            var section: Int?

            init(name:String,desc:String,price:Float) {
                self.name = name
                self.desc = desc
                self.price  = price

            }
            var description: String {
                return name
            }
    }



    @IBOutlet weak var navigation: UINavigationItem!

    @IBOutlet var BottomView: UIView!

    @IBOutlet var tableView: UITableView!



    var DETAILURL:String
    var NOMBRERESTAURANT:String
    var IDREST:String
    var checks: [String]

    var originalFrame:CGRect!
    var tabActivated:Bool = true

    // BUTTONS

    @IBOutlet var but_ofertas: UIButton!

    @IBOutlet var but_actividades: UIButton!
    @IBOutlet var but_nube: UIButton!
    @IBOutlet var but_comentarios: UIButton!

    //



    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 50.0

        self.getMenu(self.IDREST)
        self.tableView.dataSource = self
        self.tableView.delegate = self;



        get_checks()



    }




     func numberOfSectionsInTableView(tableView: UITableView)
        -> Int {
           return self.sections.count

    }



    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

      return  self.sections[section].items.count


    }

    /* section headers
    appear above each `UITableView` section */
    func tableView(tableView: UITableView,
        titleForHeaderInSection section: Int)
        -> String {
            // do not display empty `Section`s
            if !self.sections[section].items.isEmpty {
                return self.sections[section].name
            }
            return ""
    }

    func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        let header: UITableViewHeaderFooterView = view as UITableViewHeaderFooterView //recast your view as a UITableViewHeaderFooterView
       // header.contentView.backgroundColor = UIColor(red: 0/255, green: 181/255, blue: 229/255, alpha: 1.0) //make the background color light blue

        header.contentView.backgroundColor = UIColor(red: 247.0/255.0, green: 247.0/255.0, blue: 247.0/255.0, alpha: 1.0)
        header.textLabel.textColor = UIColor(red: 234.0/255.0, green: 46.0/255.0, blue: 73.0/255.0, alpha: 1.0) //make the text BAR COLOR
        header.alpha = 1 //make the header transparent
    }


    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {


      let data = self.sections[indexPath.section].items[indexPath.row]
      let cell : MenuViewCell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as MenuViewCell

        cell.lbl_nombre.text = data.name
        cell.lbl_desc.numberOfLines = 0
        cell.lbl_nombre.numberOfLines = 0
        cell.lbl_desc.text = data.desc
        cell.lbl_precio.text = "RD$\(data.price)" as String
           cell.lbl_nombre.lineBreakMode = NSLineBreakMode.ByWordWrapping
        cell.lbl_desc.lineBreakMode = NSLineBreakMode.ByWordWrapping

        cell.lbl_nombre.sizeToFit()
        cell.lbl_desc.sizeToFit()


        return cell
    }

    // Func getMenu
    func getMenu(id:String) {


        // run in background
        let qualityOfServiceClass = QOS_CLASS_BACKGROUND
        let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
        dispatch_async(backgroundQueue, {
            println("This is run on the background queue")

        Alamofire.request(.GET,"http://ift.tt/1GNUAKF", parameters: ["r": "\(id)"]).responseJSON() {

            (request,response,json,error) in

            if(error != nil) {

                println("there was an \(error)")
            }


            if(json != nil) {

                let jsonObj = JSON(json!);
                let rests = jsonObj as JSON

               // println(jsonObj);

                //generate items


                if let restsarray = rests["menu"].arrayValue as [JSON]? {


                    //var reststo = [RestsModel]()
                   // var arr = [MyItem]()

                    //3
                    for restDict in restsarray {

                        var section_nombre: String? = restDict["tipo"].stringValue
                        var section = Section(name:section_nombre!)
                        self.sections.append(section)
                      //  println("tipo es \(section_nombre)")

                        if let restDictPlatos = restDict["platos"].arrayValue as [JSON]? {

                            for restDict in restDictPlatos {
                            var plato_nombre:String? = restDict["plato_nombre"].stringValue
                            var plato_desc:String? = restDict["desc"].stringValue
                            var plato_price:Float? = restDict["precio"].floatValue

                          //  print("nombre plato: \(plato_nombre)");

                              var plat = MenuItem(name: plato_nombre!, desc: plato_desc!, price: plato_price!)
                                //var section = Section(name:section_nombre!)

                                section.addItem(plat)



                                //for item in self.sections {
                                //self.sections[item.section!].addItem(item)
                                //}

                            }

                    }





                }




            }
               // println("count from self sections is \(self.sections[1].items[1].name)")

            self.tableView.reloadData()
        }





    }

        }) // end run in background

    }
    // End getMenu




}

making a JSON file from user's input

I'm trying to use JSON as some kind of database for my application. So the user adds an input and it's written to the JSON file, then when I need that information I can loop through the JSON. I'm using 'fs' to write the JSON format of my object inside file:

fs.appendFile('log.json',  JSON.stringify(customer) + '\n' , function(err) {
    if (err) {
        return console.log(err);
    }
    console.log('saved in log.json');
});

So my log.json looks like this:

{"name":"John","email":"john@gmail.com"}
{"name":"Peter","email":"Peter@gmail.com"}

This is still can be used if I read each line and convert it to object, but obviously it's not a valid JSON file and it'd be better if I can have this as output:

{
{"name":"John","email":"john@gmail.com"},
{"name":"Peter","email":"Peter@gmail.com"}
}

or even better:

[
{"name":"John","email":"john@gmail.com"},
{"name":"Peter","email":"Peter@gmail.com"}
]

So technically all I want to do is keeping {} and append my text inside curly braces. Please note that I can't store all of the inputs in an array/object and then write that in my log file. I want an external-module-free method to update my log.json file every time user enters new information.

Multiple source API callbacks

How might one implement a callback function with multiple sources and then access an array for example, like JSONP?

//website names or API variables to add to callbacks
var callbacks = $.Callbacks();
callbacks.add(result);

//then get the callback.result[i] something like this pseudocode...?

//get API1, API2, API3 then process each API and JSON code one at a time with the callback object.

Trying to get this code block to load three API in the result callback

 var listAPIs = "";
 var darkForecastAPI = [];
 var result = [];

$.each(numDaysAPITimes, function(a, time) {
    var darkForecastAPI= /*"http://ift.tt/1eU3pXU" + currentAPIKey + "/history_" + time + "/q/" + state + "/" + city +".json?callback=?"; */
                        "http://ift.tt/1JmMFqC" + currentAPIKey + "/" + city + time + "?callback=?"; 
                        //http://ift.tt/1iYC1hI
    var JSONAPIS = $.getJSON(darkForecastAPI, {
        tags: "WxAPI[" + i + "]",  //Is this tag the name of each JSON page? I tried to index it incase this is how to refer to the JSON formatted code from the APIs.
        tagmode: "any",
        format: "json"
    },
   $.when.apply(JSONAPIS).then(function(results) { /*no log simply an array */
        var eachPrecipSum = 0.0;
        var totalPrecipSinceDate = 0.0;


 for(var c = 0; c <= result.daily.data.length-1; c++)
      {
    if(result.daily.data[c].precipIntensity >= 0.0000 &&  result.daily.data[c].precipType == "rain") /*Number(result.history.dailysummary.precipm, result.history.dailysummary.rain*/
        {
              eachPrecipSum = result.daily.data[c].precipIntensity;
              totalPrecipSinceDate = eachPrecipSum + totalPrecipSinceDate;  ///Write mean precip
                        alert( Math.round(eachPrecipSum * 10000)/10000);
                        $("body").append("p").text("There has been as least a total of "+ Math.round(totalPrecipSinceDate * 10000)/10000 + " inches per hour of rain at the location in the last " + userDataDatePick + " days")


        }   

avoiding 'exec' while updating dict with complex structure

I have a JSON file with a complex structure. This file stores categories of some sort. Each category and sub-category has its 'ID' like

2 drinks
2.1 drinks coffee
2.1.1 drinks coffee instant 
2.1.2 drinks coffee real 
2.2 drinks tea 
2.3 drinks water  

For example, suppose I want to add a new category, 'alcohol'. The proper place for it us as a subcategory of 'drinks'. So I type 2 press Enter, type alcohol press Enter, and the program creates a new dictionary with a key 'drinks' like this: nd={"drinks":{"alcohol":""}} Then it updates the existing large dictionary with that new one.

As I am new in Python and in coding at all, I've done it in a very ugly way by making that new dictionary using exec because I lack skills. Also the code doesn't work properly, for example if I want to add not to existing dictionary like drinks but to just a value of key like adding 'soda' to 'water' it will have an error. I might make a workaround for it but in the same messy way. So I just ask for help and explanation how to do it in pythonic way.

To be concise: I have a set of keys that form the 'path' for new value like:

communication | mobile | verizon | calls | out | roaming | Other country

Using this 'path' I must upgrade a dict with new value, if last step in 'path' is that value - convert it to dict and then add new value.

here goes sample of JSON file:

{
"food": {
    "dairy": {
        "cheese": "Gauda",
        "milk": {
            "origin": "place",
            "brand": "name"
        }
    }
},
"communication": {
    "mobile": {
        "life": {
            "txt": "",
            "calls": ""
        },
        "vodafone": {
            "txt": "",
            "subscr": "",
            "mms": "",
            "calls": {
                "in": {
                    "home": "",
                    "roaming": ""
                },
                "out": {
                    "home": "",
                    "roaming": ""
                }
            },
            "internet": ""
        },
        "verizon": {
            "txt": "",
            "subscr": "",
            "mms": "",
            "calls": {
                "in": {
                    "home": "",
                    "roaming": ""
                },
                "out": {
                    "home": "500 min",
                    "roaming": "Other country",
                    "reached": ""
                }
            },
            "internet": "1Gb"
        }
    },
    "internet": "SomeProviderName"
},
"taxes": "",
"drinks": {
    "water": "",
    "tea": "",
    "coffee": {
        "real": "",
        "instant": ""
    }}}

Here's the code by itself:

#!/usr/bin/env python -tt
# -*- coding: utf-8 -*-
import json
import collections

def walk_dict(d, key=None, parent=None):
    res = {}
    for i, e in enumerate(sorted(d), 1):
        k = (key    + "." + str(i)) if key    else str(i)
        p = (parent + " | " +     e ) if parent else     e
        if isinstance(d[e], dict):
            res[k] = p
            res.update(walk_dict(d[e], k, p))
        else:
            res[k] = p + " | " + str(d[e])
    return res

with open('new_cat.json') as f:
    cat_data = json.load(f)
    new_data = walk_dict(cat_data)
    for v in sorted(new_data):
        print v, new_data[v]

def find_cat(d,new_cat):
    ex_str="{"
    for i in d:
        print i
        ex_str+="\""+i+"\":{"
    ex_str+="\""+new_cat+"\":\"\""+"}"*(len(d)+1)
    print ex_str
    return ex_str

inp=raw_input("pick one (numbers) or \'ENTER\' for new in root\n")
if inp=='':
    new_cat=raw_input("input new category\n")
    upd=find_cat([],new_cat)
else:
    print new_data[inp]
    new_cat=raw_input("input new category\n")
    keys=new_data[inp].split(" | ")
    upd=find_cat(keys,new_cat)

exec "nd="+str(upd)

def update(d, u):
    for k, v in u.iteritems():
        if isinstance(v, collections.Mapping):
            r = update(d.get(k, {}), v)
            d[k] = r
        else:
            d[k] = u[k]
    return d
update(cat_data,nd)   
for i in cat_data:
    print i, cat_data[i] 
f=open("new_cat.json",'w')
json.dump(cat_data,f,indent=4,encoding='utf-8',ensure_ascii=False,sort_keys=False,separators=(',', ': '))
f.close()

Save/Get ObservableCollection to/from Roaming

I'm making a Universal windows store app and I have an ObservableCollection.

What I want is to save the data from the ObservableCollection somewhere so that the data can sync between desktop and phone that have the same universal app, and then I need to be able to get this data so that I can update the ObservableCollection.

I haven't done anything like this before, so I'm not sure how to proceed... Do I need to save this to an XML file, and if so, how will I sync it between the different devices. The only storage methods I know how to use are:

     ApplicationData.Current.LocalSettings.Values["key"] = "something"; 
     //Which stores "something" in local storage with key "key".

     ApplicationData.Current.RoamingSettings.Values["key"] = "something";
     //Which stores "something" in user's  Microsoft account storage with key "key".

Last one I think looks like to what I actually want, but it wouldn't be practical to save all my ObservableCollection items and properties like this.

FSharp.Data.dll not found

I am creating an example for our next F# meetup and have run into an issue.

I have downloaded the FSharp.Data v2.2.1 to try the JSON tutorials to parse (stock options) data downloaded from the web. I have been struggling with this issue for almost a week now. I have followed the suggestions seen in other posts including complete uninstall of packages suggestion. I ran into the same issue trying to use the CSV provider and decided to switch to JSON.

I have #load @"C:\ full path to dll ...\lib\net40\FSharp.Data.dll" For some reason I have to give the full path for the F# script file to recognize it.

The line open FSharp.Data has an error "The namespace 'Data' is not defined" Nuget package manager shows that FSharp.Data version:2.2.1 is installed. I have uninstalled and reinstalled all packages in the project several times but it does not change the error.

So I am stuck at that point. I could use some insights from anyone who has been down this path. Thanks for your help.

Android Studio: How to propperly consume remote https WCF service?

Im trying to get data from a WCF remote webservice using Android Studio, I followed a tutorial (Links down there!), wich works locally with a windows IIS hosted WCF webservice.

Now Im trying to edit the code for my purpouses and Im stuck again.

I have some questions about:

  1. How to request data to a remote WCF server by android studio?

    I need to make a get request by json like this:

    { "Status":"String", "City":"String", "Address":"String", "State":"String", "Id":"Integer", }

  2. How to access https instead http? How to send and receive data throgh WCF webserver remotely ,(https)

Here is the code I have for android, note that all the show is around the class HttpClientHelper, please check the code below (Whole code on links):

-Server source code and tutorial(cs )

http://ift.tt/1bnJ9k4

http://ift.tt/1KfsoDr

-Android source code and tutorial

http://ift.tt/1ONxe1i

http://ift.tt/1Kfsn2x

The proyect map:

AndroidClientActivity Customer HttpClientHelper <---- This is the class below ObjectAdapter

The code:

package packages.AndroidClient;

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class HttpClientHelper {

    //Tag para identificar en el Log
    private static final String TAG = "HttpClientHelper";


    public static JSONArray GET(String OperationName) throws Exception
    {
        BufferedReader reader =null;
        StringBuilder sb =null;
        try 
        {
        DefaultHttpClient httpClient = new DefaultHttpClient();


 /*
 * I GUESS I  NEED TO MAKE A JSON REQUEST AROUND HERE AND I DONT KNOW HOW TO DO IT

 I need to make a get request by json like  this:
   {
   "Status":"String",
    "City":"String",
    "Address":"String",
    "State":"String",
    "Id":"Integer",
}
 *
 *
 *
 *
  */


 /*   The line below works perfect locally but i need to work with it remotely and send request data as well, and work with https
     *   HttpGet request = new HttpGet("http://ift.tt/1bwvPtH" + OperationName);
     */


           HttpGet request = new HttpGet("http://ift.tt/1dLNaAA");


            HttpResponse response = httpClient.execute(request);
        HttpEntity responseEntity = response.getEntity();          

        InputStream stream = responseEntity.getContent();    

        reader = new BufferedReader(new InputStreamReader(stream));
        sb = new StringBuilder();

            String line = reader.readLine();

            while (line != null) 
            {
                sb.append(line);
                line = reader.readLine();
            }
        }
        catch (Exception ex) 
        {
            //Procesamos el error
            Log.e(TAG, "Error al crear la actividad. Error: " + ex.getMessage() );
            throw ex;
        }   
        finally 
        {
            reader.close();
        }
        return new JSONArray(sb.toString());        

    }
}

The links of the original example below

NOTE: To make it run switch off all firewalls.

DateTimeZoneHandling.RoundtripKind is not preserved datetime timezone

I have below code:

                JsonReader reader = new JsonTextReader(new    StringReader(content.ToString()));
                reader.DateTimeZoneHandling =            DateTimeZoneHandling.RoundtripKind;
                reader.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                reader.DateParseHandling = DateParseHandling.DateTime;
                 myObj = JObject.Load(reader);

despite using DateTimeZoneHandling.RoundtripKind; still the date converted to local timezone. For example:

   "2015-02-02T12:01:14.548-0500"

changed to :

   "2015-02-02T11:01:14.548-0500",

Json decoding and displaying in php

So i've got a list with local weather details, http://ift.tt/1GXZvLR. And I want to display some of that in formation via php on my site, but can't really find out how JSON is something completely new for me.

And the only thing i managed to do right now is this: http://ift.tt/1cjXtLO. So this is a simple script:

$getData = file_get_contents( "http://ift.tt/1GXZvLR");
 
$decode = json_decode($getData);
 
echo "<pre>";
print_r($decode);

Hopefully someone can help me with this, and explain why certain thing are that way so I don't only know how to copy / paste it but also can do it myself! Sorry for any grammarmistakes but english is not my native! Thanks everybody!

Decode json and foreach Shows key but not value

I cant seem to get the value from the foreach below. I need to basically create a loop where i can then create html buttons based on selections.

I have also added a snippet example only below this text to show what im trying to achieve within the foreach. I just need to work out how to extract the values so i can do that.

I am basically wanting to create a foreach loop that checks how many buttons the user has added and then display each button within the loop with a link in href and a custom button name. I will also have to check of they chose 1,2,3,4 from the showBtn value to determine what type of html to output.

if showBtn==1 { <a herf="btnMenuLink">btnName</a> }

if showBtn==3 { <a herf="btnPhone">btnName</a> }

I have the following code of which i have provided the outputs of the database content and also a var_dump just so you can see how the information is being stored.

The following code does output the key for me but it wont output the values. And i suspect its because my values are an array as well. How on earth would i create a loop within a loop within a loop and still achieve what i explained above?

<?php

$jsonresult =  $column->links;
$array = json_decode($jsonresult,true);

// The databse TEXT field    
/*{
"showBtn":["3","3"],
"btnMenuLink":["101","101"],
"btnArticleLink":["2","2"],
"btnPhone":["036244789","0404256478"],
"btnURL":["",""],
"btnName":["Office","Mobile"]
}*/

// The Var dump $array    
/*  array(6) {
    ["showBtn"] => array(2) {
        [0] => string(1)
        "3" [1] => string(1)
        "3"
    }["btnMenuLink"] => array(2) {
        [0] => string(3)
        "101" [1] => string(3)
        "101"
    }["btnArticleLink"] => array(2) {
        [0] => string(1)
        "2" [1] => string(1)
        "2"
    }["btnPhone"] => array(2) {
        [0] => string(9)
        "036244789" [1] => string(10)
        "0404256478"
    }["btnURL"] => array(2) {
        [0] => string(0)
        "" [1] => string(0)
        ""
    }["btnName"] => array(2) {
        [0] => string(6)
        "Office" [1] => string(6)
        "Mobile"
    }
} */

foreach($array as $key => $value) { ?>    
<?php echo $key;?>:<?php echo $value;?><hr/>    
<?php } ?>

How to write SQL result to JSON

I have this java code that writes the first record of the SQL result set to output in JSON using Google GSON.

But when the result set has more than 1 record it throws exception as "JSON must have only one top-level value"

            HttpServletResponse httpres=response;
            httpres.setContentType("application/json; charset=UTF-8"); 
            httpres.setCharacterEncoding("UTF-8"); 
            JsonWriter writer = new JsonWriter(new OutputStreamWriter(httpres.getOutputStream(), "UTF-8"));
            while(rs.next()) { 
               writer.beginObject();
               // loop rs.getResultSetMetadata columns 
               for(int idx=1; idx<=rsmd.getColumnCount(); idx++) {
                 writer.name(rsmd.getColumnLabel(idx)); // write key:value pairs
                 writer.value(rs.getString(idx));
               } 
               writer.endObject();
            } 
            writer.close(); 
            httpres.getOutputStream().flush();

Add different images to UIImageView of cells in UITableView

Needless to say, i am a novice. I am trying to add images and text to a UITableView. I have been able to add the text but I am having problems with adding different images to the desired text.

I have 2 separate PHP codes for 1 database:

  • The first gets the text and an id for the image assigned to the text (imageID)
  • The second uses the id (from the first PHP) to acquire the image

My code is fine but currently only 1 image is appearing for all the text

My question is how do I assign each image to their text ?

And how do I not assign an image to the text that do not have images as some of the texts don't have images with them?

My code is as follows:

Connection and data download:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // Create an array to store the locations
        NSMutableArray *list = [[NSMutableArray alloc] init];

    // Parse the JSON that came in
    NSError *error;
    jsonArray = [NSJSONSerialization JSONObjectWithData:downloadedData options:NSJSONReadingAllowFragments error:&error];

    // Loop through Json objects, create question objects and add them to our questions array
    for (int i = 0; i < jsonArray.count; i++)
    {
        jsonElement = jsonArray[i];

        // Create a new cell object and set its props to JsonElement properties
        if (![jsonElement [@"Thought"] isEqual:[NSNull null]])
        {
            NSString *listText =jsonElement [@"Thought"];
            if ([listText length] > 0)
            {
                NSString *cellText = jsonElement[@"Thought"];
                [list addObject:cellText];
                NSLog(@"list Cell: %@", cellText);
            }

            if (![jsonElement [@"filename"] isEqual:[NSNull null]])
            {
                imageID = jsonElement[@"id"];
            }
            NSLog(@"Cell Image: %@", imageID);
        }
    }
    [[self tableView1] reloadData];
}

Cells in the table:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleIdentifier = @"SimpleIdentifier";
    cell = [tableView dequeueReusableCellWithIdentifier:simpleIdentifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:simpleIdentifier];
    }

    cell.textLabel.text = [list objectAtIndex:indexPath.row];
    cell.textLabel.font = [UIFont italicSystemFontOfSize:20];

    if ([imageID length] > 0)
    {
        urlStr = [NSString stringWithFormat:@"http://ift.tt/1QgEkJ2", imageID];
        NSURL *imageUrl = [NSURL URLWithString:urlStr];
        NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
        UIImage *imageLoad = [[UIImage alloc] initWithData:imageData];
        cell.imageView.image = imageLoad;
    }

    return cell;
}

Is @JsonTypeResolver the only option for resolving using multiple properties?

I have incoming JSON data in the following format

{
    "header": {
        "schema_id": {
            "namespace": "omh",
            "name": "physical-activity",
        },
    },
    "body": {
        "activity_name": "walking",
        "distance": {
            "value": 1.5,
            "unit": "mi"
        },
    }
}

and corresponding Java classes that looks like

public class DataPoint<T extends Measure> {

    private DataPointHeader header;
    private T body;

and

@JsonNaming(LowerCaseWithUnderscoresStrategy.class)
public class PhysicalActivity extends Measure {

    private String activityName;
    private LengthUnitValue distance;

I'd like Jackson to resolve body to the PhysicalActivity type based on the schema_id in the JSON document, e.g. in pseudocode

if schema_id.namespace == 'omh' && schema_id.name == 'physical-activity'
     then return PhysicalActivity.class

I've tried doing this with @JsonTypeIdResolver but if I try to navigate to header.schema_id.name with @JsonTypeInfo, e.g.

@JsonTypeInfo(use = JsonTypeInfo.Id.CUSTOM,
        include = JsonTypeInfo.As.EXTERNAL_PROPERTY,
        property = "header.schema_id.name")
@JsonTypeIdResolver(DataPointTypeIdResolver.class)
public abstract class Measure {

I get a missing property: 'header.schema_id.name' error. And even if I could, I don't think I can take a decision on both the namespace and name properties.

Is there a sane way to do this besides building from scratch with @JsonTypeResolver?

Rails API - Accessing JSON Message Body

I like to create an API that adds multiple products from the message body. The JSON would look like below:

{"products":[
    {"name":"playstation"}, 
    {"name":"xbox"}, 
    {"name":"bluray"}
]}

The call would go to:

http://localhost:3000/api/v1/products/AddProducts

I'd like to run through .each item within products and do a .create, something like below:

        def AddProducts             
            *each item*.each do |p|
                Product.Create(p)
            end             
        end

My question is - How do I access the JSON being passed into my controller?

Thanks

Create API Class to handle JSON Data Swift

I'm extremely new to handling JSON Data in Swift, and almost just as new to Swift. In a Playground I wrote a whole bunch of code that parsed JSON Data out.

However I realized I don't want to copy and paste this code into every view controller that uses only some of the data. I want to create a custom class that handles the json data.

Here is a bit of my code:

var status: String!
var message: String!
var code: Int!
var dataArray: [NSDictionary]!
var responseCode: String!


var url: NSURL!
var session: NSURLSession!



url = NSURL(string: "http://ift.tt/1zyLZhE")

session = NSURLSession.sharedSession()


let task = session.dataTaskWithURL(url!, completionHandler: { data, response, error -> Void in
if (error != nil) {
    // println(error)

} else {
    let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary




    status = jsonResult["status"] as! String
    message = jsonResult["message"] as! String
    code = jsonResult["code"] as! Int
    dataArray = jsonResult["data"] as! [NSDictionary]


}

})
task.resume()

I then attempted to create a class like this:

class JsonClass {

var status: String!
var message: String!
var code: Int!
var dataArray: [NSDictionary]!
var responseCode: String!


var url: NSURL!
var session: NSURLSession!


init() {
 url = NSURL(string: "http://ift.tt/1zyLZhE")

session = NSURLSession.sharedSession()


let task = session.dataTaskWithURL(url!, completionHandler: { data, response, error -> Void in
if (error != nil) {
    // println(error)

} else {
    let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary




    status = jsonResult["status"] as! String
    message = jsonResult["message"] as! String
    code = jsonResult["code"] as! Int
    dataArray = jsonResult["data"] as! [NSDictionary]


}

})
task.resume()


}

I thought that within a new class I would be able to do something like this:

let jsonAPI = JsonClass()
println(jsonAPI.status)
println(jsonAPI.message)

etc...

However, any attempt to access an instance of the JsonClass results in every JsonClass property having a value of nil.

What are my next steps to accessing this data using instances of this class?

Convert array to json file to graph with flot

First I have no clue what I am doing. I am taking readings from 4 sensors. I get an array like this:

 [{"value":0.162512,"number":0,"channel":0},{"value":0.027835,"number":1,"channel":1},{"value":0.08361,"number":2,"channel":2},{"value":0.295788,"number":3,"channel":3},{"value":0.137746,"number":4,"channel":0},{"value":0.009403,"number":5,"channel":1},{"value":0.089616,"number":6,"channel":2},{"value":0.310242,"number":7,"channel":3},{"value":0.109047,"number":8,"channel":0},{"value":0.005558,"number":9,"channel":1},{"value":0.094369,"number":10,"channel":2},{"value":0.325739,"number":11,"channel":3},{"value":0.087932,"number":12,"channel":0},{"value":0.000298,"number":13,"channel":1},{"value":0.09723,"number":14,"channel":2},{"value":0.336811,"number":15,"channel":3},{"value":0.080258,"number":16,"channel":0},{"value":-0.004426,"number":17,"channel":1},{"value":0.100464,"number":18,"channel":2},{"value":0.338927,"number":19,"channel":3},{"value":0.078663,"number":20,"channel":0},{"value":-0.006318,"number":21,"channel":1},{"value":0.101179,"number":22,"channel":2},{"value":

0.331864,"number":23,"channel":3},{"value":0.084192,"number":24,"channel":0},{"value":0.004098,"number":25,"channel":1},{"value":0.100911,"number":26,"channel":2},{"value":0.326067,"number":27,"channel":3},{"value":0.085652,"number":28,"channel":0},{"value":0.01359,"number":29,"channel":1},{"value":0.105441,"number":30,"channel":2},{"value":0.32407,"number":31,"channel":3}]

How to pass VALID json on the command line to a Node.js application?

I'm attempting to pass, as a single command line argument, some valid JSON to my node application. However, my current attempt is failing because by the time the parameter is passed into my node application, the double quotes have been stripped. This makes the JSON invalid at best, but if there are spaces in any of the property values, it causes serious problems. This example node application will demonstrate the problem:

console.log(process.argv);

Run this with the following command-line arguments:

node test '{"name": "John Doe"}'

The output of this command is this:

[ 'C:\\Program Files\\nodejs\\node.exe',
'C:\\project\\test',
'{name:John',
'Doe}' ]

Is there anyway to prevent the double quotes from being stripped away?

Which library to choose: AngularJS Dynamic Form Generation based on JSON Schema

I am planning to build a generic Web + Desktop + Mobile solution for organizations that heavily do surveys and data collection and generate reports based on collected data (e.g. Non Profits).

The solution needs to be centrally controlled and synced, can work offline and can be used on any device supporting HTML5.

Dynamic Form Generation will be a core functionality for this product. I've been looking for a library that supports generating mobile ready forms. Given AngularJS + Bootstrap are promising in this regard, I came across:

  1. formly-js/angular-formly
  2. Textalk/angular-schema-form

which looked popular on GitHub Explorer and seemed very mature to provide the desired functionality. I need guidelines to which to choose, or should I go for some other solution?

If you have experience working on such a project, what would you suggest me, which technology stack should I use, given the following aspects of the product:

  1. As mentioned the product should run on any HTML5 supported device.
  2. Forms and Data access can be controlled from server/cloud per user.
  3. App should work offline and when finds internet, should sync collected data with server/cloud.
  4. There will be a form designer for Administrators to visually build forms and any newly designed form should instantly get available to data entry devices.
  5. Collected forms data will be used to generate Reports (Publish to Web, Excel, Interactive Charts etc.).

To address Offline behavior, Controlled Access, Syncing and HTML5 support, Sencha Space looks compelling, any thoughts?

JavaScript: Deep Copy Circular JSON

intro:

I'm trying to write a deep copy method, but need to keep track of my visited nodes, so that I can link to the previously visitedNode instead of deep copying forever until stack overflow.

attempts:

var visitedNodes = {};
var obj = {}; obj.a = obj;   // circular; can't use JSON.stringify)
var obj2 = {};

visitedNodes[obj] = "should need key obj (not obj2) to access this string";

console.log(visitedNodes[obj2]);    // logs the string unfortunately

I don't have a unique way of storing the memory location -- it stores itself at [object Object] and I can't use JSON.stringify because it's a circular structure


I tried using var visitedNodes = new Map(); but still no dice


My current approach is to utilize the Array.prototype.indexOf function, but I don't know if it works with circular structures either, because I'm getting a stack overflow here too!!!

this.clone = function (item, visitedNodes) {
    visitedNodes = visitedNodes || [];
    if (typeof item === "object" && !Array.isArray(item)) {
        if (visitedNodes.indexOf(item) === -1) {
            var cloneObject = {};
            visitedNodes.push(cloneObject);
            for (var i in item) {
                if (item.hasOwnProperty(i)) {
                    cloneObject[i] = this.clone(item[i], visitedNodes);
                }
            }
            return cloneObject;
        } else {
            return visitedNodes[visitedNodes.indexOf(item)];
        }
    }
    else if (typeof item === "object" && Array.isArray(item)) {
        if (visitedNodes.indexOf(item) === -1) {
            var cloneArray = [];
            visitedNodes.push(cloneArray);
            for (var j = 0; j < item.length; j++) {
                cloneArray.push(this.clone(item[j], visitedNodes));
            }
            return cloneArray;
        } else {
            return visitedNodes[visitedNodes.indexOf(item)];
        }
    }

    return item; // not object, not array, therefore primitive
};


the question:

Anyone have any ideas for getting a unique memory address so I can determine if I've been to the Object's reference before? I believe I could construct a unique hash based off Object.keys() and Object.prototype.constructor but that seems absurd and will give false positives if constructor is the same and the child keys are the same as the parent

Dynamic content compression does not work with IE9

I have an api page written with c# and it provides json output for my angular JS front-end page.

I recently turned on dynamic content compression on IIS7 to reduce the amount of data needs to be transferred to browser and to increase speed of api.

The angular page still work with with modern browsers, but IE9 does not work.

I tried to add Content-Encoding:gzip header manually into my api page but then it does not work with any browsers.

Any suggestions?

Shell Script CURL JSON value to variable

I was wondering how to parse the CURL JSON output from the server into variables.

Currently, I have -

curl -X POST -H "Content: agent-type: application/x-www-form-urlencoded" http://ift.tt/1JOP3tE -d username="$USERNAME" -d password="$PASSWORD" | python -m json.tool

But it only outputs the JSON from the server and then have it parsed, like so:

{
    "eta": "0",
    "position": "0",
    "queueToken": "6bee9e85-343f-41c7-a4d3-156f901da615",
    "success": "delayed"
}

But how do I put - for example the success value above returned from the server into a variable $SUCCESS and have the value as delayed & have queueToken as a variable $queueToken and 6bee9e85-343f-41c7-a4d3-156f901da615 as a value?



Then when I use-

echo "$SUCCESS"

it shows this as the output -

delayed



And when I use

echo "$queueToken"

and the output as

6bee9e85-343f-41c7-a4d3-156f901da615

Thanks!

Can't parsing JSON with SwiftyJson

Everytime I get a breakpoint! What is the problem with my code? I've tried it so many times, but it never worked!

    override func viewDidLoad() {
    super.viewDidLoad()

    let url = NSURL(string: "http://ift.tt/1Pneocm")
    let request = NSData(contentsOfURL: url!)


    let json = JSON(data: request!)
    if let firstname = json["first_name"].string{

    println(firstname)
    //nameLabel.text = firstname
    }

Align json field names in Webstorm

How can I align the JSON file as below in Webstorm? What option can I put. I cannot seem to find it.

{
  "Hero": {
    "id"       : "11111111111111111",
    "firstName": "John",
    "lastName" : "Smith",
    "title"    : "MR"
  }
}

How do I deal with transfer-Encoding chunked json using Sprint RestTemplate

I posted this the error below a few days ago and there were several responses. One suggested that the error comes up when the response is transfer-Encoding type chunked. What do I do to either tell the server not to chunk or fix my end so that ReadTemplate will work properly. And, BTW, I reading from WeatherUndergound's the REST service, if that's useful to know.

Could not extract response: no suitable HttpMessageConverter found for
response type [net.cheshiresgrin.currentConditions.Display] and
content type [application/json;charset=UTF-8]   

Remove a square bracket and receiving JSON properly in nodejs/websocket enviroment?

At the moment I can only output data of a specific key (index) with console.log(auction[index].id); but I need the data using console.log(auction.id);. How do I accomplish this?

I'm using nodejs and my WebSocket receives data just like this:

42["stream",{"streamArray":[[{"id":20,"pid":2,"nr":4,"price":5.73,"pe":506.08,"duration":14,"hb":361262},{"id":23,"pid":17,"nr":4,"price":5.59,"pe":189.13,"duration":7,"hb":null},{"id":12,"pid":8,"nr":3,"price":5.59,"pe":90.23,"duration":7,"hb":null}]]}]

So it's a multidimensional array. And I think there's one square bracket too much? (Right before {"id":20 for example)

This way I receive the data client-side:

var socket = io.connect('http://localhost:8000/',{'forceNew':true });
socket.on('stream', function (data) {
$.each(data.streamArray,function(index,auction){    

Do I have to change the code before the data is even sent to my WebSocket or can I solve this issue client-side to receive the correct data in my variable auction? How could I solve this?

How to access Nested JSON Data via Index, Angular JS, ng-click?

I have a List of cars assigned to a person for a particular month. If you search April you will get April data. How do I access Nested JSON data via Index?

Here's plunker

   $scope.cars = $scope.results[resultIndex].cars.map(function(car) {
          return {
        make: car.Make,
            year: car.Year
          };
        });

   $scope.showCars = function(resultIndex) {
      $scope.cars = $scope.results[resultIndex].cars;
    };

I can't pass a raw body without receiving a null response

I've just finished following this tutorial: http://ift.tt/1ACZDLU

And I'm trying to accomplish the trivial task of sending an abstract/raw request body without the stupid/useless middle layer in ASP.NET trying to interpret the body contents as a pre-defined class I've already created.

Here's my super simple code ASP.NET seems to %$#& up:

[HttpPost]
[Route("test")]
public string test([FromBody] string json)
{
    return json;
}

Which would lead you to think that POSTing to this URI with the following body: "trouble shooting fun" OR "{"info":"troubleshooting fun"}"

would simply result in this response:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 4

{"info":"troubleshooting fun"}

This is the kind of response you'd expect from all the other web frameworks like Django or Ruby-o-Rails because it just makes sense, but in ASP.NET Web API there is an additional layer working behind the scenes that forces you to create the request and response objects manually by declaring them as local classes like so:

public class hardCodedRequestJson
{
    public string keyValuePair { get; set; }
}

So... ummm this is kind of cool, if you want some useless backwards compatibility with XML but this approach comes at the cost of being stuck with extremely specific parameters for each API call, for my situation I'd have to make hundreds of different combinations of classes and functions that account for the dynamic number of possibilities the client must have when making an API call to the server.

How could I feed any kind of JSON object I wanted into an ASP.NET Web API controller and get that EXACT json I requested back as a response??