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 get_image_tar(image_path): '''get an image tar, either written in memory or to the file system. file_obj will either be the file object, or the file itself. ''' bot.debug('Generate file system tar...') file_obj = Client.image.export(image_path=image_path) if file_obj is 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 extract_content(image_path, member_name, return_hash=False): '''extract_content will extract content from an image using cat. If hash=True, a hash sum is returned instead ''' if member_name.startswith('./'): member_name = member_name.replace('.','',1) if return_hash: hashy = hash...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def remove_unicode_dict(input_dict): '''remove unicode keys and values from dict, encoding in utf8 ''' if isinstance(input_dict, collections.Mapping): return dict(map(remove_unicode_dict, input_dict.iteritems())) elif isinstance(input_dict, collections.Iterable): return type(input_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 RSA(m1,m2): '''RSA analysis will compare the similarity of two matrices ''' from scipy.stats import pearsonr import scipy.linalg import numpy # This will take the diagonal of each matrix (and the other half is changed to nan) and flatten to vector vectorm1 = m1.mask(numpy.triu(numpy.one...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rsync(*args, **kwargs): """ wrapper around the rsync command. the ssh connection arguments are set automatically. any args are just passed directly to rsync....
kwargs.setdefault('capture', False) replacements = dict( host_string="{user}@{host}".format( user=env.instance.config.get('user', 'root'), host=env.instance.config.get( 'host', env.instance.config.get( 'ip', env.instance.uid)))) args = [x....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def devices(self): """ computes the name of the disk devices that are suitable installation targets by subtracting CDROM- and USB devices from the list of total ...
install_devices = self.install_devices if 'bootstrap-system-devices' in env.instance.config: devices = set(env.instance.config['bootstrap-system-devices'].split()) else: devices = set(self.sysctl_devices) for sysctl_device in self.sysctl_devices: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_assets(self): """ download bootstrap assets to control host. If present on the control host they will be uploaded to the target host during bootstrappi...
# allow overwrites from the commandline packages = set( env.instance.config.get('bootstrap-packages', '').split()) packages.update(['python27']) cmd = env.instance.config.get('bootstrap-local-download-cmd', 'wget -c -O "{0.local}" "{0.url}"') items = sorted(self.boot...
<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_resource_definition(resource_name, resource_dct): """ Returns all the info extracted from a resource section of the apipie json :param resource_name: N...
new_dict = { '__module__': resource_dct.get('__module__', __name__), '__doc__': resource_dct['full_description'], '_resource_name': resource_name, '_own_methods': set(), '_conflicting_methods': [], } # methods in foreign_methods are meant for other resources, # ...
<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_resource_from_url(self, url): """ Returns the appropriate resource name for the given URL. :param url: API URL stub, like: '/api/hosts' :return: Resour...
# special case for the api root if url == '/api': return 'api' elif url == '/katello': return 'katello' match = self.resource_pattern.match(url) if match: return match.groupdict().get('resource', 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 generate_func(self, as_global=False): """ Generate function for specific method and using specific api :param as_global: if set, will use the global function...
keywords = [] params_def = [] params_doc = "" original_names = {} params = dict( (param['name'], param) for param in self.params ) # parse the url required params, as sometimes they are skipped in the # parameters list of the def...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_plugin_def(http_method, funcs): """ This function parses one of the elements of the definitions dict for a plugin and extracts the relevant informati...
methods = [] if http_method not in ('GET', 'PUT', 'POST', 'DELETE'): logger.error( 'Plugin load failure, HTTP method %s unsupported.', http_method, ) return methods for fname, params in six.iteritems(funcs): method ...
<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_authors(repo_path, from_commit): """ Given a repo and optionally a base revision to start from, will return the list of authors. """
repo = dulwich.repo.Repo(repo_path) refs = get_refs(repo) start_including = False authors = set() if from_commit is None: start_including = True for commit_sha, children in reversed( get_children_per_first_parent(repo_path).items() ): commit = get_repo_object(repo,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def emit( self, tup, tup_id=None, stream=None, direct_task=None, need_task_ids=False ): """Emit a spout Tuple message. :param tup: the Tuple to send to Storm, sh...
return super(Spout, self).emit( tup, tup_id=tup_id, stream=stream, direct_task=direct_task, need_task_ids=need_task_ids, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ack(self, tup_id): """Called when a bolt acknowledges a Tuple in the topology. :param tup_id: the ID of the Tuple that has been fully acknowledged in the top...
self.failed_tuples.pop(tup_id, None) try: del self.unacked_tuples[tup_id] except KeyError: self.logger.error("Received ack for unknown tuple ID: %r", tup_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 fail(self, tup_id): """Called when a Tuple fails in the topology A reliable spout will replay a failed tuple up to ``max_fails`` times. :param tup_id: the ID...
saved_args = self.unacked_tuples.get(tup_id) if saved_args is None: self.logger.error("Received fail for unknown tuple ID: %r", tup_id) return tup, stream, direct_task, need_task_ids = saved_args if self.failed_tuples[tup_id] < self.max_fails: self.em...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def emit( self, tup, tup_id=None, stream=None, direct_task=None, need_task_ids=False ): """Emit a spout Tuple & add metadata about it to `unacked_tuples`. In ord...
if tup_id is None: raise ValueError( "You must provide a tuple ID when emitting with a " "ReliableSpout in order for the tuple to be " "tracked." ) args = (tup, stream, direct_task, need_task_ids) self.unacked_tuples[tup_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 remote_pdb_handler(signum, frame): """ Handler to drop us into a remote debugger upon receiving SIGUSR1 """
try: from remote_pdb import RemotePdb rdb = RemotePdb(host="127.0.0.1", port=0) rdb.set_trace(frame=frame) except ImportError: log.warning( "remote_pdb unavailable. Please install remote_pdb to " "allow remote debugging." ) # Restore signal ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _setup_component(self, storm_conf, context): """Add helpful instance variables to component after initial handshake with Storm. Also configure logging. """
self.topology_name = storm_conf.get("topology.name", "") self.task_id = context.get("taskid", "") self.component_name = context.get("componentid") # If using Storm before 0.10.0 componentid is not available if self.component_name is None: self.component_name = contex...
<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_handshake(self): """Read and process an initial handshake message from Storm."""
msg = self.read_message() pid_dir, _conf, _context = msg["pidDir"], msg["conf"], msg["context"] # Write a blank PID file out to the pidDir open(join(pid_dir, str(self.pid)), "w").close() self.send_message({"pid": self.pid}) return _conf, _context
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_message(self, message): """Send a message to Storm via stdout."""
if not isinstance(message, dict): logger = self.logger if self.logger else log logger.error( "%s.%d attempted to send a non dict message to Storm: " "%r", self.component_name, self.pid, message, ) re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def raise_exception(self, exception, tup=None): """Report an exception back to Storm via logging. :param exception: a Python exception. :param tup: a :class:`Tup...
if tup: message = ( "Python {exception_name} raised while processing Tuple " "{tup!r}\n{traceback}" ) else: message = "Python {exception_name} raised\n{traceback}" message = message.format( exception_name=exception....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log(self, message, level=None): """Log a message to Storm optionally providing a logging level. :param message: the log message to send to Storm. :type messa...
level = _STORM_LOG_LEVELS.get(level, _STORM_LOG_INFO) self.send_message({"command": "log", "msg": str(message), "level": level})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """Main run loop for all components. Performs initial handshake with Storm and reads Tuples handing them off to subclasses. Any exceptions are cau...
storm_conf, context = self.read_handshake() self._setup_component(storm_conf, context) self.initialize(storm_conf, context) while True: try: self._run() except StormWentAwayError: log.info("Exiting because parent Storm process went...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _exit(self, status_code): """Properly kill Python process including zombie threads."""
# If there are active threads still running infinite loops, sys.exit # won't kill them but os._exit will. os._exit skips calling cleanup # handlers, flushing stdio buffers, etc. exit_func = os._exit if threading.active_count() > 1 else sys.exit exit_func(status_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 read_message(self): """The Storm multilang protocol consists of JSON messages followed by a newline and "end\n". All of Storm's messages (for either bolts or...
msg = "" num_blank_lines = 0 while True: # readline will return trailing \n so that output is unambigious, we # should only have line == '' if we're at EOF with self._reader_lock: line = self.input_stream.readline() if line == "end...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serialize_dict(self, msg_dict): """Serialize to JSON a message dictionary."""
serialized = json.dumps(msg_dict, namedtuple_as_object=False) if PY2: serialized = serialized.decode("utf-8") serialized = "{}\nend\n".format(serialized) return serialized
<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_tuple(self): """Read a tuple from the pipe to Storm."""
cmd = self.read_command() source = cmd["comp"] stream = cmd["stream"] values = cmd["tuple"] val_type = self._source_tuple_types[source].get(stream) return Tuple( cmd["id"], source, stream, cmd["task"], tuple(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 ack(self, tup): """Indicate that processing of a Tuple has succeeded. :param tup: the Tuple to acknowledge. :type tup: :class:`str` or :class:`pystorm.compon...
tup_id = tup.id if isinstance(tup, Tuple) else tup self.send_message({"command": "ack", "id": tup_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 fail(self, tup): """Indicate that processing of a Tuple has failed. :param tup: the Tuple to fail (its ``id`` if ``str``). :type tup: :class:`str` or :class:...
tup_id = tup.id if isinstance(tup, Tuple) else tup self.send_message({"command": "fail", "id": tup_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 emit(self, tup, **kwargs): """Modified emit that will not return task IDs after emitting. See :class:`pystorm.component.Bolt` for more information. :returns:...
kwargs["need_task_ids"] = False return super(BatchingBolt, self).emit(tup, **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 process_tick(self, tick_tup): """Increment tick counter, and call ``process_batch`` for all current batches if tick counter exceeds ``ticks_between_batches``...
self._tick_counter += 1 # ACK tick Tuple immediately, since it's just responsible for counter self.ack(tick_tup) if self._tick_counter > self.ticks_between_batches and self._batches: self.process_batches() self._tick_counter = 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_batches(self): """Iterate through all batches, call process_batch on them, and ack. Separated out for the rare instances when we want to subclass Bat...
for key, batch in iteritems(self._batches): self._current_tups = batch self._current_key = key self.process_batch(key, batch) if self.auto_ack: for tup in batch: self.ack(tup) # Set current batch to [] so that we kn...
<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(self, tup): """Group non-tick Tuples into batches by ``group_key``. .. warning:: This method should **not** be overriden. If you want to tweak how Tu...
# Append latest Tuple to batches group_key = self.group_key(tup) self._batches[group_key].append(tup)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _batch_entry_run(self): """The inside of ``_batch_entry``'s infinite loop. Separated out so it can be properly unit tested. """
time.sleep(self.secs_between_batches) with self._batch_lock: self.process_batches()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _batch_entry(self): """Entry point for the batcher thread."""
try: while True: self._batch_entry_run() except: self.exc_info = sys.exc_info() os.kill(self.pid, signal.SIGUSR1)
<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_message(self, msg_dict): """Serialize a message dictionary and write it to the output stream."""
with self._writer_lock: try: self.output_stream.flush() self.output_stream.write(self.serialize_dict(msg_dict)) self.output_stream.flush() except IOError: raise StormWentAwayError() except: log.e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _void_array_to_list(restuple, _func, _args): """ Convert the FFI result to Python data structures """
shape = (restuple.e.len, 1) array_size = np.prod(shape) mem_size = 8 * array_size array_str_e = string_at(restuple.e.data, mem_size) array_str_n = string_at(restuple.n.data, mem_size) ls_e = np.frombuffer(array_str_e, float, array_size).tolist() ls_n = np.frombuffer(array_str_n, float, ar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_data_file(filename, encoding='utf-8'): """Load a data file and return it as a list of lines. Parameters: filename: The name of the file (no directories ...
data = pkgutil.get_data(PACKAGE_NAME, os.path.join(DATA_DIR, filename)) return data.decode(encoding).splitlines()
<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_data(): """Load the word and character mapping data into a dictionary. In the data files, each line is formatted like this: HANZI PINYIN_READING/PINYIN...
data = {} for name, file_name in (('words', 'hanzi_pinyin_words.tsv'), ('characters', 'hanzi_pinyin_characters.tsv')): # Split the lines by tabs: [[hanzi, pinyin]...]. lines = [line.split('\t') for line in dragonmapper.data.load_data_file(file_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 _hanzi_to_pinyin(hanzi): """Return the Pinyin reading for a Chinese word. If the given string *hanzi* matches a CC-CEDICT word, the return value is If the gi...
try: return _HANZI_PINYIN_MAP['words'][hanzi] except KeyError: return [_CHARACTERS.get(character, character) for character in hanzi]
<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_pinyin(s, delimiter=' ', all_readings=False, container='[]', accented=True): """Convert a string's Chinese characters to Pinyin readings. *s* is a string ...
hanzi = s pinyin = '' # Process the given string. while hanzi: # Get the next match in the given string. match = re.search('[^%s%s]+' % (delimiter, zhon.hanzi.punctuation), hanzi) # There are no more matches, but the string isn't finished yet. ...
<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_zhuyin(s, delimiter=' ', all_readings=False, container='[]'): """Convert a string's Chinese characters to Zhuyin readings. *s* is a string containing Chin...
numbered_pinyin = to_pinyin(s, delimiter, all_readings, container, False) zhuyin = pinyin_to_zhuyin(numbered_pinyin) return zhuyin
<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_ipa(s, delimiter=' ', all_readings=False, container='[]'): """Convert a string's Chinese characters to IPA. *s* is a string containing Chinese characters....
numbered_pinyin = to_pinyin(s, delimiter, all_readings, container, False) ipa = pinyin_to_ipa(numbered_pinyin) return ipa
<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_data(): """Load the transcription mapping data into a dictionary."""
lines = dragonmapper.data.load_data_file('transcriptions.csv') pinyin_map, zhuyin_map, ipa_map = {}, {}, {} for line in lines: p, z, i = line.split(',') pinyin_map[p] = {'Zhuyin': z, 'IPA': i} zhuyin_map[z] = {'Pinyin': p, 'IPA': i} ipa_map[i] = {'Pinyin': p, 'Zhuyin': z} ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _numbered_vowel_to_accented(vowel, tone): """Convert a numbered Pinyin vowel to an accented Pinyin vowel."""
if isinstance(tone, int): tone = str(tone) return _PINYIN_TONES[vowel + tone]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _accented_vowel_to_numbered(vowel): """Convert an accented Pinyin vowel to a numbered Pinyin vowel."""
for numbered_vowel, accented_vowel in _PINYIN_TONES.items(): if vowel == accented_vowel: return tuple(numbered_vowel)
<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_numbered_syllable(unparsed_syllable): """Return the syllable and tone of a numbered Pinyin syllable."""
tone_number = unparsed_syllable[-1] if not tone_number.isdigit(): syllable, tone = unparsed_syllable, '5' elif tone_number == '0': syllable, tone = unparsed_syllable[:-1], '5' elif tone_number in '12345': syllable, tone = unparsed_syllable[:-1], tone_number else: rai...
<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_accented_syllable(unparsed_syllable): """Return the syllable and tone of an accented Pinyin syllable. Any accented vowels are returned without their a...
if unparsed_syllable[0] == '\u00B7': # Special case for middle dot tone mark. return unparsed_syllable[1:], '5' for character in unparsed_syllable: if character in _ACCENTED_VOWELS: vowel, tone = _accented_vowel_to_numbered(character) return unparsed_syllable.rep...
<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_zhuyin_syllable(unparsed_syllable): """Return the syllable and tone of a Zhuyin syllable."""
zhuyin_tone = unparsed_syllable[-1] if zhuyin_tone in zhon.zhuyin.characters: syllable, tone = unparsed_syllable, '1' elif zhuyin_tone in zhon.zhuyin.marks: for tone_number, tone_mark in _ZHUYIN_TONES.items(): if zhuyin_tone == tone_mark: syllable, tone = unparse...
<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_ipa_syllable(unparsed_syllable): """Return the syllable and tone of an IPA syllable."""
ipa_tone = re.search('[%(marks)s]+' % {'marks': _IPA_MARKS}, unparsed_syllable) if not ipa_tone: syllable, tone = unparsed_syllable, '5' else: for tone_number, tone_mark in _IPA_TONES.items(): if ipa_tone.group() == tone_mark: tone = tone...
<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_case(s, memory): """Restore a lowercase string's characters to their original case."""
cased_s = [] for i, c in enumerate(s): if i + 1 > len(memory): break cased_s.append(c if memory[i] else c.upper()) return ''.join(cased_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 _convert(s, re_pattern, syllable_function, add_apostrophes=False, remove_apostrophes=False, separate_syllables=False): """Convert a string's syllables to a d...
original = s new = '' while original: match = re.search(re_pattern, original, re.IGNORECASE | re.UNICODE) if match is None and original: # There are no more matches, but the given string isn't fully # processed yet. new += original 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 _is_pattern_match(re_pattern, s): """Check if a re pattern expression matches an entire string."""
match = re.match(re_pattern, s, re.I) return match.group() == s if match else 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 identify(s): """Identify a given string's transcription system. *s* is the string to identify. The string is checked to see if its contents are valid Pinyin,...
if is_pinyin(s): return PINYIN elif is_zhuyin(s): return ZHUYIN elif is_ipa(s): return IPA else: return UNKNOWN
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare(self, f): """Accept an objective function for optimization."""
self.g = autograd.grad(f) self.h = autograd.hessian(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 solve(self, angles): """Calculate a position of the end-effector and return it."""
return reduce( lambda a, m: np.dot(m, a), reversed(self._matrices(angles)), np.array([0., 0., 0., 1.]) )[:3]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def solve(self, angles0, target): """Calculate joint angles and returns it."""
return self.optimizer.optimize(np.array(angles0), target)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def matrix(self, _): """Return translation matrix in homogeneous coordinates."""
x, y, z = self.coord return np.array([ [1., 0., 0., x], [0., 1., 0., y], [0., 0., 1., z], [0., 0., 0., 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 matrix(self, angle): """Return rotation matrix in homogeneous coordinates."""
_rot_mat = { 'x': self._x_rot, 'y': self._y_rot, 'z': self._z_rot } return _rot_mat[self.axis](angle)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_logger(self, logger): """ Set a logger to send debug messages to Parameters logger : `Logger <http://docs.python.org/2/library/logging.html>`_ A python l...
self.__logger = logger self.session.set_logger(self.__logger)
<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): """ Return the version number of the Lending Club Investor tool Returns ------- string The version number string """
this_path = os.path.dirname(os.path.realpath(__file__)) version_file = os.path.join(this_path, 'VERSION') return open(version_file).read().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 authenticate(self, email=None, password=None): """ Attempt to authenticate the user. Parameters email : string The email of a user on Lending Club password :...
if self.session.authenticate(email, password): 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 get_cash_balance(self): """ Returns the account cash balance available for investing Returns ------- float The cash balance in your account. """
cash = False try: response = self.session.get('/browse/cashBalanceAj.action') json_response = response.json() if self.session.json_success(json_response): self.__log('Cash available: {0}'.format(json_response['cashBalance'])) cash_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 my_notes(self, start_index=0, limit=100, get_all=False, sort_by='loanId', sort_dir='asc'): """ Return all the loan notes you've already invested in. By defau...
index = start_index notes = { 'loans': [], 'total': 0, 'result': 'success' } while True: payload = { 'sortBy': sort_by, 'dir': sort_dir, 'startindex': index, 'pagesize': limi...
<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_note(self, note_id): """ Get a loan note that you've invested in by ID Parameters note_id : int The note ID Returns ------- dict A dictionary representin...
index = 0 while True: notes = self.my_notes(start_index=index, sort_by='noteId') if notes['result'] != 'success': break # If the first note has a higher ID, we've passed it if notes['loans'][0]['noteId'] > note_id: 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 add(self, loan_id, amount): """ Add a loan and amount you want to invest, to your order. If this loan is already in your order, it's amount will be replaced ...
assert amount > 0 and amount % 25 == 0, 'Amount must be a multiple of 25' assert type(amount) in (float, int), 'Amount must be a number' if type(loan_id) is dict: loan = loan_id assert 'loan_id' in loan and type(loan['loan_id']) is int, 'loan_id must be a number or 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 add_batch(self, loans, batch_amount=None): """ Add a batch of loans to your order. Parameters loans : list A list of dictionary objects representing each loa...
assert batch_amount is None or batch_amount % 25 == 0, 'batch_amount must be a multiple of 25' # Add each loan assert type(loans) is list, 'The loans property must be a list. (not {0})'.format(type(loans)) for loan in loans: loan_id = loan amount = batch_amount ...
<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, portfolio_name=None): """ Place the order with LendingClub Parameters portfolio_name : string The name of the portfolio to add the invested loa...
assert self.order_id == 0, 'This order has already been place. Start a new order.' assert len(self.loans) > 0, 'There aren\'t any loans in your order' # Place the order self.__stage_order() token = self.__get_strut_token() self.order_id = self.__place_order(token) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assign_to_portfolio(self, portfolio_name=None): """ Assign all the notes in this order to a portfolio Parameters portfolio_name -- The name of the portfolio ...
assert self.order_id > 0, 'You need to execute this order before you can assign to a portfolio.' # Get loan IDs as a list loan_ids = self.loans.keys() # Make a list of 1 order ID per loan order_ids = [self.order_id]*len(loan_ids) return self.lc.assign_to_portfolio(por...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __stage_order(self): """ Add all the loans to the LC order session """
# Skip staging...probably not a good idea...you've been warned if self.__already_staged is True and self.__i_know_what_im_doing is True: self.__log('Not staging the order...I hope you know what you\'re doing...'.format(len(self.loans))) return self.__log('Staging order...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __place_order(self, token): """ Use the struts token to place the order. Parameters token : string The struts token received from the place order page Return...
order_id = 0 response = None if not token or token['value'] == '': raise LendingClubError('The token parameter is False, None or unknown.') # Process order confirmation page try: # Place the order payload = {} if token: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __continue_session(self): """ Check if the time since the last HTTP request is under the session timeout limit. If it's been too long since the last request ...
now = time.time() diff = abs(now - self.last_request_time) timeout_sec = self.session_timeout * 60 # convert minutes to seconds if diff >= timeout_sec: self.__log('Session timed out, attempting to authenticate') self.authenticate()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authenticate(self, email=None, password=None): """ Authenticate with LendingClub and preserve the user session for future requests. This will raise an except...
# Get email and password if email is None: email = self.email else: self.email = email if password is None: password = self.__pass else: self.__pass = password # Get them from the user if email is 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 request(self, method, path, query=None, data=None, redirects=True): """ Sends HTTP request to LendingClub. Parameters method : {GET, POST, HEAD, DELETE} The ...
# Check session time self.__continue_session() try: url = self.build_url(path) method = method.upper() self.__log('{0} request to: {1}'.format(method, url)) if method == 'POST': request = self.__session.post(url, params=query, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def json_success(self, json): """ Check the JSON response object for the success flag Parameters json : dict A dictionary representing a JSON object from lending...
if type(json) is dict and 'result' in json and json['result'] == 'success': return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __merge_values(self, from_dict, to_dict): """ Merge dictionary objects recursively, by only updating keys existing in to_dict """
for key, value in from_dict.iteritems(): # Only if the key already exists if key in to_dict: # Make sure the values are the same datatype assert type(to_dict[key]) is type(from_dict[key]), 'Data type for {0} is incorrect: {1}, should be {2}'.format(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 __normalize_grades(self): """ Adjust the grades list. If a grade has been set, set All to false """
if 'grades' in self and self['grades']['All'] is True: for grade in self['grades']: if grade != 'All' and self['grades'][grade] is True: self['grades']['All'] = False 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 __normalize_progress(self): """ Adjust the funding progress filter to be a factor of 10 """
progress = self['funding_progress'] if progress % 10 != 0: progress = round(float(progress) / 10) progress = int(progress) * 10 self['funding_progress'] = progress
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __normalize(self): """ Adjusts the values of the filters to be correct. For example, if you set grade 'B' to True, then 'All' should be set to False """
# Don't normalize if we're already normalizing or intializing if self.__normalizing is True or self.__initialized is False: return self.__normalizing = True self.__normalize_grades() self.__normalize_progress() self.__normalizing = 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 validate_one(self, loan): """ Validate a single loan result record against the filters Parameters loan : dict A single loan note record Returns ------- boole...
assert type(loan) is dict, 'loan parameter must be a dictionary object' # Map the loan value keys to the filter keys req = { 'loanGUID': 'loan_id', 'loanGrade': 'grade', 'loanLength': 'term', 'loanUnfundedAmount': 'progress', 'loanAmo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_string(self): """" Returns the JSON string that LendingClub expects for it's search """
self.__normalize() # Get the template tmpl_source = unicode(open(self.tmpl_file).read()) # Process template compiler = Compiler() template = compiler.compile(tmpl_source) out = template(self) if not out: return False out = ''.join(ou...
<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_filters(lc): """ Get a list of all your saved filters Parameters lc : :py:class:`lendingclub.LendingClub` An instance of the authenticated LendingClub cl...
filters = [] response = lc.session.get('/browse/getSavedFiltersAj.action') json_response = response.json() # Load all filters if lc.session.json_success(json_response): for saved in json_response['filters']: filters.append(SavedFilter(lc, saved['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 load(self): """ Load the filter from the server """
# Attempt to load the saved filter payload = { 'id': self.id } response = self.lc.session.get('/browse/getSavedFilterAj.action', query=payload) self.response = response json_response = response.json() if self.lc.session.json_success(json_response) 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 __analyze(self): """ Analyze the filter JSON and attempt to parse out the individual filters. """
filter_values = {} # ID to filter name mapping name_map = { 10: 'grades', 11: 'loan_purpose', 13: 'approved', 15: 'funding_progress', 38: 'exclude_existing', 39: 'term', 43: 'keyword' } if 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 _float_copy_to_out(out, origin): """ Copy origin to out and return it. If ``out`` is None, a new copy (casted to floating point) is used. If ``out`` and ``or...
if out is None: out = origin / 1 # The division forces cast to a floating point type elif out is not origin: np.copyto(out, origin) return 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 _distance_matrix_generic(x, centering, exponent=1): """Compute a centered distance matrix given a matrix."""
_check_valid_dcov_exponent(exponent) x = _transform_to_2d(x) # Calculate distance matrices a = distances.pairwise_distances(x, exponent=exponent) # Double centering a = centering(a, out=a) return 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 _af_inv_scaled(x): """Scale a random vector for using the affinely invariant measures"""
x = _transform_to_2d(x) cov_matrix = np.atleast_2d(np.cov(x, rowvar=False)) cov_matrix_power = _mat_sqrt_inv(cov_matrix) return x.dot(cov_matrix_power)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def partial_distance_covariance(x, y, z): """ Partial distance covariance estimator. Compute the estimator for the partial distance covariance of the random vect...
a = _u_distance_matrix(x) b = _u_distance_matrix(y) c = _u_distance_matrix(z) proj = u_complementary_projection(c) return u_product(proj(a), proj(b))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def partial_distance_correlation(x, y, z): # pylint:disable=too-many-locals """ Partial distance correlation estimator. Compute the estimator for the partial dis...
a = _u_distance_matrix(x) b = _u_distance_matrix(y) c = _u_distance_matrix(z) aa = u_product(a, a) bb = u_product(b, b) cc = u_product(c, c) ab = u_product(a, b) ac = u_product(a, c) bc = u_product(b, c) denom_sqr = aa * bb r_xy = ab / _sqrt(denom_sqr) if denom_sqr != 0 el...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _energy_distance_from_distance_matrices( distance_xx, distance_yy, distance_xy): """Compute energy distance with precalculated distance matrices."""
return (2 * np.mean(distance_xy) - np.mean(distance_xx) - np.mean(distance_yy))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _distance_covariance_sqr_naive(x, y, exponent=1): """ Naive biased estimator for distance covariance. Computes the unbiased estimator for distance covariance...
a = _distance_matrix(x, exponent=exponent) b = _distance_matrix(y, exponent=exponent) return mean_product(a, b)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _u_distance_covariance_sqr_naive(x, y, exponent=1): """ Naive unbiased estimator for distance covariance. Computes the unbiased estimator for distance covari...
a = _u_distance_matrix(x, exponent=exponent) b = _u_distance_matrix(y, exponent=exponent) return u_product(a, b)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _distance_sqr_stats_naive_generic(x, y, matrix_centered, product, exponent=1): """Compute generic squared stats."""
a = matrix_centered(x, exponent=exponent) b = matrix_centered(y, exponent=exponent) covariance_xy_sqr = product(a, b) variance_x_sqr = product(a, a) variance_y_sqr = product(b, b) denominator_sqr = np.absolute(variance_x_sqr * variance_y_sqr) denominator = _sqrt(denominator_sqr) # Co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _distance_correlation_sqr_naive(x, y, exponent=1): """Biased distance correlation estimator between two matrices."""
return _distance_sqr_stats_naive_generic( x, y, matrix_centered=_distance_matrix, product=mean_product, exponent=exponent).correlation_xy
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _u_distance_correlation_sqr_naive(x, y, exponent=1): """Bias-corrected distance correlation estimator between two matrices."""
return _distance_sqr_stats_naive_generic( x, y, matrix_centered=_u_distance_matrix, product=u_product, exponent=exponent).correlation_xy
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _can_use_fast_algorithm(x, y, exponent=1): """ Check if the fast algorithm for distance stats can be used. The fast algorithm has complexity :math:`O(NlogN)`...
return (_is_random_variable(x) and _is_random_variable(y) and x.shape[0] > 3 and y.shape[0] > 3 and exponent == 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 _dyad_update(y, c): # pylint:disable=too-many-locals # This function has many locals so it can be compared # with the original algorithm. """ Inner function ...
n = y.shape[0] gamma = np.zeros(n, dtype=c.dtype) # Step 1: get the smallest l such that n <= 2^l l_max = int(math.ceil(np.log2(n))) # Step 2: assign s(l, k) = 0 s_len = 2 ** (l_max + 1) s = np.zeros(s_len, dtype=c.dtype) pos_sums = np.arange(l_max) pos_sums[:] = 2 ** (l_max - po...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _distance_covariance_sqr_fast_generic( x, y, unbiased=False): # pylint:disable=too-many-locals # This function has many locals so it can be compared # with t...
x = np.asarray(x) y = np.asarray(y) x = np.ravel(x) y = np.ravel(y) n = x.shape[0] assert n > 3 assert n == y.shape[0] temp = range(n) # Step 1 ix0 = np.argsort(x) vx = x[ix0] ix = np.zeros(n, dtype=int) ix[ix0] = temp iy0 = np.argsort(y) vy = y[iy0] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _distance_stats_sqr_fast_generic(x, y, dcov_function): """Compute the distance stats using the fast algorithm."""
covariance_xy_sqr = dcov_function(x, y) variance_x_sqr = dcov_function(x, x) variance_y_sqr = dcov_function(y, y) denominator_sqr_signed = variance_x_sqr * variance_y_sqr denominator_sqr = np.absolute(denominator_sqr_signed) denominator = _sqrt(denominator_sqr) # Comparisons using a tolera...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def distance_correlation_af_inv_sqr(x, y): """ Square of the affinely invariant distance correlation. Computes the estimator for the square of the affinely invar...
x = _af_inv_scaled(x) y = _af_inv_scaled(y) correlation = distance_correlation_sqr(x, y) return 0 if np.isnan(correlation) else correlation