Categories
discuss

JavaScript Failed to execute ‘drawImage’

Ok so I’m creating a game with JavaScript Canvas Elements and such. I’ve been able to load in TONS of Images, but on a select few, JavaScript replies with Errors such as

Uncaught TypeError: Failed to execute ‘drawImage’ on ‘CanvasRenderingContext2D’: No function was found that matched the signature provided.

Which makes NO SENSE at all, because the same code works in other places!?!

Here is an example I have in my code:

board.drawImage(document.getElementById("player_explode"), this.x, this.y);

Inside of an objects method, Player.die(), respectively.

Does anyone know why this behaviour is coming about? I’m getting very frustrated about it…

Here is a JSFiddle to demonstrate, alonside all the code. Player.die() is located on line[242].

Answer

The problem was the way that I was loading my Images, I should’ve been doing:

var image = new Image();
image.src = "imagesource.jpg";

But instead I was get the elements by id from the document page.

Resources:

Explanation on loading images

Explanation on how html loads images

Categories
discuss

Android Volley double post when have slow request

I have a problem with Volley POST request on slow network. Everytime I see BasicNetwork.logSlowRequests in my LogCat, my POST request is executed twice or more resulting multiple (2 or more) postings for 1 request. I already set the retry policy to 0, but It doesn’t help.

This is my LogCat

03-16 01:31:35.674: D/Volley(5984): [19807] BasicNetwork.logSlowRequests: HTTP response for request=<[ ] http://[myserver]/api/places 0xfa7d0c33 NORMAL 1> [lifetime=3824], [size=313], [rc=200], [retryCount=0] 03-16 01:31:35.704: D/Volley(5984): [1] Request.finish: 3853 ms: [ ] http://[myserver]/api/places 0xfa7d0c33 NORMAL 1

This is my code

JSONObject body = new JSONObject();
try {
    body.put(PROTO_BODY_AUTHORIZATION, Sessions.getActiveSession().getToken());
} catch (JSONException e) {
    e.printStackTrace();
}

JsonObjectRequest request = new JsonObjectRequest(
        Request.Method.POST,
        context.getResources().getString(R.string.server_address) + "/places",
        body,
        callback,
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(context, error.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
);

request.setRetryPolicy(
        new DefaultRetryPolicy(
                DefaultRetryPolicy.DEFAULT_TIMEOUT_MS,
                0,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    getRequestQueue().add(request);

Please help, I desperately finding solution for this problem.

Answer

Add the following values to your Request object:

request.setRetryPolicy(new DefaultRetryPolicy(
    DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2,
    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

Here: request is your object of JsonObjectRequest. Change the value of multiplicator according to the DEFAULT TIMEOUT VALUE in DefaultRetryPolicy class in Volley.

You can also set the first argument to 0, like below:

request.setRetryPolicy(new DefaultRetryPolicy(
    0,
    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Categories
discuss

What is WSDL equivalent in restful WS . If nothing,how consumer generates required client side classes?

Say ,i have producer in java and consumer in dot net. Producer has a method that takes Employee as method parameter and creates employee in db.

For SOAP based ws, dot net client will hit WSDL and creates the stubs (including employee data representation in dot net). Now it can fill the object and send to producer.

I am not sure how it will work in restful webservices as there is no WSDL. How rest consumer will get to know what are the operations exposed by producer without any WSDL contract and how dot net consumer will get stubs (like employee data object) so that it can simply fill it and send across?

I know there is WADL(parallel to WSDL) in rest but looks like its not very prominent and not a standard as of now.

I am not getting how client side code will generate EmployeeData class so that it can fill it and send to producer? Will client manually create extra class (instead of proxy EmployeeData that used to be generated on the basis of WSDL using utilities available at client side)? Even if client has to do it manually, how client will know what is the class definition of EmployeeData class without wsdl or wadl?

Answer

One important concept of REST is HATEOAS or Hypermedia as the Engine of Application State. What this means is that your client interacts with the REST service through hypermedia links that the service hands it.

Your REST web service has an entry point, say http://yourhost.com/rest. Your client will start by sending the request to that URL. Your service will respond with a resource that describes some or all the accessible resources and how to access them. You keep discovering and following links. This is how the API is published (and discovered).

Here’s an awesome video describing this concept: Hypermedia APIs.

Through HATEOAS you can make your service API completely discoverable by just following hypermedia links.


There is no concept of top down/bottom up design in REST.

REST is about resources, not about method calls, which is basically what a WSDL describes.

Even if client has to do it manually, how client will know what is the class definition of EmployeeData class without wsdl or wadl?

It won’t need to create an EmployeeData class. Say you needed to create a new Employee, you would send a GET request to /employees which would possibly return a response containing how to do that. That might be an XHTML response like so (among other things)

<form class="new-employee" action="/context/employees" method="PUT" >
    <input type="text" name="employee_name" />
    <input type="text" name="employee_age" />
    <input type="submit" name="submit" />
</form>

The response contains the exact format you need to follow to create a new employee. You need to submit the form to /context/employees with an HTTP PUT request containing those form parameters. This is HATEOAS. The hypermedia link is the /context/employees. The engine is following this link with a PUT request. The application state is that after this request, a new employee will exist.

Categories
discuss

Javascript underscore array to object

Is there an easy/clean way using Underscore to turn this

[ { id: 'medium', votes: 7 },
  { id: 'low',    votes: 9 },
  { id: 'high',   votes: 5 } ]

Into

 { 'low'    : 9,
   'medium' : 7,
   'high'   : 5 }

Answer

var data = [ { id: 'medium', votes: 7 },
  { id: 'low',    votes: 9 },
  { id: 'high',   votes: 5 } ];

You can do this with _.map, _.values and _.object, like this

console.log(_.object(_.map(data, _.values)));
# { medium: 7, low: 9, high: 5 }

Explanation

We use the map function to apply the values function (which gets all the values of a given object) over all the elements of data, which would give

# [ [ 'medium', 7 ], [ 'low', 9 ], [ 'high', 5 ] ]

Then we use object function to transform this into an object.

Categories
discuss

Java8 streams and typecasts

Can anybody explain to me why the following code is not working?

I was trying to get a feel for the new features of Java8 and solved the BerlinClock Kata. During this I had to parse a String in the format "hh:mm:ss" – I wanted to use streams and wrote the following piece of code.

import java.util.Arrays;

private Integer[] parseTime (String time){
    Integer[] hhmmss = (Integer[]) Arrays.stream(time.split(":"))
                                         .map(s->Integer.parseInt(s)).toArray();
    return hhmmss;
}

but the runtime system (I think) is complaining that the explicit type cast (Integer[]) cannot be done.

As far as I understand it the Arrays.stream(time.split(":")) part returns a Stream<String>, then map(s->Integer.parseInt(s)) converts this to Stream<Integer>, then toArray() produces an Object[]. Now a type cast to Integer[] should be possible as the intermediate stream was had an Integer type-parameter.

Note that I know how to solve this problem without type cast by using

int[] hhmmss= Arrays.stream(time.split(":")
                    .mapToInt(Integer::parseInt).toArray();

and changing the type signature accordingly to int[] parseTime. But I do not understand why there is a problem in the type-cast.

Answer

For the first case, Stream#map() method will give you a Stream<Integer>, and then Stream#toArray() returns an Object[], which you need to cast to Integer[]. But at runtime, this cast may fail, if internally an Object[] is created instead of an Integer[], which is the case here. The source code of toArray() method for this stream looks like this:

@Override
public final Object[] toArray() {
    return toArray(Object[]::new);
}

And you can’t cast an Object[] to an Integer[] reference.

You can solve this issue by using Stream#toArray(IntFunction) instead, and then you wouldn’t need a cast:

private Integer[] parseTime (String time){
    Integer[] hhmmss = Arrays.stream(time.split(":"))
                    .map(s->Integer.valueOf(s))
                    .toArray(Integer[]::new);
    return hhmmss;
}

In second case however, Stream#mapToInt() method gives you an IntStream, and IntStream#toArray() returns an int[], and hence no casting required there.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..