Daily Archives

Articles indexed Friday April 16 2010

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

  • Matching sentences with regex in Java

    - by Gary
    Hi, I'm using the Scanner class in java to go through a a text file and extract each sentence. I'm using the setDelimiter method on my Scanner to the regex: Pattern.compile("[\\w]*[\\.|?|!][\\s]") This currently seems to work, but it leaves the whitespace at the end of the sentence. Is there an easy way to match the whitespace at the end but not include it in the result? I realize this is probably an easy question but I've never used regex before so go easy :)

    Read the article

  • PHP Special Characters Test

    - by pws5068
    What's an efficient way of checking if a username contains a number of special characters that I define. Examples: % # ^ . ! @ & ( ) + / " ? ` ~ < { } [ ] | = - ; I need to detect them and return a boolean, not just strip them out. Probably a super easy question but I need a better way of doing this than a huge list of conditionals or a sloppy loop.

    Read the article

  • Class member functions instantiated by traits [policies, actually]

    - by Jive Dadson
    I am reluctant to say I can't figure this out, but I can't figure this out. I've googled and searched Stack Overflow, and come up empty. The abstract, and possibly overly vague form of the question is, how can I use the traits-pattern to instantiate member functions? [Update: I used the wrong term here. It should be "policies" rather than "traits." Traits describe existing classes. Policies prescribe synthetic classes.] The question came up while modernizing a set of multivariate function optimizers that I wrote more than 10 years ago. The optimizers all operate by selecting a straight-line path through the parameter space away from the current best point (the "update"), then finding a better point on that line (the "line search"), then testing for the "done" condition, and if not done, iterating. There are different methods for doing the update, the line-search, and conceivably for the done test, and other things. Mix and match. Different update formulae require different state-variable data. For example, the LMQN update requires a vector, and the BFGS update requires a matrix. If evaluating gradients is cheap, the line-search should do so. If not, it should use function evaluations only. Some methods require more accurate line-searches than others. Those are just some examples. The original version instantiates several of the combinations by means of virtual functions. Some traits are selected by setting mode bits that are tested at runtime. Yuck. It would be trivial to define the traits with #define's and the member functions with #ifdef's and macros. But that's so twenty years ago. It bugs me that I cannot figure out a whiz-bang modern way. If there were only one trait that varied, I could use the curiously recurring template pattern. But I see no way to extend that to arbitrary combinations of traits. I tried doing it using boost::enable_if, etc.. The specialized state information was easy. I managed to get the functions done, but only by resorting to non-friend external functions that have the this-pointer as a parameter. I never even figured out how to make the functions friends, much less member functions. The compiler (VC++ 2008) always complained that things didn't match. I would yell, "SFINAE, you moron!" but the moron is probably me. Perhaps tag-dispatch is the key. I haven't gotten very deeply into that. Surely it's possible, right? If so, what is best practice? UPDATE: Here's another try at explaining it. I want the user to be able to fill out an order (manifest) for a custom optimizer, something like ordering off of a Chinese menu - one from column A, one from column B, etc.. Waiter, from column A (updaters), I'll have the BFGS update with Cholesky-decompositon sauce. From column B (line-searchers), I'll have the cubic interpolation line-search with an eta of 0.4 and a rho of 1e-4, please. Etc... UPDATE: Okay, okay. Here's the playing-around that I've done. I offer it reluctantly, because I suspect it's a completely wrong-headed approach. It runs okay under vc++ 2008. #include <boost/utility.hpp> #include <boost/type_traits/integral_constant.hpp> namespace dj { struct CBFGS { void bar() {printf("CBFGS::bar %d\n", data);} CBFGS(): data(1234){} int data; }; template<class T> struct is_CBFGS: boost::false_type{}; template<> struct is_CBFGS<CBFGS>: boost::true_type{}; struct LMQN {LMQN(): data(54.321){} void bar() {printf("LMQN::bar %lf\n", data);} double data; }; template<class T> struct is_LMQN: boost::false_type{}; template<> struct is_LMQN<LMQN> : boost::true_type{}; // "Order form" struct default_optimizer_traits { typedef CBFGS update_type; // Selection from column A - updaters }; template<class traits> class Optimizer; template<class traits> void foo(typename boost::enable_if<is_LMQN<typename traits::update_type>, Optimizer<traits> >::type& self) { printf(" LMQN %lf\n", self.data); } template<class traits> void foo(typename boost::enable_if<is_CBFGS<typename traits::update_type>, Optimizer<traits> >::type& self) { printf("CBFGS %d\n", self.data); } template<class traits = default_optimizer_traits> class Optimizer{ friend typename traits::update_type; //friend void dj::foo<traits>(typename Optimizer<traits> & self); // How? public: //void foo(void); // How??? void foo() { dj::foo<traits>(*this); } void bar() { data.bar(); } //protected: // How? typedef typename traits::update_type update_type; update_type data; }; } // namespace dj int main() { dj::Optimizer<> opt; opt.foo(); opt.bar(); std::getchar(); return 0; }

    Read the article

  • Problems with Merb on Snow Leopard

    - by hamhoagie
    I've recently started looking at Merb, for use with some small projects around the office. I'm trying to set up my first project following the docs, and am encountering an exception such as: foo:beta user$ merb Merb root at: /Users/user/code/merb/beta Loading init file from ./config/init.rb Loading ./config/environments/development.rb ~ Connecting to database... ~ Loaded slice 'MerbAuthSlicePassword' ... ~ Parent pid: 39794 ~ Compiling routes... ~ Activating slice 'MerbAuthSlicePassword' ... ~ ~ FATAL: Mongrel is not installed, but you are trying to use it. You need to either install mongrel or a different Ruby web server, like thin. I have installed Mongrel from gem as well as from MacPorts, and am confused by this exception. Significant stats: ruby 1.8.7 (2010-01-10 patchlevel 249) [i686-darwin10] From my installed gems: merb (1.1.0) merb-action-args (1.1.0) merb-assets (1.1.0) merb-auth (1.1.0) merb-auth-core (1.1.0) merb-auth-more (1.1.0) merb-auth-slice-password (1.1.0) merb-cache (1.1.0) merb-core (1.1.0) merb-exceptions (1.1.0) merb-gen (1.1.0) merb-haml (1.1.0) merb-helpers (1.1.0) merb-mailer (1.1.0) merb-param-protection (1.1.0) merb-slices (1.1.0) merb_datamapper (1.1.0) mongrel (1.1.5) Merb documentation is non-existent, so I find myself stuck. Thanks in advance.

    Read the article

  • Schedule multiple events with NSTimer?

    - by AWright4911
    I have a schedule cache stored in a pList. For the example below, I have a schedule time of April 13, 2010 2:00PM and Aril 13, 2010 2:05PM. How can I add both of these to a queue to fire on their own? item 0 -Hour --14 -Minute --00 -Month --04 -Day --13 -Year --2010 item 1 -Hour --14 -Minute --05 -Month --04 -Day --13 -Year --2010 this is how I am attempting to schedule multiple events to fire at specific date / time. -(void) buildScheduleCache { MPNotifyViewController *notifier = [MPNotifyViewController alloc] ; [notifier setStatusText:@"Rebuilding schedule cache, this will only take a moment."]; [notifier show]; NSCalendarDate *now = [NSCalendarDate calendarDate]; NSFileManager *manager = [[NSFileManager defaultManager] autorelease]; path = @"/var/mobile/Library/MobileProfiles/Custom Profiles"; theProfiles = [manager directoryContentsAtPath:path]; myPrimaryinfo = [[NSMutableArray arrayWithCapacity:6] retain]; keys = [NSArray arrayWithObjects:@"Profile",@"MPSYear",@"MPSMonth",@"MPSDay",@"MPSHour",@"MPSMinute",nil]; for (NSString *profile in theProfiles) { plistDict = [[[NSMutableDictionary alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",path,profile]] autorelease]; [myPrimaryinfo addObject:[NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: [NSString stringWithFormat:@"%@",profile], [NSString stringWithFormat:@"%@",[plistDict objectForKey:@"MPSYear"]], [NSString stringWithFormat:@"%@",[plistDict objectForKey:@"MPSMonth"]], [NSString stringWithFormat:@"%@",[plistDict objectForKey:@"MPSDay"]], [NSString stringWithFormat:@"%@",[plistDict objectForKey:@"MPSHour"]], [NSString stringWithFormat:@"%@",[plistDict objectForKey:@"MPSMinute"]], nil]forKeys:keys]]; profileSched = [NSCalendarDate dateWithYear:[plistDict objectForKey:@"MPSYear"] month:[plistDict objectForKey:@"MPSMonth"] day:[plistDict objectForKey:@"MPSDay"] hour:[plistDict objectForKey:@"MPSHour"] minute:[plistDict objectForKey:@"MPSMinute"] second:01 timeZone:[now timeZone]]; [self rescheduleTimer]; } NSString *testPath = @"/var/mobile/Library/MobileProfiles/Schedules.plist"; [myPrimaryinfo writeToFile:testPath atomically:YES]; } -(void) rescheduleTimer { timer = [[NSTimer alloc] initWithFireDate:profileSched interval:0.0f target:self selector:@selector(theFireEvent) userInfo:nil repeats:YES]; NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; [runLoop addTimer:timer forMode:NSDefaultRunLoopMode]; }

    Read the article

  • Could a truly random number be generated using pings to psuedo-randomly selected IP addresses?

    - by _ande_turner_
    The question posed came about during a 2nd Year Comp Science lecture while discussing the impossibility of generating numbers in a deterministic computational device. This was the only suggestion which didn't depend on non-commodity-class hardware. Subsequently nobody would put their reputation on the line to argue definitively for or against it. Anyone care to make a stand for or against. If so, how about a mention as to a possible implementation?

    Read the article

  • Setting an individual DataGridView Cell

    - by user315493
    Hi, In a DataGridView, it is possible to set an individual DataGridViewCell like this: dataGridView.Item(columnIndex, rowIndex) = New DataGridViewTextBoxCell. However, is the new DataGridViewCell is set before his owning column become visible, it seems that the individual cell will be replaced (or marked?) by the column default cell. Is there a way to fix this? Regards, Simon

    Read the article

  • Darkening a UIView

    - by igul222
    I'd like to "darken" a UIView by a certain amount. Right now, I'm doing the darkening like this: UIView *overlay = [[UIView alloc] initWithFrame:mainView.bounds]; overlay.backgroundColor = [UIColor blackColor]; overlay.alpha = 0.5f; [mainView addSubview:overlay]; Unfortunately, this also adds a semi-transparent black overlay to parts of mainView that are transparent. Is there any way to only darken the non-transparent sections?

    Read the article

  • Load richtextbox from memorystream. WPF/VB>NET

    - by Peter
    Hi, I have some trouble with loading a richtextbox from a memorystream. I have some data in a database table stored as a byte array, I convert it to a string and load it into a memorystream and then I want to load that memory stream in the richtextbox. The application breaks on Dim tr As New TextRange(rtbTemplate.Document.ContentStart, rtbTemplate.Document.ContentEnd) though. Code for getting the data from the database Dim TemplateData As Byte() = TemplateDataTableInstance.Rows(0).Item("TemplateData") Dim strTemplateData As String Dim enc As New System.Text.UTF8Encoding() strTemplateData = enc.GetString(TemplateData) ' I put a messagebox here to check if I get the data I want and I do Now, how do I sort out the rest? I have Dim strDataFormat As String = DataFormats.Rtf Using ms As New MemoryStream(strTemplateData) Dim tr As New TextRange(rtbTemplate.Document.ContentStart, rtbTemplate.Document.ContentEnd) tr.Load(ms, strDataFormat) End Using and my richtextbox in xaml <RichTextBox x:Name="rtbLetter"> <RichTextBox.Resources> <Style TargetType="{x:Type Paragraph}"> <Setter Property="Margin" Value="0"/> </Style> </RichTextBox.Resources> <FlowDocument FontSize="12" FontFamily="Times New Roman"> </FlowDocument> </RichTextBox> Any help is appreciated.

    Read the article

  • sql locking on silverlight app

    - by immuner
    Hi, i am not sure if this is the correct term, but this is what id like to do: I have an application that uses a mssql database. This application can operate in 3 modes. mode 1) user does not alter, but only read the database mode 2) user can add rows (one at a time) onto a table in the database mode 3) user can alter several tables in the database (one person at a time) question 1) how can i ensure that when a user in in mode 3 that the database will "lock" and all logged in users who operate in mode 2 or mode 3 will not be able to change the database until he finishes? question 2) how can i ensure that while there are several users in mode 2, that there will be no conflict while they all update the table? my guess here, is that before adding a new row, you make a server query for the table's current unique keys and add the new entry. will this be safe enough though? Thanks

    Read the article

  • Problem using FtpWebRequest to append to file on a mainframe

    - by MusiGenesis
    I am using FtpWebRequest to append data to a mainframe file. Each record appended is 50 characters long, and I am adding them one record at a time. In our development environment, we do not have a mainframe, so my code was written and tested FTPing to a Windows-based FTP site instead of a mainframe. Initially, I was writing each record using a StreamWriter (using the stream from the FtpWebRequest) and writing each record using WriteLine (which automatically adds a CR/LF to the end). When we ran this for the first time in the test environment (in which we're writing to an actual MVS mainframe), our mainframe contact said the CR/LFs were not able to be read by his program (a green-screen mainframe program of some sort - he's sent me screen captures, which is all I know of it). I changed our code to use Write instead of WriteLine, but now my code executes successfully (i.e no thrown exceptions) when writing multiple records, but no matter how many records we append, he is only able to "see" the first record - according to his mainframe program, there is only one 50-character record in the file. I'm guessing that to fix this, I need to write some other line-delimiting character into the end of the stream (instead of CR/LF) that the mainframe will recognize as a record delimiter. Anybody know what this is, or how else I can fix this problem?

    Read the article

  • Android and Kernel-Modules...

    - by Nils Pipenbrinck
    So - Android is build on top of a stripped down linux system. Most of the convenient utilities are missing but all the basics are there. I can call insmod and rmmod. No problem. But where do kernel-modules and firmware files reside? I can't find any. there is no /lib/modules in the standard distribution. Problem: I need modules. For sure don't want to compile support for each and every usb-device in the world into the linux-kernel. Where should I put them?

    Read the article

  • blue tooth programming on android

    - by user121196
    I currently use blue tooth api on android and am able to pair with regular devices(eg. my pc with built-in blue-tooth). However it doesn't get a response when trying to connect to it. What is the meaning of connect in blue tooth? is this a built-in protocol of bluetooth?

    Read the article

  • C# 4.0: Named And Optional Arguments

    - by Paulo Morgado
    As part of the co-evolution effort of C# and Visual Basic, C# 4.0 introduces Named and Optional Arguments. First of all, let’s clarify what are arguments and parameters: Method definition parameters are the input variables of the method. Method call arguments are the values provided to the method parameters. In fact, the C# Language Specification states the following on §7.5: The argument list (§7.5.1) of a function member invocation provides actual values or variable references for the parameters of the function member. Given the above definitions, we can state that: Parameters have always been named and still are. Parameters have never been optional and still aren’t. Named Arguments Until now, the way the C# compiler matched method call definition arguments with method parameters was by position. The first argument provides the value for the first parameter, the second argument provides the value for the second parameter, and so on and so on, regardless of the name of the parameters. If a parameter was missing a corresponding argument to provide its value, the compiler would emit a compilation error. For this call: Greeting("Mr.", "Morgado", 42); this method: public void Greeting(string title, string name, int age) will receive as parameters: title: “Mr.” name: “Morgado” age: 42 What this new feature allows is to use the names of the parameters to identify the corresponding arguments in the form: name:value Not all arguments in the argument list must be named. However, all named arguments must be at the end of the argument list. The matching between arguments (and the evaluation of its value) and parameters will be done first by name for the named arguments and than by position for the unnamed arguments. This means that, for this method definition: public static void Method(int first, int second, int third) this call declaration: int i = 0; Method(i, third: i++, second: ++i); will have this code generated by the compiler: int i = 0; int CS$0$0000 = i++; int CS$0$0001 = ++i; Method(i, CS$0$0001, CS$0$0000); which will give the method the following parameter values: first: 2 second: 2 third: 0 Notice the variable names. Although invalid being invalid C# identifiers, they are valid .NET identifiers and thus avoiding collision between user written and compiler generated code. Besides allowing to re-order of the argument list, this feature is very useful for auto-documenting the code, for example, when the argument list is very long or not clear, from the call site, what the arguments are. Optional Arguments Parameters can now have default values: public static void Method(int first, int second = 2, int third = 3) Parameters with default values must be the last in the parameter list and its value is used as the value of the parameter if the corresponding argument is missing from the method call declaration. For this call declaration: int i = 0; Method(i, third: ++i); will have this code generated by the compiler: int i = 0; int CS$0$0000 = ++i; Method(i, 2, CS$0$0000); which will give the method the following parameter values: first: 1 second: 2 third: 1 Because, when method parameters have default values, arguments can be omitted from the call declaration, this might seem like method overloading or a good replacement for it, but it isn’t. Although methods like this: public static StreamReader OpenTextFile( string path, Encoding encoding = null, bool detectEncoding = true, int bufferSize = 1024) allow to have its calls written like this: OpenTextFile("foo.txt", Encoding.UTF8); OpenTextFile("foo.txt", Encoding.UTF8, bufferSize: 4096); OpenTextFile( bufferSize: 4096, path: "foo.txt", detectEncoding: false); The complier handles default values like constant fields taking the value and useing it instead of a reference to the value. So, like with constant fields, methods with parameters with default values are exposed publicly (and remember that internal members might be publicly accessible – InternalsVisibleToAttribute). If such methods are publicly accessible and used by another assembly, those values will be hard coded in the calling code and, if the called assembly has its default values changed, they won’t be assumed by already compiled code. At the first glance, I though that using optional arguments for “bad” written code was great, but the ability to write code like that was just pure evil. But than I realized that, since I use private constant fields, it’s OK to use default parameter values on privately accessed methods.

    Read the article

  • Two users using the same same user profile while not in a domain.

    - by Scott Chamberlain
    I have a windows server 2003 acting as a terminal server, this computer is not a member of any domain. We demo our product on the server by creating a user account. The person logs in uses the demo for a few weeks and when they are done we delete the user account. However every time we do this it creates a new folder in C:\Documents and Settings\. I know with domains you can have many users point at one profile and make it read only so all changes are dumped afterwords, but is there a way to do that when the machine is not on a domain? I would really like it if I didn't have to remote in and clean up the folders every time.

    Read the article

  • Wordpress, WP_Query with custom taxonomy and custom post type

    - by Chris
    This code gets 10 posts of all types that are linked to the term_name; global $wp_query; query_posts( array( "taxonomy_name" => "term_name", 'showposts' => 10 ) ); This code gets 10 posts of custom post type "message"; global $wp_query; query_posts( array( 'post_type' => 'message' 'showposts' => 10 ) ); This code however always ignores the post_type requirement but still selects all post types linked to the term_name; global $wp_query; query_posts( array( 'post_type' => 'message' , "taxonomy_name" => "term_name", 'showposts' => 10 ) ); I can't see how both can work individually but together they don't unless it might be a bug - any thoughts?

    Read the article

  • google app engine persistent globals

    - by Joey
    Hi, I'm looking for a way to keep the equivalent of persistent global variables in app engine (python). What I'm doing is creating a global kind that I initialize once (i.e. when I reset all my database objects when I'm testing). I have things in there like global counters, or the next id to assign certain kinds I create. Is this a decent way to do this sort of thing or is there generally another approach that is used?

    Read the article

  • C# to Java Conversion: What is a [DefaultProperty("value")]?

    - by Shiftbit
    I do not understand how the DefaultProperty Metadata tag work or what it signifies. I've read the MSDN and went through the sample but I find it confusing. DefaultPropertyAttribute Class I've read a few blogs and they seem to refer to the indexers. I'm not sure why you would want metadata for your properties? I am coming from a Java background, perhaps a Java analogy would help. [DefaultProperty("Value")] public abstract class FOO<T> : ANY, IBAR<T> { public FOO() { } public FOO(T value) { this.Value = value; } public virtual T Value { get; set; } }

    Read the article

  • Proxy is created, and interceptor is in the __interceptors array, but the interceptor is never calle

    - by drewbu
    This is the first time I've used interceptors with the fluent registration and I'm missing something. With the following registration, I can resolve an IProcessingStep, and it's a proxy class and the interceptor is in the __interceptors array, but for some reason, the interceptor is not called. Any ideas what I'm missing? Thanks, Drew AllTypes.Of<IProcessingStep>() .FromAssembly(Assembly.GetExecutingAssembly()) .ConfigureFor<IProcessingStep>(c => c .Unless(Component.ServiceAlreadyRegistered) .LifeStyle.PerThread .Interceptors(InterceptorReference.ForType<StepLoggingInterceptor>()).First ), Component.For<StepMonitorInterceptor>(), Component.For<StepLoggingInterceptor>(), Component.For<StoreInThreadInterceptor>() public abstract class BaseStepInterceptor : IInterceptor { public void Intercept(IInvocation invocation) { IProcessingStep processingStep = (IProcessingStep)invocation.InvocationTarget; Command cmd = (Command)invocation.Arguments[0]; OnIntercept(invocation, processingStep, cmd); } protected abstract void OnIntercept(IInvocation invocation, IProcessingStep processingStep, Command cmd); } public class StepLoggingInterceptor : BaseStepInterceptor { private readonly ILogger _logger; public StepLoggingInterceptor(ILogger logger) { _logger = logger; } protected override void OnIntercept(IInvocation invocation, IProcessingStep processingStep, Command cmd) { _logger.TraceFormat("<{0}> for cmd:<{1}> - begin", processingStep.StepType, cmd.Id); bool exceptionThrown = false; try { invocation.Proceed(); } catch { exceptionThrown = true; throw; } finally { _logger.TraceFormat("<{0}> for cmd:<{1}> - end <{2}> times:<{3}>", processingStep.StepType, cmd.Id, !exceptionThrown && processingStep.CompletedSuccessfully ? "succeeded" : "failed", cmd.CurrentMetric==null ? "{null}" : cmd.CurrentMetric.ToString()); } } }

    Read the article

  • Is it possible to compile a query for linq-to-objects

    - by Luke101
    I have a linq to objects query in a recursive loop and afraid when the objects approach more then 1000 and a have more then 100 users on the site -- my website will break. so is it possible to compile a linq to objects query. The linq query does nothing more then find the direct children of a node.

    Read the article

  • Perl unit test - start a tcp server & continue

    - by John
    I am trying to write a unit test for a client server application. To test the client, in my unit test, I want to first start my tcp server (which itself is another perl file). I tried to start the tcp server by forking: if (! fork()) { system ("$^X server.pl") == 0 or die "couldn't start server" } So when I call "make test" after "perl Makefile.PL", this test starts & I can see the server starting but after that the unit test just hangs there. So I guess I need to start this server in background and I tried the "&" at the end to force it to start in background & then test to continue. But, I still couldn't succeed. What am I doing wrong? Thanks.

    Read the article

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