• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

T

thepotatoman

Unconfirmed Member
I can't come up with a good solution to this, but here's what I want to do.
I have 3 combo boxes with 3 items to choose from. I want to make it so the 3 combo boxes always have unique values.

I can think of a convoluted way to write this, but it doesn't sound practical. If I had 200 items and no duplicates were allowed, how would I write this? Preferably in C#.

Do you mean no duplicates between all three combo boxes? if so, you can use linq like bellow for each combo box:

Code:
yourList1 = yourList1.Distinct()
                     .Where(x => !(yourList2.Any(x)) && !(yourList3.Any(x)))
                     .ToList();

If you mean no duplicates in the one list you just need:

Code:
yourList = yourList.Distinct().ToList();
 

Koren

Member
Explain the .reduce method in Javascript to me?
I think Somnid is doing great, but just in case it helps, taken from the "folding" wikipedia page
https://en.wikipedia.org/wiki/Fold_(higher-order_function)

Left-fold-transformation.png


Reduce is doing the transformation above...

A table [ 1; 2; 3; 4; 5 ] is thus converted into f( f( f( f( f( z, 1 ), 2 ), 3 ), 4 ), 5 )

So :

with multiplication and z=1, you get ((1*1)*2)*3)*4)*5
with addition and z=0, you get ((0+1)+2)+3)+4)+5

Folding is a great (and efficient) feature of functional languages (and available in a large number of languages, in fact)
 

TheSeks

Blinded by the luminous glory that is David Bowie's physical manifestation.
"reduce" is a method off an array, so you'd have all your values in an array and call reduce on it. The array is not an argument. The first argument of the reduce function is the previous value.

So you call array.reduce([function], [initialValue]);
1) the reduce function will get (initialValue, array[0]) passed into it.
2) the reduce function will get (result from 1, array[1]) passed into it.
3) the reduce function will get (result from 2, array[2]) passed into it.
...
N) the reduce function will get (result from n-1, array[n-1] passed into it


So let's say I put it into a function that is going to multiply everything in that array.

I loop to put numbers into the array to where I argument end.

[1, 2, 3, 4, 5, 6, 7, 8] is the array.

The bold/initial value would be... 8? 1?

I think Somnid is doing great, but just in case it helps, taken from the "folding" wikipedia page
https://en.wikipedia.org/wiki/Fold_(higher-order_function)

Left-fold-transformation.png


Reduce is doing the transformation above...

A table [ 1; 2; 3; 4; 5 ] is thus converted into f( f( f( f( f( z, 1 ), 2 ), 3 ), 4 ), 5 )

So :

with multiplication and z=1, you get ((1*1)*2)*3)*4)*5
with addition and z=0, you get ((0+1)+2)+3)+4)+5

Folding is a great (and efficient) feature of functional languages (and available in a large number of languages, in fact)

Okay, I think I get it.

array.reduce(function[array, x], 1) would put my array as:

(1, [1, 2, 3, 4, 5, 6, 7, 8), yeah? Then to do reduce, I "return array * x"? Which would make it 1 * 1 * 2 * 3?

I mean I get the concept, but I'm not getting the initialization
 

Koren

Member
I mean I get the concept, but I'm not getting the initialization
The initialization is the second parameter of reduce, the one that act as the first parameter of the function you provide for the first call (the second time, it's the result of the first call that will be used).

But if it bothers you, you don't have to use one in Javascript IIRC.

In theory, that's a far weaker solution, because that means the result returned by reduce will be of the same type as elements in the table, but you probably don't mind.
 

TheSeks

Blinded by the luminous glory that is David Bowie's physical manifestation.
The initialization is the second parameter of reduce, the one that act as the first parameter of the function you provide for the first call (the second time, it's the result of the first call that will be used).

Oh, alright. Then the only thing left I need to understand is putting that array into it within a function so the function loops to that number (which I already have) and then calculates the reduce/"merge"-ing of the array by the initialize/1.

I guess the variable name "array" wouldn't work for an argument to put the array in so the (1[1, 2...]) would work?
 

Aikidoka

Member
So I trying to implement a reduction operation in CUDA, and I've come across a C operator that i've never seen in this for loop. it's the s >>= 1 operator. Goofgling has taught me that it is a Binary Right Shift operator with assignment, but looking at the example I really don't understand what is going on.

I'll include the whole kernel for completeness, the part I'm concerned with is the for loop over the variable s.

Code:
__global__ void kernel_csr(int m,int n,double *d_a,int *count_block)                                                 
{                                                                                                                    
  extern __shared__ int count_thread[];                                                                              
  unsigned int tid = threadIdx.x;                                                                                    
  unsigned int i = blockIdx.x*blockDim.x+threadIdx.x;                                                                
  unsigned int count = 0;                                                                                            
                                                                                                                     
  // thread counts all nonzero elements in its row                                                                   
  countdata[tid] = 0; //initialize                                                                                   
  for(int col = 0;col<n;col++){                                                                                      
    if(d_a[i*n+col] >= 1e-17) count++;                                                                               
  }                                                                                                                  
  count_thread[tid] = count;                                                                                         
                                                                                                                     
  __syncthreads(); // syncs all threads in a block                                                                   
                                                                                                                     
  //do reduction in shared memory                                                                                    
  for(unsigned int s = blockDim.x/2; s>0; s>>=1){                                                                    
    if(tid < s){                                                                                                     
      count_thread[tid] += count_thread[tid+s];                                                                      
    }                                                                                                                
    __syncthreads();                                                                                                 
  }                                                                                                                  
  //write result for this block to global memory                                                                     
  if(tid==0) count_block[blockIdx.x]=count_thread[0]; //holds nonzeros inside a block                                
                                                                                                                     
}

Any insight would be helpful. I guess, the name is more transparent than I thought. So the loop is dividing by 2 each iteration?
 
Code:
  for(unsigned int s = blockDim.x/2; s>0; s>>=1){                                                                    
    ...                                                                                              
  }

Any insight would be helpful. I guess, the name is more transparent than I thought. So the loop is dividing by 2 each iteration?

Correct! Shifting bits left or right is the same as multiplying or dividing by two respectively. As for the rest of the code, I don't feel like there's enough of it for me to help out there.
 

_Isaac

Member
I might have to choose between a Ruby on Rails position and a WPF/UWP (Universal Windows Platform) position. It's hard to choose. I've mostly been working with .NET and C# web stuff. I like working on web stuff, but I'm not all that familiar with RoR. I've mostly been working with ASP.NET MVC. I really like C#, so the UWP position looks appealing, but I don't know much about UWP or windows thick client apps. Any of you have UWP experience? People don't seem to talk about it much.
 
So I trying to implement a reduction operation in CUDA, and I've come across a C operator that i've never seen in this for loop. it's the s >>= 1 operator. Goofgling has taught me that it is a Binary Right Shift operator with assignment, but looking at the example I really don't understand what is going on.

I'll include the whole kernel for completeness, the part I'm concerned with is the for loop over the variable s.

Code:
__global__ void kernel_csr(int m,int n,double *d_a,int *count_block)                                                 
{                                                                                                                    
  extern __shared__ int count_thread[];                                                                              
  unsigned int tid = threadIdx.x;                                                                                    
  unsigned int i = blockIdx.x*blockDim.x+threadIdx.x;                                                                
  unsigned int count = 0;                                                                                            
                                                                                                                     
  // thread counts all nonzero elements in its row                                                                   
  countdata[tid] = 0; //initialize                                                                                   
  for(int col = 0;col<n;col++){                                                                                      
    if(d_a[i*n+col] >= 1e-17) count++;                                                                               
  }                                                                                                                  
  count_thread[tid] = count;                                                                                         
                                                                                                                     
  __syncthreads(); // syncs all threads in a block                                                                   
                                                                                                                     
  //do reduction in shared memory                                                                                    
  for(unsigned int s = blockDim.x/2; s>0; s>>=1){                                                                    
    if(tid < s){                                                                                                     
      count_thread[tid] += count_thread[tid+s];                                                                      
    }                                                                                                                
    __syncthreads();                                                                                                 
  }                                                                                                                  
  //write result for this block to global memory                                                                     
  if(tid==0) count_block[blockIdx.x]=count_thread[0]; //holds nonzeros inside a block                                
                                                                                                                     
}

Any insight would be helpful. I guess, the name is more transparent than I thought. So the loop is dividing by 2 each iteration?
Yeah, bitshift.

It's equivalent to:
s = (s >> 1);
and
s = (s / 2);

Where s/2 is integer division. The reason you would usually use a bitshift is for either performance reasons (single instruction) or because what's being done to the int is actually related to bits more than it is to numbers. For an example of the latter, fixed point math implementations will use the low bits for decimal precision -- so if you want the whole number, division will get you the right answer, but it's probably more logically consistent to just clear those low bits with a right shift.
 

Koren

Member
Yeah, bitshift.

It's equivalent to:
s = (s >> 1);
and
s = (s / 2);

Where s/2 is integer division. The reason you would usually use a bitshift is for either performance reasons (single instruction)
It probably should only be chosen on readability, I'm sure all those instructions will result in a bitshift in assembly with any decent compiler.
 
I can't figure out why my linked list functions aren't working.

The function that iterates through the linked list and prints the values works just fine.

The function that prints the frontmost value returns some garbage value, UNLESS I add more than one value to the linked list, in which case it functions properly. But I've hand traced it and I can find no reason for why this would happen.

Would anyone be willing to look at the code?

edit: It looks like somehow the front sentinel will NOT point to the back sentinel... no matter what I do. But the back sentinel points to the front just fine.
 

JeTmAn81

Member
I can't figure out why my linked list functions aren't working.

The function that iterates through the linked list and prints the values works just fine.

The function that prints the frontmost value returns some garbage value, UNLESS I add more than one value to the linked list, in which case it functions properly. But I've hand traced it and I can find no reason for why this would happen.

Would anyone be willing to look at the code?

edit: It looks like somehow the front sentinel will NOT point to the back sentinel... no matter what I do. But the back sentinel points to the front just fine.

Is this a singly linked list? Why would the back or front nodes be pointing to each other? Rewrite the code that deals with keeping the front node pointing to the correct place. Also, you should post code for this.
 
Is this a singly linked list? Why would the back or front nodes be pointing to each other? Rewrite the code that deals with keeping the front node pointing to the correct place. Also, you should post code for this.

Doubly.

And for school sort of so I don't want to just post the code.

Anyway I fixed it... somehow. Not really clear on why my changes worked, but I got it to work so I'll study up on it.
 
C is so whacky sometimes.

Having to initialize variables before using them in for loops!

I've yet to look into Rust, but C has the best syntax I've used to date. There's no fluff and it almost feels magical in a world of events, properties, exceptions, polymorphism, etc. I'm thankful for all those advances, but it doesn't feel like there's a language out there that's the new "C" yet.

Initializing values was one of the things I hated because it felt like I was writing a lot of unnecessary stuff until I realized a lot of these commands are getting converted into straight assembly. Now I love it.
 

Somnid

Member
I've yet to look into Rust, but C has the best syntax I've used to date. There's no fluff and it almost feels magical in a world of events, properties, exceptions, polymorphism, etc. I'm thankful for all those advances, but it doesn't feel like there's a language out there that's the new "C" yet.

Initializing values was one of the things I hated because it felt like I was writing a lot of unnecessary stuff until I realized a lot of these commands are getting converted into straight assembly. Now I love it.

edit: didn't mean to post that.
 

Yeoman

Member
A question about vectors and memory management in C++.
I have a vector that stores pointers to objects. I've declared it like this:
Code:
std::vector<MyClass *> myVector;
// I add three elements to it:
myVector.push_back (new MyClass(att1, att2));
myVector.push_back (new MyClass(att1, att2));
myVector.push_back (new MyClass(att1, att2));
Say I want to delete one element from it. I thought I was doing it correctly but I'm not 100% sure.
I assumed it was just like this:
Code:
// Erase first element:
std::vector<MyClass *>::iterator iterator;
iterator = MyVector.begin();
delete *iterator;
myVector.erase (myVector.begin()+0);
Is this incorrect?
 
I feel like I'm getting some reeeaally weird results.

So I have to use the time/inputs to calculate the complexity of this algorithim.

The algorithm is simple:

Code:
int containsDynArr(DynArr *v, int val)
{
	int x;
	for (x=0; x < v->size; x++) 
	{
		if (v->data[x] == val)
		{
			return 1;
		}
	}
	return 0;

We make a dynamic array that is filled with 2^10, 2^11.... 2^18th values. Then the code will run contains on each value.

Code:
	for (int i = 0; i < numElements; i++)
	{
		containsDynArr(a, i);
	}

So I expected this to be O(n) complexity because you know, worst case we loop over every element once and find nothing. That's N elements.

But nope. I'm getting O(n^2) complexity.

Time for running contains() on 32768 elements: 18450 ms
Time for running contains() on 65536 elements: 73640 ms
Time for running contains() on 131072 elements: 294110 ms

Comparing 131072 elements to 65536, we see that a doubling in the number of elements results in a quadrupling of time. This means it is O(n^2) complexity, right?

I find that odd. Why isn't it O(n)?

edit: Let me guess, it is actually measuring the time of running contains on each element. So we loop N number of times, and each loop requires (worst case) looping over N elements as well. It isn't measuring the complexity of contains() but the complexity of running contains() N number of times?
 

TheSeks

Blinded by the luminous glory that is David Bowie's physical manifestation.
Code:
function pal(str) {
str.toLowerCase();
return str;
}

pal("Eye");

Works.

But if I want to modify that method:

Code:
function pal(str) {
str.toLowerCase().replace(str, 'wat');
}

pal("Eye");

Don't work? It just lowercases ("eye")??????

They're both string methods. Shouldn't replace work? AFAIK my arguments are correct? I want it to find str/("Eye") and replace it it with 'wat' but it won't find str/argument?

Looking at MDN: I need to make a new variable to replace the string/argument I want to check and replace?
 
Code:
function pal(str) {
str.toLowerCase();
return str;
}

pal("Eye");

Works.

But if I want to modify that method:

Code:
function pal(str) {
str.toLowerCase().replace(str, 'wat');
}

pal("Eye");

Don't work? It just lowercases ("eye")??????

They're both string methods. Shouldn't replace work? AFAIK my arguments are correct? I want it to find str/("Eye") and replace it it with 'wat' but it won't find str/argument?

Looking at MDN: I need to make a new variable to replace the string/argument I want to check and replace?
The string "eye" doesn't contain "Eye", though. Case matters.

Also, your second function lacks a return statement. And unless toLowerCase() actually modifies the string (usually such a function would return a new string), your first function doesn't do anything other than simply return the unaltered parameter.
 

TheSeks

Blinded by the luminous glory that is David Bowie's physical manifestation.
The string "eye" doesn't contain "Eye", though. Case matters.

Also, your second function lacks a return statement. And unless toLowerCase() actually modifies the string (usually such a function would return a new string), your first function doesn't do anything other than simply return the unaltered parameter.

So, I'm supposed to do the replacement on the str argument first over .toLowerCase?

Ugh. You'd think it'd be straight forward. "I want you to make the entire string lowercase then replace the string while keeping it lowercase. " Guess not. :/
 
edit: Let me guess, it is actually measuring the time of running contains on each element. So we loop N number of times, and each loop requires (worst case) looping over N elements as well. It isn't measuring the complexity of contains() but the complexity of running contains() N number of times?

Yes, exactly. If you unroll the code you wrote, you're essentially doing the following:
Code:
for (int i = 0; i < numElements; i++)
{
    for (x=0; x < v->size; x++) 
    {
        if (v->data[x] == i)
        {
            // ...
	}
    }
}
Which means, you're doing v->size * numElements operations, which is N^2,
 

Zeus7

Member
Hi, I am looking for some help with building an app for the childrens football team which I coach.

I have a players database table:

Code:
player_id   int    auto_increment
image        blob
name        varchar
position     varchar

I have managed to get my app to add players to the app, however, I am having a fair bit of trouble displaying the players in a Custom ListView with Images using RecyclerView and Volley.

I have been following a tutorial called 'Android Custom ListView with Images using RecyclerView and Volley' by Belal Khan but he does not seem to include a .php file which would work for me to retrieve.

My code is:

Players
Code:
public class Players extends BaseActivity {
    //Creating a List of players
    private List<PlayersGetSet> listPlayers;

    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private RecyclerView.Adapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // substantiate nav drawer
        setContentView(R.layout.activity_players);
        setNavDrawer(new MainNavDrawer(this));

        //Initializing Views
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        //Initializing our players list
        listPlayers = new ArrayList<>();

        //Calling method to get data
        getData();

    }

    private void getData() {
        //Showing a progress dialog
        final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);

        //Creating a json array request
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        //Dismissing progress dialog
                        loading.dismiss();

                        //calling method to parse json array
                        parseData(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        loading.dismiss();
                    }
                });

        //Creating request queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

        //Adding request to the queue
        requestQueue.add(jsonArrayRequest);
    }

    //This method will parse json data
    private void parseData(JSONArray array){
        for(int i = 0; i<array.length(); i++) {
            PlayersGetSet players = new PlayersGetSet();
            JSONObject json = null;
            try {
                json = array.getJSONObject(i);
                players.setImageUrl(json.getString(Config.KEY_IMAGE));
                players.setName(json.getString(Config.KEY_NAME));
                players.setPosition(json.getString(Config.KEY_POSITION));


            } catch (JSONException e) {
                e.printStackTrace();
            }
            listPlayers.add(players);
        }

        //Finally initializing our adapter
        adapter = new CardAdapter(listPlayers, this);

        //Adding adapter to recyclerview
        recyclerView.setAdapter(adapter);
    }
}

PlayersGetSet
Code:
public class PlayersGetSet {
    private String image;
    private String name;
    private String position;

    //Getters and Setters
    public String getImageUrl() {
        return image;
    }

    public void setImageUrl(String image) {
        this.image = image;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPosition() {
        return position;
    }

    public void setPosition(String position) {
        this.position = position;
    }

Custom Volley Request
Code:
public class CustomVolleyRequest {
    private static CustomVolleyRequest customVolleyRequest;
    private static Context context;
    private RequestQueue requestQueue;
    private ImageLoader imageLoader;

    private CustomVolleyRequest(Context context) {
        this.context = context;
        this.requestQueue = getRequestQueue();

        imageLoader = new ImageLoader(requestQueue,
                new ImageLoader.ImageCache() {
                    private final LruCache<String, Bitmap>
                            cache = new LruCache<String, Bitmap>(20);

                    @Override
                    public Bitmap getBitmap(String url) {
                        return cache.get(url);
                    }

                    @Override
                    public void putBitmap(String url, Bitmap bitmap) {
                        cache.put(url, bitmap);
                    }
                });
    }

    public static synchronized CustomVolleyRequest getInstance(Context context) {
        if (customVolleyRequest == null) {
            customVolleyRequest = new CustomVolleyRequest(context);
        }
        return customVolleyRequest;
    }

    public RequestQueue getRequestQueue() {
        if (requestQueue == null) {
            Cache cache = new DiskBasedCache(context.getCacheDir(), 10 * 1024 * 1024);
            Network network = new BasicNetwork(new HurlStack());
            requestQueue = new RequestQueue(cache, network);
            requestQueue.start();
        }
        return requestQueue;
    }

    public ImageLoader getImageLoader() {
        return imageLoader;
    }
}

Card Adapter
Code:
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {

    private ImageLoader imageLoader;
    private Context context;

    //List of players
    List<PlayersGetSet> players;

    public CardAdapter(List<PlayersGetSet> players, Context context){
        super();
        //Getting all the players
        this.players = players;
        this.context = context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.players_list, parent, false);
        ViewHolder viewHolder = new ViewHolder(v);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        PlayersGetSet player =  players.get(position);

        imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
        imageLoader.get(player.getImageUrl(), ImageLoader.getImageListener(holder.imageView, R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert));

        holder.imageView.setImageUrl(player.getImageUrl(), imageLoader);
        holder.textViewName.setText(player.getName());
        holder.textViewRank.setText(String.valueOf(player.getPosition()));
    }

    @Override
    public int getItemCount() {
        return players.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder{
        public NetworkImageView imageView;
        public TextView textViewName;
        public TextView textViewRank;

        public ViewHolder(View itemView) {
            super(itemView);
            imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewPlayer);
            textViewName = (TextView) itemView.findViewById(R.id.textViewName);
            textViewRank= (TextView) itemView.findViewById(R.id.textViewPosition);
        }
    }
}

PHP
Code:
<?php

 if($_SERVER['REQUEST_METHOD']=='GET'){
	 
 $id = $_GET['player_id'];
 
 require_once('dbConnect.php');
 
 $sql = "select * from players where player_id = '$id'";
 
 $r = mysqli_query($con,$sql);
 
 $res = mysqli_fetch_array($r);
 
 $result = array();
 

 array_push($result,array(
 "image"=>$res['image'],
 "name"=>$res['name'],
 "position"=>$res['position']
 )
 );
 
 echo json_encode(array("result"=>$result));
 
 mysqli_close($con);
 
 }


In my Players class, the getData() method, the Response I am getting is
"Java type String cannot be converted to array"

I would really appreciate any help with getting this to work. Thanks.
 

Zeus7

Member
You should post the stack trace.

Do I run the app in debug for this and then just copy and paste or does Android Studio have an option to save it in a file?

Edit:

Code:
04-21 11:52:41.940 32309-32309/? E/Zygote: v2
04-21 11:52:41.940 32309-32309/? E/Zygote: accessInfo : 0
04-21 11:52:43.650 32309-32535/com.android.matty.blairgowrie2006 E/GMPM: getGoogleAppId failed with status: 10
04-21 11:52:43.650 32309-32535/com.android.matty.blairgowrie2006 E/GMPM: Uploading is not possible. App measurement disabled
04-21 11:53:03.300 32309-32309/com.android.matty.blairgowrie2006 E/RecyclerView: No adapter attached; skipping layout
04-21 11:53:03.350 32309-32309/com.android.matty.blairgowrie2006 E/RecyclerView: No adapter attached; skipping layout
04-21 11:53:03.380 32309-32309/com.android.matty.blairgowrie2006 E/RecyclerView: No adapter attached; skipping layout
04-21 11:53:04.580 32309-32309/com.android.matty.blairgowrie2006 E/ViewRootImpl: sendUserActionEvent() mView == null


The response error I am getting is:

Code:
  com.android.volley.ParseError: org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONArray
 

dabig2

Member
The response error I am getting is:

Code:
  com.android.volley.ParseError: org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONArray

Usually get these errors if the URL is incorrect or that the data you get back from the server is not json formatted. For example, there could be erroneous characters at the beginning of the file and so your json parser just immediately dies. Can you print the contents of the entire json object?
 

Zeus7

Member
Usually get these errors if the URL is incorrect or that the data you get back from the server is not json formatted. For example, there could be erroneous characters at the beginning of the file and so your json parser just immediately dies. Can you print the contents of the entire json object?

Thanks for the reply.

Here is the current error:

Code:
com.android.volley.ParseError: org.json.JSONException:
Value{"result":[{"image": *MASSIVELY LONG STRING OF CHARACTERS HERE*","name":"Tam","position":"GK"}]}
of type org.json.JSONObject cannot be converted to JSONArray
 

dabig2

Member
Thanks for the reply.

Here is the current error:

Code:
com.android.volley.ParseError: org.json.JSONException:
Value{"result":[{"image": *MASSIVELY LONG STRING OF CHARACTERS HERE*","name":"Tam","position":"GK"}]}
of type org.json.JSONObject cannot be converted to JSONArray

Cools, thanks. So from this it is getting data correctly from the server. This error pretty much states that you don't have the JSONArray yet. You need to directly grab the array from the object. In your case, that would be "result".
Code:
JSONArray array = responseObject.getJSONArray("result");
 

Zeus7

Member
Cools, thanks. So from this it is getting data correctly from the server. This error pretty much states that you don't have the JSONArray yet. You need to directly grab the array from the object. In your case, that would be "result".
Code:
JSONArray array = responseObject.getJSONArray("result");

Thanks! I am trying this code but the error is saying it cannot convert the JSON array (int) to a String ("result")
 
Man, I didn't realize how well designed language grammars could be.

Code:
type 'a Transaction =
    | NoConnection
    | InvalidKey of string
    | Timeout
    | NoItemForKey
    | Ok of 'a

// Pretend there is a function that takes
// a DB of 'a and a key and returns a Transaction

let findKeyInDB default key db =
    match DB.find key db with
    | NoConnection -> failwith "No connection"
    | Ok a -> a
    | _ -> default

let getStringOrDefault (db: string DB) =
    let findKey = findKeyInDB "" in
    let s1 = findKey "1" db in
    let s2 = findKey "2" db in
    String.concat s1 s2
How many of you could tell from reading that, that the language I used was not indentation significant like Python?
 

Zeus7

Member
Cools, thanks. So from this it is getting data correctly from the server. This error pretty much states that you don't have the JSONArray yet. You need to directly grab the array from the object. In your case, that would be "result".
Code:
JSONArray array = responseObject.getJSONArray("result");

This is where I currently am at:

I have changed jsonArrayRequest to StringRequest. I now am having trouble with parseData and getting it to accept a string input.

Code:
private void getData() {
        //Showing a progress dialog
        final ProgressDialog loading = ProgressDialog.show(this, "Loading Players", "Please wait...", false, false);

        //Creating a json array request
        //TODO - CREATE JSONObjectRequest or StringRequest instead
        // Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.GET, Config.DATA_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        //Dismissing progress dialog
                        loading.dismiss();
                        //calling method to parse json array
                        parseData(response);

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // we are getting a parse error
                Toast bread = Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG);
                bread.show();
            }
        });

        /*JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        //Dismissing progress dialog
                        loading.dismiss();

                        // JSONArray array = response.getJSONArray("result");

                        //calling method to parse json array
                        parseData(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // we are getting a parse error
                        Toast bread = Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG);
                        bread.show();
                    }
                }); */

                //Creating request queue
                RequestQueue requestQueue = Volley.newRequestQueue(this);

        //Adding request to the queue
        requestQueue.add(stringRequest);
    }

Code:
    //This method will parse json data
    private void parseData(JSONArray array){
        for(int i = 0; i<array.length(); i++) {
            PlayersGetSet players = new PlayersGetSet();
            JSONObject json = null;
            try {
                json = array.getJSONObject(i);
                players.setImageUrl(json.getString(Config.KEY_IMAGE));
                players.setName(json.getString(Config.KEY_NAME));
                players.setPosition(json.getString(Config.KEY_POSITION));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            listPlayers.add(players);
        }

        //Finally initializing our adapter
        adapter = new CardAdapter(listPlayers, this);

        //Adding adapter to recyclerview
        recyclerView.setAdapter(adapter);
    }
 

Koren

Member
Man, I didn't realize how well designed language grammars could be.

How many of you could tell from reading that, that the language I used was not indentation significant like Python?
Functional languages grammar are just awful when you want to indent them properly.

Sometime, I wish indentation would prevent me from using countless begin/end (or forgetting one in a nested match with strange results) but there's so many nested definitions in some functions that it just wouldn't work well.

I just can't stick to strict indentation rules when writing ML. There's always a function where it gets out of hand, even with 2-spaces indentation (functional languages are the only ones where I use 2-spaces)

Edit : and I still don't know where I should put the "in"... at the beginning of a line or at the end of the previous one...
 
Functional languages grammar are just awful when you want to indent them properly.
I have had way more problems indenting imperative c code because of the constant tension between tersity and readability. In ml I typically get both.

Sometime, I wish indentation would prevent me from using countless begin/end (or forgetting one in a nested match with strange results) but there's so many nested definitions in some functions that it just wouldn't work well.
Begin end is just redundant syntax for ( ) in OCaml. Don't use it!

Match multiple values at once to avoid nested match!

Break up nested definitions into sequential ones!

I just can't stick to strict indentation rules when writing ML. There's always a function where it gets out of hand, even with 2-spaces indentation (functional languages are the only ones where I use 2-spaces)
I typically use four spaces but I understand 2 spaces is common. I have never had right-creep be problematic in ML, but I have had it happen in Haskell (very often). The lack of significant indentation is very helpful in this regard. There are also a lot of conventions that reduce indentation, such as

Code:
if condition then expr else
more code;
more code;
...

Which resembles "guard" in swift.

Edit : and I still don't know where I should put the "in"... at the beginning of a line or at the end of the previous one...
That's probably the simplest rule there is. Always at the end of a let line, unless you want to distinguish the result value after a long series of let bindings.

And if you are truly unopinionated about formatting, just use a formatting tool. Press tab -> magic.
 

dabig2

Member
Thanks! I am trying this code but the error is saying it cannot convert the JSON array (int) to a String ("result")

This is where I currently am at:

I have changed jsonArrayRequest to StringRequest. I now am having trouble with parseData and getting it to accept a string input.

Hm, unfortunately I'm not too familiar with the Volley API. But looking at this Android dev document real quickly, I see that they have a JsonObjectRequest callback. Have you tried that instead of JSONArray and StringRequest callbacks? I'd hesitate against StringRequest because it seems like you'll need to manually override some inherited method to tell it that the contents of the raw string is formatted as a JSON.

Maybe try something like this:
Code:
JsonObjectRequest jsonObjRequest = new JsonObjectRequest(Request.Method.GET, Config.DATA_URL, null,
                new Response.Listener<JSONObject>() {
                    @Override
                   public void onResponse(JSONObject response){
                        //Dismissing progress dialog
                        loading.dismiss();

                         //print out response and confirm that you are receiving a valid response
                        JSONArray array = response.getJSONArray("result");
                        //print out array here to confirm that it now has contents of "result"
                        
                        //calling method to parse json array
                        parseData(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // we are getting a parse error
                        Toast bread = Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG);
                        bread.show();
                    }
                });
 

Koren

Member
I have had way more problems indenting imperative c code because of the constant tension between tersity and readability. In ml I typically get both.
To each its own, I guess...

Begin end is just redundant syntax for ( ) in OCaml. Don't use it!
OCaml guidelines ask for begin...end instead of ()
How to delimit constructs in programs

When it is necessary to delimit syntactic constructs in programs, use as delimiters the keywords begin and end rather than parentheses.
and I agree, I think that in many cases, it's just unreadable with ()

Match multiple values at once to avoid nested match!
Well, when it's possible, I'll do this, but there's several cases where it's just impossible (or would result in a lot of "when ..." constructs, which seems worse to me)

Break up nested definitions into sequential ones!
When they depend on each others, that's not a solution...

That's probably the simplest rule there is. Always at the end of a let line, unless you want to distinguish the result value after a long series of let bindings.
For normal definitions, that's my take, but when I'm having local functions, things get really messier.
 
What the fuck kind of pointless homework assignment is this....

write a function that reverses the direction of a circularly linked list.... why...

just traverse it in reverse fuckin order.
 
OCaml guidelines ask for begin...end instead of ()

and I agree, I think that in many cases, it's just unreadable with ()
Okay, true. That's unfortunate. What are you asking for, though? Braces?

Well, when it's possible, I'll do this, but there's several cases where it's just impossible (or would result in a lot of "when ..." constructs, which seems worse to me)
I believe you. But my experience is still that my code is a lot shorter, less indented, and easier to read in languages like OCaml or F#.

When they depend on each others, that's not a solution...
Huh? Why not let rec . . . and ?

For normal definitions, that's my take, but when I'm having local functions, things get really messier.
I still leave it at the end of the line.

But look, I can't discount your personal experience. I'm sorry you've had such headaches with it. :(
 

Hylian7

Member
I debated putting this in the "Applying for jobs is soul crushing and exhausting" thread, but I decided it made more sense to put it here.

I've got an interview that I'm particularly excited about coming up in the near future, and I have a question based on it and past interviews I have had.

Whenever they do whiteboarding, or ask you some kind of "thought" programming question, how quickly should you be able to crank out the code for it? Is it common to erase things and fix it as you are writing it? In some of my interviews I have felt kind of stupid because I had to sit there and think for a few seconds before writing something, whether that question was something like a Fibonacci algorithm, sorting algorithm, or whatever.

I guess what I'm asking is, should it be expected for you to immediately belt out code if someone said "Mergesort, go!", or is it fine if it takes you a minute, but you understand how Mergesort (or whatever the question is about) works?

Granted, I have had interviews where I have had to do this, or they might address a problem in my code and I fix it, or I don't know what they are getting at, and those interviews have been successful (either a job offer, or getting another interview).

I'm trying to prepare as well as I can for this interview I have coming up, but I'm just worried that I will miss something and blank out on it.
 

hateradio

The Most Dangerous Yes Man
This is where I currently am at:

I have changed jsonArrayRequest to StringRequest. I now am having trouble with parseData and getting it to accept a string input.

[snip]
Can you use Jakson in Android? I would just create some models that replicate the JSON structure and use it to map it automatically.

I hate dealing with anything else, unless it's a simple structure and using Java 8.
 

Koren

Member
I believe you. But my experience is still that my code is a lot shorter, less indented, and easier to read in languages like OCaml or F#.
Depending on what you're writing, a lot shorter, I'll give you that.

I wrote solutions of a couple of assignments in Caml, and decided to write them both in functionnal and iterative styles, the second ones were indeed longer and with more complex indentation.

Huh? Why not let rec . . . and ?
Because you can't use a function call in the right hand of a let rec to statically prevent recursive definitions that could trigger a bus error.

But in fact, it's even harder in my situation, but I can't fault OCaml. I have to use Caml Light, and it forbids even a constant declaration in the right hand side of a let rec, like in:
Code:
let rec a = 2 and f = function 0 -> 1 | x -> a* (f (x-1)) in f 5;;

(correct in OCaml, but forbidden in Caml Light)

But look, I can't discount your personal experience. I'm sorry you've had such headaches with it. :(
Well, that's not THAT bad... And I probably wouldn't think so much about it if I was only writing code for myself (or experienced programmers).

The issue is that I *teach* it. So I keep wondering what will be the best for students. And I find difficult to abide to a set of rules.

The students are already doing such awful and unreadable things that I have to do my best to keep their heads as tidy as I can ^_^ (honestly, I think reading beginners code is ten times harder in Caml than in Python, C, Ada, Pascal, assembly (!) or even Java)

Let's take a basic example, dichotomy to find the index of an element in a vect:
Code:
let Index elem v =
  let rec Aux = fun
    | a b when a>b -> failwith "Not found"
    | a b -> let c = (a+b)/2 in
           if v.(c) = elem then c else
           if v.(c) > elem then (Aux a (c-1)) else
           (Aux (c+1) b)
  in Aux 0 (vect_length v - 1);;

For the in placement, I usually stick to the rule "if I can put it at the end of the let... line, I'll place it there, or else, I'll put it at the beginning of a line, aligned with the matching let". Usually, it works (like above), although there's a couple situation where it's becoming a bit akward (for example, when the in at the beginning of the line is followed by a let or a match, I don't know how to indent the following lines)

In the above example, though:
- I don't know where I should place the "if"s. I'm not that fond of putting them far to the left of let, and putting it 2/4 spaces to the right is unusable.
- in the case of multiple branches tests, guidelines suggest to align the "if"s. Suits me (although whether there's a "else" at the end of the previous line or not makes things hazardous) but I'm not that fond of aligning the last consequence with the ifs.

Definitively no big deal, but on too many occasions I wonder what would be the best solution.

And yes, I know I could write, in this case, for example
Code:
let Index elem v =
  let rec Aux a b = let c=(a+b)/2 in match a, b, c with
    | a, b, _ when a > b        -> failwith "Not found"
    | _, _, c when v.(c) = elem -> c
    | a, _, c when v.(c) > elem -> Aux a (c-1)
    | _, b, c                   -> Aux (c+1) b
  in Aux 0 (vect_length v - 1);;
which solve neatly most of the issues above (except maybe where you should put the in match)... I just don't have trickier cases on hand currently. Besides, it's slightly more difficult to write the second solution than the first, starting from the algorithm itself, for beginners.
 

Kalnos

Banned
I'm trying to prepare as well as I can for this interview I have coming up, but I'm just worried that I will miss something and blank out on it.

If an interviewer judges you harshly for taking a few minutes / realizing your own mistake and erasing something then you probably don't want to work there because they're a cunt to be honest. I think you should make sure to explain what you're doing and try to have an open dialog with the interviewer so they understand your thought process, that seems like the most important thing.
 
Trying to figure out where to go next. This summer I will have what looks to be a painfully simple internship at a decent computer science company doing something involving html, adding content to the website, and hopefully some javascript. This is my last summer before being done with college (I graduate in December) and I am looking to learn something on the side of my internship.

The last few years of my life have had me working in web dev stuff (specifically front end). And I generally enjoy that and kind of want to pursue that at a specific company in town. On the other hand, my girlfriend wants me to move with her to Germany and I saw that there are some cool game developers located there and obviously gaming is a passion of mine.

If I had to break down my interests of what to do after I graduate at this point, it is:
50% Web Dev
25% Game Dev
15% Misc. OOP type work
10% Android App Development

Any recommendations for what I should pick up on the side this summer? I am worried about picking the wrong one and hurting my chances at getting a job in the other field. Or is that not a big issue?
 

Ledbetter

Member
Applied for my first internship at a local startup. The first step was a Hacker Rank 1 hour test with 9 questions from DB queries, MVC code (which I know nothing about and they never said something about web-dev), a problem which my solution didn't get the right answers for half of the test cases and the rest were questions with multiple options.

Depending on how I did the test they'll decide if I get onto a phone interview and then an on-site interview. Is this normal for internship positions?

It sucks, because the test made me feel like I know nothing, and where I live there are not so much internship positions, with most of them being for web development (on PHP).

Any recommendations for what I should pick up on the side this summer? I am worried about picking the wrong one and hurting my chances at getting a job in the other field. Or is that not a big issue?

When does she want to move to Germany? I think that involves more of a life decision than a career one. I can't speak from experience about the chances of getting a job in another field, but I think for web development, you can build a portfolio to show people that you can do front-end, depending of previous career experience.
 
Top Bottom