code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if not text1: # Just add some text (speedup). return [(self.DIFF_INSERT, text2)] if not text2: # Just delete some text (speedup). return [(self.DIFF_DELETE, text1)] if len(text1) > len(text2): (longtext, shorttext) = (text1, text2) else: (shorttext, longtext) =...
def diff_compute(self, text1, text2, checklines, deadline)
Find the differences between two texts. Assumes that the texts do not have any common prefix or suffix. Args: text1: Old string to be diffed. text2: New string to be diffed. checklines: Speedup flag. If false, then don't run a line-level diff first to identify the changed areas. ...
1.476339
1.440802
1.024665
# Scan the text on a line-by-line basis first. (text1, text2, linearray) = self.diff_linesToChars(text1, text2) diffs = self.diff_main(text1, text2, False, deadline) # Convert the diff back to original text. self.diff_charsToLines(diffs, linearray) # Eliminate freak matches (e.g. blank l...
def diff_lineMode(self, text1, text2, deadline)
Do a quick line-level diff on both strings, then rediff the parts for greater accuracy. This speedup can produce non-minimal diffs. Args: text1: Old string to be diffed. text2: New string to be diffed. deadline: Time when the diff should be complete by. Returns: Array of ch...
1.56459
1.446713
1.081479
text1a = text1[:x] text2a = text2[:y] text1b = text1[x:] text2b = text2[y:] # Compute both diffs serially. diffs = self.diff_main(text1a, text2a, False, deadline) diffsb = self.diff_main(text1b, text2b, False, deadline) return diffs + diffsb
def diff_bisectSplit(self, text1, text2, x, y, deadline)
Given the location of the 'middle snake', split the diff in two parts and recurse. Args: text1: Old string to be diffed. text2: New string to be diffed. x: Index of split point in text1. y: Index of split point in text2. deadline: Time at which to bail if not yet complete. Re...
2.017747
1.933376
1.043639
lineArray = [] # e.g. lineArray[4] == "Hello\n" lineHash = {} # e.g. lineHash["Hello\n"] == 4 # "\x00" is a valid character, but various debuggers don't like it. # So we'll insert a junk entry to avoid generating a null character. lineArray.append('') def diff_linesToCharsMunge(text): ...
def diff_linesToChars(self, text1, text2)
Split two texts into an array of strings. Reduce the texts to a string of hashes where each Unicode character represents one line. Args: text1: First string. text2: Second string. Returns: Three element tuple, containing the encoded text1, the encoded text2 and the array of unique...
2.134912
2.076731
1.028016
for i in range(len(diffs)): text = [] for char in diffs[i][1]: text.append(lineArray[ord(char)]) diffs[i] = (diffs[i][0], "".join(text))
def diff_charsToLines(self, diffs, lineArray)
Rehydrate the text in a diff from a string of line hashes to real lines of text. Args: diffs: Array of diff tuples. lineArray: Array of unique strings.
3.067448
2.53356
1.210726
# Quick check for common null cases. if not text1 or not text2 or text1[0] != text2[0]: return 0 # Binary search. # Performance analysis: https://neil.fraser.name/news/2007/10/09/ pointermin = 0 pointermax = min(len(text1), len(text2)) pointermid = pointermax pointerstart = 0 ...
def diff_commonPrefix(self, text1, text2)
Determine the common prefix of two strings. Args: text1: First string. text2: Second string. Returns: The number of characters common to the start of each string.
1.885141
2.057483
0.916236
# Quick check for common null cases. if not text1 or not text2 or text1[-1] != text2[-1]: return 0 # Binary search. # Performance analysis: https://neil.fraser.name/news/2007/10/09/ pointermin = 0 pointermax = min(len(text1), len(text2)) pointermid = pointermax pointerend = 0 ...
def diff_commonSuffix(self, text1, text2)
Determine the common suffix of two strings. Args: text1: First string. text2: Second string. Returns: The number of characters common to the end of each string.
2.219869
2.315563
0.958674
# Cache the text lengths to prevent multiple calls. text1_length = len(text1) text2_length = len(text2) # Eliminate the null case. if text1_length == 0 or text2_length == 0: return 0 # Truncate the longer string. if text1_length > text2_length: text1 = text1[-text2_length:] ...
def diff_commonOverlap(self, text1, text2)
Determine if the suffix of one string is the prefix of another. Args: text1 First string. text2 Second string. Returns: The number of characters common to the end of the first string and the start of the second string.
1.679701
1.72428
0.974146
if self.Diff_Timeout <= 0: # Don't risk returning a non-optimal diff if we have unlimited time. return None if len(text1) > len(text2): (longtext, shorttext) = (text1, text2) else: (shorttext, longtext) = (text1, text2) if len(longtext) < 4 or len(shorttext) * 2 < len(longte...
def diff_halfMatch(self, text1, text2)
Do the two texts share a substring which is at least half the length of the longer text? This speedup can produce non-minimal diffs. Args: text1: First string. text2: Second string. Returns: Five element Array, containing the prefix of text1, the suffix of text1, the prefix of ...
1.555203
1.506405
1.032393
def diff_cleanupSemanticScore(one, two): if not one or not two: # Edges are the best. return 6 # Each port of this function behaves slightly differently due to # subtle differences in each language's definition of things like # 'whitespace'. Since this function...
def diff_cleanupSemanticLossless(self, diffs)
Look for single edits surrounded on both sides by equalities which can be shifted sideways to align the edit to a word boundary. e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came. Args: diffs: Array of diff tuples.
1.953232
1.583225
1.233705
changes = False equalities = [] # Stack of indices where equalities are found. lastEquality = None # Always equal to diffs[equalities[-1]][1] pointer = 0 # Index of current position. pre_ins = False # Is there an insertion operation before the last equality. pre_del = False # Is there ...
def diff_cleanupEfficiency(self, diffs)
Reduce the number of edits by eliminating operationally trivial equalities. Args: diffs: Array of diff tuples.
1.638592
1.593156
1.028519
chars1 = 0 chars2 = 0 last_chars1 = 0 last_chars2 = 0 for x in range(len(diffs)): (op, text) = diffs[x] if op != self.DIFF_INSERT: # Equality or deletion. chars1 += len(text) if op != self.DIFF_DELETE: # Equality or insertion. chars2 += len(text) if cha...
def diff_xIndex(self, diffs, loc)
loc is a location in text1, compute and return the equivalent location in text2. e.g. "The cat" vs "The big cat", 1->1, 5->8 Args: diffs: Array of diff tuples. loc: Location within text1. Returns: Location within text2.
2.597517
2.379667
1.091547
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: ...
def diff_prettyHtml(self, diffs)
Convert a diff array into a pretty HTML report. Args: diffs: Array of diff tuples. Returns: HTML representation.
1.880726
1.824438
1.030852
text = [] for (op, data) in diffs: if op != self.DIFF_INSERT: text.append(data) return "".join(text)
def diff_text1(self, diffs)
Compute and return the source text (all equalities and deletions). Args: diffs: Array of diff tuples. Returns: Source text.
3.413825
3.699046
0.922894
text = [] for (op, data) in diffs: if op != self.DIFF_DELETE: text.append(data) return "".join(text)
def diff_text2(self, diffs)
Compute and return the destination text (all equalities and insertions). Args: diffs: Array of diff tuples. Returns: Destination text.
3.500812
3.733959
0.93756
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. ...
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.
1.730898
1.589036
1.089275
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, ...
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.
2.398691
2.134366
1.123843
# 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. re...
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.
4.822697
4.12276
1.169774
# 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): ...
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.
1.869888
1.874806
0.997377
s = {} for char in pattern: s[char] = 0 for i in range(len(pattern)): s[pattern[i]] |= 1 << (len(pattern) - i - 1) return s
def match_alphabet(self, pattern)
Initialise the alphabet for the Bitap algorithm. Args: pattern: The text to encode. Returns: Hash of character locations.
3.148313
2.794329
1.126679
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.M...
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.
2.972015
2.488733
1.194188
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.l...
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.
2.674103
2.759019
0.969223
if not patches: return (text, []) # Deep copy the patches so that no changes are made to originals. patches = self.patch_deepCopy(patches) nullPadding = self.patch_addPadding(patches) text = nullPadding + text + nullPadding self.patch_splitMax(patches) # delta keeps track of th...
def patch_apply(self, patches, text)
Merge a set of patches onto the text. Return a patched text, as well as a list of true/false values indicating which patches were applied. Args: patches: Array of Patch objects. text: Old text. Returns: Two element Array, containing the new text and an array of boolean values.
1.902128
1.681719
1.131062
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. ...
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.
1.906536
1.85043
1.030321
patch_size = self.Match_MaxBits if patch_size == 0: # Python has the option of not splitting strings due to its ability # to handle integers of arbitrary precision. return for x in range(len(patches)): if patches[x].length1 <= patch_size: continue bigpatch = patche...
def patch_splitMax(self, patches)
Look through the patches and break up any which are longer than the maximum limit of the match algorithm. Intended to be called only from within patch_apply. Args: patches: Array of Patch objects.
1.997051
1.973434
1.011967
text = [] for patch in patches: text.append(str(patch)) return "".join(text)
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.
4.027044
4.580341
0.879202
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" ...
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. Return...
3.718794
3.44229
1.080326
s = {} for char in pattern: s[char] = 0 for i in xrange(len(pattern)): s[pattern[i]] |= 1 << (len(pattern) - i - 1) return s
def match_alphabet(self, pattern)
Initialise the alphabet for the Bitap algorithm. Args: pattern: The text to encode. Returns: Hash of character locations.
3.23097
2.896942
1.115304
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(...
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.
2.058603
1.995561
1.031591
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)
def diff_trees(left, right, diff_options=None, formatter=None)
Takes two lxml root elements or element trees
2.910863
3.036508
0.958622
return _diff(etree.fromstring, left, right, diff_options=diff_options, formatter=formatter)
def diff_texts(left, right, diff_options=None, formatter=None)
Takes two Unicode strings containing XML
5.167037
5.010765
1.031187
return _diff(etree.parse, left, right, diff_options=diff_options, formatter=formatter)
def diff_files(left, right, diff_options=None, formatter=None)
Takes two filenames or streams, and diffs the XML in those files
5.971493
5.695004
1.048549
patcher = patch.Patcher() return patcher.patch(actions, tree)
def patch_tree(actions, tree)
Takes an lxml root element or element tree, and a list of actions
5.375236
6.159687
0.872648
tree = etree.fromstring(tree) actions = patch.DiffParser().parse(actions) tree = patch_tree(actions, tree) return etree.tounicode(tree)
def patch_text(actions, tree)
Takes a string with XML and a string with actions
5.094909
4.261533
1.195558
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) t...
def patch_file(actions, tree)
Takes two filenames or streams, one with XML the other a diff
3.580269
2.86472
1.24978
# We don't want to diff comments: self._remove_comments(left_tree) self._remove_comments(right_tree) self.placeholderer.do_tree(left_tree) self.placeholderer.do_tree(right_tree)
def prepare(self, left_tree, right_tree)
prepare() is run on the trees before diffing This is so the formatter can apply magic before diffing.
5.533523
4.739836
1.16745
def draw(self): ''' Draws samples from the `true` distribution. Returns: `np.ndarray` of samples. ''' observed_arr = None for result_tuple in self.__feature_generator.generate(): observed_arr = result_tuple[0] break ...
Draws samples from the `true` distribution. Returns: `np.ndarray` of samples.
null
null
null
def generate(self): ''' Generate noise samples. Returns: `np.ndarray` of samples. ''' sampled_arr = np.zeros((self.__batch_size, self.__channel, self.__seq_len, self.__dim)) for batch in range(self.__batch_size): for i in range(...
Generate noise samples. Returns: `np.ndarray` of samples.
null
null
null
def generate(self): ''' Draws samples from the `true` distribution. Returns: `np.ndarray` of samples. ''' observed_arr = None for result_tuple in self.__feature_generator.generate(): observed_arr = result_tuple[0] bre...
Draws samples from the `true` distribution. Returns: `np.ndarray` of samples.
null
null
null
def compute(self, x_arr, y_arr): ''' Compute distance. Args: x_arr: `np.ndarray` of vectors. y_arr: `np.ndarray` of vectors. Retruns: `np.ndarray` of distances. ''' y_arr += 1e-08 return np.sum(x_arr * np...
Compute distance. Args: x_arr: `np.ndarray` of vectors. y_arr: `np.ndarray` of vectors. Retruns: `np.ndarray` of distances.
null
null
null
def generate_ngram_data_set(self, token_list, n=2): ''' Generate the N-gram's pair. Args: token_list: The list of tokens. n N Returns: zip of Tuple(Training N-gram data, Target N-gram data) ''' n_gram_tupl...
Generate the N-gram's pair. Args: token_list: The list of tokens. n N Returns: zip of Tuple(Training N-gram data, Target N-gram data)
null
null
null
def generate_skip_gram_data_set(self, token_list): ''' Generate the Skip-gram's pair. Args: token_list: The list of tokens. Returns: zip of Tuple(Training N-gram data, Target N-gram data) ''' n_gram_tuple_zip = self.generate_tuple_z...
Generate the Skip-gram's pair. Args: token_list: The list of tokens. Returns: zip of Tuple(Training N-gram data, Target N-gram data)
null
null
null
def generate_tuple_zip(self, token_list, n=2): ''' Generate the N-gram. Args: token_list: The list of tokens. n N Returns: zip of Tuple(N-gram) ''' return zip(*[token_list[i:] for i in range(n)])
Generate the N-gram. Args: token_list: The list of tokens. n N Returns: zip of Tuple(N-gram)
null
null
null
def draw(self): ''' Draws samples from the `true` distribution. Returns: `np.ndarray` of samples. ''' sampled_arr = np.empty((self.__batch_size, self.__seq_len, self.__dim)) for batch in range(self.__batch_size): key = np.random...
Draws samples from the `true` distribution. Returns: `np.ndarray` of samples.
null
null
null
''' 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)
def url_to_text(self, url)
Download PDF file and transform its document to string. Args: url: PDF url. Returns: string.
7.284948
2.966573
2.455678
''' 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,...
def path_to_text(self, path)
Transform local PDF file to string. Args: path: path to PDF file. Returns: string.
1.866135
1.561491
1.195098
''' setter ''' if isinstance(value, TokenizableDoc): self.__tokenizable_doc = value else: raise TypeError()
def set_tokenizable_doc(self, value)
setter
4.725719
4.632932
1.020028
''' Divide string into sentence list. Args: data: string. counter: recursive counter. Returns: List of sentences. ''' delimiter = self.delimiter_list[counter] sentence_list = [] [sentence_list...
def listup_sentence(self, data, counter=0)
Divide string into sentence list. Args: data: string. counter: recursive counter. Returns: List of sentences.
3.108744
2.222029
1.399056
''' Entry Point. Args: url: PDF url. ''' # The object of Web-scraping. web_scrape = WebScraping() # Set the object of reading PDF files. web_scrape.readable_web_pdf = WebPDFReading() # Execute Web-scraping. document = web_scrape.scrape(url) # The object of aut...
def Main(url)
Entry Point. Args: url: PDF url.
8.095263
7.068498
1.145259
''' 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(fa...
def observe(self, success, failure)
Observation data. Args: success: The number of success. failure: The number of failure.
2.611812
2.033792
1.284208
''' Compute likelihood. Returns: likelihood. ''' try: likelihood = self.__success / (self.__success + self.__failure) except ZeroDivisionError: likelihood = 0.0 return likelihood
def likelihood(self)
Compute likelihood. Returns: likelihood.
5.095184
3.448633
1.47745
''' 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: ...
def expected_value(self)
Compute expected value. Returns: Expected value.
4.489103
3.587366
1.251365
''' 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 ZeroDivisionEr...
def variance(self)
Compute variance. Returns: variance.
4.756139
3.901515
1.219049
''' Concreat method. Args: state_key The key of state. this value is point in map. Returns: [(x, y)] ''' if state_key in self.__state_action_list_dict: return self.__state_action_list_dict[state_key] else: a...
def extract_possible_actions(self, state_key)
Concreat method. Args: state_key The key of state. this value is point in map. Returns: [(x, y)]
4.176904
2.262469
1.846171
''' Compute the reward value. Args: state_key: The key of state. action_key: The key of action. Returns: Reward value. ''' reward_value = 0.0 if state_key in self.__state_action_list_d...
def observe_reward_value(self, state_key, action_key)
Compute the reward value. Args: state_key: The key of state. action_key: The key of action. Returns: Reward value.
2.663547
2.031289
1.311259
def convert_tokens_into_matrix(self, token_list): ''' Create matrix of sentences. Args: token_list: The list of tokens. Returns: 2-D `np.ndarray` of sentences. Each row means one hot vectors of one sentence. ''' ...
Create matrix of sentences. Args: token_list: The list of tokens. Returns: 2-D `np.ndarray` of sentences. Each row means one hot vectors of one sentence.
null
null
null
def tokenize(self, vector_list): ''' Tokenize vector. Args: vector_list: The list of vector of one token. Returns: token ''' vector_arr = np.array(vector_list) if vector_arr.ndim == 1: key_arr = vector_a...
Tokenize vector. Args: vector_list: The list of vector of one token. Returns: token
null
null
null
''' Tokenize token list. Args: token_list: The list of tokens.. Returns: [vector of token, vector of token, vector of token, ...] ''' vector_list = [self.__collection.tf_idf(token, self.__collection) for token in token_list] ...
def vectorize(self, token_list)
Tokenize token list. Args: token_list: The list of tokens.. Returns: [vector of token, vector of token, vector of token, ...]
5.766688
2.713814
2.124938
''' 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) ...
def __move(self, current_pos)
Move in the feature map. Args: current_pos: The now position. Returns: The next position.
2.557589
1.962831
1.30301
''' Annealing. ''' shape_list = list(self.var_arr.shape) shape_list[0] = self.__cycles_num + 1 self.var_log_arr = np.zeros(tuple(shape_list)) current_pos = self.__start_pos current_var_arr = self.var_arr[current_pos, :] current_cost_arr = self.__c...
def annealing(self)
Annealing.
2.687699
2.683676
1.001499
def draw(self): ''' Draws samples from the `fake` distribution. Returns: `np.ndarray` of samples. ''' observed_arr = self.noise_sampler.generate() _ = self.inference(observed_arr) feature_arr = self.__convolutional_auto_encoder.extract_featur...
Draws samples from the `fake` distribution. Returns: `np.ndarray` of samples.
null
null
null
def learn(self, grad_arr): ''' Update this Discriminator by ascending its stochastic gradient. Args: grad_arr: `np.ndarray` of gradients. Returns: `np.ndarray` of delta or gradients. ''' deconvolution_layer_list = self.__deconvoluti...
Update this Discriminator by ascending its stochastic gradient. Args: grad_arr: `np.ndarray` of gradients. Returns: `np.ndarray` of delta or gradients.
null
null
null
def __optimize_deconvolution_layer(self, learning_rate, epoch): ''' Back propagation for Deconvolution layer. Args: learning_rate: Learning rate. epoch: Now epoch. ''' params_list = [] grads_list = [] ...
Back propagation for Deconvolution layer. Args: learning_rate: Learning rate. epoch: Now epoch.
null
null
null
def update(self): ''' Update the encoder and the decoder to minimize the reconstruction error of the inputs. Returns: `np.ndarray` of the reconstruction errors. ''' observed_arr = self.noise_sampler.generate() inferenced_arr = self.inference(...
Update the encoder and the decoder to minimize the reconstruction error of the inputs. Returns: `np.ndarray` of the reconstruction errors.
null
null
null
''' getter ''' if isinstance(self.__readable_web_pdf, ReadableWebPDF) is False and self.__readable_web_pdf is not None: raise TypeError("The type of __readable_web_pdf must be ReadableWebPDF.") return self.__readable_web_pdf
def get_readable_web_pdf(self)
getter
3.841331
3.531823
1.087634
''' setter ''' if isinstance(value, ReadableWebPDF) is False and value is not None: raise TypeError("The type of __readable_web_pdf must be ReadableWebPDF.") self.__readable_web_pdf = value
def set_readable_web_pdf(self, value)
setter
4.326009
4.350037
0.994477
''' Execute Web-Scraping. The target dom objects are in self.__dom_object_list. Args: url: Web site url. Returns: The result. this is a string. @TODO(chimera0): check URLs format. ''' if isinstance(url, str) is False: ...
def scrape(self, url)
Execute Web-Scraping. The target dom objects are in self.__dom_object_list. Args: url: Web site url. Returns: The result. this is a string. @TODO(chimera0): check URLs format.
4.684637
2.463641
1.901509
''' Extract MIDI file. Args: file_path: File path of MIDI. is_drum: Extract drum data or not. Returns: pd.DataFrame(columns=["program", "start", "end", "pitch", "velocity", "duration"]) ''' midi_data = pret...
def extract(self, file_path, is_drum=False)
Extract MIDI file. Args: file_path: File path of MIDI. is_drum: Extract drum data or not. Returns: pd.DataFrame(columns=["program", "start", "end", "pitch", "velocity", "duration"])
2.057857
1.561886
1.317546
''' Save MIDI file. Args: file_path: File path of MIDI. note_df: `pd.DataFrame` of note data. ''' chord = pretty_midi.PrettyMIDI() for program in note_df.program.drop_duplicates().values.tolist(): df = not...
def save(self, file_path, note_df)
Save MIDI file. Args: file_path: File path of MIDI. note_df: `pd.DataFrame` of note data.
2.728137
2.400225
1.136617
''' Compute cost. Args: x: `np.ndarray` of explanatory variables. Returns: cost ''' q_learning = copy(self.__greedy_q_learning) q_learning.epsilon_greedy_rate = x[0] q_learning.alpha_value = x[1] q_learn...
def compute(self, x)
Compute cost. Args: x: `np.ndarray` of explanatory variables. Returns: cost
3.756557
3.230602
1.162804
''' Entry Point. Args: url: target url. ''' # The object of Web-Scraping. web_scrape = WebScraping() # Execute Web-Scraping. document = web_scrape.scrape(url) # The object of automatic summarization with N-gram. auto_abstractor = NgramAutoAbstractor() # n-gram...
def Main(url)
Entry Point. Args: url: target url.
5.944719
5.443427
1.092091
''' getter ''' if isinstance(self.__target_n, int) is False: raise TypeError("The type of __target_n must be int.") return self.__target_n
def get_target_n(self)
getter
4.726547
4.260841
1.109299
''' setter ''' if isinstance(value, int) is False: raise TypeError("The type of __target_n must be int.") self.__target_n = value
def set_target_n(self, value)
setter
4.960048
4.999998
0.99201
''' getter ''' if isinstance(self.__cluster_threshold, int) is False: raise TypeError("The type of __cluster_threshold must be int.") return self.__cluster_threshold
def get_cluster_threshold(self)
getter
4.96618
4.451202
1.115694
''' setter ''' if isinstance(value, int) is False: raise TypeError("The type of __cluster_threshold must be int.") self.__cluster_threshold = value
def set_cluster_threshold(self, value)
setter
5.26591
5.232596
1.006367
''' getter ''' if isinstance(self.__top_sentences, int) is False: raise TypeError("The type of __top_sentences must be int.") return self.__top_sentences
def get_top_sentences(self)
getter
5.562199
5.030997
1.105586
''' setter ''' if isinstance(value, int) is False: raise TypeError("The type of __top_sentences must be int.") self.__top_sentences = value
def set_top_sentences(self, value)
setter
5.423862
5.419242
1.000853
''' Execute summarization. Args: document: The target document. Abstractor: The object of AbstractableDoc. similarity_filter The object of SimilarityFilter. Returns: dict data. - "summarize_result": The lis...
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 sent...
3.638717
2.402081
1.514818
''' 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 ...
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.
2.413774
2.005952
1.203306
def draw(self): ''' Draws samples from the `true` distribution. Returns: `np.ndarray` of samples. ''' return np.random.normal(loc=self.__mu, scale=self.__sigma, size=self.__output_shape)
Draws samples from the `true` distribution. Returns: `np.ndarray` of samples.
null
null
null
''' 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_lis...
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.
2.140061
1.979808
1.080944
def draw(self): ''' Draws samples from the `fake` distribution. Returns: `np.ndarray` of samples. ''' observed_arr = self.extract_conditions() conv_arr = self.inference(observed_arr) if self.__conditon_noise_sampler is not None: ...
Draws samples from the `fake` distribution. Returns: `np.ndarray` of samples.
null
null
null
def learn(self, grad_arr, fix_opt_flag=False): ''' Update this Discriminator by ascending its stochastic gradient. Args: grad_arr: `np.ndarray` of gradients. fix_opt_flag: If `False`, no optimization in this model will be done. Returns: ...
Update this Discriminator by ascending its stochastic gradient. Args: grad_arr: `np.ndarray` of gradients. fix_opt_flag: If `False`, no optimization in this model will be done. Returns: `np.ndarray` of delta or gradients.
null
null
null
def inference(self, observed_arr): ''' Draws samples from the `fake` distribution. Args: observed_arr: `np.ndarray` of observed data points. Returns: `np.ndarray` of inferenced. ''' for i in range(len(self.__deconvolution_la...
Draws samples from the `fake` distribution. Args: observed_arr: `np.ndarray` of observed data points. Returns: `np.ndarray` of inferenced.
null
null
null
def learn(self, grad_arr, fix_opt_flag=False): ''' Update this Discriminator by ascending its stochastic gradient. Args: grad_arr: `np.ndarray` of gradients. fix_opt_flag: If `False`, no optimization in this model will be done. Returns: ...
Update this Discriminator by ascending its stochastic gradient. Args: grad_arr: `np.ndarray` of gradients. fix_opt_flag: If `False`, no optimization in this model will be done. Returns: `np.ndarray` of delta or gradients.
null
null
null
def inference(self, observed_arr): ''' Draws samples from the `true` distribution. Args: observed_arr: `np.ndarray` of observed data points. Returns: `np.ndarray` of inferenced. ''' self.__pred_arr = self.__lstm_model.infere...
Draws samples from the `true` distribution. Args: observed_arr: `np.ndarray` of observed data points. Returns: `np.ndarray` of inferenced.
null
null
null
def learn(self, grad_arr, fix_opt_flag=False): ''' Update this Discriminator by ascending its stochastic gradient. Args: grad_arr: `np.ndarray` of gradients. fix_opt_flag: If `False`, no optimization in this model will be done. Returns: ...
Update this Discriminator by ascending its stochastic gradient. Args: grad_arr: `np.ndarray` of gradients. fix_opt_flag: If `False`, no optimization in this model will be done. Returns: `np.ndarray` of delta or gradients.
null
null
null
def draw(self): ''' Draws samples from the `true` distribution. Returns: `np.ndarray` of samples. ''' return np.random.uniform(loc=self.__low, scale=self.__high, size=self.__output_shape)
Draws samples from the `true` distribution. Returns: `np.ndarray` of samples.
null
null
null
''' getter ''' if isinstance(self.__nlp_base, NlpBase) is False: raise TypeError("The type of self.__nlp_base must be NlpBase.") return self.__nlp_base
def get_nlp_base(self)
getter
4.715467
4.163293
1.132629
''' setter ''' if isinstance(value, NlpBase) is False: raise TypeError("The type of value must be NlpBase.") self.__nlp_base = value
def set_nlp_base(self, value)
setter
4.825709
4.789385
1.007584
''' getter ''' if isinstance(self.__similarity_limit, float) is False: raise TypeError("__similarity_limit must be float.") return self.__similarity_limit
def get_similarity_limit(self)
getter
5.533032
4.929867
1.122349
''' setter ''' if isinstance(value, float) is False: raise TypeError("__similarity_limit must be float.") self.__similarity_limit = value
def set_similarity_limit(self, value)
setter
6.041739
6.339773
0.95299
''' Remove duplicated elements. Args: token_list_x: [token, token, token, ...] token_list_y: [token, token, token, ...] Returns: Tuple(token_list_x, token_list_y) ''' x = set(list(token_list_x)) y = set(list(toke...
def unique(self, token_list_x, token_list_y)
Remove duplicated elements. Args: token_list_x: [token, token, token, ...] token_list_y: [token, token, token, ...] Returns: Tuple(token_list_x, token_list_y)
2.802025
1.775921
1.577787
''' Count the number of tokens in `token_list`. Args: token_list: The list of tokens. Returns: {token: the numbers} ''' token_dict = {} for token in token_list: if token in token_dict: token_dict[tok...
def count(self, token_list)
Count the number of tokens in `token_list`. Args: token_list: The list of tokens. Returns: {token: the numbers}
2.911412
1.613694
1.80419
''' Filter mutually similar sentences. Args: sentence_list: The list of sentences. Returns: The list of filtered sentences. ''' result_list = [] recursive_list = [] try: self.nlp_base.tokenize(sentence_list...
def similar_filter_r(self, sentence_list)
Filter mutually similar sentences. Args: sentence_list: The list of sentences. Returns: The list of filtered sentences.
2.53693
2.236635
1.134262
''' Annealing. ''' self.__predicted_log_list = [] for cycle in range(self.__cycles_num): for mc_step in range(self.__mc_step): self.__move() self.__gammma *= self.__fractional_reduction if isinstance(self.__tolerance_diff_e, fl...
def annealing(self)
Annealing.
4.653313
4.579215
1.016181
def calculate(self, token_list_x, token_list_y): ''' Calculate similarity with the Jaccard coefficient. Concrete method. Args: token_list_x: [token, token, token, ...] token_list_y: [token, token, token, ...] Retu...
Calculate similarity with the Jaccard coefficient. Concrete method. Args: token_list_x: [token, token, token, ...] token_list_y: [token, token, token, ...] Returns: Similarity.
null
null
null
def set_noise_sampler(self, value): ''' setter ''' if isinstance(value, NoiseSampler) is False: raise TypeError("The type of `__noise_sampler` must be `NoiseSampler`.") self.__noise_sampler = value
setter
null
null
null
''' Infernce Q-Value. Args: predicted_q_arr: `np.ndarray` of predicted Q-Values. real_q_arr: `np.ndarray` of real Q-Values. ''' loss = self.__computable_loss.compute_loss(predicted_q_arr, real_q_arr) delta_arr = self._...
def learn_q(self, predicted_q_arr, real_q_arr)
Infernce Q-Value. Args: predicted_q_arr: `np.ndarray` of predicted Q-Values. real_q_arr: `np.ndarray` of real Q-Values.
3.431894
2.544688
1.34865
''' `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 Mod...
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`.
9.830601
2.36705
4.153102