mercredi 22 avril 2015

POST using jersey not converting JSON to JAXBObject in REST service

I am writing a POST rest API service , and my service class is

@POST
@Path("/create")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response produceJSON(Student student) {


    System.out.println("===============" + student.getFirstName());

    return Response.ok().build();
}

I am using DEV HTTP Client and sending XML request with complete student object and it is working fine. But when I am sending JSON request with student object , it provides me a student object with all null values. student.getFirstName() is coming as null , though I am setting this value. Any solutions ?

Bing translator API for android can give more than 1 result?

I'm making a Translator for Thai to English, one Thai word can translate to many words in English,so can I do that in my app?

I just research about example for this api but cant find solution.

I found it use a array of string to get results but this method just use for sentence translate

How can I authorize API access with just a Phone number and SMS Pin?

I'm creating a backend that has a REST API that will be consumed from an mobile app. Because the app is mobile only we're not using an email and password to create account/login but instead a phone number and then they receive a pin number with an SMS message to confirm they own the number.

After I confirm the user is who they say they are with the pin number, how should I go about authenticating future API requests?

My first thought was to create a token and return it to the app. My second thought was to use OAuth but then i'm getting confused as to which method would work with the Phone number/SMS login method (2/3 leg, grants, etc..). I don't fully understand how this might work when using OAuth with our own apps (as opposed to OAuth with another provider). The token seems like the easier route.

If I use the token, is it bad to use the same token until the user is logged out? (over https). I'm assuming it's worth the extra work to make them expire a little longer than the avg. user session.

Unfortunately it doesn't seem to be a turn key solution that works with phone numbers. I'm using Meteor but am expecting to roll my own with Node modules (by exposing connect on the Meteor server).

Any help is greatly appreciated!

Get expired domains API

I have been searching high and low for a reliable (semi) accurate API to integrate with for checking expired domains and their availability. I've seen domainsbot and domainr and a couple others, but they are a little outdated in regards to reliability.

Anyone have any suggestions in regards to where I could find an API to access?

How to get list of softlayer's operatingSystemReferenceCode?

I am using softlayer api using the Java implementation to create multiple VMs from different locations with different operating systems.

But I need a way to know the list of available operatingSystemReferenceCode and Datacenter code.

Track likes on my photos with instagram API

I would like to track the number of likes on photos that I post to instagram via the python-instagram module using the instagram API.

how do i fix nexmo text messages with + sign

i have this text message: Im using Laravel 4.2.

Im using Nexmo API Library Made for Laravel:

http://ift.tt/1Je6Ee4

PHP:

    $from = "MyCompany";
    $to   = "09096448797";
    $text = "Confirmation Code: 55555";

    Nexmo::getBalance();
    Nexmo::prices();
    Nexmo::sendSMS($from, $to, $text);

When i received message, i get this:

Confirmation+Code%30A+55555[NEXMO DEMO]

Somehow its replacing the special characters. spaces, semi colon.

Trying to describe the request and response using Data Structures in API Blueprint

I'm trying to document an endpoint with API Blueprint, using the new Attributes and DataStructures sections of the spec.

My request payload looks like this:

{
    "url": "http://ift.tt/1HnbCEX",
    "active": true,
    "types": [
        {
            "name": "sales",
            "version": "2.0"
        },
        {
            "name": "products",
            "version": "2.0"
        }
    ]
}

My response payload looks something like that:

{
  "data": {
    "id": "dc85058a-a683-11e4-ef46-e9431a15be8c",
    "url": "http://ift.tt/1HnbCEX",
    "active": true,
    "types": [
      {
        "name": "products",
        "version": "2.0"
      },
      {
        "name": "sales",
        "version": "2.0"
      }
    ]
  }
}

I tried the following API Blueprint markdown:

FORMAT: 1A

# Vend REST API 2.0

# Group Webhooks

## api/2.0/webhooks [/webhooks]

### List all Webhooks [GET]
Returns a list of Webhooks created by the authorised application.

+ Response 200 (application/json)
    + Attributes (Webhook Collection)

### Add a new Webhook [POST]
Creates a new Webhook.

+ Attributes (Webhook Base)

+ Request (application/json)
    + Attributes (Webhook Base)

+ Response 200 (application/json)
    + Attributes (Webhook Response)

# Data Structures

## Webhook Base (object)
+ url: http://ift.tt/1DPB4io (string, required) - The address where webhooks requests should be submitted.
+ active: true (boolean, required) - This field can be used to inspect or edit state of the webhook.
+ types: array[Webhook Type] (array[Webhook Type], required) - Collection of Webhook types which should trigger Webhook event.

## Webhook Response Base (Webhook Base)
+ id: dc85058a-a683-11e4-ef46-e8b98f1a7ae4 (string, required) - Webhook `id`.

## Webhook Response (object)
+ data: webhook (Webhook Response Base, required)

## Webhook Type (object)
+ name: sales (string, required) - One of: products, sales, customers, taxes
+ version: 2.0 (string, required) - Version of the payload to be delivered. Currently the only supported value is "2.0".

## Webhook Collection (object)
+ data: array[Webhook Response Base] (array[Webhook Response Base], required) - An array of Webhook objects.

Now, when looking at it in Apiary, it tells me that this is a valid API Blueprint document, but it doesn't how me JSON previews for the request and response. Are structures like this even possible to represent in API Blueprint and able to render nicely in Apiary?

PHP Curl not posting data, although it is recieving

I'm trying to make an api through php curl and my client side (form submission) is receiving data from the api... it is just not posting it to the api..

 $ch = curl_init($url); 
curl_setopt($ch, CURLOPT_HEADER, false); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type= application/json"));
curl_setopt($ch, CURLOPT_POST, true);

// execute the request and store the return value.
$message = curl_exec($ch);

echo 'Message returned from API is:' .  $message; 

This is the code to receive the message from the API... it is returning a message so hopefully no errors there.

This is the api code (below):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://ift.tt/kkyg93">
<html xmlns="http://ift.tt/lH0Osb">

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>The API</title>
</head>

<body>
<?php

//date, job number, customer, worksite, duties performed, total hours spent, type of hours

$date = $_POST['date'];
$jobnumber = $_POST['jobnumber'];
$customer = $_POST['customer'];
$worksite = $_POST['worksite'];
$duties = $_POST['duties'];
$hours = $_POST['hours'];
$hourtype = $_POST['hourtype'];
$username = $_POST['username'];



$ok = true;
$error ;

//validate the inputs
if (empty($date)) {
    $ok = false;
    $error .= "Date field empty, ";
}

if (empty($jobnumber)) {
    $ok = false;
    $error .= "Job Number field empty, ";
}
if (empty($customer)) {
    $ok = false;
    $error .= "Customer field empty, ";
}

if (empty($worksite)) {
    $ok = false;
    $error .= "Worksite field empty, ";
}
if (empty($duties)) {
    $ok = false;
    $error .= "Duties field empty, ";
}
if (empty($hours)) {
    $ok = false;
    $error .= "Hours field empty, ";
}

if (empty($hourtype)) {
    $ok = false;
    $error .= "Hour type not specified, ";
}

$data = $date . ', ' . $jobnumber . ', ' . $customer . ', ' . $worksite . ', ' . $duties . ', ' . $hours . ', ' . $hourtype;
echo $data;
?>
</body>

</html>

My submit page is returning "Message returned from API is: , , , , , ,"

For the life of me I can't find what I'm doing wrong and I could really use a second set of eyes, and a second brain... lol..

Thanks everyone!

Pull Weather API Data Using JSON and append to li's?

I am having trouble figuring out how to pull OpenWeatherMap API data and append it to corresponding li's in my html. Thanks for your help, I am stuck right now with the following code:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Project 21</title>
  <style>
    html {margin:2em; font-size:2em; font-family:Helvetica, Arial, sans-serif;}
    h1 {margin:0 0 0.2em; color:#369;}
    img {float:left; margin-right:1em;}
    ul {float:left; margin:0; padding:0; list-style:none;}
  </style>
  <script src="http://ift.tt/1vhyxae"></script>
</head>
<body>
  <section>
    <h1>Current Weather for </h1>
    <div class="img" id="data-img"></div>
    <ul>
      <li><b>Conditions:</b> <span id="data-current"></span></li>
      <li><b>Temperature:</b> <span id="data-temp"></span>&deg;</li>
      <li><b>Humidity:</b> <span id="data-humidity"></span>%</li>
      <li><b>Wind Speed:</b> <span id="data-wind"></span>mph</li>
    </ul>
  </section>
  <script>
  $.getJSON('http://ift.tt/1HWltQY?',
  { 'zip': '46556,us', 'units':'imperial' },
    function(data){
      console.log(data);
  })
  .fail(function(jqxhr, textStatus, error) {
    console.log("Request Failed"+ textStatus + "," + error);
  });



  </script>
</body>
</html>

Searching with a defined query in Django / Python

Currently as it stands I have a search bar and a button on my homepage like so.

<div class="input-group">
<input id="address" type="textbox" placeholder="City or Zipcode" class="form-control">
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="addressSearch">Search</button>
</span>
</div>

I have created a api.py file which is within my websites folder which looks like so.

import urllib2
import json

locu_api = '17501ab24118c5cd0981b6070543d972cb2052d1'

def loc_search(query):
    api_key = locu_api
    url = 'http://ift.tt/1wKWOKF' + api_key
    locality = query.replace(' ', '%20')
    final_url = url + "&locality=" + locality + "&category=restaurant"
    json_obj = urllib2.urlopen(final_url)
    data = json.load(json_obj)

    for item in data['objects']:
        print item['name']
        print item['phone']

Essentially what I am trying to do is when the user search's for a city e.g. New York then the loc_search(query) is called populating the search field '(query)' with the users input and the data then being displayed.

I haven't much experience with either django or api's so any help would be invaluable. Thanks again

Yammer API Groups/Users in Group only being returned for 1 network

My goal is to get a count of users in each group returned from the Yammer Data Export API. The list of groups that is returned from the data export api belong to roughly 15 networks. When querying the endpoints listed below, I am getting results back for the 1 main network, but not for the other 14. Are there any known limitations for the REST API in regards to accessing data for some of the networks returned from the data export API. In other words, there is information provided in the data export API, but when trying to expand on that information using the REST API, nothing is returned.

http://ift.tt/1bjUjqj{group_id}.json

http://ift.tt/1yRoT5u{group_id}.json

Any help would be much appreciated.

Apps, Apis, and Authentication - JWT architecture pattern

My noob questions is based on...I would like to build an app where a user may want to import bulk content from another app...maybe a json hash containing 5000 [rows of] image descriptions.

My question is...in order to let the 3rd-party app POST to my app...how do I establish the connections between the apps and with the correct user context?

I am not sure how to "give" a token/auth to their app to make the REST call. I have played on localhost just fine with CURL and nodejs POSTing to my endpoint...but can you help me clarify the next "real world" steps for hooking apps together. I have a looked a little at Oauth, JWTs, starting to look at Zapier.

Thank you.

How to cache third party API access in SQL database for a WordPress plugin

Is there any way to cache data for a WordPress plugin ? I have a ready one that uses third party API access to YouTube API V3 and I need to apply cache for both optimization and keeping the hits under the quota.

Supposing I have this function:

function popular_uploads() {
        $url = 'http://ift.tt/1DCimYg'. channel_id(). '&maxResults=5&key={key}&type=video';
        $json = file_get_contents($url);
        $json_data = json_decode($json, false);
        foreach ( $json_data->items as $item ) {
            $id = $item->id->videoId;
            echo '<iframe id="ytplayer" type="text/html" width="auto" height="auto" 
                src="//www.youtube.com/embed/' . $id . '?rel=0&showinfo=1"
                frameborder="0" allowfullscreen></iframe>';
        }
}

How am I going to cache the data for sometime in a database ? I am really new to this process and I have looked it up and couldn't find a fix.

Thank you so much for assisting a beginner!

Regards.

QuickBooksOnline SDK updates all fiels instead of one

I use intuit.ipp sdk to update inventory in quickbooks acocunt. I want update one field qty on hand, but after update item's 'price','cost','Description on sales forms','Description on purchase forms' are 0 or empty string. Why quick books online updates them? My Code:

                batch.Add( new Item()
                {
                    Name = item.Sku,
                    Id = item.Id,
                    SyncToken = item.SyncToken,
                    QtyOnHand = item.QtyOnHand,
                    QtyOnHandSpecified = true,
                    UnitPriceSpecified = false,
                    PurchaseCostSpecified = false,
                    AvgCostSpecified = false,
                    ExpenseAccountRef = new ReferenceType { Value = item.ExpenseAccRefValue, name = item.ExpenseAccRefName, type = item.ExpenseAccRefType },
                    IncomeAccountRef = new ReferenceType { Value = item.IncomeAccRefValue, name = item.IncomeAccRefName, type = item.IncomeAccRefType }
                }, item.Id, OperationEnum.update );

            batch.Execute();

API Management Active-Active Clustering – Gateway

Based on my understanding, currently WSO2 API Management supports Gateway clustering in a Active-Passive mode. Is it possible to have API Management Gateway clustering set-up in an active-active mode whereby API requests are distributed across multiple clustering nodes simultaneously? In such a distributed scenario, we would like to ensure that API throttling quota is equally fulfilled (50% each for two nodes cluster) across multiple nodes in the cluster. Also, if a node goes down, how will the API requests quota be adjusted? Thanks.

  • Deepak

How to split a list of defect results from an ArrayList

Hello I am having trouble in splitting the information(severity, summary etc) I get for different components(General, Code Quality etc) in mozilla rest api. When I am calling to get information for a certain component. I get all of it in a single list. What I would like to do is separate the bugs and have each of them in an array. How would I do that? Here is my code for now

package bla_bla;

import java.io.IOException;
import java.util.ArrayList;
import java.util.*;
import javax.swing.text.html.parser.Element;

    import org.codehaus.jackson.map.ObjectMapper;
    import org.jsoup.Jsoup;
    import org.jsoup.nodes.Document;
    import org.jsoup.select.Elements;
    import org.jsoup.select.Evaluator.Id;
    import org.json.*;

    import argo.saj.InvalidSyntaxException;

    public class supermonkey {

    private static ArrayList<BugsList> bugsList;    
    private static ArrayList<BugsList> bugbug;  


    public static void main(String args[]) throws IOException {

        bugsList = new ArrayList<BugsList>();
        bugbug = new ArrayList<BugsList>();
        Document doc = Jsoup.connect("http://ift.tt/1Ht3Tna").get();
        String rawData = doc.body().text();
    //  System.out.println(title);
        JSONObject obj = new JSONObject(rawData);

    //  System.out.println(obj);

        System.out.println(obj.get("bugs"));

        JSONArray jsonMainArr = new JSONArray(obj.get("bugs").toString());
        for (int i = 0; i < jsonMainArr.length(); i++) {  // **line 2**
             JSONObject childJSONObject = jsonMainArr.getJSONObject(i);
             JSONObject assigned = childJSONObject.getJSONObject("assigned_to_detail");
          //   JSONObject assigned2 = childJSONObject.getJSONObject("assigned_to_detail");


             int id = assigned.getInt("id");
             BugsList bug = new BugsList();
             BugsList bug2 = new BugsList();
             bug.setId(id);



             String severity = childJSONObject.getString("severity");
             String resolution = childJSONObject.getString("resolution");
             String summary = childJSONObject.getString("summary");
             String component = childJSONObject.getString("component");
             bug.setSeverity(severity);
             bug.setResolution(resolution);
             bug.setSummary(summary);
             bug.setComponent(component);
             bugsList.add(bug);

             // String severity = assigned.getString();
    //       System.out.println("sss  "+ assigned);

        }



        getComponent("Code Quality");
    //  getSeverity(524276);
    //  getResolution(524276);
    //  getSummary(524276);
    }
       public static void getSeverity(int id){
           for(int i =0;i<bugsList.size(); i++){
               if(bugsList.get(i).getId() == id){
                   System.out.println("The id exists in the list " + bugsList.get(i).getSeverity());
               }
           }
       } 

       public static void getResolution(int id){
           for(int i =0;i<bugsList.size(); i++){
               if(bugsList.get(i).getId() == id){
                   System.out.println("The id exists in the list and The resolution is" + bugsList.get(i).getResolution());
               }
           }
       }  

       public static void getSummary(int id){
           for(int i =0;i<bugsList.size(); i++){
               if(bugsList.get(i).getId() == id){
    System.out.println("The comp.. exists in the list and The summary is   " + bugsList.get(i).getSummary());
               }
           }
       }
        // Current used method
       public static ArrayList<BugsList> getComponent(String component){
           for(int i =0;i<bugsList.size(); i++){
               if(bugsList.get(i).getComponent().equals(component)){
                   System.out.println("(Code Quality) component contains summary  " + bugsList.get(i).getSummary() +" /The resolution is " +                 
    bugsList.get(i).getResolution() + "  /Severity is " + bugsList.get(i).getSeverity());
                   bugbug.add(bugsList.get(i));
               }
           }
           return bugbug;
       }   


    }

How can I Allow my Chrome App to access external Api

I'm fresh out of college and trying new things. I'm attempting to make a chrome app and want to use:

<script src="http://ift.tt/OJL5Z7"></script>

When I try to run it I get this error:

Refused to load the script 'http://ift.tt/OJL5Z7' because it violates the following Content Security Policy directive: "default-src 'self' chrome-extension-resource:". Note that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.

I read up on CSP and the like but I cant seem to get it to work. Any help would be super amazing!

CRM javascript button calls json url and parse a value

I am creating a button in javascript (I can't create it using HTML - system limitation) and I want this button to go to a certain url (REST - getting JSON file). Afterwards, I'd like to display an alert with the value from that file and/or save the value from JSON file on a page where the button is placed. So far, I figured how to call the REST URI. Could anyone help me move forward with that?

<script>
oraclecrmod.onReady(function() {
if(oraclecrmod.ctx.isObject("Account") && oraclecrmod.ctx.isDetailPage()) {

var on_click = function URL() {
location.href = 'http://ift.tt/1QkKeK6';
    alert(data.accounts);
}


var tb = oraclecrmod.getTitleBar("AccountFormTB");
var bt = oraclecrmod.createButton({
id:"TestBtn",
text:"Test Read",
parent:tb
});
bt.on("click",on_click);
}
});
</script>

Best regards, Lukasz

Google Geocode API deny the request - NodeJS

I want a geocode a street address in NodeJS, but the the google API deny the request, because of the IP address. I have dedicated IP address on my server, I generated API key used this IP address. My request looks like this:

https.get('http://ift.tt/1DSDD4t', function(response){...........});

I registered my currently public IP address of my computer just for to try the API and if I send a request from my computer it is working fine.

I found the following instruction on google developer site:"Every API request is generated by software running on a machine that you control. Per-user limits will be enforced using the address found in each request's userIp parameter, (if specified). If the userIp parameter is missing, your machine's IP address will be used instead."

Does it mean that I can add userIp parameter like this?:

https.get('http://ift.tt/1CXTLOd', function(response){...........});

I tried this on as well, but still not working. Has anyone an idea what I doing wrong?

How to loop through the json onject returned by $.getJSON() method in JavaScript

I am new to JavaScript and JQuery. I am trying to get weather data using the Openweathermap API. I am trying to loop through the object returned by the $.getJSON() method using Openweathermap API.

html code:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Weather Application</title>
    <script src="http://ift.tt/1fJwIAs"></script>
    <link href="http://ift.tt/1f1Mm3V" rel="stylesheet">
        <script src="assets/js/script.js"></script>
   </head>

<body>
<header>
    <h1>Weather Forecast</h1>
</header>


<p id="location"></p>

<p id="json"></p>

<!--<form id="search-form">-->
    <!--<fieldset>-->
        <!--<input type="textbox" id="search" name="search" align="right" />-->
        <!--<button id="search-submit" align="right" value="Go" />-->
    <!--</fieldset>-->
<!--</form>-->

<div style="padding:16px;">
    Enter the name of  city : <input id="c1"type="text" value="Carbondale"/>
    <button id="button1" >Go</button>
</div>



<div>
   <p id="result"></p>
</div>

<div>
    <h1>Forecast Data</h1>
    Enter the name of  city : <input id="c2" type="text" value="....."/>
             Number of Days : <input id="days" type="text" value="1"/>
    <button id="button2">Go</button>

    <p id="forecast"></p>

</div>
</body>
</html>

Corresponding JavaScript Code:

$(document).ready(function ()
{
$("#button2").click(function () {
        var search_City2 = $("#c2").val();
        var days = $("#days").val();

        var count = Number(days);

        var search_url2 =  "http://ift.tt/1o8YE0w"+search_City2+
        "&mode=json&units=metric&cnt="+days;

        $("#forecast").html(search_City2 + " "+count+" "+search_url2+"</br>");
        //document.getElementById("location").innerHTML = city+ " "+url;
        var mydate = new Date();


            $.getJSON(search_url2, function (result) {
                $.each(result,function(i,field){
                    $("#forecast").append(JSON.stringfy(field));
                });

                //for(i =0;i<count;i++) {
                    //$("#forecast").append("</br><b>" + i + " " + count +" " + " </b>");
                    //$("#forecast").append("</br>Temperature at Day :" + result.list[5].temp.day);
                   // $("#forecast").append("</br>Temperature at Morning :" + result.list[i].temp.morn);
                   // $("#forecast").append("</br>Temperature at Evening :" + result.list[i].temp.eve);
                   // $("#forecast").append("</br>Temperature at Night :" + result.list[i].temp.night);
                   // $("#forecast").append("</br>Max Temperature:" + result.list[i].temp.max);
                    //$("#forecast").append("</br>Min Temperature:" + result.list[i].temp.min);
                    //$("#forecast").append("</br>Humidity: " + result.list[i].humidity + "%");
                   // $("#forecast").append("</br>Weather Condition : " + result.list[i].weather[i].description);
                    //$("#forecast").append("</p></div>");
                    // $("#forecast").append("</br>Temperature :" + result.list[1].temp.day);
                    // $("#result").append("</br>Humidity :"+ result.list[0].main.humidity);
                    // $("#result").append("</br>Weather Condition :"+result.list[0].weather[0].description) ;
                //}
            });
    });
});

I have tried with both for-loop and each function. But still it is not working. What am I doing wrong here ?

How to get the current free disk space in Postgres?

I need to be sure that I have at least 1Gb of free disk space before start doing some work in my database. I'm looking for something like this:

select pg_get_free_disk_space();

Is it possible? (I found nothing about it in docs).

PG: 9.3 & OS: Linux/Windows

How to Integrate bulk sms api to andorid application

What is the exact step by step procedure to integrate a Bulk SMS api with my android application.

I have a android app, in which i have a list of employes names, if i mark "No" to any employe, the bulk sms api should send sms only to the employees mobile numbers (saved in mysql table), on click on submit button in android app.

How to integrate the api provided by the bulk sms privider ? How to intergated it to the submit button in particular.

API Directory Migration

I have an application that used the old API on .NET. Would need an example to the new directory with C # APIs groups and contacts. Now check the documentation of google and insufficient .. Could help even at logging in to the application of contacts and groups?

Tengo una aplicación que utilizaba las viejas API realizada en .NET. Necesitaria un ejemplo con las nuevas APIS directory con C# de grupos y contactos. Ya revise la documentacion de google y es insuficiente.. Podrian ayudarme aunque sea a loguear en la aplicación de contactos y grupos ?

GetEmbeddedSignerView badrequest docusing api

I am trying to call the emmbeddedSignerView method from the docusign nuget package but the response fails to return a url. I ended up copying the unit test code

// create a new envelope with 2 recipients            
        var envelope = new Envelope { Login = account };
        byte[] doc1 = { 36, 45, 34, 67, 121, 87, 99, 32, 32, 32, 54, 54, 55, 56, 32 };
        var signers = new List<Signer>();
        // note we need to specify clientUserId
        signers.Add(new Signer { email = "unitests1@testing.com", name = "test1", recipientId = "1", routingOrder = "1", clientUserId = "1" });
        //signers.Add(new Signer { email = "unitests2@testing.com", name = "test2", recipientId = "2", routingOrder = "2", clientUserId = "2" });
        envelope.Recipients = new Recipients { signers = signers.ToArray() };
        envelope.Create(doc1, "test-self-signed.doc");

        // send it
        envelope.Status = "sent";
        envelope.UpdateStatus();

        // get embedded signing views for 2 recipients
        string urlForfirstSigner = envelope.GetEmbeddedSignerView("www.docusign.com", signers.First());

When I debug I can see that the response status code is "BadRequest" with the response text "RECIPIENT_NOT_IN_SEQUENCE\",\r\n \"message\": \"The token for an out of sequence recipient cannot be generated."

Am I doing something wrong? I figured since I copied the code it should work...

I am using the nuget package so I copied the object data of my create and embedded signing requests and responses hopefully this will help.

REQUEST
{System.Net.HttpWebRequest}
    base: {System.Net.HttpWebRequest}
    Accept: null
    Address: {http://ift.tt/1OEsC8u}
    AllowAutoRedirect: true
    AllowReadStreamBuffering: false
    AllowWriteStreamBuffering: true
    AutomaticDecompression: None
    ClientCertificates: {System.Security.Cryptography.X509Certificates.X509CertificateCollection}
    Connection: null
    ConnectionGroupName: null
    ContentLength: 512
    ContentType: "multipart/form-data; boundary=00000000-0000-0000-0000-000000000000"
    ContinueDelegate: null
    ContinueTimeout: 350
    CookieContainer: null
    Credentials: null
    Date: {1/1/0001 12:00:00 AM}
    Expect: null
    HaveResponse: false
    Headers: {X-DocuSign-Authentication: <DocuSignCredentials><Username>qfroth@gmail.com</Username><Password>MYPASSWORD</Password><IntegratorKey>MYINTEGRATORKEY</IntegratorKey></DocuSignCredentials>
Content-Type: multipart/form-data; boundary=00000000-0000-0000-0000-000000000000
Host: demo.docusign.net

}
    Host: "demo.docusign.net"
    IfModifiedSince: {1/1/0001 12:00:00 AM}
    KeepAlive: true
    MaximumAutomaticRedirections: 50
    MaximumResponseHeadersLength: 64
    MediaType: null
    Method: "POST"
    Pipelined: true
    PreAuthenticate: false
    ProtocolVersion: {1.1}
    Proxy: null
    ReadWriteTimeout: 300000
    Referer: null
    RequestUri: {http://ift.tt/1OEsC8u}
    SendChunked: false
    ServerCertificateValidationCallback: null
    ServicePoint: {System.Net.ServicePoint}
    SupportsCookieContainer: true
    Timeout: 100000
    TransferEncoding: null
    UnsafeAuthenticatedConnectionSharing: false
    UseDefaultCredentials: false
    UserAgent: null



RESPONSE

{DocuSign.Integrations.Client.ResponseInfo}
    ContentType: "application/json; charset=utf-8"
    ErrorMessage: ""
    ResponseBytes: {byte[198]}
    ResponseStream: {System.Net.ConnectStream}
    ResponseText: "{\r\n  \"envelopeId\": \"b3c02285-f787-49b4-951d-53bb4057023e\",\r\n  \"uri\": \"/envelopes/b3c02285-f787-49b4-951d-53bb4057023e\",\r\n  \"statusDateTime\": \"2015-04-22T04:26:41.7770000Z\",\r\n  \"status\": \"created\"\r\n}"
    StatusCode: Created


REQUEST
{System.Net.HttpWebRequest}
    base: {System.Net.HttpWebRequest}
    Accept: "application/json"
    Address: {http://ift.tt/1HiK0Rj}
    AllowAutoRedirect: true
    AllowReadStreamBuffering: false
    AllowWriteStreamBuffering: true
    AutomaticDecompression: None
    ClientCertificates: {System.Security.Cryptography.X509Certificates.X509CertificateCollection}
    Connection: null
    ConnectionGroupName: null
    ContentLength: 133
    ContentType: "application/json"
    ContinueDelegate: null
    ContinueTimeout: 350
    CookieContainer: null
    Credentials: null
    Date: {1/1/0001 12:00:00 AM}
    Expect: null
    HaveResponse: false
    Headers: {Accept: application/json
Content-Type: application/json
X-DocuSign-Authentication: <DocuSignCredentials><Username>qfroth@gmail.com</Username><Password>MYPASSWORD</Password><IntegratorKey>MYINTEGRATORKEY</IntegratorKey></DocuSignCredentials>
Host: demo.docusign.net

}
    Host: "demo.docusign.net"
    IfModifiedSince: {1/1/0001 12:00:00 AM}
    KeepAlive: true
    MaximumAutomaticRedirections: 50
    MaximumResponseHeadersLength: 64
    MediaType: null
    Method: "POST"
    Pipelined: true
    PreAuthenticate: false
    ProtocolVersion: {1.1}
    Proxy: null
    ReadWriteTimeout: 300000
    Referer: null
    RequestUri: {http://ift.tt/1HiK0Rj}
    SendChunked: false
    ServerCertificateValidationCallback: null
    ServicePoint: {System.Net.ServicePoint}
    SupportsCookieContainer: true
    Timeout: 100000
    TransferEncoding: null
    UnsafeAuthenticatedConnectionSharing: false
    UseDefaultCredentials: false
    UserAgent: null

RESPONSE
{DocuSign.Integrations.Client.ResponseInfo}
    ContentType: "application/json; charset=utf-8"
    ErrorMessage: "Bad Request"
    ResponseBytes: null
    ResponseStream: null
    ResponseText: "{\r\n  \"errorCode\": \"RECIPIENT_NOT_IN_SEQUENCE\",\r\n  \"message\": \"The token for an out of sequence recipient cannot be generated.\"\r\n}"
    StatusCode: BadRequest

Connecting eBay API with oAuth 2.0

I waited around 2 months for eBay to enable oAuth 2.0 for my developer account, but now when the user clicks "I Agree" to complete the oAuth process, they are redirected to the success url specified in my runame, but no code query parameter is present. In fact, there are no query parameters at all.

Has anyone successfully integrated with oAuth 2? Does it sound like I'm missing something?

FLASK: Serving file to browser behind API proxy

When the user enteres http://ift.tt/1aSPjZk the code below generates a data.csv file and serves it to the browser. It was perfectly on my localhost.

However, I have deployed it behind an API proxy, so that the user makes a call to http://ift.tt/1JcKTeT which is internally transformed into http://ift.tt/1aSPjZk.

As a result, instead of serving data.csv to the browser as on localhost, it shows on the browser all the data. The view source-code feature shows exactly what data.csv should contain, but it is not being served as attachement. Any ideas?

from flask import make_response

@app.route('/', methods = ['GET'])
def get_file():

    alldata = []

    while len(new_data) > 0:
            new_data = api.timeline(max_id=oldest)
            alldata.extend(new_data)
            oldest = alldata[-1].id - 1    

    outdata = ""
    for data in alldata:
            outdata += ",".join(data) + "\n"

    response = make_response(outdata)
    response.headers["Content-Disposition"] = "attachment; filename=data.csv"

    return response


if __name__ == '__main__':
  app.run(host = app.config['HOST'], port = app.config['PORT'])

Any good resources on using APIs in Laravel

I've been searching the web for the most effective and clean way of integrating an existing API into my Laravel project. All of the current resources explain how to build an API in Laravel effectively, not use one.

Thanks for your help

How to debug apis in PHP (without using var_dump();die();)

So I'm writing an api in php, and I'd like to use a full-service debugging tool. i.e., set breakpoints, view stack traces, inspect variables, etc. This kind of thing is very common in compiled languages.

I've checked out xdebug, and after configuring it to work with phpstorm (my IDE), I was disappointed to find that it only works when I run from within phpstorm, not when I actually service real api requests.

To add additional complexity to this, the api dbs are actually hosted on a vagrant instance, so although I write and edit code on my local machine, the code being run is in a virtual machine vagrant environment.

Any other way of doing this? Or should I just get used to something along the lines of print_r();exit; and rerun the request?

decode json with number object in php

I am working with HTTP API for sending SMS. I am trying to decode this json file which i actually receive after i made a post URL. Now i want to know is how can i decode the thing.. if this is static then i can decode but the fact is it have number key which may increase to any extension. In that case what i will do and how will i decode that post and also i need to save in mysql. Please anyone help me out of this problem.

{"msg_id":"4396-7666-1337896-1dc5c765ad7-5537bb07-123638242","SenderId":"EXECUT","linecount":"1","billcredit":"0.00","message":"Hello+Test+Message","sendondate":"2015-04-22 20:45:00","seq_id":{"**1**":{"valid":"true","billcredit":"1.00","id_provider":"24","providerkey":"HUTCH","regionKey":"WB","originalnumber":"1234567890","validnumber":"1234567890","mnpID":"106","dlr_seq":1},"**2**":{"valid":"true","billcredit":"1.00","id_provider":"24","providerkey":"HUTCH","regionKey":"WB","originalnumber":"1234567890","validnumber":"1234567890","mnpID":"106","dlr_seq":2}}}

How can I add a xml file from /res/values to my gitignore in my Android project?

I added a separate xml file to my /res/values folder which contains a secret api key that my app uses.

api_key.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="api_key" type="string">my_key</item>
</resources>

Now I would like to exclude it from git. How can I do that?

I added this line to the .gitignore file in my project root

/app/src/main/res/values/api_key.xml

but it does not work. The file still appears on Github after pushing the project content.

Java get metadata of public file on Google Drive

Hello I've downloaded and installed the latest version of Drive REST API for java and want to get the metadata of a public file from Google Drive by the fileID - I have the following code:

private static final String APPLICATION_NAME = "test";
private static final String FILE_ID = "theFileId";


public static void main(String[] args) {

    HttpTransport httpTransport = new NetHttpTransport();
    JacksonFactory jsonFactory = new JacksonFactory();

    Drive service = new Drive.Builder(httpTransport, jsonFactory, null).setApplicationName(APPLICATION_NAME).build();

    printFile(service, FILE_ID);
}


private static void printFile(Drive service, String fileId) {

  try {
      File file = service.files().get(fileId).execute();
      System.out.println("Title: " + file.getTitle());
  } catch (IOException e) {
      System.out.println("An error occured: " + e);
  }
}

But I get the error message: "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."

I've tried it on http://ift.tt/Q3fmNw which worked out just fine.

Do I have to authenticate with an API key when the file is public and how would I do that if so.

Thanks for your time.

Javascript/jQuery based Plugin to view RTF (or in general MS Office documents)?

I have been searching for a JavaScript/jQuery based plugin that makes it possible to view RTF files/content (either way).

Question:

  • Is there a plugin available that covers these needs?
  • If the answer is no, do you have any recommendations or tips to achieve this somehow?

How to migrate from the Provisioning API to the Admin SDK API?

The current application is written in JAVA. I plan to follow the steps here http://ift.tt/1GsG5go but I have little experience with JAVA and would like to make the migration as simple as possible. The API is being used to create a new email account.

This is what I have now:

  • The logic to create a google account and save data to our database is in GDataServlet.java
  • ClientWrapper.java is calling the function that creates the account
  • AppsForYourDomainClient.java is where the API call is being made with "http://ift.tt/1b3TGku";

How to move forward?

  • Update ClientWrapper.java to call the new API?
  • Or create a new table in our database that will store the data we need and create a new service that will call the new API?
  • I do not believe that GDataServlet.java needs to be modified.

Also if I am using the Service account Client ID type which I believe is what I need, where do I find the Client secret? I seem to have a Client Secret only when I select the Web Application Client ID type.

Get last 3 instagram images posted in a place

I've been over the Instagram API for a long time, and couldn't find a way to get the last 3 instagram images posted in a specific place.

For example, a visitor search for "Patrick's Pub". The website will redirect him to the pub's page in my website, and there I will be able to display the last 3 instagram images posted in Patrick's Pub.

Is there any way to display these images? I thought about this URL:

http://ift.tt/1Ob2F5y

But there are 2 problems with this: 1. I can't find a way to convert LAT and LNG coordinates to a place (like the Patrick's bar) 2. If need an access token for this URL, it means the user need to log in to his instagram account, and it will not be suitable for the website, for just vieweing a place instagram photos.

Any help will be appreciated.

How to version my API with Spring MVC?

For now, URLs of my API are for example:

/api/users

With Spring MVC:

@RequestMapping("/api/users")

I would like to version this api:

/api-v1.0/users

The best would be to be able to use an SpEL in the @RequestMapping annotation, but it is unfortunately not possible:

@RequestMapping("/api-#{appProps['version']}/users")

What are the other options then?

in REST what method to use for the sync operation

Synchronizing data once user gets online involves both Insert and Update (Upsert) and I'm sending both kinds of records in a single request (array in the body) and then server iterates through records to determine insert or update.

lastModified date for each record is kept on the client side and the records greater than lastSyncDate are retrieved and sent to the server.

My question is whether to use POST or PUT?

Also how a response (JSON) should like in the body?

How to get a list of permissions by specify App from Google Play programatically

I build a platform of java website and I want to program some java code that I can get a list of permissions by specify App from Google Play. I also search some Market API of open-source, such as android-market-api and google-play-crawler. When I use those API that I find some problems...

  • android-market-api:

    AppsRequest appsRequest = AppsRequest.newBuilder().setStartIndex(0)
                    .setEntriesCount(10).setQuery("pname:jp.naver.line.android")
                    .setWithExtendedInfo(true).build();
    
    session.append(appsRequest, new Callback<AppsResponse>() {
            @Override
            public void onResult(ResponseContext context, AppsResponse response) {
                    int count = response.getAppCount();
                    for (int i = 0; i < count; i++) {
                            System.out.println("app=" + i);
                            App app = response.getApp(i);
                            System.out.print(app.toString());                                   
                    }
            }
    });
    session.flush();
    
    
  • google-play-crawler

    String login = "xxxx@gmail.com";
    String password = "xxx";
    String androidId = "xxxx";
    String securitytoken = "xxx";
    String command = "permissions";
    String packageName="com.yelp.android";
    
    Changed_googleplay gp = new Changed_googleplay();
    
    gp.operate(new String[] { "-i", androidId, "-e", login,
    "-p", password, "-t", securitytoken, command,
    packageName });
    
    

My problem is that I can't get many app's permission and its' permissions always return empty. But I can make sure that API can return other info like PackegeName, version etc. Only a few app can work normally. I don't know what happen..

Can anyone help me or you can recommend me other solutions. Thank you:))

How do I get parameters from a PHP Object?

The object is contained in $response.

echo "<pre>";
 print_r($response);
echo "</pre>";

.. gives me the following:

Att\Api\Speech\SpeechResponse Object
(
   [_responseId:Att\Api\Speech\SpeechResponse:private] => f4119dcd51929c2dfae5e2d746c1d9a1
   [_status:Att\Api\Speech\SpeechResponse:private] => OK
   [_NBest:Att\Api\Speech\SpeechResponse:private] => Att\Api\Speech\NBest Object
        (
            [_hypothesis:Att\Api\Speech\NBest:private] => hi how are you
            [_languageId:Att\Api\Speech\NBest:private] => en-US
            [_confidence:Att\Api\Speech\NBest:private] => 0.5
            [_grade:Att\Api\Speech\NBest:private] => accept
            [_resultText:Att\Api\Speech\NBest:private] => Hi how are you.
            [_words:Att\Api\Speech\NBest:private] => Array
                (
                  [0] => Hi
                  [1] => how
                  [2] => are
                  [3] => you.
                )

            [_wordScores:Att\Api\Speech\NBest:private] => Array
                (
                  [0] => 0.33
                  [1] => 1
                  [2] => 1
                  [3] => 1
                )

        )

    )

N00b question: How would I now be able to receive the value from _resultText?

GET method with API's

I am not familiar with API's so I was hoping someone could help me with a question I have. My company uses Greenhouse as their hiring software for people to apply and we are redoing our career site to be more custom. They want a page where we can display each department with a text icon that has the number of positions open in that department that updates itself and when you go into that page it wants to display the positions for that department a long with the location they are in.

In the Greenhouse.io API section they say

"This is useful for reporting purposes, or for customers who have built their own tools that they want to use with Greenhouse. GET methods include Offices, Departments, Candidates, Activity Feed, Applications, Scorecards, Scheduled Interviews, Offers, Jobs, Stages, Job Post, Rejection Reasons, Email Templates, Users, and Sources."

Does this GET method mean I can pull those pieces from the API and display them where ever we need to in the site and it will update automatically? I'm primarily a web designer so this info is a bit new to me.

YouTube API V3 Search - regionCode and relevanceLanguage

As Google informed, I'm moving my service from API V2 to API V3.

But I'm having trouble making work the parameters regionCode and relevanceLanguage when I search videos in this new API. Looking for other foruns about the matter, I saw that a lot of people can't make them work too. Some people even claim that does not work.

Could somebody help me?

Thank you very much.

API call gives errors on headers

I've got an API from an organisation and it isn't working at all. When I do the request it gives this error in the console:

The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:8888, http://localhost:8888', but only one is allowed. Origin 'localhost:8888' is therefore not allowed access.

Does anyone know how I can solve this problem?

Beginner Wordpress - Stuck on Embedded Google Maps API

I'm new to Wordpress. I was just asked to erase the Google Map on this page: http://ift.tt/1ySrn3W

And to replace it with the same dimensions with a static image. I can't access the files without FTP, so I tried messing with the contact.php file. So far, no such luck. Any ideas?

Thanks,

Christian

What's mean of the API style that matching symbols?

The special matching symbols in API url eg: {?name} , {/other_user}

How to deal with clients?

Why use it ?

Reference:

http://ift.tt/1Cfu4bv

Example:

{
"upload_url": "http://ift.tt/1QeKuuj}", 
"id": 1161957,
"tag_name": "v1.6.0",
"author": {
    "following_url": "http://ift.tt/1DchPgs}",
    "gists_url": "http://ift.tt/1QeKwST}",
    "starred_url": "http://ift.tt/1QeKuun}",
    "subscriptions_url": "http://ift.tt/1DchNoB",
    "organizations_url": "http://ift.tt/1QeKuKB",
    "repos_url": "http://ift.tt/1DchNoD",
    "events_url": "http://ift.tt/1QeKwSZ}",
}
}

Placing a call programatically though GSM Modem

I was tasked with devising a solution to initiate a voice call using a GSM Modem programmatically. The call will be initiated via an API and play and audio file or just ring a number and then drop the call. This is to be used to notify staff during the night about critical alarms on the network.

Does anyone know of a solution or worked on something similar?

GSM network modem with SIM Card is to be used.

Thanks in Advance.

Received request with malformed body.. Python and REST API

I am getting this error when trying to pass a rate to a stopLoss order through Oanda's API:

code" : 41,
    "message" : "Received request with malformed body: 'units=1&instrument=
    EUR_USD&type=market&side=buy&stopLoss=%3Cmodule+%27streamer%27+from+%27%2FUsers%2Fmattduhon%2Fstreamer.py%27%3E'",

My problems seems to stem from the way that the streaming price gets passed to the order because if I poll the API and get a static price it works just fine.

So my question is, how can I format the output of the stream so that it is simply and integer because it looks to me like the API is seeing it as

%3Cmodule+%27streamer%27+from+%27%2FUsers%2Fmattduhon%2Fstreamer.py%27%3E'",

wich I do not at all understand..

Thanks in advance for all your help! Code as follows:

Streaming rates: Gets Streaming rate and drills it down to output only the ask price - .001

import requests
import json

from optparse import OptionParser

def connect_to_stream():
    """
    Environment           <Domain>
    fxTrade               stream-fxtrade.oanda.com
    fxTrade Practice      stream-fxpractice.oanda.com
    sandbox               stream-sandbox.oanda.com
    """

    # Replace the following variables with your personal ones
    domain = 'stream-fxpractice.oanda.com'
    access_token = 'xxxxxxxxxxxx'
    account_id = 'xxxxxxxxx'
    instruments = "EUR_USD"

    try:
        s = requests.Session()
        url = "https://" + domain + "/v1/prices?instruments=EUR_USD"
        headers = {'Authorization' : 'Bearer ' + access_token,
                   # 'X-Accept-Datetime-Format' : 'unix'
                  }
        params = {'instruments' : instruments, 'accountId' : account_id}
        req = requests.Request('GET', url, headers = headers, params = params)
        pre = req.prepare()
        resp = s.send(pre, stream = True, verify = False)
        return resp
    except Exception as e:
        s.close()
        print "Caught exception when connecting to stream\n" + str(e) 

def demo(displayHeartbeat):
    response = connect_to_stream()
    if response.status_code != 200:
        print response.text
        return
    for line in response.iter_lines(1):
        if line:
            try:
                msg = json.loads(line)
            except Exception as e:
                print "Caught exception when converting message into json\n" + str(e)
                return

            if displayHeartbeat:
                print line
            else:
                if msg.has_key("instrument") or msg.has_key("tick"):
                    print msg["tick"]["ask"] - .001
                    instrument = msg["tick"]["instrument"]
                    time = msg["tick"]["time"]
                    bid = msg["tick"]["bid"]
                    ask = msg["tick"]["ask"]

Trading program: This executes the trade orders and gives me the "Malformed Body" error or runs perfectly with a static stopLoss price..

import Queue
import threading
import time
import json
import oandapy
import streamer

from execution import Execution
from settings import STREAM_DOMAIN, API_DOMAIN, ACCESS_TOKEN, ACCOUNT_ID
from strategy import TestRandomStrategy
from streaming import StreamingForexPrices
from event import TickEvent
from event import StopEvent

rates = streamer

def trade(events, strategy, execution):
    """
    Carries out an infinite while loop that polls the
    events queue and directs each event to either the
    strategy component of the execution handler. The
    loop will then pause for "heartbeat" seconds and
    continue.
    """
    while True:
        try:
            event = events.get(False)
        except Queue.Empty:
            pass
        else:
            if event is not None:
                if event.type == 'TICK':
                    strategy.calculate_signals(event)
                elif event.type == 'ORDER':
                    print "Executing order!"
                    execution.execute_order(event)
        time.sleep(heartbeat)


if __name__ == "__main__":
    heartbeat = 0  # Half a second between polling
    events = Queue.Queue()



    # Trade 1000 unit of EUR/USD

    instrument = "EUR_USD"
    units = 1
    stopLoss = rates



    # Create the OANDA market price streaming class
    # making sure to provide authentication commands
    prices = StreamingForexPrices(
        STREAM_DOMAIN, ACCESS_TOKEN, ACCOUNT_ID,
        instrument, events
    )
    #handle stopLoss price
    rates = streamer

    # Create the execution handler making sure to
    # provide authentication commands
    execution = Execution(API_DOMAIN, ACCESS_TOKEN, ACCOUNT_ID)

    # Create the strategy/signal generator, passing the
    # instrument, quantity of units and the events queue
    strategy = TestRandomStrategy(instrument, units, events, stopLoss)

    # Create two separate threads: One for the trading loop
    # and another for the market price streaming class
    trade_thread = threading.Thread(target=trade, args=(events, strategy, execution))
    price_thread = threading.Thread(target=prices.stream_to_queue, args=[])
    rate_thread = threading.Thread(target=rates, args=[])

    # Start both threads
    trade_thread.start()
    price_thread.start()
    rates_thread.start()

FFMPEG API / Lib: sending video from Webcam to server using RTSP

How to realize that? Or somebody has example / tutorial ?

In ffmpeg(console) it is so simple: just set input, output and format..

But how it realize using ffmpeg api, no more information and/or tutorial((

And i'm sorry for my bad english

google web search apis from more locations

i'm going to develop an web-application using php and google api. This web-application get position/page of my website filtered by keywords list. Actually i call this google api address:

$query = "wedding%20portal";
"http://ift.tt/1JtX6bx";

and i get the result, but i need that this web-app search the results of google.com, google.fr, google.it with separated results, then look in the search engines google nations specifications ..

I can get this by google apis?

Or should I make calls to these bees by proxy, and returns results according to google I leased my proxy?

I tried using proxy and file_get_contents, but I google blocks the request.

wp.editPost 'API Wordpress' doesn't edit custom fields

When I try to edit custom_fields with wp.editPost. Only edit the other fields, but not custom fields. Custom fields are created again(repeat fields), but will have to be edited.

I am looking: http://ift.tt/1F7eEv9

My array with custom fields is:

    $content = array(
        'post_id' => (int)$idPostWp,
        'title' => $modificarPostWpDecode['title'], //ok edit
        'description' => $modificarPostWpDecode['content'], //ok edit
        'categories' => $modificarPostWpDecode['category'], //ok edit
        'custom_fields' => array(
            array('key' => 'precio', 'value' => $modificarPostWpDecodeCustom['price']), // no edit, fields will be create again
            array('key' => 'category', 'value' => $modificarPostWpDecodeCustom['category']), // no edit, fields will be create again
            array('key' => 'estrenar', 'value' => $modificarPostWpDecodeCustom['new']), // no edit, fields will be create again
            array('key' => 'currency', 'value' => $modificarPostWpDecodeCustom['currency']), // no edit, fields will be create again
            array('key' => 'search', 'value' => $modificarPostWpDecodeCustom['search']) // no edit, fields will be create again
            )
    );

My call to wordpress is:

    $params = array(1, WPUSER, WPPASS, (int)$idPostWp, $modificarPostWpDecode);
    $request = xmlrpc_encode_request('wp.editPost', $params, array('encoding' => 'UTF-8', 'escaping' => 'markup'));

Thank a lot!

Create order prestashop api php

i'm trying to create an order using Prestashop rest api but i always have this error : 400 Bad Request. I found a many topics about this problem but still no solution. I need this for my mobile app. this is my php code

$psXML = <<<XML

<prestashop>

<order>
<id/>
<id_address_delivery>11</id_address_delivery>
<id_address_invoice>11</id_address_invoice>
<id_cart>29</id_cart>
<id_currency>1</id_currency>
<id_lang>1</id_lang>
<id_customer>4</id_customer>
<id_carrier>2</id_carrier>
<current_state>11</current_state>
<module>paypal</module>
<invoice_number/>
<invoice_date/>
<delivery_number/>
<delivery_date/>
<valid/>
<date_add/>
<date_upd/>
<shipping_number/>
<id_shop_group>1</id_shop_group>
<id_shop>1</id_shop>
<secure_key>5c42fc9716c397e39275f2f60e243f4d</secure_key>
<payment>PayPal</payment>
<recyclable/>
<gift/>
<gift_message/>
<mobile_theme/>
<total_discounts/>
<total_discounts_tax_incl/>
<total_discounts_tax_excl/>
<total_paid/>
<total_paid_tax_incl/>
<total_paid_tax_excl/>
<total_paid_real/>
<total_products/>
<total_products_wt/>
<total_shipping/>
<total_shipping_tax_incl/>
<total_shipping_tax_excl/>
<carrier_tax_rate/>
<total_wrapping/>
<total_wrapping_tax_incl/>
<total_wrapping_tax_excl/>
<conversion_rate/>
<reference></reference>
<associations>
<order_rows>
<order_rows>
<id/>
<product_id>7</product_id>
<product_attribute_id>34</product_attribute_id>
<product_quantity>1</product_quantity>
<product_name>Robe de soie imprimée - Couleur : Jaune, Taille : S</product_name>
<product_reference>demo_7</product_reference>
<product_ean13/>
<product_upc/>
<product_price>20.501236</product_price>
<unit_price_tax_incl/>
<unit_price_tax_excl/>
</order_rows>
</order_rows>
</associations>
</order>
</prestashop>

XML;



try {
$webService = new PrestaShopWebservice($serverUrl, $serverApiKey, true);
$xml = new SimpleXMLElement($psXML);

$opt = array( 'resource' => 'orders' );
$opt['postXml'] = $xml->asXML();

$xml = $webService->add( $opt );
}
catch (PrestaShopWebserviceException $ex)
{
    echo 'Other error: <br />' . $ex->getMessage();
}

Facebook app: cannot post to user wall with custom privacy settings (An unknown error has occurred)

I'm working on a small Facebook app that needs to make text posts to users' walls, but with different privacy settings depending on some conditions. Everything works fine, except that when I need to post with "custom" privacy settings, the operation fails with an error code 1 and message = "an unknown error has occurred". I saw other posts talking about sessions or app tokens, etc, but I am sure none of these is the cause of my problem. I can be sure because I have made these different testings: 1. When I modify the same code, at the same spot, to making the post available with other privacy setting different that custom, this works fine. 2. When I again modify the same code keeping the custom privacy but specifying an empty string for the people allowed to view the post, it works fine setting the privacy of the post to "Only Me". 3. I have made sure of the content of the CSV String value that I pass to the command and that contains the list of friends' IDs who need to view the post. The format is correct and the IDs contained in it are also valid. When for instance I insert invalid IDs in this string, the operation succeeds and the post is published with an "Only Me" privacy level.

I really do not know what could be going wrong. Here is a snippet of the piece of code that generates the error:

$response = (new FacebookRequest( $session, 'POST', '/me/feed', array( 'message' => $message, 'privacy' => json_encode(array('value'=>'CUSTOM', 'friends'=>'SOME_FRIENDS', 'allow'=>$listOfFriends)) )))->execute()->getGraphObject();**

ListOfFriends is a CSV string that contains the IDs of the friends who should view the post. I again emphasize on the fact that this same code works with no problem when the privacy value is not CUSTOM or when it is kept CUSTOM and the string is empty or contains invalid IDs. The error occurs only when the string contains valid IDs.

I use V2.1 API.

Anyone who could help me with some clue?

Thank you very much ^^

call external php file from shopify registration page

i've been searching around for a way to call a php file on either the login or registration page of shopify.

I need to connect to another system and validate my users details and then if the users is a valid member assign the wholesale tag to the member otherwise they should remain a normal shopper.

I've tried ajax but I forgot about 'cross domain' calls so that did not work. I've also started to read up on shopify apps but it seems to be used mainly to interact with the shops database and not with external scripts or am i missing something.

What i want to do is take my users login details, do a quick checkup if they are wholesale members and then update their tag before they register.

or would it be better to perhaps have my registration page outside of shopify and perhaps do what i need with the details and then try to register the users using an API?

---------------------- EDIT --------------------------

Ok so after looking into webhooks and almost getting what i needed from that it feels as if the API will be the only way forward.

When using webhooks and the Customer creation event i received alot of info that i needed, but for me to verify the users i needed both their UN and PW and for webhooks just did not supply that for me.

So i will update my registration.liquid page to basically be a container for my iframe.

Bing translator API for android can give more than 1 result?

I'm making a Translator for Thai to English, one Thai word can translate to many words in English,so can I do that in my app?

I just research about example for this api but cant find solution.

I found it use a array of string to get results but this method just use for sentence translate :(

sorry for my poor English :)

SoundCloud API for app for search

I know the basic API of soundcloud. How can I search a track in SoundCloud without asking the user (who is logged into my website) to login/create an account in soundcloud?

I have to initialize the soundcloud with my client id before making any API call.

SC.initialize({
   client_id: 'YOUR_CLIENT_ID'
});

I don't want to pass client id to search. How can we do.

Using Google Adwords API as an SSIS datasource

My organisation is currently using google adwords and accessing it via PHP to create files, which are in turn read by an ETL script.

I'd like to access this as a datasource directly (using AWQL) within SSIS. Does anyone know if this is possible?

Authenticate Symfony2 REST API with Google Account

I'm working with Symfony2 and FOSOauthServerBundle in a REST API. I would wish that some user could log in by a client app using their Google Account, for instance.

From my REST server, by web, I can log in with my Google Account (using HWIOauthBundle), but I need to send to the client app an access_token (like FOSOauthServerBundle does).

I'm interested on persist the access_token that Google send to me in my data base and at the same time, send to the client app the json message {'access_token': 'XMekfmns.... } with Google's (and now my REST API too) access_token.

I don't know if my approach is right. Any ideas?

(sorry for my english ;-) )

Thank you very much

SMS Integration with Magento API

I am using Magento 1.8.1 and I want to integrate SMS with our store.

I have an API URL of SMS but don't know how and where to put that URL in Magento.

They provide me this code:

<?php 
class sendsms
{
        private $api_url;
        private $time;
        private $unicode;
        private $working_key;
        private $start;
        private $sender_id;
        public  $api;
        public  $wk;
        public  $sid;
        public  $to;

        /**function to set the working key
         * 
         * @param string_type $wk:helps to change the working_key
         */
        function setWorkingKey($wk)
        {   
                $this->working_key=$wk;
        }
        
        /**function to set sender id
         * 
         * @param string_type $sid:helps to change sender_id
         */
        function setSenderId($sid)
        {   
                $this->sender_id=$sid;
        }

        /**function to set API url
         * 
         * @param string_type $apiurl:it is used to set api url
         */
        function setapiurl($apiurl)
        {               $this->api=$apiurl;
                        $a=strtolower(substr($apiurl,0,7));
                         
                         if ($a=="http://") //checking if already contains http://
                         {
                                $api_url=substr($apiurl,7,strlen($apiurl));
                                $this->api_url=$api_url;
                                $this->start="http://";
                         }
                    elseif ($a=="https:/") //checking if already contains htps://
                         {
                                $api_url=substr($apiurl,8,strlen($apiurl));
                                $this->api_url=$api_url;
                                $this->start="https://";
                         }
                         else { 
                                                $this->api_url=$apiurl;
                                        $this->start="http://";
                                  }
        }

        /** function to intialize constructor
         * 
         * @param string_type $wk: it is working_key
         * @param string_type $sd: it is sender_id
         * @param string_type $apiurl: it is api_url
         *          used for intializing the parameter
         */
        function __construct($apiurl,$wk,$sd)
        {
                $this->setWorkingKey($wk);
                $this->setSenderId($sd);
                $this->setapiurl($apiurl);
        }

        /**
         * function to send sms
         * 
         */
        function send_sms($to,$message,$dlr_url,$type="xml")
        {
                $this->process_sms($to,$message,$dlr_url,$type="xml",$time="null",$unicode="null");
        }

        /**
         * function to schedule sms
         * 
         */
        function schedule_sms($to,$message,$dlr_url,$type="xml",$time)
        { 
                $this->process_sms($to,$message,$dlr_url,$type="xml",$time,$unicode='');
        }

        /**
         * function to send unicode message
         */
        function unicode_sms($to,$message,$dlr_url,$type="xml",$unicode)
        {  
                $this->process_sms($to,$message,$dlr_url,$type="xml",$time='',$unicode);
        }

        /**
         * function to send out sms
         * @param string_type $to : is mobile number where message needs to be send
         * @param string_type $message :it is message content
         * @param string_type $dlr_url: it is used for delivering report to client
         * @param string_type $type: type in which report is delivered
         * @return output               $this->api=$apiurl;
         */
        function process_sms($to,$message,$dlr_url="",$type="xml",$time='',$unicode='')
        {  
                $message=urlencode($message);
                $this->to=$to;
                $to=substr($to,-10) ;
                $arrayto=array("9", "8" ,"7");
                $to_check=substr($to,0,1);
        
         if(in_array($to_check, $arrayto))
                $this->to=$to;
         else echo "invalid number";

        if($time=='null')
                $time='';
        else
                $time="&time=$time";
        if($unicode=='null')
                $unicode='';
        else
                $unicode="&unicode=$unicode";
        
                
                $url="$this->start$this->api_url/web2sms.php?workingkey=$this->working_key&sender=$this->sender_id&to=$to&message=$message&type=$type&dlr_url=$dlr_url$time$unicode";
                $this->execute($url);
        }

        /**
         * function to check message delivery status
         * string_type $mid : it is message id 
         */
        function messagedelivery_status($mid)
        {
                $url="$this->start$this->api_url/status.php?workingkey=$this->working_key&messageid=$mid";
                        $this->execute($url);
        }

        /**
         * function to check group message delivery
         *  string_type $gid: it is group id
         */
        function groupdelivery_status($gid)
        {
                 $url="$this->start$this->api_url/groupstatus.php?workingkey=$this->working_key&messagegid=$gid";
                $this->execute($url);
                
        }

        /**
         * function to request to clent url
         */
        function execute($url)
        {
                $ch=curl_init();
                // curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                $output=curl_exec($ch);
                curl_close($ch);
                echo $output;
                return $output;
                
        }    
}

I am new to Magento, so please help me with the API integration.

Empty results in iTunes Store Search API

I am using iTunes Store Search API. My task is to retrieve app info by its app id. The problem is that for some apps and some country codes API returns empty results.

For example:

http://ift.tt/1aGwiJw - returns full info http://ift.tt/1Q2Cn3L - does not return info

Please, help me find out the root of the problem. Is that somehow connected with limitation of sale territories?

How to get simple text to speech functionality in android api 18?

I'm new to android development and I followed some tutorials to get text to speech working on an emulator with a higher API but my phone is a galaxy s3 running android 4.3 (api 18) which is too low.

So now I'm stumped,

1) is there any tutorial out there that explains how to get tts working on api 18? 2) how do I make my app behave differently depending on the android version it's dealing with?

How do I get the likes info from Facebook image or album?

I need to do simple analysis on the user facebook Image likes. How to create an API which can give the number of likes, each image has and as well as all the user who liked that image.

Should I use some crawler and give the first image and using class and Id attributes collect the user likes and then create click even for next image till it go round back to first image url.

Or is there some api facebook gives which can be used

Blogspot API: how to create new blogspot blog via API/etc.?

I need to create a blogspot blog, using their API, or just with GET/POST requests. Any ideas of doing it?

Change language in thegamesdb api

I am using thegamesdb-api to retrieve information about games, but there are in English, I want to know how to get information in another language (french).

How to programmatically set BoxITem (Folder/File) Custom URL for Box.com

We are doing migration from Lotus note to Box. There are link on Lotus note document to it's internal files which we plan to move to Box. We need to create the Customer URL on Box then we can create the hyperlink in Note document in advance and able to manage the Box link url.

Here is example code for the link.

<a style="display: inline-block; text-align: center" href="http://ift.tt/1Ht9jOZ" title="No.52 JGK HDD EM_CI seal_r3.ppt">
    <img src="http://ift.tt/1OF7san" width="205" height="48" alt="No.52 JGK HDD EM_CI seal_r3.ppt" border="0"/>
  </a>

The

href="http://10.86..../$FILE/..." 

we need to use our customer box url. for example

href="http://ift.tt/1Ht9hqu" 

which is able to set upfront. We plan to generate this document as PDF and upload to Box together with all related files.

API Office 365 create an event in user calendar format error

I am using Office 365 to post an event in user calendar. I have a problem with the format of my post.

Here is my code (using Codeigniter and Rest lib) :

    $config = array (
        'server'            => 'http://ift.tt/1GRCqe5', 
        'http_user'         => 'mail@domain.com',
        'http_pass'         => 'mypassword',
        'http_auth'         => 'basic',
    );
    $this->load->library('rest', $config);

    $event = array(
        'Subject' => 'Try to post :(',
        'Body'    => array(
            'ContentType' => 'HTML',
            'Content'     => 'Not really concluant...'),
         'Start'    => "2015-04-22T18:00:00Z",   
         'End'      => "2015-04-22T19:00:00Z",   
         'StartTimeZone'    => 'Europe Standard Time',
         'EndTimeZone'  =>  'Europe Standard Time',
    );

    var_dump($this->rest->post('events', json_encode($event), 'json'));

And here is the response :

A supported MIME type could not be found that matches the content type of the response. None of the supported type(s) 'application/json;odata.metadata=minimal

What I am doing wrong ? Don't say all please !

Posting an answer with stackexchange API 2.1

I'm trying to post an answer with stackexchange API 2.1 and I found that I can use the STACKMAN which I download from NUGET. It is very usefull but i could not find a way to post an answer with it.

Using with api SystemTimeToFileTime

When I use this function with originale SystemTime it works. I don't know because if i chance the values of System time the SystemTimeToFileTime return errore 87(invalido input). Can you help me?

Looking for an api that opens my specific page everyday to run a simple sql select query

Looking for an API that opens my specific page (http://ift.tt/1GcQGNP) everyday to run a simple sql select query and then select something.

I am using Laravel 4.2.

I have gone with Pusher and Iron.Io, i have tested it but i dont get it. It does scheduling tasks but doesnt query to your database.

Any other API out there? im running out of options.

Thanks.

Need Help For Set Google Plus API in Grails

I am using Oauth plugin here id config.groovy code

oauth {
providers {
    google {
        api = org.scribe.builder.api.GoogleApi
        key = '455253656547-3vrklc5phr5shur4l97qhk56ej8o028v.apps.googleusercontent.com'
        secret = '4isGzW-iwKdwsHlEuPs3_-h3'
        scope = 'http://ift.tt/y4qatF'
        callback = "${grails.serverURL}/oauth/google/callback"
        successUri = "${grails.serverURL}/login/google"
    }
}

}

here ic login controller code

def google() {
    Token token = (Token) session[oauthService.findSessionKeyForAccessToken('google')]
    def googleResource = oauthService.getGoogleResource(token,
               grailsApplication.config.grails.google.api.url)
    def googleResponse = JSON.parse(googleResource?.getBody())

    log.info "token = ${token}"
    log.info "googleResponse = ${googleResponse}"
    log.info "accesstoken = ${token.token}"
    log.info "id = ${googleResponse.id}"
    log.info "name = ${googleResponse.name}"
    //println googleResponse.name
    //render params
    redirect(controller: "Profile",action:"dashboard")

  }

And here is error

2015-04-22 14:10:55,902 [http-bio-8080-exec-8] ERROR errors.GrailsExceptionResolver - OAuthException occurred when processing request: [GET] /uxsurvey/oauth/google/authenticate - parameters: redirectUrl: Response body is incorrect. Can't extract token and secret from this: 'Consumer is not registered: 455253656547-3vrklc5phr5shur4l97qhk56ej8o028v.apps.googleusercontent.com '. Stacktrace follows: Message: Response body is incorrect. Can't extract token and secret from this: 'Consumer is not registered: 455253656547-3vrklc5phr5shur4l97qhk56ej8o028v.apps.googleusercontent.com '

Here is google Api client ID Code

 Client ID
455253656547-3vrklc5phr5shur4l97qhk56ej8o028v.apps.googleusercontent.com
Email address
455253656547-3vrklc5phr5shur4l97qhk56ej8o028v@developer.gserviceaccount.com
Client secret
4isGzW-iwKdwsHlEuPs3_-h3
Redirect URIs

    http://localhost:8080/uxsurvey/login/google

Javascript Origins
none

How to split a list of defect results from an ArrayList

Hello I am having trouble in splitting the information(severity, summary etc) I get for different components(General, Code Quality etc) in mozilla rest api. When I am calling to get information for a certain component. I get all of it in a single list. What I would like to do is separate the bugs and have each of them in an array. How would I do that? Here is my code for now

package bla_bla;

import java.io.IOException;
import java.util.ArrayList;
import java.util.*;
import javax.swing.text.html.parser.Element;

    import org.codehaus.jackson.map.ObjectMapper;
    import org.jsoup.Jsoup;
    import org.jsoup.nodes.Document;
    import org.jsoup.select.Elements;
    import org.jsoup.select.Evaluator.Id;
    import org.json.*;

    import argo.saj.InvalidSyntaxException;

    public class supermonkey {

    private static ArrayList<BugsList> bugsList;    
    private static ArrayList<BugsList> bugbug;  


    public static void main(String args[]) throws IOException {

        bugsList = new ArrayList<BugsList>();
        bugbug = new ArrayList<BugsList>();
        Document doc = Jsoup.connect("http://ift.tt/1Ht3Tna").get();
        String rawData = doc.body().text();
    //  System.out.println(title);
        JSONObject obj = new JSONObject(rawData);

    //  System.out.println(obj);

        System.out.println(obj.get("bugs"));

        JSONArray jsonMainArr = new JSONArray(obj.get("bugs").toString());
        for (int i = 0; i < jsonMainArr.length(); i++) {  // **line 2**
             JSONObject childJSONObject = jsonMainArr.getJSONObject(i);
             JSONObject assigned = childJSONObject.getJSONObject("assigned_to_detail");
          //   JSONObject assigned2 = childJSONObject.getJSONObject("assigned_to_detail");


             int id = assigned.getInt("id");
             BugsList bug = new BugsList();
             BugsList bug2 = new BugsList();
             bug.setId(id);



             String severity = childJSONObject.getString("severity");
             String resolution = childJSONObject.getString("resolution");
             String summary = childJSONObject.getString("summary");
             String component = childJSONObject.getString("component");
             bug.setSeverity(severity);
             bug.setResolution(resolution);
             bug.setSummary(summary);
             bug.setComponent(component);
             bugsList.add(bug);

             // String severity = assigned.getString();
    //       System.out.println("sss  "+ assigned);

        }



        getComponent("Code Quality");
    //  getSeverity(524276);
    //  getResolution(524276);
    //  getSummary(524276);
    }
       public static void getSeverity(int id){
           for(int i =0;i<bugsList.size(); i++){
               if(bugsList.get(i).getId() == id){
                   System.out.println("The id exists in the list " + bugsList.get(i).getSeverity());
               }
           }
       } 

       public static void getResolution(int id){
           for(int i =0;i<bugsList.size(); i++){
               if(bugsList.get(i).getId() == id){
                   System.out.println("The id exists in the list and The resolution is" + bugsList.get(i).getResolution());
               }
           }
       }  

       public static void getSummary(int id){
           for(int i =0;i<bugsList.size(); i++){
               if(bugsList.get(i).getId() == id){
    System.out.println("The comp.. exists in the list and The summary is   " + bugsList.get(i).getSummary());
               }
           }
       }
        // Current used method
       public static ArrayList<BugsList> getComponent(String component){
           for(int i =0;i<bugsList.size(); i++){
               if(bugsList.get(i).getComponent().equals(component)){
                   System.out.println("(Code Quality) component contains summary  " + bugsList.get(i).getSummary() +" /The resolution is " +                 
    bugsList.get(i).getResolution() + "  /Severity is " + bugsList.get(i).getSeverity());
                   bugbug.add(bugsList.get(i));
               }
           }
           return bugbug;
       }   


    }

Apply with #linkedin account

I have a website and I would like users to get registered by using their Linkedin account. I'm using this code but It's not working properly:

  • Some users told me they couldn't sign up with their linkedin account and
  • If I launch the website in my iphone it gives me an error saying that Domains must match. Linkedin api uses https and I'm using http.

The code:

<script type="text/javascript" src="http://ift.tt/IX0rQc">
     api_key: XXXXXXXXXXXXXXX
     lang:  es_ES
     scope: r_fullprofile r_emailaddress
</script>

<script type="in/Login" data-onAuth="onLinkedInAuth"></script>

function onLinkedInAuth() {
IN.API.Profile("me")
         .fields(["email-address","id","picture-urls::(original)","firstName","lastName","summary","recommendations-received","location","skills","educations","positions"])
         .result(displayProfiles).error(onError);
    }

What am I doing wrong? Thank you

where i should get USA water historical data for data science in python?

I am searching for particulate domain name they provide water data so I can scroll all data for my application.For weather i am using wunderground.

How to get all reviews from Trip advisor api

I am wondering how to get all reviews for specific place, from Trip Advisor Api. For now my call is http://ift.tt/1yR00qU

But in location response I have only 3 last reviews. How can I get them all?

Thanks.

Can't connect my app with google play games

I am trying to connect my application to the google play games services. I show somes of messages to debug the app. But when I try to connect with google play games it show that connection is wrong. Someone know where is the problem?

public class MenuActivity extends ActionBarActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
    AdView adView;

    GoogleApiClient mGoogleApiClient;

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

        android.support.v7.app.ActionBar ab = getSupportActionBar();
        ab.setBackgroundDrawable(getResources().getDrawable(R.drawable.background_tile_actionbar));

        //CONECTANDO CON LA CUENTA DE GOOGLE API CLIENT
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(Games.API).addScope(Games.SCOPE_GAMES).build();


        // Buscar AdView como recurso y cargar una solicitud.
        adView = (AdView)this.findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        adView.loadAd(adRequest);

    }

    @Override
    protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mGoogleApiClient.disconnect();
    }

    @Override
    public void onPause() {
        adView.pause();
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        adView.resume();
    }

    @Override
    public void onDestroy() {
        adView.destroy();
        super.onDestroy();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void onClickJugar(View view){
        Intent intent;
        intent = new Intent(this,LevelsActivity.class);
        startActivity(intent);
    }

    public void onClickEstadisticas(View view){
        Intent intent;
        intent = new Intent(this,StatisticsActivity.class);
        startActivity(intent);
    }

    public void onClickRanking(View view){
        if(mGoogleApiClient.isConnected()){
            Toast toast = Toast.makeText(this,"Te has conectado a google play cuando has hecho click",Toast.LENGTH_SHORT);
            toast.show();
        }else{
            Toast toast = Toast.makeText(this,"No te has conectado a google play cuando has hecho click",Toast.LENGTH_SHORT);
            toast.show();
        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        Toast toast = Toast.makeText(this,"Te has conectado a google play",Toast.LENGTH_SHORT);
        toast.show();
    }

    @Override
    public void onConnectionSuspended(int i) {
        Toast toast = Toast.makeText(this,"La conexion ha google play se ha suspendido",Toast.LENGTH_SHORT);
        toast.show();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Toast toast = Toast.makeText(this,"La conexion ha google play ha fracasado",Toast.LENGTH_SHORT);
        toast.show();
    }
}

mardi 21 avril 2015

Word prediction / Spell correction api like google search

Have a look at this image :

enter image description here

I'm looking for an api to give these kind of corrections.

  • Does Google provide same service as an api?
  • If yes, suggest me those api?
  • Do you know some other api for the same?

Architecturing API keys and access tokens

I have a question regarding how I should architecture a REST API using access token and API keys.

I have an API that needs authentication. I want to enable two use cases:

  1. The user logs into the interface using OAuth2 (password grant), and is granted a temporary access token. This token is used to authenticate the user. Therefore, the UI, that itself using the API, can fetch data and display it.

  2. I also want the user to have an API key to do the same calls, but in its application. Obviously, contrary to the access token, I want the API key to be long lived. Also, contrary to the access token that is tied to a given user (if we introduce a team mechanism, each user will have different access token, although they access the same resources), the API key should be unique to the project.

While similar, I'm not sure about how should I architecture that. I think that, internally, both API keys and access tokens should be stored in the same table, but API keys having no expiration time. Am I right?

One thing I'm not sure also is the concept of client. It seems that in the spec, the client is more like an external application. However may I actually use this concept here?

For instance, each "project" is actually a different client (although the client here is the same application, not an application created by a third-party developer).

Therefore, if user A creates an account on the system, a client A will be automatically created, with an access token tied to the client A, with a long-lived access token (aka API key). This can be used to perform API calls directly on his code, for instance.

Then, if user A logs into the dashboard, a temporary access token will be created, but this time with no application, but tied to the user, with a short life.

Does this sound sane? Have anyone already implemented such a thing?

Thanks!

GetEmbeddedSignerView badrequest docusing api

I am trying to call the emmbeddedSignerView method from the docusign nuget package but the response fails to return a url. I ended up copying the unit test code

// create a new envelope with 2 recipients            
        var envelope = new Envelope { Login = account };
        byte[] doc1 = { 36, 45, 34, 67, 121, 87, 99, 32, 32, 32, 54, 54, 55, 56, 32 };
        var signers = new List<Signer>();
        // note we need to specify clientUserId
        signers.Add(new Signer { email = "unitests1@testing.com", name = "test1", recipientId = "1", routingOrder = "1", clientUserId = "1" });
        //signers.Add(new Signer { email = "unitests2@testing.com", name = "test2", recipientId = "2", routingOrder = "2", clientUserId = "2" });
        envelope.Recipients = new Recipients { signers = signers.ToArray() };
        envelope.Create(doc1, "test-self-signed.doc");

        // send it
        envelope.Status = "sent";
        envelope.UpdateStatus();

        // get embedded signing views for 2 recipients
        string urlForfirstSigner = envelope.GetEmbeddedSignerView("www.docusign.com", signers.First());

When I debug I can see that the response status code is "BadRequest" with the response text "RECIPIENT_NOT_IN_SEQUENCE\",\r\n \"message\": \"The token for an out of sequence recipient cannot be generated."

Am I doing something wrong? I figured since I copied the code it should work...

I am using the nuget package so I copied the object data of my create and embedded signing requests and responses hopefully this will help.

REQUEST
{System.Net.HttpWebRequest}
    base: {System.Net.HttpWebRequest}
    Accept: null
    Address: {http://ift.tt/1OEsC8u}
    AllowAutoRedirect: true
    AllowReadStreamBuffering: false
    AllowWriteStreamBuffering: true
    AutomaticDecompression: None
    ClientCertificates: {System.Security.Cryptography.X509Certificates.X509CertificateCollection}
    Connection: null
    ConnectionGroupName: null
    ContentLength: 512
    ContentType: "multipart/form-data; boundary=00000000-0000-0000-0000-000000000000"
    ContinueDelegate: null
    ContinueTimeout: 350
    CookieContainer: null
    Credentials: null
    Date: {1/1/0001 12:00:00 AM}
    Expect: null
    HaveResponse: false
    Headers: {X-DocuSign-Authentication: <DocuSignCredentials><Username>qfroth@gmail.com</Username><Password>MYPASSWORD</Password><IntegratorKey>MYINTEGRATORKEY</IntegratorKey></DocuSignCredentials>
Content-Type: multipart/form-data; boundary=00000000-0000-0000-0000-000000000000
Host: demo.docusign.net

}
    Host: "demo.docusign.net"
    IfModifiedSince: {1/1/0001 12:00:00 AM}
    KeepAlive: true
    MaximumAutomaticRedirections: 50
    MaximumResponseHeadersLength: 64
    MediaType: null
    Method: "POST"
    Pipelined: true
    PreAuthenticate: false
    ProtocolVersion: {1.1}
    Proxy: null
    ReadWriteTimeout: 300000
    Referer: null
    RequestUri: {http://ift.tt/1OEsC8u}
    SendChunked: false
    ServerCertificateValidationCallback: null
    ServicePoint: {System.Net.ServicePoint}
    SupportsCookieContainer: true
    Timeout: 100000
    TransferEncoding: null
    UnsafeAuthenticatedConnectionSharing: false
    UseDefaultCredentials: false
    UserAgent: null



RESPONSE

{DocuSign.Integrations.Client.ResponseInfo}
    ContentType: "application/json; charset=utf-8"
    ErrorMessage: ""
    ResponseBytes: {byte[198]}
    ResponseStream: {System.Net.ConnectStream}
    ResponseText: "{\r\n  \"envelopeId\": \"b3c02285-f787-49b4-951d-53bb4057023e\",\r\n  \"uri\": \"/envelopes/b3c02285-f787-49b4-951d-53bb4057023e\",\r\n  \"statusDateTime\": \"2015-04-22T04:26:41.7770000Z\",\r\n  \"status\": \"created\"\r\n}"
    StatusCode: Created


REQUEST
{System.Net.HttpWebRequest}
    base: {System.Net.HttpWebRequest}
    Accept: "application/json"
    Address: {http://ift.tt/1HiK0Rj}
    AllowAutoRedirect: true
    AllowReadStreamBuffering: false
    AllowWriteStreamBuffering: true
    AutomaticDecompression: None
    ClientCertificates: {System.Security.Cryptography.X509Certificates.X509CertificateCollection}
    Connection: null
    ConnectionGroupName: null
    ContentLength: 133
    ContentType: "application/json"
    ContinueDelegate: null
    ContinueTimeout: 350
    CookieContainer: null
    Credentials: null
    Date: {1/1/0001 12:00:00 AM}
    Expect: null
    HaveResponse: false
    Headers: {Accept: application/json
Content-Type: application/json
X-DocuSign-Authentication: <DocuSignCredentials><Username>qfroth@gmail.com</Username><Password>MYPASSWORD</Password><IntegratorKey>MYINTEGRATORKEY</IntegratorKey></DocuSignCredentials>
Host: demo.docusign.net

}
    Host: "demo.docusign.net"
    IfModifiedSince: {1/1/0001 12:00:00 AM}
    KeepAlive: true
    MaximumAutomaticRedirections: 50
    MaximumResponseHeadersLength: 64
    MediaType: null
    Method: "POST"
    Pipelined: true
    PreAuthenticate: false
    ProtocolVersion: {1.1}
    Proxy: null
    ReadWriteTimeout: 300000
    Referer: null
    RequestUri: {http://ift.tt/1HiK0Rj}
    SendChunked: false
    ServerCertificateValidationCallback: null
    ServicePoint: {System.Net.ServicePoint}
    SupportsCookieContainer: true
    Timeout: 100000
    TransferEncoding: null
    UnsafeAuthenticatedConnectionSharing: false
    UseDefaultCredentials: false
    UserAgent: null

RESPONSE
{DocuSign.Integrations.Client.ResponseInfo}
    ContentType: "application/json; charset=utf-8"
    ErrorMessage: "Bad Request"
    ResponseBytes: null
    ResponseStream: null
    ResponseText: "{\r\n  \"errorCode\": \"RECIPIENT_NOT_IN_SEQUENCE\",\r\n  \"message\": \"The token for an out of sequence recipient cannot be generated.\"\r\n}"
    StatusCode: BadRequest

Rest Api Key No User Credentials

I've been scouring the internet for information about how to properly generate an api key that is not tied to any user but just to an application installation and haven't come up with much. So either I'm thinking about this the wrong way entirely or I'm not asking the question correctly.

So here's what I'm trying to do and please let me know if I'm thinking about this the wrong way.

I'm making a PHP Rest API with a MySQL back end. I have no users to speak of but I want to secure my rest api with an apikey so that I can at least log usage and other metrics. This api will be primarily consumed by an Android app but I also want the flexibility to be consumed by any client type really. So I was thinking of creating and endpoint named "generateToken" that will return an apiKey that can be used to call the service. As far as apps are concerned, they will hit this generateToken endpoint during installation and then have it saved in their shared preferences store or keychain for the lifetime of the app. Is this an appropriate way to essentially setup an apikey to identify individual calls etc? Am I thinking about this the wrong way? Should I just institute some sort of user store although I have no real use for it other than securing the api.

how to get other users' full size profile picture in linkedin

i would like to get someone's profile picture, the original one that he/she uploaded

i have been trying it with this

http://ift.tt/1QhoONZ

but i failed and the response is like this

{ "errorCode": 0, "message": "Access to people search denied.", "requestId": "XYK50W4DAD", "status": 403, "timestamp": 1429639373120 }

how can i fix it?

Connecting to a SOAP based API from PHP

I want to connect to an SOAP based API. The API is provided in the form of dynamic link library (dll) files. This API is running on IIS server.

The first method I need to call is (ValidateClient(string sUsername, string sPassword);) which returns a TAuthenticate object.

How do i connect and make the call in PHP?

Cheers,

Ahmed

google drive php api HOW TO SET labels.restricted / want to restrict the file from Downloading

Here is the parameter, under labels.restricted :

http://ift.tt/W3uLVH

But cannot code it in PHP tried almost everything but still getting error from the google drive API.

$file = new Google_Service_Drive_DriveFile();
$file->setTitle(TESTFILE);

$file->setRestricted();

$result = $service->files->insert(
  $file,
  array(
    'data' => file_get_contents(TESTFILE),
    'mimeType' => 'application/octet-stream',
    'uploadType' => 'multipart'
    //
    // HERE SHOULD BE THE CODE FOR THE labels.restricted
    //
  )
);

product catalog api fail

need help. I tried to start with http://ift.tt/1DOICmF created account. Approved it by phone. created a business account, an ad account, an app, and so on. linked app to ad accont like this http://ift.tt/1Dcmj5Q. Now i tried to create product catalog. i am getting same error all the time:

 The app is not whitelisted to use this API

i tried to call api to cteate/list/managment product catalog. when i did, the same by UI - i can create product catalog & feed. but by API - all time error. i do not understand what it need?

now try to create product set:

GET /<product_catalog ID>/product_sets/?
access_token=<my access token from app with full rights get from exploer>
{
  "error": {
    "message": "(#200) The app is not whitelisted to use this API",
    "type": "OAuthException",
    "code": 200
  }
}

try to create the same:

POST : /v2.3/<product_catalog ID>/product_sets/?access_token=<my access token from app with full rights get from exploer>&name=my new prod set
{
  "error": {
    "message": "(#275) Ad account cannot be determined for this request",
    "type": "OAuthException",
    "code": 275
  }
}

So what Are the changes i needed to make it work?

is it any way to made api calls work correctly?

p.s. i guess something wrong in settings - i run unit tests in SDK - have the same situation. i have read about that problems with game app - but my app - is not a game, so i cant use solution in my situation. if some body understand what whitelist API want - please help! Thanks.