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 ensure_dir_does_not_exist(*args):
"""Ensures that the given directory does not exist.""" |
path = os.path.join(*args)
if os.path.isdir(path):
shutil.rmtree(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 find_static_library(library_name, library_path):
"""Given the raw name of a library in `library_name`, tries to find a static library with this name in the given `library_path`. `library_path` is automatically extended with common library directories on Linux and Mac OS X.""" |
variants = ["lib{0}.a", "{0}.a", "{0}.lib", "lib{0}.lib"]
if is_unix_like():
extra_libdirs = ["/usr/local/lib64", "/usr/local/lib",
"/usr/lib64", "/usr/lib", "/lib64", "/lib"]
else:
extra_libdirs = []
for path in extra_libdirs:
if path not in library_path and os.path.isdir(path):
library_path.append(path)
for path in library_path:
for variant in variants:
full_path = os.path.join(path, variant.format(library_name))
if os.path.isfile(full_path):
return full_path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_output(command):
"""Returns the output of a command returning a single line of output.""" |
p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
p.stdin.close()
p.stderr.close()
line=p.stdout.readline().strip()
p.wait()
if type(line).__name__ == "bytes":
line = str(line, encoding="utf-8")
return line, p.returncode |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def http_url_exists(url):
"""Returns whether the given HTTP URL 'exists' in the sense that it is returning an HTTP error code or not. A URL is considered to exist if it does not return an HTTP error code.""" |
class HEADRequest(Request):
def get_method(self):
return "HEAD"
try:
response = urlopen(HEADRequest(url))
return True
except URLError:
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_unix_like(platform=None):
"""Returns whether the given platform is a Unix-like platform with the usual Unix filesystem. When the parameter is omitted, it defaults to ``sys.platform`` """ |
platform = platform or sys.platform
platform = platform.lower()
return platform.startswith("linux") or platform.startswith("darwin") or \
platform.startswith("cygwin") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def preprocess_fallback_config():
"""Preprocesses the fallback include and library paths depending on the platform.""" |
global LIBIGRAPH_FALLBACK_INCLUDE_DIRS
global LIBIGRAPH_FALLBACK_LIBRARY_DIRS
global LIBIGRAPH_FALLBACK_LIBRARIES
if os.name == 'nt' and distutils.ccompiler.get_default_compiler() == 'msvc':
# if this setup is run in the source checkout *and* the igraph msvc was build,
# this code adds the right library and include dir
version = '';
if sys.version_info >= (2, 7) and sys.version_info < (3, 0):
version = '27';
elif sys.version_info >= (3, 4) and sys.version_info < (3, 5):
version ='34';
elif sys.version_info >= (3, 5):
version ='35';
all_msvc_dirs = glob.glob(os.path.join('..', 'igraph', 'igraph-*-msvc-py{0}'.format(version)))
if len(all_msvc_dirs) > 0:
if len(all_msvc_dirs) > 1:
print("More than one MSVC build directory (igraph-*-msvc-py{0}) found!".format(version))
print("It could happen that setup.py uses the wrong one! Please remove all but the right one!\n\n")
msvc_builddir = all_msvc_dirs[-1]
if not os.path.exists(os.path.join(msvc_builddir, "Release")):
print("There is no 'Release' dir in the MSVC build directory\n(%s)" % msvc_builddir)
print("Please build the MSVC build first!\n")
else:
print("Using MSVC build dir as a fallback: %s\n\n" % msvc_builddir)
LIBIGRAPH_FALLBACK_INCLUDE_DIRS = [os.path.join(msvc_builddir, "include")]
is_64bits = sys.maxsize > 2**32
LIBIGRAPH_FALLBACK_LIBRARY_DIRS = [os.path.join(msvc_builddir, "Release", "x64" if is_64bits else "win32")] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def version_variants(version):
"""Given an igraph version number, returns a list of possible version number variants to try when looking for a suitable nightly build of the C core to download from igraph.org.""" |
result = [version]
# Add trailing ".0" as needed to ensure that we have at least
# major.minor.patch
parts = version.split(".")
while len(parts) < 3:
parts.append("0")
result.append(".".join(parts))
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tmpdir(self):
"""The temporary directory in which igraph is downloaded and extracted.""" |
if self._tmpdir is None:
self._tmpdir = tempfile.mkdtemp(prefix="igraph.")
atexit.register(cleanup_tmpdir, self._tmpdir)
return self._tmpdir |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_first_version(self):
"""Finds the first version of igraph that exists in the nightly build repo from the version numbers provided in ``self.versions_to_try``.""" |
for version in self.versions_to_try:
remote_url = self.get_download_url(version=version)
if http_url_exists(remote_url):
return version, remote_url
return None, 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 has_pkgconfig(self):
"""Returns whether ``pkg-config`` is available on the current system and it knows about igraph or not.""" |
if self._has_pkgconfig is None:
if self.use_pkgconfig:
line, exit_code = get_output("pkg-config igraph")
self._has_pkgconfig = (exit_code == 0)
else:
self._has_pkgconfig = False
return self._has_pkgconfig |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure(self, ext):
"""Configures the given Extension object using this build configuration.""" |
ext.include_dirs += self.include_dirs
ext.library_dirs += self.library_dirs
ext.libraries += self.libraries
ext.extra_compile_args += self.extra_compile_args
ext.extra_link_args += self.extra_link_args
ext.extra_objects += self.extra_objects |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def detect_from_pkgconfig(self):
"""Detects the igraph include directory, library directory and the list of libraries to link to using ``pkg-config``.""" |
if not buildcfg.has_pkgconfig:
print("Cannot find the C core of igraph on this system using pkg-config.")
return False
cmd = "pkg-config igraph --cflags --libs"
if self.static_extension:
cmd += " --static"
line, exit_code = get_output(cmd)
if exit_code > 0 or len(line) == 0:
return False
opts = line.strip().split()
self.libraries = [opt[2:] for opt in opts if opt.startswith("-l")]
self.library_dirs = [opt[2:] for opt in opts if opt.startswith("-L")]
self.include_dirs = [opt[2:] for opt in opts if opt.startswith("-I")]
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_build_info(self):
"""Prints the include and library path being used for debugging purposes.""" |
if self.static_extension:
build_type = "static extension"
else:
build_type = "dynamic extension"
print("Build type: %s" % build_type)
print("Include path: %s" % " ".join(self.include_dirs))
print("Library path: %s" % " ".join(self.library_dirs))
print("Linked dynamic libraries: %s" % " ".join(self.libraries))
print("Linked static libraries: %s" % " ".join(self.extra_objects))
print("Extra compiler options: %s" % " ".join(self.extra_compile_args))
print("Extra linker options: %s" % " ".join(self.extra_link_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 process_args_from_command_line(self):
"""Preprocesses the command line options before they are passed to setup.py and sets up the build configuration.""" |
# Yes, this is ugly, but we don't want to interfere with setup.py's own
# option handling
opts_to_remove = []
for idx, option in enumerate(sys.argv):
if not option.startswith("--"):
continue
if option == "--static":
opts_to_remove.append(idx)
self.static_extension = True
elif option == "--no-download":
opts_to_remove.append(idx)
self.download_igraph_if_needed = False
elif option == "--no-pkg-config":
opts_to_remove.append(idx)
self.use_pkgconfig = False
elif option == "--no-progress-bar":
opts_to_remove.append(idx)
self.show_progress_bar = False
elif option == "--no-wait":
opts_to_remove.append(idx)
self.wait = False
elif option.startswith("--c-core-version"):
opts_to_remove.append(idx)
if option == "--c-core-version":
value = sys.argv[idx+1]
opts_to_remove.append(idx+1)
else:
value = option.split("=", 1)[1]
self.c_core_versions = [value]
elif option.startswith("--c-core-url"):
opts_to_remove.append(idx)
if option == "--c-core-url":
value = sys.argv[idx+1]
opts_to_remove.append(idx+1)
else:
value = option.split("=", 1)[1]
self.c_core_url = value
for idx in reversed(opts_to_remove):
sys.argv[idx:(idx+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 replace_static_libraries(self, exclusions=None):
"""Replaces references to libraries with full paths to their static versions if the static version is to be found on the library path.""" |
if "stdc++" not in self.libraries:
self.libraries.append("stdc++")
if exclusions is None:
exclusions = []
for library_name in set(self.libraries) - set(exclusions):
static_lib = find_static_library(library_name, self.library_dirs)
if static_lib:
self.libraries.remove(library_name)
self.extra_objects.append(static_lib) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def use_built_igraph(self):
"""Assumes that igraph is built already in ``igraphcore`` and sets up the include and library paths and the library names accordingly.""" |
buildcfg.include_dirs = [os.path.join("igraphcore", "include")]
buildcfg.library_dirs = [os.path.join("igraphcore", "lib")]
buildcfg.static_extension = True
buildcfg_file = os.path.join("igraphcore", "build.cfg")
if os.path.exists(buildcfg_file):
buildcfg.libraries = eval(open(buildcfg_file).read()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def use_educated_guess(self):
"""Tries to guess the proper library names, include and library paths if everything else failed.""" |
preprocess_fallback_config()
global LIBIGRAPH_FALLBACK_LIBRARIES
global LIBIGRAPH_FALLBACK_INCLUDE_DIRS
global LIBIGRAPH_FALLBACK_LIBRARY_DIRS
print("WARNING: we were not able to detect where igraph is installed on")
print("your machine (if it is installed at all). We will use the fallback")
print("library and include paths hardcoded in setup.py and hope that the")
print("C core of igraph is installed there.")
print("")
print("If the compilation fails and you are sure that igraph is installed")
print("on your machine, adjust the following two variables in setup.py")
print("accordingly and try again:")
print("")
print("- LIBIGRAPH_FALLBACK_INCLUDE_DIRS",
LIBIGRAPH_FALLBACK_INCLUDE_DIRS)
print("- LIBIGRAPH_FALLBACK_LIBRARY_DIRS",
LIBIGRAPH_FALLBACK_LIBRARY_DIRS)
print("")
seconds_remaining = 10 if self.wait else 0
while seconds_remaining > 0:
if seconds_remaining > 1:
plural = "s"
else:
plural = ""
sys.stdout.write("\rContinuing in %2d second%s; press Enter to continue "
"immediately. " % (seconds_remaining, plural))
sys.stdout.flush()
if os.name == 'nt':
if msvcrt.kbhit():
if msvcrt.getch() == b'\r': # not '\n'
break
time.sleep(1)
else:
rlist, _, _ = select([sys.stdin], [], [], 1)
if rlist:
sys.stdin.readline()
break
seconds_remaining -= 1
sys.stdout.write("\r" + " "*65 + "\r")
self.libraries = LIBIGRAPH_FALLBACK_LIBRARIES[:]
if self.static_extension:
self.libraries.extend(["xml2", "z", "m", "stdc++"])
self.include_dirs = LIBIGRAPH_FALLBACK_INCLUDE_DIRS[:]
self.library_dirs = LIBIGRAPH_FALLBACK_LIBRARY_DIRS[:] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def capture(self, data_buffer = None, log_time = False, debug_print = False, retry_reset = True):
"""Capture a frame of data. Captures 80x60 uint16 array of non-normalized (raw 12-bit) data. Returns that frame and a frame_id (which is currently just the sum of all pixels). The Lepton will return multiple, identical frames at a rate of up to ~27 Hz, with unique frames at only ~9 Hz, so the frame_id can help you from doing additional work processing duplicate frames. Args: data_buffer (numpy.ndarray):
Optional. If specified, should be ``(60,80,1)`` with `dtype`=``numpy.uint16``. Returns: tuple consisting of (data_buffer, frame_id) """ |
start = time.time()
if data_buffer is None:
data_buffer = np.ndarray((Lepton.ROWS, Lepton.COLS, 1), dtype=np.uint16)
elif data_buffer.ndim < 2 or data_buffer.shape[0] < Lepton.ROWS or data_buffer.shape[1] < Lepton.COLS or data_buffer.itemsize < 2:
raise Exception("Provided input array not large enough")
while True:
Lepton.capture_segment(self.__handle, self.__xmit_buf, self.__msg_size, self.__capture_buf[0])
if retry_reset and (self.__capture_buf[20, 0] & 0xFF0F) != 0x1400: # make sure that this is a well-formed frame, should find line 20 here
# Leave chip select deasserted for at least 185 ms to reset
if debug_print:
print("Garbage frame number reset waiting...")
time.sleep(0.185)
else:
break
self.__capture_buf.byteswap(True)
data_buffer[:,:] = self.__capture_buf[:,2:]
end = time.time()
if debug_print:
print("---")
for i in range(Lepton.ROWS):
fid = self.__capture_buf[i, 0, 0]
crc = self.__capture_buf[i, 1, 0]
fnum = fid & 0xFFF
print("0x{0:04x} 0x{1:04x} : Row {2:2} : crc={1}".format(fid, crc, fnum))
print("---")
if log_time:
print("frame processed int {0}s, {1}hz".format(end-start, 1.0/(end-start)))
# TODO: turn on telemetry to get real frame id, sum on this array is fast enough though (< 500us)
return data_buffer, data_buffer.sum() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stem(self, text):
"""Stem a text string to its common stem form.""" |
normalizedText = TextNormalizer.normalize_text(text)
words = normalizedText.split(' ')
stems = []
for word in words:
stems.append(self.stem_word(word))
return ' '.join(stems) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stem_word(self, word):
"""Stem a word to its common stem form.""" |
if self.is_plural(word):
return self.stem_plural_word(word)
else:
return self.stem_singular_word(word) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stem_singular_word(self, word):
"""Stem a singular word to its common stem form.""" |
context = Context(word, self.dictionary, self.visitor_provider)
context.execute()
return context.result |
<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(self):
"""Execute stemming process; the result can be retrieved with result""" |
#step 1 - 5
self.start_stemming_process()
#step 6
if self.dictionary.contains(self.current_word):
self.result = self.current_word
else:
self.result = self.original_word |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loop_pengembalian_akhiran(self):
"""ECS Loop Pengembalian Akhiran""" |
self.restore_prefix()
removals = self.removals
reversed_removals = reversed(removals)
current_word = self.current_word
for removal in reversed_removals:
if not self.is_suffix_removal(removal):
continue
if removal.get_removed_part() == 'kan':
self.current_word = removal.result + 'k'
#step 4,5
self.remove_prefixes()
if self.dictionary.contains(self.current_word):
return
self.current_word = removal.result + 'kan'
else:
self.current_word = removal.get_subject()
#step 4,5
self.remove_prefixes()
if self.dictionary.contains(self.current_word):
return
self.removals = removals
self.current_word = current_word |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def restore_prefix(self):
"""Restore prefix to proceed with ECS loop pengembalian akhiran""" |
for removal in self.removals:
#return the word before precoding (the subject of first prefix removal)
self.current_word = removal.get_subject()
break
for removal in self.removals:
if removal.get_affix_type() == 'DP':
self.removals.remove(removal) |
<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_stemmer(self, isDev=False):
""" Returns Stemmer instance """ |
words = self.get_words(isDev)
dictionary = ArrayDictionary(words)
stemmer = Stemmer(dictionary)
resultCache = ArrayCache()
cachedStemmer = CachedStemmer(resultCache, stemmer)
return cachedStemmer |
<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(self, word):
"""Add a word to the dictionary""" |
if not word or word.strip() == '':
return
self.words[word]=word |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def truth(f):
"""Convenience decorator to convert truth functions into validators. '/' """ |
@wraps(f)
def check(v):
t = f(v)
if not t:
raise ValueError
return v
return 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 Boolean(v):
"""Convert human-readable boolean values to a bool. Accepted values are 1, true, yes, on, enable, and their negatives. Non-string values are cast to bool. True True False """ |
if isinstance(v, basestring):
v = v.lower()
if v in ('1', 'true', 'yes', 'on', 'enable'):
return True
if v in ('0', 'false', 'no', 'off', 'disable'):
return False
raise ValueError
return bool(v) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Email(v):
"""Verify that the value is an Email or not. 't@x.com' """ |
try:
if not v or "@" not in v:
raise EmailInvalid("Invalid Email")
user_part, domain_part = v.rsplit('@', 1)
if not (USER_REGEX.match(user_part) and DOMAIN_REGEX.match(domain_part)):
raise EmailInvalid("Invalid Email")
return v
except:
raise ValueError |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def FqdnUrl(v):
"""Verify that the value is a Fully qualified domain name URL. 'http://w3.org' """ |
try:
parsed_url = _url_validation(v)
if "." not in parsed_url.netloc:
raise UrlInvalid("must have a domain name in URL")
return v
except:
raise ValueError |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def IsFile(v):
"""Verify the file exists. True """ |
try:
if v:
v = str(v)
return os.path.isfile(v)
else:
raise FileInvalid('Not a file')
except TypeError:
raise FileInvalid('Not a file') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def IsDir(v):
"""Verify the directory exists. '/' """ |
try:
if v:
v = str(v)
return os.path.isdir(v)
else:
raise DirInvalid("Not a directory")
except TypeError:
raise DirInvalid("Not a 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 PathExists(v):
"""Verify the path exists, regardless of its type. True """ |
try:
if v:
v = str(v)
return os.path.exists(v)
else:
raise PathInvalid("Not a Path")
except TypeError:
raise PathInvalid("Not a 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 _compile_scalar(schema):
"""A scalar value. The schema can either be a value or a type. 1 Callables have 1.0 As a convenience, ValueError's are trapped: """ |
if inspect.isclass(schema):
def validate_instance(path, data):
if isinstance(data, schema):
return data
else:
msg = 'expected %s' % schema.__name__
raise er.TypeInvalid(msg, path)
return validate_instance
if callable(schema):
def validate_callable(path, data):
try:
return schema(data)
except ValueError as e:
raise er.ValueInvalid('not a valid value', path)
except er.Invalid as e:
e.prepend(path)
raise
return validate_callable
def validate_value(path, data):
if data != schema:
raise er.ScalarInvalid('not a valid value', path)
return data
return validate_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 _compile_itemsort():
'''return sort function of mappings'''
def is_extra(key_):
return key_ is Extra
def is_remove(key_):
return isinstance(key_, Remove)
def is_marker(key_):
return isinstance(key_, Marker)
def is_type(key_):
return inspect.isclass(key_)
def is_callable(key_):
return callable(key_)
# priority list for map sorting (in order of checking)
# We want Extra to match last, because it's a catch-all. On the other hand,
# Remove markers should match first (since invalid values will not
# raise an Error, instead the validator will check if other schemas match
# the same value).
priority = [(1, is_remove), # Remove highest priority after values
(2, is_marker), # then other Markers
(4, is_type), # types/classes lowest before Extra
(3, is_callable), # callables after markers
(5, is_extra)] # Extra lowest priority
def item_priority(item_):
key_ = item_[0]
for i, check_ in priority:
if check_(key_):
return i
# values have hightest priorities
return 0
return item_priority |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def message(default=None, cls=None):
"""Convenience decorator to allow functions to provide a message. Set a default message: The message can be overridden on a per validator basis: The class thrown too: """ |
if cls and not issubclass(cls, er.Invalid):
raise er.SchemaError("message can only use subclases of Invalid as custom class")
def decorator(f):
@wraps(f)
def check(msg=None, clsoverride=None):
@wraps(f)
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
except ValueError:
raise (clsoverride or cls or er.ValueInvalid)(msg or default or 'invalid value')
return wrapper
return check
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _args_to_dict(func, args):
"""Returns argument names as values as key-value pairs.""" |
if sys.version_info >= (3, 0):
arg_count = func.__code__.co_argcount
arg_names = func.__code__.co_varnames[:arg_count]
else:
arg_count = func.func_code.co_argcount
arg_names = func.func_code.co_varnames[:arg_count]
arg_value_list = list(args)
arguments = dict((arg_name, arg_value_list[i])
for i, arg_name in enumerate(arg_names)
if i < len(arg_value_list))
return 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 _merge_args_with_kwargs(args_dict, kwargs_dict):
"""Merge args with kwargs.""" |
ret = args_dict.copy()
ret.update(kwargs_dict)
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 validate(*a, **kw):
"""Decorator for validating arguments of a function against a given schema. Set restrictions for arguments: Set restriction for returned value: """ |
RETURNS_KEY = '__return__'
def validate_schema_decorator(func):
returns_defined = False
returns = None
schema_args_dict = _args_to_dict(func, a)
schema_arguments = _merge_args_with_kwargs(schema_args_dict, kw)
if RETURNS_KEY in schema_arguments:
returns_defined = True
returns = schema_arguments[RETURNS_KEY]
del schema_arguments[RETURNS_KEY]
input_schema = (Schema(schema_arguments, extra=ALLOW_EXTRA)
if len(schema_arguments) != 0 else lambda x: x)
output_schema = Schema(returns) if returns_defined else lambda x: x
@wraps(func)
def func_wrapper(*args, **kwargs):
args_dict = _args_to_dict(func, args)
arguments = _merge_args_with_kwargs(args_dict, kwargs)
validated_arguments = input_schema(arguments)
output = func(**validated_arguments)
return output_schema(output)
return func_wrapper
return validate_schema_decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _compile_object(self, schema):
"""Validate an object. Has the same behavior as dictionary validator but work with object attributes. For example: """ |
base_validate = self._compile_mapping(
schema, invalid_msg='object value')
def validate_object(path, data):
if schema.cls is not UNDEFINED and not isinstance(data, schema.cls):
raise er.ObjectInvalid('expected a {0!r}'.format(schema.cls), path)
iterable = _iterate_object(data)
iterable = ifilter(lambda item: item[1] is not None, iterable)
out = base_validate(path, iterable, {})
return type(data)(**out)
return validate_object |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _compile_dict(self, schema):
"""Validate a dictionary. A dictionary schema can contain a set of values, or at most one validator function/type. A dictionary schema will only validate a dictionary: An invalid dictionary value: An invalid key: Validation function, in this case the "int" type: Valid integer input: {10: 'twenty'} By default, a "type" in the schema (in this case "int") will be used purely to validate that the corresponding value is of that type. It will not Coerce the value: Wrap them in the Coerce() function to achieve this: {10: 'twenty'} Custom message for required key (This is to avoid unexpected surprises.) Multiple errors for nested field in a dict: ["expected int for dictionary value @ data['adict']['intfield']", "expected str for dictionary value @ data['adict']['strfield']"] """ |
base_validate = self._compile_mapping(
schema, invalid_msg='dictionary value')
groups_of_exclusion = {}
groups_of_inclusion = {}
for node in schema:
if isinstance(node, Exclusive):
g = groups_of_exclusion.setdefault(node.group_of_exclusion, [])
g.append(node)
elif isinstance(node, Inclusive):
g = groups_of_inclusion.setdefault(node.group_of_inclusion, [])
g.append(node)
def validate_dict(path, data):
if not isinstance(data, dict):
raise er.DictInvalid('expected a dictionary', path)
errors = []
for label, group in groups_of_exclusion.items():
exists = False
for exclusive in group:
if exclusive.schema in data:
if exists:
msg = exclusive.msg if hasattr(exclusive, 'msg') and exclusive.msg else \
"two or more values in the same group of exclusion '%s'" % label
next_path = path + [VirtualPathComponent(label)]
errors.append(er.ExclusiveInvalid(msg, next_path))
break
exists = True
if errors:
raise er.MultipleInvalid(errors)
for label, group in groups_of_inclusion.items():
included = [node.schema in data for node in group]
if any(included) and not all(included):
msg = "some but not all values in the same group of inclusion '%s'" % label
for g in group:
if hasattr(g, 'msg') and g.msg:
msg = g.msg
break
next_path = path + [VirtualPathComponent(label)]
errors.append(er.InclusiveInvalid(msg, next_path))
break
if errors:
raise er.MultipleInvalid(errors)
out = data.__class__()
return base_validate(path, iteritems(data), out)
return validate_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 _compile_sequence(self, schema, seq_type):
"""Validate a sequence type. This is a sequence of valid values or validators tried in order. ['one'] [1] """ |
_compiled = [self._compile(s) for s in schema]
seq_type_name = seq_type.__name__
def validate_sequence(path, data):
if not isinstance(data, seq_type):
raise er.SequenceTypeInvalid('expected a %s' % seq_type_name, path)
# Empty seq schema, allow any data.
if not schema:
if data:
raise er.MultipleInvalid([
er.ValueInvalid('not a valid value', [value]) for value in data
])
return data
out = []
invalid = None
errors = []
index_path = UNDEFINED
for i, value in enumerate(data):
index_path = path + [i]
invalid = None
for validate in _compiled:
try:
cval = validate(index_path, value)
if cval is not Remove: # do not include Remove values
out.append(cval)
break
except er.Invalid as e:
if len(e.path) > len(index_path):
raise
invalid = e
else:
errors.append(invalid)
if errors:
raise er.MultipleInvalid(errors)
if _isnamedtuple(data):
return type(data)(*out)
else:
return type(data)(out)
return validate_sequence |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _compile_set(self, schema):
"""Validate a set. A set is an unordered collection of unique elements. True """ |
type_ = type(schema)
type_name = type_.__name__
def validate_set(path, data):
if not isinstance(data, type_):
raise er.Invalid('expected a %s' % type_name, path)
_compiled = [self._compile(s) for s in schema]
errors = []
for value in data:
for validate in _compiled:
try:
validate(path, value)
break
except er.Invalid:
pass
else:
invalid = er.Invalid('invalid value in %s' % type_name, path)
errors.append(invalid)
if errors:
raise er.MultipleInvalid(errors)
return data
return validate_set |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extend(self, schema, required=None, extra=None):
"""Create a new `Schema` by merging this and the provided `schema`. Neither this `Schema` nor the provided `schema` are modified. The resulting `Schema` inherits the `required` and `extra` parameters of this, unless overridden. Both schemas must be dictionary-based. :param schema: dictionary to extend this `Schema` with :param required: if set, overrides `required` of this `Schema` :param extra: if set, overrides `extra` of this `Schema` """ |
assert type(self.schema) == dict and type(schema) == dict, 'Both schemas must be dictionary-based'
result = self.schema.copy()
# returns the key that may have been passed as arugment to Marker constructor
def key_literal(key):
return (key.schema if isinstance(key, Marker) else key)
# build a map that takes the key literals to the needed objects
# literal -> Required|Optional|literal
result_key_map = dict((key_literal(key), key) for key in result)
# for each item in the extension schema, replace duplicates
# or add new keys
for key, value in iteritems(schema):
# if the key is already in the dictionary, we need to replace it
# transform key to literal before checking presence
if key_literal(key) in result_key_map:
result_key = result_key_map[key_literal(key)]
result_value = result[result_key]
# if both are dictionaries, we need to extend recursively
# create the new extended sub schema, then remove the old key and add the new one
if type(result_value) == dict and type(value) == dict:
new_value = Schema(result_value).extend(value).schema
del result[result_key]
result[key] = new_value
# one or the other or both are not sub-schemas, simple replacement is fine
# remove old key and add new one
else:
del result[result_key]
result[key] = value
# key is new and can simply be added
else:
result[key] = value
# recompile and send old object
result_cls = type(self)
result_required = (required if required is not None else self.required)
result_extra = (extra if extra is not None else self.extra)
return result_cls(result, required=result_required, extra=result_extra) |
<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_upload_path(instance, filename):
"""Overriding to store the original filename""" |
if not instance.name:
instance.name = filename # set original filename
date = timezone.now().date()
filename = '{name}.{ext}'.format(name=uuid4().hex,
ext=filename.split('.')[-1])
return os.path.join('post_office_attachments', str(date.year),
str(date.month), str(date.day), filename) |
<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(sender, recipients=None, cc=None, bcc=None, subject='', message='', html_message='', context=None, scheduled_time=None, headers=None, template=None, priority=None, render_on_delivery=False, commit=True, backend=''):
""" Creates an email from supplied keyword arguments. If template is specified, email subject and content will be rendered during delivery. """ |
priority = parse_priority(priority)
status = None if priority == PRIORITY.now else STATUS.queued
if recipients is None:
recipients = []
if cc is None:
cc = []
if bcc is None:
bcc = []
if context is None:
context = ''
# If email is to be rendered during delivery, save all necessary
# information
if render_on_delivery:
email = Email(
from_email=sender,
to=recipients,
cc=cc,
bcc=bcc,
scheduled_time=scheduled_time,
headers=headers, priority=priority, status=status,
context=context, template=template, backend_alias=backend
)
else:
if template:
subject = template.subject
message = template.content
html_message = template.html_content
_context = Context(context or {})
subject = Template(subject).render(_context)
message = Template(message).render(_context)
html_message = Template(html_message).render(_context)
email = Email(
from_email=sender,
to=recipients,
cc=cc,
bcc=bcc,
subject=subject,
message=message,
html_message=html_message,
scheduled_time=scheduled_time,
headers=headers, priority=priority, status=status,
backend_alias=backend
)
if commit:
email.save()
return email |
<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_queued(processes=1, log_level=None):
""" Sends out all queued mails that has scheduled_time less than now or None """ |
queued_emails = get_queued()
total_sent, total_failed = 0, 0
total_email = len(queued_emails)
logger.info('Started sending %s emails with %s processes.' %
(total_email, processes))
if log_level is None:
log_level = get_log_level()
if queued_emails:
# Don't use more processes than number of emails
if total_email < processes:
processes = total_email
if processes == 1:
total_sent, total_failed = _send_bulk(queued_emails,
uses_multiprocessing=False,
log_level=log_level)
else:
email_lists = split_emails(queued_emails, processes)
pool = Pool(processes)
results = pool.map(_send_bulk, email_lists)
pool.terminate()
total_sent = sum([result[0] for result in results])
total_failed = sum([result[1] for result in results])
message = '%s emails attempted, %s sent, %s failed' % (
total_email,
total_sent,
total_failed
)
logger.info(message)
return (total_sent, total_failed) |
<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_messages(self, email_messages):
""" Queue one or more EmailMessage objects and returns the number of email messages sent. """ |
from .mail import create
from .utils import create_attachments
if not email_messages:
return
for email_message in email_messages:
subject = email_message.subject
from_email = email_message.from_email
message = email_message.body
headers = email_message.extra_headers
# Check whether email has 'text/html' alternative
alternatives = getattr(email_message, 'alternatives', ())
for alternative in alternatives:
if alternative[1].startswith('text/html'):
html_message = alternative[0]
break
else:
html_message = ''
attachment_files = {}
for attachment in email_message.attachments:
if isinstance(attachment, MIMEBase):
attachment_files[attachment.get_filename()] = {
'file': ContentFile(attachment.get_payload()),
'mimetype': attachment.get_content_type(),
'headers': OrderedDict(attachment.items()),
}
else:
attachment_files[attachment[0]] = ContentFile(attachment[1])
email = create(sender=from_email,
recipients=email_message.to, cc=email_message.cc,
bcc=email_message.bcc, subject=subject,
message=message, html_message=html_message,
headers=headers)
if attachment_files:
attachments = create_attachments(attachment_files)
email.attachments.add(*attachments)
if get_default_priority() == 'now':
email.dispatch() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def valid_lock(self):
""" See if the lock exists and is left over from an old process. """ |
lock_pid = self.get_lock_pid()
# If we're unable to get lock_pid
if lock_pid is None:
return False
# this is our process
if self._pid == lock_pid:
return True
# it is/was another process
# see if it is running
try:
os.kill(lock_pid, 0)
except OSError:
self.release()
return False
# it is running
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def release(self):
"""Try to delete the lock files. Doesn't matter if we fail""" |
if self.lock_filename != self.pid_filename:
try:
os.unlink(self.lock_filename)
except OSError:
pass
try:
os.remove(self.pid_filename)
except OSError:
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 validate_email_with_name(value):
""" Validate email address. Both "Recipient Name <email@example.com>" and "email@example.com" are valid. """ |
value = force_text(value)
recipient = value
if '<' and '>' in value:
start = value.find('<') + 1
end = value.find('>')
if start < end:
recipient = value[start:end]
validate_email(recipient) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_comma_separated_emails(value):
""" Validate every email address in a comma separated list of emails. """ |
if not isinstance(value, (tuple, list)):
raise ValidationError('Email list must be a list/tuple.')
for email in value:
try:
validate_email_with_name(email)
except ValidationError:
raise ValidationError('Invalid email: %s' % email, code='invalid') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_template_syntax(source):
""" Basic Django Template syntax validation. This allows for robuster template authoring. """ |
try:
Template(source)
except (TemplateSyntaxError, TemplateDoesNotExist) as err:
raise ValidationError(text_type(err)) |
<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_mail(subject, message, from_email, recipient_list, html_message='', scheduled_time=None, headers=None, priority=PRIORITY.medium):
""" Add a new message to the mail queue. This is a replacement for Django's ``send_mail`` core email method. """ |
subject = force_text(subject)
status = None if priority == PRIORITY.now else STATUS.queued
emails = []
for address in recipient_list:
emails.append(
Email.objects.create(
from_email=from_email, to=address, subject=subject,
message=message, html_message=html_message, status=status,
headers=headers, priority=priority, scheduled_time=scheduled_time
)
)
if priority == PRIORITY.now:
for email in emails:
email.dispatch()
return emails |
<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_email_template(name, language=''):
""" Function that returns an email template instance, from cache or DB. """ |
use_cache = getattr(settings, 'POST_OFFICE_CACHE', True)
if use_cache:
use_cache = getattr(settings, 'POST_OFFICE_TEMPLATE_CACHE', True)
if not use_cache:
return EmailTemplate.objects.get(name=name, language=language)
else:
composite_name = '%s:%s' % (name, language)
email_template = cache.get(composite_name)
if email_template is not None:
return email_template
else:
email_template = EmailTemplate.objects.get(name=name,
language=language)
cache.set(composite_name, email_template)
return email_template |
<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_attachments(attachment_files):
""" Create Attachment instances from files attachment_files is a dict of: * Key - the filename to be used for the attachment. * Value - file-like object, or a filename to open OR a dict of {'file': file-like-object, 'mimetype': string} Returns a list of Attachment objects """ |
attachments = []
for filename, filedata in attachment_files.items():
if isinstance(filedata, dict):
content = filedata.get('file', None)
mimetype = filedata.get('mimetype', None)
headers = filedata.get('headers', None)
else:
content = filedata
mimetype = None
headers = None
opened_file = None
if isinstance(content, string_types):
# `content` is a filename - try to open the file
opened_file = open(content, 'rb')
content = File(opened_file)
attachment = Attachment()
if mimetype:
attachment.mimetype = mimetype
attachment.headers = headers
attachment.file.save(filename, content=content, save=True)
attachments.append(attachment)
if opened_file is not None:
opened_file.close()
return attachments |
<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_emails(emails):
""" A function that returns a list of valid email addresses. This function will also convert a single email address into a list of email addresses. None value is also converted into an empty list. """ |
if isinstance(emails, string_types):
emails = [emails]
elif emails is None:
emails = []
for email in emails:
try:
validate_email_with_name(email)
except ValidationError:
raise ValidationError('%s is not a valid email address' % email)
return emails |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def VERSION(self):
"""TAN mechanism version""" |
return int(re.match(r'^(\D+)(\d+)$', self.__class__.__name__).group(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 parse_message(self, data: bytes) -> SegmentSequence: """Takes a FinTS 3.0 message as byte array, and returns a parsed segment sequence""" |
if isinstance(data, bytes):
data = self.explode_segments(data)
message = SegmentSequence()
for segment in data:
seg = self.parse_segment(segment)
message.segments.append(seg)
return message |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def terminal_flicker_unix(code, field_width=3, space_width=3, height=1, clear=False, wait=0.05):
""" Re-encodes a flicker code and prints it on a unix terminal. :param code: Challenge value :param field_width: Width of fields in characters (default: 3). :param space_width: Width of spaces in characters (default: 3). :param height: Height of fields in characters (default: 1). :param clear: Clear terminal after every line (default: ``False``). :param wait: Waiting interval between lines (default: 0.05). """ |
# Inspired by Andreas Schiermeier
# https://git.ccc-ffm.de/?p=smartkram.git;a=blob_plain;f=chiptan/flicker/flicker.sh;h
# =7066293b4e790c2c4c1f6cbdab703ed9976ffe1f;hb=refs/heads/master
code = parse(code).render()
data = swap_bytes(code)
high = '\033[48;05;15m'
low = '\033[48;05;0m'
std = '\033[0m'
stream = ['10000', '00000', '11111', '01111', '11111', '01111', '11111']
for c in data:
v = int(c, 16)
stream.append('1' + str(v & 1) + str((v & 2) >> 1) + str((v & 4) >> 2) + str((v & 8) >> 3))
stream.append('0' + str(v & 1) + str((v & 2) >> 1) + str((v & 4) >> 2) + str((v & 8) >> 3))
while True:
for frame in stream:
if clear:
print('\033c', end='')
for i in range(height):
for c in frame:
print(low + ' ' * space_width, end='')
if c == '1':
print(high + ' ' * field_width, end='')
else:
print(low+ ' ' * field_width, end='')
print(low + ' ' * space_width + std)
time.sleep(wait) |
<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_segments(self, query=None, version=None, callback=None, recurse=True, throw=False):
"""Yields an iterable of all matching segments. :param query: Either a str or class specifying a segment type (such as 'HNHBK', or :class:`~fints.segments.message.HNHBK3`), or a list or tuple of strings or classes. If a list/tuple is specified, segments returning any matching type will be returned. :param version: Either an int specifying a segment version, or a list or tuple of ints. If a list/tuple is specified, segments returning any matching version will be returned. :param callback: A callable that will be given the segment as its sole argument and must return a boolean indicating whether to return this segment. :param recurse: If True (the default), recurse into SegmentSequenceField values, otherwise only look at segments in this SegmentSequence. :param throw: If True, a FinTSNoResponseError is thrown if no result is found. Defaults to False. The match results of all given parameters will be AND-combined. """ |
found_something = False
if query is None:
query = []
elif isinstance(query, str) or not isinstance(query, (list, tuple, Iterable)):
query = [query]
if version is None:
version = []
elif not isinstance(version, (list, tuple, Iterable)):
version = [version]
if callback is None:
callback = lambda s: True
for s in self.segments:
if ((not query) or any((isinstance(s, t) if isinstance(t, type) else s.header.type == t) for t in query)) and \
((not version) or any(s.header.version == v for v in version)) and \
callback(s):
yield s
found_something = True
if recurse:
for name, field in s._fields.items():
val = getattr(s, name)
if val and hasattr(val, 'find_segments'):
for v in val.find_segments(query=query, version=version, callback=callback, recurse=recurse):
yield v
found_something = True
if throw and not found_something:
raise FinTSNoResponseError(
'The bank\'s response did not contain a response to your request, please inspect debug log.'
) |
<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_segment_first(self, *args, **kwargs):
"""Finds the first matching segment. Same parameters as find_segments(), but only returns the first match, or None if no match is found.""" |
for m in self.find_segments(*args, **kwargs):
return m
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 find_segment_highest_version(self, query=None, version=None, callback=None, recurse=True, default=None):
"""Finds the highest matching segment. Same parameters as find_segments(), but returns the match with the highest version, or default if no match is found.""" |
# FIXME Test
retval = None
for s in self.find_segments(query=query, version=version, callback=callback, recurse=recurse):
if not retval or s.header.version > retval.header.version:
retval = s
if retval is None:
return default
return retval |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_nested(self, stream=None, level=0, indent=" ", prefix="", first_level_indent=True, trailer="", print_doc=True, first_line_suffix=""):
"""Structured nested print of the object to the given stream. The print-out is eval()able to reconstruct the object.""" |
import sys
stream = stream or sys.stdout
stream.write(
((prefix + level * indent) if first_level_indent else "")
+ "{}.{}(".format(self.__class__.__module__, self.__class__.__name__)
+ first_line_suffix
+ "\n"
)
for name, value in self._repr_items:
val = getattr(self, name)
if print_doc and not name.startswith("_"):
docstring = self._fields[name]._inline_doc_comment(val)
else:
docstring = ""
if not hasattr(getattr(val, 'print_nested', None), '__call__'):
stream.write(
(prefix + (level + 1) * indent) + "{} = {!r},{}\n".format(name, val, docstring)
)
else:
stream.write(
(prefix + (level + 1) * indent) + "{} = ".format(name)
)
val.print_nested(stream=stream, level=level + 2, indent=indent, prefix=prefix, first_level_indent=False, trailer=",", print_doc=print_doc,
first_line_suffix=docstring)
stream.write((prefix + level * indent) + "){}\n".format(trailer)) |
<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_data(cls, blob):
"""Restore an object instance from a compressed datablob. Returns an instance of a concrete subclass.""" |
version, data = decompress_datablob(DATA_BLOB_MAGIC_RETRY, blob)
if version == 1:
for clazz in cls._all_subclasses():
if clazz.__name__ == data["_class_name"]:
return clazz._from_data_v1(data)
raise Exception("Invalid data blob data or version") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deconstruct(self, including_private: bool=False) -> bytes: """Return state of this FinTSClient instance as an opaque datablob. You should not use this object after calling this method. Information about the connection is implicitly retrieved from the bank and cached in the FinTSClient. This includes: system identifier, bank parameter data, user parameter data. It's not strictly required to retain this information across sessions, but beneficial. If possible, an API user SHOULD use this method to serialize the client instance before destroying it, and provide the serialized data next time an instance is constructed. Parameter `including_private` should be set to True, if the storage is sufficiently secure (with regards to confidentiality) to include private data, specifically, account numbers and names. Most often this is the case. Note: No connection information is stored in the datablob, neither is the PIN. """ |
data = self._deconstruct_v1(including_private=including_private)
return compress_datablob(DATA_BLOB_MAGIC, 1, 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 get_information(self):
""" Return information about the connected bank. Note: Can only be filled after the first communication with the bank. If in doubt, use a construction like:: with f: info = f.get_information() Returns a nested dictionary:: bank: name: Bank Name supported_operations: dict(FinTSOperations -> boolean) accounts: - iban: IBAN account_number: Account Number subaccount_number: Sub-Account Number customer_id: Customer ID type: Account type currency: Currency owner_name: ['Owner Name 1', 'Owner Name 2 (optional)'] product_name: Account product name supported_operations: dict(FinTSOperations -> boolean) """ |
retval = {
'bank': {},
'accounts': [],
'auth': {},
}
if self.bpa:
retval['bank']['name'] = self.bpa.bank_name
if self.bpd.segments:
retval['bank']['supported_operations'] = {
op: any(self.bpd.find_segment_first(cmd[0]+'I'+cmd[2:]+'S') for cmd in op.value)
for op in FinTSOperations
}
hispas = self.bpd.find_segment_first('HISPAS')
if hispas:
retval['bank']['supported_sepa_formats'] = list(hispas.parameter.supported_sepa_formats)
else:
retval['bank']['supported_sepa_formats'] = []
if self.upd.segments:
for upd in self.upd.find_segments('HIUPD'):
acc = {}
acc['iban'] = upd.iban
acc['account_number'] = upd.account_information.account_number
acc['subaccount_number'] = upd.account_information.subaccount_number
acc['bank_identifier'] = upd.account_information.bank_identifier
acc['customer_id'] = upd.customer_id
acc['type'] = upd.account_type
acc['currency'] = upd.account_currency
acc['owner_name'] = []
if upd.name_account_owner_1:
acc['owner_name'].append(upd.name_account_owner_1)
if upd.name_account_owner_2:
acc['owner_name'].append(upd.name_account_owner_2)
acc['product_name'] = upd.account_product_name
acc['supported_operations'] = {
op: any(allowed_transaction.transaction in op.value for allowed_transaction in upd.allowed_transactions)
for op in FinTSOperations
}
retval['accounts'].append(acc)
return retval |
<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_sepa_accounts(self):
""" Returns a list of SEPA accounts :return: List of SEPAAccount objects. """ |
with self._get_dialog() as dialog:
response = dialog.send(HKSPA1())
self.accounts = []
for seg in response.find_segments(HISPA1, throw=True):
self.accounts.extend(seg.accounts)
return [a for a in [acc.as_sepa_account() for acc in self.accounts] if 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 _find_highest_supported_command(self, *segment_classes, **kwargs):
"""Search the BPD for the highest supported version of a segment.""" |
return_parameter_segment = kwargs.get("return_parameter_segment", False)
parameter_segment_name = "{}I{}S".format(segment_classes[0].TYPE[0], segment_classes[0].TYPE[2:])
version_map = dict((clazz.VERSION, clazz) for clazz in segment_classes)
max_version = self.bpd.find_segment_highest_version(parameter_segment_name, version_map.keys())
if not max_version:
raise FinTSUnsupportedOperation('No supported {} version found. I support {}, bank supports {}.'.format(
parameter_segment_name,
tuple(version_map.keys()),
tuple(v.header.version for v in self.bpd.find_segments(parameter_segment_name))
))
if return_parameter_segment:
return max_version, version_map.get(max_version.header.version)
else:
return version_map.get(max_version.header.version) |
<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_transactions(self, account: SEPAAccount, start_date: datetime.date = None, end_date: datetime.date = None):
""" Fetches the list of transactions of a bank account in a certain timeframe. :param account: SEPA :param start_date: First day to fetch :param end_date: Last day to fetch :return: A list of mt940.models.Transaction objects """ |
with self._get_dialog() as dialog:
hkkaz = self._find_highest_supported_command(HKKAZ5, HKKAZ6, HKKAZ7)
logger.info('Start fetching from {} to {}'.format(start_date, end_date))
responses = self._fetch_with_touchdowns(
dialog,
lambda touchdown: hkkaz(
account=hkkaz._fields['account'].type.from_sepa_account(account),
all_accounts=False,
date_start=start_date,
date_end=end_date,
touchdown_point=touchdown,
),
'HIKAZ'
)
logger.info('Fetching done.')
statement = []
for seg in responses:
# Note: MT940 messages are encoded in the S.W.I.F.T character set,
# which is a subset of ISO 8859. There are no character in it that
# differ between ISO 8859 variants, so we'll arbitrarily chose 8859-1.
statement += mt940_to_array(seg.statement_booked.decode('iso-8859-1'))
logger.debug('Statement: {}'.format(statement))
return statement |
<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_transactions_xml(self, account: SEPAAccount, start_date: datetime.date = None, end_date: datetime.date = None) -> list: """ Fetches the list of transactions of a bank account in a certain timeframe as camt.052.001.02 XML files. :param account: SEPA :param start_date: First day to fetch :param end_date: Last day to fetch :return: A list of bytestrings containing XML documents """ |
with self._get_dialog() as dialog:
hkcaz = self._find_highest_supported_command(HKCAZ1)
logger.info('Start fetching from {} to {}'.format(start_date, end_date))
responses = self._fetch_with_touchdowns(
dialog,
lambda touchdown: hkcaz(
account=hkcaz._fields['account'].type.from_sepa_account(account),
all_accounts=False,
date_start=start_date,
date_end=end_date,
touchdown_point=touchdown,
supported_camt_messages=SupportedMessageTypes('urn:iso:std:iso:20022:tech:xsd:camt.052.001.02'),
),
'HICAZ'
)
logger.info('Fetching done.')
xml_streams = []
for seg in responses:
xml_streams.append(seg.statement_booked)
return xml_streams |
<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_balance(self, account: SEPAAccount):
""" Fetches an accounts current balance. :param account: SEPA account to fetch the balance :return: A mt940.models.Balance object """ |
with self._get_dialog() as dialog:
hksal = self._find_highest_supported_command(HKSAL5, HKSAL6, HKSAL7)
seg = hksal(
account=hksal._fields['account'].type.from_sepa_account(account),
all_accounts=False,
)
response = dialog.send(seg)
for resp in response.response_segments(seg, 'HISAL'):
return resp.balance_booked.as_mt940_Balance() |
<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_holdings(self, account: SEPAAccount):
""" Retrieve holdings of an account. :param account: SEPAAccount to retrieve holdings for. :return: List of Holding objects """ |
# init dialog
with self._get_dialog() as dialog:
hkwpd = self._find_highest_supported_command(HKWPD5, HKWPD6)
responses = self._fetch_with_touchdowns(
dialog,
lambda touchdown: hkwpd(
account=hkwpd._fields['account'].type.from_sepa_account(account),
touchdown_point=touchdown,
),
'HIWPD'
)
holdings = []
for resp in responses:
if type(resp.holdings) == bytes:
holding_str = resp.holdings.decode()
else:
holding_str = resp.holdings
mt535_lines = str.splitlines(holding_str)
# The first line is empty - drop it.
del mt535_lines[0]
mt535 = MT535_Miniparser()
holdings.extend(mt535.parse(mt535_lines))
if not holdings:
logger.debug('No HIWPD response segment found - maybe account has no holdings?')
return holdings |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def simple_sepa_transfer(self, account: SEPAAccount, iban: str, bic: str, recipient_name: str, amount: Decimal, account_name: str, reason: str, endtoend_id='NOTPROVIDED'):
""" Simple SEPA transfer. :param account: SEPAAccount to start the transfer from. :param iban: Recipient's IBAN :param bic: Recipient's BIC :param recipient_name: Recipient name :param amount: Amount as a ``Decimal`` :param account_name: Sender account name :param reason: Transfer reason :param endtoend_id: End-to-end-Id (defaults to ``NOTPROVIDED``) :return: Returns either a NeedRetryResponse or TransactionResponse """ |
config = {
"name": account_name,
"IBAN": account.iban,
"BIC": account.bic,
"batch": False,
"currency": "EUR",
}
sepa = SepaTransfer(config, 'pain.001.001.03')
payment = {
"name": recipient_name,
"IBAN": iban,
"BIC": bic,
"amount": round(Decimal(amount) * 100), # in cents
"execution_date": datetime.date(1999, 1, 1),
"description": reason,
"endtoend_id": endtoend_id,
}
sepa.add_payment(payment)
xml = sepa.export().decode()
return self.sepa_transfer(account, xml) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sepa_transfer(self, account: SEPAAccount, pain_message: str, multiple=False, control_sum=None, currency='EUR', book_as_single=False, pain_descriptor='urn:iso:std:iso:20022:tech:xsd:pain.001.001.03'):
""" Custom SEPA transfer. :param account: SEPAAccount to send the transfer from. :param pain_message: SEPA PAIN message containing the transfer details. :param multiple: Whether this message contains multiple transfers. :param control_sum: Sum of all transfers (required if there are multiple) :param currency: Transfer currency :param book_as_single: Kindly ask the bank to put multiple transactions as separate lines on the bank statement (defaults to ``False``) :param pain_descriptor: URN of the PAIN message schema used. :return: Returns either a NeedRetryResponse or TransactionResponse """ |
with self._get_dialog() as dialog:
if multiple:
command_class = HKCCM1
else:
command_class = HKCCS1
hiccxs, hkccx = self._find_highest_supported_command(
command_class,
return_parameter_segment=True
)
seg = hkccx(
account=hkccx._fields['account'].type.from_sepa_account(account),
sepa_descriptor=pain_descriptor,
sepa_pain_message=pain_message.encode(),
)
if multiple:
if hiccxs.parameter.sum_amount_required and control_sum is None:
raise ValueError("Control sum required.")
if book_as_single and not hiccxs.parameter.single_booking_allowed:
raise FinTSUnsupportedOperation("Single booking not allowed by bank.")
if control_sum:
seg.sum_amount.amount = control_sum
seg.sum_amount.currency = currency
if book_as_single:
seg.request_single_booking = True
return self._send_with_possible_retry(dialog, seg, self._continue_sepa_transfer) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sepa_debit(self, account: SEPAAccount, pain_message: str, multiple=False, cor1=False, control_sum=None, currency='EUR', book_as_single=False, pain_descriptor='urn:iso:std:iso:20022:tech:xsd:pain.008.003.01'):
""" Custom SEPA debit. :param account: SEPAAccount to send the debit from. :param pain_message: SEPA PAIN message containing the debit details. :param multiple: Whether this message contains multiple debits. :param cor1: Whether to use COR1 debit (lead time reduced to 1 day) :param control_sum: Sum of all debits (required if there are multiple) :param currency: Debit currency :param book_as_single: Kindly ask the bank to put multiple transactions as separate lines on the bank statement (defaults to ``False``) :param pain_descriptor: URN of the PAIN message schema used. Defaults to ``urn:iso:std:iso:20022:tech:xsd:pain.008.003.01``. :return: Returns either a NeedRetryResponse or TransactionResponse (with data['task_id'] set, if available) """ |
with self._get_dialog() as dialog:
if multiple:
if cor1:
command_candidates = (HKDMC1, )
else:
command_candidates = (HKDME1, HKDME2)
else:
if cor1:
command_candidates = (HKDSC1, )
else:
command_candidates = (HKDSE1, HKDSE2)
hidxxs, hkdxx = self._find_highest_supported_command(
*command_candidates,
return_parameter_segment=True
)
seg = hkdxx(
account=hkdxx._fields['account'].type.from_sepa_account(account),
sepa_descriptor=pain_descriptor,
sepa_pain_message=pain_message.encode(),
)
if multiple:
if hidxxs.parameter.sum_amount_required and control_sum is None:
raise ValueError("Control sum required.")
if book_as_single and not hidxxs.parameter.single_booking_allowed:
raise FinTSUnsupportedOperation("Single booking not allowed by bank.")
if control_sum:
seg.sum_amount.amount = control_sum
seg.sum_amount.currency = currency
if book_as_single:
seg.request_single_booking = True
return self._send_with_possible_retry(dialog, seg, self._continue_sepa_debit) |
<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_tan(self, challenge: NeedTANResponse, tan: str):
""" Sends a TAN to confirm a pending operation. :param challenge: NeedTANResponse to respond to :param tan: TAN value :return: Currently no response """ |
with self._get_dialog() as dialog:
tan_seg = self._get_tan_segment(challenge.command_seg, '2', challenge.tan_request)
self._pending_tan = tan
response = dialog.send(tan_seg)
resume_func = getattr(self, challenge.resume_method)
return resume_func(challenge.command_seg, response) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_tan_mechanisms(self):
""" Get the available TAN mechanisms. Note: Only checks for HITANS versions listed in IMPLEMENTED_HKTAN_VERSIONS. :return: Dictionary of security_function: TwoStepParameters objects. """ |
retval = OrderedDict()
for version in sorted(IMPLEMENTED_HKTAN_VERSIONS.keys()):
for seg in self.bpd.find_segments('HITANS', version):
for parameter in seg.parameter.twostep_parameters:
if parameter.security_function in self.allowed_security_functions:
retval[parameter.security_function] = parameter
return retval |
<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_MAC(segments=6, segment_length=2, delimiter=":", charset="0123456789abcdef"):
"""generate a non-guaranteed-unique mac address""" |
addr = []
for _ in range(segments):
sub = ''.join(random.choice(charset) for _ in range(segment_length))
addr.append(sub)
return delimiter.join(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 recv(self, packet, interface):
"""run incoming packet through the filters, then place it in its inq""" |
# the packet is piped into the first filter, then the result of that into the second filter, etc.
for f in self.filters:
if not packet:
break
packet = f.tr(packet, interface)
if packet:
# if the packet wasn't dropped by a filter, log the recv and place it in the interface's inq
# self.log("IN ", str(interface).ljust(30), packet.decode())
self.inq[interface].put(packet) |
<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, packet, interfaces=None):
"""write packet to given interfaces, default is broadcast to all interfaces""" |
interfaces = interfaces or self.interfaces # default to all interfaces
interfaces = interfaces if hasattr(interfaces, '__iter__') else [interfaces]
for interface in interfaces:
for f in self.filters:
packet = f.tx(packet, interface) # run outgoing packet through the filters
if packet:
# if not dropped, log the transmit and pass it to the interface's send method
# self.log("OUT ", ("<"+",".join(i.name for i in interfaces)+">").ljust(30), packet.decode())
interface.send(packet) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def match(cls, pattern, inverse=False):
"""Factory method to create a StringFilter which filters with the given pattern.""" |
string_pattern = pattern
invert_search = inverse
class DefinedStringFilter(cls):
pattern = string_pattern
inverse = invert_search
return DefinedStringFilter |
<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_cmd(command, verbose=True, shell='/bin/bash'):
"""internal helper function to run shell commands and get output""" |
process = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT, executable=shell)
output = process.stdout.read().decode().strip().split('\n')
if verbose:
# return full output including empty lines
return output
return [line for line in output if line.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 run_python(cmd, timeout=60):
"""interactively interpret recieved python code""" |
try:
try:
buffer = StringIO()
sys.stdout = buffer
exec(cmd)
sys.stdout = sys.__stdout__
out = buffer.getvalue()
except Exception as error:
out = error
out = str(out).strip()
if len(out) < 1:
try:
out = "[eval]: "+str(eval(cmd))
except Exception as error:
out = "[eval]: "+str(error)
else:
out = "[exec]: "+out
except Exception as python_exception:
out = "[X]: %s" % python_exception
return out.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 run_shell(cmd, timeout=60, verbose=False):
"""run a shell command and return the output, verbose enables live command output via yield""" |
retcode = None
try:
p = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT, executable='/bin/bash')
continue_running = True
except Exception as e:
yield("Failed: %s" % e)
continue_running = False
while continue_running:
try:
line = p.stdout.readline()
if verbose and line:
yield(line)
elif line.strip():
yield(line.strip())
except Exception:
pass
try:
data = irc.recv(4096)
except Exception as e:
data = ""
retcode = p.poll() # returns None while subprocess is running
if '!cancel' in data:
retcode = "Cancelled live output reading. You have to kill the process manually."
yield "[X]: %s" % retcode
break
elif retcode is not None:
try:
line = p.stdout.read()
except:
retcode = "Too much output, read timed out. Process is still running in background."
if verbose and line:
yield line
if retcode != 0:
yield "[X]: %s" % retcode
elif retcode == 0 and verbose:
yield "[√]"
break |
<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_platform():
"""get Mac OS X version or kernel version if mac version is not found""" |
mac_version = str(platform.mac_ver()[0]).strip() # e.g. 10.11.2
if mac_version:
return 'OS X %s' % mac_version
return platform.platform().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 email(to='medusa@sweeting.me', _from=default_from, subject='BOT MSG', message="Info email", attachments=None):
"""function to send mail to a specified address with the given attachments""" |
for attachment in attachments or []:
filename = attachment.strip()
try:
result = run_cmd('uuencode %s %s | mailx -s "%s" %s' % (filename, filename, subject, to))[0]
return "Sending email From: %s; To: %s; Subject: %s; Attachment: %s (%s)" % (_from, to, subject, filename, result or 'Succeded')
except Exception as error:
return str(error)
if not attachments:
p = os.popen("/usr/sbin/sendmail -t", "w")
p.write("From: %s\n" % _from)
p.write("To: %s\n" % to)
p.write("Subject: %s\n" % subject)
p.write("\n") # blank line separating headers from body
p.write('%s\n' % message)
result = p.close()
if not result:
return "Sent email From: %s; To: %s; Subject: %s; Attachments: %s)" % (_from, to, subject, ','.join(attachments or []))
else:
return "Error: %s. Please fix Postfix:\n %s" % (result, help_str) |
<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, *args):
"""stdout and stderr for the link""" |
print("%s %s" % (str(self).ljust(8), " ".join([str(x) for x in 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 recv(self, mac_addr=broadcast_addr, timeout=0):
"""read packet off the recv queue for a given address, optional timeout to block and wait for packet""" |
# recv on the broadcast address "00:..:00" will give you all packets (for promiscuous mode)
if self.keep_listening:
try:
return self.inq[str(mac_addr)].get(timeout=timeout)
except Empty:
return ""
else:
self.log("is down.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_on_network_adapter_changed(self, callback):
"""Set the callback function to consume on network adapter changed events. Callback receives a INetworkAdapterChangedEvent object. Returns the callback_id """ |
event_type = library.VBoxEventType.on_network_adapter_changed
return self.event_source.register_callback(callback, event_type) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_on_medium_changed(self, callback):
"""Set the callback function to consume on medium changed events. Callback receives a IMediumChangedEvent object. Returns the callback_id """ |
event_type = library.VBoxEventType.on_medium_changed
return self.event_source.register_callback(callback, event_type) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_on_clipboard_mode_changed(self, callback):
"""Set the callback function to consume on clipboard mode changed events. Callback receives a IClipboardModeChangedEvent object. Returns the callback_id """ |
event_type = library.VBoxEventType.on_clipboard_mode_changed
return self.event_source.register_callback(callback, event_type) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_on_drag_and_drop_mode_changed(self, callback):
"""Set the callback function to consume on drag and drop mode changed events. Callback receives a IDragAndDropModeChangedEvent object. Returns the callback_id """ |
event_type = library.VBoxEventType.on_drag_and_drop_mode_changed
return self.event_source.register_callback(callback, event_type) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_on_shared_folder_changed(self, callback):
"""Set the callback function to consume on shared folder changed events. Callback receives a ISharedFolderChangedEvent object. Returns the callback_id """ |
event_type = library.VBoxEventType.on_shared_folder_changed
return self.event_source.register_callback(callback, event_type) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_on_additions_state_changed(self, callback):
"""Set the callback function to consume on additions state changed events. Callback receives a IAdditionsStateChangedEvent object. Note: Interested callees should query IGuest attributes to find out what has changed. Returns the callback_id """ |
event_type = library.VBoxEventType.on_additions_state_change
return self.event_source.register_callback(callback, event_type) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_on_state_changed(self, callback):
"""Set the callback function to consume on state changed events which are generated when the state of the machine changes. Callback receives a IStateChangeEvent object. Returns the callback_id """ |
event_type = library.VBoxEventType.on_state_changed
return self.event_source.register_callback(callback, event_type) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_on_event_source_changed(self, callback):
"""Set the callback function to consume on event source changed events. This occurs when a listener is added or removed. Callback receives a IEventStateChangedEvent object. Returns the callback_id """ |
event_type = library.VBoxEventType.on_event_source_changed
return self.event_source.register_callback(callback, event_type) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_on_can_show_window(self, callback):
"""Set the callback function to consume on can show window events. This occurs when the console window is to be activated and brought to the foreground of the desktop of the host PC. If this behaviour is not desired a call to event.add_veto will stop this from happening. Callback receives a ICanShowWindowEvent object. Returns the callback_id """ |
event_type = library.VBoxEventType.on_can_show_window
return self.event_source.register_callback(callback, event_type) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_on_show_window(self, callback):
"""Set the callback function to consume on show window events. This occurs when the console window is to be activated and brought to the foreground of the desktop of the host PC. Callback receives a IShowWindowEvent object. Returns the callback_id """ |
event_type = library.VBoxEventType.on_show_window
return self.event_source.register_callback(callback, event_type) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def manager(self, value):
"Set the manager object in the global _managers dict."
pid = current_process().ident
if _managers is None:
raise RuntimeError("Can not set the manager following a system exit.")
if pid not in _managers:
_managers[pid] = value
else:
raise Exception("Manager already set for pid %s" % pid) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.