Daily Archives

Articles indexed Sunday June 30 2013

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

  • Entity System with C++ templates

    - by tommaisey
    I've been getting interested in the Entity/Component style of game programming, and I've come up with a design in C++ which I'd like a critique of. I decided to go with a fairly pure Entity system, where entities are simply an ID number. Components are stored in a series of vectors - one for each Component type. However, I didn't want to have to add boilerplate code for every new Component type I added to the game. Nor did I want to use macros to do this, which frankly scare me. So I've come up with a system based on templates and type hinting. But there are some potential issues I'd like to check before I spend ages writing this (I'm a slow coder!) All Components derive from a Component base class. This base class has a protected constructor, that takes a string parameter. When you write a new derived Component class, you must initialise the base with the name of your new class in a string. When you first instantiate a new DerivedComponent, it adds the string to a static hashmap inside Component mapped to a unique integer id. When you subsequently instantiate more Components of the same type, no action is taken. The result (I think) should be a static hashmap with the name of each class derived from Component that you instantiate at least once, mapped to a unique id, which can by obtained with the static method Component::getTypeId ("DerivedComponent"). Phew. The next important part is TypedComponentList<typename PropertyType>. This is basically just a wrapper to an std::vector<typename PropertyType> with some useful methods. It also contains a hashmap of entity ID numbers to slots in the array so we can find Components by their entity owner. Crucially TypedComponentList<> is derived from the non-template class ComponentList. This allows me to maintain a list of pointers to ComponentList in my main ComponentManager, which actually point to TypedComponentLists with different template parameters (sneaky). The Component manager has template functions such as: template <typename ComponentType> void addProperty (ComponentType& component, int componentTypeId, int entityId) and: template <typename ComponentType> TypedComponentList<ComponentType>* getComponentList (int componentTypeId) which deal with casting from ComponentList to the correct TypedComponentList for you. So to get a list of a particular type of Component you call: TypedComponentList<MyComponent>* list = componentManager.getComponentList<MyComponent> (Component::getTypeId("MyComponent")); Which I'll admit looks pretty ugly. Bad points of the design: If a user of the code writes a new Component class but supplies the wrong string to the base constructor, the whole system will fail. Each time a new Component is instantiated, we must check a hashed string to see if that component type has bee instantiated before. Will probably generate a lot of assembly because of the extensive use of templates. I don't know how well the compiler will be able to minimise this. You could consider the whole system a bit complex - perhaps premature optimisation? But I want to use this code again and again, so I want it to be performant. Good points of the design: Components are stored in typed vectors but they can also be found by using their entity owner id as a hash. This means we can iterate them fast, and minimise cache misses, but also skip straight to the component we need if necessary. We can freely add Components of different types to the system without having to add and manage new Component vectors by hand. What do you think? Do the good points outweigh the bad?

    Read the article

  • Scripting a sophisticated RTS AI with Lua

    - by T. Webster
    I'm planning to develop a somewhat sophisticated RTS AI (eg see BWAPI). have experience programming, but none in game development, so it seems easiest to start by scripting the AI of an existing game I've played, Warhammer 40k: Dawn of War (2004). As far as I can tell, the game AI is scripted with some variant of Lua (by the file extension .ai or .scar). The online documentation is sparse and the community isn't active anymore. I'd like to get some idea of the difficulty of this undertaking. Is it practical with a scripting language like Lua to develop a RTS AI that includes FSMs, decision trees, case-based reasoning, and transposition tables? If someone has any experience scripting Dawn of War, that would also help.

    Read the article

  • Java 2D Rectangle Collision? [on hold]

    - by Andreas Elia
    I am just wanting to know of another (longer OR shorter) way of getting 100% effective collisions on a 2D plat-former. The current collision system that is in place works from coords on the level and does not always work reliably. Thank you in advance for any help/support. The current system draws a rectangle and is checking to see if any two points collide. From testing, the system can sometimes "glitch" and allow the player to collide into walls etc. Player Class http://pastebin.com/2zE8vz8R Main Class http://pastebin.com/A6Utb3ti

    Read the article

  • How do I position a 2D camera in OpenGL?

    - by Elfayer
    I can't understand how the camera is working. It's a 2D game, so I'm displaying a game map from (0, 0, 0) to (mapSizeX, 0, mapSizeY). I'm initializing the camera as follow : Camera::Camera(void) : position_(0.0f, 0.0f, 0.0f), rotation_(0.0f, 0.0f, -1.0f) {} void Camera::initialize(void) { glMatrixMode(GL_PROJECTION); glLoadIdentity(); glTranslatef(position_.x, position_.y, position_.z); gluPerspective(70.0f, 800.0f/600.0f, 1.0f, 10000.0f); gluLookAt(0.0f, 6000.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); } So the camera is looking down. I currently see the up right border of the map in the center of my window and the map expand to the down left border of my window. I would like to center the map. The logical thing to do should be to move the camera to eyeX = mapSizeX / 2 and the same for z. My map has 10 x 10 cases with CASE = 400, so I should have : gluLookAt((10 / 2) * CASE /* = 2000 */, 6000.0f, (10 / 2) * CASE /* = 2000 */, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f); But that doesn't move the camera, but seems to rotate it. Am I doing something wrong? EDIT : I tried that: gluLookAt(2000.0f, 6000.0f, 0.0f, 2000.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f); Which correctly moves the map in the middle of the window in width. But I can't move if correctly in height. It always returns the axis Z. When I go up, It goes down and the same for right and left. I don't see the map anymore when I do : gluLookAt(2000.0f, 6000.0f, 2000.0f, 2000.0f, 0.0f, 2000.0f, 0.0f, 1.0f, 0.0f);

    Read the article

  • XNA - 2D Rotation of an object to a selected direction

    - by lobsterhat
    I'm trying to figure out the best way of rotating an object towards the directional input of the user. I'm attempting to mimic making turns on ice skates. For instance, if the player is moving right and the input is down and left, the player should start rotating to the right a set amount each tick. I'll calculate a new vector based on current velocity and rotation and apply that to the current velocity. That should give me nice arcing turns, correct? At the moment I've got eight if/else statements for each key combination which in turn check the current rotation: // Rotate to 225 if (keyboardState.IsKeyDown(Keys.Up) && keyboardState.IsKeyDown(Keys.Left)) { // Rotate right if (rotation >= 45 || rotation < 225) { rotation += ROTATION_PER_TICK; } // Rotate left else if (rotation < 45 || rotation > 225) { rotation -= ROTATION_PER_TICK; } } This seems like a sloppy way to do this and eventually, I'll need to do this check about 10 times a tick. Any help toward a more efficient solution is appreciated.

    Read the article

  • Referencing not-yet-defined variables - Java

    - by user2537337
    Because I'm tired of solving math problems, I decided to try something more engaging with my very rusty (and even without the rust, very basic) Java skills. I landed on a super-simple people simulator, and thus far have been having a grand time working through the various steps of getting it to function. Currently, it generates an array of people-class objects and runs a for loop to cycle through a set of actions that alter the relationships between them, which I have stored in a 2d integer array. When it ends, I go look at how much they all hate each other. Fun stuff. Trouble has arisen, however, because I would like the program to clearly print what action is happening when it happens. I thought the best way to do this would be to add a string, description, to my "action" class (which stores variables for the actor, reactor, and the amount the relationship changes). This works to a degree, in that I can print a generic message ("A fight has occurred!") with no problem. However, ideally I would like it to be a little more specific ("Person A has thrown a rock at Person B's head!"). This latter goal is proving more difficult: attempting to construct an action with a description string that references actor and reactor gets me a big old error, "Cannot reference field before it is defined." Which makes perfect sense. I believe I'm not quite in programmer mode, because the only other way I can think to do this is an unwieldy switch statement that negates the need for each action to have its own nicely-packaged description. And there must be a neater way. I am not looking for examples of code, only a push in the direction of the right concept to handle this.

    Read the article

  • how to remove .php from a certain file (with apache .htaccess)

    - by user2015253
    I want a certain file (only this!) to remove the php extension for calling it. BUT: It uses get parameters and they should remain! I tried it with my .htaccess and something like: RewriteEngine on followed by either RewriteRule ^file(.*)$ file.php$1 or RewriteRule ^file(.+)$ file.php$1 but it doesn't work. (First gives error 500, second gives 404) Example what I want to call in the browser: file?param=asd&foo=bar - It should call as: file.php?param=asd&foo=bar

    Read the article

  • iOS CollectionView with horizontal paging instead of vertical scrolling

    - by Nico Griffioen
    I'm working on a project for a client. It's an iPad pdf reader. The client wants a collection view, but instead of scrolling vertically, he wants it to use a page control. It's pretty hard to explain, but what I basically want is all the PDFs on the device in a grid, like on the iBooks app. When that grid overflows, I want to use a page control to display the extra elements on a second page (like in the weather app). My thoughts on this were: - Create a page control with one page. - On that page, create a UICollectionView. - If the number of elements is greater than 9 add a page to the page control and add another UICollectionView, until there are enough pages to display all elements. However, this seems horribly inefficient, so my question is if there's a better way to do this.

    Read the article

  • Detect whether the loading image is taken from camera directly, when using smartphones

    - by Eitan
    I am using html, tag: <input type = "file" /> On android and on many cellulars I have the ability to get the file directly by taking a picture and save it. How can I know (by javascript code) how did I get the picture (direcly by the camera, or by some files that on my cellular)? I did some workarround, and found exif (http://www.nihilogic.dk/labs/exif/exif.js), but I didn't succeed using it, either I don't know whether exif is the right solution. Thanks :)

    Read the article

  • How to get my list of rows from database to show while using Zend-Paginator

    - by Matto
    I'm fairly new to the world of Zend-Framework, and have taken over a site that is in zend-framework. There is a bug on one of the pages right now and I can not figure it out. I think it has something to do with Zend Paginator, but not sure. This is the code in the controller for the section I am having a problem with: $currentPage = $this->_getParam('page'); $numWebsitesFullOnline = $websites->getWebsitesFullOnline(); $select = $websites->select(); $select->setIntegrityCheck(false); $select->from(array('w' => 'websites'), array('id', 'online', 'kw_adjective', 'kw_name', 'kw_location', 'url', 'email', 'address', 'ftp_server', 'ftp_username', 'ftp_password', 'ftp_folder', 'phone_number', 'indexed', 'youtube_position', 'twitter_user', 'facebook_id', 'video_made', 'image1_id', 'image2_id', 'image3_id', 'bg_color', 'dark_color', 'light_color', 'links_color', 'text_color', 'google_account', 'ganalytics', 'gmaps_status', 'google_position', 'gmap_position', 'hp1', 'hp2', 'hp3', 'hp4', 'hp5', 'hp6', 'hp7', 'hp8', 'hp9', 'hp10', 'about1_id', 'about2_id', 'about3_id', 'tip1_id', 'tip2_id', 'tip3_id', 'contact_texts_id', 'quote_texts_id', 'demographics_id')) ->join(array('d' => 'demographics'), 'w.demographics_id = d.id', array('total_population')) ->order(array('total_population DESC', 'kw_location')); $paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($select)); $paginator->setItemCountPerPage(50); $paginator->setCurrentPageNumber($currentPage); $paginator->setPageRange(($paginator->getTotalItemCount() / 50) + 1); $this->view->paginator = $paginator; $numWebsitesOnline = $websites->getWebsitesOnline(); On the php page I have this code to call the websites that are in the database to a list: <p class="red"> Websites online: <?php echo $this->numOnline; ?> </p> <?php print_r(count($this->paginator)); ?> <?php if(count($this->paginator)): ?> <table class="table-list"> <?php foreach($this->paginator as $item): ?> <tr> <?php if($this->userIsAllowedAction('websites', 'reload')): ?> <td class="center noborder w30"> <img class="hidden" src="<?php echo $this->baseUrl() . '/images/loader.gif' ?>" alt="Loading..."/><a class="reload" title="refresh" href="<?php echo $this->baseUrl(); ?>/utils/ui/refresh-website.php" rel="<?php echo urlencode('http://' . $item['url'] . '/install.php'); ?>,<?php echo urlencode($item['ftp_server']); ?>,<?php echo $item['ftp_username']; ?>,<?php echo $item['ftp_password']; ?>,<?php echo $item['ftp_folder']; ?>,<?php echo $this->baseUrl(); ?>,<?php echo $item['id']; ?>"><img src="<?php echo $this->baseUrl(); ?>/images/icon-refresh.png" alt="Refresh"/></a> </td> <?php endif; ?> <td class="center noborder w30"> <?php if($this->userIsAllowedAction('websites', 'edit')): ?><a title="Edit" href="<?php echo $this->url(array('controller' => 'websites', 'action' => 'edit', 'id' => $item['id'])); ?>"><img src="<?php echo $this->baseUrl(); ?>/images/icon-edit.png" alt="Edit"/></a><?php endif; ?> </td> <td class="center noborder w30"> <?php if($this->userIsAllowedAction('websites', 'remove')): ?><a title="Remove" href="<?php echo $this->url(array('controller' => 'websites', 'action' => 'remove', 'id' => $item['id'])); ?>"><img src="<?php echo $this->baseUrl(); ?>/images/icon-delete.png" alt="Remove"/></a><?php endif; ?> </td> <td> <?php if($item['online']): ?> <span class="hidden"><?php echo trim($this->escape($item['kw_adjective'] . $item['kw_name'])); ?></span><a class="goto-website" href="http://<?php echo $item['url']; ?>" target="_blank"><?php echo $this->escape($item['kw_location']); ?></a> <?php else: ?> <?php echo $this->escape($item['kw_location']); ?> <?php endif; ?> </td> <td class="center population"> <?php if($item['total_population'] >= 0) echo $item['total_population']; ?> </td> <td class="center"> <?php if(!empty($item['url'])): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/><?php endif; ?> </td> <td class="center"> <?php if(!empty($item['email'])): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/><?php endif; ?> </td> <td class="center"> <?php if($item['demographics_id']): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/><?php endif; ?> </td> <td class="center"> <?php if($item['hp1'] && $item['hp2'] && $item['hp3'] && $item['hp4'] && $item['hp5'] && $item['hp6'] && $item['hp7'] && $item['hp8'] && $item['hp9'] && $item['hp10'] && $item['about1_id'] && $item['about2_id'] && $item['about3_id'] && $item['tip1_id'] && $item['tip2_id'] && $item['tip3_id'] && $item['contact_texts_id'] && $item['quote_texts_id']): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/><?php endif; ?> </td> <td class="center"> <?php if(file_exists($_SERVER['DOCUMENT_ROOT'] . $this->baseUrl() . Zend_Registry::get('assets_base_path') . '/' . $item['id'] . '/header.jpg')): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/><?php endif; ?> </td> <td class="center"> <?php if(($item['bg_color'] != '' && $item['bg_color'] != 'e6e6e6') || ($item['dark_color'] != '' && $item['dark_color'] != '003e75') || ($item['light_color'] != '' && $item['light_color'] != '3073ad') || ($item['links_color'] != '' && $item['links_color'] != '255593') || ($item['text_color'] != '' && $item['text_color'] != '4f4f4f')): ?> <img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/> <?php endif; ?> </td> <td class="center"> <?php if($item['image1_id'] && $item['image2_id'] && $item['image3_id']): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/><?php endif; ?> </td> <td class="center"> <?php if(!empty($item['twitter_user'])): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/><?php endif; ?> </td> <td class="center"> <?php if(!empty($item['facebook_id'])): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/><?php endif; ?> </td> <td class="center"> <?php if(!empty($item['phone_number'])): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/><?php endif; ?> </td> <td class="center"> <?php if($item['google_account']): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/><?php endif; ?> </td> <td class="center"> <?php if($item['video_made']): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/><?php endif; ?> </td> <td class="center"> <?php if($item['youtube_position']) { echo $item['youtube_position']; }; ?> </td> <td class="center"> <?php if(!empty($item['address'])): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/><?php endif; ?> </td> <td class="center"> <?php if($item['gmaps_status'] == 1): ?><img src="<?php echo $this->baseUrl(); ?>/images/icon-gmapspending.png" alt="Pending"/><?php elseif($item['gmaps_status'] == 2): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/><?php endif; ?> </td> <td class="center"> <?php if(!empty($item['ganalytics'])): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark.png" alt="DONE"/><?php endif; ?> </td> <td class="center"> <?php if($item['online']): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark_red.png" alt="Online!"/><?php endif; ?> </td> <td class="center"> <?php if($item['indexed']): ?><img src="<?php echo $this->baseUrl(); ?>/images/check_mark_red.png" alt="Online!"/><?php endif; ?> </td> <td class="center"> <?php if($item['gmap_position']) { echo $item['gmap_position']; }; ?> </td> <td class="center"> <?php if($item['google_position']) { echo $item['google_position']; }; ?> </td> </tr> <?php endforeach; ?> </table> <?php endif; ?> The print_r(count($this-paginator)); line is returning "0", and the $this-numOnline; line is returning 1. So it sees that there is one row in the websites table of the database, but it is not returning anything to page and listing out the rows in the websites table. Not sure if this is the paginator that is causing this cause it is returning 0 or something else I don't know about.

    Read the article

  • Python — How can I find the square matrix of a lower triangular numpy matrix? (with a symmetrical upper triangle)

    - by Dana Gray
    I generated a lower triangular matrix, and I want to complete the matrix using the values in the lower triangular matrix to form a square matrix, symmetrical around the diagonal zeros. lower_triangle = numpy.array([ [0,0,0,0], [1,0,0,0], [2,3,0,0], [4,5,6,0]]) I want to generate the following complete matrix, maintaining the zero diagonal: complete_matrix = numpy.array([ [0, 1, 2, 4], [1, 0, 3, 5], [2, 3, 0, 6], [4, 5, 6, 0]]) Thanks.

    Read the article

  • Counting HTML images with Python

    - by user2537246
    I need some feedback on how to count HTML images with Python 3.01 after extracting them, maybe my regular expression are used properly. Here is my code: import re, os import urllib.request def get_image(url): url = 'http://www.google.com' total = 0 try: f = urllib.request.urlopen(url) for line in f.readline(): line = re.compile('<img.*?src="(.*?)">') if total > 0: x = line.count(total) total += x print('Images total:', total) except: pass

    Read the article

  • Facebook content locker function share

    - by Vicent D
    I made a facebook content locker(PHP + HTML + JAVA) for my website, so to access the site user must press the 'facebook share "in the middle of the screen.After pressing this button, it opens facebook pop-up and user can share or NOT my link because locker disappear in 30 seconds since clicked on this button(so I put it). Is there any possibility, any function that content locker disappear only after the user has actually given share in facebook pop-up window,I mean after my site address appears on facebook ? Thanks a lot

    Read the article

  • How to access a function inside a function? Python

    - by viddhart
    I am wondering how I can access a function inside another function. I saw code like this: >>> def make_adder(x): def adder(y): return x+y return adder >>> a = make_adder(5) >>> a(10) 15 So, is there another way to call the adder function? And my second question is why in the last line I call adder not adder(...)? Good explanations are much appreciated.

    Read the article

  • Pre-Populated Date in Text Field

    - by user2537332
    I am trying to pre-populate a text box with today's date, but for some reason, it keeps showing today's date as 5/30/13, which is a month behind. This code should just be pulling the local time so why is it a month behind? Here is my code, can someone please tell me why the current date is off...Please help, :) var dateToday=new Date(); function loadDate(){ var today=dateToday.getMonth() + "/" +dateToday.getDate()+"/"+dateToday.getFullYear(); document.forms[0].curDate.value=today; } function orderReady(orderTime){ dateToday.setDate(dateToday.getDate()+orderTime); var ready=dateToday.getMonth()+"/" +dateToday.getDate()+"/"+dateToday.getFullYear(); document.forms[0].puDate.value=ready; } <body onload="loadDate();"> <p>Today's Date<br /> <input type="text" name="curDate" size="50" /><br />

    Read the article

  • C - What is the proper format to allow a function to show an error was encountered?

    - by BrainSteel
    I have a question about what a function should do if the arguments to said function don't line up quite right, through no fault of the function call. Since that sentence doesn't make much sense, I'll offer my current issue. To keep it simple, here is the most relevant and basic function I have. float getYValueAt(float x, PHYS_Line line, unsigned short* error) *error = 0; if(x < line.start.x || x > line.end.x){ *error = 1; return -1; } if(line.slope.value != 0){ //line's equation: y - line.start.y = line.slope.value(x - line.start.x) return line.slope.value * (x - line.start.x) + line.start.y; } else if(line.slope.denom == 0){ if(line.start.x == x) return line.start.y; else{ *error = 1; return -1; } } else if(line.slope.num == 0){ return line.start.y; } } The function attempts to find the point on a line, given a certain x value. However, under some circumstances, this may not be possible. For example, on the line x = 3, if 5 is passed as a value, we would have a problem. Another problem arises if the chosen x value is not within the interval the line is on. For this, I included the error pointer. Given this format, a function call could work as follows: void foo(PHYS_Line some_line){ unsigned short error = 0; float y = getYValueAt(5, some_line, &error); if(error) fooey(); else do_something_with_y(y); } My question pertains to the error. Note that the value returned is allowed to be negative. Returning -1 does not ensure that an error has occurred. I know that it is sometimes preferred to use the following method to track an error: float* getYValueAt(float x, PHYS_Line line); and then return NULL if an error occurs, but I believe this requires dynamic memory allocation, which seems even less sightly than the solution I was using. So, what is standard practice for an error occurring?

    Read the article

  • InternalsVisibleTo attribute and security vulnerability

    - by Sergey Litvinov
    I found one issue with InternalsVisibleTo attribute usage. The idea of InternalsVisibleTo attribute to allow some other assemblies to use internal classes\methods of this assembly. To make it work you need sign your assemblies. So, if other assemblies isn't specified in main assembly and if they have incorrect public key, then they can't use Internal members. But the issue in Reflection Emit type generation. For example, we have CorpLibrary1 assembly and it has such class: public class TestApi { internal virtual void DoSomething() { Console.WriteLine("Base DoSomething"); } public void DoApiTest() { // some internal logic // ... // call internal method DoSomething(); } } This assembly is marked with such attribute to allow another CorpLibrary2 to make inheritor for that TestAPI and override behaviour of DoSomething method. [assembly: InternalsVisibleTo("CorpLibrary2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100434D9C5E1F9055BF7970B0C106AAA447271ECE0F8FC56F6AF3A906353F0B848A8346DC13C42A6530B4ED2E6CB8A1E56278E664E61C0D633A6F58643A7B8448CB0B15E31218FB8FE17F63906D3BF7E20B9D1A9F7B1C8CD11877C0AF079D454C21F24D5A85A8765395E5CC5252F0BE85CFEB65896EC69FCC75201E09795AAA07D0")] The issue is that I'm able to override this internal DoSomething method and break class logic. My steps to do it: Generate new assembly in runtime via AssemblyBuilder Get AssemblyName from CorpLibrary1 and copy PublikKey to new assembly Generate new assembly that will inherit TestApi class As PublicKey and name of generated assembly is the same as in InternalsVisibleTo, then we can generate new DoSomething method that will override internal method in TestAPI assembly Then we have another assembly that isn't related to this CorpLibrary1 and can't use internal members. We have such test code in it: class Program { static void Main(string[] args) { var builder = new FakeBuilder(InjectBadCode, "DoSomething", true); TestApi fakeType = builder.CreateFake(); fakeType.DoApiTest(); // it will display: // Inject bad code // Base DoSomething Console.ReadLine(); } public static void InjectBadCode() { Console.WriteLine("Inject bad code"); } } And this FakeBuilder class has such code: /// /// Builder that will generate inheritor for specified assembly and will overload specified internal virtual method /// /// Target type public class FakeBuilder { private readonly Action _callback; private readonly Type _targetType; private readonly string _targetMethodName; private readonly string _slotName; private readonly bool _callBaseMethod; public FakeBuilder(Action callback, string targetMethodName, bool callBaseMethod) { int randomId = new Random((int)DateTime.Now.Ticks).Next(); _slotName = string.Format("FakeSlot_{0}", randomId); _callback = callback; _targetType = typeof(TFakeType); _targetMethodName = targetMethodName; _callBaseMethod = callBaseMethod; } public TFakeType CreateFake() { // as CorpLibrary1 can't use code from unreferences assemblies, we need to store this Action somewhere. // And Thread is not bad place for that. It's not the best place as it won't work in multithread application, but it's just a sample LocalDataStoreSlot slot = Thread.AllocateNamedDataSlot(_slotName); Thread.SetData(slot, _callback); // then we generate new assembly with the same nameand public key as target assembly trusts by InternalsVisibleTo attribute var newTypeName = _targetType.Name + "Fake"; var targetAssembly = Assembly.GetAssembly(_targetType); AssemblyName an = new AssemblyName(); an.Name = GetFakeAssemblyName(targetAssembly); // copying public key to new generated assembly var assemblyName = targetAssembly.GetName(); an.SetPublicKey(assemblyName.GetPublicKey()); an.SetPublicKeyToken(assemblyName.GetPublicKeyToken()); AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(an, AssemblyBuilderAccess.RunAndSave); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyBuilder.GetName().Name, true); // create inheritor for specified type TypeBuilder typeBuilder = moduleBuilder.DefineType(newTypeName, TypeAttributes.Public | TypeAttributes.Class, _targetType); // LambdaExpression.CompileToMethod can be used only with static methods, so we need to create another method that will call our Inject method // we can do the same via ILGenerator, but expression trees are more easy to use MethodInfo methodInfo = CreateMethodInfo(moduleBuilder); MethodBuilder methodBuilder = typeBuilder.DefineMethod(_targetMethodName, MethodAttributes.Public | MethodAttributes.Virtual); ILGenerator ilGenerator = methodBuilder.GetILGenerator(); // call our static method that will call inject method ilGenerator.EmitCall(OpCodes.Call, methodInfo, null); // in case if we need, then we put call to base method if (_callBaseMethod) { var baseMethodInfo = _targetType.GetMethod(_targetMethodName, BindingFlags.NonPublic | BindingFlags.Instance); // place this to stack ilGenerator.Emit(OpCodes.Ldarg_0); // call the base method ilGenerator.EmitCall(OpCodes.Call, baseMethodInfo, new Type[0]); // return ilGenerator.Emit(OpCodes.Ret); } // generate type, create it and return to caller Type cheatType = typeBuilder.CreateType(); object type = Activator.CreateInstance(cheatType); return (TFakeType)type; } /// /// Get name of assembly from InternalsVisibleTo AssemblyName /// private static string GetFakeAssemblyName(Assembly assembly) { var internalsVisibleAttr = assembly.GetCustomAttributes(typeof(InternalsVisibleToAttribute), true).FirstOrDefault() as InternalsVisibleToAttribute; if (internalsVisibleAttr == null) { throw new InvalidOperationException("Assembly hasn't InternalVisibleTo attribute"); } var ind = internalsVisibleAttr.AssemblyName.IndexOf(","); var name = internalsVisibleAttr.AssemblyName.Substring(0, ind); return name; } /// /// Generate such code: /// ((Action)Thread.GetData(Thread.GetNamedDataSlot(_slotName))).Invoke(); /// private LambdaExpression MakeStaticExpressionMethod() { var allocateMethod = typeof(Thread).GetMethod("GetNamedDataSlot", BindingFlags.Static | BindingFlags.Public); var getDataMethod = typeof(Thread).GetMethod("GetData", BindingFlags.Static | BindingFlags.Public); var call = Expression.Call(allocateMethod, Expression.Constant(_slotName)); var getCall = Expression.Call(getDataMethod, call); var convCall = Expression.Convert(getCall, typeof(Action)); var invokExpr = Expression.Invoke(convCall); var lambda = Expression.Lambda(invokExpr); return lambda; } /// /// Generate static class with one static function that will execute Action from Thread NamedDataSlot /// private MethodInfo CreateMethodInfo(ModuleBuilder moduleBuilder) { var methodName = "_StaticTestMethod_" + _slotName; var className = "_StaticClass_" + _slotName; TypeBuilder typeBuilder = moduleBuilder.DefineType(className, TypeAttributes.Public | TypeAttributes.Class); MethodBuilder methodBuilder = typeBuilder.DefineMethod(methodName, MethodAttributes.Static | MethodAttributes.Public); LambdaExpression expression = MakeStaticExpressionMethod(); expression.CompileToMethod(methodBuilder); var type = typeBuilder.CreateType(); return type.GetMethod(methodName, BindingFlags.Static | BindingFlags.Public); } } remarks about sample: as we need to execute code from another assembly, CorpLibrary1 hasn't access to it, so we need to store this delegate somewhere. Just for testing I stored it in Thread NamedDataSlot. It won't work in multithreaded applications, but it's just a sample. I know that we use Reflection to get private\internal members of any class, but within reflection we can't override them. But this issue is allows anyone to override internal class\method if that assembly has InternalsVisibleTo attribute. I tested it on .Net 3.5\4 and it works for both of them. How does it possible to just copy PublicKey without private key and use it in runtime? The whole sample can be found there - https://github.com/sergey-litvinov/Tests_InternalsVisibleTo UPDATE1: That test code in Program and FakeBuilder classes hasn't access to key.sn file and that library isn't signed, so it hasn't public key at all. It just copying it from CorpLibrary1 by using Reflection.Emit

    Read the article

  • Cannot await 'Model.PersonalInfo'

    - by Gooftroop
    I have the following method in a DesignDataService class public async Task<T> GetData<T>(T dataObject) { var typeName = typeof(T).Name; switch (typeName) { case "PersonalInfo": var person = new PersonalInfo { FirstName = "Mickey", LastName = "Mouse" , Adres = new Address{Country="DLRP"} , }; return await person; } // end Switch } // GetData<T> How can I return a new PersonalInfo class from the DataService? For now I get the error Cannot await 'Model.PersonalInfo' Even when I change the return statement as follows return await person as Task; the error stays the same Thanks in advanced Danny

    Read the article

  • Images not responsive although in responsive container

    - by Darren Sweeney
    I have the following: <div id="hp_imgs"> <img src="/images/hp/1.jpg"> <img src="/images/hp/2.jpg"> <img src="/images/hp/3.jpg"> <img src="/images/hp/4.jpg"> <img src="/images/hp/5.jpg"> <img src="/images/hp/6.jpg"> <img src="/images/hp/7.jpg"> <img src="/images/hp/8.jpg"> </div> The images were sized when created to form a grid of sorts, so need to be in the order where they are. Consequently, when/if the page is resized I want the images to resize and stay where they are. Here's what I'm trying but images are simply staying the same size and not resizing: #hp_imgs { width:66%; float:left; } #hp_imgs img { float:left; margin:2px; border-radius:4px; display: block; max-width:100%; height:100%; } Is there a better/different way to achieve this? FIDDLE Here's a sample to play with: Fiddle

    Read the article

  • Unique_ptr compiler errors

    - by Godric Seer
    I am designing and entity-component system for a project, and C++ memory management is giving me a few issues. I just want to make sure my design is legitimate. So to start I have an Entity class which stores a vector of Components: class Entity { private: std::vector<std::unique_ptr<Component> > components; public: Entity() { }; void AddComponent(Component* component) { this -> components.push_back(std::unique_ptr<Component>(component)); } ~Entity(); }; Which if I am not mistaken means that when the destructor is called (even the default, compiler created one), the destructor for the Entity, will call ~components, which will call ~std::unique_ptr for each element in the vector, and lead to the destruction of each Component, which is what I want. The component class has virtual methods, but the important part is its constructor: Component::Component(Entity parent) { parent.addComponent(this) // I am not sure if this would work like I expect // Other things here } As long as passing this to the method works, this also does what I want. My confusion is in the factory. What I want to do is something along the lines of: std::shared_ptr<Entity> createEntity() { std::shared_ptr<Entity> entityPtr(new Entity()); new Component(*parent); // Initialize more, and other types of Components return entityPtr; } Now, I believe that this setup will leave the ownership of the Component in the hands of its Parent Entity, which is what I want. First a small question, do I need to pass the entity into the Component constructor by reference or pointer or something? If I understand C++, it would pass by value, which means it gets copied, and the copied entity would die at the end of the constructor. The second, and main question is that code based on this sample will not compile. The complete error is too large to print here, however I think I know somewhat of what is going on. The compiler's error says I can't delete an incomplete type. My Component class has a purely virtual destructor with an implementation: inline Component::~Component() { }; at the end of the header. However since the whole point is that Component is actually an interface. I know from here that a complete type is required for unique_ptr destruction. The question is, how do I work around this? For reference I am using gcc 4.4.6.

    Read the article

  • RubyMotion Error When Using setTranslucent

    - by Sam Morris
    I'm getting the following error when trying rake a project I'm working on, and I can't figure out why. The message happens no matter what variable I sent it. Objective-C stub for message `setTranslucent:' type `v@:c' not precompiled. Make sure you properly link with the framework or library that defines this message Here's my app_delegate file for reference. class AppDelegate def application(application, didFinishLaunchingWithOptions:launchOptions) navigation_appearance @window = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds) tableView = StopsController.alloc.init @window.rootViewController = UINavigationController.alloc.initWithRootViewController(tableView) @window.makeKeyAndVisible true end def navigation_appearance UINavigationBar.appearance.setBackgroundImage UIImage.imageNamed('navbar_bg.png'), forBarMetrics: UIBarMetricsDefault UINavigationBar.appearance.setTranslucent(true) UINavigationBar.appearance.setShadowImage UIImage.imageNamed('navbar_shadow.png') end end

    Read the article

  • Same Origin issue with web service call

    - by Wjdavis5
    My web server runs at http://mypc.com:80 ` Given the following snip: $(window).load(function () { var myURL = "http://mypc.com:8000/PSOCharts/service/HighChart_ColumnChart/i"; $.getJSON(myURL) .done(function(data) {alert(data);}); }); I am running to this error: XMLHttpRequest cannot load http://mypc.com:8000/PSOCharts/service/HighChart_ColumnChart/i. Origin http://mypc.com is not allowed by Access-Control-Allow-Origin. I understand why (I think) b/c my webservice runs at port 8000 which is different from what IIS is running on (port 80). I thought I could get around by using jsonp (according to the jQuery documentation here So I copied the example of making a call to the flickr api, but it isnt working. Any thoughts/sugggestions? UPDATE Ok so my request is being made now: var myURL = "http://192.168.1.104:8000/PSOCharts/service/HighChart_ColumnChart/i?jsoncallback=?"; $.ajax({ url :myURL, dataType: "jsonp", success: function(data) {a(data)} , error: function(){alert("err");}, }); But I am continually hitting the error function, here is what's being returned: [1.4,54.43,49.39,93.23] Now I'm assuming this is b/c the response text doesnt contain any type of callback here is the part of the interface I'm calling: [WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "HighChart_ColumnChart/{id}?callback={cb}")] List<double> HighChart_ColumnChart(string id,string cb); Here is the actual function being called: public List<double> HighChart_ColumnChart(string id,string cb) { var z = new List<double>(); z.Add(1.4); z.Add(54.43); z.Add(49.39); z.Add(93.23); return z; } when I debug, the CB param is something like : "jQuery19108121746340766549_1372630643878". How do I modify the code to wrap it correctly? Thanks for the help thus far!

    Read the article

  • Can't obtain reference to EKReminder array retrieved from fetchRemindersMatchingPredicate

    - by Scionwest
    When I create an NSPredicate via EKEventStore predicateForRemindersInCalendars; and pass it to EKEventStore fetchRemindersMatchingPredicate:completion:^ I can loop through the reminders array provided by the completion code block, but when I try to store a reference to the reminders array, or create a copy of the array into a local variable or instance variable, both array's remain empty. The reminders array is never copied to them. This is the method I am using, in the method, I create a predicate, pass it to the event store and then loop through all of the reminders logging their title via NSLog. I can see the reminder titles during runtime thanks to NSLog, but the local arrayOfReminders object is empty. I also try to add each reminder into an instance variable of NSMutableArray, but once I leave the completion code block, the instance variable remains empty. Am I missing something here? Can someone please tell me why I can't grab a reference to all of the reminders for use through-out the app? I am not having any issues at all accessing and storing EKEvents, but for some reason I can't do it with EKReminders. - (void)findAllReminders { NSPredicate *predicate = [self.eventStore predicateForRemindersInCalendars:nil]; __block NSArray *arrayOfReminders = [[NSArray alloc] init]; [self.eventStore fetchRemindersMatchingPredicate:predicate completion:^(NSArray *reminders) { arrayOfReminders = [reminders copy]; //Does not work. for (EKReminder *reminder in reminders) { [self.remindersForTheDay addObject:reminder]; NSLog(@"%@", reminder.title); } }]; //Always = 0; if ([self.remindersForTheDay count]) { NSLog(@"Instance Variable has reminders!"); } //Always = 0; if ([arrayOfReminders count]) { NSLog(@"Local Variable has reminders!"); } } The eventStore getter is where I perform my instantiation and get access to the event store. - (EKEventStore *)eventStore { if (!_eventStore) { _eventStore = [[EKEventStore alloc] init]; //respondsToSelector indicates iOS 6 support. if ([_eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)]) { //Request access to user calendar [_eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) { if (granted) { NSLog(@"iOS 6+ Access to EventStore calendar granted."); } else { NSLog(@"Access to EventStore calendar denied."); } }]; //Request access to user Reminders [_eventStore requestAccessToEntityType:EKEntityTypeReminder completion:^(BOOL granted, NSError *error) { if (granted) { NSLog(@"iOS 6+ Access to EventStore Reminders granted."); } else { NSLog(@"Access to EventStore Reminders denied."); } }]; } else { //iOS 5.x and lower support if Selector is not supported NSLog(@"iOS 5.x < Access to EventStore calendar granted."); } for (EKCalendar *cal in self.calendars) { NSLog(@"Calendar found: %@", cal.title); } [_eventStore reset]; } return _eventStore; } Lastly, just to show that I am initializing my remindersForTheDay instance variable using lazy instantiation. - (NSMutableArray *)remindersForTheDay { if (!_remindersForTheDay) _remindersForTheDay = [[NSMutableArray alloc] init]; return _remindersForTheDay; } I've read through the Apple documentation and it doesn't provide any explanation that I can find to answer this. I read through the Blocks Programming docs and it states that you can access local and instance variables without issues from within a block, but for some reason, the above code does not work. Any help would be greatly appreciated, I've scoured Google for answers but have yet to get this figured out. Thanks everyone! Johnathon.

    Read the article

  • Setting XTick or XLabels for a plot containing millisecond data

    - by Dave
    I am trying to set the X-Axis labels on a plot. I have a vector of times, these go down to the millisecond level. I have tried setting both XTick and XTickLabel properties but things are not working correctly (labels are not valid). Any suggestions on what one needs to do to get datetick to work when working with times that go down to the second/millisecond level? Are there any alternatives to using datetick? Any suggestions are appreciated.

    Read the article

  • Java Simple Calculator

    - by Lahiru Kavinda
    I have made this calculator program in Java. This works well only when two numbers are calculated at one time. That means to get the sum of 1+2+3 you have to go this way : press 1 press + press 2 press = press + press 3 press = and it calculates it as 6. But I want to program this so that I can get the answer by: press 1 press + press 2 press + press 3 press = but this gives the answer 5!!! How to code this so that it works like an ordinary calculator? Here is my code: import java.awt.*; import java.awt.event.*; import javax.swing.*; public class cal1 extends JFrame { double op1 = 0d, op2 = 0d; double result = 0d; char action; boolean b = false; boolean pressequal = false; public cal1() { makeUI(); } private void makeUI() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 400); b0 = new JButton("0"); b1 = new JButton("1"); b2 = new JButton("2"); b3 = new JButton("3"); b4 = new JButton("4"); b5 = new JButton("5"); b6 = new JButton("6"); b7 = new JButton("7"); b8 = new JButton("8"); b9 = new JButton("9"); bDot = new JButton("."); bMul = new JButton("*"); bDiv = new JButton("/"); bPlus = new JButton("+"); bMinus = new JButton("-"); bEq = new JButton("="); t = new JTextField(12); t.setFont(new Font("Tahoma", Font.PLAIN, 24)); t.setHorizontalAlignment(JTextField.RIGHT); numpad = new JPanel(); display = new JPanel(); numpad.add(b7); numpad.add(b8); numpad.add(b9); numpad.add(bMul); numpad.add(b4); numpad.add(b5); numpad.add(b6); numpad.add(bDiv); numpad.add(b1); numpad.add(b2); numpad.add(b3); numpad.add(bMinus); numpad.add(bDot); numpad.add(b0); numpad.add(bEq); numpad.add(bPlus); numpad.setLayout(new GridLayout(4, 5, 5, 4)); display.add(t); add(display, BorderLayout.NORTH); add(numpad, BorderLayout.CENTER); t.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { typeOnt(e); } }); b0.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b0pressed(e); } }); b1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b1pressed(e); } }); b2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b2pressed(e); } }); b3.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b3pressed(e); } }); b4.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b4pressed(e); } }); b5.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b5pressed(e); } }); b6.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b6pressed(e); } }); b7.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b7pressed(e); } }); b8.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b8pressed(e); } }); b9.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { b9pressed(e); } }); bDot.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { bDotpressed(e); } }); bPlus.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { bPlusPressed(e); } }); bMinus.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { bMinusPressed(e); } }); bMul.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { bMulPressed(e); } }); bDiv.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { bDivPressed(e); } }); bEq.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { bEqpressed(e); } }); } void typeOnt(KeyEvent e) { e.consume(); } void b0pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "0"); } else { t.setText(t.getText() + "0"); } } void b1pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "1"); } else { t.setText(t.getText() + "1"); } } void b2pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "2"); } else { t.setText(t.getText() + "2"); } } void b3pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "3"); } else { t.setText(t.getText() + "3"); } } void b4pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "4"); } else { t.setText(t.getText() + "4"); } } void b5pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "5"); } else { t.setText(t.getText() + "5"); } } void b6pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "6"); } else { t.setText(t.getText() + "6"); } } void b7pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "7"); } else { t.setText(t.getText() + "7"); } } void b8pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "8"); } else { t.setText(t.getText() + "8"); } } void b9pressed(ActionEvent e) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "9"); } else { t.setText(t.getText() + "9"); } } void bDotpressed(ActionEvent e) { if (!t.getText().contains(".")) { if (b) { t.setText(null); b = false; t.setText(t.getText() + "0."); } else if (t.getText().isEmpty()) { t.setText("0."); } else { t.setText(t.getText() + "."); } } } void bPlusPressed(ActionEvent e) { b = true; action = '+'; op1 = Double.parseDouble(t.getText()); } void bMinusPressed(ActionEvent e) { b = true; action = '-'; op1 = Double.parseDouble(t.getText()); } void bMulPressed(ActionEvent e) { b = true; action = '*'; op1 = Double.parseDouble(t.getText()); } void bDivPressed(ActionEvent e) { b = true; action = '/'; op1 = Double.parseDouble(t.getText()); } void bEqpressed(ActionEvent e) { op2 = Double.parseDouble(t.getText()); doCal(); } void doCal() { switch (action) { case '+': result = op1 + op2; break; case '-': result = op1 - op2; break; case '*': result = op1 * op2; break; case '/': result = op1 / op2; break; } t.setText(String.valueOf(result)); } public static void main(String[] args) { new cal1().setVisible(true); } JButton b0; JButton b1; JButton b2; JButton b3; JButton b4; JButton b5; JButton b6; JButton b7; JButton b8; JButton b9; JButton bDot; JButton bPlus; JButton bMinus; JButton bMul; JButton bDiv; JButton bEq; JPanel display; JPanel numpad; JTextField t; }

    Read the article

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