Search Results

Search found 214 results on 9 pages for 'tuples'.

Page 6/9 | < Previous Page | 2 3 4 5 6 7 8 9  | Next Page >

  • Export list as .txt (Python)

    - by Nimbuz
    My Python module has a list that contains all the data I want to save as a .txt file somewhere. The list contains several tuples like so: list = [ ('one', 'two', 'three'), ('four', 'five', 'six')] How do I print the list so each tuple item is separated by a tab and each tuple is separated by a newline? Thanks

    Read the article

  • can i use MAX function for each tuple in the retrieved data set

    - by kshama
    Hi, My table result contains fields: id count ____________ 1 3 2 2 3 2 From this table i have to form another table **score** which should look as follows id my_score ___________ 1 1.0000 2 0.6667 3 0.6667 That is my_score=count/MAX(count) but if i give the query as create TEMPORARY TABLE(select id,(count/MAX(count)) AS my_score from result); only 1 st row is retrieved.Can any one suggest the query so that my_score is calculated for all tuples. Thanks in advance.

    Read the article

  • maintaing a sorted list that is bigger than memory

    - by tcurdt
    I have a list of tuples. [ "Bob": 3, "Alice: 2, "Jane": 1, ] When incrementing the counts "Alice" += 2 the order should be maintained: [ "Alice: 4, "Bob": 3, "Jane": 1, ] When all is in memory there rather simple ways (some more or some less) to efficiently implement this. (using an index, insert-sort etc) The question though is: What's the most promising approach when the list does not fit into memory. Bonus question: What if not even the index fits into memory? How would you approach this?

    Read the article

  • List multiplication

    - by Schitti
    Hi, Python newbie here. I have a list L = [a, b, c] and I want to generate a list of tuples : [(a,a), (a,b), (a,c), (b,a), (b,b), (b,c)...] I tried doing L * L but it didn't work. Can someone tell me how to get this in python.

    Read the article

  • HTML tags in mysql text field

    - by paracaudex
    I'm creating a database with what I anticipate will be a long (perhaps several paragraphs for some tuples) attribute. I'm assigning it text instead of varchar. I have two questions: Should I give a maximum value for the text field? Is this necessary? Is it useful? Since the contents of this field will be displayed on a website in HTML, do I need to include paragraph tags for paragraph formatting when I enter records into mysql?

    Read the article

  • Matrix in python

    - by Werner
    Hi, I am very new to Python, I need to read numbers from a file and store them in a matrix like I would do it in fortran or C; for i for j data[i][j][0]=read(0) data[i][j][1]=read(1) data[i][j][2]=read(2) ... ... How can I do the same in Python? I read a bit but got confused with tuples and similar things If you could point me to a similar example it would be great thanks

    Read the article

  • How to pick a chunksize for python multiprocessing with large datasets

    - by Sandro
    I am attempting to to use python to gain some performance on a task that can be highly parallelized using http://docs.python.org/library/multiprocessing. When looking at their library they say to use chunk size for very long iterables. Now, my iterable is not long, one of the dicts that it contains is huge: ~100000 entries, with tuples as keys and numpy arrays for values. How would I set the chunksize to handle this and how can I transfer this data quickly? Thank you.

    Read the article

  • Numpy Matrix keeps giving me an Error,

    - by uberjumper
    Okay this is werid, i keep getting the error, randomly. ValueError: matrix must be 2-dimensional So i tracked it down, and cornered it to basically something like this: a_list = [[(1,100) for _ in range(32)] for _ in range(32)] numpy.matrix(a_list) Whats wrong with this? If i print a_list it is clearly a 2d matrix of tuples, however numpy does not believe so.

    Read the article

  • GHC.Generics and Type Families

    - by jberryman
    This is a question related to my module here, and is simplified a bit. It's also related to this previous question, in which I oversimplified my problem and didn't get the answer I was looking for. I hope this isn't too specific, and please change the title if you can think if a better one. Background My module uses a concurrent chan, split into a read side and write side. I use a special class with an associated type synonym to support polymorphic channel "joins": {-# LANGUAGE TypeFamilies #-} class Sources s where type Joined s newJoinedChan :: IO (s, Messages (Joined s)) -- NOT EXPORTED --output and input sides of channel: data Messages a -- NOT EXPORTED data Mailbox a instance Sources (Mailbox a) where type Joined (Mailbox a) = a newJoinedChan = undefined instance (Sources a, Sources b)=> Sources (a,b) where type Joined (a,b) = (Joined a, Joined b) newJoinedChan = undefined -- and so on for tuples of 3,4,5... The code above allows us to do this kind of thing: example = do (mb , msgsA) <- newJoinedChan ((mb1, mb2), msgsB) <- newJoinedChan --say that: msgsA, msgsB :: Messages (Int,Int) --and: mb :: Mailbox (Int,Int) -- mb1,mb2 :: Mailbox Int We have a recursive action called a Behavior that we can run on the messages we pull out of the "read" end of the channel: newtype Behavior a = Behavior (a -> IO (Behavior a)) runBehaviorOn :: Behavior a -> Messages a -> IO () -- NOT EXPORTED This would allow us to run a Behavior (Int,Int) on either of msgsA or msgsB, where in the second case both Ints in the tuple it receives actually came through separate Mailboxes. This is all tied together for the user in the exposed spawn function spawn :: (Sources s) => Behavior (Joined s) -> IO s ...which calls newJoinedChan and runBehaviorOn, and returns the input Sources. What I'd like to do I'd like users to be able to create a Behavior of arbitrary product type (not just tuples) , so for instance we could run a Behavior (Pair Int Int) on the example Messages above. I'd like to do this with GHC.Generics while still having a polymorphic Sources, but can't manage to make it work. spawn :: (Sources s, Generic (Joined s), Rep (Joined s) ~ ??) => Behavior (Joined s) -> IO s The parts of the above example that are actually exposed in the API are the fst of the newJoinedChan action, and Behaviors, so an acceptable solution can modify one or all of runBehaviorOn or the snd of newJoinedChan. I'll also be extending the API above to support sums (not implemented yet) like Behavior (Either a b) so I hoped GHC.Generics would work for me. Questions Is there a way I can extend the API above to support arbitrary Generic a=> Behavior a? If not using GHC's Generics, are there other ways I can get the API I want with minimal end-user pain (i.e. they just have to add a deriving clause to their type)?

    Read the article

  • Python: concatenate generator and item

    - by TarGz
    I have a generator (numbers) and a value (number). I would like to iterate over these as if they were one sequence: i for i in tuple(my_generator) + (my_value,) The problem is, as far as I undestand, this creates 3 tuples only to immediately discard them and also copies items in "my_generator" once. Better approch would be: def con(seq, item): for i in seq: yield seq yield item i for i in con(my_generator, my_value) But I was wondering whether it is possible to do it without that function definition

    Read the article

  • How can I add a function reference to an object literal

    - by rob
    I need to add binders to DOM elements after rendering is done. Therefore I want to pass a list with (ID, callback) tuples to the rendering function so it can bind it after the rendering is done. So i would like to create a list of such objects and pass it to the rendering function: {id:'#someDOMelement', callback: someObject.someFunction} and bind it after the rendering like this: $(binders[i].id).bind('click', binders[i].callback);

    Read the article

  • Scientific Plotting in Python

    - by user100046
    I have a large data set of tuples containing (time of event, latitude, longitude) that I need to visualize. I was hoping to generate a 'movie'-like xy-plot, but was wondering if anyone has a better idea or if there is an easy way to do this in Python? Thanks in advance for the help, --Leo

    Read the article

  • Postgres 9.0 locking up, 100% CPU

    - by Jake
    We are having a problem where our Postgres 9.0 server occasionally locks up and kills our webapp. Restarting Postgres fixes the problem. Here's what I've been able to observe: First, usage of one CPU jumps to 100% for a few minutes Disk operations drop to ~0 during this time Database operations drop to 0 (blocks and tuples per sec) Logs show during this time: WARNING: worker took too long to start; cancelled WARNING: worker took too long to start; cancelled No Queries in logs (only those over 200ms are logged) No unusually long-running queries logged before or during Then the second CPU jumps to 100% The number of postgres processes jumps from the usual 8-10 to ~20 Matched by a spike in Postgres Blocks per second (about twice normal) Logs show LOG: could not accept SSL connection: EOF detected Queries are running but slow Restarting postgres returns everything to normal Setup: Server: Amazon EC2 Large Ubuntu 10.04.2 LTS Postgres 9.0.3 Dedicated DB server Does anyone have any idea what's causing this? Or any suggestions about what else I should be checking out?

    Read the article

  • Are there web search engines with exact match or regex capabilities (for related terms)?

    - by naxa
    Every once in a while I come upon a situation when google's way of searching results in too broad results even if I enclose my search terms in quotation marks. For example now I've tried to find pages that contain both "py.path" and "path.py" without much success. I'm currently aware of engines|sites like Google Code Search for searching actual code and (apparently) Stackoverflow for searching QAs, symbolhound that lets me find symbols, and also wikipedia is often a good place to find lists of symbols. But none of these seems to perform very good in matching exactly on search term pairs (or tuples) and use a broad-enough segment of the web. Is there a website that is good with exactly finding search term pairs? (Why not?)

    Read the article

  • Can I run into legal issues with random names?

    - by Nathan Sabruka
    I'm currently building a game whose NPC's are going to be assigned a random gender and a random name for the right gender. To do this I will be using a "database" of names (actually a text file with tuples). There would also be a list of last names, which will be added to the first name also randomly. My question is the following. Suppose one such random name is "George Bush", and this person has been randomly assigned the job of president. As you can see, this could easily be seen as having been "copied" from a real-life person. The main issue is this. Names will be randomly-generated, yes, but the seed for random-number generation will be constant. In other words, the name of an NPC would be randomly-generated, i.e. I wouldn't choose it, but it would be the same for every player. Could this get me in trouble? We cannot verify all possible names, since the generated number of NPC's could be potentially limitless (new NPC's are being created whenever needed).

    Read the article

  • Do you think Scala will be the dominant JVM langauge, ie be the next Java? [on hold]

    - by user1037729
    From what I've read about Scala do far I think it has some nice features but I do not think it should be "the next Java". It might however end up being the next Java (due to fashion rather than fact) but lets not hope it does not... To me adds a lot of complexity over Java which is a simple and scalable language. Scala Pattern matching allows you to perform some type/value checking in a more concise way, this is possible in Java, Scala's pattern matching has a limit to it, you cannot continuously match deeper and deeper down the object graph, so why not just stick to Java and use decent invariants? Scala provides tuples, easy enough to make in Java, create a static factory method and it all reads nicely too. Scala provides mixins, why not just use composition? I believe Scala implicit's are bad, they can lead to code becoming complex and hard to maintain, explicitness is good. Scala provides closures, well they will be in Java 8 too. Scala has lazy keyword for lazy instantiation, this is easy enough to do in Java by calling a getter which creates the instance when needed, no hidden magic here. Scala can be used with AKKA, well so can Java, there is an Java AKKA implementation. Scala offers addition functional features but these can all be created in Java, there are many frameworks with have implemented functional features in Java. All in all Scala seems to offer is addition complexity and thats it...

    Read the article

  • django - dynamic form fieldsets

    - by user110029
    A form will be spitting out an unknown number of questions to be answered. each question contains a prompt, a value field, and a unit field. The form is built at runtime in the formclass's init method. I'd like each question rendered on the form as an inline: prompt, value(input-text), units (select). this seems a case perfect for iterable form fieldsets, which could be easily styled. but since fieldsets - such as those in django-form-utils are defined as tuples, they are immutable... and I can't find a way to define them at runtime. is this possible, or perhaps another solution?

    Read the article

  • Ruby for Rails: underfined method 'name ' for #<Array:0xb6c971cc>

    - by erwin
    Hi, I want to display the column 'name' after being found from the table mytest. In the mytest.rb, I defined "attrib_accessor :name"; In the procedure index under directory /controller/mytest_controller.rb, def index .....###[Ignore some code] @[email protected]_by_id ### I am able to verify the tuples in @mytesttbl end In the /view/mytest/index.rhtml, I have code like "mytesttbl", :object = @mytesttbl)% In the /view/mytest/_mytesttbl.html.erb. I have code like <%=mytesttbl.name % when I ran the above code, I have error on _mytesttbl.html.erb, underfined method 'name ' for # Please help. Thanks,

    Read the article

  • Python + MySQLdb executemany

    - by lhahne
    I'm using Python and its MySQLdb module to import some measurement data into a Mysql database. The amount of data that we have is quite high (currently about ~250 MB of csv files and plenty of more to come). Currently I use cursor.execute(...) to import some metadata. This isn't problematic as there are only a few entries for these. The problem is that when I try to use cursor.executemany() to import larger quantities of the actual measurement data, MySQLdb raises a TypeError: not all arguments converted during string formatting My current code is def __insert_values(self, values): cursor = self.connection.cursor() cursor.executemany(""" insert into values (ensg, value, sampleid) values (%s, %s, %s)""", values) cursor.close() where values is a list of tuples containing three strings each. Any ideas what could be wrong with this? Edit: The values are generated by yield (prefix + row['id'], row['value'], sample_id) and then read into a list one thousand at a time where row is and iterator coming from csv.DictReader.

    Read the article

  • Does throwing an exception in an EvalFunc pig UDF skip just that line, or stop completely?

    - by Daniel Huckstep
    I have a User Defined Function (UDF) written in Java to parse lines in a log file and return information back to pig, so it can do all the processing. It looks something like this: public abstract class Foo extends EvalFunc<Tuple> { public Foo() { super(); } public Tuple exec(Tuple input) throws IOException { try { // do stuff with input } catch (Exception e) { throw WrappedIOException.wrap("Error with line", e); } } } My question is: if it throws the IOException, will it stop completely, or will it return results for the rest of the lines that don't throw an exception? Example: I run this in pig REGISTER myjar.jar DEFINE Extractor com.namespace.Extractor(); logs = LOAD '$IN' USING TextLoader AS (line: chararray); events = FOREACH logs GENERATE FLATTEN(Extractor(line)); With this input: 1.5 7 "Valid Line" 1.3 gghyhtt Inv"alid line"" I throw an exceptioN!! 1.8 10 "Valid Line 2" Will it process the two lines and will 'logs' have 2 tuples, or will it just die in a fire?

    Read the article

  • Python hashable dicts

    - by TokenMacGuy
    As an exercise, and mostly for my own amusement, I'm implementing a backtracking packrat parser. The inspiration for this is i'd like to have a better idea about how hygenic macros would work in an algol-like language (as apposed to the syntax free lisp dialects you normally find them in). Because of this, different passes through the input might see different grammars, so cached parse results are invalid, unless I also store the current version of the grammar along with the cached parse results. (EDIT: a consequence of this use of key-value collections is that they should be immutable, but I don't intend to expose the interface to allow them to be changed, so either mutable or immutable collections are fine) The problem is that python dicts cannot appear as keys to other dicts. Even using a tuple (as I'd be doing anyways) doesn't help. >>> cache = {} >>> rule = {"foo":"bar"} >>> cache[(rule, "baz")] = "quux" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'dict' >>> I guess it has to be tuples all the way down. Now the python standard library provides approximately what i'd need, collections.namedtuple has a very different syntax, but can be used as a key. continuing from above session: >>> from collections import namedtuple >>> Rule = namedtuple("Rule",rule.keys()) >>> cache[(Rule(**rule), "baz")] = "quux" >>> cache {(Rule(foo='bar'), 'baz'): 'quux'} Ok. But I have to make a class for each possible combination of keys in the rule I would want to use, which isn't so bad, because each parse rule knows exactly what parameters it uses, so that class can be defined at the same time as the function that parses the rule. But combining the rules together is much more dynamic. In particular, I'd like a simple way to have rules override other rules, but collections.namedtuple has no analogue to dict.update(). Edit: An additional problem with namedtuples is that they are strictly positional. Two tuples that look like they should be different can in fact be the same: >>> you = namedtuple("foo",["bar","baz"]) >>> me = namedtuple("foo",["bar","quux"]) >>> you(bar=1,baz=2) == me(bar=1,quux=2) True >>> bob = namedtuple("foo",["baz","bar"]) >>> you(bar=1,baz=2) == bob(bar=1,baz=2) False tl'dr: How do I get dicts that can be used as keys to other dicts? Having hacked a bit on the answers, here's the more complete solution I'm using. Note that this does a bit extra work to make the resulting dicts vaguely immutable for practical purposes. Of course it's still quite easy to hack around it by calling dict.__setitem__(instance, key, value) but we're all adults here. class hashdict(dict): """ hashable dict implementation, suitable for use as a key into other dicts. >>> h1 = hashdict({"apples": 1, "bananas":2}) >>> h2 = hashdict({"bananas": 3, "mangoes": 5}) >>> h1+h2 hashdict(apples=1, bananas=3, mangoes=5) >>> d1 = {} >>> d1[h1] = "salad" >>> d1[h1] 'salad' >>> d1[h2] Traceback (most recent call last): ... KeyError: hashdict(bananas=3, mangoes=5) based on answers from http://stackoverflow.com/questions/1151658/python-hashable-dicts """ def __key(self): return tuple(sorted(self.items())) def __repr__(self): return "{0}({1})".format(self.__class__.__name__, ", ".join("{0}={1}".format( str(i[0]),repr(i[1])) for i in self.__key())) def __hash__(self): return hash(self.__key()) def __setitem__(self, key, value): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def __delitem__(self, key): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def clear(self): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def pop(self, *args, **kwargs): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def popitem(self, *args, **kwargs): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def setdefault(self, *args, **kwargs): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def update(self, *args, **kwargs): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def __add__(self, right): result = hashdict(self) dict.update(result, right) return result if __name__ == "__main__": import doctest doctest.testmod()

    Read the article

  • Erlang code critique

    - by dagda1
    Hi, I am trying to get my head round some basic erlang functionality and I could do with some comments on the following. I have the following erlang code that takes a list of tuples and returns a list minus an element if a key is found: delete(Key, Database) -> remove(Database, Key, []). remove([], Key, Acc) -> Acc; remove([H|T], Key, Acc) -> if element(1, H) /= Key -> [H| remove(T, Key, Acc)]; true -> remove(T, Key, Acc) end. Is this a good way of doing this? The if statement seems incorrect. Also is my use of the accumulator Acc making this tail recursive? Cheers Paul

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9  | Next Page >