Search Results

Search found 332 results on 14 pages for 'baz'.

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

  • How can I declare a pointer with filled information in C++?

    - by chacham15
    typedef struct Pair_s { char *first; char *second; } Pair; Pair pairs[] = { {"foo", "bar"}, //this is fine {"bar", "baz"} }; typedef struct PairOfPairs_s { Pair *first; Pair *second; } PairOfPairs; PairOfPairs pops[] = { {{"foo", "bar"}, {"bar", "baz"}}, //How can i create an equivalent of this NEATLY {&pairs[0], &pairs[1]} //this is not considered neat (imagine trying to read a list of 30 of these) }; How can I achieve the above style declaration semantics?

    Read the article

  • Getting req.params in order in Express JS

    - by Adam Terlson
    In Express, is there a way to get the arguments passed from the matching route in the order they are defined in the route? I want to be able to apply all the params from the route to another function. The catch is that those parameters are not known up front, so I cannot refer to each parameter by name explicitly. app.get(':first/:second/:third', function (req) { output.apply(this, req.mysteryOrderedArrayOfParams); // Does this exist? }); function output() { for(var i = 0; i < arguments.length; i++) { console.log(arguments[i]); } } Call on GET: "/foo/bar/baz" Desired Output (in this order): foo bar baz

    Read the article

  • INSERT INTO ... SELECT ... vs dumping/loading a file in MySQL

    - by Daniel Huckstep
    What are the implications of using a INSERT INTO foo ... SELECT FROM bar JOIN baz ... style insert statement versus using the same SELECT statement to dump (bar, baz) to a file, and then insert into foo by loading the file? In my messing around, I haven't seen a huge difference. I would assume the former would use more memory, but the machine that this runs on has 8GB of RAM, and I never even see it go past half used. Are there any huge (or long term) performance implications that I'm not seeing? Advantages/disadvantages of either?

    Read the article

  • Process requires redirected input

    - by initialZero
    I have a UNIX native executable that requires the arguments to be fed in like this prog.exe < foo.txt. foo.txt has two lines: bar baz I am using java.lang.ProcessBuilder to execute this command. Unfortunately, prog.exe will only work using the redirect from a file. Is there some way I can mimic this behavior in Java? Of course, ProcessBuilder pb = new ProcessBuilder("prog.exe", "bar", "baz"); does not work. Thanks!

    Read the article

  • Consistent PHP _SERVER variables between Apache and nginx?

    - by Alix Axel
    I'm not sure if this should be asked here or on ServerFault, but here it goes... I am trying to get started on nginx with PHP-FPM, but I noticed that the server block setup I currently have (gathered from several guides including the nginx Pitfalls wiki page) produces $_SERVER variables that are different from what I'm used to seeing in Apache setups. After spending the last evening trying to "fix" this, I decided to install Apache on my local computer and gather the variables that I'm interested in under different conditions so that I could try and mimic them on nginx. The Apache setup I've on my computer has only one mod_rewrite rule: RewriteEngine On RewriteCond %{SCRIPT_FILENAME} !-f RewriteCond %{SCRIPT_FILENAME} !-d RewriteRule ^(.*)$ /index.php/$1 [L] And these are the values I get for different request URIs (left is Apache, right is nginx): localhost/ - http://www.mergely.com/GnzBHRV1/ localhost/foo/bar/baz/?foo=bar - http://www.mergely.com/VwsT8oTf/ localhost/index.php/foo/bar/baz/?foo=bar - http://www.mergely.com/VGEFehfT/ What configuration directives would allow me to get similar values on requests handled by nginx? My current configuration in nginx is: server { listen 80; listen 443 ssl; server_name default; ssl_certificate /etc/nginx/certificates/dummy.crt; ssl_certificate_key /etc/nginx/certificates/dummy.key; root /var/www/default/html; index index.php index.html; autoindex on; location / { try_files $uri $uri/ /index.php; } location ~ /(?:favicon[.]ico|robots[.]txt)$ { log_not_found off; } location ~* [.]php { #try_files $uri =404; include fastcgi_params; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; fastcgi_split_path_info ^(.+[.]php)(/.+)$; } location ~* [.]ht { deny all; } } And my fastcgi_params file looks like this: fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info; fastcgi_param QUERY_STRING $query_string; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_param SCRIPT_NAME $fastcgi_script_name; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param REQUEST_URI $request_uri; fastcgi_param DOCUMENT_URI $document_uri; fastcgi_param DOCUMENT_ROOT $document_root; fastcgi_param SERVER_PROTOCOL $server_protocol; fastcgi_param GATEWAY_INTERFACE CGI/1.1; fastcgi_param SERVER_SOFTWARE nginx/$nginx_version; fastcgi_param REMOTE_ADDR $remote_addr; fastcgi_param REMOTE_PORT $remote_port; fastcgi_param SERVER_ADDR $server_addr; fastcgi_param SERVER_PORT $server_port; fastcgi_param SERVER_NAME $server_name; fastcgi_param HTTPS $https; I know that the try_files $uri =404; directive is commented and that it is a security vulnerability but, if I uncomment it, the third request (localhost/index.php/foo/bar/baz/?foo=bar) will return a 404. It's also worth noting that my PHP cgi.fix_pathinfo in On (contrary to what some of the guides recommend), if I try to set it to Off, I'm presented with a "Access denied." message on every PHP request. I'm running PHP 5.4.8 and nginx/1.1.19. I don't know what else to try... Help?

    Read the article

  • rhythmbox plugin code for hot key not working

    - by Bunny Rabbit
    def activate(self,shell): self.shell = shell self.copy_selected() self.action = gtk.Action ('foo','bar','baz',None) self.activate_id = self.action.connect ('activate', self.call_bk_fn,self.shell) self.action_group = gtk.ActionGroup ('hot_key_action_group') self.action_group.add_action_with_accel (self.action, "<control>E") uim = shell.get_ui_manager () uim.insert_action_group (self.action_group, 0) uim.ensure_update () def call_bk_fn(): print('hello world') i am using the above code in a plugin for rhythmbox ,and here i am trying to register the key ctr+e so that the call_bk_fn gets called whenever the key combination is pressed , but its not working why is that so ?

    Read the article

  • Rhythmbox plugin code for hot key not working - why?

    - by Bunny Rabbit
    def activate(self,shell): self.shell = shell self.copy_selected() self.action = gtk.Action ('foo','bar','baz',None) self.activate_id = self.action.connect ('activate', self.call_bk_fn,self.shell) self.action_group = gtk.ActionGroup ('hot_key_action_group') self.action_group.add_action_with_accel (self.action, "<control>E") uim = shell.get_ui_manager () uim.insert_action_group (self.action_group, 0) uim.ensure_update () def call_bk_fn(): print('hello world') I am using the above code in a plugin for Rhythmbox and here I am trying to register the key Ctrl+E so that the call_bk_fn gets called whenever the key combination is pressed but its not working. Why is that so ?

    Read the article

  • What is a good algorithm to distribute items with specific requirements?

    - by user66160
    I have to programmatically distribute a set of items to some entities, but there are rules both on the items and on the entities like so: Item one: 100 units, only entities from Foo Item two: 200 units, no restrictions Item three: 100 units, only entities that have Bar Entity one: Only items that have Baz Entity one hundred: No items that have Fubar I only need to be pointed in the right direction, I'll research and learn the suggested methods.

    Read the article

  • redirect temporarily STDOUT to another file descriptor, but still to screen

    - by Carlos Campderrós
    I'm making a script that executes some commands inside, and these commands show some output on STDOUT (and STDERR as well, but that's no problem). I need that my script generates a .tar.gz file to STDOUT, so the output of some commands executed in the script also go to STDOUT and this ends with a not valid .tar.gz file in the output. So, in short, it's possible to output the first commands to the screen (as I still want to see the output) but not via STDOUT? Also I would like to keep the STDERR untouched so only error messages appear there. A simple example of what I mean. This would be my script: #!/bin/bash # the output of these commands shouldn't go to STDOUT, but still appear on screen some_cmd foo bar other_cmd baz #the following command creates a tar.gz of the "whatever" folder, #and outputs the result to STDOUT tar zc whatever/ I've tried messing with exec and the file descriptors, but I still can't get it to work: #!/bin/bash # save STDOUT to #3 exec 3>&1 # the output of these commands should go to #3 and screen, but not STDOUT some_cmd foo bar other_cmd baz # restore STDOUT exec 1>&3 # the output of this command should be the only one that goes to STDOUT tar zc whatever/ I guess I'm lacking closing STDOUT after the first exec and reopen it again or something, but I can't find the right way to do it (right now the result is the same as if I didn't add the execs

    Read the article

  • Copy a website and preserve the file & folder structure

    - by DrStalker
    I have an old web site running on an ancient version of Oracle Portal that we need to convert to a flat-html structure. Due to damage to the server we are not able to access the administrative interface, and even if we could there is no export functionality that can work with modern software versions. It would be enough to crawl the website and have all the pages & images saved to a folder, but the file structure needs to be preserved; that is, if a page is located at http://www.oldserver.com/foo/bar/baz/mypage.html then it needs to be saved to /foo/bar/baz/mypage.html so that the various Javascript bits will continue to function. None of the web crawlers I've found have been able to do this; they all want to rename the pages (page01.html, page02.html etc) and break the folder structure. Is there any crawler out there that will recreate the site structure as it appears to a user accessing the site? It doesn't need to redo any of teh content of the pages; once rehosted the pages will all have the same names they did originally so links will continue to work.

    Read the article

  • Tool to Save a Range of Disk Clusters to a File

    - by Synetech inc.
    Hi, Yesterday I deleted a (fragmented) archive file only to find that it did not extract correctly, so I was left stranded. Fortunately there was not much space free on the drive, so most of the space marked as free was from the now-deleted archive. I pulled up a disk editor and—painfully—managed to get a list of cluster ranges from the FAT that were marked as unused. My task then was to save these ranges of clusters to files so that I could examine them to try to determine which parts were from the archive and recombine them to attempt to restore the deleted file. This turned out to be a huge pain in the butt because the disk editor did not have the ability to select a range of clusters, so I had to navigate to the start of each cluster and hold down Ctrl+Shift+PgDn until I reached the end of the range (which usually took forever!) I did a quick Google search to see if I could find a command-line tool (preferably with Windows and DOS versions) that would allow me to issue a commands such as: SAVESECT -c 0xBEEF 0xCAFE FOO.BAR ::save clusters 0xBEEF-0xCAFE to FOO.BAR SAVESECT -s 1111 9876 BAZ.BIN ::save sectors 1111-9876 to BAZ.BIN Sadly my search came up empty. Any ideas? Thanks!

    Read the article

  • How do I go about overloading C++ operators to allow for chaining?

    - by fneep
    I, like so many programmers before me, am tearing my hair out writing the right-of-passage-matrix-class-in-C++. I have never done very serious operator overloading and this is causing issues. Essentially, by stepping through This is what I call to cause the problems. cMatrix Kev = CT::cMatrix::GetUnitMatrix(4, true); Kev *= 4.0f; cMatrix Baz = Kev; Kev = Kev+Baz; //HERE! What seems to be happening according to the debugger is that Kev and Baz are added but then the value is lost and when it comes to reassigning to Kev, the memory is just its default dodgy values. How do I overload my operators to allow for this statement? My (stripped down) code is below. //header class cMatrix { private: float* _internal; UInt32 _r; UInt32 _c; bool _zeroindexed; //fast, assumes zero index, no safety checks float cMatrix::_getelement(UInt32 r, UInt32 c) { return _internal[(r*this->_c)+c]; } void cMatrix::_setelement(UInt32 r, UInt32 c, float Value) { _internal[(r*this->_c)+c] = Value; } public: cMatrix(UInt32 r, UInt32 c, bool IsZeroIndexed); cMatrix( cMatrix& m); ~cMatrix(void); //operators cMatrix& operator + (cMatrix m); cMatrix& operator += (cMatrix m); cMatrix& operator = (const cMatrix &m); }; //stripped source file cMatrix::cMatrix(cMatrix& m) { _r = m._r; _c = m._c; _zeroindexed = m._zeroindexed; _internal = new float[_r*_c]; UInt32 size = GetElementCount(); for (UInt32 i = 0; i < size; i++) { _internal[i] = m._internal[i]; } } cMatrix::~cMatrix(void) { delete[] _internal; } cMatrix& cMatrix::operator+(cMatrix m) { return cMatrix(*this) += m; } cMatrix& cMatrix::operator*(float f) { return cMatrix(*this) *= f; } cMatrix& cMatrix::operator*=(float f) { UInt32 size = GetElementCount(); for (UInt32 i = 0; i < size; i++) { _internal[i] *= f; } return *this; } cMatrix& cMatrix::operator+=(cMatrix m) { if (_c != m._c || _r != m._r) { throw new cCTException("Cannot add two matrix classes of different sizes."); } if (!(_zeroindexed && m._zeroindexed)) { throw new cCTException("Zero-Indexed mismatch."); } for (UInt32 row = 0; row < _r; row++) { for (UInt32 column = 0; column < _c; column++) { float Current = _getelement(row, column) + m._getelement(row, column); _setelement(row, column, Current); } } return *this; } cMatrix& cMatrix::operator=(const cMatrix &m) { if (this != &m) { _r = m._r; _c = m._c; _zeroindexed = m._zeroindexed; delete[] _internal; _internal = new float[_r*_c]; UInt32 size = GetElementCount(); for (UInt32 i = 0; i < size; i++) { _internal[i] = m._internal[i]; } } return *this; }

    Read the article

  • docs/examples on libxml2 type system?

    - by Wang
    I'm reading through the libxml2 API and examples on xmlsoft.com and having some real difficulty wrapping my head around the type system. For example, the _xmlAttribute struct has an xmlChar* field called name. This obviously refers to the name of the attribute (e.g., "bar" for the struct tied to the element <foo bar='baz' />). The _xmlAttribute struct also has a field called value, which I would expect to be "baz", except the type is xmlNodePtr. Um, what? I guess I could write up some test code and examine the memory in gdb, but there has to be an easier way. Has anyone written up examples of the data structures generated by a libxml2 parser? I'm looking for an English prose text, not generated documentation, that will walk me through the various types and the values they take when parsing some example bit of XML. Bonus points if it presents only the subset of libxml2 needed to read and write a config file---no namespaces or XPath or even modifying an existing document, just parse some XML, access the data, and then write it out again.

    Read the article

  • Reloading Sinatra app on every request on Windows

    - by Darth
    I've set up Rack::Reload according to this thread # config.ru require 'rubygems' require 'sinatra' set :environment, :development require 'app' run Sinatra::Application # app.rb class Sinatra::Reloader < Rack::Reloader def safe_load(file, mtime, stderr = $stderr) if file == Sinatra::Application.app_file ::Sinatra::Application.reset! stderr.puts "#{self.class}: reseting routes" end super end end configure(:development) { use Sinatra::Reloader } get '/' do 'foo' end Running with thin via thin start -R config.ru, but it only reloads newly added routes. When I change already existing route, it still runs the old code. When I add new route, it correctly reloads it, so it is accessible, but it doesn't reload anything else. For example, if I changed routes to get '/' do 'bar' end get '/foo' do 'baz' end Than / would still serve foo, even though it has changed, but /foo would correctly reload and serve baz. Is this normal behavior, or am I missing something? I'd expect whole source file to be reloaded. The only way around I can think of right now is restarting whole webserver when filesystem changes. I'm running on Windows Vista x64, so I can't use shotgun because of fork().

    Read the article

  • Apache and backslashes in mod_rewrite

    - by NuCalTone
    I want to process all incoming requests through a single script (index.php in web-root). So, the following is what currently happens: http://localhost/foo/bar/baz Is routed by Apache (through .htaccess) to: http://localhost/index.php?url=foo/bar/baz This works well, however, in Firefox I am able to do this: http://localhost/foo\ - notice the backslash. And Apache, instead of doing: /index.php?url=foo\ Emits a generic error page saying: Object not found! The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again. If you think this is a server error, please contact the webmaster. Error 404 localhost Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1 Directly going to: http://localhost/index.php?url=foo\ works without issues, however. All the sites that I've seen on the internet seem to be able to handle backslashes gracefully (e.g., http://stackoverflow.com/tags/php\\\\\). I consider this behavior a bug and I want to force Apache to forward backslashes correctly. Here's my .htaccess file in its entirety: RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.php?url=$1 [L] How can I make this work properly?

    Read the article

  • Using cellUpdateEvent with YUI DataTable and JSON DataSource

    - by Rob Hruska
    I'm working with a UI that has a (YUI2) JSON DataSource that's being used to populate a DataTable. What I would like to do is, when a value in the table gets updated, perform a simple animation on the cell whose value changed. Here are some relevant snippets of code: var columns = [ {key: 'foo'}, {key: 'bar'}, {key: 'baz'} ]; var dataSource = new YAHOO.util.DataSource('/someUrl'); dataSource.responseType = YAHOO.util.DataSource.TYPE_JSON; dataSource.connXhrMode = 'queueRequests'; dataSource.responseSchema = { resultsList: 'results', fields: [ {key: 'foo'}, {key: 'bar'}, {key: 'baz'} ] }; var dataTable = new YAHOO.widget.DataTable('container', columns, dataSource); var callback = function() { success: dataTable.onDataReturnReplaceRows, failure: function() { // error handling code }, scope: dataTable }; dataSource.setInterval(1000, null, callback); And here's what I'd like to do with it: dataTable.subscribe('cellUpdateEvent', function(record, column, oldData) { var td = dataTable.getTdEl({record: record, column: column}); YAHOO.util.Dom.setStyle(td, 'backgroundColor', '#ffff00'); var animation = new YAHOO.util.ColorAnim(td, { backgroundColor: { to: '#ffffff'; } }); animation.animate(); }; However, it doesn't seem like using cellUpdateEvent works. Does a cell that's updated as a result of the setInterval callback even fire a cellUpdateEvent? It may be that I don't fully understand what's going on under the hood with DataTable. Perhaps the whole table is being redrawn every time the data is queried, so it doesn't know or care about changes to individual cells?. Is the solution to write my own specific function to replace onDataReturnReplaceRows? Could someone enlighten me on how I might go about accomplishing this? Edit: After digging through datatable-debug.js, it looks like onDataReturnReplaceRows won't fire the cellUpdateEvent. It calls reset() on the RecordSet that's backing the DataTable, which deletes all of the rows; it then re-populates the table with fresh data. I tried changing it to use onDataReturnUpdateRows, but that doesn't seem to work either.

    Read the article

  • Why can't I use WCF DataContract and ISerializable on the same class?

    - by Dave
    Hi all, I have a class that I need to be able to serialize to a SQLServer session variable and be available over a WCF Service. I have declared it as follows namespace MyNM { [Serializable] [DataContract(Name = "Foo", Namespace = "http://www.mydomain.co.uk")] public class Foo : IEntity, ISafeCopy<Foo> { [DataMember(Order = 0)] public virtual Guid Id { get; set; } [DataMember(Order = 1)] public virtual string a { get; set; } DataMember(Order = 2)] public virtual Bar c { get; set; } /* ISafeCopy implementation */ } [Serializable] [DataContract(Name = "Bar ", Namespace = "http://www.mydomain.co.uk")] public class Bar : IEntity, ISafeCopy<Bar> { #region Implementation of IEntity DataMember(Order = 0)] public virtual Guid Id { get; set; } [DataMember(Order = 1)] public virtual Baz y { get; set; } #endregion /* ISafeCopy implementation*/ } [Serializable] [DataContract] public enum Baz { [EnumMember(Value = "one")] one, [EnumMember(Value = "two")] two, [EnumMember(Value = "three")] three } But when I try and call this service, I get the following error in the trace log. "System.Runtime.Serialization.InvalidDataContractException: Type 'BarProxybcb100e8617f40ceaa832fe4bb94533c' cannot be ISerializable and have DataContractAttribute attribute." If I take out the Serializable attribute, the WCF service works, but when the object can't be serialized to session. If I remove the DataContract attribute from class Bar, the WCF service fails saying Type 'BarProxy3bb05a31167f4ba492909ec941a54533' with data contract name 'BarProxy3bb05a31167f4ba492909ec941a54533:http://schemas.datacontract.org/2004/07/' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer I've tried adding a KnownType attribute to the foo class [KnownType(typeof(Bar))] But I still get the same error. Can anyone help me out with this? Many thanks Dave

    Read the article

  • When does invoking a member function on a null instance result in undefined behavior?

    - by GMan
    This question arose in the comments of a now-deleted answer to this other question. Our question was asked in the comments by STingRaySC as: Where exactly do we invoke UB? Is it calling a member function through an invalid pointer? Or is it calling a member function that accesses member data through an invalid pointer? With the answer deleted I figured we might as well make it it's own question. Consider the following code: #include <iostream> struct foo { void bar(void) { std::cout << "gman was here" << std::endl; } void baz(void) { x = 5; } int x; }; int main(void) { foo* f = 0; f->bar(); // (a) f->baz(); // (b) } We expect (b) to crash, because there is no corresponding member x for the null pointer. In practice, (a) doesn't crash because the this pointer is never used. Because (b) dereferences the this pointer (this->x = 5;), and this is null, the program enters undefined behavior. Does (a) result in undefined behavior? What about if both functions are static?

    Read the article

  • loops and conditionals inside triggers

    - by Ying
    I have this piece of logic I would like to implement as a trigger, but I have no idea how to do it! I want to create a trigger that, when a row is deleted, it checks to see if the value of one of its columns exists in another table, and if it does, it should also perform a delete on another table based on another column. So say we had a table Foo that has columns Bar, Baz. This is what id be doing if i did not use a trigger: function deleteFromFooTable(FooId) { SELECT (Bar,Baz) FROM FooTable WHERE id=FooId if not-empty(SELECT * FROM BazTable WHERE id=BazId) DELETE FROM BarTable WHERE id=BarId DELETE FROM FooTable WHERE id=FooId } I jumped some hoops in that pseudo code, but i hope you all get where im going. It seems what i would need is a way to do conditionals and to loop(in case of multiple row deletes?) in the trigger statement. So far, I haven't been able to find anything. Is this not possible, or is this bad practice? Thanks!

    Read the article

  • Is Perl's flip-flop operator bugged? It has global state, how can I reset it?

    - by Evan Carroll
    I'm dismayed. Ok, so this was probably the most fun perl bug I've ever found. Even today I'm learning new stuff about perl. Essentially, the flip-flop operator .. which returns false until the left-hand-side returns true, and then true until the right-hand-side returns false keep global state (or that is what I assume.) My question is can I reset it, (perhaps this would be a good addition to perl4-esque hardly ever used reset())? Or, is there no way to use this operator safely? I also don't see this (the global context bit) documented anywhere in perldoc perlop is this a mistake? Code use feature ':5.10'; use strict; use warnings; sub search { my $arr = shift; grep { !( /start/ .. /never_exist/ ) } @$arr; } my @foo = qw/foo bar start baz end quz quz/; my @bar = qw/foo bar start baz end quz quz/; say 'first shot - foo'; say for search \@foo; say 'second shot - bar'; say for search \@bar; Spoiler $ perl test.pl first shot foo bar second shot

    Read the article

  • Saving multiple objects in a single call in rails

    - by CaptnCraig
    I have a method in rails that is doing something like this: a = Foo.new("bar") a.save b = Foo.new("baz") b.save ... x = Foo.new("123", :parent_id => a.id) x.save ... z = Foo.new("zxy", :parent_id => b.id) z.save The problem is this takes longer and longer the more entities I add. I suspect this is because it has to hit the database for every record. Since they are nested, I know I can't save the children before the parents are saved, but I would like to save all of the parents at once, and then all of the children. It would be nice to do something like: a = Foo.new("bar") b = Foo.new("baz") ... saveall(a,b,...) x = Foo.new("123", :parent_id => a.id) ... z = Foo.new("zxy", :parent_id => b.id) saveall(x,...,z) That would do it all in only two database hits. Is there an easy way to do this in rails, or am I stuck doing it one at a time?

    Read the article

  • Reading text files line by line, with exact offset/position reporting

    - by Benjamin Podszun
    Hi. My simple requirement: Reading a huge ( a million) line test file (For this example assume it's a CSV of some sorts) and keeping a reference to the beginning of that line for faster lookup in the future (read a line, starting at X). I tried the naive and easy way first, using a StreamWriter and accessing the underlying BaseStream.Position. Unfortunately that doesn't work as I intended: Given a file containing the following Foo Bar Baz Bla Fasel and this very simple code using (var sr = new StreamReader(@"C:\Temp\LineTest.txt")) { string line; long pos = sr.BaseStream.Position; while ((line = sr.ReadLine()) != null) { Console.Write("{0:d3} ", pos); Console.WriteLine(line); pos = sr.BaseStream.Position; } } the output is: 000 Foo 025 Bar 025 Baz 025 Bla 025 Fasel I can imagine that the stream is trying to be helpful/efficient and probably reads in (big) chunks whenever new data is necessary. For me this is bad.. The question, finally: Any way to get the (byte, char) offset while reading a file line by line without using a basic Stream and messing with \r \n \r\n and string encoding etc. manually? Not a big deal, really, I just don't like to build things that might exist already..

    Read the article

  • ArrayAccess multidimensional (un)set?

    - by anomareh
    I have a class implementing ArrayAccess and I'm trying to get it to work with a multidimensional array. exists and get work. set and unset are giving me a problem though. class ArrayTest implements ArrayAccess { private $_arr = array( 'test' => array( 'bar' => 1, 'baz' => 2 ) ); public function offsetExists($name) { return isset($this->_arr[$name]); } public function offsetSet($name, $value) { $this->_arr[$name] = $value; } public function offsetGet($name) { return $this->_arr[$name]; } public function offsetUnset($name) { unset($this->_arr[$name]); } } $arrTest = new ArrayTest(); isset($arrTest['test']['bar']); // Returns TRUE echo $arrTest['test']['baz']; // Echo's 2 unset($arrTest['test']['bar']; // Error $arrTest['test']['bar'] = 5; // Error I know $_arr could just be made public so you could access it directly, but for my implementation it's not desired and is private. The last 2 lines throw an error: Notice: Indirect modification of overloaded element. I know ArrayAccess just generally doesn't work with multidimensional arrays, but is there anyway around this or any somewhat clean implementation that will allow the desired functionality? The best idea I could come up with is using a character as a separator and testing for it in set and unset and acting accordingly. Though this gets really ugly really fast if you're dealing with a variable depth. Does anyone know why exists and get work so as to maybe copy over the functionality? Thanks for any help anyone can offer.

    Read the article

  • SQL Design: representing a default value with overrides?

    - by Mark Harrison
    I need a sparse table which contains a set of "override" values for another table. I also need to specify the default value for the items overridden. For example, if the default value is 17, then foo,bar,baz will have the values 17,21,17: table "things" table "xvalue" name stuff name xval ---- ----- ---- ---- foo ... bar 21 bar ... baz ... If I don't care about a FK from xvalue.name - things.name, I could simply put a "DEFAULT" name: table "xvalue" name xval ---- ---- DEFAULT 17 bar 21 But I like having a FK. I could have a separate default table, but it seems odd to have 2x the number of tables. table "xvalue_default" xval ---- 17 table "xvalue" name xval ---- ---- bar 21 I could have a "defaults table" tablename attributename defaultvalue xvalue xval 17 but then I run into type issues on defaultvalue. My operations guys prefer as compact a representation as possible, so they can most easily see the "diff" or deviations from the default. What's the best way to represent this, including the default value? This will be for Oracle 10.2 if that makes a difference.

    Read the article

  • Py_INCREF/DECREF: When

    - by Izz ad-Din Ruhulessin
    Is one correct in stating the following: If a Python object is created in a C function, but the function doesn't return it, no INCREF is needed, but a DECREF is. [false]If the function does return it, you do need to INCREF, in the function that receives the return value.[/false] When assigning C typed variables as attributes, like double, int etc., to the Python object, no INCREF or DECREF is needed. Assigning Python objects as attributes to your other Python objects goes like this: PyObject *foo; foo = bar // A Python object tmp = self->foo; Py_INCREF(foo); self->foo = foo; Py_XDECREF(tmp); //taken from the manual, but it is unclear if this works in every situation EDIT: -- can I safely use this in every situation? (haven't run into one where it caused me problems) dealloc of a Python object needs to DECREF for every other Python object that it has as an attribute, but not for attributes that are C types. Edit With 'C type as an attribute I mean bar and baz: typedef struct { PyObject_HEAD PyObject *foo; int bar; double baz; } FooBarBaz;

    Read the article

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