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
IntelPython/sdc
1ebf55c00ef38dfbd401a70b3945e352a5a38b87
sdc/distributed_lower.py
python
setitem_req_array
(context, builder, sig, args)
return builder.call(fn, args)
[]
def setitem_req_array(context, builder, sig, args): fnty = lir.FunctionType(lir.VoidType(), [lir.IntType(8).as_pointer(), lir.IntType(64), mpi_req_llvm_type]) fn = builder.module.get_or_insert_function( fnty, name="req_array_setitem") return builder.call(fn, args)
[ "def", "setitem_req_array", "(", "context", ",", "builder", ",", "sig", ",", "args", ")", ":", "fnty", "=", "lir", ".", "FunctionType", "(", "lir", ".", "VoidType", "(", ")", ",", "[", "lir", ".", "IntType", "(", "8", ")", ".", "as_pointer", "(", "...
https://github.com/IntelPython/sdc/blob/1ebf55c00ef38dfbd401a70b3945e352a5a38b87/sdc/distributed_lower.py#L449-L455
bugy/script-server
9a57ce15903c81bcb537b872f1330ee55ba31563
src/utils/collection_utils.py
python
get_first_existing
(dict, *keys, default=None)
return default
[]
def get_first_existing(dict, *keys, default=None): for key in keys: if key in dict: return dict[key] return default
[ "def", "get_first_existing", "(", "dict", ",", "*", "keys", ",", "default", "=", "None", ")", ":", "for", "key", "in", "keys", ":", "if", "key", "in", "dict", ":", "return", "dict", "[", "key", "]", "return", "default" ]
https://github.com/bugy/script-server/blob/9a57ce15903c81bcb537b872f1330ee55ba31563/src/utils/collection_utils.py#L1-L6
bukun/TorCMS
f7b44e8650aa54774f6b57e7b178edebbbf57e8e
torcms/model/entity_model.py
python
MEntity.create_entity
(uid='', path='', desc='', kind='1')
create entity record in the database.
create entity record in the database.
[ "create", "entity", "record", "in", "the", "database", "." ]
def create_entity(uid='', path='', desc='', kind='1'): ''' create entity record in the database. ''' if path: pass else: return False if uid: pass else: uid = get_uuid() try: TabEntity.create(uid=uid, path=path, desc=desc, time_create=time.time(), kind=kind) return True except Exception as err: print(repr(err)) return False
[ "def", "create_entity", "(", "uid", "=", "''", ",", "path", "=", "''", ",", "desc", "=", "''", ",", "kind", "=", "'1'", ")", ":", "if", "path", ":", "pass", "else", ":", "return", "False", "if", "uid", ":", "pass", "else", ":", "uid", "=", "get...
https://github.com/bukun/TorCMS/blob/f7b44e8650aa54774f6b57e7b178edebbbf57e8e/torcms/model/entity_model.py#L59-L82
racepwn/racepwn
052bf06adb29edecd570ab577fd26e002e2ad9a9
bindings/python/librace.py
python
UserString.index
(self, sub, start=0, end=sys.maxsize)
return self.data.index(sub, start, end)
[]
def index(self, sub, start=0, end=sys.maxsize): return self.data.index(sub, start, end)
[ "def", "index", "(", "self", ",", "sub", ",", "start", "=", "0", ",", "end", "=", "sys", ".", "maxsize", ")", ":", "return", "self", ".", "data", ".", "index", "(", "sub", ",", "start", ",", "end", ")" ]
https://github.com/racepwn/racepwn/blob/052bf06adb29edecd570ab577fd26e002e2ad9a9/bindings/python/librace.py#L125-L126
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_adm_router.py
python
DeploymentConfig.add_volume
(self, volume)
add a volume or volume mount to the proper location
add a volume or volume mount to the proper location
[ "add", "a", "volume", "or", "volume", "mount", "to", "the", "proper", "location" ]
def add_volume(self, volume): ''' add a volume or volume mount to the proper location ''' exist_volumes = self.get_volumes() if not volume: return if not exist_volumes: self.put(DeploymentConfig.volumes_path, [volume]) else: exist_volumes.append(volume)
[ "def", "add_volume", "(", "self", ",", "volume", ")", ":", "exist_volumes", "=", "self", ".", "get_volumes", "(", ")", "if", "not", "volume", ":", "return", "if", "not", "exist_volumes", ":", "self", ".", "put", "(", "DeploymentConfig", ".", "volumes_path"...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_adm_router.py#L2050-L2059
wbond/package_control
cfaaeb57612023e3679ecb7f8cd7ceac9f57990d
package_control/deps/asn1crypto/x509.py
python
Certificate.sha256
(self)
return self._sha256
:return: The SHA-256 hash of the DER-encoded bytes of this complete certificate
:return: The SHA-256 hash of the DER-encoded bytes of this complete certificate
[ ":", "return", ":", "The", "SHA", "-", "256", "hash", "of", "the", "DER", "-", "encoded", "bytes", "of", "this", "complete", "certificate" ]
def sha256(self): """ :return: The SHA-256 hash of the DER-encoded bytes of this complete certificate """ if self._sha256 is None: self._sha256 = hashlib.sha256(self.dump()).digest() return self._sha256
[ "def", "sha256", "(", "self", ")", ":", "if", "self", ".", "_sha256", "is", "None", ":", "self", ".", "_sha256", "=", "hashlib", ".", "sha256", "(", "self", ".", "dump", "(", ")", ")", ".", "digest", "(", ")", "return", "self", ".", "_sha256" ]
https://github.com/wbond/package_control/blob/cfaaeb57612023e3679ecb7f8cd7ceac9f57990d/package_control/deps/asn1crypto/x509.py#L2850-L2859
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
apps/beeswax/gen-py/hive_metastore/ThriftHiveMetastore.py
python
Iface.heartbeat_txn_range
(self, txns)
Parameters: - txns
Parameters: - txns
[ "Parameters", ":", "-", "txns" ]
def heartbeat_txn_range(self, txns): """ Parameters: - txns """ pass
[ "def", "heartbeat_txn_range", "(", "self", ",", "txns", ")", ":", "pass" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/apps/beeswax/gen-py/hive_metastore/ThriftHiveMetastore.py#L1250-L1256
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/integrals/meijerint.py
python
_int0oo_1
(g, x)
return combsimp(unpolarify(res))
Evaluate int_0^\infty g dx using G functions, assuming the necessary conditions are fulfilled. >>> from sympy.abc import a, b, c, d, x, y >>> from sympy import meijerg >>> from sympy.integrals.meijerint import _int0oo_1 >>> _int0oo_1(meijerg([a], [b], [c], [d], x*y), x) gamma(-a)*gamma(c + 1)/(y*gamma(-d)*gamma(b + 1))
Evaluate int_0^\infty g dx using G functions, assuming the necessary conditions are fulfilled.
[ "Evaluate", "int_0^", "\\", "infty", "g", "dx", "using", "G", "functions", "assuming", "the", "necessary", "conditions", "are", "fulfilled", "." ]
def _int0oo_1(g, x): """ Evaluate int_0^\infty g dx using G functions, assuming the necessary conditions are fulfilled. >>> from sympy.abc import a, b, c, d, x, y >>> from sympy import meijerg >>> from sympy.integrals.meijerint import _int0oo_1 >>> _int0oo_1(meijerg([a], [b], [c], [d], x*y), x) gamma(-a)*gamma(c + 1)/(y*gamma(-d)*gamma(b + 1)) """ # See [L, section 5.6.1]. Note that s=1. from sympy import gamma, combsimp, unpolarify eta, _ = _get_coeff_exp(g.argument, x) res = 1/eta # XXX TODO we should reduce order first for b in g.bm: res *= gamma(b + 1) for a in g.an: res *= gamma(1 - a - 1) for b in g.bother: res /= gamma(1 - b - 1) for a in g.aother: res /= gamma(a + 1) return combsimp(unpolarify(res))
[ "def", "_int0oo_1", "(", "g", ",", "x", ")", ":", "# See [L, section 5.6.1]. Note that s=1.", "from", "sympy", "import", "gamma", ",", "combsimp", ",", "unpolarify", "eta", ",", "_", "=", "_get_coeff_exp", "(", "g", ".", "argument", ",", "x", ")", "res", "...
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/integrals/meijerint.py#L825-L849
corenel/pytorch-adda
96f2689dd418ef275fcd0b057e5dff89be5762c5
datasets/usps.py
python
USPS.load_samples
(self)
return images, labels
Load sample images from dataset.
Load sample images from dataset.
[ "Load", "sample", "images", "from", "dataset", "." ]
def load_samples(self): """Load sample images from dataset.""" filename = os.path.join(self.root, self.filename) f = gzip.open(filename, "rb") data_set = pickle.load(f, encoding="bytes") f.close() if self.train: images = data_set[0][0] labels = data_set[0][1] self.dataset_size = labels.shape[0] else: images = data_set[1][0] labels = data_set[1][1] self.dataset_size = labels.shape[0] return images, labels
[ "def", "load_samples", "(", "self", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "self", ".", "root", ",", "self", ".", "filename", ")", "f", "=", "gzip", ".", "open", "(", "filename", ",", "\"rb\"", ")", "data_set", "=", "pickle...
https://github.com/corenel/pytorch-adda/blob/96f2689dd418ef275fcd0b057e5dff89be5762c5/datasets/usps.py#L100-L114
phyllisstein/alp
cbc9e9fa2de19cfd72bc416b9c879b571dc92972
alp/request/requests/cookies.py
python
get_cookie_header
(jar, request)
return r.get_new_headers().get('Cookie')
Produce an appropriate Cookie header string to be sent with `request`, or None.
Produce an appropriate Cookie header string to be sent with `request`, or None.
[ "Produce", "an", "appropriate", "Cookie", "header", "string", "to", "be", "sent", "with", "request", "or", "None", "." ]
def get_cookie_header(jar, request): """Produce an appropriate Cookie header string to be sent with `request`, or None.""" r = MockRequest(request) jar.add_cookie_header(r) return r.get_new_headers().get('Cookie')
[ "def", "get_cookie_header", "(", "jar", ",", "request", ")", ":", "r", "=", "MockRequest", "(", "request", ")", "jar", ".", "add_cookie_header", "(", "r", ")", "return", "r", ".", "get_new_headers", "(", ")", ".", "get", "(", "'Cookie'", ")" ]
https://github.com/phyllisstein/alp/blob/cbc9e9fa2de19cfd72bc416b9c879b571dc92972/alp/request/requests/cookies.py#L108-L112
GluuFederation/community-edition-setup
d0c9427ed9e3ea3d95691677b73c1402ed9ca4db
pylib/ldif3/ldif3.py
python
LDIFParser._check_changetype
(self, dn, changetype, attr_value)
Check changetype attribute for issues.
Check changetype attribute for issues.
[ "Check", "changetype", "attribute", "for", "issues", "." ]
def _check_changetype(self, dn, changetype, attr_value): """Check changetype attribute for issues.""" if dn is None: self._error('Read changetype: before getting valid dn: line.') if changetype is not None: self._error('Two lines starting with changetype: in one record.') if attr_value not in CHANGE_TYPES: self._error('changetype value %s is invalid.' % attr_value)
[ "def", "_check_changetype", "(", "self", ",", "dn", ",", "changetype", ",", "attr_value", ")", ":", "if", "dn", "is", "None", ":", "self", ".", "_error", "(", "'Read changetype: before getting valid dn: line.'", ")", "if", "changetype", "is", "not", "None", ":...
https://github.com/GluuFederation/community-edition-setup/blob/d0c9427ed9e3ea3d95691677b73c1402ed9ca4db/pylib/ldif3/ldif3.py#L342-L349
donnemartin/gitsome
d7c57abc7cb66e9c910a844f15d4536866da3310
xonsh/ply/example/newclasscalc/calc.py
python
Calc.p_expression_name
(self, p)
expression : NAME
expression : NAME
[ "expression", ":", "NAME" ]
def p_expression_name(self, p): 'expression : NAME' try: p[0] = self.names[p[1]] except LookupError: print("Undefined name '%s'" % p[1]) p[0] = 0
[ "def", "p_expression_name", "(", "self", ",", "p", ")", ":", "try", ":", "p", "[", "0", "]", "=", "self", ".", "names", "[", "p", "[", "1", "]", "]", "except", "LookupError", ":", "print", "(", "\"Undefined name '%s'\"", "%", "p", "[", "1", "]", ...
https://github.com/donnemartin/gitsome/blob/d7c57abc7cb66e9c910a844f15d4536866da3310/xonsh/ply/example/newclasscalc/calc.py#L151-L157
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/treebeard/al_tree.py
python
AL_Node.add_sibling
(self, pos=None, **kwargs)
return newobj
Adds a new node as a sibling to the current node object.
Adds a new node as a sibling to the current node object.
[ "Adds", "a", "new", "node", "as", "a", "sibling", "to", "the", "current", "node", "object", "." ]
def add_sibling(self, pos=None, **kwargs): """Adds a new node as a sibling to the current node object.""" pos = self._prepare_pos_var_for_add_sibling(pos) if len(kwargs) == 1 and 'instance' in kwargs: # adding the passed (unsaved) instance to the tree newobj = kwargs['instance'] if newobj.pk: raise NodeAlreadySaved("Attempted to add a tree node that is "\ "already in the database") else: # creating a new object newobj = get_result_class(self.__class__)(**kwargs) if not self.node_order_by: newobj.sib_order = self.__class__._get_new_sibling_order(pos, self) newobj.parent_id = self.parent_id newobj.save() return newobj
[ "def", "add_sibling", "(", "self", ",", "pos", "=", "None", ",", "*", "*", "kwargs", ")", ":", "pos", "=", "self", ".", "_prepare_pos_var_for_add_sibling", "(", "pos", ")", "if", "len", "(", "kwargs", ")", "==", "1", "and", "'instance'", "in", "kwargs"...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/treebeard/al_tree.py#L281-L300
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/pkg_resources/__init__.py
python
ZipManifests.build
(cls, path)
Build a dictionary similar to the zipimport directory caches, except instead of tuples, store ZipInfo objects. Use a platform-specific path separator (os.sep) for the path keys for compatibility with pypy on Windows.
Build a dictionary similar to the zipimport directory caches, except instead of tuples, store ZipInfo objects.
[ "Build", "a", "dictionary", "similar", "to", "the", "zipimport", "directory", "caches", "except", "instead", "of", "tuples", "store", "ZipInfo", "objects", "." ]
def build(cls, path): """ Build a dictionary similar to the zipimport directory caches, except instead of tuples, store ZipInfo objects. Use a platform-specific path separator (os.sep) for the path keys for compatibility with pypy on Windows. """ with ContextualZipFile(path) as zfile: items = ( ( name.replace('/', os.sep), zfile.getinfo(name), ) for name in zfile.namelist() ) return dict(items)
[ "def", "build", "(", "cls", ",", "path", ")", ":", "with", "ContextualZipFile", "(", "path", ")", "as", "zfile", ":", "items", "=", "(", "(", "name", ".", "replace", "(", "'/'", ",", "os", ".", "sep", ")", ",", "zfile", ".", "getinfo", "(", "name...
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/pkg_resources/__init__.py#L1629-L1645
rembo10/headphones
b3199605be1ebc83a7a8feab6b1e99b64014187c
lib/cherrypy/lib/sessions.py
python
FileSession._get_file_path
(self)
return f
[]
def _get_file_path(self): f = os.path.join(self.storage_path, self.SESSION_PREFIX + self.id) if not os.path.abspath(f).startswith(self.storage_path): raise cherrypy.HTTPError(400, "Invalid session id in cookie.") return f
[ "def", "_get_file_path", "(", "self", ")", ":", "f", "=", "os", ".", "path", ".", "join", "(", "self", ".", "storage_path", ",", "self", ".", "SESSION_PREFIX", "+", "self", ".", "id", ")", "if", "not", "os", ".", "path", ".", "abspath", "(", "f", ...
https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/cherrypy/lib/sessions.py#L490-L494
Azure/aztk
8f8e7b268bdbf82c3ae4ecdcd907077bd6fe69b6
aztk/internal/configuration_base.py
python
ConfigurationBase.from_dict
(cls, args: dict)
Create a new model from a dict values The dict is cleaned from null values and passed expanded to the constructor
Create a new model from a dict values The dict is cleaned from null values and passed expanded to the constructor
[ "Create", "a", "new", "model", "from", "a", "dict", "values", "The", "dict", "is", "cleaned", "from", "null", "values", "and", "passed", "expanded", "to", "the", "constructor" ]
def from_dict(cls, args: dict): """ Create a new model from a dict values The dict is cleaned from null values and passed expanded to the constructor """ try: return cls._from_dict(args) except (ValueError, TypeError) as e: pretty_args = yaml.dump(args, default_flow_style=False) raise AztkError("{0} {1}\n{2}".format(cls.__name__, str(e), pretty_args))
[ "def", "from_dict", "(", "cls", ",", "args", ":", "dict", ")", ":", "try", ":", "return", "cls", ".", "_from_dict", "(", "args", ")", "except", "(", "ValueError", ",", "TypeError", ")", "as", "e", ":", "pretty_args", "=", "yaml", ".", "dump", "(", ...
https://github.com/Azure/aztk/blob/8f8e7b268bdbf82c3ae4ecdcd907077bd6fe69b6/aztk/internal/configuration_base.py#L12-L21
andyzsf/TuShare
92787ad0cd492614bdb6389b71a19c80d1c8c9ae
tushare/stock/classifying.py
python
get_concept_classified
()
return data
获取概念分类数据 Return -------- DataFrame code :股票代码 name :股票名称 c_name :概念名称
获取概念分类数据 Return -------- DataFrame code :股票代码 name :股票名称 c_name :概念名称
[ "获取概念分类数据", "Return", "--------", "DataFrame", "code", ":", "股票代码", "name", ":", "股票名称", "c_name", ":", "概念名称" ]
def get_concept_classified(): """ 获取概念分类数据 Return -------- DataFrame code :股票代码 name :股票名称 c_name :概念名称 """ ct._write_head() df = _get_type_data(ct.SINA_CONCEPTS_INDEX_URL%(ct.P_TYPE['http'], ct.DOMAINS['sf'], ct.PAGES['cpt'])) data = [] for row in df.values: rowDf = _get_detail(row[0]) rowDf['c_name'] = row[1] data.append(rowDf) data = pd.concat(data,ignore_index=True) return data
[ "def", "get_concept_classified", "(", ")", ":", "ct", ".", "_write_head", "(", ")", "df", "=", "_get_type_data", "(", "ct", ".", "SINA_CONCEPTS_INDEX_URL", "%", "(", "ct", ".", "P_TYPE", "[", "'http'", "]", ",", "ct", ".", "DOMAINS", "[", "'sf'", "]", ...
https://github.com/andyzsf/TuShare/blob/92787ad0cd492614bdb6389b71a19c80d1c8c9ae/tushare/stock/classifying.py#L49-L68
javayhu/Gank-Alfred-Workflow
aca39bd0c7bc0c494eee204e10bca61dab760ab7
source-v1/workflow/workflow.py
python
LockFile.locked
(self)
return self._locked
`True` if file is locked by this instance.
`True` if file is locked by this instance.
[ "True", "if", "file", "is", "locked", "by", "this", "instance", "." ]
def locked(self): """`True` if file is locked by this instance.""" return self._locked
[ "def", "locked", "(", "self", ")", ":", "return", "self", ".", "_locked" ]
https://github.com/javayhu/Gank-Alfred-Workflow/blob/aca39bd0c7bc0c494eee204e10bca61dab760ab7/source-v1/workflow/workflow.py#L812-L814
volatilityfoundation/volatility3
168b0d0b053ab97a7cb096ef2048795cc54d885f
volatility3/framework/plugins/windows/registry/userassist.py
python
UserAssist.__init__
(self, *args, **kwargs)
[]
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._userassist_size = 0 self._userassist_type_name = "_VOL_USERASSIST_TYPES_7" self._reg_table_name = None self._win7 = None # taken from http://msdn.microsoft.com/en-us/library/dd378457%28v=vs.85%29.aspx self._folder_guids = json.load(open(os.path.join(os.path.dirname(__file__), "userassist.json"), "rb"))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", ")", ".", "__init__", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "_userassist_size", "=", "0", "self", ".", "_userassist_type_name", ...
https://github.com/volatilityfoundation/volatility3/blob/168b0d0b053ab97a7cb096ef2048795cc54d885f/volatility3/framework/plugins/windows/registry/userassist.py#L28-L35
libretro/libretro-database
22062a33c960798c5c0b63ac3fb048752154180d
scripts/FBNeo_dat_gen.py
python
setup_argparse
()
return parser
Set up the argparse arguments and return the argparse instance
Set up the argparse arguments and return the argparse instance
[ "Set", "up", "the", "argparse", "arguments", "and", "return", "the", "argparse", "instance" ]
def setup_argparse(): """Set up the argparse arguments and return the argparse instance""" parser = argparse.ArgumentParser(prog='FBgen.py', description='Generates Final Burn Neo .dat file needed for RetroArch/libretro-db/c_converter') required_arguments = parser.add_argument_group('required arguments') required_arguments.add_argument('-dat', help='Misc -> Generate dat file -> Generate dat (Arcade only)', required=True) required_arguments.add_argument('-path', help='Path to a split, ClrMamePro verified and TorrentZipped ROM set matching the Arcade only dat', required=True) parser.add_argument('-output_file', help='Path to the target output file; example: FBNeo - Arcade games.dat') parser.add_argument('-header_name', help='Override the clrmamepro(name) in the output .dat') parser.add_argument('-header_description', help='Override the clrmamepro(description) in the output .dat') parser.add_argument('-header_version', help='Override the clrmamepro(version) in the output .dat') if len(sys.argv[1:])==0: parser.print_help() print('\n'.join(['', 'example usage: python3 FBA_dat_gen.py -dat "FBNeo v0.2.97.42 (ClrMame Pro ', ' XML).dat" -path "/path/to/split/verified/torrentzipped/roms/" ', ' -output_file "FBNeo - Arcade Games.dat"'])) parser.exit() return parser
[ "def", "setup_argparse", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "'FBgen.py'", ",", "description", "=", "'Generates Final Burn Neo .dat file needed for RetroArch/libretro-db/c_converter'", ")", "required_arguments", "=", "parser", ...
https://github.com/libretro/libretro-database/blob/22062a33c960798c5c0b63ac3fb048752154180d/scripts/FBNeo_dat_gen.py#L66-L84
collinsctk/PyQYT
7af3673955f94ff1b2df2f94220cd2dab2e252af
ExtentionPackages/pysnmp/smi/rfc1902.py
python
ObjectIdentity.addMibSource
(self, *mibSources)
return self
Adds path to repository to search PySNMP MIB files. Parameters ---------- *mibSources : one or more paths to search or Python package names to import and search for PySNMP MIB modules. Returns ------- : :py:class:`~pysnmp.smi.rfc1902.ObjectIdentity` reference to itself Notes ----- Normally, ASN.1-to-Python MIB modules conversion is performed automatically through PySNMP/PySMI interaction. ASN1 MIB modules could also be manually compiled into Python via the `mibdump.py <http://pysmi.sourceforge.net/user-perspective.html>`_ tool. Examples -------- >>> ObjectIdentity('SNMPv2-MIB', 'sysDescr').addMibSource('/opt/pysnmp/mibs', 'pysnmp_mibs') ObjectIdentity('SNMPv2-MIB', 'sysDescr') >>>
Adds path to repository to search PySNMP MIB files.
[ "Adds", "path", "to", "repository", "to", "search", "PySNMP", "MIB", "files", "." ]
def addMibSource(self, *mibSources): """Adds path to repository to search PySNMP MIB files. Parameters ---------- *mibSources : one or more paths to search or Python package names to import and search for PySNMP MIB modules. Returns ------- : :py:class:`~pysnmp.smi.rfc1902.ObjectIdentity` reference to itself Notes ----- Normally, ASN.1-to-Python MIB modules conversion is performed automatically through PySNMP/PySMI interaction. ASN1 MIB modules could also be manually compiled into Python via the `mibdump.py <http://pysmi.sourceforge.net/user-perspective.html>`_ tool. Examples -------- >>> ObjectIdentity('SNMPv2-MIB', 'sysDescr').addMibSource('/opt/pysnmp/mibs', 'pysnmp_mibs') ObjectIdentity('SNMPv2-MIB', 'sysDescr') >>> """ if self.__mibSourcesToAdd is None: self.__mibSourcesToAdd = mibSources else: self.__mibSourcesToAdd += mibSources return self
[ "def", "addMibSource", "(", "self", ",", "*", "mibSources", ")", ":", "if", "self", ".", "__mibSourcesToAdd", "is", "None", ":", "self", ".", "__mibSourcesToAdd", "=", "mibSources", "else", ":", "self", ".", "__mibSourcesToAdd", "+=", "mibSources", "return", ...
https://github.com/collinsctk/PyQYT/blob/7af3673955f94ff1b2df2f94220cd2dab2e252af/ExtentionPackages/pysnmp/smi/rfc1902.py#L240-L273
numba/numba
bf480b9e0da858a65508c2b17759a72ee6a44c51
numba/cpython/numbers.py
python
int_truediv_impl
(context, builder, sig, args)
return impl_ret_untracked(context, builder, sig.return_type, res)
[]
def int_truediv_impl(context, builder, sig, args): [va, vb] = args [ta, tb] = sig.args a = context.cast(builder, va, ta, sig.return_type) b = context.cast(builder, vb, tb, sig.return_type) with cgutils.if_zero(builder, b): context.error_model.fp_zero_division(builder, ("division by zero",)) res = builder.fdiv(a, b) return impl_ret_untracked(context, builder, sig.return_type, res)
[ "def", "int_truediv_impl", "(", "context", ",", "builder", ",", "sig", ",", "args", ")", ":", "[", "va", ",", "vb", "]", "=", "args", "[", "ta", ",", "tb", "]", "=", "sig", ".", "args", "a", "=", "context", ".", "cast", "(", "builder", ",", "va...
https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/cpython/numbers.py#L179-L187
CiscoDevNet/webexteamssdk
673312779b8e05cf0535bea8b96599015cccbff1
webexteamssdk/api/rooms.py
python
RoomsAPI.__init__
(self, session, object_factory)
Initialize a new RoomsAPI object with the provided RestSession. Args: session(RestSession): The RESTful session object to be used for API calls to the Webex Teams service. Raises: TypeError: If the parameter types are incorrect.
Initialize a new RoomsAPI object with the provided RestSession.
[ "Initialize", "a", "new", "RoomsAPI", "object", "with", "the", "provided", "RestSession", "." ]
def __init__(self, session, object_factory): """Initialize a new RoomsAPI object with the provided RestSession. Args: session(RestSession): The RESTful session object to be used for API calls to the Webex Teams service. Raises: TypeError: If the parameter types are incorrect. """ check_type(session, RestSession) super(RoomsAPI, self).__init__() self._session = session self._object_factory = object_factory
[ "def", "__init__", "(", "self", ",", "session", ",", "object_factory", ")", ":", "check_type", "(", "session", ",", "RestSession", ")", "super", "(", "RoomsAPI", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "_session", "=", "session", "self"...
https://github.com/CiscoDevNet/webexteamssdk/blob/673312779b8e05cf0535bea8b96599015cccbff1/webexteamssdk/api/rooms.py#L57-L73
akulakov/django-mcbv
68970eae1733b2b252265d6d1384946f80e23ed8
dbe/mcbv/dates.py
python
WeekMixin.get_next_week
(self, date)
return _get_next_prev(self, date, is_previous=False, period='week')
Get the next valid week.
Get the next valid week.
[ "Get", "the", "next", "valid", "week", "." ]
def get_next_week(self, date): """ Get the next valid week. """ return _get_next_prev(self, date, is_previous=False, period='week')
[ "def", "get_next_week", "(", "self", ",", "date", ")", ":", "return", "_get_next_prev", "(", "self", ",", "date", ",", "is_previous", "=", "False", ",", "period", "=", "'week'", ")" ]
https://github.com/akulakov/django-mcbv/blob/68970eae1733b2b252265d6d1384946f80e23ed8/dbe/mcbv/dates.py#L216-L220
enthought/traitsui
b7c38c7a47bf6ae7971f9ddab70c8a358647dd25
traitsui/table_column.py
python
TableColumn.get_menu
(self, object)
return self.menu
Returns the context menu to display when the user right-clicks on the column for a specified object.
Returns the context menu to display when the user right-clicks on the column for a specified object.
[ "Returns", "the", "context", "menu", "to", "display", "when", "the", "user", "right", "-", "clicks", "on", "the", "column", "for", "a", "specified", "object", "." ]
def get_menu(self, object): """Returns the context menu to display when the user right-clicks on the column for a specified object. """ return self.menu
[ "def", "get_menu", "(", "self", ",", "object", ")", ":", "return", "self", ".", "menu" ]
https://github.com/enthought/traitsui/blob/b7c38c7a47bf6ae7971f9ddab70c8a358647dd25/traitsui/table_column.py#L238-L242
LINKIWI/modern-paste
ecc4168bda2a9e5981d495f9e0538258d9f727a2
app/util/cryptography.py
python
secure_hash
(s, iterations=10000)
return hash_result
Performs several iterations of a SHA256 hash of a plain-text string to generate a secure hash. :param s: Input string to hash :param iterations: Number of hash iterations to use :return: A string representing a secure hash of the string
Performs several iterations of a SHA256 hash of a plain-text string to generate a secure hash.
[ "Performs", "several", "iterations", "of", "a", "SHA256", "hash", "of", "a", "plain", "-", "text", "string", "to", "generate", "a", "secure", "hash", "." ]
def secure_hash(s, iterations=10000): """ Performs several iterations of a SHA256 hash of a plain-text string to generate a secure hash. :param s: Input string to hash :param iterations: Number of hash iterations to use :return: A string representing a secure hash of the string """ hash_result = SHA256.new(data=str(s)).hexdigest() for i in range(iterations): hash_result = SHA256.new(data=hash_result).hexdigest() return hash_result
[ "def", "secure_hash", "(", "s", ",", "iterations", "=", "10000", ")", ":", "hash_result", "=", "SHA256", ".", "new", "(", "data", "=", "str", "(", "s", ")", ")", ".", "hexdigest", "(", ")", "for", "i", "in", "range", "(", "iterations", ")", ":", ...
https://github.com/LINKIWI/modern-paste/blob/ecc4168bda2a9e5981d495f9e0538258d9f727a2/app/util/cryptography.py#L98-L109
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/sqlalchemy/sql/type_api.py
python
Variant.__init__
(self, base, mapping)
Construct a new :class:`.Variant`. :param base: the base 'fallback' type :param mapping: dictionary of string dialect names to :class:`.TypeEngine` instances.
Construct a new :class:`.Variant`.
[ "Construct", "a", "new", ":", "class", ":", ".", "Variant", "." ]
def __init__(self, base, mapping): """Construct a new :class:`.Variant`. :param base: the base 'fallback' type :param mapping: dictionary of string dialect names to :class:`.TypeEngine` instances. """ self.impl = base self.mapping = mapping
[ "def", "__init__", "(", "self", ",", "base", ",", "mapping", ")", ":", "self", ".", "impl", "=", "base", "self", ".", "mapping", "=", "mapping" ]
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/sqlalchemy/sql/type_api.py#L994-L1003
jython/jython3
def4f8ec47cb7a9c799ea4c745f12badf92c5769
lib-python/3.5.1/distutils/command/install.py
python
install.get_outputs
(self)
return outputs
Assembles the outputs of all the sub-commands.
Assembles the outputs of all the sub-commands.
[ "Assembles", "the", "outputs", "of", "all", "the", "sub", "-", "commands", "." ]
def get_outputs(self): """Assembles the outputs of all the sub-commands.""" outputs = [] for cmd_name in self.get_sub_commands(): cmd = self.get_finalized_command(cmd_name) # Add the contents of cmd.get_outputs(), ensuring # that outputs doesn't contain duplicate entries for filename in cmd.get_outputs(): if filename not in outputs: outputs.append(filename) if self.path_file and self.install_path_file: outputs.append(os.path.join(self.install_libbase, self.path_file + ".pth")) return outputs
[ "def", "get_outputs", "(", "self", ")", ":", "outputs", "=", "[", "]", "for", "cmd_name", "in", "self", ".", "get_sub_commands", "(", ")", ":", "cmd", "=", "self", ".", "get_finalized_command", "(", "cmd_name", ")", "# Add the contents of cmd.get_outputs(), ensu...
https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/lib-python/3.5.1/distutils/command/install.py#L593-L608
nate-parrott/Flashlight
c3a7c7278a1cccf8918e7543faffc68e863ff5ab
flashlightsearchrelay/requests/packages/urllib3/util.py
python
parse_url
(url)
return Url(scheme, auth, host, port, path, query, fragment)
Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is performed to parse incomplete urls. Fields not provided will be None. Partly backwards-compatible with :mod:`urlparse`. Example: :: >>> parse_url('http://google.com/mail/') Url(scheme='http', host='google.com', port=None, path='/', ...) >>> parse_url('google.com:80') Url(scheme=None, host='google.com', port=80, path=None, ...) >>> parse_url('/foo?bar') Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)
Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is performed to parse incomplete urls. Fields not provided will be None.
[ "Given", "a", "url", "return", "a", "parsed", ":", "class", ":", ".", "Url", "namedtuple", ".", "Best", "-", "effort", "is", "performed", "to", "parse", "incomplete", "urls", ".", "Fields", "not", "provided", "will", "be", "None", "." ]
def parse_url(url): """ Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is performed to parse incomplete urls. Fields not provided will be None. Partly backwards-compatible with :mod:`urlparse`. Example: :: >>> parse_url('http://google.com/mail/') Url(scheme='http', host='google.com', port=None, path='/', ...) >>> parse_url('google.com:80') Url(scheme=None, host='google.com', port=80, path=None, ...) >>> parse_url('/foo?bar') Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...) """ # While this code has overlap with stdlib's urlparse, it is much # simplified for our needs and less annoying. # Additionally, this implementations does silly things to be optimal # on CPython. scheme = None auth = None host = None port = None path = None fragment = None query = None # Scheme if '://' in url: scheme, url = url.split('://', 1) # Find the earliest Authority Terminator # (http://tools.ietf.org/html/rfc3986#section-3.2) url, path_, delim = split_first(url, ['/', '?', '#']) if delim: # Reassemble the path path = delim + path_ # Auth if '@' in url: # Last '@' denotes end of auth part auth, url = url.rsplit('@', 1) # IPv6 if url and url[0] == '[': host, url = url.split(']', 1) host += ']' # Port if ':' in url: _host, port = url.split(':', 1) if not host: host = _host if port: # If given, ports must be integers. if not port.isdigit(): raise LocationParseError("Failed to parse: %s" % url) port = int(port) else: # Blank ports are cool, too. (rfc3986#section-3.2.3) port = None elif not host and url: host = url if not path: return Url(scheme, auth, host, port, path, query, fragment) # Fragment if '#' in path: path, fragment = path.split('#', 1) # Query if '?' in path: path, query = path.split('?', 1) return Url(scheme, auth, host, port, path, query, fragment)
[ "def", "parse_url", "(", "url", ")", ":", "# While this code has overlap with stdlib's urlparse, it is much", "# simplified for our needs and less annoying.", "# Additionally, this implementations does silly things to be optimal", "# on CPython.", "scheme", "=", "None", "auth", "=", "N...
https://github.com/nate-parrott/Flashlight/blob/c3a7c7278a1cccf8918e7543faffc68e863ff5ab/flashlightsearchrelay/requests/packages/urllib3/util.py#L335-L417
rdiff-backup/rdiff-backup
321e0cd6e5e47d4c158a0172e47ab38240a8b653
src/rdiff_backup/rpath.py
python
RORPath.has_carbonfile
(self)
return 'carbonfile' in self.data
True if rpath has a carbonfile parameter
True if rpath has a carbonfile parameter
[ "True", "if", "rpath", "has", "a", "carbonfile", "parameter" ]
def has_carbonfile(self): """True if rpath has a carbonfile parameter""" return 'carbonfile' in self.data
[ "def", "has_carbonfile", "(", "self", ")", ":", "return", "'carbonfile'", "in", "self", ".", "data" ]
https://github.com/rdiff-backup/rdiff-backup/blob/321e0cd6e5e47d4c158a0172e47ab38240a8b653/src/rdiff_backup/rpath.py#L481-L483
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-darwin/x64/cryptography/hazmat/backends/openssl/aead.py
python
_aead_cipher_name
(cipher)
[]
def _aead_cipher_name(cipher): from cryptography.hazmat.primitives.ciphers.aead import ( AESCCM, AESGCM, ChaCha20Poly1305 ) if isinstance(cipher, ChaCha20Poly1305): return b"chacha20-poly1305" elif isinstance(cipher, AESCCM): return "aes-{0}-ccm".format(len(cipher._key) * 8).encode("ascii") else: assert isinstance(cipher, AESGCM) return "aes-{0}-gcm".format(len(cipher._key) * 8).encode("ascii")
[ "def", "_aead_cipher_name", "(", "cipher", ")", ":", "from", "cryptography", ".", "hazmat", ".", "primitives", ".", "ciphers", ".", "aead", "import", "(", "AESCCM", ",", "AESGCM", ",", "ChaCha20Poly1305", ")", "if", "isinstance", "(", "cipher", ",", "ChaCha2...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-darwin/x64/cryptography/hazmat/backends/openssl/aead.py#L14-L24
YonghaoHe/LFFD-A-Light-and-Fast-Face-Detector-for-Edge-Devices
529203dc07b1bd435a82907872f37d4c0c3b6807
ChasingTrainFramework_GeneralOneClassDetection/data_provider_base/base_provider.py
python
ProviderBaseclass.write
(self)
Write a single sample to the files :return:
Write a single sample to the files :return:
[ "Write", "a", "single", "sample", "to", "the", "files", ":", "return", ":" ]
def write(self): """ Write a single sample to the files :return: """ raise NotImplementedError()
[ "def", "write", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/YonghaoHe/LFFD-A-Light-and-Fast-Face-Detector-for-Edge-Devices/blob/529203dc07b1bd435a82907872f37d4c0c3b6807/ChasingTrainFramework_GeneralOneClassDetection/data_provider_base/base_provider.py#L21-L26
etetoolkit/ete
2b207357dc2a40ccad7bfd8f54964472c72e4726
ete3/tools/ete_build_lib/workflow/supermatrix.py
python
pipeline
(task, wkname, conf=None)
return new_tasks
[]
def pipeline(task, wkname, conf=None): logindent(2) # Points to npr parameters according to task properties if not task: source_seqtype = "aa" if "aa" in GLOBALS["seqtypes"] else "nt" npr_conf = IterConfig(conf, wkname, len(GLOBALS["target_species"]), source_seqtype) cogconf, cogclass = npr_conf.cog_selector initial_task = cogclass(GLOBALS["target_species"], set(), source_seqtype, conf, cogconf) initial_task.main_tree = main_tree = None initial_task.threadid = generate_runid() initial_task.configid = initial_task.threadid initial_task.target_wkname = wkname # Register node db.add_node(initial_task.threadid, initial_task.nodeid, initial_task.cladeid, initial_task.targets, initial_task.outgroups) new_tasks = [initial_task] else: conf = GLOBALS[task.configid] npr_conf = IterConfig(conf, wkname, task.size, task.seqtype) new_tasks = process_task(task, wkname, npr_conf, conf['_nodeinfo']) process_new_tasks(task, new_tasks, conf) logindent(-2) return new_tasks
[ "def", "pipeline", "(", "task", ",", "wkname", ",", "conf", "=", "None", ")", ":", "logindent", "(", "2", ")", "# Points to npr parameters according to task properties", "if", "not", "task", ":", "source_seqtype", "=", "\"aa\"", "if", "\"aa\"", "in", "GLOBALS", ...
https://github.com/etetoolkit/ete/blob/2b207357dc2a40ccad7bfd8f54964472c72e4726/ete3/tools/ete_build_lib/workflow/supermatrix.py#L255-L286
coreemu/core
7e18a7a72023a69a92ad61d87461bd659ba27f7c
daemon/core/api/grpc/server.py
python
CoreGrpcServer.GetEmaneModelConfigs
( self, request: GetEmaneModelConfigsRequest, context: ServicerContext )
return GetEmaneModelConfigsResponse(configs=configs)
Retrieve all EMANE model configurations of a session :param request: get-EMANE-model-configurations request :param context: context object :return: get-EMANE-model-configurations response that has all the EMANE configurations
Retrieve all EMANE model configurations of a session
[ "Retrieve", "all", "EMANE", "model", "configurations", "of", "a", "session" ]
def GetEmaneModelConfigs( self, request: GetEmaneModelConfigsRequest, context: ServicerContext ) -> GetEmaneModelConfigsResponse: """ Retrieve all EMANE model configurations of a session :param request: get-EMANE-model-configurations request :param context: context object :return: get-EMANE-model-configurations response that has all the EMANE configurations """ logging.debug("get emane model configs: %s", request) session = self.get_session(request.session_id, context) configs = grpcutils.get_emane_model_configs(session) return GetEmaneModelConfigsResponse(configs=configs)
[ "def", "GetEmaneModelConfigs", "(", "self", ",", "request", ":", "GetEmaneModelConfigsRequest", ",", "context", ":", "ServicerContext", ")", "->", "GetEmaneModelConfigsResponse", ":", "logging", ".", "debug", "(", "\"get emane model configs: %s\"", ",", "request", ")", ...
https://github.com/coreemu/core/blob/7e18a7a72023a69a92ad61d87461bd659ba27f7c/daemon/core/api/grpc/server.py#L1461-L1476
RodrigoGantier/Mask_R_CNN_Keypoints
6b22e72de01ae98eaa1acd8645e5dbe3a096459f
model.py
python
smooth_l1_loss
(y_true, y_pred)
return loss
Implements Smooth-L1 loss. y_true and y_pred are typicallly: [N, 4], but could be any shape.
Implements Smooth-L1 loss. y_true and y_pred are typicallly: [N, 4], but could be any shape.
[ "Implements", "Smooth", "-", "L1", "loss", ".", "y_true", "and", "y_pred", "are", "typicallly", ":", "[", "N", "4", "]", "but", "could", "be", "any", "shape", "." ]
def smooth_l1_loss(y_true, y_pred): """Implements Smooth-L1 loss. y_true and y_pred are typicallly: [N, 4], but could be any shape. """ diff = K.abs(y_true - y_pred) less_than_one = K.cast(K.less(diff, 1.0), "float32") loss = (less_than_one * 0.5 * diff ** 2) + (1 - less_than_one) * (diff - 0.5) return loss
[ "def", "smooth_l1_loss", "(", "y_true", ",", "y_pred", ")", ":", "diff", "=", "K", ".", "abs", "(", "y_true", "-", "y_pred", ")", "less_than_one", "=", "K", ".", "cast", "(", "K", ".", "less", "(", "diff", ",", "1.0", ")", ",", "\"float32\"", ")", ...
https://github.com/RodrigoGantier/Mask_R_CNN_Keypoints/blob/6b22e72de01ae98eaa1acd8645e5dbe3a096459f/model.py#L901-L908
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/clb/v20180317/models.py
python
DescribeRewriteRequest.__init__
(self)
r""" :param LoadBalancerId: 负载均衡实例ID。 :type LoadBalancerId: str :param SourceListenerIds: 负载均衡监听器ID数组。 :type SourceListenerIds: list of str :param SourceLocationIds: 负载均衡转发规则的ID数组。 :type SourceLocationIds: list of str
r""" :param LoadBalancerId: 负载均衡实例ID。 :type LoadBalancerId: str :param SourceListenerIds: 负载均衡监听器ID数组。 :type SourceListenerIds: list of str :param SourceLocationIds: 负载均衡转发规则的ID数组。 :type SourceLocationIds: list of str
[ "r", ":", "param", "LoadBalancerId", ":", "负载均衡实例ID。", ":", "type", "LoadBalancerId", ":", "str", ":", "param", "SourceListenerIds", ":", "负载均衡监听器ID数组。", ":", "type", "SourceListenerIds", ":", "list", "of", "str", ":", "param", "SourceLocationIds", ":", "负载均衡转发规...
def __init__(self): r""" :param LoadBalancerId: 负载均衡实例ID。 :type LoadBalancerId: str :param SourceListenerIds: 负载均衡监听器ID数组。 :type SourceListenerIds: list of str :param SourceLocationIds: 负载均衡转发规则的ID数组。 :type SourceLocationIds: list of str """ self.LoadBalancerId = None self.SourceListenerIds = None self.SourceLocationIds = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "LoadBalancerId", "=", "None", "self", ".", "SourceListenerIds", "=", "None", "self", ".", "SourceLocationIds", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/clb/v20180317/models.py#L3700-L3711
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/states/git.py
python
cloned
( name, target, branch=None, user=None, password=None, identity=None, https_user=None, https_pass=None, output_encoding=None, )
.. versionadded:: 2018.3.3,2019.2.0 Ensure that a repository has been cloned to the specified target directory. If not, clone that repository. No fetches will be performed once cloned. name Address of the remote repository target Name of the target directory where repository should be cloned branch Remote branch to check out. If unspecified, the default branch (i.e. the one to the remote HEAD points) will be checked out. .. note:: The local branch name will match the remote branch name. If the branch name is changed, then that branch will be checked out locally, but keep in mind that remote repository will not be fetched. If your use case requires that you keep the clone up to date with the remote repository, then consider using :py:func:`git.latest <salt.states.git.latest>`. user User under which to run git commands. By default, commands are run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. identity Path to a private key to use for ssh URLs. Works the same way as in :py:func:`git.latest <salt.states.git.latest>`, see that state's documentation for more information. https_user HTTP Basic Auth username for HTTPS (only) clones https_pass HTTP Basic Auth password for HTTPS (only) clones output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters.
.. versionadded:: 2018.3.3,2019.2.0
[ "..", "versionadded", "::", "2018", ".", "3", ".", "3", "2019", ".", "2", ".", "0" ]
def cloned( name, target, branch=None, user=None, password=None, identity=None, https_user=None, https_pass=None, output_encoding=None, ): """ .. versionadded:: 2018.3.3,2019.2.0 Ensure that a repository has been cloned to the specified target directory. If not, clone that repository. No fetches will be performed once cloned. name Address of the remote repository target Name of the target directory where repository should be cloned branch Remote branch to check out. If unspecified, the default branch (i.e. the one to the remote HEAD points) will be checked out. .. note:: The local branch name will match the remote branch name. If the branch name is changed, then that branch will be checked out locally, but keep in mind that remote repository will not be fetched. If your use case requires that you keep the clone up to date with the remote repository, then consider using :py:func:`git.latest <salt.states.git.latest>`. user User under which to run git commands. By default, commands are run by the user under which the minion is running. password Windows only. Required when specifying ``user``. This parameter will be ignored on non-Windows platforms. identity Path to a private key to use for ssh URLs. Works the same way as in :py:func:`git.latest <salt.states.git.latest>`, see that state's documentation for more information. https_user HTTP Basic Auth username for HTTPS (only) clones https_pass HTTP Basic Auth password for HTTPS (only) clones output_encoding Use this option to specify which encoding to use to decode the output from any git commands which are run. This should not be needed in most cases. .. note:: This should only be needed if the files in the repository were created with filenames using an encoding other than UTF-8 to handle Unicode characters. """ ret = {"name": name, "result": False, "comment": "", "changes": {}} if target is None: ret["comment"] = "'target' argument is required" return ret elif not isinstance(target, str): target = str(target) if not os.path.isabs(target): ret["comment"] = "'target' path must be absolute" return ret if branch is not None: if not isinstance(branch, str): branch = str(branch) if not branch: ret["comment"] = "Invalid 'branch' argument" return ret if not os.path.exists(target): need_clone = True else: try: __salt__["git.status"]( target, user=user, password=password, output_encoding=output_encoding ) except Exception as exc: # pylint: disable=broad-except ret["comment"] = str(exc) return ret else: need_clone = False comments = [] def _clone_changes(ret): ret["changes"]["new"] = name + " => " + target def _branch_changes(ret, old, new): ret["changes"]["branch"] = {"old": old, "new": new} if need_clone: if __opts__["test"]: _clone_changes(ret) comment = "{} would be cloned to {}{}".format( name, target, " with branch '{}'".format(branch) if branch is not None else "", ) return _neutral_test(ret, comment) clone_opts = ["--branch", branch] if branch is not None else None try: __salt__["git.clone"]( target, name, opts=clone_opts, user=user, password=password, identity=identity, https_user=https_user, https_pass=https_pass, output_encoding=output_encoding, ) except CommandExecutionError as exc: msg = "Clone failed: {}".format(_strip_exc(exc)) return _fail(ret, msg, comments) comments.append( "{} cloned to {}{}".format( name, target, " with branch '{}'".format(branch) if branch is not None else "", ) ) _clone_changes(ret) ret["comment"] = _format_comments(comments) ret["result"] = True return ret else: if branch is None: return _already_cloned(ret, target, branch, comments) else: current_branch = __salt__["git.current_branch"]( target, user=user, password=password, output_encoding=output_encoding ) if current_branch == branch: return _already_cloned(ret, target, branch, comments) else: if __opts__["test"]: _branch_changes(ret, current_branch, branch) return _neutral_test( ret, "Branch would be changed to '{}'".format(branch) ) try: __salt__["git.rev_parse"]( target, rev=branch, user=user, password=password, ignore_retcode=True, output_encoding=output_encoding, ) except CommandExecutionError: # Local head does not exist, so we need to check out a new # branch at the remote rev checkout_rev = "/".join(("origin", branch)) checkout_opts = ["-b", branch] else: # Local head exists, so we just need to check it out checkout_rev = branch checkout_opts = None try: __salt__["git.checkout"]( target, rev=checkout_rev, opts=checkout_opts, user=user, password=password, output_encoding=output_encoding, ) except CommandExecutionError as exc: msg = "Failed to change branch to '{}': {}".format(branch, exc) return _fail(ret, msg, comments) else: comments.append("Branch changed to '{}'".format(branch)) _branch_changes(ret, current_branch, branch) ret["comment"] = _format_comments(comments) ret["result"] = True return ret
[ "def", "cloned", "(", "name", ",", "target", ",", "branch", "=", "None", ",", "user", "=", "None", ",", "password", "=", "None", ",", "identity", "=", "None", ",", "https_user", "=", "None", ",", "https_pass", "=", "None", ",", "output_encoding", "=", ...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/states/git.py#L2636-L2828
facebookresearch/pytorch3d
fddd6a700fa9685c1ce2d4b266c111d7db424ecc
pytorch3d/transforms/se3.py
python
_se3_V_matrix
( log_rotation: torch.Tensor, log_rotation_hat: torch.Tensor, log_rotation_hat_square: torch.Tensor, rotation_angles: torch.Tensor, eps: float = 1e-4, )
return V
A helper function that computes the "V" matrix from [1], Sec 9.4.2. [1] https://jinyongjeong.github.io/Download/SE3/jlblanco2010geometry3d_techrep.pdf
A helper function that computes the "V" matrix from [1], Sec 9.4.2. [1] https://jinyongjeong.github.io/Download/SE3/jlblanco2010geometry3d_techrep.pdf
[ "A", "helper", "function", "that", "computes", "the", "V", "matrix", "from", "[", "1", "]", "Sec", "9", ".", "4", ".", "2", ".", "[", "1", "]", "https", ":", "//", "jinyongjeong", ".", "github", ".", "io", "/", "Download", "/", "SE3", "/", "jlbla...
def _se3_V_matrix( log_rotation: torch.Tensor, log_rotation_hat: torch.Tensor, log_rotation_hat_square: torch.Tensor, rotation_angles: torch.Tensor, eps: float = 1e-4, ) -> torch.Tensor: """ A helper function that computes the "V" matrix from [1], Sec 9.4.2. [1] https://jinyongjeong.github.io/Download/SE3/jlblanco2010geometry3d_techrep.pdf """ V = ( torch.eye(3, dtype=log_rotation.dtype, device=log_rotation.device)[None] + log_rotation_hat * ((1 - torch.cos(rotation_angles)) / (rotation_angles ** 2))[:, None, None] + ( log_rotation_hat_square * ((rotation_angles - torch.sin(rotation_angles)) / (rotation_angles ** 3))[ :, None, None ] ) ) return V
[ "def", "_se3_V_matrix", "(", "log_rotation", ":", "torch", ".", "Tensor", ",", "log_rotation_hat", ":", "torch", ".", "Tensor", ",", "log_rotation_hat_square", ":", "torch", ".", "Tensor", ",", "rotation_angles", ":", "torch", ".", "Tensor", ",", "eps", ":", ...
https://github.com/facebookresearch/pytorch3d/blob/fddd6a700fa9685c1ce2d4b266c111d7db424ecc/pytorch3d/transforms/se3.py#L182-L206
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_configmap.py
python
OpenShiftCLI._replace
(self, fname, force=False)
return self.openshift_cmd(cmd)
replace the current object with oc replace
replace the current object with oc replace
[ "replace", "the", "current", "object", "with", "oc", "replace" ]
def _replace(self, fname, force=False): '''replace the current object with oc replace''' # We are removing the 'resourceVersion' to handle # a race condition when modifying oc objects yed = Yedit(fname) results = yed.delete('metadata.resourceVersion') if results[0]: yed.write() cmd = ['replace', '-f', fname] if force: cmd.append('--force') return self.openshift_cmd(cmd)
[ "def", "_replace", "(", "self", ",", "fname", ",", "force", "=", "False", ")", ":", "# We are removing the 'resourceVersion' to handle", "# a race condition when modifying oc objects", "yed", "=", "Yedit", "(", "fname", ")", "results", "=", "yed", ".", "delete", "("...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_configmap.py#L918-L930
sqlmapproject/sqlmap
3b07b70864624dff4c29dcaa8a61c78e7f9189f7
lib/core/common.py
python
firstNotNone
(*args)
return retVal
Returns first not-None value from a given list of arguments >>> firstNotNone(None, None, 1, 2, 3) 1
Returns first not-None value from a given list of arguments
[ "Returns", "first", "not", "-", "None", "value", "from", "a", "given", "list", "of", "arguments" ]
def firstNotNone(*args): """ Returns first not-None value from a given list of arguments >>> firstNotNone(None, None, 1, 2, 3) 1 """ retVal = None for _ in args: if _ is not None: retVal = _ break return retVal
[ "def", "firstNotNone", "(", "*", "args", ")", ":", "retVal", "=", "None", "for", "_", "in", "args", ":", "if", "_", "is", "not", "None", ":", "retVal", "=", "_", "break", "return", "retVal" ]
https://github.com/sqlmapproject/sqlmap/blob/3b07b70864624dff4c29dcaa8a61c78e7f9189f7/lib/core/common.py#L5437-L5452
eirannejad/pyRevit
49c0b7eb54eb343458ce1365425e6552d0c47d44
pyrevitlib/pyrevit/coreutils/markdown/blockprocessors.py
python
BlockProcessor.test
(self, parent, block)
Test for block type. Must be overridden by subclasses. As the parser loops through processors, it will call the ``test`` method on each to determine if the given block of text is of that type. This method must return a boolean ``True`` or ``False``. The actual method of testing is left to the needs of that particular block type. It could be as simple as ``block.startswith(some_string)`` or a complex regular expression. As the block type may be different depending on the parent of the block (i.e. inside a list), the parent etree element is also provided and may be used as part of the test. Keywords: * ``parent``: A etree element which will be the parent of the block. * ``block``: A block of text from the source which has been split at blank lines.
Test for block type. Must be overridden by subclasses.
[ "Test", "for", "block", "type", ".", "Must", "be", "overridden", "by", "subclasses", "." ]
def test(self, parent, block): """ Test for block type. Must be overridden by subclasses. As the parser loops through processors, it will call the ``test`` method on each to determine if the given block of text is of that type. This method must return a boolean ``True`` or ``False``. The actual method of testing is left to the needs of that particular block type. It could be as simple as ``block.startswith(some_string)`` or a complex regular expression. As the block type may be different depending on the parent of the block (i.e. inside a list), the parent etree element is also provided and may be used as part of the test. Keywords: * ``parent``: A etree element which will be the parent of the block. * ``block``: A block of text from the source which has been split at blank lines. """ pass
[ "def", "test", "(", "self", ",", "parent", ",", "block", ")", ":", "pass" ]
https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/pyrevitlib/pyrevit/coreutils/markdown/blockprocessors.py#L86-L104
evennia/evennia
fa79110ba6b219932f22297838e8ac72ebc0be0e
evennia/web/website/views.py
python
ChannelDetailView.get_context_data
(self, **kwargs)
return context
Django hook; before we can display the channel logs, we need to recall the logfile and read its lines. Returns: context (dict): Django context object
Django hook; before we can display the channel logs, we need to recall the logfile and read its lines.
[ "Django", "hook", ";", "before", "we", "can", "display", "the", "channel", "logs", "we", "need", "to", "recall", "the", "logfile", "and", "read", "its", "lines", "." ]
def get_context_data(self, **kwargs): """ Django hook; before we can display the channel logs, we need to recall the logfile and read its lines. Returns: context (dict): Django context object """ # Get the parent context object, necessary first step context = super(ChannelDetailView, self).get_context_data(**kwargs) # Get the filename this Channel is recording to filename = self.object.attributes.get( "log_file", default="channel_%s.log" % self.object.key ) # Split log entries so we can filter by time bucket = [] for log in (x.strip() for x in tail_log_file(filename, 0, self.max_num_lines)): if not log: continue try: time, msg = log.split(" [-] ") time_key = time.split(":")[0] except ValueError: # malformed log line - skip line continue bucket.append({"key": time_key, "timestamp": time, "message": msg}) # Add the processed entries to the context context["object_list"] = bucket # Get a list of unique timestamps by hour and sort them context["object_filters"] = sorted(set([x["key"] for x in bucket])) return context
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Get the parent context object, necessary first step", "context", "=", "super", "(", "ChannelDetailView", ",", "self", ")", ".", "get_context_data", "(", "*", "*", "kwargs", ")", "# Get t...
https://github.com/evennia/evennia/blob/fa79110ba6b219932f22297838e8ac72ebc0be0e/evennia/web/website/views.py#L917-L953
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter3-Decision_tree/decision_tree.py
python
createDataSet
()
return dataSet,labels
函数说明:创建测试数据集 参数:无 return: dataSet-数据集 labels-分类属性
函数说明:创建测试数据集 参数:无 return: dataSet-数据集 labels-分类属性
[ "函数说明:创建测试数据集", "参数:无", "return", ":", "dataSet", "-", "数据集", "labels", "-", "分类属性" ]
def createDataSet(): """ 函数说明:创建测试数据集 参数:无 return: dataSet-数据集 labels-分类属性 """ dataSet = [ [0,0,0,0,'no'], [0,0,0,1,'no'], [0,1,0,1,'yes'], [0,1,1,0,'yes'], [0,0,0,0,'no'], [1,0,0,0,'no'], [1,0,0,1,'no'], [1,1,1,1,'yes'], [1,0,1,1,'yes'], [1,0,1,2,'yes'], [2,0,1,2,'yes'], [2,0,1,1,'yes'], [2,1,0,1,'yes'], [2,1,0,2,'yes'], [2,0,0,0,'no'] ] labels = ['年龄', '有工作', '有自己的房子', '信贷情况'] return dataSet,labels
[ "def", "createDataSet", "(", ")", ":", "dataSet", "=", "[", "[", "0", ",", "0", ",", "0", ",", "0", ",", "'no'", "]", ",", "[", "0", ",", "0", ",", "0", ",", "1", ",", "'no'", "]", ",", "[", "0", ",", "1", ",", "0", ",", "1", ",", "'y...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter3-Decision_tree/decision_tree.py#L8-L33
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/whoosh/reading.py
python
MultiReader.generation
(self)
return self._gen
[]
def generation(self): return self._gen
[ "def", "generation", "(", "self", ")", ":", "return", "self", ".", "_gen" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/whoosh/reading.py#L1026-L1027
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
chap19/monitor/monitor/monitor/openstack/common/notifier/rpc_notifier2.py
python
notify
(context, message)
Sends a notification via RPC
Sends a notification via RPC
[ "Sends", "a", "notification", "via", "RPC" ]
def notify(context, message): """Sends a notification via RPC""" if not context: context = req_context.get_admin_context() priority = message.get('priority', CONF.default_notification_level) priority = priority.lower() for topic in CONF.rpc_notifier2.topics: topic = '%s.%s' % (topic, priority) try: rpc.notify(context, topic, message, envelope=True) except Exception: LOG.exception(_("Could not send notification to %(topic)s. " "Payload=%(message)s"), locals())
[ "def", "notify", "(", "context", ",", "message", ")", ":", "if", "not", "context", ":", "context", "=", "req_context", ".", "get_admin_context", "(", ")", "priority", "=", "message", ".", "get", "(", "'priority'", ",", "CONF", ".", "default_notification_leve...
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/chap19/monitor/monitor/monitor/openstack/common/notifier/rpc_notifier2.py#L39-L52
FSX/momoko
ad2f602c85b5df09e54dcb997c2f81ccc3d2b221
momoko/connection.py
python
Connection.closed
(self)
return self.connection.closed > 0 if self.connection else True
Indicates whether the connection is closed or not.
Indicates whether the connection is closed or not.
[ "Indicates", "whether", "the", "connection", "is", "closed", "or", "not", "." ]
def closed(self): """ Indicates whether the connection is closed or not. """ # 0 = open, 1 = closed, 2 = 'something horrible happened' return self.connection.closed > 0 if self.connection else True
[ "def", "closed", "(", "self", ")", ":", "# 0 = open, 1 = closed, 2 = 'something horrible happened'", "return", "self", ".", "connection", ".", "closed", ">", "0", "if", "self", ".", "connection", "else", "True" ]
https://github.com/FSX/momoko/blob/ad2f602c85b5df09e54dcb997c2f81ccc3d2b221/momoko/connection.py#L993-L998
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/UniversalAnalytics/HTTPLog.py
python
LineBufferTranslator.__init__
(self, *a, **kw)
[]
def __init__(self, *a, **kw): self._linepending = [] super(LineBufferTranslator, self).__init__(*a, **kw)
[ "def", "__init__", "(", "self", ",", "*", "a", ",", "*", "*", "kw", ")", ":", "self", ".", "_linepending", "=", "[", "]", "super", "(", "LineBufferTranslator", ",", "self", ")", ".", "__init__", "(", "*", "a", ",", "*", "*", "kw", ")" ]
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/UniversalAnalytics/HTTPLog.py#L54-L56
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/geometry/polyhedron/cdd_file_format.py
python
cdd_Hrepresentation
(cdd_type, ieqs, eqns, file_output=None)
r""" Return a string containing the H-representation in cddlib's ine format. INPUT: - ``file_output`` (string; optional) -- a filename to which the representation should be written. If set to ``None`` (default), representation is returned as a string. EXAMPLES:: sage: from sage.geometry.polyhedron.cdd_file_format import cdd_Hrepresentation sage: cdd_Hrepresentation('rational', None, [[0,1]]) 'H-representation\nlinearity 1 1\nbegin\n 1 2 rational\n 0 1\nend\n' TESTS:: sage: from sage.misc.temporary_file import tmp_filename sage: filename = tmp_filename(ext='.ine') sage: cdd_Hrepresentation('rational', None, [[0,1]], file_output=filename)
r""" Return a string containing the H-representation in cddlib's ine format.
[ "r", "Return", "a", "string", "containing", "the", "H", "-", "representation", "in", "cddlib", "s", "ine", "format", "." ]
def cdd_Hrepresentation(cdd_type, ieqs, eqns, file_output=None): r""" Return a string containing the H-representation in cddlib's ine format. INPUT: - ``file_output`` (string; optional) -- a filename to which the representation should be written. If set to ``None`` (default), representation is returned as a string. EXAMPLES:: sage: from sage.geometry.polyhedron.cdd_file_format import cdd_Hrepresentation sage: cdd_Hrepresentation('rational', None, [[0,1]]) 'H-representation\nlinearity 1 1\nbegin\n 1 2 rational\n 0 1\nend\n' TESTS:: sage: from sage.misc.temporary_file import tmp_filename sage: filename = tmp_filename(ext='.ine') sage: cdd_Hrepresentation('rational', None, [[0,1]], file_output=filename) """ ieqs = _set_to_None_if_empty(ieqs) eqns = _set_to_None_if_empty(eqns) num, ambient_dim = _common_length_of(ieqs, eqns) ambient_dim -= 1 if cdd_type == 'real': from sage.rings.real_double import RDF base_ring = RDF else: base_ring = None s = 'H-representation\n' if eqns is not None: assert len(eqns)>0 n = len(eqns) s += "linearity " + repr(n) + ' ' s += _to_space_separated_string(range(1,n+1)) + '\n' s += 'begin\n' s += ' ' + repr(num) + ' ' + repr(ambient_dim+1) + ' ' + cdd_type + '\n' if eqns is not None: for e in eqns: s += ' ' + _to_space_separated_string(e, base_ring) + '\n' if ieqs is not None: for i in ieqs: s += ' ' + _to_space_separated_string(i, base_ring) + '\n' s += 'end\n' if file_output is not None: in_file = open(file_output, 'w') in_file.write(s) in_file.close() else: return s
[ "def", "cdd_Hrepresentation", "(", "cdd_type", ",", "ieqs", ",", "eqns", ",", "file_output", "=", "None", ")", ":", "ieqs", "=", "_set_to_None_if_empty", "(", "ieqs", ")", "eqns", "=", "_set_to_None_if_empty", "(", "eqns", ")", "num", ",", "ambient_dim", "="...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/geometry/polyhedron/cdd_file_format.py#L95-L150
hzlzh/AlfredWorkflow.com
7055f14f6922c80ea5943839eb0caff11ae57255
Sources/Workflows/Alfred-Time-Keeper/PyAl/Request/bs4/element.py
python
Tag.__repr__
(self, encoding=DEFAULT_OUTPUT_ENCODING)
return self.encode(encoding)
Renders this tag as a string.
Renders this tag as a string.
[ "Renders", "this", "tag", "as", "a", "string", "." ]
def __repr__(self, encoding=DEFAULT_OUTPUT_ENCODING): """Renders this tag as a string.""" return self.encode(encoding)
[ "def", "__repr__", "(", "self", ",", "encoding", "=", "DEFAULT_OUTPUT_ENCODING", ")", ":", "return", "self", ".", "encode", "(", "encoding", ")" ]
https://github.com/hzlzh/AlfredWorkflow.com/blob/7055f14f6922c80ea5943839eb0caff11ae57255/Sources/Workflows/Alfred-Time-Keeper/PyAl/Request/bs4/element.py#L948-L950
mgear-dev/mgear
06ddc26c5adb5eab07ca470c7fafa77404c8a1de
scripts/mgear/maya/curve.py
python
createCurveFromOrderedEdges
(edgeLoop, startVertex, name, parent=None, degree=3)
return crv
Create a curve for a edgeloop ordering the list from starting vertex Arguments: edgeLoop (list ): List of edges startVertex (vertex): Starting vertex name (str): Name of the new curve. parent (dagNode): Parent of the new curve. degree (int): Degree of the new curve. Returns: dagNode: The newly created curve.
Create a curve for a edgeloop ordering the list from starting vertex
[ "Create", "a", "curve", "for", "a", "edgeloop", "ordering", "the", "list", "from", "starting", "vertex" ]
def createCurveFromOrderedEdges(edgeLoop, startVertex, name, parent=None, degree=3): """Create a curve for a edgeloop ordering the list from starting vertex Arguments: edgeLoop (list ): List of edges startVertex (vertex): Starting vertex name (str): Name of the new curve. parent (dagNode): Parent of the new curve. degree (int): Degree of the new curve. Returns: dagNode: The newly created curve. """ orderedEdges = [] for e in edgeLoop: if startVertex in e.connectedVertices(): orderedEdges.append(e) next = e break count = 0 while True: for e in edgeLoop: if e in next.connectedEdges() and e not in orderedEdges: orderedEdges.append(e) next = e pass if len(orderedEdges) == len(edgeLoop): break count += 1 if count > 100: break # return orderedEdges orderedVertex = [startVertex] orderedVertexPos = [startVertex.getPosition(space='world')] for e in orderedEdges: for v in e.connectedVertices(): if v not in orderedVertex: orderedVertex.append(v) orderedVertexPos.append(v.getPosition(space='world')) crv = addCurve(parent, name, orderedVertexPos, degree=degree) return crv
[ "def", "createCurveFromOrderedEdges", "(", "edgeLoop", ",", "startVertex", ",", "name", ",", "parent", "=", "None", ",", "degree", "=", "3", ")", ":", "orderedEdges", "=", "[", "]", "for", "e", "in", "edgeLoop", ":", "if", "startVertex", "in", "e", ".", ...
https://github.com/mgear-dev/mgear/blob/06ddc26c5adb5eab07ca470c7fafa77404c8a1de/scripts/mgear/maya/curve.py#L87-L134
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
plexpy/newsletters.py
python
get_agent_class
(newsletter_id=None, newsletter_id_name=None, agent_id=None, config=None, email_config=None, start_date=None, end_date=None, subject=None, body=None, message=None, email_msg_id=None, email_reply_msg_id=None)
[]
def get_agent_class(newsletter_id=None, newsletter_id_name=None, agent_id=None, config=None, email_config=None, start_date=None, end_date=None, subject=None, body=None, message=None, email_msg_id=None, email_reply_msg_id=None): if str(agent_id).isdigit(): agent_id = int(agent_id) kwargs = {'newsletter_id': newsletter_id, 'newsletter_id_name': newsletter_id_name, 'config': config, 'email_config': email_config, 'start_date': start_date, 'end_date': end_date, 'subject': subject, 'body': body, 'message': message, 'email_msg_id': email_msg_id, 'email_reply_msg_id': email_reply_msg_id} if agent_id == 0: return RecentlyAdded(**kwargs) else: return Newsletter(**kwargs) else: return None
[ "def", "get_agent_class", "(", "newsletter_id", "=", "None", ",", "newsletter_id_name", "=", "None", ",", "agent_id", "=", "None", ",", "config", "=", "None", ",", "email_config", "=", "None", ",", "start_date", "=", "None", ",", "end_date", "=", "None", "...
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/plexpy/newsletters.py#L85-L108
cyverse/atmosphere
4a3e522f1f7b58abd9fa944c10b7455dc5cddac1
api/v1/views/identity.py
python
get_provider
(user, provider_uuid)
Given the (request) user and a provider uuid, return None or an Active provider
Given the (request) user and a provider uuid, return None or an Active provider
[ "Given", "the", "(", "request", ")", "user", "and", "a", "provider", "uuid", "return", "None", "or", "an", "Active", "provider" ]
def get_provider(user, provider_uuid): """ Given the (request) user and a provider uuid, return None or an Active provider """ try: provider = user.current_providers.get(uuid=provider_uuid) return provider except Provider.DoesNotExist: logger.warn( "Provider %s DoesNotExist and/or has not " "been shared with any of the groups for User:%s" % (provider_uuid, user) ) return None
[ "def", "get_provider", "(", "user", ",", "provider_uuid", ")", ":", "try", ":", "provider", "=", "user", ".", "current_providers", ".", "get", "(", "uuid", "=", "provider_uuid", ")", "return", "provider", "except", "Provider", ".", "DoesNotExist", ":", "logg...
https://github.com/cyverse/atmosphere/blob/4a3e522f1f7b58abd9fa944c10b7455dc5cddac1/api/v1/views/identity.py#L14-L28
shadowmoose/RedditDownloader
ffe38afbee64e094fe80de2267ea049401bfb2f2
redditdownloader/sources/source.py
python
Source.set_alias
(self, alias)
Set the alias of this Source.
Set the alias of this Source.
[ "Set", "the", "alias", "of", "this", "Source", "." ]
def set_alias(self, alias): """ Set the alias of this Source. """ self._alias = alias
[ "def", "set_alias", "(", "self", ",", "alias", ")", ":", "self", ".", "_alias", "=", "alias" ]
https://github.com/shadowmoose/RedditDownloader/blob/ffe38afbee64e094fe80de2267ea049401bfb2f2/redditdownloader/sources/source.py#L48-L50
CedricGuillemet/Imogen
ee417b42747ed5b46cb11b02ef0c3630000085b3
bin/Lib/lib2to3/pytree.py
python
Leaf.prefix
(self)
return self._prefix
The whitespace and comments preceding this token in the input.
The whitespace and comments preceding this token in the input.
[ "The", "whitespace", "and", "comments", "preceding", "this", "token", "in", "the", "input", "." ]
def prefix(self): """ The whitespace and comments preceding this token in the input. """ return self._prefix
[ "def", "prefix", "(", "self", ")", ":", "return", "self", ".", "_prefix" ]
https://github.com/CedricGuillemet/Imogen/blob/ee417b42747ed5b46cb11b02ef0c3630000085b3/bin/Lib/lib2to3/pytree.py#L384-L388
CGCookie/retopoflow
3d8b3a47d1d661f99ab0aeb21d31370bf15de35e
retopoflow/rf/rf_sources.py
python
RetopoFlow_Sources.raycast_sources_Point2D_all
(self, xy:Point2D)
return self.raycast_sources_Ray_all(self.Point2D_to_Ray(xy))
[]
def raycast_sources_Point2D_all(self, xy:Point2D): if xy is None: return None,None,None,None return self.raycast_sources_Ray_all(self.Point2D_to_Ray(xy))
[ "def", "raycast_sources_Point2D_all", "(", "self", ",", "xy", ":", "Point2D", ")", ":", "if", "xy", "is", "None", ":", "return", "None", ",", "None", ",", "None", ",", "None", "return", "self", ".", "raycast_sources_Ray_all", "(", "self", ".", "Point2D_to_...
https://github.com/CGCookie/retopoflow/blob/3d8b3a47d1d661f99ab0aeb21d31370bf15de35e/retopoflow/rf/rf_sources.py#L122-L124
wistbean/learn_python3_spider
73c873f4845f4385f097e5057407d03dd37a117b
stackoverflow/venv/lib/python3.6/site-packages/redis/client.py
python
Redis.sentinel_get_master_addr_by_name
(self, service_name)
return self.execute_command('SENTINEL GET-MASTER-ADDR-BY-NAME', service_name)
Returns a (host, port) pair for the given ``service_name``
Returns a (host, port) pair for the given ``service_name``
[ "Returns", "a", "(", "host", "port", ")", "pair", "for", "the", "given", "service_name" ]
def sentinel_get_master_addr_by_name(self, service_name): "Returns a (host, port) pair for the given ``service_name``" return self.execute_command('SENTINEL GET-MASTER-ADDR-BY-NAME', service_name)
[ "def", "sentinel_get_master_addr_by_name", "(", "self", ",", "service_name", ")", ":", "return", "self", ".", "execute_command", "(", "'SENTINEL GET-MASTER-ADDR-BY-NAME'", ",", "service_name", ")" ]
https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/redis/client.py#L1120-L1123
python/cpython
e13cdca0f5224ec4e23bdd04bb3120506964bc8b
Lib/smtplib.py
python
SMTP.starttls
(self, keyfile=None, certfile=None, context=None)
return (resp, reply)
Puts the connection to the SMTP server into TLS mode. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server supports TLS, this will encrypt the rest of the SMTP session. If you provide the keyfile and certfile parameters, the identity of the SMTP server and client can be checked. This, however, depends on whether the socket module really checks the certificates. This method may raise the following exceptions: SMTPHeloError The server didn't reply properly to the helo greeting.
Puts the connection to the SMTP server into TLS mode.
[ "Puts", "the", "connection", "to", "the", "SMTP", "server", "into", "TLS", "mode", "." ]
def starttls(self, keyfile=None, certfile=None, context=None): """Puts the connection to the SMTP server into TLS mode. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server supports TLS, this will encrypt the rest of the SMTP session. If you provide the keyfile and certfile parameters, the identity of the SMTP server and client can be checked. This, however, depends on whether the socket module really checks the certificates. This method may raise the following exceptions: SMTPHeloError The server didn't reply properly to the helo greeting. """ self.ehlo_or_helo_if_needed() if not self.has_extn("starttls"): raise SMTPNotSupportedError( "STARTTLS extension not supported by server.") (resp, reply) = self.docmd("STARTTLS") if resp == 220: if not _have_ssl: raise RuntimeError("No SSL support included in this Python") if context is not None and keyfile is not None: raise ValueError("context and keyfile arguments are mutually " "exclusive") if context is not None and certfile is not None: raise ValueError("context and certfile arguments are mutually " "exclusive") if keyfile is not None or certfile is not None: import warnings warnings.warn("keyfile and certfile are deprecated, use a " "custom context instead", DeprecationWarning, 2) if context is None: context = ssl._create_stdlib_context(certfile=certfile, keyfile=keyfile) self.sock = context.wrap_socket(self.sock, server_hostname=self._host) self.file = None # RFC 3207: # The client MUST discard any knowledge obtained from # the server, such as the list of SMTP service extensions, # which was not obtained from the TLS negotiation itself. self.helo_resp = None self.ehlo_resp = None self.esmtp_features = {} self.does_esmtp = False else: # RFC 3207: # 501 Syntax error (no parameters allowed) # 454 TLS not available due to temporary reason raise SMTPResponseException(resp, reply) return (resp, reply)
[ "def", "starttls", "(", "self", ",", "keyfile", "=", "None", ",", "certfile", "=", "None", ",", "context", "=", "None", ")", ":", "self", ".", "ehlo_or_helo_if_needed", "(", ")", "if", "not", "self", ".", "has_extn", "(", "\"starttls\"", ")", ":", "rai...
https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/smtplib.py#L752-L806
tensorflow/models
6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3
research/object_detection/predictors/heads/keras_mask_head.py
python
ConvolutionalMaskHead.__init__
(self, is_training, num_classes, use_dropout, dropout_keep_prob, kernel_size, num_predictions_per_location, conv_hyperparams, freeze_batchnorm, use_depthwise=False, mask_height=7, mask_width=7, masks_are_class_agnostic=False, name=None)
Constructor. Args: is_training: Indicates whether the BoxPredictor is in training mode. num_classes: Number of classes. use_dropout: Option to use dropout or not. Note that a single dropout op is applied here prior to both box and class predictions, which stands in contrast to the ConvolutionalBoxPredictor below. dropout_keep_prob: Keep probability for dropout. This is only used if use_dropout is True. kernel_size: Size of final convolution kernel. If the spatial resolution of the feature map is smaller than the kernel size, then the kernel size is automatically set to be min(feature_width, feature_height). num_predictions_per_location: Number of box predictions to be made per spatial location. Int specifying number of boxes per location. conv_hyperparams: A `hyperparams_builder.KerasLayerHyperparams` object containing hyperparameters for convolution ops. freeze_batchnorm: Bool. Whether to freeze batch norm parameters during training or not. When training with a small batch size (e.g. 1), it is desirable to freeze batch norm update and use pretrained batch norm params. use_depthwise: Whether to use depthwise convolutions for prediction steps. Default is False. mask_height: Desired output mask height. The default value is 7. mask_width: Desired output mask width. The default value is 7. masks_are_class_agnostic: Boolean determining if the mask-head is class-agnostic or not. name: A string name scope to assign to the model. If `None`, Keras will auto-generate one from the class name. Raises: ValueError: if min_depth > max_depth.
Constructor.
[ "Constructor", "." ]
def __init__(self, is_training, num_classes, use_dropout, dropout_keep_prob, kernel_size, num_predictions_per_location, conv_hyperparams, freeze_batchnorm, use_depthwise=False, mask_height=7, mask_width=7, masks_are_class_agnostic=False, name=None): """Constructor. Args: is_training: Indicates whether the BoxPredictor is in training mode. num_classes: Number of classes. use_dropout: Option to use dropout or not. Note that a single dropout op is applied here prior to both box and class predictions, which stands in contrast to the ConvolutionalBoxPredictor below. dropout_keep_prob: Keep probability for dropout. This is only used if use_dropout is True. kernel_size: Size of final convolution kernel. If the spatial resolution of the feature map is smaller than the kernel size, then the kernel size is automatically set to be min(feature_width, feature_height). num_predictions_per_location: Number of box predictions to be made per spatial location. Int specifying number of boxes per location. conv_hyperparams: A `hyperparams_builder.KerasLayerHyperparams` object containing hyperparameters for convolution ops. freeze_batchnorm: Bool. Whether to freeze batch norm parameters during training or not. When training with a small batch size (e.g. 1), it is desirable to freeze batch norm update and use pretrained batch norm params. use_depthwise: Whether to use depthwise convolutions for prediction steps. Default is False. mask_height: Desired output mask height. The default value is 7. mask_width: Desired output mask width. The default value is 7. masks_are_class_agnostic: Boolean determining if the mask-head is class-agnostic or not. name: A string name scope to assign to the model. If `None`, Keras will auto-generate one from the class name. Raises: ValueError: if min_depth > max_depth. """ super(ConvolutionalMaskHead, self).__init__(name=name) self._is_training = is_training self._num_classes = num_classes self._use_dropout = use_dropout self._dropout_keep_prob = dropout_keep_prob self._kernel_size = kernel_size self._num_predictions_per_location = num_predictions_per_location self._use_depthwise = use_depthwise self._mask_height = mask_height self._mask_width = mask_width self._masks_are_class_agnostic = masks_are_class_agnostic self._mask_predictor_layers = [] # Add a slot for the background class. if self._masks_are_class_agnostic: self._num_masks = 1 else: self._num_masks = self._num_classes num_mask_channels = self._num_masks * self._mask_height * self._mask_width if self._use_dropout: self._mask_predictor_layers.append( # The Dropout layer's `training` parameter for the call method must # be set implicitly by the Keras set_learning_phase. The object # detection training code takes care of this. tf.keras.layers.Dropout(rate=1.0 - self._dropout_keep_prob)) if self._use_depthwise: self._mask_predictor_layers.append( tf.keras.layers.DepthwiseConv2D( [self._kernel_size, self._kernel_size], padding='SAME', depth_multiplier=1, strides=1, dilation_rate=1, name='MaskPredictor_depthwise', **conv_hyperparams.params())) self._mask_predictor_layers.append( conv_hyperparams.build_batch_norm( training=(is_training and not freeze_batchnorm), name='MaskPredictor_depthwise_batchnorm')) self._mask_predictor_layers.append( conv_hyperparams.build_activation_layer( name='MaskPredictor_depthwise_activation')) self._mask_predictor_layers.append( tf.keras.layers.Conv2D( num_predictions_per_location * num_mask_channels, [1, 1], name='MaskPredictor', **conv_hyperparams.params(use_bias=True))) else: self._mask_predictor_layers.append( tf.keras.layers.Conv2D( num_predictions_per_location * num_mask_channels, [self._kernel_size, self._kernel_size], padding='SAME', name='MaskPredictor', **conv_hyperparams.params(use_bias=True)))
[ "def", "__init__", "(", "self", ",", "is_training", ",", "num_classes", ",", "use_dropout", ",", "dropout_keep_prob", ",", "kernel_size", ",", "num_predictions_per_location", ",", "conv_hyperparams", ",", "freeze_batchnorm", ",", "use_depthwise", "=", "False", ",", ...
https://github.com/tensorflow/models/blob/6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3/research/object_detection/predictors/heads/keras_mask_head.py#L39-L144
SanPen/GridCal
d3f4566d2d72c11c7e910c9d162538ef0e60df31
src/GridCal/Gui/Main/GridCalMain.py
python
MainGUI.set_value_to_column
(self)
Set the value to all the column :return: Nothing
Set the value to all the column :return: Nothing
[ "Set", "the", "value", "to", "all", "the", "column", ":", "return", ":", "Nothing" ]
def set_value_to_column(self): """ Set the value to all the column :return: Nothing """ idx = self.ui.dataStructureTableView.currentIndex() mdl = self.ui.dataStructureTableView.model() # is of type ObjectsModel col = idx.column() if mdl is not None: if col > -1: mdl.copy_to_column(idx) # update the view self.view_objects_data() else: info_msg('Select some element to serve as source to copy', 'Set value to column') else: pass
[ "def", "set_value_to_column", "(", "self", ")", ":", "idx", "=", "self", ".", "ui", ".", "dataStructureTableView", ".", "currentIndex", "(", ")", "mdl", "=", "self", ".", "ui", ".", "dataStructureTableView", ".", "model", "(", ")", "# is of type ObjectsModel",...
https://github.com/SanPen/GridCal/blob/d3f4566d2d72c11c7e910c9d162538ef0e60df31/src/GridCal/Gui/Main/GridCalMain.py#L5107-L5123
GNOME/gnome-music
b7b55c8519f9cc613ca60c01a5ab8cef6b58c92e
gnomemusic/player.py
python
Player.current_song
(self)
return self._playlist.props.current_song
Get the current song. :returns: The song being played. None if there is no playlist. :rtype: CoreSong
Get the current song.
[ "Get", "the", "current", "song", "." ]
def current_song(self): """Get the current song. :returns: The song being played. None if there is no playlist. :rtype: CoreSong """ return self._playlist.props.current_song
[ "def", "current_song", "(", "self", ")", ":", "return", "self", ".", "_playlist", ".", "props", ".", "current_song" ]
https://github.com/GNOME/gnome-music/blob/b7b55c8519f9cc613ca60c01a5ab8cef6b58c92e/gnomemusic/player.py#L624-L630
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/scrape/sensor.py
python
ScrapeSensor.__init__
( self, rest, name, select, attr, index, value_template, unit, device_class, state_class, )
Initialize a web scrape sensor.
Initialize a web scrape sensor.
[ "Initialize", "a", "web", "scrape", "sensor", "." ]
def __init__( self, rest, name, select, attr, index, value_template, unit, device_class, state_class, ): """Initialize a web scrape sensor.""" self.rest = rest self._state = None self._select = select self._attr = attr self._index = index self._value_template = value_template self._attr_name = name self._attr_native_unit_of_measurement = unit self._attr_device_class = device_class self._attr_state_class = state_class
[ "def", "__init__", "(", "self", ",", "rest", ",", "name", ",", "select", ",", "attr", ",", "index", ",", "value_template", ",", "unit", ",", "device_class", ",", "state_class", ",", ")", ":", "self", ".", "rest", "=", "rest", "self", ".", "_state", "...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/scrape/sensor.py#L129-L151
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-35/fabmetheus_utilities/geometry/creation/gear.py
python
getWidthMultipliedPath
(path, widthMultiplier)
return path
Get width multiplied path.
Get width multiplied path.
[ "Get", "width", "multiplied", "path", "." ]
def getWidthMultipliedPath(path, widthMultiplier): "Get width multiplied path." for pointIndex, point in enumerate(path): path[pointIndex] = complex(point.real * widthMultiplier, point.imag) return path
[ "def", "getWidthMultipliedPath", "(", "path", ",", "widthMultiplier", ")", ":", "for", "pointIndex", ",", "point", "in", "enumerate", "(", "path", ")", ":", "path", "[", "pointIndex", "]", "=", "complex", "(", "point", ".", "real", "*", "widthMultiplier", ...
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-35/fabmetheus_utilities/geometry/creation/gear.py#L608-L612
cisco/mindmeld
809c36112e9ea8019fe29d54d136ca14eb4fd8db
mindmeld/components/domain_classifier.py
python
DomainClassifier.load
(self, *args, **kwargs)
Loads the trained domain classification model from disk Args: model_path (str): The location on disk where the model is stored
Loads the trained domain classification model from disk
[ "Loads", "the", "trained", "domain", "classification", "model", "from", "disk" ]
def load(self, *args, **kwargs): """Loads the trained domain classification model from disk Args: model_path (str): The location on disk where the model is stored """ logger.info("Loading domain classifier") super().load(*args, **kwargs)
[ "def", "load", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "info", "(", "\"Loading domain classifier\"", ")", "super", "(", ")", ".", "load", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/cisco/mindmeld/blob/809c36112e9ea8019fe29d54d136ca14eb4fd8db/mindmeld/components/domain_classifier.py#L82-L89
nansencenter/nansat
5700ec673fbf522c19b8dedcb01cc15f7cd29a6a
nansat/mappers/envisat.py
python
Envisat.get_ads_vrts
(self, gdalDataset, adsNames, zoomSize=500, step=1, **kwargs)
return adsVRTs
Create list with VRTs with zoomed and resized ADS arrays For given names of variables (which should match self.allADSParams): Get VRT with zoomed ADS array Get resized VRT Parameters ---------- gdalDataset: GDAL Dataset input dataset adsNames: list with strings names of varaiables from self.allADSParams['list'] zoomSize: int, 500 size to which the ADS array will be zoomed by scipy.zoom step: int, 1 step, at which data will be given Returns -------- adsVRTs: list with VRT list with resized VRT with zoomed arrays
Create list with VRTs with zoomed and resized ADS arrays
[ "Create", "list", "with", "VRTs", "with", "zoomed", "and", "resized", "ADS", "arrays" ]
def get_ads_vrts(self, gdalDataset, adsNames, zoomSize=500, step=1, **kwargs): """Create list with VRTs with zoomed and resized ADS arrays For given names of variables (which should match self.allADSParams): Get VRT with zoomed ADS array Get resized VRT Parameters ---------- gdalDataset: GDAL Dataset input dataset adsNames: list with strings names of varaiables from self.allADSParams['list'] zoomSize: int, 500 size to which the ADS array will be zoomed by scipy.zoom step: int, 1 step, at which data will be given Returns -------- adsVRTs: list with VRT list with resized VRT with zoomed arrays """ XSize = gdalDataset.RasterXSize YSize = gdalDataset.RasterYSize # list with VRT with arrays of lon/lat adsVRTs = [] for adsName in adsNames: # create VRT with array from ADS adsVRTs.append(self.create_VRT_from_ADS(adsName, zoomSize)) # resize the VRT to match <step> adsVRTs[-1] = adsVRTs[-1].get_resized_vrt(XSize/step, YSize/step) return adsVRTs
[ "def", "get_ads_vrts", "(", "self", ",", "gdalDataset", ",", "adsNames", ",", "zoomSize", "=", "500", ",", "step", "=", "1", ",", "*", "*", "kwargs", ")", ":", "XSize", "=", "gdalDataset", ".", "RasterXSize", "YSize", "=", "gdalDataset", ".", "RasterYSiz...
https://github.com/nansencenter/nansat/blob/5700ec673fbf522c19b8dedcb01cc15f7cd29a6a/nansat/mappers/envisat.py#L423-L457
mrlesmithjr/Ansible
d44f0dc0d942bdf3bf7334b307e6048f0ee16e36
roles/ansible-vsphere-management/scripts/pdns/lib/python2.7/site-packages/pip/_vendor/distlib/database.py
python
DependencyGraph.__repr__
(self)
return '\n'.join(output)
Representation of the graph
Representation of the graph
[ "Representation", "of", "the", "graph" ]
def __repr__(self): """Representation of the graph""" output = [] for dist, adjs in self.adjacency_list.items(): output.append(self.repr_node(dist)) return '\n'.join(output)
[ "def", "__repr__", "(", "self", ")", ":", "output", "=", "[", "]", "for", "dist", ",", "adjs", "in", "self", ".", "adjacency_list", ".", "items", "(", ")", ":", "output", ".", "append", "(", "self", ".", "repr_node", "(", "dist", ")", ")", "return"...
https://github.com/mrlesmithjr/Ansible/blob/d44f0dc0d942bdf3bf7334b307e6048f0ee16e36/roles/ansible-vsphere-management/scripts/pdns/lib/python2.7/site-packages/pip/_vendor/distlib/database.py#L1190-L1195
jymcheong/AutoTTP
617128fe71537de4579176d7170a3e8f1680b6a6
EmpireAPIWrapper/wrapper.py
python
agents.agent_info
(self, name)
return utilties._getURL(self, full_url)
Returns JSON describing the agent specified by name. \n:param name: \n:rtype: dict
Returns JSON describing the agent specified by name. \n:param name: \n:rtype: dict
[ "Returns", "JSON", "describing", "the", "agent", "specified", "by", "name", ".", "\\", "n", ":", "param", "name", ":", "\\", "n", ":", "rtype", ":", "dict" ]
def agent_info(self, name): """ Returns JSON describing the agent specified by name. \n:param name: \n:rtype: dict """ full_url = '/api/agents/{}'.format(name) return utilties._getURL(self, full_url)
[ "def", "agent_info", "(", "self", ",", "name", ")", ":", "full_url", "=", "'/api/agents/{}'", ".", "format", "(", "name", ")", "return", "utilties", ".", "_getURL", "(", "self", ",", "full_url", ")" ]
https://github.com/jymcheong/AutoTTP/blob/617128fe71537de4579176d7170a3e8f1680b6a6/EmpireAPIWrapper/wrapper.py#L335-L342
KalleHallden/AutoTimer
2d954216700c4930baa154e28dbddc34609af7ce
env/lib/python2.7/site-packages/pip/_internal/req/req_install.py
python
InstallRequirement.assert_source_matches_version
(self)
[]
def assert_source_matches_version(self): # type: () -> None assert self.source_dir version = self.metadata['version'] if self.req.specifier and version not in self.req.specifier: logger.warning( 'Requested %s, but installing version %s', self, version, ) else: logger.debug( 'Source in %s has version %s, which satisfies requirement %s', display_path(self.source_dir), version, self, )
[ "def", "assert_source_matches_version", "(", "self", ")", ":", "# type: () -> None", "assert", "self", ".", "source_dir", "version", "=", "self", ".", "metadata", "[", "'version'", "]", "if", "self", ".", "req", ".", "specifier", "and", "version", "not", "in",...
https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/pip/_internal/req/req_install.py#L714-L730
facebookresearch/mobile-vision
f40401a44e86bb3ba9c1b66e7700e15f96b880cb
mobile_cv/arch/utils/fx_utils.py
python
get_input_nodes
(nodes: List[torch.fx.Node])
return ret
Extract the input nodes from a list of nodes Input nodes are the nodes that are not produced by other nodes
Extract the input nodes from a list of nodes Input nodes are the nodes that are not produced by other nodes
[ "Extract", "the", "input", "nodes", "from", "a", "list", "of", "nodes", "Input", "nodes", "are", "the", "nodes", "that", "are", "not", "produced", "by", "other", "nodes" ]
def get_input_nodes(nodes: List[torch.fx.Node]): """Extract the input nodes from a list of nodes Input nodes are the nodes that are not produced by other nodes """ ret = [] for node in nodes: all_inputs = node.all_input_nodes for cur_input in all_inputs: if cur_input not in nodes: ret.append(cur_input) assert len(ret) > 0 return ret
[ "def", "get_input_nodes", "(", "nodes", ":", "List", "[", "torch", ".", "fx", ".", "Node", "]", ")", ":", "ret", "=", "[", "]", "for", "node", "in", "nodes", ":", "all_inputs", "=", "node", ".", "all_input_nodes", "for", "cur_input", "in", "all_inputs"...
https://github.com/facebookresearch/mobile-vision/blob/f40401a44e86bb3ba9c1b66e7700e15f96b880cb/mobile_cv/arch/utils/fx_utils.py#L79-L90
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/cherrypy/_helper.py
python
url
(path='', qs='', script_name=None, base=None, relative=None)
return newurl
Create an absolute URL for the given path. If 'path' starts with a slash ('/'), this will return (base + script_name + path + qs). If it does not start with a slash, this returns (base + script_name [+ request.path_info] + path + qs). If script_name is None, cherrypy.request will be used to find a script_name, if available. If base is None, cherrypy.request.base will be used (if available). Note that you can use cherrypy.tools.proxy to change this. Finally, note that this function can be used to obtain an absolute URL for the current request path (minus the querystring) by passing no args. If you call url(qs=cherrypy.request.query_string), you should get the original browser URL (assuming no internal redirections). If relative is None or not provided, request.app.relative_urls will be used (if available, else False). If False, the output will be an absolute URL (including the scheme, host, vhost, and script_name). If True, the output will instead be a URL that is relative to the current request path, perhaps including '..' atoms. If relative is the string 'server', the output will instead be a URL that is relative to the server root; i.e., it will start with a slash.
Create an absolute URL for the given path.
[ "Create", "an", "absolute", "URL", "for", "the", "given", "path", "." ]
def url(path='', qs='', script_name=None, base=None, relative=None): """Create an absolute URL for the given path. If 'path' starts with a slash ('/'), this will return (base + script_name + path + qs). If it does not start with a slash, this returns (base + script_name [+ request.path_info] + path + qs). If script_name is None, cherrypy.request will be used to find a script_name, if available. If base is None, cherrypy.request.base will be used (if available). Note that you can use cherrypy.tools.proxy to change this. Finally, note that this function can be used to obtain an absolute URL for the current request path (minus the querystring) by passing no args. If you call url(qs=cherrypy.request.query_string), you should get the original browser URL (assuming no internal redirections). If relative is None or not provided, request.app.relative_urls will be used (if available, else False). If False, the output will be an absolute URL (including the scheme, host, vhost, and script_name). If True, the output will instead be a URL that is relative to the current request path, perhaps including '..' atoms. If relative is the string 'server', the output will instead be a URL that is relative to the server root; i.e., it will start with a slash. """ if isinstance(qs, (tuple, list, dict)): qs = urllib.parse.urlencode(qs) if qs: qs = '?' + qs if cherrypy.request.app: if not path.startswith('/'): # Append/remove trailing slash from path_info as needed # (this is to support mistyped URL's without redirecting; # if you want to redirect, use tools.trailing_slash). pi = cherrypy.request.path_info if cherrypy.request.is_index is True: if not pi.endswith('/'): pi = pi + '/' elif cherrypy.request.is_index is False: if pi.endswith('/') and pi != '/': pi = pi[:-1] if path == '': path = pi else: path = urllib.parse.urljoin(pi, path) if script_name is None: script_name = cherrypy.request.script_name if base is None: base = cherrypy.request.base newurl = base + script_name + normalize_path(path) + qs else: # No request.app (we're being called outside a request). # We'll have to guess the base from server.* attributes. # This will produce very different results from the above # if you're using vhosts or tools.proxy. if base is None: base = cherrypy.server.base() path = (script_name or '') + path newurl = base + normalize_path(path) + qs # At this point, we should have a fully-qualified absolute URL. if relative is None: relative = getattr(cherrypy.request.app, 'relative_urls', False) # See http://www.ietf.org/rfc/rfc2396.txt if relative == 'server': # "A relative reference beginning with a single slash character is # termed an absolute-path reference, as defined by <abs_path>..." # This is also sometimes called "server-relative". newurl = '/' + '/'.join(newurl.split('/', 3)[3:]) elif relative: # "A relative reference that does not begin with a scheme name # or a slash character is termed a relative-path reference." old = url(relative=False).split('/')[:-1] new = newurl.split('/') while old and new: a, b = old[0], new[0] if a != b: break old.pop(0) new.pop(0) new = (['..'] * len(old)) + new newurl = '/'.join(new) return newurl
[ "def", "url", "(", "path", "=", "''", ",", "qs", "=", "''", ",", "script_name", "=", "None", ",", "base", "=", "None", ",", "relative", "=", "None", ")", ":", "if", "isinstance", "(", "qs", ",", "(", "tuple", ",", "list", ",", "dict", ")", ")",...
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/cherrypy/_helper.py#L196-L288
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/patched/notpip/_vendor/distlib/metadata.py
python
Metadata.name_and_version
(self)
return _get_name_and_version(self.name, self.version, True)
[]
def name_and_version(self): return _get_name_and_version(self.name, self.version, True)
[ "def", "name_and_version", "(", "self", ")", ":", "return", "_get_name_and_version", "(", "self", ".", "name", ",", "self", ".", "version", ",", "True", ")" ]
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/patched/notpip/_vendor/distlib/metadata.py#L806-L807
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/app_manager/suite_xml/post_process/workflow.py
python
WorkflowDatumMeta.clone_to_match
(self, source_id=None)
return new_meta
[]
def clone_to_match(self, source_id=None): new_meta = WorkflowDatumMeta(self.id, self.nodeset, self.function) new_meta.source_id = source_id or self.id return new_meta
[ "def", "clone_to_match", "(", "self", ",", "source_id", "=", "None", ")", ":", "new_meta", "=", "WorkflowDatumMeta", "(", "self", ".", "id", ",", "self", ".", "nodeset", ",", "self", ".", "function", ")", "new_meta", ".", "source_id", "=", "source_id", "...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/app_manager/suite_xml/post_process/workflow.py#L713-L716
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/PIL/ImageStat.py
python
Stat._getcount
(self)
return v
Get total number of pixels in each layer
Get total number of pixels in each layer
[ "Get", "total", "number", "of", "pixels", "in", "each", "layer" ]
def _getcount(self): "Get total number of pixels in each layer" v = [] for i in range(0, len(self.h), 256): v.append(functools.reduce(operator.add, self.h[i:i+256])) return v
[ "def", "_getcount", "(", "self", ")", ":", "v", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "self", ".", "h", ")", ",", "256", ")", ":", "v", ".", "append", "(", "functools", ".", "reduce", "(", "operator", ".", "add"...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/PIL/ImageStat.py#L69-L75
bloomberg/phabricator-tools
09bd1587fe8945d93a891162fd4c89640c6fada7
py/phl/phlsys_subprocess__t.py
python
PhlsysSubprocessTests.test_run_list
(self)
Passing valid list on stdin sorted in reverse order.
Passing valid list on stdin sorted in reverse order.
[ "Passing", "valid", "list", "on", "stdin", "sorted", "in", "reverse", "order", "." ]
def test_run_list(self): """Passing valid list on stdin sorted in reverse order.""" args = ("sort", "-r") kwargs = {"stdin": "1\n2\n3"} result = phlsys_subprocess.run(*args, **kwargs) expect = phlsys_subprocess.RunResult( stdout=kwargs['stdin'][::-1] + "\n", stderr='') self.assertEqual(result, expect)
[ "def", "test_run_list", "(", "self", ")", ":", "args", "=", "(", "\"sort\"", ",", "\"-r\"", ")", "kwargs", "=", "{", "\"stdin\"", ":", "\"1\\n2\\n3\"", "}", "result", "=", "phlsys_subprocess", ".", "run", "(", "*", "args", ",", "*", "*", "kwargs", ")",...
https://github.com/bloomberg/phabricator-tools/blob/09bd1587fe8945d93a891162fd4c89640c6fada7/py/phl/phlsys_subprocess__t.py#L20-L27
google/containerregistry
8a11dc8c53003ecf5b72ffaf035ba280109356ac
client/v2_2/docker_image_.py
python
FromDisk.blob_size
(self, digest)
return info.st_size
Override.
Override.
[ "Override", "." ]
def blob_size(self, digest): """Override.""" if digest not in self._layer_to_filename: return self._legacy_base.blob_size(digest) info = os.stat(self._layer_to_filename[digest]) return info.st_size
[ "def", "blob_size", "(", "self", ",", "digest", ")", ":", "if", "digest", "not", "in", "self", ".", "_layer_to_filename", ":", "return", "self", ".", "_legacy_base", ".", "blob_size", "(", "digest", ")", "info", "=", "os", ".", "stat", "(", "self", "."...
https://github.com/google/containerregistry/blob/8a11dc8c53003ecf5b72ffaf035ba280109356ac/client/v2_2/docker_image_.py#L787-L792
DataIntegrationAlliance/data_integration_celery
6775292030213dd1fa33a1ec0f542d5d2d2e612a
tasks/jqdata/stock/available_check/__init__.py
python
check_diff
(table_name, table_name_backup=None)
return df
检查数据库两个表数据是否一致 :param table_name: :param table_name_backup: :return:
检查数据库两个表数据是否一致 :param table_name: :param table_name_backup: :return:
[ "检查数据库两个表数据是否一致", ":", "param", "table_name", ":", ":", "param", "table_name_backup", ":", ":", "return", ":" ]
def check_diff(table_name, table_name_backup=None): """ 检查数据库两个表数据是否一致 :param table_name: :param table_name_backup: :return: """ has_table = engine_md.has_table(table_name) if not has_table: logger.warning('%s 表不存在无需检查', table_name) return None if table_name_backup is None: table_name_backup = get_bak_table_name(table_name) has_table = engine_md.has_table(table_name_backup) if not has_table: logger.warning('%s 表不存在无需检查', table_name_backup) return None # table_name, table_name_backup = 'jq_stock_daily_md_pre', 'jq_stock_daily_md_pre_bak' # 测试使用 col_list = get_table_col(table_name, engine_md, config.DB_SCHEMA_MD) # 主键字段名称列表 pk_col_set = {_[0] for _ in col_list if _[2]} # 非主键字段名称列表 col_not_pk_list = [col_name for col_name, col_type, is_primary_key in col_list if not is_primary_key] # selection clause selection_clause_str = ', '.join([f"t.`{key}` {key}" for key in pk_col_set]) + ',\n' selection_clause_str += ',\n'.join([ f"t.`{col_name}` {col_name}_t, bak.`{col_name}` {col_name}_bak" for col_name in col_not_pk_list]) # join on condition # t.jq_code = bak.jq_code and t.trade_date = bak.trade_date on_condition_str = '\n and '.join([f"t.`{key}` = bak.`{key}`" for key in pk_col_set]) # where condition # t.open <> bak.open or t.close <> bak.close or ... where_condition_str = '\n or '.join([ f"t.`{col_name}` <> bak.`{col_name}`" for col_name in col_not_pk_list]) sql_str = f"""select {selection_clause_str} from {table_name} t inner join {table_name_backup} bak on {on_condition_str} where {where_condition_str}""" df = pd.read_sql(sql_str, engine_md) data_count = df.shape[0] if data_count > 0: for num, (_, data_s) in enumerate(df.T.items(), start=1): for col_name in col_not_pk_list: col_name_t, col_name_bak = f'{col_name}_t', f'{col_name}_bak' value_t, value_bak = data_s[col_name_t], data_s[col_name_bak] is_nan_on_t, is_nan_on_bak = pd.isna(value_t), pd.isna(value_bak) if is_nan_on_t and is_nan_on_bak: continue if value_t != value_bak: # 两个字段一个为空,另一个不为空,或者两者不一致 logger.warning("%s %d/%d) 字段 %s 数值不一致 %f != %f", table_name, num, data_count, ', '.join([str(data_s[key]) for key in pk_col_set]), value_t, value_bak) break return df
[ "def", "check_diff", "(", "table_name", ",", "table_name_backup", "=", "None", ")", ":", "has_table", "=", "engine_md", ".", "has_table", "(", "table_name", ")", "if", "not", "has_table", ":", "logger", ".", "warning", "(", "'%s 表不存在无需检查', table_name)", "", ""...
https://github.com/DataIntegrationAlliance/data_integration_celery/blob/6775292030213dd1fa33a1ec0f542d5d2d2e612a/tasks/jqdata/stock/available_check/__init__.py#L51-L109
kirkthaker/investopedia-trading-api
45049ac499d8eab71ee7634796c08ead5470f341
InvestopediaApi/ita.py
python
Account.get_portfolio_status
(self)
return Status( account_val=account_value, buying_power=buying_power, cash=cash, annual_return=annual_return, )
Returns a Status object containing account value, buying power, cash on hand, and annual return. Annual return is a percentage.
Returns a Status object containing account value, buying power, cash on hand, and annual return. Annual return is a percentage.
[ "Returns", "a", "Status", "object", "containing", "account", "value", "buying", "power", "cash", "on", "hand", "and", "annual", "return", ".", "Annual", "return", "is", "a", "percentage", "." ]
def get_portfolio_status(self): """ Returns a Status object containing account value, buying power, cash on hand, and annual return. Annual return is a percentage. """ response = self.fetch('/simulator/portfolio/') parsed_html = response.soup # The ids of all the account information values acct_val_id = "ctl00_MainPlaceHolder_currencyFilter_ctrlPortfolioDetails_PortfolioSummary_lblAccountValue" buying_power_id = "ctl00_MainPlaceHolder_currencyFilter_ctrlPortfolioDetails_PortfolioSummary_lblBuyingPower" cash_id = "ctl00_MainPlaceHolder_currencyFilter_ctrlPortfolioDetails_PortfolioSummary_lblCash" return_id = "ctl00_MainPlaceHolder_currencyFilter_ctrlPortfolioDetails_PortfolioSummary_lblAnnualReturn" # Use BeautifulSoup to extract the relevant values based on html ID tags account_value = parsed_html.find('span', attrs={'id': acct_val_id}).text buying_power = parsed_html.find('span', attrs={'id': buying_power_id}).text cash = parsed_html.find('span', attrs={'id': cash_id}).text annual_return = parsed_html.find('span', attrs={'id': return_id}).text # We want our returned values to be floats # Use regex to remove non-numerical or decimal characters # But keep - (negative sign) regexp = "[^0-9.-]" account_value = float(re.sub(regexp, '', account_value)) buying_power = float(re.sub(regexp, '', buying_power)) cash = float(re.sub(regexp, '', cash)) annual_return = float(re.sub(regexp, '', annual_return)) return Status( account_val=account_value, buying_power=buying_power, cash=cash, annual_return=annual_return, )
[ "def", "get_portfolio_status", "(", "self", ")", ":", "response", "=", "self", ".", "fetch", "(", "'/simulator/portfolio/'", ")", "parsed_html", "=", "response", ".", "soup", "# The ids of all the account information values", "acct_val_id", "=", "\"ctl00_MainPlaceHolder_c...
https://github.com/kirkthaker/investopedia-trading-api/blob/45049ac499d8eab71ee7634796c08ead5470f341/InvestopediaApi/ita.py#L76-L113
mne-tools/mne-python
f90b303ce66a8415e64edd4605b09ac0179c1ebf
mne/viz/utils.py
python
SelectFromCollection.style_sensors
(self, inds)
Style selected sensors as "active".
Style selected sensors as "active".
[ "Style", "selected", "sensors", "as", "active", "." ]
def style_sensors(self, inds): """Style selected sensors as "active".""" # reset self.fc[:, -1] = self.alpha_other self.ec[:, -1] = self.alpha_other / 2 self.lw[:] = self.linewidth_other # style sensors at `inds` self.fc[inds, -1] = self.alpha_selected self.ec[inds, -1] = self.alpha_selected self.lw[inds] = self.linewidth_selected self.collection.set_facecolors(self.fc) self.collection.set_edgecolors(self.ec) self.collection.set_linewidths(self.lw) self.canvas.draw_idle()
[ "def", "style_sensors", "(", "self", ",", "inds", ")", ":", "# reset", "self", ".", "fc", "[", ":", ",", "-", "1", "]", "=", "self", ".", "alpha_other", "self", ".", "ec", "[", ":", ",", "-", "1", "]", "=", "self", ".", "alpha_other", "/", "2",...
https://github.com/mne-tools/mne-python/blob/f90b303ce66a8415e64edd4605b09ac0179c1ebf/mne/viz/utils.py#L1481-L1494
Patrowl/PatrowlEngines
61dce987b662177396fa2f914ae07fd651179daf
engines/shhgit/libs/github.py
python
get_github_repositories
(logger, github_account)
return repositories
Retrieve repositories.
Retrieve repositories.
[ "Retrieve", "repositories", "." ]
def get_github_repositories(logger, github_account): """Retrieve repositories.""" github = Github(github_account['github_key']) if github_account['is_internal']: github = Github( base_url=github_account['base_url'], login_or_token=github_account['github_key'] ) raw_repositories = get_repositories(logger, github, github_account['organization']) if raw_repositories is False: logger.error('Error while getting repositories.') return False repositories = [] for raw_repository in raw_repositories: repositories.append({ 'id': raw_repository.id, 'name': raw_repository.name, 'clone_url': raw_repository.clone_url }) return repositories
[ "def", "get_github_repositories", "(", "logger", ",", "github_account", ")", ":", "github", "=", "Github", "(", "github_account", "[", "'github_key'", "]", ")", "if", "github_account", "[", "'is_internal'", "]", ":", "github", "=", "Github", "(", "base_url", "...
https://github.com/Patrowl/PatrowlEngines/blob/61dce987b662177396fa2f914ae07fd651179daf/engines/shhgit/libs/github.py#L21-L40
python/cpython
e13cdca0f5224ec4e23bdd04bb3120506964bc8b
Lib/logging/__init__.py
python
_StderrHandler.__init__
(self, level=NOTSET)
Initialize the handler.
Initialize the handler.
[ "Initialize", "the", "handler", "." ]
def __init__(self, level=NOTSET): """ Initialize the handler. """ Handler.__init__(self, level)
[ "def", "__init__", "(", "self", ",", "level", "=", "NOTSET", ")", ":", "Handler", ".", "__init__", "(", "self", ",", "level", ")" ]
https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/logging/__init__.py#L1235-L1239
mne-tools/mne-python
f90b303ce66a8415e64edd4605b09ac0179c1ebf
mne/io/brainvision/brainvision.py
python
_aux_vhdr_info
(vhdr_fname)
return settings, cfg, cinfostr, info
Aux function for _get_vhdr_info.
Aux function for _get_vhdr_info.
[ "Aux", "function", "for", "_get_vhdr_info", "." ]
def _aux_vhdr_info(vhdr_fname): """Aux function for _get_vhdr_info.""" with open(vhdr_fname, 'rb') as f: # extract the first section to resemble a cfg header = f.readline() codepage = 'utf-8' # we don't actually need to know the coding for the header line. # the characters in it all belong to ASCII and are thus the # same in Latin-1 and UTF-8 header = header.decode('ascii', 'ignore').strip() _check_bv_version(header, 'header') settings = f.read() try: # if there is an explicit codepage set, use it # we pretend like it's ascii when searching for the codepage cp_setting = re.search('Codepage=(.+)', settings.decode('ascii', 'ignore'), re.IGNORECASE & re.MULTILINE) if cp_setting: codepage = cp_setting.group(1).strip() # BrainAmp Recorder also uses ANSI codepage # an ANSI codepage raises a LookupError exception # python recognize ANSI decoding as cp1252 if codepage == 'ANSI': codepage = 'cp1252' settings = settings.decode(codepage) except UnicodeDecodeError: # if UTF-8 (new standard) or explicit codepage setting fails, # fallback to Latin-1, which is Windows default and implicit # standard in older recordings settings = settings.decode('latin-1') if settings.find('[Comment]') != -1: params, settings = settings.split('[Comment]') else: params, settings = settings, '' cfg = configparser.ConfigParser() with StringIO(params) as fid: cfg.read_file(fid) # get sampling info # Sampling interval is given in microsec cinfostr = 'Common Infos' if not cfg.has_section(cinfostr): cinfostr = 'Common infos' # NeurOne BrainVision export workaround # get sampling info # Sampling interval is given in microsec sfreq = 1e6 / cfg.getfloat(cinfostr, 'SamplingInterval') info = _empty_info(sfreq) info._unlocked = False return settings, cfg, cinfostr, info
[ "def", "_aux_vhdr_info", "(", "vhdr_fname", ")", ":", "with", "open", "(", "vhdr_fname", ",", "'rb'", ")", "as", "f", ":", "# extract the first section to resemble a cfg", "header", "=", "f", ".", "readline", "(", ")", "codepage", "=", "'utf-8'", "# we don't act...
https://github.com/mne-tools/mne-python/blob/f90b303ce66a8415e64edd4605b09ac0179c1ebf/mne/io/brainvision/brainvision.py#L359-L411
akfamily/akshare
590e50eece9ec067da3538c7059fd660b71f1339
akshare/fund/fund_amac.py
python
_get_pages
(url: str = "", payload: str = "")
return json_df["totalPages"]
中国证券投资基金业协会-信息公示-私募基金管理人公示 页数 暂时不使用本函数, 直接可以获取所有数据
中国证券投资基金业协会-信息公示-私募基金管理人公示 页数 暂时不使用本函数, 直接可以获取所有数据
[ "中国证券投资基金业协会", "-", "信息公示", "-", "私募基金管理人公示", "页数", "暂时不使用本函数", "直接可以获取所有数据" ]
def _get_pages(url: str = "", payload: str = "") -> pd.DataFrame: """ 中国证券投资基金业协会-信息公示-私募基金管理人公示 页数 暂时不使用本函数, 直接可以获取所有数据 """ headers = { "Content-Type": "application/json", } res = requests.post(url=url, json=payload, headers=headers, verify=False) res.encoding = "utf-8" json_df = res.json() return json_df["totalPages"]
[ "def", "_get_pages", "(", "url", ":", "str", "=", "\"\"", ",", "payload", ":", "str", "=", "\"\"", ")", "->", "pd", ".", "DataFrame", ":", "headers", "=", "{", "\"Content-Type\"", ":", "\"application/json\"", ",", "}", "res", "=", "requests", ".", "pos...
https://github.com/akfamily/akshare/blob/590e50eece9ec067da3538c7059fd660b71f1339/akshare/fund/fund_amac.py#L17-L28
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/user_importer/helpers.py
python
BaseUserImporter.__init__
(self, upload_domain, user_domain, user, upload_user, is_new_user, via, upload_record_id)
:param upload_domain: domain on which the bulk upload is being done :param user_domain: domain user is being updated for :param user: user to update :param upload_user: user doing the upload :param is_new_user: if user is a new user :param via: USER_CHANGE_VIA_BULK_IMPORTER :param upload_record_id: ID of the bulk upload record
:param upload_domain: domain on which the bulk upload is being done :param user_domain: domain user is being updated for :param user: user to update :param upload_user: user doing the upload :param is_new_user: if user is a new user :param via: USER_CHANGE_VIA_BULK_IMPORTER :param upload_record_id: ID of the bulk upload record
[ ":", "param", "upload_domain", ":", "domain", "on", "which", "the", "bulk", "upload", "is", "being", "done", ":", "param", "user_domain", ":", "domain", "user", "is", "being", "updated", "for", ":", "param", "user", ":", "user", "to", "update", ":", "par...
def __init__(self, upload_domain, user_domain, user, upload_user, is_new_user, via, upload_record_id): """ :param upload_domain: domain on which the bulk upload is being done :param user_domain: domain user is being updated for :param user: user to update :param upload_user: user doing the upload :param is_new_user: if user is a new user :param via: USER_CHANGE_VIA_BULK_IMPORTER :param upload_record_id: ID of the bulk upload record """ self.user_domain = user_domain self.user = user self.upload_user = upload_user self.logger = UserChangeLogger(upload_domain=upload_domain, user_domain=user_domain, user=user, is_new_user=is_new_user, changed_by_user=upload_user, changed_via=via, upload_record_id=upload_record_id) self.role_updated = False
[ "def", "__init__", "(", "self", ",", "upload_domain", ",", "user_domain", ",", "user", ",", "upload_user", ",", "is_new_user", ",", "via", ",", "upload_record_id", ")", ":", "self", ".", "user_domain", "=", "user_domain", "self", ".", "user", "=", "user", ...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/user_importer/helpers.py#L124-L142
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/IronPython/repackage/pip/pip/_vendor/distlib/locators.py
python
Locator.score_url
(self, url)
return (t.scheme != 'https', 'pypi.python.org' in t.netloc, is_wheel, compatible, basename)
Give an url a score which can be used to choose preferred URLs for a given project release.
Give an url a score which can be used to choose preferred URLs for a given project release.
[ "Give", "an", "url", "a", "score", "which", "can", "be", "used", "to", "choose", "preferred", "URLs", "for", "a", "given", "project", "release", "." ]
def score_url(self, url): """ Give an url a score which can be used to choose preferred URLs for a given project release. """ t = urlparse(url) basename = posixpath.basename(t.path) compatible = True is_wheel = basename.endswith('.whl') if is_wheel: compatible = is_compatible(Wheel(basename), self.wheel_tags) return (t.scheme != 'https', 'pypi.python.org' in t.netloc, is_wheel, compatible, basename)
[ "def", "score_url", "(", "self", ",", "url", ")", ":", "t", "=", "urlparse", "(", "url", ")", "basename", "=", "posixpath", ".", "basename", "(", "t", ".", "path", ")", "compatible", "=", "True", "is_wheel", "=", "basename", ".", "endswith", "(", "'....
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/repackage/pip/pip/_vendor/distlib/locators.py#L162-L174
matrix-org/synapse
8e57584a5859a9002759963eb546d523d2498a01
synapse/storage/databases/main/registration.py
python
RegistrationWorkerStore.set_renewal_mail_status
(self, user_id: str, email_sent: bool)
Sets or unsets the flag that indicates whether a renewal email has been sent to the user (and the user hasn't renewed their account yet). Args: user_id: ID of the user to set/unset the flag for. email_sent: Flag which indicates whether a renewal email has been sent to this user.
Sets or unsets the flag that indicates whether a renewal email has been sent to the user (and the user hasn't renewed their account yet).
[ "Sets", "or", "unsets", "the", "flag", "that", "indicates", "whether", "a", "renewal", "email", "has", "been", "sent", "to", "the", "user", "(", "and", "the", "user", "hasn", "t", "renewed", "their", "account", "yet", ")", "." ]
async def set_renewal_mail_status(self, user_id: str, email_sent: bool) -> None: """Sets or unsets the flag that indicates whether a renewal email has been sent to the user (and the user hasn't renewed their account yet). Args: user_id: ID of the user to set/unset the flag for. email_sent: Flag which indicates whether a renewal email has been sent to this user. """ await self.db_pool.simple_update_one( table="account_validity", keyvalues={"user_id": user_id}, updatevalues={"email_sent": email_sent}, desc="set_renewal_mail_status", )
[ "async", "def", "set_renewal_mail_status", "(", "self", ",", "user_id", ":", "str", ",", "email_sent", ":", "bool", ")", "->", "None", ":", "await", "self", ".", "db_pool", ".", "simple_update_one", "(", "table", "=", "\"account_validity\"", ",", "keyvalues", ...
https://github.com/matrix-org/synapse/blob/8e57584a5859a9002759963eb546d523d2498a01/synapse/storage/databases/main/registration.py#L414-L428
anchore/anchore
35d45722e6a97fb4172a607e8c7f57810b615119
anchore/util/scripting.py
python
ScriptSetExecutor.get_scripts
(self)
return(ret)
Get the scripts at the path in sorted order as set in the module properties :return: a sorted list of scripts
Get the scripts at the path in sorted order as set in the module properties :return: a sorted list of scripts
[ "Get", "the", "scripts", "at", "the", "path", "in", "sorted", "order", "as", "set", "in", "the", "module", "properties", ":", "return", ":", "a", "sorted", "list", "of", "scripts" ]
def get_scripts(self): """ Get the scripts at the path in sorted order as set in the module properties :return: a sorted list of scripts """ ret = list() for d in self.allpaths: scripts = filter(lambda x: x.startswith(self.prefix), os.listdir(d)) scripts.sort(reverse=(not self.sort_ascending)) ret = ret + [os.path.join(d, x) for x in scripts] return(ret)
[ "def", "get_scripts", "(", "self", ")", ":", "ret", "=", "list", "(", ")", "for", "d", "in", "self", ".", "allpaths", ":", "scripts", "=", "filter", "(", "lambda", "x", ":", "x", ".", "startswith", "(", "self", ".", "prefix", ")", ",", "os", ".",...
https://github.com/anchore/anchore/blob/35d45722e6a97fb4172a607e8c7f57810b615119/anchore/util/scripting.py#L132-L143
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/concrete/summations.py
python
_eval_sum_hyper
(f, i, a)
return f.subs(i, 0)*hyperexpand(h), h.convergence_statement
Returns (res, cond). Sums from a to oo.
Returns (res, cond). Sums from a to oo.
[ "Returns", "(", "res", "cond", ")", ".", "Sums", "from", "a", "to", "oo", "." ]
def _eval_sum_hyper(f, i, a): """ Returns (res, cond). Sums from a to oo. """ from sympy.functions import hyper from sympy.simplify import hyperexpand, hypersimp, fraction, simplify from sympy.polys.polytools import Poly, factor if a != 0: return _eval_sum_hyper(f.subs(i, i + a), i, 0) if f.subs(i, 0) == 0: if simplify(f.subs(i, Dummy('i', integer=True, positive=True))) == 0: return S(0), True return _eval_sum_hyper(f.subs(i, i + 1), i, 0) hs = hypersimp(f, i) if hs is None: return None numer, denom = fraction(factor(hs)) top, topl = numer.as_coeff_mul(i) bot, botl = denom.as_coeff_mul(i) ab = [top, bot] factors = [topl, botl] params = [[], []] for k in range(2): for fac in factors[k]: mul = 1 if fac.is_Pow: mul = fac.exp fac = fac.base if not mul.is_Integer: return None p = Poly(fac, i) if p.degree() != 1: return None m, n = p.all_coeffs() ab[k] *= m**mul params[k] += [n/m]*mul # Add "1" to numerator parameters, to account for implicit n! in # hypergeometric series. ap = params[0] + [1] bq = params[1] x = ab[0]/ab[1] h = hyper(ap, bq, x) return f.subs(i, 0)*hyperexpand(h), h.convergence_statement
[ "def", "_eval_sum_hyper", "(", "f", ",", "i", ",", "a", ")", ":", "from", "sympy", ".", "functions", "import", "hyper", "from", "sympy", ".", "simplify", "import", "hyperexpand", ",", "hypersimp", ",", "fraction", ",", "simplify", "from", "sympy", ".", "...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/concrete/summations.py#L688-L734
facebookresearch/Large-Scale-VRD
7ababfe1023941c3653d7aebe9f835a47f5e8277
lib/utils/vis.py
python
vis_mask
(img, mask, col, alpha=0.4, show_border=True, border_thick=1)
return img.astype(np.uint8)
Visualizes a single binary mask.
Visualizes a single binary mask.
[ "Visualizes", "a", "single", "binary", "mask", "." ]
def vis_mask(img, mask, col, alpha=0.4, show_border=True, border_thick=1): """Visualizes a single binary mask.""" img = img.astype(np.float32) idx = np.nonzero(mask) img[idx[0], idx[1], :] *= 1.0 - alpha img[idx[0], idx[1], :] += alpha * col if show_border: _, contours, _ = cv2.findContours( mask.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE) cv2.drawContours(img, contours, -1, _WHITE, border_thick, cv2.LINE_AA) return img.astype(np.uint8)
[ "def", "vis_mask", "(", "img", ",", "mask", ",", "col", ",", "alpha", "=", "0.4", ",", "show_border", "=", "True", ",", "border_thick", "=", "1", ")", ":", "img", "=", "img", ".", "astype", "(", "np", ".", "float32", ")", "idx", "=", "np", ".", ...
https://github.com/facebookresearch/Large-Scale-VRD/blob/7ababfe1023941c3653d7aebe9f835a47f5e8277/lib/utils/vis.py#L88-L102
turicas/brasil.io
f1c371fe828a090510259a5027b49e2e651936b4
brasilio_auth/scripts/migrate_wrong_usernames.py
python
migrate_usernames
(filepath)
[]
def migrate_usernames(filepath): with open(filepath, mode="w") as fobj: writer = csv.DictWriter(fobj, fieldnames=["old_username", "new_username", "email"]) writer.writeheader() for user in User.objects.all(): if is_valid_username(user.username): continue # Define possible usernames based on current and remove any # non-allowed chars possible = [ slug(username, permitted_chars=possible_chars) for username in possible_usernames(user.username, user.email) ] for username in possible: if not User.objects.filter(username=username).exists(): writer.writerow({"old_username": user.username, "new_username": username, "email": user.email}) user.username = username user.save() break print(f"ERROR: could not migrate {user} (tried: {', '.join(possible)})")
[ "def", "migrate_usernames", "(", "filepath", ")", ":", "with", "open", "(", "filepath", ",", "mode", "=", "\"w\"", ")", "as", "fobj", ":", "writer", "=", "csv", ".", "DictWriter", "(", "fobj", ",", "fieldnames", "=", "[", "\"old_username\"", ",", "\"new_...
https://github.com/turicas/brasil.io/blob/f1c371fe828a090510259a5027b49e2e651936b4/brasilio_auth/scripts/migrate_wrong_usernames.py#L50-L70
perseas/Pyrseas
957860839c3b0047293a7a4fa982b1a2b85c7eb4
pyrseas/dbobject/trigger.py
python
TriggerDict.from_map
(self, table, intriggers)
Initalize the dictionary of triggers by converting the input map :param table: table owning the triggers :param intriggers: YAML map defining the triggers
Initalize the dictionary of triggers by converting the input map
[ "Initalize", "the", "dictionary", "of", "triggers", "by", "converting", "the", "input", "map" ]
def from_map(self, table, intriggers): """Initalize the dictionary of triggers by converting the input map :param table: table owning the triggers :param intriggers: YAML map defining the triggers """ for trg in intriggers: inobj = intriggers[trg] self[(table.schema, table.name, trg)] = Trigger.from_map( trg, table, inobj)
[ "def", "from_map", "(", "self", ",", "table", ",", "intriggers", ")", ":", "for", "trg", "in", "intriggers", ":", "inobj", "=", "intriggers", "[", "trg", "]", "self", "[", "(", "table", ".", "schema", ",", "table", ".", "name", ",", "trg", ")", "]"...
https://github.com/perseas/Pyrseas/blob/957860839c3b0047293a7a4fa982b1a2b85c7eb4/pyrseas/dbobject/trigger.py#L248-L257
ssato/python-anyconfig
09af1950f3226759932f5168d52f5e06ab88815c
src/anyconfig/parser.py
python
parse_attrlist_0
(str_: str, avs_sep: str = ':', vs_sep: str = ',', as_sep: str = ';')
return list(attr_val_itr(str_, avs_sep, vs_sep, as_sep))
Simple parser to parse expressions in the form of [ATTR1:VAL0,VAL1,...;ATTR2:VAL0,VAL2,..]. :param str_: input string :param avs_sep: char to separate attribute and values :param vs_sep: char to separate values :param as_sep: char to separate attributes :return: a list of tuples of (key, value | [value]) where key = (Int | String | ...), value = (Int | Bool | String | ...) | [Int | Bool | String | ...] >>> parse_attrlist_0('a:1') [('a', 1)] >>> parse_attrlist_0('a:1;b:xyz') [('a', 1), ('b', 'xyz')] >>> parse_attrlist_0('requires:bash,zsh') [('requires', ['bash', 'zsh'])] >>> parse_attrlist_0('obsoletes:sysdata;conflicts:sysdata-old') [('obsoletes', 'sysdata'), ('conflicts', 'sysdata-old')]
Simple parser to parse expressions in the form of [ATTR1:VAL0,VAL1,...;ATTR2:VAL0,VAL2,..].
[ "Simple", "parser", "to", "parse", "expressions", "in", "the", "form", "of", "[", "ATTR1", ":", "VAL0", "VAL1", "...", ";", "ATTR2", ":", "VAL0", "VAL2", "..", "]", "." ]
def parse_attrlist_0(str_: str, avs_sep: str = ':', vs_sep: str = ',', as_sep: str = ';') -> typing.List[AttrValsT]: """ Simple parser to parse expressions in the form of [ATTR1:VAL0,VAL1,...;ATTR2:VAL0,VAL2,..]. :param str_: input string :param avs_sep: char to separate attribute and values :param vs_sep: char to separate values :param as_sep: char to separate attributes :return: a list of tuples of (key, value | [value]) where key = (Int | String | ...), value = (Int | Bool | String | ...) | [Int | Bool | String | ...] >>> parse_attrlist_0('a:1') [('a', 1)] >>> parse_attrlist_0('a:1;b:xyz') [('a', 1), ('b', 'xyz')] >>> parse_attrlist_0('requires:bash,zsh') [('requires', ['bash', 'zsh'])] >>> parse_attrlist_0('obsoletes:sysdata;conflicts:sysdata-old') [('obsoletes', 'sysdata'), ('conflicts', 'sysdata-old')] """ return list(attr_val_itr(str_, avs_sep, vs_sep, as_sep))
[ "def", "parse_attrlist_0", "(", "str_", ":", "str", ",", "avs_sep", ":", "str", "=", "':'", ",", "vs_sep", ":", "str", "=", "','", ",", "as_sep", ":", "str", "=", "';'", ")", "->", "typing", ".", "List", "[", "AttrValsT", "]", ":", "return", "list"...
https://github.com/ssato/python-anyconfig/blob/09af1950f3226759932f5168d52f5e06ab88815c/src/anyconfig/parser.py#L119-L144
lovelylain/pyctp
fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d
lts/ctp/__init__.py
python
TraderApi.OnRtnFundInByBank
(self, pFundTransfer)
银行发起入金通知
银行发起入金通知
[ "银行发起入金通知" ]
def OnRtnFundInByBank(self, pFundTransfer): """银行发起入金通知"""
[ "def", "OnRtnFundInByBank", "(", "self", ",", "pFundTransfer", ")", ":" ]
https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/lts/ctp/__init__.py#L344-L345
dawsonjon/Chips-2.0
57a986b8df36248bb4736bd84e3e68046b8665af
chips/compiler/types.py
python
is_int
(expression)
return expression.type_() == "int"
Expression object is of type int
Expression object is of type int
[ "Expression", "object", "is", "of", "type", "int" ]
def is_int(expression): """ Expression object is of type int """ return expression.type_() == "int"
[ "def", "is_int", "(", "expression", ")", ":", "return", "expression", ".", "type_", "(", ")", "==", "\"int\"" ]
https://github.com/dawsonjon/Chips-2.0/blob/57a986b8df36248bb4736bd84e3e68046b8665af/chips/compiler/types.py#L26-L29
hyperledger/sawtooth-core
704cd5837c21f53642c06ffc97ba7978a77940b0
cli/sawtooth_cli/format_utils.py
python
format_terminal_row
(headers, example_row)
return format_string
Uses headers and a row of example data to generate a format string for printing a single row of data. Args: headers (tuple of strings): The headers for each column of data example_row (tuple): A representative tuple of strings or ints Returns string: A format string with a size for each column
Uses headers and a row of example data to generate a format string for printing a single row of data.
[ "Uses", "headers", "and", "a", "row", "of", "example", "data", "to", "generate", "a", "format", "string", "for", "printing", "a", "single", "row", "of", "data", "." ]
def format_terminal_row(headers, example_row): """Uses headers and a row of example data to generate a format string for printing a single row of data. Args: headers (tuple of strings): The headers for each column of data example_row (tuple): A representative tuple of strings or ints Returns string: A format string with a size for each column """ def format_column(col): if isinstance(col, str): return '{{:{w}.{w}}}' return '{{:<{w}}}' widths = [max(len(h), len(str(d))) for h, d in zip(headers, example_row)] # Truncate last column to fit terminal width original_last_width = widths[-1] if sys.stdout.isatty(): widths[-1] = max( len(headers[-1]), # console width - width of other columns and gutters - 3 for '...' tty.width() - sum(w + 2 for w in widths[0:-1]) - 3) # Build format string cols = [format_column(c).format(w=w) for c, w in zip(example_row, widths)] format_string = ' '.join(cols) if original_last_width > widths[-1]: format_string += '...' return format_string
[ "def", "format_terminal_row", "(", "headers", ",", "example_row", ")", ":", "def", "format_column", "(", "col", ")", ":", "if", "isinstance", "(", "col", ",", "str", ")", ":", "return", "'{{:{w}.{w}}}'", "return", "'{{:<{w}}}'", "widths", "=", "[", "max", ...
https://github.com/hyperledger/sawtooth-core/blob/704cd5837c21f53642c06ffc97ba7978a77940b0/cli/sawtooth_cli/format_utils.py#L26-L59
JulianEberius/SublimePythonIDE
d70e40abc0c9f347af3204c7b910e0d6bfd6e459
server/lib/python2/rope/base/utils.py
python
ignore_exception
(exception_class)
return _decorator
A decorator that ignores `exception_class` exceptions
A decorator that ignores `exception_class` exceptions
[ "A", "decorator", "that", "ignores", "exception_class", "exceptions" ]
def ignore_exception(exception_class): """A decorator that ignores `exception_class` exceptions""" def _decorator(func): def newfunc(*args, **kwds): try: return func(*args, **kwds) except exception_class: pass return newfunc return _decorator
[ "def", "ignore_exception", "(", "exception_class", ")", ":", "def", "_decorator", "(", "func", ")", ":", "def", "newfunc", "(", "*", "args", ",", "*", "*", "kwds", ")", ":", "try", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwds", ")"...
https://github.com/JulianEberius/SublimePythonIDE/blob/d70e40abc0c9f347af3204c7b910e0d6bfd6e459/server/lib/python2/rope/base/utils.py#L32-L41
whtlkeep/BAT-algorithms
1a339effd3719be5e94e742490e582bf4a03b7c0
The beauty of programming/chapter-2/1-求二进制数中1的个数.py
python
count_one_bit_3
(x)
return count
解法三 时间复杂度是0(M), M是1的个数
解法三 时间复杂度是0(M), M是1的个数
[ "解法三", "时间复杂度是0", "(", "M", ")", "M是1的个数" ]
def count_one_bit_3(x): """ 解法三 时间复杂度是0(M), M是1的个数 """ count = 0 while x: x = x & (x-1) # 此操作可以将最右边的1置为0 count += 1 return count
[ "def", "count_one_bit_3", "(", "x", ")", ":", "count", "=", "0", "while", "x", ":", "x", "=", "x", "&", "(", "x", "-", "1", ")", "# 此操作可以将最右边的1置为0", "count", "+=", "1", "return", "count" ]
https://github.com/whtlkeep/BAT-algorithms/blob/1a339effd3719be5e94e742490e582bf4a03b7c0/The beauty of programming/chapter-2/1-求二进制数中1的个数.py#L13-L21
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/tencentcloud/mariadb/v20170312/mariadb_client.py
python
MariadbClient.DescribeBackupTime
(self, request)
本接口(DescribeBackupTime)用于获取云数据库的备份时间。后台系统将根据此配置定期进行实例备份。 :param request: 调用DescribeBackupTime所需参数的结构体。 :type request: :class:`tencentcloud.mariadb.v20170312.models.DescribeBackupTimeRequest` :rtype: :class:`tencentcloud.mariadb.v20170312.models.DescribeBackupTimeResponse`
本接口(DescribeBackupTime)用于获取云数据库的备份时间。后台系统将根据此配置定期进行实例备份。
[ "本接口(DescribeBackupTime)用于获取云数据库的备份时间。后台系统将根据此配置定期进行实例备份。" ]
def DescribeBackupTime(self, request): """本接口(DescribeBackupTime)用于获取云数据库的备份时间。后台系统将根据此配置定期进行实例备份。 :param request: 调用DescribeBackupTime所需参数的结构体。 :type request: :class:`tencentcloud.mariadb.v20170312.models.DescribeBackupTimeRequest` :rtype: :class:`tencentcloud.mariadb.v20170312.models.DescribeBackupTimeResponse` """ try: params = request._serialize() body = self.call("DescribeBackupTime", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeBackupTimeResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise e else: raise TencentCloudSDKException(e.message, e.message)
[ "def", "DescribeBackupTime", "(", "self", ",", "request", ")", ":", "try", ":", "params", "=", "request", ".", "_serialize", "(", ")", "body", "=", "self", ".", "call", "(", "\"DescribeBackupTime\"", ",", "params", ")", "response", "=", "json", ".", "loa...
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/tencentcloud/mariadb/v20170312/mariadb_client.py#L226-L251
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/tensor/modules/ext_pow_free_module.py
python
ExtPowerFreeModule._an_element_
(self)
return resu
r""" Construct some (unamed) alternating contravariant tensor. EXAMPLES:: sage: M = FiniteRankFreeModule(QQ, 4, name='M') sage: e = M.basis('e') sage: a = M.exterior_power(2)._an_element_() ; a Alternating contravariant tensor of degree 2 on the 4-dimensional vector space M over the Rational Field sage: a.display() 1/2 e_0∧e_1 sage: a = M.exterior_power(3)._an_element_() ; a Alternating contravariant tensor of degree 3 on the 4-dimensional vector space M over the Rational Field sage: a.display() 1/2 e_0∧e_1∧e_2 sage: a = M.exterior_power(4)._an_element_() ; a Alternating contravariant tensor of degree 4 on the 4-dimensional vector space M over the Rational Field sage: a.display() 1/2 e_0∧e_1∧e_2∧e_3 TESTS: When the base module has no default basis, a default basis will be set for it:: sage: M2 = FiniteRankFreeModule(QQ, 4, name='M2') sage: a = M2.exterior_power(2)._an_element_(); a Alternating contravariant tensor of degree 2 on the 4-dimensional vector space M2 over the Rational Field sage: a + a Alternating contravariant tensor of degree 2 on the 4-dimensional vector space M2 over the Rational Field sage: M2.default_basis() Basis (e_0,e_1,e_2,e_3) on the 4-dimensional vector space M2 over the Rational Field
r""" Construct some (unamed) alternating contravariant tensor.
[ "r", "Construct", "some", "(", "unamed", ")", "alternating", "contravariant", "tensor", "." ]
def _an_element_(self): r""" Construct some (unamed) alternating contravariant tensor. EXAMPLES:: sage: M = FiniteRankFreeModule(QQ, 4, name='M') sage: e = M.basis('e') sage: a = M.exterior_power(2)._an_element_() ; a Alternating contravariant tensor of degree 2 on the 4-dimensional vector space M over the Rational Field sage: a.display() 1/2 e_0∧e_1 sage: a = M.exterior_power(3)._an_element_() ; a Alternating contravariant tensor of degree 3 on the 4-dimensional vector space M over the Rational Field sage: a.display() 1/2 e_0∧e_1∧e_2 sage: a = M.exterior_power(4)._an_element_() ; a Alternating contravariant tensor of degree 4 on the 4-dimensional vector space M over the Rational Field sage: a.display() 1/2 e_0∧e_1∧e_2∧e_3 TESTS: When the base module has no default basis, a default basis will be set for it:: sage: M2 = FiniteRankFreeModule(QQ, 4, name='M2') sage: a = M2.exterior_power(2)._an_element_(); a Alternating contravariant tensor of degree 2 on the 4-dimensional vector space M2 over the Rational Field sage: a + a Alternating contravariant tensor of degree 2 on the 4-dimensional vector space M2 over the Rational Field sage: M2.default_basis() Basis (e_0,e_1,e_2,e_3) on the 4-dimensional vector space M2 over the Rational Field """ resu = self.element_class(self._fmodule, self._degree) # Make sure that the base module has a default basis self._fmodule.an_element() sindex = self._fmodule._sindex ind = [sindex + i for i in range(resu._tensor_rank)] resu.set_comp()[ind] = self._fmodule._ring.an_element() return resu
[ "def", "_an_element_", "(", "self", ")", ":", "resu", "=", "self", ".", "element_class", "(", "self", ".", "_fmodule", ",", "self", ".", "_degree", ")", "# Make sure that the base module has a default basis", "self", ".", "_fmodule", ".", "an_element", "(", ")",...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/tensor/modules/ext_pow_free_module.py#L287-L333
biolab/orange3
41685e1c7b1d1babe680113685a2d44bcc9fec0b
Orange/widgets/visualize/utils/__init__.py
python
CanvasText.setPos
(self, x, y)
setPos with adjustment for alignment
setPos with adjustment for alignment
[ "setPos", "with", "adjustment", "for", "alignment" ]
def setPos(self, x, y): """setPos with adjustment for alignment""" self.x, self.y = x, y rect = QGraphicsTextItem.boundingRect(self) if self.vertical: h, w = rect.height(), rect.width() rect.setWidth(h) rect.setHeight(-w) if int(self.alignment & Qt.AlignRight): x -= rect.width() elif int(self.alignment & Qt.AlignHCenter): x -= rect.width() / 2. if int(self.alignment & Qt.AlignBottom): y -= rect.height() elif int(self.alignment & Qt.AlignVCenter): y -= rect.height() / 2. QGraphicsTextItem.setPos(self, x, y)
[ "def", "setPos", "(", "self", ",", "x", ",", "y", ")", ":", "self", ".", "x", ",", "self", ".", "y", "=", "x", ",", "y", "rect", "=", "QGraphicsTextItem", ".", "boundingRect", "(", "self", ")", "if", "self", ".", "vertical", ":", "h", ",", "w",...
https://github.com/biolab/orange3/blob/41685e1c7b1d1babe680113685a2d44bcc9fec0b/Orange/widgets/visualize/utils/__init__.py#L633-L649
0vercl0k/z3-playground
9496201c9a21e8f0ff43015af2527b69018b73ee
proof_unsigned_integer_overflow_chech.py
python
does_overflow_check
(a, b)
return If( UGE((a_64 + b_64), BitVecVal(0x100000000, 64)), # UGE = >= unsigned True, False )
The boring way, where you have to use a greater type to store the temporary result
The boring way, where you have to use a greater type to store the temporary result
[ "The", "boring", "way", "where", "you", "have", "to", "use", "a", "greater", "type", "to", "store", "the", "temporary", "result" ]
def does_overflow_check(a, b): '''The boring way, where you have to use a greater type to store the temporary result''' a_64 = ZeroExt(32, a) b_64 = ZeroExt(32, b) return If( UGE((a_64 + b_64), BitVecVal(0x100000000, 64)), # UGE = >= unsigned True, False )
[ "def", "does_overflow_check", "(", "a", ",", "b", ")", ":", "a_64", "=", "ZeroExt", "(", "32", ",", "a", ")", "b_64", "=", "ZeroExt", "(", "32", ",", "b", ")", "return", "If", "(", "UGE", "(", "(", "a_64", "+", "b_64", ")", ",", "BitVecVal", "(...
https://github.com/0vercl0k/z3-playground/blob/9496201c9a21e8f0ff43015af2527b69018b73ee/proof_unsigned_integer_overflow_chech.py#L37-L46
PennyLaneAI/pennylane
1275736f790ced1d778858ed383448d4a43a4cdd
pennylane/gradients/vjp.py
python
batch_vjp
(tapes, dys, gradient_fn, reduction="append", gradient_kwargs=None)
return gradient_tapes, processing_fn
r"""Generate the gradient tapes and processing function required to compute the vector-Jacobian products of a batch of tapes. Consider a function :math:`\mathbf{f}(\mathbf{x})`. The Jacobian is given by .. math:: \mathbf{J}_{\mathbf{f}}(\mathbf{x}) = \begin{pmatrix} \frac{\partial f_1}{\partial x_1} &\cdots &\frac{\partial f_1}{\partial x_n}\\ \vdots &\ddots &\vdots\\ \frac{\partial f_m}{\partial x_1} &\cdots &\frac{\partial f_m}{\partial x_n}\\ \end{pmatrix}. During backpropagation, the chain rule is applied. For example, consider the cost function :math:`h = y\circ f: \mathbb{R}^n \rightarrow \mathbb{R}`, where :math:`y: \mathbb{R}^m \rightarrow \mathbb{R}`. The gradient is: .. math:: \nabla h(\mathbf{x}) = \frac{\partial y}{\partial \mathbf{f}} \frac{\partial \mathbf{f}}{\partial \mathbf{x}} = \frac{\partial y}{\partial \mathbf{f}} \mathbf{J}_{\mathbf{f}}(\mathbf{x}). Denote :math:`d\mathbf{y} = \frac{\partial y}{\partial \mathbf{f}}`; we can write this in the form of a matrix multiplication: .. math:: \left[\nabla h(\mathbf{x})\right]_{j} = \sum_{i=0}^m d\mathbf{y}_i ~ \mathbf{J}_{ij}. Thus, we can see that the gradient of the cost function is given by the so-called **vector-Jacobian product**; the product of the row-vector :math:`d\mathbf{y}`, representing the gradient of subsequent components of the cost function, and :math:`\mathbf{J}`, the Jacobian of the current node of interest. Args: tapes (Sequence[.QuantumTape]): sequence of quantum tapes to differentiate dys (Sequence[tensor_like]): Sequence of gradient-output vectors ``dy``. Must be the same length as ``tapes``. Each ``dy`` tensor should have shape matching the output shape of the corresponding tape. gradient_fn (callable): the gradient transform to use to differentiate the tapes reduction (str): Determines how the vector-Jacobian products are returned. If ``append``, then the output of the function will be of the form ``List[tensor_like]``, with each element corresponding to the VJP of each input tape. If ``extend``, then the output VJPs will be concatenated. gradient_kwargs (dict): dictionary of keyword arguments to pass when determining the gradients of tapes Returns: List[tensor_like or None]: list of vector-Jacobian products. ``None`` elements corresponds to tapes with no trainable parameters. **Example** Consider the following Torch-compatible quantum tapes: .. code-block:: python x = torch.tensor([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]], requires_grad=True, dtype=torch.float64) def ansatz(x): qml.RX(x[0, 0], wires=0) qml.RY(x[0, 1], wires=1) qml.RZ(x[0, 2], wires=0) qml.CNOT(wires=[0, 1]) qml.RX(x[1, 0], wires=1) qml.RY(x[1, 1], wires=0) qml.RZ(x[1, 2], wires=1) with TorchInterface.apply(qml.tape.JacobianTape()) as tape1: ansatz(x) qml.expval(qml.PauliZ(0)) qml.probs(wires=1) with TorchInterface.apply(qml.tape.JacobianTape()) as tape2: ansatz(x) qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) tapes = [tape1, tape2] Both tapes share the same circuit ansatz, but have different measurement outputs. We can use the ``batch_vjp`` function to compute the vector-Jacobian product, given a list of gradient-output vectors ``dys`` per tape: >>> dys = [torch.tensor([1., 1., 1.], dtype=torch.float64), ... torch.tensor([1.], dtype=torch.float64)] >>> vjp_tapes, fn = qml.gradients.batch_vjp(tapes, dys, qml.gradients.param_shift) Note that each ``dy`` has shape matching the output dimension of the tape (``tape1`` has 1 expectation and 2 probability values --- 3 outputs --- and ``tape2`` has 1 expectation value). Executing the VJP tapes, and applying the processing function: >>> dev = qml.device("default.qubit", wires=2) >>> vjps = fn([t.execute(dev) for t in vjp_tapes]) >>> vjps [tensor([-0.6069, -0.0451, 0.0451, -0.0139, -0.2809, 0.2809], dtype=torch.float64, grad_fn=<ViewBackward>), tensor([ 0.1739, -0.1641, -0.0054, -0.2937, -0.4008, 0.0000], dtype=torch.float64, grad_fn=<ViewBackward>)] We have two VJPs; one per tape. Each one corresponds to the number of parameters on the tapes (6). The output VJPs are also differentiable with respect to the tape parameters: >>> cost = torch.sum(vjps[0] + vjps[1]) >>> cost.backward() >>> x.grad tensor([[-4.7924e-01, -9.0857e-01, -2.4198e-01], [-9.2973e-02, -1.0772e+00, 4.7184e-09]], dtype=torch.float64)
r"""Generate the gradient tapes and processing function required to compute the vector-Jacobian products of a batch of tapes.
[ "r", "Generate", "the", "gradient", "tapes", "and", "processing", "function", "required", "to", "compute", "the", "vector", "-", "Jacobian", "products", "of", "a", "batch", "of", "tapes", "." ]
def batch_vjp(tapes, dys, gradient_fn, reduction="append", gradient_kwargs=None): r"""Generate the gradient tapes and processing function required to compute the vector-Jacobian products of a batch of tapes. Consider a function :math:`\mathbf{f}(\mathbf{x})`. The Jacobian is given by .. math:: \mathbf{J}_{\mathbf{f}}(\mathbf{x}) = \begin{pmatrix} \frac{\partial f_1}{\partial x_1} &\cdots &\frac{\partial f_1}{\partial x_n}\\ \vdots &\ddots &\vdots\\ \frac{\partial f_m}{\partial x_1} &\cdots &\frac{\partial f_m}{\partial x_n}\\ \end{pmatrix}. During backpropagation, the chain rule is applied. For example, consider the cost function :math:`h = y\circ f: \mathbb{R}^n \rightarrow \mathbb{R}`, where :math:`y: \mathbb{R}^m \rightarrow \mathbb{R}`. The gradient is: .. math:: \nabla h(\mathbf{x}) = \frac{\partial y}{\partial \mathbf{f}} \frac{\partial \mathbf{f}}{\partial \mathbf{x}} = \frac{\partial y}{\partial \mathbf{f}} \mathbf{J}_{\mathbf{f}}(\mathbf{x}). Denote :math:`d\mathbf{y} = \frac{\partial y}{\partial \mathbf{f}}`; we can write this in the form of a matrix multiplication: .. math:: \left[\nabla h(\mathbf{x})\right]_{j} = \sum_{i=0}^m d\mathbf{y}_i ~ \mathbf{J}_{ij}. Thus, we can see that the gradient of the cost function is given by the so-called **vector-Jacobian product**; the product of the row-vector :math:`d\mathbf{y}`, representing the gradient of subsequent components of the cost function, and :math:`\mathbf{J}`, the Jacobian of the current node of interest. Args: tapes (Sequence[.QuantumTape]): sequence of quantum tapes to differentiate dys (Sequence[tensor_like]): Sequence of gradient-output vectors ``dy``. Must be the same length as ``tapes``. Each ``dy`` tensor should have shape matching the output shape of the corresponding tape. gradient_fn (callable): the gradient transform to use to differentiate the tapes reduction (str): Determines how the vector-Jacobian products are returned. If ``append``, then the output of the function will be of the form ``List[tensor_like]``, with each element corresponding to the VJP of each input tape. If ``extend``, then the output VJPs will be concatenated. gradient_kwargs (dict): dictionary of keyword arguments to pass when determining the gradients of tapes Returns: List[tensor_like or None]: list of vector-Jacobian products. ``None`` elements corresponds to tapes with no trainable parameters. **Example** Consider the following Torch-compatible quantum tapes: .. code-block:: python x = torch.tensor([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]], requires_grad=True, dtype=torch.float64) def ansatz(x): qml.RX(x[0, 0], wires=0) qml.RY(x[0, 1], wires=1) qml.RZ(x[0, 2], wires=0) qml.CNOT(wires=[0, 1]) qml.RX(x[1, 0], wires=1) qml.RY(x[1, 1], wires=0) qml.RZ(x[1, 2], wires=1) with TorchInterface.apply(qml.tape.JacobianTape()) as tape1: ansatz(x) qml.expval(qml.PauliZ(0)) qml.probs(wires=1) with TorchInterface.apply(qml.tape.JacobianTape()) as tape2: ansatz(x) qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) tapes = [tape1, tape2] Both tapes share the same circuit ansatz, but have different measurement outputs. We can use the ``batch_vjp`` function to compute the vector-Jacobian product, given a list of gradient-output vectors ``dys`` per tape: >>> dys = [torch.tensor([1., 1., 1.], dtype=torch.float64), ... torch.tensor([1.], dtype=torch.float64)] >>> vjp_tapes, fn = qml.gradients.batch_vjp(tapes, dys, qml.gradients.param_shift) Note that each ``dy`` has shape matching the output dimension of the tape (``tape1`` has 1 expectation and 2 probability values --- 3 outputs --- and ``tape2`` has 1 expectation value). Executing the VJP tapes, and applying the processing function: >>> dev = qml.device("default.qubit", wires=2) >>> vjps = fn([t.execute(dev) for t in vjp_tapes]) >>> vjps [tensor([-0.6069, -0.0451, 0.0451, -0.0139, -0.2809, 0.2809], dtype=torch.float64, grad_fn=<ViewBackward>), tensor([ 0.1739, -0.1641, -0.0054, -0.2937, -0.4008, 0.0000], dtype=torch.float64, grad_fn=<ViewBackward>)] We have two VJPs; one per tape. Each one corresponds to the number of parameters on the tapes (6). The output VJPs are also differentiable with respect to the tape parameters: >>> cost = torch.sum(vjps[0] + vjps[1]) >>> cost.backward() >>> x.grad tensor([[-4.7924e-01, -9.0857e-01, -2.4198e-01], [-9.2973e-02, -1.0772e+00, 4.7184e-09]], dtype=torch.float64) """ gradient_kwargs = gradient_kwargs or {} reshape_info = [] gradient_tapes = [] processing_fns = [] # Loop through the tapes and dys vector for tape, dy in zip(tapes, dys): g_tapes, fn = vjp(tape, dy, gradient_fn, gradient_kwargs) reshape_info.append(len(g_tapes)) processing_fns.append(fn) gradient_tapes.extend(g_tapes) def processing_fn(results, nums=None): vjps = [] start = 0 if nums is None: nums = [None] * len(tapes) for t_idx in range(len(tapes)): # extract the correct results from the flat list res_len = reshape_info[t_idx] res_t = results[start : start + res_len] start += res_len # postprocess results to compute the VJP vjp_ = processing_fns[t_idx](res_t, num=nums[t_idx]) if vjp_ is None: if reduction == "append": vjps.append(None) continue if isinstance(reduction, str): getattr(vjps, reduction)(vjp_) elif callable(reduction): reduction(vjps, vjp_) return vjps return gradient_tapes, processing_fn
[ "def", "batch_vjp", "(", "tapes", ",", "dys", ",", "gradient_fn", ",", "reduction", "=", "\"append\"", ",", "gradient_kwargs", "=", "None", ")", ":", "gradient_kwargs", "=", "gradient_kwargs", "or", "{", "}", "reshape_info", "=", "[", "]", "gradient_tapes", ...
https://github.com/PennyLaneAI/pennylane/blob/1275736f790ced1d778858ed383448d4a43a4cdd/pennylane/gradients/vjp.py#L186-L341