nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
achael/eht-imaging
bbd3aeb06bef52bf89fa1c06de71e5509a5b0015
ehtim/obsdata.py
python
Obsdata.reorder_baselines
(self)
return
Reorder baselines to match uvfits convention, based on the telescope array ordering
Reorder baselines to match uvfits convention, based on the telescope array ordering
[ "Reorder", "baselines", "to", "match", "uvfits", "convention", "based", "on", "the", "telescope", "array", "ordering" ]
def reorder_baselines(self): """Reorder baselines to match uvfits convention, based on the telescope array ordering """ # Time partition the datatable datatable = self.data.copy() datalist = [] for key, group in it.groupby(datatable, lambda x: x['time']): datalist.append(np.array([obs for obs in group])) # Remove conjugate baselines obsdata = [] for tlist in datalist: blpairs = [] for dat in tlist: if not (set((dat['t1'], dat['t2']))) in blpairs: # Reverse the baseline in the right order for uvfits: if(self.tkey[dat['t2']] < self.tkey[dat['t1']]): (dat['t1'], dat['t2']) = (dat['t2'], dat['t1']) (dat['tau1'], dat['tau2']) = (dat['tau2'], dat['tau1']) dat['u'] = -dat['u'] dat['v'] = -dat['v'] if self.polrep == 'stokes': dat['vis'] = np.conj(dat['vis']) dat['qvis'] = np.conj(dat['qvis']) dat['uvis'] = np.conj(dat['uvis']) dat['vvis'] = np.conj(dat['vvis']) elif self.polrep == 'circ': dat['rrvis'] = np.conj(dat['rrvis']) dat['llvis'] = np.conj(dat['llvis']) # must switch l & r !! rl = dat['rlvis'].copy() lr = dat['lrvis'].copy() dat['rlvis'] = np.conj(lr) dat['lrvis'] = np.conj(rl) else: raise Exception("polrep must be either 'stokes' or 'circ'") # Append the data point blpairs.append(set((dat['t1'], dat['t2']))) obsdata.append(dat) obsdata = np.array(obsdata, dtype=self.poltype) # Timesort data obsdata = obsdata[np.argsort(obsdata, order=['time', 't1'])] # Save the data self.data = obsdata return
[ "def", "reorder_baselines", "(", "self", ")", ":", "# Time partition the datatable", "datatable", "=", "self", ".", "data", ".", "copy", "(", ")", "datalist", "=", "[", "]", "for", "key", ",", "group", "in", "it", ".", "groupby", "(", "datatable", ",", "...
https://github.com/achael/eht-imaging/blob/bbd3aeb06bef52bf89fa1c06de71e5509a5b0015/ehtim/obsdata.py#L330-L383
mvantellingen/python-zeep
2f35b7d29355ba646f5e3c6e9925033d5d6df8bb
src/zeep/xsd/elements/indicators.py
python
OrderIndicator.accept
(self, values)
return max(results)
Return the number of values which are accepted by this choice. If not all required elements are available then 0 is returned.
Return the number of values which are accepted by this choice.
[ "Return", "the", "number", "of", "values", "which", "are", "accepted", "by", "this", "choice", "." ]
def accept(self, values): """Return the number of values which are accepted by this choice. If not all required elements are available then 0 is returned. """ if not self.accepts_multiple: values = [values] results = set() for value in values: num = 0 for name, element in self.elements_nested: if isinstance(element, Element): if element.name in value and value[element.name] is not None: num += 1 else: num += element.accept(value) results.add(num) return max(results)
[ "def", "accept", "(", "self", ",", "values", ")", ":", "if", "not", "self", ".", "accepts_multiple", ":", "values", "=", "[", "values", "]", "results", "=", "set", "(", ")", "for", "value", "in", "values", ":", "num", "=", "0", "for", "name", ",", ...
https://github.com/mvantellingen/python-zeep/blob/2f35b7d29355ba646f5e3c6e9925033d5d6df8bb/src/zeep/xsd/elements/indicators.py#L114-L133
jcartledge/sublime-worksheet
44b2ba96d02759b485adbf85c1a2c9d45cc39599
repl/pexpect.py
python
spawnb.setwinsize
(self, r, c)
This sets the terminal window size of the child tty. This will cause a SIGWINCH signal to be sent to the child. This does not change the physical window size. It changes the size reported to TTY-aware applications like vi or curses -- applications that respond to the SIGWINCH signal.
This sets the terminal window size of the child tty. This will cause a SIGWINCH signal to be sent to the child. This does not change the physical window size. It changes the size reported to TTY-aware applications like vi or curses -- applications that respond to the SIGWINCH signal.
[ "This", "sets", "the", "terminal", "window", "size", "of", "the", "child", "tty", ".", "This", "will", "cause", "a", "SIGWINCH", "signal", "to", "be", "sent", "to", "the", "child", ".", "This", "does", "not", "change", "the", "physical", "window", "size"...
def setwinsize(self, r, c): """This sets the terminal window size of the child tty. This will cause a SIGWINCH signal to be sent to the child. This does not change the physical window size. It changes the size reported to TTY-aware applications like vi or curses -- applications that respond to the SIGWINCH signal. """ # Check for buggy platforms. Some Python versions on some platforms # (notably OSF1 Alpha and RedHat 7.1) truncate the value for # termios.TIOCSWINSZ. It is not clear why this happens. # These platforms don't seem to handle the signed int very well; # yet other platforms like OpenBSD have a large negative value for # TIOCSWINSZ and they don't have a truncate problem. # Newer versions of Linux have totally different values for TIOCSWINSZ. # Note that this fix is a hack. TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561) if TIOCSWINSZ == 2148037735: # L is not required in Python >= 2.2. TIOCSWINSZ = -2146929561 # Same bits, but with sign. # Note, assume ws_xpixel and ws_ypixel are zero. s = struct.pack('HHHH', r, c, 0, 0) fcntl.ioctl(self.fileno(), TIOCSWINSZ, s)
[ "def", "setwinsize", "(", "self", ",", "r", ",", "c", ")", ":", "# Check for buggy platforms. Some Python versions on some platforms", "# (notably OSF1 Alpha and RedHat 7.1) truncate the value for", "# termios.TIOCSWINSZ. It is not clear why this happens.", "# These platforms don't seem to...
https://github.com/jcartledge/sublime-worksheet/blob/44b2ba96d02759b485adbf85c1a2c9d45cc39599/repl/pexpect.py#L1512-L1533
mesonbuild/meson
a22d0f9a0a787df70ce79b05d0c45de90a970048
mesonbuild/dependencies/qt.py
python
Qt6PkgConfigDependency.get_private_includes
(self, mod_inc_dir: str, module: str)
return _qt_get_private_includes(mod_inc_dir, module, self.version)
[]
def get_private_includes(self, mod_inc_dir: str, module: str) -> T.List[str]: return _qt_get_private_includes(mod_inc_dir, module, self.version)
[ "def", "get_private_includes", "(", "self", ",", "mod_inc_dir", ":", "str", ",", "module", ":", "str", ")", "->", "T", ".", "List", "[", "str", "]", ":", "return", "_qt_get_private_includes", "(", "mod_inc_dir", ",", "module", ",", "self", ".", "version", ...
https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/mesonbuild/dependencies/qt.py#L415-L416
securityclippy/elasticintel
aa08d3e9f5ab1c000128e95161139ce97ff0e334
ingest_feed_lambda/numpy/polynomial/polynomial.py
python
polyvalfromroots
(x, r, tensor=True)
return np.prod(x - r, axis=0)
Evaluate a polynomial specified by its roots at points x. If `r` is of length `N`, this function returns the value .. math:: p(x) = \\prod_{n=1}^{N} (x - r_n) The parameter `x` is converted to an array only if it is a tuple or a list, otherwise it is treated as a scalar. In either case, either `x` or its elements must support multiplication and addition both with themselves and with the elements of `r`. If `r` is a 1-D array, then `p(x)` will have the same shape as `x`. If `r` is multidimensional, then the shape of the result depends on the value of `tensor`. If `tensor is ``True`` the shape will be r.shape[1:] + x.shape; that is, each polynomial is evaluated at every value of `x`. If `tensor` is ``False``, the shape will be r.shape[1:]; that is, each polynomial is evaluated only for the corresponding broadcast value of `x`. Note that scalars have shape (,). .. versionadded:: 1.12 Parameters ---------- x : array_like, compatible object If `x` is a list or tuple, it is converted to an ndarray, otherwise it is left unchanged and treated as a scalar. In either case, `x` or its elements must support addition and multiplication with with themselves and with the elements of `r`. r : array_like Array of roots. If `r` is multidimensional the first index is the root index, while the remaining indices enumerate multiple polynomials. For instance, in the two dimensional case the roots of each polynomial may be thought of as stored in the columns of `r`. tensor : boolean, optional If True, the shape of the roots array is extended with ones on the right, one for each dimension of `x`. Scalars have dimension 0 for this action. The result is that every column of coefficients in `r` is evaluated for every element of `x`. If False, `x` is broadcast over the columns of `r` for the evaluation. This keyword is useful when `r` is multidimensional. The default value is True. Returns ------- values : ndarray, compatible object The shape of the returned array is described above. See Also -------- polyroots, polyfromroots, polyval Examples -------- >>> from numpy.polynomial.polynomial import polyvalfromroots >>> polyvalfromroots(1, [1,2,3]) 0.0 >>> a = np.arange(4).reshape(2,2) >>> a array([[0, 1], [2, 3]]) >>> polyvalfromroots(a, [-1, 0, 1]) array([[ -0., 0.], [ 6., 24.]]) >>> r = np.arange(-2, 2).reshape(2,2) # multidimensional coefficients >>> r # each column of r defines one polynomial array([[-2, -1], [ 0, 1]]) >>> b = [-2, 1] >>> polyvalfromroots(b, r, tensor=True) array([[-0., 3.], [ 3., 0.]]) >>> polyvalfromroots(b, r, tensor=False) array([-0., 0.])
Evaluate a polynomial specified by its roots at points x.
[ "Evaluate", "a", "polynomial", "specified", "by", "its", "roots", "at", "points", "x", "." ]
def polyvalfromroots(x, r, tensor=True): """ Evaluate a polynomial specified by its roots at points x. If `r` is of length `N`, this function returns the value .. math:: p(x) = \\prod_{n=1}^{N} (x - r_n) The parameter `x` is converted to an array only if it is a tuple or a list, otherwise it is treated as a scalar. In either case, either `x` or its elements must support multiplication and addition both with themselves and with the elements of `r`. If `r` is a 1-D array, then `p(x)` will have the same shape as `x`. If `r` is multidimensional, then the shape of the result depends on the value of `tensor`. If `tensor is ``True`` the shape will be r.shape[1:] + x.shape; that is, each polynomial is evaluated at every value of `x`. If `tensor` is ``False``, the shape will be r.shape[1:]; that is, each polynomial is evaluated only for the corresponding broadcast value of `x`. Note that scalars have shape (,). .. versionadded:: 1.12 Parameters ---------- x : array_like, compatible object If `x` is a list or tuple, it is converted to an ndarray, otherwise it is left unchanged and treated as a scalar. In either case, `x` or its elements must support addition and multiplication with with themselves and with the elements of `r`. r : array_like Array of roots. If `r` is multidimensional the first index is the root index, while the remaining indices enumerate multiple polynomials. For instance, in the two dimensional case the roots of each polynomial may be thought of as stored in the columns of `r`. tensor : boolean, optional If True, the shape of the roots array is extended with ones on the right, one for each dimension of `x`. Scalars have dimension 0 for this action. The result is that every column of coefficients in `r` is evaluated for every element of `x`. If False, `x` is broadcast over the columns of `r` for the evaluation. This keyword is useful when `r` is multidimensional. The default value is True. Returns ------- values : ndarray, compatible object The shape of the returned array is described above. See Also -------- polyroots, polyfromroots, polyval Examples -------- >>> from numpy.polynomial.polynomial import polyvalfromroots >>> polyvalfromroots(1, [1,2,3]) 0.0 >>> a = np.arange(4).reshape(2,2) >>> a array([[0, 1], [2, 3]]) >>> polyvalfromroots(a, [-1, 0, 1]) array([[ -0., 0.], [ 6., 24.]]) >>> r = np.arange(-2, 2).reshape(2,2) # multidimensional coefficients >>> r # each column of r defines one polynomial array([[-2, -1], [ 0, 1]]) >>> b = [-2, 1] >>> polyvalfromroots(b, r, tensor=True) array([[-0., 3.], [ 3., 0.]]) >>> polyvalfromroots(b, r, tensor=False) array([-0., 0.]) """ r = np.array(r, ndmin=1, copy=0) if r.dtype.char in '?bBhHiIlLqQpP': r = r.astype(np.double) if isinstance(x, (tuple, list)): x = np.asarray(x) if isinstance(x, np.ndarray): if tensor: r = r.reshape(r.shape + (1,)*x.ndim) elif x.ndim >= r.ndim: raise ValueError("x.ndim must be < r.ndim when tensor == False") return np.prod(x - r, axis=0)
[ "def", "polyvalfromroots", "(", "x", ",", "r", ",", "tensor", "=", "True", ")", ":", "r", "=", "np", ".", "array", "(", "r", ",", "ndmin", "=", "1", ",", "copy", "=", "0", ")", "if", "r", ".", "dtype", ".", "char", "in", "'?bBhHiIlLqQpP'", ":",...
https://github.com/securityclippy/elasticintel/blob/aa08d3e9f5ab1c000128e95161139ce97ff0e334/ingest_feed_lambda/numpy/polynomial/polynomial.py#L779-L864
rtheunissen/foobar
06e91a741e44b662157bcafaf839aa62d1635895
peculiar_balance.py
python
number_of_steps
(weight)
return int(log(weight * 2, 3)) + 1
Returns the number of steps required to balance the scales
Returns the number of steps required to balance the scales
[ "Returns", "the", "number", "of", "steps", "required", "to", "balance", "the", "scales" ]
def number_of_steps(weight): """ Returns the number of steps required to balance the scales """ # this formula was derived from boundary = (3 ** n - 1) / 2 return int(log(weight * 2, 3)) + 1
[ "def", "number_of_steps", "(", "weight", ")", ":", "# this formula was derived from boundary = (3 ** n - 1) / 2", "return", "int", "(", "log", "(", "weight", "*", "2", ",", "3", ")", ")", "+", "1" ]
https://github.com/rtheunissen/foobar/blob/06e91a741e44b662157bcafaf839aa62d1635895/peculiar_balance.py#L34-L39
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
common/djangoapps/edxmako/paths.py
python
save_lookups
()
A context manager to save and restore the Mako template lookup path. Useful for testing.
A context manager to save and restore the Mako template lookup path.
[ "A", "context", "manager", "to", "save", "and", "restore", "the", "Mako", "template", "lookup", "path", "." ]
def save_lookups(): """ A context manager to save and restore the Mako template lookup path. Useful for testing. """ # Make a copy of the list of directories for each namespace. namespace_dirs = {namespace: list(look.directories) for namespace, look in LOOKUP.items()} try: yield finally: # Get rid of all the lookups. LOOKUP.clear() # Re-create the lookups from our saved list. for namespace, directories in namespace_dirs.items(): for directory in directories: add_lookup(namespace, directory)
[ "def", "save_lookups", "(", ")", ":", "# Make a copy of the list of directories for each namespace.", "namespace_dirs", "=", "{", "namespace", ":", "list", "(", "look", ".", "directories", ")", "for", "namespace", ",", "look", "in", "LOOKUP", ".", "items", "(", ")...
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/common/djangoapps/edxmako/paths.py#L155-L174
tomplus/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
kubernetes_asyncio/client/models/v1_job_status.py
python
V1JobStatus.active
(self, active)
Sets the active of this V1JobStatus. The number of actively running pods. # noqa: E501 :param active: The active of this V1JobStatus. # noqa: E501 :type: int
Sets the active of this V1JobStatus.
[ "Sets", "the", "active", "of", "this", "V1JobStatus", "." ]
def active(self, active): """Sets the active of this V1JobStatus. The number of actively running pods. # noqa: E501 :param active: The active of this V1JobStatus. # noqa: E501 :type: int """ self._active = active
[ "def", "active", "(", "self", ",", "active", ")", ":", "self", ".", "_active", "=", "active" ]
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1_job_status.py#L92-L101
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/combinat/root_system/root_space.py
python
RootSpace._name_string
(self, capitalize=True, base_ring=True, type=True)
return self._name_string_helper("root", capitalize=capitalize, base_ring=base_ring, type=type)
EXAMPLES:: sage: RootSystem(['A',4]).root_space()._name_string() "Root space over the Rational Field of the Root system of type ['A', 4]"
EXAMPLES::
[ "EXAMPLES", "::" ]
def _name_string(self, capitalize=True, base_ring=True, type=True): """ EXAMPLES:: sage: RootSystem(['A',4]).root_space()._name_string() "Root space over the Rational Field of the Root system of type ['A', 4]" """ return self._name_string_helper("root", capitalize=capitalize, base_ring=base_ring, type=type)
[ "def", "_name_string", "(", "self", ",", "capitalize", "=", "True", ",", "base_ring", "=", "True", ",", "type", "=", "True", ")", ":", "return", "self", ".", "_name_string_helper", "(", "\"root\"", ",", "capitalize", "=", "capitalize", ",", "base_ring", "=...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/root_system/root_space.py#L95-L102
ethereum/trinity
6383280c5044feb06695ac2f7bc1100b7bcf4fe0
trinity/components/builtin/new_block/component.py
python
NewBlockService._handle_imported_blocks
(self)
[]
async def _handle_imported_blocks(self) -> None: async for event in self._event_bus.stream(NewBlockImported): block = event.block self.logger.debug("NewBlockImported: %s", block) await self._broadcast_new_block_hashes(block)
[ "async", "def", "_handle_imported_blocks", "(", "self", ")", "->", "None", ":", "async", "for", "event", "in", "self", ".", "_event_bus", ".", "stream", "(", "NewBlockImported", ")", ":", "block", "=", "event", ".", "block", "self", ".", "logger", ".", "...
https://github.com/ethereum/trinity/blob/6383280c5044feb06695ac2f7bc1100b7bcf4fe0/trinity/components/builtin/new_block/component.py#L123-L127
explosion/prodigy-recipes
0037b32d954e0b1672f9dae1e8aa53ac0c9136e3
image/tf_odapi/misc/exporter.py
python
replace_variable_values_with_moving_averages
(graph, current_checkpoint_file, new_checkpoint_file)
Replaces variable values in the checkpoint with their moving averages. If the current checkpoint has shadow variables maintaining moving averages of the variables defined in the graph, this function generates a new checkpoint where the variables contain the values of their moving averages. Args: graph: a tf.Graph object. current_checkpoint_file: a checkpoint containing both original variables and their moving averages. new_checkpoint_file: file path to write a new checkpoint.
Replaces variable values in the checkpoint with their moving averages.
[ "Replaces", "variable", "values", "in", "the", "checkpoint", "with", "their", "moving", "averages", "." ]
def replace_variable_values_with_moving_averages(graph, current_checkpoint_file, new_checkpoint_file): """Replaces variable values in the checkpoint with their moving averages. If the current checkpoint has shadow variables maintaining moving averages of the variables defined in the graph, this function generates a new checkpoint where the variables contain the values of their moving averages. Args: graph: a tf.Graph object. current_checkpoint_file: a checkpoint containing both original variables and their moving averages. new_checkpoint_file: file path to write a new checkpoint. """ with graph.as_default(): variable_averages = tf.train.ExponentialMovingAverage(0.0) ema_variables_to_restore = variable_averages.variables_to_restore() with tf.Session() as sess: read_saver = tf.train.Saver(ema_variables_to_restore) read_saver.restore(sess, current_checkpoint_file) write_saver = tf.train.Saver() write_saver.save(sess, new_checkpoint_file)
[ "def", "replace_variable_values_with_moving_averages", "(", "graph", ",", "current_checkpoint_file", ",", "new_checkpoint_file", ")", ":", "with", "graph", ".", "as_default", "(", ")", ":", "variable_averages", "=", "tf", ".", "train", ".", "ExponentialMovingAverage", ...
https://github.com/explosion/prodigy-recipes/blob/0037b32d954e0b1672f9dae1e8aa53ac0c9136e3/image/tf_odapi/misc/exporter.py#L87-L109
rndusr/stig
334f03e2e3eda7c1856dd5489f0265a47b9861b6
stig/client/aiotransmission/rpc.py
python
TransmissionRPC.timeout
(self)
return self._timeout
Number of seconds to try to connect before giving up
Number of seconds to try to connect before giving up
[ "Number", "of", "seconds", "to", "try", "to", "connect", "before", "giving", "up" ]
def timeout(self): """Number of seconds to try to connect before giving up""" return self._timeout
[ "def", "timeout", "(", "self", ")", ":", "return", "self", ".", "_timeout" ]
https://github.com/rndusr/stig/blob/334f03e2e3eda7c1856dd5489f0265a47b9861b6/stig/client/aiotransmission/rpc.py#L262-L264
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/motech/openmrs/atom_feed.py
python
get_case_block_for_indexed_case
( mapping: ObservationMapping, external_data: dict, parent_case_attrs: CaseAttrs, )
return case_block
[]
def get_case_block_for_indexed_case( mapping: ObservationMapping, external_data: dict, parent_case_attrs: CaseAttrs, ) -> CaseBlock: parent_case_id, parent_case_type, default_owner_id = parent_case_attrs relationship = mapping.indexed_case_mapping.relationship case_block_kwargs = { "index": { mapping.indexed_case_mapping.identifier: IndexAttrs( parent_case_type, parent_case_id, relationship, ) }, "update": {} } for value_source_config in mapping.indexed_case_mapping.case_properties: value_source = as_value_source(value_source_config) value = value_source.get_import_value(external_data) if value_source.case_property in CASE_BLOCK_ARGS: case_block_kwargs[value_source.case_property] = value else: case_block_kwargs["update"][value_source.case_property] = value case_id = uuid.uuid4().hex case_type = mapping.indexed_case_mapping.case_type case_block_kwargs.setdefault("owner_id", default_owner_id) if not case_block_kwargs["owner_id"]: raise ConfigurationError(_( f'Unable to determine mobile worker to own new "{case_type}" ' f'{relationship} case or parent case "{parent_case_id}"' )) case_block = CaseBlock.deprecated_init( create=True, case_id=case_id, case_type=case_type, **case_block_kwargs ) return case_block
[ "def", "get_case_block_for_indexed_case", "(", "mapping", ":", "ObservationMapping", ",", "external_data", ":", "dict", ",", "parent_case_attrs", ":", "CaseAttrs", ",", ")", "->", "CaseBlock", ":", "parent_case_id", ",", "parent_case_type", ",", "default_owner_id", "=...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/motech/openmrs/atom_feed.py#L690-L730
zdenop/lector
d44d316dc208a2f3f3efd51444f464340d178b02
lector/editor/textwidget.py
python
TextWidget.togglewhiteSpace
(self, state=True)
Show or hide whitespace and line ending markers
Show or hide whitespace and line ending markers
[ "Show", "or", "hide", "whitespace", "and", "line", "ending", "markers" ]
def togglewhiteSpace(self, state=True): """ Show or hide whitespace and line ending markers """ option = QTextOption() if state: option.setFlags(QTextOption.ShowTabsAndSpaces | QTextOption.ShowLineAndParagraphSeparators) else: option.setFlags(option.flags() & ~option.ShowTabsAndSpaces & ~option.ShowLineAndParagraphSeparators) self.document().setDefaultTextOption(option) settings.set('editor:whiteSpace', state)
[ "def", "togglewhiteSpace", "(", "self", ",", "state", "=", "True", ")", ":", "option", "=", "QTextOption", "(", ")", "if", "state", ":", "option", ".", "setFlags", "(", "QTextOption", ".", "ShowTabsAndSpaces", "|", "QTextOption", ".", "ShowLineAndParagraphSepa...
https://github.com/zdenop/lector/blob/d44d316dc208a2f3f3efd51444f464340d178b02/lector/editor/textwidget.py#L275-L287
python-escpos/python-escpos
b16f44257e7318060fbd0c2bf548239947734359
src/escpos/magicencode.py
python
MagicEncode._handle_character_failed
(self, char)
Called when no codepage was found to render a character.
Called when no codepage was found to render a character.
[ "Called", "when", "no", "codepage", "was", "found", "to", "render", "a", "character", "." ]
def _handle_character_failed(self, char): """Called when no codepage was found to render a character.""" # Writing the default symbol via write() allows us to avoid # unnecesary codepage switches. self.write(self.defaultsymbol)
[ "def", "_handle_character_failed", "(", "self", ",", "char", ")", ":", "# Writing the default symbol via write() allows us to avoid", "# unnecesary codepage switches.", "self", ".", "write", "(", "self", ".", "defaultsymbol", ")" ]
https://github.com/python-escpos/python-escpos/blob/b16f44257e7318060fbd0c2bf548239947734359/src/escpos/magicencode.py#L274-L278
datamllab/rlcard
c21ea82519c453a42e3bdc6848bd3356e9b6ac43
rlcard/games/limitholdem/utils.py
python
determine_winner_four_of_a_kind
(hands, all_players, potential_winner_index)
return all_players
Find out who wins in the situation of having players which all have a four of a kind Args: key_index(int): the position of a card in a sorted handcard hands(list): cards of those players with a four of a kind e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']] all_players(list): all the players in this round, 0 for losing and 1 for winning or draw potential_winner_index(list): the positions of those players with same highest hand_catagory in all_players Returns: [0, 1, 0]: player1 wins [1, 0, 0]: player0 wins [1, 1, 1]: draw [1, 1, 0]: player1 and player0 draws
Find out who wins in the situation of having players which all have a four of a kind Args: key_index(int): the position of a card in a sorted handcard hands(list): cards of those players with a four of a kind e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']] all_players(list): all the players in this round, 0 for losing and 1 for winning or draw potential_winner_index(list): the positions of those players with same highest hand_catagory in all_players Returns: [0, 1, 0]: player1 wins [1, 0, 0]: player0 wins [1, 1, 1]: draw [1, 1, 0]: player1 and player0 draws
[ "Find", "out", "who", "wins", "in", "the", "situation", "of", "having", "players", "which", "all", "have", "a", "four", "of", "a", "kind", "Args", ":", "key_index", "(", "int", ")", ":", "the", "position", "of", "a", "card", "in", "a", "sorted", "han...
def determine_winner_four_of_a_kind(hands, all_players, potential_winner_index): ''' Find out who wins in the situation of having players which all have a four of a kind Args: key_index(int): the position of a card in a sorted handcard hands(list): cards of those players with a four of a kind e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']] all_players(list): all the players in this round, 0 for losing and 1 for winning or draw potential_winner_index(list): the positions of those players with same highest hand_catagory in all_players Returns: [0, 1, 0]: player1 wins [1, 0, 0]: player0 wins [1, 1, 1]: draw [1, 1, 0]: player1 and player0 draws ''' ranks = [] for hand in hands: rank_1 = hand.STRING_TO_RANK[hand.best_five[-1][1]] # rank of the four of a kind rank_2 = hand.STRING_TO_RANK[hand.best_five[0][1]] # rank of the kicker ranks.append((rank_1, rank_2)) max_rank = max(ranks) for i, rank in enumerate(ranks): if rank == max_rank: all_players[potential_winner_index[i]] = 1 return all_players
[ "def", "determine_winner_four_of_a_kind", "(", "hands", ",", "all_players", ",", "potential_winner_index", ")", ":", "ranks", "=", "[", "]", "for", "hand", "in", "hands", ":", "rank_1", "=", "hand", ".", "STRING_TO_RANK", "[", "hand", ".", "best_five", "[", ...
https://github.com/datamllab/rlcard/blob/c21ea82519c453a42e3bdc6848bd3356e9b6ac43/rlcard/games/limitholdem/utils.py#L500-L524
pypa/bandersnatch
2e3eb53029ddb8f205f85242d724ae492040c1ce
src/bandersnatch/mirror.py
python
Mirror.sync_packages
(self)
[]
async def sync_packages(self) -> None: try: self.package_queue: asyncio.Queue = asyncio.Queue() # Sorting the packages alphabetically makes it more predictable: # easier to debug and easier to follow in the logs. for name in sorted(self.packages_to_sync): serial = int(self.packages_to_sync[name]) await self.package_queue.put(Package(name, serial=serial)) sync_coros: List[Awaitable] = [ self.package_syncer(idx) for idx in range(self.workers) ] try: await asyncio.gather(*sync_coros) except KeyboardInterrupt as e: self.on_error(e) except (ValueError, TypeError) as e: # This is for when self.packages_to_sync isn't of type Dict[str, int] # Which occurs during testing or if BandersnatchMirror's todolist is # corrupted in determine_packages_to_sync() # TODO Remove this check by following packages_to_sync's typing self.on_error(e)
[ "async", "def", "sync_packages", "(", "self", ")", "->", "None", ":", "try", ":", "self", ".", "package_queue", ":", "asyncio", ".", "Queue", "=", "asyncio", ".", "Queue", "(", ")", "# Sorting the packages alphabetically makes it more predictable:", "# easier to deb...
https://github.com/pypa/bandersnatch/blob/2e3eb53029ddb8f205f85242d724ae492040c1ce/src/bandersnatch/mirror.py#L141-L162
ManiacalLabs/BiblioPixel
afb993fbbe56e75e7c98f252df402b0f3e83bb6e
bibliopixel/control/rest/decorator.py
python
single
(method)
return single
Decorator for RestServer methods that take a single address
Decorator for RestServer methods that take a single address
[ "Decorator", "for", "RestServer", "methods", "that", "take", "a", "single", "address" ]
def single(method): """Decorator for RestServer methods that take a single address""" @functools.wraps(method) def single(self, address, value=None): address = urllib.parse.unquote_plus(address) try: error = NO_PROJECT_ERROR if not self.project: raise ValueError error = BAD_ADDRESS_ERROR ed = editor.Editor(address, self.project) if value is None: error = BAD_GETTER_ERROR result = method(self, ed) else: error = BAD_SETTER_ERROR result = method(self, ed, value) result = {'value': result} except Exception as e: traceback.print_exc() msg = '%s\n%s' % (error.format(**locals()), e) result = {'error': msg} return flask.jsonify(result) return single
[ "def", "single", "(", "method", ")", ":", "@", "functools", ".", "wraps", "(", "method", ")", "def", "single", "(", "self", ",", "address", ",", "value", "=", "None", ")", ":", "address", "=", "urllib", ".", "parse", ".", "unquote_plus", "(", "addres...
https://github.com/ManiacalLabs/BiblioPixel/blob/afb993fbbe56e75e7c98f252df402b0f3e83bb6e/bibliopixel/control/rest/decorator.py#L10-L37
cvjena/semantic-embeddings
0d4177422bafbba685fb6a0f976675864f31e09f
models/DenseNet/densenet.py
python
DenseNetFCN
(input_shape, nb_dense_block=5, growth_rate=16, nb_layers_per_block=4, reduction=0.0, dropout_rate=0.0, weight_decay=1e-4, init_conv_filters=48, include_top=True, weights=None, input_tensor=None, classes=1, activation='softmax', upsampling_conv=128, upsampling_type='deconv')
return model
Instantiate the DenseNet FCN architecture. Note that when using TensorFlow, for best performance you should set `image_data_format='channels_last'` in your Keras config at ~/.keras/keras.json. # Arguments nb_dense_block: number of dense blocks to add to end (generally = 3) growth_rate: number of filters to add per dense block nb_layers_per_block: number of layers in each dense block. Can be a positive integer or a list. If positive integer, a set number of layers per dense block. If list, nb_layer is used as provided. Note that list size must be (nb_dense_block + 1) reduction: reduction factor of transition blocks. Note : reduction value is inverted to compute compression. dropout_rate: dropout rate init_conv_filters: number of layers in the initial convolution layer include_top: whether to include the fully-connected layer at the top of the network. weights: one of `None` (random initialization) or 'cifar10' (pre-training on CIFAR-10).. input_tensor: optional Keras tensor (i.e. output of `layers.Input()`) to use as image input for the model. input_shape: optional shape tuple, only to be specified if `include_top` is False (otherwise the input shape has to be `(32, 32, 3)` (with `channels_last` dim ordering) or `(3, 32, 32)` (with `channels_first` dim ordering). It should have exactly 3 inputs channels, and width and height should be no smaller than 8. E.g. `(200, 200, 3)` would be one valid value. classes: optional number of classes to classify images into, only to be specified if `include_top` is True, and if no `weights` argument is specified. activation: Type of activation at the top layer. Can be one of 'softmax' or 'sigmoid'. Note that if sigmoid is used, classes must be 1. upsampling_conv: number of convolutional layers in upsampling via subpixel convolution upsampling_type: Can be one of 'upsampling', 'deconv' and 'subpixel'. Defines type of upsampling algorithm used. batchsize: Fixed batch size. This is a temporary requirement for computation of output shape in the case of Deconvolution2D layers. Parameter will be removed in next iteration of Keras, which infers output shape of deconvolution layers automatically. # Returns A Keras model instance.
Instantiate the DenseNet FCN architecture. Note that when using TensorFlow, for best performance you should set `image_data_format='channels_last'` in your Keras config at ~/.keras/keras.json. # Arguments nb_dense_block: number of dense blocks to add to end (generally = 3) growth_rate: number of filters to add per dense block nb_layers_per_block: number of layers in each dense block. Can be a positive integer or a list. If positive integer, a set number of layers per dense block. If list, nb_layer is used as provided. Note that list size must be (nb_dense_block + 1) reduction: reduction factor of transition blocks. Note : reduction value is inverted to compute compression. dropout_rate: dropout rate init_conv_filters: number of layers in the initial convolution layer include_top: whether to include the fully-connected layer at the top of the network. weights: one of `None` (random initialization) or 'cifar10' (pre-training on CIFAR-10).. input_tensor: optional Keras tensor (i.e. output of `layers.Input()`) to use as image input for the model. input_shape: optional shape tuple, only to be specified if `include_top` is False (otherwise the input shape has to be `(32, 32, 3)` (with `channels_last` dim ordering) or `(3, 32, 32)` (with `channels_first` dim ordering). It should have exactly 3 inputs channels, and width and height should be no smaller than 8. E.g. `(200, 200, 3)` would be one valid value. classes: optional number of classes to classify images into, only to be specified if `include_top` is True, and if no `weights` argument is specified. activation: Type of activation at the top layer. Can be one of 'softmax' or 'sigmoid'. Note that if sigmoid is used, classes must be 1. upsampling_conv: number of convolutional layers in upsampling via subpixel convolution upsampling_type: Can be one of 'upsampling', 'deconv' and 'subpixel'. Defines type of upsampling algorithm used. batchsize: Fixed batch size. This is a temporary requirement for computation of output shape in the case of Deconvolution2D layers. Parameter will be removed in next iteration of Keras, which infers output shape of deconvolution layers automatically. # Returns A Keras model instance.
[ "Instantiate", "the", "DenseNet", "FCN", "architecture", ".", "Note", "that", "when", "using", "TensorFlow", "for", "best", "performance", "you", "should", "set", "image_data_format", "=", "channels_last", "in", "your", "Keras", "config", "at", "~", "/", ".", ...
def DenseNetFCN(input_shape, nb_dense_block=5, growth_rate=16, nb_layers_per_block=4, reduction=0.0, dropout_rate=0.0, weight_decay=1e-4, init_conv_filters=48, include_top=True, weights=None, input_tensor=None, classes=1, activation='softmax', upsampling_conv=128, upsampling_type='deconv'): '''Instantiate the DenseNet FCN architecture. Note that when using TensorFlow, for best performance you should set `image_data_format='channels_last'` in your Keras config at ~/.keras/keras.json. # Arguments nb_dense_block: number of dense blocks to add to end (generally = 3) growth_rate: number of filters to add per dense block nb_layers_per_block: number of layers in each dense block. Can be a positive integer or a list. If positive integer, a set number of layers per dense block. If list, nb_layer is used as provided. Note that list size must be (nb_dense_block + 1) reduction: reduction factor of transition blocks. Note : reduction value is inverted to compute compression. dropout_rate: dropout rate init_conv_filters: number of layers in the initial convolution layer include_top: whether to include the fully-connected layer at the top of the network. weights: one of `None` (random initialization) or 'cifar10' (pre-training on CIFAR-10).. input_tensor: optional Keras tensor (i.e. output of `layers.Input()`) to use as image input for the model. input_shape: optional shape tuple, only to be specified if `include_top` is False (otherwise the input shape has to be `(32, 32, 3)` (with `channels_last` dim ordering) or `(3, 32, 32)` (with `channels_first` dim ordering). It should have exactly 3 inputs channels, and width and height should be no smaller than 8. E.g. `(200, 200, 3)` would be one valid value. classes: optional number of classes to classify images into, only to be specified if `include_top` is True, and if no `weights` argument is specified. activation: Type of activation at the top layer. Can be one of 'softmax' or 'sigmoid'. Note that if sigmoid is used, classes must be 1. upsampling_conv: number of convolutional layers in upsampling via subpixel convolution upsampling_type: Can be one of 'upsampling', 'deconv' and 'subpixel'. Defines type of upsampling algorithm used. batchsize: Fixed batch size. This is a temporary requirement for computation of output shape in the case of Deconvolution2D layers. Parameter will be removed in next iteration of Keras, which infers output shape of deconvolution layers automatically. # Returns A Keras model instance. ''' if weights not in {None}: raise ValueError('The `weights` argument should be ' '`None` (random initialization) as no ' 'model weights are provided.') upsampling_type = upsampling_type.lower() if upsampling_type not in ['upsampling', 'deconv', 'subpixel']: raise ValueError('Parameter "upsampling_type" must be one of "upsampling", ' '"deconv" or "subpixel".') if input_shape is None: raise ValueError('For fully convolutional models, input shape must be supplied.') if type(nb_layers_per_block) is not list and nb_dense_block < 1: raise ValueError('Number of dense layers per block must be greater than 1. Argument ' 'value was %d.' % (nb_layers_per_block)) if activation not in ['softmax', 'sigmoid']: raise ValueError('activation must be one of "softmax" or "sigmoid"') if activation == 'sigmoid' and classes != 1: raise ValueError('sigmoid activation can only be used when classes = 1') # Determine proper input shape min_size = 2 ** nb_dense_block if K.image_data_format() == 'channels_first': if input_shape is not None: if ((input_shape[1] is not None and input_shape[1] < min_size) or (input_shape[2] is not None and input_shape[2] < min_size)): raise ValueError('Input size must be at least ' + str(min_size) + 'x' + str(min_size) + ', got ' '`input_shape=' + str(input_shape) + '`') else: input_shape = (classes, None, None) else: if input_shape is not None: if ((input_shape[0] is not None and input_shape[0] < min_size) or (input_shape[1] is not None and input_shape[1] < min_size)): raise ValueError('Input size must be at least ' + str(min_size) + 'x' + str(min_size) + ', got ' '`input_shape=' + str(input_shape) + '`') else: input_shape = (None, None, classes) if input_tensor is None: img_input = Input(shape=input_shape) else: if not K.is_keras_tensor(input_tensor): img_input = Input(tensor=input_tensor, shape=input_shape) else: img_input = input_tensor x = __create_fcn_dense_net(classes, img_input, include_top, nb_dense_block, growth_rate, reduction, dropout_rate, weight_decay, nb_layers_per_block, upsampling_conv, upsampling_type, init_conv_filters, input_shape, activation) # Ensure that the model takes into account # any potential predecessors of `input_tensor`. if input_tensor is not None: inputs = get_source_inputs(input_tensor) else: inputs = img_input # Create model. model = Model(inputs, x, name='fcn-densenet') return model
[ "def", "DenseNetFCN", "(", "input_shape", ",", "nb_dense_block", "=", "5", ",", "growth_rate", "=", "16", ",", "nb_layers_per_block", "=", "4", ",", "reduction", "=", "0.0", ",", "dropout_rate", "=", "0.0", ",", "weight_decay", "=", "1e-4", ",", "init_conv_f...
https://github.com/cvjena/semantic-embeddings/blob/0d4177422bafbba685fb6a0f976675864f31e09f/models/DenseNet/densenet.py#L245-L363
ctxis/CAPE
dae9fa6a254ecdbabeb7eb0d2389fa63722c1e82
utils/machine.py
python
update_conf
(machinery, args)
Writes the new machine to the relevant configuration file.
Writes the new machine to the relevant configuration file.
[ "Writes", "the", "new", "machine", "to", "the", "relevant", "configuration", "file", "." ]
def update_conf(machinery, args): """Writes the new machine to the relevant configuration file.""" path = os.path.join(CUCKOO_ROOT, "conf", "%s.conf" % machinery) lines = [] for line in open(path, "rb"): line = line.strip() if line.split("=")[0].strip() == "machines": # If there are already one or more labels then append the new # label to the list, otherwise make a new list. if line.split("=", 1)[1].strip(): line += ", %s" % args.vmname else: line += " %s" % args.vmname lines.append(line) lines += [ "", "[%s]" % args.vmname, "label = %s" % args.vmname, "platform = %s" % args.platform, "ip = %s" % args.ip, ] if args.snapshot: lines.append("snapshot = %s" % args.snapshot) if args.interface: lines.append("interface = %s" % args.interface) if args.resultserver: ip, port = args.resultserver.split(":") lines.append("resultserver_ip = %s" % ip) lines.append("resultserver_port = %s" % port) if args.tags: lines.append("tags = %s" % args.tags) open(path, "wb").write("\n".join(lines))
[ "def", "update_conf", "(", "machinery", ",", "args", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "CUCKOO_ROOT", ",", "\"conf\"", ",", "\"%s.conf\"", "%", "machinery", ")", "lines", "=", "[", "]", "for", "line", "in", "open", "(", "pat...
https://github.com/ctxis/CAPE/blob/dae9fa6a254ecdbabeb7eb0d2389fa63722c1e82/utils/machine.py#L17-L57
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_openshift/library/oc_adm_router.py
python
RoleBinding.add_user_name
(self, inc_user_name)
return True
add a username
add a username
[ "add", "a", "username" ]
def add_user_name(self, inc_user_name): ''' add a username ''' if self.user_names: # pylint: disable=no-member self.user_names.append(inc_user_name) else: self.put(RoleBinding.user_names_path, [inc_user_name]) return True
[ "def", "add_user_name", "(", "self", ",", "inc_user_name", ")", ":", "if", "self", ".", "user_names", ":", "# pylint: disable=no-member", "self", ".", "user_names", ".", "append", "(", "inc_user_name", ")", "else", ":", "self", ".", "put", "(", "RoleBinding", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_openshift/library/oc_adm_router.py#L2536-L2544
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
lib-python/2.7/idlelib/TreeWidget.py
python
TreeItem.IsExpandable
(self)
return 1
Return whether there are subitems.
Return whether there are subitems.
[ "Return", "whether", "there", "are", "subitems", "." ]
def IsExpandable(self): """Return whether there are subitems.""" return 1
[ "def", "IsExpandable", "(", "self", ")", ":", "return", "1" ]
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/lib-python/2.7/idlelib/TreeWidget.py#L331-L333
rembo10/headphones
b3199605be1ebc83a7a8feab6b1e99b64014187c
lib/requests/packages/urllib3/util/url.py
python
Url.request_uri
(self)
return uri
Absolute path including the query string.
Absolute path including the query string.
[ "Absolute", "path", "including", "the", "query", "string", "." ]
def request_uri(self): """Absolute path including the query string.""" uri = self.path or '/' if self.query is not None: uri += '?' + self.query return uri
[ "def", "request_uri", "(", "self", ")", ":", "uri", "=", "self", ".", "path", "or", "'/'", "if", "self", ".", "query", "is", "not", "None", ":", "uri", "+=", "'?'", "+", "self", ".", "query", "return", "uri" ]
https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/requests/packages/urllib3/util/url.py#L29-L36
sametmax/Django--an-app-at-a-time
99eddf12ead76e6dfbeb09ce0bae61e282e22f8a
ignore_this_directory/django/db/migrations/questioner.py
python
InteractiveMigrationQuestioner.ask_not_null_addition
(self, field_name, model_name)
return None
Adding a NOT NULL field to a model.
Adding a NOT NULL field to a model.
[ "Adding", "a", "NOT", "NULL", "field", "to", "a", "model", "." ]
def ask_not_null_addition(self, field_name, model_name): """Adding a NOT NULL field to a model.""" if not self.dry_run: choice = self._choice_input( "You are trying to add a non-nullable field '%s' to %s without a default; " "we can't do that (the database needs something to populate existing rows).\n" "Please select a fix:" % (field_name, model_name), [ ("Provide a one-off default now (will be set on all existing " "rows with a null value for this column)"), "Quit, and let me add a default in models.py", ] ) if choice == 2: sys.exit(3) else: return self._ask_default() return None
[ "def", "ask_not_null_addition", "(", "self", ",", "field_name", ",", "model_name", ")", ":", "if", "not", "self", ".", "dry_run", ":", "choice", "=", "self", ".", "_choice_input", "(", "\"You are trying to add a non-nullable field '%s' to %s without a default; \"", "\"w...
https://github.com/sametmax/Django--an-app-at-a-time/blob/99eddf12ead76e6dfbeb09ce0bae61e282e22f8a/ignore_this_directory/django/db/migrations/questioner.py#L143-L160
larryhastings/gilectomy
4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a
Lib/tkinter/__init__.py
python
Spinbox.index
(self, index)
return self.tk.call(self._w, 'index', index)
Returns the numerical index corresponding to index
Returns the numerical index corresponding to index
[ "Returns", "the", "numerical", "index", "corresponding", "to", "index" ]
def index(self, index): """Returns the numerical index corresponding to index """ return self.tk.call(self._w, 'index', index)
[ "def", "index", "(", "self", ",", "index", ")", ":", "return", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'index'", ",", "index", ")" ]
https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/tkinter/__init__.py#L3525-L3528
d2l-ai/d2l-en
39a7d4174534740b2387b0dc5eb22f409b82ee10
d2l/torch.py
python
_replace_mlm_tokens
(tokens, candidate_pred_positions, num_mlm_preds, vocab)
return mlm_input_tokens, pred_positions_and_labels
Defined in :numref:`sec_bert-dataset`
Defined in :numref:`sec_bert-dataset`
[ "Defined", "in", ":", "numref", ":", "sec_bert", "-", "dataset" ]
def _replace_mlm_tokens(tokens, candidate_pred_positions, num_mlm_preds, vocab): """Defined in :numref:`sec_bert-dataset`""" # Make a new copy of tokens for the input of a masked language model, # where the input may contain replaced '<mask>' or random tokens mlm_input_tokens = [token for token in tokens] pred_positions_and_labels = [] # Shuffle for getting 15% random tokens for prediction in the masked # language modeling task random.shuffle(candidate_pred_positions) for mlm_pred_position in candidate_pred_positions: if len(pred_positions_and_labels) >= num_mlm_preds: break masked_token = None # 80% of the time: replace the word with the '<mask>' token if random.random() < 0.8: masked_token = '<mask>' else: # 10% of the time: keep the word unchanged if random.random() < 0.5: masked_token = tokens[mlm_pred_position] # 10% of the time: replace the word with a random word else: masked_token = random.choice(vocab.idx_to_token) mlm_input_tokens[mlm_pred_position] = masked_token pred_positions_and_labels.append( (mlm_pred_position, tokens[mlm_pred_position])) return mlm_input_tokens, pred_positions_and_labels
[ "def", "_replace_mlm_tokens", "(", "tokens", ",", "candidate_pred_positions", ",", "num_mlm_preds", ",", "vocab", ")", ":", "# Make a new copy of tokens for the input of a masked language model,", "# where the input may contain replaced '<mask>' or random tokens", "mlm_input_tokens", "...
https://github.com/d2l-ai/d2l-en/blob/39a7d4174534740b2387b0dc5eb22f409b82ee10/d2l/torch.py#L2209-L2236
jython/frozen-mirror
b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99
lib-python/2.7/wsgiref/handlers.py
python
BaseHandler.write
(self, data)
write()' callable as specified by PEP 333
write()' callable as specified by PEP 333
[ "write", "()", "callable", "as", "specified", "by", "PEP", "333" ]
def write(self, data): """'write()' callable as specified by PEP 333""" assert type(data) is StringType,"write() argument must be string" if not self.status: raise AssertionError("write() before start_response()") elif not self.headers_sent: # Before the first output, send the stored headers self.bytes_sent = len(data) # make sure we know content-length self.send_headers() else: self.bytes_sent += len(data) # XXX check Content-Length and truncate if too many bytes written? self._write(data) self._flush()
[ "def", "write", "(", "self", ",", "data", ")", ":", "assert", "type", "(", "data", ")", "is", "StringType", ",", "\"write() argument must be string\"", "if", "not", "self", ".", "status", ":", "raise", "AssertionError", "(", "\"write() before start_response()\"", ...
https://github.com/jython/frozen-mirror/blob/b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99/lib-python/2.7/wsgiref/handlers.py#L201-L218
SanPen/GridCal
d3f4566d2d72c11c7e910c9d162538ef0e60df31
src/GridCal/Engine/Core/Compilers/circuit_to_bentayga.py
python
get_bentayga_pf_options
(opt: PowerFlowOptions)
return btg.PowerFlowOptions(solver=solver_type, tolerance=opt.tolerance, max_iter=opt.max_iter, retry_with_other_methods=opt.retry_with_other_methods, q_control_mode=q_control_dict[opt.control_Q])
Translate GridCal power flow options to Bentayga power flow options :param opt: :return:
Translate GridCal power flow options to Bentayga power flow options :param opt: :return:
[ "Translate", "GridCal", "power", "flow", "options", "to", "Bentayga", "power", "flow", "options", ":", "param", "opt", ":", ":", "return", ":" ]
def get_bentayga_pf_options(opt: PowerFlowOptions): """ Translate GridCal power flow options to Bentayga power flow options :param opt: :return: """ solver_dict = {SolverType.NR: btg.PowerFlowSolvers.NewtonRaphson, SolverType.DC: btg.PowerFlowSolvers.LinearDc, # SolverType.HELM: nn.NativeSolverType.HELM, # SolverType.IWAMOTO: nn.NativeSolverType.IWAMOTO, SolverType.LM: btg.PowerFlowSolvers.LevenbergMarquardt, # SolverType.LACPF: nn.NativeSolverType.LACPF, # SolverType.FASTDECOUPLED: nn.NativeSolverType.FD } q_control_dict = {ReactivePowerControlMode.NoControl: btg.QControlMode.NoControl, ReactivePowerControlMode.Direct: btg.QControlMode.Direct} if opt.solver_type in solver_dict.keys(): solver_type = solver_dict[opt.solver_type] else: solver_type = btg.PowerFlowSolvers.NewtonRaphson return btg.PowerFlowOptions(solver=solver_type, tolerance=opt.tolerance, max_iter=opt.max_iter, retry_with_other_methods=opt.retry_with_other_methods, q_control_mode=q_control_dict[opt.control_Q])
[ "def", "get_bentayga_pf_options", "(", "opt", ":", "PowerFlowOptions", ")", ":", "solver_dict", "=", "{", "SolverType", ".", "NR", ":", "btg", ".", "PowerFlowSolvers", ".", "NewtonRaphson", ",", "SolverType", ".", "DC", ":", "btg", ".", "PowerFlowSolvers", "."...
https://github.com/SanPen/GridCal/blob/d3f4566d2d72c11c7e910c9d162538ef0e60df31/src/GridCal/Engine/Core/Compilers/circuit_to_bentayga.py#L566-L593
mitogen-hq/mitogen
5b505f524a7ae170fe68613841ab92b299613d3f
mitogen/core.py
python
Latch._make_cookie
(self)
return struct.pack(self.COOKIE_FMT, self.COOKIE_MAGIC, os.getpid(), id(self), thread.get_ident())
Return a string encoding the ID of the process, instance and thread. This disambiguates legitimate wake-ups, accidental writes to the FD, and buggy internal FD sharing.
Return a string encoding the ID of the process, instance and thread. This disambiguates legitimate wake-ups, accidental writes to the FD, and buggy internal FD sharing.
[ "Return", "a", "string", "encoding", "the", "ID", "of", "the", "process", "instance", "and", "thread", ".", "This", "disambiguates", "legitimate", "wake", "-", "ups", "accidental", "writes", "to", "the", "FD", "and", "buggy", "internal", "FD", "sharing", "."...
def _make_cookie(self): """ Return a string encoding the ID of the process, instance and thread. This disambiguates legitimate wake-ups, accidental writes to the FD, and buggy internal FD sharing. """ return struct.pack(self.COOKIE_FMT, self.COOKIE_MAGIC, os.getpid(), id(self), thread.get_ident())
[ "def", "_make_cookie", "(", "self", ")", ":", "return", "struct", ".", "pack", "(", "self", ".", "COOKIE_FMT", ",", "self", ".", "COOKIE_MAGIC", ",", "os", ".", "getpid", "(", ")", ",", "id", "(", "self", ")", ",", "thread", ".", "get_ident", "(", ...
https://github.com/mitogen-hq/mitogen/blob/5b505f524a7ae170fe68613841ab92b299613d3f/mitogen/core.py#L2601-L2608
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-50/skeinforge_application/skeinforge_plugins/craft_plugins/multiply.py
python
MultiplySkein.parseLine
(self, line)
Parse a gcode line and add it to the multiply skein.
Parse a gcode line and add it to the multiply skein.
[ "Parse", "a", "gcode", "line", "and", "add", "it", "to", "the", "multiply", "skein", "." ]
def parseLine(self, line): 'Parse a gcode line and add it to the multiply skein.' splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line) if len(splitLine) < 1: return firstWord = splitLine[0] if firstWord == '(</layer>)': self.addLayer() self.distanceFeedRate.addLine(line) return elif firstWord == '(</crafting>)': self.shouldAccumulate = False if self.shouldAccumulate: self.layerLines.append(line) return self.distanceFeedRate.addLine(line)
[ "def", "parseLine", "(", "self", ",", "line", ")", ":", "splitLine", "=", "gcodec", ".", "getSplitLineBeforeBracketSemicolon", "(", "line", ")", "if", "len", "(", "splitLine", ")", "<", "1", ":", "return", "firstWord", "=", "splitLine", "[", "0", "]", "i...
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-50/skeinforge_application/skeinforge_plugins/craft_plugins/multiply.py#L232-L247
cjdrake/pyeda
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
pyeda/boolalg/expr.py
python
Expression.encode_cnf
(self)
Encode as a compact CNF.
Encode as a compact CNF.
[ "Encode", "as", "a", "compact", "CNF", "." ]
def encode_cnf(self): """Encode as a compact CNF.""" if self.is_cnf(): return self._encode_cnf() else: raise ValueError("expected a CNF expression")
[ "def", "encode_cnf", "(", "self", ")", ":", "if", "self", ".", "is_cnf", "(", ")", ":", "return", "self", ".", "_encode_cnf", "(", ")", "else", ":", "raise", "ValueError", "(", "\"expected a CNF expression\"", ")" ]
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L934-L939
seantis/seantis-questionnaire
698c77b3d707635f50bcd86e7f1c94e94061b0f5
questionnaire/views.py
python
show_questionnaire
(request, runinfo, errors={})
return r
Return the QuestionSet template Also add the javascript dependency code.
Return the QuestionSet template
[ "Return", "the", "QuestionSet", "template" ]
def show_questionnaire(request, runinfo, errors={}): """ Return the QuestionSet template Also add the javascript dependency code. """ request.runinfo = runinfo if request.GET.get('show_all') == '1': # for debugging purposes. questions = runinfo.questionset.questionnaire.questions() else: questions = runinfo.questionset.questions() show_all = request.GET.get('show_all') == '1' questionset = runinfo.questionset questions = questionset.questionnaire.questions() if show_all \ else questionset.questions() qlist = [] jsinclude = [] # js files to include cssinclude = [] # css files to include jstriggers = [] qvalues = {} # initialize qvalues cookiedict = runinfo.get_cookiedict() for k, v in cookiedict.items(): qvalues[k] = v substitute_answer(qvalues, runinfo.questionset) for question in questions: # if we got here the questionset will at least contain one question # which passes, so this is all we need to check for question_visible = question_satisfies_checks(question, runinfo) \ or show_all Type = question.get_type() _qnum, _qalpha = split_numal(question.number) qdict = { 'css_style': '' if question_visible else 'display:none;', 'template': 'questionnaire/%s.html' % (Type), 'qnum': _qnum, 'qalpha': _qalpha, 'qtype': Type, 'qnum_class': (_qnum % 2 == 0) and " qeven" or " qodd", 'qalpha_class': _qalpha and ( ord(_qalpha[-1]) % 2 and ' alodd' or ' aleven' ) or '', } # substitute answer texts substitute_answer(qvalues, question) # add javascript dependency checks cd = question.getcheckdict() depon = cd.get('requiredif', None) or cd.get('dependent', None) if depon: # extra args to BooleanParser are not required for toString parser = BooleanParser(dep_check) qdict['checkstring'] = ' checks="%s"' % parser.toString(depon) jstriggers.append('qc_%s' % question.number) if 'default' in cd and question.number not in cookiedict: qvalues[question.number] = cd['default'] if Type in QuestionProcessors: qdict.update(QuestionProcessors[Type](request, question)) if 'jsinclude' in qdict: if qdict['jsinclude'] not in jsinclude: jsinclude.extend(qdict['jsinclude']) if 'cssinclude' in qdict: if qdict['cssinclude'] not in cssinclude: cssinclude.extend(qdict['jsinclude']) if 'jstriggers' in qdict: jstriggers.extend(qdict['jstriggers']) if 'qvalue' in qdict and question.number not in cookiedict: qvalues[question.number] = qdict['qvalue'] qlist.append((question, qdict)) try: has_progress = settings.QUESTIONNAIRE_PROGRESS in ('async', 'default') async_progress = settings.QUESTIONNAIRE_PROGRESS == 'async' except AttributeError: has_progress = True async_progress = False if has_progress: if async_progress: progress = cache.get('progress' + runinfo.random, 1) else: progress = get_progress(runinfo) else: progress = 0 if request.POST: for k, v in request.POST.items(): if k.startswith("question_"): s = k.split("_") if len(s) == 4: qvalues[s[1] + '_' + v] = '1' # evaluates true in JS elif len(s) == 3 and s[2] == 'comment': qvalues[s[1] + '_' + s[2]] = v else: qvalues[s[1]] = v if use_session: prev_url = reverse('redirect_to_prev_questionnaire') else: prev_url = 'javascript:history.back();' r = r2r( "questionnaire/questionset.html", request, questionset=runinfo.questionset, runinfo=runinfo, errors=errors, qlist=qlist, progress=progress, triggers=jstriggers, qvalues=qvalues, jsinclude=jsinclude, cssinclude=cssinclude, async_progress=async_progress, async_url=reverse('progress', args=[runinfo.random]), prev_url=prev_url, ) r['Cache-Control'] = 'no-cache' r['Expires'] = "Thu, 24 Jan 1980 00:00:00 GMT" return r
[ "def", "show_questionnaire", "(", "request", ",", "runinfo", ",", "errors", "=", "{", "}", ")", ":", "request", ".", "runinfo", "=", "runinfo", "if", "request", ".", "GET", ".", "get", "(", "'show_all'", ")", "==", "'1'", ":", "# for debugging purposes.", ...
https://github.com/seantis/seantis-questionnaire/blob/698c77b3d707635f50bcd86e7f1c94e94061b0f5/questionnaire/views.py#L575-L704
nosmokingbandit/watcher
dadacd21a5790ee609058a98a17fcc8954d24439
lib/sqlalchemy/sql/selectable.py
python
GenerativeSelect._simple_int_limit
(self)
return isinstance(self._limit_clause, _OffsetLimitParam)
True if the LIMIT clause is a simple integer, False if it is not present or is a SQL expression.
True if the LIMIT clause is a simple integer, False if it is not present or is a SQL expression.
[ "True", "if", "the", "LIMIT", "clause", "is", "a", "simple", "integer", "False", "if", "it", "is", "not", "present", "or", "is", "a", "SQL", "expression", "." ]
def _simple_int_limit(self): """True if the LIMIT clause is a simple integer, False if it is not present or is a SQL expression. """ return isinstance(self._limit_clause, _OffsetLimitParam)
[ "def", "_simple_int_limit", "(", "self", ")", ":", "return", "isinstance", "(", "self", ".", "_limit_clause", ",", "_OffsetLimitParam", ")" ]
https://github.com/nosmokingbandit/watcher/blob/dadacd21a5790ee609058a98a17fcc8954d24439/lib/sqlalchemy/sql/selectable.py#L2077-L2081
yao8839836/kg-bert
0b8f625108efcb9b43603b6840f2548ff3d3c973
run_bert_triple_classifier.py
python
KGProcessor.get_train_examples
(self, data_dir)
return self._create_examples( self._read_tsv(os.path.join(data_dir, "train.tsv")), "train", data_dir)
See base class.
See base class.
[ "See", "base", "class", "." ]
def get_train_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "train.tsv")), "train", data_dir)
[ "def", "get_train_examples", "(", "self", ",", "data_dir", ")", ":", "return", "self", ".", "_create_examples", "(", "self", ".", "_read_tsv", "(", "os", ".", "path", ".", "join", "(", "data_dir", ",", "\"train.tsv\"", ")", ")", ",", "\"train\"", ",", "d...
https://github.com/yao8839836/kg-bert/blob/0b8f625108efcb9b43603b6840f2548ff3d3c973/run_bert_triple_classifier.py#L117-L120
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter8-Regression/venv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/distlib/database.py
python
InstalledDistribution.check_installed_files
(self)
return mismatches
Checks that the hashes and sizes of the files in ``RECORD`` are matched by the files themselves. Returns a (possibly empty) list of mismatches. Each entry in the mismatch list will be a tuple consisting of the path, 'exists', 'size' or 'hash' according to what didn't match (existence is checked first, then size, then hash), the expected value and the actual value.
Checks that the hashes and sizes of the files in ``RECORD`` are matched by the files themselves. Returns a (possibly empty) list of mismatches. Each entry in the mismatch list will be a tuple consisting of the path, 'exists', 'size' or 'hash' according to what didn't match (existence is checked first, then size, then hash), the expected value and the actual value.
[ "Checks", "that", "the", "hashes", "and", "sizes", "of", "the", "files", "in", "RECORD", "are", "matched", "by", "the", "files", "themselves", ".", "Returns", "a", "(", "possibly", "empty", ")", "list", "of", "mismatches", ".", "Each", "entry", "in", "th...
def check_installed_files(self): """ Checks that the hashes and sizes of the files in ``RECORD`` are matched by the files themselves. Returns a (possibly empty) list of mismatches. Each entry in the mismatch list will be a tuple consisting of the path, 'exists', 'size' or 'hash' according to what didn't match (existence is checked first, then size, then hash), the expected value and the actual value. """ mismatches = [] base = os.path.dirname(self.path) record_path = self.get_distinfo_file('RECORD') for path, hash_value, size in self.list_installed_files(): if not os.path.isabs(path): path = os.path.join(base, path) if path == record_path: continue if not os.path.exists(path): mismatches.append((path, 'exists', True, False)) elif os.path.isfile(path): actual_size = str(os.path.getsize(path)) if size and actual_size != size: mismatches.append((path, 'size', size, actual_size)) elif hash_value: if '=' in hash_value: hasher = hash_value.split('=', 1)[0] else: hasher = None with open(path, 'rb') as f: actual_hash = self.get_hash(f.read(), hasher) if actual_hash != hash_value: mismatches.append((path, 'hash', hash_value, actual_hash)) return mismatches
[ "def", "check_installed_files", "(", "self", ")", ":", "mismatches", "=", "[", "]", "base", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "path", ")", "record_path", "=", "self", ".", "get_distinfo_file", "(", "'RECORD'", ")", "for", "path", ...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter8-Regression/venv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/distlib/database.py#L697-L730
roclark/sportsipy
c19f545d3376d62ded6304b137dc69238ac620a9
sportsipy/mlb/boxscore.py
python
Boxscore.home_on_base_percentage
(self)
return self._home_on_base_percentage
Returns a ``float`` of the percentage of at bats that result in the batter getting on base.
Returns a ``float`` of the percentage of at bats that result in the batter getting on base.
[ "Returns", "a", "float", "of", "the", "percentage", "of", "at", "bats", "that", "result", "in", "the", "batter", "getting", "on", "base", "." ]
def home_on_base_percentage(self): """ Returns a ``float`` of the percentage of at bats that result in the batter getting on base. """ return self._home_on_base_percentage
[ "def", "home_on_base_percentage", "(", "self", ")", ":", "return", "self", ".", "_home_on_base_percentage" ]
https://github.com/roclark/sportsipy/blob/c19f545d3376d62ded6304b137dc69238ac620a9/sportsipy/mlb/boxscore.py#L1411-L1416
ReactionMechanismGenerator/RMG-Py
2b7baf51febf27157def58fb3f6cee03fb6a684c
rmgpy/data/kinetics/library.py
python
KineticsLibrary.save_entry
(self, f, entry)
return save_entry(f, entry)
Write the given `entry` in the kinetics library to the file object `f`.
Write the given `entry` in the kinetics library to the file object `f`.
[ "Write", "the", "given", "entry", "in", "the", "kinetics", "library", "to", "the", "file", "object", "f", "." ]
def save_entry(self, f, entry): """ Write the given `entry` in the kinetics library to the file object `f`. """ return save_entry(f, entry)
[ "def", "save_entry", "(", "self", ",", "f", ",", "entry", ")", ":", "return", "save_entry", "(", "f", ",", "entry", ")" ]
https://github.com/ReactionMechanismGenerator/RMG-Py/blob/2b7baf51febf27157def58fb3f6cee03fb6a684c/rmgpy/data/kinetics/library.py#L600-L604
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
examples/research_projects/quantization-qdqbert/quant_trainer.py
python
set_quantizer_by_name
(model, names, **kwargs)
Set quantizer attributes for layers where name contains a substring in names.
Set quantizer attributes for layers where name contains a substring in names.
[ "Set", "quantizer", "attributes", "for", "layers", "where", "name", "contains", "a", "substring", "in", "names", "." ]
def set_quantizer_by_name(model, names, **kwargs): """Set quantizer attributes for layers where name contains a substring in names.""" for name, mod in model.named_modules(): if hasattr(mod, "_input_quantizer") or hasattr(mod, "_weight_quantizer"): for n in names: if re.search(n, name): set_quantizers(name, mod, **kwargs) elif name.endswith("_quantizer"): for n in names: if re.search(n, name): s = f"Warning: changing {name:{name_width}}" for k, v in kwargs.items(): s += f" {k}={v}" setattr(mod, k, v) logger.info(s)
[ "def", "set_quantizer_by_name", "(", "model", ",", "names", ",", "*", "*", "kwargs", ")", ":", "for", "name", ",", "mod", "in", "model", ".", "named_modules", "(", ")", ":", "if", "hasattr", "(", "mod", ",", "\"_input_quantizer\"", ")", "or", "hasattr", ...
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/examples/research_projects/quantization-qdqbert/quant_trainer.py#L288-L303
trailofbits/manticore
b050fdf0939f6c63f503cdf87ec0ab159dd41159
manticore/platforms/linux.py
python
Linux.sys_chmod
(self, filename, mode)
return 0
Modify file permissions :return 0 on success
Modify file permissions :return 0 on success
[ "Modify", "file", "permissions", ":", "return", "0", "on", "success" ]
def sys_chmod(self, filename, mode) -> int: """ Modify file permissions :return 0 on success """ filename = self.current.read_string(filename) try: os.chmod(filename, mode) except OSError as e: return -e.errno return 0
[ "def", "sys_chmod", "(", "self", ",", "filename", ",", "mode", ")", "->", "int", ":", "filename", "=", "self", ".", "current", ".", "read_string", "(", "filename", ")", "try", ":", "os", ".", "chmod", "(", "filename", ",", "mode", ")", "except", "OSE...
https://github.com/trailofbits/manticore/blob/b050fdf0939f6c63f503cdf87ec0ab159dd41159/manticore/platforms/linux.py#L3262-L3273
openstack/python-neutronclient
517bef2c5454dde2eba5cc2194ee857be6be7164
neutronclient/v2_0/client.py
python
Client.create_flavor
(self, body=None)
return self.post(self.flavors_path, body=body)
Creates a new Neutron service flavor.
Creates a new Neutron service flavor.
[ "Creates", "a", "new", "Neutron", "service", "flavor", "." ]
def create_flavor(self, body=None): """Creates a new Neutron service flavor.""" return self.post(self.flavors_path, body=body)
[ "def", "create_flavor", "(", "self", ",", "body", "=", "None", ")", ":", "return", "self", ".", "post", "(", "self", ".", "flavors_path", ",", "body", "=", "body", ")" ]
https://github.com/openstack/python-neutronclient/blob/517bef2c5454dde2eba5cc2194ee857be6be7164/neutronclient/v2_0/client.py#L2053-L2055
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/prompt_toolkit/layout/containers.py
python
is_container
(value)
return False
Checks whether the given value is a container object (for use in assert statements).
Checks whether the given value is a container object (for use in assert statements).
[ "Checks", "whether", "the", "given", "value", "is", "a", "container", "object", "(", "for", "use", "in", "assert", "statements", ")", "." ]
def is_container(value): """ Checks whether the given value is a container object (for use in assert statements). """ if isinstance(value, Container): return True if hasattr(value, '__pt_container__'): return is_container(value.__pt_container__()) return False
[ "def", "is_container", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "Container", ")", ":", "return", "True", "if", "hasattr", "(", "value", ",", "'__pt_container__'", ")", ":", "return", "is_container", "(", "value", ".", "__pt_container__"...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/prompt_toolkit/layout/containers.py#L2266-L2275
apache/libcloud
90971e17bfd7b6bb97b2489986472c531cc8e140
libcloud/dns/drivers/godaddy.py
python
GoDaddyDNSDriver.ex_check_availability
(self, domain, for_transfer=False)
return GoDaddyAvailability( domain=result["domain"], available=result["available"], price=result["price"], currency=result["currency"], period=result["period"], )
Check the availability of the domain :param domain: the domain name e.g. wazzlewobbleflooble.com :type domain: ``str`` :param for_transfer: Check if domain is available for transfer :type for_transfer: ``bool`` :rtype: `list` of :class:`GoDaddyAvailability`
Check the availability of the domain
[ "Check", "the", "availability", "of", "the", "domain" ]
def ex_check_availability(self, domain, for_transfer=False): """ Check the availability of the domain :param domain: the domain name e.g. wazzlewobbleflooble.com :type domain: ``str`` :param for_transfer: Check if domain is available for transfer :type for_transfer: ``bool`` :rtype: `list` of :class:`GoDaddyAvailability` """ result = self.connection.request( "/v1/domains/available", method="GET", params={"domain": domain, "forTransfer": str(for_transfer)}, ).object return GoDaddyAvailability( domain=result["domain"], available=result["available"], price=result["price"], currency=result["currency"], period=result["period"], )
[ "def", "ex_check_availability", "(", "self", ",", "domain", ",", "for_transfer", "=", "False", ")", ":", "result", "=", "self", ".", "connection", ".", "request", "(", "\"/v1/domains/available\"", ",", "method", "=", "\"GET\"", ",", "params", "=", "{", "\"do...
https://github.com/apache/libcloud/blob/90971e17bfd7b6bb97b2489986472c531cc8e140/libcloud/dns/drivers/godaddy.py#L318-L341
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/pip/_vendor/cachecontrol/caches/redis_cache.py
python
RedisCache.__init__
(self, conn)
[]
def __init__(self, conn): self.conn = conn
[ "def", "__init__", "(", "self", ",", "conn", ")", ":", "self", ".", "conn", "=", "conn" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/pip/_vendor/cachecontrol/caches/redis_cache.py#L18-L19
NervanaSystems/ngraph-python
ac032c83c7152b615a9ad129d54d350f9d6a2986
ngraph/frontends/tensorflow/tf_importer/ops_bridge.py
python
OpsBridge.Range
(self, tf_node, inputs)
return ng.constant(range_val, make_pos_axes(range_val.shape)).named(tf_node.name)
Creates a sequence of integers. Arguments: tf_node: NodeDef object, the tensorflow node to convert. inputs: List of ngraph Ops as inputs to this node. Returns: A ngraph Op corresponding to the tensorflow node. Inputs to tf_node: start, limit, delta, name
Creates a sequence of integers.
[ "Creates", "a", "sequence", "of", "integers", "." ]
def Range(self, tf_node, inputs): """ Creates a sequence of integers. Arguments: tf_node: NodeDef object, the tensorflow node to convert. inputs: List of ngraph Ops as inputs to this node. Returns: A ngraph Op corresponding to the tensorflow node. Inputs to tf_node: start, limit, delta, name """ # get inputs start, limit, delta = inputs # get range try: range_val = np.arange(start.const, limit.const, delta.const) except: raise NotImplementedError("[NON-NATIVE] Input to `Range` must all " "be integer, dynamic allocation is not " "supported.") # return return ng.constant(range_val, make_pos_axes(range_val.shape)).named(tf_node.name)
[ "def", "Range", "(", "self", ",", "tf_node", ",", "inputs", ")", ":", "# get inputs", "start", ",", "limit", ",", "delta", "=", "inputs", "# get range", "try", ":", "range_val", "=", "np", ".", "arange", "(", "start", ".", "const", ",", "limit", ".", ...
https://github.com/NervanaSystems/ngraph-python/blob/ac032c83c7152b615a9ad129d54d350f9d6a2986/ngraph/frontends/tensorflow/tf_importer/ops_bridge.py#L558-L585
kupferlauncher/kupfer
1c1e9bcbce05a82f503f68f8b3955c20b02639b3
waflib/Tools/c_preproc.py
python
c_parser.start
(self, node, env)
Preprocess a source file to obtain the dependencies, which are accumulated to :py:attr:`waflib.Tools.c_preproc.c_parser.nodes` and :py:attr:`waflib.Tools.c_preproc.c_parser.names`. :param node: source file :type node: :py:class:`waflib.Node.Node` :param env: config set containing additional defines to take into account :type env: :py:class:`waflib.ConfigSet.ConfigSet`
Preprocess a source file to obtain the dependencies, which are accumulated to :py:attr:`waflib.Tools.c_preproc.c_parser.nodes` and :py:attr:`waflib.Tools.c_preproc.c_parser.names`.
[ "Preprocess", "a", "source", "file", "to", "obtain", "the", "dependencies", "which", "are", "accumulated", "to", ":", "py", ":", "attr", ":", "waflib", ".", "Tools", ".", "c_preproc", ".", "c_parser", ".", "nodes", "and", ":", "py", ":", "attr", ":", "...
def start(self, node, env): """ Preprocess a source file to obtain the dependencies, which are accumulated to :py:attr:`waflib.Tools.c_preproc.c_parser.nodes` and :py:attr:`waflib.Tools.c_preproc.c_parser.names`. :param node: source file :type node: :py:class:`waflib.Node.Node` :param env: config set containing additional defines to take into account :type env: :py:class:`waflib.ConfigSet.ConfigSet` """ Logs.debug('preproc: scanning %s (in %s)', node.name, node.parent.name) self.current_file = node self.addlines(node) # macros may be defined on the command-line, so they must be parsed as if they were part of the file if env.DEFINES: lst = format_defines(env.DEFINES) lst.reverse() self.lines.extend([('define', x) for x in lst]) while self.lines: (token, line) = self.lines.pop() if token == POPFILE: self.count_files -= 1 self.currentnode_stack.pop() continue try: state = self.state # make certain we define the state if we are about to enter in an if block if token[:2] == 'if': state.append(undefined) elif token == 'endif': state.pop() # skip lines when in a dead 'if' branch, wait for the endif if token[0] != 'e': if skipped in self.state or ignored in self.state: continue if token == 'if': ret = eval_macro(tokenize(line), self.defs) if ret: state[-1] = accepted else: state[-1] = ignored elif token == 'ifdef': m = re_mac.match(line) if m and m.group() in self.defs: state[-1] = accepted else: state[-1] = ignored elif token == 'ifndef': m = re_mac.match(line) if m and m.group() in self.defs: state[-1] = ignored else: state[-1] = accepted elif token == 'include' or token == 'import': (kind, inc) = extract_include(line, self.defs) self.current_file = self.tryfind(inc, kind, env) if token == 'import': self.ban_includes.add(self.current_file) elif token == 'elif': if state[-1] == accepted: state[-1] = skipped elif state[-1] == ignored: if eval_macro(tokenize(line), self.defs): state[-1] = accepted elif token == 'else': if state[-1] == accepted: state[-1] = skipped elif state[-1] == ignored: state[-1] = accepted elif token == 'define': try: self.defs[self.define_name(line)] = line except AttributeError: raise PreprocError('Invalid define line %r' % line) elif token == 'undef': m = re_mac.match(line) if m and m.group() in self.defs: self.defs.__delitem__(m.group()) #print "undef %s" % name elif token == 'pragma': if re_pragma_once.match(line.lower()): self.ban_includes.add(self.current_file) except Exception as e: if Logs.verbose: Logs.debug('preproc: line parsing failed (%s): %s %s', e, line, traceback.format_exc())
[ "def", "start", "(", "self", ",", "node", ",", "env", ")", ":", "Logs", ".", "debug", "(", "'preproc: scanning %s (in %s)'", ",", "node", ".", "name", ",", "node", ".", "parent", ".", "name", ")", "self", ".", "current_file", "=", "node", "self", ".", ...
https://github.com/kupferlauncher/kupfer/blob/1c1e9bcbce05a82f503f68f8b3955c20b02639b3/waflib/Tools/c_preproc.py#L969-L1060
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/idlelib/Debugger.py
python
StackViewer.popup_event
(self, event)
override base method
override base method
[ "override", "base", "method" ]
def popup_event(self, event): "override base method" if self.stack: return ScrolledList.popup_event(self, event)
[ "def", "popup_event", "(", "self", ",", "event", ")", ":", "if", "self", ".", "stack", ":", "return", "ScrolledList", ".", "popup_event", "(", "self", ",", "event", ")" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/idlelib/Debugger.py#L364-L367
ry/tensorflow-resnet
ccb9cc8cc2cc7021c67e7df4a70f96faab9553c5
image_processing.py
python
distort_color
(image, thread_id=0, scope=None)
Distort the color of the image. Each color distortion is non-commutative and thus ordering of the color ops matters. Ideally we would randomly permute the ordering of the color ops. Rather then adding that level of complication, we select a distinct ordering of color ops for each preprocessing thread. Args: image: Tensor containing single image. thread_id: preprocessing thread ID. scope: Optional scope for op_scope. Returns: color-distorted image
Distort the color of the image.
[ "Distort", "the", "color", "of", "the", "image", "." ]
def distort_color(image, thread_id=0, scope=None): """Distort the color of the image. Each color distortion is non-commutative and thus ordering of the color ops matters. Ideally we would randomly permute the ordering of the color ops. Rather then adding that level of complication, we select a distinct ordering of color ops for each preprocessing thread. Args: image: Tensor containing single image. thread_id: preprocessing thread ID. scope: Optional scope for op_scope. Returns: color-distorted image """ with tf.op_scope([image], scope, 'distort_color'): color_ordering = thread_id % 2 if color_ordering == 0: image = tf.image.random_brightness(image, max_delta=32. / 255.) image = tf.image.random_saturation(image, lower=0.5, upper=1.5) image = tf.image.random_hue(image, max_delta=0.2) image = tf.image.random_contrast(image, lower=0.5, upper=1.5) elif color_ordering == 1: image = tf.image.random_brightness(image, max_delta=32. / 255.) image = tf.image.random_contrast(image, lower=0.5, upper=1.5) image = tf.image.random_saturation(image, lower=0.5, upper=1.5) image = tf.image.random_hue(image, max_delta=0.2) # The random_* ops do not necessarily clamp. image = tf.clip_by_value(image, 0.0, 1.0) return image
[ "def", "distort_color", "(", "image", ",", "thread_id", "=", "0", ",", "scope", "=", "None", ")", ":", "with", "tf", ".", "op_scope", "(", "[", "image", "]", ",", "scope", ",", "'distort_color'", ")", ":", "color_ordering", "=", "thread_id", "%", "2", ...
https://github.com/ry/tensorflow-resnet/blob/ccb9cc8cc2cc7021c67e7df4a70f96faab9553c5/image_processing.py#L129-L160
nltk/nltk
3f74ac55681667d7ef78b664557487145f51eb02
nltk/metrics/association.py
python
NgramAssocMeasures._marginals
(*contingency)
Calculates values of contingency table marginals from its values.
Calculates values of contingency table marginals from its values.
[ "Calculates", "values", "of", "contingency", "table", "marginals", "from", "its", "values", "." ]
def _marginals(*contingency): """Calculates values of contingency table marginals from its values.""" raise NotImplementedError( "The contingency table is not available" "in the general ngram case" )
[ "def", "_marginals", "(", "*", "contingency", ")", ":", "raise", "NotImplementedError", "(", "\"The contingency table is not available\"", "\"in the general ngram case\"", ")" ]
https://github.com/nltk/nltk/blob/3f74ac55681667d7ef78b664557487145f51eb02/nltk/metrics/association.py#L76-L80
LuxCoreRender/BlendLuxCore
bf31ca58501d54c02acd97001b6db7de81da7cbf
properties/material.py
python
LuxCoreMaterialPreviewProps.update_preview
(self, context)
[]
def update_preview(self, context): material = self.id_data # A trick to force a material preview refresh (update_tag() does not work) material.preview_render_type = material.preview_render_type
[ "def", "update_preview", "(", "self", ",", "context", ")", ":", "material", "=", "self", ".", "id_data", "# A trick to force a material preview refresh (update_tag() does not work)", "material", ".", "preview_render_type", "=", "material", ".", "preview_render_type" ]
https://github.com/LuxCoreRender/BlendLuxCore/blob/bf31ca58501d54c02acd97001b6db7de81da7cbf/properties/material.py#L9-L12
cbrgm/telegram-robot-rss
58fe98de427121fdc152c8df0721f1891174e6c9
venv/lib/python2.7/site-packages/future/backports/email/message.py
python
Message.get_content_charset
(self, failobj=None)
return charset.lower()
Return the charset parameter of the Content-Type header. The returned string is always coerced to lower case. If there is no Content-Type header, or if that header has no charset parameter, failobj is returned.
Return the charset parameter of the Content-Type header.
[ "Return", "the", "charset", "parameter", "of", "the", "Content", "-", "Type", "header", "." ]
def get_content_charset(self, failobj=None): """Return the charset parameter of the Content-Type header. The returned string is always coerced to lower case. If there is no Content-Type header, or if that header has no charset parameter, failobj is returned. """ missing = object() charset = self.get_param('charset', missing) if charset is missing: return failobj if isinstance(charset, tuple): # RFC 2231 encoded, so decode it, and it better end up as ascii. pcharset = charset[0] or 'us-ascii' try: # LookupError will be raised if the charset isn't known to # Python. UnicodeError will be raised if the encoded text # contains a character not in the charset. as_bytes = charset[2].encode('raw-unicode-escape') charset = str(as_bytes, pcharset) except (LookupError, UnicodeError): charset = charset[2] # charset characters must be in us-ascii range try: charset.encode('us-ascii') except UnicodeError: return failobj # RFC 2046, $4.1.2 says charsets are not case sensitive return charset.lower()
[ "def", "get_content_charset", "(", "self", ",", "failobj", "=", "None", ")", ":", "missing", "=", "object", "(", ")", "charset", "=", "self", ".", "get_param", "(", "'charset'", ",", "missing", ")", "if", "charset", "is", "missing", ":", "return", "failo...
https://github.com/cbrgm/telegram-robot-rss/blob/58fe98de427121fdc152c8df0721f1891174e6c9/venv/lib/python2.7/site-packages/future/backports/email/message.py#L833-L861
opendistro-for-elasticsearch/sample-code
94abc715845d17fb4c24e70c7c328b2d4da0d581
es_sink/es_sink/line_buffer.py
python
LineBuffer._dict_to_string
(dic)
Encode a dict as a string. Silently swallows errors
Encode a dict as a string. Silently swallows errors
[ "Encode", "a", "dict", "as", "a", "string", ".", "Silently", "swallows", "errors" ]
def _dict_to_string(dic): ''' Encode a dict as a string. Silently swallows errors ''' try: line = json.JSONEncoder().encode(dic) return line except UnicodeDecodeError as exc: msg = "unicode problem {}, skipping line: {}" print(msg.format(str(exc), dic)) return ''
[ "def", "_dict_to_string", "(", "dic", ")", ":", "try", ":", "line", "=", "json", ".", "JSONEncoder", "(", ")", ".", "encode", "(", "dic", ")", "return", "line", "except", "UnicodeDecodeError", "as", "exc", ":", "msg", "=", "\"unicode problem {}, skipping lin...
https://github.com/opendistro-for-elasticsearch/sample-code/blob/94abc715845d17fb4c24e70c7c328b2d4da0d581/es_sink/es_sink/line_buffer.py#L38-L46
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
lib-python/2.7/SimpleXMLRPCServer.py
python
list_public_methods
(obj)
return [member for member in dir(obj) if not member.startswith('_') and hasattr(getattr(obj, member), '__call__')]
Returns a list of attribute strings, found in the specified object, which represent callable attributes
Returns a list of attribute strings, found in the specified object, which represent callable attributes
[ "Returns", "a", "list", "of", "attribute", "strings", "found", "in", "the", "specified", "object", "which", "represent", "callable", "attributes" ]
def list_public_methods(obj): """Returns a list of attribute strings, found in the specified object, which represent callable attributes""" return [member for member in dir(obj) if not member.startswith('_') and hasattr(getattr(obj, member), '__call__')]
[ "def", "list_public_methods", "(", "obj", ")", ":", "return", "[", "member", "for", "member", "in", "dir", "(", "obj", ")", "if", "not", "member", ".", "startswith", "(", "'_'", ")", "and", "hasattr", "(", "getattr", "(", "obj", ",", "member", ")", "...
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/lib-python/2.7/SimpleXMLRPCServer.py#L139-L145
psychopy/psychopy
01b674094f38d0e0bd51c45a6f66f671d7041696
psychopy/visual/pie.py
python
Pie.setRadius
(self, end, operation='', log=None)
Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message
Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message
[ "Usually", "you", "can", "use", "stim", ".", "attribute", "=", "value", "syntax", "instead", "but", "use", "this", "method", "if", "you", "need", "to", "suppress", "the", "log", "message" ]
def setRadius(self, end, operation='', log=None): """Usually you can use 'stim.attribute = value' syntax instead, but use this method if you need to suppress the log message """ setAttribute(self, 'radius', end, log, operation)
[ "def", "setRadius", "(", "self", ",", "end", ",", "operation", "=", "''", ",", "log", "=", "None", ")", ":", "setAttribute", "(", "self", ",", "'radius'", ",", "end", ",", "log", ",", "operation", ")" ]
https://github.com/psychopy/psychopy/blob/01b674094f38d0e0bd51c45a6f66f671d7041696/psychopy/visual/pie.py#L237-L241
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/packages/site-packages/sqlalchemy/dialects/postgresql/json.py
python
JSON.__init__
(self, none_as_null=False)
Construct a :class:`.JSON` type. :param none_as_null: if True, persist the value ``None`` as a SQL NULL value, not the JSON encoding of ``null``. Note that when this flag is False, the :func:`.null` construct can still be used to persist a NULL value:: from sqlalchemy import null conn.execute(table.insert(), data=null()) .. versionchanged:: 0.9.8 - Added ``none_as_null``, and :func:`.null` is now supported in order to persist a NULL value.
Construct a :class:`.JSON` type.
[ "Construct", "a", ":", "class", ":", ".", "JSON", "type", "." ]
def __init__(self, none_as_null=False): """Construct a :class:`.JSON` type. :param none_as_null: if True, persist the value ``None`` as a SQL NULL value, not the JSON encoding of ``null``. Note that when this flag is False, the :func:`.null` construct can still be used to persist a NULL value:: from sqlalchemy import null conn.execute(table.insert(), data=null()) .. versionchanged:: 0.9.8 - Added ``none_as_null``, and :func:`.null` is now supported in order to persist a NULL value. """ self.none_as_null = none_as_null
[ "def", "__init__", "(", "self", ",", "none_as_null", "=", "False", ")", ":", "self", ".", "none_as_null", "=", "none_as_null" ]
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/packages/site-packages/sqlalchemy/dialects/postgresql/json.py#L168-L183
aneisch/home-assistant-config
86e381fde9609cb8871c439c433c12989e4e225d
custom_components/localtuya/pytuya/__init__.py
python
ContextualLogger.__init__
(self)
Initialize a new ContextualLogger.
Initialize a new ContextualLogger.
[ "Initialize", "a", "new", "ContextualLogger", "." ]
def __init__(self): """Initialize a new ContextualLogger.""" self._logger = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "_logger", "=", "None" ]
https://github.com/aneisch/home-assistant-config/blob/86e381fde9609cb8871c439c433c12989e4e225d/custom_components/localtuya/pytuya/__init__.py#L121-L123
Dentosal/python-sc2
e816cce83772d1aee1291b86b300b69405aa96b4
sc2/bot_ai.py
python
BotAI._prepare_first_step
(self)
First step extra preparations. Must not be called before _prepare_step.
First step extra preparations. Must not be called before _prepare_step.
[ "First", "step", "extra", "preparations", ".", "Must", "not", "be", "called", "before", "_prepare_step", "." ]
def _prepare_first_step(self): """First step extra preparations. Must not be called before _prepare_step.""" if self.townhalls: self._game_info.player_start_location = self.townhalls.first.position self._game_info.map_ramps = self._game_info._find_ramps()
[ "def", "_prepare_first_step", "(", "self", ")", ":", "if", "self", ".", "townhalls", ":", "self", ".", "_game_info", ".", "player_start_location", "=", "self", ".", "townhalls", ".", "first", ".", "position", "self", ".", "_game_info", ".", "map_ramps", "=",...
https://github.com/Dentosal/python-sc2/blob/e816cce83772d1aee1291b86b300b69405aa96b4/sc2/bot_ai.py#L512-L516
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/future/backports/urllib/response.py
python
addbase.__repr__
(self)
return '<%s at %r whose fp = %r>' % (self.__class__.__name__, id(self), self.fp)
[]
def __repr__(self): return '<%s at %r whose fp = %r>' % (self.__class__.__name__, id(self), self.fp)
[ "def", "__repr__", "(", "self", ")", ":", "return", "'<%s at %r whose fp = %r>'", "%", "(", "self", ".", "__class__", ".", "__name__", ",", "id", "(", "self", ")", ",", "self", ".", "fp", ")" ]
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/future/backports/urllib/response.py#L37-L39
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
openedx/core/djangoapps/content/course_overviews/models.py
python
_invalidate_overview_cache
(**kwargs)
Invalidate the course overview request cache.
Invalidate the course overview request cache.
[ "Invalidate", "the", "course", "overview", "request", "cache", "." ]
def _invalidate_overview_cache(**kwargs): # pylint: disable=unused-argument """ Invalidate the course overview request cache. """ RequestCache('course_overview').clear()
[ "def", "_invalidate_overview_cache", "(", "*", "*", "kwargs", ")", ":", "# pylint: disable=unused-argument", "RequestCache", "(", "'course_overview'", ")", ".", "clear", "(", ")" ]
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/openedx/core/djangoapps/content/course_overviews/models.py#L1110-L1114
dry-python/returns
dfc1613f22ef6cbc5d1c48e086affe16c1bd33bb
returns/_internal/futures/_future_result.py
python
async_bind_result
( function: Callable[[_ValueType], Result[_NewValueType, _ErrorType]], inner_value: Awaitable[Result[_ValueType, _ErrorType]], )
return (await inner_value).bind(function)
Async binds a container returning ``Result`` over a value.
Async binds a container returning ``Result`` over a value.
[ "Async", "binds", "a", "container", "returning", "Result", "over", "a", "value", "." ]
async def async_bind_result( function: Callable[[_ValueType], Result[_NewValueType, _ErrorType]], inner_value: Awaitable[Result[_ValueType, _ErrorType]], ) -> Result[_NewValueType, _ErrorType]: """Async binds a container returning ``Result`` over a value.""" return (await inner_value).bind(function)
[ "async", "def", "async_bind_result", "(", "function", ":", "Callable", "[", "[", "_ValueType", "]", ",", "Result", "[", "_NewValueType", ",", "_ErrorType", "]", "]", ",", "inner_value", ":", "Awaitable", "[", "Result", "[", "_ValueType", ",", "_ErrorType", "...
https://github.com/dry-python/returns/blob/dfc1613f22ef6cbc5d1c48e086affe16c1bd33bb/returns/_internal/futures/_future_result.py#L80-L85
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/packages/site-packages/jinja2/runtime.py
python
make_logging_undefined
(logger=None, base=None)
return LoggingUndefined
Given a logger object this returns a new undefined class that will log certain failures. It will log iterations and printing. If no logger is given a default logger is created. Example:: logger = logging.getLogger(__name__) LoggingUndefined = make_logging_undefined( logger=logger, base=Undefined ) .. versionadded:: 2.8 :param logger: the logger to use. If not provided, a default logger is created. :param base: the base class to add logging functionality to. This defaults to :class:`Undefined`.
Given a logger object this returns a new undefined class that will log certain failures. It will log iterations and printing. If no logger is given a default logger is created.
[ "Given", "a", "logger", "object", "this", "returns", "a", "new", "undefined", "class", "that", "will", "log", "certain", "failures", ".", "It", "will", "log", "iterations", "and", "printing", ".", "If", "no", "logger", "is", "given", "a", "default", "logge...
def make_logging_undefined(logger=None, base=None): """Given a logger object this returns a new undefined class that will log certain failures. It will log iterations and printing. If no logger is given a default logger is created. Example:: logger = logging.getLogger(__name__) LoggingUndefined = make_logging_undefined( logger=logger, base=Undefined ) .. versionadded:: 2.8 :param logger: the logger to use. If not provided, a default logger is created. :param base: the base class to add logging functionality to. This defaults to :class:`Undefined`. """ if logger is None: import logging logger = logging.getLogger(__name__) logger.addHandler(logging.StreamHandler(sys.stderr)) if base is None: base = Undefined def _log_message(undef): if undef._undefined_hint is None: if undef._undefined_obj is missing: hint = '%s is undefined' % undef._undefined_name elif not isinstance(undef._undefined_name, string_types): hint = '%s has no element %s' % ( object_type_repr(undef._undefined_obj), undef._undefined_name) else: hint = '%s has no attribute %s' % ( object_type_repr(undef._undefined_obj), undef._undefined_name) else: hint = undef._undefined_hint logger.warning('Template variable warning: %s', hint) class LoggingUndefined(base): def _fail_with_undefined_error(self, *args, **kwargs): try: return base._fail_with_undefined_error(self, *args, **kwargs) except self._undefined_exception as e: logger.error('Template variable error: %s', str(e)) raise e def __str__(self): rv = base.__str__(self) _log_message(self) return rv def __iter__(self): rv = base.__iter__(self) _log_message(self) return rv if PY2: def __nonzero__(self): rv = base.__nonzero__(self) _log_message(self) return rv def __unicode__(self): rv = base.__unicode__(self) _log_message(self) return rv else: def __bool__(self): rv = base.__bool__(self) _log_message(self) return rv return LoggingUndefined
[ "def", "make_logging_undefined", "(", "logger", "=", "None", ",", "base", "=", "None", ")", ":", "if", "logger", "is", "None", ":", "import", "logging", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "addHandler", "(", "...
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/packages/site-packages/jinja2/runtime.py#L531-L609
CloudBotIRC/CloudBot
6c5a88f9961b6cd66a8f489a38feb2e8227ac9ea
plugins/wordnik.py
python
define
(text)
<word> -- Returns a dictionary definition from Wordnik for <word>.
<word> -- Returns a dictionary definition from Wordnik for <word>.
[ "<word", ">", "--", "Returns", "a", "dictionary", "definition", "from", "Wordnik", "for", "<word", ">", "." ]
def define(text): """<word> -- Returns a dictionary definition from Wordnik for <word>.""" if not api_key: return "This command requires an API key from wordnik.com." word = sanitize(text) url = API_URL + "word.json/{}/definitions".format(word) params = { 'api_key': api_key, 'limit': 1 } json = requests.get(url, params=params).json() if json: data = json[0] data['word'] = " ".join(data['word'].split()) data['url'] = web.try_shorten(WEB_URL.format(data['word'])) data['attrib'] = ATTRIB_NAMES[data['sourceDictionary']] return "\x02{word}\x02: {text} - {url} ({attrib})".format(**data) else: return "I could not find a definition for \x02{}\x02.".format(word)
[ "def", "define", "(", "text", ")", ":", "if", "not", "api_key", ":", "return", "\"This command requires an API key from wordnik.com.\"", "word", "=", "sanitize", "(", "text", ")", "url", "=", "API_URL", "+", "\"word.json/{}/definitions\"", ".", "format", "(", "wor...
https://github.com/CloudBotIRC/CloudBot/blob/6c5a88f9961b6cd66a8f489a38feb2e8227ac9ea/plugins/wordnik.py#L32-L52
micahhausler/container-transform
68223fae98f30b8bb2ce0f02ba9e58afbc80f196
container_transform/compose.py
python
ComposeTransformer.emit_privileged
(self, privileged)
return privileged
[]
def emit_privileged(self, privileged): return privileged
[ "def", "emit_privileged", "(", "self", ",", "privileged", ")", ":", "return", "privileged" ]
https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/compose.py#L359-L360
meduza-corp/interstellar
40a801ccd7856491726f5a126621d9318cabe2e1
gsutil/third_party/boto/boto/ec2/cloudwatch/alarm.py
python
MetricAlarms.__init__
(self, connection=None)
Parses a list of MetricAlarms.
Parses a list of MetricAlarms.
[ "Parses", "a", "list", "of", "MetricAlarms", "." ]
def __init__(self, connection=None): """ Parses a list of MetricAlarms. """ list.__init__(self) self.connection = connection
[ "def", "__init__", "(", "self", ",", "connection", "=", "None", ")", ":", "list", ".", "__init__", "(", "self", ")", "self", ".", "connection", "=", "connection" ]
https://github.com/meduza-corp/interstellar/blob/40a801ccd7856491726f5a126621d9318cabe2e1/gsutil/third_party/boto/boto/ec2/cloudwatch/alarm.py#L31-L36
zopefoundation/Zope
ea04dd670d1a48d4d5c879d3db38fc2e9b4330bb
src/ZPublisher/BaseRequest.py
python
BaseRequest.values
(self)
return result
[]
def values(self): result = [] for k in self.keys(): result.append(self.get(k)) return result
[ "def", "values", "(", "self", ")", ":", "result", "=", "[", "]", "for", "k", "in", "self", ".", "keys", "(", ")", ":", "result", ".", "append", "(", "self", ".", "get", "(", "k", ")", ")", "return", "result" ]
https://github.com/zopefoundation/Zope/blob/ea04dd670d1a48d4d5c879d3db38fc2e9b4330bb/src/ZPublisher/BaseRequest.py#L308-L312
analysiscenter/batchflow
294747da0bca309785f925be891441fdd824e9fa
batchflow/opensets/mnist.py
python
MNIST._extract_labels
(self, f)
Extract the labels into a 1D uint8 numpy array [index]. Args: f: A file object that can be passed into a gzip reader. Returns: labels: a 1D uint8 numpy array. Raises: ValueError: If the bystream doesn't start with 2049.
Extract the labels into a 1D uint8 numpy array [index]. Args: f: A file object that can be passed into a gzip reader. Returns: labels: a 1D uint8 numpy array. Raises: ValueError: If the bystream doesn't start with 2049.
[ "Extract", "the", "labels", "into", "a", "1D", "uint8", "numpy", "array", "[", "index", "]", ".", "Args", ":", "f", ":", "A", "file", "object", "that", "can", "be", "passed", "into", "a", "gzip", "reader", ".", "Returns", ":", "labels", ":", "a", "...
def _extract_labels(self, f): """Extract the labels into a 1D uint8 numpy array [index]. Args: f: A file object that can be passed into a gzip reader. Returns: labels: a 1D uint8 numpy array. Raises: ValueError: If the bystream doesn't start with 2049. """ logger.info('Extracting %s', f.name) with gzip.GzipFile(fileobj=f) as bytestream: magic = self._read32(bytestream) if magic != 2049: raise ValueError('Invalid magic number %d in MNIST label file: %s' % (magic, f.name)) num_items = self._read32(bytestream) buf = bytestream.read(num_items) labels = np.frombuffer(buf, dtype=np.uint8) return labels
[ "def", "_extract_labels", "(", "self", ",", "f", ")", ":", "logger", ".", "info", "(", "'Extracting %s'", ",", "f", ".", "name", ")", "with", "gzip", ".", "GzipFile", "(", "fileobj", "=", "f", ")", "as", "bytestream", ":", "magic", "=", "self", ".", ...
https://github.com/analysiscenter/batchflow/blob/294747da0bca309785f925be891441fdd824e9fa/batchflow/opensets/mnist.py#L123-L140
python/mypy
17850b3bd77ae9efb5d21f656c4e4e05ac48d894
mypy/stubgen.py
python
StubGenerator.output
(self)
return imports + ''.join(self._output)
Return the text for the stub.
Return the text for the stub.
[ "Return", "the", "text", "for", "the", "stub", "." ]
def output(self) -> str: """Return the text for the stub.""" imports = '' if self._import_lines: imports += ''.join(self._import_lines) imports += ''.join(self.import_tracker.import_lines()) if imports and self._output: imports += '\n' return imports + ''.join(self._output)
[ "def", "output", "(", "self", ")", "->", "str", ":", "imports", "=", "''", "if", "self", ".", "_import_lines", ":", "imports", "+=", "''", ".", "join", "(", "self", ".", "_import_lines", ")", "imports", "+=", "''", ".", "join", "(", "self", ".", "i...
https://github.com/python/mypy/blob/17850b3bd77ae9efb5d21f656c4e4e05ac48d894/mypy/stubgen.py#L1166-L1174
pulp/pulp
a0a28d804f997b6f81c391378aff2e4c90183df9
common/pulp/common/pic.py
python
create_repo
(id, name=None, arch='noarch', **kwargs)
return POST('/repositories/', kwargs)
Acceptable keyword arguments are any arguments for a new Repo model. Common ones are: feed and sync_schedule
Acceptable keyword arguments are any arguments for a new Repo model. Common ones are: feed and sync_schedule
[ "Acceptable", "keyword", "arguments", "are", "any", "arguments", "for", "a", "new", "Repo", "model", ".", "Common", "ones", "are", ":", "feed", "and", "sync_schedule" ]
def create_repo(id, name=None, arch='noarch', **kwargs): """ Acceptable keyword arguments are any arguments for a new Repo model. Common ones are: feed and sync_schedule """ kwargs.update({'id': id, 'name': name or id, 'arch': arch}) return POST('/repositories/', kwargs)
[ "def", "create_repo", "(", "id", ",", "name", "=", "None", ",", "arch", "=", "'noarch'", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "{", "'id'", ":", "id", ",", "'name'", ":", "name", "or", "id", ",", "'arch'", ":", "arch", ...
https://github.com/pulp/pulp/blob/a0a28d804f997b6f81c391378aff2e4c90183df9/common/pulp/common/pic.py#L133-L139
microsoft/MMdnn
19562a381c27545984a216eda7591430e274e518
mmdnn/conversion/examples/tensorflow/models/nasnet.py
python
_build_nasnet_base
(images, normal_cell, reduction_cell, num_classes, hparams, is_training, stem_type, final_endpoint=None)
return logits, end_points
Constructs a NASNet image model.
Constructs a NASNet image model.
[ "Constructs", "a", "NASNet", "image", "model", "." ]
def _build_nasnet_base(images, normal_cell, reduction_cell, num_classes, hparams, is_training, stem_type, final_endpoint=None): """Constructs a NASNet image model.""" end_points = {} def add_and_check_endpoint(endpoint_name, net): end_points[endpoint_name] = net return final_endpoint and (endpoint_name == final_endpoint) # Find where to place the reduction cells or stride normal cells reduction_indices = nasnet_utils.calc_reduction_layers( hparams.num_cells, hparams.num_reduction_layers) stem_cell = reduction_cell if stem_type == 'imagenet': stem = lambda: _imagenet_stem(images, hparams, stem_cell) elif stem_type == 'cifar': stem = lambda: _cifar_stem(images, hparams) else: raise ValueError('Unknown stem_type: ', stem_type) net, cell_outputs = stem() if add_and_check_endpoint('Stem', net): return net, end_points # Setup for building in the auxiliary head. aux_head_cell_idxes = [] if len(reduction_indices) >= 2: aux_head_cell_idxes.append(reduction_indices[1] - 1) # Run the cells filter_scaling = 1.0 # true_cell_num accounts for the stem cells true_cell_num = 2 if stem_type == 'imagenet' else 0 for cell_num in range(hparams.num_cells): stride = 1 if hparams.skip_reduction_layer_input: prev_layer = cell_outputs[-2] if cell_num in reduction_indices: filter_scaling *= hparams.filter_scaling_rate net = reduction_cell( net, scope='reduction_cell_{}'.format(reduction_indices.index(cell_num)), filter_scaling=filter_scaling, stride=2, prev_layer=cell_outputs[-2], cell_num=true_cell_num) if add_and_check_endpoint( 'Reduction_Cell_{}'.format(reduction_indices.index(cell_num)), net): return net, end_points true_cell_num += 1 cell_outputs.append(net) if not hparams.skip_reduction_layer_input: prev_layer = cell_outputs[-2] net = normal_cell( net, scope='cell_{}'.format(cell_num), filter_scaling=filter_scaling, stride=stride, prev_layer=prev_layer, cell_num=true_cell_num) if add_and_check_endpoint('Cell_{}'.format(cell_num), net): return net, end_points true_cell_num += 1 if (hparams.use_aux_head and cell_num in aux_head_cell_idxes and num_classes and is_training): aux_net = tf.nn.relu(net) _build_aux_head(aux_net, end_points, num_classes, hparams, scope='aux_{}'.format(cell_num)) cell_outputs.append(net) # Final softmax layer with tf.variable_scope('final_layer'): net = tf.nn.relu(net) net = nasnet_utils.global_avg_pool(net) if add_and_check_endpoint('global_pool', net) or num_classes is None: return net, end_points net = slim.dropout(net, hparams.dense_dropout_keep_prob, scope='dropout') logits = slim.fully_connected(net, num_classes) if add_and_check_endpoint('Logits', logits): return net, end_points predictions = tf.nn.softmax(logits, name='predictions') if add_and_check_endpoint('Predictions', predictions): return net, end_points return logits, end_points
[ "def", "_build_nasnet_base", "(", "images", ",", "normal_cell", ",", "reduction_cell", ",", "num_classes", ",", "hparams", ",", "is_training", ",", "stem_type", ",", "final_endpoint", "=", "None", ")", ":", "end_points", "=", "{", "}", "def", "add_and_check_endp...
https://github.com/microsoft/MMdnn/blob/19562a381c27545984a216eda7591430e274e518/mmdnn/conversion/examples/tensorflow/models/nasnet.py#L422-L513
plaid/plaid-python
8c60fca608e426f3ff30da8857775946d29e122c
plaid/model/wallet_transaction_counterparty_bacs.py
python
WalletTransactionCounterpartyBACS.openapi_types
()
return { 'account': (str,), # noqa: E501 'sort_code': (str,), # noqa: E501 }
This must be a method because a model may have properties that are of type self, this must run after the class is loaded Returns openapi_types (dict): The key is attribute name and the value is attribute type.
This must be a method because a model may have properties that are of type self, this must run after the class is loaded
[ "This", "must", "be", "a", "method", "because", "a", "model", "may", "have", "properties", "that", "are", "of", "type", "self", "this", "must", "run", "after", "the", "class", "is", "loaded" ]
def openapi_types(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded Returns openapi_types (dict): The key is attribute name and the value is attribute type. """ lazy_import() return { 'account': (str,), # noqa: E501 'sort_code': (str,), # noqa: E501 }
[ "def", "openapi_types", "(", ")", ":", "lazy_import", "(", ")", "return", "{", "'account'", ":", "(", "str", ",", ")", ",", "# noqa: E501", "'sort_code'", ":", "(", "str", ",", ")", ",", "# noqa: E501", "}" ]
https://github.com/plaid/plaid-python/blob/8c60fca608e426f3ff30da8857775946d29e122c/plaid/model/wallet_transaction_counterparty_bacs.py#L82-L95
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.4/django/template/loader.py
python
select_template
(template_name_list)
Given a list of template names, returns the first that can be loaded.
Given a list of template names, returns the first that can be loaded.
[ "Given", "a", "list", "of", "template", "names", "returns", "the", "first", "that", "can", "be", "loaded", "." ]
def select_template(template_name_list): "Given a list of template names, returns the first that can be loaded." if not template_name_list: raise TemplateDoesNotExist("No template names provided") not_found = [] for template_name in template_name_list: try: return get_template(template_name) except TemplateDoesNotExist, e: if e.args[0] not in not_found: not_found.append(e.args[0]) continue # If we get here, none of the templates could be loaded raise TemplateDoesNotExist(', '.join(not_found))
[ "def", "select_template", "(", "template_name_list", ")", ":", "if", "not", "template_name_list", ":", "raise", "TemplateDoesNotExist", "(", "\"No template names provided\"", ")", "not_found", "=", "[", "]", "for", "template_name", "in", "template_name_list", ":", "tr...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.4/django/template/loader.py#L180-L193
fepegar/torchio
3e07b78da16d6db4da7193325b3f9cb31fc0911a
torchio/data/subject.py
python
Subject.load
(self)
Load images in subject on RAM.
Load images in subject on RAM.
[ "Load", "images", "in", "subject", "on", "RAM", "." ]
def load(self) -> None: """Load images in subject on RAM.""" for image in self.get_images(intensity_only=False): image.load()
[ "def", "load", "(", "self", ")", "->", "None", ":", "for", "image", "in", "self", ".", "get_images", "(", "intensity_only", "=", "False", ")", ":", "image", ".", "load", "(", ")" ]
https://github.com/fepegar/torchio/blob/3e07b78da16d6db4da7193325b3f9cb31fc0911a/torchio/data/subject.py#L364-L367
mesonbuild/meson
a22d0f9a0a787df70ce79b05d0c45de90a970048
mesonbuild/backend/xcodebackend.py
python
PbxItem.__init__
(self, value, comment = '')
[]
def __init__(self, value, comment = ''): self.value = value self.comment = comment
[ "def", "__init__", "(", "self", ",", "value", ",", "comment", "=", "''", ")", ":", "self", ".", "value", "=", "value", "self", ".", "comment", "=", "comment" ]
https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/mesonbuild/backend/xcodebackend.py#L69-L71
weewx/weewx
cb594fce224560bd8696050fc5c7843c7839320e
bin/weewx/manager.py
python
Manager.firstGoodStamp
(self)
return _row[0] if _row else None
Retrieves earliest timestamp in the archive. returns: Time of the first good archive record as an epoch time, or None if there are no records.
Retrieves earliest timestamp in the archive.
[ "Retrieves", "earliest", "timestamp", "in", "the", "archive", "." ]
def firstGoodStamp(self): """Retrieves earliest timestamp in the archive. returns: Time of the first good archive record as an epoch time, or None if there are no records. """ _row = self.getSql("SELECT MIN(dateTime) FROM %s" % self.table_name) return _row[0] if _row else None
[ "def", "firstGoodStamp", "(", "self", ")", ":", "_row", "=", "self", ".", "getSql", "(", "\"SELECT MIN(dateTime) FROM %s\"", "%", "self", ".", "table_name", ")", "return", "_row", "[", "0", "]", "if", "_row", "else", "None" ]
https://github.com/weewx/weewx/blob/cb594fce224560bd8696050fc5c7843c7839320e/bin/weewx/manager.py#L241-L248
Azure/azure-cli
6c1b085a0910c6c2139006fcbd8ade44006eb6dd
src/azure-cli/azure/cli/command_modules/keyvault/vendored_sdks/azure_keyvault_t1/key_vault_authentication.py
python
KeyVaultAuthBase._handle_redirect
(self, r, **kwargs)
Reset auth_attempted on redirects.
Reset auth_attempted on redirects.
[ "Reset", "auth_attempted", "on", "redirects", "." ]
def _handle_redirect(self, r, **kwargs): """Reset auth_attempted on redirects.""" if r.is_redirect: self._thread_local.auth_attempted = False
[ "def", "_handle_redirect", "(", "self", ",", "r", ",", "*", "*", "kwargs", ")", ":", "if", "r", ".", "is_redirect", ":", "self", ".", "_thread_local", ".", "auth_attempted", "=", "False" ]
https://github.com/Azure/azure-cli/blob/6c1b085a0910c6c2139006fcbd8ade44006eb6dd/src/azure-cli/azure/cli/command_modules/keyvault/vendored_sdks/azure_keyvault_t1/key_vault_authentication.py#L94-L97
dowsnature/dowsDNS
d202e821112e1f3839de6df1a9c696fbd9502494
dnslib/zoneresolver.py
python
ZoneResolver.resolve
(self,request,handler)
return reply
Respond to DNS request - parameters are request packet & handler. Method is expected to return DNS response
Respond to DNS request - parameters are request packet & handler. Method is expected to return DNS response
[ "Respond", "to", "DNS", "request", "-", "parameters", "are", "request", "packet", "&", "handler", ".", "Method", "is", "expected", "to", "return", "DNS", "response" ]
def resolve(self,request,handler): """ Respond to DNS request - parameters are request packet & handler. Method is expected to return DNS response """ reply = request.reply() qname = request.q.qname qtype = QTYPE[request.q.qtype] for name,rtype,rr in self.zone: # Check if label & type match if getattr(qname,self.eq)(name) and (qtype == rtype or qtype == 'ANY' or rtype == 'CNAME'): # If we have a glob match fix reply label if self.glob: a = copy.copy(rr) a.rname = qname reply.add_answer(a) else: reply.add_answer(rr) # Check for A/AAAA records associated with reply and # add in additional section if rtype in ['CNAME','NS','MX','PTR']: for a_name,a_rtype,a_rr in self.zone: if a_name == rr.rdata.label and a_rtype in ['A','AAAA']: reply.add_ar(a_rr) if not reply.rr: reply.header.rcode = RCODE.NXDOMAIN return reply
[ "def", "resolve", "(", "self", ",", "request", ",", "handler", ")", ":", "reply", "=", "request", ".", "reply", "(", ")", "qname", "=", "request", ".", "q", ".", "qname", "qtype", "=", "QTYPE", "[", "request", ".", "q", ".", "qtype", "]", "for", ...
https://github.com/dowsnature/dowsDNS/blob/d202e821112e1f3839de6df1a9c696fbd9502494/dnslib/zoneresolver.py#L25-L53
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/gdata/Crypto/PublicKey/pubkey.py
python
pubkey.decrypt
(self, ciphertext)
decrypt(ciphertext:tuple|string|long): string Decrypt 'ciphertext' using this key.
decrypt(ciphertext:tuple|string|long): string Decrypt 'ciphertext' using this key.
[ "decrypt", "(", "ciphertext", ":", "tuple|string|long", ")", ":", "string", "Decrypt", "ciphertext", "using", "this", "key", "." ]
def decrypt(self, ciphertext): """decrypt(ciphertext:tuple|string|long): string Decrypt 'ciphertext' using this key. """ wasString=0 if not isinstance(ciphertext, types.TupleType): ciphertext=(ciphertext,) if isinstance(ciphertext[0], types.StringType): ciphertext=tuple(map(bytes_to_long, ciphertext)) ; wasString=1 plaintext=self._decrypt(ciphertext) if wasString: return long_to_bytes(plaintext) else: return plaintext
[ "def", "decrypt", "(", "self", ",", "ciphertext", ")", ":", "wasString", "=", "0", "if", "not", "isinstance", "(", "ciphertext", ",", "types", ".", "TupleType", ")", ":", "ciphertext", "=", "(", "ciphertext", ",", ")", "if", "isinstance", "(", "ciphertex...
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/gdata/Crypto/PublicKey/pubkey.py#L54-L65
Coalfire-Research/Slackor
aa32a7f9250bd8b107d48fd573f26176b527b2a5
impacket/impacket/dns.py
python
DNS.get_qdcount_tcp
(self)
return self.header.get_word(6)
Get Unsigned 16 bit integer specifying the number of entries in the question section.
Get Unsigned 16 bit integer specifying the number of entries in the question section.
[ "Get", "Unsigned", "16", "bit", "integer", "specifying", "the", "number", "of", "entries", "in", "the", "question", "section", "." ]
def get_qdcount_tcp(self): 'Get Unsigned 16 bit integer specifying the number of entries in the question section.' return self.header.get_word(6)
[ "def", "get_qdcount_tcp", "(", "self", ")", ":", "return", "self", ".", "header", ".", "get_word", "(", "6", ")" ]
https://github.com/Coalfire-Research/Slackor/blob/aa32a7f9250bd8b107d48fd573f26176b527b2a5/impacket/impacket/dns.py#L241-L243
hyperledger/aries-cloudagent-python
2f36776e99f6053ae92eed8123b5b1b2e891c02a
aries_cloudagent/messaging/jsonld/routes.py
python
sign
(request: web.BaseRequest)
return web.json_response(response)
Request handler for signing a jsonld doc. Args: request: aiohttp request object
Request handler for signing a jsonld doc.
[ "Request", "handler", "for", "signing", "a", "jsonld", "doc", "." ]
async def sign(request: web.BaseRequest): """ Request handler for signing a jsonld doc. Args: request: aiohttp request object """ response = {} body = await request.json() doc = body.get("doc") try: context: AdminRequestContext = request["context"] async with context.session() as session: doc_with_proof = await sign_credential( session, doc.get("credential"), doc.get("options"), body.get("verkey") ) response["signed_doc"] = doc_with_proof except (BaseJSONLDMessagingError) as err: response["error"] = str(err) except (WalletError, InjectionError): raise web.HTTPForbidden(reason="No wallet available") return web.json_response(response)
[ "async", "def", "sign", "(", "request", ":", "web", ".", "BaseRequest", ")", ":", "response", "=", "{", "}", "body", "=", "await", "request", ".", "json", "(", ")", "doc", "=", "body", ".", "get", "(", "\"doc\"", ")", "try", ":", "context", ":", ...
https://github.com/hyperledger/aries-cloudagent-python/blob/2f36776e99f6053ae92eed8123b5b1b2e891c02a/aries_cloudagent/messaging/jsonld/routes.py#L70-L92
frescobaldi/frescobaldi
301cc977fc4ba7caa3df9e4bf905212ad5d06912
frescobaldi_app/extensions/__init__.py
python
ExtensionMixin.current_document
(self)
return self.extension().current_document()
Return the current document.
Return the current document.
[ "Return", "the", "current", "document", "." ]
def current_document(self): """Return the current document.""" return self.extension().current_document()
[ "def", "current_document", "(", "self", ")", ":", "return", "self", ".", "extension", "(", ")", ".", "current_document", "(", ")" ]
https://github.com/frescobaldi/frescobaldi/blob/301cc977fc4ba7caa3df9e4bf905212ad5d06912/frescobaldi_app/extensions/__init__.py#L333-L335
eliben/pyelftools
8f7a0becaface09435c4374947548b7851e3d1a2
elftools/construct/core.py
python
RepeatUntil._parse
(self, stream, context)
return obj
[]
def _parse(self, stream, context): obj = [] try: if self.subcon.conflags & self.FLAG_COPY_CONTEXT: while True: subobj = self.subcon._parse(stream, context.__copy__()) obj.append(subobj) if self.predicate(subobj, context): break else: while True: subobj = self.subcon._parse(stream, context) obj.append(subobj) if self.predicate(subobj, context): break except ConstructError as ex: raise ArrayError("missing terminator", ex) return obj
[ "def", "_parse", "(", "self", ",", "stream", ",", "context", ")", ":", "obj", "=", "[", "]", "try", ":", "if", "self", ".", "subcon", ".", "conflags", "&", "self", ".", "FLAG_COPY_CONTEXT", ":", "while", "True", ":", "subobj", "=", "self", ".", "su...
https://github.com/eliben/pyelftools/blob/8f7a0becaface09435c4374947548b7851e3d1a2/elftools/construct/core.py#L562-L579
KalleHallden/AutoTimer
2d954216700c4930baa154e28dbddc34609af7ce
env/lib/python2.7/site-packages/pkg_resources/__init__.py
python
NullProvider._fn
(self, base, resource_name)
return base
[]
def _fn(self, base, resource_name): self._validate_resource_path(resource_name) if resource_name: return os.path.join(base, *resource_name.split('/')) return base
[ "def", "_fn", "(", "self", ",", "base", ",", "resource_name", ")", ":", "self", ".", "_validate_resource_path", "(", "resource_name", ")", "if", "resource_name", ":", "return", "os", ".", "path", ".", "join", "(", "base", ",", "*", "resource_name", ".", ...
https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/pkg_resources/__init__.py#L1486-L1490
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/batch/v20170312/batch_client.py
python
BatchClient.DescribeAvailableCvmInstanceTypes
(self, request)
查看可用的CVM机型配置信息 :param request: Request instance for DescribeAvailableCvmInstanceTypes. :type request: :class:`tencentcloud.batch.v20170312.models.DescribeAvailableCvmInstanceTypesRequest` :rtype: :class:`tencentcloud.batch.v20170312.models.DescribeAvailableCvmInstanceTypesResponse`
查看可用的CVM机型配置信息
[ "查看可用的CVM机型配置信息" ]
def DescribeAvailableCvmInstanceTypes(self, request): """查看可用的CVM机型配置信息 :param request: Request instance for DescribeAvailableCvmInstanceTypes. :type request: :class:`tencentcloud.batch.v20170312.models.DescribeAvailableCvmInstanceTypesRequest` :rtype: :class:`tencentcloud.batch.v20170312.models.DescribeAvailableCvmInstanceTypesResponse` """ try: params = request._serialize() body = self.call("DescribeAvailableCvmInstanceTypes", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeAvailableCvmInstanceTypesResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message)
[ "def", "DescribeAvailableCvmInstanceTypes", "(", "self", ",", "request", ")", ":", "try", ":", "params", "=", "request", ".", "_serialize", "(", ")", "body", "=", "self", ".", "call", "(", "\"DescribeAvailableCvmInstanceTypes\"", ",", "params", ")", "response", ...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/batch/v20170312/batch_client.py#L233-L258
minivision-ai/photo2cartoon
6204e27a71620500c2f5b2ffd36646b0e2e5c110
models/networks.py
python
adaLIN.__init__
(self, num_features, eps=1e-5)
[]
def __init__(self, num_features, eps=1e-5): super(adaLIN, self).__init__() self.eps = eps self.rho = Parameter(torch.Tensor(1, num_features, 1, 1)) self.rho.data.fill_(0.9)
[ "def", "__init__", "(", "self", ",", "num_features", ",", "eps", "=", "1e-5", ")", ":", "super", "(", "adaLIN", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "eps", "=", "eps", "self", ".", "rho", "=", "Parameter", "(", "torch", ".", ...
https://github.com/minivision-ai/photo2cartoon/blob/6204e27a71620500c2f5b2ffd36646b0e2e5c110/models/networks.py#L359-L363
IronLanguages/ironpython2
51fdedeeda15727717fb8268a805f71b06c0b9f1
Src/StdLib/Lib/lib2to3/btm_utils.py
python
MinNode.leaves
(self)
Generator that returns the leaves of the tree
Generator that returns the leaves of the tree
[ "Generator", "that", "returns", "the", "leaves", "of", "the", "tree" ]
def leaves(self): "Generator that returns the leaves of the tree" for child in self.children: for x in child.leaves(): yield x if not self.children: yield self
[ "def", "leaves", "(", "self", ")", ":", "for", "child", "in", "self", ".", "children", ":", "for", "x", "in", "child", ".", "leaves", "(", ")", ":", "yield", "x", "if", "not", "self", ".", "children", ":", "yield", "self" ]
https://github.com/IronLanguages/ironpython2/blob/51fdedeeda15727717fb8268a805f71b06c0b9f1/Src/StdLib/Lib/lib2to3/btm_utils.py#L96-L102
golismero/golismero
7d605b937e241f51c1ca4f47b20f755eeefb9d76
golismero/api/data/vulnerability/__init__.py
python
Vulnerability.nessus
(self, nessus)
:param nessus: Nessus Plugin IDs. :type nessus: tuple( str, ... )
:param nessus: Nessus Plugin IDs. :type nessus: tuple( str, ... )
[ ":", "param", "nessus", ":", "Nessus", "Plugin", "IDs", ".", ":", "type", "nessus", ":", "tuple", "(", "str", "...", ")" ]
def nessus(self, nessus): """ :param nessus: Nessus Plugin IDs. :type nessus: tuple( str, ... ) """ self.__nessus = sanitize_vuln_ids(nessus)
[ "def", "nessus", "(", "self", ",", "nessus", ")", ":", "self", ".", "__nessus", "=", "sanitize_vuln_ids", "(", "nessus", ")" ]
https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/golismero/api/data/vulnerability/__init__.py#L1180-L1185
dexy/dexy
323c1806e51f75435e11d2265703e68f46c8aef3
dexy/filters/confluence.py
python
ConfluenceRESTAPI.credentials_with_json_content_type
(self)
return self.credentials_with_headers(json_content_type)
[]
def credentials_with_json_content_type(self): json_content_type = {'content-type': 'application/json'} return self.credentials_with_headers(json_content_type)
[ "def", "credentials_with_json_content_type", "(", "self", ")", ":", "json_content_type", "=", "{", "'content-type'", ":", "'application/json'", "}", "return", "self", ".", "credentials_with_headers", "(", "json_content_type", ")" ]
https://github.com/dexy/dexy/blob/323c1806e51f75435e11d2265703e68f46c8aef3/dexy/filters/confluence.py#L77-L79
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-linux/x64/tornado/auth.py
python
FacebookGraphMixin.facebook_request
( self, path: str, access_token: str = None, post_args: Dict[str, Any] = None, **args: Any )
return await self.oauth2_request( url, access_token=access_token, post_args=post_args, **args )
Fetches the given relative API path, e.g., "/btaylor/picture" If the request is a POST, ``post_args`` should be provided. Query string arguments should be given as keyword arguments. An introduction to the Facebook Graph API can be found at http://developers.facebook.com/docs/api Many methods require an OAuth access token which you can obtain through `~OAuth2Mixin.authorize_redirect` and `get_authenticated_user`. The user returned through that process includes an ``access_token`` attribute that can be used to make authenticated requests via this method. Example usage: .. testcode:: class MainHandler(tornado.web.RequestHandler, tornado.auth.FacebookGraphMixin): @tornado.web.authenticated async def get(self): new_entry = await self.facebook_request( "/me/feed", post_args={"message": "I am posting from my Tornado application!"}, access_token=self.current_user["access_token"]) if not new_entry: # Call failed; perhaps missing permission? yield self.authorize_redirect() return self.finish("Posted a message!") .. testoutput:: :hide: The given path is relative to ``self._FACEBOOK_BASE_URL``, by default "https://graph.facebook.com". This method is a wrapper around `OAuth2Mixin.oauth2_request`; the only difference is that this method takes a relative path, while ``oauth2_request`` takes a complete url. .. versionchanged:: 3.1 Added the ability to override ``self._FACEBOOK_BASE_URL``. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned awaitable object instead.
Fetches the given relative API path, e.g., "/btaylor/picture"
[ "Fetches", "the", "given", "relative", "API", "path", "e", ".", "g", ".", "/", "btaylor", "/", "picture" ]
async def facebook_request( self, path: str, access_token: str = None, post_args: Dict[str, Any] = None, **args: Any ) -> Any: """Fetches the given relative API path, e.g., "/btaylor/picture" If the request is a POST, ``post_args`` should be provided. Query string arguments should be given as keyword arguments. An introduction to the Facebook Graph API can be found at http://developers.facebook.com/docs/api Many methods require an OAuth access token which you can obtain through `~OAuth2Mixin.authorize_redirect` and `get_authenticated_user`. The user returned through that process includes an ``access_token`` attribute that can be used to make authenticated requests via this method. Example usage: .. testcode:: class MainHandler(tornado.web.RequestHandler, tornado.auth.FacebookGraphMixin): @tornado.web.authenticated async def get(self): new_entry = await self.facebook_request( "/me/feed", post_args={"message": "I am posting from my Tornado application!"}, access_token=self.current_user["access_token"]) if not new_entry: # Call failed; perhaps missing permission? yield self.authorize_redirect() return self.finish("Posted a message!") .. testoutput:: :hide: The given path is relative to ``self._FACEBOOK_BASE_URL``, by default "https://graph.facebook.com". This method is a wrapper around `OAuth2Mixin.oauth2_request`; the only difference is that this method takes a relative path, while ``oauth2_request`` takes a complete url. .. versionchanged:: 3.1 Added the ability to override ``self._FACEBOOK_BASE_URL``. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned awaitable object instead. """ url = self._FACEBOOK_BASE_URL + path return await self.oauth2_request( url, access_token=access_token, post_args=post_args, **args )
[ "async", "def", "facebook_request", "(", "self", ",", "path", ":", "str", ",", "access_token", ":", "str", "=", "None", ",", "post_args", ":", "Dict", "[", "str", ",", "Any", "]", "=", "None", ",", "*", "*", "args", ":", "Any", ")", "->", "Any", ...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-linux/x64/tornado/auth.py#L1034-L1094
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/rings/asymptotic/misc.py
python
Locals.__getitem__
(self, key)
r""" Return an item. TESTS:: sage: from sage.rings.asymptotic.misc import Locals sage: locals = Locals() sage: locals {} sage: locals['log'] # indirect doctest <function log at 0x...>
r""" Return an item.
[ "r", "Return", "an", "item", "." ]
def __getitem__(self, key): r""" Return an item. TESTS:: sage: from sage.rings.asymptotic.misc import Locals sage: locals = Locals() sage: locals {} sage: locals['log'] # indirect doctest <function log at 0x...> """ try: return super(Locals, self).__getitem__(key) except KeyError as ke: try: return self.default_locals()[key] except KeyError: raise ke
[ "def", "__getitem__", "(", "self", ",", "key", ")", ":", "try", ":", "return", "super", "(", "Locals", ",", "self", ")", ".", "__getitem__", "(", "key", ")", "except", "KeyError", "as", "ke", ":", "try", ":", "return", "self", ".", "default_locals", ...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/rings/asymptotic/misc.py#L1064-L1083
BMW-InnovationLab/BMW-TensorFlow-Training-GUI
4f10d1f00f9ac312ca833e5b28fd0f8952cfee17
training_api/research/object_detection/core/losses.py
python
BootstrappedSigmoidClassificationLoss.__init__
(self, alpha, bootstrap_type='soft')
Constructor. Args: alpha: a float32 scalar tensor between 0 and 1 representing interpolation weight bootstrap_type: set to either 'hard' or 'soft' (default) Raises: ValueError: if bootstrap_type is not either 'hard' or 'soft'
Constructor.
[ "Constructor", "." ]
def __init__(self, alpha, bootstrap_type='soft'): """Constructor. Args: alpha: a float32 scalar tensor between 0 and 1 representing interpolation weight bootstrap_type: set to either 'hard' or 'soft' (default) Raises: ValueError: if bootstrap_type is not either 'hard' or 'soft' """ if bootstrap_type != 'hard' and bootstrap_type != 'soft': raise ValueError('Unrecognized bootstrap_type: must be one of ' '\'hard\' or \'soft.\'') self._alpha = alpha self._bootstrap_type = bootstrap_type
[ "def", "__init__", "(", "self", ",", "alpha", ",", "bootstrap_type", "=", "'soft'", ")", ":", "if", "bootstrap_type", "!=", "'hard'", "and", "bootstrap_type", "!=", "'soft'", ":", "raise", "ValueError", "(", "'Unrecognized bootstrap_type: must be one of '", "'\\'har...
https://github.com/BMW-InnovationLab/BMW-TensorFlow-Training-GUI/blob/4f10d1f00f9ac312ca833e5b28fd0f8952cfee17/training_api/research/object_detection/core/losses.py#L386-L401
fboender/ansible-cmdb
3f3e412d2a7be91c97c5a1842f4e57cc85b06961
lib/yaml3/__init__.py
python
load
(stream, Loader=Loader)
Parse the first YAML document in a stream and produce the corresponding Python object.
Parse the first YAML document in a stream and produce the corresponding Python object.
[ "Parse", "the", "first", "YAML", "document", "in", "a", "stream", "and", "produce", "the", "corresponding", "Python", "object", "." ]
def load(stream, Loader=Loader): """ Parse the first YAML document in a stream and produce the corresponding Python object. """ loader = Loader(stream) try: return loader.get_single_data() finally: loader.dispose()
[ "def", "load", "(", "stream", ",", "Loader", "=", "Loader", ")", ":", "loader", "=", "Loader", "(", "stream", ")", "try", ":", "return", "loader", ".", "get_single_data", "(", ")", "finally", ":", "loader", ".", "dispose", "(", ")" ]
https://github.com/fboender/ansible-cmdb/blob/3f3e412d2a7be91c97c5a1842f4e57cc85b06961/lib/yaml3/__init__.py#L65-L74
lovelylain/pyctp
fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d
lts/ctp/ApiStruct.py
python
Exchange.__init__
(self, ExchangeID='', ExchangeName='', ExchangeProperty=EXP_Normal)
[]
def __init__(self, ExchangeID='', ExchangeName='', ExchangeProperty=EXP_Normal): self.ExchangeID = '' #交易所代码, char[9] self.ExchangeName = '' #交易所名称, char[31] self.ExchangeProperty = ''
[ "def", "__init__", "(", "self", ",", "ExchangeID", "=", "''", ",", "ExchangeName", "=", "''", ",", "ExchangeProperty", "=", "EXP_Normal", ")", ":", "self", ".", "ExchangeID", "=", "''", "#交易所代码, char[9]", "self", ".", "ExchangeName", "=", "''", "#交易所名称, char...
https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/lts/ctp/ApiStruct.py#L593-L596
catap/namebench
9913a7a1a7955a3759eb18cbe73b421441a7a00f
nb_third_party/graphy/backends/google_chart_api/util.py
python
JoinLists
(**args)
return out
Take a dictionary of {long_name:values}, and join the values. For each long_name, join the values into a string according to JOIN_DELIMS. If values is empty or None, replace with an empty string. Returns: A dictionary {long_name:joined_value} entries.
Take a dictionary of {long_name:values}, and join the values.
[ "Take", "a", "dictionary", "of", "{", "long_name", ":", "values", "}", "and", "join", "the", "values", "." ]
def JoinLists(**args): """Take a dictionary of {long_name:values}, and join the values. For each long_name, join the values into a string according to JOIN_DELIMS. If values is empty or None, replace with an empty string. Returns: A dictionary {long_name:joined_value} entries. """ out = {} for key, val in args.items(): if val: out[key] = StrJoin(JOIN_DELIMS[key], val) else: out[key] = '' return out
[ "def", "JoinLists", "(", "*", "*", "args", ")", ":", "out", "=", "{", "}", "for", "key", ",", "val", "in", "args", ".", "items", "(", ")", ":", "if", "val", ":", "out", "[", "key", "]", "=", "StrJoin", "(", "JOIN_DELIMS", "[", "key", "]", ","...
https://github.com/catap/namebench/blob/9913a7a1a7955a3759eb18cbe73b421441a7a00f/nb_third_party/graphy/backends/google_chart_api/util.py#L170-L185
ym2011/POC-EXP
206b22d3a6b2a172359678df33bbc5b2ad04b6c3
windows/SYNfulKnock/scapy-2.3.1/scapy/crypto/cert.py
python
Cert.isSelfSigned
(self)
return False
Return True if the certificate is self signed: - issuer and subject are the same - the signature of the certificate is valid.
Return True if the certificate is self signed: - issuer and subject are the same - the signature of the certificate is valid.
[ "Return", "True", "if", "the", "certificate", "is", "self", "signed", ":", "-", "issuer", "and", "subject", "are", "the", "same", "-", "the", "signature", "of", "the", "certificate", "is", "valid", "." ]
def isSelfSigned(self): """ Return True if the certificate is self signed: - issuer and subject are the same - the signature of the certificate is valid. """ if self.issuer == self.subject: return self.isIssuerCert(self) return False
[ "def", "isSelfSigned", "(", "self", ")", ":", "if", "self", ".", "issuer", "==", "self", ".", "subject", ":", "return", "self", ".", "isIssuerCert", "(", "self", ")", "return", "False" ]
https://github.com/ym2011/POC-EXP/blob/206b22d3a6b2a172359678df33bbc5b2ad04b6c3/windows/SYNfulKnock/scapy-2.3.1/scapy/crypto/cert.py#L2055-L2063
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/gui/plug/_guioptions.py
python
GuiDestinationOption.__init__
(self, option, dbstate, uistate, track, override)
@param option: The option to display. @type option: gen.plug.menu.DestinationOption @return: nothing
[]
def __init__(self, option, dbstate, uistate, track, override): """ @param option: The option to display. @type option: gen.plug.menu.DestinationOption @return: nothing """ Gtk.Box.__init__(self) self.__option = option self.__uistate = uistate self.__entry = Gtk.Entry() self.__entry.set_text(self.__option.get_value()) self.__button = Gtk.Button() img = Gtk.Image() img.set_from_icon_name('document-open', Gtk.IconSize.BUTTON) self.__button.add(img) self.__button.connect('clicked', self.__select_file) self.pack_start(self.__entry, True, True, 0) self.pack_end(self.__button, False, False, 0) # Set up signal handlers when the widget value is changed # from user interaction or programmatically. When handling # a specific signal, we need to temporarily block the signal # that would call the other signal handler. self.changekey = self.__entry.connect('changed', self.__text_changed) self.valuekey = self.__option.connect('value-changed', self.__value_changed) self.conkey1 = self.__option.connect('options-changed', self.__option_changed) self.conkey2 = self.__option.connect('avail-changed', self.__update_avail) self.__update_avail() self.set_tooltip_text(self.__option.get_help())
[ "def", "__init__", "(", "self", ",", "option", ",", "dbstate", ",", "uistate", ",", "track", ",", "override", ")", ":", "Gtk", ".", "Box", ".", "__init__", "(", "self", ")", "self", ".", "__option", "=", "option", "self", ".", "__uistate", "=", "uist...
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/gui/plug/_guioptions.py#L1680-L1715
joxeankoret/nightmare
11b22bb7c346611de90f479ee781c9228af453ea
mutators/OleFileIO_PL.py
python
_OleDirectoryEntry.build_storage_tree
(self)
Read and build the red-black tree attached to this _OleDirectoryEntry object, if it is a storage. Note that this method builds a tree of all subentries, so it should only be called for the root object once.
Read and build the red-black tree attached to this _OleDirectoryEntry object, if it is a storage. Note that this method builds a tree of all subentries, so it should only be called for the root object once.
[ "Read", "and", "build", "the", "red", "-", "black", "tree", "attached", "to", "this", "_OleDirectoryEntry", "object", "if", "it", "is", "a", "storage", ".", "Note", "that", "this", "method", "builds", "a", "tree", "of", "all", "subentries", "so", "it", "...
def build_storage_tree(self): """ Read and build the red-black tree attached to this _OleDirectoryEntry object, if it is a storage. Note that this method builds a tree of all subentries, so it should only be called for the root object once. """ debug('build_storage_tree: SID=%d - %s - sid_child=%d' % (self.sid, repr(self.name), self.sid_child)) if self.sid_child != NOSTREAM: # if child SID is not NOSTREAM, then this entry is a storage. # Let's walk through the tree of children to fill the kids list: self.append_kids(self.sid_child) # Note from OpenOffice documentation: the safest way is to # recreate the tree because some implementations may store broken # red-black trees... # in the OLE file, entries are sorted on (length, name). # for convenience, we sort them on name instead: # (see rich comparison methods in this class) self.kids.sort()
[ "def", "build_storage_tree", "(", "self", ")", ":", "debug", "(", "'build_storage_tree: SID=%d - %s - sid_child=%d'", "%", "(", "self", ".", "sid", ",", "repr", "(", "self", ".", "name", ")", ",", "self", ".", "sid_child", ")", ")", "if", "self", ".", "sid...
https://github.com/joxeankoret/nightmare/blob/11b22bb7c346611de90f479ee781c9228af453ea/mutators/OleFileIO_PL.py#L888-L909
wxWidgets/Phoenix
b2199e299a6ca6d866aa6f3d0888499136ead9d6
wx/lib/agw/aui/framemanager.py
python
AuiPaneInfo.IsLeftSnappable
(self)
return self.HasFlag(self.optionLeftSnapped)
Returns ``True`` if the pane can be snapped on the left of the managed frame.
Returns ``True`` if the pane can be snapped on the left of the managed frame.
[ "Returns", "True", "if", "the", "pane", "can", "be", "snapped", "on", "the", "left", "of", "the", "managed", "frame", "." ]
def IsLeftSnappable(self): """ Returns ``True`` if the pane can be snapped on the left of the managed frame. """ return self.HasFlag(self.optionLeftSnapped)
[ "def", "IsLeftSnappable", "(", "self", ")", ":", "return", "self", ".", "HasFlag", "(", "self", ".", "optionLeftSnapped", ")" ]
https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/agw/aui/framemanager.py#L711-L714
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/core/data/misc/cookie_jar.py
python
ImprovedMozillaCookieJar._really_load
(self, f, filename, ignore_discard, ignore_expires)
Override this method in order to provide better error handling.
Override this method in order to provide better error handling.
[ "Override", "this", "method", "in", "order", "to", "provide", "better", "error", "handling", "." ]
def _really_load(self, f, filename, ignore_discard, ignore_expires): """ Override this method in order to provide better error handling. """ now = time.time() magic = f.readline() if not re.search(self.magic_re, magic): f.close() msg = "%r does not look like a Netscape format cookies file" raise LoadError(msg % filename) try: while 1: line = f.readline() if line == "": break # last field may be absent, so keep any trailing tab if line.endswith("\n"): line = line[:-1] # skip comments and blank lines XXX what is $ for? if line.strip().startswith(("#", "$")) or line.strip() == "": continue split_values = line.split("\t") if len(split_values) != 7: msg = 'Expected seven tab delimited fields, got %s in %s: %s' args = (len(split_values), filename, line) raise LoadError(msg % args) domain, domain_specified, path, secure, expires, name, value = split_values secure = (secure == "TRUE") domain_specified = (domain_specified == "TRUE") if name == "": # cookies.txt regards 'Set-Cookie: foo' as a cookie # with no name, whereas cookielib regards it as a # cookie with no value. name = value value = None initial_dot = domain.startswith(".") if domain_specified != initial_dot: if domain_specified: msg = ('The second tab delimited field (domain_specified) is' ' set to %s and the domain does NOT start with a dot (%s).' ' This is not acceptable by the Mozilla Cookie format.' ' Issue found at %s: %s') args = (domain_specified, domain, filename, line) raise LoadError(msg % args) else: msg = ('The second tab delimited field (domain_specified) is' ' set to %s and the domain starts with a dot (%s).' ' This is not acceptable by the Mozilla Cookie format.' ' Issue found at %s: %s') args = (domain_specified, domain, filename, line) raise LoadError(msg % args) discard = False if expires == "": expires = None discard = True # assume path_specified is false c = Cookie(0, name, value, None, False, domain, domain_specified, initial_dot, path, False, secure, expires, discard, None, None, {}) if not ignore_discard and c.discard: continue if not ignore_expires and c.is_expired(now): continue self.set_cookie(c) except IOError: raise except Exception: _warn_unhandled_exception() raise LoadError("invalid Netscape format cookies file %r: %r" % (filename, line))
[ "def", "_really_load", "(", "self", ",", "f", ",", "filename", ",", "ignore_discard", ",", "ignore_expires", ")", ":", "now", "=", "time", ".", "time", "(", ")", "magic", "=", "f", ".", "readline", "(", ")", "if", "not", "re", ".", "search", "(", "...
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/core/data/misc/cookie_jar.py#L29-L119
spesmilo/electrum
bdbd59300fbd35b01605e66145458e5f396108e8
electrum/gui/qt/util.py
python
FixedAspectRatioLayout.count
(self)
return len(self.items)
[]
def count(self) -> int: return len(self.items)
[ "def", "count", "(", "self", ")", "->", "int", ":", "return", "len", "(", "self", ".", "items", ")" ]
https://github.com/spesmilo/electrum/blob/bdbd59300fbd35b01605e66145458e5f396108e8/electrum/gui/qt/util.py#L1149-L1150
jxhe/vae-lagging-encoder
cdc4eb9d9599a026bf277db74efc2ba1ec203b15
data/text_data.py
python
MonoTextData.data_sample
(self, nsample, device, batch_first=False, shuffle=True)
return batch_data, sents_len
sample a subset of data (like data_iter) Returns: batch_data: LongTensor with shape (seq_len, batch_size) sents_len: list of data length, this is the data length after counting start and stop symbols
sample a subset of data (like data_iter) Returns: batch_data: LongTensor with shape (seq_len, batch_size) sents_len: list of data length, this is the data length after counting start and stop symbols
[ "sample", "a", "subset", "of", "data", "(", "like", "data_iter", ")", "Returns", ":", "batch_data", ":", "LongTensor", "with", "shape", "(", "seq_len", "batch_size", ")", "sents_len", ":", "list", "of", "data", "length", "this", "is", "the", "data", "lengt...
def data_sample(self, nsample, device, batch_first=False, shuffle=True): """sample a subset of data (like data_iter) Returns: batch_data: LongTensor with shape (seq_len, batch_size) sents_len: list of data length, this is the data length after counting start and stop symbols """ index_arr = np.arange(len(self.data)) if shuffle: np.random.shuffle(index_arr) batch_ids = index_arr[: nsample] batch_data = [self.data[index] for index in batch_ids] # uncomment this line if the dataset has variable length batch_data.sort(key=lambda e: -len(e)) batch_data, sents_len = self._to_tensor(batch_data, batch_first, device) return batch_data, sents_len
[ "def", "data_sample", "(", "self", ",", "nsample", ",", "device", ",", "batch_first", "=", "False", ",", "shuffle", "=", "True", ")", ":", "index_arr", "=", "np", ".", "arange", "(", "len", "(", "self", ".", "data", ")", ")", "if", "shuffle", ":", ...
https://github.com/jxhe/vae-lagging-encoder/blob/cdc4eb9d9599a026bf277db74efc2ba1ec203b15/data/text_data.py#L258-L279
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/preview/hosted_numbers/authorization_document/dependent_hosted_number_order.py
python
DependentHostedNumberOrderList.__init__
(self, version, signing_document_sid)
Initialize the DependentHostedNumberOrderList :param Version version: Version that contains the resource :param signing_document_sid: LOA document sid. :returns: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderList :rtype: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderList
Initialize the DependentHostedNumberOrderList
[ "Initialize", "the", "DependentHostedNumberOrderList" ]
def __init__(self, version, signing_document_sid): """ Initialize the DependentHostedNumberOrderList :param Version version: Version that contains the resource :param signing_document_sid: LOA document sid. :returns: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderList :rtype: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderList """ super(DependentHostedNumberOrderList, self).__init__(version) # Path Solution self._solution = {'signing_document_sid': signing_document_sid, } self._uri = '/AuthorizationDocuments/{signing_document_sid}/DependentHostedNumberOrders'.format(**self._solution)
[ "def", "__init__", "(", "self", ",", "version", ",", "signing_document_sid", ")", ":", "super", "(", "DependentHostedNumberOrderList", ",", "self", ")", ".", "__init__", "(", "version", ")", "# Path Solution", "self", ".", "_solution", "=", "{", "'signing_docume...
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/preview/hosted_numbers/authorization_document/dependent_hosted_number_order.py#L21-L35