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 make_gpg_home(appname, config_dir=None): """ Make GPG keyring dir for a particular application. Return the path. """
assert is_valid_appname(appname) config_dir = get_config_dir( config_dir ) path = os.path.join( config_dir, "gpgkeys", appname ) if not os.path.exists(path): os.makedirs( path, 0700 ) else: os.chmod( path, 0700 ) return 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_gpg_home( appname, config_dir=None ): """ Get the GPG keyring directory for a particular application. Return the path. """
assert is_valid_appname(appname) config_dir = get_config_dir( config_dir ) path = os.path.join( config_dir, "gpgkeys", appname ) return 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 make_gpg_tmphome( prefix=None, config_dir=None ): """ Make a temporary directory to hold GPG keys that are not going to be stored to the application's keyrin...
if prefix is None: prefix = "tmp" config_dir = get_config_dir( config_dir ) tmppath = os.path.join( config_dir, "tmp" ) if not os.path.exists( tmppath ): os.makedirs( tmppath, 0700 ) tmpdir = tempfile.mkdtemp( prefix=("%s-" % prefix), dir=tmppath ) return tmpdir
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gpg_stash_key( appname, key_bin, config_dir=None, gpghome=None ): """ Store a key locally to our app keyring. Does NOT put it into a blockchain ID Return the...
assert is_valid_appname(appname) key_bin = str(key_bin) assert len(key_bin) > 0 if gpghome is None: config_dir = get_config_dir( config_dir ) keydir = make_gpg_home( appname, config_dir=config_dir ) else: keydir = gpghome gpg = gnupg.GPG( homedir=keydir ) res = gp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gpg_unstash_key( appname, key_id, config_dir=None, gpghome=None ): """ Remove a public key locally from our local app keyring Return True on success Return F...
assert is_valid_appname(appname) if gpghome is None: config_dir = get_config_dir( config_dir ) keydir = get_gpg_home( appname, config_dir=config_dir ) else: keydir = gpghome gpg = gnupg.GPG( homedir=keydir ) res = gpg.delete_keys( [key_id] ) if res.status == 'Must dele...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gpg_download_key( key_id, key_server, config_dir=None ): """ Download a GPG key from a key server. Do not import it into any keyrings. Return the ASCII-armor...
config_dir = get_config_dir( config_dir ) tmpdir = make_gpg_tmphome( prefix="download", config_dir=config_dir ) gpg = gnupg.GPG( homedir=tmpdir ) recvdat = gpg.recv_keys( key_server, key_id ) fingerprint = None try: assert recvdat.count == 1 assert len(recvdat.fingerprints) ==...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gpg_key_fingerprint( key_data, config_dir=None ): """ Get the key ID of a given serialized key Return the fingerprint on success Return None on error """
key_data = str(key_data) config_dir = get_config_dir( config_dir ) tmpdir = make_gpg_tmphome( prefix="key_id-", config_dir=config_dir ) gpg = gnupg.GPG( homedir=tmpdir ) res = gpg.import_keys( key_data ) try: assert res.count == 1, "Failed to import key" assert len(res.finger...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gpg_verify_key( key_id, key_data, config_dir=None ): """ Verify that a given serialized key, when imported, has the given key ID. Return True on success Retu...
key_data = str(key_data) config_dir = get_config_dir( config_dir ) sanitized_key_id = "".join( key_id.upper().split(" ") ) if len(sanitized_key_id) < 16: log.debug("Fingerprint is too short to be secure") return False fingerprint = gpg_key_fingerprint( key_data, config_dir=c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gpg_export_key( appname, key_id, config_dir=None, include_private=False ): """ Get the ASCII-armored key, given the ID """
assert is_valid_appname(appname) config_dir = get_config_dir( config_dir ) keydir = get_gpg_home( appname, config_dir=config_dir ) gpg = gnupg.GPG( homedir=keydir ) keydat = gpg.export_keys( [key_id], secret=include_private ) if not keydat: log.debug("Failed to export key %s from '%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 gpg_fetch_key( key_url, key_id=None, config_dir=None ): """ Fetch a GPG public key from the given URL. Supports anything urllib2 supports. If the URL has no ...
dat = None from_blockstack = False # make sure it's valid try: urlparse.urlparse(key_url) except: log.error("Invalid URL") return None if "://" in key_url and not key_url.lower().startswith("iks://"): opener = None key_data = None # handle ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gpg_app_put_key( blockchain_id, appname, keyname, key_data, txid=None, immutable=False, proxy=None, wallet_keys=None, config_dir=None ): """ Put an applicati...
assert is_valid_appname(appname) assert is_valid_keyname(keyname) try: keydir = make_gpg_home( appname, config_dir=config_dir ) key_id = gpg_stash_key( appname, key_data, config_dir=config_dir, gpghome=keydir ) assert key_id is not None, "Failed to stash key" log.debug("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 gpg_app_delete_key( blockchain_id, appname, keyname, txid=None, immutable=False, proxy=None, wallet_keys=None, config_dir=None ): """ Remove an application G...
assert is_valid_appname(appname) assert is_valid_keyname(keyname) fq_key_name = "gpg.%s.%s" % (appname, keyname) result = {} dead_pubkey_dict = None dead_pubkey = None key_id = None if not immutable: # find the key first, so we can get the key ID and then remove it locall...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gpg_sign( path_to_sign, sender_key_info, config_dir=None, passphrase=None ): """ Sign a file on disk. @sender_key_info should be a dict with { } """
if config_dir is None: config_dir = get_config_dir() # ingest keys tmpdir = make_gpg_tmphome( prefix="sign", config_dir=config_dir ) try: sender_privkey = gpg_export_key( sender_key_info['app_name'], sender_key_info['key_id'], include_private=True, config_dir=config_dir ) except...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gpg_verify( path_to_verify, sigdata, sender_key_info, config_dir=None ): """ Verify a file on disk was signed by the given sender. @sender_key_info should be...
if config_dir is None: config_dir = get_config_dir() # ingest keys tmpdir = make_gpg_tmphome( prefix="verify", config_dir=config_dir ) res = gpg_stash_key( "verify", sender_key_info['key_data'], config_dir=config_dir, gpghome=tmpdir ) if res is None: shutil.rmtree(tmpdir) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gpg_encrypt( fd_in, path_out, sender_key_info, recipient_key_infos, passphrase=None, config_dir=None ): """ Encrypt a stream of data for a set of keys. @send...
if config_dir is None: config_dir = get_config_dir() # ingest keys tmpdir = make_gpg_tmphome( prefix="encrypt", config_dir=config_dir ) for key_info in recipient_key_infos: res = gpg_stash_key( "encrypt", key_info['key_data'], config_dir=config_dir, gpghome=tmpdir ) if res is...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gpg_decrypt( fd_in, path_out, sender_key_info, my_key_info, passphrase=None, config_dir=None ): """ Decrypt a stream of data using key info for a private key...
if config_dir is None: config_dir = get_config_dir() # ingest keys tmpdir = make_gpg_tmphome( prefix="decrypt", config_dir=config_dir ) res = gpg_stash_key( "decrypt", sender_key_info['key_data'], config_dir=config_dir, gpghome=tmpdir ) if res is None: shutil.rmtree(tmpdir) ...
<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_primary_command_usage(message=''): # type: (str) -> str """Return the usage string for the primary command."""
if not settings.merge_primary_command and None in settings.subcommands: return format_usage(settings.subcommands[None].__doc__) if not message: message = '\n{}\n'.format(settings.message) if settings.message else '' doc = _DEFAULT_DOC.format(message=message) if None in settings.subcomma...
<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_help_usage(command): # type: (str) -> None """Print out a help message and exit the program. Args: command: If a command value is supplied then print the...
if not command: doc = get_primary_command_usage() elif command in ('-a', '--all'): subcommands = [k for k in settings.subcommands if k is not None] available_commands = subcommands + ['help'] command_doc = '\nAvailable commands:\n{}\n'.format( '\n'.join(' {}'.format...
<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_usage(doc, width=None): # type: (str, Optional[int]) -> str """Format the docstring for display to the user. Args: doc: The docstring to reformat for ...
sections = doc.replace('\r', '').split('\n\n') width = width or get_terminal_size().columns or 80 return '\n\n'.join(_wrap_section(s.strip(), width) for s in sections)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_commands(docstring): # type: (str) -> Generator[Tuple[List[str], List[str]], None, None] """Parse a docopt-style string for commands and subcommands. A...
try: docopt.docopt(docstring, argv=()) except (TypeError, docopt.DocoptLanguageError): return except docopt.DocoptExit: pass for command in _parse_section('usage', docstring): args = command.split() commands = [] i = 0 for i, arg in enumerate(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 _merge_doc(original, to_merge): # type: (str, str) -> str """Merge two usage strings together. Args: original: The source of headers and initial section line...
if not original: return to_merge or '' if not to_merge: return original or '' sections = [] for name in ('usage', 'arguments', 'options'): sections.append(_merge_section( _get_section(name, original), _get_section(name, to_merge) )) return for...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _merge_section(original, to_merge): # type: (str, str) -> str """Merge two sections together. Args: original: The source of header and initial section lines....
if not original: return to_merge or '' if not to_merge: return original or '' try: index = original.index(':') + 1 except ValueError: index = original.index('\n') name = original[:index].strip() section = '\n '.join( (original[index + 1:].lstrip(), to_me...
<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_section(name, source): # type: (str, str) -> Optional[str] """Extract the named section from the source. Args: name: The name of the section to extract ...
pattern = re.compile( '^([^\n]*{name}[^\n]*\n?(?:[ \t].*?(?:\n|$))*)'.format(name=name), re.IGNORECASE | re.MULTILINE) usage = None for section in pattern.findall(source): usage = _merge_section(usage, section.strip()) return usage
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _wrap_section(source, width): # type: (str, int) -> str """Wrap the given section string to the current terminal size. Intelligently wraps the section string...
if _get_section('usage', source): return _wrap_usage_section(source, width) if _is_definition_section(source): return _wrap_definition_section(source, width) lines = inspect.cleandoc(source).splitlines() paragraphs = (textwrap.wrap(line, width, replace_whitespace=False) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_definition_section(source): """Determine if the source is a definition section. Args: source: The usage string source that may be a section. Returns: Tru...
try: definitions = textwrap.dedent(source).split('\n', 1)[1].splitlines() return all( re.match(r'\s\s+((?!\s\s).+)\s\s+.+', s) for s in definitions) except IndexError: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _wrap_usage_section(source, width): # type: (str, int) -> str """Wrap the given usage section string to the current terminal size. Note: Commands arguments a...
if not any(len(line) > width for line in source.splitlines()): return source section_header = source[:source.index(':') + 1].strip() lines = [section_header] for commands, args in parse_commands(source): command = ' {} '.format(' '.join(commands)) max_len = width - len(command)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _wrap_definition_section(source, width): # type: (str, int) -> str """Wrap the given definition section string to the current terminal size. Note: Auto-adjus...
index = source.index('\n') + 1 definitions, max_len = _get_definitions(source[index:]) sep = '\n' + ' ' * (max_len + 4) lines = [source[:index].strip()] for arg, desc in six.iteritems(definitions): wrapped_desc = sep.join(textwrap.wrap(desc, width - max_len - 4)) lines.append(' {ar...
<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_definitions(source): # type: (str) -> Tuple[Dict[str, str], int] """Extract a dictionary of arguments and definitions. Args: source: The source for a se...
max_len = 0 descs = collections.OrderedDict() # type: Dict[str, str] lines = (s.strip() for s in source.splitlines()) non_empty_lines = (s for s in lines if s) for line in non_empty_lines: if line: arg, desc = re.split(r'\s\s+', line.strip()) arg_len = len(arg) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_section(name, source): # type: (str, str) -> List[str] """Yield each section line. Note: Depending on how it is wrapped, a section line can take up mo...
section = textwrap.dedent(_get_section(name, source)[7:]) commands = [] # type: List[str] for line in section.splitlines(): if not commands or line[:1].isalpha() and line[:1].islower(): commands.append(line) else: commands[-1] = '{} {}'.format(commands[-1].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 move(self, particle, u, v, w, modelTimestep, **kwargs): """ I'm dead, so no behaviors should act on me """
# Kill the particle if it isn't settled and isn't already dead. if not particle.settled and not particle.dead: particle.die() # Still save the temperature and salinity for the model output temp = kwargs.get('temperature', None) if temp is not None and math.isnan(te...
<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_history_file(self, filename=None): u'''Load a readline history file.''' if filename is None: filename = self.history_filename try: for line in open(filename, u'r'): self.add_history(lineobj.ReadLineTextBuffer(ensure_unicode(line.rstrip())))...
<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_history_file(self, filename = None): u'''Save a readline history file.''' if filename is None: filename = self.history_filename fp = open(filename, u'wb') for line in self.history[-self.history_length:]: fp.write(ensure_str(line.get_line_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 add_history(self, line): u'''Append a line to the history buffer, as if it was the last line typed.''' if not hasattr(line, "get_line_text"): line = lineobj.ReadLineTextBuffer(line) if not line.get_line_text(): pass elif len(self.history) > 0 and self.hi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def beginning_of_history(self): # (M-<) u'''Move to the first line in the history.''' self.history_cursor = 0 if len(self.history) > 0: self.l_buffer = self.history[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 get_time_objects_from_model_timesteps(cls, times, start): """ Calculate the datetimes of the model timesteps times should start at 0 and be in seconds """
modelTimestep = [] newtimes = [] for i in xrange(0, len(times)): try: modelTimestep.append(times[i+1] - times[i]) except StandardError: modelTimestep.append(times[i] - times[i-1]) newtimes.append(start + timedelta(seconds=time...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fill_polygon_with_points(cls, goal=None, polygon=None): """ Fill a shapely polygon with X number of points """
if goal is None: raise ValueError("Must specify the number of points (goal) to fill the polygon with") if polygon is None or (not isinstance(polygon, Polygon) and not isinstance(polygon, MultiPolygon)): raise ValueError("Must specify a polygon to fill points with") min...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def distance_from_location_using_u_v_w(cls, u=None, v=None, w=None, timestep=None, location=None): """ Calculate the greate distance from a location using u, v, ...
# Move horizontally distance_horiz = 0 azimuth = 0 angle = 0 depth = location.depth if u is not 0 and v is not 0: s_and_d = AsaMath.speed_direction_from_u_v(u=u,v=v) # calculates velocity in m/s from transformed u and v distance_horiz = s_and_d['...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shutdown(self): """Wait for all threads to complete"""
# cleanup self.started = False try: # nice way of doing things - let's wait until all items # in the queue are processed for t in self._threads: t.join() finally: # Emergency brake - if a KeyboardInterrupt is raised, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _unpack_bytes(bytes): """ Unpack a set of bytes into an integer. First pads to 4 bytes. Little endian. """
if bytes == b'': return 0 int_length = 4 len_diff = int_length - len(bytes) bytes = bytes + len_diff * b'\x00' return struct.unpack("<L", bytes)[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 get_sprints(): """ Returns all sprints, enriched with their assigned tasks. The project should only have one ``sprints.py`` module. We will define it's path ...
sprints = load_member_from_setting( 'RAPID_PROTOTYPING_SPRINTS_MODULE') all_tasks = [] # TODO The onerror parameter is basically a workaround to ignore errors # The reason for that being, that in my case, the GeoDjango package was in # the path, permanently requesting certain libraries on ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append_overhead_costs(costs, new_id, overhead_percentage=0.15): """ Adds 15% overhead costs to the list of costs. Usage:: from rapid_prototyping.context.util...
total_time = 0 for item in costs: total_time += item['time'] costs.append({ 'id': new_id, 'task': 'Overhead, Bufixes & Iterations', 'time': total_time * overhead_percentage, }, ) return costs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def arduino_default_path(): """platform specific default root path."""
if sys.platform == 'darwin': s = path('/Applications/Arduino.app/Contents/Resources/Java') elif sys.platform == 'win32': s = None else: s = path('/usr/share/arduino/') return 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 checkForChanges(f, sde, isTable): """ returns False if there are no changes """
# try simple feature count first fCount = int(arcpy.GetCount_management(f).getOutput(0)) sdeCount = int(arcpy.GetCount_management(sde).getOutput(0)) if fCount != sdeCount: return True fields = [fld.name for fld in arcpy.ListFields(f)] # filter out shape fields if not isTable: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install_metaboard( replace_existing=False, ): """install metaboard. http://metalab.at/wiki/Metaboard """
metaboard = AutoBunch() metaboard.name = 'Metaboard' metaboard.upload.protocol = 'usbasp' metaboard.upload.maximum_size = '14336' metaboard.upload.speed = '19200' metaboard.build.mcu = 'atmega168' metaboard.build.f_cpu = '16000000L' metaboard.build.core = 'arduino' metaboard.uplo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __total_pages(self) -> int: """ Return max pages created by limit """
row_count = self.model.query.count() if isinstance(row_count, int): return int(row_count / self.limit) 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 links(self, base_link, current_page) -> dict: """ Return JSON paginate links """
max_pages = self.max_pages - 1 if \ self.max_pages > 0 else self.max_pages base_link = '/%s' % (base_link.strip("/")) self_page = current_page prev = current_page - 1 if current_page is not 0 else None prev_link = '%s/page/%s/%s' % (base_link, prev, self.limit)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def json_paginate(self, base_url, page_number): """ Return a dict for a JSON paginate """
data = self.page(page_number) first_id = None last_id = None if data: first_id = data[0].id last_id = data[-1].id return { 'meta': { 'total_pages': self.max_pages, 'first_id': first_id, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_arguments(parser, default_level=logging.INFO): """ Add arguments to an ArgumentParser or OptionParser for purposes of grabbing a logging level. "...
adder = ( getattr(parser, 'add_argument', None) or getattr(parser, 'add_option') ) adder( '-l', '--log-level', default=default_level, type=log_level, help="Set log level (DEBUG, INFO, WARNING, ERROR)")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup(options, **kwargs): """ Setup logging with options or arguments from an OptionParser or ArgumentParser. Also pass any keyword arguments to the ba...
params = dict(kwargs) params.update(level=options.log_level) logging.basicConfig(**params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_requests_logging(level): """ Setup logging for 'requests' such that it logs details about the connection, headers, etc. """
requests_log = logging.getLogger("requests.packages.urllib3") requests_log.setLevel(level) requests_log.propagate = True # enable debugging at httplib level http_client.HTTPConnection.debuglevel = level <= logging.DEBUG
<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_period(self, period): """ Set the period for the timestamp. If period is 0 or None, no period will be used. """
self._period = period if period: self._period_seconds = tempora.get_period_seconds(self._period) self._date_format = tempora.get_date_format_string( self._period_seconds) else: self._period_seconds = 0 self._date_format = ''
<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_filename(self, t): """ Return the appropriate filename for the given time based on the defined period. """
root, ext = os.path.splitext(self.base_filename) # remove seconds not significant to the period if self._period_seconds: t -= t % self._period_seconds # convert it to a datetime object for formatting dt = datetime.datetime.utcfromtimestamp(t) # append the datestring to the filename # workaroun...
<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): """ Emit a record. Output the record to the file, ensuring that the currently- opened file has the correct date. """
now = time.time() current_name = self.get_filename(now) try: if not self.stream.name == current_name: self._use_file(current_name) except AttributeError: # a stream has not been created, so create one. self._use_file(current_name) logging.StreamHandler.emit(self, record)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(app, uri, file_or_directory, pattern, use_modified_since, use_content_range): # TODO: Though mach9 is not a file server, I feel like we should at le...
# If we're not trying to match a file directly, # serve from the folder if not path.isfile(file_or_directory): uri += '<file_uri:' + pattern + '>' async def _handler(request, file_uri=None): # Using this to determine if the URL is trying to break out of the path # served. os.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 fix_imports(script): """ Replace "from PyQt5 import" by "from pyqode.qt import". :param script: script path """
with open(script, 'r') as f_script: lines = f_script.read().splitlines() new_lines = [] for l in lines: if l.startswith("import "): l = "from . " + l if "from PyQt5 import" in l: l = l.replace("from PyQt5 import", "from pyqode.qt import") new_lines.ap...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eval_py(self, _globals, _locals): """ Evaluates a file containing a Python params dictionary. """
try: params = eval(self.script, _globals, _locals) except NameError as e: raise Exception( 'Failed to evaluate parameters: {}' .format(str(e)) ) except ResolutionError as e: raise Exception('GetOutput: {}'.format(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 new(cls, arg): """ Creates a new Parameter object from the given ParameterArgument. """
content = None if arg.kind == 'file': if os.path.exists(arg.value): with open(arg.value, 'r') as f: content = f.read() else: raise Exception('File does not exist: {}'.format(arg.value)) elif arg.kind == 'cli': ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def minimum_pitch(self): """ Returns the minimal pitch between two neighboring nodes of the mesh in each direction. :return: Minimal pitch in each direction. """
pitch = self.pitch minimal_pitch = [] for p in pitch: minimal_pitch.append(min(p)) return min(minimal_pitch)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def surrounding_nodes(self, position): """ Returns nearest node indices and direction of opposite node. :param position: Position inside the mesh to search neare...
n_node_index, n_node_position, n_node_error = self.nearest_node(position) if n_node_error == 0.0: index_mod = [] for i in range(len(n_node_index)): new_point = np.asarray(n_node_position) new_point[i] += 1.e-5*np.abs(new_point[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 tokenize(self, string): """Tokenize a string and return an iterator over its tokens."""
it = colorise.compat.ifilter(None, self._pattern.finditer(string)) try: t = colorise.compat.next(it) except StopIteration: yield string, False return pos, buf, lm, escapeflag = -1, '', -1, False # Check if we need to yield any starting 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 parse(self, format_string): """Parse color syntax from a formatted string."""
txt, state = '', 0 colorstack = [(None, None)] itokens = self.tokenize(format_string) for token, escaped in itokens: if token == self._START_TOKEN and not escaped: if txt: yield txt, colorstack[-1] txt = '' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_mapping(cls, evidence_mapping): """Create an Evidence instance from the given mapping :param evidence_mapping: a mapping (e.g. dict) of values provided ...
return cls(metadata_map=MetadataMap.from_mapping(evidence_mapping['metadataMap']), copyright=evidence_mapping['copyright'], id=evidence_mapping['id'], terms_of_use=evidence_mapping['termsOfUse'], document=evidence_mapping['document'], ...
<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_obj(cls, obj_data=None, *fields, **field_map): ''' prioritize obj_dict when there are conficts ''' obj_dict = obj_data.__dict__ if hasattr(obj_data, '__dict__') else obj_data if not fields: fields = obj_dict.keys() obj = cls() update_obj(obj_dict, obj, *fields, **field_map) 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 with_ctx(func=None): ''' Auto create a new context if not available ''' if not func: return functools.partial(with_ctx) @functools.wraps(func) def func_with_context(_obj, *args, **kwargs): if 'ctx' not in kwargs or kwargs['ctx'] is None: # if context is empty, ensure con...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def open(self, auto_commit=None, schema=None): ''' Create a context to execute queries ''' if schema is None: schema = self.schema ac = auto_commit if auto_commit is not None else schema.auto_commit exe = ExecutionContext(self.path, schema=schema, auto_commit=ac) # 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 build_insert(self, table, values, columns=None): ''' Insert an active record into DB and return lastrowid if available ''' if not columns: columns = table.columns if len(values) < len(columns): column_names = ','.join(columns[-len(values):]) 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 select_record(self, table, where=None, values=None, orderby=None, limit=None, columns=None): ''' Support these keywords where, values, orderby, limit and columns''' query = self.schema.query_builder.build_select(table, where, orderby, limit, columns) return table.to_table(self.execute(query,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def should_be_excluded(name, exclude_patterns): """Check if a name should be excluded. Returns True if name matches at least one of the exclude patterns in the e...
for pattern in exclude_patterns: if fnmatch.fnmatch(name, pattern): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter_visited(curr_dir, subdirs, already_visited, follow_dirlinks, on_error): """Filter subdirs that have already been visited. This is used to avoid loops ...
filtered = [] to_visit = set() _already_visited = already_visited.copy() try: # mark the current directory as visited, so we catch symlinks to it # immediately instead of after one iteration of the directory loop file_info = os.stat(curr_dir) if follow_dirlinks else os.lstat(cu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def index_files_by_size(root, files_by_size, exclude_dirs, exclude_files, follow_dirlinks): """Recursively index files under a root directory. Each regular file ...
# encapsulate the value in a list, so we can modify it by reference # inside the auxiliary function errors = [] already_visited = set() def _print_error(error): """Print a listing error to stderr. error should be an os.OSError instance. """ # modify the outside er...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calculate_md5(filename, length): """Calculate the MD5 hash of a file, up to length bytes. Returns the MD5 in its binary form, as an 8-byte string. Raises IOE...
assert length >= 0 # shortcut: MD5 of an empty string is 'd41d8cd98f00b204e9800998ecf8427e', # represented here in binary if length == 0: return '\xd4\x1d\x8c\xd9\x8f\x00\xb2\x04\xe9\x80\t\x98\xec\xf8\x42\x7e' md5_summer = hashlib.md5() f = open(filename, 'rb') try: byte...
<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_duplicates(filenames, max_size): """Find duplicates in a list of files, comparing up to `max_size` bytes. Returns a 2-tuple of two values: ``(duplicate_...
errors = [] # shortcut: can't have duplicates if there aren't at least 2 files if len(filenames) < 2: return [], errors # shortcut: if comparing 0 bytes, they're all the same if max_size == 0: return [filenames], errors files_by_md5 = {} for filename in filenames: ...
<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_duplicates_in_dirs(directories, exclude_dirs=None, exclude_files=None, follow_dirlinks=False): """Recursively scan a list of directories, looking for du...
if exclude_dirs is None: exclude_dirs = [] if exclude_files is None: exclude_files = [] errors_in_total = [] files_by_size = {} # First, group all files by size for directory in directories: sub_errors = index_files_by_size(directory, files_by_size, exclude_dirs, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def semimajor(P,M): """P, M can be ``Quantity`` objects; otherwise default to day, M_sun """
if type(P) != Quantity: P = P*u.day if type(M) != Quantity: M = M*u.M_sun a = ((P/2/np.pi)**2*const.G*M)**(1./3) return a.to(u.AU)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def random_spherepos(n): """returns SkyCoord object with n positions randomly oriented on the unit sphere Parameters n : int number of positions desired Returns ...
signs = np.sign(rand.uniform(-1,1,size=n)) thetas = Angle(np.arccos(rand.uniform(size=n)*signs),unit=u.rad) #random b/w 0 and 180 phis = Angle(rand.uniform(0,2*np.pi,size=n),unit=u.rad) c = SkyCoord(phis,thetas,1,representation='physicsspherical') return c
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_dict(self): """ Return a dict of all instance variables with truthy values, with key names camelized """
return { inflection.camelize(k, False): v for k, v in self.__dict__.items() if 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 depth(self): """ Returns the number of ancestors of this directory. """
return len(self.path.rstrip(os.sep).split(os.sep))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ancestors(self, stop=None): """ Generates the parents until stop or the absolute root directory is reached. """
folder = self while folder.parent != stop: if folder.parent == folder: return yield folder.parent folder = folder.parent
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_descendant_of(self, ancestor): """ Checks if this folder is inside the given ancestor. """
stop = Folder(ancestor) for folder in self.ancestors(): if folder == stop: return True if stop.depth > folder.depth: return False return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_relative_path(self, root): """ Gets the fragment of the current path starting at root. """
if self.path == root: return '' ancestors = self.ancestors(stop=root) return functools.reduce(lambda f, p: Folder(p.name).child(f), ancestors, 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 get_mirror(self, target_root, source_root=None): """ Returns a File or Folder object that reperesents if the entire fragment of this directory starting with ...
fragment = self.get_relative_path( source_root if source_root else self.parent) return Folder(target_root).child(fragment)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def file_or_folder(path): """ Returns a File or Folder object that would represent the given path. """
target = unicode(path) return Folder(target) if os.path.isdir(target) else File(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 is_binary(self): """Return true if this is a binary file."""
with open(self.path, 'rb') as fin: CHUNKSIZE = 1024 while 1: chunk = fin.read(CHUNKSIZE) if b'\0' in chunk: return True if len(chunk) < CHUNKSIZE: break return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_temp(text): """ Creates a temprorary file and writes the `text` into it """
import tempfile (handle, path) = tempfile.mkstemp(text=True) os.close(handle) afile = File(path) afile.write(text) return afile
<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_all(self, encoding='utf-8'): """ Reads from the file and returns the content as a string. """
logger.info("Reading everything from %s" % self) with codecs.open(self.path, 'r', encoding) as fin: read_text = fin.read() return read_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 write(self, text, encoding="utf-8"): """ Writes the given text to the file using the given encoding. """
logger.info("Writing to %s" % self) with codecs.open(self.path, 'w', encoding) as fout: fout.write(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 copy_to(self, destination): """ Copies the file to the given destination. Returns a File object that represents the target file. `destination` must be a File...
target = self.__get_destination__(destination) logger.info("Copying %s to %s" % (self, target)) shutil.copy(self.path, unicode(destination)) return 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 etag(self): """ Generates etag from file contents. """
CHUNKSIZE = 1024 * 64 from hashlib import md5 hash = md5() with open(self.path) as fin: chunk = fin.read(CHUNKSIZE) while chunk: hash_update(hash, chunk) chunk = fin.read(CHUNKSIZE) return hash.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 child_folder(self, fragment): """ Returns a folder object by combining the fragment to this folder's path """
return Folder(os.path.join(self.path, Folder(fragment).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 child(self, fragment): """ Returns a path of a child item represented by `fragment`. """
return os.path.join(self.path, FS(fragment).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 make(self): """ Creates this directory and any of the missing directories in the path. Any errors that may occur are eaten. """
try: if not self.exists: logger.info("Creating %s" % self.path) os.makedirs(self.path) except os.error: pass 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 delete(self): """ Deletes the directory if it exists. """
if self.exists: logger.info("Deleting %s" % self.path) shutil.rmtree(self.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 _create_target_tree(self, target): """ There is a bug in dir_util that makes `copy_tree` crash if a folder in the tree has been deleted before and readded no...
source = self with source.walker as walker: @walker.folder_visitor def visit_folder(folder): """ Create the mirror directory """ if folder != source: Folder(folder.get_mirror(target, source)).ma...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy_contents_to(self, destination): """ Copies the contents of this directory to the given destination. Returns a Folder object that represents the moved di...
logger.info("Copying contents of %s to %s" % (self, destination)) target = Folder(destination) target.make() self._create_target_tree(target) dir_util.copy_tree(self.path, unicode(target)) return 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 __start(self): """ Start a new thread to process Cron """
thread = Thread(target=self.__loop, args=()) thread.daemon = True # daemonize thread thread.start() self.__enabled = True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __dict_to_BetterDict(self, attr): """Convert the passed attr to a BetterDict if the value is a dict Returns: The new value of the passed attribute."""
if type(self[attr]) == dict: self[attr] = BetterDict(self[attr]) return self[attr]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _bd_(self): """Property that allows dot lookups of otherwise hidden attributes."""
if not getattr(self, '__bd__', False): self.__bd = BetterDictLookUp(self) return self.__bd
<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_or_update(sender, **kwargs): """ Create or update an Activity Monitor item from some instance. """
now = datetime.datetime.now() # I can't explain why this import fails unless it's here. from activity_monitor.models import Activity instance = kwargs['instance'] # Find this object's content type and model class. instance_content_type = ContentType.objects.get_for_model(sender) instance_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def highlight_differences(s1, s2, color): """Highlight the characters in s2 that differ from those in s1."""
ls1, ls2 = len(s1), len(s2) diff_indices = [i for i, (a, b) in enumerate(zip(s1, s2)) if a != b] print(s1) if ls2 > ls1: colorise.cprint('_' * (ls2-ls1), fg=color) else: print() colorise.highlight(s2, indices=diff_indices, fg=color, end='') if ls1 > ls2: coloris...
<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_jinja_env(): """Create a Jinja2 `~jinja2.Environment`. Returns ------- env : `jinja2.Environment` Jinja2 template rendering environment, configured to...
template_dir = os.path.join(os.path.dirname(__file__), 'templates') env = jinja2.Environment( loader=jinja2.FileSystemLoader(template_dir), autoescape=jinja2.select_autoescape(['html']) ) env.filters['simple_date'] = filter_simple_date env.filters['paragraphify'] = filter_paragraphi...