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 load_corpus(self, path, config):
'''Load a dialogue corpus; eventually, support pickles and potentially other formats'''
# use the default dataset if no path is provided
# TODO -- change this to use a pre-saved dataset
if path == '':
path = self.default_path_to_corpus
... |
<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_dataset_prepare_args(self, parser):
'''Only invoked conditionally if subcommand is 'prepare' '''
parser.add_argument('-f', '--configuration', dest='config', default=DEFAULT_USER_CONFIG_PATH,
help='the path to the configuration file to use -- ./config.yaml by default'... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def executeBatch(cursor, sql, regex=r"(?mx) ([^';]* (?:'[^']*'[^';]*)*)", comment_regex=r"(?mx) (?:^\s*$)|(?:--.*$)"):
""" Takes a SQL file and executes it as ma... |
# First, strip comments
sql = "\n".join([x.strip().replace("%", "%%") for x in re.split(comment_regex, sql) if x.strip()])
# Stored procedures don't work with the above regex because many of them are
# made up multiple sql statements each delimited with a single ;
# where the regexes assume each 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 howToMigrate(self, fromVersion, toVersion=None):
"""Given a starting version and an ending version returns filenames of all the migrations in that range, exc... |
# slice notation [start:end:step]
# by adding a step of 1 we make a slice from 0:0 be empty
# rather than containing the whole list.
if toVersion is not None:
return self.migrations[fromVersion:toVersion:1]
else:
return self.migrations[fromVersion::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 runSql(self, migrationName, version):
""" Given a migration name and version lookup the sql file and run it. """ |
sys.stdout.write("Running migration %s to version %s: ..."%(migrationName, version))
sqlPath = os.path.join(self.migrationDirectory, migrationName)
sql = open(sqlPath, "r").read()
try:
if self.session.is_active:
print "session is active"
self.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_event(self, event):
"""Writes an ``Event`` object to Splunk. :param event: An ``Event`` object. """ |
if not self.header_written:
self._out.write("<stream>")
self.header_written = True
event.write_to(self._out) |
<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, severity, message):
"""Logs messages about the state of this modular input to Splunk. These messages will show up in Splunk's internal logs. :param... |
self._err.write("%s %s\n" % (severity, message))
self._err.flush() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def TxKazooClient(reactor, pool, client):
"""Create a client for txkazoo. :param twisted.internet.interfaces.IReactorThreads reactor: The reactor used to interac... |
make_thimble = partial(Thimble, reactor, pool)
wrapper = _RunCallbacksInReactorThreadWrapper(reactor, client)
client_thimble = make_thimble(wrapper, _blocking_client_methods)
def _Lock(path, identifier=None):
"""Return a wrapped :class:`kazoo.recipe.lock.Lock` for this client."""
lock... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_listener(self, listener):
"""Add the given listener to the wrapped client. The listener will be wrapped, so that it will be called in the reactor thread.... |
internal_listener = partial(self._call_in_reactor_thread, listener)
self._internal_listeners[listener] = internal_listener
return self._client.add_listener(internal_listener) |
<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_listener(self, listener):
"""Remove the given listener from the wrapped client. :param listener: A listener previously passed to :meth:`add_listener`.... |
internal_listener = self._internal_listeners.pop(listener)
return self._client.remove_listener(internal_listener) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _wrapped_method_with_watch_fn(self, f, *args, **kwargs):
"""A wrapped method with a watch function. When this method is called, it will call the underlying m... |
bound_args = signature(f).bind(*args, **kwargs)
orig_watch = bound_args.arguments.get("watch")
if orig_watch is not None:
wrapped_watch = partial(self._call_in_reactor_thread, orig_watch)
wrapped_watch = wraps(orig_watch)(wrapped_watch)
bound_args.arguments[... |
<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_in_reactor_thread(self, f, *args, **kwargs):
"""Call the given function with args in the reactor thread.""" |
self._reactor.callFromThread(f, *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 converse(self):
'''The 'converse' subcommand'''
# Initialize the converse subcommand's argparser
parser = argparse.ArgumentParser(description='Initiate a conversation with a trained dialogue model')
self.init_converse_args(parser)
# Parse the args we got
args = pars... |
<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_converse_args(self, parser):
'''Only invoked conditionally if subcommand is 'converse' '''
parser.add_argument('-f', '--configuration', dest='config', default=DEFAULT_USER_CONFIG_PATH,
help='the path to the configuration file to use -- ./config.yaml by default')
... |
<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_next_timestep(self, ts=None):
"""copy next frame into timestep""" |
if self.ts.frame >= self.n_frames-1:
raise IOError(errno.EIO, 'trying to go over trajectory limit')
if ts is None:
ts = self.ts
ts.frame += 1
self.zdock_inst._set_pose_num(ts.frame+1)
ts._pos = self.zdock_inst.static_mobile_copy_uni.trajectory.ts._pos
return ts |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def viterbi_alignment(es, fs, t, a):
'''
return
dictionary
e in es -> f in fs
'''
max_a = collections.defaultdict(float)
l_e = len(es)
l_f = len(fs)
for (j, e) in enumerate(es, 1):
current_max = (0, -1)
for (i, f) in enumerate(fs, 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 _make_marker_token(self, type_):
"""Make a token that has no content""" |
tok = Token(type_,
'',
self.line,
self.line_num,
self.start,
self.start)
return tok |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_nullable_map(value):
""" Converts JSON string into map object or returns null when conversion is not possible. :param value: the JSON string to convert. :... |
if value == None:
return None
# Parse JSON
try:
value = json.loads(value)
return RecursiveMapConverter.to_nullable_map(value)
except:
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 to_map_with_default(value, default_value):
""" Converts JSON string into map object or returns default value when conversion is not possible. :param value: t... |
result = JsonConverter.to_nullable_map(value)
return result if result != None else default_value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_project(self):
""" Generate the whole project. Returns True if at least one file has been generated, False otherwise.""" |
# checks needed properties
if not self.name or not self.destdir or \
not os.path.isdir(self.destdir):
raise ValueError("Empty or invalid property values: run with 'help' command")
_log("Generating project '%s'" % self.name)
_log("Destination directory is: '%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 __generate_tree(self, top, src, resources, models, ctrls, views, utils):
"""Creates directories and packages""" |
res = self.__mkdir(top)
for fn in (src, models, ctrls, views, utils): res = self.__mkpkg(fn) or res
res = self.__mkdir(resources) or res
res = self.__mkdir(os.path.join(resources, "ui", "builder")) or res
res = self.__mkdir(os.path.join(resources, "ui", "styles")) or 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 scp_put(self, src, dst):
"""Copy src file from local system to dst on remote system.""" |
cmd = [ 'scp',
'-B',
'-oStrictHostKeyChecking=no',
'-oUserKnownHostsFile=/dev/null',
'-oLogLevel=ERROR']
if self._key is not None:
cmd.extend(['-i', self._key])
cmd.append(src)
remote = ''
if self._user ... |
<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_group_by_id(self, group_id: str) -> typing.Optional['Group']: """ Gets a group by id Args: group_id: group id Returns: Group """ |
VALID_POSITIVE_INT.validate(group_id, 'get_group_by_id', exc=ValueError)
for group in self.groups:
if group.group_id == group_id:
return group
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 get_clients_groups(self) -> typing.Iterator['Group']: """ Gets all clients groups Returns: generator of Groups """ |
for group in self.groups:
if group.group_is_client_group:
yield group |
<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_group_by_name(self, group_name: str) -> typing.Optional['Group']: """ Gets a group from its name Args: group_name: Returns: Group """ |
VALID_STR.validate(group_name, 'get_group_by_name')
for group in self.groups:
if group.group_name == group_name:
return group
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 get_unit_by_name(self, unit_name: str) -> typing.Optional['BaseUnit']: """ Gets a unit from its name Args: unit_name: unit name Returns: """ |
VALID_STR.validate(unit_name, 'get_unit_by_name')
for unit in self.units:
if unit.unit_name == unit_name:
return unit
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 get_unit_by_id(self, unit_id: str) -> typing.Optional['BaseUnit']: """ Gets a unit from its ID Args: unit_id: unit id Returns: Unit """ |
VALID_POSITIVE_INT.validate(unit_id, 'get_unit_by_id')
for unit in self.units:
if unit.unit_id == unit_id:
return unit
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 units(self) -> typing.Iterator['BaseUnit']: """ Iterates over all units Returns: generator of Unit """ |
for group in self.groups:
for unit in group.units:
yield unit |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def groups(self) -> typing.Iterator['Group']: """ Iterates over all groups Returns: generator of Group """ |
for country in self.countries:
for group in country.groups:
yield group |
<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_country_by_name(self, country_name) -> 'Country': """ Gets a country in this coalition by its name Args: country_name: country name Returns: Country """ |
VALID_STR.validate(country_name, 'get_country_by_name', exc=ValueError)
if country_name not in self._countries_by_name.keys():
for country in self.countries:
if country.country_name == country_name:
return country
raise ValueError(country_nam... |
<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_country_by_id(self, country_id) -> 'Country': """ Gets a country in this coalition by its ID Args: country_id: country Id Returns: Country """ |
VALID_POSITIVE_INT.validate(country_id, 'get_country_by_id', exc=ValueError)
if country_id not in self._countries_by_id.keys():
for country in self.countries:
if country.country_id == country_id:
return country
raise ValueError(country_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 bundle_dir():
"""Handle resource management within an executable file.""" |
if frozen():
directory = sys._MEIPASS
else:
directory = os.path.dirname(os.path.abspath(stack()[1][1]))
if os.path.exists(directory):
return directory |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resource_path(relative):
"""Adjust path for executable use in executable file""" |
if hasattr(sys, "_MEIPASS"):
return os.path.join(sys._MEIPASS, relative)
return os.path.join(relative) |
<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_string(value):
""" Parses colon-separated list of descriptor fields and returns them as a Descriptor. :param value: colon-separated descriptor fields to... |
if value == None or len(value) == 0:
return None
tokens = value.split(":")
if len(tokens) != 5:
raise ConfigException(
None, "BAD_DESCRIPTOR", "Descriptor " + str(value) + " is in wrong format"
).with_details("descriptor", 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 value(self):
""" Fetch a random weighted choice """ |
choice = weighted_choice(self._responses)
# If the choice is a tuple, join the elements into a single mapped string
if isinstance(choice, tuple):
return ''.join(map(str, choice)).strip()
# Otherwise, return the choice itself as a string
return str(choice) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump(obj, name, path=None, ext="dat", overwrite=True, silent=False):
""" Dumps the object to disk with given name and extension. Optionally the path can be s... |
if path and os.path.isfile(path):
raise ValueException("Specified path is a file.")
filename = __get_filename(path, name, ext)
if not overwrite and os.path.exists(filename):
if not silent:
raise ValueException("Specified output filename already exists.")
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 load(name, path=None, ext="dat", silent=False):
""" Loads an object from file with given name and extension. Optionally the path can be specified as well. ""... |
filename = __get_filename(path, name, ext)
if not os.path.exists(filename):
if not silent:
raise ValueException("Specified input filename doesn't exist.")
return None
with open(filename, "rb") as f:
return pickle.load(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 standard_input():
"""Generator that yields lines from standard input.""" |
with click.get_text_stream("stdin") as stdin:
while stdin.readable():
line = stdin.readline()
if line:
yield line.strip().encode("utf-8") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cli(out_fmt, input, output):
"""Converts text.""" |
_input = StringIO()
for l in input:
try:
_input.write(str(l))
except TypeError:
_input.write(bytes(l, 'utf-8'))
_input = seria.load(_input)
_out = (_input.dump(out_fmt))
output.write(_out) |
<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(self):
''' Data decoded with the specified charset '''
pos = self.file.tell()
self.file.seek(0)
val = self.file.read()
self.file.seek(pos)
return val.decode(self.charset) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _violinplot(dataset, positions=None, vert=True, widths=0.5,
showmeans=False, showextrema=True, showmedians=False,
points=100, bw_method=None, ax=None):
'''Local version of the matplotlib violinplot.'''
if ax is None:
ax = plt.gca()
if positions is None:
positions = np.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 dir(suffix='', prefix='tmp', dir=None, force=True):
"""Create a temporary directory. A contextmanager that creates and returns a temporary directory, cleanin... |
name = tempfile.mkdtemp(suffix, prefix, dir)
try:
yield name
finally:
try:
if force:
shutil.rmtree(name)
else:
os.rmdir(name)
except OSError as e:
if e.errno != 2: # not found
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def file(mode='w+b', suffix='', prefix='tmp', dir=None, ignore_missing=False):
"""Create a temporary file. A contextmanager that creates and returns a named temp... |
# note: bufsize is not supported in Python3, try to prevent problems
# stemming from incorrect api usage
if isinstance(suffix, int):
raise ValueError('Passed an integer as suffix. Did you want to '
'specify the deprecated parameter `bufsize`?')
fp = tempfile.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 unix_socket(sock=None, socket_name='tmp.socket', close=True):
"""Create temporary unix socket. Creates and binds a temporary unix socket that will be closed ... |
sock = sock or socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
with dir() as dtmp:
addr = os.path.join(dtmp, socket_name)
sock.bind(addr)
try:
yield sock, addr
finally:
if close:
sock.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 load_config(self, path):
'''Load a configuration file; eventually, support dicts, .yaml, .csv, etc.'''
# if no path was provided, resort to defaults
if path == None:
print("Path to config was null; using defaults.")
return
if not os.path.exists(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 merge_config(self, user_config):
'''
Take a dictionary of user preferences and use them to update the default
data, model, and conversation configurations.
'''
# provisioanlly update the default configurations with the user preferences
temp_data_config = copy.deepcop... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def which(program):
""" A python implementation of which. https://stackoverflow.com/a/2969007 """ |
path_ext = [""]
ext_list = None
if sys.platform == "win32":
ext_list = [ext.lower() for ext in os.environ["PATHEXT"].split(";")]
def is_exe(fpath):
exe = os.path.isfile(fpath) and os.access(fpath, os.X_OK)
# search for executable under windows
if not exe:
i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def migrate(module=None):
""" Entrypoint to migrate the schema. For the moment only create tables. """ |
if not module:
#Parsing
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--service', type=str, help='Migrate the module', required=True,
dest='module')
args = parser.parse_args()
module = args.module
#1. Load settings
farine.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 execute(options):
"""execute the tool with given options.""" |
# Load the key in PKCS 12 format that you downloaded from the Google APIs
# Console when you created your Service account.
package_name = options['<package>']
source_directory = options['<output_dir>']
if options['upload'] is True:
upstream = True
else:
upstream = False
su... |
<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_credentials(credentials_file=None, service_email=None, service_key=None, scope='https://www.googleapis.com/auth/androidpublisher'):
""" Create Google ... |
credentials = None
if service_email is None and service_key is None:
print(credentials_file)
if credentials_file is None:
# try load file from env
key = 'PLAY_DELIVER_CREDENTIALS'
if key in os.environ:
credentials_file = os.environ[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 good_classmethod_decorator(decorator):
"""This decorator makes class method decorators behave well wrt to decorated class method names, doc, etc.""" |
def new_decorator(cls, f):
g = decorator(cls, f)
g.__name__ = f.__name__
g.__doc__ = f.__doc__
g.__dict__.update(f.__dict__)
return g
new_decorator.__name__ = decorator.__name__
new_decorator.__doc__ = decorator.__doc__
new_decorator.__dict__.update(dec... |
<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_descriptor_le(self, lineedit, tf):
"""Update the given line edit to show the descriptor that is stored in the index :param lineedit: the line edit to ... |
if tf:
descriptor = tf.descriptor
lineedit.setText(descriptor)
else:
lineedit.setText("") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _save_tfi(self, tfi, asset=False):
"""Save currently open scene with the information in the given taskfile info :param tfi: taskfile info :type tfi: :class:`... |
jbfile = JB_File(tfi)
self.create_dir(jbfile)
tf, note = self.create_db_entry(tfi)
try:
js = JukeboxSignals.get()
if asset:
js.before_save_asset.emit(jbfile, tf)
self.save_asset(jbfile, tf)
js.after_save_asset.emi... |
<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_dir(self, jbfile):
"""Create a dir for the given dirfile and display an error message, if it fails. :param jbfile: the jb file to make the directory f... |
try:
jbfile.create_directory()
except os.error:
self.statusbar.showMessage('Could not create path: %s' % jbfile.get_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 check_selection_for_save(self, task, releasetype, descriptor):
"""Emit warnings if the descriptor is None or the current file is of a different task. :param ... |
if not descriptor:
self.statusbar.showMessage("Please provide a descriptor!")
return False
try:
jukedj.validators.alphanum_vld(descriptor)
except ValidationError:
self.statusbar.showMessage("Descriptor contains characters other than alphanumerical... |
<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_db_entry(self, tfi):
"""Create a db entry for the given task file info :param tfi: the info for a TaskFile entry in the db :type tfi: :class:`jukeboxc... |
if tfi.task.department.assetflag:
comment = self.asset_comment_pte.toPlainText()
else:
comment = self.shot_comment_pte.toPlainText()
return tfi.create_db_entry(comment) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def closeEvent(self, event):
"""Send last file signal on close event :param event: The close event :type event: :returns: None :rtype: None :raises: None """ |
lf = self.browser.get_current_selection()
if lf:
self.last_file.emit(lf)
return super(GenesisWin, self).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 upload(client, source_dir):
"""Upload listing files in source_dir. folder herachy.""" |
print('')
print('upload store listings')
print('---------------------')
listings_folder = os.path.join(source_dir, 'listings')
langfolders = filter(os.path.isdir, list_dir_abspath(listings_folder))
for language_dir in langfolders:
language = os.path.basename(language_dir)
with ... |
<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(client, target_dir):
"""Download listing files from play and saves them into folder herachy.""" |
print('')
print('download store listings')
print('---------------------')
listings = client.list('listings')
for listing in listings:
path = os.path.join(target_dir, 'listings', listing['language'])
mkdir_p(path)
with open(os.path.join(path, 'listing.json'), 'w') as outfile:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def filter(self, **kwargs):
'''Assumes all the dict's items are hashable.
'''
# So we don't return anything more than once.
yielded = set()
dunder = '__'
filter_items = set()
for k, v in kwargs.items():
if dunder in k:
k, op = k.split(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy_ssh_keys_to_hosts(self, hosts, known_hosts=DEFAULT_KNOWN_HOSTS, dry=False):
""" Copy the SSH keys to the given hosts. :param hosts: the list of `Host` o... |
exceptions = [] # list of `CopySSHKeyError`
for host in hosts:
logger.info('[%s] Copy the SSH public key [%s]...', host.hostname, self.sshcopyid.pub_key)
if not dry:
try:
self.copy_ssh_keys_to_host(host, known_hosts=known_hosts)
... |
<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_fn(self, what, *args, **kwargs):
""" Lazy call init_adapter then call the function """ |
logger.debug('f_{0}:{1}{2}({3})'.format(
self.call_stack_level,
' ' * 4 * self.call_stack_level,
what,
arguments_as_string(args, kwargs)))
port, fn_name = self._what(what)
if port not in self['_initialized_ports']:
self._call_fn(port, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unpack_zipfile(filename):
"""Unpack a zipfile, using the names in the zip.""" |
with open(filename, "rb") as fzip:
z = zipfile.ZipFile(fzip)
for name in z.namelist():
print((" extracting {}".format(name)))
ensure_dirs(name)
z.extract(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 prog_iter(bounded_iterable, delta=0.01, line_size=50):
'''Wraps the provided sequence with an iterator that tracks its progress
on the console.
>>> for i in prog_iter(xrange(100)): 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 include(gset, elem, value=True):
"""Do whatever it takes to make ``elem in gset`` true. ['Lucy'] set(['Sky']) {'Diamonds': True} Works for sets (using ``add`... |
add = getattr(gset, 'add', None) # sets
if add is None: add = getattr(gset, 'append', None) # lists
if add is not None: add(elem)
else: # dicts
if not hasattr(gset, '__setitem__'):
raise Error("gset is not a supported container.")
gset[elem] = value
return elem |
<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_all(gset, elem):
"""Removes every occurrence of ``elem`` from ``gset``. Returns the number of times ``elem`` was removed. """ |
n = 0
while True:
try:
remove_once(gset, elem)
n = n + 1
except RemoveError:
return 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 flatten(iterable, check=is_iterable):
"""Produces a recursively flattened version of ``iterable`` ``check`` Recurses only if check(value) is true. """ |
for value in iterable:
if check(value):
for flat in flatten(value, check):
yield flat
else:
yield 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 xflatten(iterable, transform, check=is_iterable):
"""Apply a transform to iterable before flattening at each level.""" |
for value in transform(iterable):
if check(value):
for flat in xflatten(value, transform, check):
yield flat
else:
yield 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 flatten_once(iterable, check=is_iterable):
"""Flattens only the first level.""" |
for value in iterable:
if check(value):
for item in value:
yield item
else:
yield 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 join(iterable, sep):
"""Like str.join, but yields an iterable.""" |
i = 0
for i, item in enumerate(iterable):
if i == 0:
yield item
else:
yield sep
yield 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 stop_at(iterable, idx):
"""Stops iterating before yielding the specified idx.""" |
for i, item in enumerate(iterable):
if i == idx: return
yield 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 all_pairs(seq1, seq2=None):
"""Yields all pairs drawn from ``seq1`` and ``seq2``. If ``seq2`` is ``None``, ``seq2 = seq1``. ((0, 0), (0, 1), (0, 2), (0, 3), ... |
if seq2 is None: seq2 = seq1
for item1 in seq1:
for item2 in seq2:
yield (item1, item2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def padded_to_same_length(seq1, seq2, item=0):
"""Return a pair of sequences of the same length by padding the shorter sequence with ``item``. The padded sequenc... |
len1, len2 = len(seq1), len(seq2)
if len1 == len2:
return (seq1, seq2)
elif len1 < len2:
return (cons.ed(seq1, yield_n(len2-len1, item)), seq2)
else:
return (seq1, cons.ed(seq2, yield_n(len1-len2, 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 is_int_like(value):
"""Returns whether the value can be used as a standard integer. True False False False """ |
try:
if isinstance(value, int): return True
return int(value) == value and str(value).isdigit()
except:
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 is_float_like(value):
"""Returns whether the value acts like a standard float. True True False False """ |
try:
if isinstance(value, float): return True
return float(value) == value and not str(value).isdigit()
except:
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_symmetric(dict):
"""Makes the given dictionary symmetric. Values are assumed to be unique.""" |
for key, value in list(dict.items()):
dict[value] = key
return 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 fn_kwargs(callable):
"""Returns a dict with the kwargs from the provided function. Example """ |
fn = get_fn(callable)
(args, _, _, defaults) = _inspect.getargspec(fn)
if defaults is None: return { }
return dict(list(zip(reversed(args), reversed(defaults)))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fn_available_argcount(callable):
"""Returns the number of explicit non-keyword arguments that the callable can be called with. Bound methods are called with ... |
fn = get_fn_or_method(callable)
if _inspect.isfunction(fn):
return fn.__code__.co_argcount
else: # method
if fn.__self__ is None:
return fn.__func__.__code__.co_argcount
else:
return fn.__func__.__code__.co_argcount - 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 fn_minimum_argcount(callable):
"""Returns the minimum number of arguments that must be provided for the call to succeed.""" |
fn = get_fn(callable)
available_argcount = fn_available_argcount(callable)
try:
return available_argcount - len(fn.__defaults__)
except TypeError:
return available_argcount |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fn_signature(callable, argument_transform=(lambda name: name), default_transform=(lambda name, value: "%s=%s" % (name, repr(value))), vararg_transform=(lambda... |
signature = []
fn = get_fn(callable)
avail_ac = fn_available_argcount(fn)
kwargs = fn_kwargs(fn)
argnames = fn_argnames(fn)
for name in stop_at(argnames, avail_ac):
if name in kwargs:
signature.append(default_transform(name, kwargs[name]))
else:
signature... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decorator(d):
"""Creates a proper decorator. If the default for the first (function) argument is None, creates a See examples below. """ |
defaults = d.__defaults__
if defaults and defaults[0] is None:
# Can be applied as @decorator or @decorator(kwargs) because
# first argument is None
def decorate(fn=None, **kwargs):
if fn is None:
return _functools.partial(decorate, **kwargs)
else... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def memoize(fn=None):
"""Caches the result of the provided function.""" |
cache = { }
arg_hash_fn = fn_arg_hash_function(fn)
def decorated(*args, **kwargs):
try:
hash_ = arg_hash_fn(*args, **kwargs)
except TypeError:
return fn(*args, **kwargs)
try:
return cache[hash_]
except KeyError:
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 safe_setattr(obj, name, value):
"""Attempt to setattr but catch AttributeErrors.""" |
try:
setattr(obj, name, value)
return True
except AttributeError:
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 method_call_if_def(obj, attr_name, m_name, default, *args, **kwargs):
"""Calls the provided method if it is defined. Returns default if not defined. """ |
try:
attr = getattr(obj, attr_name)
except AttributeError:
return default
else:
return getattr(attr, m_name)(*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 call_on_if_def(obj, attr_name, callable, default, *args, **kwargs):
"""Calls the provided callable on the provided attribute of ``obj`` if it is defined. If ... |
try:
attr = getattr(obj, attr_name)
except AttributeError:
return default
else:
return callable(attr, *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 is_senior_subclass(obj, cls, testcls):
"""Determines whether the cls is the senior subclass of basecls for obj. The most senior subclass is the first class i... |
for base in obj.__class__.mro():
if base is cls:
return True
else:
if issubclass(base, testcls):
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 string_escape(string, delimiter='"'):
"""Turns special characters into escape sequences in the provided string. Supports both byte strings and unicode string... |
if isinstance(string, str):
escaped = string.encode("string-escape")
elif isinstance(string, str):
escaped = str(string.encode("unicode-escape"))
else:
raise Error("Unexpected string type.")
return delimiter + escape_quotes(escaped, delimiter) + delimiter |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def re_line_and_indentation(base_indentation, modifiers=(True, True)):
"""Returns a re matching newline + base_indentation. modifiers is a tuple, (include_first,... |
cache = re_line_and_indentation.cache[modifiers]
compiled = cache.get(base_indentation, None)
if compiled is None:
[prefix, suffix] = re_line_and_indentation.tuple[modifiers]
compiled = cache[modifiers] = \
_re.compile(prefix + base_indentation + suffix)
return compiled |
<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_base_indentation(code, include_start=False):
"""Heuristically extracts the base indentation from the provided code. Finds the smallest indentation follow... |
new_line_indentation = re_new_line_indentation[include_start].finditer(code)
new_line_indentation = tuple(m.groups(0)[0] for m in new_line_indentation)
if new_line_indentation:
return min(new_line_indentation, key=len)
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 fix_indentation(code, base_indentation=None, correct_indentation="", modifiers=(True, True)):
"""Replaces base_indentation at beginning of lines with correct... |
if base_indentation is None:
base_indentation = get_base_indentation(code, modifiers[0])
return re_line_and_indentation(base_indentation, modifiers).sub(
"\n" + correct_indentation, code) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def name(self):
"""The unique name of this object, relative to the parent.""" |
basename = self.basename
if basename is None:
return None
parent = self.Naming_parent
if parent is None:
return basename
else:
return parent.generate_unique_name(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 generate_unique_name(self, basename):
"""Generates a unique name for a child given a base name.""" |
counts = self.__counts
try:
count = counts[basename]
counts[basename] += 1
except KeyError:
count = 0
counts[basename] = 1
prefix = self.Naming_prefix
if count == 0:
name = prefix + basename
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_to_parent(self):
"""Adds this node to the parent's ``children`` collection if it exists.""" |
parent = self.parent
if parent is not None:
try:
children = parent.children
except AttributeError: pass
else:
include(children, self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_from_parent(self):
"""Removes this node from the parent's ``children`` collection if it exists.""" |
parent = self.parent
if parent is not None:
try:
children = parent.children
except AttributeError: pass
else:
remove_upto_once(children, self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iter_up(self, include_self=True):
"""Iterates up the tree to the root.""" |
if include_self: yield self
parent = self.parent
while parent is not None:
yield parent
try:
parent = parent.parent
except AttributeError:
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 getrec(self, name, include_self=True, *default):
"""Look up an attribute in the path to the root.""" |
for node in self.iter_up(include_self):
try:
return getattr(node, name)
except AttributeError: pass
if default:
return default[0]
else:
raise AttributeError(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 trigger_hook(self, name, *args, **kwargs):
"""Recursively call a method named ``name`` with the provided args and keyword args if defined.""" |
method = getattr(self, name, None)
if is_callable(method):
method(*args, **kwargs)
try:
children = self.children
except AttributeError:
return
else:
if children is not None:
for child in children:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _spawn_thread(self, target):
""" Create a thread """ |
t = Thread(target=target)
t.daemon = True
t.start()
return 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 join(self):
""" Wait for all current tasks to be finished """ |
self._jobs.join()
try:
return self._results, self._errors
finally:
self._clear() |
<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(exe, *argv):
""" Run a command, returning its output, or None if it fails. """ |
exes = which(exe)
if not exes:
returnValue(None)
stdout, stderr, value = yield getProcessOutputAndValue(
exes[0], argv, env=os.environ.copy()
)
if value:
returnValue(None)
returnValue(stdout.decode('utf-8').rstrip('\n')) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.