text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Compiles subroutine-forms into a complete working code.
<END_TASK>
<USER_TASK:>
Description:
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
<sub2 code ...> return
Optimizations are first done on subroutine bodies, then on the main loop
and finally, symbols are resolved (i.e., placeholders for subroutine
addresses are replaced with actual addresses).
Args:
silent: If set to False, will print optimization messages.
ignore_errors: Only applies to the optimization engine, if set to False
it will not raise any exceptions. The actual compilatio will still
raise errors.
optimize: Flag to control whether to optimize code.
Raises:
CompilationError - Raised if invalid code is detected.
Returns:
An array of code that can be run by a Machine. Typically, you want to
pass this to a Machine without doing optimizations.
Usage:
source = parse("<source code>")
code = compile(source)
machine = Machine(code, optimize=False)
machine.run()
""" |
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 builtins:
raise CompileError("Cannot shadow internal word definition '%s'." % name)
if name in [":", ";"]:
raise CompileError("Invalid word name '%s'." % name)
subroutine[name] = []
while True:
op = next(it)
if op == ";":
subroutine[name].append(instructions.lookup(instructions.return_))
break
else:
subroutine[name].append(op)
else:
output.append(word)
except StopIteration:
pass
# Expand all subroutine words to ["<name>", "call"]
for name, code in subroutine.items():
# For subroutines
xcode = []
for op in code:
xcode.append(op)
if op in subroutine:
xcode.append(instructions.lookup(instructions.call))
subroutine[name] = xcode
# Compile main code (code outside of subroutines)
xcode = []
for op in output:
xcode.append(op)
if op in subroutine:
xcode.append(instructions.lookup(instructions.call))
# Because main code comes before subroutines, we need to explicitly add an
# exit instruction
output = xcode
if len(subroutine) > 0:
output += [instructions.lookup(instructions.exit)]
# Optimize main code
if optimize:
output = optimizer.optimized(output, silent=silent, ignore_errors=False)
# Add subroutines to output, track their locations
location = {}
for name, code in subroutine.items():
location[name] = len(output)
if optimize:
output += optimizer.optimized(code, silent=silent, ignore_errors=False)
else:
output += code
# Resolve all subroutine references
for i, op in enumerate(output):
if op in location:
output[i] = location[op]
output = native_types(output)
if not ignore_errors:
check(output)
return output |
<SYSTEM_TASK:>
Convert code elements from strings to native Python types.
<END_TASK>
<USER_TASK:>
Description:
def native_types(code):
"""Convert code elements from strings to native Python types.""" |
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 type %s: %s" % (type(c).__name__, c))
# Instead of pushing constants in the code, we always push callable
# Python functions, for fast dispatching:
out.append(make_embedded_push(v))
else:
try:
out.append(instructions.lookup(c))
except KeyError:
raise CompileError("Unknown word '%s'" % c)
return out |
<SYSTEM_TASK:>
Validate the contents of a dimension data dictionary
<END_TASK>
<USER_TASK:>
Description:
def validate(self):
""" Validate the contents of a dimension data dictionary """ |
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, eu=self.upper_extent)) |
<SYSTEM_TASK:>
Returns the sum of all values in a column
<END_TASK>
<USER_TASK:>
Description:
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")``
""" |
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)) |
<SYSTEM_TASK:>
Drops some rows from the main dataframe
<END_TASK>
<USER_TASK:>
Description:
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])``
""" |
try:
self.df = rows = list(rows)
self.df.drop(rows)
except Exception as e:
self.err(e, self.dropr, "Can not drop rows") |
<SYSTEM_TASK:>
Append a row to the main dataframe
<END_TASK>
<USER_TASK:>
Description:
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])``
""" |
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") |
<SYSTEM_TASK:>
Sorts the main dataframe according to the given column
<END_TASK>
<USER_TASK:>
Description:
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")``
""" |
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)) |
<SYSTEM_TASK:>
Reverses the main dataframe order
<END_TASK>
<USER_TASK:>
Description:
def reverse(self):
"""
Reverses the main dataframe order
:example: ``ds.reverse()``
""" |
try:
self.df = self.df.iloc[::-1]
except Exception as e:
self.err(e, "Can not reverse the dataframe") |
<SYSTEM_TASK:>
Apply a function on columns values
<END_TASK>
<USER_TASK:>
Description:
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``
:type kwargs: optional
:example:
.. code-block:: python
def f(row):
# add a new column with a value
row["newcol"] = row["Col 1] + 1
return row
ds.apply(f)
""" |
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 function") |
<SYSTEM_TASK:>
Remove superior quantiles from the dataframe
<END_TASK>
<USER_TASK:>
Description:
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)``
""" |
try:
self.df = self._trimquants(col, None, sup)
except Exception as e:
self.err(e, self.trimsquants, "Can not trim superior quantiles") |
<SYSTEM_TASK:>
Checks if value is an integer, long integer or float.
<END_TASK>
<USER_TASK:>
Description:
def isnumber(*args):
"""Checks if value is an integer, long integer or float.
NOTE: Treats booleans as numbers, where True=1 and False=0.
""" |
return all(map(lambda c: isinstance(c, int) or isinstance(c, float), args)) |
<SYSTEM_TASK:>
Checks if value is boolean.
<END_TASK>
<USER_TASK:>
Description:
def isbool(*args):
"""Checks if value is boolean.""" |
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)) |
<SYSTEM_TASK:>
Checks if value is a boolean, number or string.
<END_TASK>
<USER_TASK:>
Description:
def isconstant(args, quoted=False):
"""Checks if value is a boolean, number or string.""" |
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) |
<SYSTEM_TASK:>
Compiles and runs program, returning the machine used to execute the
<END_TASK>
<USER_TASK:>
Description:
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 instructions to execute on the
virtual machine. Set to -1 for no limit.
Returns:
A Machine instance.
""" |
from crianza import compiler
code = compiler.compile(parser.parse(source), optimize=optimize)
machine = Machine(code, output=output, input=input)
return machine.run(steps) |
<SYSTEM_TASK:>
Compiles and runs program, returning the values on the stack.
<END_TASK>
<USER_TASK:>
Description:
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: An optional maximum number of instructions to execute on the
virtual machine. Set to -1 for no limit.
Returns:
None: If the stack is empty
obj: If the stack contains a single value
[obj, obj, ...]: If the stack contains many values
""" |
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 |
<SYSTEM_TASK:>
Reset stacks and instruction pointer.
<END_TASK>
<USER_TASK:>
Description:
def reset(self):
"""Reset stacks and instruction pointer.""" |
self.data_stack = stack.Stack()
self.return_stack = stack.Stack()
self.instruction_pointer = 0
return self |
<SYSTEM_TASK:>
Pops the data stack, returning the value.
<END_TASK>
<USER_TASK:>
Description:
def pop(self):
"""Pops the data stack, returning the value.""" |
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)) |
<SYSTEM_TASK:>
Executes one instruction and stops.
<END_TASK>
<USER_TASK:>
Description:
def step(self):
"""Executes one instruction and stops.""" |
op = self.code[self.instruction_pointer]
self.instruction_pointer += 1
op(self) |
<SYSTEM_TASK:>
Run threaded code in machine.
<END_TASK>
<USER_TASK:>
Description:
def run(self, steps=None):
"""Run threaded code in machine.
Args:
steps: If specified, run that many number of instructions before
stopping.
""" |
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:
pass
return self |
<SYSTEM_TASK:>
Assign the values from the dict passed in. All items in the dict
<END_TASK>
<USER_TASK:>
Description:
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
""" |
for k in values.keys():
setattr(self, k, values[k]) |
<SYSTEM_TASK:>
Return a list of attribute names for the mapping.
<END_TASK>
<USER_TASK:>
Description:
def keys(self):
"""Return a list of attribute names for the mapping.
:rtype: list
""" |
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__, k),
property)) and
not isinstance(getattr(self, k), property)]) |
<SYSTEM_TASK:>
Returns a flat representation of a column's values
<END_TASK>
<USER_TASK:>
Description:
def flat_(self, col, nums=True):
"""
Returns a flat representation of a column's values
""" |
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):
res += " "
i += 1
return res
except Exception as e:
self.err(e, "Can not flat " + col) |
<SYSTEM_TASK:>
Returns a Dataswim instance with the most frequent words in a
<END_TASK>
<USER_TASK:>
Description:
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
""" |
df = self._mfw(col, sw_lang, limit)
if df is None:
self.err("Can not find most frequent words")
return
return self._duplicate_(df) |
<SYSTEM_TASK:>
Creates descriptors associated with array name and
<END_TASK>
<USER_TASK:>
Description:
def generic_stitch(cube, arrays):
"""
Creates descriptors associated with array name and
then sets the array as a member variable
""" |
for name, ary in arrays.iteritems():
if name not in type(cube).__dict__:
setattr(type(cube), name, ArrayDescriptor(name))
setattr(cube, name, ary) |
<SYSTEM_TASK:>
Function that creates arrays, given the definitions in
<END_TASK>
<USER_TASK:>
Description:
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)
Keyword Arguments
-----------------
array_factory : function
A function used to create array objects. It's signature should
be array_factory(shape, dtype) and should return a constructed
array of the supplied shape and data type. If None,
numpy.empty will be used.
Returns
-------
A dictionary of array objects, keyed on array names
""" |
# 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() } |
<SYSTEM_TASK:>
Function that creates arrays on the supplied hypercube, given the supplied
<END_TASK>
<USER_TASK:>
Description:
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
-----------------
reified_arrays : dictionary
Dictionary keyed on array name and array definitions.
If None, obtained from cube.arrays(reify=True)
array_stitch : function
A function that stitches array objects onto the cube object.
It's signature should be array_stitch(cube, arrays)
where cube is a HyperCube object and arrays is a
dictionary containing array objects keyed by their name.
If None, a default function will be used that creates
python descriptors associated with the individual array objects.
array_factory : function
A function that creates array objects. It's signature should
be array_factory(shape, dtype) and should return a constructed
array of the supplied shape and data type. If None,
numpy.empty will be used.
Returns
-------
A dictionary of array objects, keyed on array names
""" |
# 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=array_factory)
array_stitch(cube, arrays)
return arrays |
<SYSTEM_TASK:>
Measured similarity between two points in a multi-dimensional space.
<END_TASK>
<USER_TASK:>
Description:
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.
""" |
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))]) |
<SYSTEM_TASK:>
Same as the Tanimoto coefficient, but wit weights for each dimension.
<END_TASK>
<USER_TASK:>
Description:
def weighted_tanimoto(a, b, weights):
"""Same as the Tanimoto coefficient, but wit weights for each dimension.""" |
weighted = lambda s: map(lambda (x,y): float(x)*float(y), zip(s, weights))
return tanimoto_coefficient(weighted(a), weighted(b)) |
<SYSTEM_TASK:>
Averages a sequence based on a key.
<END_TASK>
<USER_TASK:>
Description:
def average(sequence, key):
"""Averages a sequence based on a key.""" |
return sum(map(key, sequence)) / float(len(sequence)) |
<SYSTEM_TASK:>
Stochastically choose one random machine distributed along their
<END_TASK>
<USER_TASK:>
Description:
def stochastic_choice(machines):
"""Stochastically choose one random machine distributed along their
scores.""" |
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) |
<SYSTEM_TASK:>
Replaces existing code with completely random instructions. Does not
<END_TASK>
<USER_TASK:>
Description:
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 random from this
inclusive range.
strs: Inclusive range of the length of strings in the code.
chars: Inclusive range of characters in random strings.
instruction_ratio: Ratio of instructions to numbers/strings,
meaning that if this value is 0.5 then there will just as many
instructions in the code as there are numbers and strings.
number_string_ratio: Ratio of numbers to strings.
exclude: Excluded instructions. For genetic programming, one wants
to avoid the program to hang for user input. The default value is
to exclude console i/o and debug instructions.
restrict_to: Limit instructions to the given list.
Returns:
The VM.
""" |
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 <= instruction_ratio:
# Generate a random instruction
vm.code.append(random.choice(instructions))
elif r <= number_string_ratio:
# Generate a random number
vm.code.append(crianza.compiler.make_embedded_push(random.randint(*ints)))
else:
# Generate a random string
vm.code.append(crianza.compiler.make_embedded_push('%s' %
"".join(chr(random.randint(*chars)) for n in xrange(0,
random.randint(*strs)))))
return vm |
<SYSTEM_TASK:>
Produces an offspring from two Machines, whose code is a
<END_TASK>
<USER_TASK:>
Description:
def crossover(m, f):
"""Produces an offspring from two Machines, whose code is a
combination of the two.""" |
i = random.randint(0, len(m.code))
j = random.randint(0, len(f.code))
return m.code[:i] + f.code[j:] |
<SYSTEM_TASK:>
Creates a bunch of machines, runs them for a number of steps and then
<END_TASK>
<USER_TASK:>
Description:
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 Machine and contain the
following methods:
setUp(self) [optional]: Run before each new run, should at least
call self.reset() for each run.
tearDown(self) [optional]: Run after each run.
crossover(self, other): Returns a Machine offspring between itself and
another Machine.
score(self): Score the machine. Lower is better. Can return a
tuple of values used to sort the machines from best to worst in
fitness.
stop_function: An optional function that takes the current generation
number and returns True if the processing should stop.
machines: The number of machines to create for each generation.
steps: The number of instructions each machine is allowed to execute in
each run.
code_length: Tuple of (minimum code length, maximum code length) for a
Machine.
survival_ratio: Ratio of the best Machines which are allowed to produce
offspring for the next generation.
mutation_rate: Rate for each machine's chance of being mutated.
""" |
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)
generation = map(make_random, xrange(machines))
survivors = generation
if silent:
log = lambda s,stream=None: None
else:
log = _log
try:
iterations = 0
while not stop_function(iterations, survivors):
iterations += 1
log("running ... ")
# Run all machines in this generation
generation = map(run_once, generation)
# Sort machines from best to worst
generation = sorted(generation, key=lambda m: m.score())
# Select the best
survivors = generation[:int(survival_rate * len(generation))]
# Remove code larger than 50
for s in survivors:
if len(s.code) >= 50:
s.code = s.code[:50]
# Remove dead ones
survivors = [s for s in survivors if len(s.code)>0]
#survivors = [s for s in survivors if len(s.code)<=50]
# All dead? start with a new set
if len(survivors) == 0:
log("\nNo survivors, restarting")
survivors = map(make_random, xrange(machines))
generation = survivors
continue
# Create a new generation based on the survivors.
log("crossover ... ")
cross = lambda _: make_offspring(survivors)
generation = map(cross, xrange(machines))
# Add mutations from time to time
for m in generation:
if random.random() > mutation_rate:
m.mutate()
log("\rgen %d 1-fitness %.12f avg code len %.2f avg stack len %.2f\n" %
(iterations,
average(survivors, lambda m: m.score()),
average(survivors, lambda m: len(m.code)),
average(survivors, lambda m: len(m.stack) + len(m.return_stack))))
except KeyboardInterrupt:
pass
return survivors |
<SYSTEM_TASK:>
Executes up to `steps` instructions.
<END_TASK>
<USER_TASK:>
Description:
def run(self, steps=10):
"""Executes up to `steps` instructions.""" |
try:
super(GeneticMachine, self).run(steps)
self._error = False
except StopIteration:
self._error = False
except Exception:
self._error = True |
<SYSTEM_TASK:>
Just like django.contrib.admin.validation.get_field, but knows
<END_TASK>
<USER_TASK:>
Description:
def get_field(cls, model, opts, label, field):
"""
Just like django.contrib.admin.validation.get_field, but knows
about translation models.
""" |
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)
except models.FieldDoesNotExist:
raise ImproperlyConfigured("'%s.%s' refers to field '%s' that is " \
"missing from model '%s'." \
% (cls.__name__, label, field, model.__name__)) |
<SYSTEM_TASK:>
Validates a class specified as a model admin.
<END_TASK>
<USER_TASK:>
Description:
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.
""" |
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_fields', cls.prepopulated_fields)
for field, val in cls._dm_prepopulated_fields.items():
f = get_field(cls, model, opts, 'prepopulated_fields', field)
if isinstance(f, (models.DateTimeField, models.ForeignKey,
models.ManyToManyField)):
raise ImproperlyConfigured("'%s.prepopulated_fields['%s']' "
"is either a DateTimeField, ForeignKey or "
"ManyToManyField. This isn't allowed."
% (cls.__name__, field))
check_isseq(cls, "prepopulated_fields['%s']" % field, val)
for idx, f in enumerate(val):
get_field(cls, model,
opts, "prepopulated_fields['%s'][%d]"
% (f, idx), f) |
<SYSTEM_TASK:>
Helper to construct the list of nodes and edges.
<END_TASK>
<USER_TASK:>
Description:
def _independent_lattice(self, shape, lattice=None):
""" Helper to construct the list of nodes and edges. """ |
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 range(end_J)
for s in self._start_states])
lattice = lattice.tolist()
else:
lattice = []
unvisited_nodes = deque([(0, 0, s) for s in self._start_states])
lattice += _grow_independent_lattice(self._transitions,
self.n_states, (I, J),
unvisited_nodes)
lattice = np.array(sorted(lattice), dtype='int64')
return lattice |
<SYSTEM_TASK:>
Connect to host and get meta information.
<END_TASK>
<USER_TASK:>
Description:
def connect(self):
"""Connect to host and get meta information.""" |
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('/', 1)
else:
maintype = content_type
subtype = None
if maintype != 'image' and content_type not in ('application/octet-stream', 'application/x-shockwave-flash'):
raise IOError('content type %r is not an image at %s' % (content_type, self.url))
# Always use mime type for file extension if it is sane.
if maintype == 'image':
self.ext = '.' + subtype.replace('jpeg', 'jpg')
self.contentLength = int(self.urlobj.headers.get('content-length', 0))
out.debug(u'... filename = %r, ext = %r, contentLength = %d' % (self.filename, self.ext, self.contentLength)) |
<SYSTEM_TASK:>
Returns a string containing the authorization header used to authenticate
<END_TASK>
<USER_TASK:>
Description:
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.
""" |
return 'Basic %s' % base64.b64encode(bytes(self.username + ':' + self.password, 'ascii')).decode('ascii') |
<SYSTEM_TASK:>
Upload a file to a server
<END_TASK>
<USER_TASK:>
Description:
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.
Returns:
:return: A GPFile object that wraps the URI of the uploaded file, or None if the upload fails.
""" |
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(file_path, 'rb') as f:
data = f.read()
try:
response = urllib.request.urlopen(request, data)
except IOError:
print("authentication failed")
return None
if response.getcode() != 201:
print("file upload failed, status code = %i" % response.getcode())
return None
return GPFile(self, response.info().get('Location')) |
<SYSTEM_TASK:>
Runs a job defined by jobspec, optionally non-blocking.
<END_TASK>
<USER_TASK:>
Description:
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_spec: A GPJobSpec object that contains the data defining the job to be run.
:param wait_until_done: Whether to wait until the job is finished before returning.
:return:
Returns:
a GPJob object that refers to the running job on the server. If called
synchronously, this object will contain the info associated with the
completed job. Otherwise, it will just wrap the URI of the running job.
""" |
# 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 bytes for Python 3
json_string = bytes(json_string, 'utf-8')
request = urllib.request.Request(self.url + '/rest/v1/jobs')
if self.authorization_header() is not None:
request.add_header('Authorization', self.authorization_header())
request.add_header('Content-Type', 'application/json')
request.add_header('User-Agent', 'GenePatternRest')
response = urllib.request.urlopen(request, json_string)
if response.getcode() != 201:
print(" job POST failed, status code = %i" % response.getcode())
return None
data = json.loads(response.read().decode('utf-8'))
job = GPJob(self, data['jobId'])
job.get_info()
self.last_job = job # Set the last job
if wait_until_done:
job.wait_until_done()
return job |
<SYSTEM_TASK:>
Queries the GenePattern server and returns a list of GPTask objects,
<END_TASK>
<USER_TASK:>
Description:
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.
""" |
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(request)
response_string = response.read().decode('utf-8')
category_and_tasks = json.loads(response_string)
raw_list = category_and_tasks['all_modules']
task_list = []
for task_dict in raw_list:
task = GPTask(self, task_dict['lsid'], task_dict)
task_list.append(task)
return task_list |
<SYSTEM_TASK:>
Returns the user's N most recently submitted jobs on the GenePattern server.
<END_TASK>
<USER_TASK:>
Description:
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.
""" |
# 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')
if self.authorization_header() is not None:
request.add_header('Authorization', self.authorization_header())
request.add_header('User-Agent', 'GenePatternRest')
response = urllib.request.urlopen(request)
response_string = response.read().decode('utf-8')
response_json = json.loads(response_string)
# For each job in the JSON Array, build a GPJob object and add to the job list
job_list = []
for job_json in response_json['items']:
job_id = job_json['jobId']
job = GPJob(self, job_id)
job.info = job_json
job.load_info()
job_list.append(job)
return job_list |
<SYSTEM_TASK:>
Parses the JSON object stored at GPJob.info and assigns its metadata to
<END_TASK>
<USER_TASK:>
Description:
def load_info(self):
"""
Parses the JSON object stored at GPJob.info and assigns its metadata to
properties of this GPJob object.
Primarily intended to be called from GPJob.get_info().
""" |
self.task_name = self.info['taskName']
self.task_lsid = self.info['taskLsid']
self.user_id = self.info['userId']
self.job_number = int(self.info['jobId'])
self.status = self.get_status_message()
self.date_submitted = self.info['dateSubmitted']
self.log_files = self.info['logFiles']
self.output_files = self.info['outputFiles']
self.num_output_files = self.info['numOutputFiles']
# Create children, if relevant
self.children = self.get_child_jobs() |
<SYSTEM_TASK:>
Queries the GenePattern server for child jobs of this job, creates GPJob
<END_TASK>
<USER_TASK:>
Description:
def get_child_jobs(self):
"""
Queries the GenePattern server for child jobs of this job, creates GPJob
objects representing each of them and assigns the list of them to the
GPJob.children property. Then return this list.
""" |
# Lazily load info
if self.info is None:
self.get_info()
# Lazily load children
if self.children is not None:
return self.children
else:
if 'children' in self.info:
child_list = []
for child in self.info['children']['items']:
child_job = GPJob(self.server_data, child['jobId'])
child_job.info = child
child_job.load_info()
child_list.append(child_job)
return child_list
else: # No children? Return empty list
return [] |
<SYSTEM_TASK:>
Queries the server to check if the job has been completed.
<END_TASK>
<USER_TASK:>
Description:
def is_finished(self):
"""
Queries the server to check if the job has been completed.
Returns True or False.
""" |
self.get_info()
if 'status' not in self.info:
return False
if 'isFinished' not in self.info['status']:
return False
return self.info['status']['isFinished'] |
<SYSTEM_TASK:>
Queries the server to check if the job has an error.
<END_TASK>
<USER_TASK:>
Description:
def has_error(self):
"""
Queries the server to check if the job has an error.
Returns True or False.
""" |
self.get_info()
if 'status' not in self.info:
return False
if 'hasError' not in self.info['status']:
return False
return self.info['status']['hasError'] |
<SYSTEM_TASK:>
Queries the server to check if the job is pending.
<END_TASK>
<USER_TASK:>
Description:
def is_pending(self):
"""
Queries the server to check if the job is pending.
Returns True or False.
""" |
self.get_info()
if 'status' not in self.info:
return False
if 'isPending' not in self.info['status']:
return False
return self.info['status']['isPending'] |
<SYSTEM_TASK:>
Returns the tags for the job, querying the
<END_TASK>
<USER_TASK:>
Description:
def get_tags(self):
"""
Returns the tags for the job, querying the
server if necessary.
""" |
# Lazily load info
if self.info is None:
self.get_info()
if 'tags' in self.info:
return [structure['tag']['tag'] for structure in self.info['tags']]
else:
return [] |
<SYSTEM_TASK:>
Returns the comments for the job, querying the
<END_TASK>
<USER_TASK:>
Description:
def get_comments(self):
"""
Returns the comments for the job, querying the
server if necessary.
""" |
# Lazily load info
if self.info is None:
self.get_info()
if 'comments' in self.info:
return [structure['text'] for structure in self.info['comments']['comments']]
else:
return [] |
<SYSTEM_TASK:>
Returns a list of the files output by the job, querying the server if
<END_TASK>
<USER_TASK:>
Description:
def get_output_files(self):
"""
Returns a list of the files output by the job, querying the server if
necessary. If the job has output no files, an empty list will be
returned.
""" |
# Lazily load info
if self.info is None:
self.get_info()
if 'outputFiles' in self.info:
return [GPFile(self.server_data, f['link']['href']) for f in self.info['outputFiles']]
else:
return [] |
<SYSTEM_TASK:>
Returns the output file with the specified name, if no output files
<END_TASK>
<USER_TASK:>
Description:
def get_file(self, name):
"""
Returns the output file with the specified name, if no output files
match, returns None.
""" |
files = self.get_output_files()
for f in files:
if f.get_name() == name:
return f
return None |
<SYSTEM_TASK:>
This method will not return until the job is either complete or has
<END_TASK>
<USER_TASK:>
Description:
def wait_until_done(self):
"""
This method will not return until the job is either complete or has
reached an error state. This queries the server periodically to check
for an update in status.
""" |
wait = 1
while True:
time.sleep(wait)
self.get_info()
if self.info['status']['isFinished']:
break
# implements a crude exponential back off
wait = min(wait * 2, 60) |
<SYSTEM_TASK:>
Queries the server for the parameter information and other metadata associated with
<END_TASK>
<USER_TASK:>
Description:
def param_load(self):
"""
Queries the server for the parameter information and other metadata associated with
this task
""" |
escaped_uri = urllib.parse.quote(self.uri)
request = urllib.request.Request(self.server_data.url + '/rest/v1/tasks/' + escaped_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')
response = urllib.request.urlopen(request)
self.json = response.read().decode('utf-8')
self.dto = json.loads(self.json)
self.description = self.dto['description'] if 'description' in self.dto else ""
self.name = self.dto['name']
self.documentation = self.dto['documentation'] if 'documentation' in self.dto else ""
self.lsid = self.dto['lsid']
self.version = self.dto['version'] if 'version' in self.dto else ""
self.params = []
for param in self.dto['params']:
self.params.append(GPTaskParam(self, param))
self._params_loaded = True |
<SYSTEM_TASK:>
Returns either 'File' or 'String'.
<END_TASK>
<USER_TASK:>
Description:
def get_type(self):
"""
Returns either 'File' or 'String'.
The type attribute (e.g., java.io.File, java.lang.Integer, java.lang.Float),
which might give a hint as to what string should represent,
is not enforced and not employed consistently across all tasks, so we ignore.
""" |
if 'TYPE' in self.attributes and 'MODE' in self.attributes:
dto_type = self.attributes['TYPE']
dto_mode = self.attributes['MODE']
if dto_type == 'FILE' and dto_mode == 'IN':
return 'File'
return 'String' |
<SYSTEM_TASK:>
Return the default value for the parameter. If here is no default value, return None
<END_TASK>
<USER_TASK:>
Description:
def get_default_value(self):
"""
Return the default value for the parameter. If here is no default value, return None
""" |
if ('default_value' in self.attributes and
bool(self.attributes['default_value'].strip())):
return self.attributes['default_value']
else:
return None |
<SYSTEM_TASK:>
Returns a message field, which indicates whether choices statically
<END_TASK>
<USER_TASK:>
Description:
def get_choice_status(self):
"""
Returns a message field, which indicates whether choices statically
or dynamically defined, and flag indicating whether a dynamic file
selection loading error occurred.
Throws an error if this is not a choice parameter.
""" |
if 'choiceInfo' not in self.dto[self.name]:
raise GPException('not a choice parameter')
status = self.dto[self.name]['choiceInfo']['status']
return status['message'], status['flag'] |
<SYSTEM_TASK:>
Returns the HREF of a dynamic choice parameter.
<END_TASK>
<USER_TASK:>
Description:
def get_choice_href(self):
"""
Returns the HREF of a dynamic choice parameter.
Throws an error if this is not a choice parameter.
""" |
if 'choiceInfo' not in self.dto[self.name]:
raise GPException('not a choice parameter')
return self.dto[self.name]['choiceInfo']['href'] |
<SYSTEM_TASK:>
Returns the default selection from a choice menu
<END_TASK>
<USER_TASK:>
Description:
def get_choice_selected_value(self):
"""
Returns the default selection from a choice menu
Throws an error if this is not a choice parameter.
""" |
if 'choiceInfo' not in self.dto[self.name]:
raise GPException('not a choice parameter')
choice_info_dto = self.dto[self.name]['choiceInfo']
if 'selectedValue' in choice_info_dto:
return self.dto[self.name]['choiceInfo']['selectedValue']
else:
return None |
<SYSTEM_TASK:>
Returns boolean indicating whether choice parameter supports custom value.
<END_TASK>
<USER_TASK:>
Description:
def allow_choice_custom_value(self):
"""
Returns boolean indicating whether choice parameter supports custom value.
If choice parameter supports custom value, user can provide parameter value
other than those provided in choice list.
""" |
if 'choiceInfo' not in self.dto[self.name]:
raise GPException('not a choice parameter')
return self._is_string_true(self.dto[self.name]['choiceInfo']['choiceAllowCustom']) |
<SYSTEM_TASK:>
Returns a list of dictionary objects, one dictionary object per choice.
<END_TASK>
<USER_TASK:>
Description:
def get_choices(self):
"""
Returns a list of dictionary objects, one dictionary object per choice.
Each object has two keys defined: 'value', 'label'.
The 'label' entry is what should be displayed on the UI, the 'value' entry
is what is written into GPJobSpec.
""" |
if 'choiceInfo' not in self.dto[self.name]:
raise GPException('not a choice parameter')
if self.get_choice_status()[1] == "NOT_INITIALIZED":
print(self.get_choice_status())
print("choice status not initialized")
request = urllib.request.Request(self.get_choice_href())
if self.task.server_data.authorization_header() is not None:
request.add_header('Authorization', self.task.server_data.authorization_header())
request.add_header('User-Agent', 'GenePatternRest')
response = urllib.request.urlopen(request)
self.dto[self.name]['choiceInfo'] = json.loads(response.read().decode('utf-8'))
return self.dto[self.name]['choiceInfo']['choices'] |
<SYSTEM_TASK:>
Returns the alternate name of a parameter.
<END_TASK>
<USER_TASK:>
Description:
def get_alt_name(self):
"""
Returns the alternate name of a parameter.
Only pipeline prompt-when-run parameters
can have alternate names and alternate descriptions
""" |
if ('altName' in self.attributes and
bool(self.attributes['altName'].strip())):
return self.attributes['altName']
else:
return None |
<SYSTEM_TASK:>
Returns the alternate description of a parameter.
<END_TASK>
<USER_TASK:>
Description:
def get_alt_description(self):
"""
Returns the alternate description of a parameter.
Only pipeline prompt-when-run parameters
can have alternate names and alternate descriptions
""" |
if 'altDescription' in self.attributes and bool(self.attributes['altDescription'].strip()):
return self.attributes['altDescription']
else:
return None |
<SYSTEM_TASK:>
Prints code and state for VM.
<END_TASK>
<USER_TASK:>
Description:
def print_code(vm, out=sys.stdout, ops_per_line=8, registers=True):
"""Prints code and state for VM.""" |
if registers:
out.write("IP: %d\n" % vm.instruction_pointer)
out.write("DS: %s\n" % str(vm.stack))
out.write("RS: %s\n" % str(vm.return_stack))
def to_str(op):
if is_embedded_push(op):
op = get_embedded_push_value(op)
if isstring(op):
return '"%s"' % repr(op)[1:-1]
elif callable(op):
return vm.lookup(op)
else:
return str(op)
for addr, op in enumerate(vm.code):
if (addr % ops_per_line) == 0 and (addr==0 or (addr+1) < len(vm.code)):
if addr > 0:
out.write("\n")
out.write("%0*d " % (max(4, len(str(len(vm.code)))), addr))
out.write("%s " % to_str(op))
out.write("\n") |
<SYSTEM_TASK:>
Starts a simple REPL for this machine.
<END_TASK>
<USER_TASK:>
Description:
def repl(optimize=True, persist=True):
"""Starts a simple REPL for this machine.
Args:
optimize: Controls whether to run inputted code through the
optimizer.
persist: If True, the machine is not deleted after each line.
""" |
print("Extra commands for the REPL:")
print(".code - print code")
print(".raw - print raw code")
print(".quit - exit immediately")
print(".reset - reset machine (IP and stacks)")
print(".restart - create a clean, new machine")
print(".clear - same as .restart")
print(".stack - print data stack")
print("")
machine = Machine([])
def match(s, *args):
return any(map(lambda arg: s.strip()==arg, args))
while True:
try:
source = raw_input("> ").strip()
if source[0] == "." and len(source) > 1:
if match(source, ".quit"):
return
elif match(source, ".code"):
print_code(machine)
elif match(source, ".raw"):
print(machine.code)
elif match(source, ".reset"):
machine.reset()
elif match(source, ".restart", ".clear"):
machine = Machine([])
elif match(source, ".stack"):
print(machine.stack)
else:
raise ParseError("Unknown command: %s" % source)
continue
code = compile(parse(source), silent=False, optimize=optimize)
if not persist:
machine.reset()
machine.code += code
machine.run()
except EOFError:
return
except KeyboardInterrupt:
return
except ParseError as e:
print("Parse error: %s" % e)
except MachineError as e:
print("Machine error: %s" % e)
except CompileError as e:
print("Compile error: %s" % e) |
<SYSTEM_TASK:>
Connect to the database and set it as main database
<END_TASK>
<USER_TASK:>
Description:
def connect(self, url: str):
"""Connect to the database and set it as main database
:param url: path to the database, uses the Sqlalchemy format
:type url: str
:example: ``ds.connect("sqlite:///mydb.slqite")``
""" |
try:
self.db = dataset.connect(url, row_type=stuf)
except Exception as e:
self.err(e, "Can not connect to database")
return
if self.db is None:
self.err("Database " + url + " not found")
return
self.ok("Db", self.db.url, "connected") |
<SYSTEM_TASK:>
Set the main dataframe from a table's data
<END_TASK>
<USER_TASK:>
Description:
def load(self, table: str):
"""Set the main dataframe from a table's data
:param table: table name
:type table: str
:example: ``ds.load("mytable")``
""" |
if self._check_db() is False:
return
if table not in self.db.tables:
self.warning("The table " + table + " does not exists")
return
try:
self.start("Loading data from table " + table)
res = self.db[table].all()
self.df = pd.DataFrame(list(res))
self.end("Data loaded from table " + table)
except Exception as e:
self.err(e, "Can not load table " + table) |
<SYSTEM_TASK:>
Load the main dataframe from a django orm query
<END_TASK>
<USER_TASK:>
Description:
def load_django(self, query: "django query"):
"""Load the main dataframe from a django orm query
:param query: django query from a model
:type query: django query
:example: ``ds.load_django(Mymodel.objects.all())``
""" |
try:
self.df = self._load_django(query)
except Exception as e:
self.err(e, "Can not load data from query") |
<SYSTEM_TASK:>
Returns a DataSwim instance from a django orm query
<END_TASK>
<USER_TASK:>
Description:
def load_django_(self, query: "django query") -> "Ds":
"""Returns a DataSwim instance from a django orm query
:param query: django query from a model
:type query: django query
:return: a dataswim instance with data from a django query
:rtype: Ds
:example: ``ds2 = ds.load_django_(Mymodel.objects.all())``
""" |
try:
df = self._load_django(query)
return self.clone_(df)
except Exception as e:
self.err(e, "Can not load data from query") |
<SYSTEM_TASK:>
Parse an RSS feed and filter only entries that are newer than yesterday.
<END_TASK>
<USER_TASK:>
Description:
def parseFeed(filename, yesterday):
"""Parse an RSS feed and filter only entries that are newer than yesterday.""" |
dom = xml.dom.minidom.parse(filename)
getText = lambda node, tag: node.getElementsByTagName(tag)[0].childNodes[0].data
getNode = lambda tag: dom.getElementsByTagName(tag)
content = getNode('channel')[0] # Only one channel node
feedTitle = getText(content, 'title')
feedLink = getText(content, 'link')
feedDesc = getText(content, 'description')
feed = Feed(feedTitle, feedLink, feedDesc)
for item in getNode('item'):
itemDate = time.strptime(getText(item, 'pubDate'), '%a, %d %b %Y %H:%M:%S GMT')
if (itemDate > yesterday): # If newer than yesterday
feed.addItem(getText(item, 'title'),
getText(item, 'link'),
getText(item, 'description'),
getText(item, 'pubDate'))
return feed |
<SYSTEM_TASK:>
Display info about the dataframe
<END_TASK>
<USER_TASK:>
Description:
def show(self, rows: int=5,
dataframe: pd.DataFrame=None) -> pd.DataFrame:
"""
Display info about the dataframe
:param rows: number of rows to show, defaults to 5
:param rows: int, optional
:param dataframe: a pandas dataframe, defaults to None
:param dataframe: pd.DataFrame, optional
:return: a pandas dataframe
:rtype: pd.DataFrame
:example: ``ds.show()``
""" |
try:
if dataframe is not None:
df = dataframe
else:
df = self.df
if df is None:
self.warning("Dataframe is empty: nothing to show")
return
num = len(df.columns.values)
except Exception as e:
self.err(e, self.show, "Can not show dataframe")
return
f = list(df)
fds = []
for fi in f:
fds.append(str(fi))
fields = ", ".join(fds)
num_rows = len(df.index)
self.info("The dataframe has", colors.bold(num_rows), "rows and",
colors.bold(num), "columns:")
print(fields)
return df.head(rows) |
<SYSTEM_TASK:>
Shows one row of the dataframe and the field
<END_TASK>
<USER_TASK:>
Description:
def one(self):
"""
Shows one row of the dataframe and the field
names wiht count
:return: a pandas dataframe
:rtype: pd.DataFrame
:example: ``ds.one()``
""" |
try:
return self.show(1)
except Exception as e:
self.err(e, self.one, "Can not display dataframe") |
<SYSTEM_TASK:>
Returns the main dataframe's tail
<END_TASK>
<USER_TASK:>
Description:
def tail(self, rows: int=5):
"""
Returns the main dataframe's tail
:param rows: number of rows to print, defaults to 5
:param rows: int, optional
:return: a pandas dataframe
:rtype: pd.DataFrame
:example: ``ds.tail()``
""" |
if self.df is None:
self.warning("Dataframe is empty: no tail available")
return self.df.tail(rows) |
<SYSTEM_TASK:>
Display types of values in a column
<END_TASK>
<USER_TASK:>
Description:
def types_(self, col: str) -> pd.DataFrame:
"""
Display types of values in a column
:param col: column name
:type col: str
:return: a pandas dataframe
:rtype: pd.DataFrame
:example: ``ds.types_("Col 1")``
""" |
cols = self.df.columns.values
all_types = {}
for col in cols:
local_types = []
for i, val in self.df[col].iteritems():
#print(i, val, type(val))
t = type(val).__name__
if t not in local_types:
local_types.append(t)
all_types[col] = (local_types, i)
df = pd.DataFrame(all_types, index=["type", "num"])
return df |
<SYSTEM_TASK:>
The main view of the Django-CMS Articles! Takes a request and a slug,
<END_TASK>
<USER_TASK:>
Description:
def article(request, slug):
"""
The main view of the Django-CMS Articles! Takes a request and a slug,
renders the article.
""" |
# Get current CMS Page as article tree
tree = request.current_page.get_public_object()
# Check whether it really is a tree.
# It could also be one of its sub-pages.
if tree.application_urls != 'CMSArticlesApp':
# In such case show regular CMS Page
return page(request, slug)
# Get an Article object from the request
draft = use_draft(request) and request.user.has_perm('cms_articles.change_article')
preview = 'preview' in request.GET and request.user.has_perm('cms_articles.change_article')
site = tree.node.site
article = get_article_from_slug(tree, slug, preview, draft)
if not article:
# raise 404
_handle_no_page(request)
request.current_article = article
if hasattr(request, 'user') and request.user.is_staff:
user_languages = get_language_list(site_id=site.pk)
else:
user_languages = get_public_languages(site_id=site.pk)
request_language = get_language_from_request(request, check_path=True)
# get_published_languages will return all languages in draft mode
# and published only in live mode.
# These languages are then filtered out by the user allowed languages
available_languages = [
language for language in user_languages
if language in list(article.get_published_languages())
]
own_urls = [
request.build_absolute_uri(request.path),
'/%s' % request.path,
request.path,
]
try:
redirect_on_fallback = get_redirect_on_fallback(request_language, site_id=site.pk)
except LanguageError:
redirect_on_fallback = False
if request_language not in user_languages:
# Language is not allowed
# Use the default site language
default_language = get_default_language_for_site(site.pk)
fallbacks = get_fallback_languages(default_language, site_id=site.pk)
fallbacks = [default_language] + fallbacks
else:
fallbacks = get_fallback_languages(request_language, site_id=site.pk)
# Only fallback to languages the user is allowed to see
fallback_languages = [
language for language in fallbacks
if language != request_language and language in available_languages
]
language_is_unavailable = request_language not in available_languages
if language_is_unavailable and not fallback_languages:
# There is no page with the requested language
# and there's no configured fallbacks
return _handle_no_page(request)
elif language_is_unavailable and redirect_on_fallback:
# There is no page with the requested language and
# the user has explicitly requested to redirect on fallbacks,
# so redirect to the first configured / available fallback language
fallback = fallback_languages[0]
redirect_url = article.get_absolute_url(fallback, fallback=False)
else:
redirect_url = False
if redirect_url:
if request.user.is_staff and hasattr(request, 'toolbar') and request.toolbar.edit_mode_active:
request.toolbar.redirect_url = redirect_url
elif redirect_url not in own_urls:
# prevent redirect to self
return HttpResponseRedirect(redirect_url)
# permission checks
if article.login_required and not request.user.is_authenticated():
return redirect_to_login(urlquote(request.get_full_path()), settings.LOGIN_URL)
if hasattr(request, 'toolbar'):
request.toolbar.obj = article
structure_requested = get_cms_setting('CMS_TOOLBAR_URL__BUILD') in request.GET
if article.has_change_permission(request) and structure_requested:
return render_object_structure(request, article)
return render_article(request, article, current_language=request_language, slug=slug) |
<SYSTEM_TASK:>
The comic strip image is in a separate page.
<END_TASK>
<USER_TASK:>
Description:
def getComicStrip(self, url, data):
"""The comic strip image is in a separate page.""" |
pageUrl = self.fetchUrl(url, data, self.indirectImageSearch)
pageData = self.getPage(pageUrl)
return super(TheThinHLine, self).getComicStrip(pageUrl, pageData) |
<SYSTEM_TASK:>
Use page URL sequence which is apparently increasing.
<END_TASK>
<USER_TASK:>
Description:
def namer(cls, imageUrl, pageUrl):
"""Use page URL sequence which is apparently increasing.""" |
num = pageUrl.split('/')[-1]
ext = imageUrl.rsplit('.', 1)[1]
return "thethinhline-%s.%s" % (num, ext) |
<SYSTEM_TASK:>
Download the data at the URL and load it as JSON
<END_TASK>
<USER_TASK:>
Description:
def download_as_json(url):
"""
Download the data at the URL and load it as JSON
""" |
try:
return Response('application/json', request(url=url)).read()
except HTTPError as err:
raise ResponseException('application/json', err) |
<SYSTEM_TASK:>
Make a request with the received arguments and return an
<END_TASK>
<USER_TASK:>
Description:
def request(*args, **kwargs):
"""
Make a request with the received arguments and return an
HTTPResponse object
""" |
timeout = kwargs.pop('timeout', 5)
req = PythonRequest(*args, **kwargs)
return REQUEST_OPENER.open(req, timeout=timeout) |
<SYSTEM_TASK:>
Send the request defined by the data stored in the object.
<END_TASK>
<USER_TASK:>
Description:
def send(self, **kwargs):
"""
Send the request defined by the data stored in the object.
""" |
return_full_object = kwargs.get('return_full_object', False)
_verbose = kwargs.get('_verbose', False)
traversal = kwargs.get('traversal', None)
timeout = kwargs.get('_timeout', 5)
self.output['url'] = self.render_url()
with VerboseContextManager(verbose=_verbose):
try:
resp = Response(self.action.format(), request(timeout=timeout, **self.output), traversal)
except HTTPError as err:
raise ResponseException(self.action.format(), err)
except socket.timeout:
raise RequestTimeout(functools.partial(self.send, **kwargs))
except URLError as err:
if isinstance(err.reason, socket.timeout):
raise RequestTimeout(functools.partial(self.send, **kwargs))
else:
raise
if return_full_object:
return resp
else:
return resp.read() |
<SYSTEM_TASK:>
Render the final URL based on available variables
<END_TASK>
<USER_TASK:>
Description:
def render_url(self):
"""
Render the final URL based on available variables
""" |
url = self.url.format(**self.replacements)
if self.params:
return url + '?' + urlencode(self.params)
return url |
<SYSTEM_TASK:>
Get the Content-Type header from the response. Strip
<END_TASK>
<USER_TASK:>
Description:
def mimetype(self):
"""
Get the Content-Type header from the response. Strip
the ";charset=xxxxx" portion if necessary. If we can't
find it, use the predefined format.
""" |
if ';' in self.headers.get('Content-Type', ''):
return self.headers['Content-Type'].split(';')[0]
return self.headers.get('Content-Type', self.static_format) |
<SYSTEM_TASK:>
Parse the body of the response using the Content-Type
<END_TASK>
<USER_TASK:>
Description:
def read(self, raw=False, perform_traversal=True):
"""
Parse the body of the response using the Content-Type
header we pulled from the response, or the hive-defined
format, if such couldn't be pulled automatically.
""" |
if not raw:
response_body = decode(self.data, self.mimetype(), encoding=self.encoding())
if perform_traversal and self.traversal is not None:
return traverse(response_body, *self.traversal)
return response_body
else:
return self.data |
<SYSTEM_TASK:>
Return the schema instance that should be used for validating and
<END_TASK>
<USER_TASK:>
Description:
def get_schema(self, *args, **kwargs):
"""
Return the schema instance that should be used for validating and
deserializing input, and for serializing output.
""" |
klass = self.get_schema_class()
# kwargs context value take precedence.
kwargs['context'] = dict(
self.get_schema_context(),
**kwargs.get('context', {})
)
return klass(*args, strict=True, **kwargs) |
<SYSTEM_TASK:>
Filter the given query using the filter classes specified on the view if any are specified.
<END_TASK>
<USER_TASK:>
Description:
def filter_query(self, query):
"""
Filter the given query using the filter classes specified on the view if any are specified.
""" |
for filter_class in list(self.filter_classes):
query = filter_class().filter_query(self.request, query, self)
return query |
<SYSTEM_TASK:>
Return single page of results or `None` if pagination is disabled.
<END_TASK>
<USER_TASK:>
Description:
def paginate_query(self, query):
"""
Return single page of results or `None` if pagination is disabled.
""" |
if self.paginator is None:
return None
return self.paginator.paginate_query(query, self.request) |
<SYSTEM_TASK:>
Drop rows with NaN values from the main dataframe
<END_TASK>
<USER_TASK:>
Description:
def drop_nan(self, col: str=None, method: str="all", **kwargs):
"""
Drop rows with NaN values from the main dataframe
:param col: name of the column, defaults to None. Drops in
all columns if no value is provided
:type col: str, optional
:param method: ``how`` param for ``df.dropna``, defaults to "all"
:type method: str, optional
:param \*\*kwargs: params for ``df.dropna``
:type \*\*kwargs: optional
:example: ``ds.drop_nan("mycol")``
""" |
try:
if col is None:
self.df = self.df.dropna(how=method, **kwargs)
else:
self.df = self.df[self.df[col].notnull()]
except Exception as e:
self.err(e, "Error dropping nan values") |
<SYSTEM_TASK:>
Fill empty values with NaN values
<END_TASK>
<USER_TASK:>
Description:
def nan_empty(self, col: str):
"""
Fill empty values with NaN values
:param col: name of the colum
:type col: str
:example: ``ds.nan_empty("mycol")``
""" |
try:
self.df[col] = self.df[col].replace('', nan)
self.ok("Filled empty values with nan in column " + col)
except Exception as e:
self.err(e, "Can not fill empty values with nan") |
<SYSTEM_TASK:>
Converts zero values to nan values in selected columns
<END_TASK>
<USER_TASK:>
Description:
def zero_nan(self, *cols):
"""
Converts zero values to nan values in selected columns
:param \*cols: names of the colums
:type \*cols: str, at least one
:example: ``ds.zero_nan("mycol1", "mycol2")``
""" |
if len(cols) == 0:
self.warning("Can not nan zero values if a column name "
"is not provided")
df = self._zero_nan(*cols)
if df is None:
self.err("Can not fill zero values with nan")
return
self.df = df |
<SYSTEM_TASK:>
Fill NaN values with new values in the main dataframe
<END_TASK>
<USER_TASK:>
Description:
def fill_nan(self, val: str, *cols):
"""
Fill NaN values with new values in the main dataframe
:param val: new value
:type val: str
:param \*cols: names of the colums
:type \*cols: str, at least one
:example: ``ds.fill_nan("new value", "mycol1", "mycol2")``
""" |
df = self._fill_nan(val, *cols)
if df is not None:
self.df = df
else:
self.err("Can not fill nan values") |
<SYSTEM_TASK:>
Fill all null values with NaN values in a column.
<END_TASK>
<USER_TASK:>
Description:
def fill_nulls(self, col: str):
"""
Fill all null values with NaN values in a column.
Null values are ``None`` or en empty string
:param col: column name
:type col: str
:example: ``ds.fill_nulls("mycol")``
""" |
n = [None, ""]
try:
self.df[col] = self.df[col].replace(n, nan)
except Exception as e:
self.err(e) |
<SYSTEM_TASK:>
Convert some column values to integers
<END_TASK>
<USER_TASK:>
Description:
def to_int(self, *cols, **kwargs):
"""
Convert some column values to integers
:param \*cols: names of the colums
:type \*cols: str, at least one
:param \*\*kwargs: keyword arguments for ``pd.to_numeric``
:type \*\*kwargs: optional
:example: ``ds.to_int("mycol1", "mycol2", errors="coerce")``
""" |
try:
for col in cols:
self.df[col] = pd.to_numeric(self.df[col], **kwargs)
except Exception as e:
self.err(e, "Can not convert column values to integer")
return
self.ok("Converted column values to integers") |
<SYSTEM_TASK:>
Convert colums values to float
<END_TASK>
<USER_TASK:>
Description:
def to_float(self, col: str, **kwargs):
"""
Convert colums values to float
:param col: name of the colum
:type col: str, at least one
:param \*\*kwargs: keyword arguments for ``df.astype``
:type \*\*kwargs: optional
:example: ``ds.to_float("mycol1")``
""" |
try:
self.df[col] = self.df[col].astype(np.float64, **kwargs)
self.ok("Converted column values to float")
except Exception as e:
self.err(e, "Error converting to float") |
<SYSTEM_TASK:>
Convert colums values to a given type in the
<END_TASK>
<USER_TASK:>
Description:
def to_type(self, dtype: type, *cols, **kwargs):
"""
Convert colums values to a given type in the
main dataframe
:param dtype: a type to convert to: ex: ``str``
:type dtype: type
:param \*cols: names of the colums
:type \*cols: str, at least one
:param \*\*kwargs: keyword arguments for ``df.astype``
:type \*\*kwargs: optional
:example: ``ds.to_type(str, "mycol")``
""" |
try:
allcols = self.df.columns.values
for col in cols:
if col not in allcols:
self.err("Column " + col + " not found")
return
self.df[col] = self.df[col].astype(dtype, **kwargs)
except Exception as e:
self.err(e, "Can not convert to type") |
<SYSTEM_TASK:>
Convert column values to formated date string
<END_TASK>
<USER_TASK:>
Description:
def fdate(self, *cols, precision: str="S", format: str=None):
"""
Convert column values to formated date string
:param \*cols: names of the colums
:type \*cols: str, at least one
:param precision: time precision: Y, M, D, H, Min S, defaults to "S"
:type precision: str, optional
:param format: python date format, defaults to None
:type format: str, optional
:example: ``ds.fdate("mycol1", "mycol2", precision)``
""" |
def formatdate(row):
return row.strftime(format)
def convert(row):
encoded = '%Y-%m-%d %H:%M:%S'
if precision == "Min":
encoded = '%Y-%m-%d %H:%M'
elif precision == "H":
encoded = '%Y-%m-%d %H'
elif precision == "D":
encoded = '%Y-%m-%d'
elif precision == "M":
encoded = '%Y-%m'
elif precision == "Y":
encoded = '%Y'
return row.strftime(encoded)
try:
for f in cols:
try:
if format is None:
self.df[f] = pd.to_datetime(self.df[f]).apply(convert)
else:
self.df[f] = pd.to_datetime(
self.df[f]).apply(formatdate)
except ValueError as e:
self.err(e, "Can not convert date")
return
except KeyError:
self.warning("Can not find colums " + " ".join(cols))
return
except Exception as e:
self.err(e, "Can not process date col") |
<SYSTEM_TASK:>
Add a timestamps column from a date column
<END_TASK>
<USER_TASK:>
Description:
def timestamps(self, col: str, **kwargs):
""""
Add a timestamps column from a date column
:param col: name of the timestamps column to add
:type col: str
:param \*\*kwargs: keyword arguments for ``pd.to_datetime``
for date conversions
:type \*\*kwargs: optional
:example: ``ds.timestamps("mycol")``
""" |
try:
name = "Timestamps"
if "name" in kwargs:
name = kwargs["name"]
if "errors" not in kwargs:
kwargs["errors"] = "coerce"
if "unit" in kwargs:
kwargs["unit"] = "ms"
try:
self.df[col] = pd.to_datetime(self.df[col], **kwargs)
except TypeError:
pass
ts = []
for el in self.df[col]:
ts.append(arrow.get(el).timestamp)
self.df[name] = ts
except Exception as e:
self.err(e, "Can not convert to timestamps") |
<SYSTEM_TASK:>
Convert a column to date type
<END_TASK>
<USER_TASK:>
Description:
def date(self, col: str, **kwargs):
"""
Convert a column to date type
:param col: column name
:type col: str
:param \*\*kwargs: keyword arguments for ``pd.to_datetime``
:type \*\*kwargs: optional
:example: ``ds.date("mycol")``
""" |
try:
self.df[col] = pd.to_datetime(self.df[col], **kwargs)
except Exception as e:
self.err(e, "Can not convert to date") |
<SYSTEM_TASK:>
Set a datetime index from a column
<END_TASK>
<USER_TASK:>
Description:
def dateindex(self, col: str):
"""
Set a datetime index from a column
:param col: column name where to index the date from
:type col: str
:example: ``ds.dateindex("mycol")``
""" |
df = self._dateindex(col)
if df is None:
self.err("Can not create date index")
return
self.df = df
self.ok("Added a datetime index from column", col) |
<SYSTEM_TASK:>
Set an index to the main dataframe
<END_TASK>
<USER_TASK:>
Description:
def index(self, col: str):
"""
Set an index to the main dataframe
:param col: column name where to index from
:type col: str
:example: ``ds.index("mycol")``
""" |
df = self._index(col)
if df is None:
self.err("Can not create index")
return
self.df = df |
<SYSTEM_TASK:>
Remove leading and trailing white spaces in a column's values
<END_TASK>
<USER_TASK:>
Description:
def strip(self, col: str):
"""
Remove leading and trailing white spaces in a column's values
:param col: name of the column
:type col: str
:example: ``ds.strip("mycol")``
""" |
def remove_ws(row):
val = str(row[col])
if " " in val.startswith(" "):
row[col] = val.strip()
return row
try:
self.df.apply(remove_ws)
except Exception as e:
self.err(e, "Can not remove white space in column")
return
self.ok("White space removed in column values") |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.