anchor
stringlengths
16
95
positive
stringlengths
87
6.25k
negative
stringlengths
87
6.4k
python get boolean input from user
def boolean(value): """ Configuration-friendly boolean type converter. Supports both boolean-valued and string-valued inputs (e.g. from env vars). """ if isinstance(value, bool): return value if value == "": return False return strtobool(value)
def arg_bool(name, default=False): """ Fetch a query argument, as a boolean. """ v = request.args.get(name, '') if not len(v): return default return v in BOOL_TRUISH
python get boolean input from user
def boolean(value): """ Configuration-friendly boolean type converter. Supports both boolean-valued and string-valued inputs (e.g. from env vars). """ if isinstance(value, bool): return value if value == "": return False return strtobool(value)
def process_bool_arg(arg): """ Determine True/False from argument """ if isinstance(arg, bool): return arg elif isinstance(arg, basestring): if arg.lower() in ["true", "1"]: return True elif arg.lower() in ["false", "0"]: return False
python get boolean input from user
def boolean(value): """ Configuration-friendly boolean type converter. Supports both boolean-valued and string-valued inputs (e.g. from env vars). """ if isinstance(value, bool): return value if value == "": return False return strtobool(value)
def _cast_boolean(value): """ Helper to convert config values to boolean as ConfigParser do. """ _BOOLEANS = {'1': True, 'yes': True, 'true': True, 'on': True, '0': False, 'no': False, 'false': False, 'off': False, '': False} value = str(value) if value.lower() not in _BOOLEANS:...
python get boolean input from user
def boolean(value): """ Configuration-friendly boolean type converter. Supports both boolean-valued and string-valued inputs (e.g. from env vars). """ if isinstance(value, bool): return value if value == "": return False return strtobool(value)
def str2bool(value): """Parse Yes/No/Default string https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse""" if value.lower() in ('yes', 'true', 't', 'y', '1'): return True if value.lower() in ('no', 'false', 'f', 'n', '0'): return False if value.lower() i...
python get boolean input from user
def boolean(value): """ Configuration-friendly boolean type converter. Supports both boolean-valued and string-valued inputs (e.g. from env vars). """ if isinstance(value, bool): return value if value == "": return False return strtobool(value)
def to_bool(value): # type: (Any) -> bool """ Convert a value into a bool but handle "truthy" strings eg, yes, true, ok, y """ if isinstance(value, _compat.string_types): return value.upper() in ('Y', 'YES', 'T', 'TRUE', '1', 'OK') return bool(value)
delete value from heap python
def pop(h): """Pop the heap value from the heap.""" n = h.size() - 1 h.swap(0, n) down(h, 0, n) return h.pop()
def PopTask(self): """Retrieves and removes the first task from the heap. Returns: Task: the task or None if the heap is empty. """ try: _, task = heapq.heappop(self._heap) except IndexError: return None self._task_identifiers.remove(task.identifier) return task
delete value from heap python
def pop(h): """Pop the heap value from the heap.""" n = h.size() - 1 h.swap(0, n) down(h, 0, n) return h.pop()
def Flush(self): """Flush all items from cache.""" while self._age: node = self._age.PopLeft() self.KillObject(node.data) self._hash = dict()
delete value from heap python
def pop(h): """Pop the heap value from the heap.""" n = h.size() - 1 h.swap(0, n) down(h, 0, n) return h.pop()
def _heappush_max(heap, item): """ why is this not in heapq """ heap.append(item) heapq._siftdown_max(heap, 0, len(heap) - 1)
delete value from heap python
def pop(h): """Pop the heap value from the heap.""" n = h.size() - 1 h.swap(0, n) down(h, 0, n) return h.pop()
def heappush_max(heap, item): """Push item onto heap, maintaining the heap invariant.""" heap.append(item) _siftdown_max(heap, 0, len(heap) - 1)
delete value from heap python
def pop(h): """Pop the heap value from the heap.""" n = h.size() - 1 h.swap(0, n) down(h, 0, n) return h.pop()
def trim(self): """Clear not used counters""" for key, value in list(iteritems(self.counters)): if value.empty(): del self.counters[key]
display the count of index in adjacent position python
def rank(idx, dim): """Calculate the index rank according to Bertran's notation.""" idxm = multi_index(idx, dim) out = 0 while idxm[-1:] == (0,): out += 1 idxm = idxm[:-1] return out
def _rindex(mylist: Sequence[T], x: T) -> int: """Index of the last occurrence of x in the sequence.""" return len(mylist) - mylist[::-1].index(x) - 1
display the count of index in adjacent position python
def rank(idx, dim): """Calculate the index rank according to Bertran's notation.""" idxm = multi_index(idx, dim) out = 0 while idxm[-1:] == (0,): out += 1 idxm = idxm[:-1] return out
def IndexOfNth(s, value, n): """Gets the index of Nth occurance of a given character in a string :param str s: Input string :param char value: Input char to be searched. :param int n: Nth occurrence of char to be searched. :return: Index of the Nth occurrence in the...
display the count of index in adjacent position python
def rank(idx, dim): """Calculate the index rank according to Bertran's notation.""" idxm = multi_index(idx, dim) out = 0 while idxm[-1:] == (0,): out += 1 idxm = idxm[:-1] return out
def index(self, value): """ Return the smallest index of the row(s) with this column equal to value. """ for i in xrange(len(self.parentNode)): if getattr(self.parentNode[i], self.Name) == value: return i raise ValueError(value)
display the count of index in adjacent position python
def rank(idx, dim): """Calculate the index rank according to Bertran's notation.""" idxm = multi_index(idx, dim) out = 0 while idxm[-1:] == (0,): out += 1 idxm = idxm[:-1] return out
def translate_index_to_position(self, index): """ Given an index for the text, return the corresponding (row, col) tuple. (0-based. Returns (0, 0) for index=0.) """ # Find start of this line. row, row_index = self._find_line_start_index(index) col = index - row_in...
display the count of index in adjacent position python
def rank(idx, dim): """Calculate the index rank according to Bertran's notation.""" idxm = multi_index(idx, dim) out = 0 while idxm[-1:] == (0,): out += 1 idxm = idxm[:-1] return out
def getRowCurrentIndex(self): """ Returns the index of column 0 of the current item in the underlying model. See also the notes at the top of this module on current item vs selected item(s). """ curIndex = self.currentIndex() col0Index = curIndex.sibling(curIndex.row(), 0) ...
does a tree node have parent node associated with it using python
def has_parent(self, term): """Return True if this GO object has a parent GO ID.""" for parent in self.parents: if parent.item_id == term or parent.has_parent(term): return True return False
def assign_parent(node: astroid.node_classes.NodeNG) -> astroid.node_classes.NodeNG: """return the higher parent which is not an AssignName, Tuple or List node """ while node and isinstance(node, (astroid.AssignName, astroid.Tuple, astroid.List)): node = node.parent return node
does a tree node have parent node associated with it using python
def has_parent(self, term): """Return True if this GO object has a parent GO ID.""" for parent in self.parents: if parent.item_id == term or parent.has_parent(term): return True return False
def _root(self): """Attribute referencing the root node of the tree. :returns: the root node of the tree containing this instance. :rtype: Node """ _n = self while _n.parent: _n = _n.parent return _n
does a tree node have parent node associated with it using python
def has_parent(self, term): """Return True if this GO object has a parent GO ID.""" for parent in self.parents: if parent.item_id == term or parent.has_parent(term): return True return False
def _get_node_parent(self, age, pos): """Get the parent node of node, whch is located in tree's node list. Returns: object: The parent node. """ return self.nodes[age][int(pos / self.comp)]
does a tree node have parent node associated with it using python
def has_parent(self, term): """Return True if this GO object has a parent GO ID.""" for parent in self.parents: if parent.item_id == term or parent.has_parent(term): return True return False
def get_tree_type(tree): """ returns the type of the (sub)tree: Root, Nucleus or Satellite Parameters ---------- tree : nltk.tree.ParentedTree a tree representing a rhetorical structure (or a part of it) """ tree_type = tree.label() assert tree_type in SUBTREE_TYPES, "tree_type:...
does a tree node have parent node associated with it using python
def has_parent(self, term): """Return True if this GO object has a parent GO ID.""" for parent in self.parents: if parent.item_id == term or parent.has_parent(term): return True return False
def ancestors(self, node): """Returns set of the ancestors of a node as DAGNodes.""" if isinstance(node, int): warnings.warn('Calling ancestors() with a node id is deprecated,' ' use a DAGNode instead', DeprecationWarning, 2) no...
python get object property by name
def get_property_by_name(pif, name): """Get a property by name""" return next((x for x in pif.properties if x.name == name), None)
def get_propety_by_name(pif, name): """Get a property by name""" warn("This method has been deprecated in favor of get_property_by_name") return next((x for x in pif.properties if x.name == name), None)
python get object property by name
def get_property_by_name(pif, name): """Get a property by name""" return next((x for x in pif.properties if x.name == name), None)
def get_property(self, name): # type: (str) -> object """ Retrieves a framework or system property. As framework properties don't change while it's running, this method don't need to be protected. :param name: The property name """ with self.__properties_lock: ...
python get object property by name
def get_property_by_name(pif, name): """Get a property by name""" return next((x for x in pif.properties if x.name == name), None)
def getprop(self, prop_name): """Get a property of the device. This is a convenience wrapper for "adb shell getprop xxx". Args: prop_name: A string that is the name of the property to get. Returns: A string that is the value of the property, or None if the prop...
python get object property by name
def get_property_by_name(pif, name): """Get a property by name""" return next((x for x in pif.properties if x.name == name), None)
def get_property(self, property_name): """ Get a property's value. property_name -- the property to get the value of Returns the properties value, if found, else None. """ prop = self.find_property(property_name) if prop: return prop.get_value() ...
python get object property by name
def get_property_by_name(pif, name): """Get a property by name""" return next((x for x in pif.properties if x.name == name), None)
def get_member(thing_obj, member_string): """Get a member from an object by (string) name""" mems = {x[0]: x[1] for x in inspect.getmembers(thing_obj)} if member_string in mems: return mems[member_string]
double underscore function python
def us2mc(string): """Transform an underscore_case string to a mixedCase string""" return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), string)
def underscore(text): """Converts text that may be camelcased into an underscored format""" return UNDERSCORE[1].sub(r'\1_\2', UNDERSCORE[0].sub(r'\1_\2', text)).lower()
double underscore function python
def us2mc(string): """Transform an underscore_case string to a mixedCase string""" return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), string)
def camelcase_underscore(name): """ Convert camelcase names to underscore """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
double underscore function python
def us2mc(string): """Transform an underscore_case string to a mixedCase string""" return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), string)
def case_us2mc(x): """ underscore to mixed case notation """ return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), x)
double underscore function python
def us2mc(string): """Transform an underscore_case string to a mixedCase string""" return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), string)
def camel_case_from_underscores(string): """generate a CamelCase string from an underscore_string.""" components = string.split('_') string = '' for component in components: string += component[0].upper() + component[1:] return string
double underscore function python
def us2mc(string): """Transform an underscore_case string to a mixedCase string""" return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), string)
def key_to_metric(self, key): """Replace all non-letter characters with underscores""" return ''.join(l if l in string.letters else '_' for l in key)
eigen values of gradients of images, python
def center_eigenvalue_diff(mat): """Compute the eigvals of mat and then find the center eigval difference.""" N = len(mat) evals = np.sort(la.eigvals(mat)) diff = np.abs(evals[N/2] - evals[N/2-1]) return diff
def average_gradient(data, *kwargs): """ Compute average gradient norm of an image """ return np.average(np.array(np.gradient(data))**2)
eigen values of gradients of images, python
def center_eigenvalue_diff(mat): """Compute the eigvals of mat and then find the center eigval difference.""" N = len(mat) evals = np.sort(la.eigvals(mat)) diff = np.abs(evals[N/2] - evals[N/2-1]) return diff
def compute_gradient(self): """Compute the gradient of the current model using the training set """ delta = self.predict(self.X) - self.y return delta.dot(self.X) / len(self.X)
eigen values of gradients of images, python
def center_eigenvalue_diff(mat): """Compute the eigvals of mat and then find the center eigval difference.""" N = len(mat) evals = np.sort(la.eigvals(mat)) diff = np.abs(evals[N/2] - evals[N/2-1]) return diff
def fgrad_y(self, y, return_precalc=False): """ gradient of f w.r.t to y ([N x 1]) :returns: Nx1 vector of derivatives, unless return_precalc is true, then it also returns the precomputed stuff """ d = self.d mpsi = self.psi # vectorized version ...
eigen values of gradients of images, python
def center_eigenvalue_diff(mat): """Compute the eigvals of mat and then find the center eigval difference.""" N = len(mat) evals = np.sort(la.eigvals(mat)) diff = np.abs(evals[N/2] - evals[N/2-1]) return diff
def getcoef(self): """Get final coefficient map array.""" global mp_Z_Y1 return np.swapaxes(mp_Z_Y1, 0, self.xstep.cri.axisK+1)[0]
eigen values of gradients of images, python
def center_eigenvalue_diff(mat): """Compute the eigvals of mat and then find the center eigval difference.""" N = len(mat) evals = np.sort(la.eigvals(mat)) diff = np.abs(evals[N/2] - evals[N/2-1]) return diff
def _propagate_mean(mean, linop, dist): """Propagate a mean through linear Gaussian transformation.""" return linop.matmul(mean) + dist.mean()[..., tf.newaxis]
elementtree get parent python
def _get_node_parent(self, age, pos): """Get the parent node of node, whch is located in tree's node list. Returns: object: The parent node. """ return self.nodes[age][int(pos / self.comp)]
def _root(self): """Attribute referencing the root node of the tree. :returns: the root node of the tree containing this instance. :rtype: Node """ _n = self while _n.parent: _n = _n.parent return _n
elementtree get parent python
def _get_node_parent(self, age, pos): """Get the parent node of node, whch is located in tree's node list. Returns: object: The parent node. """ return self.nodes[age][int(pos / self.comp)]
def find_root(self): """ Traverse parent refs to top. """ cmd = self while cmd.parent: cmd = cmd.parent return cmd
elementtree get parent python
def _get_node_parent(self, age, pos): """Get the parent node of node, whch is located in tree's node list. Returns: object: The parent node. """ return self.nodes[age][int(pos / self.comp)]
def assign_parent(node: astroid.node_classes.NodeNG) -> astroid.node_classes.NodeNG: """return the higher parent which is not an AssignName, Tuple or List node """ while node and isinstance(node, (astroid.AssignName, astroid.Tuple, astroid.List)): node = node.parent return node
elementtree get parent python
def _get_node_parent(self, age, pos): """Get the parent node of node, whch is located in tree's node list. Returns: object: The parent node. """ return self.nodes[age][int(pos / self.comp)]
def root_parent(self, category=None): """ Returns the topmost parent of the current category. """ return next(filter(lambda c: c.is_root, self.hierarchy()))
elementtree get parent python
def _get_node_parent(self, age, pos): """Get the parent node of node, whch is located in tree's node list. Returns: object: The parent node. """ return self.nodes[age][int(pos / self.comp)]
def _lookup_parent(self, cls): """Lookup a transitive parent object that is an instance of a given class.""" codeobj = self.parent while codeobj is not None and not isinstance(codeobj, cls): codeobj = codeobj.parent return codeobj
eliminate duplicate entries python list
def dedup_list(l): """Given a list (l) will removing duplicates from the list, preserving the original order of the list. Assumes that the list entrie are hashable.""" dedup = set() return [ x for x in l if not (x in dedup or dedup.add(x))]
def delete_duplicates(seq): """ Remove duplicates from an iterable, preserving the order. Args: seq: Iterable of various type. Returns: list: List of unique objects. """ seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))]
eliminate duplicate entries python list
def dedup_list(l): """Given a list (l) will removing duplicates from the list, preserving the original order of the list. Assumes that the list entrie are hashable.""" dedup = set() return [ x for x in l if not (x in dedup or dedup.add(x))]
def remove_list_duplicates(lista, unique=False): """ Remove duplicated elements in a list. Args: lista: List with elements to clean duplicates. """ result = [] allready = [] for elem in lista: if elem not in result: result.append(elem) else: a...
eliminate duplicate entries python list
def dedup_list(l): """Given a list (l) will removing duplicates from the list, preserving the original order of the list. Assumes that the list entrie are hashable.""" dedup = set() return [ x for x in l if not (x in dedup or dedup.add(x))]
def de_duplicate(items): """Remove any duplicate item, preserving order >>> de_duplicate([1, 2, 1, 2]) [1, 2] """ result = [] for item in items: if item not in result: result.append(item) return result
eliminate duplicate entries python list
def dedup_list(l): """Given a list (l) will removing duplicates from the list, preserving the original order of the list. Assumes that the list entrie are hashable.""" dedup = set() return [ x for x in l if not (x in dedup or dedup.add(x))]
def dedupe_list(seq): """ Utility function to remove duplicates from a list :param seq: The sequence (list) to deduplicate :return: A list with original duplicates removed """ seen = set() return [x for x in seq if not (x in seen or seen.add(x))]
eliminate duplicate entries python list
def dedup_list(l): """Given a list (l) will removing duplicates from the list, preserving the original order of the list. Assumes that the list entrie are hashable.""" dedup = set() return [ x for x in l if not (x in dedup or dedup.add(x))]
def unique(transactions): """ Remove any duplicate entries. """ seen = set() # TODO: Handle comments return [x for x in transactions if not (x in seen or seen.add(x))]
python get the char width number of shell window
def size(): """Determines the height and width of the console window Returns: tuple of int: The height in lines, then width in characters """ try: assert os != 'nt' and sys.stdout.isatty() rows, columns = os.popen('stty size', 'r').read().split() except (AssertionErr...
def get_width(): """Get terminal width""" # Get terminal size ws = struct.pack("HHHH", 0, 0, 0, 0) ws = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, ws) lines, columns, x, y = struct.unpack("HHHH", ws) width = min(columns * 39 // 40, columns - 2) return width
python get the char width number of shell window
def size(): """Determines the height and width of the console window Returns: tuple of int: The height in lines, then width in characters """ try: assert os != 'nt' and sys.stdout.isatty() rows, columns = os.popen('stty size', 'r').read().split() except (AssertionErr...
def get_terminal_width(): """ -> #int width of the terminal window """ # http://www.brandonrubin.me/2014/03/18/python-snippet-get-terminal-width/ command = ['tput', 'cols'] try: width = int(subprocess.check_output(command)) except OSError as e: print( "Invalid Command '{0...
python get the char width number of shell window
def size(): """Determines the height and width of the console window Returns: tuple of int: The height in lines, then width in characters """ try: assert os != 'nt' and sys.stdout.isatty() rows, columns = os.popen('stty size', 'r').read().split() except (AssertionErr...
def get_window_dim(): """ gets the dimensions depending on python version and os""" version = sys.version_info if version >= (3, 3): return _size_36() if platform.system() == 'Windows': return _size_windows() return _size_27()
python get the char width number of shell window
def size(): """Determines the height and width of the console window Returns: tuple of int: The height in lines, then width in characters """ try: assert os != 'nt' and sys.stdout.isatty() rows, columns = os.popen('stty size', 'r').read().split() except (AssertionErr...
def getWindowPID(self, hwnd): """ Gets the process ID that the specified window belongs to """ pid = ctypes.c_ulong() ctypes.windll.user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid)) return int(pid.value)
python get the char width number of shell window
def size(): """Determines the height and width of the console window Returns: tuple of int: The height in lines, then width in characters """ try: assert os != 'nt' and sys.stdout.isatty() rows, columns = os.popen('stty size', 'r').read().split() except (AssertionErr...
def _visual_width(line): """Get the the number of columns required to display a string""" return len(re.sub(colorama.ansitowin32.AnsiToWin32.ANSI_CSI_RE, "", line))
enum en python definicion
def write_enum(fo, datum, schema): """An enum is encoded by a int, representing the zero-based position of the symbol in the schema.""" index = schema['symbols'].index(datum) write_int(fo, index)
def unpack_out(self, name): return self.parse(""" $enum = $enum_class($value.value) """, enum_class=self._import_type(), value=name)["enum"]
enum en python definicion
def write_enum(fo, datum, schema): """An enum is encoded by a int, representing the zero-based position of the symbol in the schema.""" index = schema['symbols'].index(datum) write_int(fo, index)
def _Enum(docstring, *names): """Utility to generate enum classes used by annotations. Args: docstring: Docstring for the generated enum class. *names: Enum names. Returns: A class that contains enum names as attributes. """ enums = dict(zip(names, range(len(names)))) reverse = dict((value, ke...
enum en python definicion
def write_enum(fo, datum, schema): """An enum is encoded by a int, representing the zero-based position of the symbol in the schema.""" index = schema['symbols'].index(datum) write_int(fo, index)
def get_enum_documentation(class_name, module_name, enum_class_object): documentation = """.. _{module_name}.{class_name}: ``enum {class_name}`` +++++++{plus}++ **module:** ``{module_name}``""".format( module_name=module_name, class_name=class_name, plus='+' * len(class_name), ) i...
enum en python definicion
def write_enum(fo, datum, schema): """An enum is encoded by a int, representing the zero-based position of the symbol in the schema.""" index = schema['symbols'].index(datum) write_int(fo, index)
def add_to_enum(self, clsdict): """ Compile XML mappings in addition to base add behavior. """ super(XmlMappedEnumMember, self).add_to_enum(clsdict) self.register_xml_mapping(clsdict)
enum en python definicion
def write_enum(fo, datum, schema): """An enum is encoded by a int, representing the zero-based position of the symbol in the schema.""" index = schema['symbols'].index(datum) write_int(fo, index)
def dict_to_enum_fn(d: Dict[str, Any], enum_class: Type[Enum]) -> Enum: """ Converts an ``dict`` to a ``Enum``. """ return enum_class[d['name']]
escaping characters for non printable characters in python mysql query
def _escape(s): """ Helper method that escapes parameters to a SQL query. """ e = s e = e.replace('\\', '\\\\') e = e.replace('\n', '\\n') e = e.replace('\r', '\\r') e = e.replace("'", "\\'") e = e.replace('"', '\\"') return e
def decode_mysql_string_literal(text): """ Removes quotes and decodes escape sequences from given MySQL string literal returning the result. :param text: MySQL string literal, with the quotes still included. :type text: str :return: Given string literal with quotes removed and escape sequences...
escaping characters for non printable characters in python mysql query
def _escape(s): """ Helper method that escapes parameters to a SQL query. """ e = s e = e.replace('\\', '\\\\') e = e.replace('\n', '\\n') e = e.replace('\r', '\\r') e = e.replace("'", "\\'") e = e.replace('"', '\\"') return e
def atlasdb_format_query( query, values ): """ Turn a query into a string for printing. Useful for debugging. """ return "".join( ["%s %s" % (frag, "'%s'" % val if type(val) in [str, unicode] else val) for (frag, val) in zip(query.split("?"), values + ("",))] )
escaping characters for non printable characters in python mysql query
def _escape(s): """ Helper method that escapes parameters to a SQL query. """ e = s e = e.replace('\\', '\\\\') e = e.replace('\n', '\\n') e = e.replace('\r', '\\r') e = e.replace("'", "\\'") e = e.replace('"', '\\"') return e
def _escape(self, s): """Escape bad characters for regular expressions. Similar to `re.escape` but allows '%' to pass through. """ for ch, r_ch in self.ESCAPE_SETS: s = s.replace(ch, r_ch) return s
escaping characters for non printable characters in python mysql query
def _escape(s): """ Helper method that escapes parameters to a SQL query. """ e = s e = e.replace('\\', '\\\\') e = e.replace('\n', '\\n') e = e.replace('\r', '\\r') e = e.replace("'", "\\'") e = e.replace('"', '\\"') return e
def do_forceescape(value): """Enforce HTML escaping. This will probably double escape variables.""" if hasattr(value, '__html__'): value = value.__html__() return escape(unicode(value))
escaping characters for non printable characters in python mysql query
def _escape(s): """ Helper method that escapes parameters to a SQL query. """ e = s e = e.replace('\\', '\\\\') e = e.replace('\n', '\\n') e = e.replace('\r', '\\r') e = e.replace("'", "\\'") e = e.replace('"', '\\"') return e
def do_forceescape(value): """Enforce HTML escaping. This will probably double escape variables.""" if hasattr(value, '__html__'): value = value.__html__() return escape(text_type(value))
evaluate if a set of points are inside of a polygon python
def is_in(self, point_x, point_y): """ Test if a point is within this polygonal region """ point_array = array(((point_x, point_y),)) vertices = array(self.points) winding = self.inside_rule == "winding" result = points_in_polygon(point_array, vertices, winding) return r...
def point_in_multipolygon(point, multipoly): """ valid whether the point is located in a mulitpolygon (donut polygon is not supported) Keyword arguments: point -- point geojson object multipoly -- multipolygon geojson object if(point inside multipoly) return true else false """ c...
evaluate if a set of points are inside of a polygon python
def is_in(self, point_x, point_y): """ Test if a point is within this polygonal region """ point_array = array(((point_x, point_y),)) vertices = array(self.points) winding = self.inside_rule == "winding" result = points_in_polygon(point_array, vertices, winding) return r...
def bounds_to_poly(bounds): """ Constructs a shapely Polygon from the provided bounds tuple. Parameters ---------- bounds: tuple Tuple representing the (left, bottom, right, top) coordinates Returns ------- polygon: shapely.geometry.Polygon Shapely Polygon geometry of t...
evaluate if a set of points are inside of a polygon python
def is_in(self, point_x, point_y): """ Test if a point is within this polygonal region """ point_array = array(((point_x, point_y),)) vertices = array(self.points) winding = self.inside_rule == "winding" result = points_in_polygon(point_array, vertices, winding) return r...
def polygon_from_points(points): """ Constructs a numpy-compatible polygon from a page representation. """ polygon = [] for pair in points.split(" "): x_y = pair.split(",") polygon.append([float(x_y[0]), float(x_y[1])]) return polygon
evaluate if a set of points are inside of a polygon python
def is_in(self, point_x, point_y): """ Test if a point is within this polygonal region """ point_array = array(((point_x, point_y),)) vertices = array(self.points) winding = self.inside_rule == "winding" result = points_in_polygon(point_array, vertices, winding) return r...
def get_bound(pts): """Compute a minimal rectangle that covers all the points.""" (x0, y0, x1, y1) = (INF, INF, -INF, -INF) for (x, y) in pts: x0 = min(x0, x) y0 = min(y0, y) x1 = max(x1, x) y1 = max(y1, y) return (x0, y0, x1, y1)
evaluate if a set of points are inside of a polygon python
def is_in(self, point_x, point_y): """ Test if a point is within this polygonal region """ point_array = array(((point_x, point_y),)) vertices = array(self.points) winding = self.inside_rule == "winding" result = points_in_polygon(point_array, vertices, winding) return r...
def search_overlap(self, point_list): """ Returns all intervals that overlap the point_list. """ result = set() for j in point_list: self.search_point(j, result) return result
export ipynb as python file
def nb_to_python(nb_path): """convert notebook to python script""" exporter = python.PythonExporter() output, resources = exporter.from_filename(nb_path) return output
def lambda_from_file(python_file): """ Reads a python file and returns a awslambda.Code object :param python_file: :return: """ lambda_function = [] with open(python_file, 'r') as f: lambda_function.extend(f.read().splitlines()) return awslambda.Code(ZipFile=(Join('\n', lambda_f...
export ipynb as python file
def nb_to_python(nb_path): """convert notebook to python script""" exporter = python.PythonExporter() output, resources = exporter.from_filename(nb_path) return output
def code_from_ipynb(nb, markdown=False): """ Get the code for a given notebook nb is passed in as a dictionary that's a parsed ipynb file """ code = PREAMBLE for cell in nb['cells']: if cell['cell_type'] == 'code': # transform the input to executable Python code ...
export ipynb as python file
def nb_to_python(nb_path): """convert notebook to python script""" exporter = python.PythonExporter() output, resources = exporter.from_filename(nb_path) return output
def execfile(fname, variables): """ This is builtin in python2, but we have to roll our own on py3. """ with open(fname) as f: code = compile(f.read(), fname, 'exec') exec(code, variables)
export ipynb as python file
def nb_to_python(nb_path): """convert notebook to python script""" exporter = python.PythonExporter() output, resources = exporter.from_filename(nb_path) return output
async def stdout(self) -> AsyncGenerator[str, None]: """Asynchronous generator for lines from subprocess stdout.""" await self.wait_running() async for line in self._subprocess.stdout: # type: ignore yield line
export ipynb as python file
def nb_to_python(nb_path): """convert notebook to python script""" exporter = python.PythonExporter() output, resources = exporter.from_filename(nb_path) return output
def main(pargs): """This should only be used for testing. The primary mode of operation is as an imported library. """ input_file = sys.argv[1] fp = ParseFileLineByLine(input_file) for i in fp: print(i)
faster update bulk in python mysql
def forceupdate(self, *args, **kw): """Like a bulk :meth:`forceput`.""" self._update(False, self._ON_DUP_OVERWRITE, *args, **kw)
def bulk_query(self, query, *multiparams): """Bulk insert or update.""" with self.get_connection() as conn: conn.bulk_query(query, *multiparams)
faster update bulk in python mysql
def forceupdate(self, *args, **kw): """Like a bulk :meth:`forceput`.""" self._update(False, self._ON_DUP_OVERWRITE, *args, **kw)
def update(table, values, where=(), **kwargs): """Convenience wrapper for database UPDATE.""" where = dict(where, **kwargs).items() sql, args = makeSQL("UPDATE", table, values=values, where=where) return execute(sql, args).rowcount
faster update bulk in python mysql
def forceupdate(self, *args, **kw): """Like a bulk :meth:`forceput`.""" self._update(False, self._ON_DUP_OVERWRITE, *args, **kw)
def emit_db_sequence_updates(engine): """Set database sequence objects to match the source db Relevant only when generated from SQLAlchemy connection. Needed to avoid subsequent unique key violations after DB build.""" if engine and engine.name == 'postgresql': # not implemented for othe...
faster update bulk in python mysql
def forceupdate(self, *args, **kw): """Like a bulk :meth:`forceput`.""" self._update(False, self._ON_DUP_OVERWRITE, *args, **kw)
def upsert_single(db, collection, object, match_params=None): """ Wrapper for pymongo.update_one() :param db: db connection :param collection: collection to update :param object: the modifications to apply :param match_params: a query that matches the documents to update ...
faster update bulk in python mysql
def forceupdate(self, *args, **kw): """Like a bulk :meth:`forceput`.""" self._update(False, self._ON_DUP_OVERWRITE, *args, **kw)
def upsert_multi(db, collection, object, match_params=None): """ Wrapper for pymongo.insert_many() and update_many() :param db: db connection :param collection: collection to update :param object: the modifications to apply :param match_params: a query that matches the do...
python how to check logging is disabled
def should_skip_logging(func): """ Should we skip logging for this handler? """ disabled = strtobool(request.headers.get("x-request-nolog", "false")) return disabled or getattr(func, SKIP_LOGGING, False)
def handle_logging(self): """ To allow devs to log as early as possible, logging will already be handled here """ configure_logging(self.get_scrapy_options()) # Disable duplicates self.__scrapy_options["LOG_ENABLED"] = False # Now, after log-level is co...
python how to check logging is disabled
def should_skip_logging(func): """ Should we skip logging for this handler? """ disabled = strtobool(request.headers.get("x-request-nolog", "false")) return disabled or getattr(func, SKIP_LOGGING, False)
def _configure_logger(): """Configure the logging module.""" if not app.debug: _configure_logger_for_production(logging.getLogger()) elif not app.testing: _configure_logger_for_debugging(logging.getLogger())
python how to check logging is disabled
def should_skip_logging(func): """ Should we skip logging for this handler? """ disabled = strtobool(request.headers.get("x-request-nolog", "false")) return disabled or getattr(func, SKIP_LOGGING, False)
def stop_logging(): """Stop logging to logfile and console.""" from . import log logger = logging.getLogger("gromacs") logger.info("GromacsWrapper %s STOPPED logging", get_version()) log.clear_handlers(logger)
python how to check logging is disabled
def should_skip_logging(func): """ Should we skip logging for this handler? """ disabled = strtobool(request.headers.get("x-request-nolog", "false")) return disabled or getattr(func, SKIP_LOGGING, False)
def stoplog(self): """ Stop logging. @return: 1 on success and 0 on error @rtype: integer """ if self._file_logger: self.logger.removeHandler(_file_logger) self._file_logger = None return 1
python how to check logging is disabled
def should_skip_logging(func): """ Should we skip logging for this handler? """ disabled = strtobool(request.headers.get("x-request-nolog", "false")) return disabled or getattr(func, SKIP_LOGGING, False)
def _debug_log(self, msg): """Debug log messages if debug=True""" if not self.debug: return sys.stderr.write('{}\n'.format(msg))
ftplib python secure connection
def connect(): """Connect to FTP server, login and return an ftplib.FTP instance.""" ftp_class = ftplib.FTP if not SSL else ftplib.FTP_TLS ftp = ftp_class(timeout=TIMEOUT) ftp.connect(HOST, PORT) ftp.login(USER, PASSWORD) if SSL: ftp.prot_p() # secure data connection return ftp
def enable_ssl(self, *args, **kwargs): """ Transforms the regular socket.socket to an ssl.SSLSocket for secure connections. Any arguments are passed to ssl.wrap_socket: http://docs.python.org/dev/library/ssl.html#ssl.wrap_socket """ if self.handshake_sent: rai...
ftplib python secure connection
def connect(): """Connect to FTP server, login and return an ftplib.FTP instance.""" ftp_class = ftplib.FTP if not SSL else ftplib.FTP_TLS ftp = ftp_class(timeout=TIMEOUT) ftp.connect(HOST, PORT) ftp.login(USER, PASSWORD) if SSL: ftp.prot_p() # secure data connection return ftp
def inject_into_urllib3(): """ Monkey-patch urllib3 with SecureTransport-backed SSL-support. """ util.ssl_.SSLContext = SecureTransportContext util.HAS_SNI = HAS_SNI util.ssl_.HAS_SNI = HAS_SNI util.IS_SECURETRANSPORT = True util.ssl_.IS_SECURETRANSPORT = True
ftplib python secure connection
def connect(): """Connect to FTP server, login and return an ftplib.FTP instance.""" ftp_class = ftplib.FTP if not SSL else ftplib.FTP_TLS ftp = ftp_class(timeout=TIMEOUT) ftp.connect(HOST, PORT) ftp.login(USER, PASSWORD) if SSL: ftp.prot_p() # secure data connection return ftp
def _sslobj(sock): """Returns the underlying PySLLSocket object with which the C extension functions interface. """ pass if isinstance(sock._sslobj, _ssl._SSLSocket): return sock._sslobj else: return sock._sslobj._sslobj
ftplib python secure connection
def connect(): """Connect to FTP server, login and return an ftplib.FTP instance.""" ftp_class = ftplib.FTP if not SSL else ftplib.FTP_TLS ftp = ftp_class(timeout=TIMEOUT) ftp.connect(HOST, PORT) ftp.login(USER, PASSWORD) if SSL: ftp.prot_p() # secure data connection return ftp
def connect(host, port, username, password): """Connect and login to an FTP server and return ftplib.FTP object.""" # Instantiate ftplib client session = ftplib.FTP() # Connect to host without auth session.connect(host, port) # Authenticate connection session.lo...
ftplib python secure connection
def connect(): """Connect to FTP server, login and return an ftplib.FTP instance.""" ftp_class = ftplib.FTP if not SSL else ftplib.FTP_TLS ftp = ftp_class(timeout=TIMEOUT) ftp.connect(HOST, PORT) ftp.login(USER, PASSWORD) if SSL: ftp.prot_p() # secure data connection return ftp
def start_connect(self): """Tries to connect to the Heron Server ``loop()`` method needs to be called after this. """ Log.debug("In start_connect() of %s" % self._get_classname()) # TODO: specify buffer size, exception handling self.create_socket(socket.AF_INET, socket.SOCK_STREAM) # when ...
full screen in python tkinter
def trigger_fullscreen_action(self, fullscreen): """ Toggle fullscreen from outside the GUI, causes the GUI to updated and run all its actions. """ action = self.action_group.get_action('fullscreen') action.set_active(fullscreen)
def _screen(self, s, newline=False): """Print something on screen when self.verbose == True""" if self.verbose: if newline: print(s) else: print(s, end=' ')
full screen in python tkinter
def trigger_fullscreen_action(self, fullscreen): """ Toggle fullscreen from outside the GUI, causes the GUI to updated and run all its actions. """ action = self.action_group.get_action('fullscreen') action.set_active(fullscreen)
def hidden_cursor(): """Temporarily hide the terminal cursor.""" if sys.stdout.isatty(): _LOGGER.debug('Hiding cursor.') print('\x1B[?25l', end='') sys.stdout.flush() try: yield finally: if sys.stdout.isatty(): _LOGGER.debug('Showing cursor.') ...
full screen in python tkinter
def trigger_fullscreen_action(self, fullscreen): """ Toggle fullscreen from outside the GUI, causes the GUI to updated and run all its actions. """ action = self.action_group.get_action('fullscreen') action.set_active(fullscreen)
def page_guiref(arg_s=None): """Show a basic reference about the GUI Console.""" from IPython.core import page page.page(gui_reference, auto_html=True)
full screen in python tkinter
def trigger_fullscreen_action(self, fullscreen): """ Toggle fullscreen from outside the GUI, causes the GUI to updated and run all its actions. """ action = self.action_group.get_action('fullscreen') action.set_active(fullscreen)
def _enter_plotting(self, fontsize=9): """assumes that a figure is open """ # interactive_status = matplotlib.is_interactive() self.original_fontsize = pyplot.rcParams['font.size'] pyplot.rcParams['font.size'] = fontsize pyplot.hold(False) # opens a figure window, if non exists ...
full screen in python tkinter
def trigger_fullscreen_action(self, fullscreen): """ Toggle fullscreen from outside the GUI, causes the GUI to updated and run all its actions. """ action = self.action_group.get_action('fullscreen') action.set_active(fullscreen)
def raise_figure_window(f=0): """ Raises the supplied figure number or figure window. """ if _fun.is_a_number(f): f = _pylab.figure(f) f.canvas.manager.window.raise_()
python how to drag a element to another element and stay at second element
def drag_and_drop(self, droppable): """ Performs drag a element to another elmenet. Currently works only on Chrome driver. """ self.scroll_to() ActionChains(self.parent.driver).drag_and_drop(self._element, droppable._element).perform()
def mouseMoveEvent(self, event): """ Handle the mouse move event for a drag operation. """ self.declaration.mouse_move_event(event) super(QtGraphicsView, self).mouseMoveEvent(event)
python how to drag a element to another element and stay at second element
def drag_and_drop(self, droppable): """ Performs drag a element to another elmenet. Currently works only on Chrome driver. """ self.scroll_to() ActionChains(self.parent.driver).drag_and_drop(self._element, droppable._element).perform()
def mouse_move_event(self, event): """ Forward mouse cursor position events to the example """ self.example.mouse_position_event(event.x(), event.y())
python how to drag a element to another element and stay at second element
def drag_and_drop(self, droppable): """ Performs drag a element to another elmenet. Currently works only on Chrome driver. """ self.scroll_to() ActionChains(self.parent.driver).drag_and_drop(self._element, droppable._element).perform()
def on_mouse_motion(self, x, y, dx, dy): """ Pyglet specific mouse motion callback. Forwards and traslates the event to the example """ # Screen coordinates relative to the lower-left corner # so we have to flip the y axis to make this consistent with # other wind...
python how to drag a element to another element and stay at second element
def drag_and_drop(self, droppable): """ Performs drag a element to another elmenet. Currently works only on Chrome driver. """ self.scroll_to() ActionChains(self.parent.driver).drag_and_drop(self._element, droppable._element).perform()
def scroll_up(self, locator): """Scrolls up to element""" driver = self._current_application() element = self._element_find(locator, True, True) driver.execute_script("mobile: scroll", {"direction": 'up', 'element': element.id})
python how to drag a element to another element and stay at second element
def drag_and_drop(self, droppable): """ Performs drag a element to another elmenet. Currently works only on Chrome driver. """ self.scroll_to() ActionChains(self.parent.driver).drag_and_drop(self._element, droppable._element).perform()
def yview(self, *args): """Update inplace widgets position when doing vertical scroll""" self.after_idle(self.__updateWnds) ttk.Treeview.yview(self, *args)
python how to encode url
def url_encode(url): """ Convert special characters using %xx escape. :param url: str :return: str - encoded url """ if isinstance(url, text_type): url = url.encode('utf8') return quote(url, ':/%?&=')
def get_dict_to_encoded_url(data): """ Converts a dict to an encoded URL. Example: given data = {'a': 1, 'b': 2}, it returns 'a=1&b=2' """ unicode_data = dict([(k, smart_str(v)) for k, v in data.items()]) encoded = urllib.urlencode(unicode_data) return encoded
python how to encode url
def url_encode(url): """ Convert special characters using %xx escape. :param url: str :return: str - encoded url """ if isinstance(url, text_type): url = url.encode('utf8') return quote(url, ':/%?&=')
def urlencoded(body, charset='ascii', **kwargs): """Converts query strings into native Python objects""" return parse_query_string(text(body, charset=charset), False)
python how to encode url
def url_encode(url): """ Convert special characters using %xx escape. :param url: str :return: str - encoded url """ if isinstance(url, text_type): url = url.encode('utf8') return quote(url, ':/%?&=')
def add_params_to_url(url, params): """Adds params to url :param url: Url :param params: Params to add :return: original url with new params """ url_parts = list(urlparse.urlparse(url)) # get url parts query = dict(urlparse.parse_qsl(url_parts[4])) # get url query query.update(params)...
python how to encode url
def url_encode(url): """ Convert special characters using %xx escape. :param url: str :return: str - encoded url """ if isinstance(url, text_type): url = url.encode('utf8') return quote(url, ':/%?&=')
def url_fix_common_typos (url): """Fix common typos in given URL like forgotten colon.""" if url.startswith("http//"): url = "http://" + url[6:] elif url.startswith("https//"): url = "https://" + url[7:] return url
python how to encode url
def url_encode(url): """ Convert special characters using %xx escape. :param url: str :return: str - encoded url """ if isinstance(url, text_type): url = url.encode('utf8') return quote(url, ':/%?&=')
def get_url(self, cmd, **args): """Expand the request URL for a request.""" return self.http.base_url + self._mkurl(cmd, *args)