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 _construct_columns(self, column_map):
''' a helper method for constructing the column objects for a table object '''
from sqlalchemy import Column, String, Boolean, Integer, Float, Binary
column_args = []
for key, value in column_map.items():
record_key = value[0]
datatype = value[1]
max_length = value[2]
if record_key == 'id':
if datatype in ('string', 'float', 'integer'):
if datatype == 'string':
if max_length:
column_args.insert(0, Column(record_key, String(max_length), primary_key=True))
else:
column_args.insert(0, Column(record_key, String, primary_key=True))
elif datatype == 'float':
column_args.insert(0, Column(record_key, Float, primary_key=True))
elif datatype == 'integer':
column_args.insert(0, Column(record_key, Integer, primary_key=True))
else:
raise ValueError('Field "id" in record_schema must be a string, float or integer.')
else:
if datatype == 'boolean':
column_args.append(Column(record_key, Boolean))
elif datatype == 'string':
if max_length:
column_args.append(Column(record_key, String(max_length)))
else:
column_args.append(Column(record_key, String))
elif datatype == 'float':
column_args.append(Column(record_key, Float))
elif datatype == 'integer':
column_args.append(Column(record_key, Integer))
elif datatype == 'list':
column_args.append(Column(record_key, Binary))
return column_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 _reconstruct_record(self, record_object):
''' a helper method for reconstructing record fields from record object '''
record_details = {}
current_details = record_details
for key, value in self.model.keyMap.items():
record_key = key[1:]
if record_key:
record_value = getattr(record_object, record_key, None)
if record_value != None:
record_segments = record_key.split('.')
for i in range(len(record_segments)):
segment = record_segments[i]
if i + 1 < len(record_segments):
if segment not in record_details.keys():
current_details[segment] = {}
current_details = current_details[segment]
else:
if isinstance(record_value, bytes):
current_details[segment] = pickle.loads(record_value)
else:
current_details[segment] = record_value
current_details = record_details
return record_details |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _compare_columns(self, new_columns, old_columns):
''' a helper method for generating differences between column properties '''
# print(new_columns)
# print(old_columns)
add_columns = {}
remove_columns = {}
rename_columns = {}
retype_columns = {}
resize_columns = {}
for key, value in new_columns.items():
if key not in old_columns.keys():
add_columns[key] = True
if value[2]:
if value[2] in old_columns.keys():
rename_columns[key] = value[2]
del add_columns[key]
else:
if value[1] != old_columns[key][1]:
retype_columns[key] = value[1]
if value[3] != old_columns[key][3]:
resize_columns[key] = value[3]
remove_keys = set(old_columns.keys()) - set(new_columns.keys())
if remove_keys:
for key in list(remove_keys):
remove_columns[key] = True
return add_columns, remove_columns, rename_columns, retype_columns, resize_columns |
<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_inserts(self, record, new_columns, rename_columns, retype_columns, resize_columns):
''' a helper method for constructing the insert kwargs for a record '''
insert_kwargs = {}
for key, value in new_columns.items():
# retrieve value for key (or from old key name)
if key in rename_columns.keys():
record_value = getattr(record, rename_columns[key], None)
else:
record_value = getattr(record, key, None)
# attempt to convert datatype
if record_value:
if key in retype_columns.keys():
try:
old_list = False
if isinstance(record_value, bytes):
record_value = pickle.loads(record_value)
old_list = True
if retype_columns[key] == 'boolean':
record_value = bool(record_value)
elif retype_columns[key] == 'string':
if old_list:
record_value = ','.join(record_value)
else:
record_value = str(record_value)
elif retype_columns[key] == 'integer':
if old_list:
record_value = int(record_value[0])
else:
record_value = int(record_value)
elif retype_columns[key] == 'float':
if old_list:
record_value = int(record_value[0])
else:
record_value = float(record_value)
elif retype_columns[key] == 'list':
if isinstance(record_value, str):
record_value = pickle.dumps(record_value.split(','))
else:
record_value = pickle.dumps([record_value])
except:
record_value = None
# attempt to resize string data
if key in resize_columns.keys():
max_length = resize_columns[key]
try:
if len(record_value) > max_length:
record_value = record_value[0:max_length]
except:
record_value = None
insert_kwargs[key] = record_value
return insert_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 generate(self, gender=None, part=None, snake_case=False, weighted=False):
"""Generate a Queb name. :param str gender: Gender of name to generate, one of 'male' or 'female'. If not specified, either gender can be generated. (optional) :param str part: Part of the name to generate, one of 'first' or 'last'. If not specified, full names are generated. (optional) :param bool snake_case: If True, generate a name in "snake_case" format, also stripping diacritics if any. (default: False) :param bool weighted: If True, generate names according to their relative popularity. (default: False) :return str: The generated name. """ |
if weighted:
get_random_name = self._get_weighted_random_name
else:
get_random_name = self._get_random_name
if gender == 'male':
first_names = self._male_names
elif gender == 'female':
first_names = self._female_names
else:
first_names = self._names
name = ''
surname = ''
if part == 'first':
name = get_random_name(first_names)
elif part == 'last':
surname = get_random_name(self._surnames)
else:
name = get_random_name(first_names)
surname = get_random_name(self._surnames)
return self._format_name(name, surname, snake_case=snake_case) |
<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_name_file(self, filename):
"""Read a name file from the data directory :param filename: Name of the file to read. :return: A list of name entries. """ |
file_path = os.path.join(self._DATA_DIR, filename)
with open(file_path) as f:
names = json.load(f)
return names |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_names(self):
"""Get the list of first names. :return: A list of first name entries. """ |
names = self._read_name_file('names.json')
names = self._compute_weights(names)
return names |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_surnames(self):
"""Get the list of surnames. :return: A list of surname entries. """ |
names = self._read_name_file('surnames.json')
names = self._compute_weights(names)
return names |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_random_name(name_list):
"""Get a random name from a given list. The choice of the name is fully random. :param name_list: The list of names from which to pick. :return str: A randomly chosen name. """ |
length = len(name_list)
index = random.randrange(length)
return name_list[index]['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_weighted_random_name(name_list):
"""Get a random name from a given list, according to its frequency. The choice of the name is random, but weighted in proportion to the relative frequency or popularity of each name in the list. If one name is twice as popular as another one, then it is twice as likely to get chosen. :param name_list: The list of names from which to pick. :return str: A randomly chosen name. """ |
total_weight = name_list[-1]['weight_high']
random_weight = random.randrange(total_weight + 1)
left = 0
right = len(name_list) - 1
while left <= right:
index = (left + right) // 2
entry = name_list[index]
if random_weight > entry['weight_high']:
left = index + 1
elif random_weight < entry['weight_low']:
right = index - 1
else:
return entry['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 _format_name(self, name, surname, snake_case=False):
"""Format a first name and a surname into a cohesive string. Note that either name or surname can be empty strings, and formatting will still succeed. :param str name: A first name. :param str surname: A surname. :param bool snake_case: If True, format the name as "snake_case", also stripping diacritics if any. (default: False) :return str: The formatted name. """ |
if not name or not surname:
sep = ''
elif snake_case:
sep = '_'
else:
sep = ' '
if snake_case:
name = self._snakify_name(name)
surname = self._snakify_name(surname)
disp_name = '{}{}{}'.format(name, sep, surname)
return disp_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 _snakify_name(self, name):
"""Snakify a name string. In this context, "to snakify" means to strip a name of all diacritics, convert it to lower case, and replace any spaces inside the name with hyphens. This way the name is made "machine-friendly", and ready to be combined with a second name component into a full "snake_case" name. :param str name: A name to snakify. :return str: A snakified name. """ |
name = self._strip_diacritics(name)
name = name.lower()
name = name.replace(' ', '-')
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 cmp_val_salt_hash(val, salt, str_hash):
""" Given a string, salt, & hash validate the string The salt & val will be concatented as in gen_salt_and hash() & compared to the provided hash. This will only ever work with hashes derived from gen_salt_and_hash() :param val: clear-text string :param salt: string salt :param str_hash: existing hash to compare against :return: boolean """ |
computed_hash = hashlib.sha256(val + salt).hexdigest()
return computed_hash == str_hash |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gen_salt_and_hash(val=None):
""" Generate a salt & hash If no string is provided then a random string will be used to hash & referred to as `val`. The salt will always be randomly generated & the hash will be a sha256 hex value of the `val` & the salt as a concatenated string. It follows the guidance here: crackstation.net/hashing-security.htm#properhashing :param val: str :return: tuple of strings (salt, hash) """ |
if not val:
val = random_str()
str_salt = random_str()
str_hash = hashlib.sha256(val + str_salt).hexdigest()
return str_salt, str_hash |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def str_to_bool(val):
""" Return a boolean if the string value represents one :param val: str :return: bool :raise: ValueError """ |
if isinstance(val, bool):
return val
elif val.lower() == 'true':
return True
elif val.lower() == 'false':
return False
else:
raise ValueError |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def str_to_dt(val):
""" Return a datetime object if the string value represents one Epoch integer or an ISO 8601 compatible string is supported. :param val: str :return: datetime :raise: ValueError """ |
if isinstance(val, dt):
return val
try:
if val.isdigit():
return dt.utcfromtimestamp(float(val))
else:
return dt.strptime(val, '%Y-%m-%dT%H:%M:%S.%f')
except (AttributeError, TypeError):
raise ValueError |
<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_and_write(self, level, correlation_id, error, message, *args, **kwargs):
""" Formats the log message and writes it to the logger destination. :param level: a log level. :param correlation_id: (optional) transaction id to trace execution through call chain. :param error: an error object associated with this message. :param message: a human-readable message to log. :param args: arguments to parameterize the message. :param kwargs: arguments to parameterize the message. """ |
if message != None and len(message) > 0 and len(kwargs) > 0:
message = message.format(*args, **kwargs)
self._write(level, correlation_id, error, message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log(self, level, correlation_id, error, message, *args, **kwargs):
""" Logs a message at specified log level. :param level: a log level. :param correlation_id: (optional) transaction id to trace execution through call chain. :param error: an error object associated with this message. :param message: a human-readable message to log. :param args: arguments to parameterize the message. :param kwargs: arguments to parameterize the message. """ |
self._format_and_write(level, correlation_id, error, message, 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 error(self, correlation_id, error, message, *args, **kwargs):
""" Logs recoverable application error. :param correlation_id: (optional) transaction id to trace execution through call chain. :param error: an error object associated with this message. :param message: a human-readable message to log. :param args: arguments to parameterize the message. :param kwargs: arguments to parameterize the message. """ |
self._format_and_write(LogLevel.Error, correlation_id, error, message, 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 warn(self, correlation_id, message, *args, **kwargs):
""" Logs a warning that may or may not have a negative impact. :param correlation_id: (optional) transaction id to trace execution through call chain. :param message: a human-readable message to log. :param args: arguments to parameterize the message. :param kwargs: arguments to parameterize the message. """ |
self._format_and_write(LogLevel.Warn, correlation_id, None, message, 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 info(self, correlation_id, message, *args, **kwargs):
""" Logs an important information message :param correlation_id: (optional) transaction id to trace execution through call chain. :param message: a human-readable message to log. :param args: arguments to parameterize the message. :param kwargs: arguments to parameterize the message. """ |
self._format_and_write(LogLevel.Info, correlation_id, None, message, 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 debug(self, correlation_id, message, *args, **kwargs):
""" Logs a high-level debug information for troubleshooting. :param correlation_id: (optional) transaction id to trace execution through call chain. :param message: a human-readable message to log. :param args: arguments to parameterize the message. :param kwargs: arguments to parameterize the message. """ |
self._format_and_write(LogLevel.Debug, correlation_id, None, message, 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 trace(self, correlation_id, message, *args, **kwargs):
""" Logs a low-level debug information for troubleshooting. :param correlation_id: (optional) transaction id to trace execution through call chain. :param message: a human-readable message to log. :param args: arguments to parameterize the message. :param kwargs: arguments to parameterize the message. """ |
self._format_and_write(LogLevel.Trace, correlation_id, None, message, 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 check_ipv6(ip_str):
""" Return True if is a valid IP v6 """ |
try:
socket.inet_pton(socket.AF_INET6, ip_str)
except socket.error:
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_ipv4(ip_str):
""" Return True if is a valid IP v4 """ |
try:
socket.inet_pton(socket.AF_INET, ip_str)
except AttributeError:
try:
socket.inet_aton(ip_str)
except socket.error:
return False
return ip_str.count('.') == 3
except socket.error:
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gen_str_to_sign(self, req):
"""Generate string to sign using giving prepared request""" |
url = urlsplit(req.url)
bucket_name = url.netloc.split(".", 1)[0]
logger.debug(req.headers.items())
ucloud_headers = [
(k, v.strip())
for k, v in sorted(req.headers.lower_items())
if k.startswith("x-ucloud-")
]
canonicalized_headers = "\n".join([
"{0}:{1}".format(k, v) for k, v in ucloud_headers
])
canonicalized_resource = "/{0}{1}".format(
bucket_name,
unquote(url.path)
)
str_to_sign = "\n".join([
req.method,
req.headers.get("content-md5", ""),
req.headers.get("content-type", ""),
req.headers.get("date", self._expires),
canonicalized_headers + canonicalized_resource
])
return str_to_sign |
<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_all_headers(self, req):
"""Set content-type, content-md5, date to the request.""" |
url = urlsplit(req.url)
content_type, __ = mimetypes.guess_type(url.path)
if content_type is None:
content_type = self.DEFAULT_TYPE
logger.warn("can not determine mime-type for {0}".format(url.path))
if self._expires is None:
# sign with url, no content-type for url
req.headers.setdefault("content-type", content_type)
if (
req.body is not None
and req.headers.get("content-md5") is None
and self._allow_empty_md5 is False
):
logger.debug("calculating content-md5")
content, content_md5 = utils.cal_content_md5(req.body)
req.body = content
req.headers["content-md5"] = content_md5
logger.debug("new content-md5 is: {0}".format(content_md5))
else:
logger.debug("skip content-md5 calculation")
if self._expires is None:
req.headers.setdefault(
"date",
time.strftime(self.DATE_FMT, time.gmtime())
)
return req |
<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_old_options(cli, image):
""" Returns Dockerfile values for CMD and Entrypoint """ |
return {
'cmd': dockerapi.inspect_config(cli, image, 'Cmd'),
'entrypoint': dockerapi.inspect_config(cli, image, 'Entrypoint'),
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def restore_image_options(cli, image, options):
""" Restores CMD and ENTRYPOINT values of the image This is needed because we force the overwrite of ENTRYPOINT and CMD in the `run_code_in_container` function, to be able to run the code in the container, through /bin/bash. """ |
dockerfile = io.StringIO()
dockerfile.write(u'FROM {image}\nCMD {cmd}'.format(
image=image, cmd=json.dumps(options['cmd'])))
if options['entrypoint']:
dockerfile.write(
'\nENTRYPOINT {}'.format(json.dumps(options['entrypoint'])))
cli.build(tag=image, fileobj=dockerfile) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_code_in_container(cli, image, code, mount, entrypoint):
""" Run `code` in a container, returning its ID """ |
kwargs = {
'image': image,
}
if entrypoint:
kwargs['entrypoint'] = '/bin/bash'
kwargs['command'] = '-c {}'.format(quote(code))
else:
kwargs['command'] = '/bin/bash -c {}'.format(quote(code))
if mount:
binds = []
volumes = []
for m in mount:
part = m.split(':')
if len(part) == 3:
pass
elif len(part) == 2:
part.append('rw')
else:
raise
src, target, mode = part
src = os.path.abspath(os.path.expanduser(src))
binds.append('{}:{}:{}'.format(src, target, mode))
volumes.append(target)
kwargs['host_config'] = cli.create_host_config(binds=binds)
kwargs['volumes'] = volumes
container = cli.create_container(**kwargs)
container_id = container['Id']
cli.start(container=container_id)
return container_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 read(src):
'Event generator from u2 stream.'
parser, buff_agg = Parser(), ''
while True:
buff = parser.read(src)
if not buff: break # EOF
buff_agg += buff
while True:
buff_agg, ev = parser.process(buff_agg)
if ev is None: break
yield ev |
<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_and_check_settings(base_settings, file_name=None, section=None, base_path=None, strategy_type=INIJSONStrategy, disable=None, prompt=None, quiet=None):
"""Merge local settings from file with base settings, then check. Returns a new dict containing the base settings and the loaded settings. Includes: - base settings - settings from extended file(s), if any - settings from file Settings loaded from the specified file will override base settings, then the settings will be checked to ensure that all required local settings have been set. If a file name is passed: if the file exists, local settings will be loaded from it and any missing settings will be appended to it; if the file does not exist, it will be created and all settings will be added to it. If a file name isn't passed: if the ``LOCAL_SETTINGS_FILE_NAME`` environment variable is set, the specified file will be used; otherwise ``{base_path}/local.cfg`` will be used. ``base_path`` is used when ``file_name`` is relative; if it's not passed, it will be set to the current working directory. When ``prompt`` is ``True``, the user will be prompted for missing local settings. By default, the user is prompted only when running on TTY. The ``LOCAL_SETTINGS_CONFIG_PROMPT`` environment variable can be used to set ``prompt``. When ``quiet`` is ``True``, informational messages will not be printed. The ``LOCAL_SETTINGS_CONFIG_QUIET`` environment variable can be used to set ``quiet``. .. note:: When setting flags via environment variables, use a JSON value like 'true', '1', 'false', or '0'. See :meth:`.Loader.load` and :meth:`.Checker.check` for more info. """ |
environ_config = get_config_from_environ()
disable = environ_config['disable'] if disable is None else disable
prompt = environ_config['prompt'] if prompt is None else prompt
quiet = environ_config['quiet'] if quiet is None else quiet
if disable:
return {}
if file_name is None:
file_name = get_file_name()
if ':' in file_name:
package, path = file_name.split(':', 1)
file_name = pkg_resources.resource_filename(package, path)
if not os.path.isabs(file_name):
base_path = base_path or os.getcwd()
file_name = os.path.normpath(os.path.join(base_path, file_name))
try:
loader = Loader(file_name, section, strategy_type=strategy_type)
settings, success = loader.load_and_check(base_settings, prompt)
except KeyboardInterrupt:
# Loading/checking of local settings was aborted with Ctrl-C.
# This isn't an error, but we don't want to continue.
if not quiet:
printer.print_warning('\nAborted loading/checking of local settings')
sys.exit(0)
if loader.section:
file_name = '{loader.file_name}#{loader.section}'.format(loader=loader)
else:
file_name = loader.file_name
if not success:
raise SettingsFileDidNotPassCheck(file_name)
if not quiet:
printer.print_success('Settings loaded successfully from {0}'.format(file_name))
return settings |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_challenge(http_header):
""" apparently keywords Basic and Digest are not being checked anywhere and decisions are being made based on authorization configuration of client, so I guess you better know what you are doing. Here I am requiring one or the other be specified. challenge Basic auth_param challenge Digest auth_param """ |
m = fetch_challenge.wwwauth_header_re.match(http_header)
if m is None:
raise RuntimeError, 'expecting "WWW-Authenticate header [Basic,Digest]"'
d = dict(challenge=m.groups()[0])
m = fetch_challenge.auth_param_re.search(http_header)
while m is not None:
k,v = http_header[m.start():m.end()].split('=')
d[k.lower()] = v[1:-1]
m = fetch_challenge.auth_param_re.search(http_header, m.end())
return 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 open_url(self, url):
""" Open's URL with apiToken in the headers """ |
try:
c = pycurl.Curl()
c.setopt(pycurl.FAILONERROR, True)
c.setopt(pycurl.URL, "%s/api/v0/%s" % (self.url, url))
c.setopt(pycurl.HTTPHEADER, ["User-Agent: %s" % self.userAgent,
"apiToken: %s" % self.apiToken])
b = StringIO.StringIO()
c.setopt(pycurl.WRITEFUNCTION, b.write)
c.setopt(pycurl.FOLLOWLOCATION, 1)
c.setopt(pycurl.MAXREDIRS, 5)
# Persoonlijkrooster only supports SSLv3, not the default SSLv23.
c.setopt(pycurl.SSLVERSION, pycurl.SSLVERSION_SSLv3)
# Verify authenticity of peer's certificate. (0 will not check it)
c.setopt(pycurl.SSL_VERIFYPEER, 1)
# Verify that domain in URL matches to the Common Name Field or
# a Subject Alternate Name field in the certificate.
# (0 will not check it; 1 is an invalid value)
c.setopt(pycurl.SSL_VERIFYHOST, 2)
c.perform()
return b.getvalue()
except pycurl.error, e:
raise MyTimetableError(e) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _loadConfiguration(self):
""" Load module configuration files. :return: <void> """ |
configPath = os.path.join(self.path, "config")
if not os.path.isdir(configPath):
return
config = Config(configPath)
Config.mergeDictionaries(config.getData(), self.application.config) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _loadModels(self):
""" Load module models. :return: <void> """ |
modelsPath = os.path.join(self.path, "model")
if not os.path.isdir(modelsPath):
return
for modelFile in os.listdir(modelsPath):
modelName = modelFile.replace(".py", "")
modelPath = os.path.join(
self.path, "model", modelFile
)
if not os.path.isfile(modelPath):
continue
# importing model
modelSpec = importlib.util.spec_from_file_location(
modelName,
modelPath
)
model = importlib.util.module_from_spec(modelSpec)
modelSpec.loader.exec_module(model)
# initializing model
modelInstance = model.Model(self.application)
self.application.addModel(self.name, modelName, modelInstance) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _loadServices(self):
""" Load module services. :return: <void> """ |
servicesPath = os.path.join(self.path, "service")
if not os.path.isdir(servicesPath):
return
self._scanDirectoryForServices(servicesPath) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _loadService(self, servicePath):
""" Check if an application service can be found at the specified path. If found, instantiate it and add it to the application service pool. :param: <str> service file path :return: <void> """ |
serviceName = ntpath.basename(servicePath).replace(".py", "")
# importing service
serviceSpec = importlib.util.spec_from_file_location(
serviceName,
servicePath
)
service = importlib.util.module_from_spec(serviceSpec)
serviceSpec.loader.exec_module(service)
# checking if there is a service in the file
if hasattr(service, "Service"):
# instantiate the service
serviceInstance = service.Service(self.application)
self.application.addService(
self.name,
serviceName,
serviceInstance
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post(self, request, key):
"""Create new email address that will wait for validation""" |
email = request.POST.get('email')
user_id = request.POST.get('user')
if not email:
return http.HttpResponseBadRequest()
try:
EmailAddressValidation.objects.create(address=email,
user_id=user_id)
except IntegrityError:
# 409 Conflict
# duplicated entries
# email exist and it's waiting for validation
return http.HttpResponse(status=409)
return http.HttpResponse(status=201) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def multi_iter(iterable, count=2):
"""Return `count` independent, thread-safe iterators for `iterable`""" |
# no need to special-case re-usable, container-like iterables
if not isinstance(
iterable,
(
list, tuple, set,
FutureChainResults,
collections.Sequence, collections.Set, collections.Mapping, collections.MappingView
)):
iterable = SafeTee(iterable, n=count)
return (iter(iterable) for _ in range(count)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def realise(self):
""" Realise the future if possible If the future has not been realised yet, do so in the current thread. This will block execution until the future is realised. Otherwise, do not block but return whether the result is already available. This will not return the result nor propagate any exceptions of the future itself. :return: whether the future has been realised :rtype: bool """ |
if self._mutex.acquire(False):
# realise the future in this thread
try:
if self._result is not None:
return True
call, args, kwargs = self._instruction
try:
result = call(*args, **kwargs)
except BaseException as err:
self._result = None, err
else:
self._result = result, None
return True
finally:
self._mutex.release()
else:
# indicate whether the executing thread is done
return self._result is not 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 result(self):
""" The result from realising the future If the result is not available, block until done. :return: result of the future :raises: any exception encountered during realising the future """ |
if self._result is None:
self.await_result()
chunks, exception = self._result
if exception is None:
return chunks
raise exception |
<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_warcinfo(self):
'''
Returns WARCINFO record from the archieve as a single string including
WARC header. Expects the record to be in the beginning of the archieve,
otherwise it will be not found.
'''
if self.searched_for_warcinfo:
return self.warcinfo
prev_line = None
in_warcinfo_record = False
self.searched_for_warcinfo = True
for line in self.file_object:
if not in_warcinfo_record:
if line[:11] == b'WARC-Type: ':
if line[:19] == b'WARC-Type: warcinfo':
in_warcinfo_record = True
warcinfo_lines = [prev_line, line]
else:
self.warcinfo = None
break
else:
if line[0:1] == self.w_letter and self.warc_header_re.match(line):
self.warcinfo = b''.join(warcinfo_lines)
break
warcinfo_lines.append(line)
prev_line = line
self.file_object.seek(0)
return self.warcinfo |
<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_state(self):
''' Sets the initial state of the state machine. '''
self.in_warc_response = False
self.in_http_response = False
self.in_payload = 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 _keys_from_label(self, label):
'''Convert a label into a kvl key.
'''
k1 = (label.content_id1, label.content_id2,
label.annotator_id, time_complement(label.epoch_ticks))
k2 = (label.content_id2, label.content_id1,
label.annotator_id, time_complement(label.epoch_ticks))
return k1, k2 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _value_from_label(self, label):
'''Convert a label into a kvl value.
'''
unser_val = (label.rel_strength.value, label.meta)
return cbor.dumps(unser_val) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get(self, cid1, cid2, annotator_id):
'''Retrieve a relation label from the store.
'''
t = (cid1, cid2, annotator_id)
for k, v in self.kvl.scan(self.TABLE, (t, t)):
return self._label_from_kvlayer(k, 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 get_related(self, content_id, min_strength=None):
'''Get positive relation labels for ``cid``.
If ``min_strength`` is set, will restrict results to labels
with a ``rel_strength`` greater or equal to the provided
``RelationStrength`` value. Note: ``min_strength`` should be of
type ``RelationStrength``.
'''
def is_related(label):
if min_strength is not None:
return label.rel_strength >= min_strength
else:
return label.rel_strength.is_positive
labels = self.everything(content_id=content_id)
return ifilter(is_related, labels) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_related_ids(self, content_id, min_strength=None):
'''Get identifiers for related identifiers.
'''
related_labels = self.get_related(content_id,
min_strength=min_strength)
related_idents = set()
for label in related_labels:
related_idents.add(label.other(content_id))
return list(related_idents) |
<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_relationships_for_idents(self, cid, idents):
'''Get relationships between ``idents`` and a ``cid``.
Returns a dictionary mapping the identifiers in ``idents``
to either None, if no relationship label is found between
the identifier and ``cid``, or a RelationshipType classifying
the strength of the relationship between the identifier and
``cid``.
'''
keys = [(cid, ident,) for ident in idents]
key_ranges = zip(keys, keys)
mapping = {}
for k, v in self.kvl.scan(self.TABLE, *key_ranges):
label = self._label_from_kvlayer(k, v)
ident = label.other(cid)
rel_strength = label.rel_strength
mapping[ident] = label.rel_strength
return mapping |
<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_field(param, fields):
""" Ensure the sortable field exists on the model """ |
if param.field not in fields:
raise InvalidQueryParams(**{
'detail': 'The sort query param value of "%s" is '
'invalid. That field does not exist on the '
'resource being requested.' % param.raw_field,
'links': LINK,
'parameter': PARAM,
}) |
<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_no_rels(param, rels):
""" Ensure the sortable field is not on a relationship """ |
if param.field in rels:
raise InvalidQueryParams(**{
'detail': 'The sort query param value of "%s" is not '
'supported. Sorting on relationships is not '
'currently supported' % param.raw_field,
'links': LINK,
'parameter': PARAM,
}) |
<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(req, model):
""" Determine the sorting preference by query parameter Return an array of Sortable objects. """ |
rels = model.relationships
fields = model.all_fields
params = req.get_param_as_list('sort') or [goldman.config.SORT]
params = [Sortable(param.lower()) for param in params]
for param in params:
_validate_no_rels(param, rels)
_validate_field(param, fields)
return 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 _get_site(self, url, headers, cookies, timeout, driver_args, driver_kwargs):
""" Try and return page content in the requested format using requests """ |
try:
# Headers and cookies are combined to the ones stored in the requests session
# Ones passed in here will override the ones in the session if they are the same key
response = self.driver.get(url,
*driver_args,
headers=headers,
cookies=cookies,
timeout=timeout,
**driver_kwargs)
# Set data to access from script
self.status_code = response.status_code
self.url = response.url
self.response = response
if response.status_code == requests.codes.ok:
# Return the correct format
return response.text
response.raise_for_status()
except Exception as e:
raise e.with_traceback(sys.exc_info()[2]) |
<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_controller(self, addr, port):
""" Get an uid for your controller. :param addr: Address of the controller :param port: Port of the controller :type addr: str :type port: int :return: Unique id of the controller :rtype: str """ |
for uid, controller in self.controllers.items():
if controller[0] == addr:
# duplicate address. sending the uid again
#print('/uid/{} => {}:{}'.format(uid, addr, port))
self.sock.sendto('/uid/{}'.format(uid).encode('utf-8'), (addr, port))
return False
# get an uid and add the controller to the game
uid = str(uuid4())
self.controllers[uid] = [addr, port, '00000000000000', time.time()]
# tell the controller about it
#print('/uid/{} => {}:{}'.format(uid, addr, port))
self.sock.sendto('/uid/{}'.format(uid).encode('utf-8'), (addr, port))
# create event for pymlgame
e = Event(uid, E_NEWCTLR)
self.queue.put_nowait(e)
return uid |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _del_controller(self, uid):
""" Remove controller from internal list and tell the game. :param uid: Unique id of the controller :type uid: str """ |
try:
self.controllers.pop(uid)
e = Event(uid, E_DISCONNECT)
self.queue.put_nowait(e)
except KeyError:
# There is no such controller, ignore the command
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ping(self, uid, addr, port):
""" Just say hello so that pymlgame knows that your controller is still alive. Unused controllers will be deleted after a while. This function is also used to update the address and port of the controller if it has changed. :param uid: Unique id of the controller :param addr: Address of the controller :param port: Port that the controller listens on :type uid: str :type addr: str :type port: int """ |
try:
self.controllers[uid][0] = addr
self.controllers[uid][1] = port
self.controllers[uid][3] = time.time()
e = Event(uid, E_PING)
self.queue.put_nowait(e)
except KeyError:
# There is no such controller, ignore the command
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _update_states(self, uid, states):
""" Got states of all buttons from a controller. Now check if something changed and create events if neccesary. :param uid: Unique id of the controller :param states: Buttons states :type uid: str :type states: str """ |
#TODO: use try and catch all exceptions
# test if uid exists
if self.controllers[uid]:
# test if states have correct lenght
if len(states) == 14:
old_states = self.controllers[uid][2]
if old_states != states:
for key in range(14):
if int(old_states[key]) > int(states[key]):
e = Event(uid, E_KEYUP, key)
self.queue.put_nowait(e)
elif int(old_states[key]) < int(states[key]):
e = Event(uid, E_KEYDOWN, key)
self.queue.put_nowait(e)
self.controllers[uid][2] = states
self.controllers[uid][3] = time.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 _got_message(self, uid, text):
""" The controller has send us a message. :param uid: Unique id of the controller :param text: Text to display :type uid: str :type text: str """ |
#TODO: use try
e = Event(uid, E_MESSAGE, text)
self.queue.put_nowait(e)
self.controllers[uid][2] = time.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 send(self, uid, event, payload=None):
""" Send an event to a connected controller. Use pymlgame event type and correct payload. To send a message to the controller use pymlgame.E_MESSAGE event and a string as payload. :param uid: Unique id of the controller :param event: Event type :param payload: Payload of the event :type uid: str :type event: Event :type payload: str :return: Number of bytes send or False :rtype: int """ |
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
if uid in self.controllers.keys():
addr = self.controllers[uid][0]
port = self.controllers[uid][1]
if event == E_MESSAGE:
#print('/message/{} => {}:{}'.format(payload, addr, port))
return sock.sendto('/message/{}'.format(payload).encode('utf-8'), (addr, port))
elif event == E_RUMBLE:
#print('/rumble/{} => {}:{}'.format(payload, addr, port))
return sock.sendto('/rumble/{}'.format(payload).encode('utf-8'), (addr, port))
else:
pass
else:
pass
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 run(self):
""" Listen for controllers. """ |
while True:
data, sender = self.sock.recvfrom(1024)
addr = sender[0]
msg = data.decode('utf-8')
if msg.startswith('/controller/'):
try:
uid = msg.split('/')[2]
if uid == 'new':
port = int(msg.split('/')[3])
self._new_controller(addr, port)
else:
cmd = msg.split('/')[3]
if cmd == 'ping':
port = msg.split('/')[3]
self._ping(uid, addr, port)
elif cmd == 'kthxbye':
self._del_controller(uid)
elif cmd == 'states':
states = msg.split('/')[4]
self._update_states(uid, states)
elif cmd == 'text':
# /controller/<uid>/text/<text>
text = msg[12 + len(uid) + 6:]
self._got_message(uid, text)
except IndexError or KeyError:
pass
else:
pass
# find unused controllers and delete them
ctlrs = self.controllers.items()
for uid, state in ctlrs:
if state[3] < time.time() - 60:
self.controllers.pop(uid) |
<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_obj_frm_str(obj_str, **kwargs):
""" Returns a python object from a python object string args: obj_str: python object path expamle "rdfframework.connections.ConnManager[{param1}]" kwargs: * kwargs used to format the 'obj_str' """ |
obj_str = obj_str.format(**kwargs)
args = []
kwargs = {}
params = []
# parse the call portion of the string
if "(" in obj_str:
call_args = obj_str[obj_str.find("("):]
obj_str = obj_str[:obj_str.find("(")]
call_args = call_args[1:-1]
if call_args:
call_args = call_args.split(",")
else:
call_args = []
call_args = [arg.strip() for arg in call_args]
for arg in call_args:
if "=" in arg:
parts = arg.split("=")
kwargs[parts[0]] = parts[1]
else:
args.append(arg)
# parse a the __getitem__ portion of the string
if "[" in obj_str:
params = obj_str[obj_str.find("["):]
obj_str = obj_str[:obj_str.find("[")]
params = [part.replace("[", "").replace("]", "")
for part in params.split("][")]
obj = pydoc.locate(obj_str)
if params:
for part in params:
obj = get_attr(obj, part)
if args or kwargs:
if kwargs:
obj = obj.__call__(*args, **kwargs)
else:
obj = obj.__call__(*args)
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pyfile_path(path):
""" converst a file path argment to the is path within the framework args: path: filepath to the python file """ |
if "/" in path:
parts = path.split("/")
join_term = "/"
elif "\\" in path:
parts =path.split("\\")
join_term = "\\"
parts.reverse()
base = parts[:parts.index('rdfframework')]
base.reverse()
return join_term.join(base) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def nz(value, none_value, strict=True):
''' This function is named after an old VBA function. It returns a default
value if the passed in value is None. If strict is False it will
treat an empty string as None as well.
example:
x = None
nz(x,"hello")
--> "hello"
nz(x,"")
--> ""
y = ""
nz(y,"hello")
--> ""
nz(y,"hello", False)
--> "hello" '''
if not DEBUG:
debug = False
else:
debug = False
if debug: print("START nz frameworkutilities.py ----------------------\n")
if value is None and strict:
return_val = none_value
elif strict and value is not None:
return_val = value
elif not strict and not is_not_null(value):
return_val = none_value
else:
return_val = value
if debug: print("value: %s | none_value: %s | return_val: %s" %
(value, none_value, return_val))
if debug: print("END nz frameworkutilities.py ----------------------\n")
return return_val |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def make_set(value):
''' Takes a value and turns it into a set
!!!! This is important because set(string) will parse a string to
individual characters vs. adding the string as an element of
the set i.e.
x = 'setvalue'
set(x) = {'t', 'a', 'e', 'v', 'u', 's', 'l'}
make_set(x) = {'setvalue'}
or use set([x,]) by adding string as first item in list.
'''
if isinstance(value, list):
value = set(value)
elif not isinstance(value, set):
value = set([value,])
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_triple(sub, pred, obj):
"""Takes a subject predicate and object and joins them with a space in between Args: sub -- Subject pred -- Predicate obj -- Object Returns str """ |
return "{s} {p} {o} .".format(s=sub, p=pred, o=obj) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def remove_null(obj):
''' reads through a list or set and strips any null values'''
if isinstance(obj, set):
try:
obj.remove(None)
except:
pass
elif isinstance(obj, list):
for item in obj:
if not is_not_null(item):
obj.remove(item)
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def delete_key_pattern(obj, regx_pattern):
''' takes a dictionary object and a regular expression pattern and removes
all keys that match the pattern.
args:
obj: dictionay object to search trhough
regx_pattern: string without beginning and ending / '''
if isinstance(obj, list):
_return_list = []
for item in obj:
if isinstance(item, list):
_return_list.append(delete_key_pattern(item, regx_pattern))
elif isinstance(item, set):
_return_list.append(list(item))
elif isinstance(item, dict):
_return_list.append(delete_key_pattern(item, regx_pattern))
else:
try:
json.dumps(item)
_return_list.append(item)
except:
_return_list.append(str(type(item)))
return _return_list
elif isinstance(obj, set):
return list(obj)
elif isinstance(obj, dict):
_return_obj = {}
for key, item in obj.items():
if not re.match(regx_pattern, key):
if isinstance(item, list):
_return_obj[key] = delete_key_pattern(item, regx_pattern)
elif isinstance(item, set):
_return_obj[key] = list(item)
elif isinstance(item, dict):
_return_obj[key] = delete_key_pattern(item, regx_pattern)
else:
try:
json.dumps(item)
_return_obj[key] = item
except:
_return_obj[key] = str(type(item))
return _return_obj
else:
try:
json.dumps(obj)
return obj
except:
return str(type(obj)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_dict_key(data, key):
''' will serach a mulitdemensional dictionary for a key name and return a
value list of matching results '''
if isinstance(data, Mapping):
if key in data:
yield data[key]
for key_data in data.values():
for found in get_dict_key(key_data, key):
yield found |
<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_attr(item, name, default=None):
''' similar to getattr and get but will test for class or dict '''
try:
val = item[name]
except (KeyError, TypeError):
try:
val = getattr(item, name)
except AttributeError:
val = default
return val |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get2(item, key, if_none=None, strict=True):
''' similar to dict.get functionality but None value will return then
if_none value
args:
item: dictionary to search
key: the dictionary key
if_none: the value to return if None is passed in
strict: if False an empty string is treated as None'''
if not strict and item.get(key) == "":
return if_none
elif item.get(key) is None:
return if_none
else:
return item.get(key) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def initialized(func):
""" decorator for testing if a class has been initialized prior to calling any attribute """ |
def wrapper(self, *args, **kwargs):
""" internal wrapper function """
if not self.__is_initialized__:
return EmptyDot()
return func(self, *args, **kwargs)
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find(self, value):
""" returns a dictionary of items based on the a lowercase search args: value: the value to search by """ |
value = str(value).lower()
rtn_dict = RegistryDictionary()
for key, item in self.items():
if value in key.lower():
rtn_dict[key] = item
return rtn_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, prop):
""" get the value off the passed in dot notation args: prop: a string of the property to retreive "a.b.c" ~ dictionary['a']['b']['c'] """ |
prop_parts = prop.split(".")
val = None
for part in prop_parts:
if val is None:
val = self.obj.get(part)
else:
val = val.get(part)
return val |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set(self, prop, value):
""" sets the dot notated property to the passed in value args: prop: a string of the property to retreive "a.b.c" ~ dictionary['a']['b']['c'] value: the value to set the prop object """ |
prop_parts = prop.split(".")
if self.copy_dict:
new_dict = copy.deepcopy(self.obj)
else:
new_dict = self.obj
pointer = None
parts_length = len(prop_parts) - 1
for i, part in enumerate(prop_parts):
if pointer is None and i == parts_length:
new_dict[part] = value
elif pointer is None:
pointer = new_dict.get(part)
elif i == parts_length:
pointer[part] = value
else:
pointer = pointer.get(part)
return new_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dict(self):
""" converts the class to a dictionary object """ |
return_obj = {}
for attr in dir(self):
if not attr.startswith('__') and attr not in self.__reserved:
if isinstance(getattr(self, attr), list):
return_val = []
for item in getattr(self, attr):
if isinstance(item, DictClass):
return_val.append(dict(item))
else:
return_val.append(item)
elif isinstance(getattr(self, attr), dict):
return_val = {}
for key, item in getattr(self, attr).items():
if isinstance(item, DictClass):
return_val[key] = item.dict()
else:
return_val[key] = item
elif isinstance(getattr(self, attr), DictClass):
return_val = getattr(self, attr).dict()
else:
return_val = getattr(self, attr)
return_obj[attr] = return_val
return return_obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_anchor_href(markup):
""" Given HTML markup, return a list of hrefs for each anchor tag. """ |
soup = BeautifulSoup(markup, 'lxml')
return ['%s' % link.get('href') for link in soup.find_all('a')] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_anchor_contents(markup):
""" Given HTML markup, return a list of href inner html for each anchor tag. """ |
soup = BeautifulSoup(markup, 'lxml')
return ['%s' % link.contents[0] for link in soup.find_all('a')] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def names_from_exp(exp):
"Return a list of AttrX and NameX from the expression."
def match(exp):
return isinstance(exp, (sqparse2.NameX, sqparse2.AttrX))
paths = treepath.sub_slots(exp, match, match=True, recurse_into_matches=False)
return [exp[path] for path in paths] |
<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_tarball(self, tarball, package):
"""Add a tarball, possibly creating the directory if needed.""" |
if tarball is None:
logger.error(
"No tarball found for %s: probably a renamed project?",
package)
return
target_dir = os.path.join(self.root_directory, package)
if not os.path.exists(target_dir):
os.mkdir(target_dir)
logger.info("Created %s", target_dir)
logger.info("Copying tarball to %s", target_dir)
shutil.copy(tarball, target_dir) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ls(self):
""" List the objects in the current namespace, in alphabetical order. """ |
width = max([len(x) for x in self.namespace.keys()])
for key, value in sorted(self.namespace.items()):
if key == "_":
continue
info = ""
if (isinstance(value, dict) or
isinstance(value, list) or key == "services"):
info = "data"
elif type(value).__name__ == "module":
info = value.__name__
elif type(value).__name__ == "function":
info = "%s.%s" % (value.__module__, value.__name__)
elif type(value).__name__ == "instance":
info = "%s.%s" % (value.__module__, value.__class__.__name__)
else:
info = "%s.%s.%s" % (
value.im_class.__module__, value.im_class.__name__, key)
print "\t%s - %s" % (key.ljust(width), info) |
<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_unicode(text, charset=None):
"""Convert input to an `unicode` object. For a `str` object, we'll first try to decode the bytes using the given `charset` encoding (or UTF-8 if none is specified), then we fall back to the latin1 encoding which might be correct or not, but at least preserves the original byte sequence by mapping each byte to the corresponding unicode code point in the range U+0000 to U+00FF. For anything else, a simple `unicode()` conversion is attempted, with special care taken with `Exception` objects. """ |
if isinstance(text, str):
try:
return unicode(text, charset or 'utf-8')
except UnicodeDecodeError:
return unicode(text, 'latin1')
elif isinstance(text, Exception):
if os.name == 'nt' and \
isinstance(text, (OSError, IOError)): # pragma: no cover
# the exception might have a localized error string encoded with
# ANSI codepage if OSError and IOError on Windows
try:
return unicode(str(text), 'mbcs')
except UnicodeError:
pass
# two possibilities for storing unicode strings in exception data:
try:
# custom __str__ method on the exception (e.g. PermissionError)
return unicode(text)
except UnicodeError:
# unicode arguments given to the exception (e.g. parse_date)
return ' '.join([to_unicode(arg) for arg in text.args])
return unicode(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 exception_to_unicode(e, traceback=False):
"""Convert an `Exception` to an `unicode` object. In addition to `to_unicode`, this representation of the exception also contains the class name and optionally the traceback. """ |
message = '%s: %s' % (e.__class__.__name__, to_unicode(e))
if traceback:
from docido_sdk.toolbox import get_last_traceback
traceback_only = get_last_traceback().split('\n')[:-2]
message = '\n%s\n%s' % (to_unicode('\n'.join(traceback_only)), message)
return message |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def levenshtein(s, t):
""" Compute the Levenshtein distance between 2 strings, which is the minimum number of operations required to perform on a string to get another one. code taken from https://en.wikibooks.org :param basestring s: :param basestring t: :rtype: int """ |
''' From Wikipedia article; Iterative with two matrix rows. '''
if s == t:
return 0
elif len(s) == 0:
return len(t)
elif len(t) == 0:
return len(s)
v0 = [None] * (len(t) + 1)
v1 = [None] * (len(t) + 1)
for i in range(len(v0)):
v0[i] = i
for i in range(len(s)):
v1[0] = i + 1
for j in range(len(t)):
cost = 0 if s[i] == t[j] else 1
v1[j + 1] = min(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost)
for j in range(len(v0)):
v0[j] = v1[j]
return v1[len(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 do_help(self, line):
"""Displays help information.""" |
print ""
print "Perfdump CLI provides a handful of simple ways to query your"
print "performance data."
print ""
print "The simplest queries are of the form:"
print ""
print "\t[slowest|fastest] [tests|setups]"
print ""
print "For example:"
print ""
print "\tperfdump > slowest tests"
print ""
print "Prints the slowest 10 tests"
print ""
print "Additional grouping of results can be request."
print ""
print "\tperfdump > slowest tests groupby file"
print ""
print "Grouping options include:"
print ""
print "\tfile | module | class | function"
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 get_allposts(self):
''' Return all posts in blog sorted by date
'''
result = self.client.posts(self.blog, offset = 0, limit = 1)
try:
total_posts = result['total_posts']
except:
raise phasetumblr_errors.TumblrBlogException(result['meta']['msg'])
delta = (total_posts / 10) + 1
all_posts = []
posts_ids = []
for j in range(delta):
start = j * 10
end = (j + 1) * 10
posts = self.client.posts(self.blog, offset = start, limit = end)['posts']
if not len(posts):
break
for i in posts:
if i['id'] in posts_ids:
continue
description = split_body(i['body'])
body = split_body(i['body'], 1)
post = {}
post['title'] = i['title']
post['link'] = i['post_url']
post['date'] = datetime.strptime(i['date'], '%Y-%m-%d %H:%M:%S %Z')
post['tags'] = i['tags']
post['id'] = i['id']
post['body'] = body
post['description'] = description
all_posts.append(post)
posts_ids.append(i['id'])
newlist = sorted(all_posts, key=lambda k: k['date'])
return newlist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def n_to_pf(L, n, R):
"""Returns the packing fraction for a number of non-intersecting spheres. Parameters L: float array, shape (d,) System lengths. n: integer Number of spheres. R: float Sphere radius. Returns ------- pf: float Fraction of space occupied by the spheres. """ |
dim = L.shape[0]
return (n * sphere_volume(R=R, n=dim)) / np.product(L) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pf_to_n(L, pf, R):
"""Returns the number of non-intersecting spheres required to achieve as close to a given packing fraction as possible, along with the actual achieved packing fraction. for a number of non-intersecting spheres. Parameters L: float array, shape (d,) System lengths. pf: float Fraction of space to be occupied by the spheres. R: float Sphere radius. Returns ------- n: integer Number of spheres required to achieve a packing fraction `pf_actual` pf_actual: Fraction of space occupied by `n` spheres. This is the closest possible fraction achievable to `pf`. """ |
dim = L.shape[0]
n = int(round(pf * np.product(L) / sphere_volume(R, dim)))
pf_actual = n_to_pf(L, n, R)
return n, pf_actual |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pack_simple(R, L, pf=None, n=None, rng=None, periodic=False):
"""Pack a number of non-intersecting spheres into a system. Can specify packing by number of spheres or packing fraction. This implementation uses a naive uniform distribution of spheres, and the Tabula Rasa rule (start from scratch if an intersection occurs). This is likely to be very slow for high packing fractions Parameters R: float Sphere radius. L: float array, shape (d,) System lengths. pf: float or None Packing fraction n: integer or None Number of spheres. rng: RandomState or None Random number generator. If None, use inbuilt numpy state. periodic: bool Whether or not the system is periodic. Returns ------- r: float array, shape (n, d) Coordinates of the centres of the spheres for a valid configuration. R_actual: float Actual sphere radius used in the packing. In this implementation this will always be equal to `R`; it is returned only to provide a uniform interface with the Metropolis-Hastings implementation. """ |
if rng is None:
rng = np.random
if pf is not None:
if pf == 0.0:
return np.array([]), R
# If packing fraction is specified, find required number of spheres
# and the actual packing fraction this will produce
n, pf_actual = pf_to_n(L, pf, R)
elif n is not None:
if n == 0:
return np.array([]), R
if periodic:
return _pack_simple_periodic(R, L, n, rng)
else:
return _pack_simple(R, L, n, rng) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pack(R, L, pf=None, n=None, rng=None, periodic=False, beta_max=1e4, dL_max=0.02, dr_max=0.02):
"""Pack a number of non-intersecting spheres into a periodic system. Can specify packing by number of spheres or packing fraction. This implementation uses the Metropolis-Hastings algorithm for an NPT system. Parameters R: float Sphere radius. L: float array, shape (d,) System lengths. pf: float or None Packing fraction n: integer or None Number of spheres. rng: RandomState or None Random number generator. If None, use inbuilt numpy state. periodic: bool Whether or not the system is periodic. Metropolis-Hastings parameters Playing with these parameters may improve packing speed. beta_max: float, greater than zero. Inverse temperature which controls how little noiseis in the system. dL_max: float, 0 < dL_max < 1 Maximum fraction by which to perturb the system size. dr_max: float, 0 < dr_max < 1 Maximum system fraction by which to perturb sphere positions. Returns ------- r: float array, shape (n, d) Coordinates of the centres of the spheres for a valid configuration. R_actual: float Actual sphere radius used in the packing. """ |
if pf is not None:
if pf == 0.0:
return np.array([]), R
# If packing fraction is specified, find required number of spheres
# and the actual packing fraction this will produce
n, pf_actual = pf_to_n(L, pf, R)
elif n is not None:
if n == 0:
return np.array([]), R
# If n is specified, find packing fraction
pf_actual = n_to_pf(L, n, R)
# Calculate an initial packing fraction and system size
# Start at at most 0.5%; lower if the desired packing fraction is very low
pf_initial = min(0.005, pf_actual / 2.0)
# Find system size that will create this packing fraction
dim = L.shape[0]
increase_initial_ratio = (pf_actual / pf_initial) ** (1.0 / dim)
L_0 = L * increase_initial_ratio
# Pack naively into this system
r_0, R = pack_simple(R, L_0, n=n, rng=rng, periodic=periodic)
mg = metro_rcp_factory(periodic, r_0, L_0, R, dr_max, dL_max, rng=rng)
print('Initial packing done, Initial packing: {:g}'.format(mg.pf))
t = 0
while mg.pf < pf_actual:
t += 1
beta = beta_max * mg.pf
mg.iterate(beta)
if not t % every:
print('Packing: {:g}%'.format(100.0 * mg.pf))
print('Final packing: {:g}%'.format(100.0 * mg.pf))
return mg.r, mg.R |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def relpath_for(self, path):
"""Find the relative path from here from the parent_dir""" |
if self.parent_dir in (".", ""):
return path
if path == self.parent_dir:
return ""
dirname = os.path.dirname(path) or "."
basename = os.path.basename(path)
cached = self.relpath_cache.get(dirname, empty)
if cached is empty:
cached = self.relpath_cache[dirname] = os.path.relpath(dirname, self.parent_dir)
return os.path.join(cached, basename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find(self):
""" Find all the files we want to find commit times for, and any extra files under symlinks. Then find the commit times for those files and return a dictionary of {relative_path: commit_time_as_epoch} """ |
mtimes = {}
git = Repo(self.root_folder)
all_files = git.all_files()
use_files = set(self.find_files_for_use(all_files))
# the git index won't find the files under a symlink :(
# And we include files under a symlink as seperate copies of the files
# So we still want to generate modified times for those files
extras = set(self.extra_symlinked_files(use_files))
# Combine use_files and extras
use_files.update(extras)
# Tell the user something
if not self.silent:
log.info("Finding modified times for %s/%s git controlled files in %s", len(use_files), len(all_files), self.root_folder)
# Finally get the dates from git!
return self.commit_times_for(git, use_files) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def commit_times_for(self, git, use_files):
""" Return commit times for the use_files specified. We will use a cache of commit times if self.with_cache is Truthy. Finally, we yield (relpath: epoch) pairs where path is relative to self.parent_dir and epoch is the commit time in UTC for that path. """ |
# Use real_relpath if it exists (SymlinkdPath) and default to just the path
# This is because we _want_ to compare the commits to the _real paths_
# As git only cares about the symlink itself, rather than files under it
# We also want to make sure that the symlink targets are included in use_files
# If they've been excluded by the filters
use_files_paths = set([getattr(p, "real_relpath", p.path) for p in use_files if p.relpath])
# Find us the first commit to consider
first_commit = str(git.first_commit)
# Try and get our cached commit times
# If we get a commit then it means we have a match for this parent/sorted_relpaths
commit_times = {}
cached_commit, cached_commit_times = None, {}
if self.with_cache:
sorted_relpaths = sorted([p.relpath for p in use_files])
cached_commit, cached_commit_times = get_cached_commit_times(self.root_folder, self.parent_dir, sorted_relpaths)
if cached_commit == first_commit:
commit_times = cached_commit_times
# If we couldn't find cached commit times, we have to do some work
if not commit_times:
for commit_id, commit_time, different_paths in git.file_commit_times(use_files_paths, debug=self.debug):
for path in different_paths:
commit_times[path] = commit_time
if self.with_cache:
set_cached_commit_times(self.root_folder, self.parent_dir, first_commit, commit_times, sorted_relpaths)
# Finally, yield the (relpath, commit_time) for all the files we care about.
for key in use_files:
if key.relpath:
path = getattr(key, "real_relpath", key.path)
relpath = getattr(key, "real_relpath", key.relpath)
if path in commit_times:
yield key.relpath, commit_times[path]
else:
log.warning("Couldn't find commit time for {0}".format(relpath)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extra_symlinked_files(self, potential_symlinks):
""" Find any symlinkd folders and yield SymlinkdPath objects for each file that is found under the symlink. """ |
for key in list(potential_symlinks):
location = os.path.join(self.root_folder, key.path)
real_location = os.path.realpath(location)
if os.path.islink(location) and os.path.isdir(real_location):
for root, dirs, files in os.walk(real_location, followlinks=True):
for name in files:
# So this is joining the name of the symlink
# With the name of the file, relative to the real location of the symlink
full_path = os.path.join(root, name)
rel_location = os.path.relpath(full_path, real_location)
symlinkd_path = os.path.join(key.path, rel_location)
# We then get that relative to the parent dir
dir_part = os.path.relpath(root, real_location)
symlinkd_relpath = os.path.normpath(os.path.join(key.relpath, dir_part, name))
# And we need the original file location so we can get a commit time for the symlinkd path
real_path = os.path.realpath(full_path)
real_root_folder = os.path.realpath(self.root_folder)
real_relpath = os.path.relpath(real_path, real_root_folder)
# So that's path relative to root_folder, path relative to parent_folder
# and path relative to root for the target
yield SymlinkdPath(symlinkd_path, symlinkd_relpath, real_relpath) |
<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_files_for_use(self, all_files):
""" Given a list of all the files to consider, only yield Path objects for those we care about, given our filters """ |
for path in all_files:
# Find the path relative to the parent dir
relpath = self.relpath_for(path)
# Don't care about the ./
if relpath.startswith("./"):
relpath = relpath[2:]
# Only care about paths that aren't filtered
if not self.is_filtered(relpath):
yield Path(path, relpath) |
<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_filtered(self, relpath):
"""Say whether this relpath is filtered out""" |
# Only include files under the parent_dir
if relpath.startswith("../"):
return True
# Ignore files that we don't want timestamps from
if self.timestamps_for is not None and type(self.timestamps_for) is list:
match = False
for line in self.timestamps_for:
if fnmatch.fnmatch(relpath, line):
match = True
break
if not match:
return True
# Matched is true by default if
# * Have exclude
# * No exclude and no include
matched = self.exclude or not any([self.exclude, self.include])
# Anything not matching exclude gets included
if self.exclude:
for line in self.exclude:
if fnmatch.fnmatch(relpath, line):
matched = False
# Anything matching include gets included
if self.include:
for line in self.include:
if fnmatch.fnmatch(relpath, line):
matched = True
break
return not matched |
<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_args_and_defaults(args, defaults):
"""Return a list of 2-tuples - the argument name and its default value or a special value that indicates there is no default value. Args: args: list of argument name defaults: tuple of default values """ |
defaults = defaults or []
args_and_defaults = [(argument, default) for (argument, default)
in zip_longest(args[::-1], defaults[::-1],
fillvalue=NoDefault)]
return args_and_defaults[::-1] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _prepare_doc(func, args, delimiter_chars):
"""From the function docstring get the arg parse description and arguments help message. If there is no docstring simple description and help message are created. Args: func: the function that needs argument parsing args: name of the function arguments delimiter_chars: characters used to separate the parameters from their help message in the docstring Returns: A tuple containing the description to be used in the argument parser and a dict indexed on the callable argument name and their associated help message """ |
_LOG.debug("Preparing doc for '%s'", func.__name__)
if not func.__doc__:
return _get_default_help_message(func, args)
description = []
args_help = {}
fill_description = True
arg_name = None
arg_doc_regex = re.compile("\b*(?P<arg_name>\w+)\s*%s\s*(?P<help_msg>.+)" %
delimiter_chars)
for line in func.__doc__.splitlines():
line = line.strip()
if line and fill_description:
description.append(line)
elif line:
arg_match = arg_doc_regex.match(line)
try:
arg_name = arg_match.groupdict()["arg_name"].strip()
args_help[arg_name] = arg_match.groupdict()["help_msg"].strip()
except AttributeError:
# The line didn't match the pattern we've hit a
# multiline argument docstring so we add it to the
# previous argument help message
if arg_name is not None:
args_help[arg_name] = " ".join([args_help[arg_name], line])
else:
# The first empty line we encountered means we are done with
# the description. The first empty line we encounter after
# filling the argument help means we are done with argument
# parsing.
if not fill_description and args_help:
break
fill_description = False
return _get_default_help_message(func, args, " ".join(description),
args_help) |
<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_help_message(func, args, description=None, args_help=None):
"""Create a default description for the parser and help message for the agurments if they are missing. Args: func: the method we are creating a parser for args: the argument names of the method description: a potentially existing description created from the function docstring args_help: a dict {arg_name: help} with potentially missing arguments Returns: a tuple (arg_parse_description, complete_args_help) """ |
if description is None:
description = "Argument parsing for %s" % func.__name__
args_help = args_help or {}
# If an argument is missing a help message we create a simple one
for argument in [arg_name for arg_name in args
if arg_name not in args_help]:
args_help[argument] = "Help message for %s" % argument
return (description, args_help) |
<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_arg_parser(func, types, args_and_defaults, delimiter_chars):
"""Return an ArgumentParser for the given function. Arguments are defined from the function arguments and their associated defaults. Args: func: function for which we want an ArgumentParser types: types to which the command line arguments should be converted to args_and_defaults: list of 2-tuples (arg_name, arg_default) delimiter_chars: characters used to separate the parameters from their help message in the docstring """ |
_LOG.debug("Creating ArgumentParser for '%s'", func.__name__)
(description, arg_help) = _prepare_doc(
func, [x for (x, _) in args_and_defaults], delimiter_chars)
parser = argparse.ArgumentParser(description=description)
for ((arg, default), arg_type) in zip_longest(args_and_defaults, types):
help_msg = arg_help[arg]
if default is NoDefault:
arg_type = arg_type or identity_type
if arg_type == bool:
_LOG.debug("Adding optional flag %s.%s", func.__name__, arg)
parser.add_argument("--%s" % arg, default=True, required=False,
action="store_false",
help="%s. Defaults to True if not specified"
% help_msg)
else:
_LOG.debug("Adding positional argument %s.%s", func.__name__,
arg)
parser.add_argument(arg, help=help_msg, type=arg_type)
else:
if default is None and arg_type is None:
raise ParseThisError("To use default value of 'None' you need "
"to specify the type of the argument '{}' "
"for the method '{}'"
.format(arg, func.__name__))
arg_type = arg_type or type(default)
if arg_type == bool:
action = "store_false" if default else "store_true"
_LOG.debug("Adding optional flag %s.%s", func.__name__, arg)
parser.add_argument("--%s" % arg, help=help_msg,
default=default, action=action)
else:
_LOG.debug(
"Adding optional argument %s.%s", func.__name__, arg)
parser.add_argument("--%s" % arg, help=help_msg,
default=default, type=arg_type)
return parser |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.