Search Results

Search found 7391 results on 296 pages for 'record locking'.

Page 113/296 | < Previous Page | 109 110 111 112 113 114 115 116 117 118 119 120  | Next Page >

  • Difference between SQL 2005 and SQL 2008 for inserting multiple rows with XML

    - by Sam Dahan
    I am using the following SQL code for inserting multiple rows of data in a table. The data is passed to the stored procedure using an XML variable : INSERT INTO MyTable SELECT SampleTime = T.Item.value('SampleTime[1]', 'datetime'), Volume1 = T.Item.value('Volume1[1]', 'float'), Volume2 = T.Item.value('Volume2[1]', 'float') FROM @xml.nodes('//Root/MyRecord') T(item) I have a whole bunch of unit tests to verify that I am inserting the right information, the right number of records, etc.. when I call the stored procedure. All fine and dandy - that is, until we began to monkey around with the compatibility level of the database. The code above worked beautifully as long as we kept the compatibility level of the DB at 90 (SQL 2005). When we set the compatibility level at 100 (SQL 2008), the unit tests failed, because the stored procedure using the code above times out. The unit tests are dropping the database, re-creating it from scripts, and running the tests on the brand new DB, so it's not - I think - a question of the 'old compatibility level' sticking around. Using the SQL Management studio, I made up a quick test SQL script. Using the same XML chunk, I alter the DB compat level , truncate the table, then use the code above to insert 650 rows. When the level is 90 (SQL 2005), it runs in milliseconds. When the level is 100 (SQL 2008) it sometimes takes over a minute, sometimes runs in milliseconds. I'd appreciate any insight anyone might have into that. EDIT The script takes over a minute to run with my actual data, which has more rows than I show here, is a real table, and has an index. With the following example code, the difference goes between milliseconds and around 5 seconds. --use [master] --ALTER DATABASE MyDB SET compatibility_level =100 use [MyDB] declare @xml xml set @xml = '<?xml version="1.0"?> <Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Record> <SampleTime>2009-01-24T00:00:00</SampleTime> <Volume1>0</Volume1> <Volume2>0</Volume2> </Record> ..... 653 records, sample time spaced out 4 hours ........ </Root>' DECLARE @myTable TABLE( ID int IDENTITY(1,1) NOT NULL, [SampleTime] [datetime] NOT NULL, [Volume1] [float] NULL, [Volume2] [float] NULL) INSERT INTO @myTable select T.Item.value('SampleTime[1]', 'datetime') as SampleTime, Volume1 = T.Item.value('Volume1[1]', 'float'), Volume2 = T.Item.value('Volume2[1]', 'float') FROM @xml.nodes('//Root/Record') T(item) I uncomment the 2 lines at the top, select them and run just that (the ALTER DATABASE statement), then comment the 2 lines, deselect any text and run the whole thing. When I change from 90 to 100, it runs all the time in 5 seconds (I change the level once, but I run the series several times to see if I have consistent results). When I change from 100 to 90, it runs in milliseconds all the time. Just so you can play with it too. I am using SQL Server 2008 R2 standard edition.

    Read the article

  • Virtual Cam - Cam Split .NET

    - by Fish
    I'm looking for a virtual webcam driver to use in a .NET project, this project will be GPL, and have no idea how many installations there will be The idea is that the application is using the webcam without locking the device. Found a couple of programs that do the job, but either in application and/or too expensive: * http://www.softservice.org/products_camsplitter.html (9.99$/installation) * splitcamera.com (program, no SDK available) All idea's are welcome

    Read the article

  • Looping through siblings of a specific row/setting up function

    - by Matt
    Trying to work through my javascript book I am referencing to learn the language and got stuck on looping through siblings of a specific row. W3schools and W3 didnt have what i was looking for. Below is a function walk-through... It reads: Create the countRecords() function. The purpose of this function is to count the number of visible rows in the data table after the table headings. The total is then displayed in the table cell with the id "records". Add the follow commands to the function: a. Create a object named headRow that points to the table row with the id "titleRow". Create a variable named rowCount, setting its initial value to 0. b. Create a for loop that uses familial references starting with the first sibling of headRow and moving to the next sibling until there are no siblings left. Within the for loop. test whether the node name of the currentnext sibling until there are no sibilings left. Within the for loop test whether the node name of the current node is equal to "TR". If it is, test wheter the value of its display style is equal to an empty text string. If it is (indicating that it is visible in the document) increate the value of the rowCount variable by 1. c. Change the text of the "records" table cell to the value of the rowCount variable. Don't use innerHTML. Create a text node that contains the value of the rowCount variable and assign it to a variable called txt. Create a variable called record to store the reference to the element "records" table cell. d. Insert an if condition that test whether the "records" cell has any child nodes. If it does, replace the replace the text node of the "record" table cell with the created text node (txt). If it doesn't append the text node to the cell. var headRow; // part a var rowCount = 0; //part b this is where I get lost. I know I need to access the id titleRow but unsure how to set my loop up specifically for this headRow = document.getElementById("titleRow"); for(var i=0; i<headrow.length; i++) { if (something is not equal == "TH") { make code happen here } if (is "TR" == ""){ rowCount = +1; } //part c var txt = document.createTextNode(rowCount); var record = document.getElementsById("records") //part d holding off on this part until I get a,b,c figured out. The HTML supporting snippet: <table id="filters"> <tr><th colspan="2">Filter Product List</th></tr> <tr> <td>Records: </td> <td id="records"></td> </tr> <table id="prodTable"> <tr><th colspan="8">Digital Cameras</th></tr> <tr id="titleRow"> <th>Model</th> <th>Manufacturer</th> <th>Resolution</th> <th>Zoom</th> <th>Media</th> <th>Video</th> <th>Microphone</th> </tr> Thanks for the help!

    Read the article

  • Static lock in Python?

    - by roddik
    Hello. I've got the following code: import time import threading class BaseWrapper: #static class lock = threading.Lock() @staticmethod def synchronized_def(): BaseWrapper.lock.acquire() time.sleep(5) BaseWrapper.lock.release() def test(): print time.ctime() if __name__ is '__main__': for i in xrange(10): threading.Thread(target = test).start() I want to have a method synchronized using static lock. However the above code prints the same time ten times, so it isn't really locking. How can I fix it? TIA

    Read the article

  • Determine modifier key state without an InputEvent object in Java

    - by heycam
    I need to determine the current state of the Shift key, but at the time I need the state I don't have an InputEvent object around. I need something like java.awt.Toolkit.getLockingKeyState(int) that works for Shift, not just the locking keys like VK_CAPS_LOCK. Is there a way I can do this without listening to input events and storing the for later when I need to check the state? Thanks!

    Read the article

  • How to handle recurring dates (dates only) in .NET?

    - by Wayne M
    I am trying to figure out a good way to handle recurring events in .NET, specifically for an ASP.NET MVC application. The idea is that a user can create an event and specify that the event can occur repeatedly after a specific interval (e.g. "every two weeks", "once a month" and so on). What would be the best way to tackle this? My brainstorming right now is to have two tables: Job and RecurringJob. Job is the "master" record and has the description of the job as well a key to what customer it's for, while RecurringJob links back to Job and has additional info on what the occurrence frequency is (e.g. 1 for "once a month") as well as the timespan (e.g. "Weekly", "Monthly"). The issue is how to determine and set the next occurrence of the job since this will have to be something that's done regularly. I've seen two trains of thought with this: This logic should either be stored in a database column and periodically updated, or calculated on the fly in the code. Any thoughts or suggestions on tackling this? Edit: this is for a subscription based web app I'm creating to let service businesses schedule their common recurring jobs easily and track their customers. So a typical use might be to create a "Cut lawn" job for Mr Smith that occurs every month The exact date isn't important - it's the ability for the customer to see that Mr Smith gets his lawn cut every month and followup with him about it. Let me rephrase the above to better convey my idea. A sample use case for the application might be as follows: User pulls up the customer record for John Smith and clicks the Add Job link. The user fills out the form to create a job with a name of "Cut lawn", a start date of 11/15/2009, and selects a checkbox indicating that this job continually occurs. The user is presented with a secondary screen asking for the job frequency. The user indicates (haven't decided how at this point - let's assume select lists) that the job occurs once a month. User clicks save. Now, when the user views the record for John Smith, they can see that he has a job, "Cut lawn", that occurs every month starting from 11/15/2009. On the main dashboard when it's one week prior to the assumed start date, the user sees the job displayed with an indicator such as "12/15/2009 - Cut lawn (John Smith)". A week before the due date someone from the company calls him up to schedule and he says he's going to be out of town until 1/1/2010, so he wants his appointment rescheduled for that date. Our user can change the date for the job to be 1/1/2010, and now the recurrence will start one month from that date (e.g. next time will be 2/1/2010). The idea behind this is that the app is targeting businesses like lawn care, plumbers, carpet cleaners and the like where the exact date isn't as important (because it can and will change as people are busy), the key thing is to give the business an indicator that Mr. Smith's monthly service is coming up, and someone should give him a call to determine when exactly it can be scheduled for. In effect give these businesses a way to track repeat business and know when it's time to followup with a customer.

    Read the article

  • select for update with ruby oci8

    - by ash34
    how do I do a 'select for update' and then 'update' the row using ruby oci8. I have two fields counter1 and counter2 in a table which has only 1 record. I want to select the values from this table and then increment them by locking the row using select for update. thanks.

    Read the article

  • Client server architecture question

    - by Shane Fulmer
    I am working on a client server system, and am running into issues where multiple clients are executing an action at the same time. We are able to solve this by locking on the critical section of code, which ensures that the first client will complete the action before the second client enters the code block. My question is this: our server is also clustered, so multiple instances of the server itself can exist, which recreates the same problem as before. How could we solve this problem? Thanks!

    Read the article

  • Django: How can I protect against concurrent modification of data base entries

    - by Ber
    If there a way to protect against concurrent modifications of the same data base entry by two or more users? It would be acceptable to show an error message to the user performing the second commit/save operation, but data should not be silently overwritten. I think locking the entry is not an option, as a user might use the "Back" button or simply close his browser, leaving the lock for ever.

    Read the article

  • GetAcceptExSockaddrs returns garbage! Does anyone know why?

    - by David
    Hello, I'm trying to write a quick/dirty echoserver in Delphi, but I notice that GetAcceptExSockaddrs seems to be writing to only the first 4 bytes of the structure I pass it. USES SysUtils; TYPE BOOL = LongBool; DWORD = Cardinal; LPDWORD = ^DWORD; short = SmallInt; ushort = Word; uint16 = Word; uint = Cardinal; ulong = Cardinal; SOCKET = uint; PVOID = Pointer; _HANDLE = DWORD; _in_addr = packed record s_addr : ulong; end; _sockaddr_in = packed record sin_family : short; sin_port : uint16; sin_addr : _in_addr; sin_zero : array[0..7] of Char; end; P_sockaddr_in = ^_sockaddr_in; _Overlapped = packed record Internal : Int64; Offset : Int64; hEvent : _HANDLE; end; LP_Overlapped = ^_Overlapped; IMPORTS function _AcceptEx (sListenSocket, sAcceptSocket : SOCKET; lpOutputBuffer : PVOID; dwReceiveDataLength, dwLocalAddressLength, dwRemoteAddressLength : DWORD; lpdwBytesReceived : LPDWORD; lpOverlapped : LP_OVERLAPPED) : BOOL; stdcall; external MSWinsock name 'AcceptEx'; procedure _GetAcceptExSockaddrs (lpOutputBuffer : PVOID; dwReceiveDataLength, dwLocalAddressLength, dwRemoteAddressLength : DWORD; LocalSockaddr : P_Sockaddr_in; LocalSockaddrLength : LPINT; RemoteSockaddr : P_Sockaddr_in; RemoteSockaddrLength : LPINT); stdcall; external MSWinsock name 'GetAcceptExSockaddrs'; CONST BufDataSize = 8192; BufAddrSize = SizeOf (_sockaddr_in) + 16; VAR ListenSock, AcceptSock : SOCKET; Addr, LocalAddr, RemoteAddr : _sockaddr_in; LocalAddrSize, RemoteAddrSize : INT; Buf : array[1..BufDataSize + BufAddrSize * 2] of Byte; BytesReceived : DWORD; Ov : _Overlapped; BEGIN //WSAStartup, create listen socket, bind to port 1066 on any interface, listen //Create event for overlapped (autoreset, initally not signalled) //Create accept socket if _AcceptEx (ListenSock, AcceptSock, @Buf, BufDataSize, BufAddrSize, BufAddrSize, @BytesReceived, @Ov) then WinCheck ('SetEvent', _SetEvent (Ov.hEvent)) else if GetLastError <> ERROR_IO_PENDING then WinCheck ('AcceptEx', GetLastError); {do WaitForMultipleObjects} _GetAcceptExSockaddrs (@Buf, BufDataSize, BufAddrSize, BufAddrSize, @LocalAddr, @LocalAddrSize, @RemoteAddr, @RemoteAddrSize); So if I run this, connect to it with Telnet (on same computer, connecting to localhost) and then type a key, WaitForMultipleObjects will unblock and GetAcceptExSockaddrs will run. But the result is garbage! RemoteAddr.sin_family = -13894 RemoteAddr.sin_port = 64 and the rest is zeroes. What gives? Thanks in advance!

    Read the article

  • compare windows server for patch/update/hotfix installs

    - by user12002221
    Are there any tools that can be used to connect to windows 2008 servers, and get a comparison of the installed patches/updates on the servers, showing what is installed on one and not on the other? This is to help isolate an issue we are seeing on a specific windows server, in a load balanced setup. There is a certain performance/locking issue, which is mitigated whenever one of the servers is disabled. Please share, if you have any suggestions. Thanks in advance!

    Read the article

  • DOM Storage and locks

    - by user535759
    Since DOM storage and its equivalencies persist in between tabs and windows, I've thought about using it for message passing. The problem is that fetch and store are different operations, and therefore not atomic. I have models that rely on UUID generation, conflict resolutions, and beaconing to do the small subset of what I need to do, but my real question is this: Since the local storage is a shared memory resource, what are the locking mechanisms available for mutual access?

    Read the article

  • application blocking

    - by pradeep
    I have a application which runs over browser ...php application... i need to lock this application to only few machines and laptops that we allow to access. IP locking cannot be done as laptops can be on wifi from outside... Any Idea on how to do this?

    Read the article

  • Need to determine button clicked in a JQuery mobile popup and perform actions based thereon

    - by Clifford
    I am having a problem with a JQM popup. The popup has 3 buttons, and the action taken in the main program depends on which button is clicked. The code in the main program is run more than once and I am not sure why. The simple example below uses an alert to display which button on the popup was clicked. When the popup is called the first time, it works as hoped, the 2nd time, the alert is displayed twice, the 3rd time, the alert is displayed 3 times, etc. <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="css/jquery.mobile-1.3.2.min.css" /> <script type="text/javascript" charset="utf-8" src="cordova-2.6.0.js"></script> <script type="text/javascript" src="js/jquery-1.9.1.min.js"/></script> <script type="text/javascript" src="js/jquery.mobile-1.3.2.min.js"></script> <script> function doCustomDialog(text1,button1,button2,button3,callback) { $("#customDialog .customDialogDesc").text(text1); $("#customDialog .customDialogOption1").text(button1).on("click.customDialog", function(){ callback("option1"); }); $("#customDialog .customDialogOption2").text(button2).on("click.customDialog", function(){ callback("option2"); }); $("#customDialog .customDialogOption3").text(button3).on("click.customDialog", function(){ callback("option3"); }); $("#customDialog").popup("open"); } </script> </head> <body> <div data-role="page" id="mainPage"> <div data-role="content"> <INPUT type="button" id="confirm" value="Save data" /> <div data-role="popup" id="customDialog" data-title="Are you sure?" class="ui-content"> <p class ="customDialogDesc">???</p> <a href="#" class ="customDialogOption1" data-role="button" data-theme="b" data-rel="back">Yes</a> <a href="#" class ="customDialogOption2" data-role="button" data-theme="b" data-rel="back">No</a> <a href="#" class ="customDialogOption3" data-role="button" data-theme="b" data-rel="back">Cancel</a> </div> </div> </div> <script> $("#mainPage").on("pageshow", function(e) { $("#confirm").click(function() { doCustomDialog("A similar record already exists. Do you want to Update the existing record or Add a new record?", "Update", "Add", "Cancel", function( returned ) { //Do things depending on the button clicked, for now just display which button was clicked alert(returned); }); }); }); </script> </body> </html>

    Read the article

  • Hibernate's version values in Grails app

    - by xain
    I'm looking at a database dump file, and I see many records in various tables with their version number set in values other than 0 (even 94 in one case). I understand it has to do with hibernate locking strategy, but my concern is that today is Sunday, and the site has almost no visitors so is: is this normal ? Or is there a known hibernate bug or even some programming malpractice producing this ?

    Read the article

  • c# Unable to open file for reading

    - by Maks
    I'm writing a program that uses FileSystemWatcher to monitor changes to a given directory, and when it recieves OnCreated or OnChanged event, it copies those created/changed files to a specified directorie(s). At first I had problems with the fact that OnChanged/OnCreated events can be sent twice (not acceptable in case it needed to process 500MB file) but I made a way around this and with what I'm REALLY STUCKED with is getting the following IOException: The process cannot access the file 'C:\Where are Photos\bookmarks (11).html' because it is being used by another process. Thus, preventing the program from copying all the files it should. So as I mentioned, when user uses this program he/she specifes monitored directory, when user copies/creates/changes file in that directory, program should get OnCreated/OnChanged event and then copy that file to few other directories. Above error happens in all casess, if user copies few files that needs to owerwrite other ones in folder being monitored or when copying bulk of several files or even sometimes when copying one file in a monitored directory. Whole program is quite big so I'm sending the most important parts. OnCreated: private void OnCreated(object source, FileSystemEventArgs e) { AddLogEntry(e.FullPath, "created", ""); // Update last access data if it's file so the same file doesn't // get processed twice because of sending another event. if (fileType(e.FullPath) == 2) { lastPath = e.FullPath; lastTime = DateTime.Now; } // serves no purpose now, it will be remove soon string fileName = GetFileName(e.FullPath); // copies file from source to few other directories Copy(e.FullPath, fileName); Console.WriteLine("OnCreated: " + e.FullPath); } OnChanged: private void OnChanged(object source, FileSystemEventArgs e) { // is it directory if (fileType(e.FullPath) == 1) return; // don't mind directory changes itself // Only if enough time has passed or if it's some other file // because two events can be generated int timeDiff = ((TimeSpan)(DateTime.Now - lastTime)).Seconds; if ((timeDiff < minSecsDiff) && (e.FullPath.Equals(lastPath))) { Console.WriteLine("-- skipped -- {0}, timediff: {1}", e.FullPath, timeDiff); return; } // Update last access data for above to work lastPath = e.FullPath; lastTime = DateTime.Now; // Only if size is changed, the rest will handle other handlers if (e.ChangeType == WatcherChangeTypes.Changed) { AddLogEntry(e.FullPath, "changed", ""); string fileName = GetFileName(e.FullPath); Copy(e.FullPath, fileName); Console.WriteLine("OnChanged: " + e.FullPath); } } fileType: private int fileType(string path) { if (Directory.Exists(path)) return 1; // directory else if (File.Exists(path)) return 2; // file else return 0; } Copy: private void Copy(string srcPath, string fileName) { foreach (string dstDirectoy in paths) { string eventType = "copied"; string error = "noerror"; string path = ""; string dirPortion = ""; // in case directory needs to be made if (srcPath.Length > fsw.Path.Length) { path = srcPath.Substring(fsw.Path.Length, srcPath.Length - fsw.Path.Length); int pos = path.LastIndexOf('\\'); if (pos != -1) dirPortion = path.Substring(0, pos); } if (fileType(srcPath) == 1) { try { Directory.CreateDirectory(dstDirectoy + path); //Directory.CreateDirectory(dstDirectoy + fileName); eventType = "created"; } catch (IOException e) { eventType = "error"; error = e.Message; } } else { try { if (!overwriteFile && File.Exists(dstDirectoy + path)) continue; // create new dir anyway even if it exists just to be sure Directory.CreateDirectory(dstDirectoy + dirPortion); // copy file from where event occured to all specified directories using (FileStream fsin = new FileStream(srcPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (FileStream fsout = new FileStream(dstDirectoy + path, FileMode.Create, FileAccess.Write)) { byte[] buffer = new byte[32768]; int bytesRead = -1; while ((bytesRead = fsin.Read(buffer, 0, buffer.Length)) > 0) fsout.Write(buffer, 0, bytesRead); } } } catch (Exception e) { if ((e is IOException) && (overwriteFile == false)) { eventType = "skipped"; } else { eventType = "error"; error = e.Message; // attempt to find and kill the process locking the file. // failed, miserably System.Diagnostics.Process tool = new System.Diagnostics.Process(); tool.StartInfo.FileName = "handle.exe"; tool.StartInfo.Arguments = "\"" + srcPath + "\""; tool.StartInfo.UseShellExecute = false; tool.StartInfo.RedirectStandardOutput = true; tool.Start(); tool.WaitForExit(); string outputTool = tool.StandardOutput.ReadToEnd(); string matchPattern = @"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)"; foreach (Match match in Regex.Matches(outputTool, matchPattern)) { System.Diagnostics.Process.GetProcessById(int.Parse(match.Value)).Kill(); } Console.WriteLine("ERROR: {0}: [ {1} ]", e.Message, srcPath); } } } AddLogEntry(dstDirectoy + path, eventType, error); } } I checked everywhere in my program and whenever I use some file I use it in using block so even writing event to log (class for what I ommited since there is probably too much code already in post) wont lock the file, that is it shouldn't since all operations are using using statement block. I simply have no clue who's locking the file if not my program "copy" process from user through Windows or something else. Right now I have two possible "solutions" (I can't say they are clean solutions since they are hacks and as such not desireable). Since probably the problem is with fileType method (what else could lock the file?) I tried changing it to this, to simulate "blocking-until-ready-to-open" operation: fileType: private int fileType(string path) { FileStream fs = null; int ret = 0; bool run = true; if (Directory.Exists(path)) ret = 1; else { while (run) { try { fs = new FileStream(path, FileMode.Open); ret = 2; run = false; } catch (IOException) { } finally { if (fs != null) { fs.Close(); fs.Dispose(); } } } } return ret; } This is working as much as I could tell (test), but... it's hack, not to mention other deficients. The other "solution" I could try (I didn't test it yet) is using GC.Collect() somewhere at the end of fileType() method. Maybe even worse "solution" than previous one. Can someone pleas tell me, what on earth is locking the file, preventing it from opening and how can I fix that? What am I missing to see? Thanks in advance.

    Read the article

  • hosting simple python scripts in a container to handle concurrency, configuration, caching, etc.

    - by Justin Grant
    My first real-world Python project is to write a simple framework (or re-use/adapt an existing one) which can wrap small python scripts (which are used to gather custom data for a monitoring tool) with a "container" to handle boilerplate tasks like: fetching a script's configuration from a file (and keeping that info up to date if the file changes and handle decryption of sensitive config data) running multiple instances of the same script in different threads instead of spinning up a new process for each one expose an API for caching expensive data and storing persistent state from one script invocation to the next Today, script authors must handle the issues above, which usually means that most script authors don't handle them correctly, causing bugs and performance problems. In addition to avoiding bugs, we want a solution which lowers the bar to create and maintain scripts, especially given that many script authors may not be trained programmers. Below are examples of the API I've been thinking of, and which I'm looking to get your feedback about. A scripter would need to build a single method which takes (as input) the configuration that the script needs to do its job, and either returns a python object or calls a method to stream back data in chunks. Optionally, a scripter could supply methods to handle startup and/or shutdown tasks. HTTP-fetching script example (in pseudocode, omitting the actual data-fetching details to focus on the container's API): def run (config, context, cache) : results = http_library_call (config.url, config.http_method, config.username, config.password, ...) return { html : results.html, status_code : results.status, headers : results.response_headers } def init(config, context, cache) : config.max_threads = 20 # up to 20 URLs at one time (per process) config.max_processes = 3 # launch up to 3 concurrent processes config.keepalive = 1200 # keep process alive for 10 mins without another call config.process_recycle.requests = 1000 # restart the process every 1000 requests (to avoid leaks) config.kill_timeout = 600 # kill the process if any call lasts longer than 10 minutes Database-data fetching script example might look like this (in pseudocode): def run (config, context, cache) : expensive = context.cache["something_expensive"] for record in db_library_call (expensive, context.checkpoint, config.connection_string) : context.log (record, "logDate") # log all properties, optionally specify name of timestamp property last_date = record["logDate"] context.checkpoint = last_date # persistent checkpoint, used next time through def init(config, context, cache) : cache["something_expensive"] = get_expensive_thing() def shutdown(config, context, cache) : expensive = cache["something_expensive"] expensive.release_me() Is this API appropriately "pythonic", or are there things I should do to make this more natural to the Python scripter? (I'm more familiar with building C++/C#/Java APIs so I suspect I'm missing useful Python idioms.) Specific questions: is it natural to pass a "config" object into a method and ask the callee to set various configuration options? Or is there another preferred way to do this? when a callee needs to stream data back to its caller, is a method like context.log() (see above) appropriate, or should I be using yield instead? (yeild seems natural, but I worry it'd be over the head of most scripters) My approach requires scripts to define functions with predefined names (e.g. "run", "init", "shutdown"). Is this a good way to do it? If not, what other mechanism would be more natural? I'm passing the same config, context, cache parameters into every method. Would it be better to use a single "context" parameter instead? Would it be better to use global variables instead? Finally, are there existing libraries you'd recommend to make this kind of simple "script-running container" easier to write?

    Read the article

  • Thread safety in C# arrays

    - by Betamoo
    Does having 2 different threads : one reading from a C# array (e.g from first location), and another one writing to the same C# array but to a different location(e.g to the last location) is thread safe or not? (And I mean here without locking reading nor writing)

    Read the article

  • even small file upload stops activity on apache/rails

    - by Pavel K.
    on my rails(2.3.5) app(currently 50-70rpm, maximum response time around 0.7s), uploading even 700k file(using paperclip plugin) locks up the server for web requests for everyone for 2 minutes! (other apps on same server work normally) does anyone have a clue why that might be happening? i am using some mysql transactions which lock the database also if that might be an issue i read http://www.therailsway.com/2009/4/23/uploading-files but it couldn't be locking server for 2 minutes for a small file, could it?!

    Read the article

  • Trying to convert string to datetime

    - by user1596472
    I am trying to restrict a user from entering a new record if the date requested already exits. I was trying to do a count to see if the table that the record would be placed in already has that date 1 or not 0. I have a calendar extender attached to a text box which has the date. I keep getting either a: String was not recognized as a valid DateTime. or Unable to cast object of type 'System.Web.UI.WebControls.TextBox' to type 'System.IConvertible'. depending on the different things I have tried. Here is my code. TextBox startd = (TextBox)(DetailsView1.FindControl("TextBox5")); TextBox endd = (TextBox)(DetailsView1.FindControl("TextBox7")); DropDownList lvtype = (DropDownList)(DetailsView1.FindControl("DropDownList6")); DateTime scheduledDate = DateTime.ParseExact(startd.Text, "dd/MM/yyyy", null); DateTime endDate = DateTime.ParseExact(endd.Text, "dd/MM/yyyy", null); DateTime newstartDate = Convert.ToDateTime(startd.Text); DateTime newendDate = Convert.ToDateTime(endd.Text); //foreach (DataRow row in sd.Tables[0].Rows) DateTime dt = newstartDate; while (dt <= newendDate) { //for retreiving from table Decimal sd = SelectCountDate(dt, lvtype.SelectedValue, countDate); String ndt = Convert.ToDateTime(dt).ToShortDateString(); // //start = string.CompareOrdinal(scheduledDate, ndt); // // end = string.CompareOrdinal(endDate, ndt); //trying to make say when leavetpe is greater than count 1 then throw error. if (sd > 0) { Response.Write("<script>alert('Date Already Requested');</script>"); } dt.AddDays(1); } ^^^ This version throws the: "String was not recognized as valid date type" error But if i replace the string with either of these : /*-----------------------Original------------------------------------ string scheduledDate = Convert.ToDateTime(endd).ToShortDateString(); string endDate = Convert.ToDateTime(endd).ToShortDateString(); -------------------------------------------------------------------*/ /*----------10-30--------------------------------------- DateTime scheduledDate = DateTime.Parse(startd.Text); DateTime endDate = DateTime.Parse(endd.Text); ------------------------------------------------------*/ I get the "Unable to cast object of type 'System.Web.UI.WebControls.TextBox' to type 'System.IConvertible'." error. I am just trying to stop a user from entering a record date that already exits. <InsertItemTemplate> <asp:TextBox ID="TextBox5" runat="server" Height="19px" Text='<%# Bind("lstdate", "{0:MM/dd/yyyy}") %>' Width="67px"></asp:TextBox> <asp:CalendarExtender ID="TextBox5_CalendarExtender" runat="server" Enabled="True" TargetControlID="TextBox5"> </asp:CalendarExtender> <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox5" ErrorMessage="*Leave Date Required" ForeColor="Red"></asp:RequiredFieldValidator> <br /> <asp:CompareValidator ID="CompareValidator18" runat="server" ControlToCompare="TextBox7" ControlToValidate="TextBox5" ErrorMessage="Leave date cannot be after start date" ForeColor="Red" Operator="LessThanEqual" ToolTip="Must choose start date before end date"></asp:CompareValidator> </InsertItemTemplate>

    Read the article

  • Another Synergy issue: screen lock on Windows Server 2003

    - by pmr
    I have set up Synergy on Unix systems with no problems, however when I set up a Synergy server on a Windows Server 2003 box using I get an error message that the mouse cursor is locked when trying to move to the client system. I use a Microsoft Natural keyboard in case that matters (seems Scroll Lock might be involved). Does anyone have experience with using Synergy on Windows systems that have reported mouse screen locking in the log when unable to mouse over to a client system?

    Read the article

  • VB.net SyncLock Object

    - by Budius
    I always seen on SyncLock examples people using Private Lock1 As New Object ' declaration SyncLock Lock1 ' usage but why? In my specific case I'm locking a Queue to avoid problems on mult-threading Enqueueing and Dequeueing my data. Can I lock the Queue object itself, like this? Private cmdQueue As New Queue(Of QueueItem) ' declaration SyncLock cmdQueue ' usage Any help appreciated. Thanks.

    Read the article

< Previous Page | 109 110 111 112 113 114 115 116 117 118 119 120  | Next Page >