code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
try: dss = {} unique = self.df[col].unique() for key in unique: df2 = self.df.loc[self.df[col] == key] ds2 = self._duplicate_(df2) dss[key] = ds2 return dss except Exception as e: self.er...
def split_(self, col: str) -> "list(Ds)"
Split the main dataframe according to a column's unique values and return a dict of dataswim instances :return: list of dataswim instances :rtype: list(Ds) :example: ``dss = ds.slit_("Col 1")``
3.578983
3.693769
0.968924
try: df = pd.merge(self.df, df, on=on, how=how, **kwargs) self.df = df except Exception as e: self.err(e, self.merge, "Can not merge dataframes")
def merge(self, df: pd.DataFrame, on: str, how: str="outer", **kwargs)
Set the main dataframe from the current dataframe and the passed dataframe :param df: the pandas dataframe to merge :type df: pd.DataFrame :param on: param for ``pd.merge`` :type on: str :param how: param for ``pd.merge``, defaults to "outer" :type how: str, opti...
3.54388
3.65328
0.970054
query = urllib.urlencode(options) url = "caches" if query != "": url = "%s?%s" % (url, query) result = self.client.get(url) return [cache["name"] for cache in result["body"]]
def caches(self, options={})
Query the server for a list of caches, parse the JSON response, and return the result. Keyword arguments: options -- a dict of arguments to send with the request. See http://dev.iron.io/cache/reference/api/#list_caches for more information on defaults and p...
3.750309
3.83962
0.976739
if cache is None: cache = self.name if cache is None: raise ValueError("Cache name must be set") cache = quote_plus(cache) key = quote_plus(key) url = "caches/%s/items/%s" % (cache, key) result = self.client.get(url) return Item(va...
def get(self, key, cache=None)
Query the server for an item, parse the JSON, and return the result. Keyword arguments: key -- the key of the item that you'd like to retrieve. Required. cache -- the name of the cache that the item resides in. Defaults to None, which uses self.name. If no name is set, raises a...
3.509435
3.326623
1.054954
if cache is None: cache = self.name if cache is None: raise ValueError("Cache name must be set") if not isinstance(value, str_type) and not isinstance(value, int_types): value = json.dumps(value) options["value"] = value body = json...
def put(self, key, value, cache=None, options={})
Query the server to set the key specified to the value specified in the specified cache. Keyword arguments: key -- the name of the key to be set. Required. value -- the value to set key to. Must be a string or JSON serialisable. Required. cache -- the cache to s...
3.087506
2.868146
1.076482
if cache is None: cache = self.name if cache is None: raise ValueError("Cache name must be set") cache = quote_plus(cache) key = quote_plus(key) self.client.delete("caches/%s/items/%s" % (cache, key)) return True
def delete(self, key, cache=None)
Query the server to delete the key specified from the cache specified. Keyword arguments: key -- the key the item is stored under. Required. cache -- the cache to delete the item from. Defaults to None, which uses self.name. If no name is set, raises a ValueError.
3.391823
3.142625
1.079296
if cache is None: cache = self.name if cache is None: raise ValueError("Cache name must be set") cache = quote_plus(cache) key = quote_plus(key) body = json.dumps({"amount": amount}) result = self.client.post("caches/%s/items/%s/incremen...
def increment(self, key, cache=None, amount=1)
Query the server to increment the value of the key by the specified amount. Negative amounts can be used to decrement. Keyword arguments: key -- the key the item is stored under. Required. cache -- the cache the item belongs to. Defaults to None, which uses self.name. I...
3.52034
3.336489
1.055103
amount = amount * -1 return self.increment(key=key, cache=cache, amount=amount)
def decrement(self, key, cache=None, amount=1)
A convenience function for passing negative values to increment. Keyword arguments: key -- the key the item is stored under. Required. cache -- the cache the item belongs to. Defaults to None, which uses self.name. If no name is set, raises a ValueError. amount -- the a...
4.767164
7.178379
0.6641
def getter(self): return klass(getattr(self._obj, key)) return property(getter)
def submodel(klass, key)
Shortcut for defining a submodel (has-a relation).
5.795178
8.679976
0.667649
lxml.etree.dump(self._obj, *args, **kwargs)
def dump(self, *args, **kwargs)
Dumps a representation of the Model on standard output.
8.468164
7.246749
1.168547
@classmethod def _namer(cls, imageUrl, pageUrl): url = pageUrl if usePageUrl else imageUrl return getQueryParams(url)[paramName][0] return _namer
def queryNamer(paramName, usePageUrl=False)
Get name from URL query part.
7.06276
6.417752
1.100504
@classmethod def _namer(cls, imageUrl, pageUrl): url = pageUrl if usePageUrl else imageUrl mo = regex.search(url) if mo: return mo.group(1) return _namer
def regexNamer(regex, usePageUrl=False)
Get name from regular expression.
4.511579
4.461484
1.011228
@classmethod def _starter(cls): data = cls.getPage(url) url1 = cls.fetchUrl(url, data, cls.prevSearch) data = cls.getPage(url1) return cls.fetchUrl(url1, data, nextSearch) return _starter
def bounceStarter(url, nextSearch)
Get start URL by "bouncing" back and forth one time.
5.498841
5.217295
1.053964
@classmethod def _starter(cls): data = cls.getPage(url) return cls.fetchUrl(url, data, latestSearch) return _starter
def indirectStarter(url, latestSearch)
Get start URL by indirection.
9.082171
9.121517
0.995686
return dict((item.domain, item.status) for item in self.check_domain_request(domains))
def check_many(self, domains)
Check availability for a number of domains. Returns a dictionary mapping the domain names to their statuses as a string ("active"/"free").
8.877674
7.718661
1.150157
request = E.checkDomainRequest( E.domains( E.array( *[E.item( E.name(domain.split(".")[0]), E.extension(domain.split(".")[1]) ) for domain in domains] ) ) ...
def check_domain_request(self, domains)
Return the availability of one or more domain names. The availability is a model containing a domain and a status. It can also have a premium attribute in case the domain has non-default costs.
3.906789
3.724575
1.048922
df = self._relation(table, origin_field, search_field, destination_field, id_field) self.df = df
def relation(self, table, origin_field, search_field, destination_field=None, id_field="id")
Add a column to the main dataframe from a relation foreign key
3.293955
2.953846
1.115141
df = self._relation(table, origin_field, search_field, destination_field, id_field) return self._duplicate_(df)
def relation_(self, table, origin_field, search_field, destination_field=None, id_field="id")
Returns a DataSwim instance with a column filled from a relation foreign key
4.912456
4.537725
1.082581
self.start("Processing relation", origin_field, "->", search_field) search_ds = self._duplicate_(db=self.db, quiet=True) search_ds.load(table) df = self.df.copy() if destination_field is None: destination_field = search_field df[des...
def _relation(self, table, origin_field, search_field, destination_field, id_field)
Add a column to the main dataframe from a relation foreign key
2.877208
2.861528
1.005479
with codecs.open(jsonFn(d), 'r', 'utf-8') as f: return json.load(f)
def loadJson(d)
Return JSON data.
3.909407
4.119465
0.949008
outDir = os.path.join(d, 'inorder') if not os.path.exists(outDir): os.mkdir(outDir) for f in os.listdir(outDir): f = os.path.join(outDir, f) if os.path.islink(f): os.remove(f) return outDir
def prepare_output(d)
Clean pre-existing links in output directory.
2.463823
2.325454
1.059502
data = loadJson(d) outDir = prepare_output(d) unseen = data["pages"].keys() while len(unseen) > 0: latest = work = unseen[0] while work in unseen: unseen.remove(work) if "prev" in data["pages"][work]: work = data["pages"][work]["prev"] pr...
def create_symlinks(d)
Create new symbolic links in output directory.
3.139583
3.107202
1.010422
if isinstance(source, str): return parse_stream(six.StringIO(source)) else: return parse_stream(source)
def parse(source)
Parses source code returns an array of instructions suitable for optimization and execution by a Machine. Args: source: A string or stream containing source code.
3.271288
4.305597
0.759776
code = [] for (line, col, (token, value)) in Tokenizer(stream).tokenize(): if token == Tokenizer.STRING: value = '"' + value + '"' code.append(value) return code
def parse_stream(stream)
Parse a Forth-like language and return code.
5.510781
4.539072
1.214077
try: return self.cache[var_name] except KeyError: try: var = self._resolve_var(var_name) except UnknownConfigVariable as e: if default is not _NONE: if callable(default): return defau...
def get_var(self, var_name: str, default: Optional[Any] = _NONE) -> Any
Get a config variable. If a variable is not set, a resolver is not set, and no default is given :class:`~haps.exceptions.UnknownConfigVariable` is raised. :param var_name: Name of variable :param default: Default value :return: Value of config variable
2.392862
2.175696
1.099815
def dec(f): if var_name in cls().resolvers: raise ConfigurationError( f'Resolver for {var_name} already registered') cls().resolvers[var_name] = f return f return dec
def resolver(cls, var_name: str) -> FunctionType
Variable resolver decorator. Function or method decorated with it is used to resolve the config variable. .. note:: Variable is resolved only once. Next gets are returned from the cache. :param var_name: Variable name :return: Function decorator
4.209821
5.052387
0.833234
cls.resolver(var_name)( partial( _env_resolver, var_name=var_name, env_name=env_name, default=default)) return cls()
def env_resolver(cls, var_name: str, env_name: str = None, default: Any = _NONE) -> 'Configuration'
Method for configuring environment resolver. :param var_name: Variable name :param env_name: An optional environment variable name. If not set\ haps looks for `HAPS_var_name` :param default: Default value for variable. If it's a callable,\ is called before return. If not...
4.459908
5.103022
0.873974
with cls._lock: if var_name not in cls().cache: cls().cache[var_name] = value else: raise ConfigurationError( f'Value for {var_name} already set') return cls()
def set(cls, var_name: str, value: Any) -> 'Configuration'
Set the variable :param var_name: Variable name :param value: Value of variable :return: :class:`~haps.config.Configuration` instance for easy\ chaining
3.340075
4.758979
0.701847
instance = self.model(**data) self.request.dbsession.add(instance) self.request.dbsession.flush() return instance
def perform_create(self, data)
Hook for controlling the creation of an model instance. Override this if you need to do more with your data before saving your object than just mapping the deserialized data to a new instance of ``self.model``.
3.477326
3.019562
1.1516
for key, val in data.items(): setattr(instance, key, val)
def perform_update(self, data, instance)
Hook for controlling the update of an model instance. Override this if you need to do more with your data before updating the object than just mapping the deserialized data to the attribute of the instance.
4.125906
3.613662
1.141752
for key, val in data.items(): setattr(instance, key, val)
def perform_partial_update(self, data, instance)
Hook for controlling the update of an model instance. Override this if you need to do more with your data before updating the object than just mapping the deserialized data to the attribute of the instance.
3.918256
3.472702
1.128302
try: xdata = list(self.df[xcol]) except Exception as e: self.err(e, self._get_chartjs_chart, "Can not get data for x field ", ycol) return if label is None: label = "Data" try: if type(ycol) != list...
def _get_chartjs_chart(self, xcol, ycol, chart_type, label=None, opts={}, style={}, options={}, **kwargs)
Get Chartjs html
2.347726
2.35974
0.994909
''' Login state. \b DOES: Display login email, token, server url. \b USE: wio state ''' user_token = wio.config.get("token", None) mserver_url = wio.config.get("mserver", None) if not mserver_url or not user_token: click.echo(click.style('>> ', fg='red')...
def cli(wio)
Login state. \b DOES: Display login email, token, server url. \b USE: wio state
2.660268
2.165758
1.228331
output = {} if isinstance(self.obj, dict): for name, item in self.obj.items(): if isinstance(item, dict): if item: output[name] = StrReprWrapper('{...}') else: output[name] = StrR...
def top_level(self)
Print just the top level of an object, being sure to show where it goes deeper
2.406095
2.22787
1.079998
push = lambda vm: vm.push(value) push.tag = EMBEDDED_PUSH_TAG return push
def make_embedded_push(value)
Returns a closure that pushed the given value onto a Machine's stack. We use this to embed stack pushes in the VM code, so that the interpreter can assume that all instructions are callable Python functions. This makes dispatching much faster than checking if an instruction is a constant (number, strin...
6.616614
7.34581
0.900733
assert(is_embedded_push(obj)) assert(len(obj.__closure__) == 1) return obj.__closure__[0].cell_contents
def get_embedded_push_value(obj)
Extracts the embedded push value.
4.338747
3.970827
1.092656
def safe_lookup(op): try: return instructions.lookup(op) except Exception: return op for i, a in enumerate(code): b = code[i+1] if i+1 < len(code) else None # Does instruction exist? if not isconstant(a): try: ins...
def check(code)
Checks code for obvious errors.
4.385937
4.337422
1.011185
assert(isinstance(code, list)) output = [] subroutine = {} builtins = Machine([]).instructions # Gather up subroutines try: it = code.__iter__() while True: word = next(it) if word == ":": name = next(it) if name in b...
def compile(code, silent=True, ignore_errors=False, optimize=True)
Compiles subroutine-forms into a complete working code. A program such as: : sub1 <sub1 code ...> ; : sub2 <sub2 code ...> ; sub1 foo sub2 bar is compiled into: <sub1 address> call foo <sub2 address> call exit <sub1 code ...> return <su...
3.613435
3.551179
1.017531
out = [] for c in code: if isconstant(c, quoted=True): if isstring(c, quoted=True): v = c[1:-1] elif isbool(c): v = to_bool(c) elif isnumber(c): v = c else: raise CompileError("Unknown ty...
def native_types(code)
Convert code elements from strings to native Python types.
4.751956
4.737775
1.002993
return Dimension(self._name, self._global_size, lower_extent=self._lower_extent, upper_extent=self._upper_extent, description=self._description)
def copy(self)
Returns ------- A copy of the dimension
5.993259
5.525776
1.084601
if global_size is not None: self._global_size = global_size if lower_extent is not None: self._lower_extent = lower_extent if upper_extent is not None: self._upper_extent = upper_extent if description is not None: self._description = description # Check that we've been...
def update(self, global_size=None, lower_extent=None, upper_extent=None, description=None)
Update the dimension properties Parameters ---------- global_size : int Global dimension size (Default value = None) lower_extent : int Lower dimension extent (Default value = None) upper_extent : int Upper dimension extent (Default value = No...
1.902429
2.18587
0.870331
extents_valid = (0 <= self.lower_extent <= self.upper_extent <= self.global_size) if not extents_valid: raise ValueError("Dimension '{d}' fails 0 <= {el} <= {eu} <= {gs}" .format(d=self.name, gs=self.global_size, el=self.lower_extent...
def validate(self)
Validate the contents of a dimension data dictionary
4.695326
4.213807
1.114272
try: df = self.df[col] num = float(df.sum()) return num except Exception as e: self.err(e, "Can not sum data on column " + str(col))
def sum_(self, col: str) -> float
Returns the sum of all values in a column :param col: column name :type col: str :return: sum of all the column values :rtype: float :example: ``sum = ds.sum_("Col 1")``
4.838048
5.806122
0.833267
try: self.df = rows = list(rows) self.df.drop(rows) except Exception as e: self.err(e, self.dropr, "Can not drop rows")
def dropr(self, *rows)
Drops some rows from the main dataframe :param rows: rows names :type rows: list of ints :example: ``ds.drop_rows([0, 2])``
7.170125
7.564746
0.947834
try: self.df = self.df.loc[len(self.df.index)] = vals except Exception as e: self.err(e, self.append, "Can not append row") return self.ok("Row added to dataframe")
def append(self, vals: list, index=None)
Append a row to the main dataframe :param vals: list of the row values to add :type vals: list :param index: index key, defaults to None :param index: any, optional :example: ``ds.append([0, 2, 2, 3, 4])``
6.526988
6.329479
1.031205
try: self.df = self.df.copy().sort_values(col) except Exception as e: self.err(e, "Can not sort the dataframe from column " + str(col))
def sort(self, col: str)
Sorts the main dataframe according to the given column :param col: column name :type col: str :example: ``ds.sort("Col 1")``
6.401855
6.095228
1.050306
try: self.df = self.df.iloc[::-1] except Exception as e: self.err(e, "Can not reverse the dataframe")
def reverse(self)
Reverses the main dataframe order :example: ``ds.reverse()``
5.108693
4.299167
1.188298
try: if len(cols) == 0: self.df = self.df.apply(function, axis=axis, **kwargs) else: cols = list(cols) self.df[cols] = self.df[cols].apply(function, **kwargs) except Exception as e: self.err(e, "Can not apply fu...
def apply(self, function: "function", *cols, axis=1, **kwargs)
Apply a function on columns values :param function: a function to apply to the columns :type function: function :param cols: columns names :type cols: name of columns :param axis: index (0) or column (1), default is 1 :param kwargs: arguments for ``df.apply`` :ty...
2.599732
2.789494
0.931973
try: df = self._pivot(index, **kwargs) return pd.pivot_table(self.df, index=kwargs["index"], **kwargs) except Exception as e: self.err(e, "Can not pivot dataframe")
def pivot(self, index, **kwargs)
Pivots a dataframe
5.465953
5.127997
1.065904
try: self.df = self._trimquants(col, inf, sup) except Exception as e: self.err(e, self.trimquants, "Can not trim quantiles")
def trimquants(self, col: str, inf: float, sup: float)
Remove superior and inferior quantiles from the dataframe :param col: column name :type col: str :param inf: inferior quantile :type inf: float :param sup: superior quantile :type sup: float :example: ``ds.trimquants("Col 1", 0.01, 0.99)``
5.331986
5.089987
1.047544
try: self.df = self._trimquants(col, None, sup) except Exception as e: self.err(e, self.trimsquants, "Can not trim superior quantiles")
def trimsquants(self, col: str, sup: float)
Remove superior quantiles from the dataframe :param col: column name :type col: str :param sup: superior quantile :type sup: float :example: ``ds.trimsquants("Col 1", 0.99)``
7.561919
6.774091
1.1163
try: self.df = self._trimquants(col, inf, None) except Exception as e: self.err(e, self.trimiquants, "Can not trim inferior quantiles")
def trimiquants(self, col: str, inf: float)
Remove superior and inferior quantiles from the dataframe :param col: column name :type col: str :param inf: inferior quantile :type inf: float :example: ``ds.trimiquants("Col 1", 0.05)``
7.23936
7.025594
1.030427
isquoted = lambda c: c[0]==c[-1] and c[0] in ['"', "'"] if quoted: check = lambda c: isinstance(c, str) and isquoted(c) else: check = lambda c: isinstance(c, str) if isinstance(args, list): return all(map(check, args)) else: return check(args)
def isstring(args, quoted=False)
Checks if value is a (quoted) string.
2.413778
2.454617
0.983362
return all(map(lambda c: isinstance(c, int) or isinstance(c, float), args))
def isnumber(*args)
Checks if value is an integer, long integer or float. NOTE: Treats booleans as numbers, where True=1 and False=0.
4.824438
4.827065
0.999456
true_or_false = [instructions.lookup(instructions.true_), instructions.lookup(instructions.false_)] return all(map(lambda c: isinstance(c, bool) or c in true_or_false, args))
def isbool(*args)
Checks if value is boolean.
6.478559
6.019189
1.076318
return all(map(lambda c: isnumber(c) or isbool(c), args))
def isbinary(*args)
Checks if value can be part of binary/bitwise operations.
8.951378
6.344024
1.410994
check = lambda c: isbool(c) or isnumber(c) or isstring(c, quoted) if isinstance(args, list): return all(map(check, args)) else: return check(args)
def isconstant(args, quoted=False)
Checks if value is a boolean, number or string.
3.116447
2.689117
1.158911
from crianza import compiler code = compiler.compile(parser.parse(source), optimize=optimize) machine = Machine(code, output=output, input=input) return machine.run(steps)
def execute(source, optimize=True, output=sys.stdout, input=sys.stdin, steps=-1)
Compiles and runs program, returning the machine used to execute the code. Args: optimize: Whether to optimize the code after parsing it. output: Stream which program can write output to. input: Stream which program can read input from. steps: An optional maximum number of instr...
5.345493
6.034488
0.885824
machine = execute(source, optimize=optimize, output=output, input=input, steps=steps) ds = machine.stack if len(ds) == 0: return None elif len(ds) == 1: return ds[-1] else: return ds
def eval(source, optimize=True, output=sys.stdout, input=sys.stdin, steps=-1)
Compiles and runs program, returning the values on the stack. To return the machine instead, see execute(). Args: optimize: Whether to optimize the code after parsing it. output: Stream which program can write output to. input: Stream which program can read input from. steps: A...
3.449895
3.903738
0.883741
self.data_stack = stack.Stack() self.return_stack = stack.Stack() self.instruction_pointer = 0 return self
def reset(self)
Reset stacks and instruction pointer.
4.933034
3.478592
1.418112
try: return self.data_stack.pop() except errors.MachineError as e: raise errors.MachineError("%s: At index %d in code: %s" % (e, self.instruction_pointer, self.code_string))
def pop(self)
Pops the data stack, returning the value.
6.022824
5.113019
1.177939
op = self.code[self.instruction_pointer] self.instruction_pointer += 1 op(self)
def step(self)
Executes one instruction and stops.
6.122943
4.298615
1.424399
try: while self.instruction_pointer < len(self.code): self.step() if steps is not None: steps -= 1 if steps == 0: break except StopIteration: pass except EOFError: ...
def run(self, steps=None)
Run threaded code in machine. Args: steps: If specified, run that many number of instructions before stopping.
3.34477
3.077882
1.086712
for k in values.keys(): setattr(self, k, values[k])
def from_dict(self, values)
Assign the values from the dict passed in. All items in the dict are assigned as attributes of the object. :param dict values: The dictionary of values to assign to this mapping
3.386739
4.738689
0.714699
return sorted([k for k in dir(self) if k[0:1] != '_' and k != 'keys' and not k.isupper() and not inspect.ismethod(getattr(self, k)) and not (hasattr(self.__class__, k) and isinstance(getattr(self.__class__,...
def keys(self)
Return a list of attribute names for the mapping. :rtype: list
3.007549
3.049653
0.986194
seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3] cdict = {'red': [], 'green': [], 'blue': []} for i, item in enumerate(seq): if isinstance(item, float): r1, g1, b1 = seq[i - 1] r2, g2, b2 = seq[i + 1] cdict['red'].append([item, r1, r2]) c...
def make_colormap(seq)
Return a LinearSegmentedColormap seq: a sequence of floats and RGB-tuples. The floats should be increasing and in the interval (0,1).
1.150453
1.227284
0.937398
imgname = imageUrl.split('/')[-1] imgbase = imgname.rsplit('-', 1)[0] imgext = imgname.rsplit('.', 1)[1] return '%s.%s' % (imgbase, imgext)
def namer(cls, imageUrl, pageUrl)
Remove random junk from image names.
2.889895
2.664228
1.084703
try: res = "" i = 0 vals = self.df[col].tolist() for el in vals: if nums is True: res = res + str(i) + " " + el else: res = res + el if i < (len(vals)-1): ...
def flat_(self, col, nums=True)
Returns a flat representation of a column's values
3.159952
3.086868
1.023676
df = self._mfw(col, sw_lang, limit) if df is None: self.err("Can not find most frequent words") return return self._duplicate_(df)
def mfw_(self, col, sw_lang="english", limit=100)
Returns a Dataswim instance with the most frequent words in a column exluding the most common stop words
6.340938
6.137628
1.033125
fn = os.path.join(basepath, 'dosagelib', 'languages.py') encoding = 'utf-8' with codecs.open(fn, 'w', encoding) as f: f.write('# -*- coding: %s -*-%s' % (encoding, os.linesep)) f.write('# ISO 693-1 language codes from pycountry%s' % os.linesep) f.write('# This file is automatica...
def main()
Update language information in dosagelib/languages.py.
3.647128
2.724587
1.338598
f.write("Languages = {%s" % os.linesep) for lang in sorted(l): f.write(" %r: %r,%s" % (lang, l[lang], os.linesep)) f.write("}%s" % os.linesep)
def write_languages(f, l)
Write language information.
2.612749
2.48312
1.052204
for name, ary in arrays.iteritems(): if name not in type(cube).__dict__: setattr(type(cube), name, ArrayDescriptor(name)) setattr(cube, name, ary)
def generic_stitch(cube, arrays)
Creates descriptors associated with array name and then sets the array as a member variable
5.15736
4.432219
1.163607
# By default, create numpy arrays if array_factory is None: array_factory = np.empty # Construct the array dictionary by calling the # array_factory for each array return { n: array_factory(ra.shape, ra.dtype) for n, ra in reified_arrays.iteritems() }
def create_local_arrays(reified_arrays, array_factory=None)
Function that creates arrays, given the definitions in the reified_arrays dictionary and the array_factory keyword argument. Arguments --------- reified_arrays : dictionary Dictionary keyed on array name and array definitions. Can be obtained via cube.arrays(reify=True) ...
4.758038
4.592393
1.036069
# Create a default array stitching method if array_stitch is None: array_stitch = generic_stitch # Get reified arrays from the cube if necessary if reified_arrays is None: reified_arrays = cube.arrays(reify=True) arrays = create_local_arrays(reified_arrays, array_factory=arra...
def create_local_arrays_on_cube(cube, reified_arrays=None, array_stitch=None, array_factory=None)
Function that creates arrays on the supplied hypercube, given the supplied reified_arrays dictionary and array_stitch and array_factory functions. Arguments --------- cube : HyperCube A hypercube object on which arrays will be created. Keyword Arguments ----------------- ...
2.923635
3.125234
0.935493
return sum(map(lambda (x,y): float(x)*float(y), zip(a,b))) / sum([ -sum(map(lambda (x,y): float(x)*float(y), zip(a,b))), sum(map(lambda x: float(x)**2, a)), sum(map(lambda x: float(x)**2, b))])
def tanimoto_coefficient(a, b)
Measured similarity between two points in a multi-dimensional space. Returns: 1.0 if the two points completely overlap, 0.0 if the two points are infinitely far apart.
2.559316
3.122212
0.819712
weighted = lambda s: map(lambda (x,y): float(x)*float(y), zip(s, weights)) return tanimoto_coefficient(weighted(a), weighted(b))
def weighted_tanimoto(a, b, weights)
Same as the Tanimoto coefficient, but wit weights for each dimension.
4.138883
4.220054
0.980765
return sum(map(key, sequence)) / float(len(sequence))
def average(sequence, key)
Averages a sequence based on a key.
3.752338
4.063115
0.923513
if len(machines) < 4: return random.choice(machines) r = random.random() if r < 0.5: return random.choice(machines[:len(machines)/4]) elif r < 0.75: return random.choice(machines[:len(machines)/2]) else: return random.choice(machines)
def stochastic_choice(machines)
Stochastically choose one random machine distributed along their scores.
2.14537
2.164943
0.990959
vm.code = [] instructions = set(vm.instructions.values()) - set(exclude) if restrict_to is not None: instructions = instructions.intersection(set(restrict_to)) instructions = list(instructions) for _ in xrange(random.randint(*length)): r = random.random() if r <= ins...
def randomize(vm, length=(10,10), ints=(0,999), strs=(1,10), chars=(32,126), instruction_ratio=0.5, number_string_ratio=0.8, exclude=map(crianza.instructions.lookup, [".", "exit", "read", "write", "str"]), restrict_to=None)
Replaces existing code with completely random instructions. Does not optimize code after generating it. Args: length: Tuple of minimum and maximum code lengths. Code length will be a random number between these two, inclusive values. ints: Integers in the code will be selected at rando...
2.379931
2.574574
0.924398
i = random.randint(0, len(m.code)) j = random.randint(0, len(f.code)) return m.code[:i] + f.code[j:]
def crossover(m, f)
Produces an offspring from two Machines, whose code is a combination of the two.
2.555178
2.41558
1.057791
def make_random(n): return MachineClass().randomize() def run_once(m): m.setUp() m.run() m.tearDown() return m def make_offspring(survivors): a = stochastic_choice(survivors) b = stochastic_choice(survivors) return a.crossover(b) ge...
def iterate(MachineClass, stop_function=lambda iterations: iterations < 10000, machines=1000, survival_rate=0.05, mutation_rate=0.075, silent=False)
Creates a bunch of machines, runs them for a number of steps and then gives them a fitness score. The best produce offspring that are passed on to the next generation. Args: setup: Function taking a Machine argument, makes the machine ready machine_class: A class that should inherit from M...
3.399108
3.307814
1.027599
# Choose a random position if len(self.code) == 0: return index = random.randint(0, len(self.code)-1) mutation_type = random.random() if mutation_type < 0.5: # Change self.code[index] = self.new().randomize().code[0] elif mut...
def mutate(self)
Mutates code.
2.717741
2.526078
1.075874
try: super(GeneticMachine, self).run(steps) self._error = False except StopIteration: self._error = False except Exception: self._error = True
def run(self, steps=10)
Executes up to `steps` instructions.
4.995653
4.819178
1.036619
trans_model = model._meta.translation_model try: (f, lang_id) = trans_model._meta.translated_fields[field] return f except KeyError: # fall back to the old way -- see if model contains the field # directly pass try: return opts.get_field(field) ...
def get_field(cls, model, opts, label, field)
Just like django.contrib.admin.validation.get_field, but knows about translation models.
4.04698
3.850386
1.051058
if not is_multilingual_model(model): return from django.contrib.admin.validation import check_isdict, check_isseq opts = model._meta # this is heavily based on django.contrib.admin.validation. if hasattr(cls, '_dm_prepopulated_fields'): check_isdict(cls, '_dm_prepopulated_fi...
def validate_admin_registration(cls, model)
Validates a class specified as a model admin. Right now this means validating prepopulated_fields, as for multilingual models DM handles them by itself.
3.488206
3.128171
1.115094
# store info in a dictionary {name -> shortname} res = {} session = requests.Session() handle_url('http://www.gocomics.com/features', session, res) handle_url('http://www.gocomics.com/explore/espanol', session, res) handle_url('http://www.gocomics.com/explore/editorial_list', session, res) ...
def get_results()
Parse all search result pages.
4.71053
4.631606
1.01704
min_comics, filename = args with codecs.open(filename, 'a', 'utf-8') as fp: for name, shortname in sorted(load_result(json_file).items()): if name in exclude_comics: print("Excluded " + name) continue fp.write(u"add(%r, %r)\n" % ( ...
def print_results(args)
Print all comics that have at least the given number of minimum comic strips.
7.205389
6.440591
1.118746
I, J, _ = x.shape start_states, transitions = self._start_states, self._transitions lattice = [] transitions_d = defaultdict(list) for transition_index, (s0, s1, delta) in enumerate(transitions): transitions_d[s0].append((s1, delta, transition_index)) ...
def build_lattice(self, x)
Construct the list of nodes and edges for input features.
2.756343
2.723988
1.011878
I, J = shape if lattice is not None: end_I = min(I, max(lattice[..., 3])) - 1 end_J = min(J, max(lattice[..., 4])) - 1 unvisited_nodes = deque([(i, j, s) for i in range(end_I) for j in...
def _independent_lattice(self, shape, lattice=None)
Helper to construct the list of nodes and edges.
3.568879
3.487202
1.023422
I, J, _ = x.shape lattice = self._subset_independent_lattice((I, J)) return lattice
def build_lattice(self, x)
Construct the list of nodes and edges for input features.
11.861599
12.162904
0.975228
filename = self.namer(url, self.stripUrl) if filename is None: filename = url.rsplit('/', 1)[1] dirname = getDirname(self.name) return ComicImage(self.name, url, self.stripUrl, dirname, filename, self.session, text=self.text)
def getDownloader(self, url)
Get an image downloader.
5.844621
5.470845
1.068321
self.urlobj = getImageObject(self.url, self.referrer, self.session) content_type = unquote(self.urlobj.headers.get('content-type', 'application/octet-stream')) content_type = content_type.split(';', 1)[0] if '/' in content_type: maintype, subtype = content_type.split...
def connect(self)
Connect to host and get meta information.
3.168107
3.120372
1.015298
out.info(u"Get image URL %s" % self.url, level=1) self.connect() filename = "%s%s" % (self.filename, self.ext) comicDir = os.path.join(basepath, self.dirname) if not os.path.isdir(comicDir): os.makedirs(comicDir) fn = os.path.join(comicDir, filename) ...
def save(self, basepath)
Save comic URL to filename on disk.
3.268649
3.115468
1.049168
return 'Basic %s' % base64.b64encode(bytes(self.username + ':' + self.password, 'ascii')).decode('ascii')
def authorization_header(self)
Returns a string containing the authorization header used to authenticate with GenePattern. This string is included in the header of subsequent requests sent to GenePattern.
2.70305
2.442211
1.106804
request = urllib.request.Request(self.url + '/rest/v1/data/upload/job_input?name=' + file_name) if self.authorization_header() is not None: request.add_header('Authorization', self.authorization_header()) request.add_header('User-Agent', 'GenePatternRest') with open...
def upload_file(self, file_name, file_path)
Upload a file to a server Attempts to upload a local file with path filepath, to the server, where it will be named filename. Args: :param file_name: The name that the uploaded file will be called on the server. :param file_path: The path of the local file to upload. ...
3.175771
3.040669
1.044432
# names should be a list of names, # values should be a list of **lists** of values json_string = json.dumps({'lsid': job_spec.lsid, 'params': job_spec.params, 'tags': ['GenePattern Python Client']}, cls=GPJSONEncoder) if sys.version_info.major == 3: # Handle conversion to byt...
def run_job(self, job_spec, wait_until_done=True)
Runs a job defined by jobspec, optionally non-blocking. Takes a GPJobSpec object that defines a request to run a job, and makes the request to the server. By default blocks until the job is finished by polling the server, but can also run asynchronously. Args: :param job_s...
3.225462
3.1014
1.040002
request = urllib.request.Request(self.url + '/rest/v1/tasks/all.json') if self.authorization_header() is not None: request.add_header('Authorization', self.authorization_header()) request.add_header('User-Agent', 'GenePatternRest') response = urllib.request.urlopen(r...
def get_task_list(self)
Queries the GenePattern server and returns a list of GPTask objects, each representing one of the modules installed on the server. Useful for determining which are available on the server.
3.072766
2.618874
1.173316
complete = [False] * len(job_list) wait = 1 while not all(complete): time.sleep(wait) for i, job in enumerate(job_list): if not complete[i]: complete[i] = job.is_finished() if not complete[i]: ...
def wait_until_complete(job_list)
Args: Accepts a list of GPJob objects This method will not return until all GPJob objects in the list have finished running. That us, they are either complete and have resulted in an error state. This method will occasionally query each job to see if it is finished.
2.287823
2.447135
0.934898
# Query the server for the list of jobs request = urllib.request.Request(self.url + '/rest/v1/jobs/?pageSize=' + str(n_jobs) + '&userId=' + str(urllib.parse.quote(self.username)) + '&orderBy=-dateSubmitted') ...
def get_recent_jobs(self, n_jobs=10)
Returns the user's N most recently submitted jobs on the GenePattern server. Args: If not specified, n_jobs = 10. Returns: An array of GPJob objects.
2.80556
2.578223
1.088176
request = urllib.request.Request(self.uri) if self.server_data.authorization_header() is not None: request.add_header('Authorization', self.server_data.authorization_header()) request.add_header('User-Agent', 'GenePatternRest') return urllib.request.urlopen(request)
def open(self)
Opens the URL associated with the GPFile and returns a file-like object with three extra methods: * geturl() - return the ultimate URL (can be used to determine if a redirect was followed) * info() - return the meta-information of the page, such as headers ...
3.852756
4.159694
0.926211