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 read_dataframe_from_xls(desired_type: Type[T], file_path: str, encoding: str, logger: Logger, **kwargs) -> pd.DataFrame: """ We register this method rather th...
return pd.read_excel(file_path, **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 read_df_or_series_from_csv(desired_type: Type[pd.DataFrame], file_path: str, encoding: str, logger: Logger, **kwargs) -> pd.DataFrame: """ Helper method to re...
if desired_type is pd.Series: # as recommended in http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.from_csv.html # and from http://stackoverflow.com/questions/15760856/how-to-read-a-pandas-series-from-a-csv-file # TODO there should be a way to decide between row-oriented...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dict_to_df(desired_type: Type[T], dict_obj: Dict, logger: Logger, orient: str = None, **kwargs) -> pd.DataFrame: """ Helper method to convert a dictionary int...
if len(dict_obj) > 0: first_val = dict_obj[next(iter(dict_obj))] if isinstance(first_val, dict) or isinstance(first_val, list): # --'full' table # default is index orientation orient = orient or 'index' # if orient is 'columns': # r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def single_row_or_col_df_to_series(desired_type: Type[T], single_rowcol_df: pd.DataFrame, logger: Logger, **kwargs)\ -> pd.Series: """ Helper method to convert a ...
if single_rowcol_df.shape[0] == 1: # one row return single_rowcol_df.transpose()[0] elif single_rowcol_df.shape[1] == 2 and isinstance(single_rowcol_df.index, pd.RangeIndex): # two columns but the index contains nothing but the row number : we can use the first column d = single...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def single_row_or_col_df_to_dict(desired_type: Type[T], single_rowcol_df: pd.DataFrame, logger: Logger, **kwargs)\ -> Dict[str, str]: """ Helper method to convert...
if single_rowcol_df.shape[0] == 1: return single_rowcol_df.transpose()[0].to_dict() # return {col_name: single_rowcol_df[col_name][single_rowcol_df.index.values[0]] for col_name in single_rowcol_df.columns} elif single_rowcol_df.shape[1] == 2 and isinstance(single_rowcol_df.index, pd.RangeIndex...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def full_subgraph(self, vertices): """ Return the subgraph of this graph whose vertices are the given ones and whose edges are all the edges of the original grap...
subgraph_vertices = {v for v in vertices} subgraph_edges = {edge for v in subgraph_vertices for edge in self._out_edges[v] if self._heads[edge] in subgraph_vertices} subgraph_heads = {edge: self._heads[edge] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _raw(cls, vertices, edges, heads, tails): """ Private constructor for direct construction of a DirectedGraph from its consituents. """
self = object.__new__(cls) self._vertices = vertices self._edges = edges self._heads = heads self._tails = tails # For future use, map each vertex to its outward and inward edges. # These could be computed on demand instead of precomputed. self._out_edge...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_out_edges(cls, vertices, edge_mapper): """ Create a DirectedGraph from a collection of vertices and a mapping giving the vertices that each vertex is co...
vertices = set(vertices) edges = set() heads = {} tails = {} # Number the edges arbitrarily. edge_identifier = itertools.count() for tail in vertices: for head in edge_mapper[tail]: edge = next(edge_identifier) edges.a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_edge_pairs(cls, vertices, edge_pairs): """ Create a DirectedGraph from a collection of vertices and a collection of pairs giving links between the verti...
vertices = set(vertices) edges = set() heads = {} tails = {} # Number the edges arbitrarily. edge_identifier = itertools.count() for tail, head in edge_pairs: edge = next(edge_identifier) edges.add(edge) heads[edge] = head ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def annotated(self): """ Return an AnnotatedGraph with the same structure as this graph. """
annotated_vertices = { vertex: AnnotatedVertex( id=vertex_id, annotation=six.text_type(vertex), ) for vertex_id, vertex in zip(itertools.count(), self.vertices) } annotated_edges = [ AnnotatedEdge( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(self): """ read dotfile and populate self opts will override the dotfile settings, make sure everything is synced in both opts and this object """
if self.exists(): with open(self.dot_file, 'r') as handle: self.update(json.load(handle)) if self.options['context'] is not None: self['context'] = self.options['context'] else: self.options['context'] = self['context'] if self.options...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def env_dictionary(self): """ convert the options to this script into an env var dictionary for pre and post scripts """
none_to_str = lambda x: str(x) if x else "" return {"DOCKERSTACHE_{}".format(k.upper()): none_to_str(v) for k, v in six.iteritems(self)}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pre_script(self): """ execute the pre script if it is defined """
if self['pre_script'] is None: return LOGGER.info("Executing pre script: {}".format(self['pre_script'])) cmd = self['pre_script'] execute_command(self.abs_input_dir(), cmd, self.env_dictionary()) LOGGER.info("Pre Script completed")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def say_tmp_filepath( text = None, preference_program = "festival" ): """ Say specified text to a temporary file and return the filepath. """
filepath = shijian.tmp_filepath() + ".wav" say( text = text, preference_program = preference_program, filepath = filepath ) return filepath
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clacks_overhead(fn): """ A Django view decorator that will add the `X-Clacks-Overhead` header. Usage: @clacks_overhead def my_view(request): return my_respo...
@wraps(fn) def _wrapped(*args, **kw): response = fn(*args, **kw) response['X-Clacks-Overhead'] = 'GNU Terry Pratchett' return response return _wrapped
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render(self, request, template, context): """ Returns a response. By default, this will contain the rendered PDF, but if both ``allow_force_html`` is ``True`...
if self.allow_force_html and self.request.GET.get('html', False): html = get_template(template).render(context) return HttpResponse(html) else: response = HttpResponse(content_type='application/pdf') if self.prompt_download: response['Cont...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replace(self, s, data, attrs=None): """ Replace the attributes of the plotter data in a string %(replace_note)s Parameters s: str String where the replacemen...
# insert labels s = s.format(**self.rc['labels']) # replace attributes attrs = attrs or data.attrs if hasattr(getattr(data, 'psy', None), 'arr_name'): attrs = attrs.copy() attrs['arr_name'] = data.psy.arr_name s = safe_modulo(s, attrs) # r...
<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_fig_data_attrs(self, delimiter=None): """Join the data attributes with other plotters in the project This method joins the attributes of the :class:`~psy...
if self.project is not None: delimiter = next(filter(lambda d: d is not None, [ delimiter, self.delimiter, self.rc['delimiter']])) figs = self.project.figs fig = self.ax.get_figure() if self.plotter._initialized and fig in figs: re...
<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_fmt_widget(self, parent, project): """Create a combobox with the attributes"""
from psy_simple.widgets.texts import LabelWidget return LabelWidget(parent, self, project)
<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_other_texts(self, remove=False): """Make sure that no other text is a the same position as this one This method clears all text instances in the figure...
fig = self.ax.get_figure() # don't do anything if our figtitle is the only Text instance if len(fig.texts) == 1: return for i, text in enumerate(fig.texts): if text == self._text: continue if text.get_position() == self._text.get_posit...
<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): """Dictionary containing the relevant transformations"""
ax = self.ax return {'axes': ax.transAxes, 'fig': ax.get_figure().transFigure, 'data': ax.transData}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _remove_texttuple(self, pos): """Remove a texttuple from the value in the plotter Parameters pos: tuple (x, y, cs) x and y are the x- and y-positions and cs ...
for i, (old_x, old_y, s, old_cs, d) in enumerate(self.value): if (old_x, old_y, old_cs) == pos: self.value.pop(i) return raise ValueError("{0} not found!".format(pos))
<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_texttuple(self, x, y, s, cs, d): """Update the text tuple at `x` and `y` with the given `s` and `d`"""
pos = (x, y, cs) for i, (old_x, old_y, old_s, old_cs, old_d) in enumerate(self.value): if (old_x, old_y, old_cs) == pos: self.value[i] = (old_x, old_y, s, old_cs, d) return raise ValueError("No text tuple found at {0}!".format(pos))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def share(self, fmto, **kwargs): """Share the settings of this formatoption with other data objects Parameters fmto: Formatoption The :class:`Formatoption` insta...
kwargs.setdefault('texts_to_remove', self._texts_to_remove) super(Text, self).share(fmto, **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 preprocess_cell( self, cell: "NotebookNode", resources: dict, index: int ) -> Tuple["NotebookNode", dict]: """Preprocess cell. Parameters cell : NotebookNode ...
if cell.cell_type == "markdown": variables = cell["metadata"].get("variables", {}) if len(variables) > 0: cell.source = self.replace_variables(cell.source, variables) if resources.get("delete_pymarkdown", False): del cell.metadata["var...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def index_dir(self, folder): """ Creates a nested dictionary that represents the folder structure of folder. Also extracts meta data from all markdown posts and ...
folder_path = folder print('Indexing folder: ' + folder_path) nested_dir = {} folder = folder_path.rstrip(os.sep) start = folder.rfind(os.sep) + 1 for root, dirs, files in os.walk(folder): folders = root[start:].split(os.sep) # subdir = dict.fromk...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cycles_created_by(callable): """ Return graph of cyclic garbage created by the given callable. Return an :class:`~refcycle.object_graph.ObjectGraph` represen...
with restore_gc_state(): gc.disable() gc.collect() gc.set_debug(gc.DEBUG_SAVEALL) callable() new_object_count = gc.collect() if new_object_count: objects = gc.garbage[-new_object_count:] del gc.garbage[-new_object_count:] else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def snapshot(): """Return the graph of all currently gc-tracked objects. Excludes the returned :class:`~refcycle.object_graph.ObjectGraph` and objects owned by i...
all_objects = gc.get_objects() this_frame = inspect.currentframe() selected_objects = [] for obj in all_objects: if obj is not this_frame: selected_objects.append(obj) graph = ObjectGraph(selected_objects) del this_frame, all_objects, selected_objects, obj return graph
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extendMarkdown(self, md, md_globals): """ Every extension requires a extendMarkdown method to tell the markdown renderer how use the extension. """
md.registerExtension(self) for processor in (self.preprocessors or []): md.preprocessors.add(processor.__name__.lower(), processor(md), '_end') for pattern in (self.inlinepatterns or []): md.inlinePatterns.add(pattern.__name__.lower(), pattern(md), '_end') for...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run( paths, output=_I_STILL_HATE_EVERYTHING, recurse=core.flat, sort_by=None, ls=core.ls, stdout=stdout, ): """ Project-oriented directory and file informati...
if output is _I_STILL_HATE_EVERYTHING: output = core.columnized if stdout.isatty() else core.one_per_line if sort_by is None: if output == core.as_tree: def sort_by(thing): return ( thing.parent(), thing.basename().lstrip(stri...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getCustomLogger(name, logLevel, logFormat='%(asctime)s %(levelname)-9s:%(name)s:%(module)s:%(funcName)s: %(message)s'): ''' Set up logging :param str name: What log level to set :param str logLevel: What log level to use :param str logFormat: Format string for logging :rtype: logger ''' assert isin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def mkdir_p(path): ''' Mimic `mkdir -p` since os module doesn't provide one. :param str path: directory to create ''' assert isinstance(path, basestring), ("path must be a string but is %r" % path) try: os.makedirs(path) except OSError as exception: if exception.errno != errno.EEXIST: 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 setup_exchanges(app): """ Setup result exchange to route all tasks to platform queue. """
with app.producer_or_acquire() as P: # Ensure all queues are noticed and configured with their # appropriate exchange. for q in app.amqp.queues.values(): P.maybe_declare(q)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_app(app, throw=True): """ Ensure application is set up to expected configuration. This function is typically triggered by the worker_init signal, howev...
success = True try: for func in SETUP_FUNCS: try: func(app) except Exception: success = False if throw: raise else: msg = "Failed to run setup function %r(app)" ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _poplast(self): """For avoiding lock during inserting to keep maxlen"""
try: tup = self.data.pop() except IndexError as ex: ex.args = ('DEPQ is already empty',) raise self_items = self.items try: self_items[tup[0]] -= 1 if self_items[tup[0]] == 0: del self_items[tup[0]] e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def DatabaseEnabled(cls): """Given persistence methods to classes with this annotation. All this really does is add some functions that forward to the mapped dat...
if not issubclass(cls, Storable): raise ValueError( "%s is not a subclass of gludb.datab.Storage" % repr(cls) ) cls.ensure_table = classmethod(_ensure_table) cls.find_one = classmethod(_find_one) cls.find_all = classmethod(_find_all) cls.find_by_index = classmethod(_fin...
<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_playlist(self): """ Internal method to populate the object given the ``id`` or ``reference_id`` that has been set in the constructor. """
data = None if self.id: data = self.connection.get_item( 'find_playlist_by_id', playlist_id=self.id) elif self.reference_id: data = self.connection.get_item( 'find_playlist_by_reference_id', reference_id=self.reference_id) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _to_dict(self): """ Internal method that serializes object into a dictionary. """
data = { 'name': self.name, 'referenceId': self.reference_id, 'shortDescription': self.short_description, 'playlistType': self.type, 'id': self.id} if self.videos: for video in self.videos: if video.id not in self.v...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load(self, data): """ Internal method that deserializes a ``pybrightcove.playlist.Playlist`` object. """
self.raw_data = data self.id = data['id'] self.reference_id = data['referenceId'] self.name = data['name'] self.short_description = data['shortDescription'] self.thumbnail_url = data['thumbnailURL'] self.videos = [] self.video_ids = data['videoIds'] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self): """ Create or update a playlist. """
d = self._to_dict() if len(d.get('videoIds', [])) > 0: if not self.id: self.id = self.connection.post('create_playlist', playlist=d) else: data = self.connection.post('update_playlist', playlist=d) if data: self...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, cascade=False): """ Deletes this playlist. """
if self.id: self.connection.post('delete_playlist', playlist_id=self.id, cascade=cascade) self.id = 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 find_all(connection=None, page_size=100, page_number=0, sort_by=DEFAULT_SORT_BY, sort_order=DEFAULT_SORT_ORDER): """ List all playlists. """
return pybrightcove.connection.ItemResultSet("find_all_playlists", Playlist, connection, page_size, page_number, sort_by, sort_order)
<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_by_ids(ids, connection=None, page_size=100, page_number=0, sort_by=DEFAULT_SORT_BY, sort_order=DEFAULT_SORT_ORDER): """ List playlists by specific IDs. ...
ids = ','.join([str(i) for i in ids]) return pybrightcove.connection.ItemResultSet('find_playlists_by_ids', Playlist, connection, page_size, page_number, sort_by, sort_order, playlist_ids=ids)
<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_by_reference_ids(reference_ids, connection=None, page_size=100, page_number=0, sort_by=DEFAULT_SORT_BY, sort_order=DEFAULT_SORT_ORDER): """ List playlis...
reference_ids = ','.join([str(i) for i in reference_ids]) return pybrightcove.connection.ItemResultSet( "find_playlists_by_reference_ids", Playlist, connection, page_size, page_number, sort_by, sort_order, reference_ids=reference_ids)
<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_for_player_id(player_id, connection=None, page_size=100, page_number=0, sort_by=DEFAULT_SORT_BY, sort_order=DEFAULT_SORT_ORDER): """ List playlists for ...
return pybrightcove.connection.ItemResultSet( "find_playlists_for_player_id", Playlist, connection, page_size, page_number, sort_by, sort_order, player_id=player_id)
<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_options_for_id(options: Dict[str, Dict[str, Any]], identifier: str): """ Helper method, from the full options dict of dicts, to return either the options...
check_var(options, var_types=dict, var_name='options') res = options[identifier] if identifier in options.keys() else dict() check_var(res, var_types=dict, var_name='options[' + identifier + ']') return res
<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(self, desired_type: Type[T], source_obj: S, logger: Logger, options: Dict[str, Dict[str, Any]]) -> T: """ Implementing classes should implement this ...
pass
<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(self, desired_type: Type[T], source_obj: S, logger: Logger, options: Dict[str, Dict[str, Any]]) -> T: """ Delegates to the user-provided method. Pass...
try: if self.unpack_options: opts = self.get_applicable_options(options) if self.function_args is not None: return self.conversion_method(desired_type, source_obj, logger, **self.function_args, **opts) else: ret...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_first(self, inplace: bool = False): """ Utility method to remove the first converter of this chain. If inplace is True, this object is modified and No...
if len(self._converters_list) > 1: if inplace: self._converters_list = self._converters_list[1:] # update the current source type self.from_type = self._converters_list[0].from_type return else: new = copy(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 add_conversion_steps(self, converters: List[Converter], inplace: bool = False): """ Utility method to add converters to this chain. If inplace is True, this ...
check_var(converters, var_types=list, min_len=1) if inplace: for converter in converters: self.add_conversion_step(converter, inplace=True) else: new = copy(self) new.add_conversion_steps(converters, inplace=True) return new
<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_conversion_step(self, converter: Converter[S, T], inplace: bool = False): """ Utility method to add a converter to this chain. If inplace is True, this o...
# it the current chain is generic, raise an error if self.is_generic() and converter.is_generic(): raise ValueError('Cannot chain this generic converter chain to the provided converter : it is generic too!') # if the current chain is able to transform its input into a valid input f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert_conversion_steps_at_beginning(self, converters: List[Converter], inplace: bool = False): """ Utility method to insert converters at the beginning ofth...
if inplace: for converter in reversed(converters): self.insert_conversion_step_at_beginning(converter, inplace=True) return else: new = copy(self) for converter in reversed(converters): # do inplace since it is a copy ...
<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(self, desired_type: Type[T], obj: S, logger: Logger, options: Dict[str, Dict[str, Any]]) -> T: """ Apply the converters of the chain in order to prod...
for converter in self._converters_list[:-1]: # convert into each converters destination type obj = converter.convert(converter.to_type, obj, logger, options) # the last converter in the chain should convert to desired type return self._converters_list[-1].convert(desire...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listens_to(name, sender=None, weak=True): """Listens to a named signal """
def decorator(f): if sender: return signal(name).connect(f, sender=sender, weak=weak) return signal(name).connect(f, weak=weak) return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def LoadInstallations(counter): """Load installed packages and export the version map. This function may be called multiple times, but the counters will be incre...
process = subprocess.Popen(["pip", "list", "--format=json"], stdout=subprocess.PIPE) output, _ = process.communicate() installations = json.loads(output) for i in installations: counter.labels(i["name"], i["version"]).inc()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def RESTrequest(*args, **kwargs): """return and save the blob of data that is returned from kegg without caring to the format"""
verbose = kwargs.get('verbose', False) force_download = kwargs.get('force', False) save = kwargs.get('force', True) # so you can copy paste from kegg args = list(chain.from_iterable(a.split('/') for a in args)) args = [a for a in args if a] request = 'http://rest.kegg.jp/' + "/".join(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 command_help_long(self): """ Return command help for use in global parser usage string @TODO update to support self.current_indent from formatter """
indent = " " * 2 # replace with current_indent help = "Command must be one of:\n" for action_name in self.parser.valid_commands: help += "%s%-10s %-70s\n" % (indent, action_name, self.parser.commands[action_name].desc_short.capitalize()) help += '\nSee \'%s help COMMAND\' for help and information...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """ Run the multiopt parser """
self.parser = MultioptOptionParser( usage="%prog <command> [options] [args]", prog=self.clsname, version=self.version, option_list=self.global_options, description=self.desc_short, commands=self.command_set, epilog=self.footer ) try: self.options, self.a...
<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(self, host=None, f_community=None, f_access=None, f_version=None): """ Add an SNMP community string to a host :param host: t_hosts.id or t_hosts.f_ipaddr...
return self.send.snmp_add(host, f_community, f_access, f_version)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_collection(db_name, collection_name, host='localhost', port=27017): """Almost exclusively for testing."""
client = MongoClient("mongodb://%s:%d" % (host, port)) client[db_name].drop_collection(collection_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 _check_1st_line(line, **kwargs): """First line check. Check that the first line has a known component name followed by a colon and then a short description o...
components = kwargs.get("components", ()) max_first_line = kwargs.get("max_first_line", 50) errors = [] lineno = 1 if len(line) > max_first_line: errors.append(("M190", lineno, max_first_line, len(line))) if line.endswith("."): errors.append(("M191", lineno)) if ':' not i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_bullets(lines, **kwargs): """Check that the bullet point list is well formatted. Each bullet point shall have one space before and after it. The bulle...
max_length = kwargs.get("max_length", 72) labels = {l for l, _ in kwargs.get("commit_msg_labels", tuple())} def _strip_ticket_directives(line): return re.sub(r'( \([^)]*\)){1,}$', '', line) errors = [] missed_lines = [] skipped = [] for (i, line) in enumerate(lines[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 _check_signatures(lines, **kwargs): """Check that the signatures are valid. There should be at least three signatures. If not, one of them should be a truste...
trusted = kwargs.get("trusted", ()) signatures = tuple(kwargs.get("signatures", ())) alt_signatures = tuple(kwargs.get("alt_signatures", ())) min_reviewers = kwargs.get("min_reviewers", 3) matching = [] errors = [] signatures += alt_signatures test_signatures = re.compile("^({0})".for...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_message(message, **kwargs): """Check the message format. Rules: - the first line must start by a component name - and a short description (52 chars), -...
if kwargs.pop("allow_empty", False): if not message or message.isspace(): return [] lines = re.split(r"\r\n|\r|\n", message) errors = _check_1st_line(lines[0], **kwargs) err, signature_lines = _check_bullets(lines, **kwargs) errors += err errors += _check_signatures(signatu...
<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_pyflakes_check(): """Register the pyFlakes checker into PEP8 set of checks."""
from flake8_isort import Flake8Isort from flake8_blind_except import check_blind_except # Resolving conflicts between pep8 and pyflakes. codes = { "UnusedImport": "F401", "ImportShadowedByLoopVar": "F402", "ImportStarUsed": "F403", "LateFutureImport": "F404", "R...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_pydocstyle(filename, **kwargs): """Perform static analysis on the given file docstrings. :param filename: path of file to check. :type filename: str :p...
ignore = kwargs.get("ignore") match = kwargs.get("match", None) match_dir = kwargs.get("match_dir", None) errors = [] if match and not re.match(match, os.path.basename(filename)): return errors if match_dir: # FIXME here the full path is checked, be sure, if match_dir doesn't...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_license(filename, **kwargs): """Perform a license check on the given file. The license format should be commented using # and live at the top of the fi...
year = kwargs.pop("year", datetime.now().year) python_style = kwargs.pop("python_style", True) ignores = kwargs.get("ignore") template = "{0}: {1} {2}" if python_style: re_comment = re.compile(r"^#.*|\{#.*|[\r\n]+$") starter = "# " else: re_comment = re.compile(r"^/\*.*...
<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_options(config=None): """Build the options from the config object."""
if config is None: from . import config config.get = lambda key, default=None: getattr(config, key, default) base = { "components": config.get("COMPONENTS"), "signatures": config.get("SIGNATURES"), "commit_msg_template": config.get("COMMIT_MSG_TEMPLATE"), "commi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """Yield the error messages."""
for msg in self.messages: col = getattr(msg, 'col', 0) yield msg.lineno, col, (msg.tpl % msg.message_args), msg.__class__
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def error(self, line_number, offset, text, check): """Run the checks and collect the errors."""
code = super(_Report, self).error(line_number, offset, text, check) if code: self.errors.append((line_number, offset + 1, code, text, check))
<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(prompt_string, default=None, secret=False, boolean=False, bool_type=None): """ Prompt user for a string, with a default value * secret converts to pas...
if boolean or bool_type in BOOLEAN_DEFAULTS: if bool_type is None: bool_type = 'y_n' default_msg = BOOLEAN_DEFAULTS[bool_type][is_affirmative(default)] else: default_msg = " (default {val}): " prompt_string += (default_msg.format(val=default) if default else ": ") if...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def jflatten(j): """ Flatten 3_D Jacobian into 2-D. """
nobs, nf, nargs = j.shape nrows, ncols = nf * nobs, nargs * nobs jflat = np.zeros((nrows, ncols)) for n in xrange(nobs): r, c = n * nf, n * nargs jflat[r:(r + nf), c:(c + nargs)] = j[n] return jflat
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def jtosparse(j): """ Generate sparse matrix coordinates from 3-D Jacobian. """
data = j.flatten().tolist() nobs, nf, nargs = j.shape indices = zip(*[(r, c) for n in xrange(nobs) for r in xrange(n * nf, (n + 1) * nf) for c in xrange(n * nargs, (n + 1) * nargs)]) return csr_matrix((data, indices), shape=(nobs * nf, nobs * nargs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload_file(self, service_rec=None, host_service=None, filename=None, pw_data=None, f_type=None, add_to_evidence=True): """ Upload a password file :param ser...
return self.send.accounts_upload_file(service_rec, host_service, filename, pw_data, f_type, add_to_evidence)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_datetime(time_str): """ Wraps dateutil's parser function to set an explicit UTC timezone, and to make sure microseconds are 0. Unified Uploader format ...
try: return dateutil.parser.parse( time_str ).replace(microsecond=0).astimezone(UTC_TZINFO) except ValueError: # This was some kind of unrecognizable time string. raise ParseError("Invalid time string: %s" % time_str)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append(self, content, encoding='utf8'): """ add a line to file """
if not self.parent.exists: self.parent.create() with open(self._filename, "ab") as output_file: if not is_text(content): Log.error(u"expecting to write unicode only") output_file.write(content.encode(encoding)) output_file.write(b"\n")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def url_param2value(param): """ CONVERT URL QUERY PARAMETERS INTO DICT """
if param == None: return Null if param == None: return Null def _decode(v): output = [] i = 0 while i < len(v): c = v[i] if c == "%": d = hex2chr(v[i + 1:i + 3]) output.append(d) i += 3 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configfile_from_path(path, strict=True): """Get a ConfigFile object based on a file path. This method will inspect the file extension and return the appropri...
extension = path.split('.')[-1] conf_type = FILE_TYPES.get(extension) if not conf_type: raise exc.UnrecognizedFileExtension( "Cannot parse file of type {0}. Choices are {1}.".format( extension, FILE_TYPES.keys(), ) ) return conf_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configuration_from_paths(paths, strict=True): """Get a Configuration object based on multiple file paths. Args: paths (iter of str): An iterable of file pat...
for path in paths: cfg = configfile_from_path(path, strict=strict).config return cfg
<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_environment_var_options(config, env=None, prefix='CONFPY'): """Set any configuration options which have an environment var set. Args: config (confpy.core...
env = env or os.environ for section_name, section in config: for option_name, _ in section: var_name = '{0}_{1}_{2}'.format( prefix.upper(), section_name.upper(), option_name.upper(), ) env_var = env.get(var_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 set_cli_options(config, arguments=None): """Set any configuration options which have a CLI value set. Args: config (confpy.core.config.Configuration): A con...
arguments = arguments or sys.argv[1:] parser = argparse.ArgumentParser() for section_name, section in config: for option_name, _ in section: var_name = '{0}_{1}'.format( section_name.lower(), option_name.lower(), ) parser.add_arg...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_for_missing_options(config): """Iter over a config and raise if a required option is still not set. Args: config (confpy.core.config.Configuration): T...
for section_name, section in config: for option_name, option in section: if option.required and option.value is None: raise exc.MissingRequiredOption( "Option {0} in namespace {1} is required.".format( option_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 parse_options(files, env_prefix='CONFPY', strict=True): """Parse configuration options and return a configuration object. Args: files (iter of str): File pa...
return check_for_missing_options( config=set_cli_options( config=set_environment_var_options( config=configuration_from_paths( paths=files, strict=strict, ), prefix=env_prefix, ), ) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render(self, sphinx_app: Sphinx, context): """ Given a Sphinx builder and context with sphinx_app in it, generate HTML """
# Called from kaybee.plugins.widgets.handlers.render_widgets builder: StandaloneHTMLBuilder = sphinx_app.builder resource = sphinx_app.env.resources[self.docname] context['sphinx_app'] = sphinx_app context['widget'] = self context['resource'] = resource # make...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def desc(t=None, reg=True): """ Describe Class Dependency :param reg: should we register this class as well :param t: custom type as well :return: """
def decorated_fn(cls): if not inspect.isclass(cls): return NotImplemented('For now we can only describe classes') name = t or camel_case_to_underscore(cls.__name__)[0] if reg: di.injector.register(name, cls) else: di.injector.describe(name, cls) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def label(self, value): """ Returns a pretty text version of the key for the inputted value. :param value | <variant> :return <str> """
return self._labels.get(value) or text.pretty(self(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 setLabel(self, value, label): """ Sets the label text for the inputted value. This will override the default pretty text label that is used for the key. :par...
if label: self._labels[value] = label else: self._labels.pop(value, 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 valueByLabel(self, label): """ Determine a given value based on the inputted label. :param label <str> :return <int> """
keys = self.keys() labels = [text.pretty(key) for key in keys] if label in labels: return self[keys[labels.index(label)]] return 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 load_config_file(self): """Parse configuration file and get config values."""
config_parser = SafeConfigParser() config_parser.read(self.CONFIG_FILE) if config_parser.has_section('handlers'): self._config['handlers_package'] = config_parser.get('handlers', 'package') if config_parser.has_section('auth'): self._config['consumer_key'] = c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_config_from_cli_arguments(self, *args, **kwargs): """ Get config values of passed in CLI options. :param dict kwargs: CLI options """
self._load_config_from_cli_argument(key='handlers_package', **kwargs) self._load_config_from_cli_argument(key='auth', **kwargs) self._load_config_from_cli_argument(key='user_stream', **kwargs) self._load_config_from_cli_argument(key='min_seconds_between_errors', **kwargs) self._...
<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, id): """ Gets the dict data and builds the item object. """
data = self.db.get_data(self.get_path, id=id) return self._build_item(**data['Data'][self.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 save(self, entity): """Maps entity to dict and returns future"""
assert isinstance(entity, Entity), " entity must have an instance of Entity" return self.__collection.save(entity.as_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 find_one(self, **kwargs): """Returns future. Executes collection's find_one method based on keyword args maps result ( dict to instance ) and return future E...
future = TracebackFuture() def handle_response(result, error): if error: future.set_exception(error) else: instance = self.__entity() instance.map_dict(result) future.set_result(instance) self.__collection...
<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, entity): """ Executes collection's update method based on keyword args. Example:: manager = EntityManager(Product) p = Product() p.name = 'new n...
assert isinstance(entity, Entity), "Error: entity must have an instance of Entity" return self.__collection.update({'_id': entity._id}, {'$set': entity.as_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 open(self, results=False): """ Open the strawpoll in a browser. Can specify to open the main or results page. :param results: True/False """
webbrowser.open(self.results_url if results else self.url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """ Testing function for DFA brzozowski algebraic method Operation """
argv = sys.argv if len(argv) < 2: targetfile = 'target.y' else: targetfile = argv[1] print 'Parsing ruleset: ' + targetfile, flex_a = Flexparser() mma = flex_a.yyparse(targetfile) print 'OK' print 'Perform minimization on initial automaton:', mma.minimize() print...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_mmd(): """Loads libMultiMarkdown for usage"""
global _MMD_LIB global _LIB_LOCATION try: lib_file = 'libMultiMarkdown' + SHLIB_EXT[platform.system()] _LIB_LOCATION = os.path.abspath(os.path.join(DEFAULT_LIBRARY_DIR, lib_file)) if not os.path.isfile(_LIB_LOCATION): _LIB_LOCATION = ctypes.util.find_library('MultiMarkd...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _expand_source(source, dname, fmt): """Expands source text to include headers, footers, and expands Multimarkdown transclusion directives. Keyword arguments:...
_MMD_LIB.g_string_new.restype = ctypes.POINTER(GString) _MMD_LIB.g_string_new.argtypes = [ctypes.c_char_p] src = source.encode('utf-8') gstr = _MMD_LIB.g_string_new(src) _MMD_LIB.prepend_mmd_header(gstr) _MMD_LIB.append_mmd_footer(gstr) manif = _MMD_LIB.g_string_new(b"") _MMD_LIB.tran...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_metadata(source, ext): """Returns a flag indicating if a given block of MultiMarkdown text contains metadata."""
_MMD_LIB.has_metadata.argtypes = [ctypes.c_char_p, ctypes.c_int] _MMD_LIB.has_metadata.restype = ctypes.c_bool return _MMD_LIB.has_metadata(source.encode('utf-8'), ext)
<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(source, ext=COMPLETE, fmt=HTML, dname=None): """Converts a string of MultiMarkdown text to the requested format. Transclusion is performed if the COM...
if dname and not ext & COMPATIBILITY: if os.path.isfile(dname): dname = os.path.abspath(os.path.dirname(dname)) source, _ = _expand_source(source, dname, fmt) _MMD_LIB.markdown_to_string.argtypes = [ctypes.c_char_p, ctypes.c_ulong, ctypes.c_int] _MMD_LIB.markdown_to_string.resty...