Search Results

Search found 6094 results on 244 pages for 'double gras'.

Page 98/244 | < Previous Page | 94 95 96 97 98 99 100 101 102 103 104 105  | Next Page >

  • Perl, strings, floats, unit testing and regexps!

    - by Chris R
    OK, as a preface this question potentially is 'stupider' than my normal level of question - however this problem has been annoying me for the last few days so I'll ask it anyway. I'll give a mock example of what my problem is so I can hope to generalize it to my current problem. #!/usr/bin/perl -w use strict; use Test::More 'no_plan'; my $fruit_string = 'Apples cost $1.50'; my ($fruit, $price) = $fruit_string =~ /(\w+)s cost \$(\d+\.\d+)/; # $price += 0; # Uncomment for Great Success is ($price, 1.50, 'Great Success'); Now when this is run I get the message # Failed test 'Great Success' # got: '1.50' # expected: '1.5' To make the test work - I either uncomment the commented line, or use is ($price, '1.50', 'Great Success'). Both options do not work for me - I'm testing a huge amount of nested data using Test::Deep and cmp_deeply. My question is, how can you extract a double from a regexp then use it immediately as a double - or if there is a better way altogether let me know - and feel free to tell me to take up gardening or something lol, learning Perl is hard.

    Read the article

  • Building static (but complicated) lookup table using templates.

    - by MarkD
    I am currently in the process of optimizing a numerical analysis code. Within the code, there is a 200x150 element lookup table (currently a static std::vector < std::vector < double ) that is constructed at the beginning of every run. The construction of the lookup table is actually quite complex- the values in the lookup table are constructed using an iterative secant method on a complicated set of equations. Currently, for a simulation, the construction of the lookup table is 20% of the run time (run times are on the order of 25 second, lookup table construction takes 5 seconds). While 5-seconds might not seem to be a lot, when running our MC simulations, where we are running 50k+ simulations, it suddenly becomes a big chunk of time. Along with some other ideas, one thing that has been floated- can we construct this lookup table using templates at compile time? The table itself never changes. Hard-coding a large array isn't a maintainable solution (the equations that go into generating the table are constantly being tweaked), but it seems that if the table can be generated at compile time, it would give us the best of both worlds (easily maintainable, no overhead during runtime). So, I propose the following (much simplified) scenario. Lets say you wanted to generate a static array (use whatever container suits you best- 2D c array, vector of vectors, etc..) at compile time. You have a function defined- double f(int row, int col); where the return value is the entry in the table, row is the lookup table row, and col is the lookup table column. Is it possible to generate this static array at compile time using templates, and how?

    Read the article

  • encryption in c#

    - by Raja
    i am implementing on algorithm in c#. it has encrypt one word . i have check using decrypt also. now i am using a textbox. want to pass a string in that text box that gives my whole string as cypher text. i dont know how to use. i have mad one loop there and calacated the string length. now suppose my function is it is PasswordEncryptor.cs file public static double REncryptText(double m) {// code } this fuction is doing a single number convertion into the encrpt and in code i know this is wrong i want try in this for (int i = 0; i <= 32; i++) { int [] cyph = new int[5]; // cyph=PasswordEncryptor.REncryptText(i); cypherText.Text = c; } i want that after entering the string into textbox it will call that string till string length and and by adding all the part of string one by one, i will get a final encrpytion code and will use further please help me in doing this

    Read the article

  • MSVC 2003 doesn't see any definitions from a nested include file

    - by ezpresso
    I have a piece of code with COM class declaration as follows: #include "PathTypes.h" MIDL_INTERFACE("552C7555-0555-4444-BA86-56CF39AAFFFF") IPathCalc : public IUnknown { virtual HRESULT STDMETHODCALLTYPE GetLocation( /* [retval][out] */ GeoLocation* pLoc) = 0; virtual HRESULT STDMETHODCALLTYPE SetLocation( /* [in] */ GeoLocation* pLoc) = 0; ... }; Below is the contents of PathTypes.h file: #if !defined(PATHCALC_TYPES_INCLUDED) #define PATHCALC_TYPES_INCLUDED #include "libastro/AstronomyStructs.h" #endif And the libastro/AstronomyStructs.h from an external cross-platform library: #ifndef _ASTRONOMY_STRUCTS_INCLUDED #define _ASTRONOMY_STRUCTS_INCLUDED typedef struct { double lattitude; double longitude; } GeoLocation; ... #endif /* _ASTRONOMY_STRUCTS_INCLUDED */ When I'm trying to build this code with g++ everything goes well. That's not the case with MSVC 2003 which returns error C2061: syntax error : identifier 'GeoLocation'. Seems like MSVC doesn't "see" the definitions from the libastro/AstronomyStructs.h file. When I replace #include "PathTypes.h" with #include "libastro/AstronomyStructs.h" the code compiles without errors. How to make MSVC 2003 to actually "see" the definitions from the nested include files?

    Read the article

  • Recursive templates: compilation error under g++

    - by Johannes
    Hi, I am trying to use templates recursively to define (at compile-time) a d-tuple of doubles. The code below compiles fine with Visual Studio 2010, but g++ fails and complains that it "cannot call constructor 'point<1::point' directly". Could anyone please shed some light on what is going on here? Many thanks, Jo #include <iostream> #include <utility> using namespace std; template <const int N> class point { private: pair<double, point<N-1> > coordPointPair; public: point() { coordPointPair.first = 0; coordPointPair.second.point<N-1>::point(); } }; template<> class point<1> { private: double coord; public: point() { coord= 0; } }; int main() { point<5> myPoint; return 0; }

    Read the article

  • How to check if a number is a power of 2

    - by configurator
    Today I needed a simple algorithm for checking if a number is a power of 2. The algorithm needs to be: Simple Correct for any ulong value. I came up with this simple algorithm: private bool IsPowerOfTwo(ulong number) { if (number == 0) return false; for (ulong power = 1; power > 0; power = power << 1) { // this for loop used shifting for powers of 2, meaning // that the value will become 0 after the last shift // (from binary 1000...0000 to 0000...0000) then, the for // loop will break out if (power == number) return true; if (power > number) return false; } return false; } But then I thought, how about checking if log2x is an exactly round number? But when I checked for 2^63+1, Math.Log returned exactly 63 because of rounding. So I checked if 2 to the power 63 is equal to the original number - and it is, because the calculation is done in doubles and not in exact numbers: private bool IsPowerOfTwo_2(ulong number) { double log = Math.Log(number, 2); double pow = Math.Pow(2, Math.Round(log)); return pow == number; } This returned true for the given wrong value: 9223372036854775809. Does anyone have any suggestion for a better algorithm?

    Read the article

  • fopen / fopen_s and writing to files

    - by yCalleecharan
    Hi, I'm using fopen in C to write the output to a text file. The function declaration is (where ARRAY_SIZE has been defined earlier): void create_out_file(char file_name[],long double *z1){ FILE *out; int i; if((out = fopen(file_name, "w+")) == NULL){ fprintf(stderr, "* Open error on output file %s", file_name); exit(-1); } for(i = 0; i < ARRAY_SIZE; i++) fprintf(out, "%.16Le\n", z1[i]); fclose(out); } My questions: On compilation with MVS2008 I get the warning: warning C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. I haven't see much information on fopen_s so that I can change my code. Any suggestions? Can one instruct fprintf to write at desired precision? If I'm using long double then I assume that my answers are good till 15 digits after the decimal point. Am I right? Thanks a lot...

    Read the article

  • fetching gps location in blackberry

    - by SWATI
    in my application i try to fetch users location but it always 0.0 for both latitude and longitude.I have seen blackberry forum but couldn't find what am i doing wrong??? code : package com.MyChamberApp; import javax.microedition.location.Criteria; import javax.microedition.location.Location; import javax.microedition.location.LocationListener; import javax.microedition.location.LocationProvider; public class GPS_Location { static double longi; static double lati; public GPS_Location() { } public void location() { new LocationTracker(); } class LocationTracker { private LocationProvider provider; Criteria cr; public LocationTracker() { resetGPS(); } public void resetGPS() { try { cr = new Criteria(); cr.setPreferredPowerConsumption(Criteria.POWER_USAGE_HIGH); cr.setPreferredResponseTime(120000); cr.setCostAllowed(true); provider = LocationProvider.getInstance(cr); provider.getLocation(120); if (provider != null) { provider.setLocationListener(new MyLocationListener(), 1,1,1); } } catch (Exception e) {} } public void run(){} private class MyLocationListener implements LocationListener { public void providerStateChanged(LocationProvider provider,int newState) { if (newState == LocationProvider.TEMPORARILY_UNAVAILABLE) { provider.reset(); resetGPS(); } if (newState == LocationProvider.OUT_OF_SERVICE) { provider.reset(); resetGPS(); } } public void locationUpdated(LocationProvider provider,Location location) { if (location != null && location.isValid()) { try { lati = location.getQualifiedCoordinates().getLatitude(); longi = location.getQualifiedCoordinates().getLongitude(); } catch (Exception e) {} } } } } } i have tried this code on curve8300,bold9000 It works well on simulator but does not fetches value on device till i manually do not refresh my gps. thanks in advance!!!!!!!!!!!!!!!!

    Read the article

  • Simple average calculation

    - by sasquatch90
    I'm trying to write program calculating average of given numbers stored in an array. Amount of numbers should be not more than 100, and user should input them until a !int variable is given : #include <iostream> #include <conio.h> using namespace std; double average(int tab[], int i){ int sum=0; for(int j=0; j<i; ++j){ sum+=tab[j]; } return (double)sum/i; } int main() { int tab[100]; int n=0; int number=0; do { if(n < 100){ cout << "Give " << n+1 << " number : "; cin >> number; tab[n]=number; number=0; ++n; } else{ break; } } while( !isdigit(number) ); cout << average(tab, n) << endl; getch(); return 0; } Why after giving char, it prints me 'Give n number:' for all empty cells of my array ? It should end and use only given numbers.

    Read the article

  • Textmate, open file at Caret

    - by amjags
    I bet this is really obvious but I can't find how to open the linked file that the Caret is currently on in Textmate. For example in the likes of Dreamweaver you can click in the index.html portion of <a href"index.html" hit cmd-D and it opens this file in a new tab. Is this possible? Would also be good to do this with <img src="image.jpg" to open the file directly into Photoshop. Solved! Solution for Patrick below. I used a modified version of Daustin777's example above to create a Command called OpenatCaret. The command is: open "$TM_PROJECT_DIRECTORY"/"$TM_SELECTED_TEXT" I then extended this by installing a macro which allowed you to select a path between double quotes but not including the quotes. I got this from the macromates board here. http://lists.macromates.com/textmate/2009-June/028965.html To wrap them both together I put my cursor in a path and recorded a new macro where I run the "Select within double quotes" macro and then the OpenatCaret command. I then named this OpenProjectFileAtCaret and bound this macro to cmd-D. Works a treat and is used all the time. Just make sure you have the correct default apps setup for each file type you are opening eg. Textmate for php, asp, html and it will open them in a new tab.

    Read the article

  • Creating an object in the loop

    - by Jacob
    std::vector<double> C(4); for(int i = 0; i < 1000;++i) for(int j = 0; j < 2000; ++j) { C[0] = 1.0; C[1] = 1.0; C[2] = 1.0; C[3] = 1.0; } is much faster than for(int i = 0; i < 1000;++i) for(int j = 0; j < 2000; ++j) { std::vector<double> C(4); C[0] = 1.0; C[1] = 1.0; C[2] = 1.0; C[3] = 1.0; } I realize this happens because std::vector is repeatedly being created and instantiated in the loop, but I was under the impression this would be optimized away. Is it completely wrong to keep variables local in a loop whenever possible? I was under the (perhaps false) impression that this would provide optimization opportunities for the compiler. EDIT: I use VC++2005 (release mode) with full optimization (/Ox)

    Read the article

  • How to refactor this duplicated LINQ code?

    - by benrick
    I am trying to figure out how to refactor this LINQ code nicely. This code and other similar code repeats within the same file as well as in other files. Sometime the data being manipulated is identical and sometimes the data changes and the logic remains the same. Here is an example of duplicated logic operating on different fields of different objects. public IEnumerable<FooDataItem> GetDataItemsByColor(IEnumerable<BarDto> dtos) { double totalNumber = dtos.Where(x => x.Color != null).Sum(p => p.Number); return from stat in dtos where stat.Color != null group stat by stat.Color into gr orderby gr.Sum(p => p.Number) descending select new FooDataItem { Color = gr.Key, NumberTotal = gr.Sum(p => p.Number), NumberPercentage = gr.Sum(p => p.Number) / totalNumber }; } public IEnumerable<FooDataItem> GetDataItemsByName(IEnumerable<BarDto> dtos) { double totalData = dtos.Where(x => x.Name != null).Sum(v => v.Data); return from stat in dtos where stat.Name != null group stat by stat.Name into gr orderby gr.Sum(v => v.Data) descending select new FooDataItem { Name = gr.Key, DataTotal = gr.Sum(v => v.Data), DataPercentage = gr.Sum(v => v.Data) / totalData }; } Anyone have a good way of refactoring this?

    Read the article

  • Boost threading/mutexs, why does this work?

    - by Flamewires
    Code: #include <iostream> #include "stdafx.h" #include <boost/thread.hpp> #include <boost/thread/mutex.hpp> using namespace std; boost::mutex mut; double results[10]; void doubler(int x) { //boost::mutex::scoped_lock lck(mut); results[x] = x*2; } int _tmain(int argc, _TCHAR* argv[]) { boost::thread_group thds; for (int x = 10; x>0; x--) { boost::thread *Thread = new boost::thread(&doubler, x); thds.add_thread(Thread); } thds.join_all(); for (int x = 0; x<10; x++) { cout << results[x] << endl; } return 0; } Output: 0 2 4 6 8 10 12 14 16 18 Press any key to continue . . . So...my question is why does this work(as far as i can tell, i ran it about 20 times), producing the above output, even with the locking commented out? I thought the general idea was: in each thread: calculate 2*x copy results to CPU register(s) store calculation in correct part of array copy results back to main(shared) memory I would think that under all but perfect conditions this would result in some part of the results array having 0 values. Is it only copying the required double of the array to a cpu register? Or is it just too short of a calculation to get preempted before it writes the result back to ram? Thanks.

    Read the article

  • Is the C++ compiler optimizer allowed to break my destructor ability to be called multiple times?

    - by sharptooth
    We once had an interview with a very experienced C++ developer who couldn't answer the following question: is it necessary to call the base class destructor from the derived class destructor in C++? Obviously the answer is no, C++ will call the base class destructor automagically anyway. But what if we attempt to do the call? As I see it the result will depend on whether the base class destructor can be called twice without invoking erroneous behavior. For example in this case: class BaseSafe { public: ~BaseSafe() { } private: int data; }; class DerivedSafe { public: ~DerivedSafe() { BaseSafe::~BaseSafe(); } }; everything will be fine - the BaseSafe destructor can be called twice safely and the program will run allright. But in this case: class BaseUnsafe { public: BaseUnsafe() { buffer = new char[100]; } ~BaseUnsafe () { delete[] buffer; } private: char* buffer; }; class DerivedUnsafe { public: ~DerivedUnsafe () { BaseUnsafe::~BaseUnsafe(); } }; the explicic call will run fine, but then the implicit (automagic) call to the destructor will trigger double-delete and undefined behavior. Looks like it is easy to avoid the UB in the second case. Just set buffer to null pointer after delete[]. But will this help? I mean the destructor is expected to only be run once on a fully constructed object, so the optimizer could decide that setting buffer to null pointer makes no sense and eliminate that code exposing the program to double-delete. Is the compiler allowed to do that?

    Read the article

  • Limit CPU usage of a process

    - by jb
    I have a service running which periodically checks a folder for a file and then processes it. (Reads it, extracts the data, stores it in sql) So I ran it on a test box and it took a little longer thaan expected. The file had 1.6 million rows, and it was still running after 6 hours (then I went home). The problem is the box it is running on is now absolutely crippled - remote desktop was timing out so I cant even get on it to stop the process, or attach a debugger to see how far through etc. It's solidly using 90%+ CPU, and all other running services or apps are suffering. The code is (from memory, may not compile): List<ItemDTO> items = new List<ItemDTO>(); using (StreamReader sr = fileInfo.OpenText()) { while (!sr.EndOfFile) { string line = sr.ReadLine() try { string s = line.Substring(0,8); double y = Double.Parse(line.Substring(8,7)); //If the item isnt already in the collection, add it. if (items.Find(delegate(ItemDTO i) { return (i.Item == s); }) == null) items.Add(new ItemDTO(s,y)); } catch { /*Crash*/ } } return items; } - So I am working on improving the code (any tips appreciated). But it still could be a slow affair, which is fine, I've no problems with it taking a long time as long as its not killing my server. So what I want from you fine people is: 1) Is my code hideously un-optimized? 2) Can I limit the amount of CPU my code block may use? Cheers all

    Read the article

  • How to store and locate multiple interface types within a Delphi TInterfaceList

    - by Brian Frost
    Hi, I'm storing small interfaces from a range of objects into a single TInterfaceList 'store' with the intention of offering list of specific interface types to the end user, so each interface will expose a 'GetName' function but all other methods are unique to that interface type. For example here are two interfaces: IBase = interface //---------------------------------------- function GetName : string; //---------------------------------------- end; IMeasureTemperature = interface(IBase) //------------------------------------ function MeasureTemperature : double; //---------------------------------------- end; IMeasureHumidity = interface(IBase) //---------------------------------------- function MeasureHumidity: double; //---------------------------------------- end; I put several of these interfaces into a single TInterfaceList and then I'd like to scan the list for a specific interface type (e.g. 'IMeasureTemperature') building another list of pointers to the objects exporting those interfaces. I wish to make no assumptions about the locations of those objects, some may export more than one type of interface. I know I could do this with a class hierarchy using something like: If FList[I] is TMeasureTemperature then .. but I'd like to do something simliar with an interface type, Is this possible?

    Read the article

  • Stuck in a loop

    - by Luke
    while (true) { //read in the file StreamReader convert = new StreamReader("../../convert.txt"); //define variables string line = convert.ReadLine(); double conversion; int numberIn; double conversionFactor; //ask for the conversion information Console.WriteLine("Enter the conversion in the form (Amount, Convert from, Convert to)"); String inputMeasurement = Console.ReadLine(); string[] inputMeasurementArray = inputMeasurement.Split(','); //loop through the lines looking for a match while (line != null) { string[] fileMeasurementArray = line.Split(','); if (fileMeasurementArray[0] == inputMeasurementArray[1]) { if (fileMeasurementArray[1] == inputMeasurementArray[2]) { Console.WriteLine("The conversion factor for {0} to {1} is {2}", inputMeasurementArray[1], inputMeasurementArray[2], fileMeasurementArray[2]); //convert to int numberIn = Convert.ToInt32(inputMeasurementArray[0]); conversionFactor = Convert.ToDouble(fileMeasurementArray[2]); conversion = (numberIn * conversionFactor); Console.WriteLine("{0} {1} is {2} {3} \n", inputMeasurementArray[0], inputMeasurementArray[1], conversion, inputMeasurementArray[2]); break; } } else { Console.WriteLine("Please enter two valid conversion types \n"); break; } line = convert.ReadLine(); } } The file consists of the following: ounce,gram,28.0 pound,ounce,16.0 pound,kilogram,0.454 pint,litre,0.568 inch,centimetre,2.5 mile,inch,63360.0 The user will input something like 6,ounce,gram The idea is that it finds the correct line by checking if the first and second words in the file are the same as the second and third the user enters. The problem is that if it checks the first line and it fails the if statement, if goes through to the else statement and stops. I am trying to find a way where it will stop after the it finds the correct line but not until. If someone types in a value that isn't in the file, then it should show an error.

    Read the article

  • ISO C90 forbids mixed declarations and code sscanf

    - by Need4Sleep
    I'm getting a strange error attempting to compile my unit test code,. For some reason the compiler treats my sscanf call as a mixed declaration? I don't quite understand, here is the entire error: cc1: warnings being treated as errors /home/brlcad/brlcad/src/libbn/tests/bn_complex.c: In function 'main': /home/brlcad/brlcad/src/libbn/tests/bn_complex.c:53: error: ISO C90 forbids mixed declarations and code make[2]: *** [src/libbn/tests/CMakeFiles/tester_bn_complex.dir/bn_complex.c.o] Error 1 make[1]: *** [src/libbn/tests/CMakeFiles/tester_bn_complex.dir/all] Error 2 make: *** [all] Error 2 int main(int argc, char *argv[]) { double expRe1, expIm2, expSqRe1, expSqIm2; double actRe1, actIm2, actSqRe1, actSqIm2; actRe1 = actIm2 = actSqRe1 = actSqIm2 = expRe1 = expIm2 = expSqRe1 = expSqIm2 = 0.0; bn_complex_t com1,com2; //a struct that holds two doubles if(argc < 5) bu_exit(1, "ERROR: Invalid parameters[%s]\n", argv[0]); sscanf(argv[1], "%lf,%lf", &com1.re, &com1.im); /* Error is HERE */ sscanf(argv[2], "%lf,%lf", &com2.re, &com2.im); sscanf(argv[3], "%lf,%lf", &expRe1, &expIm2); sscanf(argv[4], "%lf,%lf", &expSqRe1, &expSqIm2); test_div(com1, com2, &actRe1, &actIm2); test_sqrt(com1,com2, &actSqRe1, &actSqIm2); if((fabs(actRe1 - expRe1) < 0.00001) || (fabs(actIm2 - expIm2) < 0.00001)){ printf("Division failed...\n"); return 1; } if((fabs(actSqRe1 - expSqRe1) < 0.00001) || (fabs(actSqIm2 - expSqIm2) < 0.00001)){ printf("Square roots failed...\n"); return 1; } return 0; }

    Read the article

  • Nesting arbitrary objects in Java

    - by user1502381
    I am having trouble solving a particular problem in Java (which I did not find by search). I do not know how to create a nested lists of objects - with a different type of object/primitive type at the end. For example: *Note: only an example. I am actually doing this below with something other than Employee, but it serves as simple example. I have an array of an object Employee. It contains information on the Employee. public class Employee { int age int salary int yearsWorking public Employee () { // constructor... } // Accessors } What I need to do is organize the Employees by quantiles/percentiles. I have done so by the following: import org.apache.commons.math.stat.descriptive.rank.Percentile; public class EmployeeSort { public void main(String args[]) { Percentile p = new Percentile(); Employee[] employeeArray = new Employee(100); // filled employeeArray double[] ageArray new double[100]; // filled ageArray with ages from employeeArray int q = 25; // Percentile cutoff for (int i = 1; i*q < 100; i++) { // assign percentile cutoff to some array to contain the values } } } Now, the problem I have is that I need to organize the Employees first by the percentiles of age, then percentiles of yearsWorking, and finally by percentiles of salary. My Java knowledge is inadequate right now to solve this problem, but the project I was handed was in Java. I am primarily a python guy, so this problem would have been a lot easier in that language. No such luck.

    Read the article

  • Silverlight Image Data Binding

    - by Alexander
    I am new to Silverlight, and have an issue with binding. I have a class ItemsManager, that has inside its scope another class Item. class ItemsManager { ... class Item : INotifyPropertyChanged { ... private BitmapImage bitmapSource; public BitmapImage BitmapSource { get { return bitmapSource; } set { bitmapSource = value; if(PropertyChanged != null )PropertyChanged("BitmapSource") } } } } I do the following in code to test binding: { ItemsManager.Instance.AddItem("123"); //Items manager started downloading item visual //part (in my case bitmap image png) Binding b = new Binding("Source"); b.Source = ItemsManager.Instance.GetItem("123").BitmapSource; b.BindsDirectlyToSource = true; Image img = new Image(); img.SetBinding(Image.SourceProperty, b); img.Width = (double)100.0; img.Height = (double)100.0; LayoutRoot.Children.Add(img); } Once image is loaded, image doesn't appear. Though, if I set directly after image has been loaded its source, it displays well. I also noticed that PropertyChanged("BitmapSource") never fires, because PropertyChanged is null, like Image never binded to it. I am looking forward to hearing from you!

    Read the article

  • Replacing text with apostrophe text via sed in applescript

    - by bob stinton
    I have an applescript to find and replace a number of strings. I ran in the problem of having a replacement string which contained & some time ago, but could get around it by putting \& in the replacement property list. However an apostrophe seems to be far more annoying. Using a single apostrophe just gets ignored (replacement doesn't contain it), using \' gives a syntax error (Expected “"” but found unknown token.) and using \' gets ignored again. (You can keep doing that btw, even number gets ignored uneven gets syntax error) I tried replacing the apostrophe in the actual sed command with double quotes (sed "s…" instead of sed 's…'), which works in the command line, but gives a syntax error in the script (Expected end of line, etc. but found identifier.) The single quotes mess with the shell, the double quotes with applescript. I also tried '\'' as was suggested here and '"'"' from here. Basic script to get the type of errors: set findList to "Thats.nice" set replaceList to "That's nice" set fileName to "Thats.nice.whatever" set resultFile to do shell script "echo " & fileName & " | sed 's/" & findList & "/" & replaceList & " /'"

    Read the article

  • std::stringstream GCC Abnormal Behavior

    - by FlorianZ
    I have a very interesting problem with compiling a short little program on a Mac (GCC 4.2). The function below would only stream chars or strings into the stringstream, but not anything else (int, double, float, etc.) In fact, the fail flag is set if I attempt to convert for example an int into a string. However, removing the preprocessor flag: _GLIBCXX_DEBUG=1, which is set by default in XCode for the debug mode, will yield the desired results / correct behavior. Here is the simple function I am talking about. value is template variable of type T. Tested for int, double, float (not working), char and strings (working). template < typename T > const std::string Attribute<T>::getValueAsString() const { std::ostringstream stringValue; stringValue << value; return stringValue.str(); } Any ideas what I am doing wrong, why this doesn't work, or what the preprocessor flag does to make this not work anymore? Thanks!

    Read the article

  • jquery form validation, and submit-on-change

    - by Bee
    I want to make all my settings forms across my site confirm that changes are saved, kinda like facebook does if you make changes in a form and then try to navigate away without saving. So I'm disabling the submit button on the forms only enabling if the values change. I then prompt the user to hit save before they leave the page in the case that they do have changes pending. var form = $('form.edit'); if(form.length > 0) { var orig_str = form.serialize(); $(':submit',form).attr('disabled','disabled'); form.on('change keyup', function(){ if(form.serialize() == orig_str) { setConfirmUnload(false); $(':submit',form).attr('disabled','disabled'); } else { setConfirmUnload(true); $(':submit',form).removeAttr('disabled') } }); $('input[type=submit]').click(function(){ setConfirmUnload(false); }); } function setConfirmUnload(on) { window.onbeforeunload = (on) ? unloadMessage : null; } function unloadMessage() { return 'If you navigate away from this page without saving your changes, they will be lost.'; } One of these forms needs some additional validation which I do using jQuery.validate library. e.g. if i wanted to ensure the user can't double submit the form on accident by double clicking on submit or somesuch (the actual validation in question is for a credit-card form and not this simple): $('form').validate({ submitHandler: function(form) { $(':submit', form).attr('disabled','disabled'); form.submit(); } }); Unfortunately both bits are trying to bind to submit button and they're interfering with each other such that the submit button remains disabled no matter what I do and it is impossible to submit the form at all. Is there some way to chain the validations together or something? Or some other way to avoid re-writing the validation code to repeat the "did you change anything in the form" business?

    Read the article

  • Updating a Database from DataBound Controls

    - by Avatar_Squadron
    Hi. I'm currently creating a WinForm in VB.NET bound to an access database. Basically what i have are two forms: one is a search form used to search the database, and the other is a details form. You run a search on the searchForm and it returns a list of Primary Keys and a few other identifying values. You then double click on the entry you want to view, and it loads the details form. The Details form has a collection of databound controls to display the data: mostly text boxes and checkboxs. The way i've set it up is i used the UI to build the form and then set the DataBindings Property of each control to "TblPropertiesBindingSource - " where value name is one of the values in the table (such as PropertyID or HasWoodFloor). Then, when you double click an entry in the searchform, I handle the event by parsing the Primary Key (PropertyID) out of the selected row and then storing this to the details form: Note: Detail is the details form that is opened to display the info Private Sub propView_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles propView.CellDoubleClick Dim detail As frmPropertiesDetail = New frmPropertiesDetail detail.id = propView.Rows(e.RowIndex).Cells(0).Value detail.Show() End Sub Then, upon loading the details form, it set's the filter on the BindSource as such: TblPropertiesBindingSource.Filter() = "PropertyID=" & id This works great so far. All the controls on the details form will display the correct info. The problem is updating changes. Scenario: If i have the user load the details for say, property 10001, it will show a description in a textBox named descriptionBox which is identical to the value of the description value of for that entry in the database. I want the user to then be able to change the text of the text box (which they can currently do) and click the save button (saveBut) and have the form update all the values in the controls to the database. Theorectically, it should do this as the controls are DataBound, thus i can avoid writing code that tells each entry in the database row to take the value of the aligned control. I've tried calleding PropertiesTableAdapter.Update(PropertiesBindingSource.DataSource), but that doesnt seem to do it.

    Read the article

  • Iphone -- maintaining a list of strings and a corresponding typedef enum

    - by William Jockusch
    Suppose I have the following: typedef enum functionType {ln, sin, sqrt} functionType; NSArray *functions = [NSArray arrayWithObjects: @"ln", @"sin", @"sqrt", nil]; Suppose further that *functions will not change at runtime. Question -- is there any way to set up a single structure which updates both of these? So that I only have to keep track of one list, instead of two. To explain what is going on -- the idea is that string input from the user will be stored in a variable of type functionType. Later on, I will have code like this: double valueOfFunction: (functionType) function withInput: (double) input switch (function) { case ln: return ln(input); case sin: return sin(input); case sqrt: return sqrt(input); //etc . . . could grow to include a lot of functions. } And valueOfFunction needs to be fast. So I don't want to be doing string comparisons there.

    Read the article

< Previous Page | 94 95 96 97 98 99 100 101 102 103 104 105  | Next Page >