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 get_env(key, *default, **kwargs): """ Return env var. This is the parent function of all other get_foo functions, and is responsible for unpacking args/kwarg...
assert len(default) in (0, 1), "Too many args supplied." func = kwargs.get('coerce', lambda x: x) required = (len(default) == 0) default = default[0] if not required else None return _get_env(key, default=default, coerce=func, required=required)
<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_list(key, *default, **kwargs): """Return env var as a list."""
separator = kwargs.get('separator', ' ') return get_env(key, *default, coerce=lambda x: x.split(separator))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def row_to_content_obj(key_row): '''Returns ``FeatureCollection`` given an HBase artifact row. Note that the FC returned has a Unicode feature ``artifact_id`` set to the row's key. ''' key, row = key_row cid = mk_content_id(key.encode('utf-8')) response = row.get('response', {}) other_...
<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_tuple(d): '''Convert a dictionary to a time tuple. Depends on key values in the regexp pattern! ''' # TODO: Adding a ms field to struct_time tuples is problematic # since they don't have this field. Should use datetime # which has a microseconds field, else no ms.. When mapp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dst(self, dt): """datetime -> DST offset in minutes east of UTC."""
tt = _localtime(_mktime((dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.weekday(), 0, -1))) if tt.tm_isdst > 0: return _dstdiff return _zero
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tzname(self, dt): """datetime -> string name of time zone."""
tt = _localtime(_mktime((dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.weekday(), 0, -1))) return _time.tzname[tt.tm_isdst > 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 add_callback(instance, prop, callback, echo_old=False, priority=0): """ Attach a callback function to a property in an instance Parameters instance The insta...
p = getattr(type(instance), prop) if not isinstance(p, CallbackProperty): raise TypeError("%s is not a CallbackProperty" % prop) p.add_callback(instance, callback, echo_old=echo_old, priority=priority)
<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_callback(instance, prop, callback): """ Remove a callback function from a property in an instance Parameters instance The instance to detach the callb...
p = getattr(type(instance), prop) if not isinstance(p, CallbackProperty): raise TypeError("%s is not a CallbackProperty" % prop) p.remove_callback(instance, callback)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def callback_property(getter): """ A decorator to build a CallbackProperty. This is used by wrapping a getter method, similar to the use of @property:: class Foo...
cb = CallbackProperty(getter=getter) cb.__doc__ = getter.__doc__ return cb
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ignore_callback(instance, *props): """ Temporarily ignore any callbacks from one or more callback properties This is a context manager. Within the context bl...
for prop in props: p = getattr(type(instance), prop) if not isinstance(p, CallbackProperty): raise TypeError("%s is not a CallbackProperty" % prop) p.disable(instance) if isinstance(instance, HasCallbackProperties): instance._ignore_global_callbacks(props) yiel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def notify(self, instance, old, new): """ Call all callback functions with the current value Each callback will either be called using callback(new) or callback(...
if self._disabled.get(instance, False): return for cback in self._callbacks.get(instance, []): cback(new) for cback in self._2arg_callbacks.get(instance, []): cback(old, 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_callback(self, instance, func, echo_old=False, priority=0): """ Add a callback to a specific instance that manages this property Parameters instance The ...
if echo_old: self._2arg_callbacks.setdefault(instance, CallbackContainer()).append(func, priority=priority) else: self._callbacks.setdefault(instance, CallbackContainer()).append(func, priority=priority)
<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_callback(self, name, callback, echo_old=False, priority=0): """ Add a callback that gets triggered when a callback property of the class changes. Paramet...
if self.is_callback_property(name): prop = getattr(type(self), name) prop.add_callback(self, callback, echo_old=echo_old, priority=priority) else: raise TypeError("attribute '{0}' is not a callback property".format(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 iter_callback_properties(self): """ Iterator to loop over all callback properties. """
for name in dir(self): if self.is_callback_property(name): yield name, getattr(type(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 has_gis(wrapped, instance, args, kwargs): """Skip function execution if there are no presamples"""
if gis: return wrapped(*args, **kwargs) else: warn(MISSING_GIS)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sha256(filepath, blocksize=65536): """Generate SHA 256 hash for file at `filepath`"""
hasher = hashlib.sha256() fo = open(filepath, 'rb') buf = fo.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = fo.read(blocksize) return hasher.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 check_data(self): """Check that definitions file is present, and that faces file is readable."""
assert os.path.exists(self.data_fp) if gis: with fiona.drivers(): with fiona.open(self.faces_fp) as src: assert src.meta gpkg_hash = json.load(open(self.data_fp))['metadata']['sha256'] assert gpkg_hash == sha256(self.faces_fp)
<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_definitions(self): """Load mapping of country names to face ids"""
self.data = dict(json.load(open(self.data_fp))['data']) self.all_faces = set(self.data.pop("__all__")) self.locations = set(self.data.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 construct_rest_of_world(self, excluded, name=None, fp=None, geom=True): """Construct rest-of-world geometry and optionally write to filepath ``fp``. Excludes...
for location in excluded: assert location in self.locations, "Can't find location {}".format(location) included = self.all_faces.difference( set().union(*[set(self.data[loc]) for loc in excluded]) ) if not geom: return included elif not gis: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def construct_rest_of_worlds(self, excluded, fp=None, use_mp=True, simplify=True): """Construct many rest-of-world geometries and optionally write to filepath ``...
geoms = {} raw_data = [] for key in sorted(excluded): locations = excluded[key] for location in locations: assert location in self.locations, "Can't find location {}".format(location) included = self.all_faces.difference( {face...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def construct_rest_of_worlds_mapping(self, excluded, fp=None): """Construct topo mapping file for ``excluded``. ``excluded`` must be a **dictionary** of {"rest-o...
metadata = { 'filename': 'faces.gpkg', 'field': 'id', 'sha256': sha256(self.faces_fp) } data = [] for key, locations in excluded.items(): for location in locations: assert location in self.locations, "Can't find location {}...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def construct_difference(self, parent, excluded, name=None, fp=None): """Construct geometry from ``parent`` without the regions in ``excluded`` and optionally wr...
assert parent in self.locations, "Can't find location {}".format(parent) for location in excluded: assert location in self.locations, "Can't find location {}".format(location) included = set(self.data[parent]).difference( reduce(set.union, [set(self.data[loc]) for loc in...
<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_geoms_to_file(self, fp, geoms, names=None): """Write unioned geometries ``geoms`` to filepath ``fp``. Optionally use ``names`` in name field."""
if fp[-5:] != '.gpkg': fp = fp + '.gpkg' if names is not None: assert len(geoms) == len(names), "Inconsistent length of geometries and names" else: names = ("Merged geometry {}".format(count) for count in itertools.count()) meta = { 'crs':...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode(data): """ Handles decoding of the CSV `data`. Args: data (str): Data which will be decoded. Returns: dict: Dictionary with decoded data. """
# try to guess dialect of the csv file dialect = None try: dialect = csv.Sniffer().sniff(data) except Exception: pass # parse data with csv parser handler = None try: data = data.splitlines() # used later handler = csv.reader(data, dialect) except Excep...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli(ctx, config, quiet): """AWS ECS Docker Deployment Tool"""
ctx.obj = {} ctx.obj['config'] = load_config(config.read()) # yaml.load(config.read()) ctx.obj['quiet'] = quiet log(ctx, ' * ' + rnd_scotty_quote() + ' * ')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def emit(self, record): """ Sends exception info to Errordite. This handler will ignore the log level, and look for an exception within the record (as recored.ex...
if not self.token: raise Exception("Missing Errordite service token.") if record.levelname == 'EXCEPTION': exc_info = record.exc_info else: exc_info = sys.exc_info() if exc_info == (None, None, None): # we can't find an exception to repo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve(var, context): """ Resolve the variable, or return the value passed to it in the first place """
try: return var.resolve(context) except template.VariableDoesNotExist: return var.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 update(self, report: str = None) -> bool: """Updates raw, data, and translations by fetching and parsing the METAR report Returns True is a new report is avai...
if report is not None: self.raw = report else: raw = self.service.fetch(self.station) if raw == self.raw: return False self.raw = raw self.data, self.units = metar.parse(self.station, self.raw) self.translations = translate...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def summary(self) -> str: """ Condensed report summary created from translations """
if not self.translations: self.update() return summary.metar(self.translations)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def summary(self): # type: ignore """ Condensed summary for each forecast created from translations """
if not self.translations: self.update() return [summary.taf(trans) for trans in self.translations.forecast]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self): """Start the consumer. This starts a listen loop on a zmq.PULL socket, calling ``self.handle`` on each incoming request and pushing the response...
if not self.initialized: raise Exception("Consumer not initialized (no Producer).") producer = self.producer context = zmq._Context() self.pull = context.socket(zmq.PULL) self.push = context.socket(zmq.PUSH) self.pull.connect('tcp://%s:%s' % (producer.host, 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 listen(self): """Listen forever on the zmq.PULL socket."""
while True: message = self.pull.recv() logger.debug("received message of length %d" % len(message)) uuid, message = message[:32], message[32:] response = uuid + self.handle(message) self.push.send(response)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def guess_strategy_type(file_name_or_ext): """Guess strategy type to use for file by extension. Args: file_name_or_ext: Either a file name with an extension or j...
if '.' not in file_name_or_ext: ext = file_name_or_ext else: name, ext = os.path.splitext(file_name_or_ext) ext = ext.lstrip('.') file_type_map = get_file_type_map() return file_type_map.get(ext, 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 read_file(self, file_name, section=None): """Read settings from specified ``section`` of config file."""
file_name, section = self.parse_file_name_and_section(file_name, section) if not os.path.isfile(file_name): raise SettingsFileNotFoundError(file_name) parser = self.make_parser() with open(file_name) as fp: parser.read_file(fp) settings = OrderedDict() ...
<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_default_section(self, file_name): """Returns first non-DEFAULT section; falls back to DEFAULT."""
if not os.path.isfile(file_name): return 'DEFAULT' parser = self.make_parser() with open(file_name) as fp: parser.read_file(fp) sections = parser.sections() section = sections[0] if len(sections) > 0 else 'DEFAULT' return section
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _validate_install(self): ''' a method to validate heroku is installed ''' self.printer('Checking heroku installation ... ', flush=True) # import dependencies from os import devnull from subprocess import call, check_output # validate cli installation...
<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_netrc(self, netrc_path, auth_token, account_email): ''' a method to replace heroku login details in netrc file ''' # define patterns import re record_end = '(\n\n|\n\w|$)' heroku_regex = re.compile('(machine\sapi\.heroku\.com.*?\nmachine\sgit\.heroku\...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _validate_login(self): ''' a method to validate user can access heroku account ''' title = '%s.validate_login' % self.__class__.__name__ # verbosity windows_insert = ' On windows, run in cmd.exe' self.printer('Checking heroku credentials ......
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def access(self, app_subdomain): ''' a method to validate user can access app ''' title = '%s.access' % self.__class__.__name__ # validate input input_fields = { 'app_subdomain': app_subdomain } for key, value in input_fields.items(): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def deploy_docker(self, dockerfile_path, virtualbox_name='default'): ''' a method to deploy app to heroku using docker ''' title = '%s.deploy_docker' % self.__class__.__name__ # validate inputs input_fields = { 'dockerfile_path': dockerfile_path, 'virtualb...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def init(): '''Initialise a WSGI application to be loaded by uWSGI.''' # Load values from config file config_file = os.path.realpath(os.path.join(os.getcwd(), 'swaggery.ini')) config = configparser.RawConfigParser(allow_no_value=True) config.read(config_file) log_level = config.get('application'...
<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_names(cls): """Lists all known LXC names"""
response = subwrap.run(['lxc-ls']) output = response.std_out return map(str.strip, output.splitlines())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def info(cls, name, get_state=True, get_pid=True): """Retrieves and parses info about an LXC"""
# Run lxc-info quietly command = ['lxc-info', '-n', name] response = subwrap.run(command) lines = map(split_info_line, response.std_out.splitlines()) return dict(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 getClientModuleName(self): """client module name. """
name = GetModuleBaseNameFromWSDL(self._wsdl) if not name: raise WsdlGeneratorError, 'could not determine a service name' if self.client_module_suffix is None: return name return '%s%s' %(name, self.client_module_suffix)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getTypesModuleName(self): """types module name. """
if self.types_module_name is not None: return self.types_module_name name = GetModuleBaseNameFromWSDL(self._wsdl) if not name: raise WsdlGeneratorError, 'could not determine a service name' if self.types_module_suffix is None: return 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 gatherNamespaces(self): '''This method must execute once.. Grab all schemas representing each targetNamespace. ''' if self.usedNamespaces is not None: return self.logger.debug('gatherNamespaces') self.usedNamespaces = {} # Add all sc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def writeTypes(self, fd): """write out types module to file descriptor. """
print >>fd, '#'*50 print >>fd, '# file: %s.py' %self.getTypesModuleName() print >>fd, '#' print >>fd, '# schema types generated by "%s"' %self.__class__ print >>fd, '# %s' %' '.join(sys.argv) print >>fd, '#' print >>fd, '#'*50 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 fromSchema(self, schema): ''' Can be called multiple times, but will not redefine a previously defined type definition or element declaration. ''' ns = schema.getTargetNamespace() assert self.targetNamespace is None or self.targetNamespace == ns,\ 'SchemaDescrip...
<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(self, fd): """write out to file descriptor. """
print >>fd, self.classHead for t in self.items: print >>fd, t print >>fd, self.classFoot
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fromSchemaItem(self, item): """set up global elements. """
if item.isElement() is False or item.isLocal() is True: raise TypeError, 'expecting global element declaration: %s' %item.getItemTrace() local = False qName = item.getAttribute('type') if not qName: etp = item.content local = True 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 acquire(self): """ Attempt to acquire the lock every `delay` seconds until the lock is acquired or until `timeout` has expired. Raises FileLockTimeout if the...
self.lock = retry_call( self._attempt, retries=float('inf'), trap=zc.lockfile.LockError, cleanup=functools.partial(self._check_timeout, timing.Stopwatch()), )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def release(self): """ Release the lock and cleanup """
lock = vars(self).pop('lock', missing) lock is not missing and self._release(lock)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _resolve_view_params(self, request, defaults, *args, **kwargs): """ Resolves view params with least ammount of resistance. Firstly check for params on urls p...
params = copy.copy(defaults) params.update(self.params) params.update(kwargs) resolved_params = {} extra_context = {} for key in params: # grab from provided params. value = params[key] # otherwise grab from exis...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_valid(self, form=None, *args, **kwargs): """ Called after the form has validated. """
# Take a chance and try save a subclass of a ModelForm. if hasattr(form, 'save'): form.save() # Also try and call handle_valid method of the form itself. if hasattr(form, 'handle_valid'): form.handle_valid(*args, **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 evalMetric(self, x, w1=None, w2=None): '''Evaluates the weighted sum metric at given values of the design variables. :param iterable x: values of the design variables, this is passed as the first argument to the function fqoi :param float w1: value to weight the mean by...
<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_event(self, source, reference, event_title, event_type, method='', description='', bucket_list=[], campaign='', confidence='', date=None): """ Adds an ev...
# Check to see if the event already exists events = self.get_events(event_title) if events is not None: if events['meta']['total_count'] == 1: return events['objects'][0] if events['meta']['total_count'] > 1: log.error('Multiple events fou...
<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_sample_file(self, sample_path, source, reference, method='', file_format='raw', file_password='', sample_name='', campaign='', confidence='', description=...
if os.path.isfile(sample_path): data = { 'api_key': self.api_key, 'username': self.username, 'source': source, 'reference': reference, 'method': method, 'filetype': file_format, 'upload_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 add_sample_meta(self, source, reference, method='', filename='', md5='', sha1='', sha256='', size='', mimetype='', campaign='', confidence='', description='',...
data = { 'api_key': self.api_key, 'username': self.username, 'source': source, 'reference': reference, 'method': method, 'filename': filename, 'md5': md5, 'sha1': sha1, 'sha256': sha256, 'siz...
<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_email(self, email_path, source, reference, method='', upload_type='raw', campaign='', confidence='', description='', bucket_list=[], password=''): """ Ad...
if not os.path.isfile(email_path): log.error('{} is not a file'.format(email_path)) return None with open(email_path, 'rb') as fdata: data = { 'api_key': self.api_key, 'username': self.username, 'source': source, ...
<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_backdoor(self, backdoor_name, source, reference, method='', aliases=[], version='', campaign='', confidence='', description='', bucket_list=[]): """ Add ...
data = { 'api_key': self.api_key, 'username': self.username, 'source': source, 'reference': reference, 'method': method, 'name': backdoor_name, 'aliases': ','.join(aliases), 'version': version, 'campaign...
<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_events(self, event_title, regex=False): """ Search for events with the provided title Args: event_title: The title of the event Returns: An event JSON ob...
regex_val = 0 if regex: regex_val = 1 r = requests.get('{0}/events/?api_key={1}&username={2}&c-title=' '{3}&regex={4}'.format(self.url, self.api_key, self.username, event_title, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_samples(self, md5='', sha1='', sha256=''): """ Searches for a sample in CRITs. Currently only hashes allowed. Args: md5: md5sum sha1: sha1sum sha256: sha...
params = {'api_key': self.api_key, 'username': self.username} if md5: params['c-md5'] = md5 if sha1: params['c-sha1'] = sha1 if sha256: params['c-sha256'] = sha256 r = requests.get('{0}/samples/'.format(self.url), para...
<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_backdoor(self, name, version=''): """ Searches for the backdoor based on name and version. Args: name: The name of the backdoor. This can be an alias. ve...
params = {} params['or'] = 1 params['c-name'] = name params['c-aliases__in'] = name r = requests.get('{0}/backdoors/'.format(self.url), params=params, verify=self.verify, proxies=self.proxies) 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 has_relationship(self, left_id, left_type, right_id, right_type, rel_type='Related To'): """ Checks if the two objects are related Args: left_id: The CRITs I...
data = self.get_object(left_id, left_type) if not data: raise CRITsOperationalError('Crits Object not found with id {}' 'and type {}'.format(left_id, left_type)) if 'relationships' 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 forge_relationship(self, left_id, left_type, right_id, right_type, rel_type='Related To', rel_date=None, rel_confidence='high', rel_reason=''): """ Forges a ...
if not rel_date: rel_date = datetime.datetime.now() type_trans = self._type_translation(left_type) submit_url = '{}/{}/{}/'.format(self.url, type_trans, left_id) params = { 'api_key': self.api_key, 'username': self.username, } da...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _type_translation(self, str_type): """ Internal method to translate the named CRITs TLO type to a URL specific string. """
if str_type == 'Indicator': return 'indicators' if str_type == 'Domain': return 'domains' if str_type == 'IP': return 'ips' if str_type == 'Sample': return 'samples' if str_type == 'Event': return 'events' if st...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lineSeqmentsDoIntersect(line1, line2): """ Return True if line segment line1 intersects line segment line2 and line1 and line2 are not parallel. """
(x1, y1), (x2, y2) = line1 (u1, v1), (u2, v2) = line2 (a, b), (c, d) = (x2 - x1, u1 - u2), (y2 - y1, v1 - v2) e, f = u1 - x1, v1 - y1 denom = float(a * d - b * c) if _near(denom, 0): # parallel return False else: t = old_div((e * d - b * f), denom) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mf(pred, props=None, value_fn=None, props_on_match=False, priority=None): """ Matcher factory. """
if isinstance(pred, BaseMatcher): ret = pred if props_on_match else pred.props if isinstance(pred, basestring) or \ type(pred).__name__ == 'SRE_Pattern': ret = RegexMatcher(pred, props=props, value_fn=value_fn) if isinstance(pred, set): return OverlayMatcher(pred, props=pr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _merge_ovls(self, ovls): """ Merge ovls and also setup the value and props. """
ret = reduce(lambda x, y: x.merge(y), ovls) ret.value = self.value(ovls=ovls) ret.set_props(self.props) return 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 _fit_overlay_lists(self, text, start, matchers, **kw): """ Return a list of overlays that start at start. """
if matchers: for o in matchers[0].fit_overlays(text, start): for rest in self._fit_overlay_lists(text, o.end, matchers[1:]): yield [o] + rest else: yield []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def offset_overlays(self, text, offset=0, run_deps=True, **kw): """ The heavy lifting is done by fit_overlays. Override just that for alternatie implementation. ...
if run_deps and self.dependencies: text.overlay(self.dependencies) for ovlf in self.matchers[0].offset_overlays(text, goffset=offset, **kw): for ovll in self._fit_overlay_...
<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_run_matchers(self, text, run_matchers): """ OverlayedText should be smart enough to not run twice the same matchers but this is an extra handle of con...
if run_matchers is True or \ (run_matchers is not False and text not in self._overlayed_already): text.overlay(self.matchers) self._overlayed_already.append(text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_nodes_by_selector(self, selector, not_selector=None): """Return a collection of filtered nodes. Filtered based on the @selector and @not_selector paramet...
nodes = self.parsed(selector) if not_selector is not None: nodes = nodes.not_(not_selector) return nodes
<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_text_from_node(self, node, regex=None, group=1): """Get text from node and filter if necessary."""
text = self._get_stripped_text_from_node(node) if regex is not None: text = self._filter_by_regex(regex, text, group) return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_stripped_text_from_node(self, node): """Return the stripped text content of a node."""
return ( node.text_content() .replace(u"\u00A0", " ") .replace("\t", "") .replace("\n", "") .strip() )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wind(direction: Number, speed: Number, gust: Number, vardir: typing.List[Number] = None, unit: str = 'kt') -> str: """ Format wind details into a spoken word ...
unit = SPOKEN_UNITS.get(unit, unit) val = translate.wind(direction, speed, gust, vardir, unit, cardinals=False, spoken=True) return 'Winds ' + (val or 'unknown')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def temperature(header: str, temp: Number, unit: str = 'C') -> str: """ Format temperature details into a spoken word string """
if not (temp and temp.value): return header + ' unknown' if unit in SPOKEN_UNITS: unit = SPOKEN_UNITS[unit] use_s = '' if temp.spoken in ('one', 'minus one') else 's' return ' '.join((header, temp.spoken, 'degree' + use_s, unit))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visibility(vis: Number, unit: str = 'm') -> str: """ Format visibility details into a spoken word string """
if not vis: return 'Visibility unknown' if vis.value is None or '/' in vis.repr: ret_vis = vis.spoken else: ret_vis = translate.visibility(vis, unit=unit) if unit == 'm': unit = 'km' ret_vis = ret_vis[:ret_vis.find(' (')].lower().replace(unit, '').strip()...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def altimeter(alt: Number, unit: str = 'inHg') -> str: """ Format altimeter details into a spoken word string """
ret = 'Altimeter ' if not alt: ret += 'unknown' elif unit == 'inHg': ret += core.spoken_number(alt.repr[:2]) + ' point ' + core.spoken_number(alt.repr[2:]) elif unit == 'hPa': ret += core.spoken_number(alt.repr) return 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 other(wxcodes: typing.List[str]) -> str: """ Format wx codes into a spoken word string """
ret = [] for code in wxcodes: item = translate.wxcode(code) if item.startswith('Vicinity'): item = item.lstrip('Vicinity ') + ' in the Vicinity' ret.append(item) return '. '.join(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 type_and_times(type_: str, start: Timestamp, end: Timestamp, probability: Number = None) -> str: """ Format line type and times into the beginning of a spoken...
if not type_: return '' if type_ == 'BECMG': return f"At {start.dt.hour or 'midnight'} zulu becoming" ret = f"From {start.dt.hour or 'midnight'} to {end.dt.hour or 'midnight'} zulu," if probability and probability.value: ret += f" there's a {probability.value}% chance for" 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 wind_shear(shear: str, unit_alt: str = 'ft', unit_wind: str = 'kt') -> str: """ Format wind shear string into a spoken word string """
unit_alt = SPOKEN_UNITS.get(unit_alt, unit_alt) unit_wind = SPOKEN_UNITS.get(unit_wind, unit_wind) return translate.wind_shear(shear, unit_alt, unit_wind, spoken=True) or 'Wind shear unknown'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def metar(data: MetarData, units: Units) -> str: """ Convert MetarData into a string for text-to-speech """
speech = [] if data.wind_direction and data.wind_speed: speech.append(wind(data.wind_direction, data.wind_speed, data.wind_gust, data.wind_variable_direction, units.wind_speed)) if data.visibility: speech.append(visibility(data.visibilit...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def taf_line(line: TafLineData, units: Units) -> str: """ Convert TafLineData into a string for text-to-speech """
speech = [] start = type_and_times(line.type, line.start_time, line.end_time, line.probability) if line.wind_direction and line.wind_speed: speech.append(wind(line.wind_direction, line.wind_speed, line.wind_gust, unit=units.wind_speed)) if line.wind_shear: spe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def taf(data: TafData, units: Units) -> str: """ Convert TafData into a string for text-to-speech """
try: month = data.start_time.dt.strftime(r'%B') day = ordinal(data.start_time.dt.day) ret = f"Starting on {month} {day} - " except AttributeError: ret = '' return ret + '. '.join([taf_line(line, units) for line in data.forecast])
<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_bucket(): """ Get listing of S3 Bucket """
args = parser.parse_args() bucket = s3_bucket(args.aws_access_key_id, args.aws_secret_access_key, args.bucket_name) for b in bucket.list(): print(''.join([i if ord(i) < 128 else ' ' for i in b.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 walk_data(input_data): ''' a generator function for retrieving data in a nested dictionary :param input_data: dictionary or list with nested data :return: string with dot_path, object with value of endpoint ''' def _walk_dict(input_dict, path_to_root): if not path_to_root: ...
<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_data(function, input_data): ''' a function to apply a function to each value in a nested dictionary :param function: callable function with a single input of any datatype :param input_data: dictionary or list with nested data to transform :return: dictionary or list with data transformed...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def clean_data(input_value): ''' a function to transform a value into a json or yaml valid datatype :param input_value: object of any datatype :return: object with json valid datatype ''' # pass normal json/yaml datatypes if input_value.__class__.__name__ in ['bool', 'str', 'float', 'int', 'NoneT...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def reconstruct_dict(dot_paths, values): ''' a method for reconstructing a dictionary from the values along dot paths ''' output_dict = {} for i in range(len(dot_paths)): if i + 1 <= len(values): path_segments = segment_path(dot_paths[i]) current_nest = output_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def topological_sorting(nodes, relations): '''An implementation of Kahn's algorithm. ''' ret = [] nodes = set(nodes) | _nodes(relations) inc = _incoming(relations) out = _outgoing(relations) free = _free_nodes(nodes, inc) while free: n = free.pop() ret.append(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 _force_text_recursive(data): """ Descend into a nested data structure, forcing any lazy translation strings into plain text. """
if isinstance(data, list): ret = [ _force_text_recursive(item) for item in data ] if isinstance(data, ReturnList): return ReturnList(ret, serializer=data.serializer) return data elif isinstance(data, dict): ret = { key: _force_text_rec...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def color_text(text, color="none", bcolor="none", effect="none"): """ Return a formated text with bash color """
istty = False try: istty = sys.stdout.isatty() except: pass if not istty or not COLOR_ON: return text else: if not effect in COLOR_EFFET.keys(): effect = "none" if not color in COLOR_CODE_TEXT.keys(): color = "none" if not bcol...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def countLines(filename, buf_size=1048576): """ fast counting to the lines of a given filename through only reading out a limited buffer """
f = open(filename) try: lines = 1 read_f = f.read # loop optimization buf = read_f(buf_size) # Empty file if not buf: return 0 while buf: lines += buf.count('\n') buf = read_f(buf_size) return lines finally: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _names_to_bytes(names): """Reproducibly converts an iterable of strings to bytes :param iter[str] names: An iterable of strings :rtype: bytes """
names = sorted(names) names_bytes = json.dumps(names).encode('utf8') return names_bytes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hash_names(names, hash_function=None): """Return the hash of an iterable of strings, or a dict if multiple hash functions given. :param iter[str] names: An i...
hash_function = hash_function or hashlib.md5 names_bytes = _names_to_bytes(names) return hash_function(names_bytes).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_bel_resource_hash(location, hash_function=None): """Get a BEL resource file and returns its semantic hash. :param str location: URL of a resource :param ...
resource = get_bel_resource(location) return hash_names( resource['Values'], hash_function=hash_function )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def book_name(self, number): '''Return name of book with given index.''' try: name = self.cur.execute("SELECT name FROM book WHERE number = ?;", [number]).fetchone() except: self.error("cannot look up name of book number %s" % number) return(str(name[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 book_number(self, name): '''Return number of book with given name.''' try: number = self.cur.execute("SELECT number FROM book WHERE name= ?;", [name]).fetchone() except: self.error("cannot look up number of book with name %s" % name) return(number)
<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_books(self): ''' Return the list of book names ''' names = [] try: for n in self.cur.execute("SELECT name FROM book;").fetchall(): names.extend(n) except: self.error("ERROR: cannot find database table 'book'") return(names)