text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def should_collect(self, value): """Decide whether a given value should be collected."""
return ( # decorated with @transition isinstance(value, TransitionWrapper) # Relates to a compatible transition and value.trname in self.workflow.transitions # Either not bound to a state field or bound to the current one and (not value.field or value.field == self.state_field))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collect(self, attrs): """Collect the implementations from a given attributes dict."""
for name, value in attrs.items(): if self.should_collect(value): transition = self.workflow.transitions[value.trname] if ( value.trname in self.implementations and value.trname in self.custom_implems and name != self.transitions_at[value.trname]): # We already have an implementation registered. other_implem_at = self.transitions_at[value.trname] raise ValueError( "Error for attribute %s: it defines implementation " "%s for transition %s, which is already implemented " "at %s." % (name, value, transition, other_implem_at)) implem = self.add_implem(transition, name, value.func) self.custom_implems.add(transition.name) if value.check: implem.add_hook(Hook(HOOK_CHECK, value.check)) if value.before: implem.add_hook(Hook(HOOK_BEFORE, value.before)) if value.after: implem.add_hook(Hook(HOOK_AFTER, value.after))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_custom_implementations(self): """Retrieve a list of cutom implementations. Yields: (str, str, ImplementationProperty) tuples: The name of the attribute an implementation lives at, the name of the related transition, and the related implementation. """
for trname in self.custom_implems: attr = self.transitions_at[trname] implem = self.implementations[trname] yield (trname, attr, implem)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_function_hooks(self, func): """Looks at an object method and registers it for relevent transitions."""
for hook_kind, hooks in func.xworkflows_hook.items(): for field_name, hook in hooks: if field_name and field_name != self.state_field: continue for transition in self.workflow.transitions: if hook.applies_to(transition): implem = self.implementations[transition.name] implem.add_hook(hook)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _may_override(self, implem, other): """Checks whether an ImplementationProperty may override an attribute."""
if isinstance(other, ImplementationProperty): # Overriding another custom implementation for the same transition # and field return (other.transition == implem.transition and other.field_name == self.state_field) elif isinstance(other, TransitionWrapper): # Overriding the definition that led to adding the current # ImplementationProperty. return ( other.trname == implem.transition.name and (not other.field or other.field == self.state_field) and other.func == implem.implementation) return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fill_attrs(self, attrs): """Update the 'attrs' dict with generated ImplementationProperty."""
for trname, attrname in self.transitions_at.items(): implem = self.implementations[trname] if attrname in attrs: conflicting = attrs[attrname] if not self._may_override(implem, conflicting): raise ValueError( "Can't override transition implementation %s=%r with %r" % (attrname, conflicting, implem)) attrs[attrname] = implem return attrs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transform(self, attrs): """Perform all actions on a given attribute dict."""
self.collect(attrs) self.add_missing_implementations() self.fill_attrs(attrs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_transition(self, transition, from_state, instance, *args, **kwargs): """Log a transition. Args: transition (Transition): the name of the performed transition from_state (State): the source state instance (object): the modified object Kwargs: Any passed when calling the transition """
logger = logging.getLogger('xworkflows.transitions') try: instance_repr = u(repr(instance), 'ignore') except (UnicodeEncodeError, UnicodeDecodeError): instance_repr = u("<bad repr>") logger.info( u("%s performed transition %s.%s (%s -> %s)"), instance_repr, self.__class__.__name__, transition.name, from_state.name, transition.target.name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_workflows(mcs, attrs): """Finds all occurrences of a workflow in the attributes definitions. Returns: dict(str => StateField): maps an attribute name to a StateField describing the related Workflow. """
workflows = {} for attribute, value in attrs.items(): if isinstance(value, Workflow): workflows[attribute] = StateField(value) return workflows
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_transitions(mcs, field_name, workflow, attrs, implems=None): """Collect and enhance transition definitions to a workflow. Modifies the 'attrs' dict in-place. Args: field_name (str): name of the field transitions should update workflow (Workflow): workflow we're working on attrs (dict): dictionary of attributes to be updated. implems (ImplementationList): Implementation list from parent classes (optional) Returns: ImplementationList: The new implementation list for this field. """
new_implems = ImplementationList(field_name, workflow) if implems: new_implems.load_parent_implems(implems) new_implems.transform(attrs) return new_implems
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def update(self): "Updates cartesian coordinates for drawing tree graph" # get new shape and clear for attrs self.edges = np.zeros((self.ttree.nnodes - 1, 2), dtype=int) self.verts = np.zeros((self.ttree.nnodes, 2), dtype=float) self.lines = [] self.coords = [] # fill with updates self.update_idxs() # get dimensions of tree self.update_fixed_order() # in case ntips changed self.assign_vertices() # get node locations self.assign_coordinates() # get edge locations self.reorient_coordinates()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def update_idxs(self): "set root idx highest, tip idxs lowest ordered as ladderized" # internal nodes: root is highest idx idx = self.ttree.nnodes - 1 for node in self.ttree.treenode.traverse("levelorder"): if not node.is_leaf(): node.add_feature("idx", idx) if not node.name: node.name = str(idx) idx -= 1 # external nodes: lowest numbers are for tips (0-N) for node in self.ttree.treenode.get_leaves(): node.add_feature("idx", idx) if not node.name: node.name = str(idx) idx -= 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def tsiterator(ts, dateconverter=None, desc=None, clean=False, start_value=None, **kwargs): '''An iterator of timeseries as tuples.''' dateconverter = dateconverter or default_converter yield ['Date'] + ts.names() if clean == 'full': for dt, value in full_clean(ts, dateconverter, desc, start_value): yield (dt,) + tuple(value) else: if clean: ts = ts.clean() for dt, value in ts.items(desc=desc, start_value=start_value): dt = dateconverter(dt) yield (dt,) + tuple(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_baselines(self): """ Modify coords to shift tree position for x,y baseline arguments. This is useful for arrangeing trees onto a Canvas with other plots, but still sharing a common cartesian axes coordinates. """
if self.style.xbaseline: if self.style.orient in ("up", "down"): self.coords.coords[:, 0] += self.style.xbaseline self.coords.verts[:, 0] += self.style.xbaseline else: self.coords.coords[:, 1] += self.style.xbaseline self.coords.verts[:, 1] += self.style.xbaseline
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def add_tip_lines_to_axes(self): "add lines to connect tips to zero axis for tip_labels_align=True" # get tip-coords and align-coords from verts xpos, ypos, aedges, averts = self.get_tip_label_coords() if self.style.tip_labels_align: self.axes.graph( aedges, vcoordinates=averts, estyle=self.style.edge_align_style, vlshow=False, vsize=0, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def assign_node_labels_and_sizes(self): "assign features of nodes to be plotted based on user kwargs" # shorthand nvals = self.ttree.get_node_values() # False == Hide nodes and labels unless user entered size if self.style.node_labels is False: self.node_labels = ["" for i in nvals] if self.style.node_sizes is not None: if isinstance(self.style.node_sizes, (list, tuple, np.ndarray)): assert len(self.node_sizes) == len(self.style.node_sizes) self.node_sizes = self.style.node_sizes elif isinstance(self.style.node_sizes, (int, str)): self.node_sizes = ( [int(self.style.node_sizes)] * len(nvals) ) self.node_labels = [" " if i else "" for i in self.node_sizes] # True == Show nodes, label=idx, and show hover elif self.style.node_labels is True: # turn on node hover even if user did not set it explicit self.style.node_hover = True # get idx labels self.node_labels = self.ttree.get_node_values('idx', 1, 1) # use default node size as a list if not provided if not self.style.node_sizes: self.node_sizes = [18] * len(nvals) else: assert isinstance(self.style.node_sizes, (int, str)) self.node_sizes = ( [int(self.style.node_sizes)] * len(nvals) ) # User entered lists or other for node labels or sizes; check lengths. else: # make node labels into a list of values if isinstance(self.style.node_labels, list): assert len(self.style.node_labels) == len(nvals) self.node_labels = self.style.node_labels # check if user entered a feature else use entered val elif isinstance(self.style.node_labels, str): self.node_labels = [self.style.node_labels] * len(nvals) if self.style.node_labels in self.ttree.features: self.node_labels = self.ttree.get_node_values( self.style.node_labels, 1, 0) # default to idx at internals if nothing else else: self.node_labels = self.ttree.get_node_values("idx", 1, 0) # make node sizes as a list; set to zero if node label is "" if isinstance(self.style.node_sizes, list): assert len(self.style.node_sizes) == len(nvals) self.node_sizes = self.style.node_sizes elif isinstance(self.style.node_sizes, (str, int, float)): self.node_sizes = [int(self.style.node_sizes)] * len(nvals) else: self.node_sizes = [18] * len(nvals) # override node sizes to hide based on node labels for nidx, node in enumerate(self.node_labels): if self.node_labels[nidx] == "": self.node_sizes[nidx] = 0 # ensure string type self.node_labels = [str(i) for i in self.node_labels]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def assign_tip_labels_and_colors(self): "assign tip labels based on user provided kwargs" # COLOR # tip color overrides tipstyle.fill if self.style.tip_labels_colors: #if self.style.tip_labels_style.fill: # self.style.tip_labels_style.fill = None if self.ttree._fixed_order: if isinstance(self.style.tip_labels_colors, (list, np.ndarray)): cols = np.array(self.style.tip_labels_colors) orde = cols[self.ttree._fixed_idx] self.style.tip_labels_colors = list(orde) # LABELS # False == hide tip labels if self.style.tip_labels is False: self.style.tip_labels_style["-toyplot-anchor-shift"] = "0px" self.tip_labels = ["" for i in self.ttree.get_tip_labels()] # LABELS # user entered something... else: # if user did not change label-offset then shift it here if not self.style.tip_labels_style["-toyplot-anchor-shift"]: self.style.tip_labels_style["-toyplot-anchor-shift"] = "15px" # if user entered list in get_tip_labels order reverse it for plot if isinstance(self.style.tip_labels, list): self.tip_labels = self.style.tip_labels # True assigns tip labels from tree else: if self.ttree._fixed_order: self.tip_labels = self.ttree._fixed_order else: self.tip_labels = self.ttree.get_tip_labels()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_nodes_to_axes(self): """ Creates a new marker for every node from idx indexes and lists of node_values, node_colors, node_sizes, node_style, node_labels_style. Pulls from node_color and adds to a copy of the style dict for each node to create marker. Node_colors has priority to overwrite node_style['fill'] """
# bail out if not any visible nodes (e.g., none w/ size>0) if all([i == "" for i in self.node_labels]): return # build markers for each node. marks = [] for nidx in self.ttree.get_node_values('idx', 1, 1): # select node value from deconstructed lists nlabel = self.node_labels[nidx] nsize = self.node_sizes[nidx] nmarker = self.node_markers[nidx] # get styledict copies nstyle = deepcopy(self.style.node_style) nlstyle = deepcopy(self.style.node_labels_style) # and mod style dict copies from deconstructed lists nstyle["fill"] = self.node_colors[nidx] # create mark if text or node if (nlabel or nsize): mark = toyplot.marker.create( shape=nmarker, label=str(nlabel), size=nsize, mstyle=nstyle, lstyle=nlstyle, ) else: mark = "" # store the nodes/marks marks.append(mark) # node_hover == True to show all features interactive if self.style.node_hover is True: title = self.get_hover() elif isinstance(self.style.node_hover, list): # todo: return advice if improperly formatted title = self.style.node_hover # if hover is false then no hover else: title = None # add nodes self.axes.scatterplot( self.coords.verts[:, 0], self.coords.verts[:, 1], marker=marks, title=title, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_tip_label_coords(self): """ Get starting position of tip labels text based on locations of the leaf nodes on the tree and style offset and align options. Node positions are found using the .verts attribute of coords and is already oriented for the tree face direction. """
# number of tips ns = self.ttree.ntips # x-coordinate of tips assuming down-face tip_xpos = self.coords.verts[:ns, 0] tip_ypos = self.coords.verts[:ns, 1] align_edges = None align_verts = None # handle orientations if self.style.orient in (0, 'down'): # align tips at zero if self.style.tip_labels_align: tip_yend = np.zeros(ns) align_edges = np.array([ (i + len(tip_ypos), i) for i in range(len(tip_ypos)) ]) align_verts = np.array( list(zip(tip_xpos, tip_ypos)) + \ list(zip(tip_xpos, tip_yend)) ) tip_ypos = tip_yend else: # tip labels align finds the zero axis for orientation... if self.style.tip_labels_align: tip_xend = np.zeros(ns) align_edges = np.array([ (i + len(tip_xpos), i) for i in range(len(tip_xpos)) ]) align_verts = np.array( list(zip(tip_xpos, tip_ypos)) + \ list(zip(tip_xend, tip_ypos)) ) tip_xpos = tip_xend return tip_xpos, tip_ypos, align_edges, align_verts
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_dims_from_tree_size(self): "Calculate reasonable canvas height and width for tree given N tips" ntips = len(self.ttree) if self.style.orient in ("right", "left"): # height is long tip-wise dimension if not self.style.height: self.style.height = max(275, min(1000, 18 * ntips)) if not self.style.width: self.style.width = max(350, min(500, 18 * ntips)) else: # width is long tip-wise dimension if not self.style.height: self.style.height = max(275, min(500, 18 * ntips)) if not self.style.width: self.style.width = max(350, min(1000, 18 * ntips))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_longest_line_length(text): """Get the length longest line in a paragraph"""
lines = text.split("\n") length = 0 for i in range(len(lines)): if len(lines[i]) > length: length = len(lines[i]) return length
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def isnumeric(obj): ''' Return true if obj is a numeric value ''' from decimal import Decimal if type(obj) == Decimal: return True else: try: float(obj) except: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def significant_format(number, decimal_sep='.', thousand_sep=',', n=3): """Format a number according to a given number of significant figures. """
str_number = significant(number, n) # sign if float(number) < 0: sign = '-' else: sign = '' if str_number[0] == '-': str_number = str_number[1:] if '.' in str_number: int_part, dec_part = str_number.split('.') else: int_part, dec_part = str_number, '' if dec_part: dec_part = decimal_sep + dec_part if thousand_sep: int_part_gd = '' for cnt, digit in enumerate(int_part[::-1]): if cnt and not cnt % 3: int_part_gd += thousand_sep int_part_gd += digit int_part = int_part_gd[::-1] return sign + int_part + dec_part
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def text_to_qcolor(text): """ Create a QColor from specified string Avoid warning from Qt when an invalid QColor is instantiated """
color = QColor() if not is_string(text): # testing for QString (PyQt API#1) text = str(text) if not is_text_string(text): return color if text.startswith('#') and len(text)==7: correct = '#0123456789abcdef' for char in text: if char.lower() not in correct: return color elif text not in list(QColor.colorNames()): return color color.setNamedColor(text) return color
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_dialog(self): """Return FormDialog instance"""
dialog = self.parent() while not isinstance(dialog, QDialog): dialog = dialog.parent() return dialog
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self): """Return form result"""
# It is import to avoid accessing Qt C++ object as it has probably # already been destroyed, due to the Qt.WA_DeleteOnClose attribute if self.outfile: if self.result in ['list', 'dict', 'OrderedDict']: fd = open(self.outfile + '.py', 'w') fd.write(str(self.data)) elif self.result == 'JSON': fd = open(self.outfile + '.json', 'w') data = json.loads(self.data, object_pairs_hook=OrderedDict) json.dump(data, fd) elif self.result == 'XML': fd = open(self.outfile + '.xml', 'w') root = ET.fromstring(self.data) tree = ET.ElementTree(root) tree.write(fd, encoding='UTF-8') fd.close() else: return self.data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dates(self, desc=None): '''Returns an iterable over ``datetime.date`` instances in the timeseries.''' c = self.dateinverse for key in self.keys(desc=desc): yield c(key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def named_series(self, ordering=None): '''Generator of tuples with name and serie data.''' series = self.series() if ordering: series = list(series) todo = dict(((n, idx) for idx, n in enumerate(self.names()))) for name in ordering: if name in todo: idx = todo.pop(name) yield name, series[idx] for name in todo: idx = todo[name] yield name, series[idx] else: for name_serie in zip(self.names(), series): yield name_serie
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def clone(self, date=None, data=None, name=None): '''Create a clone of timeseries''' name = name or self.name data = data if data is not None else self.values() ts = self.__class__(name) ts._dtype = self._dtype if date is None: # dates not provided ts.make(self.keys(), data, raw=True) else: ts.make(date, data) return ts
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def isconsistent(self): '''Check if the timeseries is consistent''' for dt1, dt0 in laggeddates(self): if dt1 <= dt0: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def sd(self): '''Calculate standard deviation of timeseries''' v = self.var() if len(v): return np.sqrt(v) else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def removeduplicates(self, entries = None): ''' Loop over children a remove duplicate entries. @return - a list of removed entries ''' removed = [] if entries == None: entries = {} new_children = [] for c in self.children: cs = str(c) cp = entries.get(cs,None) if cp: new_children.append(cp) removed.append(c) else: dups = c.removeduplicates(entries) if dups: removed.extend(dups) entries[cs] = c new_children.append(c) self.children = new_children return removed
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def html2md(html_string): """ Convert a string or html file to a markdown table string. Parameters html_string : str Either the html string, or the filepath to the html Returns ------- str The html table converted to a Markdown table Notes ----- This function requires BeautifulSoup_ to work. Example ------- | Header 1 | Header 2 | Header 3 | | This is a paragraph | Just text | Hot dog | .. _BeautifulSoup: https://www.crummy.com/software/BeautifulSoup/ """
if os.path.isfile(html_string): file = open(html_string, 'r', encoding='utf-8') lines = file.readlines() file.close() html_string = ''.join(lines) table_data, spans, use_headers = html2data(html_string) if table_data == '': return '' return data2md(table_data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def table_cells_2_spans(table, spans): """ Converts the table to a list of spans, for consistency. This method combines the table data with the span data into a single, more consistent type. Any normal cell will become a span of just 1 column and 1 row. Parameters table : list of lists of str spans : list of lists of int Returns ------- table : list of lists of lists of int As you can imagine, this is pretty confusing for a human which is why data2rst accepts table data and span data separately. """
new_spans = [] for row in range(len(table)): for column in range(len(table[row])): span = get_span(spans, row, column) if not span: new_spans.append([[row, column]]) new_spans.extend(spans) new_spans = list(sorted(new_spans)) return new_spans
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def rcts(self, command, *args, **kwargs): '''General function for applying a rolling R function to a timeserie''' cls = self.__class__ name = kwargs.pop('name','') date = kwargs.pop('date',None) data = kwargs.pop('data',None) kwargs.pop('bycolumn',None) ts = cls(name=name,date=date,data=data) ts._ts = self.rc(command, *args, **kwargs) return ts
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_html_column_count(html_string): """ Gets the number of columns in an html table. Paramters --------- html_string : str Returns ------- int The number of columns in the table """
try: from bs4 import BeautifulSoup except ImportError: print("ERROR: You must have BeautifulSoup to use html2data") return soup = BeautifulSoup(html_string, 'html.parser') table = soup.find('table') if not table: return 0 column_counts = [] trs = table.findAll('tr') if len(trs) == 0: return 0 for tr in range(len(trs)): if tr == 0: tds = trs[tr].findAll('th') if len(tds) == 0: tds = trs[tr].findAll('td') else: tds = trs[tr].findAll('td') count = 0 for td in tds: if td.has_attr('colspan'): count += int(td['colspan']) else: count += 1 column_counts.append(count) return max(column_counts)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_cushions(table): """ Add space to start and end of each string in a list of lists Parameters table : list of lists of str A table of rows of strings. For example:: [ ['dog', 'cat', 'bicycle'], ['mouse', trumpet', ''] ] Returns ------- table : list of lists of str Note ---- Each cell in an rst grid table should to have a cushion of at least one space on each side of the string it contains. For example:: +-----+-------+ | foo | bar | +-----+-------+ | cat | steve | +-----+-------+ is better than:: +-----+---+ |foo| bar | +-----+---+ |cat|steve| +-----+---+ """
for row in range(len(table)): for column in range(len(table[row])): lines = table[row][column].split("\n") for i in range(len(lines)): if not lines[i] == "": lines[i] = " " + lines[i].rstrip() + " " table[row][column] = "\n".join(lines) return table
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def rollsingle(self, func, window=20, name=None, fallback=False, align='right', **kwargs): '''Efficient rolling window calculation for min, max type functions ''' rname = 'roll_{0}'.format(func) if fallback: rfunc = getattr(lib.fallback, rname) else: rfunc = getattr(lib, rname, None) if not rfunc: rfunc = getattr(lib.fallback, rname) data = np.array([list(rfunc(serie, window)) for serie in self.series()]) name = name or self.makename(func, window=window) dates = asarray(self.dates()) desc = settings.desc if (align == 'right' and not desc) or desc: dates = dates[window-1:] else: dates = dates[:-window+1] return self.clone(dates, data.transpose(), name=name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upgrade(): """Update database."""
op.create_table( 'transaction', sa.Column('issued_at', sa.DateTime(), nullable=True), sa.Column('id', sa.BigInteger(), nullable=False), sa.Column('remote_addr', sa.String(length=50), nullable=True), ) op.create_primary_key('pk_transaction', 'transaction', ['id']) if op._proxy.migration_context.dialect.supports_sequences: op.execute(CreateSequence(Sequence('transaction_id_seq')))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_newick(newick, root_node=None, format=0): """ Reads a newick tree from either a string or a file, and returns an ETE tree structure. A previously existent node object can be passed as the root of the tree, which means that all its new children will belong to the same class as the root (This allows to work with custom TreeNode objects). You can also take advantage from this behaviour to concatenate several tree structures. """
## check newick type as a string or filepath, Toytree parses urls to str's if isinstance(newick, six.string_types): if os.path.exists(newick): if newick.endswith('.gz'): import gzip nw = gzip.open(newick).read() else: nw = open(newick, 'rU').read() else: nw = newick ## get re matcher for testing newick formats matcher = compile_matchers(formatcode=format) nw = nw.strip() if not nw.startswith('(') and nw.endswith(';'): return _read_node_data(nw[:-1], root_node, "single", matcher, format) elif not nw.startswith('(') or not nw.endswith(';'): raise NewickError('Unexisting tree file or Malformed newick tree structure.') else: return _read_newick_from_string(nw, root_node, matcher, format) else: raise NewickError("'newick' argument must be either a filename or a newick string.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _read_node_data(subnw, current_node, node_type, matcher, formatcode): """ Reads a leaf node from a subpart of the original newicktree """
if node_type == "leaf" or node_type == "single": if node_type == "leaf": node = current_node.add_child() else: node = current_node else: node = current_node subnw = subnw.strip() if not subnw and node_type == 'leaf' and formatcode != 100: raise NewickError('Empty leaf node found') elif not subnw: return container1, container2, converterFn1, converterFn2, compiled_matcher = matcher[node_type] data = re.match(compiled_matcher, subnw) if data: data = data.groups() # This prevents ignoring errors even in flexible nodes: if subnw and data[0] is None and data[1] is None and data[2] is None: raise NewickError("Unexpected newick format '%s'" %subnw) if data[0] is not None and data[0] != '': node.add_feature(container1, converterFn1(data[0].strip())) if data[1] is not None and data[1] != '': node.add_feature(container2, converterFn2(data[1][1:].strip())) if data[2] is not None \ and data[2].startswith("[&&NHX"): _parse_extra_features(node, data[2]) else: raise NewickError("Unexpected newick format '%s' " %subnw[0:50]) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_newick(rootnode, features=None, format=1, format_root_node=True, is_leaf_fn=None, dist_formatter=None, support_formatter=None, name_formatter=None): """ Iteratively export a tree structure and returns its NHX representation. """
newick = [] leaf = is_leaf_fn if is_leaf_fn else lambda n: not bool(n.children) for postorder, node in rootnode.iter_prepostorder(is_leaf_fn=is_leaf_fn): if postorder: newick.append(")") if node.up is not None or format_root_node: newick.append(format_node(node, "internal", format, dist_formatter=dist_formatter, support_formatter=support_formatter, name_formatter=name_formatter)) newick.append(_get_features_string(node, features)) else: if node is not rootnode and node != node.up.children[0]: newick.append(",") if leaf(node): safe_name = re.sub("["+_ILEGAL_NEWICK_CHARS+"]", "_", \ str(getattr(node, "name"))) newick.append(format_node(node, "leaf", format, dist_formatter=dist_formatter, support_formatter=support_formatter, name_formatter=name_formatter)) newick.append(_get_features_string(node, features)) else: newick.append("(") newick.append(";") return ''.join(newick)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_features_string(self, features=None): """ Generates the extended newick string NHX with extra data about a node."""
string = "" if features is None: features = [] elif features == []: features = self.features for pr in features: if hasattr(self, pr): raw = getattr(self, pr) if type(raw) in ITERABLE_TYPES: raw = '|'.join([str(i) for i in raw]) elif type(raw) == dict: raw = '|'.join( map(lambda x,y: "%s-%s" %(x, y), six.iteritems(raw))) elif type(raw) == str: pass else: raw = str(raw) value = re.sub("["+_ILEGAL_NEWICK_CHARS+"]", "_", \ raw) if string != "": string +=":" string +="%s=%s" %(pr, str(value)) if string != "": string = "[&&NHX:"+string+"]" return string
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_column_width(column, table): """ Get the character width of a column in a table Parameters column : int The column index analyze table : list of lists of str The table of rows of strings. For this to be accurate, each string must only be 1 line long. Returns ------- width : int """
width = 3 for row in range(len(table)): cell_width = len(table[row][column]) if cell_width > width: width = cell_width return width
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def center_cell_text(cell): """ Horizontally center the text within a cell's grid Like this:: +---------+ +---------+ | foo | --> | foo | +---------+ +---------+ Parameters cell : dashtable.data2rst.Cell Returns ------- cell : dashtable.data2rst.Cell """
lines = cell.text.split('\n') cell_width = len(lines[0]) - 2 truncated_lines = [''] for i in range(1, len(lines) - 1): truncated = lines[i][2:len(lines[i]) - 2].rstrip() truncated_lines.append(truncated) truncated_lines.append('') max_line_length = get_longest_line_length('\n'.join(truncated_lines)) remainder = cell_width - max_line_length left_width = math.floor(remainder / 2) left_space = left_width * ' ' for i in range(len(truncated_lines)): truncated_lines[i] = left_space + truncated_lines[i] right_width = cell_width - len(truncated_lines[i]) truncated_lines[i] += right_width * ' ' for i in range(1, len(lines) - 1): lines[i] = ''.join([ lines[i][0], truncated_lines[i], lines[i][-1] ]) cell.text = '\n'.join(lines) return cell
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hamming_distance(word1, word2): """ Computes the Hamming distance. [Reference]: https://en.wikipedia.org/wiki/Hamming_distance [Article]: Hamming, Richard W. (1950), "Error detecting and error correcting codes", Bell System Technical Journal 29 (2): 147–160 """
from operator import ne if len(word1) != len(word2): raise WrongLengthException('The words need to be of the same length!') return sum(map(ne, word1, word2))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def polygen(*coefficients): '''Polynomial generating function''' if not coefficients: return lambda i: 0 else: c0 = coefficients[0] coefficients = coefficients[1:] def _(i): v = c0 for c in coefficients: v += c*i i *= i return v return _
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensure_table_strings(table): """ Force each cell in the table to be a string Parameters table : list of lists Returns ------- table : list of lists of str """
for row in range(len(table)): for column in range(len(table[row])): table[row][column] = str(table[row][column]) return table
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def left_sections(self): """ The number of sections that touch the left side. During merging, the cell's text will grow to include other cells. This property keeps track of the number of sections that are touching the left side. For example:: +-----+-----+ section --> | foo | dog | <-- section +-----+-----+ section --> | cat | +-----+ Has 2 sections on the left, but 1 on the right Returns ------- sections : int The number of sections on the left """
lines = self.text.split('\n') sections = 0 for i in range(len(lines)): if lines[i].startswith('+'): sections += 1 sections -= 1 return sections
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def right_sections(self): """ The number of sections that touch the right side. Returns ------- sections : int The number of sections on the right """
lines = self.text.split('\n') sections = 0 for i in range(len(lines)): if lines[i].endswith('+'): sections += 1 return sections - 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def top_sections(self): """ The number of sections that touch the top side. Returns ------- sections : int The number of sections on the top """
top_line = self.text.split('\n')[0] sections = len(top_line.split('+')) - 2 return sections
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bottom_sections(self): """ The number of cells that touch the bottom side. Returns ------- sections : int The number of sections on the top """
bottom_line = self.text.split('\n')[-1] sections = len(bottom_line.split('+')) - 2 return sections
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_header(self): """ Whether or not the cell is a header Any header cell will have "=" instead of "-" on its border. For example, this is a header cell:: +-----+ | foo | +=====+ while this cell is not:: +-----+ | foo | +-----+ Returns ------- bool Whether or not the cell is a header """
bottom_line = self.text.split('\n')[-1] if is_only(bottom_line, ['+', '=']): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_git_changeset(filename=None): """Returns a numeric identifier of the latest git changeset. The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format. This value isn't guaranteed to be unique, but collisions are very unlikely, so it's sufficient for generating the development version numbers. """
dirname = os.path.dirname(filename or __file__) git_show = sh('git show --pretty=format:%ct --quiet HEAD', cwd=dirname) timestamp = git_show.partition('\n')[0] try: timestamp = datetime.datetime.utcfromtimestamp(int(timestamp)) except ValueError: return None return timestamp.strftime('%Y%m%d%H%M%S')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_tag(node): """ Recursively go through a tag's children, converting them, then convert the tag itself. """
text = '' exceptions = ['table'] for element in node.children: if isinstance(element, NavigableString): text += element elif not node.name in exceptions: text += process_tag(element) try: convert_fn = globals()["convert_%s" % node.name.lower()] text = convert_fn(node, text) except KeyError: pass return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def laggeddates(ts, step=1): '''Lagged iterator over dates''' if step == 1: dates = ts.dates() if not hasattr(dates, 'next'): dates = dates.__iter__() dt0 = next(dates) for dt1 in dates: yield dt1, dt0 dt0 = dt1 else: while done: done += 1 lag.append(next(dates)) for dt1 in dates: lag.append(dt1) yield dt1, lag.pop(0)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def make_skiplist(*args, use_fallback=False): '''Create a new skiplist''' sl = fallback.Skiplist if use_fallback else Skiplist return sl(*args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data2md(table): """ Creates a markdown table. The first row will be headers. Parameters table : list of lists of str A list of rows containing strings. If any of these strings consist of multiple lines, they will be converted to single line because markdown tables do not support multiline cells. Returns ------- str The markdown formatted string Example ------- | Species | Coolness | | Dog | Awesome | | Cat | Meh | """
table = copy.deepcopy(table) table = ensure_table_strings(table) table = multis_2_mono(table) table = add_cushions(table) widths = [] for column in range(len(table[0])): widths.append(get_column_width(column, table)) output = '|' for i in range(len(table[0])): output = ''.join( [output, center_line(widths[i], table[0][i]), '|']) output = output + '\n|' for i in range(len(table[0])): output = ''.join([ output, center_line(widths[i], "-" * widths[i]), '|']) output = output + '\n|' for row in range(1, len(table)): for column in range(len(table[row])): output = ''.join( [output, center_line(widths[column], table[row][column]), '|']) output = output + '\n|' split = output.split('\n') split.pop() table_string = '\n'.join(split) return table_string
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def v_center_cell_text(cell): """ Vertically center the text within the cell's grid. Like this:: +--------+ +--------+ | foobar | | | | | | | | | --> | foobar | | | | | | | | | +--------+ +--------+ Parameters cell : dashtable.data2rst.Cell Returns ------- cell : dashtable.data2rst.Cell """
lines = cell.text.split('\n') cell_width = len(lines[0]) - 2 truncated_lines = [] for i in range(1, len(lines) - 1): truncated = lines[i][1:len(lines[i]) - 1] truncated_lines.append(truncated) total_height = len(truncated_lines) empty_lines_above = 0 for i in range(len(truncated_lines)): if truncated_lines[i].rstrip() == '': empty_lines_above += 1 else: break empty_lines_below = 0 for i in reversed(range(len(truncated_lines))): if truncated_lines[i].rstrip() == '': empty_lines_below += 1 else: break significant_lines = truncated_lines[ empty_lines_above:len(truncated_lines) - empty_lines_below ] remainder = total_height - len(significant_lines) blank = cell_width * ' ' above_height = math.floor(remainder / 2) for i in range(0, above_height): significant_lines.insert(0, blank) below_height = math.ceil(remainder / 2) for i in range(0, below_height): significant_lines.append(blank) for i in range(len(significant_lines)): lines[i + 1] = ''.join([ lines[i + 1][0] + significant_lines[i] + lines[i + 1][-1] ]) cell.text = '\n'.join(lines) return cell
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data2rst(table, spans=[[[0, 0]]], use_headers=True, center_cells=False, center_headers=False): """ Convert a list of lists of str into a reStructuredText Grid Table Parameters table : list of lists of str spans : list of lists of lists of int, optional These are [row, column] pairs of cells that are merged in the table. Rows and columns start in the top left of the table.For example:: +--------+--------+ | [0, 0] | [0, 1] | +--------+--------+ | [1, 0] | [1, 1] | +--------+--------+ use_headers : bool, optional Whether or not the first row of table data will become headers. center_cells : bool, optional Whether or not cells will be centered center_headers: bool, optional Whether or not headers will be centered Returns ------- str The grid table string Example ------- | Header 1 | Header 2 | Header 3 | +============+============+===========+ | body row 1 | column 2 | column 3 | | body row 2 | Cells may span columns.| | body row 3 | Cells may | - Cells | | body row 4 | | - blocks. | """
table = copy.deepcopy(table) table_ok = check_table(table) if not table_ok == "": return "ERROR: " + table_ok if not spans == [[[0, 0]]]: for span in spans: span_ok = check_span(span, table) if not span_ok == "": return "ERROR: " + span_ok table = ensure_table_strings(table) table = add_cushions(table) spans = table_cells_2_spans(table, spans) widths = get_output_column_widths(table, spans) heights = get_output_row_heights(table, spans) cells = [] for span in spans: cell = make_cell(table, span, widths, heights, use_headers) cells.append(cell) cells = list(sorted(cells)) if center_cells: for cell in cells: if not cell.is_header: center_cell_text(cell) v_center_cell_text(cell) if center_headers: for cell in cells: if cell.is_header: center_cell_text(cell) v_center_cell_text(cell) grid_table = merge_all_cells(cells) return grid_table
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def set_dims_from_tree_size(self): "Calculate reasonable height and width for tree given N tips" tlen = len(self.treelist[0]) if self.style.orient in ("right", "left"): # long tip-wise dimension if not self.style.height: self.style.height = max(275, min(1000, 18 * (tlen))) if not self.style.width: self.style.width = max(300, min(500, 18 * (tlen))) else: # long tip-wise dimension if not self.style.width: self.style.width = max(275, min(1000, 18 * (tlen))) if not self.style.height: self.style.height = max(225, min(500, 18 * (tlen)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_p(element, text): """ Adds 2 newlines to the end of text """
depth = -1 while element: if (not element.name == '[document]' and not element.parent.get('id') == '__RESTRUCTIFY_WRAPPER__'): depth += 1 element = element.parent if text: text = ' ' * depth + text return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_output_column_widths(table, spans): """ Gets the widths of the columns of the output table Parameters table : list of lists of str The table of rows of text spans : list of lists of int The [row, column] pairs of combined cells Returns ------- widths : list of int The widths of each column in the output table """
widths = [] for column in table[0]: widths.append(3) for row in range(len(table)): for column in range(len(table[row])): span = get_span(spans, row, column) column_count = get_span_column_count(span) if column_count == 1: text_row = span[0][0] text_column = span[0][1] text = table[text_row][text_column] length = get_longest_line_length(text) if length > widths[column]: widths[column] = length for row in range(len(table)): for column in range(len(table[row])): span = get_span(spans, row, column) column_count = get_span_column_count(span) if column_count > 1: text_row = span[0][0] text_column = span[0][1] text = table[text_row][text_column] end_column = text_column + column_count available_space = sum( widths[text_column:end_column]) available_space += column_count - 1 length = get_longest_line_length(text) while length > available_space: for i in range(text_column, end_column): widths[i] += 1 available_space = sum( widths[text_column:end_column]) available_space += column_count - 1 if length <= available_space: break return widths
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_empty_table(row_count, column_count): """ Make an empty table Parameters row_count : int The number of rows in the new table column_count : int The number of columns in the new table Returns ------- table : list of lists of str Each cell will be an empty str ('') """
table = [] while row_count > 0: row = [] for column in range(column_count): row.append('') table.append(row) row_count -= 1 return table
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def oftype(self, typ): '''Return a generator of formatters codes of type typ''' for key, val in self.items(): if val.type == typ: yield key
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def names(self, with_namespace=False): '''List of names for series in dataset. It will always return a list or names with length given by :class:`~.DynData.count`. ''' N = self.count() names = self.name.split(settings.splittingnames)[:N] n = 0 while len(names) < N: n += 1 names.append('unnamed%s' % n) if with_namespace and self.namespace: n = self.namespace s = settings.field_separator return [n + s + f for f in names] else: return names
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump(self, format=None, **kwargs): """Dump the timeseries using a specific ``format``. """
formatter = Formatters.get(format, None) if not format: return self.display() elif not formatter: raise FormattingException('Formatter %s not available' % format) else: return formatter(self, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_cells(cell1, cell2, direction): """ Combine the side of cell1's grid text with cell2's text. For example:: cell1 cell2 merge "RIGHT" +-----+ +------+ +-----+------+ | foo | | dog | | foo | dog | | | +------+ | +------+ | | | cat | | | cat | | | +------+ | +------+ | | | bird | | | bird | +-----+ +------+ +-----+------+ Parameters cell1 : dashtable.data2rst.Cell cell2 : dashtable.data2rst.Cell """
cell1_lines = cell1.text.split("\n") cell2_lines = cell2.text.split("\n") if direction == "RIGHT": for i in range(len(cell1_lines)): cell1_lines[i] = cell1_lines[i] + cell2_lines[i][1::] cell1.text = "\n".join(cell1_lines) cell1.column_count += cell2.column_count elif direction == "TOP": if cell1_lines[0].count('+') > cell2_lines[-1].count('+'): cell2_lines.pop(-1) else: cell1_lines.pop(0) cell2_lines.extend(cell1_lines) cell1.text = "\n".join(cell2_lines) cell1.row_count += cell2.row_count cell1.row = cell2.row cell1.column = cell2.column elif direction == "BOTTOM": if (cell1_lines[-1].count('+') > cell2_lines[0].count('+') or cell1.is_header): cell2_lines.pop(0) else: cell1_lines.pop(-1) cell1_lines.extend(cell2_lines) cell1.text = "\n".join(cell1_lines) cell1.row_count += cell2.row_count elif direction == "LEFT": for i in range(len(cell1_lines)): cell1_lines[i] = cell2_lines[i][0:-1] + cell1_lines[i] cell1.text = "\n".join(cell1_lines) cell1.column_count += cell2.column_count cell1.row = cell2.row cell1.column = cell2.column
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log(self, name, val, **tags): """Log metric name with value val. You must include at least one tag as a kwarg"""
global _last_timestamp, _last_metrics # do not allow .log after closing assert not self.done.is_set(), "worker thread has been closed" # check if valid metric name assert all(c in _valid_metric_chars for c in name), "invalid metric name " + name val = float(val) #Duck type to float/int, if possible. if int(val) == val: val = int(val) if self.host_tag and 'host' not in tags: tags['host'] = self.host_tag # get timestamp from system time, unless it's supplied as a tag timestamp = int(tags.pop('timestamp', time.time())) assert not self.done.is_set(), "tsdb object has been closed" assert tags != {}, "Need at least one tag" tagvals = ' '.join(['%s=%s' % (k, v) for k, v in tags.items()]) # OpenTSDB has major problems if you insert a data point with the same # metric, timestamp and tags. So we keep a temporary set of what points # we have sent for the last timestamp value. If we encounter a duplicate, # it is dropped. unique_str = "%s, %s, %s, %s, %s" % (name, timestamp, tagvals, self.host, self.port) if timestamp == _last_timestamp or _last_timestamp == None: if unique_str in _last_metrics: return # discard duplicate metrics else: _last_metrics.add(unique_str) else: _last_timestamp = timestamp _last_metrics.clear() line = "put %s %d %s %s\n" % (name, timestamp, val, tagvals) try: self.q.put(line, False) self.queued += 1 except queue.Full: print("potsdb - Warning: dropping oldest metric because Queue is full. Size: %s" % self.q.qsize(), file=sys.stderr) self.q.get() #Drop the oldest metric to make room self.q.put(line, False) return line
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def available_ports(): """ Scans COM1 through COM255 for available serial ports returns a list of available ports """
ports = [] for i in range(256): try: p = Serial('COM%d' % i) p.close() ports.append(p) except SerialException: pass return ports
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_current_response(self): """ reads the current response data from the object and returns it in a dict. Currently 'time' is reported as 0 until clock drift issues are resolved. """
response = {'port': 0, 'pressed': False, 'key': 0, 'time': 0} if len(self.__response_structs_queue) > 0: # make a copy just in case any other internal members of # XidConnection were tracking the structure response = self.__response_structs_queue[0].copy() # we will now hand over 'response' to the calling code, # so remove it from the internal queue self.__response_structs_queue.pop(0) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def detect_xid_devices(self): """ For all of the com ports connected to the computer, send an XID command '_c1'. If the device response with '_xid', it is an xid device. """
self.__xid_cons = [] for c in self.__com_ports: device_found = False for b in [115200, 19200, 9600, 57600, 38400]: con = XidConnection(c, b) try: con.open() except SerialException: continue con.flush_input() con.flush_output() returnval = con.send_xid_command("_c1", 5).decode('ASCII') if returnval.startswith('_xid'): device_found = True self.__xid_cons.append(con) if(returnval != '_xid0'): # set the device into XID mode con.send_xid_command('c10') con.flush_input() con.flush_output() # be sure to reset the timer to avoid the 4.66 hours # problem. (refer to XidConnection.xid_input_found to # read about the 4.66 hours) con.send_xid_command('e1') con.send_xid_command('e5') con.close() if device_found: break
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def device_at_index(self, index): """ Returns the device at the specified index """
if index >= len(self.__xid_cons): raise ValueError("Invalid device index") return self.__xid_cons[index]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query_base_timer(self): """ gets the value from the device's base timer """
(_, _, time) = unpack('<ccI', self.con.send_xid_command("e3", 6)) return time
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def poll_for_response(self): """ Polls the device for user input If there is a keymapping for the device, the key map is applied to the key reported from the device. If a response is waiting to be processed, the response is appended to the internal response_queue """
key_state = self.con.check_for_keypress() if key_state != NO_KEY_DETECTED: response = self.con.get_current_response() if self.keymap is not None: response['key'] = self.keymap[response['key']] else: response['key'] -= 1 self.response_queue.append(response)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_pulse_duration(self, duration): """ Sets the pulse duration for events in miliseconds when activate_line is called """
if duration > 4294967295: raise ValueError('Duration is too long. Please choose a value ' 'less than 4294967296.') big_endian = hex(duration)[2:] if len(big_endian) % 2 != 0: big_endian = '0'+big_endian little_endian = [] for i in range(0, len(big_endian), 2): little_endian.insert(0, big_endian[i:i+2]) for i in range(0, 4-len(little_endian)): little_endian.append('00') command = 'mp' for i in little_endian: command += chr(int(i, 16)) self.con.send_xid_command(command, 0)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def activate_line(self, lines=None, bitmask=None, leave_remaining_lines=False): """ Triggers an output line on StimTracker. There are 8 output lines on StimTracker that can be raised in any combination. To raise lines 1 and 7, for example, you pass in the list: activate_line(lines=[1, 7]). To raise a single line, pass in just an integer, or a list with a single element to the lines keyword argument: activate_line(lines=3) or activate_line(lines=[3]) The `lines` argument must either be an Integer, list of Integers, or None. If you'd rather specify a bitmask for setting the lines, you can use the bitmask keyword argument. Bitmask must be a Integer value between 0 and 255 where 0 specifies no lines, and 255 is all lines. For a mapping between lines and their bit values, see the `_lines` class variable. To use this, call the function as so to activate lines 1 and 6: activate_line(bitmask=33) leave_remaining_lines tells the function to only operate on the lines specified. For example, if lines 1 and 8 are active, and you make the following function call: activate_line(lines=4, leave_remaining_lines=True) This will result in lines 1, 4 and 8 being active. If you call activate_line(lines=4) with leave_remaining_lines=False (the default), if lines 1 and 8 were previously active, only line 4 will be active after the call. """
if lines is None and bitmask is None: raise ValueError('Must set one of lines or bitmask') if lines is not None and bitmask is not None: raise ValueError('Can only set one of lines or bitmask') if bitmask is not None: if bitmask not in range(0, 256): raise ValueError('bitmask must be an integer between ' '0 and 255') if lines is not None: if not isinstance(lines, list): lines = [lines] bitmask = 0 for l in lines: if l < 1 or l > 8: raise ValueError('Line numbers must be between 1 and 8 ' '(inclusive)') bitmask |= self._lines[l] self.con.set_digital_output_lines(bitmask, leave_remaining_lines)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_line(self, lines=None, bitmask=None, leave_remaining_lines=False): """ The inverse of activate_line. If a line is active, it deactivates it. This has the same parameters as activate_line() """
if lines is None and bitmask is None: raise ValueError('Must set one of lines or bitmask') if lines is not None and bitmask is not None: raise ValueError('Can only set one of lines or bitmask') if bitmask is not None: if bitmask not in range(0, 256): raise ValueError('bitmask must be an integer between ' '0 and 255') if lines is not None: if not isinstance(lines, list): lines = [lines] bitmask = 0 for l in lines: if l < 1 or l > 8: raise ValueError('Line numbers must be between 1 and 8 ' '(inclusive)') bitmask |= self._lines[l] self.con.clear_digital_output_lines(bitmask, leave_remaining_lines)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_device(self): """ Initializes the device with the proper keymaps and name """
try: product_id = int(self._send_command('_d2', 1)) except ValueError: product_id = self._send_command('_d2', 1) if product_id == 0: self._impl = ResponseDevice( self.con, 'Cedrus Lumina LP-400 Response Pad System', lumina_keymap) elif product_id == 1: self._impl = ResponseDevice( self.con, 'Cedrus SV-1 Voice Key', None, 'Voice Response') elif product_id == 2: model_id = int(self._send_command('_d3', 1)) if model_id == 1: self._impl = ResponseDevice( self.con, 'Cedrus RB-530', rb_530_keymap) elif model_id == 2: self._impl = ResponseDevice( self.con, 'Cedrus RB-730', rb_730_keymap) elif model_id == 3: self._impl = ResponseDevice( self.con, 'Cedrus RB-830', rb_830_keymap) elif model_id == 4: self._impl = ResponseDevice( self.con, 'Cedrus RB-834', rb_834_keymap) else: raise XidError('Unknown RB Device') elif product_id == 4: self._impl = StimTracker( self.con, 'Cedrus C-POD') elif product_id == b'S': self._impl = StimTracker( self.con, 'Cedrus StimTracker') elif product_id == -99: raise XidError('Invalid XID device')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _send_command(self, command, expected_bytes): """ Send an XID command to the device """
response = self.con.send_xid_command(command, expected_bytes) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_xid_devices(): """ Returns a list of all Xid devices connected to your computer. """
devices = [] scanner = XidScanner() for i in range(scanner.device_count()): com = scanner.device_at_index(i) com.open() device = XidDevice(com) devices.append(device) return devices
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_xid_device(device_number): """ returns device at a given index. Raises ValueError if the device at the passed in index doesn't exist. """
scanner = XidScanner() com = scanner.device_at_index(device_number) com.open() return XidDevice(com)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(self, receiver): """Append receiver."""
if not callable(receiver): raise ValueError('Invalid receiver: %s' % receiver) self.receivers.append(receiver)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disconnect(self, receiver): """Remove receiver."""
try: self.receivers.remove(receiver) except ValueError: raise ValueError('Unknown receiver: %s' % receiver)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select(cls, *args, **kwargs): """Support read slaves."""
query = super(Model, cls).select(*args, **kwargs) query.database = cls._get_read_database() return query
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_app(self, app, database=None): """Initialize application."""
# Register application if not app: raise RuntimeError('Invalid application.') self.app = app if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['peewee'] = self app.config.setdefault('PEEWEE_CONNECTION_PARAMS', {}) app.config.setdefault('PEEWEE_DATABASE_URI', 'sqlite:///peewee.sqlite') app.config.setdefault('PEEWEE_MANUAL', False) app.config.setdefault('PEEWEE_MIGRATE_DIR', 'migrations') app.config.setdefault('PEEWEE_MIGRATE_TABLE', 'migratehistory') app.config.setdefault('PEEWEE_MODELS_CLASS', Model) app.config.setdefault('PEEWEE_MODELS_IGNORE', []) app.config.setdefault('PEEWEE_MODELS_MODULE', '') app.config.setdefault('PEEWEE_READ_SLAVES', '') app.config.setdefault('PEEWEE_USE_READ_SLAVES', True) # Initialize database params = app.config['PEEWEE_CONNECTION_PARAMS'] database = database or app.config.get('PEEWEE_DATABASE_URI') if not database: raise RuntimeError('Invalid database.') database = get_database(database, **params) slaves = app.config['PEEWEE_READ_SLAVES'] if isinstance(slaves, string_types): slaves = slaves.split(',') self.slaves = [get_database(slave, **params) for slave in slaves if slave] self.database.initialize(database) if self.database.database == ':memory:': app.config['PEEWEE_MANUAL'] = True if not app.config['PEEWEE_MANUAL']: app.before_request(self.connect) app.teardown_request(self.close)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self, response): """Close connection to database."""
LOGGER.info('Closing [%s]', os.getpid()) if not self.database.is_closed(): self.database.close() return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Model(self): """Bind model to self database."""
Model_ = self.app.config['PEEWEE_MODELS_CLASS'] meta_params = {'database': self.database} if self.slaves and self.app.config['PEEWEE_USE_READ_SLAVES']: meta_params['read_slaves'] = self.slaves Meta = type('Meta', (), meta_params) return type('Model', (Model_,), {'Meta': Meta})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def models(self): """Return self.application models."""
Model_ = self.app.config['PEEWEE_MODELS_CLASS'] ignore = self.app.config['PEEWEE_MODELS_IGNORE'] models = [] if Model_ is not Model: try: mod = import_module(self.app.config['PEEWEE_MODELS_MODULE']) for model in dir(mod): models = getattr(mod, model) if not isinstance(model, pw.Model): continue models.append(models) except ImportError: return models elif isinstance(Model_, BaseSignalModel): models = BaseSignalModel.models return [m for m in models if m._meta.name not in ignore]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cmd_create(self, name, auto=False): """Create a new migration."""
LOGGER.setLevel('INFO') LOGGER.propagate = 0 router = Router(self.database, migrate_dir=self.app.config['PEEWEE_MIGRATE_DIR'], migrate_table=self.app.config['PEEWEE_MIGRATE_TABLE']) if auto: auto = self.models router.create(name, auto=auto)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cmd_rollback(self, name): """Rollback migrations."""
from peewee_migrate.router import Router, LOGGER LOGGER.setLevel('INFO') LOGGER.propagate = 0 router = Router(self.database, migrate_dir=self.app.config['PEEWEE_MIGRATE_DIR'], migrate_table=self.app.config['PEEWEE_MIGRATE_TABLE']) router.rollback(name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cmd_merge(self): """Merge migrations."""
from peewee_migrate.router import Router, LOGGER LOGGER.setLevel('DEBUG') LOGGER.propagate = 0 router = Router(self.database, migrate_dir=self.app.config['PEEWEE_MIGRATE_DIR'], migrate_table=self.app.config['PEEWEE_MIGRATE_TABLE']) router.merge()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def manager(self): """Integrate a Flask-Script."""
from flask_script import Manager, Command manager = Manager(usage="Migrate database.") manager.add_command('create', Command(self.cmd_create)) manager.add_command('migrate', Command(self.cmd_migrate)) manager.add_command('rollback', Command(self.cmd_rollback)) manager.add_command('list', Command(self.cmd_list)) manager.add_command('merge', Command(self.cmd_merge)) return manager
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def markup_line(text, offset, marker='>>!<<'): """Insert `marker` at `offset` into `text`, and return the marked line. .. code-block:: python 1>>!<<234 """
begin = text.rfind('\n', 0, offset) begin += 1 end = text.find('\n', offset) if end == -1: end = len(text) return text[begin:offset] + marker + text[offset:end]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rescale(self, factor=1.0, allow_cast=True): """ Rescales self.y by given factor, if allow_cast is set to True and division in place is impossible - casting and not in place division may occur occur. If in place is impossible and allow_cast is set to False - an exception is raised. Check simple rescaling by 2 with no casting [0. 2.5 5. ] Check rescaling with floor division [0 3 6] [ 0 -5 -10] :param factor: rescaling factor, should be a number :param allow_cast: bool - allow division not in place """
try: self.y /= factor except TypeError as e: logger.warning("Division in place is impossible: %s", e) if allow_cast: self.y = self.y / factor else: logger.error("allow_cast flag set to True should help") raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def change_domain(self, domain): """ Creating new Curve object in memory with domain passed as a parameter. New domain must include in the original domain. Copies values from original curve and uses interpolation to calculate values for new points in domain. Calculate y - values of example curve with changed domain: .change_domain([1, 2, 8, 9]).y) [1. 2. 2. 1.] :param domain: set of points representing new domain. Might be a list or np.array. :return: new Curve object with domain set by 'domain' parameter """
logger.info('Running %(name)s.change_domain() with new domain range:[%(ymin)s, %(ymax)s]', {"name": self.__class__, "ymin": np.min(domain), "ymax": np.max(domain)}) # check if new domain includes in the original domain if np.max(domain) > np.max(self.x) or np.min(domain) < np.min(self.x): logger.error('Old domain range: [%(xmin)s, %(xmax)s] does not include new domain range:' '[%(ymin)s, %(ymax)s]', {"xmin": np.min(self.x), "xmax": np.max(self.x), "ymin": np.min(domain), "ymax": np.max(domain)}) raise ValueError('in change_domain():' 'the old domain does not include the new one') y = np.interp(domain, self.x, self.y) # We need to join together domain and values (y) because we are recreating Curve object # (we pass it as argument to self.__class__) # np.dstack((arrays), axis=1) joins given arrays like np.dstack() but it also nests the result # in additional list and this is the reason why we use [0] to remove this extra layer of list like this: # np.dstack([[0, 5, 10], [0, 0, 0]]) gives [[[ 0, 0], [ 5, 0], [10, 0]]] so use dtack()[0] # to get this: [[0,0], [5, 5], [10, 0]] # which is a 2 dimensional array and can be used to create a new Curve object obj = self.__class__(np.dstack((domain, y))[0], **self.__dict__['metadata']) return obj
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def medfilt(vector, window): """ Apply a window-length median filter to a 1D array vector. Should get rid of 'spike' value 15. [1. 1. 1. 1. 1.] [15. 1. 1. 1. 1.] Inspired by: https://gist.github.com/bhawkins/3535131 """
if not window % 2 == 1: raise ValueError("Median filter length must be odd.") if not vector.ndim == 1: raise ValueError("Input must be one-dimensional.") k = (window - 1) // 2 # window movement result = np.zeros((len(vector), window), dtype=vector.dtype) result[:, k] = vector for i in range(k): j = k - i result[j:, i] = vector[:-j] result[:j, i] = vector[0] result[:-j, -(i + 1)] = vector[j:] result[-j:, -(i + 1)] = vector[-1] return np.median(result, axis=1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def model_fields(model, allow_pk=False, only=None, exclude=None, field_args=None, converter=None): """ Generate a dictionary of fields for a given Peewee model. See `model_form` docstring for description of parameters. """
converter = converter or ModelConverter() field_args = field_args or {} model_fields = list(model._meta.sorted_fields) if not allow_pk: model_fields.pop(0) if only: model_fields = [x for x in model_fields if x.name in only] elif exclude: model_fields = [x for x in model_fields if x.name not in exclude] field_dict = {} for model_field in model_fields: name, field = converter.convert( model, model_field, field_args.get(model_field.name)) field_dict[name] = field return field_dict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prompt(text='', title='' , default='', root=None, timeout=None): """Displays a message box with text input, and OK & Cancel buttons. Returns the text entered, or None if Cancel was clicked."""
assert TKINTER_IMPORT_SUCCEEDED, 'Tkinter is required for pymsgbox' return __fillablebox(text, title, default=default, mask=None,root=root, timeout=timeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_line(line): """Reads lines of XML and delimits, strips, and returns."""
name, value = '', '' if '=' in line: name, value = line.split('=', 1) return [name.strip(), value.strip()]