repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
perrygeo/simanneal
examples/watershed/shapefile.py
Reader.load
def load(self, shapefile=None): """Opens a shapefile from a filename or file-like object. Normally this method would be called by the constructor with the file object or file name as an argument.""" if shapefile: (shapeName, ext) = os.path.splitext(shapefile) self.shapeName = shapeName try: self.shp = open("%s.shp" % shapeName, "rb") except IOError: raise ShapefileException("Unable to open %s.shp" % shapeName) try: self.shx = open("%s.shx" % shapeName, "rb") except IOError: raise ShapefileException("Unable to open %s.shx" % shapeName) try: self.dbf = open("%s.dbf" % shapeName, "rb") except IOError: raise ShapefileException("Unable to open %s.dbf" % shapeName) if self.shp: self.__shpHeader() if self.dbf: self.__dbfHeader()
python
def load(self, shapefile=None): """Opens a shapefile from a filename or file-like object. Normally this method would be called by the constructor with the file object or file name as an argument.""" if shapefile: (shapeName, ext) = os.path.splitext(shapefile) self.shapeName = shapeName try: self.shp = open("%s.shp" % shapeName, "rb") except IOError: raise ShapefileException("Unable to open %s.shp" % shapeName) try: self.shx = open("%s.shx" % shapeName, "rb") except IOError: raise ShapefileException("Unable to open %s.shx" % shapeName) try: self.dbf = open("%s.dbf" % shapeName, "rb") except IOError: raise ShapefileException("Unable to open %s.dbf" % shapeName) if self.shp: self.__shpHeader() if self.dbf: self.__dbfHeader()
[ "def", "load", "(", "self", ",", "shapefile", "=", "None", ")", ":", "if", "shapefile", ":", "(", "shapeName", ",", "ext", ")", "=", "os", ".", "path", ".", "splitext", "(", "shapefile", ")", "self", ".", "shapeName", "=", "shapeName", "try", ":", ...
Opens a shapefile from a filename or file-like object. Normally this method would be called by the constructor with the file object or file name as an argument.
[ "Opens", "a", "shapefile", "from", "a", "filename", "or", "file", "-", "like", "object", ".", "Normally", "this", "method", "would", "be", "called", "by", "the", "constructor", "with", "the", "file", "object", "or", "file", "name", "as", "an", "argument", ...
293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881
https://github.com/perrygeo/simanneal/blob/293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881/examples/watershed/shapefile.py#L153-L176
train
203,100
perrygeo/simanneal
examples/watershed/shapefile.py
Reader.shapes
def shapes(self): """Returns all shapes in a shapefile.""" shp = self.__getFileObj(self.shp) shp.seek(100) shapes = [] while shp.tell() < self.shpLength: shapes.append(self.__shape()) return shapes
python
def shapes(self): """Returns all shapes in a shapefile.""" shp = self.__getFileObj(self.shp) shp.seek(100) shapes = [] while shp.tell() < self.shpLength: shapes.append(self.__shape()) return shapes
[ "def", "shapes", "(", "self", ")", ":", "shp", "=", "self", ".", "__getFileObj", "(", "self", ".", "shp", ")", "shp", ".", "seek", "(", "100", ")", "shapes", "=", "[", "]", "while", "shp", ".", "tell", "(", ")", "<", "self", ".", "shpLength", "...
Returns all shapes in a shapefile.
[ "Returns", "all", "shapes", "in", "a", "shapefile", "." ]
293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881
https://github.com/perrygeo/simanneal/blob/293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881/examples/watershed/shapefile.py#L304-L311
train
203,101
perrygeo/simanneal
examples/watershed/shapefile.py
Reader.__dbfHeaderLength
def __dbfHeaderLength(self): """Retrieves the header length of a dbf file header.""" if not self.__dbfHdrLength: if not self.dbf: raise ShapefileException("Shapefile Reader requires a shapefile or file-like object. (no dbf file found)") dbf = self.dbf (self.numRecords, self.__dbfHdrLength) = \ unpack("<xxxxLH22x", dbf.read(32)) return self.__dbfHdrLength
python
def __dbfHeaderLength(self): """Retrieves the header length of a dbf file header.""" if not self.__dbfHdrLength: if not self.dbf: raise ShapefileException("Shapefile Reader requires a shapefile or file-like object. (no dbf file found)") dbf = self.dbf (self.numRecords, self.__dbfHdrLength) = \ unpack("<xxxxLH22x", dbf.read(32)) return self.__dbfHdrLength
[ "def", "__dbfHeaderLength", "(", "self", ")", ":", "if", "not", "self", ".", "__dbfHdrLength", ":", "if", "not", "self", ".", "dbf", ":", "raise", "ShapefileException", "(", "\"Shapefile Reader requires a shapefile or file-like object. (no dbf file found)\"", ")", "dbf"...
Retrieves the header length of a dbf file header.
[ "Retrieves", "the", "header", "length", "of", "a", "dbf", "file", "header", "." ]
293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881
https://github.com/perrygeo/simanneal/blob/293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881/examples/watershed/shapefile.py#L313-L321
train
203,102
perrygeo/simanneal
examples/watershed/shapefile.py
Reader.__recordFmt
def __recordFmt(self): """Calculates the size of a .shp geometry record.""" if not self.numRecords: self.__dbfHeader() fmt = ''.join(['%ds' % fieldinfo[2] for fieldinfo in self.fields]) fmtSize = calcsize(fmt) return (fmt, fmtSize)
python
def __recordFmt(self): """Calculates the size of a .shp geometry record.""" if not self.numRecords: self.__dbfHeader() fmt = ''.join(['%ds' % fieldinfo[2] for fieldinfo in self.fields]) fmtSize = calcsize(fmt) return (fmt, fmtSize)
[ "def", "__recordFmt", "(", "self", ")", ":", "if", "not", "self", ".", "numRecords", ":", "self", ".", "__dbfHeader", "(", ")", "fmt", "=", "''", ".", "join", "(", "[", "'%ds'", "%", "fieldinfo", "[", "2", "]", "for", "fieldinfo", "in", "self", "."...
Calculates the size of a .shp geometry record.
[ "Calculates", "the", "size", "of", "a", ".", "shp", "geometry", "record", "." ]
293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881
https://github.com/perrygeo/simanneal/blob/293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881/examples/watershed/shapefile.py#L347-L353
train
203,103
perrygeo/simanneal
examples/watershed/shapefile.py
Reader.records
def records(self): """Returns all records in a dbf file.""" if not self.numRecords: self.__dbfHeader() records = [] f = self.__getFileObj(self.dbf) f.seek(self.__dbfHeaderLength()) for i in range(self.numRecords): r = self.__record() if r: records.append(r) return records
python
def records(self): """Returns all records in a dbf file.""" if not self.numRecords: self.__dbfHeader() records = [] f = self.__getFileObj(self.dbf) f.seek(self.__dbfHeaderLength()) for i in range(self.numRecords): r = self.__record() if r: records.append(r) return records
[ "def", "records", "(", "self", ")", ":", "if", "not", "self", ".", "numRecords", ":", "self", ".", "__dbfHeader", "(", ")", "records", "=", "[", "]", "f", "=", "self", ".", "__getFileObj", "(", "self", ".", "dbf", ")", "f", ".", "seek", "(", "sel...
Returns all records in a dbf file.
[ "Returns", "all", "records", "in", "a", "dbf", "file", "." ]
293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881
https://github.com/perrygeo/simanneal/blob/293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881/examples/watershed/shapefile.py#L408-L419
train
203,104
perrygeo/simanneal
examples/watershed/shapefile.py
Writer.point
def point(self, x, y, z=0, m=0): """Creates a point shape.""" pointShape = _Shape(self.shapeType) pointShape.points.append([x, y, z, m]) self._shapes.append(pointShape)
python
def point(self, x, y, z=0, m=0): """Creates a point shape.""" pointShape = _Shape(self.shapeType) pointShape.points.append([x, y, z, m]) self._shapes.append(pointShape)
[ "def", "point", "(", "self", ",", "x", ",", "y", ",", "z", "=", "0", ",", "m", "=", "0", ")", ":", "pointShape", "=", "_Shape", "(", "self", ".", "shapeType", ")", "pointShape", ".", "points", ".", "append", "(", "[", "x", ",", "y", ",", "z",...
Creates a point shape.
[ "Creates", "a", "point", "shape", "." ]
293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881
https://github.com/perrygeo/simanneal/blob/293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881/examples/watershed/shapefile.py#L751-L755
train
203,105
perrygeo/simanneal
examples/watershed/shapefile.py
Writer.saveShp
def saveShp(self, target): """Save an shp file.""" if not hasattr(target, "write"): target = os.path.splitext(target)[0] + '.shp' if not self.shapeType: self.shapeType = self._shapes[0].shapeType self.shp = self.__getFileObj(target) self.__shapefileHeader(self.shp, headerType='shp') self.__shpRecords()
python
def saveShp(self, target): """Save an shp file.""" if not hasattr(target, "write"): target = os.path.splitext(target)[0] + '.shp' if not self.shapeType: self.shapeType = self._shapes[0].shapeType self.shp = self.__getFileObj(target) self.__shapefileHeader(self.shp, headerType='shp') self.__shpRecords()
[ "def", "saveShp", "(", "self", ",", "target", ")", ":", "if", "not", "hasattr", "(", "target", ",", "\"write\"", ")", ":", "target", "=", "os", ".", "path", ".", "splitext", "(", "target", ")", "[", "0", "]", "+", "'.shp'", "if", "not", "self", "...
Save an shp file.
[ "Save", "an", "shp", "file", "." ]
293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881
https://github.com/perrygeo/simanneal/blob/293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881/examples/watershed/shapefile.py#L825-L833
train
203,106
perrygeo/simanneal
examples/watershed/shapefile.py
Writer.saveShx
def saveShx(self, target): """Save an shx file.""" if not hasattr(target, "write"): target = os.path.splitext(target)[0] + '.shx' if not self.shapeType: self.shapeType = self._shapes[0].shapeType self.shx = self.__getFileObj(target) self.__shapefileHeader(self.shx, headerType='shx') self.__shxRecords()
python
def saveShx(self, target): """Save an shx file.""" if not hasattr(target, "write"): target = os.path.splitext(target)[0] + '.shx' if not self.shapeType: self.shapeType = self._shapes[0].shapeType self.shx = self.__getFileObj(target) self.__shapefileHeader(self.shx, headerType='shx') self.__shxRecords()
[ "def", "saveShx", "(", "self", ",", "target", ")", ":", "if", "not", "hasattr", "(", "target", ",", "\"write\"", ")", ":", "target", "=", "os", ".", "path", ".", "splitext", "(", "target", ")", "[", "0", "]", "+", "'.shx'", "if", "not", "self", "...
Save an shx file.
[ "Save", "an", "shx", "file", "." ]
293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881
https://github.com/perrygeo/simanneal/blob/293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881/examples/watershed/shapefile.py#L835-L843
train
203,107
perrygeo/simanneal
examples/watershed/shapefile.py
Writer.saveDbf
def saveDbf(self, target): """Save a dbf file.""" if not hasattr(target, "write"): target = os.path.splitext(target)[0] + '.dbf' self.dbf = self.__getFileObj(target) self.__dbfHeader() self.__dbfRecords()
python
def saveDbf(self, target): """Save a dbf file.""" if not hasattr(target, "write"): target = os.path.splitext(target)[0] + '.dbf' self.dbf = self.__getFileObj(target) self.__dbfHeader() self.__dbfRecords()
[ "def", "saveDbf", "(", "self", ",", "target", ")", ":", "if", "not", "hasattr", "(", "target", ",", "\"write\"", ")", ":", "target", "=", "os", ".", "path", ".", "splitext", "(", "target", ")", "[", "0", "]", "+", "'.dbf'", "self", ".", "dbf", "=...
Save a dbf file.
[ "Save", "a", "dbf", "file", "." ]
293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881
https://github.com/perrygeo/simanneal/blob/293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881/examples/watershed/shapefile.py#L845-L851
train
203,108
perrygeo/simanneal
examples/watershed/shapefile.py
Writer.save
def save(self, target=None, shp=None, shx=None, dbf=None): """Save the shapefile data to three files or three file-like objects. SHP and DBF files can also be written exclusively using saveShp, saveShx, and saveDbf respectively.""" # TODO: Create a unique filename for target if None. if shp: self.saveShp(shp) if shx: self.saveShx(shx) if dbf: self.saveDbf(dbf) elif target: self.saveShp(target) self.shp.close() self.saveShx(target) self.shx.close() self.saveDbf(target) self.dbf.close()
python
def save(self, target=None, shp=None, shx=None, dbf=None): """Save the shapefile data to three files or three file-like objects. SHP and DBF files can also be written exclusively using saveShp, saveShx, and saveDbf respectively.""" # TODO: Create a unique filename for target if None. if shp: self.saveShp(shp) if shx: self.saveShx(shx) if dbf: self.saveDbf(dbf) elif target: self.saveShp(target) self.shp.close() self.saveShx(target) self.shx.close() self.saveDbf(target) self.dbf.close()
[ "def", "save", "(", "self", ",", "target", "=", "None", ",", "shp", "=", "None", ",", "shx", "=", "None", ",", "dbf", "=", "None", ")", ":", "# TODO: Create a unique filename for target if None.\r", "if", "shp", ":", "self", ".", "saveShp", "(", "shp", "...
Save the shapefile data to three files or three file-like objects. SHP and DBF files can also be written exclusively using saveShp, saveShx, and saveDbf respectively.
[ "Save", "the", "shapefile", "data", "to", "three", "files", "or", "three", "file", "-", "like", "objects", ".", "SHP", "and", "DBF", "files", "can", "also", "be", "written", "exclusively", "using", "saveShp", "saveShx", "and", "saveDbf", "respectively", "." ...
293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881
https://github.com/perrygeo/simanneal/blob/293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881/examples/watershed/shapefile.py#L853-L870
train
203,109
perrygeo/simanneal
examples/watershed/shapefile.py
Editor.delete
def delete(self, shape=None, part=None, point=None): """Deletes the specified part of any shape by specifying a shape number, part number, or point number.""" # shape, part, point if shape and part and point: del self._shapes[shape][part][point] # shape, part elif shape and part and not point: del self._shapes[shape][part] # shape elif shape and not part and not point: del self._shapes[shape] # point elif not shape and not part and point: for s in self._shapes: if s.shapeType == 1: del self._shapes[point] else: for part in s.parts: del s[part][point] # part, point elif not shape and part and point: for s in self._shapes: del s[part][point] # part elif not shape and part and not point: for s in self._shapes: del s[part]
python
def delete(self, shape=None, part=None, point=None): """Deletes the specified part of any shape by specifying a shape number, part number, or point number.""" # shape, part, point if shape and part and point: del self._shapes[shape][part][point] # shape, part elif shape and part and not point: del self._shapes[shape][part] # shape elif shape and not part and not point: del self._shapes[shape] # point elif not shape and not part and point: for s in self._shapes: if s.shapeType == 1: del self._shapes[point] else: for part in s.parts: del s[part][point] # part, point elif not shape and part and point: for s in self._shapes: del s[part][point] # part elif not shape and part and not point: for s in self._shapes: del s[part]
[ "def", "delete", "(", "self", ",", "shape", "=", "None", ",", "part", "=", "None", ",", "point", "=", "None", ")", ":", "# shape, part, point\r", "if", "shape", "and", "part", "and", "point", ":", "del", "self", ".", "_shapes", "[", "shape", "]", "["...
Deletes the specified part of any shape by specifying a shape number, part number, or point number.
[ "Deletes", "the", "specified", "part", "of", "any", "shape", "by", "specifying", "a", "shape", "number", "part", "number", "or", "point", "number", "." ]
293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881
https://github.com/perrygeo/simanneal/blob/293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881/examples/watershed/shapefile.py#L891-L918
train
203,110
perrygeo/simanneal
examples/watershed/shapefile.py
Editor.balance
def balance(self): """Adds a corresponding empty attribute or null geometry record depending on which type of record was created to make sure all three files are in synch.""" if len(self.records) > len(self._shapes): self.null() elif len(self.records) < len(self._shapes): self.record()
python
def balance(self): """Adds a corresponding empty attribute or null geometry record depending on which type of record was created to make sure all three files are in synch.""" if len(self.records) > len(self._shapes): self.null() elif len(self.records) < len(self._shapes): self.record()
[ "def", "balance", "(", "self", ")", ":", "if", "len", "(", "self", ".", "records", ")", ">", "len", "(", "self", ".", "_shapes", ")", ":", "self", ".", "null", "(", ")", "elif", "len", "(", "self", ".", "records", ")", "<", "len", "(", "self", ...
Adds a corresponding empty attribute or null geometry record depending on which type of record was created to make sure all three files are in synch.
[ "Adds", "a", "corresponding", "empty", "attribute", "or", "null", "geometry", "record", "depending", "on", "which", "type", "of", "record", "was", "created", "to", "make", "sure", "all", "three", "files", "are", "in", "synch", "." ]
293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881
https://github.com/perrygeo/simanneal/blob/293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881/examples/watershed/shapefile.py#L973-L980
train
203,111
perrygeo/simanneal
examples/watershed/shapefile.py
Editor.__fieldNorm
def __fieldNorm(self, fieldName): """Normalizes a dbf field name to fit within the spec and the expectations of certain ESRI software.""" if len(fieldName) > 11: fieldName = fieldName[:11] fieldName = fieldName.upper() fieldName.replace(' ', '_')
python
def __fieldNorm(self, fieldName): """Normalizes a dbf field name to fit within the spec and the expectations of certain ESRI software.""" if len(fieldName) > 11: fieldName = fieldName[:11] fieldName = fieldName.upper() fieldName.replace(' ', '_')
[ "def", "__fieldNorm", "(", "self", ",", "fieldName", ")", ":", "if", "len", "(", "fieldName", ")", ">", "11", ":", "fieldName", "=", "fieldName", "[", ":", "11", "]", "fieldName", "=", "fieldName", ".", "upper", "(", ")", "fieldName", ".", "replace", ...
Normalizes a dbf field name to fit within the spec and the expectations of certain ESRI software.
[ "Normalizes", "a", "dbf", "field", "name", "to", "fit", "within", "the", "spec", "and", "the", "expectations", "of", "certain", "ESRI", "software", "." ]
293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881
https://github.com/perrygeo/simanneal/blob/293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881/examples/watershed/shapefile.py#L982-L987
train
203,112
Shoobx/xmldiff
xmldiff/_diff_match_patch_py3.py
diff_match_patch.diff_main
def diff_main(self, text1, text2, checklines=True, deadline=None): """Find the differences between two texts. Simplifies the problem by stripping any common prefix or suffix off the texts before diffing. Args: text1: Old string to be diffed. text2: New string to be diffed. checklines: Optional speedup flag. If present and false, then don't run a line-level diff first to identify the changed areas. Defaults to true, which does a faster, slightly less optimal diff. deadline: Optional time when the diff should be complete by. Used internally for recursive calls. Users should set DiffTimeout instead. Returns: Array of changes. """ # Set a deadline by which time the diff must be complete. if deadline == None: # Unlike in most languages, Python counts time in seconds. if self.Diff_Timeout <= 0: deadline = sys.maxsize else: deadline = time.time() + self.Diff_Timeout # Check for null inputs. if text1 == None or text2 == None: raise ValueError("Null inputs. (diff_main)") # Check for equality (speedup). if text1 == text2: if text1: return [(self.DIFF_EQUAL, text1)] return [] # Trim off common prefix (speedup). commonlength = self.diff_commonPrefix(text1, text2) commonprefix = text1[:commonlength] text1 = text1[commonlength:] text2 = text2[commonlength:] # Trim off common suffix (speedup). commonlength = self.diff_commonSuffix(text1, text2) if commonlength == 0: commonsuffix = '' else: commonsuffix = text1[-commonlength:] text1 = text1[:-commonlength] text2 = text2[:-commonlength] # Compute the diff on the middle block. diffs = self.diff_compute(text1, text2, checklines, deadline) # Restore the prefix and suffix. if commonprefix: diffs[:0] = [(self.DIFF_EQUAL, commonprefix)] if commonsuffix: diffs.append((self.DIFF_EQUAL, commonsuffix)) self.diff_cleanupMerge(diffs) return diffs
python
def diff_main(self, text1, text2, checklines=True, deadline=None): """Find the differences between two texts. Simplifies the problem by stripping any common prefix or suffix off the texts before diffing. Args: text1: Old string to be diffed. text2: New string to be diffed. checklines: Optional speedup flag. If present and false, then don't run a line-level diff first to identify the changed areas. Defaults to true, which does a faster, slightly less optimal diff. deadline: Optional time when the diff should be complete by. Used internally for recursive calls. Users should set DiffTimeout instead. Returns: Array of changes. """ # Set a deadline by which time the diff must be complete. if deadline == None: # Unlike in most languages, Python counts time in seconds. if self.Diff_Timeout <= 0: deadline = sys.maxsize else: deadline = time.time() + self.Diff_Timeout # Check for null inputs. if text1 == None or text2 == None: raise ValueError("Null inputs. (diff_main)") # Check for equality (speedup). if text1 == text2: if text1: return [(self.DIFF_EQUAL, text1)] return [] # Trim off common prefix (speedup). commonlength = self.diff_commonPrefix(text1, text2) commonprefix = text1[:commonlength] text1 = text1[commonlength:] text2 = text2[commonlength:] # Trim off common suffix (speedup). commonlength = self.diff_commonSuffix(text1, text2) if commonlength == 0: commonsuffix = '' else: commonsuffix = text1[-commonlength:] text1 = text1[:-commonlength] text2 = text2[:-commonlength] # Compute the diff on the middle block. diffs = self.diff_compute(text1, text2, checklines, deadline) # Restore the prefix and suffix. if commonprefix: diffs[:0] = [(self.DIFF_EQUAL, commonprefix)] if commonsuffix: diffs.append((self.DIFF_EQUAL, commonsuffix)) self.diff_cleanupMerge(diffs) return diffs
[ "def", "diff_main", "(", "self", ",", "text1", ",", "text2", ",", "checklines", "=", "True", ",", "deadline", "=", "None", ")", ":", "# Set a deadline by which time the diff must be complete.", "if", "deadline", "==", "None", ":", "# Unlike in most languages, Python c...
Find the differences between two texts. Simplifies the problem by stripping any common prefix or suffix off the texts before diffing. Args: text1: Old string to be diffed. text2: New string to be diffed. checklines: Optional speedup flag. If present and false, then don't run a line-level diff first to identify the changed areas. Defaults to true, which does a faster, slightly less optimal diff. deadline: Optional time when the diff should be complete by. Used internally for recursive calls. Users should set DiffTimeout instead. Returns: Array of changes.
[ "Find", "the", "differences", "between", "two", "texts", ".", "Simplifies", "the", "problem", "by", "stripping", "any", "common", "prefix", "or", "suffix", "off", "the", "texts", "before", "diffing", "." ]
ec7835bce9ba69ff4ce03ab6c11397183b6f8411
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/_diff_match_patch_py3.py#L78-L136
train
203,113
Shoobx/xmldiff
xmldiff/_diff_match_patch_py3.py
diff_match_patch.diff_compute
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. If true, then run a faster, slightly less optimal diff. deadline: Time when the diff should be complete by. Returns: Array of changes. """ 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) = (text1, text2) i = longtext.find(shorttext) if i != -1: # Shorter text is inside the longer text (speedup). diffs = [(self.DIFF_INSERT, longtext[:i]), (self.DIFF_EQUAL, shorttext), (self.DIFF_INSERT, longtext[i + len(shorttext):])] # Swap insertions for deletions if diff is reversed. if len(text1) > len(text2): diffs[0] = (self.DIFF_DELETE, diffs[0][1]) diffs[2] = (self.DIFF_DELETE, diffs[2][1]) return diffs if len(shorttext) == 1: # Single character string. # After the previous speedup, the character can't be an equality. return [(self.DIFF_DELETE, text1), (self.DIFF_INSERT, text2)] # Check to see if the problem can be split in two. hm = self.diff_halfMatch(text1, text2) if hm: # A half-match was found, sort out the return data. (text1_a, text1_b, text2_a, text2_b, mid_common) = hm # Send both pairs off for separate processing. diffs_a = self.diff_main(text1_a, text2_a, checklines, deadline) diffs_b = self.diff_main(text1_b, text2_b, checklines, deadline) # Merge the results. return diffs_a + [(self.DIFF_EQUAL, mid_common)] + diffs_b if checklines and len(text1) > 100 and len(text2) > 100: return self.diff_lineMode(text1, text2, deadline) return self.diff_bisect(text1, text2, deadline)
python
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. If true, then run a faster, slightly less optimal diff. deadline: Time when the diff should be complete by. Returns: Array of changes. """ 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) = (text1, text2) i = longtext.find(shorttext) if i != -1: # Shorter text is inside the longer text (speedup). diffs = [(self.DIFF_INSERT, longtext[:i]), (self.DIFF_EQUAL, shorttext), (self.DIFF_INSERT, longtext[i + len(shorttext):])] # Swap insertions for deletions if diff is reversed. if len(text1) > len(text2): diffs[0] = (self.DIFF_DELETE, diffs[0][1]) diffs[2] = (self.DIFF_DELETE, diffs[2][1]) return diffs if len(shorttext) == 1: # Single character string. # After the previous speedup, the character can't be an equality. return [(self.DIFF_DELETE, text1), (self.DIFF_INSERT, text2)] # Check to see if the problem can be split in two. hm = self.diff_halfMatch(text1, text2) if hm: # A half-match was found, sort out the return data. (text1_a, text1_b, text2_a, text2_b, mid_common) = hm # Send both pairs off for separate processing. diffs_a = self.diff_main(text1_a, text2_a, checklines, deadline) diffs_b = self.diff_main(text1_b, text2_b, checklines, deadline) # Merge the results. return diffs_a + [(self.DIFF_EQUAL, mid_common)] + diffs_b if checklines and len(text1) > 100 and len(text2) > 100: return self.diff_lineMode(text1, text2, deadline) return self.diff_bisect(text1, text2, deadline)
[ "def", "diff_compute", "(", "self", ",", "text1", ",", "text2", ",", "checklines", ",", "deadline", ")", ":", "if", "not", "text1", ":", "# Just add some text (speedup).", "return", "[", "(", "self", ".", "DIFF_INSERT", ",", "text2", ")", "]", "if", "not",...
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. If true, then run a faster, slightly less optimal diff. deadline: Time when the diff should be complete by. Returns: Array of changes.
[ "Find", "the", "differences", "between", "two", "texts", ".", "Assumes", "that", "the", "texts", "do", "not", "have", "any", "common", "prefix", "or", "suffix", "." ]
ec7835bce9ba69ff4ce03ab6c11397183b6f8411
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/_diff_match_patch_py3.py#L138-L195
train
203,114
Shoobx/xmldiff
xmldiff/_diff_match_patch_py3.py
diff_match_patch.diff_lineMode
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 changes. """ # 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 lines) self.diff_cleanupSemantic(diffs) # Rediff any replacement blocks, this time character-by-character. # Add a dummy entry at the end. diffs.append((self.DIFF_EQUAL, '')) pointer = 0 count_delete = 0 count_insert = 0 text_delete = '' text_insert = '' while pointer < len(diffs): if diffs[pointer][0] == self.DIFF_INSERT: count_insert += 1 text_insert += diffs[pointer][1] elif diffs[pointer][0] == self.DIFF_DELETE: count_delete += 1 text_delete += diffs[pointer][1] elif diffs[pointer][0] == self.DIFF_EQUAL: # Upon reaching an equality, check for prior redundancies. if count_delete >= 1 and count_insert >= 1: # Delete the offending records and add the merged ones. subDiff = self.diff_main(text_delete, text_insert, False, deadline) diffs[pointer - count_delete - count_insert : pointer] = subDiff pointer = pointer - count_delete - count_insert + len(subDiff) count_insert = 0 count_delete = 0 text_delete = '' text_insert = '' pointer += 1 diffs.pop() # Remove the dummy entry at the end. return diffs
python
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 changes. """ # 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 lines) self.diff_cleanupSemantic(diffs) # Rediff any replacement blocks, this time character-by-character. # Add a dummy entry at the end. diffs.append((self.DIFF_EQUAL, '')) pointer = 0 count_delete = 0 count_insert = 0 text_delete = '' text_insert = '' while pointer < len(diffs): if diffs[pointer][0] == self.DIFF_INSERT: count_insert += 1 text_insert += diffs[pointer][1] elif diffs[pointer][0] == self.DIFF_DELETE: count_delete += 1 text_delete += diffs[pointer][1] elif diffs[pointer][0] == self.DIFF_EQUAL: # Upon reaching an equality, check for prior redundancies. if count_delete >= 1 and count_insert >= 1: # Delete the offending records and add the merged ones. subDiff = self.diff_main(text_delete, text_insert, False, deadline) diffs[pointer - count_delete - count_insert : pointer] = subDiff pointer = pointer - count_delete - count_insert + len(subDiff) count_insert = 0 count_delete = 0 text_delete = '' text_insert = '' pointer += 1 diffs.pop() # Remove the dummy entry at the end. return diffs
[ "def", "diff_lineMode", "(", "self", ",", "text1", ",", "text2", ",", "deadline", ")", ":", "# Scan the text on a line-by-line basis first.", "(", "text1", ",", "text2", ",", "linearray", ")", "=", "self", ".", "diff_linesToChars", "(", "text1", ",", "text2", ...
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 changes.
[ "Do", "a", "quick", "line", "-", "level", "diff", "on", "both", "strings", "then", "rediff", "the", "parts", "for", "greater", "accuracy", ".", "This", "speedup", "can", "produce", "non", "-", "minimal", "diffs", "." ]
ec7835bce9ba69ff4ce03ab6c11397183b6f8411
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/_diff_match_patch_py3.py#L197-L252
train
203,115
Shoobx/xmldiff
xmldiff/_diff_match_patch_py3.py
diff_match_patch.diff_bisectSplit
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. Returns: Array of diff tuples. """ 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
python
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. Returns: Array of diff tuples. """ 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", ")", ":", "text1a", "=", "text1", "[", ":", "x", "]", "text2a", "=", "text2", "[", ":", "y", "]", "text1b", "=", "text1", "[", "x", ":", "]...
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. Returns: Array of diff tuples.
[ "Given", "the", "location", "of", "the", "middle", "snake", "split", "the", "diff", "in", "two", "parts", "and", "recurse", "." ]
ec7835bce9ba69ff4ce03ab6c11397183b6f8411
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/_diff_match_patch_py3.py#L356-L379
train
203,116
Shoobx/xmldiff
xmldiff/_diff_match_patch_py3.py
diff_match_patch.diff_linesToChars
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 strings. The zeroth element of the array of unique strings is intentionally blank. """ 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): """Split a text into an array of strings. Reduce the texts to a string of hashes where each Unicode character represents one line. Modifies linearray and linehash through being a closure. Args: text: String to encode. Returns: Encoded string. """ chars = [] # Walk the text, pulling out a substring for each line. # text.split('\n') would would temporarily double our memory footprint. # Modifying text would create many large strings to garbage collect. lineStart = 0 lineEnd = -1 while lineEnd < len(text) - 1: lineEnd = text.find('\n', lineStart) if lineEnd == -1: lineEnd = len(text) - 1 line = text[lineStart:lineEnd + 1] if line in lineHash: chars.append(chr(lineHash[line])) else: if len(lineArray) == maxLines: # Bail out at 1114111 because chr(1114112) throws. line = text[lineStart:] lineEnd = len(text) lineArray.append(line) lineHash[line] = len(lineArray) - 1 chars.append(chr(len(lineArray) - 1)) lineStart = lineEnd + 1 return "".join(chars) # Allocate 2/3rds of the space for text1, the rest for text2. maxLines = 666666 chars1 = diff_linesToCharsMunge(text1) maxLines = 1114111 chars2 = diff_linesToCharsMunge(text2) return (chars1, chars2, lineArray)
python
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 strings. The zeroth element of the array of unique strings is intentionally blank. """ 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): """Split a text into an array of strings. Reduce the texts to a string of hashes where each Unicode character represents one line. Modifies linearray and linehash through being a closure. Args: text: String to encode. Returns: Encoded string. """ chars = [] # Walk the text, pulling out a substring for each line. # text.split('\n') would would temporarily double our memory footprint. # Modifying text would create many large strings to garbage collect. lineStart = 0 lineEnd = -1 while lineEnd < len(text) - 1: lineEnd = text.find('\n', lineStart) if lineEnd == -1: lineEnd = len(text) - 1 line = text[lineStart:lineEnd + 1] if line in lineHash: chars.append(chr(lineHash[line])) else: if len(lineArray) == maxLines: # Bail out at 1114111 because chr(1114112) throws. line = text[lineStart:] lineEnd = len(text) lineArray.append(line) lineHash[line] = len(lineArray) - 1 chars.append(chr(len(lineArray) - 1)) lineStart = lineEnd + 1 return "".join(chars) # Allocate 2/3rds of the space for text1, the rest for text2. maxLines = 666666 chars1 = diff_linesToCharsMunge(text1) maxLines = 1114111 chars2 = diff_linesToCharsMunge(text2) return (chars1, chars2, lineArray)
[ "def", "diff_linesToChars", "(", "self", ",", "text1", ",", "text2", ")", ":", "lineArray", "=", "[", "]", "# e.g. lineArray[4] == \"Hello\\n\"", "lineHash", "=", "{", "}", "# e.g. lineHash[\"Hello\\n\"] == 4", "# \"\\x00\" is a valid character, but various debuggers don't li...
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 strings. The zeroth element of the array of unique strings is intentionally blank.
[ "Split", "two", "texts", "into", "an", "array", "of", "strings", ".", "Reduce", "the", "texts", "to", "a", "string", "of", "hashes", "where", "each", "Unicode", "character", "represents", "one", "line", "." ]
ec7835bce9ba69ff4ce03ab6c11397183b6f8411
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/_diff_match_patch_py3.py#L381-L442
train
203,117
Shoobx/xmldiff
xmldiff/_diff_match_patch_py3.py
diff_match_patch.diff_charsToLines
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. """ 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))
python
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. """ 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", ")", ":", "for", "i", "in", "range", "(", "len", "(", "diffs", ")", ")", ":", "text", "=", "[", "]", "for", "char", "in", "diffs", "[", "i", "]", "[", "1", "]", ":", "text...
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.
[ "Rehydrate", "the", "text", "in", "a", "diff", "from", "a", "string", "of", "line", "hashes", "to", "real", "lines", "of", "text", "." ]
ec7835bce9ba69ff4ce03ab6c11397183b6f8411
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/_diff_match_patch_py3.py#L444-L456
train
203,118
Shoobx/xmldiff
xmldiff/_diff_match_patch_py3.py
diff_match_patch.diff_commonPrefix
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. """ # 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 while pointermin < pointermid: if text1[pointerstart:pointermid] == text2[pointerstart:pointermid]: pointermin = pointermid pointerstart = pointermin else: pointermax = pointermid pointermid = (pointermax - pointermin) // 2 + pointermin return pointermid
python
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. """ # 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 while pointermin < pointermid: if text1[pointerstart:pointermid] == text2[pointerstart:pointermid]: pointermin = pointermid pointerstart = pointermin else: pointermax = pointermid pointermid = (pointermax - pointermin) // 2 + pointermin return pointermid
[ "def", "diff_commonPrefix", "(", "self", ",", "text1", ",", "text2", ")", ":", "# Quick check for common null cases.", "if", "not", "text1", "or", "not", "text2", "or", "text1", "[", "0", "]", "!=", "text2", "[", "0", "]", ":", "return", "0", "# Binary sea...
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.
[ "Determine", "the", "common", "prefix", "of", "two", "strings", "." ]
ec7835bce9ba69ff4ce03ab6c11397183b6f8411
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/_diff_match_patch_py3.py#L458-L484
train
203,119
Shoobx/xmldiff
xmldiff/_diff_match_patch_py3.py
diff_match_patch.diff_commonSuffix
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. """ # 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 while pointermin < pointermid: if (text1[-pointermid:len(text1) - pointerend] == text2[-pointermid:len(text2) - pointerend]): pointermin = pointermid pointerend = pointermin else: pointermax = pointermid pointermid = (pointermax - pointermin) // 2 + pointermin return pointermid
python
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. """ # 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 while pointermin < pointermid: if (text1[-pointermid:len(text1) - pointerend] == text2[-pointermid:len(text2) - pointerend]): pointermin = pointermid pointerend = pointermin else: pointermax = pointermid pointermid = (pointermax - pointermin) // 2 + pointermin return pointermid
[ "def", "diff_commonSuffix", "(", "self", ",", "text1", ",", "text2", ")", ":", "# Quick check for common null cases.", "if", "not", "text1", "or", "not", "text2", "or", "text1", "[", "-", "1", "]", "!=", "text2", "[", "-", "1", "]", ":", "return", "0", ...
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.
[ "Determine", "the", "common", "suffix", "of", "two", "strings", "." ]
ec7835bce9ba69ff4ce03ab6c11397183b6f8411
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/_diff_match_patch_py3.py#L486-L513
train
203,120
Shoobx/xmldiff
xmldiff/_diff_match_patch_py3.py
diff_match_patch.diff_commonOverlap
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. """ # 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:] elif text1_length < text2_length: text2 = text2[:text1_length] text_length = min(text1_length, text2_length) # Quick check for the worst case. if text1 == text2: return text_length # Start by looking for a single character match # and increase length until no match is found. # Performance analysis: https://neil.fraser.name/news/2010/11/04/ best = 0 length = 1 while True: pattern = text1[-length:] found = text2.find(pattern) if found == -1: return best length += found if found == 0 or text1[-length:] == text2[:length]: best = length length += 1
python
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. """ # 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:] elif text1_length < text2_length: text2 = text2[:text1_length] text_length = min(text1_length, text2_length) # Quick check for the worst case. if text1 == text2: return text_length # Start by looking for a single character match # and increase length until no match is found. # Performance analysis: https://neil.fraser.name/news/2010/11/04/ best = 0 length = 1 while True: pattern = text1[-length:] found = text2.find(pattern) if found == -1: return best length += found if found == 0 or text1[-length:] == text2[:length]: best = length length += 1
[ "def", "diff_commonOverlap", "(", "self", ",", "text1", ",", "text2", ")", ":", "# Cache the text lengths to prevent multiple calls.", "text1_length", "=", "len", "(", "text1", ")", "text2_length", "=", "len", "(", "text2", ")", "# Eliminate the null case.", "if", "...
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.
[ "Determine", "if", "the", "suffix", "of", "one", "string", "is", "the", "prefix", "of", "another", "." ]
ec7835bce9ba69ff4ce03ab6c11397183b6f8411
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/_diff_match_patch_py3.py#L515-L555
train
203,121
Shoobx/xmldiff
xmldiff/_diff_match_patch_py3.py
diff_match_patch.diff_halfMatch
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 text2, the suffix of text2 and the common middle. Or None if there was no match. """ 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(longtext): return None # Pointless. def diff_halfMatchI(longtext, shorttext, i): """Does a substring of shorttext exist within longtext such that the substring is at least half the length of longtext? Closure, but does not reference any external variables. Args: longtext: Longer string. shorttext: Shorter string. i: Start index of quarter length substring within longtext. Returns: Five element Array, containing the prefix of longtext, the suffix of longtext, the prefix of shorttext, the suffix of shorttext and the common middle. Or None if there was no match. """ seed = longtext[i:i + len(longtext) // 4] best_common = '' j = shorttext.find(seed) while j != -1: prefixLength = self.diff_commonPrefix(longtext[i:], shorttext[j:]) suffixLength = self.diff_commonSuffix(longtext[:i], shorttext[:j]) if len(best_common) < suffixLength + prefixLength: best_common = (shorttext[j - suffixLength:j] + shorttext[j:j + prefixLength]) best_longtext_a = longtext[:i - suffixLength] best_longtext_b = longtext[i + prefixLength:] best_shorttext_a = shorttext[:j - suffixLength] best_shorttext_b = shorttext[j + prefixLength:] j = shorttext.find(seed, j + 1) if len(best_common) * 2 >= len(longtext): return (best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b, best_common) else: return None # First check if the second quarter is the seed for a half-match. hm1 = diff_halfMatchI(longtext, shorttext, (len(longtext) + 3) // 4) # Check again based on the third quarter. hm2 = diff_halfMatchI(longtext, shorttext, (len(longtext) + 1) // 2) if not hm1 and not hm2: return None elif not hm2: hm = hm1 elif not hm1: hm = hm2 else: # Both matched. Select the longest. if len(hm1[4]) > len(hm2[4]): hm = hm1 else: hm = hm2 # A half-match was found, sort out the return data. if len(text1) > len(text2): (text1_a, text1_b, text2_a, text2_b, mid_common) = hm else: (text2_a, text2_b, text1_a, text1_b, mid_common) = hm return (text1_a, text1_b, text2_a, text2_b, mid_common)
python
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 text2, the suffix of text2 and the common middle. Or None if there was no match. """ 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(longtext): return None # Pointless. def diff_halfMatchI(longtext, shorttext, i): """Does a substring of shorttext exist within longtext such that the substring is at least half the length of longtext? Closure, but does not reference any external variables. Args: longtext: Longer string. shorttext: Shorter string. i: Start index of quarter length substring within longtext. Returns: Five element Array, containing the prefix of longtext, the suffix of longtext, the prefix of shorttext, the suffix of shorttext and the common middle. Or None if there was no match. """ seed = longtext[i:i + len(longtext) // 4] best_common = '' j = shorttext.find(seed) while j != -1: prefixLength = self.diff_commonPrefix(longtext[i:], shorttext[j:]) suffixLength = self.diff_commonSuffix(longtext[:i], shorttext[:j]) if len(best_common) < suffixLength + prefixLength: best_common = (shorttext[j - suffixLength:j] + shorttext[j:j + prefixLength]) best_longtext_a = longtext[:i - suffixLength] best_longtext_b = longtext[i + prefixLength:] best_shorttext_a = shorttext[:j - suffixLength] best_shorttext_b = shorttext[j + prefixLength:] j = shorttext.find(seed, j + 1) if len(best_common) * 2 >= len(longtext): return (best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b, best_common) else: return None # First check if the second quarter is the seed for a half-match. hm1 = diff_halfMatchI(longtext, shorttext, (len(longtext) + 3) // 4) # Check again based on the third quarter. hm2 = diff_halfMatchI(longtext, shorttext, (len(longtext) + 1) // 2) if not hm1 and not hm2: return None elif not hm2: hm = hm1 elif not hm1: hm = hm2 else: # Both matched. Select the longest. if len(hm1[4]) > len(hm2[4]): hm = hm1 else: hm = hm2 # A half-match was found, sort out the return data. if len(text1) > len(text2): (text1_a, text1_b, text2_a, text2_b, mid_common) = hm else: (text2_a, text2_b, text1_a, text1_b, mid_common) = hm return (text1_a, text1_b, text2_a, text2_b, mid_common)
[ "def", "diff_halfMatch", "(", "self", ",", "text1", ",", "text2", ")", ":", "if", "self", ".", "Diff_Timeout", "<=", "0", ":", "# Don't risk returning a non-optimal diff if we have unlimited time.", "return", "None", "if", "len", "(", "text1", ")", ">", "len", "...
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 text2, the suffix of text2 and the common middle. Or None if there was no match.
[ "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", "." ]
ec7835bce9ba69ff4ce03ab6c11397183b6f8411
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/_diff_match_patch_py3.py#L557-L639
train
203,122
Shoobx/xmldiff
xmldiff/_diff_match_patch_py3.py
diff_match_patch.diff_cleanupEfficiency
def diff_cleanupEfficiency(self, diffs): """Reduce the number of edits by eliminating operationally trivial equalities. Args: diffs: Array of diff tuples. """ 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 a deletion operation before the last equality. post_ins = False # Is there an insertion operation after the last equality. post_del = False # Is there a deletion operation after the last equality. while pointer < len(diffs): if diffs[pointer][0] == self.DIFF_EQUAL: # Equality found. if (len(diffs[pointer][1]) < self.Diff_EditCost and (post_ins or post_del)): # Candidate found. equalities.append(pointer) pre_ins = post_ins pre_del = post_del lastEquality = diffs[pointer][1] else: # Not a candidate, and can never become one. equalities = [] lastEquality = None post_ins = post_del = False else: # An insertion or deletion. if diffs[pointer][0] == self.DIFF_DELETE: post_del = True else: post_ins = True # Five types to be split: # <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del> # <ins>A</ins>X<ins>C</ins><del>D</del> # <ins>A</ins><del>B</del>X<ins>C</ins> # <ins>A</del>X<ins>C</ins><del>D</del> # <ins>A</ins><del>B</del>X<del>C</del> if lastEquality and ((pre_ins and pre_del and post_ins and post_del) or ((len(lastEquality) < self.Diff_EditCost / 2) and (pre_ins + pre_del + post_ins + post_del) == 3)): # Duplicate record. diffs.insert(equalities[-1], (self.DIFF_DELETE, lastEquality)) # Change second copy to insert. diffs[equalities[-1] + 1] = (self.DIFF_INSERT, diffs[equalities[-1] + 1][1]) equalities.pop() # Throw away the equality we just deleted. lastEquality = None if pre_ins and pre_del: # No changes made which could affect previous entry, keep going. post_ins = post_del = True equalities = [] else: if len(equalities): equalities.pop() # Throw away the previous equality. if len(equalities): pointer = equalities[-1] else: pointer = -1 post_ins = post_del = False changes = True pointer += 1 if changes: self.diff_cleanupMerge(diffs)
python
def diff_cleanupEfficiency(self, diffs): """Reduce the number of edits by eliminating operationally trivial equalities. Args: diffs: Array of diff tuples. """ 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 a deletion operation before the last equality. post_ins = False # Is there an insertion operation after the last equality. post_del = False # Is there a deletion operation after the last equality. while pointer < len(diffs): if diffs[pointer][0] == self.DIFF_EQUAL: # Equality found. if (len(diffs[pointer][1]) < self.Diff_EditCost and (post_ins or post_del)): # Candidate found. equalities.append(pointer) pre_ins = post_ins pre_del = post_del lastEquality = diffs[pointer][1] else: # Not a candidate, and can never become one. equalities = [] lastEquality = None post_ins = post_del = False else: # An insertion or deletion. if diffs[pointer][0] == self.DIFF_DELETE: post_del = True else: post_ins = True # Five types to be split: # <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del> # <ins>A</ins>X<ins>C</ins><del>D</del> # <ins>A</ins><del>B</del>X<ins>C</ins> # <ins>A</del>X<ins>C</ins><del>D</del> # <ins>A</ins><del>B</del>X<del>C</del> if lastEquality and ((pre_ins and pre_del and post_ins and post_del) or ((len(lastEquality) < self.Diff_EditCost / 2) and (pre_ins + pre_del + post_ins + post_del) == 3)): # Duplicate record. diffs.insert(equalities[-1], (self.DIFF_DELETE, lastEquality)) # Change second copy to insert. diffs[equalities[-1] + 1] = (self.DIFF_INSERT, diffs[equalities[-1] + 1][1]) equalities.pop() # Throw away the equality we just deleted. lastEquality = None if pre_ins and pre_del: # No changes made which could affect previous entry, keep going. post_ins = post_del = True equalities = [] else: if len(equalities): equalities.pop() # Throw away the previous equality. if len(equalities): pointer = equalities[-1] else: pointer = -1 post_ins = post_del = False changes = True pointer += 1 if changes: self.diff_cleanupMerge(diffs)
[ "def", "diff_cleanupEfficiency", "(", "self", ",", "diffs", ")", ":", "changes", "=", "False", "equalities", "=", "[", "]", "# Stack of indices where equalities are found.", "lastEquality", "=", "None", "# Always equal to diffs[equalities[-1]][1]", "pointer", "=", "0", ...
Reduce the number of edits by eliminating operationally trivial equalities. Args: diffs: Array of diff tuples.
[ "Reduce", "the", "number", "of", "edits", "by", "eliminating", "operationally", "trivial", "equalities", "." ]
ec7835bce9ba69ff4ce03ab6c11397183b6f8411
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/_diff_match_patch_py3.py#L851-L920
train
203,123
Shoobx/xmldiff
xmldiff/_diff_match_patch_py3.py
diff_match_patch.diff_prettyHtml
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)
python
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)
[ "def", "diff_prettyHtml", "(", "self", ",", "diffs", ")", ":", "html", "=", "[", "]", "for", "(", "op", ",", "data", ")", "in", "diffs", ":", "text", "=", "(", "data", ".", "replace", "(", "\"&\"", ",", "\"&amp;\"", ")", ".", "replace", "(", "\"<...
Convert a diff array into a pretty HTML report. Args: diffs: Array of diff tuples. Returns: HTML representation.
[ "Convert", "a", "diff", "array", "into", "a", "pretty", "HTML", "report", "." ]
ec7835bce9ba69ff4ce03ab6c11397183b6f8411
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/_diff_match_patch_py3.py#L1059-L1078
train
203,124
Shoobx/xmldiff
xmldiff/_diff_match_patch_py3.py
diff_match_patch.diff_levenshtein
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
python
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
[ "def", "diff_levenshtein", "(", "self", ",", "diffs", ")", ":", "levenshtein", "=", "0", "insertions", "=", "0", "deletions", "=", "0", "for", "(", "op", ",", "data", ")", "in", "diffs", ":", "if", "op", "==", "self", ".", "DIFF_INSERT", ":", "insert...
Compute the Levenshtein distance; the number of inserted, deleted or substituted characters. Args: diffs: Array of diff tuples. Returns: Number of changes.
[ "Compute", "the", "Levenshtein", "distance", ";", "the", "number", "of", "inserted", "deleted", "or", "substituted", "characters", "." ]
ec7835bce9ba69ff4ce03ab6c11397183b6f8411
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/_diff_match_patch_py3.py#L1110-L1134
train
203,125
Shoobx/xmldiff
xmldiff/_diff_match_patch_py3.py
diff_match_patch.diff_fromDelta
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
python
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
[ "def", "diff_fromDelta", "(", "self", ",", "text1", ",", "delta", ")", ":", "diffs", "=", "[", "]", "pointer", "=", "0", "# Cursor in text1", "tokens", "=", "delta", ".", "split", "(", "\"\\t\"", ")", "for", "token", "in", "tokens", ":", "if", "token",...
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.
[ "Given", "the", "original", "text1", "and", "an", "encoded", "string", "which", "describes", "the", "operations", "required", "to", "transform", "text1", "into", "text2", "compute", "the", "full", "diff", "." ]
ec7835bce9ba69ff4ce03ab6c11397183b6f8411
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/_diff_match_patch_py3.py#L1160-L1208
train
203,126
Shoobx/xmldiff
xmldiff/_diff_match_patch_py3.py
diff_match_patch.match_main
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
python
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
[ "def", "match_main", "(", "self", ",", "text", ",", "pattern", ",", "loc", ")", ":", "# Check for null inputs.", "if", "text", "==", "None", "or", "pattern", "==", "None", ":", "raise", "ValueError", "(", "\"Null inputs. (match_main)\"", ")", "loc", "=", "ma...
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.
[ "Locate", "the", "best", "instance", "of", "pattern", "in", "text", "near", "loc", "." ]
ec7835bce9ba69ff4ce03ab6c11397183b6f8411
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/_diff_match_patch_py3.py#L1212-L1240
train
203,127
Shoobx/xmldiff
xmldiff/_diff_match_patch_py3.py
diff_match_patch.match_bitap
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
python
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
[ "def", "match_bitap", "(", "self", ",", "text", ",", "pattern", ",", "loc", ")", ":", "# 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.\")", ...
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.
[ "Locate", "the", "best", "instance", "of", "pattern", "in", "text", "near", "loc", "using", "the", "Bitap", "algorithm", "." ]
ec7835bce9ba69ff4ce03ab6c11397183b6f8411
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/_diff_match_patch_py3.py#L1242-L1346
train
203,128
Shoobx/xmldiff
xmldiff/_diff_match_patch_py3.py
diff_match_patch.patch_addContext
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)
python
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)
[ "def", "patch_addContext", "(", "self", ",", "patch", ",", "text", ")", ":", "if", "len", "(", "text", ")", "==", "0", ":", "return", "pattern", "=", "text", "[", "patch", ".", "start2", ":", "patch", ".", "start2", "+", "patch", ".", "length1", "]...
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.
[ "Increase", "the", "context", "until", "it", "is", "unique", "but", "don", "t", "let", "the", "pattern", "expand", "beyond", "Match_MaxBits", "." ]
ec7835bce9ba69ff4ce03ab6c11397183b6f8411
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/_diff_match_patch_py3.py#L1366-L1405
train
203,129
Shoobx/xmldiff
xmldiff/_diff_match_patch_py3.py
diff_match_patch.patch_deepCopy
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
python
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
[ "def", "patch_deepCopy", "(", "self", ",", "patches", ")", ":", "patchesCopy", "=", "[", "]", "for", "patch", "in", "patches", ":", "patchCopy", "=", "patch_obj", "(", ")", "# No need to deep copy the tuples since they are immutable.", "patchCopy", ".", "diffs", "...
Given an array of patches, return another array that is identical. Args: patches: Array of Patch objects. Returns: Array of Patch objects.
[ "Given", "an", "array", "of", "patches", "return", "another", "array", "that", "is", "identical", "." ]
ec7835bce9ba69ff4ce03ab6c11397183b6f8411
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/_diff_match_patch_py3.py#L1520-L1539
train
203,130
Shoobx/xmldiff
xmldiff/_diff_match_patch_py3.py
diff_match_patch.patch_addPadding
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
python
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
[ "def", "patch_addPadding", "(", "self", ",", "patches", ")", ":", "paddingLength", "=", "self", ".", "Patch_Margin", "nullPadding", "=", "\"\"", "for", "x", "in", "range", "(", "1", ",", "paddingLength", "+", "1", ")", ":", "nullPadding", "+=", "chr", "(...
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.
[ "Add", "some", "padding", "on", "text", "start", "and", "end", "so", "that", "edges", "can", "match", "something", ".", "Intended", "to", "be", "called", "only", "from", "within", "patch_apply", "." ]
ec7835bce9ba69ff4ce03ab6c11397183b6f8411
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/_diff_match_patch_py3.py#L1629-L1685
train
203,131
Shoobx/xmldiff
xmldiff/_diff_match_patch_py3.py
diff_match_patch.patch_toText
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)
python
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)
[ "def", "patch_toText", "(", "self", ",", "patches", ")", ":", "text", "=", "[", "]", "for", "patch", "in", "patches", ":", "text", ".", "append", "(", "str", "(", "patch", ")", ")", "return", "\"\"", ".", "join", "(", "text", ")" ]
Take a list of patches and return a textual representation. Args: patches: Array of Patch objects. Returns: Text representation of patches.
[ "Take", "a", "list", "of", "patches", "and", "return", "a", "textual", "representation", "." ]
ec7835bce9ba69ff4ce03ab6c11397183b6f8411
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/_diff_match_patch_py3.py#L1775-L1787
train
203,132
Shoobx/xmldiff
xmldiff/_diff_match_patch_py2.py
diff_match_patch.diff_toDelta
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)
python
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)
[ "def", "diff_toDelta", "(", "self", ",", "diffs", ")", ":", "text", "=", "[", "]", "for", "(", "op", ",", "data", ")", "in", "diffs", ":", "if", "op", "==", "self", ".", "DIFF_INSERT", ":", "# High ascii will raise UnicodeDecodeError. Use Unicode instead.", ...
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.
[ "Crush", "the", "diff", "into", "an", "encoded", "string", "which", "describes", "the", "operations", "required", "to", "transform", "text1", "into", "text2", ".", "E", ".", "g", ".", "=", "3", "\\", "t", "-", "2", "\\", "t", "+", "ing", "-", ">", ...
ec7835bce9ba69ff4ce03ab6c11397183b6f8411
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/_diff_match_patch_py2.py#L1138-L1160
train
203,133
Shoobx/xmldiff
xmldiff/_diff_match_patch_py2.py
diff_match_patch.patch_fromText
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
python
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
[ "def", "patch_fromText", "(", "self", ",", "textline", ")", ":", "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...
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.
[ "Parse", "a", "textual", "representation", "of", "patches", "and", "return", "a", "list", "of", "patch", "objects", "." ]
ec7835bce9ba69ff4ce03ab6c11397183b6f8411
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/_diff_match_patch_py2.py#L1796-L1871
train
203,134
Shoobx/xmldiff
xmldiff/main.py
diff_trees
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)
python
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)
[ "def", "diff_trees", "(", "left", ",", "right", ",", "diff_options", "=", "None", ",", "formatter", "=", "None", ")", ":", "if", "formatter", "is", "not", "None", ":", "formatter", ".", "prepare", "(", "left", ",", "right", ")", "if", "diff_options", "...
Takes two lxml root elements or element trees
[ "Takes", "two", "lxml", "root", "elements", "or", "element", "trees" ]
ec7835bce9ba69ff4ce03ab6c11397183b6f8411
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/main.py#L18-L30
train
203,135
Shoobx/xmldiff
xmldiff/main.py
diff_texts
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)
python
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)
[ "def", "diff_texts", "(", "left", ",", "right", ",", "diff_options", "=", "None", ",", "formatter", "=", "None", ")", ":", "return", "_diff", "(", "etree", ".", "fromstring", ",", "left", ",", "right", ",", "diff_options", "=", "diff_options", ",", "form...
Takes two Unicode strings containing XML
[ "Takes", "two", "Unicode", "strings", "containing", "XML" ]
ec7835bce9ba69ff4ce03ab6c11397183b6f8411
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/main.py#L42-L45
train
203,136
Shoobx/xmldiff
xmldiff/main.py
diff_files
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)
python
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)
[ "def", "diff_files", "(", "left", ",", "right", ",", "diff_options", "=", "None", ",", "formatter", "=", "None", ")", ":", "return", "_diff", "(", "etree", ".", "parse", ",", "left", ",", "right", ",", "diff_options", "=", "diff_options", ",", "formatter...
Takes two filenames or streams, and diffs the XML in those files
[ "Takes", "two", "filenames", "or", "streams", "and", "diffs", "the", "XML", "in", "those", "files" ]
ec7835bce9ba69ff4ce03ab6c11397183b6f8411
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/main.py#L48-L51
train
203,137
Shoobx/xmldiff
xmldiff/main.py
patch_tree
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)
python
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)
[ "def", "patch_tree", "(", "actions", ",", "tree", ")", ":", "patcher", "=", "patch", ".", "Patcher", "(", ")", "return", "patcher", ".", "patch", "(", "actions", ",", "tree", ")" ]
Takes an lxml root element or element tree, and a list of actions
[ "Takes", "an", "lxml", "root", "element", "or", "element", "tree", "and", "a", "list", "of", "actions" ]
ec7835bce9ba69ff4ce03ab6c11397183b6f8411
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/main.py#L115-L118
train
203,138
Shoobx/xmldiff
xmldiff/main.py
patch_text
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)
python
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)
[ "def", "patch_text", "(", "actions", ",", "tree", ")", ":", "tree", "=", "etree", ".", "fromstring", "(", "tree", ")", "actions", "=", "patch", ".", "DiffParser", "(", ")", ".", "parse", "(", "actions", ")", "tree", "=", "patch_tree", "(", "actions", ...
Takes a string with XML and a string with actions
[ "Takes", "a", "string", "with", "XML", "and", "a", "string", "with", "actions" ]
ec7835bce9ba69ff4ce03ab6c11397183b6f8411
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/main.py#L121-L126
train
203,139
Shoobx/xmldiff
xmldiff/main.py
patch_file
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)
python
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)
[ "def", "patch_file", "(", "actions", ",", "tree", ")", ":", "tree", "=", "etree", ".", "parse", "(", "tree", ")", "if", "isinstance", "(", "actions", ",", "six", ".", "string_types", ")", ":", "# It's a string, so it's a filename", "with", "open", "(", "ac...
Takes two filenames or streams, one with XML the other a diff
[ "Takes", "two", "filenames", "or", "streams", "one", "with", "XML", "the", "other", "a", "diff" ]
ec7835bce9ba69ff4ce03ab6c11397183b6f8411
https://github.com/Shoobx/xmldiff/blob/ec7835bce9ba69ff4ce03ab6c11397183b6f8411/xmldiff/main.py#L129-L143
train
203,140
chimera0/accel-brain-code
Automatic-Summarization/pysummarization/readablewebpdf/web_pdf_reading.py
WebPDFReading.url_to_text
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)
python
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)
[ "def", "url_to_text", "(", "self", ",", "url", ")", ":", "path", ",", "headers", "=", "urllib", ".", "request", ".", "urlretrieve", "(", "url", ")", "return", "self", ".", "path_to_text", "(", "path", ")" ]
Download PDF file and transform its document to string. Args: url: PDF url. Returns: string.
[ "Download", "PDF", "file", "and", "transform", "its", "document", "to", "string", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Automatic-Summarization/pysummarization/readablewebpdf/web_pdf_reading.py#L16-L28
train
203,141
chimera0/accel-brain-code
Automatic-Summarization/pysummarization/readablewebpdf/web_pdf_reading.py
WebPDFReading.path_to_text
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
python
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
[ "def", "path_to_text", "(", "self", ",", "path", ")", ":", "rsrcmgr", "=", "PDFResourceManager", "(", ")", "retstr", "=", "StringIO", "(", ")", "codec", "=", "'utf-8'", "laparams", "=", "LAParams", "(", ")", "device", "=", "TextConverter", "(", "rsrcmgr", ...
Transform local PDF file to string. Args: path: path to PDF file. Returns: string.
[ "Transform", "local", "PDF", "file", "to", "string", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Automatic-Summarization/pysummarization/readablewebpdf/web_pdf_reading.py#L30-L71
train
203,142
chimera0/accel-brain-code
Automatic-Summarization/pysummarization/nlp_base.py
NlpBase.listup_sentence
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
python
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
[ "def", "listup_sentence", "(", "self", ",", "data", ",", "counter", "=", "0", ")", ":", "delimiter", "=", "self", ".", "delimiter_list", "[", "counter", "]", "sentence_list", "=", "[", "]", "[", "sentence_list", ".", "append", "(", "sentence", "+", "deli...
Divide string into sentence list. Args: data: string. counter: recursive counter. Returns: List of sentences.
[ "Divide", "string", "into", "sentence", "list", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Automatic-Summarization/pysummarization/nlp_base.py#L66-L86
train
203,143
chimera0/accel-brain-code
Reinforcement-Learning/pyqlearning/misc/beta_dist.py
BetaDist.observe
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
python
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
[ "def", "observe", "(", "self", ",", "success", ",", "failure", ")", ":", "if", "isinstance", "(", "success", ",", "int", ")", "is", "False", ":", "if", "isinstance", "(", "success", ",", "float", ")", "is", "False", ":", "raise", "TypeError", "(", ")...
Observation data. Args: success: The number of success. failure: The number of failure.
[ "Observation", "data", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/misc/beta_dist.py#L42-L64
train
203,144
chimera0/accel-brain-code
Reinforcement-Learning/pyqlearning/misc/beta_dist.py
BetaDist.likelihood
def likelihood(self): ''' Compute likelihood. Returns: likelihood. ''' try: likelihood = self.__success / (self.__success + self.__failure) except ZeroDivisionError: likelihood = 0.0 return likelihood
python
def likelihood(self): ''' Compute likelihood. Returns: likelihood. ''' try: likelihood = self.__success / (self.__success + self.__failure) except ZeroDivisionError: likelihood = 0.0 return likelihood
[ "def", "likelihood", "(", "self", ")", ":", "try", ":", "likelihood", "=", "self", ".", "__success", "/", "(", "self", ".", "__success", "+", "self", ".", "__failure", ")", "except", "ZeroDivisionError", ":", "likelihood", "=", "0.0", "return", "likelihood...
Compute likelihood. Returns: likelihood.
[ "Compute", "likelihood", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/misc/beta_dist.py#L66-L77
train
203,145
chimera0/accel-brain-code
Reinforcement-Learning/pyqlearning/misc/beta_dist.py
BetaDist.expected_value
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
python
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
[ "def", "expected_value", "(", "self", ")", ":", "alpha", "=", "self", ".", "__success", "+", "self", ".", "__default_alpha", "beta", "=", "self", ".", "__failure", "+", "self", ".", "__default_beta", "try", ":", "expected_value", "=", "alpha", "/", "(", ...
Compute expected value. Returns: Expected value.
[ "Compute", "expected", "value", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/misc/beta_dist.py#L79-L93
train
203,146
chimera0/accel-brain-code
Reinforcement-Learning/pyqlearning/misc/beta_dist.py
BetaDist.variance
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
python
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
[ "def", "variance", "(", "self", ")", ":", "alpha", "=", "self", ".", "__success", "+", "self", ".", "__default_alpha", "beta", "=", "self", ".", "__failure", "+", "self", ".", "__default_beta", "try", ":", "variance", "=", "alpha", "*", "beta", "/", "(...
Compute variance. Returns: variance.
[ "Compute", "variance", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/misc/beta_dist.py#L95-L109
train
203,147
chimera0/accel-brain-code
Reinforcement-Learning/pyqlearning/annealingmodel/simulated_annealing.py
SimulatedAnnealing.__move
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
python
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
[ "def", "__move", "(", "self", ",", "current_pos", ")", ":", "if", "self", ".", "__move_range", "is", "not", "None", ":", "next_pos", "=", "np", ".", "random", ".", "randint", "(", "current_pos", "-", "self", ".", "__move_range", ",", "current_pos", "+", ...
Move in the feature map. Args: current_pos: The now position. Returns: The next position.
[ "Move", "in", "the", "feature", "map", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/annealingmodel/simulated_annealing.py#L105-L124
train
203,148
chimera0/accel-brain-code
Automatic-Summarization/pysummarization/nlpbase/auto_abstractor.py
AutoAbstractor.summarize
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
python
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
[ "def", "summarize", "(", "self", ",", "document", ",", "Abstractor", ",", "similarity_filter", "=", "None", ")", ":", "if", "isinstance", "(", "document", ",", "str", ")", "is", "False", ":", "raise", "TypeError", "(", "\"The type of document must be str.\"", ...
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.
[ "Execute", "summarization", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Automatic-Summarization/pysummarization/nlpbase/auto_abstractor.py#L62-L103
train
203,149
chimera0/accel-brain-code
Automatic-Summarization/pysummarization/nlpbase/auto_abstractor.py
AutoAbstractor.__closely_associated_score
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
python
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
[ "def", "__closely_associated_score", "(", "self", ",", "normalized_sentences", ",", "top_n_words", ")", ":", "scores_list", "=", "[", "]", "sentence_idx", "=", "-", "1", "for", "sentence", "in", "normalized_sentences", ":", "self", ".", "tokenize", "(", "sentenc...
Scoring the sentence with closely associations. Args: normalized_sentences: The list of sentences. top_n_words: Important sentences. Returns: The list of scores.
[ "Scoring", "the", "sentence", "with", "closely", "associations", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Automatic-Summarization/pysummarization/nlpbase/auto_abstractor.py#L105-L161
train
203,150
chimera0/accel-brain-code
Reinforcement-Learning/pyqlearning/misc/multiagentqlearning/completed_multi_agent.py
CompletedMultiAgent.learn
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
python
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
[ "def", "learn", "(", "self", ",", "initial_state_key", ",", "limit", "=", "1000", ",", "game_n", "=", "1", ")", ":", "end_flag", "=", "False", "state_key_list", "=", "[", "None", "]", "*", "len", "(", "self", ".", "q_learning_list", ")", "action_key_list...
Multi-Agent Learning. Override. Args: initial_state_key: Initial state. limit: Limit of the number of learning. game_n: The number of games.
[ "Multi", "-", "Agent", "Learning", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/misc/multiagentqlearning/completed_multi_agent.py#L13-L88
train
203,151
chimera0/accel-brain-code
Reinforcement-Learning/pyqlearning/functionapproximator/cnn_fa.py
CNNFA.get_model
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)
python
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)
[ "def", "get_model", "(", "self", ")", ":", "class", "Model", "(", "object", ")", ":", "def", "__init__", "(", "self", ",", "cnn", ")", ":", "self", ".", "cnn", "=", "cnn", "return", "Model", "(", "self", ".", "__cnn", ")" ]
`object` of model as a function approximator, which has `cnn` whose type is `pydbm.cnn.pydbm.cnn.convolutional_neural_network.ConvolutionalNeuralNetwork`.
[ "object", "of", "model", "as", "a", "function", "approximator", "which", "has", "cnn", "whose", "type", "is", "pydbm", ".", "cnn", ".", "pydbm", ".", "cnn", ".", "convolutional_neural_network", ".", "ConvolutionalNeuralNetwork", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/functionapproximator/cnn_fa.py#L174-L184
train
203,152
chimera0/accel-brain-code
Reinforcement-Learning/demo/demo_maze_deep_q_network.py
MazeDeepQNetwork.update_state
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()
python
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()
[ "def", "update_state", "(", "self", ",", "state_arr", ",", "action_arr", ")", ":", "x", ",", "y", "=", "np", ".", "where", "(", "action_arr", "[", "-", "1", "]", "==", "1", ")", "self", ".", "__agent_pos", "=", "(", "x", "[", "0", "]", ",", "y"...
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`.
[ "Update", "state", ".", "Override", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/demo/demo_maze_deep_q_network.py#L207-L228
train
203,153
chimera0/accel-brain-code
Reinforcement-Learning/demo/demo_maze_greedy_q_learning.py
MazeGreedyQLearning.initialize
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))
python
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))
[ "def", "initialize", "(", "self", ",", "map_arr", ",", "start_point_label", "=", "\"S\"", ",", "end_point_label", "=", "\"G\"", ",", "wall_label", "=", "\"#\"", ",", "agent_label", "=", "\"@\"", ")", ":", "np", ".", "set_printoptions", "(", "threshold", "=",...
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.
[ "Initialize", "map", "of", "maze", "and", "setup", "reward", "value", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/demo/demo_maze_greedy_q_learning.py#L36-L69
train
203,154
chimera0/accel-brain-code
Reinforcement-Learning/demo/demo_maze_greedy_q_learning.py
MazeGreedyQLearning.visualize_learning_result
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 !!")
python
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 !!")
[ "def", "visualize_learning_result", "(", "self", ",", "state_key", ")", ":", "x", ",", "y", "=", "state_key", "map_arr", "=", "copy", ".", "deepcopy", "(", "self", ".", "__map_arr", ")", "goal_point_tuple", "=", "np", ".", "where", "(", "map_arr", "==", ...
Visualize learning result.
[ "Visualize", "learning", "result", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/demo/demo_maze_greedy_q_learning.py#L115-L132
train
203,155
chimera0/accel-brain-code
Reinforcement-Learning/demo/demo_maze_greedy_q_learning.py
MazeGreedyQLearning.normalize_r_value
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()
python
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()
[ "def", "normalize_r_value", "(", "self", ")", ":", "if", "self", ".", "r_df", "is", "not", "None", "and", "self", ".", "r_df", ".", "shape", "[", "0", "]", ":", "# z-score normalization.", "self", ".", "r_df", ".", "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()
[ "Normalize", "r", "-", "value", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/demo/demo_maze_greedy_q_learning.py#L170-L183
train
203,156
chimera0/accel-brain-code
Reinforcement-Learning/pyqlearning/deep_q_learning.py
DeepQLearning.get_alpha_value
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
python
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
[ "def", "get_alpha_value", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "__alpha_value", ",", "float", ")", "is", "False", ":", "raise", "TypeError", "(", "\"The type of __alpha_value must be float.\"", ")", "return", "self", ".", "__alpha_value" ]
getter Learning rate.
[ "getter", "Learning", "rate", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/deep_q_learning.py#L237-L244
train
203,157
chimera0/accel-brain-code
Reinforcement-Learning/pyqlearning/deep_q_learning.py
DeepQLearning.set_alpha_value
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
python
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
[ "def", "set_alpha_value", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "float", ")", "is", "False", ":", "raise", "TypeError", "(", "\"The type of __alpha_value must be float.\"", ")", "self", ".", "__alpha_value", "=", "value" ]
setter Learning rate.
[ "setter", "Learning", "rate", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/deep_q_learning.py#L246-L253
train
203,158
chimera0/accel-brain-code
Reinforcement-Learning/pyqlearning/deep_q_learning.py
DeepQLearning.get_gamma_value
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
python
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
[ "def", "get_gamma_value", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "__gamma_value", ",", "float", ")", "is", "False", ":", "raise", "TypeError", "(", "\"The type of __gamma_value must be float.\"", ")", "return", "self", ".", "__gamma_value" ]
getter Gamma value.
[ "getter", "Gamma", "value", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/deep_q_learning.py#L257-L264
train
203,159
chimera0/accel-brain-code
Reinforcement-Learning/pyqlearning/deep_q_learning.py
DeepQLearning.set_gamma_value
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
python
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
[ "def", "set_gamma_value", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "float", ")", "is", "False", ":", "raise", "TypeError", "(", "\"The type of __gamma_value must be float.\"", ")", "self", ".", "__gamma_value", "=", "value" ]
setter Gamma value.
[ "setter", "Gamma", "value", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/deep_q_learning.py#L266-L273
train
203,160
chimera0/accel-brain-code
Automatic-Summarization/pysummarization/abstractabledoc/top_n_rank_abstractor.py
TopNRankAbstractor.filter
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
python
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
[ "def", "filter", "(", "self", ",", "scored_list", ")", ":", "top_n_key", "=", "-", "1", "*", "self", ".", "top_n", "top_n_list", "=", "sorted", "(", "scored_list", ",", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ")", "[", "top_n_key", ":",...
Filtering with top-n ranking. Args: scored_list: The list of scoring. Retruns: The list of filtered result.
[ "Filtering", "with", "top", "-", "n", "ranking", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Automatic-Summarization/pysummarization/abstractabledoc/top_n_rank_abstractor.py#L27-L41
train
203,161
chimera0/accel-brain-code
Automatic-Summarization/pysummarization/nlpbase/autoabstractor/n_gram_auto_abstractor.py
NgramAutoAbstractor.tokenize
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]
python
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]
[ "def", "tokenize", "(", "self", ",", "data", ")", ":", "super", "(", ")", ".", "tokenize", "(", "data", ")", "token_tuple_zip", "=", "self", ".", "n_gram", ".", "generate_tuple_zip", "(", "self", ".", "token", ",", "self", ".", "n", ")", "token_list", ...
Tokenize sentence. Args: [n-gram, n-gram, n-gram, ...]
[ "Tokenize", "sentence", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Automatic-Summarization/pysummarization/nlpbase/autoabstractor/n_gram_auto_abstractor.py#L50-L61
train
203,162
chimera0/accel-brain-code
Reinforcement-Learning/pyqlearning/q_learning.py
QLearning.extract_q_df
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
python
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
[ "def", "extract_q_df", "(", "self", ",", "state_key", ",", "action_key", ")", ":", "q", "=", "0.0", "if", "self", ".", "q_df", "is", "None", ":", "self", ".", "save_q_df", "(", "state_key", ",", "action_key", ",", "q", ")", "return", "q", "q_df", "="...
Extract Q-Value from `self.q_df`. Args: state_key: The key of state. action_key: The key of action. Returns: Q-Value.
[ "Extract", "Q", "-", "Value", "from", "self", ".", "q_df", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/q_learning.py#L111-L135
train
203,163
chimera0/accel-brain-code
Reinforcement-Learning/pyqlearning/q_learning.py
QLearning.save_q_df
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
python
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
[ "def", "save_q_df", "(", "self", ",", "state_key", ",", "action_key", ",", "q_value", ")", ":", "if", "isinstance", "(", "q_value", ",", "float", ")", "is", "False", ":", "raise", "TypeError", "(", "\"The type of q_value must be float.\"", ")", "new_q_df", "="...
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.
[ "Insert", "or", "update", "Q", "-", "Value", "in", "self", ".", "q_df", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/q_learning.py#L137-L158
train
203,164
chimera0/accel-brain-code
Reinforcement-Learning/pyqlearning/q_learning.py
QLearning.get_t
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
python
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
[ "def", "get_t", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "__t", ",", "int", ")", "is", "False", ":", "raise", "TypeError", "(", "\"The type of __t must be int.\"", ")", "return", "self", ".", "__t" ]
getter Time.
[ "getter", "Time", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/q_learning.py#L235-L242
train
203,165
chimera0/accel-brain-code
Reinforcement-Learning/pyqlearning/q_learning.py
QLearning.set_t
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
python
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
[ "def", "set_t", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "int", ")", "is", "False", ":", "raise", "TypeError", "(", "\"The type of __t must be int.\"", ")", "self", ".", "__t", "=", "value" ]
setter Time.
[ "setter", "Time", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/q_learning.py#L244-L251
train
203,166
chimera0/accel-brain-code
Reinforcement-Learning/pyqlearning/q_learning.py
QLearning.update_q
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)
python
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)
[ "def", "update_q", "(", "self", ",", "state_key", ",", "action_key", ",", "reward_value", ",", "next_max_q", ")", ":", "# Now Q-Value.", "q", "=", "self", ".", "extract_q_df", "(", "state_key", ",", "action_key", ")", "# Update Q-Value.", "new_q", "=", "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.
[ "Update", "Q", "-", "Value", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/q_learning.py#L355-L371
train
203,167
chimera0/accel-brain-code
Reinforcement-Learning/pyqlearning/q_learning.py
QLearning.predict_next_action
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)
python
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)
[ "def", "predict_next_action", "(", "self", ",", "state_key", ",", "next_action_list", ")", ":", "if", "self", ".", "q_df", "is", "not", "None", ":", "next_action_q_df", "=", "self", ".", "q_df", "[", "self", ".", "q_df", ".", "state_key", "==", "state_key"...
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.
[ "Predict", "next", "action", "by", "Q", "-", "Learning", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/q_learning.py#L373-L398
train
203,168
chimera0/accel-brain-code
Reinforcement-Learning/pyqlearning/misc/thompson_sampling.py
ThompsonSampling.pull
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)
python
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)
[ "def", "pull", "(", "self", ",", "arm_id", ",", "success", ",", "failure", ")", ":", "self", ".", "__beta_dist_dict", "[", "arm_id", "]", ".", "observe", "(", "success", ",", "failure", ")" ]
Pull arms. Args: arm_id: Arms master id. success: The number of success. failure: The number of failure.
[ "Pull", "arms", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/misc/thompson_sampling.py#L23-L32
train
203,169
chimera0/accel-brain-code
Reinforcement-Learning/pyqlearning/misc/thompson_sampling.py
ThompsonSampling.recommend
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]
python
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]
[ "def", "recommend", "(", "self", ",", "limit", "=", "10", ")", ":", "expected_list", "=", "[", "(", "arm_id", ",", "beta_dist", ".", "expected_value", "(", ")", ")", "for", "arm_id", ",", "beta_dist", "in", "self", ".", "__beta_dist_dict", ".", "items", ...
Listup arms and expected value. Args: limit: Length of the list. Returns: [Tuple(`Arms master id`, `expected value`)]
[ "Listup", "arms", "and", "expected", "value", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/misc/thompson_sampling.py#L34-L46
train
203,170
chimera0/accel-brain-code
Reinforcement-Learning/pyqlearning/qlearning/boltzmann_q_learning.py
BoltzmannQLearning.get_time_rate
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
python
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
[ "def", "get_time_rate", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "__time_rate", ",", "float", ")", "is", "False", ":", "raise", "TypeError", "(", "\"The type of __time_rate must be float.\"", ")", "if", "self", ".", "__time_rate", "<=", "0....
getter Time rate.
[ "getter", "Time", "rate", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/qlearning/boltzmann_q_learning.py#L30-L41
train
203,171
chimera0/accel-brain-code
Reinforcement-Learning/pyqlearning/qlearning/boltzmann_q_learning.py
BoltzmannQLearning.set_time_rate
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
python
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
[ "def", "set_time_rate", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "float", ")", "is", "False", ":", "raise", "TypeError", "(", "\"The type of __time_rate must be float.\"", ")", "if", "value", "<=", "0.0", ":", "raise", "Val...
setter Time rate.
[ "setter", "Time", "rate", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/qlearning/boltzmann_q_learning.py#L43-L54
train
203,172
chimera0/accel-brain-code
Reinforcement-Learning/pyqlearning/qlearning/boltzmann_q_learning.py
BoltzmannQLearning.__calculate_sigmoid
def __calculate_sigmoid(self): ''' Function of temperature. Returns: Sigmoid. ''' sigmoid = 1 / np.log(self.t * self.time_rate + 1.1) return sigmoid
python
def __calculate_sigmoid(self): ''' Function of temperature. Returns: Sigmoid. ''' sigmoid = 1 / np.log(self.t * self.time_rate + 1.1) return sigmoid
[ "def", "__calculate_sigmoid", "(", "self", ")", ":", "sigmoid", "=", "1", "/", "np", ".", "log", "(", "self", ".", "t", "*", "self", ".", "time_rate", "+", "1.1", ")", "return", "sigmoid" ]
Function of temperature. Returns: Sigmoid.
[ "Function", "of", "temperature", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/qlearning/boltzmann_q_learning.py#L93-L102
train
203,173
chimera0/accel-brain-code
Reinforcement-Learning/pyqlearning/qlearning/boltzmann_q_learning.py
BoltzmannQLearning.__calculate_boltzmann_factor
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
python
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
[ "def", "__calculate_boltzmann_factor", "(", "self", ",", "state_key", ",", "next_action_list", ")", ":", "sigmoid", "=", "self", ".", "__calculate_sigmoid", "(", ")", "q_df", "=", "self", ".", "q_df", "[", "self", ".", "q_df", ".", "state_key", "==", "state_...
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`)]
[ "Calculate", "boltzmann", "factor", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/qlearning/boltzmann_q_learning.py#L104-L123
train
203,174
chimera0/accel-brain-code
Reinforcement-Learning/pyqlearning/functionapproximator/lstm_fa.py
LSTMFA.get_model
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)
python
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)
[ "def", "get_model", "(", "self", ")", ":", "class", "Model", "(", "object", ")", ":", "def", "__init__", "(", "self", ",", "lstm_model", ")", ":", "self", ".", "lstm_model", "=", "lstm_model", "return", "Model", "(", "self", ".", "__lstm_model", ")" ]
`object` of model as a function approximator, which has `lstm_model` whose type is `pydbm.rnn.lstm_model.LSTMModel`.
[ "object", "of", "model", "as", "a", "function", "approximator", "which", "has", "lstm_model", "whose", "type", "is", "pydbm", ".", "rnn", ".", "lstm_model", ".", "LSTMModel", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/functionapproximator/lstm_fa.py#L181-L189
train
203,175
chimera0/accel-brain-code
Automatic-Summarization/pysummarization/abstractabledoc/std_abstractor.py
StdAbstractor.filter
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
python
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
[ "def", "filter", "(", "self", ",", "scored_list", ")", ":", "if", "len", "(", "scored_list", ")", ">", "0", ":", "avg", "=", "np", ".", "mean", "(", "[", "s", "[", "1", "]", "for", "s", "in", "scored_list", "]", ")", "std", "=", "np", ".", "s...
Filtering with std. Args: scored_list: The list of scoring. Retruns: The list of filtered result.
[ "Filtering", "with", "std", "." ]
03661f6f544bed656269fcd4b3c23c9061629daa
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Automatic-Summarization/pysummarization/abstractabledoc/std_abstractor.py#L11-L30
train
203,176
censys/censys-python
censys/base.py
CensysIndex.search
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
python
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
[ "def", "search", "(", "self", ",", "query", ",", "fields", "=", "None", ",", "page", "=", "1", ",", "max_records", "=", "None", ",", "flatten", "=", "True", ")", ":", "if", "fields", "is", "None", ":", "fields", "=", "[", "]", "page", "=", "int",...
returns iterator over all records that match the given query
[ "returns", "iterator", "over", "all", "records", "that", "match", "the", "given", "query" ]
8825fb868719331fb62b821fe1ea8687509877d2
https://github.com/censys/censys-python/blob/8825fb868719331fb62b821fe1ea8687509877d2/censys/base.py#L157-L181
train
203,177
bfontaine/term2048
term2048/game.py
Game.adjustColors
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)
python
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)
[ "def", "adjustColors", "(", "self", ",", "mode", "=", "'dark'", ")", ":", "rp", "=", "Game", ".", "__color_modes", ".", "get", "(", "mode", ",", "{", "}", ")", "for", "k", ",", "color", "in", "self", ".", "__colors", ".", "items", "(", ")", ":", ...
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.
[ "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",...
8b5ce8b65f44f20a7ad36022a34dce56184070af
https://github.com/bfontaine/term2048/blob/8b5ce8b65f44f20a7ad36022a34dce56184070af/term2048/game.py#L97-L106
train
203,178
bfontaine/term2048
term2048/game.py
Game.loadBestScore
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
python
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
[ "def", "loadBestScore", "(", "self", ")", ":", "try", ":", "with", "open", "(", "self", ".", "scores_file", ",", "'r'", ")", "as", "f", ":", "self", ".", "best_score", "=", "int", "(", "f", ".", "readline", "(", ")", ",", "10", ")", "except", ":"...
load local best score from the default file
[ "load", "local", "best", "score", "from", "the", "default", "file" ]
8b5ce8b65f44f20a7ad36022a34dce56184070af
https://github.com/bfontaine/term2048/blob/8b5ce8b65f44f20a7ad36022a34dce56184070af/term2048/game.py#L108-L117
train
203,179
bfontaine/term2048
term2048/game.py
Game.saveBestScore
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
python
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
[ "def", "saveBestScore", "(", "self", ")", ":", "if", "self", ".", "score", ">", "self", ".", "best_score", ":", "self", ".", "best_score", "=", "self", ".", "score", "try", ":", "with", "open", "(", "self", ".", "scores_file", ",", "'w'", ")", "as", ...
save current best score in the default file
[ "save", "current", "best", "score", "in", "the", "default", "file" ]
8b5ce8b65f44f20a7ad36022a34dce56184070af
https://github.com/bfontaine/term2048/blob/8b5ce8b65f44f20a7ad36022a34dce56184070af/term2048/game.py#L119-L130
train
203,180
bfontaine/term2048
term2048/game.py
Game.incScore
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
python
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
[ "def", "incScore", "(", "self", ",", "pts", ")", ":", "self", ".", "score", "+=", "pts", "if", "self", ".", "score", ">", "self", ".", "best_score", ":", "self", ".", "best_score", "=", "self", ".", "score" ]
update the current score by adding it the specified number of points
[ "update", "the", "current", "score", "by", "adding", "it", "the", "specified", "number", "of", "points" ]
8b5ce8b65f44f20a7ad36022a34dce56184070af
https://github.com/bfontaine/term2048/blob/8b5ce8b65f44f20a7ad36022a34dce56184070af/term2048/game.py#L132-L138
train
203,181
bfontaine/term2048
term2048/game.py
Game.store
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
python
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
[ "def", "store", "(", "self", ")", ":", "size", "=", "self", ".", "board", ".", "SIZE", "cells", "=", "[", "]", "for", "i", "in", "range", "(", "size", ")", ":", "for", "j", "in", "range", "(", "size", ")", ":", "cells", ".", "append", "(", "s...
save the current game session's score and data for further use
[ "save", "the", "current", "game", "session", "s", "score", "and", "data", "for", "further", "use" ]
8b5ce8b65f44f20a7ad36022a34dce56184070af
https://github.com/bfontaine/term2048/blob/8b5ce8b65f44f20a7ad36022a34dce56184070af/term2048/game.py#L147-L165
train
203,182
bfontaine/term2048
term2048/game.py
Game.restore
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
python
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
[ "def", "restore", "(", "self", ")", ":", "size", "=", "self", ".", "board", ".", "SIZE", "try", ":", "with", "open", "(", "self", ".", "store_file", ",", "'r'", ")", "as", "f", ":", "lines", "=", "f", ".", "readlines", "(", ")", "score_str", "=",...
restore the saved game score and data
[ "restore", "the", "saved", "game", "score", "and", "data" ]
8b5ce8b65f44f20a7ad36022a34dce56184070af
https://github.com/bfontaine/term2048/blob/8b5ce8b65f44f20a7ad36022a34dce56184070af/term2048/game.py#L167-L191
train
203,183
bfontaine/term2048
term2048/game.py
Game.loop
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
python
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
[ "def", "loop", "(", "self", ")", ":", "pause_key", "=", "self", ".", "board", ".", "PAUSE", "margins", "=", "{", "'left'", ":", "4", ",", "'top'", ":", "4", ",", "'bottom'", ":", "4", "}", "atexit", ".", "register", "(", "self", ".", "showCursor", ...
main game loop. returns the final score.
[ "main", "game", "loop", ".", "returns", "the", "final", "score", "." ]
8b5ce8b65f44f20a7ad36022a34dce56184070af
https://github.com/bfontaine/term2048/blob/8b5ce8b65f44f20a7ad36022a34dce56184070af/term2048/game.py#L216-L252
train
203,184
bfontaine/term2048
term2048/game.py
Game.getCellStr
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
python
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
[ "def", "getCellStr", "(", "self", ",", "x", ",", "y", ")", ":", "# TODO: refactor regarding issue #11", "c", "=", "self", ".", "board", ".", "getCell", "(", "x", ",", "y", ")", "if", "c", "==", "0", ":", "return", "'.'", "if", "self", ".", "__azmode"...
return a string representation of the cell located at x,y.
[ "return", "a", "string", "representation", "of", "the", "cell", "located", "at", "x", "y", "." ]
8b5ce8b65f44f20a7ad36022a34dce56184070af
https://github.com/bfontaine/term2048/blob/8b5ce8b65f44f20a7ad36022a34dce56184070af/term2048/game.py#L254-L278
train
203,185
bfontaine/term2048
term2048/game.py
Game.boardToString
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
python
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
[ "def", "boardToString", "(", "self", ",", "margins", "=", "None", ")", ":", "if", "margins", "is", "None", ":", "margins", "=", "{", "}", "b", "=", "self", ".", "board", "rg", "=", "range", "(", "b", ".", "size", "(", ")", ")", "left", "=", "' ...
return a string representation of the current board.
[ "return", "a", "string", "representation", "of", "the", "current", "board", "." ]
8b5ce8b65f44f20a7ad36022a34dce56184070af
https://github.com/bfontaine/term2048/blob/8b5ce8b65f44f20a7ad36022a34dce56184070af/term2048/game.py#L280-L292
train
203,186
bfontaine/term2048
term2048/board.py
Board.canMove
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
python
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
[ "def", "canMove", "(", "self", ")", ":", "if", "not", "self", ".", "filled", "(", ")", ":", "return", "True", "for", "y", "in", "self", ".", "__size_range", ":", "for", "x", "in", "self", ".", "__size_range", ":", "c", "=", "self", ".", "getCell", ...
test if a move is possible
[ "test", "if", "a", "move", "is", "possible" ]
8b5ce8b65f44f20a7ad36022a34dce56184070af
https://github.com/bfontaine/term2048/blob/8b5ce8b65f44f20a7ad36022a34dce56184070af/term2048/board.py#L49-L63
train
203,187
bfontaine/term2048
term2048/board.py
Board.setCell
def setCell(self, x, y, v): """set the cell value at x,y""" self.cells[y][x] = v
python
def setCell(self, x, y, v): """set the cell value at x,y""" self.cells[y][x] = v
[ "def", "setCell", "(", "self", ",", "x", ",", "y", ",", "v", ")", ":", "self", ".", "cells", "[", "y", "]", "[", "x", "]", "=", "v" ]
set the cell value at x,y
[ "set", "the", "cell", "value", "at", "x", "y" ]
8b5ce8b65f44f20a7ad36022a34dce56184070af
https://github.com/bfontaine/term2048/blob/8b5ce8b65f44f20a7ad36022a34dce56184070af/term2048/board.py#L95-L97
train
203,188
bfontaine/term2048
term2048/board.py
Board.getCol
def getCol(self, x): """return the x-th column, starting at 0""" return [self.getCell(x, i) for i in self.__size_range]
python
def getCol(self, x): """return the x-th column, starting at 0""" return [self.getCell(x, i) for i in self.__size_range]
[ "def", "getCol", "(", "self", ",", "x", ")", ":", "return", "[", "self", ".", "getCell", "(", "x", ",", "i", ")", "for", "i", "in", "self", ".", "__size_range", "]" ]
return the x-th column, starting at 0
[ "return", "the", "x", "-", "th", "column", "starting", "at", "0" ]
8b5ce8b65f44f20a7ad36022a34dce56184070af
https://github.com/bfontaine/term2048/blob/8b5ce8b65f44f20a7ad36022a34dce56184070af/term2048/board.py#L103-L105
train
203,189
bfontaine/term2048
term2048/board.py
Board.setCol
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])
python
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])
[ "def", "setCol", "(", "self", ",", "x", ",", "l", ")", ":", "for", "i", "in", "xrange", "(", "0", ",", "self", ".", "__size", ")", ":", "self", ".", "setCell", "(", "x", ",", "i", ",", "l", "[", "i", "]", ")" ]
set the x-th column, starting at 0
[ "set", "the", "x", "-", "th", "column", "starting", "at", "0" ]
8b5ce8b65f44f20a7ad36022a34dce56184070af
https://github.com/bfontaine/term2048/blob/8b5ce8b65f44f20a7ad36022a34dce56184070af/term2048/board.py#L111-L114
train
203,190
bfontaine/term2048
term2048/board.py
Board.__collapseLineOrCol
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)
python
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)
[ "def", "__collapseLineOrCol", "(", "self", ",", "line", ",", "d", ")", ":", "if", "(", "d", "==", "Board", ".", "LEFT", "or", "d", "==", "Board", ".", "UP", ")", ":", "inc", "=", "1", "rg", "=", "xrange", "(", "0", ",", "self", ".", "__size", ...
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
[ "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" ]
8b5ce8b65f44f20a7ad36022a34dce56184070af
https://github.com/bfontaine/term2048/blob/8b5ce8b65f44f20a7ad36022a34dce56184070af/term2048/board.py#L122-L147
train
203,191
bfontaine/term2048
term2048/board.py
Board.move
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
python
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
[ "def", "move", "(", "self", ",", "d", ",", "add_tile", "=", "True", ")", ":", "if", "d", "==", "Board", ".", "LEFT", "or", "d", "==", "Board", ".", "RIGHT", ":", "chg", ",", "get", "=", "self", ".", "setLine", ",", "self", ".", "getLine", "elif...
move and return the move score
[ "move", "and", "return", "the", "move", "score" ]
8b5ce8b65f44f20a7ad36022a34dce56184070af
https://github.com/bfontaine/term2048/blob/8b5ce8b65f44f20a7ad36022a34dce56184070af/term2048/board.py#L158-L193
train
203,192
bfontaine/term2048
term2048/ui.py
parse_cli_args
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())
python
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())
[ "def", "parse_cli_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'2048 in your terminal'", ")", "parser", ".", "add_argument", "(", "'--mode'", ",", "dest", "=", "'mode'", ",", "type", "=", "str", ",", "defa...
parse args from the CLI and return a dict
[ "parse", "args", "from", "the", "CLI", "and", "return", "a", "dict" ]
8b5ce8b65f44f20a7ad36022a34dce56184070af
https://github.com/bfontaine/term2048/blob/8b5ce8b65f44f20a7ad36022a34dce56184070af/term2048/ui.py#L30-L41
train
203,193
bfontaine/term2048
term2048/ui.py
start_game
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()
python
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()
[ "def", "start_game", "(", "debug", "=", "False", ")", ":", "args", "=", "parse_cli_args", "(", ")", "if", "args", "[", "'version'", "]", ":", "print_version_and_exit", "(", ")", "if", "args", "[", "'rules'", "]", ":", "print_rules_and_exit", "(", ")", "g...
Start a new game. If ``debug`` is set to ``True``, the game object is returned and the game loop isn't fired.
[ "Start", "a", "new", "game", ".", "If", "debug", "is", "set", "to", "True", "the", "game", "object", "is", "returned", "and", "the", "game", "loop", "isn", "t", "fired", "." ]
8b5ce8b65f44f20a7ad36022a34dce56184070af
https://github.com/bfontaine/term2048/blob/8b5ce8b65f44f20a7ad36022a34dce56184070af/term2048/ui.py#L44-L64
train
203,194
lepture/python-livereload
livereload/handlers.py
LiveReloadHandler.on_message
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)
python
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)
[ "def", "on_message", "(", "self", ",", "message", ")", ":", "message", "=", "ObjectDict", "(", "escape", ".", "json_decode", "(", "message", ")", ")", "if", "message", ".", "command", "==", "'hello'", ":", "handshake", "=", "{", "'command'", ":", "'hello...
Handshake with livereload.js 1. client send 'hello' 2. server reply 'hello' 3. client send 'info'
[ "Handshake", "with", "livereload", ".", "js" ]
f80cb3ae0f8f2cdf38203a712fe25ef7f1899c34
https://github.com/lepture/python-livereload/blob/f80cb3ae0f8f2cdf38203a712fe25ef7f1899c34/livereload/handlers.py#L116-L136
train
203,195
lepture/python-livereload
livereload/handlers.py
MtimeStaticFileHandler.get_content_modified_time
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
python
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
[ "def", "get_content_modified_time", "(", "cls", ",", "abspath", ")", ":", "stat_result", "=", "os", ".", "stat", "(", "abspath", ")", "modified", "=", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "stat_result", "[", "stat", ".", "ST_MTIME", "]"...
Returns the time that ``abspath`` was last modified. May be overridden in subclasses. Should return a `~datetime.datetime` object or None.
[ "Returns", "the", "time", "that", "abspath", "was", "last", "modified", "." ]
f80cb3ae0f8f2cdf38203a712fe25ef7f1899c34
https://github.com/lepture/python-livereload/blob/f80cb3ae0f8f2cdf38203a712fe25ef7f1899c34/livereload/handlers.py#L143-L152
train
203,196
lepture/python-livereload
livereload/watcher.py
Watcher.ignore
def ignore(self, filename): """Ignore a given filename or not.""" _, ext = os.path.splitext(filename) return ext in ['.pyc', '.pyo', '.o', '.swp']
python
def ignore(self, filename): """Ignore a given filename or not.""" _, ext = os.path.splitext(filename) return ext in ['.pyc', '.pyo', '.o', '.swp']
[ "def", "ignore", "(", "self", ",", "filename", ")", ":", "_", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "return", "ext", "in", "[", "'.pyc'", ",", "'.pyo'", ",", "'.o'", ",", "'.swp'", "]" ]
Ignore a given filename or not.
[ "Ignore", "a", "given", "filename", "or", "not", "." ]
f80cb3ae0f8f2cdf38203a712fe25ef7f1899c34
https://github.com/lepture/python-livereload/blob/f80cb3ae0f8f2cdf38203a712fe25ef7f1899c34/livereload/watcher.py#L48-L51
train
203,197
lepture/python-livereload
livereload/watcher.py
Watcher.watch
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, }
python
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, }
[ "def", "watch", "(", "self", ",", "path", ",", "func", "=", "None", ",", "delay", "=", "0", ",", "ignore", "=", "None", ")", ":", "self", ".", "_tasks", "[", "path", "]", "=", "{", "'func'", ":", "func", ",", "'delay'", ":", "delay", ",", "'ign...
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.
[ "Add", "a", "task", "to", "watcher", "." ]
f80cb3ae0f8f2cdf38203a712fe25ef7f1899c34
https://github.com/lepture/python-livereload/blob/f80cb3ae0f8f2cdf38203a712fe25ef7f1899c34/livereload/watcher.py#L53-L68
train
203,198
kovacsbalu/WazeRouteCalculator
WazeRouteCalculator/WazeRouteCalculator.py
WazeRouteCalculator.already_coords
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)
python
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)
[ "def", "already_coords", "(", "self", ",", "address", ")", ":", "m", "=", "re", ".", "search", "(", "self", ".", "COORD_MATCH", ",", "address", ")", "return", "(", "m", "!=", "None", ")" ]
test used to see if we have coordinates or address
[ "test", "used", "to", "see", "if", "we", "have", "coordinates", "or", "address" ]
13ddb064571bb2bc0ceec51b5b317640b2bc3fb2
https://github.com/kovacsbalu/WazeRouteCalculator/blob/13ddb064571bb2bc0ceec51b5b317640b2bc3fb2/WazeRouteCalculator/WazeRouteCalculator.py#L76-L80
train
203,199