Daily Archives

Articles indexed Tuesday December 18 2012

Page 12/17 | < Previous Page | 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • Why isnt my data persisting with nskeyedarchiver?

    - by aking63
    Im just working on what should be the "finishing touches" of my first iPhone game. For some reason, when I save with NSKeyedArchiver/Unarchiver, the data seems to load once and then gets lost or something. Here's what I've been able to deduce: When I save in this viewController, pop to the previous one, and then push back into this one, the data is saved and prints as I want it to. But when I save in this viewController, then push a new one and pop back into this one, the data is lost. Any idea why this might be happening? Do I have this set up all wrong? I copied it from a book months ago. Here's the methods I use to save and load. - (void) saveGameData { NSLog(@"LS:saveGameData"); // SAVE DATA IMMEDIATELY NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *gameStatePath = [documentsDirectory stringByAppendingPathComponent:@"gameState.dat"]; NSMutableData *gameSave= [NSMutableData data]; NSKeyedArchiver *encoder = [[NSKeyedArchiver alloc] initForWritingWithMutableData:gameSave]; [encoder encodeObject:categoryLockStateArray forKey:kCategoryLockStateArray]; [encoder encodeObject:self.levelsPlist forKey:@"levelsPlist"]; [encoder finishEncoding]; [gameSave writeToFile:gameStatePath atomically:YES]; NSLog(@"encoded catLockState:%@",categoryLockStateArray); } - (void) loadGameData { NSLog(@"loadGameData"); // If there is a saved file, perform the load NSMutableData *gameData = [NSData dataWithContentsOfFile:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"gameState.dat"]]; // LOAD GAME DATA if (gameData) { NSLog(@"-Loaded Game Data-"); NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:gameData]; self.levelsPlist = [unarchiver decodeObjectForKey:@"levelsPlist"]; categoryLockStateArray = [unarchiver decodeObjectForKey:kCategoryLockStateArray]; NSLog(@"decoded catLockState:%@",categoryLockStateArray); } // CREATE GAME DATA else { NSLog(@"-Created Game Data-"); self.levelsPlist = [[NSMutableDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kLevelsPlist ofType:@"plist"]]; } if (!categoryLockStateArray) { NSLog(@"-Created categoryLockStateArray-"); categoryLockStateArray = [[NSMutableArray alloc] initWithCapacity:[[self.levelsPlist allKeys] count]]; for (int i=0; i<[[self.levelsPlist allKeys] count]; i++) { [categoryLockStateArray insertObject:[NSNumber numberWithBool:FALSE] atIndex:i]; } } // set the properties of the categories self.categoryNames = [self.levelsPlist allKeys]; NUM_CATEGORIES = [self.categoryNames count]; thisCatCopy = [[NSMutableDictionary alloc] initWithDictionary:[[levelsPlist objectForKey:[self.categoryNames objectAtIndex:pageControl.currentPage]] mutableCopy]]; NUM_FINISHED = [[thisCatCopy objectForKey:kNumLevelsBeatenInCategory] intValue]; }

    Read the article

  • Android - Retrieve all data from a SQLite table row

    - by Paul
    I have searched and cannot find an answer to my issue so i hope i am not completely barking up the wrong tree (so to speak). I am new to android and have started to create an app. My app on one screen creates and adds entries to a SQLite database using public class DatabaseHandler extends SQLiteOpenHelper and this all appears to work. I retrieve all the data and populate it into a grid, again this now works. My issue is I am unable to retrieve one complete line from the grid. I populate/display the grid with the following code. I have cut a lot out as the grid is made in stages, header, blank lines etc but the grid does display as I want. The id’s work as when I touch a line it displays its unique id. The onClick is right at the end and when I use getText() instead of getID() all it returns is the data in the labelDate. How do I retrieve all the labels as listed below? TextView labelDATE = new TextView(this); TextView labelCP = new TextView(this); TextView labelBG = new TextView(this); TextView labelQA = new TextView(this); TextView labelCN = new TextView(this); TextView labelKT = new TextView(this); TextView[] tvArray = {labelDATE, labelCP, labelBG, labelQA, labelCN, labelKT}; labelDATE.setText(re.getTime()); labelCP.setText(re.getCP()); labelBG.setText(re.getBG()); labelQA.setText(re.getQA()); labelCN.setText(re.getCN()); labelKT.setText(re.getKT()); for (TextView tv : tvArray) { tv.setTextColor(Color.WHITE); tv.setId(200+count); tr.setOnClickListener(this); tr.addView(tv); } //add this to the table row tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT)); public void onClick(View v) { if (v instanceof TableRow) { TableRow row = (TableRow) v; TextView child = (TextView) row.getChildAt(0); Toast toast = Toast.makeText(this, String.valueOf(child.getId()), Toast.LENGTH_SHORT); toast.show(); } } I can supply all the code for the grid creation if required. Thanks for any help.

    Read the article

  • using usort to re-arrange multi-dimension array

    - by Thomas Bennett
    I have a large array: [0] => stdClass Object ( [products] => Array ( [0] => stdClass Object ( [body_html] => bodyhtml [published_at] => 2012-12-16T23:59:18+00:00 [created_at] => 2012-12-16T11:30:24+00:00 [updated_at] => 2012-12-18T10:52:14+00:00 [vendor] => Name [product_type] => type ) [1] => stdClass Object ( [body_html] => bodyhtml [published_at] => 2012-12-16T23:59:18+00:00 [created_at] => 2012-12-16T10:30:24+00:00 [updated_at] => 2012-12-18T10:52:14+00:00 [vendor] => Name [product_type] => type ) ) ) and I need to arrange each of the products by the date they where created... I've tried and failed all kinds of usort, ksort, uksort techniques to try and get it to be in a specific order (chronological) but failed! any guidance would be most appreciated

    Read the article

  • Union - Same table, excluding previous results MySQL

    - by user82302124
    I'm trying to write a query that will: Run a query, give me (x) number of rows (limit 4) If that query didn't give me the 4 I need, run a second query limit 4-(x) and exclude the ids from the first query A third query that acts like the second I have this: (SELECT *, 1 as SORY_QUERY1 FROM xbamZ where state = 'Minnesota' and industry = 'Miscellaneous' and id != '229' limit 4) UNION (SELECT *, 2 FROM xbamZ where state = 'Minnesota' limit 2) UNION (SELECT *, 3 FROM xbamZ where industry = 'Miscellaneous' limit 1) How (or is?) do I do that? Am I close? This query gives me duplicates

    Read the article

  • PIG doesn't read my custom InputFormat

    - by Simon Guo
    I have a custom MyInputFormat that suppose to deal with record boundary problem for multi-lined inputs. But when I put the MyInputFormat into my UDF load function. As follow: public class EccUDFLogLoader extends LoadFunc { @Override public InputFormat getInputFormat() { System.out.println("I am in getInputFormat function"); return new MyInputFormat(); } } public class MyInputFormat extends TextInputFormat { public RecordReader createRecordReader(InputSplit inputSplit, JobConf jobConf) throws IOException { System.out.prinln("I am in createRecordReader"); //MyRecordReader suppose to handle record boundary return new MyRecordReader((FileSplit)inputSplit, jobConf); } } For each mapper, it print out I am in getInputFormat function but not I am in createRecordReader. I am wondering if anyone can provide a hint on how to hoop up my costome MyInputFormat to PIG's UDF loader? Much Thanks. I am using PIG on Amazon EMR.

    Read the article

  • rabbitmq-erlang-client, using rebar friendly pkg, works on dev env fails on rebar release

    - by lfurrea
    I am successfully using the rebar-friendly package of rabbitmq-erlang-client for a simple Hello World rebarized and OTP "compliant" app and things work fine on the dev environment. I am able to fire up an erl console and do my application:start(helloworld). and connect to the broker, open up a channel and communicate to queues. However, then I proceed to do rebar generate and it builds up the release just fine, but when I try to fire up from the self contained release package then things suddenly explode. I know rebar releases are known to be an obscure art, but I would like to know what are my options as far as deployment for an app using the rabbitmq-erlang-client. Below you will find the output of the console on the crash: =INFO REPORT==== 18-Dec-2012::16:41:35 === application: session_record exited: {{{badmatch, {error, {'EXIT', {undef, [{amqp_connection_sup,start_link, [{amqp_params_network,<<"guest">>,<<"guest">>,<<"/">>, "127.0.0.1",5672,0,0,0,infinity,none, [#Fun<amqp_auth_mechanisms.plain.3>, #Fun<amqp_auth_mechanisms.amqplain.3>], [],[]}], []}, {supervisor2,do_start_child_i,3, [{file,"src/supervisor2.erl"},{line,391}]}, {supervisor2,handle_call,3, [{file,"src/supervisor2.erl"},{line,413}]}, {gen_server,handle_msg,5, [{file,"gen_server.erl"},{line,588}]}, {proc_lib,init_p_do_apply,3, [{file,"proc_lib.erl"},{line,227}]}]}}}}, [{amqp_connection,start,1, [{file,"src/amqp_connection.erl"},{line,164}]}, {hello_qp,start_link,0,[{file,"src/hello_qp.erl"},{line,10}]}, {session_record_sup,init,1, [{file,"src/session_record_sup.erl"},{line,55}]}, {supervisor_bridge,init,1, [{file,"supervisor_bridge.erl"},{line,79}]}, {gen_server,init_it,6,[{file,"gen_server.erl"},{line,304}]}, {proc_lib,init_p_do_apply,3, [{file,"proc_lib.erl"},{line,227}]}]}, {session_record_app,start,[normal,[]]}} type: permanent

    Read the article

  • C# Sql Connection Best Practises 2013

    - by Pete Petersen
    With the new year approaching I'm drawing up a development plan for 2013. I won't bore you with the details but I started thinking about whether the way I do things is actually the 'correct' way. In particular how I'm interfacing with SQL. I create predominantly create WPF desktop applications and often some Silverlight Web Applications. All of my programs are very Data-Centric. When connecting to SQL from WPF I tend to use Stored Procedures stored on the server and fetch them using ADO.NET (e.g. SQLConnection(), .ExecuteQuery()). However with Silverlight I have a WCF service and use LINQ to SQL (and I'm using LINQ much more in WPF). My question is really is am I doing anything wrong in a sense that it's a little old fashioned? I've tried to look this up online but could find anything useful after about 2010 and of those half were 'LINQ is dead!' and the other 'Always use LINQ' Just want to make sure going forward I'm doing the right things the right way, or at least the advised way :). What principles are you using when connecting to SQL? Is it the same for WPF and Silverlight/WCF?

    Read the article

  • php download file slows

    - by hobbywebsite
    OK first off thanks for your time I wish I could give more than one point for this question. Problem: I have some music files on my site (.mp3) and I am using a php file to increment a database to count the number of downloads and to point to the file to download. For some reason this method starts at 350kb/s then slowly drops to 5kb/s which then the file says it will take 11hrs to complete. BUT if I go directly to the .mp3 file my browser brings up a player and then I can right click and "save as" which works fine complete download in 3mins. (Yes both during the same time for those that are thinking it's my connection or ISP and its not my server either.) So the only thing that I've been playing around with recently is the php.ini and the .htcaccess files. So without further ado, the php file, php.ini, and the .htcaccess: download.php <?php include("config.php"); include("opendb.php"); $filename = 'song_name'; $filedl = $filename . '.mp3'; $query = "UPDATE songs SET song_download=song_download+1 WHER song_linkname='$filename'"; mysql_query($query); header('Content-Disposition: attachment; filename='.basename($filedl)); header('Content-type: audio/mp3'); header('Content-Length: ' . filesize($filedl)); readfile('/music/' . $filename . '/' . $filedl); include("closedb.php"); ?> php.ini register_globals = off allow_url_fopen = off expose_php = Off max_input_time = 60 variables_order = "EGPCS" extension_dir = ./ upload_tmp_dir = /tmp precision = 12 SMTP = relay-hosting.secureserver.net url_rewriter.tags = "a=href,area=href,frame=src,input=src,form=,fieldset=" ; Defines the default timezone used by the date functions date.timezone = "America/Los_Angeles" .htaccess Options +FollowSymLinks RewriteEngine on RewriteCond %{HTTP_HOST} !^(www.MindCollar.com)?$ [NC] RewriteRule (.*) http://www.MindCollar.com/$1 [R=301,L] <IfModule mod_rewrite.c> RewriteEngine On ErrorDocument 404 /errors/404.php ErrorDocument 403 /errors/403.php ErrorDocument 500 /errors/500.php </IfModule> Options -Indexes Options +FollowSymlinks <Files .htaccess> deny from all </Files> thanks for you time

    Read the article

  • Designing a database file format

    - by RoliSoft
    I would like to design my own database engine for educational purposes, for the time being. Designing a binary file format is not hard nor the question, I've done it in the past, but while designing a database file format, I have come across a very important question: How to handle the deletion of an item? So far, I've thought of the following two options: Each item will have a "deleted" bit which is set to 1 upon deletion. Pro: relatively fast. Con: potentially sensitive data will remain in the file. 0x00 out the whole item upon deletion. Pro: potentially sensitive data will be removed from the file. Con: relatively slow. Recreating the whole database. Pro: no empty blocks which makes the follow-up question void. Con: it's a really good idea to overwrite the whole 4 GB database file because a user corrected a typo. I will sell this method to Twitter ASAP! Now let's say you already have a few empty blocks in your database (deleted items). The follow-up question is how to handle the insertion of a new item? Append the item to the end of the file. Pro: fastest possible. Con: file will get huge because of all the empty blocks that remain because deleted items aren't actually deleted. Search for an empty block exactly the size of the one you're inserting. Pro: may get rid of some blocks. Con: you may end up scanning the whole file at each insert only to find out it's very unlikely to come across a perfectly fitting empty block. Find the first empty block which is equal or larger than the item you're inserting. Pro: you probably won't end up scanning the whole file, as you will find an empty block somewhere mid-way; this will keep the file size relatively low. Con: there will still be lots of leftover 0x00 bytes at the end of items which were inserted into bigger empty blocks than they are. Rigth now, I think the first deletion method and the last insertion method are probably the "best" mix, but they would still have their own small issues. Alternatively, the first insertion method and scheduled full database recreation. (Probably not a good idea when working with really large databases. Also, each small update in that method will clone the whole item to the end of the file, thus accelerating file growth at a potentially insane rate.) Unless there is a way of deleting/inserting blocks from/to the middle of the file in a file-system approved way, what's the best way to do this? More importantly, how do databases currently used in production usually handle this?

    Read the article

  • Fade out/in sperate divs with button click

    - by user1914298
    I saw a flash website and was curious to now if this is something possible to build using Jquery, obviously not the entire thing. I was more looking to fade out div1 and div2 with a button click. This is the example site: www.justinfarrellyconstruction.com Example: If i come to the homepage and click the portfolio button the Gallery Div will fade out then fade in another image. At the same time the Text div will fade out its content and load the portfolio text. My apologies if this does not make sense, this is all quite new to me and im trying got learn.

    Read the article

  • Getting 404 in Android app while trying to get xml from localhost

    - by Patrick
    This must be something really stupid, trying to solve this issue for a couple of days now and it's really not working. I searched everywhere and there probably is someone with the same problem, but I can't seem to find it. I'm working on an Android app and this app pulls some xml from a website. Since this website is down a lot, I decided to save it and run it locally. Now what I did; - I downloaded the kWs app for hosting the downloaded xml file - I put the file in the right directory and could access it through the mobile browser, but not with my app (same code as I used with pulling it from some other website, not hosted by me, only difference was the URL obviously) So I tried to host it on my PC and access it with my app from there. Again the same results, the mobile browsers had no problem finding it, but the app kept saying 404 Not Found: "The requested URL /test.xml&parama=Someone&paramb= was not found on this server." Note: Don't mind the 2 parameters I am sending, I needed that to get the right stuff from the website that wasn't hosted by me. My code: public String getStuff(String name){ String URL = "http://10.0.0.8/test.xml"; ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(2); params.add(new BasicNameValuePair("parama", name)); params.add(new BasicNameValuePair("paramb", "")); APIRequest request = new APIRequest(URL, params); try { RequestXML rxml = new RequestXML(); AsyncTask<APIRequest, Void, String> a = rxml.execute(request); ... } catch(Exception e) { e.printStackTrace(); } return null; } That should be working correctly. Now the RequestXML class part: class RequestXML extends AsyncTask<APIRequest, Void, String>{ @Override protected String doInBackground(APIRequest... uri) { HttpClient httpclient = new DefaultHttpClient(); String completeUrl = uri[0].url; // ... Add parameters to URL ... HttpGet request = null; try { request = new HttpGet(new URI(completeUrl)); } catch (URISyntaxException e1) { e1.printStackTrace(); } HttpResponse response; String responseString = ""; try { response = httpclient.execute(request); StatusLine statusLine = response.getStatusLine(); if(statusLine.getStatusCode() == HttpStatus.SC_OK){ // .. It crashes here, because statusLine.getStatusCode() returns a 404 instead of a 200. The xml is just plain xml, nothing special about it. I changed the contents of the .htaccess file into "ALLOW FROM ALL" (works, cause the browser on my mobile device can access it and shows the correct xml). I am running Android 4.0.4 and I am using the default browser AND chrome on my mobile device. I am using MoWeS to host the website on my PC. Any help would be appreciated and if you need to know anything before you can find an answer to this problem, I'll be more than happy to give you that info. Thank you for you time! Cheers.

    Read the article

  • Evaluation of (de)reference operators

    - by Micha
    I have an (uncommented...) source file which I'm trying to understand. static const Map *gCurMap; static std::vector<Map> mapVec; then auto e = mapVec.end(); auto i = mapVec.begin(); while(i!=e) { // ... const Map *map = gCurMap = &(*(i++)); // ... } I don't understand what &(*(i++)) does. It does not compile when just using i++, but to me it looks the same, because I'm "incrementing" i, then I'm requesting the value at the given address and then I'm requesting the address of this value?!

    Read the article

  • 500 error on function call in Codeigniter

    - by Ilia Lev
    I am using just installed CI 2.1.3 Following phpacademy tutorial I wrote in the routes.php: $route['default_controller'] = "site"; (instead of: $route['default_controller'] = "welcome";) and in controllers/site.php: <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Site extends CI_Controller { public function index() { echo "default function started.<br/>"; } public function hello(){ echo "hello function started.<br/>"; } } After uploading it to the server and going to the [www.mydomain.ext] it works ok (writes: "default function started.") BUT if I add 'this-hello();' to the index() function it throws a 500 error. Why does it happen and how can I resolve this? Thank you in advance.

    Read the article

  • Unity Framework constructor parameters in MVC

    - by ubersteve
    I have an ASP.NET MVC3 site that I want to be able to use different types of email service, depending on how busy the site is. Consider the following: public interface IEmailService { void SendEmail(MailMessage mailMessage); } public class LocalEmailService : IEmailService { public LocalEmailService() { // no setup required } public void SendEmail(MailMessage mailMessage) { // send email via local smtp server, write it to a text file, whatever } } public class BetterEmailService : IEmailService { public BetterEmailService (string smtpServer, string portNumber, string username, string password) { // initialize the object with the parameters } public void SendEmail(MailMessage mailMessage) { //actually send the email } } Whilst the site is in development, all of my controllers will send emails via the LocalEmailService; when the site is in production, they will use the BetterEmailService. My question is twofold: 1) How exactly do I pass the BetterEmailService constructor parameters? Is it something like this (from ~/Bootstrapper.cs): private static IUnityContainer BuildUnityContainer() { var container = new UnityContainer(); container.RegisterType<IEmailService, BetterEmailService>("server name", "port", "username", "password"); return container; } 2) Is there a better way of doing that - i.e. putting those keys in the web.config or another configuration file so that the site would not need to be recompiled to switch which email service it was using? Many thanks!

    Read the article

  • How to implement message passing in GNUradio?

    - by xuandl
    I need to implement message passing, my idea is to make some sort of message source (I inherit from public gr_sync_block) that works as a controller for another block (it has to send a message each 6 minutes). I read that is necessary to inherit from gnuradio::block -and by the way, installing grextras is mandatory-. In the .h file I added the #include and inherited from block"class JDFM_API jdfm_control : public gr_sync_block, public gnuradio::block". I know that I have redefine some things like the gnuradio::block constructor but I dont know what msg_signature is, I also don't get the relation between block's parameters and work parameter, the last thing that I am not sure is if I still can use gnuradio-companion if I create a block like this. I haven't been able to find a simple example of messages implementation. If anyone can guide me or show me an example, it would be awesome. Thanks in advance.

    Read the article

  • CrystalDecisions.Web reference version changes suddenly when run the webapp

    - by Somebody
    I'm breaking my head with this issue, I have a webapp that has a report using crystal report, in the development pc it works fine, but when copy the same project to another pc, when I load the project (VS 2003) the following msg appears: One or more projects in solution need to be updated to use Crystal Reports XI Release 2. If you choose "Yes", the update will be applied permanently... I choose "Yes" and after that I can see that CrystalDecisions.Web reference has the correct version, and location according to the develpment machine, in this case: 11.5.3300.0. But when run the webapp, I can see when the version and path suddenly changes to: 11.0.3300.0. And when trying to see the report the following error appears: Parser Error Message: The base class includes the field 'CrystalReportViewer1', but its type (CrystalDecisions.Web.CrystalReportViewer) is not compatible with the type of control (CrystalDecisions.Web.CrystalReportViewer). the asp.net has the following: <%@ Register TagPrefix="cr" Namespace="CrystalDecisions.Web" Assembly="CrystalDecisions.Web, Version=11.5.3300.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" %> How is this possible? what's happening here? EDIT This is what I did: the wrong version (11.0.3300.0) was located at: C:\Program Files\Common Files\Business Objects\3.0\managed and the right version (11.5.3300.0) is located at: C:\Program Files\Business Objects\Common\3.5\managed So I just deleted the files of the wrong solution, and I made it work in my new computer, no more errors when running the webapp, the report shows fine. But when try to do the same thing in production server, a different error came out, now an exception: This report could not be loaded due to the following issue: The type initializer for 'CrystalDecisions.CristalReports.Engine.ReportDocument' threw an exception. Any idea what could be causing this error now? Here is the code: Try Dim cr As New ReportDocument cr.Load(strpath) cr.SetDatabaseLogon("usring", "pwding") Select Case rt Case 1 cr.SummaryInfo.ReportTitle = "RMA Ticket" Case 2 cr.SummaryInfo.ReportTitle = "Service Ticket" End Select 'cr.SummaryInfo.ReportTitle = tt cr.SetParameterValue("TicketNo", tn) 'cr.SummaryInfo.ReportComments = comment CrystalReportViewer1.PrintMode = CrystalDecisions.Web.PrintMode.ActiveX CrystalReportViewer1.ReportSource = cr CrystalReportViewer1.ShowFirstPage() 'cr.Close() 'cr.Dispose() Catch ex As Exception MsgBox1.alert("This report could not be loaded due to the following issue: " & ex.Message) End Try

    Read the article

  • SwingWorker exceptions lost even when using wrapper classes

    - by Ti Strga
    I've been struggling with the usability problem of SwingWorker eating any exceptions thrown in the background task, for example, described on this SO thread. That thread gives a nice description of the problem, but doesn't discuss recovering the original exception. The applet I've been handed needs to propagate the exception upwards. But I haven't been able to even catch it. I'm using the SimpleSwingWorker wrapper class from this blog entry specifically to try and address this issue. It's a fairly small class but I'll repost it at the end here just for reference. The calling code looks broadly like try { // lots of code here to prepare data, finishing with SpecialDataHelper helper = new SpecialDataHelper(...stuff...); helper.execute(); } catch (Throwable e) { // used "Throwable" here in desperation to try and get // anything at all to match, including unchecked exceptions // // no luck, this code is never ever used :-( } The wrappers: class SpecialDataHelper extends SimpleSwingWorker { public SpecialDataHelper (SpecialData sd) { this.stuff = etc etc etc; } public Void doInBackground() throws Exception { OurCodeThatThrowsACheckedException(this.stuff); return null; } protected void done() { // called only when successful // never reached if there's an error } } The feature of SimpleSwingWorker is that the actual SwingWorker's done()/get() methods are automatically called. This, in theory, rethrows any exceptions that happened in the background. In practice, nothing is ever caught, and I don't even know why. The SimpleSwingWorker class, for reference, and with nothing elided for brevity: import java.util.concurrent.ExecutionException; import javax.swing.SwingWorker; /** * A drop-in replacement for SwingWorker<Void,Void> but will not silently * swallow exceptions during background execution. * * Taken from http://jonathangiles.net/blog/?p=341 with thanks. */ public abstract class SimpleSwingWorker { private final SwingWorker<Void,Void> worker = new SwingWorker<Void,Void>() { @Override protected Void doInBackground() throws Exception { SimpleSwingWorker.this.doInBackground(); return null; } @Override protected void done() { // Exceptions are lost unless get() is called on the // originating thread. We do so here. try { get(); } catch (final InterruptedException ex) { throw new RuntimeException(ex); } catch (final ExecutionException ex) { throw new RuntimeException(ex.getCause()); } SimpleSwingWorker.this.done(); } }; public SimpleSwingWorker() {} protected abstract Void doInBackground() throws Exception; protected abstract void done(); public void execute() { worker.execute(); } }

    Read the article

  • java RMI newbie-- some basic questions about SSL and auth/.rate limiting an RMI service

    - by Arvind
    I am trying to work to secure a java based RMI service using SSL. I have some basic questions about the capabilities of using SSL. Specifically, from what I understand, the client and server connecting via SSL will need to have appropriate credential certificates in both client and server, for a client to be granted access to the server. Am I correct in my understanding? Also, what I want to know is, can a person who is already using my RMI service and has access to a client machine , make a copy of the certificate in the client machine to other client machines-- and then invoke my RMI service from those other machines as well? How do I prevent such a situation from occurring? I mean, in a REST API you can use OAuth authentication, can we have some kind of authentication in an RMI Service? Also, can I possibly limit usage of the RMI service? For eg, a specific client may be allowed to make only 5000 calls per day to my RMI service, and if he makes more calls the calls occurring after the 5000 calls limit are all denied? How do I do such rate limiting and/or authentication for my RMI Service?

    Read the article

  • Linq query joining with a subquery

    - by Alan Fisher
    I am trying to reproduce a SQL query using a LINQ to Entities query. The following SQL works fine, I just don't see how to do it in LINQ. I have tried for a few hours today but I'm just missing something. SELECT h.ReqID, rs.RoutingSection FROM ReqHeader h JOIN ReqRoutings rr ON rr.ReqRoutingID = (SELECT TOP 1 r1.ReqRoutingID FROM ReqRoutings r1 WHERE r1.ReqID = h.ReqID ORDER BY r1.ReqRoutingID desc) JOIN ReqRoutingSections rs ON rs.RoutingSectionID = rr.RoutingSectionID Edit*** Here is my table scema- Requisitions: ReqID PK string ReqDate datetime etc... ReqRoutings: ID PK int ReqID FK RoutingSection FK int RoutingDate ReqRoutingSections: Id PK int RoutingSection string The idea is that each Requisition can be routed many times, for my query I need the last RoutingSection to be returned along with the Requisition info. Sample data: Requisitions: - 1 record ReqID 123456 ReqDate '12/1/2012' ReqRoutings: -- 3 records id 1 ReqID 123456 RoutingSection 3 RoutingDate '12/2/2012' id 2 ReqID 123456 RoutingSection 2 RoutingDate '12/3/2012' id 3 ReqID 123456 RoutingSection 4 RoutingDate '12/4/2012' ReqRoutingSections: -- 3 records id 2 Supervision id 3 Safety id 4 Qaulity Control The results of the query would be ReqID = '123456' RoutingSection = 'QualityControl' -- Last RoutingSection requisition was routed to

    Read the article

  • Amazon EC2 EBS automatic backup one-liner works manually but not from cron

    - by dan
    I am trying to implement an automatic backup system for my EBS on Amazon AWS. When I run this command as ec2-user: /opt/aws/bin/ec2-create-snapshot --region us-east-1 -K /home/ec2-user/pk.pem -C /home/ec2-user/cert.pem -d "vol-******** snapshot" vol-******** everything works fine. But if I add this line into /etc/crontab and restart the crond service: 15 12 * * * ec2-user /opt/aws/bin/ec2-create-snapshot --region us-east-1 -K /home/ec2-user/pk.pem -C /home/ec2-user/cert.pem -d "vol-******** snapshot" vol-******** that doesn't work. I checked var/log/cron and there is this line, therefore the command gets executed: Dec 13 12:15:01 ip-10-204-111-94 CROND[4201]: (ec2-user) CMD (/opt/aws/bin/ec2-create-snapshot --region us-east-1 -K /home/ec2-user/pk.pem -C /home/ec2-user/cert.pem -d "vol-******** snapshot" vol-******** ) Can you please help me to troubleshoot the problem? I guess is some environment problem - maybe the lack of some variable. If that's the case I don't know what to do about it. Thanks.

    Read the article

  • How to reduce iOS AVPlayer start delay

    - by Bernt Habermeier
    Note, for the below question: All assets are local on the device -- no network streaming is taking place. The videos contain audio tracks. I'm working on an iOS application that requires playing video files with minimum delay to start the video clip in question. Unfortunately we do not know what specific video clip is next until we actually need to start it up. Specifically: When one video clip is playing, we will know what the next set of (roughly) 10 video clips are, but we don't know which one exactly, until it comes time to 'immediately' play the next clip. What I've done to look at actual start delays is to call addBoundaryTimeObserverForTimes on the video player, with a time period of one millisecond to see when the video actually started to play, and I take the difference of that time stamp with the first place in the code that indicates which asset to start playing. From what I've seen thus-far, I have found that using the combination of AVAsset loading, and then creating an AVPlayerItem from that once it's ready, and then waiting for AVPlayerStatusReadyToPlay before I call play, tends to take between 1 and 3 seconds to start the clip. I've since switched to what I think is roughly equivalent: calling [AVPlayerItem playerItemWithURL:] and waiting for AVPlayerItemStatusReadyToPlay to play. Roughly same performance. One thing I'm observing is that the first AVPlayer item load is slower than the rest. Seems one idea is to pre-flight the AVPlayer with a short / empty asset before trying to play the first video might be of good general practice. [http://stackoverflow.com/questions/900461/slow-start-for-avaudioplayer-the-first-time-a-sound-is-played] I'd love to get the video start times down as much as possible, and have some ideas of things to experiment with, but would like some guidance from anyone that might be able to help. Update: idea 7, below, as-implemented yields switching times of around 500 ms. This is an improvement, but it it'd be nice to get this even faster. Idea 1: Use N AVPlayers (won't work) Using ~ 10 AVPPlayer objects and start-and-pause all ~ 10 clips, and once we know which one we really need, switch to, and un-pause the correct AVPlayer, and start all over again for the next cycle. I don't think this works, because I've read there is roughly a limit of 4 active AVPlayer's in iOS. There was someone asking about this on StackOverflow here, and found out about the 4 AVPlayer limit: fast-switching-between-videos-using-avfoundation Idea 2: Use AVQueuePlayer (won't work) I don't believe that shoving 10 AVPlayerItems into an AVQueuePlayer would pre-load them all for seamless start. AVQueuePlayer is a queue, and I think it really only makes the next video in the queue ready for immediate playback. I don't know which one out of ~10 videos we do want to play back, until it's time to start that one. ios-avplayer-video-preloading Idea 3: Load, Play, and retain AVPlayerItems in background (not 100% sure yet -- but not looking good) I'm looking at if there is any benefit to load and play the first second of each video clip in the background (suppress video and audio output), and keep a reference to each AVPlayerItem, and when we know which item needs to be played for real, swap that one in, and swap the background AVPlayer with the active one. Rinse and Repeat. The theory would be that recently played AVPlayer/AVPlayerItem's may still hold some prepared resources which would make subsequent playback faster. So far, I have not seen benefits from this, but I might not have the AVPlayerLayer setup correctly for the background. I doubt this will really improve things from what I've seen. Idea 4: Use a different file format -- maybe one that is faster to load? I'm currently using .m4v's (video-MPEG4) H.264 format. I have not played around with other formats, but it may well be that some formats are faster to decode / get ready than others. Possible still using video-MPEG4 but with a different codec, or maybe quicktime? Maybe a lossless video format where decoding / setup is faster? Idea 5: Combination of lossless video format + AVQueuePlayer If there is a video format that is fast to load, but maybe where the file size is insane, one idea might be to pre-prepare the first 10 seconds of each video clip with a version that is boated but faster to load, but back that up with an asset that is encoded in H.264. Use an AVQueuePlayer, and add the first 10 seconds in the uncompressed file format, and follow that up with one that is in H.264 which gets up to 10 seconds of prepare/preload time. So I'd get 'the best' of both worlds: fast start times, but also benefits from a more compact format. Idea 6: Use a non-standard AVPlayer / write my own / use someone else's Given my needs, maybe I can't use AVPlayer, but have to resort to AVAssetReader, and decode the first few seconds (possibly write raw file to disk), and when it comes to playback, make use of the raw format to play it back fast. Seems like a huge project to me, and if I go about it in a naive way, it's unclear / unlikely to even work better. Each decoded and uncompressed video frame is 2.25 MB. Naively speaking -- if we go with ~ 30 fps for the video, I'd end up with ~60 MB/s read-from-disk requirement, which is probably impossible / pushing it. Obviously we'd have to do some level of image compression (perhaps native openGL/es compression formats via PVRTC)... but that's kind crazy. Maybe there is a library out there that I can use? Idea 7: Combine everything into a single movie asset, and seekToTime One idea that might be easier than some of the above, is to combine everything into a single movie, and use seekToTime. The thing is that we'd be jumping all around the place. Essentially random access into the movie. I think this may actually work out okay: avplayer-movie-playing-lag-in-ios5 Which approach do you think would be best? So far, I've not made that much progress in terms of reducing the lag.

    Read the article

  • Changing printer preferences in Windows programmatically

    - by Andrew Alexander
    I've written a script that installs several printers for a new user. I want to change the settings on some of these so that they can print on both sides of the page. I BELIEVE this involves modifying an attribute with printui, however it might need VB script or possibly another .NET language (I'd either use VB, C# or IronPython). I can add a comment to a given printer, but how do I select preferences and modify them? Pseudocode would look like this: printui.exe /n printername /??? [how to change quality desired] OR calls to the relevant Windows API.

    Read the article

  • Facebook PHP SDK - will not logout properly

    - by garethdn
    I've been searching for hours for the solution to this problem but can't find one that works for me. When i click "Logout" on my site the user information is still visible and the logout button is still displayed. Here is the code: require 'facebook-php-sdk/src/facebook.php'; $facebook = new Facebook(array( 'appId' => 'xxxx', 'secret' => 'xxxx', )); // Get User ID $user = $facebook->getUser(); var_dump($user); if ($user) { try { // Proceed knowing you have a logged in user who's authenticated. $user_profile = $facebook->api('/me'); } catch (FacebookApiException $e) { error_log($e); $user = null; } } // Login or logout url will be needed depending on current user state. if ($_GET['logout'] == "yes") { setcookie('fbs_'.$facebook->getAppId(), '', time()-100, '/', 'http://gno.....ment/index.php'); session_destroy(); header("Location: ".$_SERVER['PHP_SELF'].""); } if ($user_profile) { $logoutUrl = $facebook->getLogoutUrl; } else { $loginUrl = $facebook->getLoginUrl(array('scope' => 'email,publish_stream,user_status', 'canvas' => 1, 'fbconnect' => 0, 'redirect_uri' => 'http://gno.....ment/index.php')); } ..... ..... <?php if ($user): ?> <h3>You</h3> <img src="https://graph.facebook.com/<?php echo $user; ?>/picture"> <h3>Your User Object (/me)</h3> <pre><?php print_r($user_profile); ?></pre> <?php else: ?> <strong><em>You are not Connected.</em></strong> <?php endif ?> <?php if ($user): ?> <a href="<?php echo $logoutUrl; ?>">Logout of FB</a> <?php else: ?> <div> Login using OAuth 2.0 handled by the PHP SDK: <a href="<?php echo $loginUrl; ?>">Login with Facebook</a> </div> <?php endif ?> It seems that if ($_GET['logout'] == "yes") might be the answer for me but i can't get it working. I don't know where logout is gotten from or where it is defined? This seems to be a common issue but i can't figure it out. I'd really appreciate some help.

    Read the article

  • iPhone NSDateFormatter Timezone Conversion

    - by MobileDeveloperTips
    I am trying to create a formatter that will convert the date format shown to an NSDate object: NSString *dateStr = @"2010-06-21T19:00:00-05:00"; NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZ"]; NSDate *date = [dateFormat dateFromString:dateStr]; The issue is the timezone -05:00, which is not parsed properly with the format above. Any suggestions?

    Read the article

  • /etc/init.d/libvirtd start fails but service libvirtd start works. Why?

    - by Gregg
    CentOS 6.3, running as root (Shush). Can you please tell me why I would get initialisation failures from the init scripts but the service command works a treat? There was nothing in /var/log/messages or /var/log/libvirt/* all I have it the Terminal output: /etc/init.d/libvirtd start Starting libvirtd daemon: libvirtd: initialization failed [FAILED] I changed the libvirtd logging level to 1, the highest, but saw nothing in messages after another failure.

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17  | Next Page >