Search Results

Search found 581 results on 24 pages for 'iterating'.

Page 17/24 | < Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >

  • How is fundamental mathematics efficiently evaluated by programming languages?

    - by Korvin Szanto
    As I get more and more involved with the theory behind programming, I find myself fascinated and dumbfounded by seemingly simple things.. I realize that my understanding of the majority of fundamental processes is justified through circular logic Q: How does this work? A: Because it does! I hate this realization! I love knowledge, and on top of that I love learning, which leads me to my question (albeit it's a broad one). Question: How are fundamental mathematical operators assessed with programming languages? How have current methods been improved? Example var = 5 * 5; My interpretation: $num1 = 5; $num2 = 5; $num3 = 0; while ($num2 > 0) { $num3 = $num3 + $num1; $num2 = $num2 - 1; } echo $num3; This seems to be highly inefficient. With Higher factors, this method is very slow while the standard built in method is instantanious. How would you simulate multiplication without iterating addition? var = 5 / 5; How is this even done? I can't think of a way to literally split it 5 into 5 equal parts. var = 5 ^ 5; Iterations of iterations of addition? My interpretation: $base = 5; $mod = 5; $num1 = $base; while ($mod > 1) { $num2 = 5; $num3 = 0; while ($num2 > 0) { $num3 = $num3 + $num1; $num2 = $num2 - 1; } $num1 = $num3; $mod -=1; } echo $num3; Again, this is EXTREMELY inefficient, yet I can't think of another way to do this. This same question extends to all mathematical related functions that are handled automagically.

    Read the article

  • Automating first time login process in Windows Server 2008 R2 SP1 virtual machine

    - by George Durzi
    I have a set of Windows 2008 Server R2 SP1 Enterprise Edition virtual machines running in Hyper-V. The host server has 64GB of RAM and two SSD drives (one drive for the host OS, and the second one for the VMs). The virtual machines are as follows: Domain Controller: 4GB RAM Exchange Server: 4GB RAM Terminal Services: 50GB RAM We use this setup for a travelling training class where users remote desktop to one of the VMs - let's call it the Terminal Services or "TS" VM - where tools such as Visual Studio are installed. The students go through some labs on the TS VMs in Visual Studio. Overall, this setup works great. However, when users are collectively logging in for the first time, the VM really struggles to keep up while all the user profiles are created. It can take some users up to 10 minutes to login. The number varies from 30 to 40 students. A workaround to this would be to manually remote desktop to the TS virtual machine using all the accounts to ensure that the local profile is created in advance. I'm looking for a way to automate the first time login process on the TS virtual machine. I am envisioning iterating through the accounts in a certain Active Directory OU, and then somehow initiating a remote desktop session to the TS VM to log them in for the first time. Are there ways to do this? Thanks

    Read the article

  • Android - Images from Assets folder in a GridView

    - by Saran
    Hi, I have been working on creating a Grid View of images, with images being present in the Assets folder. http://stackoverflow.com/questions/1933015/opening-an-image-file-inside-the-assets-folder link helped me with using the bitmap to read it. The code am currently having is: public View getView(final int position, View convertView, ViewGroup parent) { try { AssetManager am = mContext.getAssets(); String list[] = am.list(""); int count_files = imagelist.length; for(int i= 0;i<=count_files; i++) { BufferedInputStream buf = new BufferedInputStream(am.open(list[i])); Bitmap bitmap = BitmapFactory.decodeStream(buf); imageView.setImageBitmap(bitmap); buf.close(); } } catch (IOException e) { e.printStackTrace(); } } My application does read the image from the Assets folder, but it is not iterating through the cells in the grid view. All the cells of the grid view have a same image picked from the set of images. Can anyone tell me how to iterate through the cells and still have different images ? I have the above code in an ImageAdapter Class which extends the BaseAdapter class, and in my main class I am linking that with my gridview by: GridView gv =(GridView)findViewById(R.id.gridview); gv.setAdapter(new ImageAdapter(this, assetlist)); Thanks a lot for any help in advance, Saran

    Read the article

  • Dealing with huge SQL resultset

    - by Dave McClelland
    I am working with a rather large mysql database (several million rows) with a column storing blob images. The application attempts to grab a subset of the images and runs some processing algorithms on them. The problem I'm running into is that, due to the rather large dataset that I have, the dataset that my query is returning is too large to store in memory. For the time being, I have changed the query to not return the images. While iterating over the resultset, I run another select which grabs the individual image that relates to the current record. This works, but the tens of thousands of extra queries have resulted in a performance decrease that is unacceptable. My next idea is to limit the original query to 10,000 results or so, and then keep querying over spans of 10,000 rows. This seems like the middle of the road compromise between the two approaches. I feel that there is probably a better solution that I am not aware of. Is there another way to only have portions of a gigantic resultset in memory at a time? Cheers, Dave McClelland

    Read the article

  • Working with a large data object between ruby processes

    - by Gdeglin
    I have a Ruby hash that reaches approximately 10 megabytes if written to a file using Marshal.dump. After gzip compression it is approximately 500 kilobytes. Iterating through and altering this hash is very fast in ruby (fractions of a millisecond). Even copying it is extremely fast. The problem is that I need to share the data in this hash between Ruby on Rails processes. In order to do this using the Rails cache (file_store or memcached) I need to Marshal.dump the file first, however this incurs a 1000 millisecond delay when serializing the file and a 400 millisecond delay when serializing it. Ideally I would want to be able to save and load this hash from each process in under 100 milliseconds. One idea is to spawn a new Ruby process to hold this hash that provides an API to the other processes to modify or process the data within it, but I want to avoid doing this unless I'm certain that there are no other ways to share this object quickly. Is there a way I can more directly share this hash between processes without needing to serialize or deserialize it? Here is the code I'm using to generate a hash similar to the one I'm working with: @a = [] 0.upto(500) do |r| @a[r] = [] 0.upto(10_000) do |c| if rand(10) == 0 @a[r][c] = 1 # 10% chance of being 1 else @a[r][c] = 0 end end end @c = Marshal.dump(@a) # 1000 milliseconds Marshal.load(@c) # 400 milliseconds Update: Since my original question did not receive many responses, I'm assuming there's no solution as easy as I would have hoped. Presently I'm considering two options: Create a Sinatra application to store this hash with an API to modify/access it. Create a C application to do the same as #1, but a lot faster. The scope of my problem has increased such that the hash may be larger than my original example. So #2 may be necessary. But I have no idea where to start in terms of writing a C application that exposes an appropriate API. A good walkthrough through how best to implement #1 or #2 may receive best answer credit.

    Read the article

  • Very simply, how can check if a user exists against my MySQL database?

    - by Sergio Tapia
    Here's what I have but nothing is output to the screen. :\ <html> <head> </head> <body> <? mysql_connect(localhost, "sergio", "123"); @mysql_select_db("multas") or die( "Unable to select database"); $query="SELECT * FROM usuario"; $result=mysql_query($query); $num=mysql_numrows($result); $i=0; $username=GET["u"]; $password=GET["p"]; while ($i < $num) { $dbusername=mysql_result($result,$i,"username"); $dbpassword=mysql_result($result,$i,"password"); if(($username == $dbusername) && ($password == $dbpassword)){ echo "si"; } $i++; } ?> </body> </html> I'm iterating through all users and seeing if there is a match for user && password. Any guidance?

    Read the article

  • Silverlight 4 Drag and Drop Treeview

    - by Rich
    Does anyone have an example for any of the following scenarios. Given, these are all dynamically populated trees. Not using a Heirarchal data template, but by iterating through object collections manually and appending children at the appropriate level. Treeview1 has 3 levels, but items can only be reordered within their level. So, lets say we have Drives, Folders and Files. Drives can be rearranged in an order, but not put into a Folder. When navigated down one level in a drive, the individual folders can be reordered, but not dragged between drives.. and same with files, only can be reordered, but not moved to a different folder or drive I have 2 treeviews, Treeview1 is the same as #1 above and Treeview2 is like a picklist of available items. A user can drag an item from Treeview2 to Treeview1, but it can only be placed at Treeview1's File Level. The dragged item cannot be a child of a file, or placed at the folder level, nor placed at the drive level. Also, how to handle the Above, On Top, or Below an item. I have yet to come across these examples.

    Read the article

  • Editing 8bpp indexed Bitmaps

    - by Pedro Sá
    hi, i'm trying to edit the pixels of a 8bpp. Since this PixelFormat is indexed i'm aware that it uses a Color Table to map the pixel values. Even though I can edit the bitmap by converting it to 24bpp, 8bpp editing is much faster (13ms vs 3ms). But, changing each value when accessing the 8bpp bitmap results in some random rgb colors even though the PixelFormat remains 8bpp. I'm currently developing in c# and the algorithm is as follows: (C#) 1- Load original Bitmap at 8bpp 2- Create Empty temp Bitmap with 8bpp with the same size as the original 3-LockBits of both bitmaps and, using P/Invoke, calling c++ method where I pass the Scan0 of each BitmapData object. (I used a c++ method as it offers better performance when iterating through the Bitmap's pixels) (C++) 4- Create a int[256] palette according to some parameters and edit the temp bitmap bytes by passing the original's pixel values through the palette. (C#) 5- UnlockBits. My question is how can I edit the pixel values without having the strange rgb colors, or even better, edit the 8bpp bitmap's Color Table? Regards, Pedro

    Read the article

  • Flow control in a batch file

    - by dboarman-FissureStudios
    Reference Iterating arrays in a batch file I have the following: for /f "tokens=1" %%Q in ('query termserver') do ( if not ERRORLEVEL ( echo Checking %%Q for /f "tokens=1" %%U in ('query user %UserID% /server:%%Q') do (echo %%Q) ) ) When running query termserver from the command line, the first two lines are: Known ------------------------- ...followed by the list of terminal servers. However, I do not want to include these as part of the query user command. Also, there are about 4 servers I do not wish to include. When I supply UserID with this code, the program is promptly exiting. I know it has something to do with the if statement. Is this not possible to nest flow control inside the for-loop? I had tried setting a variable to exactly the names of the servers I wanted to check, but the iteration would end on the first server: set TermServers=Server1.Server2.Server3.Server7.Server8.Server10 for /f "tokens=2 delims=.=" %%Q in ('set TermServers') do ( echo Checking %%Q for /f "tokens=1" %%U in ('query user %UserID% /server:%%Q') do (echo %%Q) ) I would prefer this second example over the first if nothing else for cleanliness. Any help regarding either of these issues would be greatly appreciated.

    Read the article

  • template engine implementation

    - by qwerty
    I am currently building this small template engine. It takes a string containing the template in parameter, and a dictionary of "tags,values" to fill in the template. In the engine, I have no idea of the tags that will be in the template and the ones that won't. I am currently iterating (foreach) on the dictionnary, parsing my string that I have put in a string builder, and replacing the tags in the template by their corresponding value. Is there a more efficient/convenient way of doing this? I know the main drawback here is that the stringbuilder is parsed everytime entirely for each tag, which is quite bad... (I am also checking, though not included in the sample, after the process that my template does not contain any tag anymore. They are all formated in the same way: @@tag@@) //Dictionary<string, string> tagsValueCorrespondence; //string template; StringBuilder outputBuilder = new StringBuilder(template); foreach (string tag in tagsValueCorrespondence.Keys) { outputBuilder.Replace(tag, tagsValueCorrespondence[tag]); } template = outputBuilder.ToString(); Responses: @Marc: string template = "Some @@foobar@@ text in a @@bar@@ template"; StringDictionary data = new StringDictionary(); data.Add("foo", "value1"); data.Add("bar", "value2"); data.Add("foo2bar", "value3"); Output: "Some text in a value2 template" instead of: "Some @@foobar@@ text in a value2 template"

    Read the article

  • Sharing large objects between ruby processes without a performance hit

    - by Gdeglin
    I have a Ruby hash that reaches approximately 10 megabytes if written to a file using Marshal.dump. After gzip compression it is approximately 500 kilobytes. Iterating through and altering this hash is very fast in ruby (fractions of a millisecond). Even copying it is extremely fast. The problem is that I need to share the data in this hash between Ruby on Rails processes. In order to do this using the Rails cache (file_store or memcached) I need to Marshal.dump the file first, however this incurs a 1000 millisecond delay when serializing the file and a 400 millisecond delay when serializing it. Ideally I would want to be able to save and load this hash from each process in under 100 milliseconds. One idea is to spawn a new Ruby process to hold this hash that provides an API to the other processes to modify or process the data within it, but I want to avoid doing this unless I'm certain that there are no other ways to share this object quickly. Is there a way I can more directly share this hash between processes without needing to serialize or deserialize it? Here is the code I'm using to generate a hash similar to the one I'm working with: @a = [] 0.upto(500) do |r| @a[r] = [] 0.upto(10_000) do |c| if rand(10) == 0 @a[r][c] = 1 # 10% chance of being 1 else @a[r][c] = 0 end end end @c = Marshal.dump(@a) # 1000 milliseconds Marshal.load(@c) # 400 milliseconds

    Read the article

  • (C#) Get index of current foreach iteration

    - by Graphain
    Hi, Is there some rare language construct I haven't encountered (like the few I've learned recently, some on Stack Overflow) in C# to get a value representing the current iteration of a foreach loop? For instance, I currently do something like this depending on the circumstances: int i=0; foreach (Object o in collection) { ... i++; } Answers: @bryansh: I am setting the class of an element in a view page based on the position in the list. I guess I could add a method that gets the CSSClass for the Objects I am iterating through but that almost feels like a violation of the interface of that class. @Brad Wilson: I really like that - I've often thought about something like that when using the ternary operator but never really given it enough thought. As a bit of food for thought it would be nice if you could do something similar to somehow add (generically to all IEnumerable objects) a handle on the enumerator to increment the value that an extension method returns i.e. inject a method into the IEnumerable interface that returns an iterationindex. Of course this would be blatant hacks and witchcraft... Cool though... @crucible: Awesome I totally forgot to check the LINQ methods. Hmm appears to be a terrible library implementation though. I don't see why people are downvoting you though. You'd expect the method to either use some sort of HashTable of indices or even another SQL call, not an O(N) iteration... (@Jonathan Holland yes you are right, expecting SQL was wrong) @Joseph Daigle: The difficulty is that I assume the foreach casting/retrieval is optimised more than my own code would be. @Jonathan Holland: Ah, cheers for explaining how it works and ha at firing someone for using it.

    Read the article

  • ASP.NET putting dynamic controls on page in reverse messes up events

    - by Jimmy Geels
    I have this weird problem when putting textboxes on the page in reverse. The whole event system is messed up. Changing one textbox fires TextChange on all textboxes. I can fix this by putting the controls in a list first and then call add while iterating trough the list in reverse. But i just want to know why this fails. Heres some code (.net 2.0) public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { InitFields(); } private void InitFields() { int nrFields; //We have a static textbox called nrElements, this determines the number //of fields to initialize if (int.TryParse(nrElements.Text, out nrFields)) { //Put all the dynamic fields on the screen in reverse order foreach(Control t in GetDynamicFields(nrFields)) { //Calling Controls.Add works fine //Calling Controls.AddAt messes up the events //Try changing different textboxes plhFields.Controls.AddAt(0, t); } } } private IEnumerable<Control> GetDynamicFields(int nrFields) { for (int i = 0; i < nrFields; i++) { TextBox txtBox = new TextBox(); txtBox.ID = string.Format("dynTextBox{0}", i.ToString()); txtBox.AutoPostBack = true; txtBox.TextChanged += t_TextChanged; yield return txtBox; } } private void t_TextChanged(object sender, EventArgs e) { TextBox txtBox = sender as TextBox; if (txtBox != null) txtBox.Text = txtBox.Text + "Changed "; } }

    Read the article

  • WPF - Setting ComboBox.SelectedItem in XAML based on matching object

    - by Andy T
    Hi, so, I have templated combobox that is basically acting as a simple colour palette. It is populated with a list of SolidColorBrush objects. Fine. Now, I have some data that holds the hex value of the current colour. I have a converter that converts the hex into a SolidColorBrush. Also fine. Now, I want to set the SelectedItem property of the combobox based on the colour from my datasource. Since my combo is populated with objects of type SolidColourBrush, and my binding converter is returning a SolidColorBrush, I assumed it would be as simple as saying: SelectedItem="{Binding Color, Converter={StaticResource StringToBrush}}" However... it doesn't work :( I've tested that the binding is working behind the scenes by using the exact same value for the Background property of the combobox. It works fine. So, clearly I can't just say SelectedItem = [something] where that [something] is basically an object equal to the item I want to be selected. What is the right way to do this? Surely it's possible in a XAML-only styley using binding, and I don't have to do some nasty C# iterating through all items in the combobox trying to find a match (that seems awfully old-school)...? Any help appreciated. Many thanks! AT

    Read the article

  • Using prepared statements with JDBCTemplate

    - by Bernhard V
    Hi. I'm using the Jdbc template and want to read from the database using prepared statements. I iterate over many lines in a csv file and on every line I execute some sql select queries with it's values. Now I want to speed up my reading from the database but I just can't get the Jdbc template to work with prepared statements. Actually I even don't know how to do it. There is the PreparedStatementCreator and the PreparedStatementCreator. As in this example both of them are created with anonymous inner classes. But inside the PreparedStatementCreator class I don't have access to the values I want to set in the prepared statement. Since I'm iterating through a csv file I can't hard code them as a String because I don't know them. I also can't pass them to the PreparedStatementCreator because there are no arguments for the constructor. I was used to the creation of prepared statements being fairly simple. Something like PreparedStatement updateSales = con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ? "); updateSales.setInt(1, 75); updateSales.setString(2, "Colombian"); updateSales.executeUpdate(): as in the Java tutorial. Your help would be very appreciated.

    Read the article

  • Why doesn't Perl file glob() work outside of a loop in scalar context?

    - by Rob
    According to the Perl documentation on file globbing, the <*> operator or glob() function, when used in a scalar context, should iterate through the list of files matching the specified pattern, returning the next file name each time it is called or undef when there are no more files. But, the iterating process only seems to work from within a loop. If it isn't in a loop, then it seems to start over immediately before all values have been read. From the Perl docs: In scalar context, glob iterates through such filename expansions, returning undef when the list is exhausted. http://perldoc.perl.org/functions/glob.html However, in scalar context the operator returns the next value each time it's called, or undef when the list has run out. http://perldoc.perl.org/perlop.html#I/O-Operators Example code: use warnings; use strict; my $filename; # in scalar context, <*> should return the next file name # each time it is called or undef when the list has run out $filename = <*>; print "$filename\n"; $filename = <*>; # doesn't work as documented, starts over and print "$filename\n"; # always returns the same file name $filename = <*>; print "$filename\n"; print "\n"; print "$filename\n" while $filename = <*>; # works in a loop, returns next file # each time it is called In a directory with 3 files...file1.txt, file2.txt, and file3.txt, the above code will output: file1.txt file1.txt file1.txt file1.txt file2.txt file3.txt Note: The actual perl script should be outside the test directory, or you will see the file name of the script in the output as well. Am I doing something wrong here, or is this how it is supposed to work?

    Read the article

  • Python, dictionaries, and chi-square contingency table

    - by rohanbk
    I have a file which contains several lines in the following format (word, time that the word occurred in, and frequency of documents containing the given word within the given instance in time): #inputfile <word, time, frequency> apple, 1, 3 banana, 1, 2 apple, 2, 1 banana, 2, 4 orange, 3, 1 I have Python class below that I used to create 2-D dictionaries to store the above file using as the key, and frequency as the value: class Ddict(dict): ''' 2D dictionary class ''' def __init__(self, default=None): self.default = default def __getitem__(self, key): if not self.has_key(key): self[key] = self.default() return dict.__getitem__(self, key) wordtime=Ddict(dict) # Store each inputfile entry with a <word,time> key timeword=Ddict(dict) # Store each inputfile entry with a <time,word> key # Loop over every line of the inputfile for line in open('inputfile'): word,time,count=line.split(',') # If <word,time> already a key, increment count try: wordtime[word][time]+=count # Otherwise, create the key except KeyError: wordtime[word][time]=count # If <time,word> already a key, increment count try: timeword[time][word]+=count # Otherwise, create the key except KeyError: timeword[time][word]=count The question that I have pertains to calculating certain things while iterating over the entries in this 2D dictionary. For each word 'w' at each time 't', calculate: The number of documents with word 'w' within time 't'. (a) The number of documents without word 'w' within time 't'. (b) The number of documents with word 'w' outside time 't'. (c) The number of documents without word 'w' outside time 't'. (d) Each of the items above represents one of the cells of a chi-square contingency table for each word and time. Can all of these be calculated within a single loop or do they need to be done one at a time? Ideally, I would like the output to be what's below, where a,b,c,d are all the items calculated above: print "%s, %s, %s, %s" %(a,b,c,d)

    Read the article

  • In WPF, accessing containers within ListBox

    - by Jim
    I'm creating a DerivedListBox : ListBox and a DerivedHeaderedContentControl : HeaderedContentControl, which will serve as a container for each item in the ListBox. In order to calculate the size available for the expanded content of the DerivedHeaderedContentControls, I am storing each container object in a list within the DerivedListBox. This way I can calculate the height of the headers of each DerivedHeaderedContentControl and subtract that from the total size available to the DerivedListBox. This would be the size available for the expanded content of a DerivedHeaderedContentControl. public class DerivedHeaderedContentControl : HeaderedContentControl { // Do some binding to DerivedListBox to calculate height. } public class DerivedListBox : ListBox { private List<DerivedHeaderedContentControl> containers; protected override DependencyObject GetContainerForItemOverride() { DerivedHeaderedContentControl val = new DerivedHeaderedContentControl(); this.containers.Add(val); return val; } // Do some binding to calculate height available for an expanded // container by iterating over containers. } The problem comes in when the DerivedListBox's ItemsSource is cleared (or an item in the items source is removed). How can I determine when the ItemsSource is cleared so that I can clear the containers list?

    Read the article

  • Parsing files "/etc/default" using java

    - by rmarimon
    I'm trying to parse the configuration files usually found in /etc/default using java and regular expressions. So far this is the code I have iterating over every line on each file: // remove comments from the line int hash = line.indexOf("#"); if (hash >= 0) { line = line.substring(0, hash); } // create the patterns Pattern doubleQuotePattern = Pattern.compile("\\s*([a-zA-Z_][a-zA-Z_0-9]*)\\s*=\\s*\"(.*)\"\\s*"); Pattern singleQuotePattern = Pattern.compile("\\s*([a-zA-Z_][a-zA-Z_0-9]*)\\s*=\\s*\\'(.*)\\'\\s*"); Pattern noQuotePattern = Pattern.compile("\\s*([a-zA-Z_][a-zA-Z_0-9]*)\\s*=(.*)"); // try to match each of the patterns to the line Matcher matcher = doubleQuotePattern.matcher(line); if (matcher.matches()) { System.out.println(matcher.group(1) + " == " + matcher.group(2)); } else { matcher = singleQuotePattern.matcher(line); if (matcher.matches()) { System.out.println(matcher.group(1) + " == " + matcher.group(2)); } else { matcher = noQuotePattern.matcher(line); if (matcher.matches()) { System.out.println(matcher.group(1) + " == " + matcher.group(2)); } } } This works as I expect but I'm pretty sure that I can make this way smaller by using better regular expression but I haven't had any luck. Anyone know of a better way to read these types of files?

    Read the article

  • Python SQLite FTS3 alternatives?

    - by Mike Cialowicz
    Are there any good alternatives to SQLite + FTS3 for python? I'm iterating over a series of text documents, and would like to categorize them according to some text queries. For example, I might want to know if a document mentions the words "rating" or "upgraded" within three words of "buy." The FTS3 syntax for this query is the following: (rating OR upgraded) NEAR/3 buy That's all well and good, but if I use FTS3, this operation seems rather expensive. The process goes something like this: # create an SQLite3 db in memory conn = sqlite3.connect(':memory:') c = conn.cursor() c.execute('CREATE VIRTUAL TABLE fts USING FTS3(content TEXT)') conn.commit() Then, for each document, do something like this: #insert the document text into the fts table, so I can run a query c.execute('insert into fts(content) values (?)', content) conn.commit() # execute my FTS query here, look at the results, etc # remove the document text from the fts table before working on the next document c.execute('delete from fts') conn.commit() This seems rather expensive to me. The other problem I have with SQLite FTS is that it doesn't appear to work with Python 2.5.4. The 'CREATE VIRTUAL TABLE' syntax is unrecognized. This means that I'd have to upgrade to Python 2.6, which means re-testing numerous existing scripts and programs to make sure they work under 2.6. Is there a better way? Perhaps a different library? Something faster? Thank you.

    Read the article

  • Opengl Iphone SDK: How to tell if you're touching an object on screen?

    - by TheGambler
    First is my touchesBegan function and then the struct that stores the values for my object. I have an array of these objects and I'm trying to figure out when I touch the screen if I'm touching an object on the screen. I don't know if I need to do this by iterating through all my objects and figure out if I'm touching an object that way or maybe there is an easier more efficient way. How is this usually handled? -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ [super touchesEnded:touches withEvent:event]; UITouch* touch = ([touches count] == 1 ? [touches anyObject] : nil); CGRect bounds = [self bounds]; CGPoint location = [touch locationInView:self]; location.y = bounds.size.height - location.y; float xTouched = location.x/20 - 8 + ((int)location.x % 20)/20; float yTouched = location.y/20 - 12 + ((int)location.y % 20)/20; } typedef struct object_tag // Create A Structure Called Object { int tex; // Integer Used To Select Our Texture float x; // X Position float y; // Y Position float z; // Z Position float yi; // Y Increase Speed (Fall Speed) float spinz; // Z Axis Spin float spinzi; // Z Axis Spin Speed float flap; // Flapping Triangles :) float fi; // Flap Direction (Increase Value) } object;

    Read the article

  • Android : SQL Lite insertion or create table issue

    - by Ram
    Team, can anyone please help me to understand what could be the problem in the below snippet of code? It fails after insertion 2 and insertion 3 debug statements I have the contentValues in the Array list, I am iterating the arraylist and inserting the content values in to the database. Log.d("database","before insertion 1 "); liteDatabase = this.openOrCreateDatabase("Sales", MODE_PRIVATE, null); Log.d("database","before insertion 2 "); liteDatabase .execSQL("Create table activity ( ActivityId VARCHAR,Created VARCHAR,AMTaps_X VARCHAR,AMTemperature_X VARCHAR,AccountId VARCHAR,AccountLocation VARCHAR,AccountName VARCHAR,Classification VARCHAR,ActivityType VARCHAR,COTaps_X VARCHAR,COTemperature_X VARCHAR,Comment VARCHAR,ContactWorkPhone VARCHAR,CreatedByName VARCHAR,DSCycleNo_X VARCHAR,DSRouteNo_X VARCHAR,DSSequenceNo_X VARCHAR,Description VARCHAR,HETaps_X VARCHAR,HETemperature_X VARCHAR,Pro_Setup VARCHAR,LastUpdated VARCHAR,LastUpdatedBy VARCHAR,Licensee VARCHAR,MUTaps_X VARCHAR,MUTemperature_X VARCHAR,Objective VARCHAR,OwnerFirstName VARCHAR,OwnerLastName VARCHAR,PhoneNumber VARCHAR,Planned VARCHAR,PlannedCleanActualDt_X VARCHAR,PlannedCleanReason_X VARCHAR,PrimaryOwnedBy VARCHAR,Pro_Name VARCHAR,ServiceRepTerritory_X VARCHAR,ServiceRep_X VARCHAR,Status VARCHAR,Type VARCHAR,HEINDSTapAuditDate VARCHAR,HEINEmployeeType VARCHAR)"); Log.d("database","before insertion 3 "); int counter = 0; int size = arrayList.size(); for (counter = 0; counter < size; counter++) { ContentValues contentValues = (ContentValues) arrayList .get(counter); liteDatabase.insert("activity", "activityInfo", contentValues); Log.d("database", "Database insertion is done"); } }

    Read the article

  • XMLStreamReader and a real stream

    - by Yuri Ushakov
    Update There is no ready XML parser in Java community which can do NIO and XML parsing. This is the closest I found, and it's incomplete: http://wiki.fasterxml.com/AaltoHome I have the following code: InputStream input = ...; XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); XMLStreamReader streamReader = xmlInputFactory.createXMLStreamReader(input, "UTF-8"); Question is, why does the method #createXMLStreamReader() expects to have an entire XML document in the input stream? Why is it called a "stream reader", if it can't seem to process a portion of XML data? For example, if I feed: <root> <child> to it, it would tell me I'm missing the closing tags. Even before I begin iterating the stream reader itself. I suspect that I just don't know how to use a XMLStreamReader properly. I should be able to supply it with data by pieces, right? I need it because I'm processing a XML stream coming in from network socket, and don't want to load the whole source text into memory. Thank you for help, Yuri.

    Read the article

  • How to perform spatial partitioning in n-dimensions?

    - by kevin42
    I'm trying to design an implementation of Vector Quantization as a c++ template class that can handle different types and dimensions of vectors (e.g. 16 dimension vectors of bytes, or 4d vectors of doubles, etc). I've been reading up on the algorithms, and I understand most of it: here and here I want to implement the Linde-Buzo-Gray (LBG) Algorithm, but I'm having difficulty figuring out the general algorithm for partitioning the clusters. I think I need to define a plane (hyperplane?) that splits the vectors in a cluster so there is an equal number on each side of the plane. [edit to add more info] This is an iterative process, but I think I start by finding the centroid of all the vectors, then use that centroid to define the splitting plane, get the centroid of each of the sides of the plane, continuing until I have the number of clusters needed for the VQ algorithm (iterating to optimize for less distortion along the way). The animation in the first link above shows it nicely. My questions are: What is an algorithm to find the plane once I have the centroid? How can I test a vector to see if it is on either side of that plane?

    Read the article

  • Why aren't my objects sorting with sortedArrayUsingDescriptors?

    - by clozach
    I expected the code below to return the objects in imageSet as a sorted array. Instead, there's no difference in the ordering before and after. NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"imageID" ascending:YES]; NSSet *imageSet = collection.images; for (CBImage *image in imageSet) { NSLog(@"imageID in Set: %@",image.imageID); } NSArray *imageArray = [[imageSet allObjects] sortedArrayUsingDescriptors:(descriptor, nil)]; [descriptor release]; for (CBImage *image in imageArray) { NSLog(@"imageID in Array: %@",image.imageID); } Fwiw, CBImage is defined in my core data model. I don't know why sorting on managed objects would work any differently than on "regular" objects, but maybe it matters. As proof that @"imageID" should work as the key for the descriptor, here's what the two log loops above output for one of the sets I'm iterating through: 2010-05-05 00:49:52.876 Cover Browser[38678:207] imageID in Array: 360339 2010-05-05 00:49:52.876 Cover Browser[38678:207] imageID in Array: 360337 2010-05-05 00:49:52.877 Cover Browser[38678:207] imageID in Array: 360338 2010-05-05 00:49:52.878 Cover Browser[38678:207] imageID in Array: 360336 2010-05-05 00:49:52.879 Cover Browser[38678:207] imageID in Array: 360335 ... For extra credit, I'd love to get a general solution to troubleshooting NSSortDescriptor troubles (esp. if it also applies to troubleshooting NSPredicate). The functionality of these things seems totally opaque to me and consequently debugging takes forever.

    Read the article

< Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >