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 listen_until_return(self, *temporary_handlers, timeout=0):
"""Calls listen repeatedly until listen returns something else than None. Then returns listen's result. If timeout is not zero listen_until_return stops after timeout seconds and returns None.""" |
start = time.time()
while timeout == 0 or time.time() - start < timeout:
res = self.listen(*temporary_handlers)
if res is not None:
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wait_for_n_keypresses(self, key, n=1):
"""Waits till one key was pressed n times. :param key: the key to be pressed as defined by pygame. E.g. pygame.K_LEFT for the left arrow key :type key: int :param n: number of repetitions till the function returns :type n: int """ |
my_const = "key_consumed"
counter = 0
def keypress_listener(e): return my_const \
if e.type == pygame.KEYDOWN and e.key == key \
else EventConsumerInfo.DONT_CARE
while counter < n:
if self.listen(keypress_listener) == my_const:
counter += 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 wait_for_keys(self, *keys, timeout=0):
"""Waits until one of the specified keys was pressed, and returns which key was pressed. :param keys: iterable of integers of pygame-keycodes, or simply multiple keys passed via multiple arguments :type keys: iterable :param timeout: number of seconds to wait till the function returns :type timeout: float :returns: The keycode of the pressed key, or None in case of timeout :rtype: int """ |
if len(keys) == 1 and _is_iterable(keys[0]):
keys = keys[0]
return self.listen_until_return(Handler.key_press(keys), timeout=timeout) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wait_for_keys_modified(self, *keys, modifiers_to_check=_mod_keys, timeout=0):
"""The same as wait_for_keys, but returns a frozen_set which contains the pressed key, and the modifier keys. :param modifiers_to_check: iterable of modifiers for which the function will check whether they are pressed :type modifiers: Iterable[int]""" |
set_mods = pygame.key.get_mods()
return frozenset.union(
frozenset([self.wait_for_keys(*keys, timeout=timeout)]),
EventListener._contained_modifiers(set_mods, modifiers_to_check)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_all_first_files(self, item):
""" Does not support the full range of ways rar can split as it'd require reading the file to ensure you are using the correct way. """ |
for listed_item in item.list():
new_style = re.findall(r'(?i)\.part(\d+)\.rar^', listed_item.id)
if new_style:
if int(new_style[0]) == 1:
yield 'new', listed_item
elif listed_item.id.lower().endswith('.rar'):
yield 'old', listed_item |
<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, *, text: str, ) -> List[OutputRecord]: """ Send birdsite message. :param text: text to send in post. :returns: list of output records, each corresponding to either a single post, or an error. """ |
try:
status = self.api.update_status(text)
self.ldebug(f"Status object from tweet: {status}.")
return [TweetRecord(record_data={"tweet_id": status._json["id"], "text": text})]
except tweepy.TweepError as e:
return [self.handle_error(
message=(f"Bot {self.bot_name} encountered an error when "
f"sending post {text} without media:\n{e}\n"),
error=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 send_with_media( self, *, text: str, files: List[str], captions: List[str]=[] ) -> List[OutputRecord]: """ Upload media to birdsite, and send status and media, and captions if present. :param text: tweet text. :param files: list of files to upload with post. :param captions: list of captions to include as alt-text with files. :returns: list of output records, each corresponding to either a single post, or an error. """ |
# upload media
media_ids = None
try:
self.ldebug(f"Uploading files {files}.")
media_ids = [self.api.media_upload(file).media_id_string for file in files]
except tweepy.TweepError as e:
return [self.handle_error(
message=f"Bot {self.bot_name} encountered an error when uploading {files}:\n{e}\n",
error=e)]
# apply captions, if present
self._handle_caption_upload(media_ids=media_ids, captions=captions)
# send status
try:
status = self.api.update_status(status=text, media_ids=media_ids)
self.ldebug(f"Status object from tweet: {status}.")
return [TweetRecord(record_data={
"tweet_id": status._json["id"],
"text": text,
"media_ids": media_ids,
"captions": captions,
"files": files
})]
except tweepy.TweepError as e:
return [self.handle_error(
message=(f"Bot {self.bot_name} encountered an error when "
f"sending post {text} with media ids {media_ids}:\n{e}\n"),
error=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 send_dm_sos(self, message: str) -> None: """ Send DM to owner if something happens. :param message: message to send to owner. :returns: None. """ |
if self.owner_handle:
try:
# twitter changed the DM API and tweepy (as of 2019-03-08)
# has not adapted.
# fixing with
# https://github.com/tweepy/tweepy/issues/1081#issuecomment-423486837
owner_id = self.api.get_user(screen_name=self.owner_handle).id
event = {
"event": {
"type": "message_create",
"message_create": {
"target": {
"recipient_id": f"{owner_id}",
},
"message_data": {
"text": message
}
}
}
}
self._send_direct_message_new(event)
except tweepy.TweepError as de:
self.lerror(f"Error trying to send DM about error!: {de}")
else:
self.lerror("Can't send DM SOS, no owner 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 _handle_caption_upload( self, *, media_ids: List[str], captions: Optional[List[str]], ) -> None: """ Handle uploading all captions. :param media_ids: media ids of uploads to attach captions to. :param captions: captions to be attached to those media ids. :returns: None. """ |
if captions is None:
captions = []
if len(media_ids) > len(captions):
captions.extend([self.default_caption_message] * (len(media_ids) - len(captions)))
for i, media_id in enumerate(media_ids):
caption = captions[i]
self._upload_caption(media_id=media_id, caption=caption) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
"""Takes crash data via stdin and generates a Socorro signature""" |
parser = argparse.ArgumentParser(description=DESCRIPTION)
parser.add_argument(
'-v', '--verbose', help='increase output verbosity', action='store_true'
)
args = parser.parse_args()
generator = SignatureGenerator(debug=args.verbose)
crash_data = json.loads(sys.stdin.read())
ret = generator.generate(crash_data)
print(json.dumps(ret, indent=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 add_config(self, config):
""" Update internel configuration dict with config and recheck """ |
for attr in self.__fixed_attrs:
if attr in config:
raise Exception("cannot set '%s' outside of init", attr)
# pre checkout
stages = config.get('stages', None)
if stages:
self.stages = stages
# maybe pre checkout
# validate options
self.__dry_run = config.get('dry_run', False)
self.system = str.lower(platform.system())
self.__start = config.get('start', None)
self.__end = config.get('end', None)
self.__only = config.get('only', None)
self.__build_docs = config.get('build_docs', False)
self.__chatty = config.get('chatty', False)
self.__clean = config.get('clean', False)
self.__devel = config.get('devel', False)
self.__debug = config.get('debug', False)
self.__skip_libcheck = config.get('skip_libcheck', False)
self.__debuginfo = config.get('debuginfo', False)
self.__release = config.get('release', False)
self.__skip_unit = config.get('skip_unit', False)
self.__static = config.get('static', False)
self.__make_dash_j = int(config.get('j', 0))
self.__target_only = config.get('target_only', None)
bits = config.get('bits', None)
if bits:
self.bits = int(bits)
else:
self.bits = self.sys_bits
self.compiler = config.get('compiler', None)
self.test_config = config.get('test_config', '-')
if not self.test_config:
self.test_config = '-'
self.use_ccache = config.get('use_ccache', False)
self.tmpl_engine = config.get('tmpl_engine', 'jinja2')
self.__write_codec = config.get('write_codec', None)
self.__codec = None
# TODO move out of init
if not config.get('skip_env_check', False):
if "LD_LIBRARY_PATH" in os.environ:
raise Exception("environment variable LD_LIBRARY_PATH is set")
self.check_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 check_config(self):
""" called after config was modified to sanity check raises on error """ |
# sanity checks - no config access past here
if not getattr(self, 'stages', None):
raise NotImplementedError("member variable 'stages' must be defined")
# start at stage
if self.__start:
self.__stage_start = self.find_stage(self.__start)
else:
self.__stage_start = 0
# end at stage
if self.__end:
self.__stage_end = self.find_stage(self.__end) + 1
self.opt_end = self.__end
else:
self.__stage_end = len(self.stages)
# only stage
if self.__only:
if self.__start or self.__end:
raise Exception(
"stage option 'only' cannot be used with start or end")
self.__stage_start = self.find_stage(self.__only)
self.__stage_end = self.__stage_start + 1
if self.__devel:
self.__devel = True
# force deploy skip
if self.__stage_end >= len(self.stages):
self.status_msg("removing deploy stage for development build")
# XXX self.__stage_end = self.__stage_end - 1
if self.stage_start >= self.stage_end:
raise Exception("start and end produce no stages")
if self.bits not in [32, 64]:
raise Exception(
"can't do a %d bit build: unknown build process" % self.bits)
if self.bits == 64 and not self.is_64b:
raise Exception(
"this machine is not 64 bit, cannot perform 64 bit build")
if self.system == 'windows':
self.compilertag = 'vc10'
elif self.system == 'linux':
self.compilertag = 'gcc44'
else:
raise RuntimeError("can't decide compilertag on " + self.system)
self.build_suffix = ''
if not self.is_unixy:
if self.__static:
runtime = 'MT'
else:
runtime = 'MD'
if self.__release:
self.configuration_name = 'Release'
else:
runtime += 'd'
self.configuration_name = 'Debug'
self.build_suffix = '-' + runtime
self.runtime = runtime
else:
self.configuration_name = 'CFNAME_INVALID_ON_LINUX'
self.runtime = 'RUNTIME_INVALID_ON_LINUX'
if self.test_config != '-':
self.test_config = os.path.abspath(self.test_config)
# split version
if self.version:
ver = self.version.split('.')
self.version_major = int(ver[0])
self.version_minor = int(ver[1])
self.version_patch = int(ver[2])
if(len(ver) == 4):
self.version_build = int(ver[3]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_definition(self):
""" called after Defintion was loaded to sanity check raises on error """ |
if not self.write_codec:
self.__write_codec = self.defined.data_ext
# TODO need to add back a class scope target limited for subprojects with sub target sets
targets = self.get_defined_targets()
if self.__target_only:
if self.__target_only not in targets:
raise RuntimeError("invalid target '%s'" % self.__target_only)
self.targets = [self.__target_only]
else:
self.targets = targets |
<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_datafile(self, name, search_path=None, **kwargs):
""" find datafile and load them from codec """ |
if not search_path:
search_path = self.define_dir
self.debug_msg('loading datafile %s from %s' % (name, str(search_path)))
return codec.load_datafile(name, search_path, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self):
""" run all configured stages """ |
self.sanity_check()
# TODO - check for devel
# if not self.version:
# raise Exception("no version")
# XXX check attr exist
if not self.release_environment:
raise Exception("no instance name")
time_start = time.time()
cwd = os.getcwd()
who = getpass.getuser()
self._make_outdirs()
append_notices = ""
if hasattr(self, 'opt_end'):
append_notices = ". shortened push, only to %s stage" % self.opt_end
if self.is_devel:
append_notices += ". devel build"
if hasattr(self, 'append_notices'):
append_notices += self.append_notices
line = "%s %s %s by %s%s" % (
sys.argv[0], self.version, self.release_environment, who, append_notices)
b = 'deploy begin %s' % line
e = 'deploy done %s' % line
if self.chatty:
self.alact(b)
ok = False
stage_passed = None
try:
for stage in self.stages[self.stage_start:self.stage_end]:
self.debug_msg("stage %s starting" % (stage,))
getattr(self, stage)()
self.chdir(cwd)
stage_passed = stage
self.debug_msg("stage %s complete" % (stage,))
ok = True
finally:
if not ok:
if self.chatty:
if not stage_passed:
self.alact(
'deploy failed %s. completed no stages' % line)
else:
self.alact('deploy failed %s. completed %s' %
(line, stage_passed))
self.status_msg('[OK]')
if self.chatty:
self.alact('%s in %0.3f sec' % (e, time.time() - time_start))
return 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def timestamp(dt):
""" Return POSIX timestamp as float. True True """ |
if dt.tzinfo is None:
return time.mktime((
dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second,
-1, -1, -1)) + dt.microsecond / 1e6
else:
return (dt - _EPOCH).total_seconds() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
"""Rate limit a function.""" |
return util.rate_limited(max_per_hour, *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 _repair(record: Dict[str, Any]) -> Dict[str, Any]: """Repair a corrupted IterationRecord with a specific known issue.""" |
output_records = record.get("output_records")
if record.get("_type", None) == "IterationRecord" and output_records is not None:
birdsite_record = output_records.get("birdsite")
# check for the bug
if isinstance(birdsite_record, dict) and birdsite_record.get("_type") == "IterationRecord":
# get to the bottom of the corrupted record
failed = False
while birdsite_record.get("_type") == "IterationRecord":
sub_record = birdsite_record.get("output_records")
if sub_record is None:
failed = True
break
birdsite_record = sub_record.get("birdsite")
if birdsite_record is None:
failed = True
break
if failed:
return record
# add type
birdsite_record["_type"] = TweetRecord.__name__
# lift extra keys, just in case
if "extra_keys" in birdsite_record:
record_extra_values = record.get("extra_keys", {})
for key, value in birdsite_record["extra_keys"].items():
if key not in record_extra_values:
record_extra_values[key] = value
record["extra_keys"] = record_extra_values
del birdsite_record["extra_keys"]
output_records["birdsite"] = birdsite_record
# pull that correct record up to the top level, fixing corruption
record["output_records"] = output_records
return 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 from_dict(cls, obj_dict: Dict[str, Any]) -> "IterationRecord": """Get object back from dict.""" |
obj = cls()
for key, item in obj_dict.items():
obj.__dict__[key] = 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 send( self, *args: str, text: str=None, ) -> IterationRecord: """ Post text-only to all outputs. :param args: positional arguments. expected: text to send as message in post. keyword text argument is preferred over this. :param text: text to send as message in post. :returns: new record of iteration """ |
if text is not None:
final_text = text
else:
if len(args) == 0:
raise BotSkeletonException(("Please provide text either as a positional arg or "
"as a keyword arg (text=TEXT)"))
else:
final_text = args[0]
# TODO there could be some annotation stuff here.
record = IterationRecord(extra_keys=self.extra_keys)
for key, output in self.outputs.items():
if output["active"]:
self.log.info(f"Output {key} is active, calling send on it.")
entry: Any = output["obj"]
output_result = entry.send(text=final_text)
record.output_records[key] = output_result
else:
self.log.info(f"Output {key} is inactive. Not sending.")
self.history.append(record)
self.update_history()
return 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 send_with_one_media( self, *args: str, text: str=None, file: str=None, caption: str=None, ) -> IterationRecord: """ Post with one media item to all outputs. Provide filename so outputs can handle their own uploads. :param args: positional arguments. expected: text to send as message in post. file to be uploaded. caption to be paired with file. keyword arguments preferred over positional ones. :param text: text to send as message in post. :param file: file to be uploaded in post. :param caption: caption to be uploaded alongside file. :returns: new record of iteration """ |
final_text = text
if final_text is None:
if len(args) < 1:
raise TypeError(("Please provide either positional argument "
"TEXT, or keyword argument text=TEXT"))
else:
final_text = args[0]
final_file = file
if final_file is None:
if len(args) < 2:
raise TypeError(("Please provide either positional argument "
"FILE, or keyword argument file=FILE"))
else:
final_file = args[1]
# this arg is ACTUALLY optional,
# so the pattern is changed.
final_caption = caption
if final_caption is None:
if len(args) >= 3:
final_caption = args[2]
# TODO more error checking like this.
if final_caption is None or final_caption == "":
captions:List[str] = []
else:
captions = [final_caption]
record = IterationRecord(extra_keys=self.extra_keys)
for key, output in self.outputs.items():
if output["active"]:
self.log.info(f"Output {key} is active, calling media send on it.")
entry: Any = output["obj"]
output_result = entry.send_with_media(text=final_text,
files=[final_file],
captions=captions)
record.output_records[key] = output_result
else:
self.log.info(f"Output {key} is inactive. Not sending with media.")
self.history.append(record)
self.update_history()
return 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 send_with_many_media( self, *args: str, text: str=None, files: List[str]=None, captions: List[str]=[], ) -> IterationRecord: """ Post with several media. Provide filenames so outputs can handle their own uploads. :param args: positional arguments. expected: text to send as message in post. files to be uploaded. captions to be paired with files. keyword arguments preferred over positional ones. :param text: text to send as message in post. :param files: files to be uploaded in post. :param captions: captions to be uploaded alongside files. :returns: new record of iteration """ |
if text is None:
if len(args) < 1:
raise TypeError(("Please provide either required positional argument "
"TEXT, or keyword argument text=TEXT"))
else:
final_text = args[0]
else:
final_text = text
if files is None:
if len(args) < 2:
raise TypeError(("Please provide either positional argument "
"FILES, or keyword argument files=FILES"))
else:
final_files = list(args[1:])
else:
final_files = files
# captions have never been permitted to be provided as positional args
# (kind of backed myself into that)
# so they just get defaulted and it's fine.
record = IterationRecord(extra_keys=self.extra_keys)
for key, output in self.outputs.items():
if output["active"]:
self.log.info(f"Output {key} is active, calling media send on it.")
entry: Any = output["obj"]
output_result = entry.send_with_media(text=final_text,
files=final_files,
captions=captions)
record.output_records[key] = output_result
else:
self.log.info(f"Output {key} is inactive. Not sending with media.")
self.history.append(record)
self.update_history()
return 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 nap(self) -> None: """ Go to sleep for the duration of self.delay. :returns: None """ |
self.log.info(f"Sleeping for {self.delay} seconds.")
for _ in progress.bar(range(self.delay)):
time.sleep(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 store_extra_info(self, key: str, value: Any) -> None: """ Store some extra value in the messaging storage. :param key: key of dictionary entry to add. :param value: value of dictionary entry to add. :returns: None """ |
self.extra_keys[key] = 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 store_extra_keys(self, d: Dict[str, Any]) -> None: """ Store several extra values in the messaging storage. :param d: dictionary entry to merge with current self.extra_keys. :returns: None """ |
new_dict = dict(self.extra_keys, **d)
self.extra_keys = new_dict.copy() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_history(self) -> None: """ Update messaging history on disk. :returns: None """ |
self.log.debug(f"Saving history. History is: \n{self.history}")
jsons = []
for item in self.history:
json_item = item.__dict__
# Convert sub-entries into JSON as well.
json_item["output_records"] = self._parse_output_records(item)
jsons.append(json_item)
if not path.isfile(self.history_filename):
open(self.history_filename, "a+").close()
with open(self.history_filename, "w") as f:
json.dump(jsons, f, default=lambda x: x.__dict__.copy(), sort_keys=True, indent=4)
f.write("\n") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_history(self) -> List["IterationRecord"]: """ Load messaging history from disk to self. :returns: List of iteration records comprising history. """ |
if path.isfile(self.history_filename):
with open(self.history_filename, "r") as f:
try:
dicts = json.load(f)
except json.decoder.JSONDecodeError as e:
self.log.error(f"Got error \n{e}\n decoding JSON history, overwriting it.\n"
f"Former history available in {self.history_filename}.bak")
copyfile(self.history_filename, f"{self.history_filename}.bak")
return []
history: List[IterationRecord] = []
for hdict_pre in dicts:
if "_type" in hdict_pre and hdict_pre["_type"] == IterationRecord.__name__:
# repair any corrupted entries
hdict = _repair(hdict_pre)
record = IterationRecord.from_dict(hdict)
history.append(record)
# Be sure to handle legacy tweetrecord-only histories.
# Assume anything without our new _type (which should have been there from the
# start, whoops) is a legacy history.
else:
item = IterationRecord()
# Lift extra keys up to upper record (if they exist).
extra_keys = hdict_pre.pop("extra_keys", {})
item.extra_keys = extra_keys
hdict_obj = TweetRecord.from_dict(hdict_pre)
# Lift timestamp up to upper record.
item.timestamp = hdict_obj.timestamp
item.output_records["birdsite"] = hdict_obj
history.append(item)
self.log.debug(f"Loaded history:\n {history}")
return history
else:
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 _setup_all_outputs(self) -> None: """Set up all output methods. Provide them credentials and anything else they need.""" |
# The way this is gonna work is that we assume an output should be set up iff it has a
# credentials_ directory under our secrets dir.
for key in self.outputs.keys():
credentials_dir = path.join(self.secrets_dir, f"credentials_{key}")
# special-case birdsite for historical reasons.
if key == "birdsite" and not path.isdir(credentials_dir) \
and path.isfile(path.join(self.secrets_dir, "CONSUMER_KEY")):
credentials_dir = self.secrets_dir
if path.isdir(credentials_dir):
output_skeleton = self.outputs[key]
output_skeleton["active"] = True
obj: Any = output_skeleton["obj"]
obj.cred_init(secrets_dir=credentials_dir, log=self.log, bot_name=self.bot_name)
output_skeleton["obj"] = obj
self.outputs[key] = output_skeleton |
<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_output_records(self, item: IterationRecord) -> Dict[str, Any]: """Parse output records into dicts ready for JSON.""" |
output_records = {}
for key, sub_item in item.output_records.items():
if isinstance(sub_item, dict) or isinstance(sub_item, list):
output_records[key] = sub_item
else:
output_records[key] = sub_item.__dict__
return output_records |
<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_dir(fname):
""" Create the directory of a fully qualified file name if it does not exist. :param fname: File name :type fname: string Equivalent to these Bash shell commands: .. code-block:: bash $ fname="${HOME}/mydir/myfile.txt" $ dir=$(dirname "${fname}") $ mkdir -p "${dir}" :param fname: Fully qualified file name :type fname: string """ |
file_path, fname = os.path.split(os.path.abspath(fname))
if not os.path.exists(file_path):
os.makedirs(file_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 normalize_windows_fname(fname, _force=False):
r""" Fix potential problems with a Microsoft Windows file name. Superfluous backslashes are removed and unintended escape sequences are converted to their equivalent (presumably correct and intended) representation, for example :code:`r'\\\\x07pps'` is transformed to :code:`r'\\\\\\\\apps'`. A file name is considered network shares if the file does not include a drive letter and they start with a double backslash (:code:`'\\\\\\\\'`) :param fname: File name :type fname: string :rtype: string """ |
if (platform.system().lower() != "windows") and (not _force): # pragma: no cover
return fname
# Replace unintended escape sequences that could be in
# the file name, like "C:\appdata"
rchars = {
"\x07": r"\\a",
"\x08": r"\\b",
"\x0C": r"\\f",
"\x0A": r"\\n",
"\x0D": r"\\r",
"\x09": r"\\t",
"\x0B": r"\\v",
}
ret = ""
for char in os.path.normpath(fname):
ret = ret + rchars.get(char, char)
# Remove superfluous double backslashes
network_share = False
tmp = None
network_share = fname.startswith(r"\\")
while tmp != ret:
tmp, ret = ret, ret.replace(r"\\\\", r"\\")
ret = ret.replace(r"\\\\", r"\\")
# Put back network share if needed
if network_share:
ret = r"\\" + ret.lstrip(r"\\")
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _homogenize_linesep(line):
"""Enforce line separators to be the right one depending on platform.""" |
token = str(uuid.uuid4())
line = line.replace(os.linesep, token).replace("\n", "").replace("\r", "")
return line.replace(token, os.linesep) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _proc_token(spec, mlines):
"""Process line range tokens.""" |
spec = spec.strip().replace(" ", "")
regexp = re.compile(r".*[^0123456789\-,]+.*")
tokens = spec.split(",")
cond = any([not item for item in tokens])
if ("--" in spec) or ("-," in spec) or (",-" in spec) or cond or regexp.match(spec):
raise RuntimeError("Argument `lrange` is not valid")
lines = []
for token in tokens:
if token.count("-") > 1:
raise RuntimeError("Argument `lrange` is not valid")
if "-" in token:
subtokens = token.split("-")
lmin, lmax = (
int(subtokens[0]),
int(subtokens[1]) if subtokens[1] else mlines,
)
for num in range(lmin, lmax + 1):
lines.append(num)
else:
lines.append(int(token))
if lines != sorted(lines):
raise RuntimeError("Argument `lrange` is not valid")
return lines |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def incfile(fname, fpointer, lrange=None, sdir=None):
r""" Return a Python source file formatted in reStructuredText. .. role:: bash(code) :language: bash :param fname: File name, relative to environment variable :bash:`PKG_DOC_DIR` :type fname: string :param fpointer: Output function pointer. Normally is :code:`cog.out` but other functions can be used for debugging :type fpointer: function object :param lrange: Line range to include, similar to Sphinx `literalinclude <http://www.sphinx-doc.org/en/master/usage /restructuredtext/directives.html #directive-literalinclude>`_ directive :type lrange: string :param sdir: Source file directory. If None the :bash:`PKG_DOC_DIR` environment variable is used if it is defined, otherwise the directory where the module is located is used :type sdir: string For example: .. code-block:: python def func():
\"\"\" This is a docstring. This file shows how to use it: .. =[=cog .. import docs.support.incfile .. docs.support.incfile.incfile('func_example.py', cog.out) .. =]= .. code-block:: python # func_example.py if __name__ == '__main__': func() .. =[=end=]= \"\"\" return 'This is func output' """ |
# pylint: disable=R0914
# Read file
file_dir = (
sdir
if sdir
else os.environ.get("PKG_DOC_DIR", os.path.abspath(os.path.dirname(__file__)))
)
fname = os.path.join(file_dir, fname)
with open(fname, "r") as fobj:
lines = fobj.readlines()
# Eliminate spurious carriage returns in Microsoft Windows
lines = [_homogenize_linesep(line) for line in lines]
# Parse line specification
inc_lines = (
_proc_token(lrange, len(lines)) if lrange else list(range(1, len(lines) + 1))
)
# Produce output
fpointer(".. code-block:: python" + os.linesep)
fpointer(os.linesep)
for num, line in enumerate(lines):
if num + 1 in inc_lines:
fpointer(
" " + line.replace("\t", " ").rstrip() + os.linesep
if line.strip()
else os.linesep
)
fpointer(os.linesep) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def flo(string):
'''Return the string given by param formatted with the callers locals.'''
callers_locals = {}
frame = inspect.currentframe()
try:
outerframe = frame.f_back
callers_locals = outerframe.f_locals
finally:
del frame
return string.format(**callers_locals) |
<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_with(color_code):
'''Color wrapper.
Example:
>>> blue = _wrap_with('34')
>>> print(blue('text'))
\033[34mtext\033[0m
'''
def inner(text, bold=False):
'''Inner color function.'''
code = color_code
if bold:
code = flo("1;{code}")
return flo('\033[{code}m{text}\033[0m')
return inner |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def pythons():
'''Install latest pythons with pyenv.
The python version will be activated in the projects base dir.
Will skip already installed latest python versions.
'''
if not _pyenv_exists():
print('\npyenv is not installed. You can install it with fabsetup '
'(https://github.com/theno/fabsetup):\n\n ' +
cyan('mkdir ~/repos && cd ~/repos\n '
'git clone https://github.com/theno/fabsetup.git\n '
'cd fabsetup && fab setup.pyenv -H localhost'))
return 1
latest_pythons = _determine_latest_pythons()
print(cyan('\n## install latest python versions'))
for version in latest_pythons:
local(flo('pyenv install --skip-existing {version}'))
print(cyan('\n## activate pythons'))
basedir = dirname(__file__)
latest_pythons_str = ' '.join(latest_pythons)
local(flo('cd {basedir} && pyenv local system {latest_pythons_str}'))
highest_python = latest_pythons[-1]
print(cyan(flo(
'\n## prepare Python-{highest_python} for testing and packaging')))
packages_for_testing = 'pytest tox'
packages_for_packaging = 'pypandoc twine'
local(flo('~/.pyenv/versions/{highest_python}/bin/pip install --upgrade '
'pip {packages_for_testing} {packages_for_packaging}')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def tox(args=''):
'''Run tox.
Build package and run unit tests against several pythons.
Args:
args: Optional arguments passed to tox.
Example:
fab tox:'-e py36 -r'
'''
basedir = dirname(__file__)
latest_pythons = _determine_latest_pythons()
# e.g. highest_minor_python: '3.6'
highest_minor_python = _highest_minor(latest_pythons)
_local_needs_pythons(flo('cd {basedir} && '
'python{highest_minor_python} -m tox {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 import_gene_history(file_handle, tax_id, tax_id_col, id_col, symbol_col):
""" Read input gene history file into the database. Note that the arguments tax_id_col, id_col and symbol_col have been converted into 0-based column indexes. """ |
# Make sure that tax_id is not "" or " "
if not tax_id or tax_id.isspace():
raise Exception("Input tax_id is blank")
# Make sure that tax_id exists in Organism table in the database.
try:
organism = Organism.objects.get(taxonomy_id=tax_id)
except Organism.DoesNotExist:
raise Exception('Input tax_id %s does NOT exist in Organism table. '
'Please add it into Organism table first.' % tax_id)
if tax_id_col < 0 or id_col < 0 or symbol_col < 0:
raise Exception(
'tax_id_col, id_col and symbol_col must be positive integers')
for line_index, line in enumerate(file_handle):
if line.startswith('#'): # Skip comment lines.
continue
fields = line.rstrip().split('\t')
# Check input column numbers.
chk_col_numbers(line_index + 1, len(fields), tax_id_col, id_col,
symbol_col)
# Skip lines whose tax_id's do not match input tax_id.
if tax_id != fields[tax_id_col]:
continue
entrez_id = fields[id_col]
# If the gene already exists in database, set its "obsolete" attribute
# to True; otherwise create a new obsolete Gene record in database.
try:
gene = Gene.objects.get(entrezid=entrez_id)
if not gene.obsolete:
gene.obsolete = True
gene.save()
except Gene.DoesNotExist:
Gene.objects.create(entrezid=entrez_id, organism=organism,
systematic_name=fields[symbol_col],
obsolete=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 send( self, *, text: str, ) -> List[OutputRecord]: """ Send mastodon message. :param text: text to send in post. :returns: list of output records, each corresponding to either a single post, or an error. """ |
try:
status = self.api.status_post(status=text)
return [TootRecord(record_data={
"toot_id": status["id"],
"text": text
})]
except mastodon.MastodonError as e:
return [self.handle_error((f"Bot {self.bot_name} encountered an error when "
f"sending post {text} without media:\n{e}\n"),
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 send_with_media( self, *, text: str, files: List[str], captions: List[str]=[], ) -> List[OutputRecord]: """ Upload media to mastodon, and send status and media, and captions if present. :param text: post text. :param files: list of files to upload with post. :param captions: list of captions to include as alt-text with files. :returns: list of output records, each corresponding to either a single post, or an error. """ |
try:
self.ldebug(f"Uploading files {files}.")
if captions is None:
captions = []
if len(files) > len(captions):
captions.extend([self.default_caption_message] * (len(files) - len(captions)))
media_dicts = []
for i, file in enumerate(files):
caption = captions[i]
media_dicts.append(self.api.media_post(file, description=caption))
self.ldebug(f"Media ids {media_dicts}")
except mastodon.MastodonError as e:
return [self.handle_error(
f"Bot {self.bot_name} encountered an error when uploading {files}:\n{e}\n", e
)]
try:
status = self.api.status_post(status=text, media_ids=media_dicts)
self.ldebug(f"Status object from toot: {status}.")
return [TootRecord(record_data={
"toot_id": status["id"],
"text": text,
"media_ids": media_dicts,
"captions": captions
})]
except mastodon.MastodonError as e:
return [self.handle_error((f"Bot {self.bot_name} encountered an error when "
f"sending post {text} with media dicts {media_dicts}:"
f"\n{e}\n"),
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 _read_header(self):
'''
Little-endian
|... 4 bytes unsigned int ...|... 4 bytes unsigned int ...|
| frames count | dimensions count |
'''
self._fh.seek(0)
buf = self._fh.read(4*2)
fc, dc = struct.unpack("<II", buf)
return fc, dc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def listen(self, you):
""" Request a callback for value modification. Parameters you : object An instance having ``__call__`` attribute. """ |
self._listeners.append(you)
self.raw.talk_to(you) |
<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_term_by_id(self, id):
'''Simple utility function to load a term.
'''
url = (self.url + '/%s.json') % id
r = self.session.get(url)
return r.json() |
<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_top_display(self, **kwargs):
'''
Returns all concepts or collections that form the top-level of a display
hierarchy.
As opposed to the :meth:`get_top_concepts`, this method can possibly
return both concepts and collections.
:rtype: Returns a list of concepts and collections. For each an
id is present and a label. The label is determined by looking at
the `**kwargs` parameter, the default language of the provider
and falls back to `en` if nothing is present.
'''
language = self._get_language(**kwargs)
url = self.url + '/lijst.json'
args = {'type[]': ['HR']}
r = self.session.get(url, params=args)
result = r.json()
items = result
top = self.get_by_id(items[0]['id'])
res = []
def expand_coll(res, coll):
for nid in coll.members:
c = self.get_by_id(nid)
res.append({
'id': c.id,
'label': c.label(language)
})
return res
return expand_coll(res, top) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _inner_func_anot(func):
"""must be applied to all inner functions that return contexts. Wraps all instances of pygame.Surface in the input in Surface""" |
@wraps(func)
def new_func(*args):
return func(*_lmap(_wrap_surface, args))
return new_func |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Cross(width=3, color=0):
"""Draws a cross centered in the target area :param width: width of the lines of the cross in pixels :type width: int :param color: color of the lines of the cross :type color: pygame.Color """ |
return Overlay(Line("h", width, color), Line("v", width, color)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Font(name=None, source="sys", italic=False, bold=False, size=20):
"""Unifies loading of fonts. :param name: name of system-font or filepath, if None is passed the default system-font is loaded :type name: str :param source: "sys" for system font, or "file" to load a file :type source: str """ |
assert source in ["sys", "file"]
if not name:
return pygame.font.SysFont(pygame.font.get_default_font(),
size, bold=bold, italic=italic)
if source == "sys":
return pygame.font.SysFont(name,
size, bold=bold, italic=italic)
else:
f = pygame.font.Font(name, size)
f.set_italic(italic)
f.set_bold(bold)
return f |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_scale(scale_w, scale_h=None):
"""Creates a padding by the remaining space after scaling the content. E.g. Padding.from_scale(0.5) would produce Padding(0.25, 0.25, 0.25, 0.25) and Padding.from_scale(0.5, 1) would produce Padding(0.25, 0.25, 0, 0) because the content would not be scaled (since scale_h=1) and therefore there would be no vertical padding. If scale_h is not specified scale_h=scale_w is used as default :param scale_w: horizontal scaling factors :type scale_w: float :param scale_h: vertical scaling factor :type scale_h: float """ |
if not scale_h: scale_h = scale_w
w_padding = [(1 - scale_w) * 0.5] * 2
h_padding = [(1 - scale_h) * 0.5] * 2
return Padding(*w_padding, *h_padding) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ishex(obj):
""" Test if the argument is a string representing a valid hexadecimal digit. :param obj: Object :type obj: any :rtype: boolean """ |
return isinstance(obj, str) and (len(obj) == 1) and (obj in string.hexdigits) |
<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_api_context(self, cls):
"""Create and return an API context""" |
return self.api_context_schema().load({
"name": cls.name,
"cls": cls,
"inst": [],
"conf": self.conf.get_api_service(cls.name),
"calls": self.conf.get_api_calls(),
"shared": {}, # Used per-API to monitor state
"log_level": self.conf.get_log_level(),
"callback": self.receive
}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def receive(self, data, api_context):
"""Pass an API result down the pipeline""" |
self.log.debug(f"Putting data on the pipeline: {data}")
result = {
"api_contexts": self.api_contexts,
"api_context": api_context,
"strategy": dict(), # Shared strategy data
"result": data,
"log_level": api_context["log_level"],
}
self.strat.execute(self.strategy_context_schema().load(result).data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shutdown(self, signum, frame):
# pylint: disable=unused-argument """Shut it down""" |
if not self.exit:
self.exit = True
self.log.debug(f"SIGTRAP!{signum};{frame}")
self.api.shutdown()
self.strat.shutdown() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def course(self):
""" Course this node belongs to """ |
course = self.parent
while course.parent:
course = course.parent
return course |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def title(self):
""" get title of this node. If an entry for this course is found in the configuration namemap it is used, otherwise the default value from stud.ip is used. """ |
tmp = c.namemap_lookup(self.id) if c.namemap_lookup(self.id) is not None else self._title
return secure_filename(tmp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deep_documents(self):
""" list of all documents find in subtrees of this node """ |
tree = []
for entry in self.contents:
if isinstance(entry, Document):
tree.append(entry)
else:
tree += entry.deep_documents
return tree |
<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, route, stream=False):
""" run a get request against an url. Returns the response which can optionally be streamed """ |
log.debug("Running GET request against %s" % route)
return r.get(self._url(route), auth=c.auth, stream=stream) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_document(self, document: Document, overwrite=True, path=None):
""" Download a document to the given path. if no path is provided the path is constructed frome the base_url + stud.ip path + filename. If overwrite is set the local version will be overwritten if the file was changed on studip since the last check """ |
if not path:
path = os.path.join(os.path.expanduser(c["base_path"]), document.path)
if (self.modified(document) and overwrite) or not os.path.exists(join(path, document.title)):
log.info("Downloading %s" % join(path, document.title))
file = self._get('/api/documents/%s/download' % document.id, stream=True)
os.makedirs(path, exist_ok=True)
with open(join(path, document.title), 'wb') as f:
shutil.copyfileobj(file.raw, f) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_semester_title(self, node: BaseNode):
""" get the semester of a node """ |
log.debug("Getting Semester Title for %s" % node.course.id)
return self._get_semester_from_id(node.course.semester) |
<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_courses(self):
""" use the base_url and auth data from the configuration to list all courses the user is subscribed to """ |
log.info("Listing Courses...")
courses = json.loads(self._get('/api/courses').text)["courses"]
courses = [Course.from_response(course) for course in courses]
log.debug("Courses: %s" % [str(entry) for entry in courses])
return courses |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _minimize_scalar( self, desc="Progress", rtol=1.4902e-08, atol=1.4902e-08, verbose=True ):
""" Minimize a scalar function using Brent's method. Parameters verbose : bool ``True`` for verbose output; ``False`` otherwise. """ |
from tqdm import tqdm
from numpy import asarray
from brent_search import minimize as brent_minimize
variables = self._variables.select(fixed=False)
if len(variables) != 1:
raise ValueError("The number of variables must be equal to one.")
var = variables[variables.names()[0]]
progress = tqdm(desc=desc, disable=not verbose)
def func(x):
progress.update(1)
var.value = x
return self.__sign * self.value()
r = asarray(
brent_minimize(func, a=var.bounds[0], b=var.bounds[1], rtol=rtol, atol=atol)
)
var.value = r[0]
progress.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def camelify(self):
"""turn a string to CamelCase, omitting non-word characters""" |
outstring = self.titleify(allwords=True)
outstring = re.sub(r"&[^;]+;", " ", outstring)
outstring = re.sub(r"\W+", "", outstring)
return String(outstring) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def titleify(self, lang='en', allwords=False, lastword=True):
"""takes a string and makes a title from it""" |
if lang in LOWERCASE_WORDS:
lc_words = LOWERCASE_WORDS[lang]
else:
lc_words = []
s = str(self).strip()
l = re.split(r"([_\W]+)", s)
for i in range(len(l)):
l[i] = l[i].lower()
if (
allwords == True
or i == 0
or (lastword == True and i == len(l) - 1)
or l[i].lower() not in lc_words
):
w = l[i]
if len(w) > 1:
w = w[0].upper() + w[1:]
else:
w = w.upper()
l[i] = w
s = "".join(l)
return String(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 camelsplit(self):
"""Turn a CamelCase string into a string with spaces""" |
s = str(self)
for i in range(len(s) - 1, -1, -1):
if i != 0 and (
(s[i].isupper() and s[i - 1].isalnum() and not s[i - 1].isupper())
or (s[i].isnumeric() and s[i - 1].isalpha())
):
s = s[:i] + ' ' + s[i:]
return String(s.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 includeme(config):
"""Pyramid pluggable and discoverable function.""" |
global_settings = config.registry.settings
settings = local_settings(global_settings, PREFIX)
try:
file = settings['file']
except KeyError:
raise KeyError("Must supply '{}.file' configuration value "
"in order to configure logging via '{}'."
.format(PREFIX, PROJECT))
with open(file, 'r') as f:
logging_config = yaml.load(f)
dictConfig(logging_config)
# Enable transit logging?
if asbool(settings.get('transit_logging.enabled?', False)):
config.add_tween('pyramid_sawing.main.TransitLogger') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call(self, callname, arguments=None):
"""Executed on each scheduled iteration""" |
# See if a method override exists
action = getattr(self.api, callname, None)
if action is None:
try:
action = self.api.ENDPOINT_OVERRIDES.get(callname, None)
except AttributeError:
action = callname
if not callable(action):
request = self._generate_request(action, arguments)
if action is None:
return self._generate_result(
callname, self.api.call(*call_args(callname, arguments)))
return self._generate_result(
callname, self.api.call(*call_args(action, arguments)))
request = self._generate_request(callname, arguments)
return self._generate_result(callname, action(request)) |
<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_request(self, callname, request):
"""Generate a request object for delivery to the API""" |
# Retrieve path from API class
schema = self.api.request_schema()
schema.context['callname'] = callname
return schema.dump(request).data.get("payload") |
<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_result(self, callname, result):
"""Generate a results object for delivery to the context object""" |
# Retrieve path from API class
schema = self.api.result_schema()
schema.context['callname'] = callname
self.callback(schema.load(result), self.context) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def excel_key(index):
"""create a key for index by converting index into a base-26 number, using A-Z as the characters.""" |
X = lambda n: ~n and X((n // 26)-1) + chr(65 + (n % 26)) or ''
return X(int(index)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def drop_bad_characters(text):
"""Takes a text and drops all non-printable and non-ascii characters and also any whitespace characters that aren't space. :arg str text: the text to fix :returns: text with all bad characters dropped """ |
# Strip all non-ascii and non-printable characters
text = ''.join([c for c in text if c in ALLOWED_CHARS])
return text |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_source_file(source_file):
"""Parses a source file thing and returns the file name Example: 'js/src/jit/MIR.h' :arg str source_file: the source file ("file") from a stack frame :returns: the filename or ``None`` if it couldn't determine one """ |
if not source_file:
return None
vcsinfo = source_file.split(':')
if len(vcsinfo) == 4:
# These are repositories or cloud file systems (e.g. hg, git, s3)
vcstype, root, vcs_source_file, revision = vcsinfo
return vcs_source_file
if len(vcsinfo) == 2:
# These are directories on someone's Windows computer and vcstype is a
# file system (e.g. "c:", "d:", "f:")
vcstype, vcs_source_file = vcsinfo
return vcs_source_file
if source_file.startswith('/'):
# These are directories on OSX or Linux
return source_file
# We have no idea what this is, so return None
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 _is_exception(exceptions, before_token, after_token, token):
"""Predicate for whether the open token is in an exception context :arg exceptions: list of strings or None :arg before_token: the text of the function up to the token delimiter :arg after_token: the text of the function after the token delimiter :arg token: the token (only if we're looking at a close delimiter :returns: bool """ |
if not exceptions:
return False
for s in exceptions:
if before_token.endswith(s):
return True
if s in token:
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 collapse( function, open_string, close_string, replacement='', exceptions=None, ):
"""Collapses the text between two delimiters in a frame function value This collapses the text between two delimiters and either removes the text altogether or replaces it with a replacement string. There are certain contexts in which we might not want to collapse the text between two delimiters. These are denoted as "exceptions" and collapse will check for those exception strings occuring before the token to be replaced or inside the token to be replaced. Before:: IPC::ParamTraits<nsTSubstring<char> >::Write(IPC::Message *,nsTSubstring<char> const &) ^ ^ open token exception string occurring before open token Inside:: <rayon_core::job::HeapJob<BODY> as rayon_core::job::Job>::execute ^ ^^^^ exception string inside token open token :arg function: the function value from a frame to collapse tokens in :arg open_string: the open delimiter; e.g. ``(`` :arg close_string: the close delimiter; e.g. ``)`` :arg replacement: what to replace the token with; e.g. ``<T>`` :arg exceptions: list of strings denoting exceptions where we don't want to collapse the token :returns: new function string with tokens collapsed """ |
collapsed = []
open_count = 0
open_token = []
for i, char in enumerate(function):
if not open_count:
if char == open_string and not _is_exception(exceptions, function[:i], function[i + 1:], ''): # noqa
open_count += 1
open_token = [char]
else:
collapsed.append(char)
else:
if char == open_string:
open_count += 1
open_token.append(char)
elif char == close_string:
open_count -= 1
open_token.append(char)
if open_count == 0:
token = ''.join(open_token)
if _is_exception(exceptions, function[:i], function[i + 1:], token):
collapsed.append(''.join(open_token))
else:
collapsed.append(replacement)
open_token = []
else:
open_token.append(char)
if open_count:
token = ''.join(open_token)
if _is_exception(exceptions, function[:i], function[i + 1:], token):
collapsed.append(''.join(open_token))
else:
collapsed.append(replacement)
return ''.join(collapsed) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def drop_prefix_and_return_type(function):
"""Takes the function value from a frame and drops prefix and return type For example:: static void * Allocator<MozJemallocBase>::malloc(unsigned __int64) ^ ^^^^^^ return type prefix This gets changes to this:: Allocator<MozJemallocBase>::malloc(unsigned __int64) This tokenizes on space, but takes into account types, generics, traits, function arguments, and other parts of the function signature delimited by things like `', <>, {}, [], and () for both C/C++ and Rust. After tokenizing, this returns the last token since that's comprised of the function name and its arguments. :arg function: the function value in a frame to drop bits from :returns: adjusted function value """ |
DELIMITERS = {
'(': ')',
'{': '}',
'[': ']',
'<': '>',
'`': "'"
}
OPEN = DELIMITERS.keys()
CLOSE = DELIMITERS.values()
# The list of tokens accumulated so far
tokens = []
# Keeps track of open delimiters so we can match and close them
levels = []
# The current token we're building
current = []
for i, char in enumerate(function):
if char in OPEN:
levels.append(char)
current.append(char)
elif char in CLOSE:
if levels and DELIMITERS[levels[-1]] == char:
levels.pop()
current.append(char)
else:
# This is an unmatched close.
current.append(char)
elif levels:
current.append(char)
elif char == ' ':
tokens.append(''.join(current))
current = []
else:
current.append(char)
if current:
tokens.append(''.join(current))
while len(tokens) > 1 and tokens[-1].startswith(('(', '[clone')):
# It's possible for the function signature to have a space between
# the function name and the parenthesized arguments or [clone ...]
# thing. If that's the case, we join the last two tokens. We keep doing
# that until the last token is nice.
#
# Example:
#
# somefunc (int arg1, int arg2)
# ^
# somefunc(int arg1, int arg2) [clone .cold.111]
# ^
# somefunc(int arg1, int arg2) [clone .cold.111] [clone .cold.222]
# ^ ^
tokens = tokens[:-2] + [' '.join(tokens[-2:])]
return tokens[-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 shutdown(self):
'Close all peer connections and stop listening for new ones'
log.info("shutting down")
for peer in self._dispatcher.peers.values():
peer.go_down(reconnect=False)
if self._listener_coro:
backend.schedule_exception(
errors._BailOutOfListener(), self._listener_coro)
if self._udp_listener_coro:
backend.schedule_exception(
errors._BailOutOfListener(), self._udp_listener_coro) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def accept_publish(
self, service, mask, value, method, handler=None, schedule=False):
'''Set a handler for incoming publish messages
:param service: the incoming message must have this service
:type service: anything hash-able
:param mask:
value to be bitwise-and'ed against the incoming id, the result of
which must mask the 'value' param
:type mask: int
:param value:
the result of `routing_id & mask` must match this in order to
trigger the handler
:type value: int
:param method: the method name
:type method: string
:param handler:
the function that will be called on incoming matching messages
:type handler: callable
:param schedule:
whether to schedule a separate greenlet running ``handler`` for
each matching message. default ``False``.
:type schedule: bool
:raises:
- :class:`ImpossibleSubscription
<junction.errors.ImpossibleSubscription>` if there is no routing
ID which could possibly match the mask/value pair
- :class:`OverlappingSubscription
<junction.errors.OverlappingSubscription>` if a prior publish
registration that overlaps with this one (there is a
service/method/routing id that would match *both* this *and* a
previously-made registration).
'''
# support @hub.accept_publish(serv, mask, val, meth) decorator usage
if handler is None:
return lambda h: self.accept_publish(
service, mask, value, method, h, schedule)
log.info("accepting publishes%s %r" % (
" scheduled" if schedule else "",
(service, (mask, value), method),))
self._dispatcher.add_local_subscription(const.MSG_TYPE_PUBLISH,
service, mask, value, method, handler, schedule)
return handler |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def unsubscribe_publish(self, service, mask, value):
'''Remove a publish subscription
:param service: the service of the subscription to remove
:type service: anything hash-able
:param mask: the mask of the subscription to remove
:type mask: int
:param value: the value in the subscription to remove
:type value: int
:returns:
a boolean indicating whether the subscription was there (True) and
removed, or not (False)
'''
log.info("unsubscribing from publish %r" % (
(service, (mask, value)),))
return self._dispatcher.remove_local_subscription(
const.MSG_TYPE_PUBLISH, service, mask, 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 accept_rpc(self, service, mask, value, method,
handler=None, schedule=True):
'''Set a handler for incoming RPCs
:param service: the incoming RPC must have this service
:type service: anything hash-able
:param mask:
value to be bitwise-and'ed against the incoming id, the result of
which must mask the 'value' param
:type mask: int
:param value:
the result of `routing_id & mask` must match this in order to
trigger the handler
:type value: int
:param method: the method name to trigger handler
:type method: string
:param handler:
the function that will be called on incoming matching RPC requests
:type handler: callable
:param schedule:
whether to schedule a separate greenlet running ``handler`` for
each matching message. default ``True``.
:type schedule: bool
:raises:
- :class:`ImpossibleSubscription
<junction.errors.ImpossibleSubscription>` if there is no routing
ID which could possibly match the mask/value pair
- :class:`OverlappingSubscription
<junction.errors.OverlappingSubscription>` if a prior rpc
registration that overlaps with this one (there is a
service/method/routing id that would match *both* this *and* a
previously-made registration).
'''
# support @hub.accept_rpc(serv, mask, val, meth) decorator usage
if handler is None:
return lambda h: self.accept_rpc(
service, mask, value, method, h, schedule)
log.info("accepting RPCs%s %r" % (
" scheduled" if schedule else "",
(service, (mask, value), method),))
self._dispatcher.add_local_subscription(const.MSG_TYPE_RPC_REQUEST,
service, mask, value, method, handler, schedule)
return handler |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def unsubscribe_rpc(self, service, mask, value):
'''Remove a rpc subscription
:param service: the service of the subscription to remove
:type service: anything hash-able
:param mask: the mask of the subscription to remove
:type mask: int
:param value: the value in the subscription to remove
:type value: int
:param handler: the handler function of the subscription to remove
:type handler: callable
:returns:
a boolean indicating whether the subscription was there (True) and
removed, or not (False)
'''
log.info("unsubscribing from RPC %r" % ((service, (mask, value)),))
return self._dispatcher.remove_local_subscription(
const.MSG_TYPE_RPC_REQUEST, service, mask, 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 rpc(self, service, routing_id, method, args=None, kwargs=None,
timeout=None, broadcast=False):
'''Send an RPC request and return the corresponding response
This will block waiting until the response has been received.
:param service: the service name (the routing top level)
:type service: anything hash-able
:param routing_id:
The id used for routing within the registered handlers of the
service.
:type routing_id: int
:param method: the method name to call
:type method: string
:param args:
The positional arguments to send along with the request. If the
first argument is a generator, the request will be sent in chunks
:ref:`(more info) <chunked-messages>`.
:type args: tuple
:param kwargs: keyword arguments to send along with the request
:type kwargs: dict
:param timeout:
maximum time to wait for a response in seconds. with None, there is
no timeout.
:type timeout: float or None
:param broadcast:
if ``True``, send to every peer with a matching subscription
:type broadcast: bool
:returns:
a list of the objects returned by the RPC's targets. these could be
of any serializable type.
:raises:
- :class:`Unroutable <junction.errors.Unroutable>` if no peers are
registered to receive the message
- :class:`WaitTimeout <junction.errors.WaitTimeout>` if a timeout
was provided and it expires
'''
rpc = self.send_rpc(service, routing_id, method,
args or (), kwargs or {}, broadcast)
return rpc.get(timeout) |
<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 up the hub's server, and have it start initiating connections"
log.info("starting")
self._listener_coro = backend.greenlet(self._listener)
self._udp_listener_coro = backend.greenlet(self._udp_listener)
backend.schedule(self._listener_coro)
backend.schedule(self._udp_listener_coro)
for addr in self._peers:
self.add_peer(addr) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(argv=None):
"""Takes crash data via args and generates a Socorro signature """ |
parser = argparse.ArgumentParser(description=DESCRIPTION, epilog=EPILOG)
parser.add_argument(
'-v', '--verbose', help='increase output verbosity', action='store_true'
)
parser.add_argument(
'--format', help='specify output format: csv, text (default)'
)
parser.add_argument(
'--different-only', dest='different', action='store_true',
help='limit output to just the signatures that changed',
)
parser.add_argument(
'crashids', metavar='crashid', nargs='*', help='crash id to generate signatures for'
)
if argv is None:
args = parser.parse_args()
else:
args = parser.parse_args(argv)
if args.format == 'csv':
outputter = CSVOutput
else:
outputter = TextOutput
api_token = os.environ.get('SOCORRO_API_TOKEN', '')
generator = SignatureGenerator()
if args.crashids:
crashids_iterable = args.crashids
elif not sys.stdin.isatty():
# If a script is piping to this script, then isatty() returns False. If
# there is no script piping to this script, then isatty() returns True
# and if we do list(sys.stdin), it'll block waiting for input.
crashids_iterable = list(sys.stdin)
else:
crashids_iterable = []
if not crashids_iterable:
parser.print_help()
return 0
with outputter() as out:
for crash_id in crashids_iterable:
crash_id = crash_id.strip()
resp = fetch('/RawCrash/', crash_id, api_token)
if resp.status_code == 404:
out.warning('%s: does not exist.' % crash_id)
continue
if resp.status_code == 429:
out.warning('API rate limit reached. %s' % resp.content)
# FIXME(willkg): Maybe there's something better we could do here. Like maybe wait a
# few minutes.
return 1
if resp.status_code == 500:
out.warning('HTTP 500: %s' % resp.content)
continue
raw_crash = resp.json()
# If there's an error in the raw crash, then something is wrong--probably with the API
# token. So print that out and exit.
if 'error' in raw_crash:
out.warning('Error fetching raw crash: %s' % raw_crash['error'])
return 1
resp = fetch('/ProcessedCrash/', crash_id, api_token)
if resp.status_code == 404:
out.warning('%s: does not have processed crash.' % crash_id)
continue
if resp.status_code == 429:
out.warning('API rate limit reached. %s' % resp.content)
# FIXME(willkg): Maybe there's something better we could do here. Like maybe wait a
# few minutes.
return 1
if resp.status_code == 500:
out.warning('HTTP 500: %s' % resp.content)
continue
processed_crash = resp.json()
# If there's an error in the processed crash, then something is wrong--probably with the
# API token. So print that out and exit.
if 'error' in processed_crash:
out.warning('Error fetching processed crash: %s' % processed_crash['error'])
return 1
old_signature = processed_crash['signature']
crash_data = convert_to_crash_data(raw_crash, processed_crash)
result = generator.generate(crash_data)
if not args.different or old_signature != result.signature:
out.data(crash_id, old_signature, result, args.verbose) |
<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_result(self, return_code, output, service_description='', time_stamp=0, specific_servers=None):
'''
Send result to the Skinken WS
'''
if time_stamp == 0:
time_stamp = int(time.time())
if specific_servers == None:
specific_servers = self.servers
else:
specific_servers = set(self.servers).intersection(specific_servers)
for server in specific_servers:
post_data = {}
post_data['time_stamp'] = time_stamp
post_data['host_name'] = self.servers[server]['custom_fqdn']
post_data['service_description'] = service_description
post_data['return_code'] = return_code
post_data['output'] = output
if self.servers[server]['availability']:
url = '%s://%s:%s%s' % (self.servers[server]['protocol'],
self.servers[server]['host'],
self.servers[server]['port'],
self.servers[server]['uri'])
auth = (self.servers[server]['username'],
self.servers[server]['password'])
try:
response = requests.post(url,
auth=auth,
headers=self.http_headers,
verify=self.servers[server]['verify'],
timeout=self.servers[server]['timeout'],
data=post_data)
if response.status_code == 400:
LOG.error("[ws_shinken][%s]: HTTP status: %s - The content of the WebService call is incorrect",
server,
response.status_code)
elif response.status_code == 401:
LOG.error("[ws_shinken][%s]: HTTP status: %s - You must provide an username and password",
server,
response.status_code)
elif response.status_code == 403:
LOG.error("[ws_shinken][%s]: HTTP status: %s - The username or password is wrong",
server,
response.status_code)
elif response.status_code != 200:
LOG.error("[ws_shinken][%s]: HTTP status: %s", server, response.status_code)
except (requests.ConnectionError, requests.Timeout), error:
self.servers[server]['availability'] = False
LOG.error(error)
else:
LOG.error("[ws_shinken][%s]: Data not sent, server is unavailable", server)
if self.servers[server]['availability'] == False and self.servers[server]['cache'] == True:
self.servers[server]['csv'].writerow(post_data)
LOG.info("[ws_shinken][%s]: Data cached", server) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def close_cache(self):
'''
Close cache of WS Shinken
'''
# Close all WS_Shinken cache files
for server in self.servers:
if self.servers[server]['cache'] == True:
self.servers[server]['file'].close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def makename(package, module):
"""Join package and module with a dot. Package or Module can be empty. :param package: the package name :type package: :class:`str` :param module: the module name :type module: :class:`str` :returns: the joined name :rtype: :class:`str` :raises: :class:`AssertionError`, if both package and module are empty """ |
# Both package and module can be None/empty.
assert package or module, "Specify either package or module"
if package:
name = package
if module:
name += '.' + module
else:
name = module
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 import_name(app, name):
"""Import the given name and return name, obj, parent, mod_name :param name: name to import :type name: str :returns: the imported object or None :rtype: object | None :raises: None """ |
try:
logger.debug('Importing %r', name)
name, obj = autosummary.import_by_name(name)[:2]
logger.debug('Imported %s', obj)
return obj
except ImportError as e:
logger.warn("Jinjapidoc failed to import %r: %s", name, 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 get_members(app, mod, typ, include_public=None):
"""Return the members of mod of the given type :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param mod: the module with members :type mod: module :param typ: the typ, ``'class'``, ``'function'``, ``'exception'``, ``'data'``, ``'members'`` :type typ: str :param include_public: list of private members to include to publics :type include_public: list | None :returns: None :rtype: None :raises: None """ |
def include_here(x):
"""Return true if the member should be included in mod.
A member will be included if it is declared in this module or package.
If the `jinjaapidoc_include_from_all` option is `True` then the member
can also be included if it is listed in `__all__`.
:param x: The member
:type x: A class, exception, or function.
:returns: True if the member should be included in mod. False otherwise.
:rtype: bool
"""
return (x.__module__ == mod.__name__ or (include_from_all and x.__name__ in all_list))
all_list = getattr(mod, '__all__', [])
include_from_all = app.config.jinjaapi_include_from_all
include_public = include_public or []
tests = {'class': lambda x: inspect.isclass(x) and not issubclass(x, BaseException) and include_here(x),
'function': lambda x: inspect.isfunction(x) and include_here(x),
'exception': lambda x: inspect.isclass(x) and issubclass(x, BaseException) and include_here(x),
'data': lambda x: not inspect.ismodule(x) and not inspect.isclass(x) and not inspect.isfunction(x),
'members': lambda x: True}
items = []
for name in dir(mod):
i = getattr(mod, name)
inspect.ismodule(i)
if tests.get(typ, lambda x: False)(i):
items.append(name)
public = [x for x in items
if x in include_public or not x.startswith('_')]
logger.debug('Got members of %s of type %s: public %s and %s', mod, typ, public, items)
return public, items |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_context(app, package, module, fullname):
"""Return a dict for template rendering Variables: * :package: The top package * :module: the module * :fullname: package.module * :subpkgs: packages beneath module * :submods: modules beneath module * :classes: public classes in module * :allclasses: public and private classes in module * :exceptions: public exceptions in module * :allexceptions: public and private exceptions in module * :functions: public functions in module * :allfunctions: public and private functions in module * :data: public data in module * :alldata: public and private data in module * :members: dir(module) :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param package: the parent package name :type package: str :param module: the module name :type module: str :param fullname: package.module :type fullname: str :returns: a dict with variables for template rendering :rtype: :class:`dict` :raises: None """ |
var = {'package': package,
'module': module,
'fullname': fullname}
logger.debug('Creating context for: package %s, module %s, fullname %s', package, module, fullname)
obj = import_name(app, fullname)
if not obj:
for k in ('subpkgs', 'submods', 'classes', 'allclasses',
'exceptions', 'allexceptions', 'functions', 'allfunctions',
'data', 'alldata', 'memebers'):
var[k] = []
return var
var['subpkgs'] = get_subpackages(app, obj)
var['submods'] = get_submodules(app, obj)
var['classes'], var['allclasses'] = get_members(app, obj, 'class')
var['exceptions'], var['allexceptions'] = get_members(app, obj, 'exception')
var['functions'], var['allfunctions'] = get_members(app, obj, 'function')
var['data'], var['alldata'] = get_members(app, obj, 'data')
var['members'] = get_members(app, obj, 'members')
logger.debug('Created context: %s', var)
return var |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate(app, src, dest, exclude=[], followlinks=False, force=False, dryrun=False, private=False, suffix='rst', template_dirs=None):
"""Generage the rst files Raises an :class:`OSError` if the source path is not a directory. :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param src: path to python source files :type src: :class:`str` :param dest: output directory :type dest: :class:`str` :param exclude: list of paths to exclude :type exclude: :class:`list` :param followlinks: follow symbolic links :type followlinks: :class:`bool` :param force: overwrite existing files :type force: :class:`bool` :param dryrun: do not create any files :type dryrun: :class:`bool` :param private: include \"_private\" modules :type private: :class:`bool` :param suffix: file suffix :type suffix: :class:`str` :param template_dirs: directories to search for user templates :type template_dirs: None | :class:`list` :returns: None :rtype: None :raises: OSError """ |
suffix = suffix.strip('.')
if not os.path.isdir(src):
raise OSError("%s is not a directory" % src)
if not os.path.isdir(dest) and not dryrun:
os.makedirs(dest)
src = os.path.normpath(os.path.abspath(src))
exclude = normalize_excludes(exclude)
loader = make_loader(template_dirs)
env = make_environment(loader)
recurse_tree(app, env, src, dest, exclude, followlinks, force, dryrun, private, suffix) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(app):
"""Parse the config of the app and initiate the generation process :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :returns: None :rtype: None :raises: None """ |
c = app.config
src = c.jinjaapi_srcdir
if not src:
return
suffix = "rst"
out = c.jinjaapi_outputdir or app.env.srcdir
if c.jinjaapi_addsummarytemplate:
tpath = pkg_resources.resource_filename(__package__, AUTOSUMMARYTEMPLATE_DIR)
c.templates_path.append(tpath)
tpath = pkg_resources.resource_filename(__package__, TEMPLATE_DIR)
c.templates_path.append(tpath)
prepare_dir(app, out, not c.jinjaapi_nodelete)
generate(app, src, out,
exclude=c.jinjaapi_exclude_paths,
force=c.jinjaapi_force,
followlinks=c.jinjaapi_followlinks,
dryrun=c.jinjaapi_dryrun,
private=c.jinjaapi_includeprivate,
suffix=suffix,
template_dirs=c.templates_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 _isclose(obja, objb, rtol=1e-05, atol=1e-08):
"""Return floating point equality.""" |
return abs(obja - objb) <= (atol + rtol * abs(objb)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _isreal(obj):
""" Determine if an object is a real number. Both Python standard data types and Numpy data types are supported. :param obj: Object :type obj: any :rtype: boolean """ |
# pylint: disable=W0702
if (obj is None) or isinstance(obj, bool):
return False
try:
cond = (int(obj) == obj) or (float(obj) == obj)
except:
return False
return cond |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _no_exp(number):
r""" Convert a number to a string without using scientific notation. :param number: Number to convert :type number: integer or float :rtype: string :raises: RuntimeError (Argument \`number\` is not valid) """ |
if isinstance(number, bool) or (not isinstance(number, (int, float))):
raise RuntimeError("Argument `number` is not valid")
mant, exp = _to_scientific_tuple(number)
if not exp:
return str(number)
floating_mant = "." in mant
mant = mant.replace(".", "")
if exp < 0:
return "0." + "0" * (-exp - 1) + mant
if not floating_mant:
return mant + "0" * exp + (".0" if isinstance(number, float) else "")
lfpart = len(mant) - 1
if lfpart < exp:
return (mant + "0" * (exp - lfpart)).rstrip(".")
return mant |
<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_scientific_tuple(number):
r""" Return mantissa and exponent of a number expressed in scientific notation. Full precision is maintained if the number is represented as a string. :param number: Number :type number: integer, float or string :rtype: Tuple whose first item is the mantissa (*string*) and the second item is the exponent (*integer*) of the number when expressed in scientific notation :raises: RuntimeError (Argument \`number\` is not valid) """ |
# pylint: disable=W0632
if isinstance(number, bool) or (not isinstance(number, (int, float, str))):
raise RuntimeError("Argument `number` is not valid")
convert = not isinstance(number, str)
# Detect zero and return, simplifies subsequent algorithm
if (convert and (not number)) or (
(not convert) and (not number.strip("0").strip("."))
):
return ("0", 0)
# Break down number into its components, use Decimal type to
# preserve resolution:
# sign : 0 -> +, 1 -> -
# digits: tuple with digits of number
# exp : exponent that gives null fractional part
sign, digits, exp = Decimal(str(number) if convert else number).as_tuple()
mant = (
"{sign}{itg}.{frac}".format(
sign="-" if sign else "",
itg=digits[0],
frac="".join(str(item) for item in digits[1:]),
)
.rstrip("0")
.rstrip(".")
)
exp += len(digits) - 1
return (mant, exp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normalize(value, series, offset=0):
r""" Scale a value to the range defined by a series. :param value: Value to normalize :type value: number :param series: List of numbers that defines the normalization range :type series: list :param offset: Normalization offset, i.e. the returned value will be in the range [**offset**, 1.0] :type offset: number :rtype: number :raises: * RuntimeError (Argument \`offset\` is not valid) * RuntimeError (Argument \`series\` is not valid) * RuntimeError (Argument \`value\` is not valid) * ValueError (Argument \`offset\` has to be in the [0.0, 1.0] range) * ValueError (Argument \`value\` has to be within the bounds of the argument \`series\`) For example:: 0.5 0.75 """ |
if not _isreal(value):
raise RuntimeError("Argument `value` is not valid")
if not _isreal(offset):
raise RuntimeError("Argument `offset` is not valid")
try:
smin = float(min(series))
smax = float(max(series))
except:
raise RuntimeError("Argument `series` is not valid")
value = float(value)
offset = float(offset)
if not 0 <= offset <= 1:
raise ValueError("Argument `offset` has to be in the [0.0, 1.0] range")
if not smin <= value <= smax:
raise ValueError(
"Argument `value` has to be within the bounds of argument `series`"
)
return offset + ((1.0 - offset) * (value - smin) / (smax - smin)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def per(arga, argb, prec=10):
r""" Calculate percentage difference between numbers. If only two numbers are given, the percentage difference between them is computed. If two sequences of numbers are given (either two lists of numbers or Numpy vectors), the element-wise percentage difference is computed. If any of the numbers in the arguments is zero the value returned is the maximum floating-point number supported by the Python interpreter. :param arga: First number, list of numbers or Numpy vector :type arga: float, integer, list of floats or integers, or Numpy vector of floats or integers :param argb: Second number, list of numbers or or Numpy vector :type argb: float, integer, list of floats or integers, or Numpy vector of floats or integers :param prec: Maximum length of the fractional part of the result :type prec: integer :rtype: Float, list of floats or Numpy vector, depending on the arguments type :raises: * RuntimeError (Argument \`arga\` is not valid) * RuntimeError (Argument \`argb\` is not valid) * RuntimeError (Argument \`prec\` is not valid) * TypeError (Arguments are not of the same type) """ |
# pylint: disable=C0103,C0200,E1101,R0204
if not isinstance(prec, int):
raise RuntimeError("Argument `prec` is not valid")
a_type = 1 * _isreal(arga) + 2 * (isiterable(arga) and not isinstance(arga, str))
b_type = 1 * _isreal(argb) + 2 * (isiterable(argb) and not isinstance(argb, str))
if not a_type:
raise RuntimeError("Argument `arga` is not valid")
if not b_type:
raise RuntimeError("Argument `argb` is not valid")
if a_type != b_type:
raise TypeError("Arguments are not of the same type")
if a_type == 1:
arga, argb = float(arga), float(argb)
num_min, num_max = min(arga, argb), max(arga, argb)
return (
0
if _isclose(arga, argb)
else (
sys.float_info.max
if _isclose(num_min, 0.0)
else round((num_max / num_min) - 1, prec)
)
)
# Contortions to handle lists and Numpy arrays without explicitly
# having to import numpy
ret = copy.copy(arga)
for num, (x, y) in enumerate(zip(arga, argb)):
if not _isreal(x):
raise RuntimeError("Argument `arga` is not valid")
if not _isreal(y):
raise RuntimeError("Argument `argb` is not valid")
x, y = float(x), float(y)
ret[num] = (
0
if _isclose(x, y)
else (
sys.float_info.max
if _isclose(x, 0.0) or _isclose(y, 0)
else (round((max(x, y) / min(x, y)) - 1, prec))
)
)
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wscall(self, method, query=None, callback=None):
"""Submit a request on the websocket""" |
if callback is None:
self.sock.emit(method, query)
else:
self.sock.emitack(method, query, callback) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect_channels(self, channels):
"""Connect the provided channels""" |
self.log.info(f"Connecting to channels...")
for chan in channels:
chan.connect(self.sock)
self.log.info(f"\t{chan.channel}") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _on_set_auth(self, sock, token):
"""Set Auth request received from websocket""" |
self.log.info(f"Token received: {token}")
sock.setAuthtoken(token) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _on_auth(self, sock, authenticated):
# pylint: disable=unused-argument """Message received from websocket""" |
def ack(eventname, error, data): # pylint: disable=unused-argument
"""Ack"""
if error:
self.log.error(f"""OnAuth: {error}""")
else:
self.connect_channels(self.channels)
self.post_conn_cb()
sock.emitack("auth", self.creds, ack) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.