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 diff_prettyHtml(self, diffs): """Convert a diff array into a pretty HTML report. Args: diffs: Array of diff tuples. Returns: HTML representation. """
html = [] for (op, data) in diffs: text = (data.replace("&", "&amp;").replace("<", "&lt;") .replace(">", "&gt;").replace("\n", "&para;<br>")) if op == self.DIFF_INSERT: html.append("<ins style=\"background:#e6ffe6;\">%s</ins>" % text) elif op == self.DIFF_DELETE: html.append("<del style=\"background:#ffe6e6;\">%s</del>" % text) elif op == self.DIFF_EQUAL: html.append("<span>%s</span>" % text) return "".join(html)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diff_levenshtein(self, diffs): """Compute the Levenshtein distance; the number of inserted, deleted or substituted characters. Args: diffs: Array of diff tuples. Returns: Number of changes. """
levenshtein = 0 insertions = 0 deletions = 0 for (op, data) in diffs: if op == self.DIFF_INSERT: insertions += len(data) elif op == self.DIFF_DELETE: deletions += len(data) elif op == self.DIFF_EQUAL: # A deletion and an insertion is one substitution. levenshtein += max(insertions, deletions) insertions = 0 deletions = 0 levenshtein += max(insertions, deletions) return levenshtein
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diff_fromDelta(self, text1, delta): """Given the original text1, and an encoded string which describes the operations required to transform text1 into text2, compute the full diff. Args: text1: Source string for the diff. delta: Delta text. Returns: Array of diff tuples. Raises: ValueError: If invalid input. """
diffs = [] pointer = 0 # Cursor in text1 tokens = delta.split("\t") for token in tokens: if token == "": # Blank tokens are ok (from a trailing \t). continue # Each token begins with a one character parameter which specifies the # operation of this token (delete, insert, equality). param = token[1:] if token[0] == "+": param = urllib.parse.unquote(param) diffs.append((self.DIFF_INSERT, param)) elif token[0] == "-" or token[0] == "=": try: n = int(param) except ValueError: raise ValueError("Invalid number in diff_fromDelta: " + param) if n < 0: raise ValueError("Negative number in diff_fromDelta: " + param) text = text1[pointer : pointer + n] pointer += n if token[0] == "=": diffs.append((self.DIFF_EQUAL, text)) else: diffs.append((self.DIFF_DELETE, text)) else: # Anything else is an error. raise ValueError("Invalid diff operation in diff_fromDelta: " + token[0]) if pointer != len(text1): raise ValueError( "Delta length (%d) does not equal source text length (%d)." % (pointer, len(text1))) return diffs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def match_main(self, text, pattern, loc): """Locate the best instance of 'pattern' in 'text' near 'loc'. Args: text: The text to search. pattern: The pattern to search for. loc: The location to search around. Returns: Best match index or -1. """
# Check for null inputs. if text == None or pattern == None: raise ValueError("Null inputs. (match_main)") loc = max(0, min(loc, len(text))) if text == pattern: # Shortcut (potentially not guaranteed by the algorithm) return 0 elif not text: # Nothing to match. return -1 elif text[loc:loc + len(pattern)] == pattern: # Perfect match at the perfect spot! (Includes case of null pattern) return loc else: # Do a fuzzy compare. match = self.match_bitap(text, pattern, loc) return match
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def match_bitap(self, text, pattern, loc): """Locate the best instance of 'pattern' in 'text' near 'loc' using the Bitap algorithm. Args: text: The text to search. pattern: The pattern to search for. loc: The location to search around. Returns: Best match index or -1. """
# Python doesn't have a maxint limit, so ignore this check. #if self.Match_MaxBits != 0 and len(pattern) > self.Match_MaxBits: # raise ValueError("Pattern too long for this application.") # Initialise the alphabet. s = self.match_alphabet(pattern) def match_bitapScore(e, x): """Compute and return the score for a match with e errors and x location. Accesses loc and pattern through being a closure. Args: e: Number of errors in match. x: Location of match. Returns: Overall score for match (0.0 = good, 1.0 = bad). """ accuracy = float(e) / len(pattern) proximity = abs(loc - x) if not self.Match_Distance: # Dodge divide by zero error. return proximity and 1.0 or accuracy return accuracy + (proximity / float(self.Match_Distance)) # Highest score beyond which we give up. score_threshold = self.Match_Threshold # Is there a nearby exact match? (speedup) best_loc = text.find(pattern, loc) if best_loc != -1: score_threshold = min(match_bitapScore(0, best_loc), score_threshold) # What about in the other direction? (speedup) best_loc = text.rfind(pattern, loc + len(pattern)) if best_loc != -1: score_threshold = min(match_bitapScore(0, best_loc), score_threshold) # Initialise the bit arrays. matchmask = 1 << (len(pattern) - 1) best_loc = -1 bin_max = len(pattern) + len(text) # Empty initialization added to appease pychecker. last_rd = None for d in range(len(pattern)): # Scan for the best match each iteration allows for one more error. # Run a binary search to determine how far from 'loc' we can stray at # this error level. bin_min = 0 bin_mid = bin_max while bin_min < bin_mid: if match_bitapScore(d, loc + bin_mid) <= score_threshold: bin_min = bin_mid else: bin_max = bin_mid bin_mid = (bin_max - bin_min) // 2 + bin_min # Use the result from this iteration as the maximum for the next. bin_max = bin_mid start = max(1, loc - bin_mid + 1) finish = min(loc + bin_mid, len(text)) + len(pattern) rd = [0] * (finish + 2) rd[finish + 1] = (1 << d) - 1 for j in range(finish, start - 1, -1): if len(text) <= j - 1: # Out of range. charMatch = 0 else: charMatch = s.get(text[j - 1], 0) if d == 0: # First pass: exact match. rd[j] = ((rd[j + 1] << 1) | 1) & charMatch else: # Subsequent passes: fuzzy match. rd[j] = (((rd[j + 1] << 1) | 1) & charMatch) | ( ((last_rd[j + 1] | last_rd[j]) << 1) | 1) | last_rd[j + 1] if rd[j] & matchmask: score = match_bitapScore(d, j - 1) # This match will almost certainly be better than any existing match. # But check anyway. if score <= score_threshold: # Told you so. score_threshold = score best_loc = j - 1 if best_loc > loc: # When passing loc, don't exceed our current distance from loc. start = max(1, 2 * loc - best_loc) else: # Already passed loc, downhill from here on in. break # No hope for a (better) match at greater error levels. if match_bitapScore(d + 1, loc) > score_threshold: break last_rd = rd return best_loc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch_addContext(self, patch, text): """Increase the context until it is unique, but don't let the pattern expand beyond Match_MaxBits. Args: patch: The patch to grow. text: Source text. """
if len(text) == 0: return pattern = text[patch.start2 : patch.start2 + patch.length1] padding = 0 # Look for the first and last matches of pattern in text. If two different # matches are found, increase the pattern length. while (text.find(pattern) != text.rfind(pattern) and (self.Match_MaxBits == 0 or len(pattern) < self.Match_MaxBits - self.Patch_Margin - self.Patch_Margin)): padding += self.Patch_Margin pattern = text[max(0, patch.start2 - padding) : patch.start2 + patch.length1 + padding] # Add one chunk for good luck. padding += self.Patch_Margin # Add the prefix. prefix = text[max(0, patch.start2 - padding) : patch.start2] if prefix: patch.diffs[:0] = [(self.DIFF_EQUAL, prefix)] # Add the suffix. suffix = text[patch.start2 + patch.length1 : patch.start2 + patch.length1 + padding] if suffix: patch.diffs.append((self.DIFF_EQUAL, suffix)) # Roll back the start points. patch.start1 -= len(prefix) patch.start2 -= len(prefix) # Extend lengths. patch.length1 += len(prefix) + len(suffix) patch.length2 += len(prefix) + len(suffix)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch_deepCopy(self, patches): """Given an array of patches, return another array that is identical. Args: patches: Array of Patch objects. Returns: Array of Patch objects. """
patchesCopy = [] for patch in patches: patchCopy = patch_obj() # No need to deep copy the tuples since they are immutable. patchCopy.diffs = patch.diffs[:] patchCopy.start1 = patch.start1 patchCopy.start2 = patch.start2 patchCopy.length1 = patch.length1 patchCopy.length2 = patch.length2 patchesCopy.append(patchCopy) return patchesCopy
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch_addPadding(self, patches): """Add some padding on text start and end so that edges can match something. Intended to be called only from within patch_apply. Args: patches: Array of Patch objects. Returns: The padding string added to each side. """
paddingLength = self.Patch_Margin nullPadding = "" for x in range(1, paddingLength + 1): nullPadding += chr(x) # Bump all the patches forward. for patch in patches: patch.start1 += paddingLength patch.start2 += paddingLength # Add some padding on start of first diff. patch = patches[0] diffs = patch.diffs if not diffs or diffs[0][0] != self.DIFF_EQUAL: # Add nullPadding equality. diffs.insert(0, (self.DIFF_EQUAL, nullPadding)) patch.start1 -= paddingLength # Should be 0. patch.start2 -= paddingLength # Should be 0. patch.length1 += paddingLength patch.length2 += paddingLength elif paddingLength > len(diffs[0][1]): # Grow first equality. extraLength = paddingLength - len(diffs[0][1]) newText = nullPadding[len(diffs[0][1]):] + diffs[0][1] diffs[0] = (diffs[0][0], newText) patch.start1 -= extraLength patch.start2 -= extraLength patch.length1 += extraLength patch.length2 += extraLength # Add some padding on end of last diff. patch = patches[-1] diffs = patch.diffs if not diffs or diffs[-1][0] != self.DIFF_EQUAL: # Add nullPadding equality. diffs.append((self.DIFF_EQUAL, nullPadding)) patch.length1 += paddingLength patch.length2 += paddingLength elif paddingLength > len(diffs[-1][1]): # Grow last equality. extraLength = paddingLength - len(diffs[-1][1]) newText = diffs[-1][1] + nullPadding[:extraLength] diffs[-1] = (diffs[-1][0], newText) patch.length1 += extraLength patch.length2 += extraLength return nullPadding
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch_toText(self, patches): """Take a list of patches and return a textual representation. Args: patches: Array of Patch objects. Returns: Text representation of patches. """
text = [] for patch in patches: text.append(str(patch)) return "".join(text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diff_toDelta(self, diffs): """Crush the diff into an encoded string which describes the operations required to transform text1 into text2. E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'. Operations are tab-separated. Inserted text is escaped using %xx notation. Args: diffs: Array of diff tuples. Returns: Delta text. """
text = [] for (op, data) in diffs: if op == self.DIFF_INSERT: # High ascii will raise UnicodeDecodeError. Use Unicode instead. data = data.encode("utf-8") text.append("+" + urllib.quote(data, "!~*'();/?:@&=+$,# ")) elif op == self.DIFF_DELETE: text.append("-%d" % len(data)) elif op == self.DIFF_EQUAL: text.append("=%d" % len(data)) return "\t".join(text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch_fromText(self, textline): """Parse a textual representation of patches and return a list of patch objects. Args: textline: Text representation of patches. Returns: Array of Patch objects. Raises: ValueError: If invalid input. """
if type(textline) == unicode: # Patches should be composed of a subset of ascii chars, Unicode not # required. If this encode raises UnicodeEncodeError, patch is invalid. textline = textline.encode("ascii") patches = [] if not textline: return patches text = textline.split('\n') while len(text) != 0: m = re.match("^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$", text[0]) if not m: raise ValueError("Invalid patch string: " + text[0]) patch = patch_obj() patches.append(patch) patch.start1 = int(m.group(1)) if m.group(2) == '': patch.start1 -= 1 patch.length1 = 1 elif m.group(2) == '0': patch.length1 = 0 else: patch.start1 -= 1 patch.length1 = int(m.group(2)) patch.start2 = int(m.group(3)) if m.group(4) == '': patch.start2 -= 1 patch.length2 = 1 elif m.group(4) == '0': patch.length2 = 0 else: patch.start2 -= 1 patch.length2 = int(m.group(4)) del text[0] while len(text) != 0: if text[0]: sign = text[0][0] else: sign = '' line = urllib.unquote(text[0][1:]) line = line.decode("utf-8") if sign == '+': # Insertion. patch.diffs.append((self.DIFF_INSERT, line)) elif sign == '-': # Deletion. patch.diffs.append((self.DIFF_DELETE, line)) elif sign == ' ': # Minor equality. patch.diffs.append((self.DIFF_EQUAL, line)) elif sign == '@': # Start of next patch. break elif sign == '': # Blank line? Whatever. pass else: # WTF? raise ValueError("Invalid patch mode: '%s'\n%s" % (sign, line)) del text[0] return patches
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diff_trees(left, right, diff_options=None, formatter=None): """Takes two lxml root elements or element trees"""
if formatter is not None: formatter.prepare(left, right) if diff_options is None: diff_options = {} differ = diff.Differ(**diff_options) diffs = differ.diff(left, right) if formatter is None: return list(diffs) return formatter.format(diffs, left)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diff_texts(left, right, diff_options=None, formatter=None): """Takes two Unicode strings containing XML"""
return _diff(etree.fromstring, left, right, diff_options=diff_options, formatter=formatter)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diff_files(left, right, diff_options=None, formatter=None): """Takes two filenames or streams, and diffs the XML in those files"""
return _diff(etree.parse, left, right, diff_options=diff_options, formatter=formatter)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch_tree(actions, tree): """Takes an lxml root element or element tree, and a list of actions"""
patcher = patch.Patcher() return patcher.patch(actions, tree)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch_text(actions, tree): """Takes a string with XML and a string with actions"""
tree = etree.fromstring(tree) actions = patch.DiffParser().parse(actions) tree = patch_tree(actions, tree) return etree.tounicode(tree)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch_file(actions, tree): """Takes two filenames or streams, one with XML the other a diff"""
tree = etree.parse(tree) if isinstance(actions, six.string_types): # It's a string, so it's a filename with open(actions) as f: actions = f.read() else: # We assume it's a stream actions = actions.read() actions = patch.DiffParser().parse(actions) tree = patch_tree(actions, tree) return etree.tounicode(tree)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def url_to_text(self, url): ''' Download PDF file and transform its document to string. Args: url: PDF url. Returns: string. ''' path, headers = urllib.request.urlretrieve(url) return self.path_to_text(path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def path_to_text(self, path): ''' Transform local PDF file to string. Args: path: path to PDF file. Returns: string. ''' rsrcmgr = PDFResourceManager() retstr = StringIO() codec = 'utf-8' laparams = LAParams() device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams) fp = open(path, 'rb') interpreter = PDFPageInterpreter(rsrcmgr, device) password = "" maxpages = 0 caching = True pagenos = set() pages_data = PDFPage.get_pages( fp, pagenos, maxpages=maxpages, password=password, caching=caching, check_extractable=True ) for page in pages_data: interpreter.process_page(page) text = retstr.getvalue() text = text.replace("\n", "") fp.close() device.close() retstr.close() return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def listup_sentence(self, data, counter=0): ''' Divide string into sentence list. Args: data: string. counter: recursive counter. Returns: List of sentences. ''' delimiter = self.delimiter_list[counter] sentence_list = [] [sentence_list.append(sentence + delimiter) for sentence in data.split(delimiter) if sentence != ""] if counter + 1 < len(self.delimiter_list): sentence_list_r = [] [sentence_list_r.extend(self.listup_sentence(sentence, counter+1)) for sentence in sentence_list] sentence_list = sentence_list_r return sentence_list
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def observe(self, success, failure): ''' Observation data. Args: success: The number of success. failure: The number of failure. ''' if isinstance(success, int) is False: if isinstance(success, float) is False: raise TypeError() if isinstance(failure, int) is False: if isinstance(failure, float) is False: raise TypeError() if success <= 0: raise ValueError() if failure <= 0: raise ValueError() self.__success += success self.__failure += failure
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def likelihood(self): ''' Compute likelihood. Returns: likelihood. ''' try: likelihood = self.__success / (self.__success + self.__failure) except ZeroDivisionError: likelihood = 0.0 return likelihood
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def expected_value(self): ''' Compute expected value. Returns: Expected value. ''' alpha = self.__success + self.__default_alpha beta = self.__failure + self.__default_beta try: expected_value = alpha / (alpha + beta) except ZeroDivisionError: expected_value = 0.0 return expected_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 variance(self): ''' Compute variance. Returns: variance. ''' alpha = self.__success + self.__default_alpha beta = self.__failure + self.__default_beta try: variance = alpha * beta / ((alpha + beta) ** 2) * (alpha + beta + 1) except ZeroDivisionError: variance = 0.0 return variance
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def __move(self, current_pos): ''' Move in the feature map. Args: current_pos: The now position. Returns: The next position. ''' if self.__move_range is not None: next_pos = np.random.randint(current_pos - self.__move_range, current_pos + self.__move_range) if next_pos < 0: next_pos = 0 elif next_pos >= self.var_arr.shape[0] - 1: next_pos = self.var_arr.shape[0] - 1 return next_pos else: next_pos = np.random.randint(self.var_arr.shape[0] - 1) return next_pos
<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, document, Abstractor, similarity_filter=None): ''' Execute summarization. Args: document: The target document. Abstractor: The object of AbstractableDoc. similarity_filter The object of SimilarityFilter. Returns: dict data. - "summarize_result": The list of summarized sentences., - "scoring_data": The list of scores. ''' if isinstance(document, str) is False: raise TypeError("The type of document must be str.") if isinstance(Abstractor, AbstractableDoc) is False: raise TypeError("The type of Abstractor must be AbstractableDoc.") if isinstance(similarity_filter, SimilarityFilter) is False and similarity_filter is not None: raise TypeError("The type of similarity_filter must be SimilarityFilter.") normalized_sentences = self.listup_sentence(document) # for filtering similar sentences. if similarity_filter is not None: normalized_sentences = similarity_filter.similar_filter_r(normalized_sentences) self.tokenize(document) words = self.token fdist = nltk.FreqDist(words) top_n_words = [w[0] for w in fdist.items()][:self.target_n] scored_list = self.__closely_associated_score(normalized_sentences, top_n_words) filtered_list = Abstractor.filter(scored_list) result_list = [normalized_sentences[idx] for (idx, score) in filtered_list] result_dict = { "summarize_result": result_list, "scoring_data": filtered_list } return result_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 __closely_associated_score(self, normalized_sentences, top_n_words): ''' Scoring the sentence with closely associations. Args: normalized_sentences: The list of sentences. top_n_words: Important sentences. Returns: The list of scores. ''' scores_list = [] sentence_idx = -1 for sentence in normalized_sentences: self.tokenize(sentence) sentence = self.token sentence_idx += 1 word_idx = [] for w in top_n_words: try: word_idx.append(sentence.index(w)) except ValueError: pass word_idx.sort() if len(word_idx) == 0: continue clusters = [] cluster = [word_idx[0]] i = 1 while i < len(word_idx): if word_idx[i] - word_idx[i - 1] < self.cluster_threshold: cluster.append(word_idx[i]) else: clusters.append(cluster[:]) cluster = [word_idx[i]] i += 1 clusters.append(cluster) max_cluster_score = 0 for c in clusters: significant_words_in_cluster = len(c) total_words_in_cluster = c[-1] - c[0] + 1 score = 1.0 * significant_words_in_cluster \ * significant_words_in_cluster / total_words_in_cluster if score > max_cluster_score: max_cluster_score = score scores_list.append((sentence_idx, score)) return scores_list
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def learn(self, initial_state_key, limit=1000, game_n=1): ''' Multi-Agent Learning. Override. Args: initial_state_key: Initial state. limit: Limit of the number of learning. game_n: The number of games. ''' end_flag = False state_key_list = [None] * len(self.q_learning_list) action_key_list = [None] * len(self.q_learning_list) next_action_key_list = [None] * len(self.q_learning_list) for game in range(game_n): state_key = initial_state_key self.t = 1 while self.t <= limit: for i in range(len(self.q_learning_list)): state_key_list[i] = state_key if game + 1 == game_n: self.state_key_list.append(tuple(i, state_key_list)) self.q_learning_list[i].t = self.t next_action_list = self.q_learning_list[i].extract_possible_actions(tuple(i, state_key_list)) if len(next_action_list): action_key = self.q_learning_list[i].select_action( state_key=tuple(i, state_key_list), next_action_list=next_action_list ) action_key_list[i] = action_key reward_value = self.q_learning_list[i].observe_reward_value( tuple(i, state_key_list), tuple(i, action_key_list) ) # Check. if self.q_learning_list[i].check_the_end_flag(tuple(i, state_key_list)) is True: end_flag = True # Max-Q-Value in next action time. next_next_action_list = self.q_learning_list[i].extract_possible_actions( tuple(i, action_key_list) ) if len(next_next_action_list): next_action_key = self.q_learning_list[i].predict_next_action( tuple(i, action_key_list), next_next_action_list ) next_action_key_list[i] = next_action_key next_max_q = self.q_learning_list[i].extract_q_df( tuple(i, action_key_list), next_action_key ) # Update Q-Value. self.q_learning_list[i].update_q( state_key=tuple(i, state_key_list), action_key=tuple(i, action_key_list), reward_value=reward_value, next_max_q=next_max_q ) # Update State. state_key = self.q_learning_list[i].update_state( state_key=tuple(i, state_key_list), action_key=tuple(i, action_key_list) ) state_key_list[i] = state_key # Epsode. self.t += 1 self.q_learning_list[i].t = self.t if end_flag is True: break
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_model(self): ''' `object` of model as a function approximator, which has `cnn` whose type is `pydbm.cnn.pydbm.cnn.convolutional_neural_network.ConvolutionalNeuralNetwork`. ''' class Model(object): def __init__(self, cnn): self.cnn = cnn return Model(self.__cnn)
<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_state(self, state_arr, action_arr): ''' Update state. Override. Args: state_arr: `np.ndarray` of state in `self.t`. action_arr: `np.ndarray` of action in `self.t`. Returns: `np.ndarray` of state in `self.t+1`. ''' x, y = np.where(action_arr[-1] == 1) self.__agent_pos = (x[0], y[0]) self.__route_memory_list.append((x[0], y[0])) self.__route_long_memory_list.append((x[0], y[0])) self.__route_long_memory_list = list(set(self.__route_long_memory_list)) while len(self.__route_memory_list) > self.__memory_num: self.__route_memory_list = self.__route_memory_list[1:] return self.extract_now_state()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def initialize(self, map_arr, start_point_label="S", end_point_label="G", wall_label="#", agent_label="@"): ''' Initialize map of maze and setup reward value. Args: map_arr: Map. the 2d- `np.ndarray`. start_point_label: Label of start point. end_point_label: Label of end point. wall_label: Label of wall. agent_label: Label of agent. ''' np.set_printoptions(threshold=np.inf) self.__agent_label = agent_label self.__map_arr = map_arr self.__start_point_label = start_point_label start_arr_tuple = np.where(self.__map_arr == self.__start_point_label) x_arr, y_arr = start_arr_tuple self.__start_point_tuple = (x_arr[0], y_arr[0]) end_arr_tuple = np.where(self.__map_arr == self.__end_point_label) x_arr, y_arr = end_arr_tuple self.__end_point_tuple = (x_arr[0], y_arr[0]) self.__wall_label = wall_label for x in range(self.__map_arr.shape[1]): for y in range(self.__map_arr.shape[0]): if (x, y) == self.__start_point_tuple or (x, y) == self.__end_point_tuple: continue arr_value = self.__map_arr[y][x] if arr_value == self.__wall_label: continue self.save_r_df((x, y), float(arr_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 visualize_learning_result(self, state_key): ''' Visualize learning result. ''' x, y = state_key map_arr = copy.deepcopy(self.__map_arr) goal_point_tuple = np.where(map_arr == self.__end_point_label) goal_x, goal_y = goal_point_tuple map_arr[y][x] = "@" self.__map_arr_list.append(map_arr) if goal_x == x and goal_y == y: for i in range(10): key = len(self.__map_arr_list) - (10 - i) print("Number of searches: " + str(key)) print(self.__map_arr_list[key]) print("Total number of searches: " + str(self.t)) print(self.__map_arr_list[-1]) print("Goal !!")
<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_r_value(self): ''' Normalize r-value. Override. This method is called in each learning steps. For example: self.r_df = self.r_df.r_value / self.r_df.r_value.sum() ''' if self.r_df is not None and self.r_df.shape[0]: # z-score normalization. self.r_df.r_value = (self.r_df.r_value - self.r_df.r_value.mean()) / self.r_df.r_value.std()
<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_alpha_value(self): ''' getter Learning rate. ''' if isinstance(self.__alpha_value, float) is False: raise TypeError("The type of __alpha_value must be float.") return self.__alpha_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 set_alpha_value(self, value): ''' setter Learning rate. ''' if isinstance(value, float) is False: raise TypeError("The type of __alpha_value must be float.") self.__alpha_value = 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 get_gamma_value(self): ''' getter Gamma value. ''' if isinstance(self.__gamma_value, float) is False: raise TypeError("The type of __gamma_value must be float.") return self.__gamma_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 set_gamma_value(self, value): ''' setter Gamma value. ''' if isinstance(value, float) is False: raise TypeError("The type of __gamma_value must be float.") self.__gamma_value = 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 filter(self, scored_list): ''' Filtering with top-n ranking. Args: scored_list: The list of scoring. Retruns: The list of filtered result. ''' top_n_key = -1 * self.top_n top_n_list = sorted(scored_list, key=lambda x: x[1])[top_n_key:] result_list = sorted(top_n_list, key=lambda x: x[0]) return result_list
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def tokenize(self, data): ''' Tokenize sentence. Args: [n-gram, n-gram, n-gram, ...] ''' super().tokenize(data) token_tuple_zip = self.n_gram.generate_tuple_zip(self.token, self.n) token_list = [] self.token = ["".join(list(token_tuple)) for token_tuple in token_tuple_zip]
<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_q_df(self, state_key, action_key): ''' Extract Q-Value from `self.q_df`. Args: state_key: The key of state. action_key: The key of action. Returns: Q-Value. ''' q = 0.0 if self.q_df is None: self.save_q_df(state_key, action_key, q) return q q_df = self.q_df[self.q_df.state_key == state_key] q_df = q_df[q_df.action_key == action_key] if q_df.shape[0]: q = float(q_df["q_value"]) else: self.save_q_df(state_key, action_key, q) return q
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def save_q_df(self, state_key, action_key, q_value): ''' Insert or update Q-Value in `self.q_df`. Args: state_key: State. action_key: Action. q_value: Q-Value. Exceptions: TypeError: If the type of `q_value` is not float. ''' if isinstance(q_value, float) is False: raise TypeError("The type of q_value must be float.") new_q_df = pd.DataFrame([(state_key, action_key, q_value)], columns=["state_key", "action_key", "q_value"]) if self.q_df is not None: self.q_df = pd.concat([new_q_df, self.q_df]) self.q_df = self.q_df.drop_duplicates(["state_key", "action_key"]) else: self.q_df = new_q_df
<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_t(self): ''' getter Time. ''' if isinstance(self.__t, int) is False: raise TypeError("The type of __t must be int.") return self.__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 set_t(self, value): ''' setter Time. ''' if isinstance(value, int) is False: raise TypeError("The type of __t must be int.") self.__t = 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 update_q(self, state_key, action_key, reward_value, next_max_q): ''' Update Q-Value. Args: state_key: The key of state. action_key: The key of action. reward_value: R-Value(Reward). next_max_q: Maximum Q-Value. ''' # Now Q-Value. q = self.extract_q_df(state_key, action_key) # Update Q-Value. new_q = q + self.alpha_value * (reward_value + (self.gamma_value * next_max_q) - q) # Save updated Q-Value. self.save_q_df(state_key, action_key, new_q)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def predict_next_action(self, state_key, next_action_list): ''' Predict next action by Q-Learning. Args: state_key: The key of state in `self.t+1`. next_action_list: The possible action in `self.t+1`. Returns: The key of action. ''' if self.q_df is not None: next_action_q_df = self.q_df[self.q_df.state_key == state_key] next_action_q_df = next_action_q_df[next_action_q_df.action_key.isin(next_action_list)] if next_action_q_df.shape[0] == 0: return random.choice(next_action_list) else: if next_action_q_df.shape[0] == 1: max_q_action = next_action_q_df["action_key"].values[0] else: next_action_q_df = next_action_q_df.sort_values(by=["q_value"], ascending=False) max_q_action = next_action_q_df.iloc[0, :]["action_key"] return max_q_action else: return random.choice(next_action_list)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def pull(self, arm_id, success, failure): ''' Pull arms. Args: arm_id: Arms master id. success: The number of success. failure: The number of failure. ''' self.__beta_dist_dict[arm_id].observe(success, failure)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def recommend(self, limit=10): ''' Listup arms and expected value. Args: limit: Length of the list. Returns: [Tuple(`Arms master id`, `expected value`)] ''' expected_list = [(arm_id, beta_dist.expected_value()) for arm_id, beta_dist in self.__beta_dist_dict.items()] expected_list = sorted(expected_list, key=lambda x: x[1], reverse=True) return expected_list[:limit]
<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_time_rate(self): ''' getter Time rate. ''' if isinstance(self.__time_rate, float) is False: raise TypeError("The type of __time_rate must be float.") if self.__time_rate <= 0.0: raise ValueError("The value of __time_rate must be greater than 0.0") return self.__time_rate
<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_time_rate(self, value): ''' setter Time rate. ''' if isinstance(value, float) is False: raise TypeError("The type of __time_rate must be float.") if value <= 0.0: raise ValueError("The value of __time_rate must be greater than 0.0") self.__time_rate = 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 __calculate_sigmoid(self): ''' Function of temperature. Returns: Sigmoid. ''' sigmoid = 1 / np.log(self.t * self.time_rate + 1.1) return sigmoid
<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_boltzmann_factor(self, state_key, next_action_list): ''' Calculate boltzmann factor. Args: state_key: The key of state. next_action_list: The possible action in `self.t+1`. If the length of this list is 0, all action should be possible. Returns: [(`The key of action`, `boltzmann probability`)] ''' sigmoid = self.__calculate_sigmoid() q_df = self.q_df[self.q_df.state_key == state_key] q_df = q_df[q_df.isin(next_action_list)] q_df["boltzmann_factor"] = q_df["q_value"] / sigmoid q_df["boltzmann_factor"] = q_df["boltzmann_factor"].apply(np.exp) q_df["boltzmann_factor"] = q_df["boltzmann_factor"] / q_df["boltzmann_factor"].sum() return q_df
<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_model(self): ''' `object` of model as a function approximator, which has `lstm_model` whose type is `pydbm.rnn.lstm_model.LSTMModel`. ''' class Model(object): def __init__(self, lstm_model): self.lstm_model = lstm_model return Model(self.__lstm_model)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def filter(self, scored_list): ''' Filtering with std. Args: scored_list: The list of scoring. Retruns: The list of filtered result. ''' if len(scored_list) > 0: avg = np.mean([s[1] for s in scored_list]) std = np.std([s[1] for s in scored_list]) else: avg = 0 std = 0 limiter = avg + 0.5 * std mean_scored = [(sent_idx, score) for (sent_idx, score) in scored_list if score > limiter] return mean_scored
<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(self, query, fields=None, page=1, max_records=None, flatten=True): """returns iterator over all records that match the given query"""
if fields is None: fields = [] page = int(page) pages = float('inf') data = { "query": query, "page": page, "fields": fields, "flatten": flatten } count = 0 while page <= pages: payload = self._post(self.search_path, data=data) pages = payload['metadata']['pages'] page += 1 data["page"] = page for result in payload["results"]: yield result count += 1 if max_records and count >= max_records: return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def adjustColors(self, mode='dark'): """ Change a few colors depending on the mode to use. The default mode doesn't assume anything and avoid using white & black colors. The dark mode use white and avoid dark blue while the light mode use black and avoid yellow, to give a few examples. """
rp = Game.__color_modes.get(mode, {}) for k, color in self.__colors.items(): self.__colors[k] = rp.get(color, color)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loadBestScore(self): """ load local best score from the default file """
try: with open(self.scores_file, 'r') as f: self.best_score = int(f.readline(), 10) except: return False 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 saveBestScore(self): """ save current best score in the default file """
if self.score > self.best_score: self.best_score = self.score try: with open(self.scores_file, 'w') as f: f.write(str(self.best_score)) except: return False 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 incScore(self, pts): """ update the current score by adding it the specified number of points """
self.score += pts if self.score > self.best_score: self.best_score = self.score
<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(self): """ save the current game session's score and data for further use """
size = self.board.SIZE cells = [] for i in range(size): for j in range(size): cells.append(str(self.board.getCell(j, i))) score_str = "%s\n%d" % (' '.join(cells), self.score) try: with open(self.store_file, 'w') as f: f.write(score_str) except: return False 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 restore(self): """ restore the saved game score and data """
size = self.board.SIZE try: with open(self.store_file, 'r') as f: lines = f.readlines() score_str = lines[0] self.score = int(lines[1]) except: return False score_str_list = score_str.split(' ') count = 0 for i in range(size): for j in range(size): value = score_str_list[count] self.board.setCell(j, i, int(value)) count += 1 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 loop(self): """ main game loop. returns the final score. """
pause_key = self.board.PAUSE margins = {'left': 4, 'top': 4, 'bottom': 4} atexit.register(self.showCursor) try: self.hideCursor() while True: self.clearScreen() print(self.__str__(margins=margins)) if self.board.won() or not self.board.canMove(): break m = self.readMove() if m == pause_key: self.saveBestScore() if self.store(): print("Game successfully saved. " "Resume it with `term2048 --resume`.") return self.score print("An error ocurred while saving your game.") return None self.incScore(self.board.move(m)) except KeyboardInterrupt: self.saveBestScore() return None self.saveBestScore() print('You won!' if self.board.won() else 'Game Over') return self.score
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getCellStr(self, x, y): # TODO: refactor regarding issue #11 """ return a string representation of the cell located at x,y. """
c = self.board.getCell(x, y) if c == 0: return '.' if self.__azmode else ' .' elif self.__azmode: az = {} for i in range(1, int(math.log(self.board.goal(), 2))): az[2 ** i] = chr(i + 96) if c not in az: return '?' s = az[c] elif c == 1024: s = ' 1k' elif c == 2048: s = ' 2k' else: s = '%3d' % c return self.__colors.get(c, Fore.RESET) + s + Style.RESET_ALL
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def boardToString(self, margins=None): """ return a string representation of the current board. """
if margins is None: margins = {} b = self.board rg = range(b.size()) left = ' '*margins.get('left', 0) s = '\n'.join( [left + ' '.join([self.getCellStr(x, y) for x in rg]) for y in rg]) return 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 canMove(self): """ test if a move is possible """
if not self.filled(): return True for y in self.__size_range: for x in self.__size_range: c = self.getCell(x, y) if (x < self.__size-1 and c == self.getCell(x+1, y)) \ or (y < self.__size-1 and c == self.getCell(x, y+1)): 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 setCell(self, x, y, v): """set the cell value at x,y"""
self.cells[y][x] = 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 getCol(self, x): """return the x-th column, starting at 0"""
return [self.getCell(x, i) for i in self.__size_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 setCol(self, x, l): """set the x-th column, starting at 0"""
for i in xrange(0, self.__size): self.setCell(x, i, l[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 __collapseLineOrCol(self, line, d): """ Merge tiles in a line or column according to a direction and return a tuple with the new line and the score for the move on this line """
if (d == Board.LEFT or d == Board.UP): inc = 1 rg = xrange(0, self.__size-1, inc) else: inc = -1 rg = xrange(self.__size-1, 0, inc) pts = 0 for i in rg: if line[i] == 0: continue if line[i] == line[i+inc]: v = line[i]*2 if v == self.__goal: self.__won = True line[i] = v line[i+inc] = 0 pts += v return (line, pts)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move(self, d, add_tile=True): """ move and return the move score """
if d == Board.LEFT or d == Board.RIGHT: chg, get = self.setLine, self.getLine elif d == Board.UP or d == Board.DOWN: chg, get = self.setCol, self.getCol else: return 0 moved = False score = 0 for i in self.__size_range: # save the original line/col origin = get(i) # move it line = self.__moveLineOrCol(origin, d) # merge adjacent tiles collapsed, pts = self.__collapseLineOrCol(line, d) # move it again (for when tiles are merged, because empty cells are # inserted in the middle of the line/col) new = self.__moveLineOrCol(collapsed, d) # set it back in the board chg(i, new) # did it change? if origin != new: moved = True score += pts # don't add a new tile if nothing changed if moved and add_tile: self.addTile() return score
<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_cli_args(): """parse args from the CLI and return a dict"""
parser = argparse.ArgumentParser(description='2048 in your terminal') parser.add_argument('--mode', dest='mode', type=str, default=None, help='colors mode (dark or light)') parser.add_argument('--az', dest='azmode', action='store_true', help='Use the letters a-z instead of numbers') parser.add_argument('--resume', dest='resume', action='store_true', help='restart the game from where you left') parser.add_argument('-v', '--version', action='store_true') parser.add_argument('-r', '--rules', action='store_true') return vars(parser.parse_args())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_game(debug=False): """ Start a new game. If ``debug`` is set to ``True``, the game object is returned and the game loop isn't fired. """
args = parse_cli_args() if args['version']: print_version_and_exit() if args['rules']: print_rules_and_exit() game = Game(**args) if args['resume']: game.restore() if debug: return game return game.loop()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_message(self, message): """Handshake with livereload.js 1. client send 'hello' 2. server reply 'hello' 3. client send 'info' """
message = ObjectDict(escape.json_decode(message)) if message.command == 'hello': handshake = { 'command': 'hello', 'protocols': [ 'http://livereload.com/protocols/official-7', ], 'serverName': 'livereload-tornado', } self.send_message(handshake) if message.command == 'info' and 'url' in message: logger.info('Browser Connected: %s' % message.url) LiveReloadHandler.waiters.add(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 get_content_modified_time(cls, abspath): """Returns the time that ``abspath`` was last modified. May be overridden in subclasses. Should return a `~datetime.datetime` object or None. """
stat_result = os.stat(abspath) modified = datetime.datetime.utcfromtimestamp( stat_result[stat.ST_MTIME]) return modified
<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(self, filename): """Ignore a given filename or not."""
_, ext = os.path.splitext(filename) return ext in ['.pyc', '.pyo', '.o', '.swp']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def watch(self, path, func=None, delay=0, ignore=None): """Add a task to watcher. :param path: a filepath or directory path or glob pattern :param func: the function to be executed when file changed :param delay: Delay sending the reload message. Use 'forever' to not send it. This is useful to compile sass files to css, but reload on changed css files then only. :param ignore: A function return True to ignore a certain pattern of filepath. """
self._tasks[path] = { 'func': func, 'delay': delay, 'ignore': ignore, }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def already_coords(self, address): """test used to see if we have coordinates or address"""
m = re.search(self.COORD_MATCH, address) return (m != 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 coords_string_parser(self, coords): """Pareses the address string into coordinates to match address_to_coords return object"""
lat, lon = coords.split(',') return {"lat": lat.strip(), "lon": lon.strip(), "bounds": {}}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def address_to_coords(self, address): """Convert address to coordinates"""
base_coords = self.BASE_COORDS[self.region] get_cord = self.COORD_SERVERS[self.region] url_options = { "q": address, "lang": "eng", "origin": "livemap", "lat": base_coords["lat"], "lon": base_coords["lon"] } response = requests.get(self.WAZE_URL + get_cord, params=url_options, headers=self.HEADERS) for response_json in response.json(): if response_json.get('city'): lat = response_json['location']['lat'] lon = response_json['location']['lon'] bounds = response_json['bounds'] # sometimes the coords don't match up if bounds is not None: bounds['top'], bounds['bottom'] = max(bounds['top'], bounds['bottom']), min(bounds['top'], bounds['bottom']) bounds['left'], bounds['right'] = min(bounds['left'], bounds['right']), max(bounds['left'], bounds['right']) else: bounds = {} return {"lat": lat, "lon": lon, "bounds": bounds} raise WRCError("Cannot get coords for %s" % address)
<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_route(self, npaths=1, time_delta=0): """Get route data from waze"""
routing_server = self.ROUTING_SERVERS[self.region] url_options = { "from": "x:%s y:%s" % (self.start_coords["lon"], self.start_coords["lat"]), "to": "x:%s y:%s" % (self.end_coords["lon"], self.end_coords["lat"]), "at": time_delta, "returnJSON": "true", "returnGeometries": "true", "returnInstructions": "true", "timeout": 60000, "nPaths": npaths, "options": "AVOID_TRAILS:t", } if self.vehicle_type: url_options["vehicleType"] = self.vehicle_type response = requests.get(self.WAZE_URL + routing_server, params=url_options, headers=self.HEADERS) response.encoding = 'utf-8' response_json = self._check_response(response) if response_json: if 'error' in response_json: raise WRCError(response_json.get("error")) else: if response_json.get("alternatives"): return [alt['response'] for alt in response_json['alternatives']] if npaths > 1: return [response_json['response']] return response_json['response'] else: raise WRCError("empty response")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_up_route(self, results, real_time=True, stop_at_bounds=False): """Calculate route time and distance."""
start_bounds = self.start_coords['bounds'] end_bounds = self.end_coords['bounds'] def between(target, min, max): return target > min and target < max time = 0 distance = 0 for segment in results: if stop_at_bounds and segment.get('path'): x = segment['path']['x'] y = segment['path']['y'] if ( between(x, start_bounds.get('left', 0), start_bounds.get('right', 0)) or between(x, end_bounds.get('left', 0), end_bounds.get('right', 0)) ) and ( between(y, start_bounds.get('bottom', 0), start_bounds.get('top', 0)) or between(y, end_bounds.get('bottom', 0), end_bounds.get('top', 0)) ): continue time += segment['crossTime' if real_time else 'crossTimeWithoutRealTime'] distance += segment['length'] route_time = time / 60.0 route_distance = distance / 1000.0 return route_time, route_distance
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_route_info(self, real_time=True, stop_at_bounds=False, time_delta=0): """Calculate best route info."""
route = self.get_route(1, time_delta) results = route['results'] route_time, route_distance = self._add_up_route(results, real_time=real_time, stop_at_bounds=stop_at_bounds) self.log.info('Time %.2f minutes, distance %.2f km.', route_time, route_distance) return route_time, route_distance
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_all_routes_info(self, npaths=3, real_time=True, stop_at_bounds=False, time_delta=0): """Calculate all route infos."""
routes = self.get_route(npaths, time_delta) results = {route['routeName']: self._add_up_route(route['results'], real_time=real_time, stop_at_bounds=stop_at_bounds) for route in routes} route_time = [route[0] for route in results.values()] route_distance = [route[1] for route in results.values()] self.log.info('Time %.2f - %.2f minutes, distance %.2f - %.2f km.', min(route_time), max(route_time), min(route_distance), max(route_distance)) return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _initialize(self): """Read the SharQ configuration and set appropriate variables. Open a redis connection pool and load all the Lua scripts. """
self._key_prefix = self._config.get('redis', 'key_prefix') self._job_expire_interval = int( self._config.get('sharq', 'job_expire_interval') ) self._default_job_requeue_limit = int( self._config.get('sharq', 'default_job_requeue_limit') ) # initalize redis redis_connection_type = self._config.get('redis', 'conn_type') db = self._config.get('redis', 'db') if redis_connection_type == 'unix_sock': self._r = redis.StrictRedis( db=db, unix_socket_path=self._config.get('redis', 'unix_socket_path') ) elif redis_connection_type == 'tcp_sock': self._r = redis.StrictRedis( db=db, host=self._config.get('redis', 'host'), port=self._config.get('redis', 'port') ) self._load_lua_scripts()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load_config(self): """Read the configuration file and load it into memory."""
self._config = ConfigParser.SafeConfigParser() self._config.read(self.config_path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load_lua_scripts(self): """Loads all lua scripts required by SharQ."""
# load lua scripts lua_script_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'scripts/lua' ) with open(os.path.join( lua_script_path, 'enqueue.lua'), 'r') as enqueue_file: self._lua_enqueue_script = enqueue_file.read() self._lua_enqueue = self._r.register_script( self._lua_enqueue_script) with open(os.path.join( lua_script_path, 'dequeue.lua'), 'r') as dequeue_file: self._lua_dequeue_script = dequeue_file.read() self._lua_dequeue = self._r.register_script( self._lua_dequeue_script) with open(os.path.join( lua_script_path, 'finish.lua'), 'r') as finish_file: self._lua_finish_script = finish_file.read() self._lua_finish = self._r.register_script(self._lua_finish_script) with open(os.path.join( lua_script_path, 'interval.lua'), 'r') as interval_file: self._lua_interval_script = interval_file.read() self._lua_interval = self._r.register_script( self._lua_interval_script) with open(os.path.join( lua_script_path, 'requeue.lua'), 'r') as requeue_file: self._lua_requeue_script = requeue_file.read() self._lua_requeue = self._r.register_script( self._lua_requeue_script) with open(os.path.join( lua_script_path, 'metrics.lua'), 'r') as metrics_file: self._lua_metrics_script = metrics_file.read() self._lua_metrics = self._r.register_script( self._lua_metrics_script)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enqueue(self, payload, interval, job_id, queue_id, queue_type='default', requeue_limit=None): """Enqueues the job into the specified queue_id of a particular queue_type """
# validate all the input if not is_valid_interval(interval): raise BadArgumentException('`interval` has an invalid value.') if not is_valid_identifier(job_id): raise BadArgumentException('`job_id` has an invalid value.') if not is_valid_identifier(queue_id): raise BadArgumentException('`queue_id` has an invalid value.') if not is_valid_identifier(queue_type): raise BadArgumentException('`queue_type` has an invalid value.') if requeue_limit is None: requeue_limit = self._default_job_requeue_limit if not is_valid_requeue_limit(requeue_limit): raise BadArgumentException('`requeue_limit` has an invalid value.') try: serialized_payload = serialize_payload(payload) except TypeError as e: raise BadArgumentException(e.message) timestamp = str(generate_epoch()) keys = [ self._key_prefix, queue_type ] args = [ timestamp, queue_id, job_id, '"%s"' % serialized_payload, interval, requeue_limit ] self._lua_enqueue(keys=keys, args=args) response = { 'status': 'queued' } return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dequeue(self, queue_type='default'): """Dequeues a job from any of the ready queues based on the queue_type. If no job is ready, returns a failure status. """
if not is_valid_identifier(queue_type): raise BadArgumentException('`queue_type` has an invalid value.') timestamp = str(generate_epoch()) keys = [ self._key_prefix, queue_type ] args = [ timestamp, self._job_expire_interval ] dequeue_response = self._lua_dequeue(keys=keys, args=args) if len(dequeue_response) < 4: response = { 'status': 'failure' } return response queue_id, job_id, payload, requeues_remaining = dequeue_response payload = deserialize_payload(payload[1:-1]) response = { 'status': 'success', 'queue_id': queue_id, 'job_id': job_id, 'payload': payload, 'requeues_remaining': int(requeues_remaining) } return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interval(self, interval, queue_id, queue_type='default'): """Updates the interval for a specific queue_id of a particular queue type. """
# validate all the input if not is_valid_interval(interval): raise BadArgumentException('`interval` has an invalid value.') if not is_valid_identifier(queue_id): raise BadArgumentException('`queue_id` has an invalid value.') if not is_valid_identifier(queue_type): raise BadArgumentException('`queue_type` has an invalid value.') # generate the interval key interval_hmap_key = '%s:interval' % self._key_prefix interval_queue_key = '%s:%s' % (queue_type, queue_id) keys = [ interval_hmap_key, interval_queue_key ] args = [ interval ] interval_response = self._lua_interval(keys=keys, args=args) if interval_response == 0: # the queue with the id and type does not exist. response = { 'status': 'failure' } else: response = { 'status': 'success' } return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_valid_identifier(identifier): """Checks if the given identifier is valid or not. A valid identifier may consists of the following characters with a maximum length of 100 characters, minimum of 1 character. Valid characters for an identifier, - A to Z - a to z - 0 to 9 - _ (underscore) - - (hypen) """
if not isinstance(identifier, basestring): return False if len(identifier) > 100 or len(identifier) < 1: return False condensed_form = set(list(identifier.lower())) return condensed_form.issubset(VALID_IDENTIFIER_SET)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_valid_interval(interval): """Checks if the given interval is valid. A valid interval is always a positive, non-zero integer value. """
if not isinstance(interval, (int, long)): return False if interval <= 0: return False 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 is_valid_requeue_limit(requeue_limit): """Checks if the given requeue limit is valid. A valid requeue limit is always greater than or equal to -1. """
if not isinstance(requeue_limit, (int, long)): return False if requeue_limit <= -2: return False 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_search_names(name): """Return a list of values to search on when we are looking for a package with the given name. This is required to search on both pyramid_debugtoolbar and pyramid-debugtoolbar. """
parts = re.split('[-_.]', name) if len(parts) == 1: return parts result = set() for i in range(len(parts) - 1, 0, -1): for s1 in '-_.': prefix = s1.join(parts[:i]) for s2 in '-_.': suffix = s2.join(parts[i:]) for s3 in '-_.': result.add(s3.join([prefix, suffix])) return list(result)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def alter_old_distutils_request(request: WSGIRequest): """Alter the request body for compatibility with older distutils clients Due to a bug in the Python distutils library, the request post is sent using \n as a separator instead of the \r\n that the HTTP spec demands. This breaks the Django form parser and therefore we have to write a custom parser. This bug was fixed in the Python 2.7.4 and 3.4: http://bugs.python.org/issue10510 """
# We first need to retrieve the body before accessing POST or FILES since # it can only be read once. body = request.body if request.POST or request.FILES: return new_body = BytesIO() # Split the response in the various parts based on the boundary string content_type, opts = parse_header(request.META['CONTENT_TYPE'].encode('ascii')) parts = body.split(b'\n--' + opts['boundary'] + b'\n') for part in parts: if b'\n\n' not in part: continue headers, content = part.split(b'\n\n', 1) if not headers: continue new_body.write(b'--' + opts['boundary'] + b'\r\n') new_body.write(headers.replace(b'\n', b'\r\n')) new_body.write(b'\r\n\r\n') new_body.write(content) new_body.write(b'\r\n') new_body.write(b'--' + opts['boundary'] + b'--\r\n') request._body = new_body.getvalue() request.META['CONTENT_LENGTH'] = len(request._body) # Clear out _files and _post so that the request object re-parses the body if hasattr(request, '_files'): delattr(request, '_files') if hasattr(request, '_post'): delattr(request, '_post')
<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_files(sender, **kwargs): """Signal callback for deleting old files when database item is deleted"""
instance = kwargs['instance'] if not hasattr(instance.distribution, 'path'): return if not os.path.exists(instance.distribution.path): return # Check if there are other instances which reference this fle is_referenced = ( instance.__class__.objects .filter(distribution=instance.distribution) .exclude(pk=instance._get_pk_val()) .exists()) if is_referenced: return try: instance.distribution.storage.delete(instance.distribution.path) except Exception: logger.exception( 'Error when trying to delete file %s of package %s:' % ( instance.pk, instance.distribution.path))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def md5_hash_file(fh): """Return the md5 hash of the given file-object"""
md5 = hashlib.md5() while True: data = fh.read(8192) if not data: break md5.update(data) return md5.hexdigest()
<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_versio_versioning_scheme(full_class_path): """Return a class based on it's full path"""
module_path = '.'.join(full_class_path.split('.')[0:-1]) class_name = full_class_path.split('.')[-1] try: module = importlib.import_module(module_path) except ImportError: raise RuntimeError('Invalid specified Versio schema {}'.format(full_class_path)) try: return getattr(module, class_name) except AttributeError: raise RuntimeError( 'Could not find Versio schema class {!r} inside {!r} module.'.format( class_name, module_path))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search(spec, operator='and'): """Implement xmlrpc search command. This only searches through the mirrored and private packages """
field_map = { 'name': 'name__icontains', 'summary': 'releases__summary__icontains', } query_filter = None for field, values in spec.items(): for value in values: if field not in field_map: continue field_filter = Q(**{field_map[field]: value}) if not query_filter: query_filter = field_filter continue if operator == 'and': query_filter &= field_filter else: query_filter |= field_filter result = [] packages = models.Package.objects.filter(query_filter).all()[:20] for package in packages: release = package.releases.all()[0] result.append({ 'name': package.name, 'summary': release.summary, 'version': release.version, '_pypi_ordering': 0, }) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def credentials_required(view_func): """ This decorator should be used with views that need simple authentication against Django's authentication framework. """
@wraps(view_func, assigned=available_attrs(view_func)) def decorator(request, *args, **kwargs): if settings.LOCALSHOP_USE_PROXIED_IP: try: ip_addr = request.META['HTTP_X_FORWARDED_FOR'] except KeyError: return HttpResponseForbidden('No permission') else: # HTTP_X_FORWARDED_FOR can be a comma-separated list of IPs. # The client's IP will be the first one. ip_addr = ip_addr.split(",")[0].strip() else: ip_addr = request.META['REMOTE_ADDR'] if CIDR.objects.has_access(ip_addr, with_credentials=False): return view_func(request, *args, **kwargs) if not CIDR.objects.has_access(ip_addr, with_credentials=True): return HttpResponseForbidden('No permission') # Just return the original view because already logged in if request.user.is_authenticated(): return view_func(request, *args, **kwargs) user = authenticate_user(request) if user is not None: login(request, user) return view_func(request, *args, **kwargs) return HttpResponseUnauthorized(content='Authorization Required') return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def no_duplicates(function, *args, **kwargs): """ Makes sure that no duplicated tasks are enqueued. """
@wraps(function) def wrapper(self, *args, **kwargs): key = generate_key(function, *args, **kwargs) try: function(self, *args, **kwargs) finally: logging.info('Removing key %s', key) cache.delete(key) 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 download_file(pk): """Download the file reference in `models.ReleaseFile` with the given pk. """
release_file = models.ReleaseFile.objects.get(pk=pk) logging.info("Downloading %s", release_file.url) proxies = None if settings.LOCALSHOP_HTTP_PROXY: proxies = settings.LOCALSHOP_HTTP_PROXY response = requests.get(release_file.url, stream=True, proxies=proxies) # Write the file to the django file field filename = os.path.basename(release_file.url) # Setting the size manually since Django can't figure it our from # the raw HTTPResponse if 'content-length' in response.headers: size = int(response.headers['content-length']) else: size = len(response.content) # Setting the content type by first looking at the response header # and falling back to guessing it from the filename default_content_type = 'application/octet-stream' content_type = response.headers.get('content-type') if content_type is None or content_type == default_content_type: content_type = mimetypes.guess_type(filename)[0] or default_content_type # Using Django's temporary file upload system to not risk memory # overflows with TemporaryUploadedFile(name=filename, size=size, charset='utf-8', content_type=content_type) as temp_file: temp_file.write(response.content) temp_file.seek(0) # Validate the md5 hash of the downloaded file md5_hash = md5_hash_file(temp_file) if md5_hash != release_file.md5_digest: logging.error("MD5 hash mismatch: %s (expected: %s)" % ( md5_hash, release_file.md5_digest)) return release_file.distribution.save(filename, temp_file) release_file.save() logging.info("Complete")