Search Results

Search found 22043 results on 882 pages for 'int ua'.

Page 8/882 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • nul terminating a int array

    - by robUK
    Hello, gcc 4.4.4 c89 I was just experimenting with a int array. And something just came to my mind. Can I nul terminate it. For example, I am using a 0 to nul terminate. However, 0 could well be a valid value in this array. The code below will terminate after the 5. Even though I mean 0 to be a valid number. However, I could specify the size of the array. But in this case, I don't want to this as I am just interested in this particular problem. Many thanks for any advice, #include <stdio.h> static void test(int *p); int main(void) { int arr[] = {30, 450, 14, 5, 0, 10, '\0'}; test(arr); return 0; } static void test(int *p) { while(*p) { printf("Array values [ %d ]\n", *p++); } }

    Read the article

  • Predicate<INT> match question

    - by Petr
    Hi, I do not understand how following code works. Specifically, I do not understand using of "return i<3". I would expect return i IF its < than 3. I always though that return just returns value. I could not even find what syntax is it. Second question, it seems to me like using anonymous method (delegate(int i)) but could be possible to write it with normal delegate pointing to method elsewere? Thanks List<int> listOfInts = new List<int> { 1, 2, 3, 4, 5 }; List<int> result = listOfInts.FindAll(delegate(int i) { return i < 3; });

    Read the article

  • convert int to string for use in allegro function

    - by ace
    I am trying to run the following code using allegro. textout_ex(screen, font, numbComments , 100, 100, GREEN, BLACK); numbComments is an integer, the function prototype of this function is void textout_ex(BITMAP *bmp, const FONT *f, const char *s, int x, int y, int color, int bg); and i cannot, according to my understanding pass this integer in the third position. I therefore need to convert the integer into a string. I did it like this, but it didnt work. Help please? int score = numbComments; string Str; stringstream out; // YOU MUST INCLUDE <sstream> FOR THIS. out << score; Str = out.str(); and then tried to use the string Str, which didnt work

    Read the article

  • C++ Pointers to functions.

    - by Andy Leman
    using namespace std; int addition (int a, int b) { return (a+b); } int subtraction (int a, int b) { return (a-b); } int operation (int x, int y, int (*functocall)(int,int)) { int g; g = (*functocall)(x,y); return(g); } int main() { int m,n; int (*minus)(int,int) = subtraction; m = operation (7,5,addition); n = operation (20,m,minus); cout << n; return 0; } Can anybody explain this line for me int (*minus)(int,int) = subtraction; Thanks a lot!

    Read the article

  • How to concatenate int values in java?

    - by Shamli
    hi, I have the following values: int a=1; int b=0; int c=2; int d=2; int e=1; How do i concatenate these values so that i end up with a String that is 10221; please note that multiplying a by 10000, b by 1000.....and e by 1 will not working since b=0 and therefore i will lose it when i add the values up. Thnks you in advance.

    Read the article

  • Converting c++ string to int

    - by skazhy
    Hi! I have the following data in a c++ string John Doe 01.01.1970 I need to extract the date and time from it into int variables. I tried it like this: int last_space = text_string.find_last_of(' '); int day = int(text_string.substr(last_space + 1, 2)); But I got invalid cast from type ‘std::basic_string’ to type ‘int’. When I extract the "John Doe" part in another string variable, all works fine. What's wrong? I am trying to compile it with g++ -Wall -Werror.

    Read the article

  • Why is Spritebatch drawing my Textures out of order?

    - by Andrew
    I just started working with XNA Studio after programming 2D games in java. Because of this, I have absolutely no experience with Spritebatch and sprite sorting. In java, I could just layer the images by calling the draw methods in order. For a while, my Spritebatch was working fine in deferred sorting mode, but when I made a change to one of my textures, it suddenly started drawing them out of order. I have searched for a solution to this problem, but nothing seems to work. I have tried adding layer depths to the sprites and changing the sort mode to BackToFront or FrontToBack or even immediate, but nothing seems to work. Here is my drawing code: protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Gray); Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); for (int x = 0; x < 5; x++) { for (int y = 0; y < 5; y++) { region[x, y].draw(((float)w / aw)); // Draws the Tile-Based background } } player.draw(spriteBatch, ((float)w / aw));//draws the character (This method is where the problem occurs) enemy.draw(spriteBatch, (float)w/aw); // draws a basic enemy Game1.spriteBatch.End(); base.Draw(gameTime); } player.draw method: public void draw(SpriteBatch sb, float ratio){ //draws the player base (The character without hair or equipment) sb.Draw(playerbase[0], new Rectangle((int)(pos.X - (24 * ratio)), (int)(pos.Y - (48 * ratio)), (int)(48 * ratio), (int)(48 * ratio)), new Rectangle(orientation * 48, animFrame * 48, 48, 48), Color.White,0,Vector2.Zero,SpriteEffects.None,0); //draws the player's hair sb.Draw(playerbase[3], new Rectangle((int)(pos.X - (24 * ratio)), (int)(pos.Y - (48 * ratio)), (int)(48 * ratio), (int)(48 * ratio)), new Rectangle(orientation * 48, animFrame * 48, 48, 48), Color.White, 0, Vector2.Zero, SpriteEffects.None, 0); //draws the player's shirt sb.Draw(equipment[0], new Rectangle((int)(pos.X - (24 * ratio)), (int)(pos.Y - (48 * ratio)), (int)(48 * ratio), (int)(48 * ratio)), new Rectangle(orientation * 48, animFrame * 48, 48, 48), Color.White, 0, Vector2.Zero, SpriteEffects.None, 0); //draws the player's pants sb.Draw(equipment[1], new Rectangle((int)(pos.X - (24 * ratio)), (int)(pos.Y - (48 * ratio)), (int)(48 * ratio), (int)(48 * ratio)), new Rectangle(orientation * 48, animFrame * 48, 48, 48), Color.White, 0, Vector2.Zero, SpriteEffects.None, 0); //draws the player's shoes sb.Draw(equipment[2], new Rectangle((int)(pos.X - (24 * ratio)), (int)(pos.Y - (48 * ratio)), (int)(48 * ratio), (int)(48 * ratio)), new Rectangle(orientation * 48, animFrame * 48, 48, 48), Color.White, 0, Vector2.Zero, SpriteEffects.None, 0); } the game has a top-down perspective much like the early legend of zelda games. It draws sections of the texture depending on which direction the character is facing and the animation frame. However, instead of drawing the character in the order the draw methods are called, it ends up drawing the character out of order. Please help me with this problem.

    Read the article

  • Casting interfaces in java

    - by owca
    I had two separate interfaces, one 'MultiLingual' for choosing language of text to return, and second 'Justification' to justify returned text. Now I need to join them, but I'm stuck at 'java.lang.ClassCastException' error. Class Book is not important here. Data.length and FormattedInt.width correspond to the width of the line. The code : public interface MultiLingual { static int ENG = 0; static int PL = 1; String get(int lang); int setLength(int length); } class Book implements MultiLingual { private String title; private String publisher; private String author; private int jezyk; public Book(String t, String a, String p, int y){ this(t, a, p, y, 1); } public Book(String t, String a, String p, int y, int lang){ title = t; author = a; publisher = p; jezyk = lang; } public String get(int lang){ jezyk = lang; return this.toString(); } public int setLength(int i){ return 0; } @Override public String toString(){ String dane; if (jezyk == ENG){ dane = "Author: "+this.author+"\n"+ "Title: "+this.title+"\n"+ "Publisher: "+this.publisher+"\n"; } else { dane = "Autor: "+this.author+"\n"+ "Tytul: "+this.title+"\n"+ "Wydawca: "+this.publisher+"\n"; } return dane; } } class Data implements MultiLingual { private int day; private int month; private int year; private int jezyk; private int length; public Data(int d, int m, int y){ this(d, m, y, 1); } public Data(int d, int m, int y, int lang){ day = d; month = m; year = y; jezyk = lang; } public String get(int lang){ jezyk = lang; return this.toString(); } public int setLength(int i){ length = i; return length; } @Override public String toString(){ String dane=""; String miesiac=""; String dzien=""; switch(month){ case 1: miesiac="January"; case 2: miesiac="February"; case 3: miesiac="March"; case 4: miesiac="April"; case 5: miesiac="May"; case 6: miesiac="June"; case 7: miesiac="July"; case 8: miesiac="August"; case 9: miesiac="September"; case 10: miesiac="October"; case 11: miesiac="November"; case 12: miesiac="December"; } if(day==1){ dzien="st"; } if(day==2 || day==22){ dzien="nd"; } if(day==3 || day==23){ dzien="rd"; } else{ dzien="th"; } if(jezyk==ENG){ dane =this.day+dzien+" of "+miesiac+" "+this.year; } else{ dane = this.day+"."+this.month+"."+this.year; } return dane; } } interface Justification { static int RIGHT=1; static int LEFT=2; static int CENTER=3; String justify(int just); } class FormattedInt implements Justification { private int liczba; private int width; private int wyrownanie; public FormattedInt(int s, int i){ liczba = s; width = i; wyrownanie = 2; } public String justify(int just){ wyrownanie = just; String wynik=""; String tekst = Integer.toString(liczba); int len = tekst.length(); int space_left=width - len; int space_right = space_left; int space_center_left = (width - len)/2; int space_center_right = width - len - space_center_left -1; String puste=""; if(wyrownanie == LEFT){ for(int i=0; i<space_right; i++){ puste = puste + " "; } wynik = tekst+puste; } else if(wyrownanie == RIGHT){ for(int i=0; i<space_left; i++){ puste = puste + " "; } wynik = puste+tekst; } else if(wyrownanie == CENTER){ for(int i=0; i<space_center_left; i++){ puste = puste + " "; } wynik = puste + tekst; puste = " "; for(int i=0; i< space_center_right; i++){ puste = puste + " "; } wynik = wynik + puste; } return wynik; } } And the test code that shows this casting "(Justification)gatecrasher[1]" which gives me errors : MultiLingual gatecrasher[]={ new Data(3,12,1998), new Data(10,6,1924,MultiLingual.ENG), new Book("Sekret","Rhonda Byrne", "Nowa proza",2007), new Book("Tuesdays with Morrie", "Mitch Albom", "Time Warner Books",2003, MultiLingual.ENG), }; gatecrasher[0].setLength(25); gatecrasher[1].setLength(25); Justification[] t={ new FormattedInt(345,25), (Justification)gatecrasher[1], (Justification)gatecrasher[0], new FormattedInt(-7,25) }; System.out.println(" 10 20 30"); System.out.println("123456789 123456789 123456789"); for(int i=0;i < t.length;i++) System.out.println(t[i].justify(Justification.RIGHT)+"<----\n");

    Read the article

  • Performance: float to int cast and clipping result to range

    - by durandai
    I'm doing some audio processing with float. The result needs to be converted back to PCM samples, and I noticed that the cast from float to int is surprisingly expensive. Whats furthermore frustrating that I need to clip the result to the range of a short (-32768 to 32767). While I would normally instictively assume that this could be assured by simply casting float to short, this fails miserably in Java, since on the bytecode level it results in F2I followed by I2S. So instead of a simple: int sample = (short) flotVal; I needed to resort to this ugly sequence: int sample = (int) floatVal; if (sample > 32767) { sample = 32767; } else if (sample < -32768) { sample = -32768; } Is there a faster way to do this? (about ~6% of the total runtime seems to be spent on casting, while 6% seem to be not that much at first glance, its astounding when I consider that the processing part involves a good chunk of matrix multiplications and IDCT) EDIT The cast/clipping code above is (not surprisingly) in the body of a loop that reads float values from a float[] and puts them into a byte[]. I have a test suite that measures total runtime on several test cases (processing about 200MB of raw audio data). The 6% were concluded from the runtime difference when the cast assignment "int sample = (int) floatVal" was replaced by assigning the loop index to sample. EDIT @leopoldkot: I'm aware of the truncation in Java, as stated in the original question (F2I, I2S bytecode sequence). I only tried the cast to short because I assumed that Java had an F2S bytecode, which it unfortunately does not (comming originally from an 68K assembly background, where a simple "fmove.w FP0, D0" would have done exactly what I wanted).

    Read the article

  • int, short, byte performance in back-to-back for-loops

    - by runrunraygun
    (background: http://stackoverflow.com/questions/1097467/why-should-i-use-int-instead-of-a-byte-or-short-in-c) To satisfy my own curiosity about the pros and cons of using the "appropriate size" integer vs the "optimized" integer i wrote the following code which reinforced what I previously held true about int performance in .Net (and which is explained in the link above) which is that it is optimized for int performance rather than short or byte. DateTime t; long a, b, c; t = DateTime.Now; for (int index = 0; index < 127; index++) { Console.WriteLine(index.ToString()); } a = DateTime.Now.Ticks - t.Ticks; t = DateTime.Now; for (short index = 0; index < 127; index++) { Console.WriteLine(index.ToString()); } b=DateTime.Now.Ticks - t.Ticks; t = DateTime.Now; for (byte index = 0; index < 127; index++) { Console.WriteLine(index.ToString()); } c=DateTime.Now.Ticks - t.Ticks; Console.WriteLine(a.ToString()); Console.WriteLine(b.ToString()); Console.WriteLine(c.ToString()); This gives roughly consistent results in the area of... ~950000 ~2000000 ~1700000 which is in line with what i would expect to see. However when I try repeating the loops for each data type like this... t = DateTime.Now; for (int index = 0; index < 127; index++) { Console.WriteLine(index.ToString()); } for (int index = 0; index < 127; index++) { Console.WriteLine(index.ToString()); } for (int index = 0; index < 127; index++) { Console.WriteLine(index.ToString()); } a = DateTime.Now.Ticks - t.Ticks; the numbers are more like... ~4500000 ~3100000 ~300000 Which I find puzzling. Can anyone offer an explanation? NOTE: In the interest of compairing like for like i've limited the loops to 127 because of the range of the byte value type. Also this is an act of curiosity not production code micro-optimization.

    Read the article

  • C++ Template const char array to int

    - by Levi Schuck
    So, I'm wishing to be able to have a static const compile time struct that holds some value based on a string by using templates. I only desire up to four characters. I know that the type of 'abcd' is int, and so is 'ab','abc', and although 'a' is of type char, it works out for a template<int v> struct What I wish to do is take sizes of 2,3,4,5 of some const char, "abcd" and have the same functionality as if they used 'abcd'. Note that I do not mean 1,2,3, or 4 because I expect the null terminator. cout << typeid("abcd").name() << endl; tells me that the type for this hard coded string is char const [5], which includes the null terminator on the end. I understand that I will need to twiddle the values as characters, so they are represented as an integer. I cannot use constexpr since VS10 does not support it (VS11 doesn't either..) So, for example with somewhere this template defined, and later the last line template <int v> struct something { static const int value = v; }; //Eventually in some method cout << typeid(something<'abcd'>::value).name() << endl; works just fine. I've tried template<char v[5]> struct something2 { static const int value = v[0]; } template<char const v[5]> struct something2 { static const int value = v[0]; } template<const char v[5]> struct something2 { static const int value = v[0]; } All of them build individually, though when I throw in my test, cout << typeid(something2<"abcd">::value).name() << endl; I get 'something2' : invalid expression as a template argument for 'v' 'something2' : use of class template requires template argument list Is this not feasible or am I misunderstanding something?

    Read the article

  • fill an array with Int like a Char; C++, cin object

    - by Duknov007
    This is a pretty simple question; first time poster and long time looker. Here is my binary to decimal converter I wrote: #include <iostream> #include <cmath> using namespace std; const int MAX = 6; int conv(int z[MAX], int l[6], int MAX); int main() { int zelda[MAX]; const int d = 6; int link[d]; cout << "Enter a binary number: \n"; int i = 0; while (i < MAX && (cin >> zelda[i]).get()) //input loop { ++i; } cout << conv(zelda, link, MAX); cin.get(); return 0; } int conv(int zelda[MAX], int link[6], int MAX) { int sum = 0; for (int t = 0; t < MAX; t++) { long int h, i; for (int h = 5, i = 0; h >= 0; --h, ++i) if (zelda[t] == 1) link[h] = pow(2.0, i); else link[h] = 0; sum += link[t]; } return sum; } With the way the input loop is being handled, I have to press enter after each input of a number. I haven't added any error correction yet either (and some of my variables are vague), but would like to enter a binary say 111111 instead of 1 enter, 1 enter, 1 enter, etc to fill the array. I am open to any technique and other suggestions. Maybe input it as a string and convert it to an int? I will keep researching. Thanks.

    Read the article

  • socket operation on nonsocket or bad file descriptor

    - by Magn3s1um
    I'm writing a pthread server which takes requests from clients and sends them back a bunch of .ppm files. Everything seems to go well, but sometimes when I have just 1 client connected, when trying to read from the file descriptor (for the file), it says Bad file Descriptor. This doesn't make sense, since my int fd isn't -1, and the file most certainly exists. Other times, I get this "Socket operation on nonsocket" error. This is weird because other times, it doesn't give me this error and everything works fine. When trying to connect multiple clients, for some reason, it will only send correctly to one, and then the other client gets the bad file descriptor or "nonsocket" error, even though both threads are processing the same messages and do the same routines. Anyone have an idea why? Here's the code that is giving me that error: while(mqueue.head != mqueue.tail && count < dis_m){ printf("Sending to client %s: %s\n", pointer->id, pointer->message); int fd; fd = open(pointer->message, O_RDONLY); char buf[58368]; int bytesRead; printf("This is fd %d\n", fd); bytesRead=read(fd,buf,58368); send(pointer->socket,buf,bytesRead,0); perror("Error:\n"); fflush(stdout); close(fd); mqueue.mcount--; mqueue.head = mqueue.head->next; free(pointer->message); free(pointer); pointer = mqueue.head; count++; } printf("Sending %s\n", pointer->message); int fd; fd = open(pointer->message, O_RDONLY); printf("This is fd %d\n", fd); printf("I am hhere2\n"); char buf[58368]; int bytesRead; bytesRead=read(fd,buf,58368); send(pointer->socket,buf,bytesRead,0); perror("Error:\n"); close(fd); mqueue.mcount--; if(mqueue.head != mqueue.tail){ mqueue.head = mqueue.head->next; } else{ mqueue.head->next = malloc(sizeof(struct message)); mqueue.head = mqueue.head->next; mqueue.head->next = malloc(sizeof(struct message)); mqueue.tail = mqueue.head->next; mqueue.head->message = NULL; } free(pointer->message); free(pointer); pthread_mutex_unlock(&numm); pthread_mutex_unlock(&circ); pthread_mutex_unlock(&slots); The messages for both threads are the same, being of the form ./path/imageXX.ppm where XX is the number that should go to the client. The file size of each image is 58368 bytes. Sometimes, this code hangs on the read, and stops execution. I don't know this would be either, because the file descriptor comes back as valid. Thanks in advanced. Edit: Here's some sample output: Sending to client a: ./support/images/sw90.ppm This is fd 4 Error: : Socket operation on non-socket Sending to client a: ./support/images/sw91.ppm This is fd 4 Error: : Socket operation on non-socket Sending ./support/images/sw92.ppm This is fd 4 I am hhere2 Error: : Socket operation on non-socket My dispatcher has defeated evil Sample with 2 clients (client b was serviced first) Sending to client b: ./support/images/sw87.ppm This is fd 6 Error: : Success Sending to client b: ./support/images/sw88.ppm This is fd 6 Error: : Success Sending to client b: ./support/images/sw89.ppm This is fd 6 Error: : Success This is fd 6 Error: : Bad file descriptor Sending to client a: ./support/images/sw85.ppm This is fd 6 Error: As you can see, who ever is serviced first in this instance can open the files, but not the 2nd person. Edit2: Full code. Sorry, its pretty long and terribly formatted. #include <netinet/in.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <errno.h> #include <stdio.h> #include <unistd.h> #include <pthread.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "ring.h" /* Version 1 Here is what is implemented so far: The threads are created from the arguments specified (number of threads that is) The server will lock and update variables based on how many clients are in the system and such. The socket that is opened when a new client connects, must be passed to the threads. To do this, we need some sort of global array. I did this by specifying an int client and main_pool_busy, and two pointers poolsockets and nonpoolsockets. My thinking on this was that when a new client enters the system, the server thread increments the variable client. When a thread is finished with this client (after it sends it the data), the thread will decrement client and close the socket. HTTP servers act this way sometimes (they terminate the socket as soon as one transmission is sent). *Note down at bottom After the server portion increments the client counter, we must open up a new socket (denoted by new_sd) and get this value to the appropriate thread. To do this, I created global array poolsockets, which will hold all the socket descriptors for our pooled threads. The server portion gets the new socket descriptor, and places the value in the first spot of the array that has a 0. We only place a value in this array IF: 1. The variable main_pool_busy < worknum (If we have more clients in the system than in our pool, it doesn't mean we should always create a new thread. At the end of this, the server signals on the condition variable clientin that a new client has arrived. In our pooled thread, we then must walk this array and check the array until we hit our first non-zero value. This is the socket we will give to that thread. The thread then changes the array to have a zero here. What if our all threads in our pool our busy? If this is the case, then we will know it because our threads in this pool will increment main_pool_busy by one when they are working on a request and decrement it when they are done. If main_pool_busy >= worknum, then we must dynamically create a new thread. Then, we must realloc the size of our nonpoolsockets array by 1 int. We then add the new socket descriptor to our pool. Here's what we need to figure out: NOTE* Each worker should generate 100 messages which specify the worker thread ID, client socket descriptor and a copy of the client message. Additionally, each message should include a message number, starting from 0 and incrementing for each subsequent message sent to the same client. I don't know how to keep track of how many messages were to the same client. Maybe we shouldn't close the socket descriptor, but rather keep an array of structs for each socket that includes how many messages they have been sent. Then, the server adds the struct, the threads remove it, then the threads add it back once they've serviced one request (unless the count is 100). ------------------------------------------------------------- CHANGES Version 1 ---------- NONE: this is the first version. */ #define MAXSLOTS 30 #define dis_m 15 //problems with dis_m ==1 //Function prototypes void inc_clients(); void init_mutex_stuff(pthread_t*, pthread_t*); void *threadpool(void *); void server(int); void add_to_socket_pool(int); void inc_busy(); void dec_busy(); void *dispatcher(); void create_message(long, int, int, char *, char *); void init_ring(); void add_to_ring(char *, char *, int, int, int); int socket_from_string(char *); void add_to_head(char *); void add_to_tail(char *); struct message * reorder(struct message *, struct message *, int); int get_threadid(char *); void delete_socket_messages(int); struct message * merge(struct message *, struct message *, int); int get_request(char *, char *, char*); ///////////////////// //Global mutexes and condition variables pthread_mutex_t startservice; pthread_mutex_t numclients; pthread_mutex_t pool_sockets; pthread_mutex_t nonpool_sockets; pthread_mutex_t m_pool_busy; pthread_mutex_t slots; pthread_mutex_t numm; pthread_mutex_t circ; pthread_cond_t clientin; pthread_cond_t m; /////////////////////////////////////// //Global variables int clients; int main_pool_busy; int * poolsockets, nonpoolsockets; int worknum; struct ring mqueue; /////////////////////////////////////// int main(int argc, char ** argv){ //error handling if not enough arguments to program if(argc != 3){ printf("Not enough arguments to server: ./server portnum NumThreadsinPool\n"); _exit(-1); } //Convert arguments from strings to integer values int port = atoi(argv[1]); worknum = atoi(argv[2]); //Start server portion server(port); } /////////////////////////////////////////////////////////////////////////////////////////////// //The listen server thread///////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// void server(int port){ int sd, new_sd; struct sockaddr_in name, cli_name; int sock_opt_val = 1; int cli_len; pthread_t threads[worknum]; //create our pthread id array pthread_t dis[1]; //create our dispatcher array (necessary to create thread) init_mutex_stuff(threads, dis); //initialize mutexes and stuff //Server setup /////////////////////////////////////////////////////// if ((sd = socket (AF_INET, SOCK_STREAM, 0)) < 0) { perror("(servConn): socket() error"); _exit (-1); } if (setsockopt (sd, SOL_SOCKET, SO_REUSEADDR, (char *) &sock_opt_val, sizeof(sock_opt_val)) < 0) { perror ("(servConn): Failed to set SO_REUSEADDR on INET socket"); _exit (-1); } name.sin_family = AF_INET; name.sin_port = htons (port); name.sin_addr.s_addr = htonl(INADDR_ANY); if (bind (sd, (struct sockaddr *)&name, sizeof(name)) < 0) { perror ("(servConn): bind() error"); _exit (-1); } listen (sd, 5); //End of server Setup ////////////////////////////////////////////////// for (;;) { cli_len = sizeof (cli_name); new_sd = accept (sd, (struct sockaddr *) &cli_name, &cli_len); printf ("Assigning new socket descriptor: %d\n", new_sd); inc_clients(); //New client has come in, increment clients add_to_socket_pool(new_sd); //Add client to the pool of sockets if (new_sd < 0) { perror ("(servConn): accept() error"); _exit (-1); } } pthread_exit(NULL); //Quit } //Adds the new socket to the array designated for pthreads in the pool void add_to_socket_pool(int socket){ pthread_mutex_lock(&m_pool_busy); //Lock so that we can check main_pool_busy int i; //If not all our main pool is busy, then allocate to one of them if(main_pool_busy < worknum){ pthread_mutex_unlock(&m_pool_busy); //unlock busy, we no longer need to hold it pthread_mutex_lock(&pool_sockets); //Lock the socket pool array so that we can edit it without worry for(i = 0; i < worknum; i++){ //Find a poolsocket that is -1; then we should put the real socket there. This value will be changed back to -1 when the thread grabs the sockfd if(poolsockets[i] == -1){ poolsockets[i] = socket; pthread_mutex_unlock(&pool_sockets); //unlock our pool array, we don't need it anymore inc_busy(); //Incrememnt busy (locks the mutex itself) pthread_cond_signal(&clientin); //Signal first thread waiting on a client that a client needs to be serviced break; } } } else{ //Dynamic thread creation goes here pthread_mutex_unlock(&m_pool_busy); } } //Increments the client number. If client number goes over worknum, we must dynamically create new pthreads void inc_clients(){ pthread_mutex_lock(&numclients); clients++; pthread_mutex_unlock(&numclients); } //Increments busy void inc_busy(){ pthread_mutex_lock(&m_pool_busy); main_pool_busy++; pthread_mutex_unlock(&m_pool_busy); } //Initialize all of our mutexes at the beginning and create our pthreads void init_mutex_stuff(pthread_t * threads, pthread_t * dis){ pthread_mutex_init(&startservice, NULL); pthread_mutex_init(&numclients, NULL); pthread_mutex_init(&pool_sockets, NULL); pthread_mutex_init(&nonpool_sockets, NULL); pthread_mutex_init(&m_pool_busy, NULL); pthread_mutex_init(&circ, NULL); pthread_cond_init (&clientin, NULL); main_pool_busy = 0; poolsockets = malloc(sizeof(int)*worknum); int threadreturn; //error checking variables long i = 0; //Loop and create pthreads for(i; i < worknum; i++){ threadreturn = pthread_create(&threads[i], NULL, threadpool, (void *) i); poolsockets[i] = -1; if(threadreturn){ perror("Thread pool created unsuccessfully"); _exit(-1); } } pthread_create(&dis[0], NULL, dispatcher, NULL); } ////////////////////////////////////////////////////////////////////////////////////////// /////////Main pool routines ///////////////////////////////////////////////////////////////////////////////////////// void dec_busy(){ pthread_mutex_lock(&m_pool_busy); main_pool_busy--; pthread_mutex_unlock(&m_pool_busy); } void dec_clients(){ pthread_mutex_lock(&numclients); clients--; pthread_mutex_unlock(&numclients); } //This is what our threadpool pthreads will be running. void *threadpool(void * threadid){ long id = (long) threadid; //Id of this thread int i; int socket; int counter = 0; //Try and gain access to the next client that comes in and wait until server signals that a client as arrived while(1){ pthread_mutex_lock(&startservice); //lock start service (required for cond wait) pthread_cond_wait(&clientin, &startservice); //wait for signal from server that client exists pthread_mutex_unlock(&startservice); //unlock mutex. pthread_mutex_lock(&pool_sockets); //Lock the pool socket so we can get the socket fd unhindered/interrupted for(i = 0; i < worknum; i++){ if(poolsockets[i] != -1){ socket = poolsockets[i]; poolsockets[i] = -1; pthread_mutex_unlock(&pool_sockets); } } printf("Thread #%d is past getting the socket\n", id); int incoming = 1; while(counter < 100 && incoming != 0){ char buffer[512]; bzero(buffer,512); int startcounter = 0; incoming = read(socket, buffer, 512); if(buffer[0] != 0){ //client ID:priority:request:arguments char id[100]; long prior; char request[100]; char arg1[100]; char message[100]; char arg2[100]; char * point; point = strtok(buffer, ":"); strcpy(id, point); point = strtok(NULL, ":"); prior = atoi(point); point = strtok(NULL, ":"); strcpy(request, point); point = strtok(NULL, ":"); strcpy(arg1, point); point = strtok(NULL, ":"); if(point != NULL){ strcpy(arg2, point); } int fd; if(strcmp(request, "start_movie") == 0){ int count = 1; while(count <= 100){ char temp[10]; snprintf(temp, 50, "%d\0", count); strcpy(message, "./support/images/"); strcat(message, arg1); strcat(message, temp); strcat(message, ".ppm"); printf("This is message %s to %s\n", message, id); count++; add_to_ring(message, id, prior, counter, socket); //Adds our created message to the ring counter++; } printf("I'm out of the loop\n"); } else if(strcmp(request, "seek_movie") == 0){ int count = atoi(arg2); while(count <= 100){ char temp[10]; snprintf(temp, 10, "%d\0", count); strcpy(message, "./support/images/"); strcat(message, arg1); strcat(message, temp); strcat(message, ".ppm"); printf("This is message %s\n", message); count++; } } //create_message(id, socket, counter, buffer, message); //Creates our message from the input from the client. Stores it in buffer } else{ delete_socket_messages(socket); break; } } counter = 0; close(socket);//Zero out counter again } dec_clients(); //client serviced, decrement clients dec_busy(); //thread finished, decrement busy } //Creates a message void create_message(long threadid, int socket, int counter, char * buffer, char * message){ snprintf(message, strlen(buffer)+15, "%d:%d:%d:%s", threadid, socket, counter, buffer); } //Gets the socket from the message string (maybe I should just pass in the socket to another method) int socket_from_string(char * message){ char * substr1 = strstr(message, ":"); char * substr2 = substr1; substr2++; int occurance = strcspn(substr2, ":"); char sock[10]; strncpy(sock, substr2, occurance); return atoi(sock); } //Adds message to our ring buffer's head void add_to_head(char * message){ printf("Adding to head of ring\n"); mqueue.head->message = malloc(strlen(message)+1); //Allocate space for message strcpy(mqueue.head->message, message); //copy bytes into allocated space } //Adds our message to our ring buffer's tail void add_to_tail(char * message){ printf("Adding to tail of ring\n"); mqueue.tail->message = malloc(strlen(message)+1); //allocate space for message strcpy(mqueue.tail->message, message); //copy bytes into allocated space mqueue.tail->next = malloc(sizeof(struct message)); //allocate space for the next message struct } //Adds a message to our ring void add_to_ring(char * message, char * id, int prior, int mnum, int socket){ //printf("This is message %s:" , message); pthread_mutex_lock(&circ); //Lock the ring buffer pthread_mutex_lock(&numm); //Lock the message count (will need this to make sure we can't fill the buffer over the max slots) if(mqueue.head->message == NULL){ add_to_head(message); //Adds it to head mqueue.head->socket = socket; //Set message socket mqueue.head->priority = prior; //Set its priority (thread id) mqueue.head->mnum = mnum; //Set its message number (used for sorting) mqueue.head->id = malloc(sizeof(id)); strcpy(mqueue.head->id, id); } else if(mqueue.tail->message == NULL){ //This is the problem for dis_m 1 I'm pretty sure add_to_tail(message); mqueue.tail->socket = socket; mqueue.tail->priority = prior; mqueue.tail->mnum = mnum; mqueue.tail->id = malloc(sizeof(id)); strcpy(mqueue.tail->id, id); } else{ mqueue.tail->next = malloc(sizeof(struct message)); mqueue.tail = mqueue.tail->next; add_to_tail(message); mqueue.tail->socket = socket; mqueue.tail->priority = prior; mqueue.tail->mnum = mnum; mqueue.tail->id = malloc(sizeof(id)); strcpy(mqueue.tail->id, id); } mqueue.mcount++; pthread_mutex_unlock(&circ); if(mqueue.mcount >= dis_m){ pthread_mutex_unlock(&numm); pthread_cond_signal(&m); } else{ pthread_mutex_unlock(&numm); } printf("out of add to ring\n"); fflush(stdout); } ////////////////////////////////// //Dispatcher routines ///////////////////////////////// void *dispatcher(){ init_ring(); while(1){ pthread_mutex_lock(&slots); pthread_cond_wait(&m, &slots); pthread_mutex_lock(&numm); pthread_mutex_lock(&circ); printf("Dispatcher to the rescue!\n"); mqueue.head = reorder(mqueue.head, mqueue.tail, mqueue.mcount); //printf("This is the head %s\n", mqueue.head->message); //printf("This is the tail %s\n", mqueue.head->message); fflush(stdout); struct message * pointer = mqueue.head; int count = 0; while(mqueue.head != mqueue.tail && count < dis_m){ printf("Sending to client %s: %s\n", pointer->id, pointer->message); int fd; fd = open(pointer->message, O_RDONLY); char buf[58368]; int bytesRead; printf("This is fd %d\n", fd); bytesRead=read(fd,buf,58368); send(pointer->socket,buf,bytesRead,0); perror("Error:\n"); fflush(stdout); close(fd); mqueue.mcount--; mqueue.head = mqueue.head->next; free(pointer->message); free(pointer); pointer = mqueue.head; count++; } printf("Sending %s\n", pointer->message); int fd; fd = open(pointer->message, O_RDONLY); printf("This is fd %d\n", fd); printf("I am hhere2\n"); char buf[58368]; int bytesRead; bytesRead=read(fd,buf,58368); send(pointer->socket,buf,bytesRead,0); perror("Error:\n"); close(fd); mqueue.mcount--; if(mqueue.head != mqueue.tail){ mqueue.head = mqueue.head->next; } else{ mqueue.head->next = malloc(sizeof(struct message)); mqueue.head = mqueue.head->next; mqueue.head->next = malloc(sizeof(struct message)); mqueue.tail = mqueue.head->next; mqueue.head->message = NULL; } free(pointer->message); free(pointer); pthread_mutex_unlock(&numm); pthread_mutex_unlock(&circ); pthread_mutex_unlock(&slots); printf("My dispatcher has defeated evil\n"); } } void init_ring(){ mqueue.head = malloc(sizeof(struct message)); mqueue.head->next = malloc(sizeof(struct message)); mqueue.tail = mqueue.head->next; mqueue.mcount = 0; } struct message * reorder(struct message * begin, struct message * end, int num){ //printf("I am reordering for size %d\n", num); fflush(stdout); int i; if(num == 1){ //printf("Begin: %s\n", begin->message); begin->next = NULL; return begin; } else{ struct message * left = begin; struct message * right; int middle = num/2; for(i = 1; i < middle; i++){ left = left->next; } right = left -> next; left -> next = NULL; //printf("Begin: %s\nLeft: %s\nright: %s\nend:%s\n", begin->message, left->message, right->message, end->message); left = reorder(begin, left, middle); if(num%2 != 0){ right = reorder(right, end, middle+1); } else{ right = reorder(right, end, middle); } return merge(left, right, num); } } struct message * merge(struct message * left, struct message * right, int num){ //printf("I am merginging! left: %s %d, right: %s %dnum: %d\n", left->message,left->priority, right->message, right->priority, num); struct message * start, * point; int lenL= 0; int lenR = 0; int flagL = 0; int flagR = 0; int count = 0; int middle1 = num/2; int middle2; if(num%2 != 0){ middle2 = middle1+1; } else{ middle2 = middle1; } while(lenL < middle1 && lenR < middle2){ count++; //printf("In here for count %d\n", count); if(lenL == 0 && lenR == 0){ if(left->priority < right->priority){ start = left; //Set the start point point = left; //set our enum; left = left->next; //move the left pointer point->next = NULL; //Set the next node to NULL lenL++; } else if(left->priority > right->priority){ start = right; point = right; right = right->next; point->next = NULL; lenR++; } else{ if(left->mnum < right->mnum){ ////printf("This is where we are\n"); start = left; //Set the start point point = left; //set our enum; left = left->next; //move the left pointer point->next = NULL; //Set the next node to NULL lenL++; } else{ start = right; point = right; right = right->next; point->next = NULL; lenR++; } } } else{ if(left->priority < right->priority){ point->next = left; left = left->next; //move the left pointer point = point->next; point->next = NULL; //Set the next node to NULL lenL++; } else if(left->priority > right->priority){ point->next = right; right = right->next; point = point->next; point->next = NULL; lenR++; } else{ if(left->mnum < right->mnum){ point->next = left; //set our enum; left = left->next; point = point->next;//move the left pointer point->next = NULL; //Set the next node to NULL lenL++; } else{ point->next = right; right = right->next; point = point->next; point->next = NULL; lenR++; } } } if(lenL == middle1){ flagL = 1; break; } if(lenR == middle2){ flagR = 1; break; } } if(flagL == 1){ point->next = right; point = point->next; for(lenR; lenR< middle2-1; lenR++){ point = point->next; } point->next = NULL; mqueue.tail = point; } else{ point->next = left; point = point->next; for(lenL; lenL< middle1-1; lenL++){ point = point->next; } point->next = NULL; mqueue.tail = point; } //printf("This is the start %s\n", start->message); //printf("This is mqueue.tail %s\n", mqueue.tail->message); return start; } void delete_socket_messages(int a){ }

    Read the article

  • What is the fastest way to Initialize a multi-dimensional array to non-default values in .NET?

    - by AMissico
    How do I initialize a multi-dimensional array of a primitive type as fast as possible? I am stuck with using multi-dimensional arrays. My problem is performance. The following routine initializes a 100x100 array in approx. 500 ticks. Removing the int.MaxValue initialization results in approx. 180 ticks just for the looping. Approximately 100 ticks to create the array without looping and without initializing to int.MaxValue. Routines similiar to this are called a few hundred-thousand to several million times during a "run". The array size will not change during a run and arrays are created one-at-a-time, used, then discarded, and a new array created. A "run" which may last from one minute (using 10x10 arrays) to forty-five minutes (100x100). The application creates arrays of int, bool, and struct. There can be multiple "runs" executing at same time, but are not because performance degrades terribly. I am using 100x100 as a base-line. I am open to suggestions on how to optimize this non-default initialization of an array. One idea I had is to use a smaller primitive type when available. For instance, using byte instead of int, saves 100 ticks. I would be happy with this, but I am hoping that I don't have to change the primitive data type. public int[,] CreateArray(Size size) { int[,] array = new int[size.Width, size.Height]; for (int x = 0; x < size.Width; x++) { for (int y = 0; y < size.Height; y++) { array[x, y] = int.MaxValue; } } return array; } Down to 450 ticks with the following: public int[,] CreateArray1(Size size) { int iX = size.Width; int iY = size.Height; int[,] array = new int[iX, iY]; for (int x = 0; x < iX; x++) { for (int y = 0; y < iY; y++) { array[x, y] = int.MaxValue; } } return array; } Down to approximately 165 ticks after a one-time initialization of 2800 ticks. (See my answer below.) If I can get stackalloc to work with multi-dimensional arrays, I should be able to get the same performance without having to intialize the private static array. private static bool _arrayInitialized5; private static int[,] _array5; public static int[,] CreateArray5(Size size) { if (!_arrayInitialized5) { int iX = size.Width; int iY = size.Height; _array5 = new int[iX, iY]; for (int x = 0; x < iX; x++) { for (int y = 0; y < iY; y++) { _array5[x, y] = int.MaxValue; } } _arrayInitialized5 = true; } return (int[,])_array5.Clone(); } Down to approximately 165 ticks without using the "clone technique" above. (See my answer below.) I am sure I can get the ticks lower, if I can just figure out the return of CreateArray9. public unsafe static int[,] CreateArray8(Size size) { int iX = size.Width; int iY = size.Height; int[,] array = new int[iX, iY]; fixed (int* pfixed = array) { int count = array.Length; for (int* p = pfixed; count-- > 0; p++) *p = int.MaxValue; } return array; }

    Read the article

  • Accessing a vector<vector<int>> as a flat array

    - by user1762276
    For this array: vector<vector<int> > v; v.push_back(vector<int>(0)); v.back().push_back(1); v.back().push_back(2); v.back().push_back(3); v.back().push_back(4); I can output {1, 2, 3, 4} easily enough: cout << v[0][0] << endl; cout << v[0][1] << endl; cout << v[0][2] << endl; cout << v[0][3] << endl; To access it as a flat array I can do this: int* z = (int*)&v[0].front(); cout << z[0] << endl; cout << z[1] << endl; cout << z[2] << endl; cout << z[3] << endl; Now, how do I access the multidimensional vector as a flat multidimensional array? I cannot use the same format as accessing a single-dimensional vector: // This does not work (outputs garbage) int** n = (int**)&v.front(); cout << n[0][0] << endl; cout << n[0][1] << endl; cout << n[0][2] << endl; cout << n[0][3] << endl; The workaround I've found is to do this: int** n = new int* [v.size()]; for (size_t i = 0; i < v.size(); i++) { n[i] = &v.at(i).front(); } cout << n[0][0] << endl; cout << n[0][1] << endl; cout << n[0][2] << endl; cout << n[0][3] << endl; Is there a way to access the entire multidimensional vector like a flat c-style array without having to dynamically allocate each dimension above the data before accessing it? Speed is not critical in the implementation and clarity for maintenance is paramount. A multidimensional vector is just fine for storing the data. However, I want to also expose the data as a flat c-style array in the SDK so that it can be easily accessible by other languages. This means that exposing the vectors as an STL object is a no go. The solution I came up with works fine for my needs as I only evaluate the array once at the very end of processing to "flatten" it. However, is there a better way to go about this? Or am I already doing it the best way I possibly can without re-implementing my own data structure (overkill since my flatten code is only a few lines). Thank you for your advice, friends!

    Read the article

  • Linux program unable to access files in group

    - by user1064665
    I'm having trouble configuring things on linux so that a program can access certain files. Let's call it pgm A. It has uid uA and gid gA. In addition, uid uA is listed in /etc/group as a member of group gX. The problem is that pgm A cannot access files for which the uid is root and the gid is gX, but only when pgm A is called from another program, pgm B, which also runs as user uA. If I su as user uA and run pgm A from bash, it has no problem accessing files in group gX. But if another program, pgm B, which also runs as user uA, forks and execs pgm A, pgm A cannot access the files. I've verified that pgm A is indeed running as user uA, group gA, when launched from pgm B. So, if uA is a member of group gX, why can't the program access files which are readable by group gX? It's as if the operating system is ignoring the fact that user uA is also in group gX.

    Read the article

  • Cannot implicitly convert type 'System.Linq.IQueryable<int>' to 'int?'

    - by Aneef
    Hi this is my code var cityList = from country in doc.Element("result").Element("cities").Descendants("city") select new { Name = country.Element("name").Value, Code = country.Element("code").Value, CountryCode = int.Parse(country.Element("countrycode").Value) }; foreach(var citee in cityList) { City city = new City(); city.CountryID = from cnt in db.Countries where cnt.DOTWInternalID == citee.CountryCode select cnt.ID; } Im getting an error on the second query as the title of this post, i tried converting to int, to nullable int nothing worked? help me guys Thanks,

    Read the article

  • Knight movement.... " how to output all possible moves. "

    - by josh kant
    hi tried the following code and is still not working. it is having problem on backtracking. it just fills the squares of a board with numbers but not in expected order. The code is as follows : include include using namespace std; int i=0; int permuteno = 0; bool move(int *p[], int *used[] ,int x, int y,int n, int count); bool knights (int *p[], int *used[],int x,int y,int n, int count); void output(int *p[],int n); int main(char argc, char *argv[]) { int count = 1; int n; //for size of board int x,y; // starting pos int **p; // to hold no. of combinations int **used; // to keep track of used squares on the board if ( argc != 5) { cout << "Very few arguments. Please try again."; cout << endl; return 0; } n = atoi(argv[2]); if( argv[1] <= 0 ) { cout << " Invalid board size. "; return 0; } x = atoi(argv[4]); y = atoi(argv[4]); cout << "board size: " << n << ", "<< n << endl; cout << "starting pos: " << x << ", " << y << endl; //dynamic allocation of arrays to hold permutation p = new int *[n]; for (int i = 0; i < n; i++) p[i] = new int [n]; //dynamic allocation of used arrays used = new int*[n]; for (int i = 0; i < n; i++) used[i] = new int [n]; //initializing board int i, j; for (i=0; i output(p,n); if (knights(p,used,x, y, n, count)) { cout << "solution found: " << endl < int i, j; for (i=0; i else { cout << "Solution not found" << endl; output (p, n); } knights (p,used, x, y, n, 1); //knights (p,used,x, y, n, count); cout << "no. perm " << permuteno << endl; return 0; } void output(int *p[],int n) { int i = 0,j; while ( i !=n) { for ( j=0; j bool move(int *p[], int *used[] ,int x, int y,int n,int count) { if (x < 0 || x = n) { return false; } if ( y < 0 || y = n) { return false; } if( used[x][y] != 0) { return false; } if( p[x][y] != 0) { return false; } count++; return true; } bool knights (int *p[], int *used[], int x,int y,int n ,int count) { //used[x][y] = 1; if (!move(p,used,x,y,n, count)) { return false; } if (move(p,used,x,y,n, count)) { i++; } p[x][y] = count; used[x][y] = 1; cout << "knight moved " << x << ", " << y << " " << count << endl; if(n*n == count) { return true; } //move 1 if (!knights (p,used, x-1, y-2, n, count+1)) { used[x][y] = 0; //p[x][y] = 0; } //move 2 if (!knights (p,used, x+1, y-2, n, count+1)) { used[x][y] = 0; //p[x][y] = 0; } //move 3 if (!knights (p,used, x+2, y-1, n, count+1)) { used[x][y] = 0; //p[x][y] = 0; } //move 4 if (!knights (p,used, x+2, y+1, n, count+1)) { used[x][y] = 0; //p[x][y] = 0; } //move 5 if (!knights (p,used, x+1, y+2, n, count+1)) { used[x][y] = 0; //p[x][y] = 0; } //move 6 if (!knights (p,used, x-1, y+2, n, count+1)) { used[x][y] = 0; //p[x][y] = 0; } //move 7 if (!knights (p,used, x-2, y+1, n, count+1)) { used[x][y] = 0; //p[x][y] = 0; } //move 8 if (!knights (p,used, x-2, y-1, n, count+1)) { used[x][y] = 0; //p[x][y] = 0; } permuteno++; //return true; //}while ( x*y != n*n ); return false; } I has to output all the possible combinations of the knight in a nXn board.. any help would be appreciated...

    Read the article

  • CONVERT(int, (datepart(month, @search)), (datepart(day, @search)), DateAdd(year, Years.Year - (datepart(year, @search)))

    - by MyHeadHurts
    In the query the top part is getting all the years that will run in the stored procedure. Works fine But at first i just wanted to run the queries for yesterdays date for all the years, but now i realized i want the user to select a date that will be in a parameter @search Booked <= CONVERT(int,DateAdd(year, Years.Year - Year(getdate()), DateAdd(day, DateDiff(day, 2, getdate()), 1))) this should be easy because normally it would just be Booked <= CONVERT(int,@search) but the problem is i want to do something like a Booked <= CONVERT(int, (datepart(month, @search)), (datepart(day, @search)), DateAdd(year, Years.Year - (datepart(year, @search))) would something like that work i dont need to worry about subtracting days but i still need to worry about the years WITH Years AS ( SELECT DATEPART(year, GETDATE()) [Year] UNION ALL SELECT [Year]-1 FROM Years WHERE [Year]>@YearToGet ), q_00 as ( select DIVISION , DYYYY , sum(PARTY) as asofPAX , sum(APRICE) as asofSales from dbo.B101BookingsDetails INNER JOIN Years ON B101BookingsDetails.DYYYY = Years.Year where Booked <= CONVERT(int,DateAdd(year, Years.Year - Year(getdate()), DateAdd(day, DateDiff(day, 2, getdate()), 1))) and DYYYY = Years.Year group by DIVISION, DYYYY, years.year having DYYYY = years.year ),

    Read the article

  • How do i convert String to Integer/Float in Haskell

    - by Ranhiru
    data GroceryItem = CartItem ItemName Price Quantity | StockItem ItemName Price Quantity makeGroceryItem :: String -> Float -> Int -> GroceryItem makeGroceryItem name price quantity = CartItem name price quantity I want to create a GroceryItem when using a String or [String] createGroceryItem :: [String] -> GroceryItem createGroceryItem (a:b:c) = makeGroceryItem a b c The input will be in the format ["Apple","15.00","5"] which i broke up using words function in haskell. I get this error which i think is because the makeGroceryItem accepts a Float and an Int. But how do i make b and c Float and Int respectively? *Type error in application *** Expression : makeGroceryItem a read b read c *** Term : makeGroceryItem *** Type : String -> Float -> Int -> GroceryItem *** Does not match : a -> b -> c -> d -> e -> f* Thanx a lot in advance :)

    Read the article

  • Java RMI InitialContext: Equivalent of LocateRegistry.createRegistry(int) ?

    - by bguiz
    I am trying to some pretty basic RMI: // Context namingContext = new InitialContext(); Registry reg = LocateRegistry.createRegistry(9999); for ( int i = 0; i < objs.length; i++ ) { int id = objs[i].getID(); // namingContext.bind( "rmi:CustomObj" + id , objs[i] ); reg.bind( "CustomObj" + id , objs[i] ); } That works without a hitch, but for future purposes, I need to use InitialContext. Context namingContext = new InitialContext(); for ( int i = 0; i < objs.length; i++ ) { int id = objs[i].getID(); namingContext.bind( "rmi:CustomObj" + id , objs[i] ); } But I cannot get this to work. I have started rmiregistry from the command line. Is there an equivalent of LocateRegistry.createRegistry(int)? Or some other way to start the RMI registry / registry used by InitialContext from inside my class? (Instead of the command line) Stack trace: javax.naming.CommunicationException [Root exception is java.rmi.ServerException: RemoteException occurred in server thread; nested exception is: java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is: java.lang.ClassNotFoundException: bguiz.scratch.network.eg.Student] at com.sun.jndi.rmi.registry.RegistryContext.bind(RegistryContext.java:126) at com.sun.jndi.toolkit.url.GenericURLContext.bind(GenericURLContext.java:208) at javax.naming.InitialContext.bind(InitialContext.java:400) at bguiz.scratch.RMITest.main(RMITest.java:29) Caused by: java.rmi.ServerException: RemoteException occurred in server thread; nested exception is: java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is: java.lang.ClassNotFoundException: bguiz.scratch.CustomObj at sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:396) at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:250) ....(truncated) EDIT: I will delete my own question in a couple of days, as there seems to be no answer to this (I haven't been able to figure it out myself). Last call for any biters!

    Read the article

  • Assert.AreEqual to not fail when comparing an enum and an int

    - by codingbear
    I'm not sure if this is doable, but I will just give a shot. I am calling Assert.AreEqual() method. For the parameters, I'm passing... an enum value which has Int32 as the underlying type because I didn't specify the base type an int (Int32) value Assert fails because it sees that the enum is not int (which is definitely correct). However, is there a way to make this Assert pass when the enum has the correct int value as the 2nd parameter? I can cast the enum to int and have it a quick fix, but it's really ugly. I was expecting some kind of overriding a method that Assert uses to compare 2 different objects and implicitly make that enum type look like an int. However, I wasn't successful at finding any hint/answer around that so far. Someone suggested to create a type converter and use the TypeConverterAttribute to get around. If this works for sure and is the only way to do it, I would; however, it does seem a lot of unnecessary work.

    Read the article

  • Converting a int to a BCD byte array

    - by Lily
    I want to convert an int to a byte[2] array using BCD. The int in question will come from DateTime representing the Year and must be converted to two bytes. Is there any pre-made function that does this or can you give me a simple way of doing this? example: int year = 2010 would output: byte[2]{0x20, 0x10};

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >