Search Results

Search found 3602 results on 145 pages for 'jagged arrays'.

Page 12/145 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • Given an array of arrays, how can I strip out the substring "GB" from each value?

    - by stormist
    Each item in my array is an array of about 5 values.. Some of them are numerical ending in "GB".. I need the same array but with "GB" stripped out so that just the number remains. So I need to iterate through my whole array, on each subarray take each value and strip the string "GB" from it and create a new array from the output. Can anyone recommend and efficient method of doing this?

    Read the article

  • Why do Lua arrays(tables) start at 1 instead of 0?

    - by AraK
    Hi, I don't understand the rational behind the decision of this part of Lua. Why does indexing start at 1? I have read(as many others did) this great paper. It seems to me a strange corner of a language that is very pleasant to learn and program. Don't get me wrong, Lua is just great but there has to be an explanation somewhere. Most of what I found(on the web) is just saying the index starts at 1. Full stop. It would be very interesting to read what its designers said about the subject. Note that I am "very" beginner in Lua, I hope I am not missing something obvious about tables.

    Read the article

  • the best way to make codeigniter website multi-language. calling from lang arrays depends on lang se

    - by artmania
    Hi friends, I'm researching hours and hours, but I could not find any clear, efficient way to make it :/ I have a codeigniter base website in English and I have to add a Polish language now. What is the best way to make my site in 2 language depending visitor selection? is there any way to create array files for each language and call them in view files depends on Session from lang selection? I don't wanna use database. Appreciate helps! I'm running out of deadline :/ thanks!!

    Read the article

  • Why doesn't Java allow for the creaton of generic arrays?

    - by byte
    There are plenty of questions on stackoverflow from people who have attempted to create an array of generics like so: ArrayList<Foo>[] poo = new ArrayList<Foo>[5]; And the answer of course is that the Java specification doesn't allow you to declare an array of generics. My question however is why ? What is the technical reason underlying this restriction in the java language or java vm? It's a technical curiosity I've always wondered about.

    Read the article

  • How create new array which subtracts values from 2 double arrays in C#?

    - by Tomek eM
    Helou it's my problem, I have 2 array which have double values: (this is function which get back values(latitude) from richTextBox) private Tuple<double>[] szerokosc(string[] lines) { return Array.ConvertAll(lines, line => { string[] elems = line.Split(','); double we = 0.01 * double.Parse(elems[3], EnglishCulture); int stopnie = (int)we; double minuty = ((we - stopnie) * 100) / 60; double szerokosc_dziesietna = stopnie + minuty; return new Tuple<double>(Math.Round(szerokosc_dziesietna, (int)numericUpDown2.Value)); }); ; } (this part of code call function) var data1 = szerokosc(szerdlugeo_diag_gps.Lines); var data2 = szerokosc(szerdlugeo_diag_gpsglonass.Lines); What should I do, to get something like this: for example: var data3 = data1 - data2; My values in this data looks like (f.e.) data1 = (x11, x12, ... x1(n) ): 53.11818160073043, 53.11816348903661, 53.11814874695463, ... data2 = (x21, x22, ... x(2n) ): 53.11814200771546, 53.118131477652156, 53.11812263239697, 53.11811884157276, 53.11811631435644, .... I would like back data3 = (x31=x11-x21, x32=x12=x22, ... x(3n)=x(1n)-x(2n) ) It would be good if it included the following condition: if data1 = ( 1, 5, 6, 8) data2 = (1.5, 3.3) data3 = (-0.5, 1.7) not data3 = (-0.5, 1.7, 6, 8) Please help.

    Read the article

  • I'm new to Java most basic question about arrays!

    - by ambidextorous
    Hey I have not been able to find a proper answer on any forums about this but how exactly do I pass an array to a class? public class TestArray { String name; String[] array; public TestArray(String name, String[] anArray){ this.name = name; int len = anArray.length; this.array = new String[len]; for (int i = 0; i < len; i++){ this.array[i] = new String(anArray[i]); } } } public static void main(String[] args){ String[] anArray = new String[2]; anArray[0] = new String("Test"); anArray[1] = new String("Test2"); TestArray work = new TestArray("Jordan", anArray?); } }

    Read the article

  • PHP arrays. There must be a simpler method to do this

    - by RisingSun
    I have this array in php returned from db Array ( [inv_templates] = Array ( [0] = Array ( [inven_subgroup_template_id] = 1 [inven_group] = Wires [inven_subgroup] = CopperWires [inven_template_id] = 1 [inven_template_name] = CopperWires6G [constrained] = 0 [value_constraints] = [accept_range] = 2 - 16 [information] = Measured Manual ) [1] = Array ( [inven_subgroup_template_id] = 1 [inven_group] = Wires [inven_subgroup] = CopperWires [inven_template_id] = 2 [inven_template_name] = CopperWires2G [constrained] = 0 [value_constraints] = [accept_range] = 1 - 7 [information] = Measured by Automated Calipers ) ) ) I need to output this kind of multidimensional stuff Array ( [Wires] = Array ( [inv_group_name] = Wires [inv_subgroups] = Array ( [CopperWires] = Array ( [inv_subgroup_id] = 1 [inv_subgroup_name] = CopperWires [inv_templates] = Array ( [CopperWires6G] = Array ( [inv_name] = CopperWires6G [inv_id] = 1 ) [CopperWires2G] = Array ( [inv_name] = CopperWires2G [inv_id] = 2 ) ) ) ) ) ) I currently do this stuff foreach ($data['inv_templates'] as $key = $value) { $processeddata[$value['inven_group']]['inv_group_name'] = $value['inven_group']; $processeddata[$value['inven_group']]['inv_subgroups'][$value['inven_subgroup']]['inv_subgroup_id'] = $value['inven_subgroup_template_id']; $processeddata[$value['inven_group']]['inv_subgroups'][$value['inven_subgroup']]['inv_subgroup_name'] = $value['inven_subgroup']; $processeddata[$value['inven_group']]['inv_subgroups'][$value['inven_subgroup']]['inv_templates'][$value['inven_template_name']]['inv_name'] = $value['inven_template_name']; $processeddata[$value['inven_group']]['inv_subgroups'][$value['inven_subgroup']]['inv_templates'][$value['inven_template_name']]['inv_id'] = $value['inven_template_id']; } return $processeddata; EDIT : A var_export array ( 'inv_templates' = array ( 0 = array ( 'inven_subgroup_template_id' = '1', 'inven_group' = 'Wires', 'inven_subgroup' = 'CopperWires', 'inven_template_id' = '1', 'inven_template_name' = 'CopperWires6G', 'constrained' = '0', 'value_constraints' = '', 'accept_range' = '2 - 16', 'information' = 'Measured Manual', ), 1 = array ( 'inven_subgroup_template_id' = '1', 'inven_group' = 'Wires', 'inven_subgroup' = 'CopperWires', 'inven_template_id' = '2', 'inven_template_name' = 'CopperWires6G', 'constrained' = '0', 'value_constraints' = '', 'accept_range' = '1 - 7', 'information' = 'Measured by Automated Calipers', ), ), ) The foreach is almost unreadable. There must be a simpler way

    Read the article

  • How do I dump arrays in a nice orderly fashion?

    - by George
    Whenever I use print_r or var_dump they come out all sloppy and in one line instead of formatted like I see so many people and the actual php.net site being able to achieve. What do I do to get them like this - Array ( [a] => apple [b] => banana [c] => Array ( [0] => x [1] => y [2] => z ) ) Instead of this Array([a] => apple [b] => banana [c] => Array ( [0] => x [1] => y [2] => z )) (Pretty sure it comes out even messier than that I was just deleting whitespace by hand.)

    Read the article

  • Refactoring an immediate drawing function into VBO, access violation error

    - by Alex
    I have a MD2 model loader, I am trying to substitute its immediate drawing function with a Vertex Buffer Object one.... I am getting a really annoying access violation reading error and I can't figure out why, but mostly I'd like an opinion as to whether this looks correct (never used VBOs before). This is the original function (that compiles ok) which calculates the keyframe and draws at the same time: glBegin(GL_TRIANGLES); for(int i = 0; i < numTriangles; i++) { MD2Triangle* triangle = triangles + i; for(int j = 0; j < 3; j++) { MD2Vertex* v1 = frame1->vertices + triangle->vertices[j]; MD2Vertex* v2 = frame2->vertices + triangle->vertices[j]; Vec3f pos = v1->pos * (1 - frac) + v2->pos * frac; Vec3f normal = v1->normal * (1 - frac) + v2->normal * frac; if (normal[0] == 0 && normal[1] == 0 && normal[2] == 0) { normal = Vec3f(0, 0, 1); } glNormal3f(normal[0], normal[1], normal[2]); MD2TexCoord* texCoord = texCoords + triangle->texCoords[j]; glTexCoord2f(texCoord->texCoordX, texCoord->texCoordY); glVertex3f(pos[0], pos[1], pos[2]); } } glEnd(); What I'd like to do is to calculate all positions before hand, store them in a Vertex array and then draw them. This is what I am trying to replace it with (in the exact same part of the program) int vCount = 0; for(int i = 0; i < numTriangles; i++) { MD2Triangle* triangle = triangles + i; for(int j = 0; j < 3; j++) { MD2Vertex* v1 = frame1->vertices + triangle->vertices[j]; MD2Vertex* v2 = frame2->vertices + triangle->vertices[j]; Vec3f pos = v1->pos * (1 - frac) + v2->pos * frac; Vec3f normal = v1->normal * (1 - frac) + v2->normal * frac; if (normal[0] == 0 && normal[1] == 0 && normal[2] == 0) { normal = Vec3f(0, 0, 1); } indices[vCount] = normal[0]; vCount++; indices[vCount] = normal[1]; vCount++; indices[vCount] = normal[2]; vCount++; MD2TexCoord* texCoord = texCoords + triangle->texCoords[j]; indices[vCount] = texCoord->texCoordX; vCount++; indices[vCount] = texCoord->texCoordY; vCount++; indices[vCount] = pos[0]; vCount++; indices[vCount] = pos[1]; vCount++; indices[vCount] = pos[2]; vCount++; } } totalVertices = vCount; glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); glNormalPointer(GL_FLOAT, 0, indices); glTexCoordPointer(2, GL_FLOAT, sizeof(float)*3, indices); glVertexPointer(3, GL_FLOAT, sizeof(float)*5, indices); glDrawElements(GL_TRIANGLES, totalVertices, GL_UNSIGNED_BYTE, indices); glDisableClientState(GL_VERTEX_ARRAY); // disable vertex arrays glEnableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); First of all, does it look right? Second, I get access violation error "Unhandled exception at 0x01455626 in Graphics_template_1.exe: 0xC0000005: Access violation reading location 0xed5243c0" pointing at line 7 Vec3f pos = v1->pos * (1 - frac) + v2->pos * frac; where the two Vs seems to have no value in the debugger.... Till this point the function behaves in exactly the same way as the one above, I don't understand why this happens? Thanks for any help you may be able to provide!

    Read the article

  • Using XNA's XML content pipeline to read arrays of objects with different subtypes

    - by Mcguirk
    Using XNA's XML content importer, is it possible to read in an array of objects with different subtypes? For instance, assume these are my class definitions: public abstract class MyBaseClass { public string MyBaseData; } public class MySubClass0 : MyBaseClass { public int MySubData0; } public class MySubClass1 : MyBaseClass { public bool MySubData1; } And this is my XML file: <XnaContent> <Asset Type="MyBaseClass[]"> <Item> <!-- I want this to be an instance of MySubClass0 --> <MyBaseData>alpha</MyBaseData> <MySubData0>314</MySubData0> </Item> <Item> <!-- I want this to be an instance of MySubClass1 --> <MyBaseData>bravo</MyBaseData> <MySubData1>true</MySubData1> </Item> </Asset> </XnaContent> How do I specify that I want the first Item to be an instance of MySubclass0 and the second Item to be an instance of MySubclass1?

    Read the article

  • openGL migration from SFML to glut, vertices arrays or display lists are not displayed

    - by user3714670
    Due to using quad buffered stereo 3D (which i have not included yet), i need to migrate my openGL program from a SFML window to a glut window. With SFML my vertices and display list were properly displayed, now with glut my window is blank white (or another color depending on the way i clear it). Here is the code to initialise the window : int type; int stereoMode = 0; if ( stereoMode == 0 ) type = GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH; else type = GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH | GLUT_STEREO; glutInitDisplayMode(type); int argc = 0; char *argv = ""; glewExperimental = GL_TRUE; glutInit(&argc, &argv); bool fullscreen = false; glutInitWindowSize(width,height); int win = glutCreateWindow(title.c_str()); glutSetWindow(win); assert(win != 0); if ( fullscreen ) { glutFullScreen(); width = glutGet(GLUT_SCREEN_WIDTH); height = glutGet(GLUT_SCREEN_HEIGHT); } GLenum err = glewInit(); if (GLEW_OK != err) { fprintf(stderr, "Error: %s\n", glewGetErrorString(err)); } glutDisplayFunc(loop_function); This is the only code i had to change for now, but here is the code i used with sfml and displayed my objects in the loop, if i change the value of glClearColor, the window's background does change color : glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClearColor(255.0f, 255.0f, 255.0f, 0.0f); glLoadIdentity(); sf::Time elapsed_time = clock.getElapsedTime(); clock.restart(); camera->animate(elapsed_time.asMilliseconds()); camera->look(); for (auto i = objects->cbegin(); i != objects->cend(); ++i) (*i)->draw(camera); glutSwapBuffers(); Is there any other changes i should have done switching to glut ? that would be great if someone could enlighten me on the subject. In addition to that, i found out that adding too many objects (that were well handled before with SFML), openGL gives error 1285: out of memory. Maybe this is related. EDIT : Here is the code i use to draw each object, maybe it is the problem : GLuint LightID = glGetUniformLocation(this->shaderProgram, "LightPosition_worldspace"); if(LightID ==-1) cout << "LightID not found ..." << endl; GLuint MaterialAmbientID = glGetUniformLocation(this->shaderProgram, "MaterialAmbient"); if(LightID ==-1) cout << "LightID not found ..." << endl; GLuint MaterialSpecularID = glGetUniformLocation(this->shaderProgram, "MaterialSpecular"); if(LightID ==-1) cout << "LightID not found ..." << endl; glm::vec3 lightPos = glm::vec3(0,150,150); glUniform3f(LightID, lightPos.x, lightPos.y, lightPos.z); glUniform3f(MaterialAmbientID, MaterialAmbient.x, MaterialAmbient.y, MaterialAmbient.z); glUniform3f(MaterialSpecularID, MaterialSpecular.x, MaterialSpecular.y, MaterialSpecular.z); // Get a handle for our "myTextureSampler" uniform GLuint TextureID = glGetUniformLocation(shaderProgram, "myTextureSampler"); if(!TextureID) cout << "TextureID not found ..." << endl; glActiveTexture(GL_TEXTURE0); sf::Texture::bind(texture); glUniform1i(TextureID, 0); // 2nd attribute buffer : UVs GLuint vertexUVID = glGetAttribLocation(shaderProgram, "color"); if(vertexUVID==-1) cout << "vertexUVID not found ..." << endl; glEnableVertexAttribArray(vertexUVID); glBindBuffer(GL_ARRAY_BUFFER, color_array_buffer); glVertexAttribPointer(vertexUVID, 2, GL_FLOAT, GL_FALSE, 0, 0); GLuint vertexNormal_modelspaceID = glGetAttribLocation(shaderProgram, "normal"); if(!vertexNormal_modelspaceID) cout << "vertexNormal_modelspaceID not found ..." << endl; glEnableVertexAttribArray(vertexNormal_modelspaceID); glBindBuffer(GL_ARRAY_BUFFER, normal_array_buffer); glVertexAttribPointer(vertexNormal_modelspaceID, 3, GL_FLOAT, GL_FALSE, 0, 0 ); GLint posAttrib; posAttrib = glGetAttribLocation(shaderProgram, "position"); if(!posAttrib) cout << "posAttrib not found ..." << endl; glEnableVertexAttribArray(posAttrib); glBindBuffer(GL_ARRAY_BUFFER, position_array_buffer); glVertexAttribPointer(posAttrib, 3, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elements_array_buffer); glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0); GLuint error; while ((error = glGetError()) != GL_NO_ERROR) { cerr << "OpenGL error: " << error << endl; } disableShaders();

    Read the article

  • Bash arrays and case statements - review my script

    - by Felipe Alvarez
    #!/bin/bash # Change the environment in which you are currently working. # Actually, it calls the relevant 'lettus.sh' script if [ "${BASH_SOURCE[0]}" == "$0" ]; then echo "Try running this as \". chenv $1\"" exit 0 fi usage(){ echo "Usage: . ${PROG} -- Shows a list of user-selectable environments." echo " . ${PROG} [env] -- Select environment." echo " . ${PROG} -h -- Shows this usage screen." return } showEnv(){ # check if index0 exists, assume we have at least the first (zeroth) element #if [ -z "${envList}" ]; then if [ -z "${envList[0]}" ]; then echo "array \$envList is empty! " >&2 return 1 fi # Show all elements in array (0 -> n-1) for i in $(seq 0 $((${#envList[@]} - 1))); do echo ${envList[$i]} done return } setEnv(){ if [ -z "$1" ]; then usage; return fi case $1 in cold) FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_cold.sh;; coles) FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_coles.sh;; fc) FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_fc.sh;; fcrm) FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_fcrm.sh;; stable) FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_stable.sh;; tip) FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_tip.sh;; uat) FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_uat.sh;; wellmdc) FILE_TO_SOURCE=/u2/tip/conf/ctrl/lettus_wellmdc.sh;; *) usage; return;; esac if $IS_SOURCED; then echo "Environment \"$1\" selected." echo "Now sourcing file \"$FILE_TO_SOURCE\"..." . ${FILE_TO_SOURCE} return else return 1 fi } main(){ if [ -z "$1" ]; then showEnv; return fi case $1 in -h) usage;; *) setEnv $1;; esac return } PROG="chenv" # create array of user-selectable environments envList=( cold coles fc fcrm stable tip uat wellmdc ) main "$@" return If I could, I'd like to get some feedback on a better way to accomplish any of the following: run through the case statement make script trivally simple to maintain/upgrade/update

    Read the article

  • Arrays for a heightmap tile-based map

    - by JPiolho
    I'm making a game that uses a map which have tiles, corners and borders. Here's a graphical representation: I've managed to store tiles and corners in memory but I'm having troubles to get borders structured. For the tiles, I have a [Map Width * Map Height] sized array. For corners I have [(Map Width + 1) * (Map Height + 1)] sized array. I've already made up the math needed to access corners from a tile, but I can't figure out how to store and access the borders from a single array. Tiles store the type (and other game logic variables) and via the array index I can get the X, Y. Via this tile position it is possible to get the array index of the corners (which store the Z index). The borders will store a game object and accessing corners from only border info would be also required. If someone even has a better way to store these for better memory and performance I would gladly accept that. EDIT: Using in C# and Javascript.

    Read the article

  • libgdx rotation (animation, arrays) issues and help needed

    - by johnny-b
    well i am a noob at java and libgdx. i got the homing bullet working with the help of someone. now i am smashing my head as to how i can make it rotate so it faces the ball (which is the main character) when it goes around it or when it is coming towards it. the bullet is facing <--- and the code below is what i have done so far. also i used sprites for the bullet and also animation method. Also how do i make it an array/arraylist which is best so i can have multiple bullets at random or placed places. i tried many things nothing workd :( thank you for the help. // below is the bullet or enemy if you want to call it. public class Bullet extends Sprite { public static final float BULLET_HOMING = 6000; public static final float BULLET_SPEED = 300; private Vector2 velocity; private float lifetime; public Bullet(float x, float y) { velocity = new Vector2(0, 0); setPosition(x, y); } public void update(float delta) { float targetX = GameWorld.getBall().getX(); float targetY = GameWorld.getBall().getY(); float dx = targetX - getX(); float dy = targetY - getY(); float distToTarget = (float) Math.sqrt(dx * dx + dy * dy); dx /= distToTarget; dy /= distToTarget; dx *= BULLET_HOMING; dy *= BULLET_HOMING; velocity.x += dx * delta; velocity.y += dy * delta; float vMag = (float) Math.sqrt(velocity.x * velocity.x + velocity.y * velocity.y); velocity.x /= vMag; velocity.y /= vMag; velocity.x *= BULLET_SPEED; velocity.y *= BULLET_SPEED; Vector2 v = velocity.cpy().scl(delta); setPosition(getX() + v.x, getY() + v.y); setOriginCenter(); setRotation(velocity.angle()); lifetime += delta; setRegion(AssetLoader.bulletAnimation.getKeyFrame(lifetime)); } } // this is where i load the images. public class AssetLoader { public static Animation bulletAnimation; public static Sprite bullet1, bullet2; public static void load() { texture = new Texture(Gdx.files.internal("SpriteN1.png")); texture.setFilter(TextureFilter.Nearest, TextureFilter.Nearest); bullet1 = new Sprite(texture, 380, 350, 45, 20); bullet1.flip(false, true); bullet2 = new Sprite(texture, 425, 350, 45, 20); bullet2.flip(false, true); Sprite[] bullets = { bullet1, bullet2 }; bulletAnimation = new Animation(0.06f, aims); bulletAnimation.setPlayMode(Animation.PlayMode.LOOP); } public static void dispose() { // We must dispose of the texture when we are finished. texture.dispose(); } // this is for the rendering of the images etc public class GameRenderer { private Bullet bullet; private Ball ball; public GameRenderer(GameWorld world) { myWorld = world; cam = new OrthographicCamera(); cam.setToOrtho(true, 480, 320); batcher = new SpriteBatch(); // Attach batcher to camera batcher.setProjectionMatrix(cam.combined); shapeRenderer = new ShapeRenderer(); shapeRenderer.setProjectionMatrix(cam.combined); // Call helper methods to initialize instance variables initGameObjects(); initAssets(); } private void initGameObjects() { ball = GameWorld.getBall(); bullet = myWorld.getBullet(); scroller = myWorld.getScroller(); } private void initAssets() { ballAnimation = AssetLoader.ballAnimation; bulletAnimation = AssetLoader.bulletAnimation; } public void render(float runTime) { Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT); batcher.begin(); // Disable transparency // This is good for performance when drawing images that do not require // transparency. batcher.disableBlending(); // The ball needs transparency, so we enable that again. batcher.enableBlending(); batcher.draw(AssetLoader.ballAnimation.getKeyFrame(runTime), ball.getX(), ball.getY(), ball.getWidth(), ball.getHeight()); batcher.draw(AssetLoader.bulletAnimation.getKeyFrame(runTime), bullet.getX(), bullet.getY()); // End SpriteBatch batcher.end(); } } // this is to load the image etc on the screen i guess public class GameWorld { public static Ball ball; private Bullet bullet; private ScrollHandler scroller; public GameWorld() { ball = new Ball(480, 273, 32, 32); bullet = new Bullet(10, 10); scroller = new ScrollHandler(0); } public void update(float delta) { ball.update(delta); bullet.update(delta); scroller.update(delta); } public static Ball getBall() { return ball; } public ScrollHandler getScroller() { return scroller; } public Bullet getBullet() { return bullet; } } so there is the whole thing. the images are loaded via the AssetLoader then to the GameRenderer and GameWorld via the Bullet class. i am guessing that is how it is. sorry newbie so still learning. thank you in advace for the help or any advice.

    Read the article

  • Code Contracts: validating arrays and collections

    - by DigiMortal
    Validating collections before using them is very common task when we use built-in generic types for our collections. In this posting I will show you how to validate collections using code contracts. It is cool how much awful looking code you can avoid using code contracts. Failing code Let’s suppose we have method that calculates sum of all invoices in collection. We have class Invoice and one of properties it has is Sum. I don’t introduce here any complex calculations on invoices because we have another problem to solve in this topic. Here is our code. public static decimal CalculateTotal(IList<Invoice> invoices) {     var sum = invoices.Sum(p => p.Sum);     return sum; } This method is very simple but it fails when invoices list contains at least one null. Of course, we can test if invoice is null but having nulls in lists like this is not good idea – it opens green way for different coding bugs in system. Our goal is to react to bugs ASAP at the nearest place they occur. There is one more way how to make our method fail. It happens when invoices is null. I thing it is also one common bugs during development and it even happens in production environments under some conditions that are usually hardly met. Now let’s protect our little calculation method with code contracts. We need two contracts: invoices cannot be null invoices cannot contain any nulls Our first contract is easy but how to write the second one? Solution: Contract.ForAll Preconditions in code are checked using Contract.Ensures method. This method takes boolean value as argument that sais if contract holds or not. There is also method Contract.ForAll that takes collection and predicate that must hold for that collection. Nice thing is ForAll returns boolean. So, we have very simple solution. public static decimal CalculateTotal(IList<Invoice> invoices) {     Contract.Requires(invoices != null);     Contract.Requires(Contract.ForAll<Invoice>(invoices, p => p != null));       var sum = invoices.Sum(p => p.Sum);     return sum; } And here are some lines of code you can use to test the contracts quickly. var invoices = new List<Invoice>(); invoices.Add(new Invoice()); invoices.Add(null); invoices.Add(new Invoice()); //CalculateTotal(null); CalculateTotal(invoices); If your code is covered with unit tests then I suggest you to write tests to check that these contracts hold for every code run. Conclusion Although it seemed at first place that checking all elements in collection may end up with for-loops that does not look so nice we were able to solve our problem nicely. ForAll method of contract class offered us simple mechanism to check collections and it does it smoothly the code-contracts-way. P.S. I suggest you also read devlicio.us blog posting Validating Collections with Code Contracts by Derik Whittaker.

    Read the article

  • C++ simple arrays and pointers question

    - by nashmaniac
    So here's the confusion, let's say I declare an array of characters char name[3] = "Sam"; and then I declare another array but this time using pointers char * name = "Sam"; What's the difference between the two? I mean they work the same way in a program. Also how does the latter store the size of the stuff that someone puts in it, in this case 3 characters? Also how is it different from char * name = new char[3]; If those three are different where should they be used I mean in what circumstances?

    Read the article

  • libgdx arrays onTouch() method and delays for objects

    - by johnny-b
    i am trying to create random bullets but it is not working for some reason. also how can i make a delay so the bullets come every 30 seconds or 1 minute???? also the onTouch method does not work and it is not taking the bullet away???? shall i put the array in the GameRender class? thanks public class GameWorld { public static Ball ball; private Bullet bullet1; private ScrollHandler scroller; private Array<Bullet> bullets = new Array<Bullet>(); public GameWorld() { ball = new Ball(280, 273, 32, 32); bullet = new Bullet(-300, 200); scroller = new ScrollHandler(0); bullets.add(new Bullet(bullet.getX(), bullet.getY())); bullets = new Array<Bullet>(); Bullet bullet = null; float bulletX = 0.0f; float bulletY = 0.0f; for (int i=0; i < 10; i++) { bulletX = MathUtils.random(-10, 10); bulletY = MathUtils.random(-10, 10); bullet = new Bullet(bulletX, bulletY); bullets.add(bullet); } } public void update(float delta) { ball.update(delta); bullet.update(delta); scroller.update(delta); } public static Ball getBall() { return ball; } public ScrollHandler getScroller() { return scroller; } public Bullet getBullet1() { return bullet1; } } i also tried this and it is not working, i used this in the GameRender class Array<Bullet> enemies=new Array<Bullet>(); //in the constructor of the class enemies.add(new Bullet(bullet.getX(), bullet.getY())); // this throws an exception for some reason??? this is in the render method for(int i=0; i<bullet.size; i++) bullet.get(i).draw(batcher); //this i am using in any method that will allow me from the constructor to update to render for(int i=0; i<bullet.size; i++) bullet.get(i).update(delta); this is not taking the bullet out @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { for(int i=0; i<bullet.size; i++) if(bullet.get(i).getBounds().contains(screenX,screenY)) bullet.removeIndex(i--); return false; } thanks for the help anyone.

    Read the article

  • Creating a voxel world with 3D arrays using threads

    - by Sean M.
    I am making a voxel game (a bit like Minecraft) in C++(11), and I've come across an issue with creating a world efficiently. In my program, I have a World class, which holds a 3D array of Region class pointers. When I initialize the world, I give it a width, height, and depth so it knows how large of a world to create. Each Region is split up into a 32x32x32 area of blocks, so as you may guess, it takes a while to initialize the world once the world gets to be above 8x4x8 Regions. In order to alleviate this issue, I thought that using threads to generate different levels of the world concurrently would make it go faster. Having not used threads much before this, and being still relatively new to C++, I'm not entirely sure how to go about implementing one thread per level (level being a xz plane with a height of 1), when there is a variable number of levels. I tried this: for(int i = 0; i < height; i++) { std::thread th(std::bind(&World::load, this, width, height, depth)); th.join(); } Where load() just loads all Regions at height "height". But that executes the threads one at a time (which makes sense, looking back), and that of course takes as long as generating all Regions in one loop. I then tried: std::thread t1(std::bind(&World::load, this, w, h1, h2 - 1, d)); std::thread t2(std::bind(&World::load, this, w, h2, h3 - 1, d)); std::thread t3(std::bind(&World::load, this, w, h3, h4 - 1, d)); std::thread t4(std::bind(&World::load, this, w, h4, h - 1, d)); t1.join(); t2.join(); t3.join(); t4.join(); This works in that the world loads about 3-3.5 times faster, but this forces the height to be a multiple of 4, and it also gives the same exact VAO object to every single Region, which need individual VAOs in order to render properly. The VAO of each Region is set in the constructor, so I'm assuming that somehow the VAO number is not thread safe or something (again, unfamiliar with threads). So basically, my question is two one-part: How to I implement a variable number of threads that all execute at the same time, and force the main thread to wait for them using join() without stopping the other threads? How do I make the VAO objects thread safe, so when a bunch of Regions are being created at the same time across multiple threads, they don't all get the exact same VAO? Turns out it has to do with GL contexts not working across multiple threads. I moved the VAO/VBO creation back to the main thread. Fixed! Here is the code for block.h/.cpp, region.h/.cpp, and CVBObject.h/.cpp which controls VBOs and VAOs, in case you need it. If you need to see anything else just ask. EDIT: Also, I'd prefer not to have answers that are like "you should have used boost". I'm trying to do this without boost to get used to threads before moving onto other libraries.

    Read the article

  • Matrices: Arrays or separate member variables?

    - by bjz
    I'm teaching myself 3D maths and in the process building my own rudimentary engine (of sorts). I was wondering what would be the best way to structure my matrix class. There are a few options: Separate member variables: struct Mat4 { float m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44; // methods } A multi-dimensional array: struct Mat4 { float[4][4] m; // methods } An array of vectors struct Mat4 { Vec4[4] m; // methods } I'm guessing there would be positives and negatives to each. From 3D Math Primer for Graphics and Game Development, 2nd Edition p.155: Matrices use 1-based indices, so the first row and column are numbered 1. For example, a12 (read “a one two,” not “a twelve”) is the element in the first row, second column. Notice that this is different from programming languages such as C++ and Java, which use 0-based array indices. A matrix does not have a column 0 or row 0. This difference in indexing can cause some confusion if matrices are stored using an actual array data type. For this reason, it’s common for classes that store small, fixed size matrices of the type used for geometric purposes to give each element its own named member variable, such as float a11, instead of using the language’s native array support with something like float elem[3][3]. So that's one vote for method one. Is this really the accepted way to do things? It seems rather unwieldy if the only benefit would be sticking with the conventional math notation.

    Read the article

  • How do you format arrays within parameters?

    - by joslinm
    I'm talking about something like this: echo $form->input('general_addresss', array( 'label' => 'Where will you go today?' 'format' => array('before', 'input', 'after', 'label', 'after', 'error') )); Do you start with one array parameter, then break a line? If it can't fit on a line, do you immediately break a line? After of which, do you do a set number of tabs over? What happens if an array within an array has lots of properties? Is there any particular guide you follow?

    Read the article

  • BlockingCollection having issues with byte arrays

    - by MJLaukala
    I am having an issue where an object with a byte[20] is being passed into a BlockingCollection on one thread and another thread returning the object with a byte[0] using BlockingCollection.Take(). I think this is a threading issue but I do not know where or why this is happening considering that BlockingCollection is a concurrent collection. Sometimes on thread2, myclass2.mybytes equals byte[0]. Any information on how to fix this is greatly appreciated. MessageBuffer.cs public class MessageBuffer : BlockingCollection<Message> { } In the class that has Listener() and ReceivedMessageHandler(object messageProcessor) private MessageBuffer RecievedMessageBuffer; On Thread1 private void Listener() { while (this.IsListening) { try { Message message = Message.ReadMessage(this.Stream, this); if (message != null) { this.RecievedMessageBuffer.Add(message); } } catch (IOException ex) { if (!this.Client.Connected) { this.OnDisconnected(); } else { Logger.LogException(ex.ToString()); this.OnDisconnected(); } } catch (Exception ex) { Logger.LogException(ex.ToString()); this.OnDisconnected(); } } } Message.ReadMessage(NetworkStream stream, iTcpConnectClient client) public static Message ReadMessage(NetworkStream stream, iTcpConnectClient client) { int ClassType = -1; Message message = null; try { ClassType = stream.ReadByte(); if (ClassType == -1) { return null; } if (!Message.IDTOCLASS.ContainsKey((byte)ClassType)) { throw new IOException("Class type not found"); } message = Message.GetNewMessage((byte)ClassType); message.Client = client; message.ReadData(stream); if (message.Buffer.Length < message.MessageSize + Message.HeaderSize) { return null; } } catch (IOException ex) { Logger.LogException(ex.ToString()); throw ex; } catch (Exception ex) { Logger.LogException(ex.ToString()); //throw ex; } return message; } On Thread2 private void ReceivedMessageHandler(object messageProcessor) { if (messageProcessor != null) { while (this.IsListening) { Message message = this.RecievedMessageBuffer.Take(); message.Reconstruct(); message.HandleMessage(messageProcessor); } } else { while (this.IsListening) { Message message = this.RecievedMessageBuffer.Take(); message.Reconstruct(); message.HandleMessage(); } } } PlayerStateMessage.cs public class PlayerStateMessage : Message { public GameObject PlayerState; public override int MessageSize { get { return 12; } } public PlayerStateMessage() : base() { this.PlayerState = new GameObject(); } public PlayerStateMessage(GameObject playerState) { this.PlayerState = playerState; } public override void Reconstruct() { this.PlayerState.Poisiton = this.GetVector2FromBuffer(0); this.PlayerState.Rotation = this.GetFloatFromBuffer(8); base.Reconstruct(); } public override void Deconstruct() { this.CreateBuffer(); this.AddToBuffer(this.PlayerState.Poisiton, 0); this.AddToBuffer(this.PlayerState.Rotation, 8); base.Deconstruct(); } public override void HandleMessage(object messageProcessor) { ((MessageProcessor)messageProcessor).ProcessPlayerStateMessage(this); } } Message.GetVector2FromBuffer(int bufferlocation) This is where the exception is thrown because this.Buffer is byte[0] when it should be byte[20]. public Vector2 GetVector2FromBuffer(int bufferlocation) { return new Vector2( BitConverter.ToSingle(this.Buffer, Message.HeaderSize + bufferlocation), BitConverter.ToSingle(this.Buffer, Message.HeaderSize + bufferlocation + 4)); }

    Read the article

  • Factory for arrays of objects in python

    - by Vorac
    Ok, the title might be a little misleading. I have a Window class that draws widgets inside itself in the constructor. The widgets are all of the same type. So I pass a list of dictionaries, which contain the parameters for each widget. This works quite nicely, but I am worried that the interface to callers is obfuscated. That is, in order to use Window, one has to study the class, construct a correct list of dictionaries, and then call the constructor with only one parameter - widgets_params. Is this good or bad design? What alternatives does the python syntax provide?

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >