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 mag_calibration(self): """Perform magnetometer calibration for current IMU."""
self.calibration_state = self.CAL_MAG self.mag_dialog = SK8MagDialog(self.sk8.get_imu(self.spinIMU.value()), self) if self.mag_dialog.exec_() == QDialog.Rejected: return self.calculate_mag_calibration(self.mag_dialog.samples)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calculate_gyro_calibration(self, gyro_samples): """Performs a basic gyroscope bias calculation. Takes a list of (x, y, z) samples and averages over each axis...
totals = [0, 0, 0] for gs in gyro_samples: totals[0] += gs[0] totals[1] += gs[1] totals[2] += gs[2] for i in range(3): totals[i] = int(float(totals[i]) / len(gyro_samples)) print('Saving gyro offsets for {}'.format(self.current_imuid)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def device_selected(self, index): """Handler for selecting a device from the list in the UI"""
device = self.devicelist_model.itemFromIndex(index) print(device.device.addr) self.btnConnect.setEnabled(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 _handle_block(self, task, disable=False): """ Handles blocking domains using hosts file. `task` ``Task`` instance. `disable` Set to ``True``, to turn off blo...
backup_file = os.path.join(task.task_dir, '.hosts.bak') self.orig_data = self.orig_data or common.readfile(backup_file) self.last_updated = self.last_updated or -1 if not self.orig_data: # should't attempt restore without good original data, bail if disable: ...
<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_option(self, option, block_name, *values): """ Parse domain values for option. """
_extra_subs = ('www', 'm', 'mobile') if len(values) == 0: # expect some values here.. raise ValueError for value in values: value = value.lower() # if it doesn't look like a protocol, assume http # (e.g. only domain supplied) if no...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sign(self, data): """ Create url-safe signed token. :param data: Data to sign :type data: object """
try: jsonstr = json.dumps(data, separators=(',', ':')) except TypeError as e: raise DataSignError(e.args[0]) else: signature = self._create_signature(jsonstr) return self._b64encode(jsonstr + '.' + signature)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unsign(self, b64msg): """ Retrieves data from signed token. :param b64msg: Token to unsign :type b64msg: str """
msg = self._b64decode(b64msg) try: body, signature = msg.rsplit('.', 1) except ValueError as e: raise MalformedSigendMessage(e.args[0]) else: if signature == self._create_signature(body): try: return json.loads(bo...
<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_file_name(content_dispo): """Extract file name from the input request body"""
# print type(content_dispo) # print repr(content_dispo) # convertion of escape string (str type) from server # to unicode object content_dispo = content_dispo.decode('unicode-escape').strip('"') file_name = "" for key_val in content_dispo.split(';'): param = key_val.strip().split('=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download(self, uuid, url, forced_file_name=None, progress_bar=True, chunk_size=256, directory=None, overwrite=False): """ download a file from LinShare using...
self.last_req_time = None url = self.get_full_url(url) self.log.debug("download url : " + url) # Building request request = urllib2.Request(url) # request.add_header('Content-Type', 'application/json; charset=UTF-8') request.add_header('Accept', 'application/json...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_field(self, field, arg=None, value=None, extended=False, hidden=False, e_type=str, required=None): """Add a new field to the current ResourceBuilder. Key...
if required is None: required = self._required if arg is None: arg = re.sub('(?!^)([A-Z]+)', r'_\1', field).lower() self._fields[field] = { 'field': field, 'arg': arg, 'value': value, 'extended': extended, 'requ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kill(self): """Kill instantiated process :raises: `AttributeError` if instantiated process doesn't seem to satisfy `constraints <relshell.daemon_shelloperato...
BaseShellOperator._close_process_input_stdin(self._batcmd.batch_to_file_s) BaseShellOperator._wait_process(self._process, self._batcmd.sh_cmd, self._success_exitcodes) BaseShellOperator._rm_process_input_tmpfiles(self._batcmd.batch_to_file_s) self._process = 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 env_timestamp(name, required=False, default=empty): """Pulls an environment variable out of the environment and parses it to a ``datetime.datetime`` object. ...
if required and default is not empty: raise ValueError("Using `default` with `required=True` is invalid") value = get_env_value(name, required=required, default=empty) # change datetime.datetime to time, return time.struct_time type if default is not empty and value is empty: return de...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def env_iso8601(name, required=False, default=empty): """Pulls an environment variable out of the environment and parses it to a ``datetime.datetime`` object. Th...
try: import iso8601 except ImportError: raise ImportError( 'Parsing iso8601 datetime strings requires the iso8601 library' ) if required and default is not empty: raise ValueError("Using `default` with `required=True` is invalid") value = get_env_value(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 _set_es_workers(self, **kwargs): """ Creates index worker instances for each class to index kwargs: ------- idx_only_base[bool]: True will only index the bas...
def make_es_worker(search_conn, es_index, es_doc_type, class_name): """ Returns a new es_worker instance args: ----- search_conn: the connection to elasticsearch es_index: the name of the elasticsearch index es_doc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _index_sub(self, uri_list, num, batch_num): """ Converts a list of uris to elasticsearch json objects args: uri_list: list of uris to convert num: the ending...
bname = '%s-%s' % (batch_num, num) log.debug("batch_num '%s' starting es_json conversion", bname) qry_data = get_all_item_data([item[0] for item in uri_list], self.tstore_conn, rdfclass=self.rdf_class) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_idx_status(self, rdf_class): """ Removes all of the index status triples from the datastore Args: ----- rdf_class: The class of items to remove the st...
sparql_template = """ DELETE {{ ?s kds:esIndexTime ?esTime . ?s kds:esIndexError ?esError . }} WHERE {{ VALUES ?rdftypes {{\n\t\t{} }} . ?s a ?rdftypes . OPTIONAL {{ ...
<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_es_ids(self): """ reads all the elasticssearch ids for an index """
search = self.search.source(['uri']).sort(['uri']) es_ids = [item.meta.id for item in search.scan()] return es_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 validate_index(self, rdf_class): """ Will compare the triplestore and elasticsearch index to ensure that that elasticsearch and triplestore items match. elas...
es_ids = set(self.get_es_ids()) tstore_ids = set([item[1] for item in self.get_uri_list(no_status=True)]) diff = es_ids - tstore_ids if diff: pdb.set_trace() action_list = self.es_worker.make_action_list(diff, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _disable_prometheus_process_collector(self) -> None: """ There is a bug in SDC' Docker implementation and intolerable prometheus_client code, due to which its...
logger.info("Removing prometheus process collector") try: core.REGISTRY.unregister(PROCESS_COLLECTOR) except KeyError: logger.debug("PROCESS_COLLECTOR already removed from prometheus")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connection(self, handshake=None): """ Connects if necessary, returns existing one if it can. :param handshake: A function to be called with the client to com...
if self._state == _State.CONNECTED: return succeed(self._current_client) elif self._state == _State.DISCONNECTING: return fail(ClientDisconnecting()) elif self._state == _State.NOT_CONNECTED: d = self._notify_on_connect() self._connect(handshake) ...
<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_single_char(func): """ Decorator that ensures that the first argument of the decorated function is a single character, i.e. a string of length one....
@functools.wraps(func) def wrapper(*args, **kwargs): if not isinstance(args[0], str) or len(args[0]) != 1: raise ValueError(( 'This function should be invoked with a string of length one ' 'as its first argument')) return func(*args, **kwargs) return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_vowel(char): """ Check whether the character is a vowel letter. """
if is_letter(char, strict=True): return char in chart.vowels 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_suprasegmental(char, strict=True): """ Check whether the character is a suprasegmental according to the IPA spec. This includes tones, word accents, an...
if (char in chart.suprasegmentals) or (char in chart.lengths): return True return is_tone(char, strict)
<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_substitutes(string): """ Return the given string with all known common substitutes replaced with their IPA-compliant counterparts. """
for non_ipa, ipa in chart.replacements.items(): string = string.replace(non_ipa, ipa) return string
<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_ipa(self, file_path): """ Populate the instance's set properties using the specified file. """
sections = { '# consonants (pulmonic)': self.consonants, '# consonants (non-pulmonic)': self.consonants, '# other symbols': self.consonants, '# tie bars': self.tie_bars, '# vowels': self.vowels, '# diacritics': self.diacritics, '# suprasegmentals': self.suprasegmentals, '# lengths': self.leng...
<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_replacements(self, file_path): """ Populate self.replacements using the specified file. """
with open(file_path, encoding='utf-8') as f: for line in map(lambda x: x.strip(), f): if line: line = line.split('\t') self.replacements[line[0]] = line[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 sort_by_name(names): """Sort by last name, uniquely."""
def last_name_key(full_name): parts = full_name.split(' ') if len(parts) == 1: return full_name.upper() last_first = parts[-1] + ' ' + ' '.join(parts[:-1]) return last_first.upper() return sorted(set(names), key=last_name_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 store_attribute(self, key, value): """Store blame info we are interested in."""
if key == 'summary' or key == 'filename' or key == 'previous': return attr = key.replace('-', '_') if key.endswith('-time'): value = int(value) setattr(self, attr, 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 is_git_file(cls, path, name): """Determine if file is known by git."""
os.chdir(path) p = subprocess.Popen(['git', 'ls-files', '--error-unmatch', name], stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.wait() return p.returncode == 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 collect_modules(self): """Generator to look for git files in tree. Will handle all lines."""
for path, dirlist, filelist in os.walk(self.root): for name in fnmatch.filter(filelist, self.filter): if self.is_git_file(path, name): yield (os.path.join(path, 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 collect_blame_info(cls, matches): """Runs git blame on files, for the specified sets of line ranges. If no line range tuples are provided, it will do all lin...
old_area = None for filename, ranges in matches: area, name = os.path.split(filename) if not area: area = '.' if area != old_area: print("\n\n%s/\n" % area) old_area = area print("%s " % name, 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 unique_authors(self, limit): """Unique list of authors, but preserving order."""
seen = set() if limit == 0: limit = None seen_add = seen.add # Assign to variable, so not resolved each time return [x.author for x in self.sorted_commits[:limit] if not (x.author in seen or seen_add(x.author))]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show(self, commit): """Display one commit line. The output will be: <uuid> <#lines> <author> <short-commit-date> If verbose flag set, the output will be: <uu...
author = commit.author author_width = 25 committer = '' commit_date = date_to_str(commit.committer_time, commit.committer_tz, self.verbose) if self.verbose: author += " %s" % commit.author_mail author_width = 50 ...
<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_user_commits(cls, commits): """Merge all the commits for the user. Aggregate line counts, and use the most recent commit (by date/time) as the represen...
user = None for commit in commits: if not user: user = commit else: if commit.committer_time > user.committer_time: commit.line_count += user.line_count user = commit else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort(self): """Sort by commit size, per author."""
# First sort commits by author email users = [] # Group commits by author email, so they can be merged for _, group in itertools.groupby(sorted(self.commits), operator.attrgetter('author_mail')): if group: users.appen...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_ranges(cls, lines): """Convert list of lines into list of line range tuples. Only will be called if there is one or more entries in the list. Single lin...
start_line = last_line = lines.pop(0) ranges = [] for line in lines: if line == (last_line + 1): last_line = line else: ranges.append((start_line, last_line)) start_line = line last_line = line range...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def determine_coverage(cls, coverage_file): """Scan the summary section of report looking for coverage data. Will see CSS class with "stm mis" (missing coverage)...
lines = [] source_file = 'ERROR' for line in coverage_file: m = title_re.match(line) if m: if m.group(2) == '100': return ('', []) source_file = m.group(1) continue m = source_re.match(line) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collect_modules(self): """Generator to obtain lines of interest from coverage report files. Will verify that the source file is within the project tree, rela...
coverage_dir = os.path.join(self.root, 'cover') for name in fnmatch.filter(os.listdir(coverage_dir), "*.html"): if name == 'index.html': continue with open(os.path.join(coverage_dir, name)) as cover_file: src_file, line_ranges = se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort(self): """Consolidate adjacent lines, if same commit ID. Will modify line number to be a range, when two or more lines with the same commit ID. """
self.sorted_commits = [] if not self.commits: return self.sorted_commits prev_commit = self.commits.pop(0) prev_line = prev_commit.line_number prev_uuid = prev_commit.uuid for commit in self.commits: if (commit.uuid != prev_uuid or ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(url, content, **args): """Put an object into a ftps URL."""
with FTPSResource(url, **args) as resource: resource.write(content)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def yaml_str_join(l, n): ''' YAML loader to join strings The keywords are as following: * `hostname`: Your hostname (from :func:`util.system.get_hostname`) * `timestamp`: Current timestamp (from :func:`util.system.get_timestamp`) :returns: A `non character` joined string |yaml_loader...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def yaml_loc_join(l, n): ''' YAML loader to join paths The keywords come directly from :func:`util.locations.get_locations`. See there! :returns: A `path seperator` (``/``) joined string |yaml_loader_returns| .. seealso:: |yaml_loader_seealso| ''' from photon.util.locations i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dict_merge(o, v): ''' Recursively climbs through dictionaries and merges them together. :param o: The first dictionary :param v: The second dictionary :returns: A dictionary (who would have guessed?) .. note:: Make sure `o` & `v` are indeed dictionaries, ...
<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_list(i, use_keys=False): ''' Converts items to a list. :param i: Item to convert * If `i` is ``None``, the result is an empty list * If `i` is 'string', the result won't be \ ``['s', 't', 'r',...]`` rather more like ``['string']`` * If `i` is a nested dictionary, t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def this(obj, **kwargs): """Prints series of debugging steps to user. Runs through pipeline of functions and print results of each. """
verbose = kwargs.get("verbose", True) if verbose: print('{:=^30}'.format(" whatis.this? ")) for func in pipeline: s = func(obj, **kwargs) if s is not None: print(s) if verbose: print('{:=^30}\n'.format(" whatis.this? "))
<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_repeat_masker_header(pairwise_alignment): """generate header string of repeatmasker formated repr of self."""
res = "" res += str(pairwise_alignment.meta[ALIG_SCORE_KEY]) + " " res += "{:.2f}".format(pairwise_alignment.meta[PCENT_SUBS_KEY]) + " " res += "{:.2f}".format(pairwise_alignment.meta[PCENT_S1_INDELS_KEY]) + " " res += "{:.2f}".format(pairwise_alignment.meta[PCENT_S2_INDELS_KEY]) + " " res += (pairwise_ali...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _rm_is_alignment_line(parts, s1_name, s2_name): """ return true if the tokenized line is a repeatmasker alignment line. :param parts: the line, already split...
if len(parts) < 2: return False if _rm_name_match(parts[0], s1_name): return True if (_rm_name_match(parts[0], s2_name) or (parts[0] == "C" and _rm_name_match(parts[1], s2_name))): 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 _rm_is_header_line(parts, n): """ determine whether a pre-split string is a repeat-masker alignment header. headers have no special structure or symbol to ma...
if (n == 15 and parts[8] == "C"): return True if (n == 14 and parts[0].isdigit()): 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 _rm_get_names_from_header(parts): """ get repeat and seq. name from repeatmasker alignment header line. An example header line is:: 239 29.42 1.92 0.97 chr1 ...
assert((parts[8] == "C" and len(parts) == 15) or (len(parts) == 14)) return (parts[4], parts[8]) if len(parts) == 14 else (parts[4], parts[9])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _rm_get_repeat_coords_from_header(parts): """ extract the repeat coordinates of a repeat masker match from a header line. An example header line is:: 239 29....
assert((parts[8] == "C" and len(parts) == 15) or (len(parts) == 14)) if len(parts) == 14: s = int(parts[9]) e = int(parts[10]) + 1 else: s = int(parts[12]) e = int(parts[11]) + 1 if (s >= e): raise AlignmentIteratorError("invalid repeatmakser header: " + " "...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _rm_name_match(s1, s2): """ determine whether two sequence names from a repeatmasker alignment match. :return: True if they are the same string, or if one fo...
m_len = min(len(s1), len(s2)) return s1[:m_len] == s2[:m_len]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _rm_extract_sequence_and_name(alig_str_parts, s1_name, s2_name): """ parse an alignment line from a repeatmasker alignment and return the name of the sequenc...
# first, based on the number of parts we have we'll guess whether its a # reverse complement or not if len(alig_str_parts) == 4: # expect the first element to amtch something.. nm = alig_str_parts[0] seq = alig_str_parts[2] elif len(alig_str_parts) == 5: # expect the second element to match som...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scan_file(path): """ Scan `path` for viruses using ``clamd`` antivirus daemon. Args: path (str): Relative or absolute path of file/directory you need to sca...
path = os.path.abspath(path) assert os.path.exists(path), "Unreachable file '%s'." % path try: cd = pyclamd.ClamdUnixSocket() cd.ping() except pyclamd.ConnectionError: cd = pyclamd.ClamdNetworkSocket() try: cd.ping() except pyclamd.ConnectionError: ...
<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_best_local_timezone(): """ Compares local timezone offset to pytz's timezone db, to determine a matching timezone name to use when TIME_ZONE is not set. ...
zone_name = tzlocal.get_localzone().zone if zone_name in pytz.all_timezones: return zone_name if time.daylight: local_offset = time.altzone localtz = time.tzname[1] else: local_offset = time.timezone localtz = time.tzname[0] local_offset = datetime.timedelta(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def topic_quick_links(context, topic, latest, last_seen_time): """ Creates topic listing page links for the given topic, with the given number of posts per page....
output_text = u'' pages = topic.page_count if not pages or pages == 0: hits = topic.post_count - 1 if hits < 1: hits = 1 pages = hits // PAGINATE_BY + 1 # determine if we need to show new link. if latest and latest.post_date_int > last_seen_time: output...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ignore_user_agent(user_agent): """ compare the useragent from the broswer to the ignore list This is popular if you want a mobile device to not trigger as mo...
if user_agent: for ua in MOBI_USER_AGENT_IGNORE_LIST: if ua and ua.lower() in user_agent.lower(): 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 process_request(request): """Adds a "mobile" attribute to the request which is True or False depending on whether the request should be considered to come fr...
if 'HTTP_X_OPERAMINI_FEATURES' in request.META: # Then it's running opera mini. 'Nuff said. # Reference from: # http://dev.opera.com/articles/view/opera-mini-request-headers/ request.mobile = True return None if 'HTTP_ACCEPT' in request.META...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_by_builder(self, builder: Builder, stats: BuildProcessStats): """ run one builder, return statistics about the run """
logger = logging.getLogger(__name__) target_signature = builder.get_signature() assert target_signature is not None, "builder signature is None" if self.cache.list_sig_ok(target_signature): logger.info("verifying [{}]".format(builder.get_name())) file_bad = 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 anomalous_score(self): """Anomalous score of this reviewer. Initial anomalous score is :math:`1 / |R|` where :math:`R` is a set of reviewers. """
return self._anomalous if self._anomalous else 1. / len(self._graph.reviewers)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def summary(self): """Summary of reviews for this product. Initial summary is computed by .. math:: \\frac{1}{|R|} \\sum_{r \\in R} \\mbox{review}(r), where :mat...
if self._summary: return self._summary reviewers = self._graph.retrieve_reviewers(self) return self._summary_cls( [self._graph.retrieve_review(r, self) for r in reviewers])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def summary(self, v): """Set summary. Args: v: A new summary. It could be a single number or lists. """
if hasattr(v, "__iter__"): self._summary = self._summary_cls(v) else: self._summary = self._summary_cls(float(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 update_summary(self, w): """Update summary. The new summary is a weighted average of reviews i.e. .. math:: \\frac{\\sum_{r \\in R} \\mbox{weight}(r) \\times...
old = self.summary.v # pylint: disable=no-member reviewers = self._graph.retrieve_reviewers(self) reviews = [self._graph.retrieve_review( r, self).score for r in reviewers] weights = [w(r.anomalous_score) for r in reviewers] if sum(weights) == 0: self.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 new_reviewer(self, name, anomalous=None): """Create a new reviewer. Args: name: name of the new reviewer. anomalous: initial anomalous score. (default: None)...
n = self._reviewer_cls( self, name=name, credibility=self.credibility, anomalous=anomalous) self.graph.add_node(n) self.reviewers.append(n) return n
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def new_product(self, name): """Create a new product. Args: name: name of the new product. Returns: A new product instance. """
n = self._product_cls(self, name, summary_cls=self._summary_cls) self.graph.add_node(n) self.products.append(n) return n
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_review(self, reviewer, product, review, date=None): """Add a new review from a given reviewer to a given product. Args: reviewer: an instance of Reviewer...
if not isinstance(reviewer, self._reviewer_cls): raise TypeError( "Type of given reviewer isn't acceptable:", reviewer, ", expected:", self._reviewer_cls) elif not isinstance(product, self._product_cls): raise TypeError( "Type of g...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retrieve_products(self, reviewer): """Retrieve products reviewed by a given reviewer. Args: reviewer: A reviewer. Returns: A list of products which the revie...
if not isinstance(reviewer, self._reviewer_cls): raise TypeError( "Type of given reviewer isn't acceptable:", reviewer, ", expected:", self._reviewer_cls) return list(self.graph.successors(reviewer))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retrieve_reviewers(self, product): """Retrieve reviewers who reviewed a given product. Args: product: A product specifying reviewers. Returns: A list of revi...
if not isinstance(product, self._product_cls): raise TypeError( "Type of given product isn't acceptable:", product, ", expected:", self._product_cls) return list(self.graph.predecessors(product))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retrieve_review(self, reviewer, product): """Retrieve review that the given reviewer put the given product. Args: reviewer: An instance of Reviewer. product:...
if not isinstance(reviewer, self._reviewer_cls): raise TypeError( "Type of given reviewer isn't acceptable:", reviewer, ", expected:", self._reviewer_cls) elif not isinstance(product, self._product_cls): raise TypeError( "Type of g...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _weight_generator(self, reviewers): """Compute a weight function for the given reviewers. Args: reviewers: a set of reviewers to compute weight function. Ret...
scores = [r.anomalous_score for r in reviewers] mu = np.average(scores) sigma = np.std(scores) if sigma: def w(v): """Compute a weight for the given reviewer. Args: v: anomalous score of a reviewer. Returns:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump_credibilities(self, output): """Dump credibilities of all products. Args: output: a writable object. """
for p in self.products: json.dump({ "product_id": p.name, "credibility": self.credibility(p) }, output) output.write("\n")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_dictionaries(a, b): """Merge two dictionaries; duplicate keys get value from b."""
res = {} for k in a: res[k] = a[k] for k in b: res[k] = b[k] return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __build_sequence(parts): """Build a sequence object using the pre-tokenized parts from a MAF line. s -- a sequence line; has 6 fields in addition to 's': * s...
strand = parts[4] seq_length = int(parts[3]) total_seq_len = int(parts[5]) start = (int(parts[2]) if strand == "+" else total_seq_len - int(parts[2]) - seq_length) end = start + seq_length remain = total_seq_len - end return Sequence(parts[1], parts[6], start, end, strand, remain)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __annotate_sequence_with_context(seq, i_line_parts): """Extract meta data from pre-tokenized maf i-line and populate sequence. i -- always come after s lines...
if i_line_parts[1] != seq.name: raise MAFError("Trying to populate meta data for sequence " + seq.name + " with i-line information for " + str(i_line_parts[1]) + "; maflormed MAF file?") if len(i_line_parts) != 6: raise MAFError("i-line with " + str(len(i_line_parts)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __annotate_sequence_with_quality(seq, q_line_parts): """Extract meta data from pre-tokenized maf q-line and populate sequence. q -- quality information about...
if q_line_parts[1] != seq.name: raise MAFError("trying to populate meta data for sequence " + seq.name + " with q-line information for " + str(q_line_parts[1]) + "; maflormed MAF file?") if len(q_line_parts[2]) != len(seq): raise MAFError("trying to populate quality me...
<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_frontmatter(file_name, title, makenew=False): """ Adds basic frontmatter to a MarkDown file that will be used in a Jekyll project. Parameters ========== ...
with open(file_name, "r+") as oldfile: # Creates new file and writes to it if specified if makenew: with open(file_name[:-3] + '_added_frontmatter.md', 'w') as newfile: newfile.write('---\n' + 'title: ' + title + '\n' + '---\n') newfile.write(oldfile.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 summarize(self, text, n): """ Return a list of n sentences which represent the summary of text. """
sents = sent_tokenize(text) assert n <= len(sents) word_sent = [word_tokenize(s.lower()) for s in sents] self._freq = self._compute_frequencies(word_sent) ranking = defaultdict(int) for i,sent in enumerate(word_sent): for w in sent: if w in self._freq: ranking[i] += 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 _rank(self, ranking, n): """ return the first n sentences with highest ranking """
return nlargest(n, ranking, key=ranking.get)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_certifier(): """ Decorator that can wrap raw functions to create a certifier function. Certifier functions support partial application. If a function wr...
def decorator(func): @six.wraps(func) def wrapper(value=_undefined, **kwargs): def certify(val): if is_enabled(): exec_func(func, val, **kwargs) return val if value is not _undefined: return certify(va...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def certify_required(value, required=False): """ Certify that a value is present if required. :param object value: The value that is to be certified. :param bool...
# Certify our kwargs: if not isinstance(required, bool): raise CertifierParamError( 'required', required, ) if value is None: if required: raise CertifierValueError( message="required value is None", ) return Tr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def certify_parameter(certifier, name, value, kwargs=None): """ Internal certifier for kwargs passed to Certifiable public methods. :param callable certifier: Th...
try: certifier(value, **kwargs or {}) except CertifierError as err: six.raise_from( CertifierParamError( name, value, ), 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 enable_from_env(state=None): """ Enable certification for this thread based on the environment variable `CERTIFIABLE_STATE`. :param bool state: Default statu...
try: x = os.environ.get( ENVVAR, state, ) value = bool(int(x)) except Exception: # pylint: disable=broad-except value = bool(state) return enable(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 compete(source_x, source_o, timeout=None, memlimit=None, cgroup='tictactoe', cgroup_path='/sys/fs/cgroup'): """Fights two source files. Returns either: * ('o...
gameplay = [] for xo, moveresult, log in run_interactive(source_x, source_o, timeout, memlimit, cgroup, cgroup_path): if moveresult[0] == 'error': return 'error', xo, moveresult[1], gameplay + [0] elif moveresult[0] == 'state_coords': ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _fix_key(key): '''Normalize keys to Unicode strings.''' if isinstance(key, unicode): return key if isinstance(key, str): # On my system, the default encoding is `ascii`, so let's # explicitly say UTF-8? return unicode(key, 'utf-8') rais...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def truncate_most_common(self, truncation_length): ''' Sorts the counter and keeps only the most common items up to ``truncation_length`` in place. :type truncation_length: int ''' keep_keys = set(v[0] for v in self.most_common(truncation_length)) for key in 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 rst(value_rule): '''Given the data and type information, generate a list of strings for insertion into a RST document. ''' lines = [] if value_rule.has('type'): value_type = value_rule['type'].value else: value_type = 'string' if value_type=='ignore': pass els...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def circle_touching_line(center, radius, start, end): """ Return true if the given circle intersects the given segment. Note that this checks for intersection wi...
C, R = center, radius A, B = start, end a = (B.x - A.x)**2 + (B.y - A.y)**2 b = 2 * (B.x - A.x) * (A.x - C.x) \ + 2 * (B.y - A.y) * (A.y - C.y) c = C.x**2 + C.y**2 + A.x**2 + A.y**2 \ - 2 * (C.x * A.x + C.y * A.y) - R**2 discriminant = b**2 - 4 * a * c if...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate(self, overwrite=False): """Generate a config file for an upstart service. """
super(Upstart, self).generate(overwrite=overwrite) svc_file_template = self.template_prefix + '.conf' self.svc_file_path = self.generate_into_prefix + '.conf' self.generate_file_from_template(svc_file_template, self.svc_file_path) return self.files
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fetch(self, default_path): """ Internal method for fetching. This differs from :meth:`.fetch` in that it accepts a default path as an argument. """
if not self._path: path = default_path else: path = self._path req_type = 'GET' if len(self._post_params) == 0 else 'POST' url = '/'.join(['http:/', self.spacegdn.endpoint, path]) resp = requests.request(req_type, url, params=self._get_params, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def tokens(self, si, k): '''`si` is a stream item and `k` is a key in this feature. The purpose of this method is to dereference the token pointers with respect to the given stream item. That is, it translates each sequence of token pointers to a sequence of `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 get_lines(fname): """Return generator with line number and line for file `fname`."""
for line in fileinput.input(fname): yield fileinput.filelineno(), 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 tonicdns_client(uri, method, token='', data='', keyword='', content='', raw_flag=False): """TonicDNS API client Arguments: uri: TonicDNS API URI method: Toni...
res = request(uri, method, data, token) if token: if keyword == 'serial': args = {"token": token, "keyword": keyword, "content": content} cur_soa, new_soa = response(uri, method, res, **args) return cur_soa, new_soa else: if content 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(uri, method, data, token=''): """Request to TonicDNS API. Arguments: uri: TonicDNS API URI method: TonicDNS API request method data: Post data to Ton...
socket.setdefaulttimeout(__timeout__) obj = urllib.build_opener(urllib.HTTPHandler) # encoding json encoded = json.JSONEncoder(object).encode(data) # encoding utf8 data_utf8 = encoded.encode('utf-8') req = urllib.Request(uri, data=data_utf8) # When encoded(=data) is False, retrieve ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def response(uri, method, res, token='', keyword='', content='', raw_flag=False): """Response of tonicdns_client request Arguments: uri: TonicDNS API URI method:...
if method == 'GET' or (method == 'PUT' and not token): # response body data = res.read() data_utf8 = data.decode('utf-8') if token: datas = json.loads(data_utf8) else: token = json.loads(data_utf8)['hash'] return token if keyword ...
<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_record(datas, keyword): """Search target JSON -> dictionary Arguments: datas: dictionary of record datas keyword: search keyword (default is null) Key...
key_name, key_type, key_content = False, False, False if keyword.find(',') > -1: if len(keyword.split(',')) == 3: key_content = keyword.split(',')[2] key_name = keyword.split(',')[0] key_type = keyword.split(',')[1] result = [] for record in datas['records']: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_formatted(datas): """Pretty print JSON DATA Argument: datas: dictionary of data """
if not datas: print("No data") exit(1) if isinstance(datas, list): # get all zones # API /zone without :identifier hr() print('%-20s %-8s %-12s' % ('name', 'type', 'notified_serial')) hr() for record in datas: # print '...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute_deferred_effects(self, pos): """ Evaluates deferred effects that are triggered by the prefix of the pos on the current beliefstate. For instance, if ...
costs = 0 to_delete = [] for entry in self.__dict__['deferred_effects']: effect_pos, effect = entry if pos.startswith(effect_pos): costs += effect(self) to_delete.append(entry) # we delete afterwards, because Python cannot delete 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 set_environment_variable(self, key, val): """ Sets a variable if that variable is not already set """
if self.get_environment_variable(key) in [None, val]: self.__dict__['environment_variables'][key] = val else: raise Contradiction("Could not set environment variable %s" % (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 iter_breadth_first(self, root=None): """ Traverses the belief state's structure breadth-first """
if root == None: root = self yield root last = root for node in self.iter_breadth_first(root): if isinstance(node, DictCell): # recurse for subpart in node: yield subpart last = subpart ...
<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_path(self, test_function=None, on_targets=False): """ General helper method that iterates breadth-first over the referential_domain's cells and returns ...
assert self.has_referential_domain(), "need context set" if not test_function: test_function = lambda x, y: True def find_path_inner(part, prefix): name, structure = part if test_function(name, structure): yield prefix + [name] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_nth_unique_value(self, keypath, n, distance_from, open_interval=True): """ Returns the `n-1`th unique value, or raises a contradiction if that is out of ...
unique_values = self.get_ordered_values(keypath, distance_from, open_interval) if 0 <= n < len(unique_values): #logging.error("%i th unique value is %s" % (n, str(unique_values[n]))) return unique_values[n] else: raise Contradiction("n-th Unique value out of ...