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
conansherry/detectron2
72c935d9aad8935406b1038af408aa06077d950a
detectron2/structures/masks.py
python
BitMasks.from_polygon_masks
( polygon_masks: Union["PolygonMasks", List[List[np.ndarray]]], height: int, width: int )
return BitMasks(torch.stack([torch.from_numpy(x) for x in masks]))
Args: polygon_masks (list[list[ndarray]] or PolygonMasks) height, width (int)
Args: polygon_masks (list[list[ndarray]] or PolygonMasks) height, width (int)
[ "Args", ":", "polygon_masks", "(", "list", "[", "list", "[", "ndarray", "]]", "or", "PolygonMasks", ")", "height", "width", "(", "int", ")" ]
def from_polygon_masks( polygon_masks: Union["PolygonMasks", List[List[np.ndarray]]], height: int, width: int ) -> "BitMasks": """ Args: polygon_masks (list[list[ndarray]] or PolygonMasks) height, width (int) """ if isinstance(polygon_masks, PolygonMasks): polygon_masks = polygon_masks.polygons masks = [polygons_to_bitmask(p, height, width) for p in polygon_masks] return BitMasks(torch.stack([torch.from_numpy(x) for x in masks]))
[ "def", "from_polygon_masks", "(", "polygon_masks", ":", "Union", "[", "\"PolygonMasks\"", ",", "List", "[", "List", "[", "np", ".", "ndarray", "]", "]", "]", ",", "height", ":", "int", ",", "width", ":", "int", ")", "->", "\"BitMasks\"", ":", "if", "is...
https://github.com/conansherry/detectron2/blob/72c935d9aad8935406b1038af408aa06077d950a/detectron2/structures/masks.py#L150-L161
sripathikrishnan/redis-rdb-tools
548b11ec3c81a603f5b321228d07a61a0b940159
rdbtools/parser.py
python
DebugCallback.end_sorted_set
(self, key)
[]
def end_sorted_set(self, key): print('}')
[ "def", "end_sorted_set", "(", "self", ",", "key", ")", ":", "print", "(", "'}'", ")" ]
https://github.com/sripathikrishnan/redis-rdb-tools/blob/548b11ec3c81a603f5b321228d07a61a0b940159/rdbtools/parser.py#L1173-L1174
angr/angr
4b04d56ace135018083d36d9083805be8146688b
angr/engines/light/data.py
python
SpOffset.__gt__
(self, other)
return self.offset > other.offset
[]
def __gt__(self, other): if type(other) is not SpOffset or self.reg != other.reg: return NotImplemented return self.offset > other.offset
[ "def", "__gt__", "(", "self", ",", "other", ")", ":", "if", "type", "(", "other", ")", "is", "not", "SpOffset", "or", "self", ".", "reg", "!=", "other", ".", "reg", ":", "return", "NotImplemented", "return", "self", ".", "offset", ">", "other", ".", ...
https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/engines/light/data.py#L390-L393
mdiazcl/fuzzbunch-debian
2b76c2249ade83a389ae3badb12a1bd09901fd2c
windows/Resources/Python/Core/Lib/logging/handlers.py
python
SocketHandler.emit
(self, record)
Emit a record. Pickles the record and writes it to the socket in binary format. If there is an error with the socket, silently drop the packet. If there was a problem with the socket, re-establishes the socket.
Emit a record. Pickles the record and writes it to the socket in binary format. If there is an error with the socket, silently drop the packet. If there was a problem with the socket, re-establishes the socket.
[ "Emit", "a", "record", ".", "Pickles", "the", "record", "and", "writes", "it", "to", "the", "socket", "in", "binary", "format", ".", "If", "there", "is", "an", "error", "with", "the", "socket", "silently", "drop", "the", "packet", ".", "If", "there", "...
def emit(self, record): """ Emit a record. Pickles the record and writes it to the socket in binary format. If there is an error with the socket, silently drop the packet. If there was a problem with the socket, re-establishes the socket. """ try: s = self.makePickle(record) self.send(s) except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record)
[ "def", "emit", "(", "self", ",", "record", ")", ":", "try", ":", "s", "=", "self", ".", "makePickle", "(", "record", ")", "self", ".", "send", "(", "s", ")", "except", "(", "KeyboardInterrupt", ",", "SystemExit", ")", ":", "raise", "except", ":", "...
https://github.com/mdiazcl/fuzzbunch-debian/blob/2b76c2249ade83a389ae3badb12a1bd09901fd2c/windows/Resources/Python/Core/Lib/logging/handlers.py#L493-L508
psychopy/psychopy
01b674094f38d0e0bd51c45a6f66f671d7041696
psychopy/visual/backends/pygletbackend.py
python
PygletBackend._windowToBufferCoords
(self, pos)
return np.asarray(pos, dtype=np.float32)
Convert window coordinates to OpenGL buffer coordinates. The standard convention for window coordinates is that the origin is at the top-left corner. The `y` coordinate increases in the downwards direction. OpenGL places the origin at bottom left corner, where `y` increases in the upwards direction. Parameters ---------- pos : ArrayLike Position `(x, y)` in window coordinates. Returns ------- ndarray Position `(x, y)` in buffer coordinates.
Convert window coordinates to OpenGL buffer coordinates.
[ "Convert", "window", "coordinates", "to", "OpenGL", "buffer", "coordinates", "." ]
def _windowToBufferCoords(self, pos): """Convert window coordinates to OpenGL buffer coordinates. The standard convention for window coordinates is that the origin is at the top-left corner. The `y` coordinate increases in the downwards direction. OpenGL places the origin at bottom left corner, where `y` increases in the upwards direction. Parameters ---------- pos : ArrayLike Position `(x, y)` in window coordinates. Returns ------- ndarray Position `(x, y)` in buffer coordinates. """ # We override `_winToBufferCoords` here since Pyglet uses the OpenGL # window coordinate convention by default. return np.asarray(pos, dtype=np.float32)
[ "def", "_windowToBufferCoords", "(", "self", ",", "pos", ")", ":", "# We override `_winToBufferCoords` here since Pyglet uses the OpenGL", "# window coordinate convention by default.", "return", "np", ".", "asarray", "(", "pos", ",", "dtype", "=", "np", ".", "float32", ")...
https://github.com/psychopy/psychopy/blob/01b674094f38d0e0bd51c45a6f66f671d7041696/psychopy/visual/backends/pygletbackend.py#L648-L669
wishinlife/SyncY
71597eb523cc411e5f41558570d3814d52cfe92e
syncy.py
python
SYThread.__save_status2
(self, idx, startpos=0, endpos=0, status=0, rmd5='0' * 32)
[]
def __save_status2(self, idx, startpos=0, endpos=0, status=0, rmd5='0' * 32): with open('%s.db.syy' % self.__filepath, 'wb') as dbfile: if idx < 1: return dbfile.seek(idx * 35) dbfile.write(struct.pack('>H2qB16s', idx, startpos, endpos, status, rmd5.decode('hex'))) dbfile.flush() os.fsync(dbfile.fileno()) dbfile.close()
[ "def", "__save_status2", "(", "self", ",", "idx", ",", "startpos", "=", "0", ",", "endpos", "=", "0", ",", "status", "=", "0", ",", "rmd5", "=", "'0'", "*", "32", ")", ":", "with", "open", "(", "'%s.db.syy'", "%", "self", ".", "__filepath", ",", ...
https://github.com/wishinlife/SyncY/blob/71597eb523cc411e5f41558570d3814d52cfe92e/syncy.py#L2209-L2217
luyishisi/tensorflow
448e72bfb64f826aff8672d74fd7e59c0112e924
4.Object_Detection/object_detection/core/preprocessor.py
python
random_image_scale
(image, masks=None, min_scale_ratio=0.5, max_scale_ratio=2.0, seed=None)
Scales the image size. Args: image: rank 3 float32 tensor contains 1 image -> [height, width, channels]. masks: (optional) rank 3 float32 tensor containing masks with size [height, width, num_masks]. The value is set to None if there are no masks. min_scale_ratio: minimum scaling ratio. max_scale_ratio: maximum scaling ratio. seed: random seed. Returns: image: image which is the same rank as input image. masks: If masks is not none, resized masks which are the same rank as input masks will be returned.
Scales the image size.
[ "Scales", "the", "image", "size", "." ]
def random_image_scale(image, masks=None, min_scale_ratio=0.5, max_scale_ratio=2.0, seed=None): """Scales the image size. Args: image: rank 3 float32 tensor contains 1 image -> [height, width, channels]. masks: (optional) rank 3 float32 tensor containing masks with size [height, width, num_masks]. The value is set to None if there are no masks. min_scale_ratio: minimum scaling ratio. max_scale_ratio: maximum scaling ratio. seed: random seed. Returns: image: image which is the same rank as input image. masks: If masks is not none, resized masks which are the same rank as input masks will be returned. """ with tf.name_scope('RandomImageScale', values=[image]): result = [] image_shape = tf.shape(image) image_height = image_shape[0] image_width = image_shape[1] size_coef = tf.random_uniform([], minval=min_scale_ratio, maxval=max_scale_ratio, dtype=tf.float32, seed=seed) image_newysize = tf.to_int32( tf.multiply(tf.to_float(image_height), size_coef)) image_newxsize = tf.to_int32( tf.multiply(tf.to_float(image_width), size_coef)) image = tf.image.resize_images( image, [image_newysize, image_newxsize], align_corners=True) result.append(image) if masks: masks = tf.image.resize_nearest_neighbor( masks, [image_newysize, image_newxsize], align_corners=True) result.append(masks) return tuple(result)
[ "def", "random_image_scale", "(", "image", ",", "masks", "=", "None", ",", "min_scale_ratio", "=", "0.5", ",", "max_scale_ratio", "=", "2.0", ",", "seed", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "'RandomImageScale'", ",", "values", "="...
https://github.com/luyishisi/tensorflow/blob/448e72bfb64f826aff8672d74fd7e59c0112e924/4.Object_Detection/object_detection/core/preprocessor.py#L358-L399
Cartucho/mAP
3605865a350859e60c7b711838d09c4e0012c774
main.py
python
log_average_miss_rate
(prec, rec, num_images)
return lamr, mr, fppi
log-average miss rate: Calculated by averaging miss rates at 9 evenly spaced FPPI points between 10e-2 and 10e0, in log-space. output: lamr | log-average miss rate mr | miss rate fppi | false positives per image references: [1] Dollar, Piotr, et al. "Pedestrian Detection: An Evaluation of the State of the Art." Pattern Analysis and Machine Intelligence, IEEE Transactions on 34.4 (2012): 743 - 761.
log-average miss rate: Calculated by averaging miss rates at 9 evenly spaced FPPI points between 10e-2 and 10e0, in log-space.
[ "log", "-", "average", "miss", "rate", ":", "Calculated", "by", "averaging", "miss", "rates", "at", "9", "evenly", "spaced", "FPPI", "points", "between", "10e", "-", "2", "and", "10e0", "in", "log", "-", "space", "." ]
def log_average_miss_rate(prec, rec, num_images): """ log-average miss rate: Calculated by averaging miss rates at 9 evenly spaced FPPI points between 10e-2 and 10e0, in log-space. output: lamr | log-average miss rate mr | miss rate fppi | false positives per image references: [1] Dollar, Piotr, et al. "Pedestrian Detection: An Evaluation of the State of the Art." Pattern Analysis and Machine Intelligence, IEEE Transactions on 34.4 (2012): 743 - 761. """ # if there were no detections of that class if prec.size == 0: lamr = 0 mr = 1 fppi = 0 return lamr, mr, fppi fppi = (1 - prec) mr = (1 - rec) fppi_tmp = np.insert(fppi, 0, -1.0) mr_tmp = np.insert(mr, 0, 1.0) # Use 9 evenly spaced reference points in log-space ref = np.logspace(-2.0, 0.0, num = 9) for i, ref_i in enumerate(ref): # np.where() will always find at least 1 index, since min(ref) = 0.01 and min(fppi_tmp) = -1.0 j = np.where(fppi_tmp <= ref_i)[-1][-1] ref[i] = mr_tmp[j] # log(0) is undefined, so we use the np.maximum(1e-10, ref) lamr = math.exp(np.mean(np.log(np.maximum(1e-10, ref)))) return lamr, mr, fppi
[ "def", "log_average_miss_rate", "(", "prec", ",", "rec", ",", "num_images", ")", ":", "# if there were no detections of that class", "if", "prec", ".", "size", "==", "0", ":", "lamr", "=", "0", "mr", "=", "1", "fppi", "=", "0", "return", "lamr", ",", "mr",...
https://github.com/Cartucho/mAP/blob/3605865a350859e60c7b711838d09c4e0012c774/main.py#L80-L120
auth0/auth0-python
511b016ac9853c7f4ee66769be7ad315c5585735
auth0/v3/management/log_streams.py
python
LogStreams.delete
(self, id)
return self.client.delete(self._url(id))
Delete a log stream. Args: id (str): The id of the log ste to delete. See: https://auth0.com/docs/api/management/v2/#!/Log_Streams/delete_log_streams_by_id
Delete a log stream.
[ "Delete", "a", "log", "stream", "." ]
def delete(self, id): """Delete a log stream. Args: id (str): The id of the log ste to delete. See: https://auth0.com/docs/api/management/v2/#!/Log_Streams/delete_log_streams_by_id """ return self.client.delete(self._url(id))
[ "def", "delete", "(", "self", ",", "id", ")", ":", "return", "self", ".", "client", ".", "delete", "(", "self", ".", "_url", "(", "id", ")", ")" ]
https://github.com/auth0/auth0-python/blob/511b016ac9853c7f4ee66769be7ad315c5585735/auth0/v3/management/log_streams.py#L67-L75
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/dynamics/arithmetic_dynamics/projective_ds.py
python
DynamicalSystem_projective.sigma_invariants
(self, n, formal=False, embedding=None, type='point', return_polynomial=False, chow=False, deform=False, check=True)
return sig
r""" Computes the values of the elementary symmetric polynomials evaluated on the ``n`` multiplier spectra of this dynamical system. The sigma invariants are the symetric polynomials evaluated on the characteristic polynomial of the multipliers. See [Hutz2019]_ for the full definition. Spepcifically, this function returns either the following polynomial or its coefficients (with signs appropriately adjusted): .. MATH:: \prod_{P \text{ period n}} ( w - c(P,t)), where `c(P,t)` is the charateristic polynomial (variable `t`) of the multiplier at `P`. Note that in dimension 1, only the coefficients of the constant term is returned. The invariants can be computed for points of period ``n`` or points of formal period ``n``. The base ring should be a number field, number field order, or a finite field or a polynomial ring or function field over a number field, number field order, or finite field. The parameter ``type`` determines if the sigma are computed from the multipliers calculated at one per cycle (with multiplicity) or one per point (with multiplicity). Only implemented for dimension 1. Note that in the ``cycle`` case, a map with a cycle which collapses into multiple smaller cycles, this is still considered one cycle. In other words, if a 4-cycle collapses into a 2-cycle with multiplicity 2, there is only one multiplier used for the doubled 2-cycle when computing ``n=4``. ALGORITHM: In dimension 1, we use the Poisson product of the resultant of two polynomials: .. MATH:: res(f,g) = \prod_{f(a)=0} g(a). In higher dimensions, we use elimination theory (Groebner bases) to compute the equivalent of the Poisson product. Letting `f` be the polynomial defining the periodic or formal periodic points and `g` the polynomial `w - F` for an auxilarly variable `w` and `F` the characteristic polynomial of the Jacobian matrix of `f`. Note that if `f` is a rational function, we clear denominators for `g`. To calculate the full polynomial defining the sigma invariants, we follow the algorithm outlined in section 4 of [Hutz2019]_. There are 4 cases: - multipliers and ``n`` periodic points all distinct -- in this case, we can use Proposition 4.1 of [Hutz2019]_ to compute the sigma invariants. - ``n`` periodic points are all distinct, multipliers are repeated -- here we can use Proposition 4.2 of [Hutz2019]_ to compute the sigma invariants. This corresponds to ``chow=True``. - ``n`` periodic points are repeated, multipliers are all distinct -- to deal with this case, we deform the map by a formal parameter `k`. The deformation seperates the ``n`` periodic points, making them distinct, and we can recover the ``n`` periodic points of the original map by specializing `k` to 0. This corresponds to ``deform=True``. - ``n`` periodic points are repeated, multipliers are repeated -- here we can use both cases 2 and 3 together. This corresponds to ``deform=True`` and ``chow=True``. As we do not want to check which case we are in beforehand, we throw a ValueError if the computed polynomial does not have the correct degree. INPUT: - ``n`` -- a positive integer, the period - ``formal`` -- (default: ``False``) boolean; ``True`` specifies to find the values of the elementary symmetric polynomials corresponding to the formal ``n`` multiplier spectra and ``False`` specifies to instead find the values corresponding to the ``n`` multiplier spectra, which includes the multipliers of all periodic points of period ``n`` - ``embedding`` -- (default: ``None``) must be ``None``, passing an embedding is no longer supported, see :trac: `32205`. - ``type`` -- (default: ``'point'``) string; either ``'point'`` or ``'cycle'`` depending on whether you compute with one multiplier per point or one per cycle. Not implemented for dimension greater than 1. - ``return polynomial`` -- (default: ``False``) boolean; ``True`` specifies returning the polynomial which generates the sigma invariants, see [Hutz2019]_ for the full definition. The polynomial is always a multivariate polynomial with variables ``w`` and ``t``. - ``chow`` -- (default: ``False``) boolean; ``True`` specifies using the Chow algorithm from [Hutz2019]_ to compute the sigma invariants. While slower, the Chow algorithm does not lose information about multiplicities of the multipliers. In order to accurately compute the sigma polynomial when there is a repeated multiplier, ``chow`` must be ``True``. - ``deform`` -- (default: ``False``) boolean; ``True`` specifies first deforming the map so that all periodic points are distinct and then calculating the sigma invariants. In order to accurately calculate the sigma polynomial when there is a periodic point with multiplicity, ``deform`` must be ``True``. - ``check`` -- (default: ``True``) boolean; when ``True`` the degree of the sigma polynomial is checked against the expected degree. This is done as the sigma polynomial may drop degree if multiplicites of periodic points or multipliers are not correctly accounted for using ``chow`` or ``deform``. .. WARNING:: Setting ``check`` to ``False`` can lead to mathematically incorrect answers. OUTPUT: a list of elements in the base ring, unless ``return_polynomial`` is ``True``, in which case a polynomial in ``w`` and ``t`` is returned. The variable ``t`` is the variable of the characteristic polynomials of the multipliers. If this map is defined over `\mathbb{P}^N`, where `N > 1`, then the list is the coefficients of `w` and `t`, in lexographical order with `w > t`. EXAMPLES:: sage: P.<x,y> = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 + x*y + y^2, y^2 + x*y]) sage: f.sigma_invariants(1) [3, 3, 1] If ``return_polynomial`` is ``True``, then following [Hutz2019]_ we return a two variable polynomial in `w` and `t`:: sage: P.<x,y> = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 + 2*y^2, y^2]) sage: poly = f.sigma_invariants(1, return_polynomial=True); poly w^3 - 3*w^2*t + 2*w^2 + 3*w*t^2 - 4*w*t + 8*w - t^3 + 2*t^2 - 8*t From the full polynomial, we can easily recover the one variable polynomial whose coefficients are symmetric functions in the multipliers, up to sign:: sage: w, t = poly.variables() sage: poly.specialization({w:0}).monic() t^3 - 2*t^2 + 8*t sage: f.sigma_invariants(1) [2, 8, 0] For dynamical systems on `\mathbb{P}^N`, where `N > 1`, the full polynomial is needed to distinguish the conjugacy class. We can, however, still return a list in this case:: sage: P.<x,y,z> = ProjectiveSpace(QQ, 2) sage: f = DynamicalSystem_projective([x^2, z^2, y^2]) sage: f.sigma_invariants(1, chow=True) [1, 7, -6, -12, 21, -36, -60, 72, 48, 35, -90, -120, 352, 96, -288, -64, 35, -120, -120, 688, -96, -1056, 320, 384, 0, 21, -90, -60, 672, -384, -1440, 1344, 768, -768, 0, 0, 7, -36, -12, 328, -336, -864, 1472, 384, -1536, 512, 0, 0, 0, 1, -6, 0, 64, -96, -192, 512, 0, -768, 512, 0, 0, 0, 0, 0] When calculating the sigma invariants for `\mathbb{P}^N`, with `N > 1`, the default algorithm loses information about multiplicities. Note that the following call to sigma invariants returns a degree 6 polynomial in `w`:: sage: P.<x,y,z> = ProjectiveSpace(QQ, 2) sage: f = DynamicalSystem_projective([x^2, y^2, z^2]) sage: f.sigma_invariants(1, return_polynomial=True, check=False) w^6 - 6*w^5*t^2 + 8*w^5*t - 4*w^5 + 15*w^4*t^4 - 40*w^4*t^3 + 40*w^4*t^2 - 16*w^4*t - 20*w^3*t^6 + 80*w^3*t^5 - 120*w^3*t^4 + 80*w^3*t^3 - 16*w^3*t^2 + 15*w^2*t^8 - 80*w^2*t^7 + 160*w^2*t^6 - 144*w^2*t^5 + 48*w^2*t^4 - 6*w*t^10 + 40*w*t^9 - 100*w*t^8 + 112*w*t^7 - 48*w*t^6 + t^12 - 8*t^11 + 24*t^10 - 32*t^9 + 16*t^8 Setting ``chow`` to ``True``, while much slower, accounts correctly for multiplicities. Note that the following returns a degree 7 polynomial in `w`:: sage: f.sigma_invariants(1, return_polynomial=True, chow=True) w^7 - 7*w^6*t^2 + 10*w^6*t - 4*w^6 + 21*w^5*t^4 - 60*w^5*t^3 + 60*w^5*t^2 - 24*w^5*t - 35*w^4*t^6 + 150*w^4*t^5 - 240*w^4*t^4 + 176*w^4*t^3 - 48*w^4*t^2 + 35*w^3*t^8 - 200*w^3*t^7 + 440*w^3*t^6 - 464*w^3*t^5 + 224*w^3*t^4 - 32*w^3*t^3 - 21*w^2*t^10 + 150*w^2*t^9 - 420*w^2*t^8 + 576*w^2*t^7 - 384*w^2*t^6 + 96*w^2*t^5 + 7*w*t^12 - 60*w*t^11 + 204*w*t^10 - 344*w*t^9 + 288*w*t^8 - 96*w*t^7 - t^14 + 10*t^13 - 40*t^12 + 80*t^11 - 80*t^10 + 32*t^9 :: sage: set_verbose(None) sage: z = QQ['z'].0 sage: K = NumberField(z^4 - 4*z^2 + 1, 'z') sage: P.<x,y> = ProjectiveSpace(K, 1) sage: f = DynamicalSystem_projective([x^2 - 5/4*y^2, y^2]) sage: f.sigma_invariants(2, formal=False, type='cycle') [13, 11, -25, 0] sage: f.sigma_invariants(2, formal=False, type='point') [12, -2, -36, 25, 0] check that infinity as part of a longer cycle is handled correctly:: sage: P.<x,y> = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([y^2, x^2]) sage: f.sigma_invariants(2, type='cycle') [12, 48, 64, 0] sage: f.sigma_invariants(2, type='point') [12, 48, 64, 0, 0] sage: f.sigma_invariants(2, type='cycle', formal=True) [0] sage: f.sigma_invariants(2, type='point', formal=True) [0, 0] :: sage: K.<w> = QuadraticField(3) sage: P.<x,y> = ProjectiveSpace(K, 1) sage: f = DynamicalSystem_projective([x^2 - w*y^2, (1-w)*x*y]) sage: f.sigma_invariants(2, formal=False, type='cycle') [6*w + 21, 78*w + 159, 210*w + 367, 90*w + 156] sage: f.sigma_invariants(2, formal=False, type='point') [6*w + 24, 96*w + 222, 444*w + 844, 720*w + 1257, 270*w + 468] :: sage: P.<x,y> = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([512*x^5 - 378128*x^4*y + 76594292*x^3*y^2 - 4570550136*x^2*y^3 - 2630045017*x*y^4\ + 28193217129*y^5, 512*y^5]) sage: f.sigma_invariants(1) [19575526074450617/1048576, -9078122048145044298567432325/2147483648, -2622661114909099878224381377917540931367/1099511627776, -2622661107937102104196133701280271632423/549755813888, 338523204830161116503153209450763500631714178825448006778305/72057594037927936, 0] :: sage: P.<x,y,z> = ProjectiveSpace(GF(5), 2) sage: f = DynamicalSystem([x^2, y^2, z^2]) sage: f.sigma_invariants(1, chow=True, return_polynomial=True) w^7 - 2*w^6*t^2 + w^6 + w^5*t^4 + w^5*t + w^4*t^3 + 2*w^4*t^2 + w^3*t^5 - w^3*t^4 - 2*w^3*t^3 - w^2*t^10 + w^2*t^7 + w^2*t^6 + w^2*t^5 + 2*w*t^12 - w*t^10 + w*t^9 - 2*w*t^8 - w*t^7 - t^14 + 2*t^9 :: sage: R.<c> = QQ[] sage: Pc.<x,y> = ProjectiveSpace(R, 1) sage: f = DynamicalSystem_projective([x^2 + c*y^2, y^2]) sage: f.sigma_invariants(1) [2, 4*c, 0] sage: f.sigma_invariants(2, formal=True, type='point') [8*c + 8, 16*c^2 + 32*c + 16] sage: f.sigma_invariants(2, formal=True, type='cycle') [4*c + 4] :: sage: R.<c> = QQ[] sage: P.<x,y> = ProjectiveSpace(R, 1) sage: f = DynamicalSystem([x^2 + c*y^2, y^2]) sage: f.sigma_invariants(1, return_polynomial=True) w^3 + (-3)*w^2*t + 2*w^2 + 3*w*t^2 + (-4)*w*t + 4*c*w - t^3 + 2*t^2 + (-4*c)*t sage: f.sigma_invariants(2, chow=True, formal=True, return_polynomial=True) w^2 + (-2)*w*t + (8*c + 8)*w + t^2 + (-8*c - 8)*t + 16*c^2 + 32*c + 16 :: sage: R.<c,d> = QQ[] sage: P.<x,y,z> = ProjectiveSpace(R, 2) sage: f = DynamicalSystem([x^2 + c*z^2, y^2 + d*z^2, z^2]) sage: len(dict(f.sigma_invariants(1, return_polynomial=True))) 51 :: sage: P.<x,y> = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem([x^2 + 3*y^2, x*y]) sage: f.sigma_invariants(1, deform = True, return_polynomial=True) w^3 - 3*w^2*t + 3*w^2 + 3*w*t^2 - 6*w*t + 3*w - t^3 + 3*t^2 - 3*t + 1 doubled fixed point:: sage: P.<x,y> = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 - 3/4*y^2, y^2]) sage: f.sigma_invariants(2, formal=True) [2, 1] doubled 2 cycle:: sage: P.<x,y> = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 - 5/4*y^2, y^2]) sage: f.sigma_invariants(4, formal=False, type='cycle') [170, 5195, 172700, 968615, 1439066, 638125, 0] TESTS:: sage: F.<t> = FunctionField(GF(5)) sage: P.<x,y> = ProjectiveSpace(F,1) sage: f = DynamicalSystem_projective([x^2 + (t/(t^2+1))*y^2, y^2], P) sage: f.sigma_invariants(1) [2, 4*t/(t^2 + 1), 0] :: sage: R.<w> = QQ[] sage: N.<n> = NumberField(w^2 + 1) sage: P.<x,y,z> = ProjectiveSpace(N, 2) sage: f = DynamicalSystem_projective([x^2, y^2, z^2]) sage: f.sigma_invariants(1, chow=True) == f.change_ring(QQ).sigma_invariants(1, chow=True) True :: sage: P.<x,y> = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem([x^2 + 3*y^2, x*y]) sage: f.sigma_invariants(1, formal=True, return_polynomial=True) Traceback (most recent call last): .. ValueError: sigma polynomial dropped degree, as multiplicities were not accounted for correctly. try setting chow=True and/or deform=True :: sage: P.<x,y> = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem([x^2 + 3*y^2, x*y]) sage: f.sigma_invariants(1, return_polynomial=True) Traceback (most recent call last): .. ValueError: sigma polynomial dropped degree, as multiplicities were not accounted for correctly. try setting chow=True and/or deform=True
r""" Computes the values of the elementary symmetric polynomials evaluated on the ``n`` multiplier spectra of this dynamical system.
[ "r", "Computes", "the", "values", "of", "the", "elementary", "symmetric", "polynomials", "evaluated", "on", "the", "n", "multiplier", "spectra", "of", "this", "dynamical", "system", "." ]
def sigma_invariants(self, n, formal=False, embedding=None, type='point', return_polynomial=False, chow=False, deform=False, check=True): r""" Computes the values of the elementary symmetric polynomials evaluated on the ``n`` multiplier spectra of this dynamical system. The sigma invariants are the symetric polynomials evaluated on the characteristic polynomial of the multipliers. See [Hutz2019]_ for the full definition. Spepcifically, this function returns either the following polynomial or its coefficients (with signs appropriately adjusted): .. MATH:: \prod_{P \text{ period n}} ( w - c(P,t)), where `c(P,t)` is the charateristic polynomial (variable `t`) of the multiplier at `P`. Note that in dimension 1, only the coefficients of the constant term is returned. The invariants can be computed for points of period ``n`` or points of formal period ``n``. The base ring should be a number field, number field order, or a finite field or a polynomial ring or function field over a number field, number field order, or finite field. The parameter ``type`` determines if the sigma are computed from the multipliers calculated at one per cycle (with multiplicity) or one per point (with multiplicity). Only implemented for dimension 1. Note that in the ``cycle`` case, a map with a cycle which collapses into multiple smaller cycles, this is still considered one cycle. In other words, if a 4-cycle collapses into a 2-cycle with multiplicity 2, there is only one multiplier used for the doubled 2-cycle when computing ``n=4``. ALGORITHM: In dimension 1, we use the Poisson product of the resultant of two polynomials: .. MATH:: res(f,g) = \prod_{f(a)=0} g(a). In higher dimensions, we use elimination theory (Groebner bases) to compute the equivalent of the Poisson product. Letting `f` be the polynomial defining the periodic or formal periodic points and `g` the polynomial `w - F` for an auxilarly variable `w` and `F` the characteristic polynomial of the Jacobian matrix of `f`. Note that if `f` is a rational function, we clear denominators for `g`. To calculate the full polynomial defining the sigma invariants, we follow the algorithm outlined in section 4 of [Hutz2019]_. There are 4 cases: - multipliers and ``n`` periodic points all distinct -- in this case, we can use Proposition 4.1 of [Hutz2019]_ to compute the sigma invariants. - ``n`` periodic points are all distinct, multipliers are repeated -- here we can use Proposition 4.2 of [Hutz2019]_ to compute the sigma invariants. This corresponds to ``chow=True``. - ``n`` periodic points are repeated, multipliers are all distinct -- to deal with this case, we deform the map by a formal parameter `k`. The deformation seperates the ``n`` periodic points, making them distinct, and we can recover the ``n`` periodic points of the original map by specializing `k` to 0. This corresponds to ``deform=True``. - ``n`` periodic points are repeated, multipliers are repeated -- here we can use both cases 2 and 3 together. This corresponds to ``deform=True`` and ``chow=True``. As we do not want to check which case we are in beforehand, we throw a ValueError if the computed polynomial does not have the correct degree. INPUT: - ``n`` -- a positive integer, the period - ``formal`` -- (default: ``False``) boolean; ``True`` specifies to find the values of the elementary symmetric polynomials corresponding to the formal ``n`` multiplier spectra and ``False`` specifies to instead find the values corresponding to the ``n`` multiplier spectra, which includes the multipliers of all periodic points of period ``n`` - ``embedding`` -- (default: ``None``) must be ``None``, passing an embedding is no longer supported, see :trac: `32205`. - ``type`` -- (default: ``'point'``) string; either ``'point'`` or ``'cycle'`` depending on whether you compute with one multiplier per point or one per cycle. Not implemented for dimension greater than 1. - ``return polynomial`` -- (default: ``False``) boolean; ``True`` specifies returning the polynomial which generates the sigma invariants, see [Hutz2019]_ for the full definition. The polynomial is always a multivariate polynomial with variables ``w`` and ``t``. - ``chow`` -- (default: ``False``) boolean; ``True`` specifies using the Chow algorithm from [Hutz2019]_ to compute the sigma invariants. While slower, the Chow algorithm does not lose information about multiplicities of the multipliers. In order to accurately compute the sigma polynomial when there is a repeated multiplier, ``chow`` must be ``True``. - ``deform`` -- (default: ``False``) boolean; ``True`` specifies first deforming the map so that all periodic points are distinct and then calculating the sigma invariants. In order to accurately calculate the sigma polynomial when there is a periodic point with multiplicity, ``deform`` must be ``True``. - ``check`` -- (default: ``True``) boolean; when ``True`` the degree of the sigma polynomial is checked against the expected degree. This is done as the sigma polynomial may drop degree if multiplicites of periodic points or multipliers are not correctly accounted for using ``chow`` or ``deform``. .. WARNING:: Setting ``check`` to ``False`` can lead to mathematically incorrect answers. OUTPUT: a list of elements in the base ring, unless ``return_polynomial`` is ``True``, in which case a polynomial in ``w`` and ``t`` is returned. The variable ``t`` is the variable of the characteristic polynomials of the multipliers. If this map is defined over `\mathbb{P}^N`, where `N > 1`, then the list is the coefficients of `w` and `t`, in lexographical order with `w > t`. EXAMPLES:: sage: P.<x,y> = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 + x*y + y^2, y^2 + x*y]) sage: f.sigma_invariants(1) [3, 3, 1] If ``return_polynomial`` is ``True``, then following [Hutz2019]_ we return a two variable polynomial in `w` and `t`:: sage: P.<x,y> = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 + 2*y^2, y^2]) sage: poly = f.sigma_invariants(1, return_polynomial=True); poly w^3 - 3*w^2*t + 2*w^2 + 3*w*t^2 - 4*w*t + 8*w - t^3 + 2*t^2 - 8*t From the full polynomial, we can easily recover the one variable polynomial whose coefficients are symmetric functions in the multipliers, up to sign:: sage: w, t = poly.variables() sage: poly.specialization({w:0}).monic() t^3 - 2*t^2 + 8*t sage: f.sigma_invariants(1) [2, 8, 0] For dynamical systems on `\mathbb{P}^N`, where `N > 1`, the full polynomial is needed to distinguish the conjugacy class. We can, however, still return a list in this case:: sage: P.<x,y,z> = ProjectiveSpace(QQ, 2) sage: f = DynamicalSystem_projective([x^2, z^2, y^2]) sage: f.sigma_invariants(1, chow=True) [1, 7, -6, -12, 21, -36, -60, 72, 48, 35, -90, -120, 352, 96, -288, -64, 35, -120, -120, 688, -96, -1056, 320, 384, 0, 21, -90, -60, 672, -384, -1440, 1344, 768, -768, 0, 0, 7, -36, -12, 328, -336, -864, 1472, 384, -1536, 512, 0, 0, 0, 1, -6, 0, 64, -96, -192, 512, 0, -768, 512, 0, 0, 0, 0, 0] When calculating the sigma invariants for `\mathbb{P}^N`, with `N > 1`, the default algorithm loses information about multiplicities. Note that the following call to sigma invariants returns a degree 6 polynomial in `w`:: sage: P.<x,y,z> = ProjectiveSpace(QQ, 2) sage: f = DynamicalSystem_projective([x^2, y^2, z^2]) sage: f.sigma_invariants(1, return_polynomial=True, check=False) w^6 - 6*w^5*t^2 + 8*w^5*t - 4*w^5 + 15*w^4*t^4 - 40*w^4*t^3 + 40*w^4*t^2 - 16*w^4*t - 20*w^3*t^6 + 80*w^3*t^5 - 120*w^3*t^4 + 80*w^3*t^3 - 16*w^3*t^2 + 15*w^2*t^8 - 80*w^2*t^7 + 160*w^2*t^6 - 144*w^2*t^5 + 48*w^2*t^4 - 6*w*t^10 + 40*w*t^9 - 100*w*t^8 + 112*w*t^7 - 48*w*t^6 + t^12 - 8*t^11 + 24*t^10 - 32*t^9 + 16*t^8 Setting ``chow`` to ``True``, while much slower, accounts correctly for multiplicities. Note that the following returns a degree 7 polynomial in `w`:: sage: f.sigma_invariants(1, return_polynomial=True, chow=True) w^7 - 7*w^6*t^2 + 10*w^6*t - 4*w^6 + 21*w^5*t^4 - 60*w^5*t^3 + 60*w^5*t^2 - 24*w^5*t - 35*w^4*t^6 + 150*w^4*t^5 - 240*w^4*t^4 + 176*w^4*t^3 - 48*w^4*t^2 + 35*w^3*t^8 - 200*w^3*t^7 + 440*w^3*t^6 - 464*w^3*t^5 + 224*w^3*t^4 - 32*w^3*t^3 - 21*w^2*t^10 + 150*w^2*t^9 - 420*w^2*t^8 + 576*w^2*t^7 - 384*w^2*t^6 + 96*w^2*t^5 + 7*w*t^12 - 60*w*t^11 + 204*w*t^10 - 344*w*t^9 + 288*w*t^8 - 96*w*t^7 - t^14 + 10*t^13 - 40*t^12 + 80*t^11 - 80*t^10 + 32*t^9 :: sage: set_verbose(None) sage: z = QQ['z'].0 sage: K = NumberField(z^4 - 4*z^2 + 1, 'z') sage: P.<x,y> = ProjectiveSpace(K, 1) sage: f = DynamicalSystem_projective([x^2 - 5/4*y^2, y^2]) sage: f.sigma_invariants(2, formal=False, type='cycle') [13, 11, -25, 0] sage: f.sigma_invariants(2, formal=False, type='point') [12, -2, -36, 25, 0] check that infinity as part of a longer cycle is handled correctly:: sage: P.<x,y> = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([y^2, x^2]) sage: f.sigma_invariants(2, type='cycle') [12, 48, 64, 0] sage: f.sigma_invariants(2, type='point') [12, 48, 64, 0, 0] sage: f.sigma_invariants(2, type='cycle', formal=True) [0] sage: f.sigma_invariants(2, type='point', formal=True) [0, 0] :: sage: K.<w> = QuadraticField(3) sage: P.<x,y> = ProjectiveSpace(K, 1) sage: f = DynamicalSystem_projective([x^2 - w*y^2, (1-w)*x*y]) sage: f.sigma_invariants(2, formal=False, type='cycle') [6*w + 21, 78*w + 159, 210*w + 367, 90*w + 156] sage: f.sigma_invariants(2, formal=False, type='point') [6*w + 24, 96*w + 222, 444*w + 844, 720*w + 1257, 270*w + 468] :: sage: P.<x,y> = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([512*x^5 - 378128*x^4*y + 76594292*x^3*y^2 - 4570550136*x^2*y^3 - 2630045017*x*y^4\ + 28193217129*y^5, 512*y^5]) sage: f.sigma_invariants(1) [19575526074450617/1048576, -9078122048145044298567432325/2147483648, -2622661114909099878224381377917540931367/1099511627776, -2622661107937102104196133701280271632423/549755813888, 338523204830161116503153209450763500631714178825448006778305/72057594037927936, 0] :: sage: P.<x,y,z> = ProjectiveSpace(GF(5), 2) sage: f = DynamicalSystem([x^2, y^2, z^2]) sage: f.sigma_invariants(1, chow=True, return_polynomial=True) w^7 - 2*w^6*t^2 + w^6 + w^5*t^4 + w^5*t + w^4*t^3 + 2*w^4*t^2 + w^3*t^5 - w^3*t^4 - 2*w^3*t^3 - w^2*t^10 + w^2*t^7 + w^2*t^6 + w^2*t^5 + 2*w*t^12 - w*t^10 + w*t^9 - 2*w*t^8 - w*t^7 - t^14 + 2*t^9 :: sage: R.<c> = QQ[] sage: Pc.<x,y> = ProjectiveSpace(R, 1) sage: f = DynamicalSystem_projective([x^2 + c*y^2, y^2]) sage: f.sigma_invariants(1) [2, 4*c, 0] sage: f.sigma_invariants(2, formal=True, type='point') [8*c + 8, 16*c^2 + 32*c + 16] sage: f.sigma_invariants(2, formal=True, type='cycle') [4*c + 4] :: sage: R.<c> = QQ[] sage: P.<x,y> = ProjectiveSpace(R, 1) sage: f = DynamicalSystem([x^2 + c*y^2, y^2]) sage: f.sigma_invariants(1, return_polynomial=True) w^3 + (-3)*w^2*t + 2*w^2 + 3*w*t^2 + (-4)*w*t + 4*c*w - t^3 + 2*t^2 + (-4*c)*t sage: f.sigma_invariants(2, chow=True, formal=True, return_polynomial=True) w^2 + (-2)*w*t + (8*c + 8)*w + t^2 + (-8*c - 8)*t + 16*c^2 + 32*c + 16 :: sage: R.<c,d> = QQ[] sage: P.<x,y,z> = ProjectiveSpace(R, 2) sage: f = DynamicalSystem([x^2 + c*z^2, y^2 + d*z^2, z^2]) sage: len(dict(f.sigma_invariants(1, return_polynomial=True))) 51 :: sage: P.<x,y> = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem([x^2 + 3*y^2, x*y]) sage: f.sigma_invariants(1, deform = True, return_polynomial=True) w^3 - 3*w^2*t + 3*w^2 + 3*w*t^2 - 6*w*t + 3*w - t^3 + 3*t^2 - 3*t + 1 doubled fixed point:: sage: P.<x,y> = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 - 3/4*y^2, y^2]) sage: f.sigma_invariants(2, formal=True) [2, 1] doubled 2 cycle:: sage: P.<x,y> = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem_projective([x^2 - 5/4*y^2, y^2]) sage: f.sigma_invariants(4, formal=False, type='cycle') [170, 5195, 172700, 968615, 1439066, 638125, 0] TESTS:: sage: F.<t> = FunctionField(GF(5)) sage: P.<x,y> = ProjectiveSpace(F,1) sage: f = DynamicalSystem_projective([x^2 + (t/(t^2+1))*y^2, y^2], P) sage: f.sigma_invariants(1) [2, 4*t/(t^2 + 1), 0] :: sage: R.<w> = QQ[] sage: N.<n> = NumberField(w^2 + 1) sage: P.<x,y,z> = ProjectiveSpace(N, 2) sage: f = DynamicalSystem_projective([x^2, y^2, z^2]) sage: f.sigma_invariants(1, chow=True) == f.change_ring(QQ).sigma_invariants(1, chow=True) True :: sage: P.<x,y> = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem([x^2 + 3*y^2, x*y]) sage: f.sigma_invariants(1, formal=True, return_polynomial=True) Traceback (most recent call last): .. ValueError: sigma polynomial dropped degree, as multiplicities were not accounted for correctly. try setting chow=True and/or deform=True :: sage: P.<x,y> = ProjectiveSpace(QQ, 1) sage: f = DynamicalSystem([x^2 + 3*y^2, x*y]) sage: f.sigma_invariants(1, return_polynomial=True) Traceback (most recent call last): .. ValueError: sigma polynomial dropped degree, as multiplicities were not accounted for correctly. try setting chow=True and/or deform=True """ n = ZZ(n) if embedding is not None: raise ValueError('do not specify an embedding') if n < 1: raise ValueError("period must be a positive integer") dom = self.domain() if not is_ProjectiveSpace(dom): raise NotImplementedError("not implemented for subschemes") if self.degree() <= 1: raise TypeError("must have degree at least 2") if type not in ['point', 'cycle']: raise ValueError("type must be either point or cycle") if dom.dimension_relative() > 1 or return_polynomial: if type == 'cycle': raise NotImplementedError('cycle not implemented for dimension greater than 1') base_ring = self.base_ring() d = self.degree() N = dom.dimension_relative() f = copy(self) Fn = f.nth_iterate_map(n) CR = f.codomain().ambient_space().coordinate_ring() if deform: # we need a model with all affine periodic points new_f = f.affine_preperiodic_model(0, n) new_f.normalize_coordinates() # we now deform by a parameter t T = base_ring['k'] k = T.gens()[0] Pt = ProjectiveSpace(N, R=T, names = [str(i) for i in CR.gens()]) deformed_polys = [poly + k*Pt.gens()[-1]**d for poly in new_f.defining_polynomials()[:-1]] deformed_polys += [new_f.defining_polynomials()[-1]] f_deformed = DynamicalSystem(deformed_polys) sigma_poly = f_deformed.sigma_invariants(n, chow=chow, deform=False, return_polynomial=True, check=False) sigma_polynomial = sigma_poly.specialization({k:0}) # we fix the ordering of the parent polynomial ring new_parent = sigma_polynomial.parent().change_ring(order='lex') sigma_polynomial = new_parent(sigma_polynomial) sigma_polynomial *= sigma_polynomial.coefficients()[0].inverse_of_unit() else: if not base_ring.is_field(): F = FractionField(base_ring) f.normalize_coordinates() X = f.periodic_points(n, minimal=False, formal=formal, return_scheme=True) X = X.change_ring(F) else: F = base_ring if is_FractionField(base_ring): if is_MPolynomialRing(base_ring.ring()) or is_PolynomialRing(base_ring.ring()): f.normalize_coordinates() f_ring = f.change_ring(base_ring.ring()) X = f_ring.periodic_points(n, minimal=False, formal=formal, return_scheme=True) X = X.change_ring(F) else: X = f.periodic_points(n, minimal=False, formal=formal, return_scheme=True) newR = PolynomialRing(F, 'w, t', 2, order='lex') if not base_ring.is_field(): ringR = PolynomialRing(base_ring, 'w, t', 2, order='lex') if chow: # create full polynomial ring R = PolynomialRing(F, 'v', 2*N+3, order='lex') var = list(R.gens()) # create polynomial ring for result R2 = PolynomialRing(F, var[:N] + var[-2:]) psi = R2.hom(N*[0]+list(newR.gens()), newR) # create substition to set extra variables to 0 R_zero = {R.gen(N):1} for j in range(N+1, 2*N+1): R_zero[R.gen(j)] = 0 t = var.pop() w = var.pop() var = var[:N] else: R = PolynomialRing(F, 'v', N+2, order='lex') psi = R.hom(N*[0] + list(newR.gens()), newR) var = list(R.gens()) t = var.pop() w = var.pop() sigma_polynomial = 1 # go through each affine patch to avoid repeating periodic points # setting the visited coordiantes to 0 as we go for j in range(N,-1,-1): Xa = X.affine_patch(j) fa = Fn.dehomogenize(j) Pa = fa.domain() Ra = Pa.coordinate_ring() # create the images for the Hom to the ring we will do the elimination over # with done affine patch coordinates as 0 if chow: im = [R.gen(i) for i in range(j)] + (N-j)*[0] + [R.gen(i) for i in range(N, R.ngens())] else: im = list(R.gens())[:j] + (N-j)*[0] + [R.gen(i) for i in range(N, R.ngens())] phi = Ra.hom(R.gens()[0:len(Ra.gens())]) # create polymomial that evaluates to the characteristic polynomial M = t*matrix.identity(R, N) g = (M-jacobian([phi(F.numerator())/phi(F.denominator()) for F in fa], var)).det() # create the terms of the sigma invariants prod(w-lambda) g_prime = w*R(g.denominator())(im)-R(g.numerator())(im) # move the defining polynomials to the polynomial ring L = [phi(h)(im) for h in Xa.defining_polynomials()] # add the appropriate final polynomial to compute the sigma invariant polynomial # via a Poisson product in elimination if chow: L += [g_prime + sum(R.gen(j-1)*R.gen(N+j)*(R(g.denominator())(im)) for j in range(1,N+1))] else: L += [g_prime] I = R.ideal(L) # since R is lex ordering, this is an elimination step G = I.groebner_basis() # the polynomial we need is the one just in w and t if chow: poly = psi(G[-1].specialization(R_zero)) if len(list(poly)) > 0: poly *= poly.coefficients()[0].inverse_of_unit() else: poly = psi(G[-1]) if not base_ring.is_field(): denom = lcm([coeff[0].denominator() for coeff in poly]) poly *= denom sigma_polynomial *= poly if not base_ring.is_field(): sigma_polynomial = ringR(sigma_polynomial) if check: degree_w = sigma_polynomial.degrees()[0] if formal: expected_degree = 0 for D in n.divisors(): u = moebius(n/D) inner_sum = sum(d**(D*j) for j in range(N+1)) expected_degree += u*inner_sum else: expected_degree = sum(d**(n*i) for i in range(N+1)) if degree_w != expected_degree: raise ValueError('sigma polynomial dropped degree, as multiplicities were not accounted for correctly.'+ ' try setting chow=True and/or deform=True') if return_polynomial: return sigma_polynomial # if we are returing a numerical list, read off the coefficients # in order of degree adjusting sign appropriately sigmas = [] sigma_dictionary = dict([list(reversed(i)) for i in list(sigma_polynomial)]) degree_w = sigma_polynomial.degrees()[0] w, t = sigma_polynomial.variables() for i in range(degree_w + 1): for j in range(2*i, -1, -1): sigmas.append((-1)**(i+j)*sigma_dictionary.pop(w**(degree_w - i)*t**(j), 0)) return sigmas base_ring = dom.base_ring() if is_FractionField(base_ring): base_ring = base_ring.ring() if (is_PolynomialRing(base_ring) or is_MPolynomialRing(base_ring)): base_ring = base_ring.base_ring() elif base_ring in FunctionFields(): base_ring = base_ring.constant_base_field() from sage.rings.number_field.order import is_NumberFieldOrder if not (base_ring in NumberFields() or is_NumberFieldOrder(base_ring) or (base_ring in FiniteFields())): raise NotImplementedError("incompatible base field, see documentation") #now we find the two polynomials for the resultant Fn = self.nth_iterate_map(n) fn = Fn.dehomogenize(1) R = fn.domain().coordinate_ring() S = PolynomialRing(FractionField(self.base_ring()), 'z', 2) phi = R.hom([S.gen(0)], S) psi = dom.coordinate_ring().hom([S.gen(0), 1], S) #dehomogenize dfn = fn[0].derivative(R.gen()) #polynomial to be evaluated at the periodic points mult_poly = phi(dfn.denominator())*S.gen(1) - phi(dfn.numerator()) #w-f'(z) #polynomial defining the periodic points x,y = dom.gens() if formal: fix_poly = self.dynatomic_polynomial(n) #f(z)-z else: fix_poly = Fn[0]*y - Fn[1]*x #f(z) - z #check infinity inf = dom(1,0) inf_per = ZZ(1) Q = self(inf) while Q != inf and inf_per <= n: inf_per += 1 Q = self(Q) #get multiplicity if inf_per <= n: e_inf = 0 while (y**(e_inf + 1)).divides(fix_poly): e_inf += 1 if type == 'cycle': #now we need to deal with having the correct number of factors #1 multiplier for each cycle. But we need to be careful about #the length of the cycle and the multiplicities good_res = 1 if formal: #then we are working with the n-th dynatomic and just need #to take one multiplier per cycle #evaluate the resultant fix_poly = psi(fix_poly) res = fix_poly.resultant(mult_poly, S.gen(0)) #take infinity into consideration if inf_per.divides(n): res *= (S.gen(1) - self.multiplier(inf, n)[0,0])**e_inf res = res.univariate_polynomial() #adjust multiplicities L = res.factor() for p,exp in L: good_res *= p**(exp/n) else: #For each d-th dynatomic for d dividing n, take #one multiplier per cycle; e.g., this treats a double 2 #cycle as a single 4 cycle for n=4 for d in n.divisors(): fix_poly_d = self.dynatomic_polynomial(d) resd = mult_poly.resultant(psi(fix_poly_d), S.gen(0)) #check infinity if inf_per == d: e_inf_d = 0 while (y**(e_inf_d + 1)).divides(fix_poly_d): e_inf_d += 1 resd *= (S.gen(1) - self.multiplier(inf, n)[0,0])**e_inf resd = resd.univariate_polynomial() Ld = resd.factor() for pd,ed in Ld: good_res *= pd**(ed/d) res = good_res else: #type is 'point' #evaluate the resultant fix_poly = psi(fix_poly) res = fix_poly.resultant(mult_poly, S.gen(0)) #take infinity into consideration if inf_per.divides(n): res *= (S.gen(1) - self.multiplier(inf, n)[0,0])**e_inf res = res.univariate_polynomial() # the sigmas are the coefficients # needed to fix the signs and the order sig = res.coefficients(sparse=False) den = sig.pop(-1) sig.reverse() sig = [sig[i] * (-1)**(i+1) / den for i in range(len(sig))] return sig
[ "def", "sigma_invariants", "(", "self", ",", "n", ",", "formal", "=", "False", ",", "embedding", "=", "None", ",", "type", "=", "'point'", ",", "return_polynomial", "=", "False", ",", "chow", "=", "False", ",", "deform", "=", "False", ",", "check", "="...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/dynamics/arithmetic_dynamics/projective_ds.py#L4845-L5425
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/models/deberta/modeling_tf_deberta.py
python
TFDebertaEmbeddings.build
(self, input_shape: tf.TensorShape)
[]
def build(self, input_shape: tf.TensorShape): with tf.name_scope("word_embeddings"): self.weight = self.add_weight( name="weight", shape=[self.vocab_size, self.embedding_size], initializer=get_initializer(self.initializer_range), ) with tf.name_scope("token_type_embeddings"): if self.type_vocab_size > 0: self.token_type_embeddings = self.add_weight( name="embeddings", shape=[self.type_vocab_size, self.embedding_size], initializer=get_initializer(self.initializer_range), ) else: self.token_type_embeddings = None with tf.name_scope("position_embeddings"): if self.position_biased_input: self.position_embeddings = self.add_weight( name="embeddings", shape=[self.max_position_embeddings, self.hidden_size], initializer=get_initializer(self.initializer_range), ) else: self.position_embeddings = None super().build(input_shape)
[ "def", "build", "(", "self", ",", "input_shape", ":", "tf", ".", "TensorShape", ")", ":", "with", "tf", ".", "name_scope", "(", "\"word_embeddings\"", ")", ":", "self", ".", "weight", "=", "self", ".", "add_weight", "(", "name", "=", "\"weight\"", ",", ...
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/models/deberta/modeling_tf_deberta.py#L732-L760
ambujraj/hacktoberfest2018
53df2cac8b3404261131a873352ec4f2ffa3544d
MAC_changer/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_internal/index.py
python
HTMLPage._get_content_type
(url, session)
return resp.headers.get("Content-Type", "")
Get the Content-Type of the given url, using a HEAD request
Get the Content-Type of the given url, using a HEAD request
[ "Get", "the", "Content", "-", "Type", "of", "the", "given", "url", "using", "a", "HEAD", "request" ]
def _get_content_type(url, session): """Get the Content-Type of the given url, using a HEAD request""" scheme, netloc, path, query, fragment = urllib_parse.urlsplit(url) if scheme not in {'http', 'https'}: # FIXME: some warning or something? # assertion error? return '' resp = session.head(url, allow_redirects=True) resp.raise_for_status() return resp.headers.get("Content-Type", "")
[ "def", "_get_content_type", "(", "url", ",", "session", ")", ":", "scheme", ",", "netloc", ",", "path", ",", "query", ",", "fragment", "=", "urllib_parse", ".", "urlsplit", "(", "url", ")", "if", "scheme", "not", "in", "{", "'http'", ",", "'https'", "}...
https://github.com/ambujraj/hacktoberfest2018/blob/53df2cac8b3404261131a873352ec4f2ffa3544d/MAC_changer/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_internal/index.py#L855-L866
replit-archive/empythoned
977ec10ced29a3541a4973dc2b59910805695752
cpython/Lib/plat-mac/lib-scriptpackages/Explorer/URL_Suite.py
python
URL_Suite_Events.GetURL
(self, _object, _attributes={}, **_arguments)
GetURL: Open the URL (and optionally save it to disk) Required argument: URL to open Keyword argument to: File into which to save resource located at URL. Keyword argument _attributes: AppleEvent attribute dictionary
GetURL: Open the URL (and optionally save it to disk) Required argument: URL to open Keyword argument to: File into which to save resource located at URL. Keyword argument _attributes: AppleEvent attribute dictionary
[ "GetURL", ":", "Open", "the", "URL", "(", "and", "optionally", "save", "it", "to", "disk", ")", "Required", "argument", ":", "URL", "to", "open", "Keyword", "argument", "to", ":", "File", "into", "which", "to", "save", "resource", "located", "at", "URL",...
def GetURL(self, _object, _attributes={}, **_arguments): """GetURL: Open the URL (and optionally save it to disk) Required argument: URL to open Keyword argument to: File into which to save resource located at URL. Keyword argument _attributes: AppleEvent attribute dictionary """ _code = 'GURL' _subcode = 'GURL' aetools.keysubst(_arguments, self._argmap_GetURL) _arguments['----'] = _object _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.get('errn', 0): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----']
[ "def", "GetURL", "(", "self", ",", "_object", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'GURL'", "_subcode", "=", "'GURL'", "aetools", ".", "keysubst", "(", "_arguments", ",", "self", ".", "_argmap_GetURL", ...
https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/cpython/Lib/plat-mac/lib-scriptpackages/Explorer/URL_Suite.py#L19-L38
materialsproject/fireworks
83a907c19baf2a5c9fdcf63996f9797c3c85b785
fireworks/utilities/filepad.py
python
FilePad._insert_contents
(self, contents, identifier, root_data, compress)
return gfs_id, identifier
Insert the file contents(string) to gridfs and store the file info doc in filepad Args: contents (str): file contents or any arbitrary string to be stored in gridfs identifier (str): file identifier compress (bool): compress or not root_data (dict): key:value pairs to be added to the document root Returns: (str, str): the id returned by gridfs, identifier
Insert the file contents(string) to gridfs and store the file info doc in filepad
[ "Insert", "the", "file", "contents", "(", "string", ")", "to", "gridfs", "and", "store", "the", "file", "info", "doc", "in", "filepad" ]
def _insert_contents(self, contents, identifier, root_data, compress): """ Insert the file contents(string) to gridfs and store the file info doc in filepad Args: contents (str): file contents or any arbitrary string to be stored in gridfs identifier (str): file identifier compress (bool): compress or not root_data (dict): key:value pairs to be added to the document root Returns: (str, str): the id returned by gridfs, identifier """ gfs_id = self._insert_to_gridfs(contents, compress) identifier = identifier or gfs_id root_data["gfs_id"] = gfs_id self.filepad.insert_one(root_data) return gfs_id, identifier
[ "def", "_insert_contents", "(", "self", ",", "contents", ",", "identifier", ",", "root_data", ",", "compress", ")", ":", "gfs_id", "=", "self", ".", "_insert_to_gridfs", "(", "contents", ",", "compress", ")", "identifier", "=", "identifier", "or", "gfs_id", ...
https://github.com/materialsproject/fireworks/blob/83a907c19baf2a5c9fdcf63996f9797c3c85b785/fireworks/utilities/filepad.py#L260-L277
mrjoes/tornadio2
c251c65b2f6921feafc72e39ece647cfe05e9909
examples/gen/gen.py
python
QueryConnection.long_running
(self, value, callback)
Long running task implementation. Simply adds 3 second timeout and then calls provided callback method.
Long running task implementation. Simply adds 3 second timeout and then calls provided callback method.
[ "Long", "running", "task", "implementation", ".", "Simply", "adds", "3", "second", "timeout", "and", "then", "calls", "provided", "callback", "method", "." ]
def long_running(self, value, callback): """Long running task implementation. Simply adds 3 second timeout and then calls provided callback method. """ def finish(): callback('Handled %s.' % value) ioloop.IOLoop.instance().add_timeout(timedelta(seconds=3), finish)
[ "def", "long_running", "(", "self", ",", "value", ",", "callback", ")", ":", "def", "finish", "(", ")", ":", "callback", "(", "'Handled %s.'", "%", "value", ")", "ioloop", ".", "IOLoop", ".", "instance", "(", ")", ".", "add_timeout", "(", "timedelta", ...
https://github.com/mrjoes/tornadio2/blob/c251c65b2f6921feafc72e39ece647cfe05e9909/examples/gen/gen.py#L24-L31
google/apitools
31cad2d904f356872d2965687e84b2d87ee2cdd3
apitools/base/py/credentials_lib.py
python
GaeAssertionCredentials._refresh
(self, _)
Refresh self.access_token. Args: _: (ignored) A function matching httplib2.Http.request's signature.
Refresh self.access_token.
[ "Refresh", "self", ".", "access_token", "." ]
def _refresh(self, _): """Refresh self.access_token. Args: _: (ignored) A function matching httplib2.Http.request's signature. """ # pylint: disable=import-error from google.appengine.api import app_identity try: token, _ = app_identity.get_access_token(self._scopes) except app_identity.Error as e: raise exceptions.CredentialsError(str(e)) self.access_token = token
[ "def", "_refresh", "(", "self", ",", "_", ")", ":", "# pylint: disable=import-error", "from", "google", ".", "appengine", ".", "api", "import", "app_identity", "try", ":", "token", ",", "_", "=", "app_identity", ".", "get_access_token", "(", "self", ".", "_s...
https://github.com/google/apitools/blob/31cad2d904f356872d2965687e84b2d87ee2cdd3/apitools/base/py/credentials_lib.py#L481-L493
cogitas3d/OrtogOnBlender
881e93f5beb2263e44c270974dd0e81deca44762
CalculaPontos.py
python
geraDeslocamentoTODOS.execute
(self, context)
return {'FINISHED'}
[]
def execute(self, context): geraDeslocamentoTODOSDef(self, context) return {'FINISHED'}
[ "def", "execute", "(", "self", ",", "context", ")", ":", "geraDeslocamentoTODOSDef", "(", "self", ",", "context", ")", "return", "{", "'FINISHED'", "}" ]
https://github.com/cogitas3d/OrtogOnBlender/blob/881e93f5beb2263e44c270974dd0e81deca44762/CalculaPontos.py#L221-L223
pkkid/python-plexapi
8a048d28360b0cdc728a41fa7d3077d0593b68fb
plexapi/myplex.py
python
MyPlexAccount._filterDictToStr
(self, filterDict)
return '|'.join(values)
Converts friend filters to a string representation for transport.
Converts friend filters to a string representation for transport.
[ "Converts", "friend", "filters", "to", "a", "string", "representation", "for", "transport", "." ]
def _filterDictToStr(self, filterDict): """ Converts friend filters to a string representation for transport. """ values = [] for key, vals in filterDict.items(): if key not in ('contentRating', 'label'): raise BadRequest('Unknown filter key: %s', key) values.append('%s=%s' % (key, '%2C'.join(vals))) return '|'.join(values)
[ "def", "_filterDictToStr", "(", "self", ",", "filterDict", ")", ":", "values", "=", "[", "]", "for", "key", ",", "vals", "in", "filterDict", ".", "items", "(", ")", ":", "if", "key", "not", "in", "(", "'contentRating'", ",", "'label'", ")", ":", "rai...
https://github.com/pkkid/python-plexapi/blob/8a048d28360b0cdc728a41fa7d3077d0593b68fb/plexapi/myplex.py#L564-L571
ocrmypdf/OCRmyPDF
7966192d6edb989f208cbbc6487346fdda635e78
src/ocrmypdf/cli.py
python
str_to_int
(mapping: Mapping[str, int])
return _str_to_int
Accept text on command line and convert to integer.
Accept text on command line and convert to integer.
[ "Accept", "text", "on", "command", "line", "and", "convert", "to", "integer", "." ]
def str_to_int(mapping: Mapping[str, int]): """Accept text on command line and convert to integer.""" def _str_to_int(s: str) -> int: try: return mapping[s] except KeyError: raise argparse.ArgumentTypeError( f"{s!r} must be one of: {', '.join(mapping.keys())}" ) return _str_to_int
[ "def", "str_to_int", "(", "mapping", ":", "Mapping", "[", "str", ",", "int", "]", ")", ":", "def", "_str_to_int", "(", "s", ":", "str", ")", "->", "int", ":", "try", ":", "return", "mapping", "[", "s", "]", "except", "KeyError", ":", "raise", "argp...
https://github.com/ocrmypdf/OCRmyPDF/blob/7966192d6edb989f208cbbc6487346fdda635e78/src/ocrmypdf/cli.py#L36-L47
getting-things-gnome/gtg
4b02c43744b32a00facb98174f04ec5953bd055d
GTG/core/task.py
python
Task.recursive_sync
(self)
Recursively sync the task and all task children. Defined
Recursively sync the task and all task children. Defined
[ "Recursively", "sync", "the", "task", "and", "all", "task", "children", ".", "Defined" ]
def recursive_sync(self): """Recursively sync the task and all task children. Defined""" self.sync() for sub_id in self.children: sub = self.req.get_task(sub_id) sub.recursive_sync()
[ "def", "recursive_sync", "(", "self", ")", ":", "self", ".", "sync", "(", ")", "for", "sub_id", "in", "self", ".", "children", ":", "sub", "=", "self", ".", "req", ".", "get_task", "(", "sub_id", ")", "sub", ".", "recursive_sync", "(", ")" ]
https://github.com/getting-things-gnome/gtg/blob/4b02c43744b32a00facb98174f04ec5953bd055d/GTG/core/task.py#L256-L261
vim-vdebug/vdebug
a5121a28335cf7f561d111031e69baac52eed035
python3/vdebug/dbgp.py
python
Response.as_xml
(self)
return self.xml
Get the response as element tree XML. Returns an xml.etree.ElementTree.Element object.
Get the response as element tree XML.
[ "Get", "the", "response", "as", "element", "tree", "XML", "." ]
def as_xml(self): """Get the response as element tree XML. Returns an xml.etree.ElementTree.Element object. """ if self.xml is None: self.xml = ET.fromstring(self.response) self.__determine_ns() return self.xml
[ "def", "as_xml", "(", "self", ")", ":", "if", "self", ".", "xml", "is", "None", ":", "self", ".", "xml", "=", "ET", ".", "fromstring", "(", "self", ".", "response", ")", "self", ".", "__determine_ns", "(", ")", "return", "self", ".", "xml" ]
https://github.com/vim-vdebug/vdebug/blob/a5121a28335cf7f561d111031e69baac52eed035/python3/vdebug/dbgp.py#L61-L69
mutpy/mutpy
5c8b3ca0d365083a4da8333f7fce8783114371fa
mutpy/controller.py
python
MutationController.update_incompetent_mutant
(self, result, duration)
[]
def update_incompetent_mutant(self, result, duration): self.notify_incompetent(duration, result.exception, result.tests_run) self.score.inc_incompetent()
[ "def", "update_incompetent_mutant", "(", "self", ",", "result", ",", "duration", ")", ":", "self", ".", "notify_incompetent", "(", "duration", ",", "result", ".", "exception", ",", "result", ".", "tests_run", ")", "self", ".", "score", ".", "inc_incompetent", ...
https://github.com/mutpy/mutpy/blob/5c8b3ca0d365083a4da8333f7fce8783114371fa/mutpy/controller.py#L164-L166
kivymd/KivyMD
1cb82f7d2437770f71be7c5a4f7de4b8da61f352
kivymd/uix/taptargetview.py
python
MDTapTargetView.on_open
(self, *args)
Called at the time of the start of the widget opening animation.
Called at the time of the start of the widget opening animation.
[ "Called", "at", "the", "time", "of", "the", "start", "of", "the", "widget", "opening", "animation", "." ]
def on_open(self, *args): """Called at the time of the start of the widget opening animation."""
[ "def", "on_open", "(", "self", ",", "*", "args", ")", ":" ]
https://github.com/kivymd/KivyMD/blob/1cb82f7d2437770f71be7c5a4f7de4b8da61f352/kivymd/uix/taptargetview.py#L687-L688
Thriftpy/thriftpy2
8755065bdd3a51b55cbab488fe628027f2c060db
thriftpy2/transport/base.py
python
TTransportBase.is_open
(self)
Check if this transport is open.
Check if this transport is open.
[ "Check", "if", "this", "transport", "is", "open", "." ]
def is_open(self): """Check if this transport is open.""" raise NotImplementedError
[ "def", "is_open", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/Thriftpy/thriftpy2/blob/8755065bdd3a51b55cbab488fe628027f2c060db/thriftpy2/transport/base.py#L26-L28
LinuxCNC/linuxcnc
d42398ede7c839b3ef76298a5d2d753b50b6620c
src/emc/usr_intf/gscreen/gscreen.py
python
Gscreen.init_sensitive_edit_mode
(self)
creates a list of widgets that need to be sensitive to edit mode list is held in data.sensitive_edit_mode
creates a list of widgets that need to be sensitive to edit mode list is held in data.sensitive_edit_mode
[ "creates", "a", "list", "of", "widgets", "that", "need", "to", "be", "sensitive", "to", "edit", "mode", "list", "is", "held", "in", "data", ".", "sensitive_edit_mode" ]
def init_sensitive_edit_mode(self): """creates a list of widgets that need to be sensitive to edit mode list is held in data.sensitive_edit_mode """ self.data.sensitive_edit_mode = ["button_mode","button_menu","button_graphics","button_override","button_restart", "button_single_step","button_run","ignore_limits"]
[ "def", "init_sensitive_edit_mode", "(", "self", ")", ":", "self", ".", "data", ".", "sensitive_edit_mode", "=", "[", "\"button_mode\"", ",", "\"button_menu\"", ",", "\"button_graphics\"", ",", "\"button_override\"", ",", "\"button_restart\"", ",", "\"button_single_step\...
https://github.com/LinuxCNC/linuxcnc/blob/d42398ede7c839b3ef76298a5d2d753b50b6620c/src/emc/usr_intf/gscreen/gscreen.py#L1454-L1459
brython-dev/brython
9cba5fb7f43a9b52fff13e89b403e02a1dfaa5f3
www/src/Lib/gzip.py
python
GzipFile.fileno
(self)
return self.fileobj.fileno()
Invoke the underlying file object's fileno() method. This will raise AttributeError if the underlying file object doesn't support fileno().
Invoke the underlying file object's fileno() method.
[ "Invoke", "the", "underlying", "file", "object", "s", "fileno", "()", "method", "." ]
def fileno(self): """Invoke the underlying file object's fileno() method. This will raise AttributeError if the underlying file object doesn't support fileno(). """ return self.fileobj.fileno()
[ "def", "fileno", "(", "self", ")", ":", "return", "self", ".", "fileobj", ".", "fileno", "(", ")" ]
https://github.com/brython-dev/brython/blob/9cba5fb7f43a9b52fff13e89b403e02a1dfaa5f3/www/src/Lib/gzip.py#L353-L359
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/tkinter/tix.py
python
_dummyDirList.__init__
(self, master, name, destroy_physically=1)
[]
def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) self.subwidget_list['hlist'] = _dummyHList(self, 'hlist') self.subwidget_list['vsb'] = _dummyScrollbar(self, 'vsb') self.subwidget_list['hsb'] = _dummyScrollbar(self, 'hsb')
[ "def", "__init__", "(", "self", ",", "master", ",", "name", ",", "destroy_physically", "=", "1", ")", ":", "TixSubWidget", ".", "__init__", "(", "self", ",", "master", ",", "name", ",", "destroy_physically", ")", "self", ".", "subwidget_list", "[", "'hlist...
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/tkinter/tix.py#L1682-L1686
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/FeedCrowdstrikeFalconIntel/Integrations/FeedCrowdstrikeFalconIntel/FeedCrowdstrikeFalconIntel.py
python
fetch_indicators
(client: Client, feed_tags: List, tlp_color: Optional[str], limit=None, offset=None, target_countries=None, target_industries=None, custom_filter=None)
return indicators
Fetch-indicators command from CrowdStrike Feeds Args: client(Client): CrowdStrike Feed client. feed_tags: The indicator tags. tlp_color (str): Traffic Light Protocol color. limit: limit the amount of indicators fetched. offset: the index of the first index to fetch. target_industries: the actor's target_industries. target_countries: the actor's target_countries. custom_filter: user actor's filter. Returns: list. List of indicators.
Fetch-indicators command from CrowdStrike Feeds
[ "Fetch", "-", "indicators", "command", "from", "CrowdStrike", "Feeds" ]
def fetch_indicators(client: Client, feed_tags: List, tlp_color: Optional[str], limit=None, offset=None, target_countries=None, target_industries=None, custom_filter=None) -> list: """Fetch-indicators command from CrowdStrike Feeds Args: client(Client): CrowdStrike Feed client. feed_tags: The indicator tags. tlp_color (str): Traffic Light Protocol color. limit: limit the amount of indicators fetched. offset: the index of the first index to fetch. target_industries: the actor's target_industries. target_countries: the actor's target_countries. custom_filter: user actor's filter. Returns: list. List of indicators. """ indicators = client.build_iterator(feed_tags, tlp_color, limit, offset, target_countries, target_industries, custom_filter) return indicators
[ "def", "fetch_indicators", "(", "client", ":", "Client", ",", "feed_tags", ":", "List", ",", "tlp_color", ":", "Optional", "[", "str", "]", ",", "limit", "=", "None", ",", "offset", "=", "None", ",", "target_countries", "=", "None", ",", "target_industries...
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/FeedCrowdstrikeFalconIntel/Integrations/FeedCrowdstrikeFalconIntel/FeedCrowdstrikeFalconIntel.py#L232-L251
DataXujing/vehicle-license-plate-recognition
d6f9d6b7b90b52f32721510858fc1a01f35a5aeb
my_main_ui.py
python
MainWindow.on_pushButton_6_clicked
(self)
加载图像
加载图像
[ "加载图像" ]
def on_pushButton_6_clicked(self): """ 加载图像 """ print("加载图像") try: self.file_dir_temp,_ = QFileDialog.getOpenFileName(self,"选择被检测的车辆","D:/") self.file_dir = self.file_dir_temp.replace("\\","/") print(self.file_dir) roi, label, color = CaridDetect(self.file_dir) seg_dict, _, pre = Cardseg([roi],[color],None) print(pre) # segment cv2.imwrite(os.path.join("./temp/seg_card.jpg"),roi) seg_img = cv2.imread("./temp/seg_card.jpg") seg_rows, seg_cols, seg_channels = seg_img.shape bytesPerLine = seg_channels * seg_cols cv2.cvtColor(seg_img, cv2.COLOR_BGR2RGB,seg_img) QImg = QImage(seg_img.data, seg_cols, seg_rows,bytesPerLine, QImage.Format_RGB888) self.label_2.setPixmap(QPixmap.fromImage(QImg).scaled(self.label_2.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)) # reg result pre.insert(2,"·") self.label_3.setText(" "+"".join(pre)) # clor view if color == "yello": self.label_4.setStyleSheet("background-color: rgb(255, 255, 0);") elif color == "green": self.label_4.setStyleSheet("background-color: rgb(0, 255,0);") elif color == "blue": self.label_4.setStyleSheet("background-color: rgb(0, 0, 255);") else: self.label_4.setText("未识别出车牌颜色") frame = cv2.imread(self.file_dir) # cv2.rectangle(frame, (label[0],label[2]), (label[1],label[3]), (0,0,255), 2) font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(frame, 'https://github.com/DataXujing/vehicle-license-plate-recognition', (10, 10), font, 0.3, (0, 0, 255), 1) img_rows, img_cols, channels = frame.shape bytesPerLine = channels * img_cols cv2.cvtColor(frame, cv2.COLOR_BGR2RGB,frame) QImg = QImage(frame.data, img_cols, img_rows,bytesPerLine, QImage.Format_RGB888) self.label.setPixmap(QPixmap.fromImage(QImg).scaled(self.label.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)) QtWidgets.QApplication.processEvents() except Exception as e: QMessageBox.warning(self,"错误提示","[错误提示(请联系开发人员处理)]:\n" + str(e)+"\n或识别失败导致")
[ "def", "on_pushButton_6_clicked", "(", "self", ")", ":", "print", "(", "\"加载图像\")", "", "try", ":", "self", ".", "file_dir_temp", ",", "_", "=", "QFileDialog", ".", "getOpenFileName", "(", "self", ",", "\"选择被检测的车辆\",\"D:/\")", "", "", "", "self", ".", "fil...
https://github.com/DataXujing/vehicle-license-plate-recognition/blob/d6f9d6b7b90b52f32721510858fc1a01f35a5aeb/my_main_ui.py#L55-L107
ctxis/canape
5f0e03424577296bcc60c2008a60a98ec5307e4b
CANAPE.Scripting/Lib/lib2to3/fixer_base.py
python
BaseFix.finish_tree
(self, tree, filename)
Some fixers need to maintain tree-wide state. This method is called once, at the conclusion of tree fix-up. tree - the root node of the tree to be processed. filename - the name of the file the tree came from.
Some fixers need to maintain tree-wide state. This method is called once, at the conclusion of tree fix-up.
[ "Some", "fixers", "need", "to", "maintain", "tree", "-", "wide", "state", ".", "This", "method", "is", "called", "once", "at", "the", "conclusion", "of", "tree", "fix", "-", "up", "." ]
def finish_tree(self, tree, filename): """Some fixers need to maintain tree-wide state. This method is called once, at the conclusion of tree fix-up. tree - the root node of the tree to be processed. filename - the name of the file the tree came from. """ pass
[ "def", "finish_tree", "(", "self", ",", "tree", ",", "filename", ")", ":", "pass" ]
https://github.com/ctxis/canape/blob/5f0e03424577296bcc60c2008a60a98ec5307e4b/CANAPE.Scripting/Lib/lib2to3/fixer_base.py#L162-L169
JDAI-CV/DCL
895081603dc68aeeda07301dbddf32b364ecacf7
transforms/transforms.py
python
RandomAffine.__call__
(self, img)
return F.affine(img, *ret, resample=self.resample, fillcolor=self.fillcolor)
img (PIL Image): Image to be transformed. Returns: PIL Image: Affine transformed image.
img (PIL Image): Image to be transformed.
[ "img", "(", "PIL", "Image", ")", ":", "Image", "to", "be", "transformed", "." ]
def __call__(self, img): """ img (PIL Image): Image to be transformed. Returns: PIL Image: Affine transformed image. """ ret = self.get_params(self.degrees, self.translate, self.scale, self.shear, img.size) return F.affine(img, *ret, resample=self.resample, fillcolor=self.fillcolor)
[ "def", "__call__", "(", "self", ",", "img", ")", ":", "ret", "=", "self", ".", "get_params", "(", "self", ".", "degrees", ",", "self", ".", "translate", ",", "self", ".", "scale", ",", "self", ".", "shear", ",", "img", ".", "size", ")", "return", ...
https://github.com/JDAI-CV/DCL/blob/895081603dc68aeeda07301dbddf32b364ecacf7/transforms/transforms.py#L942-L950
cloudant/python-cloudant
5b1ecc215b2caea22ccc2d7310462df56be6e848
src/cloudant/document.py
python
Document.field_set
(doc, field, value)
Sets or replaces a value for a field in a locally cached Document object. To remove the field set the ``value`` to None. :param Document doc: Locally cached Document object that can be a Document, DesignDocument or dict. :param str field: Name of the field to set. :param value: Value to set the field to.
Sets or replaces a value for a field in a locally cached Document object. To remove the field set the ``value`` to None.
[ "Sets", "or", "replaces", "a", "value", "for", "a", "field", "in", "a", "locally", "cached", "Document", "object", ".", "To", "remove", "the", "field", "set", "the", "value", "to", "None", "." ]
def field_set(doc, field, value): """ Sets or replaces a value for a field in a locally cached Document object. To remove the field set the ``value`` to None. :param Document doc: Locally cached Document object that can be a Document, DesignDocument or dict. :param str field: Name of the field to set. :param value: Value to set the field to. """ if value is None: doc.__delitem__(field) else: doc[field] = value
[ "def", "field_set", "(", "doc", ",", "field", ",", "value", ")", ":", "if", "value", "is", "None", ":", "doc", ".", "__delitem__", "(", "field", ")", "else", ":", "doc", "[", "field", "]", "=", "value" ]
https://github.com/cloudant/python-cloudant/blob/5b1ecc215b2caea22ccc2d7310462df56be6e848/src/cloudant/document.py#L241-L254
IndicoDataSolutions/finetune
83ba222eed331df64b2fa7157bb64f0a2eef4a2c
finetune/util/group_metrics.py
python
group_token_counts
(pred, label)
return Counts(TP, FP, FN)
Return TP, FP, FN counts based on tokens in groups :param pred, label: A group, represeted as a dict :return: A Counts namedtuple with TP, FP and FN counts
Return TP, FP, FN counts based on tokens in groups
[ "Return", "TP", "FP", "FN", "counts", "based", "on", "tokens", "in", "groups" ]
def group_token_counts(pred, label): """ Return TP, FP, FN counts based on tokens in groups :param pred, label: A group, represeted as a dict :return: A Counts namedtuple with TP, FP and FN counts """ pred_tokens = _convert_to_token_list(pred["spans"]) label_tokens = _convert_to_token_list(label["spans"]) if pred["label"] != label["label"]: # All predicted tokens are false positives # All ground truth tokens are false negatives return Counts(0, len(pred_tokens), len(label_tokens)) TP, FP, FN = 0, 0, 0 # TP and FN for l_token in label_tokens: for p_token in pred_tokens: if (p_token["start"] == l_token["start"] and p_token["end"] == l_token["end"]): TP += 1 break else: FN += 1 # FP for p_token in pred_tokens: for l_token in label_tokens: if (p_token["start"] == l_token["start"] and p_token["end"] == l_token["end"]): break else: FP += 1 return Counts(TP, FP, FN)
[ "def", "group_token_counts", "(", "pred", ",", "label", ")", ":", "pred_tokens", "=", "_convert_to_token_list", "(", "pred", "[", "\"spans\"", "]", ")", "label_tokens", "=", "_convert_to_token_list", "(", "label", "[", "\"spans\"", "]", ")", "if", "pred", "[",...
https://github.com/IndicoDataSolutions/finetune/blob/83ba222eed331df64b2fa7157bb64f0a2eef4a2c/finetune/util/group_metrics.py#L32-L65
jython/jython3
def4f8ec47cb7a9c799ea4c745f12badf92c5769
lib-python/3.5.1/tkinter/__init__.py
python
Text.dlineinfo
(self, index)
return self._getints(self.tk.call(self._w, 'dlineinfo', index))
Return tuple (x,y,width,height,baseline) giving the bounding box and baseline position of the visible part of the line containing the character at INDEX.
Return tuple (x,y,width,height,baseline) giving the bounding box and baseline position of the visible part of the line containing the character at INDEX.
[ "Return", "tuple", "(", "x", "y", "width", "height", "baseline", ")", "giving", "the", "bounding", "box", "and", "baseline", "position", "of", "the", "visible", "part", "of", "the", "line", "containing", "the", "character", "at", "INDEX", "." ]
def dlineinfo(self, index): """Return tuple (x,y,width,height,baseline) giving the bounding box and baseline position of the visible part of the line containing the character at INDEX.""" return self._getints(self.tk.call(self._w, 'dlineinfo', index))
[ "def", "dlineinfo", "(", "self", ",", "index", ")", ":", "return", "self", ".", "_getints", "(", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'dlineinfo'", ",", "index", ")", ")" ]
https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/lib-python/3.5.1/tkinter/__init__.py#L2985-L2989
angr/angr-management
60ae5fa483e74810fb3a3da8d37b00034d7fefab
angrmanagement/ui/workspace.py
python
Workspace.create_and_show_graph_disassembly_view
(self)
Create a new disassembly view and select the Graph disassembly mode.
Create a new disassembly view and select the Graph disassembly mode.
[ "Create", "a", "new", "disassembly", "view", "and", "select", "the", "Graph", "disassembly", "mode", "." ]
def create_and_show_graph_disassembly_view(self): """ Create a new disassembly view and select the Graph disassembly mode. """ view = self.new_disassembly_view() view.display_disasm_graph() self.raise_view(view) view.setFocus()
[ "def", "create_and_show_graph_disassembly_view", "(", "self", ")", ":", "view", "=", "self", ".", "new_disassembly_view", "(", ")", "view", ".", "display_disasm_graph", "(", ")", "self", ".", "raise_view", "(", "view", ")", "view", ".", "setFocus", "(", ")" ]
https://github.com/angr/angr-management/blob/60ae5fa483e74810fb3a3da8d37b00034d7fefab/angrmanagement/ui/workspace.py#L411-L418
elfi-dev/elfi
07ac0ed5e81d5d5fb42de63db3cf9ccc9135b88c
elfi/methods/bo/gpy_regression.py
python
GPyRegression.optimize
(self)
Optimize GP hyperparameters.
Optimize GP hyperparameters.
[ "Optimize", "GP", "hyperparameters", "." ]
def optimize(self): """Optimize GP hyperparameters.""" logger.debug("Optimizing GP hyperparameters") try: self._gp.optimize(self.optimizer, max_iters=self.max_opt_iters) except np.linalg.linalg.LinAlgError: logger.warning("Numerical error in GP optimization. Stopping optimization")
[ "def", "optimize", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Optimizing GP hyperparameters\"", ")", "try", ":", "self", ".", "_gp", ".", "optimize", "(", "self", ".", "optimizer", ",", "max_iters", "=", "self", ".", "max_opt_iters", ")", "exce...
https://github.com/elfi-dev/elfi/blob/07ac0ed5e81d5d5fb42de63db3cf9ccc9135b88c/elfi/methods/bo/gpy_regression.py#L316-L322
PetrochukM/PyTorch-NLP
d7814a297811c9b0dfb285fe0475098b86f3d348
torchnlp/nn/weight_drop.py
python
_weight_drop
(module, weights, dropout)
Helper for `WeightDrop`.
Helper for `WeightDrop`.
[ "Helper", "for", "WeightDrop", "." ]
def _weight_drop(module, weights, dropout): """ Helper for `WeightDrop`. """ for name_w in weights: w = getattr(module, name_w) del module._parameters[name_w] module.register_parameter(name_w + '_raw', Parameter(w)) original_module_forward = module.forward def forward(*args, **kwargs): for name_w in weights: raw_w = getattr(module, name_w + '_raw') w = torch.nn.functional.dropout(raw_w, p=dropout, training=module.training) setattr(module, name_w, w) return original_module_forward(*args, **kwargs) setattr(module, 'forward', forward)
[ "def", "_weight_drop", "(", "module", ",", "weights", ",", "dropout", ")", ":", "for", "name_w", "in", "weights", ":", "w", "=", "getattr", "(", "module", ",", "name_w", ")", "del", "module", ".", "_parameters", "[", "name_w", "]", "module", ".", "regi...
https://github.com/PetrochukM/PyTorch-NLP/blob/d7814a297811c9b0dfb285fe0475098b86f3d348/torchnlp/nn/weight_drop.py#L6-L26
paulwinex/pw_MultiScriptEditor
e447e99f87cb07e238baf693b7e124e50efdbc51
multi_script_editor/managers/nuke/main.py
python
AnimationCurve.size
(self)
return 0
self.size() -> Number of keys. @return: Number of keys.
self.size() -> Number of keys.
[ "self", ".", "size", "()", "-", ">", "Number", "of", "keys", "." ]
def size(self): """self.size() -> Number of keys. @return: Number of keys. """ return 0
[ "def", "size", "(", "self", ")", ":", "return", "0" ]
https://github.com/paulwinex/pw_MultiScriptEditor/blob/e447e99f87cb07e238baf693b7e124e50efdbc51/multi_script_editor/managers/nuke/main.py#L2242-L2246
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/jinja2/parser.py
python
Parser.parse_include
(self)
return self.parse_import_context(node, True)
[]
def parse_include(self): node = nodes.Include(lineno=next(self.stream).lineno) node.template = self.parse_expression() if self.stream.current.test('name:ignore') and \ self.stream.look().test('name:missing'): node.ignore_missing = True self.stream.skip(2) else: node.ignore_missing = False return self.parse_import_context(node, True)
[ "def", "parse_include", "(", "self", ")", ":", "node", "=", "nodes", ".", "Include", "(", "lineno", "=", "next", "(", "self", ".", "stream", ")", ".", "lineno", ")", "node", ".", "template", "=", "self", ".", "parse_expression", "(", ")", "if", "self...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/jinja2/parser.py#L286-L295
openseg-group/openseg.pytorch
2cdb3de5dcbc96f531b68e5bf1233c860f247b3e
lib/models/backbones/resnet/resnext_models.py
python
ResNextModels.resnext101_32x16d
(self, **kwargs)
return model
Constructs a ResNeXt-101 32x16d model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr
Constructs a ResNeXt-101 32x16d model.
[ "Constructs", "a", "ResNeXt", "-", "101", "32x16d", "model", "." ]
def resnext101_32x16d(self, **kwargs): """Constructs a ResNeXt-101 32x16d model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr """ pretrained = False progress = False kwargs['groups'] = 32 kwargs['width_per_group'] = 16 model = ResNext('resnext101_32x16d', Bottleneck, [3, 4, 23, 3], pretrained, progress, bn_type=self.configer.get('network', 'bn_type'), **kwargs) model = ModuleHelper.load_model(model, pretrained=self.configer.get('network', 'pretrained'), all_match=False, network="resnext") return model
[ "def", "resnext101_32x16d", "(", "self", ",", "*", "*", "kwargs", ")", ":", "pretrained", "=", "False", "progress", "=", "False", "kwargs", "[", "'groups'", "]", "=", "32", "kwargs", "[", "'width_per_group'", "]", "=", "16", "model", "=", "ResNext", "(",...
https://github.com/openseg-group/openseg.pytorch/blob/2cdb3de5dcbc96f531b68e5bf1233c860f247b3e/lib/models/backbones/resnet/resnext_models.py#L246-L262
mozilla/addons-server
cbfb29e5be99539c30248d70b93bb15e1c1bc9d7
src/olympia/files/utils.py
python
ManifestJSONExtractor.apps
(self)
Get `AppVersion`s for the application.
Get `AppVersion`s for the application.
[ "Get", "AppVersion", "s", "for", "the", "application", "." ]
def apps(self): """Get `AppVersion`s for the application.""" type_ = self.type if type_ == amo.ADDON_LPAPP: # Langpack are only compatible with Firefox desktop at the moment. # https://github.com/mozilla/addons-server/issues/8381 # They are all strictly compatible with a specific version, so # the default min version here doesn't matter much. apps = ((amo.FIREFOX, amo.DEFAULT_WEBEXT_MIN_VERSION),) elif type_ == amo.ADDON_STATICTHEME: # Static themes are only compatible with Firefox desktop >= 53 # and Firefox for Android >=65. apps = ( (amo.FIREFOX, amo.DEFAULT_STATIC_THEME_MIN_VERSION_FIREFOX), (amo.ANDROID, amo.DEFAULT_STATIC_THEME_MIN_VERSION_ANDROID), ) elif type_ == amo.ADDON_DICT: # WebExt dicts are only compatible with Firefox desktop >= 61. apps = ((amo.FIREFOX, amo.DEFAULT_WEBEXT_DICT_MIN_VERSION_FIREFOX),) else: webext_min = ( amo.DEFAULT_WEBEXT_MIN_VERSION if self.get('browser_specific_settings', None) is None else amo.DEFAULT_WEBEXT_MIN_VERSION_BROWSER_SPECIFIC ) # amo.DEFAULT_WEBEXT_MIN_VERSION_BROWSER_SPECIFIC should be 48.0, # which is the same as amo.DEFAULT_WEBEXT_MIN_VERSION_ANDROID, so # no specific treatment for Android. apps = ( (amo.FIREFOX, webext_min), (amo.ANDROID, amo.DEFAULT_WEBEXT_MIN_VERSION_ANDROID), ) if self.get('manifest_version') == 3: # Update minimum supported versions if it's an mv3 addon. mv3_mins = { amo.FIREFOX: amo.DEFAULT_WEBEXT_MIN_VERSION_MV3_FIREFOX, amo.ANDROID: amo.DEFAULT_WEBEXT_MIN_VERSION_MV3_ANDROID, } apps = ( (app, max(VersionString(ver), mv3_mins.get(app, mv3_mins[amo.FIREFOX]))) for app, ver in apps ) doesnt_support_no_id = ( self.strict_min_version and self.strict_min_version < VersionString(amo.DEFAULT_WEBEXT_MIN_VERSION_NO_ID) ) if self.guid is None and doesnt_support_no_id: raise forms.ValidationError( gettext('Add-on ID is required for Firefox 47 and below.') ) # If a minimum strict version is specified, it needs to be higher # than the version when Firefox started supporting WebExtensions. unsupported_no_matter_what = ( self.strict_min_version and self.strict_min_version < VersionString(amo.DEFAULT_WEBEXT_MIN_VERSION) ) if unsupported_no_matter_what: msg = gettext('Lowest supported "strict_min_version" is 42.0.') raise forms.ValidationError(msg) for app, default_min_version in apps: if self.guid is None and not self.strict_min_version: strict_min_version = max( VersionString(amo.DEFAULT_WEBEXT_MIN_VERSION_NO_ID), VersionString(default_min_version), ) else: # strict_min_version for this app shouldn't be lower than the # default min version for this app. strict_min_version = max( self.strict_min_version, VersionString(default_min_version) ) strict_max_version = self.strict_max_version or VersionString( amo.DEFAULT_WEBEXT_MAX_VERSION ) if strict_max_version < strict_min_version: strict_max_version = strict_min_version qs = AppVersion.objects.filter(application=app.id) try: min_appver = qs.get(version=strict_min_version) except AppVersion.DoesNotExist: msg = gettext( 'Unknown "strict_min_version" {appver} for {app}'.format( app=app.pretty, appver=strict_min_version ) ) raise forms.ValidationError(msg) try: max_appver = qs.get(version=strict_max_version) except AppVersion.DoesNotExist: # If the specified strict_max_version can't be found, raise an # error: we used to use '*' instead but this caused more # problems, especially with langpacks that are really specific # to a given Firefox version. msg = gettext( 'Unknown "strict_max_version" {appver} for {app}'.format( app=app.pretty, appver=strict_max_version ) ) raise forms.ValidationError(msg) yield Extractor.App(appdata=app, id=app.id, min=min_appver, max=max_appver)
[ "def", "apps", "(", "self", ")", ":", "type_", "=", "self", ".", "type", "if", "type_", "==", "amo", ".", "ADDON_LPAPP", ":", "# Langpack are only compatible with Firefox desktop at the moment.", "# https://github.com/mozilla/addons-server/issues/8381", "# They are all strict...
https://github.com/mozilla/addons-server/blob/cbfb29e5be99539c30248d70b93bb15e1c1bc9d7/src/olympia/files/utils.py#L283-L393
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/site-packages/django/forms/fields.py
python
ImageField.to_python
(self, data)
return f
Checks that the file-upload field data contains a valid image (GIF, JPG, PNG, possibly others -- whatever the Python Imaging Library supports).
Checks that the file-upload field data contains a valid image (GIF, JPG, PNG, possibly others -- whatever the Python Imaging Library supports).
[ "Checks", "that", "the", "file", "-", "upload", "field", "data", "contains", "a", "valid", "image", "(", "GIF", "JPG", "PNG", "possibly", "others", "--", "whatever", "the", "Python", "Imaging", "Library", "supports", ")", "." ]
def to_python(self, data): """ Checks that the file-upload field data contains a valid image (GIF, JPG, PNG, possibly others -- whatever the Python Imaging Library supports). """ f = super(ImageField, self).to_python(data) if f is None: return None # Try to import PIL in either of the two ways it can end up installed. try: from PIL import Image except ImportError: import Image # We need to get a file object for PIL. We might have a path or we might # have to read the data into memory. if hasattr(data, 'temporary_file_path'): file = data.temporary_file_path() else: if hasattr(data, 'read'): file = StringIO(data.read()) else: file = StringIO(data['content']) try: # load() is the only method that can spot a truncated JPEG, # but it cannot be called sanely after verify() trial_image = Image.open(file) trial_image.load() # Since we're about to use the file again we have to reset the # file object if possible. if hasattr(file, 'reset'): file.reset() # verify() is the only method that can spot a corrupt PNG, # but it must be called immediately after the constructor trial_image = Image.open(file) trial_image.verify() except ImportError: # Under PyPy, it is possible to import PIL. However, the underlying # _imaging C module isn't available, so an ImportError will be # raised. Catch and re-raise. raise except Exception: # Python Imaging Library doesn't recognize it as an image raise ValidationError(self.error_messages['invalid_image']) if hasattr(f, 'seek') and callable(f.seek): f.seek(0) return f
[ "def", "to_python", "(", "self", ",", "data", ")", ":", "f", "=", "super", "(", "ImageField", ",", "self", ")", ".", "to_python", "(", "data", ")", "if", "f", "is", "None", ":", "return", "None", "# Try to import PIL in either of the two ways it can end up ins...
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/site-packages/django/forms/fields.py#L547-L596
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/idlelib/rpc.py
python
RPCServer.get_request
(self)
return self.socket, self.server_address
Override TCPServer method, return already connected socket
Override TCPServer method, return already connected socket
[ "Override", "TCPServer", "method", "return", "already", "connected", "socket" ]
def get_request(self): "Override TCPServer method, return already connected socket" return self.socket, self.server_address
[ "def", "get_request", "(", "self", ")", ":", "return", "self", ".", "socket", ",", "self", ".", "server_address" ]
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/idlelib/rpc.py#L89-L91
modoboa/modoboa
9065b7a5679fee149fc6f6f0e1760699c194cf89
modoboa/admin/forms/domain.py
python
DomainForm.extra_context
(self, context)
Add information to template context.
Add information to template context.
[ "Add", "information", "to", "template", "context", "." ]
def extra_context(self, context): """Add information to template context.""" context.update({ "title": self.domain.name, "action": reverse( "admin:domain_change", args=[self.domain.pk]), "formid": "domform", "domain": self.domain })
[ "def", "extra_context", "(", "self", ",", "context", ")", ":", "context", ".", "update", "(", "{", "\"title\"", ":", "self", ".", "domain", ".", "name", ",", "\"action\"", ":", "reverse", "(", "\"admin:domain_change\"", ",", "args", "=", "[", "self", "."...
https://github.com/modoboa/modoboa/blob/9065b7a5679fee149fc6f6f0e1760699c194cf89/modoboa/admin/forms/domain.py#L384-L392
edgedb/edgedb
872bf5abbb10f7c72df21f57635238ed27b9f280
edb/edgeql/parser/grammar/statements.py
python
DescribeStmt.reduce_DESCRIBE_OBJECT
(self, *kids)
%reduce DESCRIBE OBJECT NodeName DescribeFormat
%reduce DESCRIBE OBJECT NodeName DescribeFormat
[ "%reduce", "DESCRIBE", "OBJECT", "NodeName", "DescribeFormat" ]
def reduce_DESCRIBE_OBJECT(self, *kids): """%reduce DESCRIBE OBJECT NodeName DescribeFormat""" self.val = qlast.DescribeStmt( object=kids[2].val, language=kids[3].val.language, options=kids[3].val.options, )
[ "def", "reduce_DESCRIBE_OBJECT", "(", "self", ",", "*", "kids", ")", ":", "self", ".", "val", "=", "qlast", ".", "DescribeStmt", "(", "object", "=", "kids", "[", "2", "]", ".", "val", ",", "language", "=", "kids", "[", "3", "]", ".", "val", ".", ...
https://github.com/edgedb/edgedb/blob/872bf5abbb10f7c72df21f57635238ed27b9f280/edb/edgeql/parser/grammar/statements.py#L229-L235
wrenfairbank/telegram_gcloner
5a64fa95c19c58032f2c64323358a4cb42cf1a30
telegram_gcloner/handlers/process_message.py
python
init
(dispatcher: Dispatcher)
Provide handlers initialization.
Provide handlers initialization.
[ "Provide", "handlers", "initialization", "." ]
def init(dispatcher: Dispatcher): """Provide handlers initialization.""" dispatcher.add_handler( MessageHandler(Filters.group & Filters.chat(config.GROUP_IDS) & (Filters.text | Filters.caption) & ~Filters.update.edited_message, process_message)) dispatcher.add_handler( MessageHandler(Filters.chat(config.USER_IDS[0]) & (Filters.text | Filters.caption) & ~Filters.update.edited_message, process_message_from_authorised_user)) dispatcher.add_handler( MessageHandler((~Filters.group) & (Filters.text | Filters.caption) & ~Filters.update.edited_message, process_message)) dispatcher.add_handler(CallbackQueryHandler(ignore_callback, pattern=r'^#$')) dispatcher.add_handler(CallbackQueryHandler(get_warning))
[ "def", "init", "(", "dispatcher", ":", "Dispatcher", ")", ":", "dispatcher", ".", "add_handler", "(", "MessageHandler", "(", "Filters", ".", "group", "&", "Filters", ".", "chat", "(", "config", ".", "GROUP_IDS", ")", "&", "(", "Filters", ".", "text", "|"...
https://github.com/wrenfairbank/telegram_gcloner/blob/5a64fa95c19c58032f2c64323358a4cb42cf1a30/telegram_gcloner/handlers/process_message.py#L16-L35
phreeza/cells
1286eaac8b62c922b6cd300df6491f2b215c705e
cells.py
python
Plant.get_view
(self)
return PlantView(self)
[]
def get_view(self): return PlantView(self)
[ "def", "get_view", "(", "self", ")", ":", "return", "PlantView", "(", "self", ")" ]
https://github.com/phreeza/cells/blob/1286eaac8b62c922b6cd300df6491f2b215c705e/cells.py#L676-L677
yifita/DSS
ce1151b27556a7e2aac18aea2a30ed97f792bb4d
DSS/misc/pix2pix/models/template_model.py
python
TemplateModel.modify_commandline_options
(parser, is_train=True)
return parser
Add new model-specific options and rewrite default values for existing options. Parameters: parser -- the option parser is_train -- if it is training phase or test phase. You can use this flag to add training-specific or test-specific options. Returns: the modified parser.
Add new model-specific options and rewrite default values for existing options.
[ "Add", "new", "model", "-", "specific", "options", "and", "rewrite", "default", "values", "for", "existing", "options", "." ]
def modify_commandline_options(parser, is_train=True): """Add new model-specific options and rewrite default values for existing options. Parameters: parser -- the option parser is_train -- if it is training phase or test phase. You can use this flag to add training-specific or test-specific options. Returns: the modified parser. """ parser.set_defaults(dataset_mode='aligned') # You can rewrite default values for this model. For example, this model usually uses aligned dataset as its dataset. if is_train: parser.add_argument('--lambda_regression', type=float, default=1.0, help='weight for the regression loss') # You can define new arguments for this model. return parser
[ "def", "modify_commandline_options", "(", "parser", ",", "is_train", "=", "True", ")", ":", "parser", ".", "set_defaults", "(", "dataset_mode", "=", "'aligned'", ")", "# You can rewrite default values for this model. For example, this model usually uses aligned dataset as its dat...
https://github.com/yifita/DSS/blob/ce1151b27556a7e2aac18aea2a30ed97f792bb4d/DSS/misc/pix2pix/models/template_model.py#L25-L39
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/sqlalchemy/pool.py
python
_DBProxy.get_pool
(self, *args, **kw)
[]
def get_pool(self, *args, **kw): key = self._serialize(*args, **kw) try: return self.pools[key] except KeyError: self._create_pool_mutex.acquire() try: if key not in self.pools: kw.pop('sa_pool_key', None) pool = self.poolclass( lambda: self.module.connect(*args, **kw), **self.kw) self.pools[key] = pool return pool else: return self.pools[key] finally: self._create_pool_mutex.release()
[ "def", "get_pool", "(", "self", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "key", "=", "self", ".", "_serialize", "(", "*", "args", ",", "*", "*", "kw", ")", "try", ":", "return", "self", ".", "pools", "[", "key", "]", "except", "KeyError...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/sqlalchemy/pool.py#L1450-L1466
nccgroup/PMapper
a79e332ff8e93f4c55be2ca8fd8e9348a86acdc4
principalmapper/querying/query_actions.py
python
_write_query_help
(output: io.StringIO)
Writes information about querying
Writes information about querying
[ "Writes", "information", "about", "querying" ]
def _write_query_help(output: io.StringIO) -> None: """Writes information about querying""" output.write(_query_help_string)
[ "def", "_write_query_help", "(", "output", ":", "io", ".", "StringIO", ")", "->", "None", ":", "output", ".", "write", "(", "_query_help_string", ")" ]
https://github.com/nccgroup/PMapper/blob/a79e332ff8e93f4c55be2ca8fd8e9348a86acdc4/principalmapper/querying/query_actions.py#L210-L212
thu-coai/ConvLab-2
ad32b76022fa29cbc2f24cbefbb855b60492985e
convlab2/policy/rule/camrest/rule_based_camrest_bot.py
python
generate_ref_num
(length)
return string
Generate a ref num for booking.
Generate a ref num for booking.
[ "Generate", "a", "ref", "num", "for", "booking", "." ]
def generate_ref_num(length): """ Generate a ref num for booking. """ string = "" while len(string) < length: string += alphabet[random.randint(0, 999999) % 36] return string
[ "def", "generate_ref_num", "(", "length", ")", ":", "string", "=", "\"\"", "while", "len", "(", "string", ")", "<", "length", ":", "string", "+=", "alphabet", "[", "random", ".", "randint", "(", "0", ",", "999999", ")", "%", "36", "]", "return", "str...
https://github.com/thu-coai/ConvLab-2/blob/ad32b76022fa29cbc2f24cbefbb855b60492985e/convlab2/policy/rule/camrest/rule_based_camrest_bot.py#L200-L205
scrapy/scrapy
b04cfa48328d5d5749dca6f50fa34e0cfc664c89
scrapy/utils/datatypes.py
python
CaselessDict.setdefault
(self, key, def_val=None)
return dict.setdefault(self, self.normkey(key), self.normvalue(def_val))
[]
def setdefault(self, key, def_val=None): return dict.setdefault(self, self.normkey(key), self.normvalue(def_val))
[ "def", "setdefault", "(", "self", ",", "key", ",", "def_val", "=", "None", ")", ":", "return", "dict", ".", "setdefault", "(", "self", ",", "self", ".", "normkey", "(", "key", ")", ",", "self", ".", "normvalue", "(", "def_val", ")", ")" ]
https://github.com/scrapy/scrapy/blob/b04cfa48328d5d5749dca6f50fa34e0cfc664c89/scrapy/utils/datatypes.py#L50-L51
kaaedit/kaa
e6a8819a5ecba04b7db8303bd5736b5a7c9b822d
gappedbuf/sre_parse.py
python
SubPattern.__len__
(self)
return len(self.data)
[]
def __len__(self): return len(self.data)
[ "def", "__len__", "(", "self", ")", ":", "return", "len", "(", "self", ".", "data", ")" ]
https://github.com/kaaedit/kaa/blob/e6a8819a5ecba04b7db8303bd5736b5a7c9b822d/gappedbuf/sre_parse.py#L147-L148
VITA-Group/FasterSeg
478b0265eb9ab626cfbe503ad16d2452878b38cc
latency/model_seg.py
python
Network_Multi_Path_Infer.build_structure
(self, lasts)
[]
def build_structure(self, lasts): self._branch = len(lasts) self.lasts = lasts self.ops = [ getattr(self, "ops%d"%last) for last in lasts ] self.paths = [ getattr(self, "path%d"%last) for last in lasts ] self.downs = [ getattr(self, "downs%d"%last) for last in lasts ] self.widths = [ getattr(self, "widths%d"%last) for last in lasts ] self.branch_groups, self.cells = self.get_branch_groups_cells(self.ops, self.paths, self.downs, self.widths, self.lasts) self.build_arm_ffm_head()
[ "def", "build_structure", "(", "self", ",", "lasts", ")", ":", "self", ".", "_branch", "=", "len", "(", "lasts", ")", "self", ".", "lasts", "=", "lasts", "self", ".", "ops", "=", "[", "getattr", "(", "self", ",", "\"ops%d\"", "%", "last", ")", "for...
https://github.com/VITA-Group/FasterSeg/blob/478b0265eb9ab626cfbe503ad16d2452878b38cc/latency/model_seg.py#L205-L213
osmr/imgclsmob
f2993d3ce73a2f7ddba05da3891defb08547d504
chainer_/chainercv2/models/common.py
python
depthwise_conv3x3
(channels, stride=1, pad=1, dilate=1, use_bias=False)
return L.Convolution2D( in_channels=channels, out_channels=channels, ksize=3, stride=stride, pad=pad, nobias=(not use_bias), dilate=dilate, groups=channels)
Depthwise convolution 3x3 layer. Parameters: ---------- channels : int Number of input/output channels. stride : int or tuple/list of 2 int, default 1 Stride of the convolution. pad : int or tuple/list of 2 int, default 1 Padding value for convolution layer. dilate : int or tuple/list of 2 int, default 1 Dilation value for convolution layer. use_bias : bool, default False Whether the layer uses a bias vector.
Depthwise convolution 3x3 layer.
[ "Depthwise", "convolution", "3x3", "layer", "." ]
def depthwise_conv3x3(channels, stride=1, pad=1, dilate=1, use_bias=False): """ Depthwise convolution 3x3 layer. Parameters: ---------- channels : int Number of input/output channels. stride : int or tuple/list of 2 int, default 1 Stride of the convolution. pad : int or tuple/list of 2 int, default 1 Padding value for convolution layer. dilate : int or tuple/list of 2 int, default 1 Dilation value for convolution layer. use_bias : bool, default False Whether the layer uses a bias vector. """ return L.Convolution2D( in_channels=channels, out_channels=channels, ksize=3, stride=stride, pad=pad, nobias=(not use_bias), dilate=dilate, groups=channels)
[ "def", "depthwise_conv3x3", "(", "channels", ",", "stride", "=", "1", ",", "pad", "=", "1", ",", "dilate", "=", "1", ",", "use_bias", "=", "False", ")", ":", "return", "L", ".", "Convolution2D", "(", "in_channels", "=", "channels", ",", "out_channels", ...
https://github.com/osmr/imgclsmob/blob/f2993d3ce73a2f7ddba05da3891defb08547d504/chainer_/chainercv2/models/common.py#L402-L431
nlloyd/SubliminalCollaborator
5c619e17ddbe8acb9eea8996ec038169ddcd50a1
libs/twisted/python/threadpool.py
python
ThreadPool.stop
(self)
Shutdown the threads in the threadpool.
Shutdown the threads in the threadpool.
[ "Shutdown", "the", "threads", "in", "the", "threadpool", "." ]
def stop(self): """ Shutdown the threads in the threadpool. """ self.joined = True threads = copy.copy(self.threads) while self.workers: self.q.put(WorkerStop) self.workers -= 1 # and let's just make sure # FIXME: threads that have died before calling stop() are not joined. for thread in threads: thread.join()
[ "def", "stop", "(", "self", ")", ":", "self", ".", "joined", "=", "True", "threads", "=", "copy", ".", "copy", "(", "self", ".", "threads", ")", "while", "self", ".", "workers", ":", "self", ".", "q", ".", "put", "(", "WorkerStop", ")", "self", "...
https://github.com/nlloyd/SubliminalCollaborator/blob/5c619e17ddbe8acb9eea8996ec038169ddcd50a1/libs/twisted/python/threadpool.py#L196-L209
gusibi/python-weixin
db997152673b205966146b6aab304ba6e4755bec
weixin/lib/WXBizMsgCrypt.py
python
throw_exception
(message, exception_class=FormatException)
my define raise exception function
my define raise exception function
[ "my", "define", "raise", "exception", "function" ]
def throw_exception(message, exception_class=FormatException): """my define raise exception function""" raise exception_class(message)
[ "def", "throw_exception", "(", "message", ",", "exception_class", "=", "FormatException", ")", ":", "raise", "exception_class", "(", "message", ")" ]
https://github.com/gusibi/python-weixin/blob/db997152673b205966146b6aab304ba6e4755bec/weixin/lib/WXBizMsgCrypt.py#L32-L34
NVIDIA/DeepLearningExamples
589604d49e016cd9ef4525f7abcc9c7b826cfc5e
PyTorch/Segmentation/MaskRCNN/pytorch/maskrcnn_benchmark/utils/comm.py
python
all_gather
(data)
return data_list
Run all_gather on arbitrary picklable data (not necessarily tensors) Args: data: any picklable object Returns: list[data]: list of data gathered from each rank
Run all_gather on arbitrary picklable data (not necessarily tensors) Args: data: any picklable object Returns: list[data]: list of data gathered from each rank
[ "Run", "all_gather", "on", "arbitrary", "picklable", "data", "(", "not", "necessarily", "tensors", ")", "Args", ":", "data", ":", "any", "picklable", "object", "Returns", ":", "list", "[", "data", "]", ":", "list", "of", "data", "gathered", "from", "each",...
def all_gather(data): """ Run all_gather on arbitrary picklable data (not necessarily tensors) Args: data: any picklable object Returns: list[data]: list of data gathered from each rank """ world_size = get_world_size() if world_size == 1: return [data] # serialized to a Tensor buffer = pickle.dumps(data) storage = torch.ByteStorage.from_buffer(buffer) tensor = torch.ByteTensor(storage).to("cuda") # obtain Tensor size of each rank local_size = torch.IntTensor([tensor.numel()]).to("cuda") size_list = [torch.IntTensor([0]).to("cuda") for _ in range(world_size)] dist.all_gather(size_list, local_size) size_list = [int(size.item()) for size in size_list] max_size = max(size_list) # receiving Tensor from all ranks # we pad the tensor because torch all_gather does not support # gathering tensors of different shapes tensor_list = [] for _ in size_list: tensor_list.append(torch.ByteTensor(size=(max_size,)).to("cuda")) if local_size != max_size: padding = torch.ByteTensor(size=(max_size - local_size,)).to("cuda") tensor = torch.cat((tensor, padding), dim=0) dist.all_gather(tensor_list, tensor) data_list = [] for size, tensor in zip(size_list, tensor_list): buffer = tensor.cpu().numpy().tobytes()[:size] data_list.append(pickle.loads(buffer)) return data_list
[ "def", "all_gather", "(", "data", ")", ":", "world_size", "=", "get_world_size", "(", ")", "if", "world_size", "==", "1", ":", "return", "[", "data", "]", "# serialized to a Tensor", "buffer", "=", "pickle", ".", "dumps", "(", "data", ")", "storage", "=", ...
https://github.com/NVIDIA/DeepLearningExamples/blob/589604d49e016cd9ef4525f7abcc9c7b826cfc5e/PyTorch/Segmentation/MaskRCNN/pytorch/maskrcnn_benchmark/utils/comm.py#L49-L89
SanPen/GridCal
d3f4566d2d72c11c7e910c9d162538ef0e60df31
src/GridCal/Gui/Main/GridCalMain.py
python
MainGUI.post_time_series
(self)
Events to do when the time series simulation has finished @return:
Events to do when the time series simulation has finished
[ "Events", "to", "do", "when", "the", "time", "series", "simulation", "has", "finished" ]
def post_time_series(self): """ Events to do when the time series simulation has finished @return: """ drv, results = self.session.get_driver_results(sim.SimulationTypes.TimeSeries_run) if results is not None: self.remove_simulation(sim.SimulationTypes.TimeSeries_run) if self.ui.draw_schematic_checkBox.isChecked(): voltage = results.voltage.max(axis=0) loading = np.abs(results.loading).max(axis=0) Sbranch = results.Sf.max(axis=0) Sbus = results.S.max(axis=0) viz.colour_the_schematic(circuit=self.circuit, Sbus=Sbus, Sf=Sbranch, voltages=voltage, loadings=loading, types=results.bus_types, use_flow_based_width=self.ui.branch_width_based_on_flow_checkBox.isChecked(), min_branch_width=self.ui.min_branch_size_spinBox.value(), max_branch_width=self.ui.max_branch_size_spinBox.value(), min_bus_width=self.ui.min_node_size_spinBox.value(), max_bus_width=self.ui.max_node_size_spinBox.value() ) self.update_available_results() else: warning_msg('No results for the time series simulation.') if not self.session.is_anything_running(): self.UNLOCK()
[ "def", "post_time_series", "(", "self", ")", ":", "drv", ",", "results", "=", "self", ".", "session", ".", "get_driver_results", "(", "sim", ".", "SimulationTypes", ".", "TimeSeries_run", ")", "if", "results", "is", "not", "None", ":", "self", ".", "remove...
https://github.com/SanPen/GridCal/blob/d3f4566d2d72c11c7e910c9d162538ef0e60df31/src/GridCal/Gui/Main/GridCalMain.py#L3415-L3452
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/Werkzeug-0.8.3-py2.7.egg/werkzeug/http.py
python
http_date
(timestamp=None)
return _dump_date(timestamp, ' ')
Formats the time to match the RFC1123 date format. Accepts a floating point number expressed in seconds since the epoch in, a datetime object or a timetuple. All times in UTC. The :func:`parse_date` function can be used to parse such a date. Outputs a string in the format ``Wdy, DD Mon YYYY HH:MM:SS GMT``. :param timestamp: If provided that date is used, otherwise the current.
Formats the time to match the RFC1123 date format.
[ "Formats", "the", "time", "to", "match", "the", "RFC1123", "date", "format", "." ]
def http_date(timestamp=None): """Formats the time to match the RFC1123 date format. Accepts a floating point number expressed in seconds since the epoch in, a datetime object or a timetuple. All times in UTC. The :func:`parse_date` function can be used to parse such a date. Outputs a string in the format ``Wdy, DD Mon YYYY HH:MM:SS GMT``. :param timestamp: If provided that date is used, otherwise the current. """ return _dump_date(timestamp, ' ')
[ "def", "http_date", "(", "timestamp", "=", "None", ")", ":", "return", "_dump_date", "(", "timestamp", ",", "' '", ")" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/Werkzeug-0.8.3-py2.7.egg/werkzeug/http.py#L612-L623
osroom/osroom
fcb9b7c5e5cfd8e919f8d87521800e70b09b5b44
apps/modules/plug_in_manager/apis/manager.py
python
api_adm_plugin
()
return response_format(data)
插件管理 GET: 获取所有插件 page:<int>,第几页, 默认1 pre:<int>,每页个数, 默认10 keyword:<str>, 搜索用 POST: 插件安装 upfile:<file>,上传的插件压缩包 PUT: 操作插件 action:<str>, start:激活插件 stop:停用插件 name:<str>, 插件名称 :return:
插件管理 GET: 获取所有插件 page:<int>,第几页, 默认1 pre:<int>,每页个数, 默认10 keyword:<str>, 搜索用
[ "插件管理", "GET", ":", "获取所有插件", "page", ":", "<int", ">", "第几页", "默认1", "pre", ":", "<int", ">", "每页个数", "默认10", "keyword", ":", "<str", ">", "搜索用" ]
def api_adm_plugin(): """ 插件管理 GET: 获取所有插件 page:<int>,第几页, 默认1 pre:<int>,每页个数, 默认10 keyword:<str>, 搜索用 POST: 插件安装 upfile:<file>,上传的插件压缩包 PUT: 操作插件 action:<str>, start:激活插件 stop:停用插件 name:<str>, 插件名称 :return: """ if request.c_method == "GET": data = get_plugins() elif request.c_method == "POST": data = upload_plugin() elif request.c_method == "PUT": if request.argget.all('action') == "start": data = start_plugin() else: data = stop_plugin() elif request.c_method == "DELETE": data = delete_plugin() else: data = {"msg_type": "w", "msg": METHOD_WARNING, "custom_status": 405} return response_format(data)
[ "def", "api_adm_plugin", "(", ")", ":", "if", "request", ".", "c_method", "==", "\"GET\"", ":", "data", "=", "get_plugins", "(", ")", "elif", "request", ".", "c_method", "==", "\"POST\"", ":", "data", "=", "upload_plugin", "(", ")", "elif", "request", "....
https://github.com/osroom/osroom/blob/fcb9b7c5e5cfd8e919f8d87521800e70b09b5b44/apps/modules/plug_in_manager/apis/manager.py#L19-L50
Pylons/waitress
f41e59826c81d7da5309e4b3694d5ac7a8bbd626
src/waitress/adjustments.py
python
asoctal
(s)
return int(s, 8)
Convert the given octal string to an actual number.
Convert the given octal string to an actual number.
[ "Convert", "the", "given", "octal", "string", "to", "an", "actual", "number", "." ]
def asoctal(s): """Convert the given octal string to an actual number.""" return int(s, 8)
[ "def", "asoctal", "(", "s", ")", ":", "return", "int", "(", "s", ",", "8", ")" ]
https://github.com/Pylons/waitress/blob/f41e59826c81d7da5309e4b3694d5ac7a8bbd626/src/waitress/adjustments.py#L44-L46
jython/jython3
def4f8ec47cb7a9c799ea4c745f12badf92c5769
lib-python/3.5.1/turtle.py
python
TPen.penup
(self)
Pull the pen up -- no drawing when moving. Aliases: penup | pu | up No argument Example (for a Turtle instance named turtle): >>> turtle.penup()
Pull the pen up -- no drawing when moving.
[ "Pull", "the", "pen", "up", "--", "no", "drawing", "when", "moving", "." ]
def penup(self): """Pull the pen up -- no drawing when moving. Aliases: penup | pu | up No argument Example (for a Turtle instance named turtle): >>> turtle.penup() """ if not self._drawing: return self.pen(pendown=False)
[ "def", "penup", "(", "self", ")", ":", "if", "not", "self", ".", "_drawing", ":", "return", "self", ".", "pen", "(", "pendown", "=", "False", ")" ]
https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/lib-python/3.5.1/turtle.py#L2095-L2107
napari/napari
dbf4158e801fa7a429de8ef1cdee73bf6d64c61e
napari/_vispy/experimental/vispy_tiled_image_layer.py
python
VispyTiledImageLayer._update_tile_shape
(self)
If the tile shape was changed, update our node.
If the tile shape was changed, update our node.
[ "If", "the", "tile", "shape", "was", "changed", "update", "our", "node", "." ]
def _update_tile_shape(self) -> None: """If the tile shape was changed, update our node.""" # This might be overly dynamic, but for now if we see there's a new # tile shape we nuke our texture atlas and start over with the new # shape. tile_shape = self.layer.tile_shape if self.node.tile_shape != tile_shape: self.node.set_tile_shape(tile_shape)
[ "def", "_update_tile_shape", "(", "self", ")", "->", "None", ":", "# This might be overly dynamic, but for now if we see there's a new", "# tile shape we nuke our texture atlas and start over with the new", "# shape.", "tile_shape", "=", "self", ".", "layer", ".", "tile_shape", "...
https://github.com/napari/napari/blob/dbf4158e801fa7a429de8ef1cdee73bf6d64c61e/napari/_vispy/experimental/vispy_tiled_image_layer.py#L124-L131
talkatv/talkatv
d5528c8b313683bfa24cc6299cfaaced05c6b17f
setup.py
python
get_version
()
Author: GNU MediaGoblin contributors
Author: GNU MediaGoblin contributors
[ "Author", ":", "GNU", "MediaGoblin", "contributors" ]
def get_version(): ''' Author: GNU MediaGoblin contributors ''' verstrline = open(VERSIONFILE, "rt").read() mo = re.search(VSRE, verstrline, re.M) if mo: return mo.group(1) else: raise RuntimeError("Unable to find version string in %s." % VERSIONFILE)
[ "def", "get_version", "(", ")", ":", "verstrline", "=", "open", "(", "VERSIONFILE", ",", "\"rt\"", ")", ".", "read", "(", ")", "mo", "=", "re", ".", "search", "(", "VSRE", ",", "verstrline", ",", "re", ".", "M", ")", "if", "mo", ":", "return", "m...
https://github.com/talkatv/talkatv/blob/d5528c8b313683bfa24cc6299cfaaced05c6b17f/setup.py#L27-L38
LMFDB/lmfdb
6cf48a4c18a96e6298da6ae43f587f96845bcb43
lmfdb/groups/abstract/web_groups.py
python
WebAbstractSubgroup._full
(self)
return list( db.gps_groups.search({"label": {"$in": labels}}) )
Get information from gps_groups for each of the abstract groups included here (the subgroup, the ambient group and the quotient, if normal)
Get information from gps_groups for each of the abstract groups included here (the subgroup, the ambient group and the quotient, if normal)
[ "Get", "information", "from", "gps_groups", "for", "each", "of", "the", "abstract", "groups", "included", "here", "(", "the", "subgroup", "the", "ambient", "group", "and", "the", "quotient", "if", "normal", ")" ]
def _full(self): """ Get information from gps_groups for each of the abstract groups included here (the subgroup, the ambient group and the quotient, if normal) """ labels = [self.subgroup, self.ambient] if self.normal: labels.append(self.quotient) if self.weyl_group is not None: labels.append(self.weyl_group) if self.aut_weyl_group is not None: labels.append(self.aut_weyl_group) if self.projective_image is not None: labels.append(self.projective_image) return list( db.gps_groups.search({"label": {"$in": labels}}) )
[ "def", "_full", "(", "self", ")", ":", "labels", "=", "[", "self", ".", "subgroup", ",", "self", ".", "ambient", "]", "if", "self", ".", "normal", ":", "labels", ".", "append", "(", "self", ".", "quotient", ")", "if", "self", ".", "weyl_group", "is...
https://github.com/LMFDB/lmfdb/blob/6cf48a4c18a96e6298da6ae43f587f96845bcb43/lmfdb/groups/abstract/web_groups.py#L1569-L1584
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/tkinter/tix.py
python
HList.nearest
(self, y)
return self.tk.call(self._w, 'nearest', y)
[]
def nearest(self, y): return self.tk.call(self._w, 'nearest', y)
[ "def", "nearest", "(", "self", ",", "y", ")", ":", "return", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'nearest'", ",", "y", ")" ]
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/tkinter/tix.py#L1027-L1028
openstack/taskflow
38b9011094dbcfdd00e6446393816201e8256d38
taskflow/listeners/base.py
python
_retry_matcher
(details)
return False
Matches retry details emitted.
Matches retry details emitted.
[ "Matches", "retry", "details", "emitted", "." ]
def _retry_matcher(details): """Matches retry details emitted.""" if not details: return False if 'retry_name' in details and 'retry_uuid' in details: return True return False
[ "def", "_retry_matcher", "(", "details", ")", ":", "if", "not", "details", ":", "return", "False", "if", "'retry_name'", "in", "details", "and", "'retry_uuid'", "in", "details", ":", "return", "True", "return", "False" ]
https://github.com/openstack/taskflow/blob/38b9011094dbcfdd00e6446393816201e8256d38/taskflow/listeners/base.py#L46-L52
alek-sys/sublimetext_indentxml
2e4ddf443444fcd8308108857e96669e8316cba7
indentxml.py
python
BaseIndentCommand.is_enabled
(self)
return self.check_enabled(self.get_language())
Enables or disables the 'indent' command. Command will be disabled if there are currently no text selections and current file is not 'XML' or 'Plain Text'. This helps clarify to the user about when the command can be executed, especially useful for UI controls.
Enables or disables the 'indent' command. Command will be disabled if there are currently no text selections and current file is not 'XML' or 'Plain Text'. This helps clarify to the user about when the command can be executed, especially useful for UI controls.
[ "Enables", "or", "disables", "the", "indent", "command", ".", "Command", "will", "be", "disabled", "if", "there", "are", "currently", "no", "text", "selections", "and", "current", "file", "is", "not", "XML", "or", "Plain", "Text", ".", "This", "helps", "cl...
def is_enabled(self): """ Enables or disables the 'indent' command. Command will be disabled if there are currently no text selections and current file is not 'XML' or 'Plain Text'. This helps clarify to the user about when the command can be executed, especially useful for UI controls. """ if self.view is None: return False return self.check_enabled(self.get_language())
[ "def", "is_enabled", "(", "self", ")", ":", "if", "self", ".", "view", "is", "None", ":", "return", "False", "return", "self", ".", "check_enabled", "(", "self", ".", "get_language", "(", ")", ")" ]
https://github.com/alek-sys/sublimetext_indentxml/blob/2e4ddf443444fcd8308108857e96669e8316cba7/indentxml.py#L23-L33
dib-lab/khmer
fb65d21eaedf0d397d49ae3debc578897f9d6eb4
ez_setup.py
python
download_file_wget
(url, target)
[]
def download_file_wget(url, target): cmd = ['wget', url, '--quiet', '--output-document', target] _clean_check(cmd, target)
[ "def", "download_file_wget", "(", "url", ",", "target", ")", ":", "cmd", "=", "[", "'wget'", ",", "url", ",", "'--quiet'", ",", "'--output-document'", ",", "target", "]", "_clean_check", "(", "cmd", ",", "target", ")" ]
https://github.com/dib-lab/khmer/blob/fb65d21eaedf0d397d49ae3debc578897f9d6eb4/ez_setup.py#L210-L212
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v1_cron_job.py
python
V1CronJob.__repr__
(self)
return self.to_str()
For `print` and `pprint`
For `print` and `pprint`
[ "For", "print", "and", "pprint" ]
def __repr__(self): """For `print` and `pprint`""" return self.to_str()
[ "def", "__repr__", "(", "self", ")", ":", "return", "self", ".", "to_str", "(", ")" ]
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1_cron_job.py#L212-L214
mozman/ezdxf
59d0fc2ea63f5cf82293428f5931da7e9f9718e9
examples/blocks/exploding_with_attribs.py
python
get_random_point
()
return x, y
Returns random x, y coordinates.
Returns random x, y coordinates.
[ "Returns", "random", "x", "y", "coordinates", "." ]
def get_random_point() -> Tuple[int, int]: """Returns random x, y coordinates.""" x = random.randint(-100, 100) y = random.randint(-100, 100) return x, y
[ "def", "get_random_point", "(", ")", "->", "Tuple", "[", "int", ",", "int", "]", ":", "x", "=", "random", ".", "randint", "(", "-", "100", ",", "100", ")", "y", "=", "random", ".", "randint", "(", "-", "100", ",", "100", ")", "return", "x", ","...
https://github.com/mozman/ezdxf/blob/59d0fc2ea63f5cf82293428f5931da7e9f9718e9/examples/blocks/exploding_with_attribs.py#L12-L16
bikalims/bika.lims
35e4bbdb5a3912cae0b5eb13e51097c8b0486349
bika/lims/browser/worksheet/views/add_analyses.py
python
AddAnalysesView.getWorksheetTemplates
(self)
return [(c.UID, c.Title) for c in bsc(portal_type = 'WorksheetTemplate', inactive_state = 'active', sort_on = 'sortable_title')]
Return WS Templates
Return WS Templates
[ "Return", "WS", "Templates" ]
def getWorksheetTemplates(self): """ Return WS Templates """ profiles = [] bsc = getToolByName(self.context, 'bika_setup_catalog') return [(c.UID, c.Title) for c in bsc(portal_type = 'WorksheetTemplate', inactive_state = 'active', sort_on = 'sortable_title')]
[ "def", "getWorksheetTemplates", "(", "self", ")", ":", "profiles", "=", "[", "]", "bsc", "=", "getToolByName", "(", "self", ".", "context", ",", "'bika_setup_catalog'", ")", "return", "[", "(", "c", ".", "UID", ",", "c", ".", "Title", ")", "for", "c", ...
https://github.com/bikalims/bika.lims/blob/35e4bbdb5a3912cae0b5eb13e51097c8b0486349/bika/lims/browser/worksheet/views/add_analyses.py#L226-L233
MicrosoftResearch/Azimuth
84eb013b8dde7132357a9b69206e99a4c65e2b89
azimuth/models/regression.py
python
train_linreg_model
(alpha, l1r, learn_options, fold, X, y, y_all)
return clf
fold is something like train_inner (boolean array specifying what is in the fold)
fold is something like train_inner (boolean array specifying what is in the fold)
[ "fold", "is", "something", "like", "train_inner", "(", "boolean", "array", "specifying", "what", "is", "in", "the", "fold", ")" ]
def train_linreg_model(alpha, l1r, learn_options, fold, X, y, y_all): ''' fold is something like train_inner (boolean array specifying what is in the fold) ''' if learn_options["penalty"] == "L2": clf = sklearn.linear_model.Ridge(alpha=alpha, fit_intercept=learn_options["fit_intercept"], normalize=learn_options['normalize_features'], copy_X=True, max_iter=None, tol=0.001, solver='auto') weights = get_weights(learn_options, fold, y, y_all) clf.fit(X[fold], y[fold], sample_weight=weights) elif learn_options["penalty"] == 'EN' or learn_options["penalty"] == 'L1': if learn_options["loss"] == "squared": clf = sklearn.linear_model.ElasticNet(alpha=alpha, l1_ratio=l1r, fit_intercept=learn_options["fit_intercept"], normalize=learn_options['normalize_features'], max_iter=3000) elif learn_options["loss"] == "huber": clf = sklearn.linear_model.SGDRegressor('huber', epsilon=0.7, alpha=alpha, l1_ratio=l1r, fit_intercept=learn_options["fit_intercept"], n_iter=10, penalty='elasticnet', shuffle=True, normalize=learn_options['normalize_features']) clf.fit(X[fold], y[fold]) return clf
[ "def", "train_linreg_model", "(", "alpha", ",", "l1r", ",", "learn_options", ",", "fold", ",", "X", ",", "y", ",", "y_all", ")", ":", "if", "learn_options", "[", "\"penalty\"", "]", "==", "\"L2\"", ":", "clf", "=", "sklearn", ".", "linear_model", ".", ...
https://github.com/MicrosoftResearch/Azimuth/blob/84eb013b8dde7132357a9b69206e99a4c65e2b89/azimuth/models/regression.py#L20-L36
EdCo95/scientific-paper-summarisation
5a6217556704dda5694c298e17b909acd1608be1
DataTools/useful_functions.py
python
paper2vec
(paper, model, metadata)
return new_paper
Converts a paper into a list of vectors, one vector for each sentence. :param paper: the paper in the form of a dictionary. The keys of the dictionary are the sections of the paper, and the values are a list of lists, where each list is a list of words corresponding to a sentence in that section. :param model: the word2vec model used to transform the paper into a vector. :param metadata: dictionaries containing metadata about the paper. :return: the paper in the form of a dictionary, the key being the section and the values being a list of vectors, with each vector corresponding to a sentence from that part of the paper.
Converts a paper into a list of vectors, one vector for each sentence. :param paper: the paper in the form of a dictionary. The keys of the dictionary are the sections of the paper, and the values are a list of lists, where each list is a list of words corresponding to a sentence in that section. :param model: the word2vec model used to transform the paper into a vector. :param metadata: dictionaries containing metadata about the paper. :return: the paper in the form of a dictionary, the key being the section and the values being a list of vectors, with each vector corresponding to a sentence from that part of the paper.
[ "Converts", "a", "paper", "into", "a", "list", "of", "vectors", "one", "vector", "for", "each", "sentence", ".", ":", "param", "paper", ":", "the", "paper", "in", "the", "form", "of", "a", "dictionary", ".", "The", "keys", "of", "the", "dictionary", "a...
def paper2vec(paper, model, metadata): """ Converts a paper into a list of vectors, one vector for each sentence. :param paper: the paper in the form of a dictionary. The keys of the dictionary are the sections of the paper, and the values are a list of lists, where each list is a list of words corresponding to a sentence in that section. :param model: the word2vec model used to transform the paper into a vector. :param metadata: dictionaries containing metadata about the paper. :return: the paper in the form of a dictionary, the key being the section and the values being a list of vectors, with each vector corresponding to a sentence from that part of the paper. """ stopwords = read_stopwords() new_paper = defaultdict(None) for section, text in paper.iteritems(): section_as_vector = [] section_text = [] pos = text[1] text = text[0] for sentence in text: if "HIGHLIGHTS" in section: sentence_vec = sentence2vec(sentence, model, stopwords, metadata, HIGHLIGHT, False) elif "ABSTRACT" in section: sentence_vec = sentence2vec(sentence, model, stopwords, metadata, ABSTRACT, False) elif "INTRODUCTION" in section: sentence_vec = sentence2vec(sentence, model, stopwords, metadata, INTRODUCTION, False) elif "RESULT" in section or "DISCUSSION" in section: sentence_vec = sentence2vec(sentence, model, stopwords, metadata, RESULT_DISCUSSION, False) elif "CONCLUSION" in section: sentence_vec = sentence2vec(sentence, model, stopwords, metadata, CONCLUSION, False) else: sentence_vec = sentence2vec(sentence, model, stopwords, metadata, OTHER, False) section_as_vector.append(sentence_vec) section_text.append(sentence) new_paper[section] = (section_text, section_as_vector, pos) return new_paper
[ "def", "paper2vec", "(", "paper", ",", "model", ",", "metadata", ")", ":", "stopwords", "=", "read_stopwords", "(", ")", "new_paper", "=", "defaultdict", "(", "None", ")", "for", "section", ",", "text", "in", "paper", ".", "iteritems", "(", ")", ":", "...
https://github.com/EdCo95/scientific-paper-summarisation/blob/5a6217556704dda5694c298e17b909acd1608be1/DataTools/useful_functions.py#L695-L730
sympy/sympy
d822fcba181155b85ff2b29fe525adbafb22b448
sympy/physics/vector/vector.py
python
Vector.simplify
(self)
return Vector(d)
Returns a simplified Vector.
Returns a simplified Vector.
[ "Returns", "a", "simplified", "Vector", "." ]
def simplify(self): """Returns a simplified Vector.""" d = {} for v in self.args: d[v[1]] = _simplify_matrix(v[0]) return Vector(d)
[ "def", "simplify", "(", "self", ")", ":", "d", "=", "{", "}", "for", "v", "in", "self", ".", "args", ":", "d", "[", "v", "[", "1", "]", "]", "=", "_simplify_matrix", "(", "v", "[", "0", "]", ")", "return", "Vector", "(", "d", ")" ]
https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/physics/vector/vector.py#L655-L660
ConsenSys/mythril
d00152f8e4d925c7749d63b533152a937e1dd516
mythril/laser/ethereum/svm.py
python
LaserEVM.__init__
( self, dynamic_loader=None, max_depth=float("inf"), execution_timeout=60, create_timeout=10, strategy=DepthFirstSearchStrategy, transaction_count=2, requires_statespace=True, iprof=None, )
Initializes the laser evm object :param dynamic_loader: Loads data from chain :param max_depth: Maximum execution depth this vm should execute :param execution_timeout: Time to take for execution :param create_timeout: Time to take for contract creation :param strategy: Execution search strategy :param transaction_count: The amount of transactions to execute :param requires_statespace: Variable indicating whether the statespace should be recorded :param iprof: Instruction Profiler
Initializes the laser evm object
[ "Initializes", "the", "laser", "evm", "object" ]
def __init__( self, dynamic_loader=None, max_depth=float("inf"), execution_timeout=60, create_timeout=10, strategy=DepthFirstSearchStrategy, transaction_count=2, requires_statespace=True, iprof=None, ) -> None: """ Initializes the laser evm object :param dynamic_loader: Loads data from chain :param max_depth: Maximum execution depth this vm should execute :param execution_timeout: Time to take for execution :param create_timeout: Time to take for contract creation :param strategy: Execution search strategy :param transaction_count: The amount of transactions to execute :param requires_statespace: Variable indicating whether the statespace should be recorded :param iprof: Instruction Profiler """ self.execution_info = [] # type: List[ExecutionInfo] self.open_states = [] # type: List[WorldState] self.total_states = 0 self.dynamic_loader = dynamic_loader # TODO: What about using a deque here? self.work_list = [] # type: List[GlobalState] self.strategy = strategy(self.work_list, max_depth) self.max_depth = max_depth self.transaction_count = transaction_count self.execution_timeout = execution_timeout or 0 self.create_timeout = create_timeout or 0 self.requires_statespace = requires_statespace if self.requires_statespace: self.nodes = {} # type: Dict[int, Node] self.edges = [] # type: List[Edge] self.time = None # type: datetime self.pre_hooks = defaultdict(list) # type: DefaultDict[str, List[Callable]] self.post_hooks = defaultdict(list) # type: DefaultDict[str, List[Callable]] self._add_world_state_hooks = [] # type: List[Callable] self._execute_state_hooks = [] # type: List[Callable] self._start_sym_trans_hooks = [] # type: List[Callable] self._stop_sym_trans_hooks = [] # type: List[Callable] self._start_sym_exec_hooks = [] # type: List[Callable] self._stop_sym_exec_hooks = [] # type: List[Callable] self.iprof = iprof self.instr_pre_hook = {} # type: Dict[str, List[Callable]] self.instr_post_hook = {} # type: Dict[str, List[Callable]] for op in OPCODES: self.instr_pre_hook[op] = [] self.instr_post_hook[op] = [] log.info("LASER EVM initialized with dynamic loader: " + str(dynamic_loader))
[ "def", "__init__", "(", "self", ",", "dynamic_loader", "=", "None", ",", "max_depth", "=", "float", "(", "\"inf\"", ")", ",", "execution_timeout", "=", "60", ",", "create_timeout", "=", "10", ",", "strategy", "=", "DepthFirstSearchStrategy", ",", "transaction_...
https://github.com/ConsenSys/mythril/blob/d00152f8e4d925c7749d63b533152a937e1dd516/mythril/laser/ethereum/svm.py#L53-L116
openworm/owmeta
4d546107c12ecb12f3d946db7a44b93b80877132
owmeta/network.py
python
Network.motor
(self)
return res
Get all motor :returns: A iterable of all motor neurons :rtype: iter(Neuron)
Get all motor
[ "Get", "all", "motor" ]
def motor(self): """ Get all motor :returns: A iterable of all motor neurons :rtype: iter(Neuron) """ n = Neuron.contextualize(self.context)() n.type('motor') self.neuron.set(n) res = list(n.load()) self.neuron.unset(n) return res
[ "def", "motor", "(", "self", ")", ":", "n", "=", "Neuron", ".", "contextualize", "(", "self", ".", "context", ")", "(", ")", "n", ".", "type", "(", "'motor'", ")", "self", ".", "neuron", ".", "set", "(", "n", ")", "res", "=", "list", "(", "n", ...
https://github.com/openworm/owmeta/blob/4d546107c12ecb12f3d946db7a44b93b80877132/owmeta/network.py#L112-L126
EdinburghNLP/XSum
7b95485c3e861d7caff76a8b4c6b3fd3bf7ee9b1
XSum-ConvS2S/fairseq/dictionary.py
python
Dictionary.string
(self, tensor, bpe_symbol=None, escape_unk=False)
return sent
Helper for converting a tensor of token indices to a string. Can optionally remove BPE symbols or escape <unk> words.
Helper for converting a tensor of token indices to a string.
[ "Helper", "for", "converting", "a", "tensor", "of", "token", "indices", "to", "a", "string", "." ]
def string(self, tensor, bpe_symbol=None, escape_unk=False): """Helper for converting a tensor of token indices to a string. Can optionally remove BPE symbols or escape <unk> words. """ if torch.is_tensor(tensor) and tensor.dim() == 2: return '\n'.join(self.string(t) for t in tensor) def token_string(i): if i == self.unk(): return self.unk_string(escape_unk) else: return self[i] sent = ' '.join(token_string(i) for i in tensor if i != self.eos()) if bpe_symbol is not None: sent = sent.replace(bpe_symbol, '') return sent
[ "def", "string", "(", "self", ",", "tensor", ",", "bpe_symbol", "=", "None", ",", "escape_unk", "=", "False", ")", ":", "if", "torch", ".", "is_tensor", "(", "tensor", ")", "and", "tensor", ".", "dim", "(", ")", "==", "2", ":", "return", "'\\n'", "...
https://github.com/EdinburghNLP/XSum/blob/7b95485c3e861d7caff76a8b4c6b3fd3bf7ee9b1/XSum-ConvS2S/fairseq/dictionary.py#L41-L58
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/supervisord/sensor.py
python
SupervisorProcessSensor.available
(self)
return self._available
Could the device be accessed during the last update call.
Could the device be accessed during the last update call.
[ "Could", "the", "device", "be", "accessed", "during", "the", "last", "update", "call", "." ]
def available(self): """Could the device be accessed during the last update call.""" return self._available
[ "def", "available", "(", "self", ")", ":", "return", "self", ".", "_available" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/supervisord/sensor.py#L70-L72
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/min/symtable.py
python
SymbolTableFactory.new
(self, table, filename)
return SymbolTable(table, filename)
[]
def new(self, table, filename): if table.type == _symtable.TYPE_FUNCTION: return Function(table, filename) if table.type == _symtable.TYPE_CLASS: return Class(table, filename) return SymbolTable(table, filename)
[ "def", "new", "(", "self", ",", "table", ",", "filename", ")", ":", "if", "table", ".", "type", "==", "_symtable", ".", "TYPE_FUNCTION", ":", "return", "Function", "(", "table", ",", "filename", ")", "if", "table", ".", "type", "==", "_symtable", ".", ...
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/symtable.py#L25-L30
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
haproxy/datadog_checks/haproxy/config_models/defaults.py
python
instance_tags
(field, value)
return get_default_field_value(field, value)
[]
def instance_tags(field, value): return get_default_field_value(field, value)
[ "def", "instance_tags", "(", "field", ",", "value", ")", ":", "return", "get_default_field_value", "(", "field", ",", "value", ")" ]
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/haproxy/datadog_checks/haproxy/config_models/defaults.py#L277-L278
aleju/imgaug
0101108d4fed06bc5056c4a03e2bcb0216dac326
imgaug/parameters.py
python
Sigmoid.__repr__
(self)
return self.__str__()
[]
def __repr__(self): return self.__str__()
[ "def", "__repr__", "(", "self", ")", ":", "return", "self", ".", "__str__", "(", ")" ]
https://github.com/aleju/imgaug/blob/0101108d4fed06bc5056c4a03e2bcb0216dac326/imgaug/parameters.py#L3186-L3187
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/argparse.py
python
ArgumentParser.print_help
(self, file=None)
[]
def print_help(self, file=None): if file is None: file = _sys.stdout self._print_message(self.format_help(), file)
[ "def", "print_help", "(", "self", ",", "file", "=", "None", ")", ":", "if", "file", "is", "None", ":", "file", "=", "_sys", ".", "stdout", "self", ".", "_print_message", "(", "self", ".", "format_help", "(", ")", ",", "file", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/argparse.py#L2337-L2340
nosmokingbandit/Watcher3
0217e75158b563bdefc8e01c3be7620008cf3977
lib/sqlalchemy/dialects/mssql/base.py
python
MSIdentifierPreparer.quote_schema
(self, schema, force=None)
return result
Prepare a quoted table and schema name.
Prepare a quoted table and schema name.
[ "Prepare", "a", "quoted", "table", "and", "schema", "name", "." ]
def quote_schema(self, schema, force=None): """Prepare a quoted table and schema name.""" result = '.'.join([self.quote(x, force) for x in schema.split('.')]) return result
[ "def", "quote_schema", "(", "self", ",", "schema", ",", "force", "=", "None", ")", ":", "result", "=", "'.'", ".", "join", "(", "[", "self", ".", "quote", "(", "x", ",", "force", ")", "for", "x", "in", "schema", ".", "split", "(", "'.'", ")", "...
https://github.com/nosmokingbandit/Watcher3/blob/0217e75158b563bdefc8e01c3be7620008cf3977/lib/sqlalchemy/dialects/mssql/base.py#L1552-L1555
dcos/dcos
79b9a39b4e639dc2c9435a869918399b50bfaf24
gen/exhibitor_tls_bootstrap.py
python
_check
(config: Dict[str, Any])
return reasons, hard_failure
Current constraints are: config.yaml: - exhibitor_tls_enabled == True, - bootstrap_url must not be a local path This is necessary to prevent this orchestration from running when gen is not executed on a proper bootstrap node. This is a soft failure - master_discovery must be static - DC/OS variant must be enterprise - exhibitor_bootstrap_ca_url must not be set. When set, it indicates that the ca service will be initialized and started outside of gen. Hard failures help us to fail early when exhibitor_tls_required == True. Soft "failures" allow CA initialization to occur outside of genconf.
Current constraints are: config.yaml: - exhibitor_tls_enabled == True, - bootstrap_url must not be a local path This is necessary to prevent this orchestration from running when gen is not executed on a proper bootstrap node. This is a soft failure - master_discovery must be static - DC/OS variant must be enterprise - exhibitor_bootstrap_ca_url must not be set. When set, it indicates that the ca service will be initialized and started outside of gen. Hard failures help us to fail early when exhibitor_tls_required == True. Soft "failures" allow CA initialization to occur outside of genconf.
[ "Current", "constraints", "are", ":", "config", ".", "yaml", ":", "-", "exhibitor_tls_enabled", "==", "True", "-", "bootstrap_url", "must", "not", "be", "a", "local", "path", "This", "is", "necessary", "to", "prevent", "this", "orchestration", "from", "running...
def _check(config: Dict[str, Any]) -> Tuple[List[str], bool]: """ Current constraints are: config.yaml: - exhibitor_tls_enabled == True, - bootstrap_url must not be a local path This is necessary to prevent this orchestration from running when gen is not executed on a proper bootstrap node. This is a soft failure - master_discovery must be static - DC/OS variant must be enterprise - exhibitor_bootstrap_ca_url must not be set. When set, it indicates that the ca service will be initialized and started outside of gen. Hard failures help us to fail early when exhibitor_tls_required == True. Soft "failures" allow CA initialization to occur outside of genconf. """ checks = [ (lambda: config.get('exhibitor_tls_enabled') == 'true', 'Exhibitor security is disabled', True), (lambda: config['master_discovery'] == 'static', 'Only static master discovery is supported', True), (lambda: config['dcos_variant'] == 'enterprise', 'Exhibitor security is an enterprise feature', True), (lambda: urlparse(config['bootstrap_url']).scheme != 'file', 'CA init in gen is only supported when using a remote' ' bootstrap node', False), (lambda: 'exhibitor_bootstrap_ca_url' in config, 'Custom CA url has been specified, not initializing CA', False) ] reasons = [] hard_failure = False for (func, reason, hard) in checks: if not func(): if hard: hard_failure = True reasons.append(reason) return reasons, hard_failure
[ "def", "_check", "(", "config", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Tuple", "[", "List", "[", "str", "]", ",", "bool", "]", ":", "checks", "=", "[", "(", "lambda", ":", "config", ".", "get", "(", "'exhibitor_tls_enabled'", ")", ...
https://github.com/dcos/dcos/blob/79b9a39b4e639dc2c9435a869918399b50bfaf24/gen/exhibitor_tls_bootstrap.py#L18-L58
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v8/services/services/campaign_budget_service/client.py
python
CampaignBudgetServiceClient.parse_common_organization_path
(path: str)
return m.groupdict() if m else {}
Parse a organization path into its component segments.
Parse a organization path into its component segments.
[ "Parse", "a", "organization", "path", "into", "its", "component", "segments", "." ]
def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P<organization>.+?)$", path) return m.groupdict() if m else {}
[ "def", "parse_common_organization_path", "(", "path", ":", "str", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "m", "=", "re", ".", "match", "(", "r\"^organizations/(?P<organization>.+?)$\"", ",", "path", ")", "return", "m", ".", "groupdict", "(", ...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v8/services/services/campaign_budget_service/client.py#L205-L208
mpenning/ciscoconfparse
a6a176e6ceac7c5f3e974272fa70273476ba84a3
ciscoconfparse/models_cisco.py
python
BaseIOSIntfLine.has_no_icmp_unreachables
(self)
return retval
[]
def has_no_icmp_unreachables(self): ## NOTE: I have no intention of checking self.is_shutdown here ## People should be able to check the sanity of interfaces ## before they put them into production ## Interface must have an IP addr to respond if self.ipv4_addr == "": return False retval = self.re_match_iter_typed( r"^\s*no\sip\s(unreachables)\s*$", result_type=bool, default=False ) return retval
[ "def", "has_no_icmp_unreachables", "(", "self", ")", ":", "## NOTE: I have no intention of checking self.is_shutdown here", "## People should be able to check the sanity of interfaces", "## before they put them into production", "## Interface must have an IP addr to respond", "if", "se...
https://github.com/mpenning/ciscoconfparse/blob/a6a176e6ceac7c5f3e974272fa70273476ba84a3/ciscoconfparse/models_cisco.py#L1104-L1116
wxWidgets/Phoenix
b2199e299a6ca6d866aa6f3d0888499136ead9d6
wx/lib/throbber.py
python
Throbber.__init__
(self, parent, id, bitmap, pos = wx.DefaultPosition, size = wx.DefaultSize, frameDelay = 0.1, frames = 0, frameWidth = 0, label = None, overlay = None, reverse = 0, style = 0, name = "throbber", rest = 0, current = 0, direction = 1, sequence = None )
Default class constructor. :param `parent`: parent window, must not be ``None`` :param integer `id`: window identifier. A value of -1 indicates a default value :param `bitmap`: a :class:`wx.Bitmap` to be used :param `pos`: the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform :param `size`: the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform :param `frameDelay`: time delay between frames :param `frames`: number of frames (only necessary for composite image) :param `frameWidth`: width of each frame (only necessary for composite image) :param string `label`: optional text to be displayed :param `overlay`: optional :class:`wx.Bitmap` to overlay on animation :param boolean `reverse`: reverse direction at end of animation :param integer `style`: the underlying :class:`wx.Control` style :param string `name`: the widget name. :param `rest`: the rest frame :param `current`: the current frame :param `direction`: 1 advances = -1 reverses :param `sequence`: sequence of frames, defaults to range(self.frames)
Default class constructor.
[ "Default", "class", "constructor", "." ]
def __init__(self, parent, id, bitmap, pos = wx.DefaultPosition, size = wx.DefaultSize, frameDelay = 0.1, frames = 0, frameWidth = 0, label = None, overlay = None, reverse = 0, style = 0, name = "throbber", rest = 0, current = 0, direction = 1, sequence = None ): """ Default class constructor. :param `parent`: parent window, must not be ``None`` :param integer `id`: window identifier. A value of -1 indicates a default value :param `bitmap`: a :class:`wx.Bitmap` to be used :param `pos`: the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform :param `size`: the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform :param `frameDelay`: time delay between frames :param `frames`: number of frames (only necessary for composite image) :param `frameWidth`: width of each frame (only necessary for composite image) :param string `label`: optional text to be displayed :param `overlay`: optional :class:`wx.Bitmap` to overlay on animation :param boolean `reverse`: reverse direction at end of animation :param integer `style`: the underlying :class:`wx.Control` style :param string `name`: the widget name. :param `rest`: the rest frame :param `current`: the current frame :param `direction`: 1 advances = -1 reverses :param `sequence`: sequence of frames, defaults to range(self.frames) """ super(Throbber, self).__init__(parent, id, pos, size, style, name) self.name = name self.label = label self.running = (1 != 1) _seqTypes = (type([]), type(())) # set size, guessing if necessary width, height = size if width == -1: if type(bitmap) in _seqTypes: width = bitmap[0].GetWidth() else: if frameWidth: width = frameWidth if height == -1: if type(bitmap) in _seqTypes: height = bitmap[0].GetHeight() else: height = bitmap.GetHeight() self.width, self.height = width, height # double check it assert width != -1 and height != -1, "Unable to guess size" if label: extentX, extentY = self.GetTextExtent(label) self.labelX = (width - extentX)/2 self.labelY = (height - extentY)/2 self.frameDelay = frameDelay self.rest = rest self.current = current self.direction = direction self.autoReverse = reverse self.overlay = overlay if overlay is not None: self.overlay = overlay self.overlayX = (width - self.overlay.GetWidth()) / 2 self.overlayY = (height - self.overlay.GetHeight()) / 2 self.showOverlay = overlay is not None self.showLabel = label is not None # do we have a sequence of images? if type(bitmap) in _seqTypes: self.submaps = bitmap self.frames = len(self.submaps) # or a composite image that needs to be split? else: self.frames = frames self.submaps = [] for chunk in range(frames): rect = (chunk * frameWidth, 0, width, height) self.submaps.append(bitmap.GetSubBitmap(rect)) # self.sequence can be changed, but it's not recommended doing it # while the throbber is running. self.sequence[0] should always # refer to whatever frame is to be shown when 'resting' and be sure # that no item in self.sequence >= self.frames or < 0!!! self.SetSequence(sequence) self.SetClientSize((width, height)) timerID = wx.NewIdRef() self.timer = wx.Timer(self, timerID) self.Bind(EVT_UPDATE_THROBBER, self.Update) self.Bind(wx.EVT_PAINT, self.OnPaint) self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer) self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroyWindow)
[ "def", "__init__", "(", "self", ",", "parent", ",", "id", ",", "bitmap", ",", "pos", "=", "wx", ".", "DefaultPosition", ",", "size", "=", "wx", ".", "DefaultSize", ",", "frameDelay", "=", "0.1", ",", "frames", "=", "0", ",", "frameWidth", "=", "0", ...
https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/throbber.py#L51-L160
YujiaBao/Distributional-Signatures
c613ed070af3e7ae4967b9942fde16864af28cde
src/embedding/meta.py
python
RNN._sort_tensor
(self, input, lengths)
return sorted_input, sorted_lengths, invert_order, num_zero
pack_padded_sequence requires the length of seq be in descending order to work. Returns the sorted tensor, the sorted seq length, and the indices for inverting the order. Input: input: batch_size, seq_len, * lengths: batch_size Output: sorted_tensor: batch_size-num_zero, seq_len, * sorted_len: batch_size-num_zero sorted_order: batch_size num_zero
pack_padded_sequence requires the length of seq be in descending order to work. Returns the sorted tensor, the sorted seq length, and the indices for inverting the order.
[ "pack_padded_sequence", "requires", "the", "length", "of", "seq", "be", "in", "descending", "order", "to", "work", ".", "Returns", "the", "sorted", "tensor", "the", "sorted", "seq", "length", "and", "the", "indices", "for", "inverting", "the", "order", "." ]
def _sort_tensor(self, input, lengths): ''' pack_padded_sequence requires the length of seq be in descending order to work. Returns the sorted tensor, the sorted seq length, and the indices for inverting the order. Input: input: batch_size, seq_len, * lengths: batch_size Output: sorted_tensor: batch_size-num_zero, seq_len, * sorted_len: batch_size-num_zero sorted_order: batch_size num_zero ''' sorted_lengths, sorted_order = lengths.sort(0, descending=True) sorted_input = input[sorted_order] _, invert_order = sorted_order.sort(0, descending=False) # Calculate the num. of sequences that have len 0 nonzero_idx = sorted_lengths.nonzero() num_nonzero = nonzero_idx.size()[0] num_zero = sorted_lengths.size()[0] - num_nonzero # temporarily remove seq with len zero sorted_input = sorted_input[:num_nonzero] sorted_lengths = sorted_lengths[:num_nonzero] return sorted_input, sorted_lengths, invert_order, num_zero
[ "def", "_sort_tensor", "(", "self", ",", "input", ",", "lengths", ")", ":", "sorted_lengths", ",", "sorted_order", "=", "lengths", ".", "sort", "(", "0", ",", "descending", "=", "True", ")", "sorted_input", "=", "input", "[", "sorted_order", "]", "_", ",...
https://github.com/YujiaBao/Distributional-Signatures/blob/c613ed070af3e7ae4967b9942fde16864af28cde/src/embedding/meta.py#L18-L47
jrzaurin/pytorch-widedeep
8b4c3a8acbf06b385c821d7111b1139a16b4f480
pytorch_widedeep/training/trainer.py
python
Trainer._predict
( # noqa: C901 self, X_wide: Optional[np.ndarray] = None, X_tab: Optional[np.ndarray] = None, X_text: Optional[np.ndarray] = None, X_img: Optional[np.ndarray] = None, X_test: Optional[Dict[str, np.ndarray]] = None, batch_size: int = 256, uncertainty_granularity=1000, uncertainty: bool = False, quantiles: bool = False, )
return preds_l
r"""Private method to avoid code repetition in predict and predict_proba. For parameter information, please, see the .predict() method documentation
r"""Private method to avoid code repetition in predict and predict_proba. For parameter information, please, see the .predict() method documentation
[ "r", "Private", "method", "to", "avoid", "code", "repetition", "in", "predict", "and", "predict_proba", ".", "For", "parameter", "information", "please", "see", "the", ".", "predict", "()", "method", "documentation" ]
def _predict( # noqa: C901 self, X_wide: Optional[np.ndarray] = None, X_tab: Optional[np.ndarray] = None, X_text: Optional[np.ndarray] = None, X_img: Optional[np.ndarray] = None, X_test: Optional[Dict[str, np.ndarray]] = None, batch_size: int = 256, uncertainty_granularity=1000, uncertainty: bool = False, quantiles: bool = False, ) -> List: r"""Private method to avoid code repetition in predict and predict_proba. For parameter information, please, see the .predict() method documentation """ if X_test is not None: test_set = WideDeepDataset(**X_test) else: load_dict = {} if X_wide is not None: load_dict = {"X_wide": X_wide} if X_tab is not None: load_dict.update({"X_tab": X_tab}) if X_text is not None: load_dict.update({"X_text": X_text}) if X_img is not None: load_dict.update({"X_img": X_img}) test_set = WideDeepDataset(**load_dict) if not hasattr(self, "batch_size"): self.batch_size = batch_size test_loader = DataLoader( dataset=test_set, batch_size=self.batch_size, num_workers=n_cpus, shuffle=False, ) test_steps = (len(test_loader.dataset) // test_loader.batch_size) + 1 # type: ignore[arg-type] self.model.eval() preds_l = [] if uncertainty: for m in self.model.modules(): if m.__class__.__name__.startswith("Dropout"): m.train() prediction_iters = uncertainty_granularity else: prediction_iters = 1 with torch.no_grad(): with trange(uncertainty_granularity, disable=uncertainty is False) as t: for i, k in zip(t, range(prediction_iters)): t.set_description("predict_UncertaintyIter") with trange( test_steps, disable=self.verbose != 1 or uncertainty is True ) as tt: for j, data in zip(tt, test_loader): tt.set_description("predict") X = ( {k: v.cuda() for k, v in data.items()} if use_cuda else data ) preds = ( self.model(X) if not self.model.is_tabnet else self.model(X)[0] ) if self.method == "binary": preds = torch.sigmoid(preds) if self.method == "multiclass": preds = F.softmax(preds, dim=1) if self.method == "regression" and isinstance( self.loss_fn, ZILNLoss ): preds = self._predict_ziln(preds) preds = preds.cpu().data.numpy() preds_l.append(preds) self.model.train() return preds_l
[ "def", "_predict", "(", "# noqa: C901", "self", ",", "X_wide", ":", "Optional", "[", "np", ".", "ndarray", "]", "=", "None", ",", "X_tab", ":", "Optional", "[", "np", ".", "ndarray", "]", "=", "None", ",", "X_text", ":", "Optional", "[", "np", ".", ...
https://github.com/jrzaurin/pytorch-widedeep/blob/8b4c3a8acbf06b385c821d7111b1139a16b4f480/pytorch_widedeep/training/trainer.py#L1237-L1320
DevTable/gantryd
eb348113f0f73a0be45a45f7a5626ad2b5dd30ba
config/object.py
python
CFObject.getRootConfig
(self)
return self
Returns the root configuration object.
Returns the root configuration object.
[ "Returns", "the", "root", "configuration", "object", "." ]
def getRootConfig(self): """ Returns the root configuration object. """ if self.parent: return self.parent return self
[ "def", "getRootConfig", "(", "self", ")", ":", "if", "self", ".", "parent", ":", "return", "self", ".", "parent", "return", "self" ]
https://github.com/DevTable/gantryd/blob/eb348113f0f73a0be45a45f7a5626ad2b5dd30ba/config/object.py#L105-L110
mlflow/mlflow
364aca7daf0fcee3ec407ae0b1b16d9cb3085081
mlflow/tracking/client.py
python
MlflowClient.delete_model_version_tag
(self, name: str, version: str, key: str)
Delete a tag associated with the model version. :param name: Registered model name. :param version: Registered model version. :param key: Tag key. :return: None .. code-block:: python :caption: Example import mlflow.sklearn from mlflow.tracking import MlflowClient from sklearn.ensemble import RandomForestRegressor def print_model_version_info(mv): print("Name: {}".format(mv.name)) print("Version: {}".format(mv.version)) print("Tags: {}".format(mv.tags)) mlflow.set_tracking_uri("sqlite:///mlruns.db") params = {"n_estimators": 3, "random_state": 42} name = "RandomForestRegression" rfr = RandomForestRegressor(**params).fit([[0, 1]], [1]) # Log MLflow entities with mlflow.start_run() as run: mlflow.log_params(params) mlflow.sklearn.log_model(rfr, artifact_path="sklearn-model") # Register model name in the model registry client = MlflowClient() client.create_registered_model(name) # Create a new version of the rfr model under the registered model name # and delete a tag model_uri = "runs:/{}/sklearn-model".format(run.info.run_id) tags = {'t': "t1"} mv = client.create_model_version(name, model_uri, run.info.run_id, tags=tags) print_model_version_info(mv) print("--") client.delete_model_version_tag(name, mv.version, "t") mv = client.get_model_version(name, mv.version) print_model_version_info(mv) .. code-block:: text :caption: Output Name: RandomForestRegression Version: 1 Tags: {'t': 't1'} -- Name: RandomForestRegression Version: 1 Tags: {}
Delete a tag associated with the model version.
[ "Delete", "a", "tag", "associated", "with", "the", "model", "version", "." ]
def delete_model_version_tag(self, name: str, version: str, key: str) -> None: """ Delete a tag associated with the model version. :param name: Registered model name. :param version: Registered model version. :param key: Tag key. :return: None .. code-block:: python :caption: Example import mlflow.sklearn from mlflow.tracking import MlflowClient from sklearn.ensemble import RandomForestRegressor def print_model_version_info(mv): print("Name: {}".format(mv.name)) print("Version: {}".format(mv.version)) print("Tags: {}".format(mv.tags)) mlflow.set_tracking_uri("sqlite:///mlruns.db") params = {"n_estimators": 3, "random_state": 42} name = "RandomForestRegression" rfr = RandomForestRegressor(**params).fit([[0, 1]], [1]) # Log MLflow entities with mlflow.start_run() as run: mlflow.log_params(params) mlflow.sklearn.log_model(rfr, artifact_path="sklearn-model") # Register model name in the model registry client = MlflowClient() client.create_registered_model(name) # Create a new version of the rfr model under the registered model name # and delete a tag model_uri = "runs:/{}/sklearn-model".format(run.info.run_id) tags = {'t': "t1"} mv = client.create_model_version(name, model_uri, run.info.run_id, tags=tags) print_model_version_info(mv) print("--") client.delete_model_version_tag(name, mv.version, "t") mv = client.get_model_version(name, mv.version) print_model_version_info(mv) .. code-block:: text :caption: Output Name: RandomForestRegression Version: 1 Tags: {'t': 't1'} -- Name: RandomForestRegression Version: 1 Tags: {} """ self._get_registry_client().delete_model_version_tag(name, version, key)
[ "def", "delete_model_version_tag", "(", "self", ",", "name", ":", "str", ",", "version", ":", "str", ",", "key", ":", "str", ")", "->", "None", ":", "self", ".", "_get_registry_client", "(", ")", ".", "delete_model_version_tag", "(", "name", ",", "version"...
https://github.com/mlflow/mlflow/blob/364aca7daf0fcee3ec407ae0b1b16d9cb3085081/mlflow/tracking/client.py#L2735-L2792
hugapi/hug
8b5ac00632543addfdcecc326d0475a685a0cba7
hug/routing.py
python
URLRouter.post
(self, urls=None, **overrides)
return self.where(accept="POST", **overrides)
Sets the acceptable HTTP method to POST
Sets the acceptable HTTP method to POST
[ "Sets", "the", "acceptable", "HTTP", "method", "to", "POST" ]
def post(self, urls=None, **overrides): """Sets the acceptable HTTP method to POST""" if urls is not None: overrides["urls"] = urls return self.where(accept="POST", **overrides)
[ "def", "post", "(", "self", ",", "urls", "=", "None", ",", "*", "*", "overrides", ")", ":", "if", "urls", "is", "not", "None", ":", "overrides", "[", "\"urls\"", "]", "=", "urls", "return", "self", ".", "where", "(", "accept", "=", "\"POST\"", ",",...
https://github.com/hugapi/hug/blob/8b5ac00632543addfdcecc326d0475a685a0cba7/hug/routing.py#L531-L535
dropbox/dropbox-sdk-python
015437429be224732990041164a21a0501235db1
dropbox/team_log.py
python
AdminConsoleAppPermission.is_other
(self)
return self._tag == 'other'
Check if the union tag is ``other``. :rtype: bool
Check if the union tag is ``other``.
[ "Check", "if", "the", "union", "tag", "is", "other", "." ]
def is_other(self): """ Check if the union tag is ``other``. :rtype: bool """ return self._tag == 'other'
[ "def", "is_other", "(", "self", ")", ":", "return", "self", ".", "_tag", "==", "'other'" ]
https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/team_log.py#L1779-L1785
BradNeuberg/cloudless
052d16e314a24b3ff36d9da94f2e9e53e0e1e0e0
src/annotate/train/scripts/download_planetlabs.py
python
download
(lat, lng, buff_meters, download_dir='/tmp', image_type='planetlabs')
return downloaded_scenes
Given a latitude, longitude, and a number of meters to buffer by, get all imagery that intersects the bounding box of the buffer and download it to the specified directory. Return the names of the downloaded files.
Given a latitude, longitude, and a number of meters to buffer by, get all imagery that intersects the bounding box of the buffer and download it to the specified directory. Return the names of the downloaded files.
[ "Given", "a", "latitude", "longitude", "and", "a", "number", "of", "meters", "to", "buffer", "by", "get", "all", "imagery", "that", "intersects", "the", "bounding", "box", "of", "the", "buffer", "and", "download", "it", "to", "the", "specified", "directory",...
def download(lat, lng, buff_meters, download_dir='/tmp', image_type='planetlabs'): """ Given a latitude, longitude, and a number of meters to buffer by, get all imagery that intersects the bounding box of the buffer and download it to the specified directory. Return the names of the downloaded files. """ pt = ogr.CreateGeometryFromWkt('POINT(%s %s)' % (lng, lat)) pt = reproject(pt, 4326, 2163) # from WGS84 to National Atlas buff = buffer_bbox(pt, buff_meters) buff = reproject(buff, 2163, 4326) if image_type == 'planetlabs': scenes_url = "https://api.planet.com/v0/scenes/ortho/" elif image_type == 'rapideye': scenes_url = "https://api.planet.com/v0/scenes/rapideye/" # Download the initial scenes URL and also any paged results that come after that. downloaded_scenes = [] next_url = scenes_url params = {"intersects": buff.ExportToWkt()} while next_url != None: next_url = download_results(next_url, params, downloaded_scenes, download_dir, image_type) print "\nWorking with next page of results: %s" % next_url return downloaded_scenes
[ "def", "download", "(", "lat", ",", "lng", ",", "buff_meters", ",", "download_dir", "=", "'/tmp'", ",", "image_type", "=", "'planetlabs'", ")", ":", "pt", "=", "ogr", ".", "CreateGeometryFromWkt", "(", "'POINT(%s %s)'", "%", "(", "lng", ",", "lat", ")", ...
https://github.com/BradNeuberg/cloudless/blob/052d16e314a24b3ff36d9da94f2e9e53e0e1e0e0/src/annotate/train/scripts/download_planetlabs.py#L19-L44
log2timeline/plaso
fe2e316b8c76a0141760c0f2f181d84acb83abc2
plaso/storage/redis/writer.py
python
RedisStorageWriter.GetNextWrittenEventSource
(self)
return None
Retrieves the next event source that was written after open. Returns: EventSource: None as there are no newly written event sources. Raises: IOError: if the storage writer is closed. OSError: if the storage writer is closed.
Retrieves the next event source that was written after open.
[ "Retrieves", "the", "next", "event", "source", "that", "was", "written", "after", "open", "." ]
def GetNextWrittenEventSource(self): """Retrieves the next event source that was written after open. Returns: EventSource: None as there are no newly written event sources. Raises: IOError: if the storage writer is closed. OSError: if the storage writer is closed. """ if not self._store: raise IOError('Unable to read from closed storage writer.') return None
[ "def", "GetNextWrittenEventSource", "(", "self", ")", ":", "if", "not", "self", ".", "_store", ":", "raise", "IOError", "(", "'Unable to read from closed storage writer.'", ")", "return", "None" ]
https://github.com/log2timeline/plaso/blob/fe2e316b8c76a0141760c0f2f181d84acb83abc2/plaso/storage/redis/writer.py#L31-L44
qibinlou/SinaWeibo-Emotion-Classification
f336fc104abd68b0ec4180fe2ed80fafe49cb790
jinja2/compiler.py
python
Frame.soft
(self)
return rv
Return a soft frame. A soft frame may not be modified as standalone thing as it shares the resources with the frame it was created of, but it's not a rootlevel frame any longer.
Return a soft frame. A soft frame may not be modified as standalone thing as it shares the resources with the frame it was created of, but it's not a rootlevel frame any longer.
[ "Return", "a", "soft", "frame", ".", "A", "soft", "frame", "may", "not", "be", "modified", "as", "standalone", "thing", "as", "it", "shares", "the", "resources", "with", "the", "frame", "it", "was", "created", "of", "but", "it", "s", "not", "a", "rootl...
def soft(self): """Return a soft frame. A soft frame may not be modified as standalone thing as it shares the resources with the frame it was created of, but it's not a rootlevel frame any longer. """ rv = self.copy() rv.rootlevel = False return rv
[ "def", "soft", "(", "self", ")", ":", "rv", "=", "self", ".", "copy", "(", ")", "rv", ".", "rootlevel", "=", "False", "return", "rv" ]
https://github.com/qibinlou/SinaWeibo-Emotion-Classification/blob/f336fc104abd68b0ec4180fe2ed80fafe49cb790/jinja2/compiler.py#L214-L221
osmr/imgclsmob
f2993d3ce73a2f7ddba05da3891defb08547d504
chainer_/chainercv2/models/seresnet.py
python
seresnet16
(**kwargs)
return get_seresnet(blocks=16, model_name="seresnet16", **kwargs)
SE-ResNet-16 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. It's an experimental model. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.chainer/models' Location for keeping the model parameters.
SE-ResNet-16 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. It's an experimental model.
[ "SE", "-", "ResNet", "-", "16", "model", "from", "Squeeze", "-", "and", "-", "Excitation", "Networks", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1709", ".", "01507", ".", "It", "s", "an", "experimental", "model", "." ]
def seresnet16(**kwargs): """ SE-ResNet-16 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. It's an experimental model. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.chainer/models' Location for keeping the model parameters. """ return get_seresnet(blocks=16, model_name="seresnet16", **kwargs)
[ "def", "seresnet16", "(", "*", "*", "kwargs", ")", ":", "return", "get_seresnet", "(", "blocks", "=", "16", ",", "model_name", "=", "\"seresnet16\"", ",", "*", "*", "kwargs", ")" ]
https://github.com/osmr/imgclsmob/blob/f2993d3ce73a2f7ddba05da3891defb08547d504/chainer_/chainercv2/models/seresnet.py#L290-L302
guillermooo/dart-sublime-bundle
d891fb36c98ca0b111a35cba109b05a16b6c4b83
out_there/yaml/scanner.py
python
Scanner.__init__
(self)
Initialize the scanner.
Initialize the scanner.
[ "Initialize", "the", "scanner", "." ]
def __init__(self): """Initialize the scanner.""" # It is assumed that Scanner and Reader will have a common descendant. # Reader do the dirty work of checking for BOM and converting the # input data to Unicode. It also adds NUL to the end. # # Reader supports the following methods # self.peek(i=0) # peek the next i-th character # self.prefix(l=1) # peek the next l characters # self.forward(l=1) # read the next l characters and move the pointer. # Had we reached the end of the stream? self.done = False # The number of unclosed '{' and '['. `flow_level == 0` means block # context. self.flow_level = 0 # List of processed tokens that are not yet emitted. self.tokens = [] # Add the STREAM-START token. self.fetch_stream_start() # Number of tokens that were emitted through the `get_token` method. self.tokens_taken = 0 # The current indentation level. self.indent = -1 # Past indentation levels. self.indents = [] # Variables related to simple keys treatment. # A simple key is a key that is not denoted by the '?' indicator. # Example of simple keys: # --- # block simple key: value # ? not a simple key: # : { flow simple key: value } # We emit the KEY token before all keys, so when we find a potential # simple key, we try to locate the corresponding ':' indicator. # Simple keys should be limited to a single line and 1024 characters. # Can a simple key start at the current position? A simple key may # start: # - at the beginning of the line, not counting indentation spaces # (in block context), # - after '{', '[', ',' (in the flow context), # - after '?', ':', '-' (in the block context). # In the block context, this flag also signifies if a block collection # may start at the current position. self.allow_simple_key = True # Keep track of possible simple keys. This is a dictionary. The key # is `flow_level`; there can be no more that one possible simple key # for each level. The value is a SimpleKey record: # (token_number, required, index, line, column, mark) # A simple key may start with ALIAS, ANCHOR, TAG, SCALAR(flow), # '[', or '{' tokens. self.possible_simple_keys = {}
[ "def", "__init__", "(", "self", ")", ":", "# It is assumed that Scanner and Reader will have a common descendant.", "# Reader do the dirty work of checking for BOM and converting the", "# input data to Unicode. It also adds NUL to the end.", "#", "# Reader supports the following methods", "# ...
https://github.com/guillermooo/dart-sublime-bundle/blob/d891fb36c98ca0b111a35cba109b05a16b6c4b83/out_there/yaml/scanner.py#L48-L109