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
cobbler/cobbler
eed8cdca3e970c8aa1d199e80b8c8f19b3f940cc
cobbler/items/system.py
python
NetworkInterface.serialize
(self)
This method is a proxy for :meth:`~cobbler.items.item.Item.to_dict` and contains additional logic for serialization to a persistent location. :return: The dictionary with the information for serialization.
This method is a proxy for :meth:`~cobbler.items.item.Item.to_dict` and contains additional logic for serialization to a persistent location.
[ "This", "method", "is", "a", "proxy", "for", ":", "meth", ":", "~cobbler", ".", "items", ".", "item", ".", "Item", ".", "to_dict", "and", "contains", "additional", "logic", "for", "serialization", "to", "a", "persistent", "location", "." ]
def serialize(self): """ This method is a proxy for :meth:`~cobbler.items.item.Item.to_dict` and contains additional logic for serialization to a persistent location. :return: The dictionary with the information for serialization. """ self.to_dict()
[ "def", "serialize", "(", "self", ")", ":", "self", ".", "to_dict", "(", ")" ]
https://github.com/cobbler/cobbler/blob/eed8cdca3e970c8aa1d199e80b8c8f19b3f940cc/cobbler/items/system.py#L102-L109
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-darwin/x64/mako/runtime.py
python
Namespace.get_cached
(self, key, **kwargs)
return self.cache.get(key, **kwargs)
Return a value from the :class:`.Cache` referenced by this :class:`.Namespace` object's :class:`.Template`. The advantage to this method versus direct access to the :class:`.Cache` is that the configuration parameters declared in ``<%page>`` take effect here, thereby calling up the same configured backend as that configured by ``<%page>``.
Return a value from the :class:`.Cache` referenced by this :class:`.Namespace` object's :class:`.Template`.
[ "Return", "a", "value", "from", "the", ":", "class", ":", ".", "Cache", "referenced", "by", "this", ":", "class", ":", ".", "Namespace", "object", "s", ":", "class", ":", ".", "Template", "." ]
def get_cached(self, key, **kwargs): """Return a value from the :class:`.Cache` referenced by this :class:`.Namespace` object's :class:`.Template`. The advantage to this method versus direct access to the :class:`.Cache` is that the configuration parameters declared in ``<%page>`` take effect here, thereby calling up the same configured backend as that configured by ``<%page>``. """ return self.cache.get(key, **kwargs)
[ "def", "get_cached", "(", "self", ",", "key", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "cache", ".", "get", "(", "key", ",", "*", "*", "kwargs", ")" ]
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-darwin/x64/mako/runtime.py#L491-L503
DeepGraphLearning/GMNN
e8a2232bca60b8b6a43e97a9c5d8121ed83780a1
unsupervised/codes/loader.py
python
Vocab.__init__
(self, file_name, cols, with_padding=False)
[]
def __init__(self, file_name, cols, with_padding=False): self.itos = [] self.stoi = {} self.vocab_size = 0 if with_padding: string = '<pad>' self.stoi[string] = self.vocab_size self.itos.append(string) self.vocab_size += 1 fi = open(file_name, 'r') for line in fi: items = line.strip().split('\t') for col in cols: item = items[col] strings = item.strip().split(' ') for string in strings: string = string.split(':')[0] if string not in self.stoi: self.stoi[string] = self.vocab_size self.itos.append(string) self.vocab_size += 1 fi.close()
[ "def", "__init__", "(", "self", ",", "file_name", ",", "cols", ",", "with_padding", "=", "False", ")", ":", "self", ".", "itos", "=", "[", "]", "self", ".", "stoi", "=", "{", "}", "self", ".", "vocab_size", "=", "0", "if", "with_padding", ":", "str...
https://github.com/DeepGraphLearning/GMNN/blob/e8a2232bca60b8b6a43e97a9c5d8121ed83780a1/unsupervised/codes/loader.py#L10-L33
chrisconlan/algorithmic-trading-with-python
ebe01087c7d9172db72bc3c9adc1eee5e882ac49
listings/chapter_3/3_6_calculate_chaikin_money_flow.py
python
calculate_money_flow_volume
(df: pd.DataFrame, n: int=20)
return calculate_money_flow_volume_series(df).rolling(n).sum()
Calculates money flow volume, or q_t in our formula
Calculates money flow volume, or q_t in our formula
[ "Calculates", "money", "flow", "volume", "or", "q_t", "in", "our", "formula" ]
def calculate_money_flow_volume(df: pd.DataFrame, n: int=20) -> pd.Series: """ Calculates money flow volume, or q_t in our formula """ return calculate_money_flow_volume_series(df).rolling(n).sum()
[ "def", "calculate_money_flow_volume", "(", "df", ":", "pd", ".", "DataFrame", ",", "n", ":", "int", "=", "20", ")", "->", "pd", ".", "Series", ":", "return", "calculate_money_flow_volume_series", "(", "df", ")", ".", "rolling", "(", "n", ")", ".", "sum",...
https://github.com/chrisconlan/algorithmic-trading-with-python/blob/ebe01087c7d9172db72bc3c9adc1eee5e882ac49/listings/chapter_3/3_6_calculate_chaikin_money_flow.py#L9-L13
chadmv/cmt
1b1a9a4fb154d1d10e73373cf899e4d83c95a6a1
scripts/pyparsing/core.py
python
Forward.leaveWhitespace
(self)
return self
[]
def leaveWhitespace(self): self.skipWhitespace = False return self
[ "def", "leaveWhitespace", "(", "self", ")", ":", "self", ".", "skipWhitespace", "=", "False", "return", "self" ]
https://github.com/chadmv/cmt/blob/1b1a9a4fb154d1d10e73373cf899e4d83c95a6a1/scripts/pyparsing/core.py#L4264-L4266
seppius-xbmc-repo/ru
d0879d56ec8243b2c7af44fda5cf3d1ff77fd2e2
plugin.video.online.anidub.com/BeautifulSoup.py
python
PageElement.findAllNext
(self, name=None, attrs={}, text=None, limit=None, **kwargs)
return self._findAll(name, attrs, text, limit, self.nextGenerator, **kwargs)
Returns all items that match the given criteria and appear after this Tag in the document.
Returns all items that match the given criteria and appear after this Tag in the document.
[ "Returns", "all", "items", "that", "match", "the", "given", "criteria", "and", "appear", "after", "this", "Tag", "in", "the", "document", "." ]
def findAllNext(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns all items that match the given criteria and appear after this Tag in the document.""" return self._findAll(name, attrs, text, limit, self.nextGenerator, **kwargs)
[ "def", "findAllNext", "(", "self", ",", "name", "=", "None", ",", "attrs", "=", "{", "}", ",", "text", "=", "None", ",", "limit", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_findAll", "(", "name", ",", "attrs", ",", ...
https://github.com/seppius-xbmc-repo/ru/blob/d0879d56ec8243b2c7af44fda5cf3d1ff77fd2e2/plugin.video.online.anidub.com/BeautifulSoup.py#L257-L262
log2timeline/plaso
fe2e316b8c76a0141760c0f2f181d84acb83abc2
plaso/cli/helpers/hashers.py
python
HashersArgumentsHelper.AddArguments
(cls, argument_group)
Adds command line arguments to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group (argparse._ArgumentGroup|argparse.ArgumentParser): argparse group.
Adds command line arguments to an argument group.
[ "Adds", "command", "line", "arguments", "to", "an", "argument", "group", "." ]
def AddArguments(cls, argument_group): """Adds command line arguments to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group (argparse._ArgumentGroup|argparse.ArgumentParser): argparse group. """ argument_group.add_argument( '--hasher_file_size_limit', '--hasher-file-size-limit', dest='hasher_file_size_limit', type=int, action='store', default=0, metavar='SIZE', help=( 'Define the maximum file size in bytes that hashers should ' 'process. Any larger file will be skipped. A size of 0 represents ' 'no limit.')) argument_group.add_argument( '--hashers', dest='hashers', type=str, action='store', default=cls._DEFAULT_HASHER_STRING, metavar='HASHER_LIST', help=( 'Define a list of hashers to use by the tool. This is a comma ' 'separated list where each entry is the name of a hasher, such as ' '"md5,sha256". "all" indicates that all hashers should be ' 'enabled. "none" disables all hashers. Use "--hashers list" or ' '"--info" to list the available hashers.'))
[ "def", "AddArguments", "(", "cls", ",", "argument_group", ")", ":", "argument_group", ".", "add_argument", "(", "'--hasher_file_size_limit'", ",", "'--hasher-file-size-limit'", ",", "dest", "=", "'hasher_file_size_limit'", ",", "type", "=", "int", ",", "action", "="...
https://github.com/log2timeline/plaso/blob/fe2e316b8c76a0141760c0f2f181d84acb83abc2/plaso/cli/helpers/hashers.py#L19-L44
emmetio/livestyle-sublime-old
c42833c046e9b2f53ebce3df3aa926528f5a33b5
tornado/httpserver.py
python
HTTPRequest.get_ssl_certificate
(self, binary_form=False)
Returns the client's SSL certificate, if any. To use client certificates, the HTTPServer must have been constructed with cert_reqs set in ssl_options, e.g.:: server = HTTPServer(app, ssl_options=dict( certfile="foo.crt", keyfile="foo.key", cert_reqs=ssl.CERT_REQUIRED, ca_certs="cacert.crt")) By default, the return value is a dictionary (or None, if no client certificate is present). If ``binary_form`` is true, a DER-encoded form of the certificate is returned instead. See SSLSocket.getpeercert() in the standard library for more details. http://docs.python.org/library/ssl.html#sslsocket-objects
Returns the client's SSL certificate, if any.
[ "Returns", "the", "client", "s", "SSL", "certificate", "if", "any", "." ]
def get_ssl_certificate(self, binary_form=False): """Returns the client's SSL certificate, if any. To use client certificates, the HTTPServer must have been constructed with cert_reqs set in ssl_options, e.g.:: server = HTTPServer(app, ssl_options=dict( certfile="foo.crt", keyfile="foo.key", cert_reqs=ssl.CERT_REQUIRED, ca_certs="cacert.crt")) By default, the return value is a dictionary (or None, if no client certificate is present). If ``binary_form`` is true, a DER-encoded form of the certificate is returned instead. See SSLSocket.getpeercert() in the standard library for more details. http://docs.python.org/library/ssl.html#sslsocket-objects """ try: return self.connection.stream.socket.getpeercert( binary_form=binary_form) except ssl.SSLError: return None
[ "def", "get_ssl_certificate", "(", "self", ",", "binary_form", "=", "False", ")", ":", "try", ":", "return", "self", ".", "connection", ".", "stream", ".", "socket", ".", "getpeercert", "(", "binary_form", "=", "binary_form", ")", "except", "ssl", ".", "SS...
https://github.com/emmetio/livestyle-sublime-old/blob/c42833c046e9b2f53ebce3df3aa926528f5a33b5/tornado/httpserver.py#L499-L523
r9y9/deepvoice3_pytorch
a5c24624bad314db5a5dcb0ea320fc3623a94f15
synthesis.py
python
tts
(model, text, p=0, speaker_id=None, fast=False)
return waveform, alignment, spectrogram, mel
Convert text to speech waveform given a deepvoice3 model. Args: text (str) : Input text to be synthesized p (float) : Replace word to pronounciation if p > 0. Default is 0.
Convert text to speech waveform given a deepvoice3 model.
[ "Convert", "text", "to", "speech", "waveform", "given", "a", "deepvoice3", "model", "." ]
def tts(model, text, p=0, speaker_id=None, fast=False): """Convert text to speech waveform given a deepvoice3 model. Args: text (str) : Input text to be synthesized p (float) : Replace word to pronounciation if p > 0. Default is 0. """ model = model.to(device) model.eval() if fast: model.make_generation_fast_() sequence = np.array(_frontend.text_to_sequence(text, p=p)) sequence = torch.from_numpy(sequence).unsqueeze(0).long().to(device) text_positions = torch.arange(1, sequence.size(-1) + 1).unsqueeze(0).long().to(device) speaker_ids = None if speaker_id is None else torch.LongTensor([speaker_id]).to(device) # Greedy decoding with torch.no_grad(): mel_outputs, linear_outputs, alignments, done = model( sequence, text_positions=text_positions, speaker_ids=speaker_ids) linear_output = linear_outputs[0].cpu().data.numpy() spectrogram = audio._denormalize(linear_output) alignment = alignments[0].cpu().data.numpy() mel = mel_outputs[0].cpu().data.numpy() mel = audio._denormalize(mel) # Predicted audio signal waveform = audio.inv_spectrogram(linear_output.T) return waveform, alignment, spectrogram, mel
[ "def", "tts", "(", "model", ",", "text", ",", "p", "=", "0", ",", "speaker_id", "=", "None", ",", "fast", "=", "False", ")", ":", "model", "=", "model", ".", "to", "(", "device", ")", "model", ".", "eval", "(", ")", "if", "fast", ":", "model", ...
https://github.com/r9y9/deepvoice3_pytorch/blob/a5c24624bad314db5a5dcb0ea320fc3623a94f15/synthesis.py#L42-L73
jython/frozen-mirror
b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99
lib-python/2.7/ntpath.py
python
relpath
(path, start=curdir)
return join(*rel_list)
Return a relative version of a path
Return a relative version of a path
[ "Return", "a", "relative", "version", "of", "a", "path" ]
def relpath(path, start=curdir): """Return a relative version of a path""" if not path: raise ValueError("no path specified") start_is_unc, start_prefix, start_list = _abspath_split(start) path_is_unc, path_prefix, path_list = _abspath_split(path) if path_is_unc ^ start_is_unc: raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)" % (path, start)) if path_prefix.lower() != start_prefix.lower(): if path_is_unc: raise ValueError("path is on UNC root %s, start on UNC root %s" % (path_prefix, start_prefix)) else: raise ValueError("path is on drive %s, start on drive %s" % (path_prefix, start_prefix)) # Work out how much of the filepath is shared by start and path. i = 0 for e1, e2 in zip(start_list, path_list): if e1.lower() != e2.lower(): break i += 1 rel_list = [pardir] * (len(start_list)-i) + path_list[i:] if not rel_list: return curdir return join(*rel_list)
[ "def", "relpath", "(", "path", ",", "start", "=", "curdir", ")", ":", "if", "not", "path", ":", "raise", "ValueError", "(", "\"no path specified\"", ")", "start_is_unc", ",", "start_prefix", ",", "start_list", "=", "_abspath_split", "(", "start", ")", "path_...
https://github.com/jython/frozen-mirror/blob/b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99/lib-python/2.7/ntpath.py#L494-L523
mysql/mysql-connector-python
c5460bcbb0dff8e4e48bf4af7a971c89bf486d85
lib/mysql/connector/utils.py
python
intread
(buf)
Unpacks the given buffer to an integer
Unpacks the given buffer to an integer
[ "Unpacks", "the", "given", "buffer", "to", "an", "integer" ]
def intread(buf): """Unpacks the given buffer to an integer""" try: if isinstance(buf, int): return buf length = len(buf) if length == 1: return buf[0] elif length <= 4: tmp = buf + b'\x00'*(4-length) return struct.unpack('<I', tmp)[0] tmp = buf + b'\x00'*(8-length) return struct.unpack('<Q', tmp)[0] except: raise
[ "def", "intread", "(", "buf", ")", ":", "try", ":", "if", "isinstance", "(", "buf", ",", "int", ")", ":", "return", "buf", "length", "=", "len", "(", "buf", ")", "if", "length", "==", "1", ":", "return", "buf", "[", "0", "]", "elif", "length", ...
https://github.com/mysql/mysql-connector-python/blob/c5460bcbb0dff8e4e48bf4af7a971c89bf486d85/lib/mysql/connector/utils.py#L54-L68
appknox/AFE
bc9c909ea306506985b00f27ca17b1df5d1a92cc
internals/urlgrabber/grabber.py
python
URLGrabberOptions.derive
(self, **kwargs)
return URLGrabberOptions(delegate=self, **kwargs)
Create a derived URLGrabberOptions instance. This method creates a new instance and overrides the options specified in kwargs.
Create a derived URLGrabberOptions instance. This method creates a new instance and overrides the options specified in kwargs.
[ "Create", "a", "derived", "URLGrabberOptions", "instance", ".", "This", "method", "creates", "a", "new", "instance", "and", "overrides", "the", "options", "specified", "in", "kwargs", "." ]
def derive(self, **kwargs): """Create a derived URLGrabberOptions instance. This method creates a new instance and overrides the options specified in kwargs. """ return URLGrabberOptions(delegate=self, **kwargs)
[ "def", "derive", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "URLGrabberOptions", "(", "delegate", "=", "self", ",", "*", "*", "kwargs", ")" ]
https://github.com/appknox/AFE/blob/bc9c909ea306506985b00f27ca17b1df5d1a92cc/internals/urlgrabber/grabber.py#L771-L776
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/sympy/solvers/diophantine.py
python
gaussian_reduce
(w, a, b)
return c[0]*w + b*c[1], c[0]
r""" Returns a reduced solution `(x, z)` to the congruence `X^2 - aZ^2 \equiv 0 \ (mod \ b)` so that `x^2 + |a|z^2` is minimal. Details ======= Here ``w`` is a solution of the congruence `x^2 \equiv a \ (mod \ b)` References ========== .. [1] Gaussian lattice Reduction [online]. Available: http://home.ie.cuhk.edu.hk/~wkshum/wordpress/?p=404 .. [2] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin, Mathematics of Computation, Volume 00, Number 0.
r""" Returns a reduced solution `(x, z)` to the congruence `X^2 - aZ^2 \equiv 0 \ (mod \ b)` so that `x^2 + |a|z^2` is minimal.
[ "r", "Returns", "a", "reduced", "solution", "(", "x", "z", ")", "to", "the", "congruence", "X^2", "-", "aZ^2", "\\", "equiv", "0", "\\", "(", "mod", "\\", "b", ")", "so", "that", "x^2", "+", "|a|z^2", "is", "minimal", "." ]
def gaussian_reduce(w, a, b): r""" Returns a reduced solution `(x, z)` to the congruence `X^2 - aZ^2 \equiv 0 \ (mod \ b)` so that `x^2 + |a|z^2` is minimal. Details ======= Here ``w`` is a solution of the congruence `x^2 \equiv a \ (mod \ b)` References ========== .. [1] Gaussian lattice Reduction [online]. Available: http://home.ie.cuhk.edu.hk/~wkshum/wordpress/?p=404 .. [2] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin, Mathematics of Computation, Volume 00, Number 0. """ u = (0, 1) v = (1, 0) if dot(u, v, w, a, b) < 0: v = (-v[0], -v[1]) if norm(u, w, a, b) < norm(v, w, a, b): u, v = v, u while norm(u, w, a, b) > norm(v, w, a, b): k = dot(u, v, w, a, b) // dot(v, v, w, a, b) u, v = v, (u[0]- k*v[0], u[1]- k*v[1]) u, v = v, u if dot(u, v, w, a, b) < dot(v, v, w, a, b)/2 or norm((u[0]-v[0], u[1]-v[1]), w, a, b) > norm(v, w, a, b): c = v else: c = (u[0] - v[0], u[1] - v[1]) return c[0]*w + b*c[1], c[0]
[ "def", "gaussian_reduce", "(", "w", ",", "a", ",", "b", ")", ":", "u", "=", "(", "0", ",", "1", ")", "v", "=", "(", "1", ",", "0", ")", "if", "dot", "(", "u", ",", "v", ",", "w", ",", "a", ",", "b", ")", "<", "0", ":", "v", "=", "("...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/solvers/diophantine.py#L2584-L2622
joxeankoret/nightmare
11b22bb7c346611de90f479ee781c9228af453ea
lib/interfaces/vtrace/__init__.py
python
Trace.resumeThread
(self, threadid)
Resume a suspended thread.
Resume a suspended thread.
[ "Resume", "a", "suspended", "thread", "." ]
def resumeThread(self, threadid): """ Resume a suspended thread. """ self.requireNotRunning() if not self.sus_threads.get(threadid): raise Exception("The specified thread is not suspended") self.platformResumeThread(threadid) self.sus_threads.pop(threadid)
[ "def", "resumeThread", "(", "self", ",", "threadid", ")", ":", "self", ".", "requireNotRunning", "(", ")", "if", "not", "self", ".", "sus_threads", ".", "get", "(", "threadid", ")", ":", "raise", "Exception", "(", "\"The specified thread is not suspended\"", "...
https://github.com/joxeankoret/nightmare/blob/11b22bb7c346611de90f479ee781c9228af453ea/lib/interfaces/vtrace/__init__.py#L934-L942
IronLanguages/ironpython2
51fdedeeda15727717fb8268a805f71b06c0b9f1
Src/StdLib/Lib/decimal.py
python
_decimal_lshift_exact
(n, e)
Given integers n and e, return n * 10**e if it's an integer, else None. The computation is designed to avoid computing large powers of 10 unnecessarily. >>> _decimal_lshift_exact(3, 4) 30000 >>> _decimal_lshift_exact(300, -999999999) # returns None
Given integers n and e, return n * 10**e if it's an integer, else None.
[ "Given", "integers", "n", "and", "e", "return", "n", "*", "10", "**", "e", "if", "it", "s", "an", "integer", "else", "None", "." ]
def _decimal_lshift_exact(n, e): """ Given integers n and e, return n * 10**e if it's an integer, else None. The computation is designed to avoid computing large powers of 10 unnecessarily. >>> _decimal_lshift_exact(3, 4) 30000 >>> _decimal_lshift_exact(300, -999999999) # returns None """ if n == 0: return 0 elif e >= 0: return n * 10**e else: # val_n = largest power of 10 dividing n. str_n = str(abs(n)) val_n = len(str_n) - len(str_n.rstrip('0')) return None if val_n < -e else n // 10**-e
[ "def", "_decimal_lshift_exact", "(", "n", ",", "e", ")", ":", "if", "n", "==", "0", ":", "return", "0", "elif", "e", ">=", "0", ":", "return", "n", "*", "10", "**", "e", "else", ":", "# val_n = largest power of 10 dividing n.", "str_n", "=", "str", "("...
https://github.com/IronLanguages/ironpython2/blob/51fdedeeda15727717fb8268a805f71b06c0b9f1/Src/StdLib/Lib/decimal.py#L5520-L5539
AlexanderParkin/ChaLearn_liveness_challenge
6dc26c1bd68beb6bd6e3d24107ee2d9557dcb9a3
attributes_trainer/trainer.py
python
Model.calculate_metrics
(self, output, target)
return batch_result
Calculates test metrix for given batch and its input
Calculates test metrix for given batch and its input
[ "Calculates", "test", "metrix", "for", "given", "batch", "and", "its", "input" ]
def calculate_metrics(self, output, target): """ Calculates test metrix for given batch and its input """ batch_result = None t = target o = output if self.opt.loss_type == 'bce': binary_accuracy = (t.byte()==(o>0.5)).float().mean(0).cpu().numpy() batch_result = binary_accuracy elif self.opt.loss_type =='mse': mean_average_error = torch.abs(t-o.squeeze()).mean(0).cpu().numpy() batch_result = mean_average_error elif self.opt.loss_type == 'cce' or self.opt.loss_type == 'arc_margin': top1_accuracy = (torch.argmax(o, 1)==t).float().mean().item() batch_result = top1_accuracy else: raise Exception('This loss function is not implemented yet') return batch_result
[ "def", "calculate_metrics", "(", "self", ",", "output", ",", "target", ")", ":", "batch_result", "=", "None", "t", "=", "target", "o", "=", "output", "if", "self", ".", "opt", ".", "loss_type", "==", "'bce'", ":", "binary_accuracy", "=", "(", "t", ".",...
https://github.com/AlexanderParkin/ChaLearn_liveness_challenge/blob/6dc26c1bd68beb6bd6e3d24107ee2d9557dcb9a3/attributes_trainer/trainer.py#L198-L219
Asana/python-asana
9b54ab99423208bd6aa87dbfaa628c069430b127
asana/resources/stories.py
python
Stories.create_on_task
(self, task, params={}, **options)
return self.client.post(path, params, **options)
Adds a comment to a task. The comment will be authored by the currently authenticated user, and timestamped when the server receives the request. Returns the full record for the new story added to the task. Parameters ---------- task : {Id} Globally unique identifier for the task. [data] : {Object} Data for the request - text : {String} The plain text of the comment to add.
Adds a comment to a task. The comment will be authored by the currently authenticated user, and timestamped when the server receives the request.
[ "Adds", "a", "comment", "to", "a", "task", ".", "The", "comment", "will", "be", "authored", "by", "the", "currently", "authenticated", "user", "and", "timestamped", "when", "the", "server", "receives", "the", "request", "." ]
def create_on_task(self, task, params={}, **options): """Adds a comment to a task. The comment will be authored by the currently authenticated user, and timestamped when the server receives the request. Returns the full record for the new story added to the task. Parameters ---------- task : {Id} Globally unique identifier for the task. [data] : {Object} Data for the request - text : {String} The plain text of the comment to add. """ path = "/tasks/%s/stories" % (task) return self.client.post(path, params, **options)
[ "def", "create_on_task", "(", "self", ",", "task", ",", "params", "=", "{", "}", ",", "*", "*", "options", ")", ":", "path", "=", "\"/tasks/%s/stories\"", "%", "(", "task", ")", "return", "self", ".", "client", ".", "post", "(", "path", ",", "params"...
https://github.com/Asana/python-asana/blob/9b54ab99423208bd6aa87dbfaa628c069430b127/asana/resources/stories.py#L28-L42
Ha0Tang/SelectionGAN
80aa7ad9f79f643c28633c40c621f208f3fb0121
semantic_synthesis/util/html.py
python
HTML.get_image_dir
(self)
return self.img_dir
[]
def get_image_dir(self): return self.img_dir
[ "def", "get_image_dir", "(", "self", ")", ":", "return", "self", ".", "img_dir" ]
https://github.com/Ha0Tang/SelectionGAN/blob/80aa7ad9f79f643c28633c40c621f208f3fb0121/semantic_synthesis/util/html.py#L34-L35
snowflakedb/snowflake-connector-python
1659ec6b78930d1f947b4eff985c891af614d86c
src/snowflake/connector/auth_okta.py
python
_is_prefix_equal
(url1, url2)
return ( parsed_url1.hostname == parsed_url2.hostname and port1 == port2 and parsed_url1.scheme == parsed_url2.scheme )
Checks if URL prefixes are identical. The scheme, hostname and port number are compared. If the port number is not specified and the scheme is https, the port number is assumed to be 443.
Checks if URL prefixes are identical.
[ "Checks", "if", "URL", "prefixes", "are", "identical", "." ]
def _is_prefix_equal(url1, url2): """Checks if URL prefixes are identical. The scheme, hostname and port number are compared. If the port number is not specified and the scheme is https, the port number is assumed to be 443. """ parsed_url1 = urlsplit(url1) parsed_url2 = urlsplit(url2) port1 = parsed_url1.port if not port1 and parsed_url1.scheme == "https": port1 = "443" port2 = parsed_url1.port if not port2 and parsed_url2.scheme == "https": port2 = "443" return ( parsed_url1.hostname == parsed_url2.hostname and port1 == port2 and parsed_url1.scheme == parsed_url2.scheme )
[ "def", "_is_prefix_equal", "(", "url1", ",", "url2", ")", ":", "parsed_url1", "=", "urlsplit", "(", "url1", ")", "parsed_url2", "=", "urlsplit", "(", "url2", ")", "port1", "=", "parsed_url1", ".", "port", "if", "not", "port1", "and", "parsed_url1", ".", ...
https://github.com/snowflakedb/snowflake-connector-python/blob/1659ec6b78930d1f947b4eff985c891af614d86c/src/snowflake/connector/auth_okta.py#L27-L47
jgyates/genmon
2cb2ed2945f55cd8c259b09ccfa9a51e23f1341e
genmonlib/generac_evolution.py
python
Evolution.WriteIndexedRegister
(self, register, value)
[]
def WriteIndexedRegister(self, register, value): try: with self.ModBus.CommAccessLock: # LowByte = value & 0x00FF HighByte = value >> 8 Data= [] Data.append(HighByte) # Value for indexed register (High byte) Data.append(LowByte) # Value for indexed register (Low byte) self.ModBus.ProcessWriteTransaction("0004", len(Data) / 2, Data) LowByte = register & 0x00FF HighByte = register >> 8 Data= [] Data.append(HighByte) # indexed register to be written (High byte) Data.append(LowByte) # indexed register to be written (Low byte) self.ModBus.ProcessWriteTransaction("0003", len(Data) / 2, Data) except Exception as e1: self.LogErrorLine("Error in WriteIndexedRegister: " + str(e1))
[ "def", "WriteIndexedRegister", "(", "self", ",", "register", ",", "value", ")", ":", "try", ":", "with", "self", ".", "ModBus", ".", "CommAccessLock", ":", "#", "LowByte", "=", "value", "&", "0x00FF", "HighByte", "=", "value", ">>", "8", "Data", "=", "...
https://github.com/jgyates/genmon/blob/2cb2ed2945f55cd8c259b09ccfa9a51e23f1341e/genmonlib/generac_evolution.py#L1168-L1189
exaile/exaile
a7b58996c5c15b3aa7b9975ac13ee8f784ef4689
xlgui/cover.py
python
CoverWidget.do_expose_event
(self, event)
Paints alpha transparency
Paints alpha transparency
[ "Paints", "alpha", "transparency" ]
def do_expose_event(self, event): """ Paints alpha transparency """ opacity = 1 - settings.get_option('gui/transparency', 0.3) context = self.props.window.cairo_create() background = self.style.bg[Gtk.StateType.NORMAL] context.set_source_rgba( float(background.red) / 256 ** 2, float(background.green) / 256 ** 2, float(background.blue) / 256 ** 2, opacity, ) context.set_operator(cairo.OPERATOR_SOURCE) context.paint() Gtk.EventBox.do_expose_event(self, event)
[ "def", "do_expose_event", "(", "self", ",", "event", ")", ":", "opacity", "=", "1", "-", "settings", ".", "get_option", "(", "'gui/transparency'", ",", "0.3", ")", "context", "=", "self", ".", "props", ".", "window", ".", "cairo_create", "(", ")", "backg...
https://github.com/exaile/exaile/blob/a7b58996c5c15b3aa7b9975ac13ee8f784ef4689/xlgui/cover.py#L675-L691
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/sqlalchemy/sql/util.py
python
ColumnAdapter.wrap
(self, adapter)
return ac
[]
def wrap(self, adapter): ac = self.__class__.__new__(self.__class__) ac.__dict__.update(self.__dict__) ac._wrap = adapter ac.columns = util.populate_column_dict(ac._locate_col) if ac.include_fn or ac.exclude_fn: ac.columns = self._IncludeExcludeMapping(ac, ac.columns) return ac
[ "def", "wrap", "(", "self", ",", "adapter", ")", ":", "ac", "=", "self", ".", "__class__", ".", "__new__", "(", "self", ".", "__class__", ")", "ac", ".", "__dict__", ".", "update", "(", "self", ".", "__dict__", ")", "ac", ".", "_wrap", "=", "adapte...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/sqlalchemy/sql/util.py#L727-L735
conjure-up/conjure-up
d2bf8ab8e71ff01321d0e691a8d3e3833a047678
conjureup/controllers/juju/credentials/tui.py
python
CredentialsController.render
(self)
[]
def render(self): self.load_credentials() if app.provider.cloud_type == cloud_types.LOCAL: # no credentials required for localhost self.finish() elif not self.credentials: utils.warning("You attempted to do an install against a cloud " "that requires credentials that could not be " "found. If you wish to supply those " "credentials please run " "`juju add-credential " "{}`.".format(app.provider.cloud)) events.Shutdown.set(1) elif not app.provider.credential: utils.warning("You attempted to install against a cloud with " "multiple credentials and no default credentials " "set. Please set a default credential with:\n" "\n" " juju set-default-credential {} <credential>") events.Shutdown.set(1) else: self.finish()
[ "def", "render", "(", "self", ")", ":", "self", ".", "load_credentials", "(", ")", "if", "app", ".", "provider", ".", "cloud_type", "==", "cloud_types", ".", "LOCAL", ":", "# no credentials required for localhost", "self", ".", "finish", "(", ")", "elif", "n...
https://github.com/conjure-up/conjure-up/blob/d2bf8ab8e71ff01321d0e691a8d3e3833a047678/conjureup/controllers/juju/credentials/tui.py#L9-L30
menpo/menpo
a61500656c4fc2eea82497684f13cc31a605550b
menpo/shape/labelled.py
python
LabelledPointUndirectedGraph._view_2d
( self, with_labels=None, without_labels=None, group="group", figure_id=None, new_figure=False, image_view=True, render_lines=True, line_colour=None, line_style="-", line_width=1, render_markers=True, marker_style="o", marker_size=5, marker_face_colour=None, marker_edge_colour=None, marker_edge_width=1.0, render_numbering=False, numbers_horizontal_align="center", numbers_vertical_align="bottom", numbers_font_name="sans-serif", numbers_font_size=10, numbers_font_style="normal", numbers_font_weight="normal", numbers_font_colour="k", render_legend=True, legend_title="", legend_font_name="sans-serif", legend_font_style="normal", legend_font_size=10, legend_font_weight="normal", legend_marker_scale=None, legend_location=2, legend_bbox_to_anchor=(1.05, 1.0), legend_border_axes_pad=None, legend_n_columns=1, legend_horizontal_spacing=None, legend_vertical_spacing=None, legend_border=True, legend_border_padding=None, legend_shadow=False, legend_rounded_corners=False, render_axes=True, axes_font_name="sans-serif", axes_font_size=10, axes_font_style="normal", axes_font_weight="normal", axes_x_limits=None, axes_y_limits=None, axes_x_ticks=None, axes_y_ticks=None, figure_size=(10, 8), )
return landmark_viewer.render( image_view=image_view, render_lines=render_lines, line_colour=line_colour, line_style=line_style, line_width=line_width, render_markers=render_markers, marker_style=marker_style, marker_size=marker_size, marker_face_colour=marker_face_colour, marker_edge_colour=marker_edge_colour, marker_edge_width=marker_edge_width, render_numbering=render_numbering, numbers_horizontal_align=numbers_horizontal_align, numbers_vertical_align=numbers_vertical_align, numbers_font_name=numbers_font_name, numbers_font_size=numbers_font_size, numbers_font_style=numbers_font_style, numbers_font_weight=numbers_font_weight, numbers_font_colour=numbers_font_colour, render_legend=render_legend, legend_title=legend_title, legend_font_name=legend_font_name, legend_font_style=legend_font_style, legend_font_size=legend_font_size, legend_font_weight=legend_font_weight, legend_marker_scale=legend_marker_scale, legend_location=legend_location, legend_bbox_to_anchor=legend_bbox_to_anchor, legend_border_axes_pad=legend_border_axes_pad, legend_n_columns=legend_n_columns, legend_horizontal_spacing=legend_horizontal_spacing, legend_vertical_spacing=legend_vertical_spacing, legend_border=legend_border, legend_border_padding=legend_border_padding, legend_shadow=legend_shadow, legend_rounded_corners=legend_rounded_corners, render_axes=render_axes, axes_font_name=axes_font_name, axes_font_size=axes_font_size, axes_font_style=axes_font_style, axes_font_weight=axes_font_weight, axes_x_limits=axes_x_limits, axes_y_limits=axes_y_limits, axes_x_ticks=axes_x_ticks, axes_y_ticks=axes_y_ticks, figure_size=figure_size, )
Visualize the labelled point undirected graph. Parameters ---------- with_labels : ``None`` or `str` or `list` of `str`, optional If not ``None``, only show the given label(s). Should **not** be used with the ``without_labels`` kwarg. without_labels : ``None`` or `str` or `list` of `str`, optional If not ``None``, show all except the given label(s). Should **not** be used with the ``with_labels`` kwarg. group : `str` or `None`, optional The name of the labelled point undirected graph. It is used in the legend. figure_id : `object`, optional The id of the figure to be used. new_figure : `bool`, optional If ``True``, a new figure is created. image_view : `bool`, optional If ``True``, the x and y axes are flipped. render_lines : `bool`, optional If ``True``, the edges will be rendered. line_colour : See Below, optional The colour of the lines. Example options:: {r, g, b, c, m, k, w} or (3, ) ndarray It can either be one of the above or a `list` of those defining a value per label. line_style : ``{'-', '--', '-.', ':'}``, optional The style of the lines. line_width : `float`, optional The width of the lines. render_markers : `bool`, optional If ``True``, the markers will be rendered. marker_style : See Below, optional The style of the markers. Example options :: {., ,, o, v, ^, <, >, +, x, D, d, s, p, *, h, H, 1, 2, 3, 4, 8} marker_size : `int`, optional The size of the markers in points. marker_face_colour : See Below, optional The face (filling) colour of the markers. Example options :: {r, g, b, c, m, k, w} or (3, ) ndarray It can either be one of the above or a `list` of those defining a value per label. marker_edge_colour : See Below, optional The edge colour of the markers. Example options :: {r, g, b, c, m, k, w} or (3, ) ndarray It can either be one of the above or a `list` of those defining a value per label. marker_edge_width : `float`, optional The width of the markers' edge. render_numbering : `bool`, optional If ``True``, the landmarks will be numbered. numbers_horizontal_align : ``{center, right, left}``, optional The horizontal alignment of the numbers' texts. numbers_vertical_align : ``{center, top, bottom, baseline}``, optional The vertical alignment of the numbers' texts. numbers_font_name : See Below, optional The font of the numbers. Example options :: {serif, sans-serif, cursive, fantasy, monospace} numbers_font_size : `int`, optional The font size of the numbers. numbers_font_style : ``{normal, italic, oblique}``, optional The font style of the numbers. numbers_font_weight : See Below, optional The font weight of the numbers. Example options :: {ultralight, light, normal, regular, book, medium, roman, semibold, demibold, demi, bold, heavy, extra bold, black} numbers_font_colour : See Below, optional The font colour of the numbers. Example options :: {r, g, b, c, m, k, w} or (3, ) ndarray render_legend : `bool`, optional If ``True``, the legend will be rendered. legend_title : `str`, optional The title of the legend. legend_font_name : See Below, optional The font of the legend. Possible options :: {serif, sans-serif, cursive, fantasy, monospace} legend_font_style : {``normal``, ``italic``, ``oblique``}, optional The font style of the legend. legend_font_size : `int`, optional The font size of the legend. legend_font_weight : See Below, optional The font weight of the legend. Possible options :: {ultralight, light, normal, regular, book, medium, roman, semibold, demibold, demi, bold, heavy, extra bold, black} legend_marker_scale : `float`, optional The relative size of the legend markers with respect to the original legend_location : `int`, optional The location of the legend. The predefined values are: =============== === 'best' 0 'upper right' 1 'upper left' 2 'lower left' 3 'lower right' 4 'right' 5 'center left' 6 'center right' 7 'lower center' 8 'upper center' 9 'center' 10 =============== === legend_bbox_to_anchor : (`float`, `float`), optional The bbox that the legend will be anchored. legend_border_axes_pad : `float`, optional The pad between the axes and legend border. legend_n_columns : `int`, optional The number of the legend's columns. legend_horizontal_spacing : `float`, optional The spacing between the columns. legend_vertical_spacing : `float`, optional The vertical space between the legend entries. legend_border : `bool`, optional If ``True``, a frame will be drawn around the legend. legend_border_padding : `float`, optional The fractional whitespace inside the legend border. legend_shadow : `bool`, optional If ``True``, a shadow will be drawn behind legend. legend_rounded_corners : `bool`, optional If ``True``, the frame's corners will be rounded (fancybox). render_axes : `bool`, optional If ``True``, the axes will be rendered. axes_font_name : See Below, optional The font of the axes. Example options :: {serif, sans-serif, cursive, fantasy, monospace} axes_font_size : `int`, optional The font size of the axes. axes_font_style : {``normal``, ``italic``, ``oblique``}, optional The font style of the axes. axes_font_weight : See Below, optional The font weight of the axes. Example options :: {ultralight, light, normal, regular, book, medium, roman, semibold, demibold, demi, bold, heavy, extra bold, black} axes_x_limits : `float` or (`float`, `float`) or ``None``, optional The limits of the x axis. If `float`, then it sets padding on the right and left of the LabelledPointUndirectedGraph as a percentage of the LabelledPointUndirectedGraph's width. If `tuple` or `list`, then it defines the axis limits. If ``None``, then the limits are set automatically. axes_y_limits : (`float`, `float`) `tuple` or ``None``, optional The limits of the y axis. If `float`, then it sets padding on the top and bottom of the LabelledPointUndirectedGraph as a percentage of the LabelledPointUndirectedGraph's height. If `tuple` or `list`, then it defines the axis limits. If ``None``, then the limits are set automatically. axes_x_ticks : `list` or `tuple` or ``None``, optional The ticks of the x axis. axes_y_ticks : `list` or `tuple` or ``None``, optional The ticks of the y axis. figure_size : (`float`, `float`) or `None`, optional The size of the figure in inches. Raises ------ ValueError If both ``with_labels`` and ``without_labels`` are passed.
Visualize the labelled point undirected graph.
[ "Visualize", "the", "labelled", "point", "undirected", "graph", "." ]
def _view_2d( self, with_labels=None, without_labels=None, group="group", figure_id=None, new_figure=False, image_view=True, render_lines=True, line_colour=None, line_style="-", line_width=1, render_markers=True, marker_style="o", marker_size=5, marker_face_colour=None, marker_edge_colour=None, marker_edge_width=1.0, render_numbering=False, numbers_horizontal_align="center", numbers_vertical_align="bottom", numbers_font_name="sans-serif", numbers_font_size=10, numbers_font_style="normal", numbers_font_weight="normal", numbers_font_colour="k", render_legend=True, legend_title="", legend_font_name="sans-serif", legend_font_style="normal", legend_font_size=10, legend_font_weight="normal", legend_marker_scale=None, legend_location=2, legend_bbox_to_anchor=(1.05, 1.0), legend_border_axes_pad=None, legend_n_columns=1, legend_horizontal_spacing=None, legend_vertical_spacing=None, legend_border=True, legend_border_padding=None, legend_shadow=False, legend_rounded_corners=False, render_axes=True, axes_font_name="sans-serif", axes_font_size=10, axes_font_style="normal", axes_font_weight="normal", axes_x_limits=None, axes_y_limits=None, axes_x_ticks=None, axes_y_ticks=None, figure_size=(10, 8), ): """ Visualize the labelled point undirected graph. Parameters ---------- with_labels : ``None`` or `str` or `list` of `str`, optional If not ``None``, only show the given label(s). Should **not** be used with the ``without_labels`` kwarg. without_labels : ``None`` or `str` or `list` of `str`, optional If not ``None``, show all except the given label(s). Should **not** be used with the ``with_labels`` kwarg. group : `str` or `None`, optional The name of the labelled point undirected graph. It is used in the legend. figure_id : `object`, optional The id of the figure to be used. new_figure : `bool`, optional If ``True``, a new figure is created. image_view : `bool`, optional If ``True``, the x and y axes are flipped. render_lines : `bool`, optional If ``True``, the edges will be rendered. line_colour : See Below, optional The colour of the lines. Example options:: {r, g, b, c, m, k, w} or (3, ) ndarray It can either be one of the above or a `list` of those defining a value per label. line_style : ``{'-', '--', '-.', ':'}``, optional The style of the lines. line_width : `float`, optional The width of the lines. render_markers : `bool`, optional If ``True``, the markers will be rendered. marker_style : See Below, optional The style of the markers. Example options :: {., ,, o, v, ^, <, >, +, x, D, d, s, p, *, h, H, 1, 2, 3, 4, 8} marker_size : `int`, optional The size of the markers in points. marker_face_colour : See Below, optional The face (filling) colour of the markers. Example options :: {r, g, b, c, m, k, w} or (3, ) ndarray It can either be one of the above or a `list` of those defining a value per label. marker_edge_colour : See Below, optional The edge colour of the markers. Example options :: {r, g, b, c, m, k, w} or (3, ) ndarray It can either be one of the above or a `list` of those defining a value per label. marker_edge_width : `float`, optional The width of the markers' edge. render_numbering : `bool`, optional If ``True``, the landmarks will be numbered. numbers_horizontal_align : ``{center, right, left}``, optional The horizontal alignment of the numbers' texts. numbers_vertical_align : ``{center, top, bottom, baseline}``, optional The vertical alignment of the numbers' texts. numbers_font_name : See Below, optional The font of the numbers. Example options :: {serif, sans-serif, cursive, fantasy, monospace} numbers_font_size : `int`, optional The font size of the numbers. numbers_font_style : ``{normal, italic, oblique}``, optional The font style of the numbers. numbers_font_weight : See Below, optional The font weight of the numbers. Example options :: {ultralight, light, normal, regular, book, medium, roman, semibold, demibold, demi, bold, heavy, extra bold, black} numbers_font_colour : See Below, optional The font colour of the numbers. Example options :: {r, g, b, c, m, k, w} or (3, ) ndarray render_legend : `bool`, optional If ``True``, the legend will be rendered. legend_title : `str`, optional The title of the legend. legend_font_name : See Below, optional The font of the legend. Possible options :: {serif, sans-serif, cursive, fantasy, monospace} legend_font_style : {``normal``, ``italic``, ``oblique``}, optional The font style of the legend. legend_font_size : `int`, optional The font size of the legend. legend_font_weight : See Below, optional The font weight of the legend. Possible options :: {ultralight, light, normal, regular, book, medium, roman, semibold, demibold, demi, bold, heavy, extra bold, black} legend_marker_scale : `float`, optional The relative size of the legend markers with respect to the original legend_location : `int`, optional The location of the legend. The predefined values are: =============== === 'best' 0 'upper right' 1 'upper left' 2 'lower left' 3 'lower right' 4 'right' 5 'center left' 6 'center right' 7 'lower center' 8 'upper center' 9 'center' 10 =============== === legend_bbox_to_anchor : (`float`, `float`), optional The bbox that the legend will be anchored. legend_border_axes_pad : `float`, optional The pad between the axes and legend border. legend_n_columns : `int`, optional The number of the legend's columns. legend_horizontal_spacing : `float`, optional The spacing between the columns. legend_vertical_spacing : `float`, optional The vertical space between the legend entries. legend_border : `bool`, optional If ``True``, a frame will be drawn around the legend. legend_border_padding : `float`, optional The fractional whitespace inside the legend border. legend_shadow : `bool`, optional If ``True``, a shadow will be drawn behind legend. legend_rounded_corners : `bool`, optional If ``True``, the frame's corners will be rounded (fancybox). render_axes : `bool`, optional If ``True``, the axes will be rendered. axes_font_name : See Below, optional The font of the axes. Example options :: {serif, sans-serif, cursive, fantasy, monospace} axes_font_size : `int`, optional The font size of the axes. axes_font_style : {``normal``, ``italic``, ``oblique``}, optional The font style of the axes. axes_font_weight : See Below, optional The font weight of the axes. Example options :: {ultralight, light, normal, regular, book, medium, roman, semibold, demibold, demi, bold, heavy, extra bold, black} axes_x_limits : `float` or (`float`, `float`) or ``None``, optional The limits of the x axis. If `float`, then it sets padding on the right and left of the LabelledPointUndirectedGraph as a percentage of the LabelledPointUndirectedGraph's width. If `tuple` or `list`, then it defines the axis limits. If ``None``, then the limits are set automatically. axes_y_limits : (`float`, `float`) `tuple` or ``None``, optional The limits of the y axis. If `float`, then it sets padding on the top and bottom of the LabelledPointUndirectedGraph as a percentage of the LabelledPointUndirectedGraph's height. If `tuple` or `list`, then it defines the axis limits. If ``None``, then the limits are set automatically. axes_x_ticks : `list` or `tuple` or ``None``, optional The ticks of the x axis. axes_y_ticks : `list` or `tuple` or ``None``, optional The ticks of the y axis. figure_size : (`float`, `float`) or `None`, optional The size of the figure in inches. Raises ------ ValueError If both ``with_labels`` and ``without_labels`` are passed. """ from menpo.visualize import LandmarkViewer2d if with_labels is not None and without_labels is not None: raise ValueError( "You may only pass one of `with_labels` or " "`without_labels`." ) elif with_labels is not None: lmark_group = self.with_labels(with_labels) elif without_labels is not None: lmark_group = self.without_labels(without_labels) else: lmark_group = self # Fall through landmark_viewer = LandmarkViewer2d(figure_id, new_figure, group, lmark_group) return landmark_viewer.render( image_view=image_view, render_lines=render_lines, line_colour=line_colour, line_style=line_style, line_width=line_width, render_markers=render_markers, marker_style=marker_style, marker_size=marker_size, marker_face_colour=marker_face_colour, marker_edge_colour=marker_edge_colour, marker_edge_width=marker_edge_width, render_numbering=render_numbering, numbers_horizontal_align=numbers_horizontal_align, numbers_vertical_align=numbers_vertical_align, numbers_font_name=numbers_font_name, numbers_font_size=numbers_font_size, numbers_font_style=numbers_font_style, numbers_font_weight=numbers_font_weight, numbers_font_colour=numbers_font_colour, render_legend=render_legend, legend_title=legend_title, legend_font_name=legend_font_name, legend_font_style=legend_font_style, legend_font_size=legend_font_size, legend_font_weight=legend_font_weight, legend_marker_scale=legend_marker_scale, legend_location=legend_location, legend_bbox_to_anchor=legend_bbox_to_anchor, legend_border_axes_pad=legend_border_axes_pad, legend_n_columns=legend_n_columns, legend_horizontal_spacing=legend_horizontal_spacing, legend_vertical_spacing=legend_vertical_spacing, legend_border=legend_border, legend_border_padding=legend_border_padding, legend_shadow=legend_shadow, legend_rounded_corners=legend_rounded_corners, render_axes=render_axes, axes_font_name=axes_font_name, axes_font_size=axes_font_size, axes_font_style=axes_font_style, axes_font_weight=axes_font_weight, axes_x_limits=axes_x_limits, axes_y_limits=axes_y_limits, axes_x_ticks=axes_x_ticks, axes_y_ticks=axes_y_ticks, figure_size=figure_size, )
[ "def", "_view_2d", "(", "self", ",", "with_labels", "=", "None", ",", "without_labels", "=", "None", ",", "group", "=", "\"group\"", ",", "figure_id", "=", "None", ",", "new_figure", "=", "False", ",", "image_view", "=", "True", ",", "render_lines", "=", ...
https://github.com/menpo/menpo/blob/a61500656c4fc2eea82497684f13cc31a605550b/menpo/shape/labelled.py#L504-L816
pytorch/benchmark
5c93a5389563a5b6ccfa17d265d60f4fe7272f31
torchbenchmark/models/maml/learner.py
python
Learner.forward
(self, x, vars=None, bn_training=True)
return x
This function can be called by finetunning, however, in finetunning, we dont wish to update running_mean/running_var. Thought weights/bias of bn is updated, it has been separated by fast_weights. Indeed, to not update running_mean/running_var, we need set update_bn_statistics=False but weight/bias will be updated and not dirty initial theta parameters via fast_weiths. :param x: [b, 1, 28, 28] :param vars: :param bn_training: set False to not update :return: x, loss, likelihood, kld
This function can be called by finetunning, however, in finetunning, we dont wish to update running_mean/running_var. Thought weights/bias of bn is updated, it has been separated by fast_weights. Indeed, to not update running_mean/running_var, we need set update_bn_statistics=False but weight/bias will be updated and not dirty initial theta parameters via fast_weiths. :param x: [b, 1, 28, 28] :param vars: :param bn_training: set False to not update :return: x, loss, likelihood, kld
[ "This", "function", "can", "be", "called", "by", "finetunning", "however", "in", "finetunning", "we", "dont", "wish", "to", "update", "running_mean", "/", "running_var", ".", "Thought", "weights", "/", "bias", "of", "bn", "is", "updated", "it", "has", "been"...
def forward(self, x, vars=None, bn_training=True): """ This function can be called by finetunning, however, in finetunning, we dont wish to update running_mean/running_var. Thought weights/bias of bn is updated, it has been separated by fast_weights. Indeed, to not update running_mean/running_var, we need set update_bn_statistics=False but weight/bias will be updated and not dirty initial theta parameters via fast_weiths. :param x: [b, 1, 28, 28] :param vars: :param bn_training: set False to not update :return: x, loss, likelihood, kld """ if vars is None: vars = self.vars idx = 0 bn_idx = 0 for name, param in self.config: if name is 'conv2d': w, b = vars[idx], vars[idx + 1] # remember to keep synchrozied of forward_encoder and forward_decoder! x = F.conv2d(x, w, b, stride=param[4], padding=param[5]) idx += 2 # print(name, param, '\tout:', x.shape) elif name is 'convt2d': w, b = vars[idx], vars[idx + 1] # remember to keep synchrozied of forward_encoder and forward_decoder! x = F.conv_transpose2d(x, w, b, stride=param[4], padding=param[5]) idx += 2 # print(name, param, '\tout:', x.shape) elif name is 'linear': w, b = vars[idx], vars[idx + 1] x = F.linear(x, w, b) idx += 2 # print('forward:', idx, x.norm().item()) elif name is 'bn': w, b = vars[idx], vars[idx + 1] running_mean, running_var = self.vars_bn[bn_idx], self.vars_bn[bn_idx+1] x = F.batch_norm(x, running_mean, running_var, weight=w, bias=b, training=bn_training) idx += 2 bn_idx += 2 elif name is 'flatten': # print(x.shape) x = x.view(x.size(0), -1) elif name is 'reshape': # [b, 8] => [b, 2, 2, 2] x = x.view(x.size(0), *param) elif name is 'relu': x = F.relu(x, inplace=param[0]) elif name is 'leakyrelu': x = F.leaky_relu(x, negative_slope=param[0], inplace=param[1]) elif name is 'tanh': x = F.tanh(x) elif name is 'sigmoid': x = torch.sigmoid(x) elif name is 'upsample': x = F.upsample_nearest(x, scale_factor=param[0]) elif name is 'max_pool2d': x = F.max_pool2d(x, param[0], param[1], param[2]) elif name is 'avg_pool2d': x = F.avg_pool2d(x, param[0], param[1], param[2]) else: raise NotImplementedError # make sure variable is used properly assert idx == len(vars) assert bn_idx == len(self.vars_bn) return x
[ "def", "forward", "(", "self", ",", "x", ",", "vars", "=", "None", ",", "bn_training", "=", "True", ")", ":", "if", "vars", "is", "None", ":", "vars", "=", "self", ".", "vars", "idx", "=", "0", "bn_idx", "=", "0", "for", "name", ",", "param", "...
https://github.com/pytorch/benchmark/blob/5c93a5389563a5b6ccfa17d265d60f4fe7272f31/torchbenchmark/models/maml/learner.py#L122-L194
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
lib-python/2.7/mailbox.py
python
BabylMessage.set_visible
(self, visible)
Set the Message representation of visible headers.
Set the Message representation of visible headers.
[ "Set", "the", "Message", "representation", "of", "visible", "headers", "." ]
def set_visible(self, visible): """Set the Message representation of visible headers.""" self._visible = Message(visible)
[ "def", "set_visible", "(", "self", ",", "visible", ")", ":", "self", ".", "_visible", "=", "Message", "(", "visible", ")" ]
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/lib-python/2.7/mailbox.py#L1809-L1811
prkumar/uplink
3472806f68a60a93f7cb555d36365551a5411cc5
uplink/models.py
python
dumps._wrap_delegate
(self, delegate)
return RequestBodyConverterFactory(delegate)
[]
def _wrap_delegate(self, delegate): return RequestBodyConverterFactory(delegate)
[ "def", "_wrap_delegate", "(", "self", ",", "delegate", ")", ":", "return", "RequestBodyConverterFactory", "(", "delegate", ")" ]
https://github.com/prkumar/uplink/blob/3472806f68a60a93f7cb555d36365551a5411cc5/uplink/models.py#L169-L170
hatRiot/zarp
2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad
src/lib/libmproxy/flow.py
python
HTTPMsg.size
(self, **kwargs)
Size in bytes of a fully rendered message, including headers and HTTP lead-in.
Size in bytes of a fully rendered message, including headers and HTTP lead-in.
[ "Size", "in", "bytes", "of", "a", "fully", "rendered", "message", "including", "headers", "and", "HTTP", "lead", "-", "in", "." ]
def size(self, **kwargs): """ Size in bytes of a fully rendered message, including headers and HTTP lead-in. """ hl = len(self._assemble_head(**kwargs)) if self.content: return hl + len(self.content) else: return hl
[ "def", "size", "(", "self", ",", "*", "*", "kwargs", ")", ":", "hl", "=", "len", "(", "self", ".", "_assemble_head", "(", "*", "*", "kwargs", ")", ")", "if", "self", ".", "content", ":", "return", "hl", "+", "len", "(", "self", ".", "content", ...
https://github.com/hatRiot/zarp/blob/2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad/src/lib/libmproxy/flow.py#L243-L252
openstack/ironic
b392dc19bcd29cef5a69ec00d2f18a7a19a679e5
ironic/drivers/modules/irmc/inspect.py
python
_get_mac_addresses
(node)
return [a for c, a in zip(node_classes, mac_addresses) if c == NODE_CLASS_OID_VALUE['primary']]
Get mac addresses of the node. :param node: node object. :raises: SNMPFailure if SNMP operation failed. :returns: a list of mac addresses.
Get mac addresses of the node.
[ "Get", "mac", "addresses", "of", "the", "node", "." ]
def _get_mac_addresses(node): """Get mac addresses of the node. :param node: node object. :raises: SNMPFailure if SNMP operation failed. :returns: a list of mac addresses. """ d_info = irmc_common.parse_driver_info(node) snmp_client = snmp.SNMPClient(d_info['irmc_address'], d_info['irmc_snmp_port'], d_info['irmc_snmp_version'], d_info['irmc_snmp_community'], d_info['irmc_snmp_security']) node_classes = snmp_client.get_next(NODE_CLASS_OID) mac_addresses = [':'.join(['%02x' % x for x in mac]) for mac in snmp_client.get_next(MAC_ADDRESS_OID)] return [a for c, a in zip(node_classes, mac_addresses) if c == NODE_CLASS_OID_VALUE['primary']]
[ "def", "_get_mac_addresses", "(", "node", ")", ":", "d_info", "=", "irmc_common", ".", "parse_driver_info", "(", "node", ")", "snmp_client", "=", "snmp", ".", "SNMPClient", "(", "d_info", "[", "'irmc_address'", "]", ",", "d_info", "[", "'irmc_snmp_port'", "]",...
https://github.com/openstack/ironic/blob/b392dc19bcd29cef5a69ec00d2f18a7a19a679e5/ironic/drivers/modules/irmc/inspect.py#L98-L117
magenta/magenta
be6558f1a06984faff6d6949234f5fe9ad0ffdb5
magenta/models/melody_rnn/melody_rnn_pipeline.py
python
EncoderPipeline.transform
(self, input_object)
return [encoded]
[]
def transform(self, input_object): melody = input_object melody.squash( self._min_note, self._max_note, self._transpose_to_key) encoded = pipelines_common.make_sequence_example( *self._melody_encoder_decoder.encode(melody)) return [encoded]
[ "def", "transform", "(", "self", ",", "input_object", ")", ":", "melody", "=", "input_object", "melody", ".", "squash", "(", "self", ".", "_min_note", ",", "self", ".", "_max_note", ",", "self", ".", "_transpose_to_key", ")", "encoded", "=", "pipelines_commo...
https://github.com/magenta/magenta/blob/be6558f1a06984faff6d6949234f5fe9ad0ffdb5/magenta/models/melody_rnn/melody_rnn_pipeline.py#L46-L54
translate/virtaal
8b0a6fbf764ed92cc44a189499dec399c6423761
virtaal/views/placeablesguiinfo.py
python
StringElemGUI.render
(self, offset=-1)
return offset
Render the string element string and its associated widgets.
Render the string element string and its associated widgets.
[ "Render", "the", "string", "element", "string", "and", "its", "associated", "widgets", "." ]
def render(self, offset=-1): """Render the string element string and its associated widgets.""" buffer = self.textbox.buffer if offset < 0: offset = 0 buffer.set_text('') if self.has_start_widget(): anchor = buffer.create_child_anchor(buffer.get_iter_at_offset(offset)) self.textbox.add_child_at_anchor(self.widgets[0], anchor) self.widgets[0].show() offset += 1 for child in self.elem.sub: if isinstance(child, StringElem): child.gui_info.render(offset) offset += child.gui_info.length() else: buffer.insert(buffer.get_iter_at_offset(offset), child) offset += len(child) if self.has_end_widget(): anchor = buffer.create_child_anchor(buffer.get_iter_at_offset(offset)) self.textbox.add_child_at_anchor(self.widgets[1], anchor) self.widgets[1].show() offset += 1 return offset
[ "def", "render", "(", "self", ",", "offset", "=", "-", "1", ")", ":", "buffer", "=", "self", ".", "textbox", ".", "buffer", "if", "offset", "<", "0", ":", "offset", "=", "0", "buffer", ".", "set_text", "(", "''", ")", "if", "self", ".", "has_star...
https://github.com/translate/virtaal/blob/8b0a6fbf764ed92cc44a189499dec399c6423761/virtaal/views/placeablesguiinfo.py#L226-L253
ZhixiuYe/NER-pytorch
bc6c7db2a522a4b21721481eb84546b2f448807d
utils.py
python
adjust_learning_rate
(optimizer, lr)
shrink learning rate for pytorch
shrink learning rate for pytorch
[ "shrink", "learning", "rate", "for", "pytorch" ]
def adjust_learning_rate(optimizer, lr): """ shrink learning rate for pytorch """ for param_group in optimizer.param_groups: param_group['lr'] = lr
[ "def", "adjust_learning_rate", "(", "optimizer", ",", "lr", ")", ":", "for", "param_group", "in", "optimizer", ".", "param_groups", ":", "param_group", "[", "'lr'", "]", "=", "lr" ]
https://github.com/ZhixiuYe/NER-pytorch/blob/bc6c7db2a522a4b21721481eb84546b2f448807d/utils.py#L224-L229
hortonworks/ansible-hortonworks
d4c303e036d3b0d28ea5962b946644a8c4910a80
inventory/gce/gce.py
python
GceInventory.parse_cli_args
(self)
Command line argument processing
Command line argument processing
[ "Command", "line", "argument", "processing" ]
def parse_cli_args(self): ''' Command line argument processing ''' parser = argparse.ArgumentParser( description='Produce an Ansible Inventory file based on GCE') parser.add_argument('--list', action='store_true', default=True, help='List instances (default: True)') parser.add_argument('--host', action='store', help='Get all information about an instance') parser.add_argument('--instance-tags', action='store', help='Only include instances with this tags, separated by comma') parser.add_argument('--pretty', action='store_true', default=False, help='Pretty format (default: False)') parser.add_argument( '--refresh-cache', action='store_true', default=False, help='Force refresh of cache by making API requests (default: False - use cache files)') self.args = parser.parse_args()
[ "def", "parse_cli_args", "(", "self", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Produce an Ansible Inventory file based on GCE'", ")", "parser", ".", "add_argument", "(", "'--list'", ",", "action", "=", "'store_true'", ",...
https://github.com/hortonworks/ansible-hortonworks/blob/d4c303e036d3b0d28ea5962b946644a8c4910a80/inventory/gce/gce.py#L329-L345
aliutkus/speechmetrics
6e1542913bd7c64dc66317ae6c753426c59cb2c0
speechmetrics/relative/sisdr.py
python
load
(window, hop=None)
return SISDR(window, hop)
[]
def load(window, hop=None): return SISDR(window, hop)
[ "def", "load", "(", "window", ",", "hop", "=", "None", ")", ":", "return", "SISDR", "(", "window", ",", "hop", ")" ]
https://github.com/aliutkus/speechmetrics/blob/6e1542913bd7c64dc66317ae6c753426c59cb2c0/speechmetrics/relative/sisdr.py#L31-L32
hakril/PythonForWindows
61e027a678d5b87aa64fcf8a37a6661a86236589
windows/rpc/ndr.py
python
NdrHyper.get_alignment
(self)
return 8
[]
def get_alignment(self): return 8
[ "def", "get_alignment", "(", "self", ")", ":", "return", "8" ]
https://github.com/hakril/PythonForWindows/blob/61e027a678d5b87aa64fcf8a37a6661a86236589/windows/rpc/ndr.py#L231-L232
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_openshift/library/oc_volume.py
python
Yedit.separator
(self)
return self._separator
getter method for separator
getter method for separator
[ "getter", "method", "for", "separator" ]
def separator(self): ''' getter method for separator ''' return self._separator
[ "def", "separator", "(", "self", ")", ":", "return", "self", ".", "_separator" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_openshift/library/oc_volume.py#L207-L209
spyder-ide/spyder
55da47c032dfcf519600f67f8b30eab467f965e7
spyder/plugins/variableexplorer/widgets/dataframeeditor.py
python
DataFrameModel.sort
(self, column, order=Qt.AscendingOrder)
return True
Overriding sort method
Overriding sort method
[ "Overriding", "sort", "method" ]
def sort(self, column, order=Qt.AscendingOrder): """Overriding sort method""" if self.complex_intran is not None: if self.complex_intran.any(axis=0).iloc[column]: QMessageBox.critical(self.dialog, "Error", "TypeError error: no ordering " "relation is defined for complex numbers") return False try: ascending = order == Qt.AscendingOrder if column >= 0: try: self.df.sort_values(by=self.df.columns[column], ascending=ascending, inplace=True, kind='mergesort') except AttributeError: # for pandas version < 0.17 self.df.sort(columns=self.df.columns[column], ascending=ascending, inplace=True, kind='mergesort') except ValueError as e: # Not possible to sort on duplicate columns # See spyder-ide/spyder#5225. QMessageBox.critical(self.dialog, "Error", "ValueError: %s" % to_text_string(e)) except SystemError as e: # Not possible to sort on category dtypes # See spyder-ide/spyder#5361. QMessageBox.critical(self.dialog, "Error", "SystemError: %s" % to_text_string(e)) else: # Update index list self.recalculate_index() # To sort by index self.df.sort_index(inplace=True, ascending=ascending) except TypeError as e: QMessageBox.critical(self.dialog, "Error", "TypeError error: %s" % str(e)) return False self.reset() return True
[ "def", "sort", "(", "self", ",", "column", ",", "order", "=", "Qt", ".", "AscendingOrder", ")", ":", "if", "self", ".", "complex_intran", "is", "not", "None", ":", "if", "self", ".", "complex_intran", ".", "any", "(", "axis", "=", "0", ")", ".", "i...
https://github.com/spyder-ide/spyder/blob/55da47c032dfcf519600f67f8b30eab467f965e7/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L375-L416
inducer/pycuda
9f3b898ec0846e2a4dff5077d4403ea03b1fccf9
pycuda/sparse/packeted.py
python
PacketedSpMV.find_local_row_costs_and_remaining_coo
( self, csr_mat, dof_to_packet_nr, old2new_fetch_indices )
return local_row_costs, remaining_coo
[]
def find_local_row_costs_and_remaining_coo( self, csr_mat, dof_to_packet_nr, old2new_fetch_indices ): h, w = self.shape local_row_costs = [0] * h rem_coo_values = [] rem_coo_i = [] rem_coo_j = [] iptr = csr_mat.indptr indices = csr_mat.indices data = csr_mat.data for i in range(h): for idx in range(iptr[i], iptr[i + 1]): j = indices[idx] if dof_to_packet_nr[i] == dof_to_packet_nr[j]: local_row_costs[i] += 1 else: rem_coo_values.append(data[idx]) rem_coo_i.append(old2new_fetch_indices[i]) rem_coo_j.append(old2new_fetch_indices[j]) from scipy.sparse import coo_matrix remaining_coo = coo_matrix( (rem_coo_values, (rem_coo_i, rem_coo_j)), self.shape, dtype=self.dtype ) return local_row_costs, remaining_coo
[ "def", "find_local_row_costs_and_remaining_coo", "(", "self", ",", "csr_mat", ",", "dof_to_packet_nr", ",", "old2new_fetch_indices", ")", ":", "h", ",", "w", "=", "self", ".", "shape", "local_row_costs", "=", "[", "0", "]", "*", "h", "rem_coo_values", "=", "["...
https://github.com/inducer/pycuda/blob/9f3b898ec0846e2a4dff5077d4403ea03b1fccf9/pycuda/sparse/packeted.py#L230-L260
keiffster/program-y
8c99b56f8c32f01a7b9887b5daae9465619d0385
src/programy/storage/stores/sql/engine.py
python
SQLStorageEngine.user_store
(self)
return SQLUserStore(self)
[]
def user_store(self): return SQLUserStore(self)
[ "def", "user_store", "(", "self", ")", ":", "return", "SQLUserStore", "(", "self", ")" ]
https://github.com/keiffster/program-y/blob/8c99b56f8c32f01a7b9887b5daae9465619d0385/src/programy/storage/stores/sql/engine.py#L89-L90
pymedusa/Medusa
1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38
ext/oauthlib/oauth2/rfc6749/endpoints/pre_configured.py
python
MobileApplicationServer.__init__
(self, request_validator, token_generator=None, token_expires_in=None, refresh_token_generator=None, **kwargs)
Construct a new implicit grant server. :param request_validator: An implementation of oauthlib.oauth2.RequestValidator. :param token_expires_in: An int or a function to generate a token expiration offset (in seconds) given a oauthlib.common.Request object. :param token_generator: A function to generate a token from a request. :param refresh_token_generator: A function to generate a token from a request for the refresh token. :param kwargs: Extra parameters to pass to authorization-, token-, resource-, and revocation-endpoint constructors.
Construct a new implicit grant server.
[ "Construct", "a", "new", "implicit", "grant", "server", "." ]
def __init__(self, request_validator, token_generator=None, token_expires_in=None, refresh_token_generator=None, **kwargs): """Construct a new implicit grant server. :param request_validator: An implementation of oauthlib.oauth2.RequestValidator. :param token_expires_in: An int or a function to generate a token expiration offset (in seconds) given a oauthlib.common.Request object. :param token_generator: A function to generate a token from a request. :param refresh_token_generator: A function to generate a token from a request for the refresh token. :param kwargs: Extra parameters to pass to authorization-, token-, resource-, and revocation-endpoint constructors. """ implicit_grant = ImplicitGrant(request_validator) bearer = BearerToken(request_validator, token_generator, token_expires_in, refresh_token_generator) AuthorizationEndpoint.__init__(self, default_response_type='token', response_types={ 'token': implicit_grant}, default_token_type=bearer) ResourceEndpoint.__init__(self, default_token='Bearer', token_types={'Bearer': bearer}) RevocationEndpoint.__init__(self, request_validator, supported_token_types=['access_token']) IntrospectEndpoint.__init__(self, request_validator, supported_token_types=['access_token'])
[ "def", "__init__", "(", "self", ",", "request_validator", ",", "token_generator", "=", "None", ",", "token_expires_in", "=", "None", ",", "refresh_token_generator", "=", "None", ",", "*", "*", "kwargs", ")", ":", "implicit_grant", "=", "ImplicitGrant", "(", "r...
https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/oauthlib/oauth2/rfc6749/endpoints/pre_configured.py#L121-L148
facebookresearch/SlowFast
39ef35c9a086443209b458cceaec86a02e27b369
slowfast/utils/misc.py
python
is_eval_epoch
(cfg, cur_epoch, multigrid_schedule)
return (cur_epoch + 1) % cfg.TRAIN.EVAL_PERIOD == 0
Determine if the model should be evaluated at the current epoch. Args: cfg (CfgNode): configs. Details can be found in slowfast/config/defaults.py cur_epoch (int): current epoch. multigrid_schedule (List): schedule for multigrid training.
Determine if the model should be evaluated at the current epoch. Args: cfg (CfgNode): configs. Details can be found in slowfast/config/defaults.py cur_epoch (int): current epoch. multigrid_schedule (List): schedule for multigrid training.
[ "Determine", "if", "the", "model", "should", "be", "evaluated", "at", "the", "current", "epoch", ".", "Args", ":", "cfg", "(", "CfgNode", ")", ":", "configs", ".", "Details", "can", "be", "found", "in", "slowfast", "/", "config", "/", "defaults", ".", ...
def is_eval_epoch(cfg, cur_epoch, multigrid_schedule): """ Determine if the model should be evaluated at the current epoch. Args: cfg (CfgNode): configs. Details can be found in slowfast/config/defaults.py cur_epoch (int): current epoch. multigrid_schedule (List): schedule for multigrid training. """ if cur_epoch + 1 == cfg.SOLVER.MAX_EPOCH: return True if multigrid_schedule is not None: prev_epoch = 0 for s in multigrid_schedule: if cur_epoch < s[-1]: period = max( (s[-1] - prev_epoch) // cfg.MULTIGRID.EVAL_FREQ + 1, 1 ) return (s[-1] - 1 - cur_epoch) % period == 0 prev_epoch = s[-1] return (cur_epoch + 1) % cfg.TRAIN.EVAL_PERIOD == 0
[ "def", "is_eval_epoch", "(", "cfg", ",", "cur_epoch", ",", "multigrid_schedule", ")", ":", "if", "cur_epoch", "+", "1", "==", "cfg", ".", "SOLVER", ".", "MAX_EPOCH", ":", "return", "True", "if", "multigrid_schedule", "is", "not", "None", ":", "prev_epoch", ...
https://github.com/facebookresearch/SlowFast/blob/39ef35c9a086443209b458cceaec86a02e27b369/slowfast/utils/misc.py#L200-L221
danielfm/pybreaker
1dbcbda76dda1d1d3a9df25cbe1912655dbbf6cc
src/pybreaker.py
python
CircuitBreaker.add_excluded_exception
(self, exception)
Adds an exception to the list of excluded exceptions.
Adds an exception to the list of excluded exceptions.
[ "Adds", "an", "exception", "to", "the", "list", "of", "excluded", "exceptions", "." ]
def add_excluded_exception(self, exception): """ Adds an exception to the list of excluded exceptions. """ with self._lock: self._excluded_exceptions.append(exception)
[ "def", "add_excluded_exception", "(", "self", ",", "exception", ")", ":", "with", "self", ".", "_lock", ":", "self", ".", "_excluded_exceptions", ".", "append", "(", "exception", ")" ]
https://github.com/danielfm/pybreaker/blob/1dbcbda76dda1d1d3a9df25cbe1912655dbbf6cc/src/pybreaker.py#L167-L172
ComplianceAsCode/content
6760a14e7fe3fb34205bd1a165095a9334412e95
ssg/build_renumber.py
python
FileLinker._get_input_fname
(self)
return fnames.pop() if fnames else None
Returns the input filename referenced from the related check. Raises SSGError if there are more than one filenames related to this check system.
Returns the input filename referenced from the related check.
[ "Returns", "the", "input", "filename", "referenced", "from", "the", "related", "check", "." ]
def _get_input_fname(self): """ Returns the input filename referenced from the related check. Raises SSGError if there are more than one filenames related to this check system. """ fnames = self._get_fnames_from_related_checks() if len(fnames) > 1: msg = ("referencing more than one file per check system " "is not yet supported by this script.") raise SSGError(msg) return fnames.pop() if fnames else None
[ "def", "_get_input_fname", "(", "self", ")", ":", "fnames", "=", "self", ".", "_get_fnames_from_related_checks", "(", ")", "if", "len", "(", "fnames", ")", ">", "1", ":", "msg", "=", "(", "\"referencing more than one file per check system \"", "\"is not yet supporte...
https://github.com/ComplianceAsCode/content/blob/6760a14e7fe3fb34205bd1a165095a9334412e95/ssg/build_renumber.py#L59-L71
zzzeek/sqlalchemy
fc5c54fcd4d868c2a4c7ac19668d72f506fe821e
lib/sqlalchemy/engine/interfaces.py
python
Dialect.is_disconnect
(self, e, connection, cursor)
Return True if the given DB-API error indicates an invalid connection
Return True if the given DB-API error indicates an invalid connection
[ "Return", "True", "if", "the", "given", "DB", "-", "API", "error", "indicates", "an", "invalid", "connection" ]
def is_disconnect(self, e, connection, cursor): """Return True if the given DB-API error indicates an invalid connection""" raise NotImplementedError()
[ "def", "is_disconnect", "(", "self", ",", "e", ",", "connection", ",", "cursor", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/zzzeek/sqlalchemy/blob/fc5c54fcd4d868c2a4c7ac19668d72f506fe821e/lib/sqlalchemy/engine/interfaces.py#L742-L746
SheffieldML/GPy
bb1bc5088671f9316bc92a46d356734e34c2d5c0
GPy/kern/src/psi_comp/rbf_psi_gpucomp.py
python
PSICOMP_RBF_GPU._initGPUCache
(self, N, M, Q)
[]
def _initGPUCache(self, N, M, Q): import pycuda.gpuarray as gpuarray if self.gpuCache == None: self.gpuCache = { 'l_gpu' :gpuarray.empty((Q,),np.float64,order='F'), 'Z_gpu' :gpuarray.empty((M,Q),np.float64,order='F'), 'mu_gpu' :gpuarray.empty((N,Q),np.float64,order='F'), 'S_gpu' :gpuarray.empty((N,Q),np.float64,order='F'), 'psi1_gpu' :gpuarray.empty((N,M),np.float64,order='F'), 'psi2_gpu' :gpuarray.empty((M,M),np.float64,order='F'), 'psi2n_gpu' :gpuarray.empty((N,M,M),np.float64,order='F'), 'dL_dpsi1_gpu' :gpuarray.empty((N,M),np.float64,order='F'), 'dL_dpsi2_gpu' :gpuarray.empty((M,M),np.float64,order='F'), 'log_denom1_gpu' :gpuarray.empty((N,Q),np.float64,order='F'), 'log_denom2_gpu' :gpuarray.empty((N,Q),np.float64,order='F'), # derivatives 'dvar_gpu' :gpuarray.empty((self.blocknum,),np.float64, order='F'), 'dl_gpu' :gpuarray.empty((Q,self.blocknum),np.float64, order='F'), 'dZ_gpu' :gpuarray.empty((M,Q),np.float64, order='F'), 'dmu_gpu' :gpuarray.empty((N,Q,self.blocknum),np.float64, order='F'), 'dS_gpu' :gpuarray.empty((N,Q,self.blocknum),np.float64, order='F'), # grad 'grad_l_gpu' :gpuarray.empty((Q,),np.float64, order='F'), 'grad_mu_gpu' :gpuarray.empty((N,Q,),np.float64, order='F'), 'grad_S_gpu' :gpuarray.empty((N,Q,),np.float64, order='F'), } else: assert N==self.gpuCache['mu_gpu'].shape[0] assert M==self.gpuCache['Z_gpu'].shape[0] assert Q==self.gpuCache['l_gpu'].shape[0]
[ "def", "_initGPUCache", "(", "self", ",", "N", ",", "M", ",", "Q", ")", ":", "import", "pycuda", ".", "gpuarray", "as", "gpuarray", "if", "self", ".", "gpuCache", "==", "None", ":", "self", ".", "gpuCache", "=", "{", "'l_gpu'", ":", "gpuarray", ".", ...
https://github.com/SheffieldML/GPy/blob/bb1bc5088671f9316bc92a46d356734e34c2d5c0/GPy/kern/src/psi_comp/rbf_psi_gpucomp.py#L264-L293
marcosfede/algorithms
1ee7c815f9d556c9cef4d4b0d21ee3a409d21629
union-find/count_islands/count_islands.py
python
Union.__init__
(self)
[]
def __init__(self): self.parents = {} self.sizes = {} self.count = 0
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "parents", "=", "{", "}", "self", ".", "sizes", "=", "{", "}", "self", ".", "count", "=", "0" ]
https://github.com/marcosfede/algorithms/blob/1ee7c815f9d556c9cef4d4b0d21ee3a409d21629/union-find/count_islands/count_islands.py#L16-L19
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/kubernetes/client/models/v1_cinder_volume_source.py
python
V1CinderVolumeSource.__eq__
(self, other)
return self.__dict__ == other.__dict__
Returns true if both objects are equal
Returns true if both objects are equal
[ "Returns", "true", "if", "both", "objects", "are", "equal" ]
def __eq__(self, other): """ Returns true if both objects are equal """ if not isinstance(other, V1CinderVolumeSource): return False return self.__dict__ == other.__dict__
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "V1CinderVolumeSource", ")", ":", "return", "False", "return", "self", ".", "__dict__", "==", "other", ".", "__dict__" ]
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/models/v1_cinder_volume_source.py#L158-L165
researchmm/tasn
5dba8ccc096cedc63913730eeea14a9647911129
tasn-mxnet/python/mxnet/rnn/rnn_cell.py
python
BaseRNNCell.unpack_weights
(self, args)
return args
Unpack fused weight matrices into separate weight matrices. For example, say you use a module object `mod` to run a network that has an lstm cell. In `mod.get_params()[0]`, the lstm parameters are all represented as a single big vector. `cell.unpack_weights(mod.get_params()[0])` will unpack this vector into a dictionary of more readable lstm parameters - c, f, i, o gates for i2h (input to hidden) and h2h (hidden to hidden) weights. Parameters ---------- args : dict of str -> NDArray Dictionary containing packed weights. usually from `Module.get_params()[0]`. Returns ------- args : dict of str -> NDArray Dictionary with unpacked weights associated with this cell. See Also -------- pack_weights: Performs the reverse operation of this function.
Unpack fused weight matrices into separate weight matrices.
[ "Unpack", "fused", "weight", "matrices", "into", "separate", "weight", "matrices", "." ]
def unpack_weights(self, args): """Unpack fused weight matrices into separate weight matrices. For example, say you use a module object `mod` to run a network that has an lstm cell. In `mod.get_params()[0]`, the lstm parameters are all represented as a single big vector. `cell.unpack_weights(mod.get_params()[0])` will unpack this vector into a dictionary of more readable lstm parameters - c, f, i, o gates for i2h (input to hidden) and h2h (hidden to hidden) weights. Parameters ---------- args : dict of str -> NDArray Dictionary containing packed weights. usually from `Module.get_params()[0]`. Returns ------- args : dict of str -> NDArray Dictionary with unpacked weights associated with this cell. See Also -------- pack_weights: Performs the reverse operation of this function. """ args = args.copy() if not self._gate_names: return args h = self._num_hidden for group_name in ['i2h', 'h2h']: weight = args.pop('%s%s_weight'%(self._prefix, group_name)) bias = args.pop('%s%s_bias' % (self._prefix, group_name)) for j, gate in enumerate(self._gate_names): wname = '%s%s%s_weight' % (self._prefix, group_name, gate) args[wname] = weight[j*h:(j+1)*h].copy() bname = '%s%s%s_bias' % (self._prefix, group_name, gate) args[bname] = bias[j*h:(j+1)*h].copy() return args
[ "def", "unpack_weights", "(", "self", ",", "args", ")", ":", "args", "=", "args", ".", "copy", "(", ")", "if", "not", "self", ".", "_gate_names", ":", "return", "args", "h", "=", "self", ".", "_num_hidden", "for", "group_name", "in", "[", "'i2h'", ",...
https://github.com/researchmm/tasn/blob/5dba8ccc096cedc63913730eeea14a9647911129/tasn-mxnet/python/mxnet/rnn/rnn_cell.py#L225-L263
nortikin/sverchok
7b460f01317c15f2681bfa3e337c5e7346f3711b
nodes/object_nodes/getsetprop_mk2.py
python
apply_alias
(eval_str, nodetree=None)
return eval_str
- apply standard aliases - will raise error if it isn't an bpy path
- apply standard aliases - will raise error if it isn't an bpy path
[ "-", "apply", "standard", "aliases", "-", "will", "raise", "error", "if", "it", "isn", "t", "an", "bpy", "path" ]
def apply_alias(eval_str, nodetree=None): ''' - apply standard aliases - will raise error if it isn't an bpy path ''' if not eval_str.startswith("bpy."): # special case for the nodes alias, end early if eval_str.startswith("nodes") and nodetree: string_path_to_current_tree = f'bpy.data.node_groups["{nodetree.name}"].nodes' eval_str = eval_str.replace("nodes", string_path_to_current_tree, 1) return eval_str # all other aliases for alias, expanded in aliases.items(): if eval_str.startswith(alias): eval_str = eval_str.replace(alias, expanded, 1) break if not eval_str.startswith("bpy."): raise NameError return eval_str
[ "def", "apply_alias", "(", "eval_str", ",", "nodetree", "=", "None", ")", ":", "if", "not", "eval_str", ".", "startswith", "(", "\"bpy.\"", ")", ":", "# special case for the nodes alias, end early", "if", "eval_str", ".", "startswith", "(", "\"nodes\"", ")", "an...
https://github.com/nortikin/sverchok/blob/7b460f01317c15f2681bfa3e337c5e7346f3711b/nodes/object_nodes/getsetprop_mk2.py#L82-L103
joelibaceta/video-to-ascii
906abad87083afbd2b13a44a31e614566446bbb9
video_to_ascii/render_strategy/image_processor.py
python
rgb_to_ansi
(r, g, b)
return int(ansi)
Convert an rgb color to ansi color
Convert an rgb color to ansi color
[ "Convert", "an", "rgb", "color", "to", "ansi", "color" ]
def rgb_to_ansi(r, g, b): """ Convert an rgb color to ansi color """ (r, g, b) = int(r), int(g), int(b) if r == g & g == b: if r < 8: return int(16) if r > 248: return int(230) return int(round(((r - 8) / 247) * 24) + 232) to_ansi_range = lambda a: int(round(a / 51.0)) r_in_range = to_ansi_range(r) g_in_range = to_ansi_range(g) b_in_range = to_ansi_range(b) ansi = 16 + (36 * r_in_range) + (6 * g_in_range) + b_in_range return int(ansi)
[ "def", "rgb_to_ansi", "(", "r", ",", "g", ",", "b", ")", ":", "(", "r", ",", "g", ",", "b", ")", "=", "int", "(", "r", ")", ",", "int", "(", "g", ")", ",", "int", "(", "b", ")", "if", "r", "==", "g", "&", "g", "==", "b", ":", "if", ...
https://github.com/joelibaceta/video-to-ascii/blob/906abad87083afbd2b13a44a31e614566446bbb9/video_to_ascii/render_strategy/image_processor.py#L64-L81
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/tkinter/__init__.py
python
Menubutton.__init__
(self, master=None, cnf={}, **kw)
[]
def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, 'menubutton', cnf, kw)
[ "def", "__init__", "(", "self", ",", "master", "=", "None", ",", "cnf", "=", "{", "}", ",", "*", "*", "kw", ")", ":", "Widget", ".", "__init__", "(", "self", ",", "master", ",", "'menubutton'", ",", "cnf", ",", "kw", ")" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/tkinter/__init__.py#L2678-L2679
davidmalcolm/gcc-python-plugin
4deefc840e69e3c2c42f8a50963b8fb69c17efee
libcpychecker/initializers.py
python
StructInitializer.function_ptr_field
(self, fieldname)
return tree.operand
Extract the initializer for the given field, as a gcc.FunctionDecl, or None for NULL.
Extract the initializer for the given field, as a gcc.FunctionDecl, or None for NULL.
[ "Extract", "the", "initializer", "for", "the", "given", "field", "as", "a", "gcc", ".", "FunctionDecl", "or", "None", "for", "NULL", "." ]
def function_ptr_field(self, fieldname): """ Extract the initializer for the given field, as a gcc.FunctionDecl, or None for NULL. """ if fieldname not in self.fielddict: return None # implicit NULL tree = self.fielddict[fieldname] # go past casts: if isinstance(tree, gcc.NopExpr): tree = tree.operand if isinstance(tree, gcc.IntegerCst): if tree.constant == 0: return None # NULL check_isinstance(tree, gcc.AddrExpr) return tree.operand
[ "def", "function_ptr_field", "(", "self", ",", "fieldname", ")", ":", "if", "fieldname", "not", "in", "self", ".", "fielddict", ":", "return", "None", "# implicit NULL", "tree", "=", "self", ".", "fielddict", "[", "fieldname", "]", "# go past casts:", "if", ...
https://github.com/davidmalcolm/gcc-python-plugin/blob/4deefc840e69e3c2c42f8a50963b8fb69c17efee/libcpychecker/initializers.py#L73-L90
freesunshine0316/neural-graph-to-seq-mp
330b24acb5439797d858de30aeefedd2d907c91d
src_g2s/generator_utils.py
python
_mask_and_avg
(values, loss_weights)
return tf.reduce_mean(values_per_ex)
Applies mask to values then returns overall average (a scalar) Args: values: a list length max_dec_steps containing arrays shape (batch_size). loss_weights: tensor shape (batch_size, max_dec_steps) containing 1s and 0s. Returns: a scalar
Applies mask to values then returns overall average (a scalar)
[ "Applies", "mask", "to", "values", "then", "returns", "overall", "average", "(", "a", "scalar", ")" ]
def _mask_and_avg(values, loss_weights): """Applies mask to values then returns overall average (a scalar) Args: values: a list length max_dec_steps containing arrays shape (batch_size). loss_weights: tensor shape (batch_size, max_dec_steps) containing 1s and 0s. Returns: a scalar """ if loss_weights == None: return tf.reduce_mean(tf.stack(values, axis=0)) dec_lens = tf.reduce_sum(loss_weights, axis=1) # shape batch_size. float32 values_per_step = [v * loss_weights[:,dec_step] for dec_step,v in enumerate(values)] values_per_ex = sum(values_per_step)/dec_lens # shape (batch_size); normalized value for each batch member return tf.reduce_mean(values_per_ex)
[ "def", "_mask_and_avg", "(", "values", ",", "loss_weights", ")", ":", "if", "loss_weights", "==", "None", ":", "return", "tf", ".", "reduce_mean", "(", "tf", ".", "stack", "(", "values", ",", "axis", "=", "0", ")", ")", "dec_lens", "=", "tf", ".", "r...
https://github.com/freesunshine0316/neural-graph-to-seq-mp/blob/330b24acb5439797d858de30aeefedd2d907c91d/src_g2s/generator_utils.py#L362-L378
Pyomo/pyomo
dbd4faee151084f343b893cc2b0c04cf2b76fd92
pyomo/contrib/parmest/create_ef.py
python
get_objs
(scenario_instance)
return scenario_objs
return the list of objective functions for scenario_instance
return the list of objective functions for scenario_instance
[ "return", "the", "list", "of", "objective", "functions", "for", "scenario_instance" ]
def get_objs(scenario_instance): """ return the list of objective functions for scenario_instance""" scenario_objs = scenario_instance.component_data_objects(pyo.Objective, active=True, descend_into=True) scenario_objs = list(scenario_objs) if (len(scenario_objs) == 0): raise RuntimeError("Scenario " + sname + " has no active " "objective functions.") if (len(scenario_objs) > 1): print("WARNING: Scenario", sname, "has multiple active " "objectives. Selecting the first objective for " "inclusion in the extensive form.") return scenario_objs
[ "def", "get_objs", "(", "scenario_instance", ")", ":", "scenario_objs", "=", "scenario_instance", ".", "component_data_objects", "(", "pyo", ".", "Objective", ",", "active", "=", "True", ",", "descend_into", "=", "True", ")", "scenario_objs", "=", "list", "(", ...
https://github.com/Pyomo/pyomo/blob/dbd4faee151084f343b893cc2b0c04cf2b76fd92/pyomo/contrib/parmest/create_ef.py#L14-L26
tobiasfshr/MOTSFusion
32fa6d7d3282c5046e45842370d225fa5a06603e
eval/mot_eval/munkres.py
python
Munkres.__step3
(self)
return step
Cover each column containing a starred zero. If K columns are covered, the starred zeros describe a complete set of unique assignments. In this case, Go to DONE, otherwise, Go to Step 4.
Cover each column containing a starred zero. If K columns are covered, the starred zeros describe a complete set of unique assignments. In this case, Go to DONE, otherwise, Go to Step 4.
[ "Cover", "each", "column", "containing", "a", "starred", "zero", ".", "If", "K", "columns", "are", "covered", "the", "starred", "zeros", "describe", "a", "complete", "set", "of", "unique", "assignments", ".", "In", "this", "case", "Go", "to", "DONE", "othe...
def __step3(self): """ Cover each column containing a starred zero. If K columns are covered, the starred zeros describe a complete set of unique assignments. In this case, Go to DONE, otherwise, Go to Step 4. """ n = self.n count = 0 for i in range(n): for j in range(n): if self.marked[i][j] == 1: self.col_covered[j] = True count += 1 if count >= n: step = 7 # done else: step = 4 return step
[ "def", "__step3", "(", "self", ")", ":", "n", "=", "self", ".", "n", "count", "=", "0", "for", "i", "in", "range", "(", "n", ")", ":", "for", "j", "in", "range", "(", "n", ")", ":", "if", "self", ".", "marked", "[", "i", "]", "[", "j", "]...
https://github.com/tobiasfshr/MOTSFusion/blob/32fa6d7d3282c5046e45842370d225fa5a06603e/eval/mot_eval/munkres.py#L470-L489
dropbox/dropbox-sdk-python
015437429be224732990041164a21a0501235db1
dropbox/sharing.py
python
UpdateFolderMemberError.is_no_permission
(self)
return self._tag == 'no_permission'
Check if the union tag is ``no_permission``. :rtype: bool
Check if the union tag is ``no_permission``.
[ "Check", "if", "the", "union", "tag", "is", "no_permission", "." ]
def is_no_permission(self): """ Check if the union tag is ``no_permission``. :rtype: bool """ return self._tag == 'no_permission'
[ "def", "is_no_permission", "(", "self", ")", ":", "return", "self", ".", "_tag", "==", "'no_permission'" ]
https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/sharing.py#L10402-L10408
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/object_storage/object_storage_client.py
python
ObjectStorageClient.update_bucket
(self, namespace_name, bucket_name, update_bucket_details, **kwargs)
Performs a partial or full update of a bucket's user-defined metadata. Use UpdateBucket to move a bucket from one compartment to another within the same tenancy. Supply the compartmentID of the compartment that you want to move the bucket to. For more information about moving resources between compartments, see `Moving Resources to a Different Compartment`__. __ https://docs.cloud.oracle.com/iaas/Content/Identity/Tasks/managingcompartments.htm#moveRes :param str namespace_name: (required) The Object Storage namespace used for the request. :param str bucket_name: (required) The name of the bucket. Avoid entering confidential information. Example: `my-new-bucket1` :param oci.object_storage.models.UpdateBucketDetails update_bucket_details: (required) Request object for updating a bucket. :param str if_match: (optional) The entity tag (ETag) to match with the ETag of an existing resource. If the specified ETag matches the ETag of the existing resource, GET and HEAD requests will return the resource and PUT and POST requests will upload the resource. :param str opc_client_request_id: (optional) The client request ID for tracing. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.object_storage.models.Bucket` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/objectstorage/update_bucket.py.html>`__ to see an example of how to use update_bucket API.
Performs a partial or full update of a bucket's user-defined metadata.
[ "Performs", "a", "partial", "or", "full", "update", "of", "a", "bucket", "s", "user", "-", "defined", "metadata", "." ]
def update_bucket(self, namespace_name, bucket_name, update_bucket_details, **kwargs): """ Performs a partial or full update of a bucket's user-defined metadata. Use UpdateBucket to move a bucket from one compartment to another within the same tenancy. Supply the compartmentID of the compartment that you want to move the bucket to. For more information about moving resources between compartments, see `Moving Resources to a Different Compartment`__. __ https://docs.cloud.oracle.com/iaas/Content/Identity/Tasks/managingcompartments.htm#moveRes :param str namespace_name: (required) The Object Storage namespace used for the request. :param str bucket_name: (required) The name of the bucket. Avoid entering confidential information. Example: `my-new-bucket1` :param oci.object_storage.models.UpdateBucketDetails update_bucket_details: (required) Request object for updating a bucket. :param str if_match: (optional) The entity tag (ETag) to match with the ETag of an existing resource. If the specified ETag matches the ETag of the existing resource, GET and HEAD requests will return the resource and PUT and POST requests will upload the resource. :param str opc_client_request_id: (optional) The client request ID for tracing. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.object_storage.models.Bucket` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/objectstorage/update_bucket.py.html>`__ to see an example of how to use update_bucket API. """ resource_path = "/n/{namespaceName}/b/{bucketName}" method = "POST" # Don't accept unknown kwargs expected_kwargs = [ "retry_strategy", "if_match", "opc_client_request_id" ] extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs] if extra_kwargs: raise ValueError( "update_bucket got unknown kwargs: {!r}".format(extra_kwargs)) path_params = { "namespaceName": namespace_name, "bucketName": bucket_name } path_params = {k: v for (k, v) in six.iteritems(path_params) if v is not missing} for (k, v) in six.iteritems(path_params): if v is None or (isinstance(v, six.string_types) and len(v.strip()) == 0): raise ValueError('Parameter {} cannot be None, whitespace or empty string'.format(k)) header_params = { "accept": "application/json", "content-type": "application/json", "if-match": kwargs.get("if_match", missing), "opc-client-request-id": kwargs.get("opc_client_request_id", missing) } header_params = {k: v for (k, v) in six.iteritems(header_params) if v is not missing and v is not None} retry_strategy = self.base_client.get_preferred_retry_strategy( operation_retry_strategy=kwargs.get('retry_strategy'), client_retry_strategy=self.retry_strategy ) if retry_strategy: if not isinstance(retry_strategy, retry.NoneRetryStrategy): self.base_client.add_opc_client_retries_header(header_params) retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback) return retry_strategy.make_retrying_call( self.base_client.call_api, resource_path=resource_path, method=method, path_params=path_params, header_params=header_params, body=update_bucket_details, response_type="Bucket") else: return self.base_client.call_api( resource_path=resource_path, method=method, path_params=path_params, header_params=header_params, body=update_bucket_details, response_type="Bucket")
[ "def", "update_bucket", "(", "self", ",", "namespace_name", ",", "bucket_name", ",", "update_bucket_details", ",", "*", "*", "kwargs", ")", ":", "resource_path", "=", "\"/n/{namespaceName}/b/{bucketName}\"", "method", "=", "\"POST\"", "# Don't accept unknown kwargs", "e...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/object_storage/object_storage_client.py#L4928-L5028
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/vpc/v20170312/models.py
python
DescribeVpcInstancesResponse.__init__
(self)
r""" :param InstanceSet: 云主机实例列表。 :type InstanceSet: list of CvmInstance :param TotalCount: 满足条件的云主机实例个数。 :type TotalCount: int :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
r""" :param InstanceSet: 云主机实例列表。 :type InstanceSet: list of CvmInstance :param TotalCount: 满足条件的云主机实例个数。 :type TotalCount: int :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
[ "r", ":", "param", "InstanceSet", ":", "云主机实例列表。", ":", "type", "InstanceSet", ":", "list", "of", "CvmInstance", ":", "param", "TotalCount", ":", "满足条件的云主机实例个数。", ":", "type", "TotalCount", ":", "int", ":", "param", "RequestId", ":", "唯一请求", "ID,每次请求都会返回。定位问题时...
def __init__(self): r""" :param InstanceSet: 云主机实例列表。 :type InstanceSet: list of CvmInstance :param TotalCount: 满足条件的云主机实例个数。 :type TotalCount: int :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.InstanceSet = None self.TotalCount = None self.RequestId = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "InstanceSet", "=", "None", "self", ".", "TotalCount", "=", "None", "self", ".", "RequestId", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/vpc/v20170312/models.py#L10487-L10498
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/site-packages/pandas-0.17.0-py3.3-win-amd64.egg/pandas/core/base.py
python
IndexOpsMixin.strides
(self)
return self.values.strides
return the strides of the underlying data
return the strides of the underlying data
[ "return", "the", "strides", "of", "the", "underlying", "data" ]
def strides(self): """ return the strides of the underlying data """ return self.values.strides
[ "def", "strides", "(", "self", ")", ":", "return", "self", ".", "values", ".", "strides" ]
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/pandas-0.17.0-py3.3-win-amd64.egg/pandas/core/base.py#L348-L350
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/whoosh/benchmark/dictionary.py
python
VulgarTongue.whoosh_schema
(self)
return schema
[]
def whoosh_schema(self): ana = analysis.StemmingAnalyzer() #ana = analysis.StandardAnalyzer() schema = fields.Schema(head=fields.ID(stored=True), body=fields.TEXT(analyzer=ana, stored=True)) return schema
[ "def", "whoosh_schema", "(", "self", ")", ":", "ana", "=", "analysis", ".", "StemmingAnalyzer", "(", ")", "#ana = analysis.StandardAnalyzer()", "schema", "=", "fields", ".", "Schema", "(", "head", "=", "fields", ".", "ID", "(", "stored", "=", "True", ")", ...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/whoosh/benchmark/dictionary.py#L29-L34
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/modular/modform_hecketriangle/subspace.py
python
SubSpaceForms.coordinate_vector
(self, v)
return self._module.coordinate_vector(self.ambient_coordinate_vector(v))
r""" Return the coordinate vector of ``v`` with respect to the basis ``self.gens()``. INPUT: - ``v`` -- An element of ``self``. OUTPUT: The coordinate vector of ``v`` with respect to the basis ``self.gens()``. Note: The coordinate vector is not an element of ``self.module()``. EXAMPLES:: sage: from sage.modular.modform_hecketriangle.space import ModularForms, QuasiCuspForms sage: MF = ModularForms(n=6, k=20, ep=1) sage: subspace = MF.subspace([(MF.Delta()*MF.E4()^2).as_ring_element(), MF.gen(0)]) sage: subspace.coordinate_vector(MF.gen(0) + MF.Delta()*MF.E4()^2).parent() Vector space of dimension 2 over Fraction Field of Univariate Polynomial Ring in d over Integer Ring sage: subspace.coordinate_vector(MF.gen(0) + MF.Delta()*MF.E4()^2) (1, 1) sage: MF = ModularForms(n=4, k=24, ep=-1) sage: subspace = MF.subspace([MF.gen(0), MF.gen(2)]) sage: subspace.coordinate_vector(subspace.gen(0)).parent() Vector space of dimension 2 over Fraction Field of Univariate Polynomial Ring in d over Integer Ring sage: subspace.coordinate_vector(subspace.gen(0)) (1, 0) sage: MF = QuasiCuspForms(n=infinity, k=12, ep=1) sage: subspace = MF.subspace([MF.Delta(), MF.E4()*MF.f_inf()*MF.E2()*MF.f_i(), MF.E4()*MF.f_inf()*MF.E2()^2, MF.E4()*MF.f_inf()*(MF.E4()-MF.E2()^2)]) sage: el = MF.E4()*MF.f_inf()*(7*MF.E4() - 3*MF.E2()^2) sage: subspace.coordinate_vector(el) (7, 0, -3) sage: subspace.ambient_coordinate_vector(el) (7, 21/(8*d), 0, -3)
r""" Return the coordinate vector of ``v`` with respect to the basis ``self.gens()``.
[ "r", "Return", "the", "coordinate", "vector", "of", "v", "with", "respect", "to", "the", "basis", "self", ".", "gens", "()", "." ]
def coordinate_vector(self, v): r""" Return the coordinate vector of ``v`` with respect to the basis ``self.gens()``. INPUT: - ``v`` -- An element of ``self``. OUTPUT: The coordinate vector of ``v`` with respect to the basis ``self.gens()``. Note: The coordinate vector is not an element of ``self.module()``. EXAMPLES:: sage: from sage.modular.modform_hecketriangle.space import ModularForms, QuasiCuspForms sage: MF = ModularForms(n=6, k=20, ep=1) sage: subspace = MF.subspace([(MF.Delta()*MF.E4()^2).as_ring_element(), MF.gen(0)]) sage: subspace.coordinate_vector(MF.gen(0) + MF.Delta()*MF.E4()^2).parent() Vector space of dimension 2 over Fraction Field of Univariate Polynomial Ring in d over Integer Ring sage: subspace.coordinate_vector(MF.gen(0) + MF.Delta()*MF.E4()^2) (1, 1) sage: MF = ModularForms(n=4, k=24, ep=-1) sage: subspace = MF.subspace([MF.gen(0), MF.gen(2)]) sage: subspace.coordinate_vector(subspace.gen(0)).parent() Vector space of dimension 2 over Fraction Field of Univariate Polynomial Ring in d over Integer Ring sage: subspace.coordinate_vector(subspace.gen(0)) (1, 0) sage: MF = QuasiCuspForms(n=infinity, k=12, ep=1) sage: subspace = MF.subspace([MF.Delta(), MF.E4()*MF.f_inf()*MF.E2()*MF.f_i(), MF.E4()*MF.f_inf()*MF.E2()^2, MF.E4()*MF.f_inf()*(MF.E4()-MF.E2()^2)]) sage: el = MF.E4()*MF.f_inf()*(7*MF.E4() - 3*MF.E2()^2) sage: subspace.coordinate_vector(el) (7, 0, -3) sage: subspace.ambient_coordinate_vector(el) (7, 21/(8*d), 0, -3) """ return self._module.coordinate_vector(self.ambient_coordinate_vector(v))
[ "def", "coordinate_vector", "(", "self", ",", "v", ")", ":", "return", "self", ".", "_module", ".", "coordinate_vector", "(", "self", ".", "ambient_coordinate_vector", "(", "v", ")", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/modular/modform_hecketriangle/subspace.py#L385-L427
yongheng1991/3D-point-capsule-networks
f2d55d845f4bf74e931ee1eaeaf60f481e4c59ad
dataloaders/modelnet40_loader.py
python
load_h5
(h5_filename)
return (data, label)
[]
def load_h5(h5_filename): f = h5py.File(h5_filename) data = f['data'][:] label = f['label'][:] return (data, label)
[ "def", "load_h5", "(", "h5_filename", ")", ":", "f", "=", "h5py", ".", "File", "(", "h5_filename", ")", "data", "=", "f", "[", "'data'", "]", "[", ":", "]", "label", "=", "f", "[", "'label'", "]", "[", ":", "]", "return", "(", "data", ",", "lab...
https://github.com/yongheng1991/3D-point-capsule-networks/blob/f2d55d845f4bf74e931ee1eaeaf60f481e4c59ad/dataloaders/modelnet40_loader.py#L51-L55
shiweibsw/Translation-Tools
2fbbf902364e557fa7017f9a74a8797b7440c077
venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/utils/__init__.py
python
dist_is_local
(dist)
return is_local(dist_location(dist))
Return True if given Distribution object is installed locally (i.e. within current virtualenv). Always True if we're not in a virtualenv.
Return True if given Distribution object is installed locally (i.e. within current virtualenv).
[ "Return", "True", "if", "given", "Distribution", "object", "is", "installed", "locally", "(", "i", ".", "e", ".", "within", "current", "virtualenv", ")", "." ]
def dist_is_local(dist): """ Return True if given Distribution object is installed locally (i.e. within current virtualenv). Always True if we're not in a virtualenv. """ return is_local(dist_location(dist))
[ "def", "dist_is_local", "(", "dist", ")", ":", "return", "is_local", "(", "dist_location", "(", "dist", ")", ")" ]
https://github.com/shiweibsw/Translation-Tools/blob/2fbbf902364e557fa7017f9a74a8797b7440c077/venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/utils/__init__.py#L289-L297
wxWidgets/Phoenix
b2199e299a6ca6d866aa6f3d0888499136ead9d6
wx/lib/agw/shortcuteditor.py
python
HTMLHelpWindow.OnUpdateUI
(self, event)
Handles all the ``wx.EVT_UPDATE_UI`` events for :class:`HTMLHelpWindow`. :param `event`: an instance of :class:`UpdateUIEvent`.
Handles all the ``wx.EVT_UPDATE_UI`` events for :class:`HTMLHelpWindow`.
[ "Handles", "all", "the", "wx", ".", "EVT_UPDATE_UI", "events", "for", ":", "class", ":", "HTMLHelpWindow", "." ]
def OnUpdateUI(self, event): """ Handles all the ``wx.EVT_UPDATE_UI`` events for :class:`HTMLHelpWindow`. :param `event`: an instance of :class:`UpdateUIEvent`. """ evId = event.GetId() if evId == wx.ID_BACKWARD: event.Enable(self.html.HistoryCanBack()) elif evId == wx.ID_FORWARD: event.Enable(self.html.HistoryCanForward()) else: event.Skip()
[ "def", "OnUpdateUI", "(", "self", ",", "event", ")", ":", "evId", "=", "event", ".", "GetId", "(", ")", "if", "evId", "==", "wx", ".", "ID_BACKWARD", ":", "event", ".", "Enable", "(", "self", ".", "html", ".", "HistoryCanBack", "(", ")", ")", "elif...
https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/agw/shortcuteditor.py#L1035-L1049
learningequality/ka-lite
571918ea668013dcf022286ea85eff1c5333fb8b
kalite/packages/bundled/django/utils/timezone.py
python
get_current_timezone
()
return getattr(_active, "value", get_default_timezone())
Returns the currently active time zone as a tzinfo instance.
Returns the currently active time zone as a tzinfo instance.
[ "Returns", "the", "currently", "active", "time", "zone", "as", "a", "tzinfo", "instance", "." ]
def get_current_timezone(): """ Returns the currently active time zone as a tzinfo instance. """ return getattr(_active, "value", get_default_timezone())
[ "def", "get_current_timezone", "(", ")", ":", "return", "getattr", "(", "_active", ",", "\"value\"", ",", "get_default_timezone", "(", ")", ")" ]
https://github.com/learningequality/ka-lite/blob/571918ea668013dcf022286ea85eff1c5333fb8b/kalite/packages/bundled/django/utils/timezone.py#L127-L131
pythonanywhere/dirigible-spreadsheet
c771e9a391708f3b219248bf9974e05b1582fdd0
documentation/BeautifulSoup.py
python
UnicodeDammit._subMSChar
(self, match)
return sub
Changes a MS smart quote character to an XML or HTML entity.
Changes a MS smart quote character to an XML or HTML entity.
[ "Changes", "a", "MS", "smart", "quote", "character", "to", "an", "XML", "or", "HTML", "entity", "." ]
def _subMSChar(self, match): """Changes a MS smart quote character to an XML or HTML entity.""" orig = match.group(1) sub = self.MS_CHARS.get(orig) if type(sub) == types.TupleType: if self.smartQuotesTo == 'xml': sub = '&#x'.encode() + sub[1].encode() + ';'.encode() else: sub = '&'.encode() + sub[0].encode() + ';'.encode() else: sub = sub.encode() return sub
[ "def", "_subMSChar", "(", "self", ",", "match", ")", ":", "orig", "=", "match", ".", "group", "(", "1", ")", "sub", "=", "self", ".", "MS_CHARS", ".", "get", "(", "orig", ")", "if", "type", "(", "sub", ")", "==", "types", ".", "TupleType", ":", ...
https://github.com/pythonanywhere/dirigible-spreadsheet/blob/c771e9a391708f3b219248bf9974e05b1582fdd0/documentation/BeautifulSoup.py#L1781-L1793
kennethreitz/records
0e2d186857f16686139c20be10a1f70a689c9ea0
records.py
python
Database.close
(self)
Closes the Database.
Closes the Database.
[ "Closes", "the", "Database", "." ]
def close(self): """Closes the Database.""" self._engine.dispose() self.open = False
[ "def", "close", "(", "self", ")", ":", "self", ".", "_engine", ".", "dispose", "(", ")", "self", ".", "open", "=", "False" ]
https://github.com/kennethreitz/records/blob/0e2d186857f16686139c20be10a1f70a689c9ea0/records.py#L263-L266
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/django/db/models/expressions.py
python
OrderBy.get_source_expressions
(self)
return [self.expression]
[]
def get_source_expressions(self): return [self.expression]
[ "def", "get_source_expressions", "(", "self", ")", ":", "return", "[", "self", ".", "expression", "]" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/db/models/expressions.py#L878-L879
xtiankisutsa/MARA_Framework
ac4ac88bfd38f33ae8780a606ed09ab97177c562
tools/androwarn/androguard/core/bytecode.py
python
method2format
( output, _format="png", mx = None, raw = False )
Export method to a specific file format @param output : output filename @param _format : format type (png, jpg ...) (default : png) @param mx : specify the MethodAnalysis object @param raw : use directly a dot raw buffer
Export method to a specific file format
[ "Export", "method", "to", "a", "specific", "file", "format" ]
def method2format( output, _format="png", mx = None, raw = False ) : """ Export method to a specific file format @param output : output filename @param _format : format type (png, jpg ...) (default : png) @param mx : specify the MethodAnalysis object @param raw : use directly a dot raw buffer """ try : import pydot except ImportError : error("module pydot not found") buff = "digraph code {\n" buff += "graph [bgcolor=white];\n" buff += "node [color=lightgray, style=filled shape=box fontname=\"Courier\" fontsize=\"8\"];\n" if raw == False : buff += method2dot( mx ) else : buff += raw buff += "}" d = pydot.graph_from_dot_data( buff ) if d : getattr(d, "write_" + _format)( output )
[ "def", "method2format", "(", "output", ",", "_format", "=", "\"png\"", ",", "mx", "=", "None", ",", "raw", "=", "False", ")", ":", "try", ":", "import", "pydot", "except", "ImportError", ":", "error", "(", "\"module pydot not found\"", ")", "buff", "=", ...
https://github.com/xtiankisutsa/MARA_Framework/blob/ac4ac88bfd38f33ae8780a606ed09ab97177c562/tools/androwarn/androguard/core/bytecode.py#L178-L205
talebolano/yolov3-network-slimming
335227f60477f7f078d2f9595a69faf7fc9541b2
parse_config.py
python
ImageFolder.__getitem__
(self, index)
return img_path, input_img
[]
def __getitem__(self, index): img_path = self.files[index % len(self.files)] # Extract image img = np.array(Image.open(img_path)) h, w, _ = img.shape dim_diff = np.abs(h - w) # Upper (left) and lower (right) padding pad1, pad2 = dim_diff // 2, dim_diff - dim_diff // 2 # Determine padding pad = ((pad1, pad2), (0, 0), (0, 0)) if h <= w else ((0, 0), (pad1, pad2), (0, 0)) # Add padding input_img = np.pad(img, pad, 'constant', constant_values=127.5) / 255. # Resize and normalize input_img = resize(input_img, (*self.img_shape, 3), mode='reflect') # Channels-first input_img = np.transpose(input_img, (2, 0, 1)) # As pytorch tensor input_img = torch.from_numpy(input_img).float() return img_path, input_img
[ "def", "__getitem__", "(", "self", ",", "index", ")", ":", "img_path", "=", "self", ".", "files", "[", "index", "%", "len", "(", "self", ".", "files", ")", "]", "# Extract image", "img", "=", "np", ".", "array", "(", "Image", ".", "open", "(", "img...
https://github.com/talebolano/yolov3-network-slimming/blob/335227f60477f7f078d2f9595a69faf7fc9541b2/parse_config.py#L118-L137
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.5/django/db/models/query.py
python
QuerySet.create
(self, **kwargs)
return obj
Creates a new object with the given kwargs, saving it to the database and returning the created object.
Creates a new object with the given kwargs, saving it to the database and returning the created object.
[ "Creates", "a", "new", "object", "with", "the", "given", "kwargs", "saving", "it", "to", "the", "database", "and", "returning", "the", "created", "object", "." ]
def create(self, **kwargs): """ Creates a new object with the given kwargs, saving it to the database and returning the created object. """ obj = self.model(**kwargs) self._for_write = True obj.save(force_insert=True, using=self.db) return obj
[ "def", "create", "(", "self", ",", "*", "*", "kwargs", ")", ":", "obj", "=", "self", ".", "model", "(", "*", "*", "kwargs", ")", "self", ".", "_for_write", "=", "True", "obj", ".", "save", "(", "force_insert", "=", "True", ",", "using", "=", "sel...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.5/django/db/models/query.py#L407-L415
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v2beta1_horizontal_pod_autoscaler_spec.py
python
V2beta1HorizontalPodAutoscalerSpec.__init__
(self, max_replicas=None, metrics=None, min_replicas=None, scale_target_ref=None, local_vars_configuration=None)
V2beta1HorizontalPodAutoscalerSpec - a model defined in OpenAPI
V2beta1HorizontalPodAutoscalerSpec - a model defined in OpenAPI
[ "V2beta1HorizontalPodAutoscalerSpec", "-", "a", "model", "defined", "in", "OpenAPI" ]
def __init__(self, max_replicas=None, metrics=None, min_replicas=None, scale_target_ref=None, local_vars_configuration=None): # noqa: E501 """V2beta1HorizontalPodAutoscalerSpec - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._max_replicas = None self._metrics = None self._min_replicas = None self._scale_target_ref = None self.discriminator = None self.max_replicas = max_replicas if metrics is not None: self.metrics = metrics if min_replicas is not None: self.min_replicas = min_replicas self.scale_target_ref = scale_target_ref
[ "def", "__init__", "(", "self", ",", "max_replicas", "=", "None", ",", "metrics", "=", "None", ",", "min_replicas", "=", "None", ",", "scale_target_ref", "=", "None", ",", "local_vars_configuration", "=", "None", ")", ":", "# noqa: E501", "# noqa: E501", "if",...
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v2beta1_horizontal_pod_autoscaler_spec.py#L49-L66
davidoren/CuckooSploit
3fce8183bee8f7917e08f765ce2a01c921f86354
lib/cuckoo/core/scheduler.py
python
AnalysisManager.init_storage
(self)
return True
Initialize analysis storage folder.
Initialize analysis storage folder.
[ "Initialize", "analysis", "storage", "folder", "." ]
def init_storage(self): """Initialize analysis storage folder.""" self.storage = os.path.join(CUCKOO_ROOT, "storage", "analyses", str(self.task.id)) # If the analysis storage folder already exists, we need to abort the # analysis or previous results will be overwritten and lost. if os.path.exists(self.storage): log.error("Analysis results folder already exists at path \"%s\"," " analysis aborted", self.storage) return False # If we're not able to create the analysis storage folder, we have to # abort the analysis. try: create_folder(folder=self.storage) except CuckooOperationalError: log.error("Unable to create analysis folder %s", self.storage) return False return True
[ "def", "init_storage", "(", "self", ")", ":", "self", ".", "storage", "=", "os", ".", "path", ".", "join", "(", "CUCKOO_ROOT", ",", "\"storage\"", ",", "\"analyses\"", ",", "str", "(", "self", ".", "task", ".", "id", ")", ")", "# If the analysis storage ...
https://github.com/davidoren/CuckooSploit/blob/3fce8183bee8f7917e08f765ce2a01c921f86354/lib/cuckoo/core/scheduler.py#L64-L86
hsoft/pdfmasher
08943dd1ad9d8fa91c547d5e91d2f90114d76094
ebooks/metadata/book.py
python
Metadata.get_all_user_metadata
(self, make_copy)
return res
return a dict containing all the custom field metadata associated with the book.
return a dict containing all the custom field metadata associated with the book.
[ "return", "a", "dict", "containing", "all", "the", "custom", "field", "metadata", "associated", "with", "the", "book", "." ]
def get_all_user_metadata(self, make_copy): ''' return a dict containing all the custom field metadata associated with the book. ''' _data = object.__getattribute__(self, '_data') user_metadata = _data['user_metadata'] if not make_copy: return user_metadata res = {} for k in user_metadata: res[k] = copy.deepcopy(user_metadata[k]) return res
[ "def", "get_all_user_metadata", "(", "self", ",", "make_copy", ")", ":", "_data", "=", "object", ".", "__getattribute__", "(", "self", ",", "'_data'", ")", "user_metadata", "=", "_data", "[", "'user_metadata'", "]", "if", "not", "make_copy", ":", "return", "...
https://github.com/hsoft/pdfmasher/blob/08943dd1ad9d8fa91c547d5e91d2f90114d76094/ebooks/metadata/book.py#L399-L411
robotlearn/pyrobolearn
9cd7c060723fda7d2779fa255ac998c2c82b8436
pyrobolearn/terminal_conditions/body_conditions.py
python
PositionCondition.__init__
(self, body, bounds=(None, None), dim=None, out=False, stay=False, all=False)
Initialize the world position terminal condition. Args: body (Body): body instance. bounds (tuple of 2 float / np.array[3]): bounds on the body position. dim (None, int, int[3]): dimensions that we should consider when looking at the bounds. If None, it will consider all 3 dimensions. If one dimension is provided it will only check along that dimension. If a np.array of 0 and 1 is provided, it will consider the dimensions that are equal to 1. Thus, [1,0,1] means to consider the bounds along the x and z axes. out (bool): if True, we are outside the provided bounds. If False, we are inside the provided bounds. stay (bool): if True, it must stay in the bounds defined by in_bounds or out_bounds; if the position leaves the bounds it results in a failure. if :attr:`stay` is False, it must get outside these bounds; if the position leaves the bounds, it results in a success. all (bool): this is only used if they are multiple dimensions. if True, all the dimensions of the state are checked if they are inside or outside the bounds depending on the other parameters. if False, any dimensions will be checked.
Initialize the world position terminal condition.
[ "Initialize", "the", "world", "position", "terminal", "condition", "." ]
def __init__(self, body, bounds=(None, None), dim=None, out=False, stay=False, all=False): """ Initialize the world position terminal condition. Args: body (Body): body instance. bounds (tuple of 2 float / np.array[3]): bounds on the body position. dim (None, int, int[3]): dimensions that we should consider when looking at the bounds. If None, it will consider all 3 dimensions. If one dimension is provided it will only check along that dimension. If a np.array of 0 and 1 is provided, it will consider the dimensions that are equal to 1. Thus, [1,0,1] means to consider the bounds along the x and z axes. out (bool): if True, we are outside the provided bounds. If False, we are inside the provided bounds. stay (bool): if True, it must stay in the bounds defined by in_bounds or out_bounds; if the position leaves the bounds it results in a failure. if :attr:`stay` is False, it must get outside these bounds; if the position leaves the bounds, it results in a success. all (bool): this is only used if they are multiple dimensions. if True, all the dimensions of the state are checked if they are inside or outside the bounds depending on the other parameters. if False, any dimensions will be checked. """ super(PositionCondition, self).__init__(body, bounds=bounds, dim=dim, out=out, stay=stay, all=all) # check the bounds self.bounds = self._check_bounds(bounds=bounds)
[ "def", "__init__", "(", "self", ",", "body", ",", "bounds", "=", "(", "None", ",", "None", ")", ",", "dim", "=", "None", ",", "out", "=", "False", ",", "stay", "=", "False", ",", "all", "=", "False", ")", ":", "super", "(", "PositionCondition", "...
https://github.com/robotlearn/pyrobolearn/blob/9cd7c060723fda7d2779fa255ac998c2c82b8436/pyrobolearn/terminal_conditions/body_conditions.py#L264-L285
ergoithz/browsepy
274028eaa460652a9d5a8c2062db1d410d09f3b7
browsepy/appconfig.py
python
Config.gendict
(cls, *args, **kwargs)
return dict((gk(k), v) for k, v in dict(*args, **kwargs).items())
Pre-translated key dictionary constructor. See :type:`dict` for more info. :returns: dictionary with uppercase keys :rtype: dict
Pre-translated key dictionary constructor.
[ "Pre", "-", "translated", "key", "dictionary", "constructor", "." ]
def gendict(cls, *args, **kwargs): ''' Pre-translated key dictionary constructor. See :type:`dict` for more info. :returns: dictionary with uppercase keys :rtype: dict ''' gk = cls.genkey return dict((gk(k), v) for k, v in dict(*args, **kwargs).items())
[ "def", "gendict", "(", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "gk", "=", "cls", ".", "genkey", "return", "dict", "(", "(", "gk", "(", "k", ")", ",", "v", ")", "for", "k", ",", "v", "in", "dict", "(", "*", "args", ",", ...
https://github.com/ergoithz/browsepy/blob/274028eaa460652a9d5a8c2062db1d410d09f3b7/browsepy/appconfig.py#L31-L41
svenevs/exhale
d6fa84fa32ee079c6b70898a1b0863a38e703591
exhale/utils.py
python
verbose_log
(msg, ansi_fmt=None)
[]
def verbose_log(msg, ansi_fmt=None): if configs.verboseBuild: if ansi_fmt: log = _use_color(msg, ansi_fmt, sys.stderr) else: log = msg sys.stderr.write("{log}\n".format(log=log))
[ "def", "verbose_log", "(", "msg", ",", "ansi_fmt", "=", "None", ")", ":", "if", "configs", ".", "verboseBuild", ":", "if", "ansi_fmt", ":", "log", "=", "_use_color", "(", "msg", ",", "ansi_fmt", ",", "sys", ".", "stderr", ")", "else", ":", "log", "="...
https://github.com/svenevs/exhale/blob/d6fa84fa32ee079c6b70898a1b0863a38e703591/exhale/utils.py#L785-L791
catap/namebench
9913a7a1a7955a3759eb18cbe73b421441a7a00f
nb_third_party/dns/rcode.py
python
from_flags
(flags, ednsflags)
return value
Return the rcode value encoded by flags and ednsflags. @param flags: the DNS flags @type flags: int @param ednsflags: the EDNS flags @type ednsflags: int @raises ValueError: rcode is < 0 or > 4095 @rtype: int
Return the rcode value encoded by flags and ednsflags.
[ "Return", "the", "rcode", "value", "encoded", "by", "flags", "and", "ednsflags", "." ]
def from_flags(flags, ednsflags): """Return the rcode value encoded by flags and ednsflags. @param flags: the DNS flags @type flags: int @param ednsflags: the EDNS flags @type ednsflags: int @raises ValueError: rcode is < 0 or > 4095 @rtype: int """ value = (flags & 0x000f) | ((ednsflags >> 20) & 0xff0) if value < 0 or value > 4095: raise ValueError('rcode must be >= 0 and <= 4095') return value
[ "def", "from_flags", "(", "flags", ",", "ednsflags", ")", ":", "value", "=", "(", "flags", "&", "0x000f", ")", "|", "(", "(", "ednsflags", ">>", "20", ")", "&", "0xff0", ")", "if", "value", "<", "0", "or", "value", ">", "4095", ":", "raise", "Val...
https://github.com/catap/namebench/blob/9913a7a1a7955a3759eb18cbe73b421441a7a00f/nb_third_party/dns/rcode.py#L77-L91
liyi14/mx-DeepIM
f1c850e5f8f75f1051a89c40daff9185870020f5
lib/dataset/LM6D_REFINE_SYN.py
python
LM6D_REFINE_SYN.__init__
( self, cfg, image_set, root_path, devkit_path, class_name, result_path=None, mask_size=-1, binary_thresh=None, mask_syn_name="", )
fill basic information to initialize imdb :param image_set: 2007_trainval, 2007_test, etc :param root_path: 'selective_search_data' and 'cache' :param devkit_path: data and results :return: imdb object
fill basic information to initialize imdb :param image_set: 2007_trainval, 2007_test, etc :param root_path: 'selective_search_data' and 'cache' :param devkit_path: data and results :return: imdb object
[ "fill", "basic", "information", "to", "initialize", "imdb", ":", "param", "image_set", ":", "2007_trainval", "2007_test", "etc", ":", "param", "root_path", ":", "selective_search_data", "and", "cache", ":", "param", "devkit_path", ":", "data", "and", "results", ...
def __init__( self, cfg, image_set, root_path, devkit_path, class_name, result_path=None, mask_size=-1, binary_thresh=None, mask_syn_name="", ): """ fill basic information to initialize imdb :param image_set: 2007_trainval, 2007_test, etc :param root_path: 'selective_search_data' and 'cache' :param devkit_path: data and results :return: imdb object """ # image_set = image_set[len(year) + 1 : len(image_set)] if len(mask_syn_name) > 0: super(LM6D_REFINE_SYN, self).__init__( "LM6D_data_syn_light" + mask_syn_name, image_set, root_path, devkit_path, result_path ) # set self.name else: super(LM6D_REFINE_SYN, self).__init__( "LM6D_data_syn_light", image_set, root_path, devkit_path, result_path ) # set self.name self.root_path = root_path self.devkit_path = os.path.join(devkit_path, "../LM6d_refine_syn") print("*******************lm6d data syn devkit path: {}".format(self.devkit_path)) self.gt_observed_data_path = os.path.join(self.devkit_path, "data", "gt_observed") self.observed_data_path = os.path.join(self.devkit_path, "data", "observed") self._linemod_path = self._get_default_path() if image_set.startswith("train") or image_set.startswith("my_val") or image_set.startswith("my_minival"): self.rendered_data_path = os.path.join(self.devkit_path, "data", "rendered") else: raise Exception("unknown prefix of " + image_set) print("LM6d data syn v1 rendered path: {}".format(self.rendered_data_path)) if image_set.startswith("train"): self.phase = "train" elif image_set.startswith("my_val") or image_set.startswith("my_minival"): self.phase = "val" else: raise Exception("unknown prefix of " + image_set) self.classes = [ "ape", "benchvise", "cam", "can", "cat", "driller", "duck", "eggbox", "glue", "holepuncher", "iron", "lamp", "phone", ] self.cur_class = class_name self.num_classes = len(self.classes) self.image_set_index = self.load_image_set_index() self.num_pairs = len(self.image_set_index) print("num_pairs", self.num_pairs) self.mask_size = mask_size self.binary_thresh = binary_thresh
[ "def", "__init__", "(", "self", ",", "cfg", ",", "image_set", ",", "root_path", ",", "devkit_path", ",", "class_name", ",", "result_path", "=", "None", ",", "mask_size", "=", "-", "1", ",", "binary_thresh", "=", "None", ",", "mask_syn_name", "=", "\"\"", ...
https://github.com/liyi14/mx-DeepIM/blob/f1c850e5f8f75f1051a89c40daff9185870020f5/lib/dataset/LM6D_REFINE_SYN.py#L22-L91
robotframework/RIDE
6e8a50774ff33dead3a2757a11b0b4418ab205c0
src/robotide/preferences/configobj.py
python
InterpolationEngine._parse_match
(self, match)
Implementation-dependent helper function. Will be passed a match object corresponding to the interpolation key we just found (e.g., "%(foo)s" or "$foo"). Should look up that key in the appropriate config file section (using the ``_fetch()`` helper function) and return a 3-tuple: (key, value, section) ``key`` is the name of the key we're looking for ``value`` is the value found for that key ``section`` is a reference to the section where it was found ``key`` and ``section`` should be None if no further interpolation should be performed on the resulting value (e.g., if we interpolated "$$" and returned "$").
Implementation-dependent helper function.
[ "Implementation", "-", "dependent", "helper", "function", "." ]
def _parse_match(self, match): """Implementation-dependent helper function. Will be passed a match object corresponding to the interpolation key we just found (e.g., "%(foo)s" or "$foo"). Should look up that key in the appropriate config file section (using the ``_fetch()`` helper function) and return a 3-tuple: (key, value, section) ``key`` is the name of the key we're looking for ``value`` is the value found for that key ``section`` is a reference to the section where it was found ``key`` and ``section`` should be None if no further interpolation should be performed on the resulting value (e.g., if we interpolated "$$" and returned "$"). """ raise NotImplementedError()
[ "def", "_parse_match", "(", "self", ",", "match", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/robotframework/RIDE/blob/6e8a50774ff33dead3a2757a11b0b4418ab205c0/src/robotide/preferences/configobj.py#L388-L404
XuShaohua/bcloud
4b54e0fdccf2b3013285fef05c97354cfa31697b
bcloud/RequestCookie.py
python
RequestCookie.load_list
(self, raw_items)
读取多个以字符串形式存放的cookie.
读取多个以字符串形式存放的cookie.
[ "读取多个以字符串形式存放的cookie", "." ]
def load_list(self, raw_items): '''读取多个以字符串形式存放的cookie.''' if not raw_items: return for item in raw_items: self.load(item)
[ "def", "load_list", "(", "self", ",", "raw_items", ")", ":", "if", "not", "raw_items", ":", "return", "for", "item", "in", "raw_items", ":", "self", ".", "load", "(", "item", ")" ]
https://github.com/XuShaohua/bcloud/blob/4b54e0fdccf2b3013285fef05c97354cfa31697b/bcloud/RequestCookie.py#L38-L43
jankrepl/pychubby
04d8f66273da6f9bd2f85b740681b56ec5c25ddb
pychubby/data.py
python
get_pretrained_68
(folder=None, verbose=True)
Get pretrained landmarks model for dlib. Parameters ---------- folder : str or pathlib.Path or None Folder where to save the .dat file. verbose : bool Print some output. References ---------- [1] C. Sagonas, E. Antonakos, G, Tzimiropoulos, S. Zafeiriou, M. Pantic. 300 faces In-the-wild challenge: Database and results. Image and Vision Computing (IMAVIS), Special Issue on Facial Landmark Localisation "In-The-Wild". 2016. [2] C. Sagonas, G. Tzimiropoulos, S. Zafeiriou, M. Pantic. A semi-automatic methodology for facial landmark annotation. Proceedings of IEEE Int’l Conf. Computer Vision and Pattern Recognition (CVPR-W), 5th Workshop on Analysis and Modeling of Faces and Gestures (AMFG 2013). Oregon, USA, June 2013. [3] C. Sagonas, G. Tzimiropoulos, S. Zafeiriou, M. Pantic. 300 Faces in-the-Wild Challenge: The first facial landmark localization Challenge. Proceedings of IEEE Int’l Conf. on Computer Vision (ICCV-W), 300 Faces in-the-Wild
Get pretrained landmarks model for dlib.
[ "Get", "pretrained", "landmarks", "model", "for", "dlib", "." ]
def get_pretrained_68(folder=None, verbose=True): """Get pretrained landmarks model for dlib. Parameters ---------- folder : str or pathlib.Path or None Folder where to save the .dat file. verbose : bool Print some output. References ---------- [1] C. Sagonas, E. Antonakos, G, Tzimiropoulos, S. Zafeiriou, M. Pantic. 300 faces In-the-wild challenge: Database and results. Image and Vision Computing (IMAVIS), Special Issue on Facial Landmark Localisation "In-The-Wild". 2016. [2] C. Sagonas, G. Tzimiropoulos, S. Zafeiriou, M. Pantic. A semi-automatic methodology for facial landmark annotation. Proceedings of IEEE Int’l Conf. Computer Vision and Pattern Recognition (CVPR-W), 5th Workshop on Analysis and Modeling of Faces and Gestures (AMFG 2013). Oregon, USA, June 2013. [3] C. Sagonas, G. Tzimiropoulos, S. Zafeiriou, M. Pantic. 300 Faces in-the-Wild Challenge: The first facial landmark localization Challenge. Proceedings of IEEE Int’l Conf. on Computer Vision (ICCV-W), 300 Faces in-the-Wild """ url = "https://raw.githubusercontent.com/" url += "davisking/dlib-models/master/shape_predictor_68_face_landmarks.dat.bz2" folder = pathlib.Path(CACHE_FOLDER) if folder is None else pathlib.Path(folder) filepath = folder / "shape_predictor_68_face_landmarks.dat" if filepath.is_file(): return if verbose: print("Downloading and decompressing {} to {}.".format(url, filepath)) req = urllib.request.urlopen(url) CHUNK = 16 * 1024 decompressor = bz2.BZ2Decompressor() with open(str(filepath), 'wb') as fp: while True: chunk = req.read(CHUNK) if not chunk: break fp.write(decompressor.decompress(chunk)) req.close()
[ "def", "get_pretrained_68", "(", "folder", "=", "None", ",", "verbose", "=", "True", ")", ":", "url", "=", "\"https://raw.githubusercontent.com/\"", "url", "+=", "\"davisking/dlib-models/master/shape_predictor_68_face_landmarks.dat.bz2\"", "folder", "=", "pathlib", ".", "...
https://github.com/jankrepl/pychubby/blob/04d8f66273da6f9bd2f85b740681b56ec5c25ddb/pychubby/data.py#L10-L59
malwaredllc/byob
3924dd6aea6d0421397cdf35f692933b340bfccf
web-gui/buildyourownbotnet/modules/miner.py
python
Job.merkle_root_bin
(self, extranounce2_bin)
return merkle_root
Builds a merkle root from the merkle tree
Builds a merkle root from the merkle tree
[ "Builds", "a", "merkle", "root", "from", "the", "merkle", "tree" ]
def merkle_root_bin(self, extranounce2_bin): '''Builds a merkle root from the merkle tree''' coinbase_bin = unhexlify(self._coinb1) + unhexlify(self._extranounce1) + extranounce2_bin + unhexlify(self._coinb2) coinbase_hash_bin = sha256d(coinbase_bin) merkle_root = coinbase_hash_bin for branch in self._merkle_branches: merkle_root = sha256d(merkle_root + unhexlify(branch)) return merkle_root
[ "def", "merkle_root_bin", "(", "self", ",", "extranounce2_bin", ")", ":", "coinbase_bin", "=", "unhexlify", "(", "self", ".", "_coinb1", ")", "+", "unhexlify", "(", "self", ".", "_extranounce1", ")", "+", "extranounce2_bin", "+", "unhexlify", "(", "self", "....
https://github.com/malwaredllc/byob/blob/3924dd6aea6d0421397cdf35f692933b340bfccf/web-gui/buildyourownbotnet/modules/miner.py#L385-L394
pyside/pyside2-setup
d526f801ced4687d5413907a93dedcd782ef72fa
examples/widgets/itemviews/stardelegate/starrating.py
python
StarRating.sizeHint
(self)
return PAINTING_SCALE_FACTOR * QSize(self.maxStarCount, 1)
Tell the caller how big we are.
Tell the caller how big we are.
[ "Tell", "the", "caller", "how", "big", "we", "are", "." ]
def sizeHint(self): """ Tell the caller how big we are. """ return PAINTING_SCALE_FACTOR * QSize(self.maxStarCount, 1)
[ "def", "sizeHint", "(", "self", ")", ":", "return", "PAINTING_SCALE_FACTOR", "*", "QSize", "(", "self", ".", "maxStarCount", ",", "1", ")" ]
https://github.com/pyside/pyside2-setup/blob/d526f801ced4687d5413907a93dedcd782ef72fa/examples/widgets/itemviews/stardelegate/starrating.py#L73-L75
mesonbuild/meson
a22d0f9a0a787df70ce79b05d0c45de90a970048
docs/refman/loaderbase.py
python
_Resolver.__init__
(self)
[]
def __init__(self) -> None: self.type_map: T.Dict[str, Object] = {} self.func_map: T.Dict[str, T.Union[Function, Method]] = {} self.processed_funcs: T.Set[str] = set()
[ "def", "__init__", "(", "self", ")", "->", "None", ":", "self", ".", "type_map", ":", "T", ".", "Dict", "[", "str", ",", "Object", "]", "=", "{", "}", "self", ".", "func_map", ":", "T", ".", "Dict", "[", "str", ",", "T", ".", "Union", "[", "F...
https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/docs/refman/loaderbase.py#L37-L40
dhlab-epfl/dhSegment
cca94e94aec52baa9350eaaa60c006d7fde103b7
dh_segment/io/input_utils.py
python
extract_patches_fn
(image: tf.Tensor, patch_shape: Tuple[int, int], offsets: Tuple[int, int])
Will cut a given image into patches. :param image: tf.Tensor :param patch_shape: shape of the extracted patches [h, w] :param offsets: offset to add to the origin of first patch top-right coordinate, useful during data augmentation \ to have slighlty different patches each time. This value will be multiplied by [h/2, w/2] (range values [0,1]) :return: patches [batch_patches, h, w, c]
Will cut a given image into patches.
[ "Will", "cut", "a", "given", "image", "into", "patches", "." ]
def extract_patches_fn(image: tf.Tensor, patch_shape: Tuple[int, int], offsets: Tuple[int, int]) -> tf.Tensor: """Will cut a given image into patches. :param image: tf.Tensor :param patch_shape: shape of the extracted patches [h, w] :param offsets: offset to add to the origin of first patch top-right coordinate, useful during data augmentation \ to have slighlty different patches each time. This value will be multiplied by [h/2, w/2] (range values [0,1]) :return: patches [batch_patches, h, w, c] """ with tf.name_scope('patch_extraction'): h, w = patch_shape c = image.get_shape()[-1] offset_h = tf.cast(tf.round(offsets[0] * h // 2), dtype=tf.int32) offset_w = tf.cast(tf.round(offsets[1] * w // 2), dtype=tf.int32) offset_img = image[offset_h:, offset_w:, :] offset_img = offset_img[None, :, :, :] patches = tf.extract_image_patches(offset_img, ksizes=[1, h, w, 1], strides=[1, h // 2, w // 2, 1], rates=[1, 1, 1, 1], padding='VALID') patches_shape = tf.shape(patches) return tf.reshape(patches, [tf.reduce_prod(patches_shape[:3]), h, w, int(c)])
[ "def", "extract_patches_fn", "(", "image", ":", "tf", ".", "Tensor", ",", "patch_shape", ":", "Tuple", "[", "int", ",", "int", "]", ",", "offsets", ":", "Tuple", "[", "int", ",", "int", "]", ")", "->", "tf", ".", "Tensor", ":", "with", "tf", ".", ...
https://github.com/dhlab-epfl/dhSegment/blob/cca94e94aec52baa9350eaaa60c006d7fde103b7/dh_segment/io/input_utils.py#L125-L146
huawei-noah/vega
d9f13deede7f2b584e4b1d32ffdb833856129989
vega/core/pipeline/conf.py
python
SearchSpaceConfig.from_dict
(cls, data, skip_check=True)
return cls
Restore config from a dictionary or a file.
Restore config from a dictionary or a file.
[ "Restore", "config", "from", "a", "dictionary", "or", "a", "file", "." ]
def from_dict(cls, data, skip_check=True): """Restore config from a dictionary or a file.""" cls = super(SearchSpaceConfig, cls).from_dict(data, skip_check) if "type" in data and not data["type"]: if hasattr(cls, "hyperparameters"): del cls.hyperparameters return cls
[ "def", "from_dict", "(", "cls", ",", "data", ",", "skip_check", "=", "True", ")", ":", "cls", "=", "super", "(", "SearchSpaceConfig", ",", "cls", ")", ".", "from_dict", "(", "data", ",", "skip_check", ")", "if", "\"type\"", "in", "data", "and", "not", ...
https://github.com/huawei-noah/vega/blob/d9f13deede7f2b584e4b1d32ffdb833856129989/vega/core/pipeline/conf.py#L33-L39
blurstudio/cross3d
277968d1227de740fc87ef61005c75034420eadf
cross3d/softimage/softimagescene.py
python
SoftimageScene.currentFileName
(cls)
return xsi.ActiveProject.ActiveScene.FileName.Value
\remarks implements AbstractScene.currentFileName method to return the current filename for the scene that is active in the application \return <str>
\remarks implements AbstractScene.currentFileName method to return the current filename for the scene that is active in the application \return <str>
[ "\\", "remarks", "implements", "AbstractScene", ".", "currentFileName", "method", "to", "return", "the", "current", "filename", "for", "the", "scene", "that", "is", "active", "in", "the", "application", "\\", "return", "<str", ">" ]
def currentFileName(cls): """ \remarks implements AbstractScene.currentFileName method to return the current filename for the scene that is active in the application \return <str> """ return xsi.ActiveProject.ActiveScene.FileName.Value
[ "def", "currentFileName", "(", "cls", ")", ":", "return", "xsi", ".", "ActiveProject", ".", "ActiveScene", ".", "FileName", ".", "Value" ]
https://github.com/blurstudio/cross3d/blob/277968d1227de740fc87ef61005c75034420eadf/cross3d/softimage/softimagescene.py#L506-L511
keiffster/program-y
8c99b56f8c32f01a7b9887b5daae9465619d0385
src/programy/oob/callmom/map.py
python
MapOutOfBandProcessor.parse_oob_xml
(self, oob: ET.Element)
[]
def parse_oob_xml(self, oob: ET.Element): if oob is not None and oob.text is not None: self._location = oob.text return True else: YLogger.error(self, "Unvalid geomap oob command - missing location text!") return False
[ "def", "parse_oob_xml", "(", "self", ",", "oob", ":", "ET", ".", "Element", ")", ":", "if", "oob", "is", "not", "None", "and", "oob", ".", "text", "is", "not", "None", ":", "self", ".", "_location", "=", "oob", ".", "text", "return", "True", "else"...
https://github.com/keiffster/program-y/blob/8c99b56f8c32f01a7b9887b5daae9465619d0385/src/programy/oob/callmom/map.py#L33-L39
pytoolz/toolz
294e981edad035a7ac6f0e2b48f1738368fa4b34
versioneer.py
python
render_pep440_pre
(pieces)
return rendered
TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE
TAG[.post.devDISTANCE] -- No -dirty.
[ "TAG", "[", ".", "post", ".", "devDISTANCE", "]", "--", "No", "-", "dirty", "." ]
def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exception #1 rendered = "0.post.dev%d" % pieces["distance"] return rendered
[ "def", "render_pep440_pre", "(", "pieces", ")", ":", "if", "pieces", "[", "\"closest-tag\"", "]", ":", "rendered", "=", "pieces", "[", "\"closest-tag\"", "]", "if", "pieces", "[", "\"distance\"", "]", ":", "rendered", "+=", "\".post.dev%d\"", "%", "pieces", ...
https://github.com/pytoolz/toolz/blob/294e981edad035a7ac6f0e2b48f1738368fa4b34/versioneer.py#L1261-L1274
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
examples/client_validation.py
python
example
()
Example of using the ValidationClient for signed requests to Twilio. This is only available to enterprise customers. This will walkthrough creating an API Key, generating an RSA keypair, setting up a ValidationClient with these values and making requests with the client.
Example of using the ValidationClient for signed requests to Twilio. This is only available to enterprise customers.
[ "Example", "of", "using", "the", "ValidationClient", "for", "signed", "requests", "to", "Twilio", ".", "This", "is", "only", "available", "to", "enterprise", "customers", "." ]
def example(): """ Example of using the ValidationClient for signed requests to Twilio. This is only available to enterprise customers. This will walkthrough creating an API Key, generating an RSA keypair, setting up a ValidationClient with these values and making requests with the client. """ client = Client(ACCOUNT_SID, AUTH_TOKEN) # Using Client Validation requires using API Keys for auth # First create an API key using the standard account sid, auth token client print('Creating new api key...') api_key = client.new_keys.create(friendly_name='ClientValidationApiKey') # Generate a new RSA Keypair print('Generating RSA key pair...') key_pair = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend() ) public_key = key_pair.public_key().public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo) private_key = key_pair.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()) # Register the public key with Twilio print('Registering public key with Twilio...') credential = client.accounts.credentials.public_key.create( public_key, friendly_name='ClientValidationPublicKey' ) # Create a new ValidationClient with the keys we created validation_client = ValidationClient( ACCOUNT_SID, api_key.sid, credential.sid, private_key ) # Create a REST Client using the validation_client client = Client(api_key.sid, api_key.secret, ACCOUNT_SID, http_client=validation_client) # Use the library as usual print('Trying out client validation...') messages = client.messages.list(limit=10) for m in messages: print('Message {}'.format(m.sid)) print('Client validation works!')
[ "def", "example", "(", ")", ":", "client", "=", "Client", "(", "ACCOUNT_SID", ",", "AUTH_TOKEN", ")", "# Using Client Validation requires using API Keys for auth", "# First create an API key using the standard account sid, auth token client", "print", "(", "'Creating new api key......
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/examples/client_validation.py#L19-L68
uber/doubles
15e68dcf98f709b19a581915fa6af5ef49ebdd8a
doubles/allowance.py
python
Allowance.__call__
(self, *args, **kwargs)
return self.with_args(*args, **kwargs)
A short hand syntax for with_args Allows callers to do: allow(module).foo.with_args(1, 2) With: allow(module).foo(1, 2) :param args: Any positional arguments required for invocation. :param kwargs: Any keyword arguments required for invocation.
A short hand syntax for with_args
[ "A", "short", "hand", "syntax", "for", "with_args" ]
def __call__(self, *args, **kwargs): """A short hand syntax for with_args Allows callers to do: allow(module).foo.with_args(1, 2) With: allow(module).foo(1, 2) :param args: Any positional arguments required for invocation. :param kwargs: Any keyword arguments required for invocation. """ return self.with_args(*args, **kwargs)
[ "def", "__call__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "with_args", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/allowance.py#L175-L186
uvemas/ViTables
2ce8ec26f85c7392677cf0c7c83ad1ddd7d071e0
vitables/vtwidgets/renamedlg.py
python
RenameDlg.__init__
(self, name, pattern, info)
A customised `QInputDialog`.
A customised `QInputDialog`.
[ "A", "customised", "QInputDialog", "." ]
def __init__(self, name, pattern, info): """A customised `QInputDialog`. """ vtapp = vitables.utils.getVTApp() # Makes the dialog and gives it a layout super(RenameDlg, self).__init__(vtapp.gui) self.setupUi(self) # Sets dialog caption self.setWindowTitle(info[0]) self.generalInfo.setText(info[1]) self.troubled_name = name self.cpattern = re.compile(pattern) # The result returned by this dialog will be contained in the # action dictionary. Its values can be: # If Overwrite --> True, troubled_name # If Rename --> False, new_name # If Cancel --> False, '' self.action = {'overwrite': False, 'new_name': ''} # The dialog buttons: Rename, Overwrite and Cancel self.overwrite_button = self.buttonsBox.addButton( translate('RenameDlg', 'Overwrite', 'A button label'), QtWidgets.QDialogButtonBox.AcceptRole) self.rename_button = self.buttonsBox.addButton( translate('RenameDlg', 'Rename', 'A button label'), QtWidgets.QDialogButtonBox.AcceptRole) self.rename_button.setDefault(1) self.cancel_button = self.buttonsBox.button( QtWidgets.QDialogButtonBox.Cancel) # Setup a validator for checking the entered node name validator = QtGui.QRegExpValidator(self) qt_pattern = QtCore.QRegExp(pattern) validator.setRegExp(qt_pattern) self.valueLE.setValidator(validator) self.valueLE.setText(self.troubled_name) self.valueLE.selectAll() # Make sure that buttons are in the proper activation state self.valueLE.textChanged.emit(self.valueLE.text())
[ "def", "__init__", "(", "self", ",", "name", ",", "pattern", ",", "info", ")", ":", "vtapp", "=", "vitables", ".", "utils", ".", "getVTApp", "(", ")", "# Makes the dialog and gives it a layout", "super", "(", "RenameDlg", ",", "self", ")", ".", "__init__", ...
https://github.com/uvemas/ViTables/blob/2ce8ec26f85c7392677cf0c7c83ad1ddd7d071e0/vitables/vtwidgets/renamedlg.py#L93-L137
robotframework/SeleniumLibrary
0d8caf35cd8325ff391c27fe814744060470018e
src/SeleniumLibrary/keywords/selectelement.py
python
SelectElementKeywords.select_all_from_list
(self, locator: Union[WebElement, str])
Selects all options from multi-selection list ``locator``. See the `Locating elements` section for details about the locator syntax.
Selects all options from multi-selection list ``locator``.
[ "Selects", "all", "options", "from", "multi", "-", "selection", "list", "locator", "." ]
def select_all_from_list(self, locator: Union[WebElement, str]): """Selects all options from multi-selection list ``locator``. See the `Locating elements` section for details about the locator syntax. """ self.info(f"Selecting all options from list '{locator}'.") select = self._get_select_list(locator) if not select.is_multiple: raise RuntimeError( "'Select All From List' works only with multi-selection lists." ) for index in range(len(select.options)): select.select_by_index(index)
[ "def", "select_all_from_list", "(", "self", ",", "locator", ":", "Union", "[", "WebElement", ",", "str", "]", ")", ":", "self", ".", "info", "(", "f\"Selecting all options from list '{locator}'.\"", ")", "select", "=", "self", ".", "_get_select_list", "(", "loca...
https://github.com/robotframework/SeleniumLibrary/blob/0d8caf35cd8325ff391c27fe814744060470018e/src/SeleniumLibrary/keywords/selectelement.py#L193-L206
kamalgill/flask-appengine-template
11760f83faccbb0d0afe416fc58e67ecfb4643c2
src/lib/gae_mini_profiler/util.py
python
short_method_fmt
(s)
return s[s.rfind("/") + 1:]
[]
def short_method_fmt(s): return s[s.rfind("/") + 1:]
[ "def", "short_method_fmt", "(", "s", ")", ":", "return", "s", "[", "s", ".", "rfind", "(", "\"/\"", ")", "+", "1", ":", "]" ]
https://github.com/kamalgill/flask-appengine-template/blob/11760f83faccbb0d0afe416fc58e67ecfb4643c2/src/lib/gae_mini_profiler/util.py#L11-L12
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/graphs/digraph.py
python
DiGraph.in_branchings
(self, source, spanning=True)
return _rec_in_branchings(depth)
r""" Return an iterator over the in branchings rooted at given vertex in ``self``. An in-branching is a directed tree rooted at ``source`` whose arcs are directed to source from leaves. An in-branching is spanning if it contains all vertices of the digraph. If no spanning in branching rooted at ``source`` exist, raises ValueError or return non spanning in branching rooted at ``source``, depending on the value of ``spanning``. INPUT: - ``source`` -- vertex used as the source for all in branchings. - ``spanning`` -- boolean (default: ``True``); if ``False`` return maximum in branching to ``source``. Otherwise, return spanning in branching if exists. OUTPUT: An iterator over the in branchings rooted in the given source. .. SEEALSO:: - :meth:`~sage.graphs.digraph.DiGraph.out_branchings` -- iterator over out-branchings rooted at given vertex. - :meth:`~sage.graphs.graph.Graph.spanning_trees` -- returns all spanning trees. - :meth:`~sage.graphs.generic_graph.GenericGraph.spanning_trees_count` -- counts the number of spanning trees. ALGORITHM: Recursively computes all in branchings. At each step: 0. clean the graph (see below) 1. pick an edge e incoming to source 2. find all in branchings that do not contain e by first removing it 3. find all in branchings that do contain e by first merging the end vertices of e Cleaning the graph implies to remove loops and replace multiedges by a single one with an appropriate label since these lead to similar steps of computation. EXAMPLES: A bidirectional 4-cycle:: sage: G = DiGraph({1:[2,3], 2:[1,4], 3:[1,4], 4:[2,3]}, format='dict_of_lists') sage: list(G.in_branchings(1)) [Digraph on 4 vertices, Digraph on 4 vertices, Digraph on 4 vertices, Digraph on 4 vertices] With the Petersen graph turned into a symmetric directed graph:: sage: G = graphs.PetersenGraph().to_directed() sage: len(list(G.in_branchings(0))) 2000 With a non connected ``DiGraph`` and ``spanning = True``:: sage: G = graphs.PetersenGraph().to_directed() + graphs.PetersenGraph().to_directed() sage: G.in_branchings(0) Traceback (most recent call last): ... ValueError: no spanning in branching to vertex (0) exist With a non connected ``DiGraph`` and ``spanning = False``:: sage: g=DiGraph([(1,0), (1,0), (2,1), (3,4)],multiedges=True) sage: list(g.in_branchings(0,spanning=False)) [Digraph on 3 vertices, Digraph on 3 vertices] With multiedges:: sage: G = DiGraph({0:[1,1,1], 1:[2,2]}, format='dict_of_lists', multiedges=True) sage: len(list(G.in_branchings(2))) 6 With a DiGraph already being a spanning in branching:: sage: G = DiGraph({0:[], 1:[0], 2:[0], 3:[1], 4:[1], 5:[2]}, format='dict_of_lists') sage: next(G.in_branchings(0)) == G True TESTS: The empty ``DiGraph``:: sage: G = DiGraph() sage: G.in_branchings(0) Traceback (most recent call last): ... ValueError: vertex (0) is not a vertex of the digraph sage: edges = [(0,0,'x'), (0,0,'y')] sage: G = DiGraph(edges, multiedges=True, loops=True, weighted=True) sage: list(G.in_branchings(0)) [Digraph on 1 vertex] sage: edges = [(0,1,'x'), (0,1,'y'), (1,2,'z'), (2,0,'w')] sage: G = DiGraph(edges, multiedges=True, loops=True, weighted=True) sage: len(list(G.in_branchings(0))) 1
r""" Return an iterator over the in branchings rooted at given vertex in ``self``.
[ "r", "Return", "an", "iterator", "over", "the", "in", "branchings", "rooted", "at", "given", "vertex", "in", "self", "." ]
def in_branchings(self, source, spanning=True): r""" Return an iterator over the in branchings rooted at given vertex in ``self``. An in-branching is a directed tree rooted at ``source`` whose arcs are directed to source from leaves. An in-branching is spanning if it contains all vertices of the digraph. If no spanning in branching rooted at ``source`` exist, raises ValueError or return non spanning in branching rooted at ``source``, depending on the value of ``spanning``. INPUT: - ``source`` -- vertex used as the source for all in branchings. - ``spanning`` -- boolean (default: ``True``); if ``False`` return maximum in branching to ``source``. Otherwise, return spanning in branching if exists. OUTPUT: An iterator over the in branchings rooted in the given source. .. SEEALSO:: - :meth:`~sage.graphs.digraph.DiGraph.out_branchings` -- iterator over out-branchings rooted at given vertex. - :meth:`~sage.graphs.graph.Graph.spanning_trees` -- returns all spanning trees. - :meth:`~sage.graphs.generic_graph.GenericGraph.spanning_trees_count` -- counts the number of spanning trees. ALGORITHM: Recursively computes all in branchings. At each step: 0. clean the graph (see below) 1. pick an edge e incoming to source 2. find all in branchings that do not contain e by first removing it 3. find all in branchings that do contain e by first merging the end vertices of e Cleaning the graph implies to remove loops and replace multiedges by a single one with an appropriate label since these lead to similar steps of computation. EXAMPLES: A bidirectional 4-cycle:: sage: G = DiGraph({1:[2,3], 2:[1,4], 3:[1,4], 4:[2,3]}, format='dict_of_lists') sage: list(G.in_branchings(1)) [Digraph on 4 vertices, Digraph on 4 vertices, Digraph on 4 vertices, Digraph on 4 vertices] With the Petersen graph turned into a symmetric directed graph:: sage: G = graphs.PetersenGraph().to_directed() sage: len(list(G.in_branchings(0))) 2000 With a non connected ``DiGraph`` and ``spanning = True``:: sage: G = graphs.PetersenGraph().to_directed() + graphs.PetersenGraph().to_directed() sage: G.in_branchings(0) Traceback (most recent call last): ... ValueError: no spanning in branching to vertex (0) exist With a non connected ``DiGraph`` and ``spanning = False``:: sage: g=DiGraph([(1,0), (1,0), (2,1), (3,4)],multiedges=True) sage: list(g.in_branchings(0,spanning=False)) [Digraph on 3 vertices, Digraph on 3 vertices] With multiedges:: sage: G = DiGraph({0:[1,1,1], 1:[2,2]}, format='dict_of_lists', multiedges=True) sage: len(list(G.in_branchings(2))) 6 With a DiGraph already being a spanning in branching:: sage: G = DiGraph({0:[], 1:[0], 2:[0], 3:[1], 4:[1], 5:[2]}, format='dict_of_lists') sage: next(G.in_branchings(0)) == G True TESTS: The empty ``DiGraph``:: sage: G = DiGraph() sage: G.in_branchings(0) Traceback (most recent call last): ... ValueError: vertex (0) is not a vertex of the digraph sage: edges = [(0,0,'x'), (0,0,'y')] sage: G = DiGraph(edges, multiedges=True, loops=True, weighted=True) sage: list(G.in_branchings(0)) [Digraph on 1 vertex] sage: edges = [(0,1,'x'), (0,1,'y'), (1,2,'z'), (2,0,'w')] sage: G = DiGraph(edges, multiedges=True, loops=True, weighted=True) sage: len(list(G.in_branchings(0))) 1 """ def _rec_in_branchings(depth): r""" The recursive function used to enumerate in branchings. This function makes use of the following to keep track of partial in branchings: list_edges -- list of edges in self. list_merged_edges -- list of edges that are currently merged graph -- a copy of self where edges have an appropriate label """ if not depth: # We have enough merged edges to form a in_branching # We iterate over the lists of labels in list_merged_edges and # yield the corresponding in_branchings for indexes in product(*list_merged_edges): yield DiGraph([list_edges[index] for index in indexes], format='list_of_edges', pos=self.get_pos()) # 1) Clean the graph # delete loops on source if any D.delete_edges(D.outgoing_edge_iterator(source)) # merge multi-edges if any by concatenating their labels if D.has_multiple_edges(): merged_multiple_edges = {} for u, v, l in D.multiple_edges(): D.delete_edge(u, v, l) if (u, v) not in merged_multiple_edges: merged_multiple_edges[(u, v)] = l else: merged_multiple_edges[(u, v)] += l D.add_edges([(u, v, l) for (u, v),l in merged_multiple_edges.items()]) # 2) Pick an edge e incoming to the source try: x, s, l = next(D.incoming_edge_iterator(source)) except: return # 3) Find all in_branchings that do not contain e # by first removing it D.delete_edge(x, s, l) if len(list(D.depth_first_search(source, neighbors=D.neighbor_in_iterator))) == depth + 1: for in_branch in _rec_in_branchings(depth): yield in_branch D.add_edge(x, s, l) # 4) Find all in_branchings that do contain e by merging # the end vertices of e # store different edges to unmerged the end vertices of e saved_edges = D.incoming_edges(source) saved_edges.remove((x, s, l)) saved_edges += D.outgoing_edges(x) saved_edges += D.incoming_edges(x) D.merge_vertices((source, x)) list_merged_edges.add(l) for in_branch in _rec_in_branchings(depth - 1): yield in_branch list_merged_edges.remove(l) # unmerge the end vertices of e D.delete_vertex(source) D.add_edges(saved_edges) def _singleton_in_branching(): r""" Returns a DiGraph containing only ``source`` and no edges. """ D = DiGraph() D.add_vertex(source) yield D if not self.has_vertex(source): raise ValueError("vertex ({0}) is not a vertex of the digraph".format(source)) # check if self.order == 1 if self.order() == 1: return _singleton_in_branching() # check if the source can access to every other vertex if spanning: depth = self.order() - 1 if len(list(self.depth_first_search(source, neighbors=self.neighbor_in_iterator))) < self.order(): raise ValueError("no spanning in branching to vertex ({0}) exist".format(source)) else: depth = len(list(self.depth_first_search(source, neighbors=self.neighbor_in_iterator))) - 1 # if vertex is isolated if not depth: return _singleton_in_branching() # We build a copy of self in which each edge has a distinct label. # On the way, we remove loops and edges incoming to source. D = DiGraph(multiedges=True, loops=True) list_edges = list(self.edges(sort=False)) for i, (u, v, _) in enumerate(list_edges): if u != v and u != source: D.add_edge(u, v, (i,)) list_merged_edges = set() return _rec_in_branchings(depth)
[ "def", "in_branchings", "(", "self", ",", "source", ",", "spanning", "=", "True", ")", ":", "def", "_rec_in_branchings", "(", "depth", ")", ":", "r\"\"\"\n The recursive function used to enumerate in branchings.\n\n This function makes use of the following t...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/graphs/digraph.py#L4039-L4254
gdraheim/docker-systemctl-replacement
9cbe1a00eb4bdac6ff05b96ca34ec9ed3d8fc06c
files/docker/systemctl.py
python
Systemctl.reload_modules
(self, *modules)
return self.reload_units(units) and found_all
[UNIT]... -- reload these units
[UNIT]... -- reload these units
[ "[", "UNIT", "]", "...", "--", "reload", "these", "units" ]
def reload_modules(self, *modules): """ [UNIT]... -- reload these units """ self.wait_system() found_all = True units = [] for module in modules: matched = self.match_units(to_list(module)) if not matched: logg.error("Unit %s not found.", unit_of(module)) self.error |= NOT_FOUND found_all = False continue for unit in matched: if unit not in units: units += [ unit ] return self.reload_units(units) and found_all
[ "def", "reload_modules", "(", "self", ",", "*", "modules", ")", ":", "self", ".", "wait_system", "(", ")", "found_all", "=", "True", "units", "=", "[", "]", "for", "module", "in", "modules", ":", "matched", "=", "self", ".", "match_units", "(", "to_lis...
https://github.com/gdraheim/docker-systemctl-replacement/blob/9cbe1a00eb4bdac6ff05b96ca34ec9ed3d8fc06c/files/docker/systemctl.py#L3630-L3645
cvxgrp/cvxportfolio
3985059af9341b58d3f6219280da64e2c85d2749
cvxportfolio/result.py
python
SimulationResult.annual_growth_rate
(self)
return self.growth_rates.sum() * self.PPY / self.growth_rates.size
The annualized growth rate PPY/T sum_{t=1}^T log(v_{t+1}/v_t)
The annualized growth rate PPY/T sum_{t=1}^T log(v_{t+1}/v_t)
[ "The", "annualized", "growth", "rate", "PPY", "/", "T", "sum_", "{", "t", "=", "1", "}", "^T", "log", "(", "v_", "{", "t", "+", "1", "}", "/", "v_t", ")" ]
def annual_growth_rate(self): """The annualized growth rate PPY/T sum_{t=1}^T log(v_{t+1}/v_t) """ return self.growth_rates.sum() * self.PPY / self.growth_rates.size
[ "def", "annual_growth_rate", "(", "self", ")", ":", "return", "self", ".", "growth_rates", ".", "sum", "(", ")", "*", "self", ".", "PPY", "/", "self", ".", "growth_rates", ".", "size" ]
https://github.com/cvxgrp/cvxportfolio/blob/3985059af9341b58d3f6219280da64e2c85d2749/cvxportfolio/result.py#L180-L183
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/logging/config.py
python
_resolve
(name)
return found
Resolve a dotted name to a global object.
Resolve a dotted name to a global object.
[ "Resolve", "a", "dotted", "name", "to", "a", "global", "object", "." ]
def _resolve(name): """Resolve a dotted name to a global object.""" name = name.split('.') used = name.pop(0) found = __import__(used) for n in name: used = used + '.' + n try: found = getattr(found, n) except AttributeError: __import__(used) found = getattr(found, n) return found
[ "def", "_resolve", "(", "name", ")", ":", "name", "=", "name", ".", "split", "(", "'.'", ")", "used", "=", "name", ".", "pop", "(", "0", ")", "found", "=", "__import__", "(", "used", ")", "for", "n", "in", "name", ":", "used", "=", "used", "+",...
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/logging/config.py#L86-L98
lbryio/torba
190304344c0ff68f8a24cf50272307a11bf7f62b
torba/server/daemon.py
python
Daemon.mempool_hashes
(self)
return await self._send_single('getrawmempool')
Update our record of the daemon's mempool hashes.
Update our record of the daemon's mempool hashes.
[ "Update", "our", "record", "of", "the", "daemon", "s", "mempool", "hashes", "." ]
async def mempool_hashes(self): """Update our record of the daemon's mempool hashes.""" return await self._send_single('getrawmempool')
[ "async", "def", "mempool_hashes", "(", "self", ")", ":", "return", "await", "self", ".", "_send_single", "(", "'getrawmempool'", ")" ]
https://github.com/lbryio/torba/blob/190304344c0ff68f8a24cf50272307a11bf7f62b/torba/server/daemon.py#L224-L226