Search Results

Search found 338 results on 14 pages for 'jordan kay'.

Page 4/14 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • WCF: Using Streaming and Username/Password authentication at the same time

    - by Kay
    Hi, I have a WCF Service with the following requirements: a) The client requests a file from the server which is transferred as a Stream. Files may be 100MB or larger. I need streaming or chucking or whatever to make sure that IIS is not loading the whole package into memory before starting to send it. b) The client will transfer an ID to identify the file to be downloaded. The user should be authenticated by providing username/password. c) While the username/password part of the communication needs to be encrypted, encryption of the downloaded file is optional for our use case. My other services, where I am returning smaller files, I am using the following binding: <ws2007HttpBinding> <binding name="ws2007HttpExtern" maxReceivedMessageSize="65536000"> <security mode="Message"> <message clientCredentialType="UserName" /> </security> </binding> </ws2007HttpBinding> But, as I said, that is no good for streaming (Message encryption needs the complete message to encrypt and that is not the case when streaming). So, I asked Microsoft support and I got more or less the following proposal: <bindings> <basicHttpBinding> <binding name="basicStreaming" messageEncoding="Mtom" transferMode="StreamedResponse"> <security mode="Transport"> <transport clientCredentialType="Basic" /> </security> </binding> </bindings> <services> <service behaviorConfiguration="MyProject.WCFInterface.DownloadBehavior" name="MyProject.WCFInterface.DownloadFile"> <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicStreaming" contract="MyProject.WCFInterface.IDownloadFile" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services> <behaviors> <serviceBehaviors> <behavior name="MyProject.WCFInterface.DownloadBehavior"> <serviceMetadata httpGetEnabled="false" httpsGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> When I use this, I get the following error message: Could not find a base address that matches scheme https for the endpoint with binding BasicHttpBinding. Registered base address schemes are [http]. I am using the Web Development Server so far (for production IIS7). I have two questions. a) How would you configure WCF to achieve the goal? b) If the MS proposal is good: What I am doing wrong, the error message does not really help me. Thanks.

    Read the article

  • MVC2 Ajax Form does unwanted page refresh

    - by Kay
    Hi, I am pretty new to MVC. I have my first Ajax Form here: <div id="test"></div> <div id="MainChatMenu"> <% using (Ajax.BeginForm("SendMessage", "MainChat", new AjaxOptions { UpdateTargetId="test"})) { %> <input id="chatMessageText" type="text" maxlength="200" /> <input type="submit" value="Go"/> <% } %> Now, if I click the submit button, the page is reloading, goint to mysite/controller/action. I thought that the default behaviour of the Ajax.BeginForm was exactly not to do that? Where's my newbie mistake? My Controller is called correctly, but data passing also doesn't work. Probably because of the same mistake? Here's the code: public class MainChatController : Controller { [AcceptVerbs(HttpVerbs.Post)] public EmptyResult SendMessage(FormCollection formValues) { return new EmptyResult(); } }

    Read the article

  • Designing a data model in VS2010 and generating ORM code, application

    - by Kay Zed
    Simply put: I have a database design in my head and I now want to use Visual Studio 2010 to create a WPF application. Key is to use the VS2010 tools to take much as possible manual work out of my hands. -The database engine is SQLite -ORM probably through DBLINQ -Use of LINQ -The application can create new, empty database instances -Easily maintainable (changes in data model possible) Q- How do I start designing the database model (visually) in Visual Studio 2010? Should this be an xsd? Do I do this in a separate project? Q- Next, how can I make the most use of VS2010 code generation tools to generate a business layer? Q- I suppose the business layer will be added as a Data Source (in another project?) and from there it's a rather generic data binding solution? I tried finding clear examples of this but it's a jungle out there, the hunt for a solution is NOT converging to one clear method.... :_(

    Read the article

  • WPF: Textbox not firing onTextInput event

    - by Kay Ell
    So basically, I have a bunch of TextBoxes that the user gets to fill out. I've got a button that I want to keep disabled until all the TextBoxes have had text entered in them. Here is a sample XAML TextBox that I'm using: <TextBox Name="DelayedRecallScore" TextInput="CheckTextBoxFilled" Width="24" /> And here is the function that I'm trying to trigger: //Disables the OK button until all score textboxes have content private void CheckTextBoxFilled(object sender, RoutedEventArgs e) { /* foreach (TextBox scorebox in TextBoxList) { if (string.IsNullOrEmpty(scorebox.Text)) { Ok_Button.IsEnabled = false; return; } } Ok_Button.IsEnabled = true; */ MessageBox.Show("THIS MAKES NO SENSE"); } The MessageBox is not showing up when TextInput should be getting triggered. As an experiment I tried triggering CheckTextBoxFilled() on PreviewTextInput, and it worked fine then, meaning that for whatever reason, the function just isn't getting called. I also have a validation function that is triggered by PreviewTextInput, which works as it should. At first I thought PreviewTextInput might somehow be interfering with TextInput, so I took PreviewTextInput off the TextBox, but that hasn't managed to fix anything. I'm completely befuddled by why this might happen, so any help would be appreciated.

    Read the article

  • Android NDK - does it support straight ARM code or just Thumb

    - by Russell Kay
    All, I have been asked to evaluate the Android platform for our product and I am looking at various options, I am only just scratching the surface just now and the one thing that is bothering me is that I cannot see how to compile code as straight ARM code (no Thumb), I know that Thumb runs slower and we will need the performance in key sections of our code. I think it should just be setting the -march flag in the LOCAL_CFLAGS of the Android.mk file, but I cannot get that to work... Can anyone help. Russell

    Read the article

  • ASP.NET MVC Users unable to login after password change, and being locked out.

    - by Russell Kay
    All, I have a website that is in use and has several users, using the MySqlMembershipProvider. We have had a few users that have been locked out (for some reason) and recently I unlocked them and reset the passwords, using the MembershipUser.UnlockUser and MembershipUser.ResetPassword methods. Now they are definitely marked in the database as Unlocked and the password has been reset, but they still cannot log in. Does anyone have any ideas why this might happen?

    Read the article

  • Matlab N-Queen Problem

    - by Kay
    main.m counter = 1; n = 8; board = zeros(1,n); back(0, board); disp(counter); sol.m function value = sol(board) for ( i = 1:(length(board))) for ( j = (i+1): (length(board)-1)) if (board(i) == board(j)) value = 0; return; end if ((board(i) - board(j)) == (i-j)) value = 0; return; end if ((board(i) - board(j)) == (j-i)) value = 0; return; end end end value = 1; return; back.m function back(depth, board) disp(board); if ( (depth == length(board)) && (sol2(board) == 1)) counter = counter + 1; end if ( depth < length(board)) for ( i = 0:length(board)) board(1,depth+1) = i; depth = depth + 1; solv2(depth, board); end end I'm attempting to find the maximum number of ways n-queen can be placed on an n-by-n board such that those queens aren't attacking eachother. I cannot figure out the problem with the above matlab code, i doubt it's a problem with my logic since i've tested out this logic in java and it seems to work perfectly well there. The code compiles but the issue is that the results it produces are erroneous. Java Code which works: public static int counter=0; public static boolean isSolution(final int[] board){ for (int i = 0; i < board.length; i++) { for (int j = i + 1; j < board.length; j++) { if (board[i] == board[j]) return false; if (board[i]-board[j] == i-j) return false; if (board[i]-board[j] == j-i) return false; } } return true; } public static void solve(int depth, int[] board){ if (depth == board.length && isSolution(board)) { counter++; } if (depth < board.length) { // try all positions of the next row for (int i = 0; i < board.length; i++) { board[depth] = i; solve(depth + 1, board); } } } public static void main(String[] args){ int n = 8; solve(0, new int[n]); System.out.println(counter); }

    Read the article

  • How to animate the drawing of a CGPath?

    - by Jordan Kay
    I am wondering if there is a way to do this using Core Animation. Specifically, I am adding a sub-layer to a layer-backed custom NSView and setting its delegate to another custom NSView. That class's drawInRect method draws a single CGPath: - (void)drawInRect:(CGRect)rect inContext:(CGContextRef)context { CGContextSaveGState(context); CGContextSetLineWidth(context, 12); CGMutablePathRef path = CGPathCreateMutable(); CGPathMoveToPoint(path, NULL, 0, 0); CGPathAddLineToPoint(path, NULL, rect.size.width, rect.size.height); CGContextBeginPath(context); CGContextAddPath(context, path); CGContextStrokePath(context); CGContextRestoreGState(context); } My desired effect would be to animate the drawing of this line. That is, I'd like for the line to actually "stretch" in an animated way. It seems like there would be a simple way to do this using Core Animation, but I haven't been able to come across any. Do you have any suggestions as to how I could accomplish this goal?

    Read the article

  • Java Generic Casting Type Mismatch

    - by Kay
    public class MaxHeap<T extends Comparable<T>> implements Heap<T>{ private T[] heap; private int lastIndex; public void main(String[] args){ int i; T[] arr = {1,3,4,5,2}; //ERROR HERE ******* foo } public T[] Heapsort(T[]anArray, int n){ // build initial heap T[]sortedArray = anArray; for (int i = n-1; i< 0; i--){ //assert: the tree rooted at index is a semiheap heapRebuild(anArray, i, n); //assert: the tree rooted at index is a heap } //sort the heap array int last = n-1; //invariant: Array[0..last] is a heap, //Array[last+1..n-1] is sorted for (int j=1; j<n-1;j++) { sortedArray[0]=sortedArray[last]; last--; heapRebuild(anArray, 0, last); } return sortedArray; } protected void heapRebuild(T[ ] items, int root, int size){ foo } } The error is on the line with "T[arr] = {1,3,4,5,2}" Eclispe complains that there is a: "Type mismatch: cannot convert from int to T" I've tried to casting nearly everywhere but to no avail.A simple way out would be to not use generics but instead just ints but that's sadly not an option. I've got to find a way to resolve the array of ints "{1,3,4,5,2}" into an array of T so that the rest of my code will work smoothly.

    Read the article

  • Intel Assembly Programming

    - by Kay
    class MyString{ char buf[100]; int len; boolean append(MyString str){ int k; if(this.len + str.len>100){ for(k=0; k<str.len; k++){ this.buf[this.len] = str.buf[k]; this.len ++; } return false; } return true; } } Does the above translate to: start: push ebp ; save calling ebp mov ebp, esp ; setup new ebp push esi ; push ebx ; mov esi, [ebp + 8] ; esi = 'this' mov ebx, [ebp + 14] ; ebx = str mov ecx, 0 ; k=0 mov edx, [esi + 200] ; edx = this.len append: cmp edx + [ebx + 200], 100 jle ret_true ; if (this.len + str.len)<= 100 then ret_true cmp ecx, edx jge ret_false ; if k >= str.len then ret_false mov [esi + edx], [ebx + 2*ecx] ; this.buf[this.len] = str.buf[k] inc edx ; this.len++ aux: inc ecx ; k++ jmp append ret_true: pop ebx ; restore ebx pop esi ; restore esi pop ebp ; restore ebp ret true ret_false: pop ebx ; restore ebx pop esi ; restore esi pop ebp ; restore ebp ret false My greatest difficulty here is figuring out what to push onto the stack and the math for pointers. NOTE: I'm not allowed to use global variables and i must assume 32-bit ints, 16-bit chars and 8-bit booleans.

    Read the article

  • Implementing Java Priority Queue

    - by Kay
    public class PriorityQueue<T> { private PriorityNode<T> head, tail; private int numItems; public PriorityQueue(){ numItems = 0; head=null; tail=null; } public void add(int priority, T value){ PriorityNode<T> newNode = new PriorityNode<T>(priority,value); if(numItems == 0){ head = newNode; tail = newNode; } else{ head.setNext(newNode); head = newNode; } } } Where PriorityNode is defined as: public class PriorityNode<T> implements Comparable<T> { private T value; private PriorityNode<T> next; private int priority; public PriorityNode(int priority,T newValue){ value = newValue; next = null; priority = 0; } public PriorityNode(T newValue){ value = newValue; next = null; priority = 0; } public void setPriority(int priority){ this.priority = priority; } public int getPriority(){ return this.priority; } public T getValue(){ return value; } public PriorityNode<T> getNext(){ return next; } public void setNext(PriorityNode<T> nextNode){ this.next = nextNode; } public void setValue(T newValue){ value = newValue; } public int compareTo(int pri) { // TODO Auto-generated method stub if(this.priority<pri){ return -1; } else if(this.priority == pri){ return 0; } else{ return 1; } } } I'm having a lot of difficulty using the Comparator here and implementing a priority queue - please point me in the right direction.

    Read the article

  • Significant new inventions in computing since 1980

    - by Alan Kay
    This question arose from comments about different kinds of progress in computing over the last 50 years or so. I was asked by some of the other participants to raise it as a question to the whole forum. Basic idea here is not to bash the current state of things but to try to understand something about the progress of coming up with fundamental new ideas and principles. I claim that we need really new ideas in most areas of computing, and I would like to know of any important and powerful ones that have been done recently. If we can't really find them, then we should ask "Why?" and "What should we be doing?"

    Read the article

  • Intel IA-32 Assembly

    - by Kay
    I'm having a bit of difficulty converting the following java code into Intel IA-32 Assembly: class Person() { char name [8]; int age; void printName() {...} static void printAdults(Person [] list) { for(int k = 0; k < 100; k++){ if (list[k].age >= 18) { list[k].printName(); } } } } My attempt is: Person: push ebp; save callers ebp mov ebp, esp; setup new ebp push esi; esi will hold name push ebx; ebx will hold list push ecx; ecx will hold k init: mov esi, [ebp + 8]; mov ebx, [ebp + 12]; mov ecx, 0; k=0 forloop: cmp ecx, 100; jge end; if k>= 100 then break forloop cmp [ebx + 4 * ecx], 18 ; jl auxloop; if list[k].age < 18 then go to auxloop jmp printName; printName: auxloop: inc ecx; jmp forloop; end: pop ecx; pop ebx; pop esi; pop ebp; Is my code correct? NOTE: I'm not allowed to use global variables.

    Read the article

  • a full-screen UIImagePickerController with the right scale?

    - by Kay
    Hi, I'm customizing my image picker controller and I want to have a full-screen viewfinder. I think this might be pretty an old topic and I found an answer here: http://www.gorbster.net/blog/archives/144 But what I want to know is if there's a way to achieve this without distorting the scale of the image. If I scale that clipped preview image, I'm distorting its original x-y ratio, and I want to avoid it. Is there a way to prevent the preview image from being clipped so that I could retain the original 1200x1600 ratio? Thanks!

    Read the article

  • Real-time aggregation of files from multiple machines to one

    - by dmitry-kay
    I need a tool which gets a list of machine names and file wildcards. Then it connects to all these machines (SSH) and begins to monitor changes (appendings to the end) in each file matched by wildcards. New lines in each such file are saved to the local machine to the file with the same name. (This is a task of real-time log files collecting.) I could use ssh + tail -f, of course, but it is not very robust: if a monitoring process dies and then restarts, some data from remote files may be lost (because tail -f does not save the position at which it is finished before). I may write this tool manually, but before - I'd like to know if such tool already exists or not.

    Read the article

  • How to bind gridview using linq/Entity Framework?

    - by Kay
    I need to bind GridView, I am using this code: ProductDBEntities db = new ProductPDBEntities(); var pro = from u in db.Products where u.PID == 1 select u; if (pro != null) { GridView1.DataSource = pro; GridView1.DataBind(); } and getting this error. System.InvalidOperationException: Sequence contains more than one element Can somebody please tell me what am I doin wrong?

    Read the article

  • Speed up the loop operation in R

    - by Kay
    Hi, i have a big performance problem in R. I wrote a function that iterates over an data.frame object. It simply adds a new col to a data.frame and accumulate sth. (simple operation). The data.frame has round about 850.000 rows. My PC is still working about 10h now and i have no idea about the runtime. dayloop2 <- function(temp){ for (i in 1:nrow(temp)){ temp[i,10] <- i if (i > 1) { if ((temp[i,6] == temp[i-1,6]) & (temp[i,3] == temp[i-1,3])) { temp[i,10] <- temp[i,9] + temp[i-1,10] } else { temp[i,10] <- temp[i,9] } } else { temp[i,10] <- temp[i,9] } } names(temp)[names(temp) == "V10"] <- "Kumm." return(temp) } Any ideas how to speed up this operation ?

    Read the article

  • Get the src part of a string [duplicate]

    - by Kay Lakeman
    This question already has an answer here: Grabbing the href attribute of an A element 7 answers First post ever here, and i really hope you can help. I use a database where a large piece of html is stored, now i just need the src part of the image tag. I already found a thread, but i just doesn't do the trick. My code: Original string: <p><img alt=\"\" src=\"http://domain.nl/cms/ckeditor/filemanager/userfiles/background.png\" style=\"width: 80px; height: 160px;\" /></p> How i start: $image = strip_tags($row['information'], '<img>'); echo stripslashes($image); This returns: <img alt="" src="http://domain.nl/cms/ckeditor/filemanager/userfiles/background.png" style="width: 80px; height: 160px;" /> Next step: extract the src part: preg_match('/< *img[^>]*src *= *["\']?([^"\']*)/i', $image, $matches); echo $matches ; This last echo returns: Array What is going wrong? Thanks in advance for your anwser.

    Read the article

  • jquery live problem

    - by Kay
    Hi, I have a website which uses jquery and lots of mouseover/mouseout effect. So far I used the .bind() method of jquery but if you have 1000 event handlers, this is slowing down your browser a lot. So, I want to move to use .live or .delegate. One part of my portal site is a chat area. User can set chat messages which will then be displayed in a simple table. There is a feature that if you move the mouse over a chat message a trash can will appear allowing you to delete the message (if it is by you or you are a moderator). The trash bin is in the same table cell as the chat message. The problem: Using .bind() it worked like a charm. This is the old code: function CreateChatMessageContextMenu(ctrl, messageID, message, sender) { var a = document.createElement("a"); a.href = "javascript:RemoveChatMessage(" + messageID + ");" a.id = 'aDeleteChatMessage' + messageID; a.style.display = 'none'; var img = document.createElement("span"); img.className = "sprite-common messages-image sprite-common-btnDelete"; a.appendChild(img); ctrl.appendChild(a); $(ctrl) .bind('mouseover', function(event) { $('#aDeleteChatMessage' + messageID).show() }) .bind('mouseout', function(event) { $('#aDeleteChatMessage' + messageID).hide() }); return; } 'ctrl' is the reference to a table cell. Now, using .live() the trashbin also appears but it is flickering a lot and when I move the mouse over the trashbin, it is disappearing or inactive. I have the feeling that more events are thrown or something. It seems like the 'mouseout' is thrown when moving over the trashbin, but the thrashbin is inside the tablecell so mouseout should not be triggered. The new code is as follows. $(document).ready { $('.jDeleteableChatMessage').live('mouseover mouseout', function(event) { var linkID = '#aDelete' + event.target.id; if (event.type == 'mouseover') { $(linkID).show(); } else { $(linkID).hide(); } return false; }); } function CreateChatMessageContextMenu(ctrl, messageID, message, sender) { if (!UserIsModerator && (UserLogin != sender)) return; ctrl.id = 'ChatMessage' + messageID; var deleteString = 'Diese Chatnachricht löschen'; if (UserLang == '1') deleteString = 'Delete this chat message'; var a = document.createElement("a"); a.href = "javascript:RemoveChatMessage(" + messageID + ");" a.id = 'aDeleteChatMessage' + messageID; a.style.display = 'none'; var img = document.createElement("span"); img.className = "sprite-common messages-image sprite-common-btnDelete"; img.alt = deleteString; img.title = deleteString; a.appendChild(img); ctrl.appendChild(a); $(ctrl).addClass('jDeleteableChatMessage'); } I add a class to tell jQuery which chat cell have a trash bin and which don't. I also add an ID to the table cell which is later used to determine the associated trash bin. Yes, that's clumsy data passing to an event method. And, naturally, there is the document.ready function which initialises the .live() method. So, where is my mistake?

    Read the article

  • getURL, parsing web-site with german special characters

    - by Kay
    I am using getURL() and htmlParse() - how can I make web-site content with special characters to be displayed properly? library(RCurl); library(XML) script <- getURL("http://www.floraweb.de/pflanzenarten/foto.xsql?suchnr=814") doc <- htmlParse(script, encoding = "UTF-8") xpathSApply(doc, "//div[@id='content']//p", xmlValue)[2] [1] "Bellis perennis L., Gänseblümchen" # should say: [1] "Bellis perennis L., Gänseblümchen" > Sys.getlocale() [1] "LC_COLLATE=German_Austria.1252;LC_CTYPE=German_Austria.1252;LC_MONETARY=German_Austria.1252;LC_NUMERIC=C;LC_TIME=German_Austria.1252"

    Read the article

  • Bizzare Java invalid Assignment Operator Error

    - by Kay
    public class MaxHeap<T extends Comparable<T>> implements Heap<T>{ private T[] heap; private int lastIndex; private static final int defaultInitialCapacity = 25; public void add(T newItem) throws HeapException{ if (lastIndex < Max_Heap){ heap[lastIndex] = newItem; int place = lastIndex; int parent = (place – 1)/2; //ERROR HERE********** while ( (parent >=0) && (heap[place].compareTo(heap[parent])>0)){ T temp = heap[place]; heap[place] = heap[parent]; heap[parent] = temp; place = parent; parent = (place-1)/2; }else { throw new HeapException(“HeapException: Heap full”); } } } Eclipse complains that there is a: "Syntax error on token "Invalid Character", invalid AssignmentOperator" With the red line beneath the '(place-1)' There shouldn't be an error at all since it's just straight-forward arithmetic. Or is it not that simple?

    Read the article

  • Why is false being returned in this function

    - by Kay
    Hello all, I have this function below which makes it to the second IF function which sets the variable th as true but what is returned is false? Why?! public boolean nodeExist(TreeNode Tree, T value){ boolean th = false; if(Tree.getValue()!= null){ if(value == Tree.getValue()){ th = true; }else{ if(value.compareTo((T) Tree.getValue()) < 0){ nodeExist(Tree.getLeft(), value); }else{ nodeExist(Tree.getRight(), value); } } }else{ th = false; } return th; }

    Read the article

  • How is this function being made use of?

    - by Kay
    Hello all, I am just studying a few classes given to me by my lecturer and I can't understand how the function heapRebuild is being made used of! It doesn't change any global variables and it doesn't print out anything ad it doesn't return anything - so should this even work? It shouldn't, should it? If you were told to make use of heapRebuild to make a new function removeMac would you edit heapRebuild? public class MaxHeap<T extends Comparable<T>> implements Heap<T>{ private T[] heap; private int lastIndex; public T removeMax(){ T rootItem = heap[0]; heap[0] = heap[lastIndex-1]; lastIndex--; heapRebuild(heap, 0, lastIndex); return rootItem; } protected void heapRebuild(T[ ] items, int root, int size){ int child = 2*root+1; if( child < size){ int rightChild = child+1; if ((rightChild < size) && (items[rightChild].compareTo(items[child]) > 0)){ child = rightChild; } if (items[root].compareTo(items[child]) < 0){ T temp = items[root]; items[root] = items[child]; items[child] = temp; heapRebuild(items, child, size);} } } }

    Read the article

  • Removing object/array difference from different arrays [duplicate]

    - by Kay Singian
    This question already has an answer here: remove objects from array by object property 3 answers I have two JavaScript objects: object_1 = [ {'value': '9:00', 'text':'9:00 am', 'eventtime':'09:00:00' }, {'value': '9:30', 'text':'9:30 am', 'eventtime':'09:30:00' }, {'value': '10:00', 'text':'10:00 am', 'eventtime':'10:00:00' }, {'value': '10:30', 'text':'10:30 am', 'eventtime':'10:30:00' }, {'value': '11:00', 'text':'11:00 am', 'eventtime':'11:00:00' }, {'value': '11:30', 'text':'11:30 am', 'eventtime':'11:30:00' }, ]; object_2 = [ {'eventtime': '10:30:00'}, {'eventtime': '11:00:00'} ]; I want to remove the object in object_1 which has the same eventtime value and store it in a new array/object . Please help me do so, I cant find a solution to this. This will be the new array/object: object_new = [ {'value': '9:00', 'text':'9:00 am', 'eventtime':'09:00:00' }, {'value': '9:30', 'text':'9:30 am', 'eventtime':'09:30:00' }, {'value': '10:00', 'text':'10:00 am', 'eventtime':'10:00:00' }, {'value': '11:30', 'text':'11:30 am', 'eventtime':'11:30:00' }, ];

    Read the article

  • Help getting frame rate (fps) up in Python + Pygame

    - by Jordan Magnuson
    I am working on a little card-swapping world-travel game that I sort of envision as a cross between Bejeweled and the 10 Days geography board games. So far the coding has been going okay, but the frame rate is pretty bad... currently I'm getting low 20's on my Core 2 Duo. This is a problem since I'm creating the game for Intel's March developer competition, which is squarely aimed at netbooks packing underpowered Atom processors. Here's a screen from the game: ![www.necessarygames.com/my_games/betraveled/betraveled-fps.png][1] I am very new to Python and Pygame (this is the first thing I've used them for), and am sadly lacking in formal CS training... which is to say that I think there are probably A LOT of bad practices going on in my code, and A LOT that could be optimized. If some of you older Python hands wouldn't mind taking a look at my code and seeing if you can't find any obvious areas for optimization, I would be extremely grateful. You can download the full source code here: http://www.necessarygames.com/my_games/betraveled/betraveled_src0328.zip Compiled exe here: www.necessarygames.com/my_games/betraveled/betraveled_src0328.zip One thing I am concerned about is my event manager, which I feel may have some performance wholes in it, and another thing is my rendering... I'm pretty much just blitting everything to the screen all the time (see the render routines in my game_components.py below); I recently found out that you should only update the areas of the screen that have changed, but I'm still foggy on how that accomplished exactly... could this be a huge performance issue? Any thoughts are much appreciated! As usual, I'm happy to "tip" you for your time and energy via PayPal. Jordan Here are some bits of the source: Main.py #Remote imports import pygame from pygame.locals import * #Local imports import config import rooms from event_manager import * from events import * class RoomController(object): """Controls which room is currently active (eg Title Screen)""" def __init__(self, screen, ev_manager): self.room = None self.screen = screen self.ev_manager = ev_manager self.ev_manager.register_listener(self) self.room = self.set_room(config.room) def set_room(self, room_const): #Unregister old room from ev_manager if self.room: self.room.ev_manager.unregister_listener(self.room) self.room = None #Set new room based on const if room_const == config.TITLE_SCREEN: return rooms.TitleScreen(self.screen, self.ev_manager) elif room_const == config.GAME_MODE_ROOM: return rooms.GameModeRoom(self.screen, self.ev_manager) elif room_const == config.GAME_ROOM: return rooms.GameRoom(self.screen, self.ev_manager) elif room_const == config.HIGH_SCORES_ROOM: return rooms.HighScoresRoom(self.screen, self.ev_manager) def notify(self, event): if isinstance(event, ChangeRoomRequest): if event.game_mode: config.game_mode = event.game_mode self.room = self.set_room(event.new_room) def render(self, surface): self.room.render(surface) #Run game def main(): pygame.init() screen = pygame.display.set_mode(config.screen_size) ev_manager = EventManager() spinner = CPUSpinnerController(ev_manager) room_controller = RoomController(screen, ev_manager) pygame_event_controller = PyGameEventController(ev_manager) spinner.run() # this runs the main function if this script is called to run. # If it is imported as a module, we don't run the main function. if __name__ == "__main__": main() event_manager.py #Remote imports import pygame from pygame.locals import * #Local imports import config from events import * def debug( msg ): print "Debug Message: " + str(msg) class EventManager: #This object is responsible for coordinating most communication #between the Model, View, and Controller. def __init__(self): from weakref import WeakKeyDictionary self.listeners = WeakKeyDictionary() self.eventQueue= [] self.gui_app = None #---------------------------------------------------------------------- def register_listener(self, listener): self.listeners[listener] = 1 #---------------------------------------------------------------------- def unregister_listener(self, listener): if listener in self.listeners: del self.listeners[listener] #---------------------------------------------------------------------- def post(self, event): if isinstance(event, MouseButtonLeftEvent): debug(event.name) #NOTE: copying the list like this before iterating over it, EVERY tick, is highly inefficient, #but currently has to be done because of how new listeners are added to the queue while it is running #(eg when popping cards from a deck). Should be changed. See: http://dr0id.homepage.bluewin.ch/pygame_tutorial08.html #and search for "Watch the iteration" for listener in list(self.listeners): #NOTE: If the weakref has died, it will be #automatically removed, so we don't have #to worry about it. listener.notify(event) #------------------------------------------------------------------------------ class PyGameEventController: """...""" def __init__(self, ev_manager): self.ev_manager = ev_manager self.ev_manager.register_listener(self) self.input_freeze = False #---------------------------------------------------------------------- def notify(self, incoming_event): if isinstance(incoming_event, UserInputFreeze): self.input_freeze = True elif isinstance(incoming_event, UserInputUnFreeze): self.input_freeze = False elif isinstance(incoming_event, TickEvent): #Share some time with other processes, so we don't hog the cpu pygame.time.wait(5) #Handle Pygame Events for event in pygame.event.get(): #If this event manager has an associated PGU GUI app, notify it of the event if self.ev_manager.gui_app: self.ev_manager.gui_app.event(event) #Standard event handling for everything else ev = None if event.type == QUIT: ev = QuitEvent() elif event.type == pygame.MOUSEBUTTONDOWN and not self.input_freeze: if event.button == 1: #Button 1 pos = pygame.mouse.get_pos() ev = MouseButtonLeftEvent(pos) elif event.type == pygame.MOUSEMOTION: pos = pygame.mouse.get_pos() ev = MouseMoveEvent(pos) #Post event to event manager if ev: self.ev_manager.post(ev) #------------------------------------------------------------------------------ class CPUSpinnerController: def __init__(self, ev_manager): self.ev_manager = ev_manager self.ev_manager.register_listener(self) self.clock = pygame.time.Clock() self.cumu_time = 0 self.keep_going = True #---------------------------------------------------------------------- def run(self): if not self.keep_going: raise Exception('dead spinner') while self.keep_going: time_passed = self.clock.tick() fps = self.clock.get_fps() self.cumu_time += time_passed self.ev_manager.post(TickEvent(time_passed, fps)) if self.cumu_time >= 1000: self.cumu_time = 0 self.ev_manager.post(SecondEvent()) pygame.quit() #---------------------------------------------------------------------- def notify(self, event): if isinstance(event, QuitEvent): #this will stop the while loop from running self.keep_going = False rooms.py #Remote imports import pygame #Local imports import config import continents from game_components import * from my_gui import * from pgu import high class Room(object): def __init__(self, screen, ev_manager): self.screen = screen self.ev_manager = ev_manager self.ev_manager.register_listener(self) def notify(self, event): if isinstance(event, TickEvent): pygame.display.set_caption('FPS: ' + str(int(event.fps))) self.render(self.screen) pygame.display.update() def get_highs_table(self): fname = 'high_scores.txt' highs_table = None config.all_highs = high.Highs(fname) if config.game_mode == config.TIME_CHALLENGE: if config.difficulty == config.EASY: highs_table = config.all_highs['time_challenge_easy'] if config.difficulty == config.MED_DIF: highs_table = config.all_highs['time_challenge_med'] if config.difficulty == config.HARD: highs_table = config.all_highs['time_challenge_hard'] if config.difficulty == config.SUPER: highs_table = config.all_highs['time_challenge_super'] elif config.game_mode == config.PLAN_AHEAD: pass return highs_table class TitleScreen(Room): def __init__(self, screen, ev_manager): Room.__init__(self, screen, ev_manager) self.background = pygame.image.load('assets/images/interface/background.jpg').convert() #Initialize #--------------------------------------- self.gui_form = gui.Form() self.gui_app = gui.App(config.gui_theme) self.ev_manager.gui_app = self.gui_app c = gui.Container(align=0,valign=0) #Quit Button #--------------------------------------- b = StartGameButton(ev_manager=self.ev_manager) c.add(b, 0, 0) self.gui_app.init(c) def render(self, surface): surface.blit(self.background, (0, 0)) #GUI self.gui_app.paint(surface) class GameModeRoom(Room): def __init__(self, screen, ev_manager): Room.__init__(self, screen, ev_manager) self.background = pygame.image.load('assets/images/interface/background.jpg').convert() self.create_gui() #Create pgu gui elements def create_gui(self): #Setup #--------------------------------------- self.gui_form = gui.Form() self.gui_app = gui.App(config.gui_theme) self.ev_manager.gui_app = self.gui_app c = gui.Container(align=0,valign=-1) #Mode Relaxed Button #--------------------------------------- b = GameModeRelaxedButton(ev_manager=self.ev_manager) self.b = b print b.rect c.add(b, 0, 200) #Mode Time Challenge Button #--------------------------------------- b = TimeChallengeButton(ev_manager=self.ev_manager) self.b = b print b.rect c.add(b, 0, 250) #Mode Think Ahead Button #--------------------------------------- # b = PlanAheadButton(ev_manager=self.ev_manager) # self.b = b # print b.rect # c.add(b, 0, 300) #Initialize #--------------------------------------- self.gui_app.init(c) def render(self, surface): surface.blit(self.background, (0, 0)) #GUI self.gui_app.paint(surface) class GameRoom(Room): def __init__(self, screen, ev_manager): Room.__init__(self, screen, ev_manager) #Game mode #--------------------------------------- self.new_board_timer = None self.game_mode = config.game_mode config.current_highs = self.get_highs_table() self.highs_dialog = None self.game_over = False #Images #--------------------------------------- self.background = pygame.image.load('assets/images/interface/game screen2-1.jpg').convert() self.logo = pygame.image.load('assets/images/interface/logo_small.png').convert_alpha() self.game_over_text = pygame.image.load('assets/images/interface/text_game_over.png').convert_alpha() self.trip_complete_text = pygame.image.load('assets/images/interface/text_trip_complete.png').convert_alpha() self.zoom_game_over = None self.zoom_trip_complete = None self.fade_out = None #Text #--------------------------------------- self.font = pygame.font.Font(config.font_sans, config.interface_font_size) #Create game components #--------------------------------------- self.continent = self.set_continent(config.continent) self.board = Board(config.board_size, self.ev_manager) self.deck = Deck(self.ev_manager, self.continent) self.map = Map(self.continent) self.longest_trip = 0 #Set pos of game components #--------------------------------------- board_pos = (SCREEN_MARGIN[0], 109) self.board.set_pos(board_pos) map_pos = (config.screen_size[0] - self.map.size[0] - SCREEN_MARGIN[0], 57); self.map.set_pos(map_pos) #Trackers #--------------------------------------- self.game_clock = Chrono(self.ev_manager) self.swap_counter = 0 self.level = 0 #Create gui #--------------------------------------- self.create_gui() #Create initial board #--------------------------------------- self.new_board = self.deck.deal_new_board(self.board) self.ev_manager.post(NewBoardComplete(self.new_board)) def set_continent(self, continent_const): #Set continent based on const if continent_const == config.EUROPE: return continents.Europe() if continent_const == config.AFRICA: return continents.Africa() else: raise Exception('Continent constant not recognized') #Create pgu gui elements def create_gui(self): #Setup #--------------------------------------- self.gui_form = gui.Form() self.gui_app = gui.App(config.gui_theme) self.ev_manager.gui_app = self.gui_app c = gui.Container(align=-1,valign=-1) #Timer Progress bar #--------------------------------------- self.timer_bar = None self.time_increase = None self.minutes_left = None self.seconds_left = None self.timer_text = None if self.game_mode == config.TIME_CHALLENGE: self.time_increase = config.time_challenge_start_time self.timer_bar = gui.ProgressBar(config.time_challenge_start_time,0,config.max_time_bank,width=306) c.add(self.timer_bar, 172, 57) #Connections Progress bar #--------------------------------------- self.connections_bar = None self.connections_bar = gui.ProgressBar(0,0,config.longest_trip_needed,width=306) c.add(self.connections_bar, 172, 83) #Quit Button #--------------------------------------- b = QuitButton(ev_manager=self.ev_manager) c.add(b, 950, 20) #Generate Board Button #--------------------------------------- b = GenerateBoardButton(ev_manager=self.ev_manager, room=self) c.add(b, 500, 20) #Board Size? #--------------------------------------- bs = SetBoardSizeContainer(config.BOARD_LARGE, ev_manager=self.ev_manager, board=self.board) c.add(bs, 640, 20) #Fill Board? #--------------------------------------- t = FillBoardCheckbox(config.fill_board, ev_manager=self.ev_manager) c.add(t, 740, 20) #Darkness? #--------------------------------------- t = UseDarknessCheckbox(config.use_darkness, ev_manager=self.ev_manager) c.add(t, 840, 20) #Initialize #--------------------------------------- self.gui_app.init(c) def advance_level(self): self.level += 1 print 'Advancing to next level' print 'New level: ' + str(self.level) if self.timer_bar: print 'Time increase: ' + str(self.time_increase) self.timer_bar.value += self.time_increase self.time_increase = max(config.min_advance_time, int(self.time_increase * 0.9)) self.board = self.new_board self.new_board = None self.zoom_trip_complete = None self.game_clock.unpause() def notify(self, event): #Tick event if isinstance(event, TickEvent): pygame.display.set_caption('FPS: ' + str(int(event.fps))) self.render(self.screen) pygame.display.update() #Wait to deal new board when advancing levels if self.zoom_trip_complete and self.zoom_trip_complete.finished: self.zoom_trip_complete = None self.ev_manager.post(UnfreezeCards()) self.new_board = self.deck.deal_new_board(self.board) self.ev_manager.post(NewBoardComplete(self.new_board)) #New high score? if self.zoom_game_over and self.zoom_game_over.finished and not self.highs_dialog: if config.current_highs.check(self.level) != None: self.zoom_game_over.visible = False data = 'time:' + str(self.game_clock.time) + ',swaps:' + str(self.swap_counter) self.highs_dialog = HighScoreDialog(score=self.level, data=data, ev_manager=self.ev_manager) self.highs_dialog.open() elif not self.fade_out: self.fade_out = FadeOut(self.ev_manager, config.TITLE_SCREEN) #Second event elif isinstance(event, SecondEvent): if self.timer_bar: if not self.game_clock.paused: self.timer_bar.value -= 1 if self.timer_bar.value <= 0 and not self.game_over: self.ev_manager.post(GameOver()) self.minutes_left = self.timer_bar.value / 60 self.seconds_left = self.timer_bar.value % 60 if self.seconds_left < 10: leading_zero = '0' else: leading_zero = '' self.timer_text = ''.join(['Time Left: ', str(self.minutes_left), ':', leading_zero, str(self.seconds_left)]) #Game over elif isinstance(event, GameOver): self.game_over = True self.zoom_game_over = ZoomImage(self.ev_manager, self.game_over_text) #Trip complete event elif isinstance(event, TripComplete): print 'You did it!' self.game_clock.pause() self.zoom_trip_complete = ZoomImage(self.ev_manager, self.trip_complete_text) self.new_board_timer = Timer(self.ev_manager, 2) self.ev_manager.post(FreezeCards()) print 'Room posted newboardcomplete' #Board Refresh Complete elif isinstance(event, BoardRefreshComplete): if event.board == self.board: print 'Longest trip needed: ' + str(config.longest_trip_needed) print 'Your longest trip: ' + str(self.board.longest_trip) if self.board.longest_trip >= config.longest_trip_needed: self.ev_manager.post(TripComplete()) elif event.board == self.new_board: self.advance_level() self.connections_bar.value = self.board.longest_trip self.connection_text = ' '.join(['Connections:', str(self.board.longest_trip), '/', str(config.longest_trip_needed)]) #CardSwapComplete elif isinstance(event, CardSwapComplete): self.swap_counter += 1 elif isinstance(event, ConfigChangeBoardSize): config.board_size = event.new_size elif isinstance(event, ConfigChangeCardSize): config.card_size = event.new_size elif isinstance(event, ConfigChangeFillBoard): config.fill_board = event.new_value elif isinstance(event, ConfigChangeDarkness): config.use_darkness = event.new_value def render(self, surface): #Background surface.blit(self.background, (0, 0)) #Map self.map.render(surface) #Board self.board.render(surface) #Logo surface.blit(self.logo, (10,10)) #Text connection_text = self.font.render(self.connection_text, True, BLACK) surface.blit(connection_text, (25, 84)) if self.timer_text: timer_text = self.font.render(self.timer_text, True, BLACK) surface.blit(timer_text, (25, 64)) #GUI self.gui_app.paint(surface) if self.zoom_trip_complete: self.zoom_trip_complete.render(surface) if self.zoom_game_over: self.zoom_game_over.render(surface) if self.fade_out: self.fade_out.render(surface) class HighScoresRoom(Room): def __init__(self, screen, ev_manager): Room.__init__(self, screen, ev_manager) self.background = pygame.image.load('assets/images/interface/background.jpg').convert() #Initialize #--------------------------------------- self.gui_app = gui.App(config.gui_theme) self.ev_manager.gui_app = self.gui_app c = gui.Container(align=0,valign=0) #High Scores Table #--------------------------------------- hst = HighScoresTable() c.add(hst, 0, 0) self.gui_app.init(c) def render(self, surface): surface.blit(self.background, (0, 0)) #GUI self.gui_app.paint(surface) game_components.py #Remote imports import pygame from pygame.locals import * import random import operator from copy import copy from math import sqrt, floor #Local imports import config from events import * from matrix import Matrix from textrect import render_textrect, TextRectException from hyphen import hyphenator from textwrap2 import TextWrapper ############################## #CONSTANTS ############################## SCREEN_MARGIN = (10, 10) #Colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) YELLOW = (255, 200, 0) #Directions LEFT = -1 RIGHT = 1 UP = 2 DOWN = -2 #Cards CARD_MARGIN = (10, 10) CARD_PADDING = (2, 2) #Card types BLANK = 0 COUNTRY = 1 TRANSPORT = 2 #Transport types PLANE = 0 TRAIN = 1 CAR = 2 SHIP = 3 class Timer(object): def __init__(self, ev_manager, time_left): self.ev_manager = ev_manager self.ev_manager.register_listener(self) self.time_left = time_left self.paused = False def __repr__(self): return str(self.time_left) def pause(self): self.paused = True def unpause(self): self.paused = False def notify(self, event): #Pause Event if isinstance(event, Pause): self.pause() #Unpause Event elif isinstance(event, Unpause): self.unpause() #Second Event elif isinstance(event, SecondEvent): if not self.paused: self.time_left -= 1 class Chrono(object): def __init__(self, ev_manager, start_time=0): self.ev_manager = ev_manager self.ev_manager.register_listener(self) self.time = start_time self.paused = False def __repr__(self): return str(self.time_left) def pause(self): self.paused = True def unpause(self): self.paused = False def notify(self, event): #Pause Event if isinstance(event, Pause): self.pause() #Unpause Event elif isinstance(event, Unpause): self.unpause() #Second Event elif isinstance(event, SecondEvent): if not self.paused: self.time += 1 class Map(object): def __init__(self, continent): self.map_image = pygame.image.load(continent.map).convert_alpha() self.map_text = pygame.image.load(continent.map_text).convert_alpha() self.pos = (0, 0) self.set_color() self.map_image = pygame.transform.smoothscale(self.map_image, config.map_size) self.size = self.map_image.get_size() def set_pos(self, pos): self.pos = pos def set_color(self): image_pixel_array = pygame.PixelArray(self.map_image) image_pixel_array.replace(config.GRAY1, config.COLOR1) image_pixel_array.replace(config.GRAY2, config.COLOR2) image_pixel_array.replace(config.GRAY3, config.COLOR3) image_pixel_array.replace(config.GRAY4, config.COLOR4) image_pixel_array.replace(config.GRAY5, config.COLOR5)

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >