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 taskfileinfo_descriptor_data(tfi, role): """Return the data for descriptor :param tfi: the :class:`jukeboxcore.filesys.TaskFileInfo` holds the data :type tfi...
if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole: return tfi.descriptor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pick(self): """ picks a value accoriding to the given density """
v = random.uniform(0, self.ub) d = self.dist c = self.vc - 1 s = self.vc while True: s = s / 2 if s == 0: break if v <= d[c][1]: c -= s else: c += s # we only need thi...
<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_output_fields(self, output_fields): """Defines where to put the dictionary output of the extractor in the doc, but renames the fields of the extracted ou...
if isinstance(output_fields, dict) or isinstance(output_fields, list): self.output_fields = output_fields elif isinstance(output_fields, basestring): self.output_field = output_fields else: raise ValueError("set_output_fields requires a dictionary of " ...
<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_jp(self, extractor_processor, sub_output=None): """Tries to get name from ExtractorProcessor to filter on first. Otherwise falls back to filtering base...
if sub_output is None and extractor_processor.output_field is None: raise ValueError( "ExtractorProcessors input paths cannot be unioned across fields. Please specify either a sub_output or use a single scalar output_field") if extractor_processor.get_output_jsonpath_with_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 set_extractor_processor_inputs(self, extractor_processors, sub_output=None): """Instead of specifying fields in the source document to rename for the extract...
if not (isinstance(extractor_processors, ExtractorProcessor) or isinstance(extractor_processors, types.ListType)): raise ValueError( "extractor_processors must be an ExtractorProcessor or a list") if isinstance(extractor_processors, ExtractorProcessor): ...
<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_jsonpath_field(self, sub_output=None): """attempts to create an output jsonpath from a particular ouput field"""
if sub_output is not None: if self.output_fields is None or\ (isinstance(self.output_fields, dict) and not sub_output in self.output_fields.itervalues()) or\ (isinstance(self.output_fields, list) and not sub_output in self.output_fields): raise Va...
<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_jsonpath_with_name(self, sub_output=None): """If ExtractorProcessor has a name defined, return a JSONPath that has a filter on that name"""
if self.name is None: return None output_jsonpath_field = self.get_output_jsonpath_field(sub_output) extractor_filter = "name='{}'".format(self.name) output_jsonpath = "{}[?{}].(result[*][value])".format( output_jsonpath_field, extractor_filter) 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 get_output_jsonpath(self, sub_output=None): """Attempt to build a JSONPath filter for this ExtractorProcessor that captures how to get at the outputs of the ...
output_jsonpath_field = self.get_output_jsonpath_field(sub_output) metadata = self.extractor.get_metadata() metadata['source'] = str(self.input_fields) extractor_filter = "" is_first = True for key, value in metadata.iteritems(): if is_first: ...
<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_input_fields(self, input_fields): """Given a scalar or ordered list of strings generate JSONPaths that describe how to access the values necessary for th...
if not (isinstance(input_fields, basestring) or isinstance(input_fields, types.ListType)): raise ValueError("input_fields must be a string or a list") self.input_fields = input_fields self.generate_json_paths() return 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 generate_json_paths(self): """Given a scalar or ordered list of strings parse them to generate JSONPaths"""
if isinstance(self.input_fields, basestring): try: self.jsonpaths = parse(self.input_fields) except Exception as exception: print "input_fields failed {}".format(self.input_fields) raise exception elif isinstance(self.input_fields...
<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_extracted_value(self, doc, extracted_value, output_field, original_output_field=None): """inserts the extracted value into doc at the field specified ...
if not extracted_value: return doc metadata = self.extractor.get_metadata() if not self.extractor.get_include_context(): if isinstance(extracted_value, list): result = list() for ev in extracted_value: result.append({'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 extract_from_renamed_inputs(self, doc, renamed_inputs): """Apply the extractor to a document containing the renamed_inputs and insert the resulting value if ...
extracted_value = self.extractor.extract(renamed_inputs) if not extracted_value: return doc if self.output_fields is not None and isinstance(extracted_value, dict): if isinstance(self.output_fields, list): for field in self.output_fields: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def db_for_write(self, model, **hints): """ Attempts to write auth models go to duashttp. """
if model._meta.app_label == 'duashttp': if not DUAS_ENABLE_DB_WRITE: raise ImproperlyConfigured( "Set `DUAS_ENABLE_DB_WRITE` to True in your settings to enable " "write operations on unity asset server database" ) 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 allow_migrate(self, db, model): """ Make sure the auth app only appears in the 'duashttp' database. """
if db == DUAS_DB_ROUTE_PREFIX: return model._meta.app_label == 'duashttp' elif model._meta.app_label == 'duashttp': return False 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 sometimes(fn): """ They've done studies, you know. 50% of the time, it works every time. """
def wrapped(*args, **kwargs): wrapped.x += 1 if wrapped.x % 2 == 1: return fn(*args, **kwargs) wrapped.x = 0 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 percent_of_the_time(p): """ Function has a X percentage chance of running """
def decorator(fn): def wrapped(*args, **kwargs): if in_percentage(p): fn(*args, **kwargs) return wrapped 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 rarely(fn): """ Only 5% chance of happening """
def wrapped(*args, **kwargs): if in_percentage(5): fn(*args, **kwargs) 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 mostly(fn): """ 95% chance of happening """
def wrapped(*args, **kwargs): if in_percentage(95): fn(*args, **kwargs) 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 times(x, y): """ Do something a random amount of times between x & y """
def decorator(fn): def wrapped(*args, **kwargs): n = random.randint(x, y) for z in range(1, n): fn(*args, **kwargs) return wrapped 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 pformat_tokens(self, tokens): """ format a tokenized BASIC program line. Useful for debugging. returns a list of formated string lines. """
result = [] for token_value in self.iter_token_values(tokens): char = self.token2ascii(token_value) if token_value > 0xff: result.append("\t$%04x -> %s" % (token_value, repr(char))) else: result.append("\t $%02x -> %s" % (token_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 get_destinations(self, ascii_listing): """ returns all line numbers that are used in a jump. """
self.destinations = set() def collect_destinations(matchobj): numbers = matchobj.group("no") if numbers: self.destinations.update(set( [n.strip() for n in numbers.split(",")] )) for line in self._iter_lines(ascii_listi...
<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_cell_format(column_dict, key=None): """ Return the cell format for the given column :param column_dict: The column datas collected during inspection :par...
format = column_dict.get('format') prop = column_dict.get('__col__') if format is None and prop is not None: if hasattr(prop, 'columns'): sqla_column = prop.columns[0] column_type = getattr(sqla_column.type, 'impl', sqla_column.type) format = FORMAT_REGISTRY.get...
<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_book(self, f_buf=None): """ Return a file buffer containing the resulting xls :param obj f_buf: A file buffer supporting the write and seek methods """
if f_buf is None: f_buf = StringIO.StringIO() f_buf.write(openpyxl.writer.excel.save_virtual_workbook(self.book)) f_buf.seek(0) return f_buf
<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_color(self, cell, color): """ Set the given color to the provided cell cell A xls cell object color A openpyxl color var """
cell.style = cell.style.copy(font=Font(color=Color(rgb=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 format_row(self, row): """ The render method expects rows as lists, here we switch our row format from dict to list respecting the order of the headers """
res = [] headers = getattr(self, 'headers', []) for column in headers: column_name = column['name'] value = row.get(column_name, '') if hasattr(self, "format_%s" % column_name): value = getattr(self, "format_%s" % column_name)(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 _render_rows(self): """ Render the rows in the current stylesheet """
_datas = getattr(self, '_datas', ()) headers = getattr(self, 'headers', ()) for index, row in enumerate(_datas): row_number = index + 2 for col_num, value in enumerate(row): cell = self.worksheet.cell(row=row_number, column=col_num + 1) 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 _get_related_exporter(self, related_obj, column): """ returns an SqlaXlsExporter for the given related object and stores it in the column object as a cache "...
result = column.get('sqla_xls_exporter') if result is None: worksheet = self.book.create_sheet( title=column.get('label', 'default title') ) result = column['sqla_xls_exporter'] = SqlaXlsExporter( related_obj.__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 _populate(self): """ Enhance the default populate script by handling related elements """
XlsWriter._populate(self) for header in self.headers: if "sqla_xls_exporter" in header: header['sqla_xls_exporter']._populate()
<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_table_schema(self, tname): ''' Returns a list of column names of the provided table name ''' tname = self._check_tname(tname, noload=True) if tname not in self._schemas: raise ValueError('Table "%s" not found in schema store' % tname) return list(self._schemas[tname])
<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, table_names=None, table_schemas=None, table_rowgens=None): ''' Initiates the tables, schemas and record generators for this database. Parameters ---------- table_names : list of str, str or None List of tables to load into this database. If `auto_load`...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def drop_all(self): ''' Drops all tables from this database ''' self.drop(self.get_table_names()) if self.persistent: with self._lock: try: dbfolder = os.path.join(self.root_dir, self.name) if os.path.exists(dbfolder) and not os...
<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(self, tname, where=None, where_not=None, columns=None, astype=None): ''' Find records in the provided table from the database. If no records are found, return empty list, str or dataframe depending on the value of `astype`. Parameters ---------- tname : 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 find_one(self, tname, where=None, where_not=None, columns=None, astype=None): ''' Find a single record in the provided table from the database. If multiple match, return the first one based on the internal order of the records. If no records are found, return empty dictionary, 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 insert(self, tname, record=None, columns=None, astype=None): ''' Inserts record into the provided table from the database. Returns inserted record as list, str or series depending on the value of `astype`. Parameters ---------- tname : str Table to insert...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def upsert(self, tname, record=None, where=None, where_not=None, columns=None, astype=None): ''' Attempts to update records in the provided table from the database. If none are found, inserts new record that would match all the conditions. Returns updated or inserted record as list, 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 _extract_params(request_dict, param_list, param_fallback=False): ''' Extract pddb parameters from request ''' if not param_list or not request_dict: return dict() query = dict() for param in param_list: # Retrieve all items in the form of {param: value} and ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sha1(s): """ Returns a sha1 of the given string """
h = hashlib.new('sha1') h.update(s) return h.hexdigest()
<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_translated_items(fapi, file_uri, use_cache, cache_dir=None): """ Returns the last modified from smarterling """
items = None cache_file = os.path.join(cache_dir, sha1(file_uri)) if use_cache else None if use_cache and os.path.exists(cache_file): print("Using cache file %s for translated items for: %s" % (cache_file, file_uri)) items = json.loads(read_from_file(cache_file)) if not items: p...
<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_translated_file(fapi, file_uri, locale, retrieval_type, include_original_strings, use_cache, cache_dir=None): """ Returns a translated file from smartlin...
file_data = None cache_name = str(file_uri)+"."+str(locale)+"."+str(retrieval_type)+"."+str(include_original_strings) cache_file = os.path.join(cache_dir, sha1(cache_name)) if cache_dir else None if use_cache and os.path.exists(cache_file): print("Using cache file %s for %s translation file: %...
<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(fapi, file_name, conf): """ Uploads a file to smartling """
if not conf.has_key('file-type'): raise SmarterlingError("%s doesn't have a file-type" % file_name) print("Uploading %s to smartling" % file_name) data = UploadData( os.path.dirname(file_name)+os.sep, os.path.basename(file_name), conf.get('file-type')) data.setUri(file_u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_file_api(conf): """ Creates a SmartlingFileApi from the given config """
api_key = conf.config.get('api-key', os.environ.get('SMARTLING_API_KEY')) project_id = conf.config.get('project-id', os.environ.get('SMARTLING_PROJECT_ID')) if not project_id or not api_key: raise SmarterlingError('config.api-key and config.project-id are required configuration items') proxy_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 parse_config(file_name='smarterling.config'): """ Parses a smarterling configuration file """
if not os.path.exists(file_name) or not os.path.isfile(file_name): raise SmarterlingError('Config file not found: %s' % file_name) try: contents = read_from_file(file_name) contents_with_environment_variables_expanded = os.path.expandvars(contents) return AttributeDict(yaml.load...
<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, key, default_val=None, require_value=False): """ Returns a dictionary value """
val = dict.get(self, key, default_val) if val is None and require_value: raise KeyError('key "%s" not found' % key) if isinstance(val, dict): return AttributeDict(val) return val
<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_widget(self, wid, getter=None, setter=None, signal=None, arg=None, update=True, flavour=None): """ Finish set-up by connecting the widget. The model ...
if wid in self._wid_info: raise ValueError("Widget " + str(wid) + " was already connected") wid_type = None if None in (getter, setter, signal): w = search_adapter_info(wid, flavour) if getter is None: getter = w[GETTER] if sett...
<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_model(self, model): """ Used internally to connect the property into the model, and register self as a value observer for that property"""
parts = self._prop_name.split(".") if len(parts) > 1: # identifies the model models = parts[:-1] Intermediate(model, models, self) for name in models: model = getattr(model, name) if not isinstance(model, Model): ...
<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_observer_fun(self, prop_name): """This is the code for an value change observer"""
def _observer_fun(self, model, old, new): if self._itsme: return self._on_prop_changed() # doesn't affect stack traces _observer_fun.__name__ = "property_%s_value_change" % prop_name return _observer_fun
<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_property(self, val, *args): """Sets the value of property. Given val is transformed accodingly to prop_write function when specified at construction-t...
val_wid = val # 'finally' would be better here, but not supported in 2.4 :( try: totype = type(self._get_property(*args)) if (totype is not type(None) and (self._prop_cast or not self._prop_write)): val = self._cast_value(val, totype) ...
<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_widget(self): """Returns the value currently stored into the widget, after transforming it accordingly to possibly specified function. This is implemen...
getter = self._wid_info[self._wid][0] return getter(self._wid)
<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_widget(self, val): """Writes value into the widget. If specified, user setter is invoked."""
self._itsme = True try: setter = self._wid_info[self._wid][1] wtype = self._wid_info[self._wid][2] if setter: if wtype is not None: setter(self._wid, self._cast_value(val, wtype)) else: setter(se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _on_prop_changed(self, instance, meth_name, res, args, kwargs): """Called by the observation code, when a modifying method is called"""
Adapter._on_prop_changed(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_property(self, *args): """Private method that returns the value currently stored into the property"""
val = self._getter(Adapter._get_property(self), *args) if self._prop_read: return self._prop_read(val, *args) return val
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def distort(value): """ Distorts a string by randomly replacing characters in it. :param value: a string to distort. :return: a distored string. """
value = value.lower() if (RandomBoolean.chance(1, 5)): value = value[0:1].upper() + value[1:] if (RandomBoolean.chance(1, 3)): value = value + random.choice(_symbols) return 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 pwm_start(self, channel, duty_cycle=None, frequency=None): """ Starts the pwm signal on a channel. The channel should be defined as pwm prior to this call. I...
if frequency: self.set_pwm_freq(frequency) self.set_pwm(channel, 0, int(4096 * (duty_cycle/100)))
<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_pwm_freq(self, freq_hz): """Set the PWM frequency to the provided value in hertz."""
prescaleval = 25000000.0 # 25MHz prescaleval /= 4096.0 # 12-bit prescaleval /= float(freq_hz) prescaleval -= 1.0 logger.debug('Setting PWM frequency to {0} Hz'.format(freq_hz)) logger.debug('Estimated pre-scale: {0}'.format(prescaleval)) prescale = int(m...
<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_pwm(self, channel, on, off): """Sets a single PWM channel."""
self.i2c.write8(LED0_ON_L+4*channel, on & 0xFF) self.i2c.write8(LED0_ON_H+4*channel, on >> 8) self.i2c.write8(LED0_OFF_L+4*channel, off & 0xFF) self.i2c.write8(LED0_OFF_H+4*channel, off >> 8)
<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_all_pwm(self, on, off): """Sets all PWM channels."""
self.i2c.write8(ALL_LED_ON_L, on & 0xFF) self.i2c.write8(ALL_LED_ON_H, on >> 8) self.i2c.write8(ALL_LED_OFF_L, off & 0xFF) self.i2c.write8(ALL_LED_OFF_H, off >> 8)
<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_ansible_classes(): """Run playbook and collect classes of ansible that are run."""
def trace_calls(frame, event, arg): # pylint: disable=W0613 """Trace function calls to collect ansible classes. Trace functions and check if they have self as an arg. If so, get their class if the class belongs to ansible. """ if event != 'call': 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 _parse_args(): """Parse args and separate generator and playbook args."""
class HelpOnErrorArgParser(argparse.ArgumentParser): """Print help message as well when an error is raised.""" def error(self, message): sys.stderr.write("Error: %s\n" % message) self.print_help() sys.exit(2) def validate(_file): """Validate if the g...
<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_process(cls, headers): """Returns tuple of process, legacy or None, None if not process originating."""
try: if 'Libprocess-From' in headers: return PID.from_string(headers['Libprocess-From']), False elif 'User-Agent' in headers and headers['User-Agent'].startswith('libprocess/'): return PID.from_string(headers['User-Agent'][len('libprocess/'):]), True except ValueError as e: l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mount_process(self, process): """ Mount a Process onto the http server to receive message callbacks. """
for route_path in process.route_paths: route = '/%s%s' % (process.pid.id, route_path) log.info('Mounting route %s' % route) self.app.add_handlers('.*$', [( re.escape(route), RoutedRequestHandler, dict(process=process, path=route_path) )]) for message_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 unmount_process(self, process): """ Unmount a process from the http server to stop receiving message callbacks. """
# There is no remove_handlers, but .handlers is public so why not. server.handlers is a list of # 2-tuples of the form (host_pattern, [list of RequestHandler]) objects. We filter out all # handlers matching our process from the RequestHandler list for each host pattern. def nonmatching(handler): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def typevalue(self, key, value): """Given a parameter identified by ``key`` and an untyped string, convert that string to the type that our version of key has. "...
def listconvert(value): # this function might be called with both string # represenations of entire lists and simple (unquoted) # strings. String representations come in two flavours, # the (legacy/deprecated) python literal (eg "['foo', # 'bar']") 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 generate_valid_keys(): """ create a list of valid keys """
valid_keys = [] for minimum, maximum in RANGES: for i in range(ord(minimum), ord(maximum) + 1): valid_keys.append(chr(i)) return valid_keys
<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_configuration_file(): """ return jenks configuration file """
path = os.path.abspath(os.curdir) while path != os.sep: config_path = os.path.join(path, CONFIG_FILE_NAME) if os.path.exists(config_path): return config_path path = os.path.dirname(path) 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 generate_write_yaml_to_file(file_name): """ generate a method to write the configuration in yaml to the method desired """
def write_yaml(config): with open(file_name, 'w+') as fh: fh.write(yaml.dump(config)) return write_yaml
<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_grid_data(file_list, data_type="binary", sort=True, delim=" "): """ Loads data from one or multiple grid_task files. Arguments: file_list - either a str...
# If there's only one file, we pretend it's a list if not type(file_list) is list: file_list = [file_list] elif sort: # put file_list in chronological order file_list.sort(key=lambda f: int(re.sub("[^0-9]", "", f))) world_size = get_world_dimensions(file_list[0], delim) #...
<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_niche_grid(res_dict, world_size=(60, 60)): """ Converts dictionary specifying where resources are to nested lists specifying what sets of resources are ...
# Initialize array to represent world world = initialize_grid(world_size, set()) # Fill in data on niches present in each cell of the world for res in res_dict: for cell in res_dict[res]: world[cell[1]][cell[0]].add(res) return world
<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_environment_file_list(names, world_size=(60, 60)): """ Extract information about spatial resources from all environment files in a list. Arguments: nam...
# Convert single file to list if necessary try: names[0] = names[0] except: names = [names] envs = [] for name in names: envs.append(parse_environment_file(name, world_size)) return envs
<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_environment_file(filename, world_size=(60, 60)): """ Extract information about spatial resources from an environment file. Arguments: filename - a stri...
infile = open(filename) lines = infile.readlines() infile.close() tasks = [] # Find all spatial resources and record which cells they're in res_order = [] res_dict = {} for line in lines: if line.startswith("GRADIENT_RESOURCE"): name, cells = parse_gradient(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 add_category_labels(level_name, cat_name, dataframe_needing_cat): '''A function that adds a category name column to a pandas dataframe :param level_name: an aggregation from elasticsearch results with nesting :type level_name: elasticsearch response.aggregation object :param cat_name: 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 chained_set(self, value, command='set', *keys): """ chained_set takes the value to enter into the dictionary, a command of what to do with the value, and a s...
new_object = self.__class__() existing = self for i in range(0, len(keys) - 1): if keys[i] in existing: existing = existing[keys[i]] else: existing[keys[i]] = new_object existing = existing[keys[i]] if command == '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 set_renamed_input_fields(self, renamed_input_fields): """This method expects a scalar string or a list of input_fields to """
if not (isinstance(renamed_input_fields, basestring) or isinstance(renamed_input_fields, ListType)): raise ValueError("renamed_input_fields must be a string or a list") self.renamed_input_fields = renamed_input_fields return 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 list_dir_abspath(path): """ Return a list absolute file paths. see mkdir_p os.listdir. """
return map(lambda f: os.path.join(path, f), os.listdir(path))
<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_digest(self): """ return int uuid number for digest :rtype: int :return: digest """
a, b = struct.unpack('>QQ', self.digest) return (a << 64) | b
<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_blob_hash(self, h=hashlib.md5): """ get hash instance of blob content :param h: callable hash generator :type h: builtin_function_or_method :rtype: _hash...
assert callable(h) return h(self.get_blob_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 get_blob_data(self, tag_target='asset', force=False): """ get asset version content using pg large object streams :param bool force: False by default, forces...
if hasattr(self, '_blob_data') and not force: return self._blob_data if six.PY2: self._blob_data = six.binary_type('') elif six.PY3: self._blob_data = six.binary_type('', encoding='ascii') asset_contents = self.contents.filter(tag=tag_target) ...
<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, obj): """Execute the actions on the given object. :param obj: The object that the action should process :type obj: :class:`object` :returns: None :...
for d in self.depsuccess: if d.status.value != ActionStatus.SUCCESS: self.status = ActionStatus(ActionStatus.SKIPPED, "Skipped because action \"%s\" did not succeed." % d.name) return for d in self.depfail: if d.status.value == ActionStatus.SUCCES...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def status(self, ): """The global status that summerizes all actions The status will be calculated in the following order: If any error occured, the status will ...
status = ActionStatus(ActionStatus.SUCCESS, "All actions succeeded.") for a in self.actions: if a.status.value == ActionStatus.ERROR: status = ActionStatus(ActionStatus.ERROR, "Error: action \"%s\" raised an error!" % a.name, a.status.traceback) 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 format_explanation(explanation, original_msg=None): """This formats an explanation Normally all embedded newlines are escaped, however there are three except...
if not conf.is_message_introspection_enabled() and original_msg: return original_msg explanation = ecu(explanation) lines = _split_explanation(explanation) result = _format_lines(lines) return u('\n').join(result)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _split_explanation(explanation): """Return a list of individual lines in the explanation This will return a list of lines split on '\n{', '\n}' and '\n~'. An...
raw_lines = (explanation or u('')).split('\n') lines = [raw_lines[0]] for l in raw_lines[1:]: if l and l[0] in ['{', '}', '~', '>']: lines.append(l) else: lines[-1] += '\\n' + l return 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 _format_lines(lines): """Format the individual lines This will replace the '{', '}' and '~' characters of our mini Return a list of formatted lines. """
result = lines[:1] stack = [0] stackcnt = [0] for line in lines[1:]: if line.startswith('{'): if stackcnt[-1]: s = u('and ') else: s = u('where ') stack.append(len(result)) stackcnt[-1] += 1 stackcnt.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 _diff_text(left, right, verbose=False): """Return the explanation for the diff between text or bytes Unless --verbose is used this will skip leading and trai...
from difflib import ndiff explanation = [] if isinstance(left, py.builtin.bytes): left = u(repr(left)[1:-1]).replace(r'\n', '\n') if isinstance(right, py.builtin.bytes): right = u(repr(right)[1:-1]).replace(r'\n', '\n') if not verbose: i = 0 # just in case left or right has...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def with_rule(self, rule): """ Adds validation rule to this schema. This method returns reference to this exception to implement Builder pattern to chain additio...
self.rules = self.rules if self.rules != None else [] self.rules.append(rule) return 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 _make_socket(cls, ip, port): """Bind to a new socket. If LIBPROCESS_PORT or LIBPROCESS_IP are configured in the environment, these will be used for socket co...
bound_socket = bind_sockets(port, address=ip)[0] ip, port = bound_socket.getsockname() if not ip or ip == '0.0.0.0': ip = socket.gethostbyname(socket.gethostname()) return bound_socket, ip, port
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop(self): """Stops the context. This terminates all PIDs and closes all connections."""
log.info('Stopping %s' % self) pids = list(self._processes) # Clean up the context for pid in pids: self.terminate(pid) while self._connections: pid = next(iter(self._connections)) conn = self._connections.pop(pid, None) if conn: conn.close() self.__loop.sto...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spawn(self, process): """Spawn a process. Spawning a process binds it to this context and assigns the process a pid which is returned. The process' ``initial...
self._assert_started() process.bind(self) self.http.mount_process(process) self._processes[process.pid] = process process.initialize() return process.pid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dispatch(self, pid, method, *args): """Call a method on another process by its pid. The method on the other process does not need to be installed with ``Proc...
self._assert_started() self._assert_local_pid(pid) function = self._get_dispatch_method(pid, method) self.__loop.add_callback(function, *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 delay(self, amount, pid, method, *args): """Call a method on another process after a specified delay. This is equivalent to ``dispatch`` except with an addit...
self._assert_started() self._assert_local_pid(pid) function = self._get_dispatch_method(pid, method) self.__loop.add_timeout(self.__loop.time() + amount, function, *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 _maybe_connect(self, to_pid, callback=None): """Asynchronously establish a connection to the remote pid."""
callback = stack_context.wrap(callback or (lambda stream: None)) def streaming_callback(data): # we are not guaranteed to get an acknowledgment, but log and discard bytes if we do. log.info('Received %d bytes from %s, discarding.' % (len(data), to_pid)) log.debug(' data: %r' % (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 send(self, from_pid, to_pid, method, body=None): """Send a message method from one pid to another with an optional body. Note: It is more idiomatic to send d...
self._assert_started() self._assert_local_pid(from_pid) if self._is_local(to_pid): local_method = self._get_local_mailbox(to_pid, method) if local_method: log.info('Doing local dispatch of %s => %s (method: %s)' % (from_pid, to_pid, local_method)) self.__loop.add_callback(loca...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def link(self, pid, to): """Link a local process to a possibly remote process. Note: It is more idiomatic to call ``link`` directly on the bound Process object i...
self._assert_started() def really_link(): self._links[pid].add(to) log.info('Added link from %s to %s' % (pid, to)) def on_connect(stream): really_link() if self._is_local(pid): really_link() else: self.__loop.add_callback(self._maybe_connect, to, on_connect)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def terminate(self, pid): """Terminate a process bound to this context. When a process is terminated, all the processes to which it is linked will be have their ...
self._assert_started() log.info('Terminating %s' % pid) process = self._processes.pop(pid, None) if process: log.info('Unmounting %s' % process) self.http.unmount_process(process) self.__erase_link(pid)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _page_gen(self): """ Generates The String for pages """
track = "" for page in self.__pages__: track += "/{page}".format(page=page) return track
<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_gen(self): """Generates The String for queries"""
return urlencode(self.__query__, safe=self.safe, querydelimiter=self.__querydelimiter__)
<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_nullable_string(value): """ Converts value into string or returns None when value is None. :param value: the value to convert. :return: string value or No...
if value == None: return None if type(value) == datetime.date: return value.isoformat() if type(value) == datetime.datetime: if value.tzinfo == None: return value.isoformat() + "Z" else: return value.isoformat() ...
<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_string_with_default(value, default_value): """ Converts value into string or returns default when value is None. :param value: the value to convert. :para...
result = StringConverter.to_nullable_string(value) return result if result != None else default_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 run(itf): """ Run postanalyze functions. """
if not itf: return 1 # access user input options = SplitInput(itf) # check input args error_check(options) # read input files try: molecules, ensemble_lookup = ReadFiles(options) except: return 1 if options.compare: compare(molecules, ensemble_lo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def evaluate_list(molecules, ensemble_lookup, options): """ Evaluate a list of ensembles and return statistics and ROC plots if appropriate """
# create stats dictionaries to store results from each ensemble stats = {} # {file name : metric_List} # print progress messages if options.write_roc: print(" Determining virtual screening performance and writing ROC data ... ") print('') else: print(" Determining virtual...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sentry_context_dict(context): """Create a dict with context information for Sentry."""
d = { "function_name": context.function_name, "function_version": context.function_version, "invoked_function_arn": context.invoked_function_arn, "memory_limit_in_mb": context.memory_limit_in_mb, "aws_request_id": context.aws_request_id, "log_group_name": context.log...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sentry_monitor(error_stream=None, **kwargs): """Sentry monitoring for AWS Lambda handler."""
def decorator(func): """A decorator that adds Sentry monitoring to a Lambda handler.""" def wrapper(event, context): """Wrap the target function.""" client = _setup_sentry_client(context) try: return func(event, context) except (Proces...