Search Results

Search found 1234 results on 50 pages for 'enum'.

Page 41/50 | < Previous Page | 37 38 39 40 41 42 43 44 45 46 47 48  | Next Page >

  • Culture Sensitive GetHashCode

    - by user114928
    Hi, I'm writing a c# application that will process some text and provide basic query functions. In order to ensure the best possible support for other languages, I am allowing the users of the application to specify the System.Globalization.CultureInfo (via the "en-GB" style code) and also the full range of collation options using the System.Globalization.CompareOptions flags enum. For regular string comparison I'm then using a combination of: a) String.Compare overload that accepts the culture and options b) For some bulk processes I'm caching the byte data (KeyData) from CompareInfo.GetSortKey (overload that accepts the options) and using a byte-by-byte comparison of the KeyData. This seemed fine (although please comment if you think these two methods shouldn't be mixed), but then I had reason to use the HashSet< class which only has an overload for IEqualityComparer<. MS documentation seems to suggest that I should use StringComparer (which implements both IEqualityComparer< and IComparer<), but this only seems to support the "IgnoreCase" option from CompareOptions and not "IgnoreKanaType", "IgnoreSymbols", "IgnoreWidth" etc. I'm assuming that a StringComparer that ignores these other options could produce different hashcodes for two strings that might be considered the same using my other comparison options. I'd therefore get incorrect results from my application. Only thought at the moment is to create my own IEqualityComparer< that generates a hashcode from the SortKey.KeyData and compares eqality be using the String.Compare overload. Any suggestions?

    Read the article

  • Loading enumerations from database

    - by Mosh
    Hello, I have a problem with mapping .NET enumerations to database tables. Imagine I have a table called Statuses with the following values: StatusID | Name 1 Draft 2 Ready ... ... In the application layer, I can either use a Repository to get all Statuses as an IList object. However, the problem with this approach is that I cannot reference a certain status in my business logic. For example, how can I implement something like this? if (myObject.Status is Ready) do this else if (myObject.Status is Draft) do that... Since the statuses are loaded dynamically, I cannot tell for sure what particular Status object in the List represents the Draft or Ready status. Alternatively, I could just use an enumeration like public enum Statuses { Draft, Ready }; Then I could easily use an enumeration in my business logic. if (myObject.Status == Statuses.Draft) // do something... However, the problem with this approach is that every time the user wants to modify the list of Statuses (adding a new status, or renaming an existing status) the application has to be re-compiled. We cannot load the statuses dynamically from the database. Has anyone else come across a similar situation? Any solutions/patterns? Cheers, Mosh

    Read the article

  • Simply doing modelType.ToString() isn't sufficient, How can i use it via Activator.CreateInstance?

    - by programmerist
    public class MyController { public object CreateByEnum(DataModelType modeltype) { string enumText = modeltype.ToString(); // will return for example "Company" Type classType = Type.GetType(enumText); // the Type for Company class object t = Activator.CreateInstance(classType); // create an instance of Company class return t; } } public class CompanyView { public static List<Personel> GetPersonel() { MyController controller = new MyController(); _Company company = controller.CreateByEnum(DataModelType.Company) as _Company; return company.GetPersonel(); } } public enum DataModelType { xyz, klm, tucyz, Company } Yes, I agree Activator.CreateInstance() is very useful. Unfortunately, I need to pass in the correct type. That means building the correct string to pass to Type.GetType(). If I trace through the call to Controller.CreatebyEnum() in the code I posted above, simply doing modelType.ToString() isn't sufficient, even for the case of DataModelType.Company. My solution'll be maintenance bottleneck. What would be better is something that takes the results of modelType.ToString() and then recursively searches through all the types found in all the assemblies loaded in the current AppDomain. According to MSDN, Type.GetType() only searches the current calling assembly, and mscorlib.dll. How can i do that? . i need best performance?

    Read the article

  • MFC CDialog not showing

    - by Jesus_21
    here is my problem : In my Solution, I have 2 projects, one is a lib in which I created a ressource file (mylib.rc) and a dialog template in it. Then I made a class which inherits CDialog and uses this template. But when I instantiate it and call DoModal(), nothing appends... here the code of my class, is something wrong with it ? MyDialog.h /*MyDialog.h*/ #pragma once #include "../../../resource.h" class MyDialog : public CDialog { enum {IDD=IDD_DLGTEMPLATE}; public: MyDialog(CWnd* pParent = NULL); virtual ~MyDialog(); protected: virtual BOOL OnInitDialog(); DECLARE_MESSAGE_MAP() private: afx_msg void OnBnClickedOk(); afx_msg void OnBnClickedCancel(); }; MyDialog.cpp /*MyDialog.cpp*/ #include "stdafx.h" #include "MyDialog.h" MyDialog::MyDialog(CWnd* pParent /*=NULL*/) : CDialog(IDD_DLGTEMPLATE, pParent) {} MyDialog::~MyDialog() {} BOOL MyDialog::OnInitDialog() { return TRUE; } BEGIN_MESSAGE_MAP(MyDialog, CDialog) ON_BN_CLICKED(IDOK, &MyDialog::OnBnClickedOk) ON_BN_CLICKED(IDCANCEL, &MyDialog::OnBnClickedCancel) END_MESSAGE_MAP() void MyDialog::OnBnClickedOk() { OnOK(); } void MyDialog::OnBnClickedCancel() { OnCancel(); }

    Read the article

  • java singleton instantiation

    - by jurchiks
    I've found three ways of instantiating a Singleton, but I have doubts as to whether any of them is the best there is. I'm using them in a multi-threaded environment and prefer lazy instantiation. Sample 1: private static final ClassName INSTANCE = new ClassName(); public static ClassName getInstance() { return INSTANCE; } Sample 2: private static class SingletonHolder { public static final ClassName INSTANCE = new ClassName(); } public static ClassName getInstance() { return SingletonHolder.INSTANCE; } Sample 3: private static ClassName INSTANCE; public static synchronized ClassName getInstance() { if (INSTANCE == null) INSTANCE = new ClassName(); return INSTANCE; } The project I'm using ATM uses Sample 2 everywhere, but I kind of like Sample 3 more. There is also the Enum version, but I just don't get it. The question here is - in which cases I should/shouldn't use any of these variations? I'm not looking for lengthy explanations though (there's plenty of other topics about that, but they all eventually turn into arguing IMO), I'd like it to be understandable with few words.

    Read the article

  • Is it possible to order by a composite key with JPA and CriteriaBuilder

    - by Kjir
    I would like to create a query using the JPA CriteriaBuilder and I would like to add an ORDER BY clause. This is my entity: @Entity @Table(name = "brands") public class Brand implements Serializable { public enum OwnModeType { OWNER, LICENCED } @EmbeddedId private IdBrand id; private String code; //bunch of other properties } Embedded class is: @Embeddable public class IdBrand implements Serializable { @ManyToOne private Edition edition; private String name; } And the way I am building my query is like this: CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Brand> q = cb.createQuery(Brand.class).distinct(true); Root<Brand> root = q.from(Brand.class); if (f != null) { f.addCriteria(cb, q, root); f.addOrder(cb, q, root, sortCol, ascending); } return em.createQuery(q).getResultList(); And here are the functions called: public void addCriteria(CriteriaBuilder cb, CriteriaQuery<?> q, Root<Brand> r) { } public void addOrder(CriteriaBuilder cb, CriteriaQuery<?> q, Root<Brand> r, String sortCol, boolean ascending) { if (ascending) { q.orderBy(cb.asc(r.get(sortCol))); } else { q.orderBy(cb.desc(r.get(sortCol))); } } If I try to set sortCol to something like "id.edition.number" I get the following error: javax.ejb.EJBException: java.lang.IllegalArgumentException: Unable to resolve attribute [id.name] against path Any idea how I could accomplish that? I tried searching online, but I couldn't find a hint about this... Also would be great if I could do a similar ORDER BY when I have a @ManyToOne relationship (for instance, "id.edition.number")

    Read the article

  • Sorting by custom field and fetching whole tree from DB

    - by Niaxon
    Hello everyone, I am trying to do file browser in a tree form and have a problem to sort it somehow. I use PHP and MySQL for that. I've created mixed (nested set + adjacency) table 'element' with the following fields: element_id, left_key, right_key, level, parent_id, element_name, element_type (enum: 'folder','file'), element_size. Let's not discuss right now that it is better to move information about element (name, type, size) into other table. Function to scan specified directory and fill table work correctly. Noteworthy, i am adding elements to tree in specific order: folders first and then files. After that i can easily fetch and display whole table on the page using simple query: SELECT * FROM element WHERE 1=1 ORDER BY left_key With the result of that query and another function i can generate correct html code (<ul><li>... and so on). to display tree. Now back to the question (finally, huh?). I am struggling to add sorting functionality. For example i want to order my result by size. Here i need to keep in my mind whole hierarchy of tree and rule: folders first, files later. I believe i can do that by generating in PHP recursive query: SELECT * FROM element WHERE parent_id = {$parentId} ORDER BY element_type (so folders would be first), size (or name for example) asc/desc After that for each result which has type = 'folder' i will send another query to get it's content. Also it's possible to fetch whole tree by left_key and after that sort it in PHP as array but i guess that would be worse :) I wonder if there is better and more efficient way to do such a thing?

    Read the article

  • Bitwise OR of constants

    - by ryyst
    While reading some documentation here, I came across this: unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit; NSDateComponents *comps = [gregorian components:unitFlags fromDate:date]; I have no idea how this works. I read up on the bitwise operators in C, but I do not understand how you can fit three (or more!) constants inside one int and later being able to somehow extract them back from the int? Digging further down the documentation, I also found this, which is probably related: typedef enum { kCFCalendarUnitEra = (1 << 1), kCFCalendarUnitYear = (1 << 2), kCFCalendarUnitMonth = (1 << 3), kCFCalendarUnitDay = (1 << 4), kCFCalendarUnitHour = (1 << 5), kCFCalendarUnitMinute = (1 << 6), kCFCalendarUnitSecond = (1 << 7), kCFCalendarUnitWeek = (1 << 8), kCFCalendarUnitWeekday = (1 << 9), kCFCalendarUnitWeekdayOrdinal = (1 << 10), } CFCalendarUnit; How do the (1 << 3) statements / variables work? I'm sorry if this is trivial, but could someone please enlighten me by either explaining or maybe posting a link to a good explanation? Thanks! -- ry

    Read the article

  • How to check if two records have a self-referencing relation?

    - by Machine
    Consider the following schema with users and their collegues (friends): Users User: columns: user_id: name: user_id as userId type: integer(8) unsigned: 1 primary: true autoincrement: true first_name: name: first_name as firstName type: string(45) notnull: true last_name: name: last_name as lastName type: string(45) notnull: true email: type: string(45) notnull: true unique: true relations: Collegues: class: User local: invitor foreign: invitee refClass: CollegueStatus equal: true onDelete: CASCADE onUpdate: CASCADE Join table: CollegueStatus: columns: invitor: type: integer(8) unsigned: 1 primary: true invitee: type: integer(8) unsigned: 1 primary: true status: type: enum(8) values: [pending, accepted, denied] default: pending notnull: true Now, let's say I two records, one for the user making a HTTP request (the logged in user), and one record for a user he wants to send a message to. I want to check if these users are collegues. Questions: Does Doctrine have any pre-build functionality to check if two records with with self-relations are related? If not, how would you write a method to check this? Where would you put said method? (In the User-class, UserTable-class etc) I could probably do something like this: public function (User $user1, User $user2) { // Ensure we load collegues if $user1 was fetched with DQL that // doesn't load this relation $collegues = $user1->get('Collegues'); $areCollegues = false; foreach($collegues as $collegue) { if($collegue['userId'] === $user2['userId']) { $areCollegues = true; break; } } return $areCollegues; } But this looks a neither efficient nor pretty. I just feel that it should be solved already for self-referencing relations to be nice to use.

    Read the article

  • How to extend this design for a generic converter in java?

    - by Jay
    Here is a small currency converter piece of code: public enum CurrencyType { DOLLAR(1), POUND(1.2), RUPEE(.25); private CurrencyType(double factor) { this.factor = factor; } private double factor; public double getFactor() { return factor; } } public class Currency { public Currency(double value, CurrencyType type) { this.value = value; this.type = type; } private CurrencyType type; private double value; public CurrencyType getCurrencyType() { return type; } public double getCurrencyValue() { return value; } public void setCurrenctyValue(double value){ this.value = value; } } public class CurrencyConversion { public static Currency convert(Currency c1, Currency c2) throws Exception { if (c1 != null && c2 != null) { c2.setCurrenctyValue(c1.getCurrencyValue() * c1.getCurrencyType().getFactor() * c2.getCurrencyType().getFactor()); return c2; } else throw new Exception(); } } I would like to improve this code to make it work for different units of conversion, for example: kgs to pounds, miles to kms, etc etc. Something that looks like this: public class ConversionManager<T extends Convertible> { public T convert(T c1, T c2) { //return null; } } Appreciate your ideas and suggestions.

    Read the article

  • d2: assigning ranges/iterators to array slices

    - by modchan
    Consider following code: enum size = 16; double[size] arr1 = [...]; double[size] arr2 = [...]; process = (double x) { return (x + 1); }; arr2[] = map!(process)(arr1[]); // here I have trouble converting results of map back to my plain array. Problem applies not only to map, but also to take, repeat and all those fine tools from std.algorithm and std.range that operate on ranges. On this assignment, I get Error: cannot implicitly convert expression (map(arr1[])) of type Result to double[]. How can I evaluate range to array without using uint i = 0; foreach (x; map!(process)(arr1[])) { arr2[i] = x; i++; } ? Additionally, can someone please explain, why I must call map!(process)(arr1[]) instead of map!(process)(arr1) with static arrays? Shouldn't static arrays be compatible with dynamic for means of iteration, or I don't get something? Also, it seems that straightforward enumeration syntax foreach (index, item; sequence) does not work for ranges - are there workarounds? I guess the reason is the same as why ranges cannot be assigned to array slices.

    Read the article

  • Is there any benefit to my rather quirky character sizing convention?

    - by Paul Alan Taylor
    I love things that are a power of 2. I celebrated my 32nd birthday knowing it was the last time in 32 years I'd be able to claim that my age was a power of 2. I'm obsessed. It's like being some Z-list Batman villain, except without the colourful adventures and a face full of batarangs. I ensure that all my enum values are powers of 2, if only for future bitwise operations, and I'm reasonably assured that there is some purpose (even if latent) for doing it. Where I'm less sure, is in how I define the lengths of database fields. Again, I can't help it. Everything ends up being a power of 2. CREATE TABLE Person ( PersonID int IDENTITY PRIMARY KEY ,Firstname varchar(64) ,Surname varchar(128) ) Can any SQL super-boffins who know about the internals of how stuff is stored and retrieved tell me whether there is any benefit to my inexplicable obsession? Is it more efficient to size character fields this way? Can anyone pop in with an "actually, what you're doing works because ....."? I suspect I'm just getting crazier in my older age, but it'd be nice to know that there is some method to my madness.

    Read the article

  • Create static instances of a class inside said class in Python

    - by Samir Talwar
    Apologies if I've got the terminology wrong here—I can't think what this particular idiom would be called. I've been trying to create a Python 3 class that statically declares instances of itself inside itself—sort of like an enum would work. Here's a simplified version of the code I wrote: class Test: A = Test("A") B = Test("B") def __init__(self, value): self.value = value def __str__(self): return "Test: " + self.value print(str(Test.A)) print(str(Test.B)) Writing this, I got an exception on line 2 (A = Test("A")). I assume line 3 would also error if it had made it that far. Using __class__ instead of Test gives the same error. File "<stdin>", line 1, in <module> File "<stdin>", line 2, in Test NameError: name 'Test' is not defined Is there any way to refer to the current class in a static context in Python? I could declare these particular variables outside the class or in a separate class, but for clarity's sake, I'd rather not if I can help it. To better demonstrate what I'm trying to do, here's the same example in Java: public class Test { private static final Test A = new Test("A"); private static final Test B = new Test("B"); private final String value; public Test(String value) { this.value = value; } public String toString() { return "Test: " + value; } public static void main(String[] args) { System.out.println(A); System.out.println(B); } } This works as you would expect: it prints: Test: A Test: B How can I do the same thing in Python?

    Read the article

  • Where should an application's default folder live?

    - by HotOil
    Hi: I'm creating a little app that configures a connected device and then saves the config information in a file. The filename cannot be chosen by the user, but its location can be chosen. Where is the best place for the app's default save-to folder? I have seen examples out there where it is the "MyDocuments" location (eg Visual Studio does this). I have seen a folder created right at the top of the C:\ drive. I find that to be a little obnoxious, personally. It could be in the Program Files[Manufacturer] or Program Files[Product Name], or wherever the app was installed. I have used this location in the past; I dislike it because Windows Explorer does not allow a user to browse to there very easily ('browsability'). Going with this last notion that 'browsability' is a factor, I suppose MyDocuments is the best choice. Is this the most common, most widely accepted practice? I think historically we have chosen the install folder because that co-locates the data with the device management utilities. But I would really like to get away from that. I don't want the user to have to go pawing through system files to find his/her data, esp if that person is not too Windows-savvy. Also, I am using the .NET WinForms FolderBrowserDialog, and the "Environment.SpecialFolders" enum isn't helpful in setting up the dialog to point into the Program Files folder. Thanks for your input! Suz.

    Read the article

  • How to Make a Game like Space Invaders - Ray Wenderlich (why do my space invaders scroll off screen)

    - by Erv Noel
    I'm following this tutorial(http://www.raywenderlich.com/51068/how-to-make-a-game-like-space-invaders-with-sprite-kit-tutorial-part-1) and I've run into a problem right after the part where I add [self determineInvaderMovementDirection]; to my GameScene.m file (specifically to my moveInvadersForUpdate method) The tutorial states that the space invaders should be moving accordingly after adding this piece of code but when I run they move to the left and they do not come back. I'm not sure what I am doing wrong as I have followed this tutorial very carefully. Any help or clarification would be greatly appreciated. Thanks in advance ! Here is the full GameScene.m #import "GameScene.h" #import <CoreMotion/CoreMotion.h> #pragma mark - Custom Type Definitions /* The type definition and constant definitions 1,2,3 take care of the following tasks: 1.Define the possible types of invader enemies. This can be used in switch statements later when things like displaying different sprites images for each enemy type. The typedef makes InvaderType a formal Obj-C type that is type checked for method arguments and variables.This is so that the wrong method argument is not used or assigned to the wrong variable. 2. Define the size of the invaders and that they'll be laid out in a grid of rows and columns on the screen. 3. Define a name that will be used to identify invaders when searching for them. */ //1 typedef enum InvaderType { InvaderTypeA, InvaderTypeB, InvaderTypeC } InvaderType; /* Invaders move in a fixed pattern: right, right, down, left, down, right right. InvaderMovementDirection tracks the invaders' progress through this pattern */ typedef enum InvaderMovementDirection { InvaderMovementDirectionRight, InvaderMovementDirectionLeft, InvaderMovementDirectionDownThenRight, InvaderMovementDirectionDownThenLeft, InvaderMovementDirectionNone } InvaderMovementDirection; //2 #define kInvaderSize CGSizeMake(24,16) #define kInvaderGridSpacing CGSizeMake(12,12) #define kInvaderRowCount 6 #define kInvaderColCount 6 //3 #define kInvaderName @"invader" #define kShipSize CGSizeMake(30, 16) //stores the size of the ship #define kShipName @"ship" // stores the name of the ship stored on the sprite node #define kScoreHudName @"scoreHud" #define kHealthHudName @"healthHud" /* this class extension allows you to add “private” properties to GameScene class, without revealing the properties to other classes or code. You still get the benefit of using Objective-C properties, but your GameScene state is stored internally and can’t be modified by other external classes. As well, it doesn’t clutter the namespace of datatypes that your other classes see. This class extension is used in the method didMoveToView */ #pragma mark - Private GameScene Properties @interface GameScene () @property BOOL contentCreated; @property InvaderMovementDirection invaderMovementDirection; @property NSTimeInterval timeOfLastMove; @property NSTimeInterval timePerMove; @end @implementation GameScene #pragma mark Object Lifecycle Management #pragma mark - Scene Setup and Content Creation /*This method simply invokes createContent using the BOOL property contentCreated to make sure you don’t create your scene’s content more than once. This property is defined in an Objective-C Class Extension found near the top of the file()*/ - (void)didMoveToView:(SKView *)view { if (!self.contentCreated) { [self createContent]; self.contentCreated = YES; } } - (void)createContent { //1 - Invaders begin by moving to the right self.invaderMovementDirection = InvaderMovementDirectionRight; //2 - Invaders take 1 sec for each move. Each step left, right or down // takes 1 second. self.timePerMove = 1.0; //3 - Invaders haven't moved yet, so set the time to zero self.timeOfLastMove = 0.0; [self setupInvaders]; [self setupShip]; [self setupHud]; } /* Creates an invade sprite of a given type 1. Use the invadeType parameterr to determine color of the invader 2. Call spriteNodeWithColor:size: of SKSpriteNode to alloc and init a sprite that renders as a rect of the given color invaderColor with size kInvaderSize */ -(SKNode*)makeInvaderOfType:(InvaderType)invaderType { //1 SKColor* invaderColor; switch (invaderType) { case InvaderTypeA: invaderColor = [SKColor redColor]; break; case InvaderTypeB: invaderColor = [SKColor greenColor]; break; case InvaderTypeC: invaderColor = [SKColor blueColor]; break; } //2 SKSpriteNode* invader = [SKSpriteNode spriteNodeWithColor:invaderColor size:kInvaderSize]; invader.name = kInvaderName; return invader; } -(void)setupInvaders { //1 - loop over the rows CGPoint baseOrigin = CGPointMake(kInvaderSize.width / 2, 180); for (NSUInteger row = 0; row < kInvaderRowCount; ++row) { //2 - Choose a single InvaderType for all invaders // in this row based on the row number InvaderType invaderType; if (row % 3 == 0) invaderType = InvaderTypeA; else if (row % 3 == 1) invaderType = InvaderTypeB; else invaderType = InvaderTypeC; //3 - Does some math to figure out where the first invader // in the row should be positioned CGPoint invaderPosition = CGPointMake(baseOrigin.x, row * (kInvaderGridSpacing.height + kInvaderSize.height) + baseOrigin.y); //4 - Loop over the columns for (NSUInteger col = 0; col < kInvaderColCount; ++col) { //5 - Create an invader for the current row and column and add it // to the scene SKNode* invader = [self makeInvaderOfType:invaderType]; invader.position = invaderPosition; [self addChild:invader]; //6 - update the invaderPosition so that it's correct for the //next invader invaderPosition.x += kInvaderSize.width + kInvaderGridSpacing.width; } } } -(void)setupShip { //1 - creates ship using makeShip. makeShip can easily be used later // to create another ship (ex. to set up more lives) SKNode* ship = [self makeShip]; //2 - Places the ship on the screen. In SpriteKit the origin is at the lower //left corner of the screen. The anchorPoint is based on a unit square with (0, 0) at the lower left of the sprite's area and (1, 1) at its top right. Since SKSpriteNode has a default anchorPoint of (0.5, 0.5), i.e., its center, the ship's position is the position of its center. Positioning the ship at kShipSize.height/2.0f means that half of the ship's height will protrude below its position and half above. If you check the math, you'll see that the ship's bottom aligns exactly with the bottom of the scene. ship.position = CGPointMake(self.size.width / 2.0f, kShipSize.height/2.0f); [self addChild:ship]; } -(SKNode*)makeShip { SKNode* ship = [SKSpriteNode spriteNodeWithColor:[SKColor greenColor] size:kShipSize]; ship.name = kShipName; return ship; } -(void)setupHud { //Sets the score label font to Courier SKLabelNode* scoreLabel = [SKLabelNode labelNodeWithFontNamed:@"Courier"]; //1 - Give the score label a name so it becomes easy to find later when // the score needs to be updated. scoreLabel.name = kScoreHudName; scoreLabel.fontSize = 15; //2 - Color the score label green scoreLabel.fontColor = [SKColor greenColor]; scoreLabel.text = [NSString stringWithFormat:@"Score: %04u", 0]; //3 - Positions the score label near the top left corner of the screen scoreLabel.position = CGPointMake(20 + scoreLabel.frame.size.width/2, self.size.height - (20 + scoreLabel.frame.size.height/2)); [self addChild:scoreLabel]; //Applies the font of the health label SKLabelNode* healthLabel = [SKLabelNode labelNodeWithFontNamed:@"Courier"]; //4 - Give the health label a name so it can be referenced later when it needs // to be updated to display the health healthLabel.name = kHealthHudName; healthLabel.fontSize = 15; //5 - Colors the health label red healthLabel.fontColor = [SKColor redColor]; healthLabel.text = [NSString stringWithFormat:@"Health: %.1f%%", 100.0f]; //6 - Positions the health Label on the upper right hand side of the screen healthLabel.position = CGPointMake(self.size.width - healthLabel.frame.size.width/2 - 20, self.size.height - (20 + healthLabel.frame.size.height/2)); [self addChild:healthLabel]; } #pragma mark - Scene Update - (void)update:(NSTimeInterval)currentTime { //Makes the invaders move [self moveInvadersForUpdate:currentTime]; } #pragma mark - Scene Update Helpers //This method will get invoked by update -(void)moveInvadersForUpdate:(NSTimeInterval)currentTime { //1 - if it's not yet time to move, exit the method. moveInvadersForUpdate: // is invoked 60 times per second, but you don't want the invaders to move // that often since the movement would be too fast to see if (currentTime - self.timeOfLastMove < self.timePerMove) return; //2 - Recall that the scene holds all the invaders as child nodes; which were // added to the scene using addChild: in setupInvaders identifying each invader // by its name property. Invoking enumerateChildNodesWithName:usingBlock only loops over the invaders because they're named kInvaderType; which makes the loop skip the ship and the HUD. The guts og the block moves the invaders 10 pixels either right, left or down depending on the value of invaderMovementDirection [self enumerateChildNodesWithName:kInvaderName usingBlock:^(SKNode *node, BOOL *stop) { switch (self.invaderMovementDirection) { case InvaderMovementDirectionRight: node.position = CGPointMake(node.position.x - 10, node.position.y); break; case InvaderMovementDirectionLeft: node.position = CGPointMake(node.position.x - 10, node.position.y); break; case InvaderMovementDirectionDownThenLeft: case InvaderMovementDirectionDownThenRight: node.position = CGPointMake(node.position.x, node.position.y - 10); break; InvaderMovementDirectionNone: default: break; } }]; //3 - Record that you just moved the invaders, so that the next time this method is invoked (1/60th of a second from when it starts), the invaders won't move again until the set time period of one second has elapsed. self.timeOfLastMove = currentTime; //Makes it so that the invader movement direction changes only when the invaders are actually moving. Invaders only move when the check on self.timeOfLastMove passes (when conditional expression is true) [self determineInvaderMovementDirection]; } #pragma mark - Invader Movement Helpers -(void)determineInvaderMovementDirection { //1 - Since local vars accessed by block are default const(means they cannot be changed), this snippet of code qualifies proposedMovementDirection with __block so that you can modify it in //2 __block InvaderMovementDirection proposedMovementDirection = self.invaderMovementDirection; //2 - Loops over the invaders in the scene and refers to the block with the invader as an argument [self enumerateChildNodesWithName:kInvaderName usingBlock:^(SKNode *node, BOOL *stop) { switch (self.invaderMovementDirection) { case InvaderMovementDirectionRight: //3 - If the invader's right edge is within 1pt of the right edge of the scene, it's about to move offscreen. Sets proposedMovementDirection so that the invaders move down then left. You compare the invader's frame(the frame that contains its content in the scene's coordinate system) with the scene width. Since the scene has an anchorPoint of (0,0) by default and is scaled to fill it's parent view, this comparison ensures you're testing against the view's edges. if (CGRectGetMaxX(node.frame) >= node.scene.size.width - 1.0f) { proposedMovementDirection = InvaderMovementDirectionDownThenLeft; *stop = YES; } break; case InvaderMovementDirectionLeft: //4 - If the invader's left edge is within 1 pt of the left edge of the scene, it's about to move offscreen. Sets the proposedMovementDirection so invaders move down then right if (CGRectGetMinX(node.frame) <= 1.0f) { proposedMovementDirection = InvaderMovementDirectionDownThenRight; *stop = YES; } break; case InvaderMovementDirectionDownThenLeft: //5 - If invaders are moving down then left, they already moved down at this point, so they should now move left. proposedMovementDirection = InvaderMovementDirectionLeft; *stop = YES; break; case InvaderMovementDirectionDownThenRight: //6 - if the invaders are moving down then right, they already moved down so they should now move right. proposedMovementDirection = InvaderMovementDirectionRight; *stop = YES; break; default: break; } }]; //7 - if the proposed invader movement direction is different than the current invader movement direction, update the current direction to the proposed direction if (proposedMovementDirection != self.invaderMovementDirection) { self.invaderMovementDirection = proposedMovementDirection; } } #pragma mark - Bullet Helpers #pragma mark - User Tap Helpers #pragma mark - HUD Helpers #pragma mark - Physics Contact Helpers #pragma mark - Game End Helpers @end

    Read the article

  • Fetch the most viewed data in databases

    - by Erik Edgren
    I want to get the most viewed photo from the database but I don't know how I shall accomplish this. Here's my SQL at the moment: SELECT * FROM photos AS p, viewers AS v WHERE p.id = v.id_photo GROUP BY v.id_photo The databases: CREATE TABLE IF NOT EXISTS `photos` ( `id` int(10) NOT NULL AUTO_INCREMENT, `photo_filename` varchar(50) NOT NULL, `photo_camera` varchar(150) NOT NULL, `photo_taken` datetime NOT NULL, `photo_resolution` varchar(10) NOT NULL, `photo_exposure` varchar(10) NOT NULL, `photo_iso` varchar(3) NOT NULL, `photo_fnumber` varchar(10) NOT NULL, `photo_focallength` varchar(10) NOT NULL, `post_coordinates` text NOT NULL, `post_description` text NOT NULL, `post_uploaded` datetime NOT NULL, `post_edited` datetime NOT NULL, `checkbox_approxcoor` enum('0','1') NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) CREATE TABLE IF NOT EXISTS `viewers` ( `id` int(10) NOT NULL AUTO_INCREMENT, `id_photo` int(10) DEFAULT '0', `ipaddress` text NOT NULL, `date_viewed` datetime NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) The data in viewers looks like this: (1, 85, '3892a0ab97d6ff325f285b27b847070f', '2012-06-21 22:49:25'), (2, 84, '3892a0ab97d6ff325f285b27b847070f', '2012-06-21 22:49:25'), (3, 85, '3892a0ab97d6ff325f285b27b847070f', '2012-06-21 22:49:25'); One single row from the database for photos to understand how the rows looks like in this database: (85, 'P1170986.JPG', 'Panasonic DMC-LX3', '2012-06-19 18:00:40', '3968x2232', '10/8000', '80', '50/10', '51/10', '', '', '2012-06-19 18:45:17', '0000-00-00 00:00:00', '0') At the moment the SQL only prints the photo with ID 84. In this case it's wrong - it should print out the photo with ID 85. How can I fix this problem? Thanks in advance.

    Read the article

  • vs2008, opencv2.1,compile error in cxcore.hpp

    - by Long Gu
    Hi, gurus: I installed opencv2.1, made a new project (proj_A) using vs2008, used it for my computer vision tasks, it works fine. I copied an old project (proj_B, also made using vs2008) from other PC, compile it with ".h" and ".lib" files copied from opencv1.0 (which I did not install onto my PC), it compiles fine. I re-directed ".h" and ".lib" files in proj_B to opencv2.1 folders instead, compiled the proj_B, and then I got these errors from cxcore.hpp: class CV_EXPORTS RNG { public: enum { A=4164903690U, UNIFORM=0, NORMAL=1 }; // errors here, line 936 errors are: 5c:\opencv2.1\include\opencv\cxcore.hpp(936) : error C2143: syntax error : missing '}' before 'constant' 5c:\opencv2.1\include\opencv\cxcore.hpp(936) : error C2059: syntax error : 'constant' 5c:\opencv2.1\include\opencv\cxcore.hpp(936) : error C2143: syntax error : missing ';' before '}' 5c:\opencv2.1\include\opencv\cxcore.hpp(936) : error C2238: unexpected token(s) preceding ';' (400+ similar errors, but I believe the answer should be the same, so only list 1 set here) I compared setting for proj_A and proj_B, made them identical, and find no improvement. proj_A works well, proj_B refuse to compile. May I know what's wrong? Urgent, need to get it solved ASAP! Thanks a lot!

    Read the article

  • MPMoviePlayerContentPreloadDidFinishNotification seems more reliable than MPMoviePlayerLoadStateDidChangeNotification

    - by user567889
    I am streaming small movies (1-3MB) off my website into my app. I have a slicehost webserver, I think it's a "500MB slice". Not sure off the top of my head how this translates to bandwidth, but I can figure that out later. My experience with MPMoviePlayerLoadStateDidChangeNotification is not very good. I get much more reliable results with the old MPMoviePlayerContentPreloadDidFinishNotification If I get a MPMoviePlayerContentPreloadDidFinishNotification, the movie will play without stuttering, but if I use MPMoviePlayerLoadStateDidChangeNotification, the movie frequently stalls. I'm not sure which load state to check for: enum { MPMovieLoadStateUnknown = 0, MPMovieLoadStatePlayable = 1 << 0, MPMovieLoadStatePlaythroughOK = 1 << 1, MPMovieLoadStateStalled = 1 << 2, }; MPMovieLoadStatePlaythroughOK seems to be what I want (based on the description in the documentation): MPMovieLoadStatePlaythroughOK Enough data has been buffered for playback to continue uninterrupted. Available in iOS 3.2 and later. but that load state NEVER gets set to this in my app. Am I missing something? Is there a better way to do this?

    Read the article

  • JPA entitylisteners and @embeddable

    - by seanizer
    I have a class hierarchy of JPA entities that all inherit from a BaseEntity class: @MappedSuperclass @EntityListeners( { ValidatorListener.class }) public abstract class BaseEntity implements Serializable { // other stuff } I want all entities that implement a given interface to be validated automatically on persist and/or update. Here's what I've got. My ValidatorListener: public class ValidatorListener { private enum Type { PERSIST, UPDATE } @PrePersist public void checkPersist(final Object entity) { if (entity instanceof Validateable) { this.check((Validateable) entity, Type.PERSIST); } } @PreUpdate public void checkUpdate(final Object entity) { if (entity instanceof Validateable) { this.check((Validateable) entity, Type.UPDATE); } } private void check(final Validateable entity, final Type persist) { switch (persist) { case PERSIST: if (entity instanceof Persist) { ((Persist) entity).persist(); } if (entity instanceof PersistOrUpdate) { ((PersistOrUpdate) entity).persistOrUpdate(); } break; case UPDATE: if (entity instanceof Update) { ((Update) entity).update(); } if (entity instanceof PersistOrUpdate) { ((PersistOrUpdate) entity).persistOrUpdate(); } break; default: break; } } } and here's my Validateable interface that it checks against (the outer interface is just a marker, the inner contain the methods): public interface Validateable { interface Persist extends Validateable { void persist(); } interface PersistOrUpdate extends Validateable { void persistOrUpdate(); } interface Update extends Validateable { void update(); } } All of this works, however I would like to extend this behavior to Embeddable classes. I know two solutions: call the validation method of the embeddable object manually from the entity validation method: public void persistOrUpdate(){ // validate my own properties first // then manually validate the embeddable property: myEmbeddable.persistOrUpdate(); // this works but I'd like something that I don't have to call manually } use reflection, checking all properties to see if their type is of one of their interface types. This would work, but it's not pretty. Is there a more elegant solution?

    Read the article

  • Access property of DataContext in ItemTemplate

    - by amrinder
    My datacontext has two properties: Items which is a collection and DetailsVisiblity which is enum of type Visiblity. On the page I have a Listbox with ItemsSource="{Binding Entries}". Inside the DataTemplate, I can bind stuff to properties of Items, but how do I get access to DetailsVisiblity which is a property of DataContext? DataContext has two properties: ObservableCollection<Item> Entries, and Visibility DetailsVisiblity. Item class has two properties: Title and Details. Here is the view. How do I bind Visiblity of the second TextBlock to DetailsVisiblity property? <ListBox "{Binding Items}"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Title}" /> <TextBlock Text="{Binding Details}" Visibility="{Binding ???}" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox>

    Read the article

  • Flex vs GWT again

    - by CK Lee
    Hi all, I am working on a customized web ontology editor (something like http://webprotege.stanford.edu/ which is built by GWT). My backend will be Java+Spring+Hibernate and domain models are in Java. My frontend will be something like WebProtege which requires extensive RPC call. It is quite clear that I should use GWT as I can refer to the open source code. However, due to company policy, I shall consider Flex as well. I understand Flex can remotely invoke Java backend methods via BlazeDS using AMF (Is there a Flex equivalent of GWT-RPC?). I have read discussion on GWT vs Flex vs ?. If I can make full decision sure I will go with GWT. GWT strengths like support right to left characters, support iPhone/iPad, smaller size, support JSON out of the box, support printing are not important considerations for my project. Besides GWT supports Java generic, enum; domain objects can be shared with both GWT client and server; coding are more seamlessly... anyone can suggest other strong reasons that I should only go with GWT? FYI, I have plenty of Java experience but both GWT and Flex are new to me. Thanks.

    Read the article

  • Questions on Juval Lowy's IDesign C# Coding Standard

    - by Jan
    We are trying to use the IDesign C# Coding standard. Unfortunately, I found no comprehensive document to explain all the rules that it gives, and also his book does not always help. Here are the open questions that remain for me (from chapter 2, Coding Practices): No. 26: Avoid providing explicit values for enums unless they are integer powers of 2 No. 34: Always explicitly initialize an array of reference types using a for loop No. 50: Avoid events as interface members No. 52: Expose interfaces on class hierarchies No. 73: Do not define method-specific constraints in interfaces No. 74: Do not define constraints in delegates Here's what I think about those: I thought that providing explicit values would be especially useful when adding new enum members at a later point in time. If these members are added between other already existing members, I would provide explicit values to make sure the integer representation of existing members does not change. No idea why I would want to do this. I'd say this totally depends on the logic of my program. I see that there is alternative option of providing "Sink interfaces" (simply providing already all "OnXxxHappened" methods), but what is the reason to prefer one over the other? Unsure what he means here: Could this mean "When implementing an interface explicitly in a non-sealed class, consider providing the implementation in a protected virtual method that can be overridden"? (see Programming .NET Components 2nd Edition, end of chapter “Interfaces and Class Hierarchies”). I suppose this is about providing a "where" clause when using generics, but why is this bad on an interface? I suppose this is about providing a "where" clause when using generics, but why is this bad on a delegate?

    Read the article

  • Implementing a bitfield using java enums

    - by soappatrol
    Hello, I maintain a large document archive and I often use bit fields to record the status of my documents during processing or when validating them. My legacy code simply uses static int constants such as: static int DOCUMENT_STATUS_NO_STATE = 0 static int DOCUMENT_STATUS_OK = 1 static int DOCUMENT_STATUS_NO_TIF_FILE = 2 static int DOCUMENT_STATUS_NO_PDF_FILE = 4 This makes it pretty easy to indicate the state a document is in, by setting the appropriate flags. For example: status = DOCUMENT_STATUS_NO_TIF_FILE | DOCUMENT_STATUS_NO_PDF_FILE; Since the approach of using static constants is bad practice and because I would like to improve the code, I was looking to use Enums to achieve the same. There are a few requirements, one of them being the need to save the status into a database as a numeric type. So there is a need to transform the enumeration constants to a numeric value. Below is my first approach and I wonder if this is the correct way to go about this? class DocumentStatus{ public enum StatusFlag { DOCUMENT_STATUS_NOT_DEFINED(1<<0), DOCUMENT_STATUS_OK(1<<1), DOCUMENT_STATUS_MISSING_TID_DIR(1<<2), DOCUMENT_STATUS_MISSING_TIF_FILE(1<<3), DOCUMENT_STATUS_MISSING_PDF_FILE(1<<4), DOCUMENT_STATUS_MISSING_OCR_FILE(1<<5), DOCUMENT_STATUS_PAGE_COUNT_TIF(1<<6), DOCUMENT_STATUS_PAGE_COUNT_PDF(1<<7), DOCUMENT_STATUS_UNAVAILABLE(1<<8), private final long statusFlagValue; StatusFlag(long statusFlagValue) { this.statusFlagValue = statusFlagValue } public long getStatusFlagValue(){ return statusFlagValue } } /** * Translates a numeric status code into a Set of StatusFlag enums * @param numeric statusValue * @return EnumSet representing a documents status */ public EnumSet<StatusFlag> getStatusFlags(long statusValue) { EnumSet statusFlags = EnumSet.noneOf(StatusFlag.class) StatusFlag.each { statusFlag -> long flagValue = statusFlag.statusFlagValue if ( (flagValue&statusValue ) == flagValue ) { statusFlags.add(statusFlag) } } return statusFlags } /** * Translates a set of StatusFlag enums into a numeric status code * @param Set if statusFlags * @return numeric representation of the document status */ public long getStatusValue(Set<StatusFlag> flags) { long value=0 flags.each { statusFlag -> value|=statusFlag.getStatusFlagValue() } return value } public static void main(String[] args) { DocumentStatus ds = new DocumentStatus(); Set statusFlags = EnumSet.of( StatusFlag.DOCUMENT_STATUS_OK, StatusFlag.DOCUMENT_STATUS_UNAVAILABLE) assert ds.getStatusValue( statusFlags )==258 // 0000.0001|0000.0010 long numericStatusCode = 56 statusFlags = ds.getStatusFlags(numericStatusCode) assert !statusFlags.contains(StatusFlag.DOCUMENT_STATUS_OK) assert statusFlags.contains(StatusFlag.DOCUMENT_STATUS_MISSING_TIF_FILE) assert statusFlags.contains(StatusFlag.DOCUMENT_STATUS_MISSING_PDF_FILE) assert statusFlags.contains(StatusFlag.DOCUMENT_STATUS_MISSING_OCR_FILE) } }

    Read the article

  • Organising UI code in .NET forms

    - by sb3700
    Hi I'm someone who has taught myself programming, and haven't had any formal training in .NET programming. A while back, I started C# in order to develop a GUI program to control sensors, and the project has blossomed. I was just wondering how best to organise the code, particularly UI code, in my forms. My forms currently are a mess, or at least seem a mess to me. I have a constructor which initialises all the parameters and creates events. I have a giant State property, which updates the Enabled state of all my form control as users progress through the application (ie: disconnected, connected, setup, scanning) controlled by a States enum. I have 3-10 private variables accessed through properties, some of which have side-effects in changing the values of form elements. I have a lot of "UpdateXXX" functions to handle UI elements that depend on other UI elements - ie: if a sensor is changed, then change the baud rate drop down list. They are separated into regions I have a lot of events calling these Update functions I have a background worker which does all the scanning and analysis. My problem is this seems like a mess, particularly the State property, and is getting unmaintainable. Also, my application logic code and UI code are in the same file and to some degree, intermingled which seems wrong and means I need to do a lot of scrolling to find what I need. How do you structure your .net forms? Thanks

    Read the article

  • SFINAE + sizeof = detect if expression compiles

    - by FredOverflow
    I just found out how to check if operator<< is provided for a type. template<class T> T& lvalue_of_type(); template<class T> T rvalue_of_type(); template<class T> struct is_printable { template<class U> static char test(char(*)[sizeof( lvalue_of_type<std::ostream>() << rvalue_of_type<U>() )]); template<class U> static long test(...); enum { value = 1 == sizeof test<T>(0) }; typedef boost::integral_constant<bool, value> type; }; Is this trick well-known, or have I just won the metaprogramming Nobel prize? ;) EDIT: I made the code simpler to understand and easier to adapt with two global function template declarations lvalue_of_type and rvalue_of_type.

    Read the article

< Previous Page | 37 38 39 40 41 42 43 44 45 46 47 48  | Next Page >