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
F8LEFT/DecLLVM
d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c
python/idaapi.py
python
qfile_t_tmpfile
(*args)
return _idaapi.qfile_t_tmpfile(*args)
qfile_t_tmpfile() -> qfile_t
qfile_t_tmpfile() -> qfile_t
[ "qfile_t_tmpfile", "()", "-", ">", "qfile_t" ]
def qfile_t_tmpfile(*args): """ qfile_t_tmpfile() -> qfile_t """ return _idaapi.qfile_t_tmpfile(*args)
[ "def", "qfile_t_tmpfile", "(", "*", "args", ")", ":", "return", "_idaapi", ".", "qfile_t_tmpfile", "(", "*", "args", ")" ]
https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idaapi.py#L51301-L51305
huggingface/datasets
249b4a38390bf1543f5b6e2f3dc208b5689c1c13
datasets/iapp_wiki_qa_squad/iapp_wiki_qa_squad.py
python
IappWikiQaSquad._generate_examples
(self, filepath)
Yields examples.
Yields examples.
[ "Yields", "examples", "." ]
def _generate_examples(self, filepath): """Yields examples.""" with open(filepath, encoding="utf-8") as f: for id_, row in enumerate(f): data = json.loads(row) yield id_, { "question_id": data["question_id"], "article_id": data["article_id"], "title": data["title"], "context": data["context"], "question": data["question"], "answers": { "text": data["answers"]["text"], "answer_start": data["answers"]["answer_start"], "answer_end": data["answers"]["answer_end"], }, }
[ "def", "_generate_examples", "(", "self", ",", "filepath", ")", ":", "with", "open", "(", "filepath", ",", "encoding", "=", "\"utf-8\"", ")", "as", "f", ":", "for", "id_", ",", "row", "in", "enumerate", "(", "f", ")", ":", "data", "=", "json", ".", ...
https://github.com/huggingface/datasets/blob/249b4a38390bf1543f5b6e2f3dc208b5689c1c13/datasets/iapp_wiki_qa_squad/iapp_wiki_qa_squad.py#L101-L118
ryanmcgrath/twython
0c405604285364457f3c309969f11ba68163bd05
twython/api.py
python
Twython.post
(self, endpoint, params=None, version='1.1', json_encoded=False)
return self.request(endpoint, 'POST', params=params, version=version, json_encoded=json_encoded)
Shortcut for POST requests via :class:`request`
Shortcut for POST requests via :class:`request`
[ "Shortcut", "for", "POST", "requests", "via", ":", "class", ":", "request" ]
def post(self, endpoint, params=None, version='1.1', json_encoded=False): """Shortcut for POST requests via :class:`request`""" return self.request(endpoint, 'POST', params=params, version=version, json_encoded=json_encoded)
[ "def", "post", "(", "self", ",", "endpoint", ",", "params", "=", "None", ",", "version", "=", "'1.1'", ",", "json_encoded", "=", "False", ")", ":", "return", "self", ".", "request", "(", "endpoint", ",", "'POST'", ",", "params", "=", "params", ",", "...
https://github.com/ryanmcgrath/twython/blob/0c405604285364457f3c309969f11ba68163bd05/twython/api.py#L281-L283
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/pstats.py
python
Stats.add
(self, *arg_list)
return self
[]
def add(self, *arg_list): if not arg_list: return self for item in reversed(arg_list): if type(self) != type(item): item = Stats(item) self.files += item.files self.total_calls += item.total_calls self.prim_calls += item.prim_calls self.total_tt += item.total_tt for func in item.top_level: self.top_level.add(func) if self.max_name_len < item.max_name_len: self.max_name_len = item.max_name_len self.fcn_list = None for func, stat in item.stats.items(): if func in self.stats: old_func_stat = self.stats[func] else: old_func_stat = (0, 0, 0, 0, {},) self.stats[func] = add_func_stats(old_func_stat, stat) return self
[ "def", "add", "(", "self", ",", "*", "arg_list", ")", ":", "if", "not", "arg_list", ":", "return", "self", "for", "item", "in", "reversed", "(", "arg_list", ")", ":", "if", "type", "(", "self", ")", "!=", "type", "(", "item", ")", ":", "item", "=...
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/pstats.py#L168-L192
rsc-dev/loophole
f9389c73f06b419c97ad32847346663a30d80225
loophole/polar/__init__.py
python
Protocol.read
(path)
return Protocol.pb_pftp_operation(path, 0x00)
Create read path message. :param path: Path to read. :return: Read path message bytes array.
Create read path message.
[ "Create", "read", "path", "message", "." ]
def read(path): """ Create read path message. :param path: Path to read. :return: Read path message bytes array. """ return Protocol.pb_pftp_operation(path, 0x00)
[ "def", "read", "(", "path", ")", ":", "return", "Protocol", ".", "pb_pftp_operation", "(", "path", ",", "0x00", ")" ]
https://github.com/rsc-dev/loophole/blob/f9389c73f06b419c97ad32847346663a30d80225/loophole/polar/__init__.py#L127-L134
bastibe/python-soundfile
d1d125f5749780b0b068b5fcb49d8e84f7f4f045
soundfile.py
python
SoundFile.close
(self)
Close the file. Can be called multiple times.
Close the file. Can be called multiple times.
[ "Close", "the", "file", ".", "Can", "be", "called", "multiple", "times", "." ]
def close(self): """Close the file. Can be called multiple times.""" if not self.closed: # be sure to flush data to disk before closing the file self.flush() err = _snd.sf_close(self._file) self._file = None _error_check(err)
[ "def", "close", "(", "self", ")", ":", "if", "not", "self", ".", "closed", ":", "# be sure to flush data to disk before closing the file", "self", ".", "flush", "(", ")", "err", "=", "_snd", ".", "sf_close", "(", "self", ".", "_file", ")", "self", ".", "_f...
https://github.com/bastibe/python-soundfile/blob/d1d125f5749780b0b068b5fcb49d8e84f7f4f045/soundfile.py#L1161-L1168
selfteaching/selfteaching-python-camp
9982ee964b984595e7d664b07c389cddaf158f1e
exercises/1901040051/d07/mymodule/stats_word.py
python
stats_text
(text)
combine the stats_text_cn and stats_text_en,count english words and chinese characters
combine the stats_text_cn and stats_text_en,count english words and chinese characters
[ "combine", "the", "stats_text_cn", "and", "stats_text_en", "count", "english", "words", "and", "chinese", "characters" ]
def stats_text(text): # 合并中英文词频统计, 如何调用两个函数 【原来就是两个函数相加这么简单。】 """combine the stats_text_cn and stats_text_en,count english words and chinese characters""" a = stats_text_en(text) b = stats_text_cn(text) c = a+b
[ "def", "stats_text", "(", "text", ")", ":", "# 合并中英文词频统计, 如何调用两个函数 【原来就是两个函数相加这么简单。】", "a", "=", "stats_text_en", "(", "text", ")", "b", "=", "stats_text_cn", "(", "text", ")", "c", "=", "a", "+", "b" ]
https://github.com/selfteaching/selfteaching-python-camp/blob/9982ee964b984595e7d664b07c389cddaf158f1e/exercises/1901040051/d07/mymodule/stats_word.py#L183-L191
wbond/oscrypto
d40c62577706682a0f6da5616ad09964f1c9137d
oscrypto/_mac/_core_foundation_ctypes.py
python
CFHelpers.cf_string_to_unicode
(value)
return string
Creates a python unicode string from a CFString object :param value: The CFString to convert :return: A python unicode string
Creates a python unicode string from a CFString object
[ "Creates", "a", "python", "unicode", "string", "from", "a", "CFString", "object" ]
def cf_string_to_unicode(value): """ Creates a python unicode string from a CFString object :param value: The CFString to convert :return: A python unicode string """ string = CoreFoundation.CFStringGetCStringPtr( _cast_pointer_p(value), kCFStringEncodingUTF8 ) if string is None: buffer = buffer_from_bytes(1024) result = CoreFoundation.CFStringGetCString( _cast_pointer_p(value), buffer, 1024, kCFStringEncodingUTF8 ) if not result: raise OSError('Error copying C string from CFStringRef') string = byte_string_from_buffer(buffer) if string is not None: string = string.decode('utf-8') return string
[ "def", "cf_string_to_unicode", "(", "value", ")", ":", "string", "=", "CoreFoundation", ".", "CFStringGetCStringPtr", "(", "_cast_pointer_p", "(", "value", ")", ",", "kCFStringEncodingUTF8", ")", "if", "string", "is", "None", ":", "buffer", "=", "buffer_from_bytes...
https://github.com/wbond/oscrypto/blob/d40c62577706682a0f6da5616ad09964f1c9137d/oscrypto/_mac/_core_foundation_ctypes.py#L335-L363
andyzsf/TuShare
92787ad0cd492614bdb6389b71a19c80d1c8c9ae
tushare/datayes/macro.py
python
Macro.ItalyDataInterestRate
(self, indicID='', indicName='', beginDate='', endDate='', field='')
return _ret_data(code, result)
包含意大利利率数据,具体指标可参见API文档;历史数据从1980年开始,按月更新。
包含意大利利率数据,具体指标可参见API文档;历史数据从1980年开始,按月更新。
[ "包含意大利利率数据,具体指标可参见API文档;历史数据从1980年开始,按月更新。" ]
def ItalyDataInterestRate(self, indicID='', indicName='', beginDate='', endDate='', field=''): """ 包含意大利利率数据,具体指标可参见API文档;历史数据从1980年开始,按月更新。 """ code, result = self.client.getData(vs.ITALYDATAINTERESTRATE%(indicID, indicName, beginDate, endDate, field)) return _ret_data(code, result)
[ "def", "ItalyDataInterestRate", "(", "self", ",", "indicID", "=", "''", ",", "indicName", "=", "''", ",", "beginDate", "=", "''", ",", "endDate", "=", "''", ",", "field", "=", "''", ")", ":", "code", ",", "result", "=", "self", ".", "client", ".", ...
https://github.com/andyzsf/TuShare/blob/92787ad0cd492614bdb6389b71a19c80d1c8c9ae/tushare/datayes/macro.py#L668-L673
rembo10/headphones
b3199605be1ebc83a7a8feab6b1e99b64014187c
lib/concurrent/futures/_base.py
python
_AllCompletedWaiter.__init__
(self, num_pending_calls, stop_on_exception)
[]
def __init__(self, num_pending_calls, stop_on_exception): self.num_pending_calls = num_pending_calls self.stop_on_exception = stop_on_exception self.lock = threading.Lock() super(_AllCompletedWaiter, self).__init__()
[ "def", "__init__", "(", "self", ",", "num_pending_calls", ",", "stop_on_exception", ")", ":", "self", ".", "num_pending_calls", "=", "num_pending_calls", "self", ".", "stop_on_exception", "=", "stop_on_exception", "self", ".", "lock", "=", "threading", ".", "Lock"...
https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/concurrent/futures/_base.py#L118-L122
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/itsdangerous.py
python
Serializer.dump
(self, obj, f, salt=None)
Like :meth:`dumps` but dumps into a file. The file handle has to be compatible with what the internal serializer expects.
Like :meth:`dumps` but dumps into a file. The file handle has to be compatible with what the internal serializer expects.
[ "Like", ":", "meth", ":", "dumps", "but", "dumps", "into", "a", "file", ".", "The", "file", "handle", "has", "to", "be", "compatible", "with", "what", "the", "internal", "serializer", "expects", "." ]
def dump(self, obj, f, salt=None): """Like :meth:`dumps` but dumps into a file. The file handle has to be compatible with what the internal serializer expects. """ f.write(self.dumps(obj, salt))
[ "def", "dump", "(", "self", ",", "obj", ",", "f", ",", "salt", "=", "None", ")", ":", "f", ".", "write", "(", "self", ".", "dumps", "(", "obj", ",", "salt", ")", ")" ]
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/itsdangerous.py#L571-L575
edfungus/Crouton
ada98b3930192938a48909072b45cb84b945f875
clients/esp8266_clients/venv/lib/python2.7/site-packages/pip/_vendor/cachecontrol/caches/redis_cache.py
python
RedisCache.clear
(self)
Helper for clearing all the keys in a database. Use with caution!
Helper for clearing all the keys in a database. Use with caution!
[ "Helper", "for", "clearing", "all", "the", "keys", "in", "a", "database", ".", "Use", "with", "caution!" ]
def clear(self): """Helper for clearing all the keys in a database. Use with caution!""" for key in self.conn.keys(): self.conn.delete(key)
[ "def", "clear", "(", "self", ")", ":", "for", "key", "in", "self", ".", "conn", ".", "keys", "(", ")", ":", "self", ".", "conn", ".", "delete", "(", "key", ")" ]
https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/esp8266_clients/venv/lib/python2.7/site-packages/pip/_vendor/cachecontrol/caches/redis_cache.py#L34-L38
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v1_secret.py
python
V1Secret.immutable
(self)
return self._immutable
Gets the immutable of this V1Secret. # noqa: E501 Immutable, if set to true, ensures that data stored in the Secret cannot be updated (only object metadata can be modified). If not set to true, the field can be modified at any time. Defaulted to nil. # noqa: E501 :return: The immutable of this V1Secret. # noqa: E501 :rtype: bool
Gets the immutable of this V1Secret. # noqa: E501
[ "Gets", "the", "immutable", "of", "this", "V1Secret", ".", "#", "noqa", ":", "E501" ]
def immutable(self): """Gets the immutable of this V1Secret. # noqa: E501 Immutable, if set to true, ensures that data stored in the Secret cannot be updated (only object metadata can be modified). If not set to true, the field can be modified at any time. Defaulted to nil. # noqa: E501 :return: The immutable of this V1Secret. # noqa: E501 :rtype: bool """ return self._immutable
[ "def", "immutable", "(", "self", ")", ":", "return", "self", ".", "_immutable" ]
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1_secret.py#L132-L140
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/plugins/attack/db/sqlmap/thirdparty/colorama/ansitowin32.py
python
is_stream_closed
(stream)
return not hasattr(stream, 'closed') or stream.closed
[]
def is_stream_closed(stream): return not hasattr(stream, 'closed') or stream.closed
[ "def", "is_stream_closed", "(", "stream", ")", ":", "return", "not", "hasattr", "(", "stream", ",", "'closed'", ")", "or", "stream", ".", "closed" ]
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/plugins/attack/db/sqlmap/thirdparty/colorama/ansitowin32.py#L16-L17
Pymol-Scripts/Pymol-script-repo
bcd7bb7812dc6db1595953dfa4471fa15fb68c77
modules/pdb2pqr/src/aa.py
python
HIS.__init__
(self, atoms, ref)
Initialize the class Parameters atoms: A list of Atom objects to be stored in this class (list)
Initialize the class
[ "Initialize", "the", "class" ]
def __init__(self, atoms, ref): """ Initialize the class Parameters atoms: A list of Atom objects to be stored in this class (list) """ Amino.__init__(self, atoms, ref) self.reference = ref
[ "def", "__init__", "(", "self", ",", "atoms", ",", "ref", ")", ":", "Amino", ".", "__init__", "(", "self", ",", "atoms", ",", "ref", ")", "self", ".", "reference", "=", "ref" ]
https://github.com/Pymol-Scripts/Pymol-script-repo/blob/bcd7bb7812dc6db1595953dfa4471fa15fb68c77/modules/pdb2pqr/src/aa.py#L365-L374
PacktPublishing/Mastering-Natural-Language-Processing-with-Python
1dd1091e691d8d7febd930b1f4c51519dce2e96e
__pycache__/replacers.py
python
WordReplacer.replace
(self, word)
return self.word_map.get(word, word)
[]
def replace(self, word): return self.word_map.get(word, word)
[ "def", "replace", "(", "self", ",", "word", ")", ":", "return", "self", ".", "word_map", ".", "get", "(", "word", ",", "word", ")" ]
https://github.com/PacktPublishing/Mastering-Natural-Language-Processing-with-Python/blob/1dd1091e691d8d7febd930b1f4c51519dce2e96e/__pycache__/replacers.py#L43-L44
plaid/plaid-python
8c60fca608e426f3ff30da8857775946d29e122c
plaid/model/institution.py
python
Institution.additional_properties_type
()
return (bool, date, datetime, dict, float, int, list, str, none_type,)
This must be a method because a model may have properties that are of type self, this must run after the class is loaded
This must be a method because a model may have properties that are of type self, this must run after the class is loaded
[ "This", "must", "be", "a", "method", "because", "a", "model", "may", "have", "properties", "that", "are", "of", "type", "self", "this", "must", "run", "after", "the", "class", "is", "loaded" ]
def additional_properties_type(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded """ lazy_import() return (bool, date, datetime, dict, float, int, list, str, none_type,)
[ "def", "additional_properties_type", "(", ")", ":", "lazy_import", "(", ")", "return", "(", "bool", ",", "date", ",", "datetime", ",", "dict", ",", "float", ",", "int", ",", "list", ",", "str", ",", "none_type", ",", ")" ]
https://github.com/plaid/plaid-python/blob/8c60fca608e426f3ff30da8857775946d29e122c/plaid/model/institution.py#L71-L77
ivre/ivre
5728855b51c0ae2e59450a1c3a782febcad2128b
ivre/db/mongo.py
python
MongoDB._migrate_update_record
(self, colname, recid, update)
return self.db[colname].update_one({"_id": recid}, update)
Define how an update is handled. Purpose-specific subclasses may want to do something special here, e.g., mix with other records.
Define how an update is handled. Purpose-specific subclasses may want to do something special here, e.g., mix with other records.
[ "Define", "how", "an", "update", "is", "handled", ".", "Purpose", "-", "specific", "subclasses", "may", "want", "to", "do", "something", "special", "here", "e", ".", "g", ".", "mix", "with", "other", "records", "." ]
def _migrate_update_record(self, colname, recid, update): """Define how an update is handled. Purpose-specific subclasses may want to do something special here, e.g., mix with other records. """ return self.db[colname].update_one({"_id": recid}, update)
[ "def", "_migrate_update_record", "(", "self", ",", "colname", ",", "recid", ",", "update", ")", ":", "return", "self", ".", "db", "[", "colname", "]", ".", "update_one", "(", "{", "\"_id\"", ":", "recid", "}", ",", "update", ")" ]
https://github.com/ivre/ivre/blob/5728855b51c0ae2e59450a1c3a782febcad2128b/ivre/db/mongo.py#L272-L277
ahmetcemturan/SFACT
7576e29ba72b33e5058049b77b7b558875542747
skeinforge_application/skeinforge_plugins/craft_plugins/coil.py
python
CoilRepository.execute
(self)
Coil button has been clicked.
Coil button has been clicked.
[ "Coil", "button", "has", "been", "clicked", "." ]
def execute(self): "Coil button has been clicked." fileNames = skeinforge_polyfile.getFileOrDirectoryTypesUnmodifiedGcode(self.fileNameInput.value, fabmetheus_interpret.getImportPluginFileNames(), self.fileNameInput.wasCancelled) for fileName in fileNames: writeOutput(fileName)
[ "def", "execute", "(", "self", ")", ":", "fileNames", "=", "skeinforge_polyfile", ".", "getFileOrDirectoryTypesUnmodifiedGcode", "(", "self", ".", "fileNameInput", ".", "value", ",", "fabmetheus_interpret", ".", "getImportPluginFileNames", "(", ")", ",", "self", "."...
https://github.com/ahmetcemturan/SFACT/blob/7576e29ba72b33e5058049b77b7b558875542747/skeinforge_application/skeinforge_plugins/craft_plugins/coil.py#L86-L90
gleeda/memtriage
c24f4859995cccb9d88ccc0118d90693019cc1d5
volatility/volatility/plugins/patcher.py
python
PatcherObject.get_name
(self)
return self.name
Returns the name of the patcher
Returns the name of the patcher
[ "Returns", "the", "name", "of", "the", "patcher" ]
def get_name(self): """Returns the name of the patcher""" return self.name
[ "def", "get_name", "(", "self", ")", ":", "return", "self", ".", "name" ]
https://github.com/gleeda/memtriage/blob/c24f4859995cccb9d88ccc0118d90693019cc1d5/volatility/volatility/plugins/patcher.py#L145-L147
angr/angr
4b04d56ace135018083d36d9083805be8146688b
angr/engines/soot/expressions/arrayref.py
python
SimSootExpr_ArrayRef._execute
(self)
[]
def _execute(self): array_base_local = self._translate_value(self.expr.base) array_base = self.state.memory.load(array_base_local) if array_base is not None: # translate idx and check against array bounds idx = SimSootValue_ArrayRef.translate_array_index(self.expr.index, self.state) SimSootValue_ArrayRef.check_array_bounds(idx, array_base, self.state) # load element array_ref = SimSootValue_ArrayRef(array_base, idx) self.expr = self.state.memory.load(array_ref) else: l.warning("Trying to access a non existing array! (%r)", self.expr)
[ "def", "_execute", "(", "self", ")", ":", "array_base_local", "=", "self", ".", "_translate_value", "(", "self", ".", "expr", ".", "base", ")", "array_base", "=", "self", ".", "state", ".", "memory", ".", "load", "(", "array_base_local", ")", "if", "arra...
https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/engines/soot/expressions/arrayref.py#L12-L23
shchur/gnn-benchmark
1e72912a0810cdf27ae54fd589a3b43358a2b161
gnnbench/early_stopping.py
python
GCNCriterion.__init__
(self, patience, sess, _log)
[]
def __init__(self, patience, sess, _log): super().__init__(patience, sess, _log) self.val_losses = []
[ "def", "__init__", "(", "self", ",", "patience", ",", "sess", ",", "_log", ")", ":", "super", "(", ")", ".", "__init__", "(", "patience", ",", "sess", ",", "_log", ")", "self", ".", "val_losses", "=", "[", "]" ]
https://github.com/shchur/gnn-benchmark/blob/1e72912a0810cdf27ae54fd589a3b43358a2b161/gnnbench/early_stopping.py#L35-L37
PaddlePaddle/PaddleX
2bab73f81ab54e328204e7871e6ae4a82e719f5d
paddlex/ppcls/arch/backbone/legendary_models/pp_lcnet.py
python
SEModule.__init__
(self, channel, reduction=4)
[]
def __init__(self, channel, reduction=4): super().__init__() self.avg_pool = AdaptiveAvgPool2D(1) self.conv1 = Conv2D( in_channels=channel, out_channels=channel // reduction, kernel_size=1, stride=1, padding=0) self.relu = nn.ReLU() self.conv2 = Conv2D( in_channels=channel // reduction, out_channels=channel, kernel_size=1, stride=1, padding=0) self.hardsigmoid = nn.Hardsigmoid()
[ "def", "__init__", "(", "self", ",", "channel", ",", "reduction", "=", "4", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "self", ".", "avg_pool", "=", "AdaptiveAvgPool2D", "(", "1", ")", "self", ".", "conv1", "=", "Conv2D", "(", "in_channe...
https://github.com/PaddlePaddle/PaddleX/blob/2bab73f81ab54e328204e7871e6ae4a82e719f5d/paddlex/ppcls/arch/backbone/legendary_models/pp_lcnet.py#L140-L156
boto/boto
b2a6f08122b2f1b89888d2848e730893595cd001
boto/auth.py
python
HmacAuthV4Handler.headers_to_sign
(self, http_request)
return headers_to_sign
Select the headers from the request that need to be included in the StringToSign.
Select the headers from the request that need to be included in the StringToSign.
[ "Select", "the", "headers", "from", "the", "request", "that", "need", "to", "be", "included", "in", "the", "StringToSign", "." ]
def headers_to_sign(self, http_request): """ Select the headers from the request that need to be included in the StringToSign. """ host_header_value = self.host_header(self.host, http_request) if http_request.headers.get('Host'): host_header_value = http_request.headers['Host'] headers_to_sign = {'Host': host_header_value} for name, value in http_request.headers.items(): lname = name.lower() if lname.startswith('x-amz'): if isinstance(value, bytes): value = value.decode('utf-8') headers_to_sign[name] = value return headers_to_sign
[ "def", "headers_to_sign", "(", "self", ",", "http_request", ")", ":", "host_header_value", "=", "self", ".", "host_header", "(", "self", ".", "host", ",", "http_request", ")", "if", "http_request", ".", "headers", ".", "get", "(", "'Host'", ")", ":", "host...
https://github.com/boto/boto/blob/b2a6f08122b2f1b89888d2848e730893595cd001/boto/auth.py#L359-L374
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/rfc822.py
python
Message.getaddr
(self, name)
Get a single address from a header, as a tuple. An example return value: ('Guido van Rossum', 'guido@cwi.nl')
Get a single address from a header, as a tuple.
[ "Get", "a", "single", "address", "from", "a", "header", "as", "a", "tuple", "." ]
def getaddr(self, name): """Get a single address from a header, as a tuple. An example return value: ('Guido van Rossum', 'guido@cwi.nl') """ # New, by Ben Escoto alist = self.getaddrlist(name) if alist: return alist[0] else: return (None, None)
[ "def", "getaddr", "(", "self", ",", "name", ")", ":", "# New, by Ben Escoto", "alist", "=", "self", ".", "getaddrlist", "(", "name", ")", "if", "alist", ":", "return", "alist", "[", "0", "]", "else", ":", "return", "(", "None", ",", "None", ")" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/rfc822.py#L320-L331
python-discord/bot
26c5587ac13e5414361bb6e7ada42983b81014d2
bot/exts/backend/branding/_cog.py
python
make_embed
(title: str, description: str, *, success: bool)
return discord.Embed(title=title[:256], description=description[:4096], colour=colour)
Construct simple response embed. If `success` is True, use green colour, otherwise red. For both `title` and `description`, empty string are valid values ~ fields will be empty.
Construct simple response embed.
[ "Construct", "simple", "response", "embed", "." ]
def make_embed(title: str, description: str, *, success: bool) -> discord.Embed: """ Construct simple response embed. If `success` is True, use green colour, otherwise red. For both `title` and `description`, empty string are valid values ~ fields will be empty. """ colour = Colours.soft_green if success else Colours.soft_red return discord.Embed(title=title[:256], description=description[:4096], colour=colour)
[ "def", "make_embed", "(", "title", ":", "str", ",", "description", ":", "str", ",", "*", ",", "success", ":", "bool", ")", "->", "discord", ".", "Embed", ":", "colour", "=", "Colours", ".", "soft_green", "if", "success", "else", "Colours", ".", "soft_r...
https://github.com/python-discord/bot/blob/26c5587ac13e5414361bb6e7ada42983b81014d2/bot/exts/backend/branding/_cog.py#L45-L54
exaile/exaile
a7b58996c5c15b3aa7b9975ac13ee8f784ef4689
xlgui/widgets/info.py
python
StatusbarTextFormatter.get_playlist_count
(self, selection='none')
return text % count
Retrieves the count of tracks in either the full playlist or the current selection :param selection: 'none' for playlist count only, 'override' for selection count if tracks are selected, playlist count otherwise, 'only' for selection count only :type selection: string
Retrieves the count of tracks in either the full playlist or the current selection
[ "Retrieves", "the", "count", "of", "tracks", "in", "either", "the", "full", "playlist", "or", "the", "current", "selection" ]
def get_playlist_count(self, selection='none'): """ Retrieves the count of tracks in either the full playlist or the current selection :param selection: 'none' for playlist count only, 'override' for selection count if tracks are selected, playlist count otherwise, 'only' for selection count only :type selection: string """ if not settings.get_option( 'gui/show_status_bar_count_tracks_in_playlist', True ): return '' page = xlgui.main.get_selected_page() if not isinstance(page, playlist.PlaylistPage) and not isinstance( page, queue.QueuePage ): return '' playlist_count = len(page.playlist) selection_count = page.view.get_selection_count() if selection == 'none': count = playlist_count text = _('%d showing') elif selection == 'override': if selection_count > 1: count = selection_count text = _('%d selected') else: count = playlist_count text = _('%d showing') elif selection == 'only': if selection_count > 1: count = selection_count text = _('%d selected') else: count = 0 else: raise ValueError( 'Invalid argument "%s" passed to parameter ' '"selection" for "playlist_count", possible arguments are ' '"none", "override" and "only"' % selection ) if count == 0: return '' return text % count
[ "def", "get_playlist_count", "(", "self", ",", "selection", "=", "'none'", ")", ":", "if", "not", "settings", ".", "get_option", "(", "'gui/show_status_bar_count_tracks_in_playlist'", ",", "True", ")", ":", "return", "''", "page", "=", "xlgui", ".", "main", "....
https://github.com/exaile/exaile/blob/a7b58996c5c15b3aa7b9975ac13ee8f784ef4689/xlgui/widgets/info.py#L419-L470
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/docutils-0.14/docutils/utils/smartquotes.py
python
educateDashes
(text)
return text
Parameter: String (unicode or bytes). Returns: The `text`, with each instance of "--" translated to an em-dash character.
Parameter: String (unicode or bytes). Returns: The `text`, with each instance of "--" translated to an em-dash character.
[ "Parameter", ":", "String", "(", "unicode", "or", "bytes", ")", ".", "Returns", ":", "The", "text", "with", "each", "instance", "of", "--", "translated", "to", "an", "em", "-", "dash", "character", "." ]
def educateDashes(text): """ Parameter: String (unicode or bytes). Returns: The `text`, with each instance of "--" translated to an em-dash character. """ text = re.sub(r"""---""", smartchars.endash, text) # en (yes, backwards) text = re.sub(r"""--""", smartchars.emdash, text) # em (yes, backwards) return text
[ "def", "educateDashes", "(", "text", ")", ":", "text", "=", "re", ".", "sub", "(", "r\"\"\"---\"\"\"", ",", "smartchars", ".", "endash", ",", "text", ")", "# en (yes, backwards)", "text", "=", "re", ".", "sub", "(", "r\"\"\"--\"\"\"", ",", "smartchars", "...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/docutils-0.14/docutils/utils/smartquotes.py#L767-L776
Chia-Network/chia-blockchain
34d44c1324ae634a0896f7b02eaa2802af9526cd
chia/wallet/wallet_transaction_store.py
python
WalletTransactionStore.get_all_transactions
(self)
return records
Returns all stored transactions.
Returns all stored transactions.
[ "Returns", "all", "stored", "transactions", "." ]
async def get_all_transactions(self) -> List[TransactionRecord]: """ Returns all stored transactions. """ cursor = await self.db_connection.execute("SELECT * from transaction_record") rows = await cursor.fetchall() await cursor.close() records = [] for row in rows: record = TransactionRecord.from_bytes(row[0]) records.append(record) return records
[ "async", "def", "get_all_transactions", "(", "self", ")", "->", "List", "[", "TransactionRecord", "]", ":", "cursor", "=", "await", "self", ".", "db_connection", ".", "execute", "(", "\"SELECT * from transaction_record\"", ")", "rows", "=", "await", "cursor", "....
https://github.com/Chia-Network/chia-blockchain/blob/34d44c1324ae634a0896f7b02eaa2802af9526cd/chia/wallet/wallet_transaction_store.py#L409-L422
ray-project/ray
703c1610348615dcb8c2d141a0c46675084660f5
python/ray/util/client/api.py
python
ClientAPI._internal_kv_del
(self, key: bytes)
return self.worker.internal_kv_del(as_bytes(key))
Hook for internal_kv._internal_kv_del.
Hook for internal_kv._internal_kv_del.
[ "Hook", "for", "internal_kv", ".", "_internal_kv_del", "." ]
def _internal_kv_del(self, key: bytes) -> None: """Hook for internal_kv._internal_kv_del.""" return self.worker.internal_kv_del(as_bytes(key))
[ "def", "_internal_kv_del", "(", "self", ",", "key", ":", "bytes", ")", "->", "None", ":", "return", "self", ".", "worker", ".", "internal_kv_del", "(", "as_bytes", "(", "key", ")", ")" ]
https://github.com/ray-project/ray/blob/703c1610348615dcb8c2d141a0c46675084660f5/python/ray/util/client/api.py#L312-L314
barronalex/Dynamic-Memory-Networks-in-TensorFlow
6b35d5b397f70656d243855fcb24fd8dd1779e70
dmn_plus.py
python
DMN_PLUS.get_attention
(self, q_vec, prev_memory, fact_vec, reuse)
return attention
Use question vector and previous memory to create scalar attention for current fact
Use question vector and previous memory to create scalar attention for current fact
[ "Use", "question", "vector", "and", "previous", "memory", "to", "create", "scalar", "attention", "for", "current", "fact" ]
def get_attention(self, q_vec, prev_memory, fact_vec, reuse): """Use question vector and previous memory to create scalar attention for current fact""" with tf.variable_scope("attention", reuse=reuse): features = [fact_vec*q_vec, fact_vec*prev_memory, tf.abs(fact_vec - q_vec), tf.abs(fact_vec - prev_memory)] feature_vec = tf.concat(features, 1) attention = tf.contrib.layers.fully_connected(feature_vec, self.config.embed_size, activation_fn=tf.nn.tanh, reuse=reuse, scope="fc1") attention = tf.contrib.layers.fully_connected(attention, 1, activation_fn=None, reuse=reuse, scope="fc2") return attention
[ "def", "get_attention", "(", "self", ",", "q_vec", ",", "prev_memory", ",", "fact_vec", ",", "reuse", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"attention\"", ",", "reuse", "=", "reuse", ")", ":", "features", "=", "[", "fact_vec", "*", "q_vec...
https://github.com/barronalex/Dynamic-Memory-Networks-in-TensorFlow/blob/6b35d5b397f70656d243855fcb24fd8dd1779e70/dmn_plus.py#L172-L193
keiffster/program-y
8c99b56f8c32f01a7b9887b5daae9465619d0385
src/programy/nlp/sentiment/textblob_sentiment.py
python
TextBlobSentimentAnalyser.analyse_each
(self, text)
return sentiments
[]
def analyse_each(self, text): blob = TextBlob(text) sentiments = [] for sentence in blob.sentences: sentiments.append((sentence.sentiment.polarity, sentence.sentiment.subjectivity)) return sentiments
[ "def", "analyse_each", "(", "self", ",", "text", ")", ":", "blob", "=", "TextBlob", "(", "text", ")", "sentiments", "=", "[", "]", "for", "sentence", "in", "blob", ".", "sentences", ":", "sentiments", ".", "append", "(", "(", "sentence", ".", "sentimen...
https://github.com/keiffster/program-y/blob/8c99b56f8c32f01a7b9887b5daae9465619d0385/src/programy/nlp/sentiment/textblob_sentiment.py#L23-L30
securityclippy/elasticintel
aa08d3e9f5ab1c000128e95161139ce97ff0e334
ingest_feed_lambda/numpy/lib/shape_base.py
python
get_array_prepare
(*args)
return None
Find the wrapper for the array with the highest priority. In case of ties, leftmost wins. If no wrapper is found, return None
Find the wrapper for the array with the highest priority.
[ "Find", "the", "wrapper", "for", "the", "array", "with", "the", "highest", "priority", "." ]
def get_array_prepare(*args): """Find the wrapper for the array with the highest priority. In case of ties, leftmost wins. If no wrapper is found, return None """ wrappers = sorted((getattr(x, '__array_priority__', 0), -i, x.__array_prepare__) for i, x in enumerate(args) if hasattr(x, '__array_prepare__')) if wrappers: return wrappers[-1][-1] return None
[ "def", "get_array_prepare", "(", "*", "args", ")", ":", "wrappers", "=", "sorted", "(", "(", "getattr", "(", "x", ",", "'__array_priority__'", ",", "0", ")", ",", "-", "i", ",", "x", ".", "__array_prepare__", ")", "for", "i", ",", "x", "in", "enumera...
https://github.com/securityclippy/elasticintel/blob/aa08d3e9f5ab1c000128e95161139ce97ff0e334/ingest_feed_lambda/numpy/lib/shape_base.py#L703-L713
inspurer/WorkAttendanceSystem
1221e2d67bdf5bb15fe99517cc3ded58ccb066df
V2.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/_vendor/distlib/_backport/tarfile.py
python
TarFile.next
(self)
return tarinfo
Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no more available.
Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no more available.
[ "Return", "the", "next", "member", "of", "the", "archive", "as", "a", "TarInfo", "object", "when", "TarFile", "is", "opened", "for", "reading", ".", "Return", "None", "if", "there", "is", "no", "more", "available", "." ]
def next(self): """Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no more available. """ self._check("ra") if self.firstmember is not None: m = self.firstmember self.firstmember = None return m # Read the next block. self.fileobj.seek(self.offset) tarinfo = None while True: try: tarinfo = self.tarinfo.fromtarfile(self) except EOFHeaderError as e: if self.ignore_zeros: self._dbg(2, "0x%X: %s" % (self.offset, e)) self.offset += BLOCKSIZE continue except InvalidHeaderError as e: if self.ignore_zeros: self._dbg(2, "0x%X: %s" % (self.offset, e)) self.offset += BLOCKSIZE continue elif self.offset == 0: raise ReadError(str(e)) except EmptyHeaderError: if self.offset == 0: raise ReadError("empty file") except TruncatedHeaderError as e: if self.offset == 0: raise ReadError(str(e)) except SubsequentHeaderError as e: raise ReadError(str(e)) break if tarinfo is not None: self.members.append(tarinfo) else: self._loaded = True return tarinfo
[ "def", "next", "(", "self", ")", ":", "self", ".", "_check", "(", "\"ra\"", ")", "if", "self", ".", "firstmember", "is", "not", "None", ":", "m", "=", "self", ".", "firstmember", "self", ".", "firstmember", "=", "None", "return", "m", "# Read the next ...
https://github.com/inspurer/WorkAttendanceSystem/blob/1221e2d67bdf5bb15fe99517cc3ded58ccb066df/V2.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/_vendor/distlib/_backport/tarfile.py#L2414-L2458
kupferlauncher/kupfer
1c1e9bcbce05a82f503f68f8b3955c20b02639b3
kupfer/plugin/notes.py
python
_get_notes_interactive
()
return obj
Return the dbus proxy object, activate if necessary, raise an OperationError if not available.
Return the dbus proxy object, activate if necessary, raise an OperationError if not available.
[ "Return", "the", "dbus", "proxy", "object", "activate", "if", "necessary", "raise", "an", "OperationError", "if", "not", "available", "." ]
def _get_notes_interactive(): """ Return the dbus proxy object, activate if necessary, raise an OperationError if not available. """ obj = _get_notes_interface(activate=True) if obj is None: raise NotAvailableError(__kupfer_settings__["notes_application"]) return obj
[ "def", "_get_notes_interactive", "(", ")", ":", "obj", "=", "_get_notes_interface", "(", "activate", "=", "True", ")", "if", "obj", "is", "None", ":", "raise", "NotAvailableError", "(", "__kupfer_settings__", "[", "\"notes_application\"", "]", ")", "return", "ob...
https://github.com/kupferlauncher/kupfer/blob/1c1e9bcbce05a82f503f68f8b3955c20b02639b3/kupfer/plugin/notes.py#L89-L97
deepmind/acme
9880719d9def1d87a194377b394a414a17d11064
acme/agents/jax/ail/builder.py
python
AILBuilder.__init__
(self, rl_agent: builders.GenericActorLearnerBuilder[ ail_networks.DirectRLNetworks, DirectPolicyNetwork, reverb.ReplaySample], config: ail_config.AILConfig, discriminator_loss: losses.Loss, make_demonstrations: Callable[[int], Iterator[types.Transition]], logger_fn: Callable[[], loggers.Logger] = lambda: None)
Implements a builder for AIL using rl_agent as forward RL algorithm. Args: rl_agent: The standard RL agent used by AIL to optimize the generator. config: a AIL config discriminator_loss: The loss function for the discriminator to minimize. make_demonstrations: A function that returns an iterator with demonstrations to be imitated. logger_fn: a logger factory for the learner
Implements a builder for AIL using rl_agent as forward RL algorithm.
[ "Implements", "a", "builder", "for", "AIL", "using", "rl_agent", "as", "forward", "RL", "algorithm", "." ]
def __init__(self, rl_agent: builders.GenericActorLearnerBuilder[ ail_networks.DirectRLNetworks, DirectPolicyNetwork, reverb.ReplaySample], config: ail_config.AILConfig, discriminator_loss: losses.Loss, make_demonstrations: Callable[[int], Iterator[types.Transition]], logger_fn: Callable[[], loggers.Logger] = lambda: None): """Implements a builder for AIL using rl_agent as forward RL algorithm. Args: rl_agent: The standard RL agent used by AIL to optimize the generator. config: a AIL config discriminator_loss: The loss function for the discriminator to minimize. make_demonstrations: A function that returns an iterator with demonstrations to be imitated. logger_fn: a logger factory for the learner """ self._rl_agent = rl_agent self._config = config self._discriminator_loss = discriminator_loss self._make_demonstrations = make_demonstrations self._logger_fn = logger_fn
[ "def", "__init__", "(", "self", ",", "rl_agent", ":", "builders", ".", "GenericActorLearnerBuilder", "[", "ail_networks", ".", "DirectRLNetworks", ",", "DirectPolicyNetwork", ",", "reverb", ".", "ReplaySample", "]", ",", "config", ":", "ail_config", ".", "AILConfi...
https://github.com/deepmind/acme/blob/9880719d9def1d87a194377b394a414a17d11064/acme/agents/jax/ail/builder.py#L157-L179
CalebBell/fluids
dbbdd1d5ea3c458bd68dd8e21cf6281a0ec3fc80
fluids/two_phase.py
python
Xu_Fang
(m, x, rhol, rhog, mul, mug, sigma, D, roughness=0.0, L=1.0)
return phi_lo2*dP_lo
r'''Calculates two-phase pressure drop with the Xu and Fang (2013) correlation. Developed after a comprehensive review of available correlations, likely meaning it is quite accurate. .. math:: \Delta P = \Delta P_{lo} \phi_{lo}^2 .. math:: \phi_{lo}^2 = Y^2x^3 + (1-x^{2.59})^{0.632}[1 + 2x^{1.17}(Y^2-1) + 0.00775x^{-0.475} Fr_{tp}^{0.535} We_{tp}^{0.188}] .. math:: Y^2 = \frac{\Delta P_{go}}{\Delta P_{lo}} .. math:: Fr_{tp} = \frac{G_{tp}^2}{gD\rho_{tp}^2} .. math:: We_{tp} = \frac{G_{tp}^2 D}{\sigma \rho_{tp}} .. math:: \frac{1}{\rho_{tp}} = \frac{1-x}{\rho_l} + \frac{x}{\rho_g} Parameters ---------- m : float Mass flow rate of fluid, [kg/s] x : float Quality of fluid, [-] rhol : float Liquid density, [kg/m^3] rhog : float Gas density, [kg/m^3] mul : float Viscosity of liquid, [Pa*s] mug : float Viscosity of gas, [Pa*s] sigma : float Surface tension, [N/m] D : float Diameter of pipe, [m] roughness : float, optional Roughness of pipe for use in calculating friction factor, [m] L : float, optional Length of pipe, [m] Returns ------- dP : float Pressure drop of the two-phase flow, [Pa] Notes ----- Examples -------- >>> Xu_Fang(m=0.6, x=0.1, rhol=915., rhog=2.67, mul=180E-6, mug=14E-6, ... sigma=0.0487, D=0.05, roughness=0.0, L=1.0) 604.0595632116267 References ---------- .. [1] Xu, Yu, and Xiande Fang. "A New Correlation of Two-Phase Frictional Pressure Drop for Condensing Flow in Pipes." Nuclear Engineering and Design 263 (October 2013): 87-96. doi:10.1016/j.nucengdes.2013.04.017.
r'''Calculates two-phase pressure drop with the Xu and Fang (2013) correlation. Developed after a comprehensive review of available correlations, likely meaning it is quite accurate.
[ "r", "Calculates", "two", "-", "phase", "pressure", "drop", "with", "the", "Xu", "and", "Fang", "(", "2013", ")", "correlation", ".", "Developed", "after", "a", "comprehensive", "review", "of", "available", "correlations", "likely", "meaning", "it", "is", "q...
def Xu_Fang(m, x, rhol, rhog, mul, mug, sigma, D, roughness=0.0, L=1.0): r'''Calculates two-phase pressure drop with the Xu and Fang (2013) correlation. Developed after a comprehensive review of available correlations, likely meaning it is quite accurate. .. math:: \Delta P = \Delta P_{lo} \phi_{lo}^2 .. math:: \phi_{lo}^2 = Y^2x^3 + (1-x^{2.59})^{0.632}[1 + 2x^{1.17}(Y^2-1) + 0.00775x^{-0.475} Fr_{tp}^{0.535} We_{tp}^{0.188}] .. math:: Y^2 = \frac{\Delta P_{go}}{\Delta P_{lo}} .. math:: Fr_{tp} = \frac{G_{tp}^2}{gD\rho_{tp}^2} .. math:: We_{tp} = \frac{G_{tp}^2 D}{\sigma \rho_{tp}} .. math:: \frac{1}{\rho_{tp}} = \frac{1-x}{\rho_l} + \frac{x}{\rho_g} Parameters ---------- m : float Mass flow rate of fluid, [kg/s] x : float Quality of fluid, [-] rhol : float Liquid density, [kg/m^3] rhog : float Gas density, [kg/m^3] mul : float Viscosity of liquid, [Pa*s] mug : float Viscosity of gas, [Pa*s] sigma : float Surface tension, [N/m] D : float Diameter of pipe, [m] roughness : float, optional Roughness of pipe for use in calculating friction factor, [m] L : float, optional Length of pipe, [m] Returns ------- dP : float Pressure drop of the two-phase flow, [Pa] Notes ----- Examples -------- >>> Xu_Fang(m=0.6, x=0.1, rhol=915., rhog=2.67, mul=180E-6, mug=14E-6, ... sigma=0.0487, D=0.05, roughness=0.0, L=1.0) 604.0595632116267 References ---------- .. [1] Xu, Yu, and Xiande Fang. "A New Correlation of Two-Phase Frictional Pressure Drop for Condensing Flow in Pipes." Nuclear Engineering and Design 263 (October 2013): 87-96. doi:10.1016/j.nucengdes.2013.04.017. ''' A = pi/4*D*D # Liquid-only properties, for calculation of E, dP_lo v_lo = m/rhol/A Re_lo = Reynolds(V=v_lo, rho=rhol, mu=mul, D=D) fd_lo = friction_factor(Re=Re_lo, eD=roughness/D) dP_lo = fd_lo*L/D*(0.5*rhol*v_lo**2) # Gas-only properties, for calculation of E v_go = m/rhog/A Re_go = Reynolds(V=v_go, rho=rhog, mu=mug, D=D) fd_go = friction_factor(Re=Re_go, eD=roughness/D) dP_go = fd_go*L/D*(0.5*rhog*v_go**2) # Homogeneous properties, for Froude/Weber numbers voidage_h = homogeneous(x, rhol, rhog) rho_h = rhol*(1-voidage_h) + rhog*voidage_h Q_h = m/rho_h v_h = Q_h/A Fr = Froude(V=v_h, L=D, squared=True) We = Weber(V=v_h, L=D, rho=rho_h, sigma=sigma) Y2 = dP_go/dP_lo phi_lo2 = Y2*x**3 + (1-x**2.59)**0.632*(1 + 2*x**1.17*(Y2-1) + 0.00775*x**-0.475*Fr**0.535*We**0.188) return phi_lo2*dP_lo
[ "def", "Xu_Fang", "(", "m", ",", "x", ",", "rhol", ",", "rhog", ",", "mul", ",", "mug", ",", "sigma", ",", "D", ",", "roughness", "=", "0.0", ",", "L", "=", "1.0", ")", ":", "A", "=", "pi", "/", "4", "*", "D", "*", "D", "# Liquid-only propert...
https://github.com/CalebBell/fluids/blob/dbbdd1d5ea3c458bd68dd8e21cf6281a0ec3fc80/fluids/two_phase.py#L1420-L1515
khanhnamle1994/natural-language-processing
01d450d5ac002b0156ef4cf93a07cb508c1bcdc5
assignment1/.env/lib/python2.7/site-packages/scipy/interpolate/interpolate.py
python
interp1d._check_bounds
(self, x_new)
return out_of_bounds
Check the inputs for being in the bounds of the interpolated data. Parameters ---------- x_new : array Returns ------- out_of_bounds : bool array The mask on x_new of values that are out of the bounds.
Check the inputs for being in the bounds of the interpolated data.
[ "Check", "the", "inputs", "for", "being", "in", "the", "bounds", "of", "the", "interpolated", "data", "." ]
def _check_bounds(self, x_new): """Check the inputs for being in the bounds of the interpolated data. Parameters ---------- x_new : array Returns ------- out_of_bounds : bool array The mask on x_new of values that are out of the bounds. """ # If self.bounds_error is True, we raise an error if any x_new values # fall outside the range of x. Otherwise, we return an array indicating # which values are outside the boundary region. below_bounds = x_new < self.x[0] above_bounds = x_new > self.x[-1] # !! Could provide more information about which values are out of bounds if self.bounds_error and below_bounds.any(): raise ValueError("A value in x_new is below the interpolation " "range.") if self.bounds_error and above_bounds.any(): raise ValueError("A value in x_new is above the interpolation " "range.") # !! Should we emit a warning if some values are out of bounds? # !! matlab does not. out_of_bounds = logical_or(below_bounds, above_bounds) return out_of_bounds
[ "def", "_check_bounds", "(", "self", ",", "x_new", ")", ":", "# If self.bounds_error is True, we raise an error if any x_new values", "# fall outside the range of x. Otherwise, we return an array indicating", "# which values are outside the boundary region.", "below_bounds", "=", "x_new",...
https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/scipy/interpolate/interpolate.py#L483-L513
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/plugins/attack/db/sqlmap/lib/controller/checks.py
python
checkSuhosinPatch
(injection)
Checks for existence of Suhosin-patch (and alike) protection mechanism(s)
Checks for existence of Suhosin-patch (and alike) protection mechanism(s)
[ "Checks", "for", "existence", "of", "Suhosin", "-", "patch", "(", "and", "alike", ")", "protection", "mechanism", "(", "s", ")" ]
def checkSuhosinPatch(injection): """ Checks for existence of Suhosin-patch (and alike) protection mechanism(s) """ if injection.place == PLACE.GET: debugMsg = "checking for parameter length " debugMsg += "constrainting mechanisms" logger.debug(debugMsg) pushValue(kb.injection) kb.injection = injection randInt = randomInt() if not checkBooleanExpression("%d=%s%d" % (randInt, ' ' * SUHOSIN_MAX_VALUE_LENGTH, randInt)): warnMsg = "parameter length constrainting " warnMsg += "mechanism detected (e.g. Suhosin patch). " warnMsg += "Potential problems in enumeration phase can be expected" logger.warn(warnMsg) kb.injection = popValue()
[ "def", "checkSuhosinPatch", "(", "injection", ")", ":", "if", "injection", ".", "place", "==", "PLACE", ".", "GET", ":", "debugMsg", "=", "\"checking for parameter length \"", "debugMsg", "+=", "\"constrainting mechanisms\"", "logger", ".", "debug", "(", "debugMsg",...
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/plugins/attack/db/sqlmap/lib/controller/checks.py#L916-L937
robotframework/RIDE
6e8a50774ff33dead3a2757a11b0b4418ab205c0
src/robotide/preferences/configobj.py
python
ConfigObj._unquote
(self, value)
return value
Return an unquoted version of a value
Return an unquoted version of a value
[ "Return", "an", "unquoted", "version", "of", "a", "value" ]
def _unquote(self, value): """Return an unquoted version of a value""" if not value: # should only happen during parsing of lists raise SyntaxError if (value[0] == value[-1]) and (value[0] in ('"', "'")): value = value[1:-1] return value
[ "def", "_unquote", "(", "self", ",", "value", ")", ":", "if", "not", "value", ":", "# should only happen during parsing of lists", "raise", "SyntaxError", "if", "(", "value", "[", "0", "]", "==", "value", "[", "-", "1", "]", ")", "and", "(", "value", "["...
https://github.com/robotframework/RIDE/blob/6e8a50774ff33dead3a2757a11b0b4418ab205c0/src/robotide/preferences/configobj.py#L1746-L1753
peering-manager/peering-manager
62c870fb9caa6dfc056feb77c595d45bc3c4988a
peering/models/models.py
python
Router.get_netbox_bgp_neighbors
(self)
return bgp_sessions
Returns a list of dictionaries listing all BGP neighbors found on the router using NetBox. Each dictionary contains two keys 'ip_address' and 'remote_asn'. If an error occurs or no BGP neighbors can be found, the returned list will be empty.
Returns a list of dictionaries listing all BGP neighbors found on the router using NetBox.
[ "Returns", "a", "list", "of", "dictionaries", "listing", "all", "BGP", "neighbors", "found", "on", "the", "router", "using", "NetBox", "." ]
def get_netbox_bgp_neighbors(self): """ Returns a list of dictionaries listing all BGP neighbors found on the router using NetBox. Each dictionary contains two keys 'ip_address' and 'remote_asn'. If an error occurs or no BGP neighbors can be found, the returned list will be empty. """ bgp_sessions = [] self.logger.debug("getting bgp neighbors on %s", self.hostname) bgp_neighbors = NetBox().napalm(self.netbox_device_id, "get_bgp_neighbors") self.logger.debug("raw napalm output %s", bgp_neighbors) self.logger.debug( "found %s vrfs with bgp neighbors on %s", len(bgp_neighbors), self.hostname ) bgp_sessions = self._napalm_bgp_neighbors_to_peer_list(bgp_neighbors) self.logger.debug( "found %s bgp neighbors on %s", len(bgp_sessions), self.hostname ) return bgp_sessions
[ "def", "get_netbox_bgp_neighbors", "(", "self", ")", ":", "bgp_sessions", "=", "[", "]", "self", ".", "logger", ".", "debug", "(", "\"getting bgp neighbors on %s\"", ",", "self", ".", "hostname", ")", "bgp_neighbors", "=", "NetBox", "(", ")", ".", "napalm", ...
https://github.com/peering-manager/peering-manager/blob/62c870fb9caa6dfc056feb77c595d45bc3c4988a/peering/models/models.py#L1520-L1544
grnet/synnefo
d06ec8c7871092131cdaabf6b03ed0b504c93e43
snf-webproject/synnefo/webproject/validators.py
python
whitespace
(char)
return unicodedata.category(char).startswith("Z")
Returns True if char is a whitespace
Returns True if char is a whitespace
[ "Returns", "True", "if", "char", "is", "a", "whitespace" ]
def whitespace(char): """Returns True if char is a whitespace""" return unicodedata.category(char).startswith("Z")
[ "def", "whitespace", "(", "char", ")", ":", "return", "unicodedata", ".", "category", "(", "char", ")", ".", "startswith", "(", "\"Z\"", ")" ]
https://github.com/grnet/synnefo/blob/d06ec8c7871092131cdaabf6b03ed0b504c93e43/snf-webproject/synnefo/webproject/validators.py#L22-L24
rowliny/DiffHelper
ab3a96f58f9579d0023aed9ebd785f4edf26f8af
Tool/SitePackages/nltk/featstruct.py
python
substitute_bindings
(fstruct, bindings, fs_class="default")
return fstruct
Return the feature structure that is obtained by replacing each variable bound by ``bindings`` with its binding. If a variable is aliased to a bound variable, then it will be replaced by that variable's value. If a variable is aliased to an unbound variable, then it will be replaced by that variable. :type bindings: dict(Variable -> any) :param bindings: A dictionary mapping from variables to values.
Return the feature structure that is obtained by replacing each variable bound by ``bindings`` with its binding. If a variable is aliased to a bound variable, then it will be replaced by that variable's value. If a variable is aliased to an unbound variable, then it will be replaced by that variable.
[ "Return", "the", "feature", "structure", "that", "is", "obtained", "by", "replacing", "each", "variable", "bound", "by", "bindings", "with", "its", "binding", ".", "If", "a", "variable", "is", "aliased", "to", "a", "bound", "variable", "then", "it", "will", ...
def substitute_bindings(fstruct, bindings, fs_class="default"): """ Return the feature structure that is obtained by replacing each variable bound by ``bindings`` with its binding. If a variable is aliased to a bound variable, then it will be replaced by that variable's value. If a variable is aliased to an unbound variable, then it will be replaced by that variable. :type bindings: dict(Variable -> any) :param bindings: A dictionary mapping from variables to values. """ if fs_class == "default": fs_class = _default_fs_class(fstruct) fstruct = copy.deepcopy(fstruct) _substitute_bindings(fstruct, bindings, fs_class, set()) return fstruct
[ "def", "substitute_bindings", "(", "fstruct", ",", "bindings", ",", "fs_class", "=", "\"default\"", ")", ":", "if", "fs_class", "==", "\"default\"", ":", "fs_class", "=", "_default_fs_class", "(", "fstruct", ")", "fstruct", "=", "copy", ".", "deepcopy", "(", ...
https://github.com/rowliny/DiffHelper/blob/ab3a96f58f9579d0023aed9ebd785f4edf26f8af/Tool/SitePackages/nltk/featstruct.py#L1079-L1094
pkumza/LibRadar
2fa3891123e5fd97d631fbe14bf029714c328ca3
LibRadar/job_dispatching.py
python
DexExtractorDispatcher.execute
(self)
[]
def execute(self): q = multiprocessing.Manager().Queue() p = Pool() logger.info("Pool created") app_list = glob.glob("%s/*" % self.folder) for apk in app_list: if len(apk) < 4 or apk[-4:] != ".apk": continue q.put(apk) for i in range(RUNNING_PROCESS_NUMBER): process_name = str(i).zfill(2) p.apply_async(run_dex_extractor_wrapper, args=(process_name, q)) logger.info("Waiting for all sub-processes done.") p.close() p.join() logger.critical("All sub-processes done.")
[ "def", "execute", "(", "self", ")", ":", "q", "=", "multiprocessing", ".", "Manager", "(", ")", ".", "Queue", "(", ")", "p", "=", "Pool", "(", ")", "logger", ".", "info", "(", "\"Pool created\"", ")", "app_list", "=", "glob", ".", "glob", "(", "\"%...
https://github.com/pkumza/LibRadar/blob/2fa3891123e5fd97d631fbe14bf029714c328ca3/LibRadar/job_dispatching.py#L136-L151
skylander86/lambda-text-extractor
6da52d077a2fc571e38bfe29c33ae68f6443cd5a
lib-linux_x64/PIL/Image.py
python
Image.putpalette
(self, data, rawmode="RGB")
Attaches a palette to this image. The image must be a "P" or "L" image, and the palette sequence must contain 768 integer values, where each group of three values represent the red, green, and blue values for the corresponding pixel index. Instead of an integer sequence, you can use an 8-bit string. :param data: A palette sequence (either a list or a string).
Attaches a palette to this image. The image must be a "P" or "L" image, and the palette sequence must contain 768 integer values, where each group of three values represent the red, green, and blue values for the corresponding pixel index. Instead of an integer sequence, you can use an 8-bit string.
[ "Attaches", "a", "palette", "to", "this", "image", ".", "The", "image", "must", "be", "a", "P", "or", "L", "image", "and", "the", "palette", "sequence", "must", "contain", "768", "integer", "values", "where", "each", "group", "of", "three", "values", "re...
def putpalette(self, data, rawmode="RGB"): """ Attaches a palette to this image. The image must be a "P" or "L" image, and the palette sequence must contain 768 integer values, where each group of three values represent the red, green, and blue values for the corresponding pixel index. Instead of an integer sequence, you can use an 8-bit string. :param data: A palette sequence (either a list or a string). """ from . import ImagePalette if self.mode not in ("L", "P"): raise ValueError("illegal image mode") self.load() if isinstance(data, ImagePalette.ImagePalette): palette = ImagePalette.raw(data.rawmode, data.palette) else: if not isinstance(data, bytes): if bytes is str: data = "".join(chr(x) for x in data) else: data = bytes(data) palette = ImagePalette.raw(rawmode, data) self.mode = "P" self.palette = palette self.palette.mode = "RGB" self.load()
[ "def", "putpalette", "(", "self", ",", "data", ",", "rawmode", "=", "\"RGB\"", ")", ":", "from", ".", "import", "ImagePalette", "if", "self", ".", "mode", "not", "in", "(", "\"L\"", ",", "\"P\"", ")", ":", "raise", "ValueError", "(", "\"illegal image mod...
https://github.com/skylander86/lambda-text-extractor/blob/6da52d077a2fc571e38bfe29c33ae68f6443cd5a/lib-linux_x64/PIL/Image.py#L1542-L1570
shahar603/SpaceXtract
fe8a30b9f5cf1d2bee83fa1df214081c34aeb283
src/Analysis/analyse_raw_telemetry.py
python
acceleration_func
(x, Isp, m_dot, m0)
return 9.8*Isp*9*m_dot/(m0-9*m_dot*x)
[]
def acceleration_func(x, Isp, m_dot, m0): return 9.8*Isp*9*m_dot/(m0-9*m_dot*x)
[ "def", "acceleration_func", "(", "x", ",", "Isp", ",", "m_dot", ",", "m0", ")", ":", "return", "9.8", "*", "Isp", "*", "9", "*", "m_dot", "/", "(", "m0", "-", "9", "*", "m_dot", "*", "x", ")" ]
https://github.com/shahar603/SpaceXtract/blob/fe8a30b9f5cf1d2bee83fa1df214081c34aeb283/src/Analysis/analyse_raw_telemetry.py#L243-L244
skylander86/lambda-text-extractor
6da52d077a2fc571e38bfe29c33ae68f6443cd5a
lib-linux_x64/requests/utils.py
python
guess_json_utf
(data)
return None
:rtype: str
:rtype: str
[ ":", "rtype", ":", "str" ]
def guess_json_utf(data): """ :rtype: str """ # JSON always starts with two ASCII characters, so detection is as # easy as counting the nulls and from their location and count # determine the encoding. Also detect a BOM, if present. sample = data[:4] if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE): return 'utf-32' # BOM included if sample[:3] == codecs.BOM_UTF8: return 'utf-8-sig' # BOM included, MS style (discouraged) if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE): return 'utf-16' # BOM included nullcount = sample.count(_null) if nullcount == 0: return 'utf-8' if nullcount == 2: if sample[::2] == _null2: # 1st and 3rd are null return 'utf-16-be' if sample[1::2] == _null2: # 2nd and 4th are null return 'utf-16-le' # Did not detect 2 valid UTF-16 ascii-range characters if nullcount == 3: if sample[:3] == _null3: return 'utf-32-be' if sample[1:] == _null3: return 'utf-32-le' # Did not detect a valid UTF-32 ascii-range character return None
[ "def", "guess_json_utf", "(", "data", ")", ":", "# JSON always starts with two ASCII characters, so detection is as", "# easy as counting the nulls and from their location and count", "# determine the encoding. Also detect a BOM, if present.", "sample", "=", "data", "[", ":", "4", "]",...
https://github.com/skylander86/lambda-text-extractor/blob/6da52d077a2fc571e38bfe29c33ae68f6443cd5a/lib-linux_x64/requests/utils.py#L784-L813
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/Base/Scripts/ValidateContent/ValidateContent.py
python
_create_pack_base_files
(self)
Create empty 'README.md', '.secrets-ignore', and '.pack-ignore' files that are expected to be in the base directory of a pack
Create empty 'README.md', '.secrets-ignore', and '.pack-ignore' files that are expected to be in the base directory of a pack
[ "Create", "empty", "README", ".", "md", ".", "secrets", "-", "ignore", "and", ".", "pack", "-", "ignore", "files", "that", "are", "expected", "to", "be", "in", "the", "base", "directory", "of", "a", "pack" ]
def _create_pack_base_files(self): """ Create empty 'README.md', '.secrets-ignore', and '.pack-ignore' files that are expected to be in the base directory of a pack """ fp = open(os.path.join(self.pack_dir_path, 'README.md'), 'a') fp.close() fp = open(os.path.join(self.pack_dir_path, '.secrets-ignore'), 'a') fp.close() fp = open(os.path.join(self.pack_dir_path, '.pack-ignore'), 'a') fp.close()
[ "def", "_create_pack_base_files", "(", "self", ")", ":", "fp", "=", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "pack_dir_path", ",", "'README.md'", ")", ",", "'a'", ")", "fp", ".", "close", "(", ")", "fp", "=", "open", "(", "os"...
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/Base/Scripts/ValidateContent/ValidateContent.py#L34-L46
wiseman/mavelous
eef41c096cc282bb3acd33a747146a88d2bd1eee
modules/camera.py
python
ImagePacket.__init__
(self, frame_time, jpeg)
[]
def __init__(self, frame_time, jpeg): self.frame_time = frame_time self.jpeg = jpeg
[ "def", "__init__", "(", "self", ",", "frame_time", ",", "jpeg", ")", ":", "self", ".", "frame_time", "=", "frame_time", "self", ".", "jpeg", "=", "jpeg" ]
https://github.com/wiseman/mavelous/blob/eef41c096cc282bb3acd33a747146a88d2bd1eee/modules/camera.py#L325-L327
DonnchaC/shadowbrokers-exploits
42d8265db860b634717da4faa668b2670457cf7e
windows/fuzzbunch/pyreadline/modes/vi.py
python
ViMode.init_editing_mode
(self, e)
Initialize vi editingmode
Initialize vi editingmode
[ "Initialize", "vi", "editingmode" ]
def init_editing_mode(self, e): # (M-C-j) '''Initialize vi editingmode''' self.show_all_if_ambiguous = 'on' self.key_dispatch = {} self.__vi_insert_mode = None self._vi_command = None self._vi_command_edit = None self._vi_key_find_char = None self._vi_key_find_direction = True self._vi_yank_buffer = None self._vi_multiplier1 = '' self._vi_multiplier2 = '' self._vi_undo_stack = [] self._vi_undo_cursor = -1 self._vi_current = None self._vi_search_text = '' self.vi_save_line () self.vi_set_insert_mode (True) # make ' ' to ~ self insert for c in range(ord(' '), 127): self._bind_key('%s' % chr(c), self.vi_key) self._bind_key('BackSpace', self.vi_backspace) self._bind_key('Escape', self.vi_escape) self._bind_key('Return', self.vi_accept_line) self._bind_key('Left', self.backward_char) self._bind_key('Right', self.forward_char) self._bind_key('Home', self.beginning_of_line) self._bind_key('End', self.end_of_line) self._bind_key('Delete', self.delete_char) self._bind_key('Control-d', self.vi_eof) self._bind_key('Control-z', self.vi_eof) self._bind_key('Control-r', self.vi_redo) self._bind_key('Up', self.vi_arrow_up) self._bind_key('Control-p', self.vi_up) self._bind_key('Down', self.vi_arrow_down) self._bind_key('Control-n', self.vi_down) self._bind_key('Tab', self.vi_complete)
[ "def", "init_editing_mode", "(", "self", ",", "e", ")", ":", "# (M-C-j)", "self", ".", "show_all_if_ambiguous", "=", "'on'", "self", ".", "key_dispatch", "=", "{", "}", "self", ".", "__vi_insert_mode", "=", "None", "self", ".", "_vi_command", "=", "None", ...
https://github.com/DonnchaC/shadowbrokers-exploits/blob/42d8265db860b634717da4faa668b2670457cf7e/windows/fuzzbunch/pyreadline/modes/vi.py#L95-L133
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-47/fabmetheus_utilities/settings.py
python
BooleanSetting.addToMenu
( self, repositoryMenu )
Add this to the repository menu.
Add this to the repository menu.
[ "Add", "this", "to", "the", "repository", "menu", "." ]
def addToMenu( self, repositoryMenu ): "Add this to the repository menu." self.activateToggleMenuCheckbutton = False #activateToggleMenuCheckbutton is being used instead of setting command after because add_checkbutton does not return a checkbutton. repositoryMenu.add_checkbutton( label = getTitleFromName( self.name ), command = self.toggleMenuCheckbutton ) if self.value: repositoryMenu.invoke( repositoryMenu.index( Tkinter.END ) ) self.activateToggleMenuCheckbutton = True
[ "def", "addToMenu", "(", "self", ",", "repositoryMenu", ")", ":", "self", ".", "activateToggleMenuCheckbutton", "=", "False", "#activateToggleMenuCheckbutton is being used instead of setting command after because add_checkbutton does not return a checkbutton.", "repositoryMenu", ".", ...
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-47/fabmetheus_utilities/settings.py#L743-L750
rwth-i6/returnn
f2d718a197a280b0d5f0fd91a7fcb8658560dddb
returnn/tf/network.py
python
CustomCheckpointLoader.load_now
(self, session)
:param tf.compat.v1.Session session: :return: nothing, will assign the variables in the session
:param tf.compat.v1.Session session: :return: nothing, will assign the variables in the session
[ ":", "param", "tf", ".", "compat", ".", "v1", ".", "Session", "session", ":", ":", "return", ":", "nothing", "will", "assign", "the", "variables", "in", "the", "session" ]
def load_now(self, session): """ :param tf.compat.v1.Session session: :return: nothing, will assign the variables in the session """ for var, value in self.get_variable_value_map().items(): value.assign_var(var=var, session=session)
[ "def", "load_now", "(", "self", ",", "session", ")", ":", "for", "var", ",", "value", "in", "self", ".", "get_variable_value_map", "(", ")", ".", "items", "(", ")", ":", "value", ".", "assign_var", "(", "var", "=", "var", ",", "session", "=", "sessio...
https://github.com/rwth-i6/returnn/blob/f2d718a197a280b0d5f0fd91a7fcb8658560dddb/returnn/tf/network.py#L4018-L4024
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/bmvpc/v20180625/bmvpc_client.py
python
BmvpcClient.ModifyRoutePolicy
(self, request)
修改自定义路由 :param request: Request instance for ModifyRoutePolicy. :type request: :class:`tencentcloud.bmvpc.v20180625.models.ModifyRoutePolicyRequest` :rtype: :class:`tencentcloud.bmvpc.v20180625.models.ModifyRoutePolicyResponse`
修改自定义路由
[ "修改自定义路由" ]
def ModifyRoutePolicy(self, request): """修改自定义路由 :param request: Request instance for ModifyRoutePolicy. :type request: :class:`tencentcloud.bmvpc.v20180625.models.ModifyRoutePolicyRequest` :rtype: :class:`tencentcloud.bmvpc.v20180625.models.ModifyRoutePolicyResponse` """ try: params = request._serialize() body = self.call("ModifyRoutePolicy", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyRoutePolicyResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message)
[ "def", "ModifyRoutePolicy", "(", "self", ",", "request", ")", ":", "try", ":", "params", "=", "request", ".", "_serialize", "(", ")", "body", "=", "self", ".", "call", "(", "\"ModifyRoutePolicy\"", ",", "params", ")", "response", "=", "json", ".", "loads...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/bmvpc/v20180625/bmvpc_client.py#L1356-L1381
cfpb/consumerfinance.gov
4fa9bc60472dbf99a3412d8721442e3536efa4f1
cfgov/search/elasticsearch_helpers.py
python
strip_html
(markup)
return re.sub(clean, " ", markup).strip().replace("\xa0", "")
Make sure markup stripping doesn't mash content elements together. Also remove no-break space characters.
Make sure markup stripping doesn't mash content elements together.
[ "Make", "sure", "markup", "stripping", "doesn", "t", "mash", "content", "elements", "together", "." ]
def strip_html(markup): """ Make sure markup stripping doesn't mash content elements together. Also remove no-break space characters. """ clean = re.compile("<.*?>") return re.sub(clean, " ", markup).strip().replace("\xa0", "")
[ "def", "strip_html", "(", "markup", ")", ":", "clean", "=", "re", ".", "compile", "(", "\"<.*?>\"", ")", "return", "re", ".", "sub", "(", "clean", ",", "\" \"", ",", "markup", ")", ".", "strip", "(", ")", ".", "replace", "(", "\"\\xa0\"", ",", "\"\...
https://github.com/cfpb/consumerfinance.gov/blob/4fa9bc60472dbf99a3412d8721442e3536efa4f1/cfgov/search/elasticsearch_helpers.py#L23-L30
WikidPad/WikidPad
558109638807bc76b4672922686e416ab2d5f79c
WikidPad/lib/pwiki/WikiDocument.py
python
WikiDocument.getFileSignatureBlock
(self, filename)
return getFileSignatureBlock(filename, coarsening)
Mainly called by WikiData. Returns the file signature block for a given file. It is a bytestring containing size and modification date of the file and can be compared to a db-stored version to check for file changes outside of WikidPad. It calls StringOps.getFileSignatureBlock with the time coarsening given in the wiki options.
Mainly called by WikiData. Returns the file signature block for a given file. It is a bytestring containing size and modification date of the file and can be compared to a db-stored version to check for file changes outside of WikidPad. It calls StringOps.getFileSignatureBlock with the time coarsening given in the wiki options.
[ "Mainly", "called", "by", "WikiData", ".", "Returns", "the", "file", "signature", "block", "for", "a", "given", "file", ".", "It", "is", "a", "bytestring", "containing", "size", "and", "modification", "date", "of", "the", "file", "and", "can", "be", "compa...
def getFileSignatureBlock(self, filename): """ Mainly called by WikiData. Returns the file signature block for a given file. It is a bytestring containing size and modification date of the file and can be compared to a db-stored version to check for file changes outside of WikidPad. It calls StringOps.getFileSignatureBlock with the time coarsening given in the wiki options. """ coarseStr = self.getWikiConfig().get("main", "fileSignature_timeCoarsening", "0") try: if "." in coarseStr: coarsening = float(coarseStr) else: coarsening = int(coarseStr) except ValueError: coarsening = None return getFileSignatureBlock(filename, coarsening)
[ "def", "getFileSignatureBlock", "(", "self", ",", "filename", ")", ":", "coarseStr", "=", "self", ".", "getWikiConfig", "(", ")", ".", "get", "(", "\"main\"", ",", "\"fileSignature_timeCoarsening\"", ",", "\"0\"", ")", "try", ":", "if", "\".\"", "in", "coars...
https://github.com/WikidPad/WikidPad/blob/558109638807bc76b4672922686e416ab2d5f79c/WikidPad/lib/pwiki/WikiDocument.py#L2550-L2572
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/argparse.py
python
_StoreAction.__call__
(self, parser, namespace, values, option_string=None)
[]
def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, self.dest, values)
[ "def", "__call__", "(", "self", ",", "parser", ",", "namespace", ",", "values", ",", "option_string", "=", "None", ")", ":", "setattr", "(", "namespace", ",", "self", ".", "dest", ",", "values", ")" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/argparse.py#L836-L837
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/vlc/media_player.py
python
VlcDevice.media_content_type
(self)
return MEDIA_TYPE_MUSIC
Content type of current playing media.
Content type of current playing media.
[ "Content", "type", "of", "current", "playing", "media", "." ]
def media_content_type(self): """Content type of current playing media.""" return MEDIA_TYPE_MUSIC
[ "def", "media_content_type", "(", "self", ")", ":", "return", "MEDIA_TYPE_MUSIC" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/vlc/media_player.py#L121-L123
compas-dev/compas
0b33f8786481f710115fb1ae5fe79abc2a9a5175
src/compas/datastructures/halfface/halfface.py
python
HalfFace.number_of_vertices
(self)
return len(list(self.vertices()))
Count the number of vertices in the volmesh.
Count the number of vertices in the volmesh.
[ "Count", "the", "number", "of", "vertices", "in", "the", "volmesh", "." ]
def number_of_vertices(self): """Count the number of vertices in the volmesh.""" return len(list(self.vertices()))
[ "def", "number_of_vertices", "(", "self", ")", ":", "return", "len", "(", "list", "(", "self", ".", "vertices", "(", ")", ")", ")" ]
https://github.com/compas-dev/compas/blob/0b33f8786481f710115fb1ae5fe79abc2a9a5175/src/compas/datastructures/halfface/halfface.py#L1532-L1534
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/asn1crypto/core.py
python
Asn1Value.__deepcopy__
(self, memo)
return new_obj
Implements the copy.deepcopy() interface :param memo: A dict for memoization :return: A new deep copy of the current Asn1Value object
Implements the copy.deepcopy() interface
[ "Implements", "the", "copy", ".", "deepcopy", "()", "interface" ]
def __deepcopy__(self, memo): """ Implements the copy.deepcopy() interface :param memo: A dict for memoization :return: A new deep copy of the current Asn1Value object """ new_obj = self._new_instance() memo[id(self)] = new_obj new_obj._copy(self, copy.deepcopy) return new_obj
[ "def", "__deepcopy__", "(", "self", ",", "memo", ")", ":", "new_obj", "=", "self", ".", "_new_instance", "(", ")", "memo", "[", "id", "(", "self", ")", "]", "=", "new_obj", "new_obj", ".", "_copy", "(", "self", ",", "copy", ".", "deepcopy", ")", "r...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/asn1crypto/core.py#L486-L500
MillionIntegrals/vel
f3ce7da64362ad207f40f2c0d58d9300a25df3e8
vel/util/random.py
python
set_seed
(seed: int)
Set random seed for python, numpy and pytorch RNGs
Set random seed for python, numpy and pytorch RNGs
[ "Set", "random", "seed", "for", "python", "numpy", "and", "pytorch", "RNGs" ]
def set_seed(seed: int): """ Set random seed for python, numpy and pytorch RNGs """ random.seed(seed) np.random.seed(seed) torch.random.manual_seed(seed)
[ "def", "set_seed", "(", "seed", ":", "int", ")", ":", "random", ".", "seed", "(", "seed", ")", "np", ".", "random", ".", "seed", "(", "seed", ")", "torch", ".", "random", ".", "manual_seed", "(", "seed", ")" ]
https://github.com/MillionIntegrals/vel/blob/f3ce7da64362ad207f40f2c0d58d9300a25df3e8/vel/util/random.py#L6-L10
chenyuntc/pytorch-best-practice
cf8cd600978571dfd78fafc71a7f467e08b8fdc3
models/BasicModule.py
python
BasicModule.load
(self, path)
可加载指定路径的模型
可加载指定路径的模型
[ "可加载指定路径的模型" ]
def load(self, path): ''' 可加载指定路径的模型 ''' self.load_state_dict(t.load(path))
[ "def", "load", "(", "self", ",", "path", ")", ":", "self", ".", "load_state_dict", "(", "t", ".", "load", "(", "path", ")", ")" ]
https://github.com/chenyuntc/pytorch-best-practice/blob/cf8cd600978571dfd78fafc71a7f467e08b8fdc3/models/BasicModule.py#L15-L19
plaid/plaid-python
8c60fca608e426f3ff30da8857775946d29e122c
plaid/model/standalone_investment_transaction_type.py
python
StandaloneInvestmentTransactionType.additional_properties_type
()
return (bool, date, datetime, dict, float, int, list, str, none_type,)
This must be a method because a model may have properties that are of type self, this must run after the class is loaded
This must be a method because a model may have properties that are of type self, this must run after the class is loaded
[ "This", "must", "be", "a", "method", "because", "a", "model", "may", "have", "properties", "that", "are", "of", "type", "self", "this", "must", "run", "after", "the", "class", "is", "loaded" ]
def additional_properties_type(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded """ return (bool, date, datetime, dict, float, int, list, str, none_type,)
[ "def", "additional_properties_type", "(", ")", ":", "return", "(", "bool", ",", "date", ",", "datetime", ",", "dict", ",", "float", ",", "int", ",", "list", ",", "str", ",", "none_type", ",", ")" ]
https://github.com/plaid/plaid-python/blob/8c60fca608e426f3ff30da8857775946d29e122c/plaid/model/standalone_investment_transaction_type.py#L59-L64
tendenci/tendenci
0f2c348cc0e7d41bc56f50b00ce05544b083bf1d
tendenci/apps/memberships/admin.py
python
expire_selected
(modeladmin, request, queryset)
Expire [only active] selected memberships.
Expire [only active] selected memberships.
[ "Expire", "[", "only", "active", "]", "selected", "memberships", "." ]
def expire_selected(modeladmin, request, queryset): """ Expire [only active] selected memberships. """ memberships = queryset.filter( status=True, status_detail='active', application_approved=True, ) for membership in memberships: # Since we're selecting memberships with 'active' status_detail, # this `membership` is either active membership or expired # but not being marked as expired yet (maybe due to a failed cron job). membership.expire(request_user=request.user)
[ "def", "expire_selected", "(", "modeladmin", ",", "request", ",", "queryset", ")", ":", "memberships", "=", "queryset", ".", "filter", "(", "status", "=", "True", ",", "status_detail", "=", "'active'", ",", "application_approved", "=", "True", ",", ")", "for...
https://github.com/tendenci/tendenci/blob/0f2c348cc0e7d41bc56f50b00ce05544b083bf1d/tendenci/apps/memberships/admin.py#L149-L164
PYFTS/pyFTS
ad3e857024d0da068feb0d7eae214b55a038a9ca
pyFTS/common/FLR.py
python
FLR.__init__
(self, LHS, RHS)
Creates a Fuzzy Logical Relationship
Creates a Fuzzy Logical Relationship
[ "Creates", "a", "Fuzzy", "Logical", "Relationship" ]
def __init__(self, LHS, RHS): """ Creates a Fuzzy Logical Relationship """ self.LHS = LHS """Left Hand Side fuzzy set""" self.RHS = RHS """Right Hand Side fuzzy set"""
[ "def", "__init__", "(", "self", ",", "LHS", ",", "RHS", ")", ":", "self", ".", "LHS", "=", "LHS", "\"\"\"Left Hand Side fuzzy set\"\"\"", "self", ".", "RHS", "=", "RHS", "\"\"\"Right Hand Side fuzzy set\"\"\"" ]
https://github.com/PYFTS/pyFTS/blob/ad3e857024d0da068feb0d7eae214b55a038a9ca/pyFTS/common/FLR.py#L15-L22
foremast/foremast
e8eb9bd24e975772532d90efa8a9ba1850e968cc
src/foremast/gcp_iam/create_iam_resources.py
python
GcpIamResourceClient._check_group_permitted_project
(project, group_name)
return False
Returns true if a group is permitted to access this project based on the projects FOREMAST_GROUPS=team1,team2 label. If no label is present all groups are permitted.
Returns true if a group is permitted to access this project based on the projects FOREMAST_GROUPS=team1,team2 label. If no label is present all groups are permitted.
[ "Returns", "true", "if", "a", "group", "is", "permitted", "to", "access", "this", "project", "based", "on", "the", "projects", "FOREMAST_GROUPS", "=", "team1", "team2", "label", ".", "If", "no", "label", "is", "present", "all", "groups", "are", "permitted", ...
def _check_group_permitted_project(project, group_name): """Returns true if a group is permitted to access this project based on the projects FOREMAST_GROUPS=team1,team2 label. If no label is present all groups are permitted.""" if 'foremast_groups' not in project['labels'] or not project['labels']['foremast_groups'].strip(): LOG.debug("Project '%s' permits access from all groups", project['projectId']) return True # foremast_groups defined and not empty foremast_groups = project['labels']['foremast_groups'].split('__') # split on two underscores LOG.debug("Project '%s' only supports foremast deployments from groups: '%s'", project['projectId'], foremast_groups) for permitted_group in foremast_groups: if group_name == permitted_group.strip(): return True # Default to denied return False
[ "def", "_check_group_permitted_project", "(", "project", ",", "group_name", ")", ":", "if", "'foremast_groups'", "not", "in", "project", "[", "'labels'", "]", "or", "not", "project", "[", "'labels'", "]", "[", "'foremast_groups'", "]", ".", "strip", "(", ")", ...
https://github.com/foremast/foremast/blob/e8eb9bd24e975772532d90efa8a9ba1850e968cc/src/foremast/gcp_iam/create_iam_resources.py#L257-L275
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/mobile_auth/views.py
python
admin_fetch_key_records
(request, domain)
return HttpResponse(payload)
[]
def admin_fetch_key_records(request, domain): last_issued = request.GET.get('last_issued') if last_issued: last_issued = string_to_datetime(last_issued).replace(tzinfo=None) username = request.GET.get('as', '') key_user = CommCareUser.get_by_username(username) if not key_user: return HttpResponseNotFound('User %s not found.' % username) payload = FetchKeyRecords(domain, key_user._id, last_issued).get_payload() return HttpResponse(payload)
[ "def", "admin_fetch_key_records", "(", "request", ",", "domain", ")", ":", "last_issued", "=", "request", ".", "GET", ".", "get", "(", "'last_issued'", ")", "if", "last_issued", ":", "last_issued", "=", "string_to_datetime", "(", "last_issued", ")", ".", "repl...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/mobile_auth/views.py#L84-L93
reviewboard/rbtools
b4838a640b458641ffd233093ae65971d0b4d529
rbtools/deprecation.py
python
BaseRemovedInRBToolsVersionWarning.warn
(cls, message, stacklevel=2)
Emit the deprecation warning. This is a convenience function that emits a deprecation warning using this class, with a suitable default stack level. Callers can provide a useful message and a custom stack level. Args: message (unicode): The message to show in the deprecation warning. stacklevel (int, optional): The stack level for the warning.
Emit the deprecation warning.
[ "Emit", "the", "deprecation", "warning", "." ]
def warn(cls, message, stacklevel=2): """Emit the deprecation warning. This is a convenience function that emits a deprecation warning using this class, with a suitable default stack level. Callers can provide a useful message and a custom stack level. Args: message (unicode): The message to show in the deprecation warning. stacklevel (int, optional): The stack level for the warning. """ warnings.warn(message, cls, stacklevel=stacklevel + 1)
[ "def", "warn", "(", "cls", ",", "message", ",", "stacklevel", "=", "2", ")", ":", "warnings", ".", "warn", "(", "message", ",", "cls", ",", "stacklevel", "=", "stacklevel", "+", "1", ")" ]
https://github.com/reviewboard/rbtools/blob/b4838a640b458641ffd233093ae65971d0b4d529/rbtools/deprecation.py#L22-L36
Ultimaker/Cura
a1622c77ea7259ecb956acd6de07b7d34b7ac52b
plugins/UM3NetworkPrinting/src/Models/Http/ClusterPrinterMaterialStationSlot.py
python
ClusterPrinterMaterialStationSlot.__init__
(self, slot_index: int, compatible: bool, material_remaining: float, material_empty: Optional[bool] = False, **kwargs)
Create a new material station slot object. :param slot_index: The index of the slot in the material station (ranging 0 to 5). :param compatible: Whether the configuration is compatible with the print core. :param material_remaining: How much material is remaining on the spool (between 0 and 1, or -1 for missing data). :param material_empty: Whether the material spool is too empty to be used.
Create a new material station slot object.
[ "Create", "a", "new", "material", "station", "slot", "object", "." ]
def __init__(self, slot_index: int, compatible: bool, material_remaining: float, material_empty: Optional[bool] = False, **kwargs) -> None: """Create a new material station slot object. :param slot_index: The index of the slot in the material station (ranging 0 to 5). :param compatible: Whether the configuration is compatible with the print core. :param material_remaining: How much material is remaining on the spool (between 0 and 1, or -1 for missing data). :param material_empty: Whether the material spool is too empty to be used. """ self.slot_index = slot_index self.compatible = compatible self.material_remaining = material_remaining self.material_empty = material_empty super().__init__(**kwargs)
[ "def", "__init__", "(", "self", ",", "slot_index", ":", "int", ",", "compatible", ":", "bool", ",", "material_remaining", ":", "float", ",", "material_empty", ":", "Optional", "[", "bool", "]", "=", "False", ",", "*", "*", "kwargs", ")", "->", "None", ...
https://github.com/Ultimaker/Cura/blob/a1622c77ea7259ecb956acd6de07b7d34b7ac52b/plugins/UM3NetworkPrinting/src/Models/Http/ClusterPrinterMaterialStationSlot.py#L11-L25
hkust-vgd/scanobjectnn
fe60aeade9ceb8882bc3f1bc40612e65469d7e77
dgcnn/utils/tf_util.py
python
knn
(adj_matrix, k=20)
return nn_idx
Get KNN based on the pairwise distance. Args: pairwise distance: (batch_size, num_points, num_points) k: int Returns: nearest neighbors: (batch_size, num_points, k)
Get KNN based on the pairwise distance. Args: pairwise distance: (batch_size, num_points, num_points) k: int
[ "Get", "KNN", "based", "on", "the", "pairwise", "distance", ".", "Args", ":", "pairwise", "distance", ":", "(", "batch_size", "num_points", "num_points", ")", "k", ":", "int" ]
def knn(adj_matrix, k=20): """Get KNN based on the pairwise distance. Args: pairwise distance: (batch_size, num_points, num_points) k: int Returns: nearest neighbors: (batch_size, num_points, k) """ neg_adj = -adj_matrix _, nn_idx = tf.nn.top_k(neg_adj, k=k) return nn_idx
[ "def", "knn", "(", "adj_matrix", ",", "k", "=", "20", ")", ":", "neg_adj", "=", "-", "adj_matrix", "_", ",", "nn_idx", "=", "tf", ".", "nn", ".", "top_k", "(", "neg_adj", ",", "k", "=", "k", ")", "return", "nn_idx" ]
https://github.com/hkust-vgd/scanobjectnn/blob/fe60aeade9ceb8882bc3f1bc40612e65469d7e77/dgcnn/utils/tf_util.py#L660-L671
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/geometry/linear_expression.py
python
LinearExpressionModule._repr_
(self)
return 'Module of linear expressions in variable{2} {0} over {1}'.format( ', '.join(self._names), self.base_ring(), 's' if self.ngens() > 1 else '')
Return a string representation. OUTPUT: A string. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x> = LinearExpressionModule(QQ); L Module of linear expressions in variable x over Rational Field
Return a string representation.
[ "Return", "a", "string", "representation", "." ]
def _repr_(self): """ Return a string representation. OUTPUT: A string. EXAMPLES:: sage: from sage.geometry.linear_expression import LinearExpressionModule sage: L.<x> = LinearExpressionModule(QQ); L Module of linear expressions in variable x over Rational Field """ return 'Module of linear expressions in variable{2} {0} over {1}'.format( ', '.join(self._names), self.base_ring(), 's' if self.ngens() > 1 else '')
[ "def", "_repr_", "(", "self", ")", ":", "return", "'Module of linear expressions in variable{2} {0} over {1}'", ".", "format", "(", "', '", ".", "join", "(", "self", ".", "_names", ")", ",", "self", ".", "base_ring", "(", ")", ",", "'s'", "if", "self", ".", ...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/geometry/linear_expression.py#L751-L766
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/importlib/util.py
python
module_for_loader
(fxn)
return module_for_loader_wrapper
Decorator to handle selecting the proper module for loaders. The decorated function is passed the module to use instead of the module name. The module passed in to the function is either from sys.modules if it already exists or is a new module. If the module is new, then __name__ is set the first argument to the method, __loader__ is set to self, and __package__ is set accordingly (if self.is_package() is defined) will be set before it is passed to the decorated function (if self.is_package() does not work for the module it will be set post-load). If an exception is raised and the decorator created the module it is subsequently removed from sys.modules. The decorator assumes that the decorated function takes the module name as the second argument.
Decorator to handle selecting the proper module for loaders.
[ "Decorator", "to", "handle", "selecting", "the", "proper", "module", "for", "loaders", "." ]
def module_for_loader(fxn): """Decorator to handle selecting the proper module for loaders. The decorated function is passed the module to use instead of the module name. The module passed in to the function is either from sys.modules if it already exists or is a new module. If the module is new, then __name__ is set the first argument to the method, __loader__ is set to self, and __package__ is set accordingly (if self.is_package() is defined) will be set before it is passed to the decorated function (if self.is_package() does not work for the module it will be set post-load). If an exception is raised and the decorator created the module it is subsequently removed from sys.modules. The decorator assumes that the decorated function takes the module name as the second argument. """ warnings.warn('The import system now takes care of this automatically.', DeprecationWarning, stacklevel=2) @functools.wraps(fxn) def module_for_loader_wrapper(self, fullname, *args, **kwargs): with _module_to_load(fullname) as module: module.__loader__ = self try: is_package = self.is_package(fullname) except (ImportError, AttributeError): pass else: if is_package: module.__package__ = fullname else: module.__package__ = fullname.rpartition('.')[0] # If __package__ was not set above, __import__() will do it later. return fxn(self, module, *args, **kwargs) return module_for_loader_wrapper
[ "def", "module_for_loader", "(", "fxn", ")", ":", "warnings", ".", "warn", "(", "'The import system now takes care of this automatically.'", ",", "DeprecationWarning", ",", "stacklevel", "=", "2", ")", "@", "functools", ".", "wraps", "(", "fxn", ")", "def", "modul...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/importlib/util.py#L180-L216
rbonghi/jetson_stats
628b07d935a2d980eac158c242812a0510e4efb8
jtop/gui/lib/common.py
python
check_size
(height_max, width_max)
return check_size_window
Check curses size window
Check curses size window
[ "Check", "curses", "size", "window" ]
def check_size(height_max, width_max): """ Check curses size window """ def check_size_window(func): @wraps(func) def wrapped(self, *args, **kwargs): # Extract window size height, width = self.stdscr.getmaxyx() # Check size window if width >= width_max and height >= height_max: return func(self, *args, **kwargs) else: # First, clear the screen self.stdscr.erase() # Message string_warning = "jtop" string_warning_msg = "Change size window!" size_window_width = "Width: " + str(width) + " >= " + str(width_max) size_window_height = "Height: " + str(height) + " >= " + str(height_max) try: height_c = int(height / 2) self.stdscr.addstr(height_c - 2, int((width - len(string_warning)) / 2), string_warning, curses.A_BOLD) self.stdscr.addstr(height_c - 1, int((width - len(string_warning_msg)) / 2), string_warning_msg, curses.A_BOLD) # Show size window if width < width_max: self.stdscr.addstr(height_c, int((width - len(size_window_width)) / 2), str(size_window_width), curses.color_pair(1)) else: size_window_width = "Width OK!" self.stdscr.addstr(height_c, int((width - len(size_window_width)) / 2), size_window_width, curses.A_BOLD) if height < height_max: self.stdscr.addstr(height_c + 1, int((width - len(size_window_height)) / 2), str(size_window_height), curses.color_pair(1)) else: size_window_height = "Height OK!" self.stdscr.addstr(height_c + 1, int((width - len(size_window_height)) / 2), str(size_window_height), curses.A_BOLD) # Set background for all menu line self.stdscr.addstr(height - 1, 0, ("{0:<" + str(width - 1) + "}").format(" "), curses.A_REVERSE) # Add close option menu self.stdscr.addstr(height - 1, 1, "Q", curses.A_REVERSE | curses.A_BOLD) self.stdscr.addstr(height - 1, 2, "uit ", curses.A_REVERSE) except curses.error: pass return wrapped return check_size_window
[ "def", "check_size", "(", "height_max", ",", "width_max", ")", ":", "def", "check_size_window", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapped", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Extract window...
https://github.com/rbonghi/jetson_stats/blob/628b07d935a2d980eac158c242812a0510e4efb8/jtop/gui/lib/common.py#L71-L112
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/Centos_6.4/ecdsa/util.py
python
lsb_of_ones
(numbits)
return (1 << numbits) - 1
[]
def lsb_of_ones(numbits): return (1 << numbits) - 1
[ "def", "lsb_of_ones", "(", "numbits", ")", ":", "return", "(", "1", "<<", "numbits", ")", "-", "1" ]
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/Centos_6.4/ecdsa/util.py#L96-L97
obonaventure/cnp3
155b3a61690f282a7c72fe117fcd3b83c7c09035
Missions/S8/Nat.py
python
Nat.received_TCP
(self, pkt)
[]
def received_TCP(self, pkt): # Packets arrived from the private network if (self.mac_addr_src[pkt.dst.upper()] == "eth0"): #Look for the entry in the mapping #If if doesn't exist, create a new one (with a random port). if((pkt[IP].src,pkt[TCP].sport) in self.mapping.values()): for map_src,map_port in self.mapping.keys(): if(self.mapping[map_src,map_port] == (pkt[IP].src,pkt[TCP].sport)): break else: print "Nat: Creating a new NAT mapping entry:",pkt[IP].src," ",pkt[TCP].sport src_port=int(random.random()*65535) self.mapping[(self.public_addr,src_port)]=(pkt[IP].src,pkt[TCP].sport) map_src,map_port=self.public_addr,src_port #extract the destination #Fill up the important information for the new packet new_ip_packet=IP(src=map_src,dst=pkt[IP].dst,ttl=pkt[IP].ttl)/pkt[TCP] new_ip_packet[TCP].sport=map_port #Remove checksum to force scapy to recompute it #and send the packet new_ip_packet[TCP].chksum=None self.send(new_ip_packet) # Packets arrived from the public network if (self.mac_addr_src[pkt.dst.upper()] == "eth1"): #Try to find the corresponding mapping entry try: #Extract the source IP and the dport from the mapping (src,map_port)=self.mapping[(pkt[IP].dst,pkt[TCP].dport)] #Build the destination and fill up important information new_ip_packet=IP(src=pkt[IP].src,dst=src,ttl=pkt[IP].ttl)/pkt[TCP] new_ip_packet[TCP].dport=map_port #Remove checksum to force scapy to recompute it #and send the packet new_ip_packet[TCP].chksum=None self.send(new_ip_packet) except KeyError: print "Nat: Mapping entry not found:",pkt[IP].dst," ",pkt[TCP].dport
[ "def", "received_TCP", "(", "self", ",", "pkt", ")", ":", "# Packets arrived from the private network", "if", "(", "self", ".", "mac_addr_src", "[", "pkt", ".", "dst", ".", "upper", "(", ")", "]", "==", "\"eth0\"", ")", ":", "#Look for the entry in the mapping",...
https://github.com/obonaventure/cnp3/blob/155b3a61690f282a7c72fe117fcd3b83c7c09035/Missions/S8/Nat.py#L47-L92
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/appengine/api/lib_config.py
python
ConfigHandle.__init__
(self, prefix, registry)
Constructor. Args: prefix: A shared prefix for the configuration names being registered. It *must* end in '_'. (This is enforced by LibConfigRegistry.) registry: A LibConfigRegistry instance.
Constructor.
[ "Constructor", "." ]
def __init__(self, prefix, registry): """Constructor. Args: prefix: A shared prefix for the configuration names being registered. It *must* end in '_'. (This is enforced by LibConfigRegistry.) registry: A LibConfigRegistry instance. """ assert prefix.endswith('_') self._prefix = prefix self._defaults = {} self._overrides = {} self._registry = registry self._lock = threading.RLock()
[ "def", "__init__", "(", "self", ",", "prefix", ",", "registry", ")", ":", "assert", "prefix", ".", "endswith", "(", "'_'", ")", "self", ".", "_prefix", "=", "prefix", "self", ".", "_defaults", "=", "{", "}", "self", ".", "_overrides", "=", "{", "}", ...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/api/lib_config.py#L247-L260
SigmaHQ/sigma
6f7d28b52a6468b2430e8d7dfefb79dc01e2f1af
tools/sigma/backends/base.py
python
SingleTextQueryBackend.generateORNode
(self, node)
[]
def generateORNode(self, node): generated = [ self.generateNode(val) for val in node ] filtered = [ g for g in generated if g is not None ] if filtered: if self.sort_condition_lists: filtered = sorted(filtered) return self.orToken.join(filtered) else: return None
[ "def", "generateORNode", "(", "self", ",", "node", ")", ":", "generated", "=", "[", "self", ".", "generateNode", "(", "val", ")", "for", "val", "in", "node", "]", "filtered", "=", "[", "g", "for", "g", "in", "generated", "if", "g", "is", "not", "No...
https://github.com/SigmaHQ/sigma/blob/6f7d28b52a6468b2430e8d7dfefb79dc01e2f1af/tools/sigma/backends/base.py#L271-L279
quantopian/qdb
c25018d2f0979589a38a07667478cb6022d57ed9
qdb/compat.py
python
with_metaclass
(metaclass, *bases)
return metaclass('SurrogateBase', bases, {})
Adds a new base in the mro for python 2 and 3 compatible metaclass syntax.
Adds a new base in the mro for python 2 and 3 compatible metaclass syntax.
[ "Adds", "a", "new", "base", "in", "the", "mro", "for", "python", "2", "and", "3", "compatible", "metaclass", "syntax", "." ]
def with_metaclass(metaclass, *bases): """ Adds a new base in the mro for python 2 and 3 compatible metaclass syntax. """ return metaclass('SurrogateBase', bases, {})
[ "def", "with_metaclass", "(", "metaclass", ",", "*", "bases", ")", ":", "return", "metaclass", "(", "'SurrogateBase'", ",", "bases", ",", "{", "}", ")" ]
https://github.com/quantopian/qdb/blob/c25018d2f0979589a38a07667478cb6022d57ed9/qdb/compat.py#L109-L114
wistbean/learn_python3_spider
73c873f4845f4385f097e5057407d03dd37a117b
stackoverflow/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/packaging/specifiers.py
python
BaseSpecifier.prereleases
(self, value)
Sets whether or not pre-releases as a whole are allowed by this specifier.
Sets whether or not pre-releases as a whole are allowed by this specifier.
[ "Sets", "whether", "or", "not", "pre", "-", "releases", "as", "a", "whole", "are", "allowed", "by", "this", "specifier", "." ]
def prereleases(self, value): """ Sets whether or not pre-releases as a whole are allowed by this specifier. """
[ "def", "prereleases", "(", "self", ",", "value", ")", ":" ]
https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/packaging/specifiers.py#L57-L61
bigboNed3/bert_serving
44d33920da6888cf91cb72e6c7b27c7b0c7d8815
extract_features.py
python
input_fn_builder
(features, seq_length)
return input_fn
Creates an `input_fn` closure to be passed to TPUEstimator.
Creates an `input_fn` closure to be passed to TPUEstimator.
[ "Creates", "an", "input_fn", "closure", "to", "be", "passed", "to", "TPUEstimator", "." ]
def input_fn_builder(features, seq_length): """Creates an `input_fn` closure to be passed to TPUEstimator.""" all_unique_ids = [] all_input_ids = [] all_input_mask = [] all_input_type_ids = [] for feature in features: all_unique_ids.append(feature.unique_id) all_input_ids.append(feature.input_ids) all_input_mask.append(feature.input_mask) all_input_type_ids.append(feature.input_type_ids) def input_fn(params): """The actual input function.""" batch_size = params["batch_size"] num_examples = len(features) # This is for demo purposes and does NOT scale to large data sets. We do # not use Dataset.from_generator() because that uses tf.py_func which is # not TPU compatible. The right way to load data is with TFRecordReader. d = tf.data.Dataset.from_tensor_slices({ "unique_ids": tf.constant(all_unique_ids, shape=[num_examples], dtype=tf.int32), "input_ids": tf.constant( all_input_ids, shape=[num_examples, seq_length], dtype=tf.int32), "input_mask": tf.constant( all_input_mask, shape=[num_examples, seq_length], dtype=tf.int32), "input_type_ids": tf.constant( all_input_type_ids, shape=[num_examples, seq_length], dtype=tf.int32), }) d = d.batch(batch_size=batch_size, drop_remainder=False) return d return input_fn
[ "def", "input_fn_builder", "(", "features", ",", "seq_length", ")", ":", "all_unique_ids", "=", "[", "]", "all_input_ids", "=", "[", "]", "all_input_mask", "=", "[", "]", "all_input_type_ids", "=", "[", "]", "for", "feature", "in", "features", ":", "all_uniq...
https://github.com/bigboNed3/bert_serving/blob/44d33920da6888cf91cb72e6c7b27c7b0c7d8815/extract_features.py#L100-L145
stopstalk/stopstalk-deployment
10c3ab44c4ece33ae515f6888c15033db2004bb1
aws_lambda/spoj_aws_lambda_function/lambda_code/setuptools/pep425tags.py
python
get_abbr_impl
()
return pyimpl
Return abbreviated implementation name.
Return abbreviated implementation name.
[ "Return", "abbreviated", "implementation", "name", "." ]
def get_abbr_impl(): """Return abbreviated implementation name.""" if hasattr(sys, 'pypy_version_info'): pyimpl = 'pp' elif sys.platform.startswith('java'): pyimpl = 'jy' elif sys.platform == 'cli': pyimpl = 'ip' else: pyimpl = 'cp' return pyimpl
[ "def", "get_abbr_impl", "(", ")", ":", "if", "hasattr", "(", "sys", ",", "'pypy_version_info'", ")", ":", "pyimpl", "=", "'pp'", "elif", "sys", ".", "platform", ".", "startswith", "(", "'java'", ")", ":", "pyimpl", "=", "'jy'", "elif", "sys", ".", "pla...
https://github.com/stopstalk/stopstalk-deployment/blob/10c3ab44c4ece33ae515f6888c15033db2004bb1/aws_lambda/spoj_aws_lambda_function/lambda_code/setuptools/pep425tags.py#L30-L40
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/django/forms/fields.py
python
Field.bound_data
(self, data, initial)
return data
Return the value that should be shown for this field on render of a bound form, given the submitted POST data for the field and the initial data, if any. For most fields, this will simply be data; FileFields need to handle it a bit differently.
Return the value that should be shown for this field on render of a bound form, given the submitted POST data for the field and the initial data, if any.
[ "Return", "the", "value", "that", "should", "be", "shown", "for", "this", "field", "on", "render", "of", "a", "bound", "form", "given", "the", "submitted", "POST", "data", "for", "the", "field", "and", "the", "initial", "data", "if", "any", "." ]
def bound_data(self, data, initial): """ Return the value that should be shown for this field on render of a bound form, given the submitted POST data for the field and the initial data, if any. For most fields, this will simply be data; FileFields need to handle it a bit differently. """ return data
[ "def", "bound_data", "(", "self", ",", "data", ",", "initial", ")", ":", "return", "data" ]
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/django/forms/fields.py#L159-L168
SecureAuthCorp/pysap
7578dc55c8510dbe63ac094e783eacf5fbfb130b
pysap/SAPCAR.py
python
SAPCARArchiveFile.checksum
(self)
return checksum
The checksum of the file. :return: checksum :rtype: int :raise SAPCARInvalidFileException: if the file is invalid and contains more than one end of data block
The checksum of the file.
[ "The", "checksum", "of", "the", "file", "." ]
def checksum(self): """The checksum of the file. :return: checksum :rtype: int :raise SAPCARInvalidFileException: if the file is invalid and contains more than one end of data block """ checksum = None if self._file_format.blocks: for block in self._file_format.blocks: if block.type == SAPCAR_BLOCK_TYPE_COMPRESSED_LAST: if checksum is not None: raise SAPCARInvalidFileException("More than one end of data block found for the file") checksum = block.checksum return checksum
[ "def", "checksum", "(", "self", ")", ":", "checksum", "=", "None", "if", "self", ".", "_file_format", ".", "blocks", ":", "for", "block", "in", "self", ".", "_file_format", ".", "blocks", ":", "if", "block", ".", "type", "==", "SAPCAR_BLOCK_TYPE_COMPRESSED...
https://github.com/SecureAuthCorp/pysap/blob/7578dc55c8510dbe63ac094e783eacf5fbfb130b/pysap/SAPCAR.py#L458-L473
WilsonWangTHU/mbbl
bb88a016de2fcd8ea0ed9c4d5c539817d2b476e7
mbbl/util/kfac/fisher_factors.py
python
scope_string_from_params
(params)
return "_".join(name_parts)
Builds a variable scope string name from the given parameters. Supported parameters are: * tensors * booleans * ints * strings * depth-1 tuples/lists of ints * any depth tuples/lists of tensors Other parameter types will throw an error. Args: params: A parameter or list of parameters. Returns: A string to use for the variable scope. Raises: ValueError: if params includes an unsupported type.
Builds a variable scope string name from the given parameters. Supported parameters are: * tensors * booleans * ints * strings * depth-1 tuples/lists of ints * any depth tuples/lists of tensors Other parameter types will throw an error. Args: params: A parameter or list of parameters. Returns: A string to use for the variable scope. Raises: ValueError: if params includes an unsupported type.
[ "Builds", "a", "variable", "scope", "string", "name", "from", "the", "given", "parameters", ".", "Supported", "parameters", "are", ":", "*", "tensors", "*", "booleans", "*", "ints", "*", "strings", "*", "depth", "-", "1", "tuples", "/", "lists", "of", "i...
def scope_string_from_params(params): """Builds a variable scope string name from the given parameters. Supported parameters are: * tensors * booleans * ints * strings * depth-1 tuples/lists of ints * any depth tuples/lists of tensors Other parameter types will throw an error. Args: params: A parameter or list of parameters. Returns: A string to use for the variable scope. Raises: ValueError: if params includes an unsupported type. """ params = params if isinstance(params, (tuple, list)) else (params,) name_parts = [] for param in params: if isinstance(param, (tuple, list)): if all([isinstance(p, int) for p in param]): name_parts.append("-".join([str(p) for p in param])) else: name_parts.append(scope_string_from_name(param)) elif isinstance(param, (str, int, bool)): name_parts.append(str(param)) elif isinstance(param, (tf_ops.Tensor, variables.Variable)): name_parts.append(scope_string_from_name(param)) else: raise ValueError("Encountered an unsupported param type {}".format( type(param))) return "_".join(name_parts)
[ "def", "scope_string_from_params", "(", "params", ")", ":", "params", "=", "params", "if", "isinstance", "(", "params", ",", "(", "tuple", ",", "list", ")", ")", "else", "(", "params", ",", ")", "name_parts", "=", "[", "]", "for", "param", "in", "param...
https://github.com/WilsonWangTHU/mbbl/blob/bb88a016de2fcd8ea0ed9c4d5c539817d2b476e7/mbbl/util/kfac/fisher_factors.py#L129-L162
Blueqat/Blueqat
b676f30489b71767419fd20503403d290d4950b5
blueqat/pauli.py
python
Expr.__radd__
(self, other)
return NotImplemented
[]
def __radd__(self, other): if isinstance(other, Number): return Expr.from_number(other) + self if isinstance(other, Term): return Expr.from_term(other) + self return NotImplemented
[ "def", "__radd__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "Number", ")", ":", "return", "Expr", ".", "from_number", "(", "other", ")", "+", "self", "if", "isinstance", "(", "other", ",", "Term", ")", ":", "return"...
https://github.com/Blueqat/Blueqat/blob/b676f30489b71767419fd20503403d290d4950b5/blueqat/pauli.py#L755-L760
nephila/django-meta
329a466f50dc74038c23cbb93fbe1566a3f3ef31
meta/templatetags/meta.py
python
meta_namespaces_gplus
(context)
return meta_namespaces_schemaorg(context)
Legacy Google+ attributes.
Legacy Google+ attributes.
[ "Legacy", "Google", "+", "attributes", "." ]
def meta_namespaces_gplus(context): """ Legacy Google+ attributes. """ warnings.warn("meta_namespaces_gplus will be removed in version 3.0", PendingDeprecationWarning) return meta_namespaces_schemaorg(context)
[ "def", "meta_namespaces_gplus", "(", "context", ")", ":", "warnings", ".", "warn", "(", "\"meta_namespaces_gplus will be removed in version 3.0\"", ",", "PendingDeprecationWarning", ")", "return", "meta_namespaces_schemaorg", "(", "context", ")" ]
https://github.com/nephila/django-meta/blob/329a466f50dc74038c23cbb93fbe1566a3f3ef31/meta/templatetags/meta.py#L262-L267
aiidateam/aiida-core
c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2
aiida/orm/implementation/django/logs.py
python
DjangoLog.loggername
(self)
return self._dbmodel.loggername
The name of the logger that created this entry
The name of the logger that created this entry
[ "The", "name", "of", "the", "logger", "that", "created", "this", "entry" ]
def loggername(self): """ The name of the logger that created this entry """ return self._dbmodel.loggername
[ "def", "loggername", "(", "self", ")", ":", "return", "self", ".", "_dbmodel", ".", "loggername" ]
https://github.com/aiidateam/aiida-core/blob/c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2/aiida/orm/implementation/django/logs.py#L54-L58
ilastik/ilastik
6acd2c554bc517e9c8ddad3623a7aaa2e6970c28
ilastik/applets/base/standardApplet.py
python
StandardApplet.singleLaneOperatorClass
(self)
return NotImplemented
Return the operator class which handles a single image. Single-lane applets should override this property. (Multi-lane applets must override ``topLevelOperator`` directly.)
Return the operator class which handles a single image. Single-lane applets should override this property. (Multi-lane applets must override ``topLevelOperator`` directly.)
[ "Return", "the", "operator", "class", "which", "handles", "a", "single", "image", ".", "Single", "-", "lane", "applets", "should", "override", "this", "property", ".", "(", "Multi", "-", "lane", "applets", "must", "override", "topLevelOperator", "directly", "....
def singleLaneOperatorClass(self): """ Return the operator class which handles a single image. Single-lane applets should override this property. (Multi-lane applets must override ``topLevelOperator`` directly.) """ return NotImplemented
[ "def", "singleLaneOperatorClass", "(", "self", ")", ":", "return", "NotImplemented" ]
https://github.com/ilastik/ilastik/blob/6acd2c554bc517e9c8ddad3623a7aaa2e6970c28/ilastik/applets/base/standardApplet.py#L63-L69
chadmv/cmt
1b1a9a4fb154d1d10e73373cf899e4d83c95a6a1
scripts/cmt/rig/common.py
python
place_pole_vector
(start, mid, end, pole_vector, offset=None)
Place a pole vector along the plane of the 2 bone ik :param start: Start joint :param mid: Mid joint :param end: End joint :param pole_vector: Pole vector transform :param offset: Scalar offset from the mid joint
Place a pole vector along the plane of the 2 bone ik
[ "Place", "a", "pole", "vector", "along", "the", "plane", "of", "the", "2", "bone", "ik" ]
def place_pole_vector(start, mid, end, pole_vector, offset=None): """Place a pole vector along the plane of the 2 bone ik :param start: Start joint :param mid: Mid joint :param end: End joint :param pole_vector: Pole vector transform :param offset: Scalar offset from the mid joint """ v1 = OpenMaya.MVector(cmds.xform(start, q=True, ws=True, t=True)) v2 = OpenMaya.MVector(cmds.xform(mid, q=True, ws=True, t=True)) v3 = OpenMaya.MVector(cmds.xform(end, q=True, ws=True, t=True)) e1 = (v3 - v1).normal() e2 = v2 - v1 v = v1 + e1 * (e1 * e2) if offset is None: offset = ((v2 - v1).length() + (v3 - v2).length()) * 0.5 pos = v2 + (v2 - v).normal() * offset cmds.xform(pole_vector, ws=True, t=list(pos))
[ "def", "place_pole_vector", "(", "start", ",", "mid", ",", "end", ",", "pole_vector", ",", "offset", "=", "None", ")", ":", "v1", "=", "OpenMaya", ".", "MVector", "(", "cmds", ".", "xform", "(", "start", ",", "q", "=", "True", ",", "ws", "=", "True...
https://github.com/chadmv/cmt/blob/1b1a9a4fb154d1d10e73373cf899e4d83c95a6a1/scripts/cmt/rig/common.py#L292-L312
anyoptimization/pymoo
c6426a721d95c932ae6dbb610e09b6c1b0e13594
pymoo/visualization/scatter.py
python
Scatter.__init__
(self, angle=(45, 45), **kwargs)
Scatter Plot Parameters ---------------- axis_style : {axis_style} endpoint_style : dict Endpoints are drawn at each extreme point of an objective. This style can be modified. labels : {labels} Other Parameters ---------------- figsize : {figsize} title : {title} legend : {legend} tight_layout : {tight_layout} cmap : {cmap}
[]
def __init__(self, angle=(45, 45), **kwargs): """ Scatter Plot Parameters ---------------- axis_style : {axis_style} endpoint_style : dict Endpoints are drawn at each extreme point of an objective. This style can be modified. labels : {labels} Other Parameters ---------------- figsize : {figsize} title : {title} legend : {legend} tight_layout : {tight_layout} cmap : {cmap} """ super().__init__(**kwargs) self.angle = angle
[ "def", "__init__", "(", "self", ",", "angle", "=", "(", "45", ",", "45", ")", ",", "*", "*", "kwargs", ")", ":", "super", "(", ")", ".", "__init__", "(", "*", "*", "kwargs", ")", "self", ".", "angle", "=", "angle" ]
https://github.com/anyoptimization/pymoo/blob/c6426a721d95c932ae6dbb610e09b6c1b0e13594/pymoo/visualization/scatter.py#L10-L37
Minyus/causallift
c808b15de7e7912c4c08e9ad4152e4bd33f008c9
src/causallift/context/flexible_context.py
python
ProjectContext.run
( self, tags=None, # type: Iterable[str] runner=None, # type: AbstractRunner node_names=None, # type: Iterable[str] only_missing=False, # type: bool )
return runner.run(pipeline, self.catalog)
Runs the pipeline wi th a specified runner. Args: tags: An optional list of node tags which should be used to filter the nodes of the ``Pipeline``. If specified, only the nodes containing *any* of these tags will be run. runner: An optional parameter specifying the runner that you want to run the pipeline with. node_names: An optional list of node names which should be used to filter the nodes of the ``Pipeline``. If specified, only the nodes with these names will be run. only_missing: An option to run only missing nodes. Raises: KedroContextError: If the resulting ``Pipeline`` is empty or incorrect tags are provided. Returns: Any node outputs that cannot be processed by the ``DataCatalog``. These are returned in a dictionary, where the keys are defined by the node outputs.
Runs the pipeline wi th a specified runner.
[ "Runs", "the", "pipeline", "wi", "th", "a", "specified", "runner", "." ]
def run( self, tags=None, # type: Iterable[str] runner=None, # type: AbstractRunner node_names=None, # type: Iterable[str] only_missing=False, # type: bool ): # type: (...) -> Dict[str, Any] """Runs the pipeline wi th a specified runner. Args: tags: An optional list of node tags which should be used to filter the nodes of the ``Pipeline``. If specified, only the nodes containing *any* of these tags will be run. runner: An optional parameter specifying the runner that you want to run the pipeline with. node_names: An optional list of node names which should be used to filter the nodes of the ``Pipeline``. If specified, only the nodes with these names will be run. only_missing: An option to run only missing nodes. Raises: KedroContextError: If the resulting ``Pipeline`` is empty or incorrect tags are provided. Returns: Any node outputs that cannot be processed by the ``DataCatalog``. These are returned in a dictionary, where the keys are defined by the node outputs. """ # Load the pipeline pipeline = self.pipeline if node_names: pipeline = pipeline.only_nodes(*node_names) if tags: pipeline = pipeline.only_nodes_with_tags(*tags) if not pipeline.nodes: msg = "Pipeline contains no nodes" if tags: msg += " with tags: {}".format(str(tags)) raise KedroContextError(msg) # Run the runner runner = runner or SequentialRunner() if only_missing and _skippable(self.catalog): return runner.run_only_missing(pipeline, self.catalog) return runner.run(pipeline, self.catalog)
[ "def", "run", "(", "self", ",", "tags", "=", "None", ",", "# type: Iterable[str]", "runner", "=", "None", ",", "# type: AbstractRunner", "node_names", "=", "None", ",", "# type: Iterable[str]", "only_missing", "=", "False", ",", "# type: bool", ")", ":", "# type...
https://github.com/Minyus/causallift/blob/c808b15de7e7912c4c08e9ad4152e4bd33f008c9/src/causallift/context/flexible_context.py#L60-L106
openstack/openstacksdk
58384268487fa854f21c470b101641ab382c9897
openstack/cloud/_baremetal.py
python
BaremetalCloudMixin.set_machine_power_on
(self, name_or_id)
Activate baremetal machine power This is a method that sets the node power state to "on". :params string name_or_id: A string representing the baremetal node to have power turned to an "on" state. :raises: OpenStackCloudException on operation error. :returns: None
Activate baremetal machine power
[ "Activate", "baremetal", "machine", "power" ]
def set_machine_power_on(self, name_or_id): """Activate baremetal machine power This is a method that sets the node power state to "on". :params string name_or_id: A string representing the baremetal node to have power turned to an "on" state. :raises: OpenStackCloudException on operation error. :returns: None """ self.baremetal.set_node_power_state(name_or_id, 'power on')
[ "def", "set_machine_power_on", "(", "self", ",", "name_or_id", ")", ":", "self", ".", "baremetal", ".", "set_node_power_state", "(", "name_or_id", ",", "'power on'", ")" ]
https://github.com/openstack/openstacksdk/blob/58384268487fa854f21c470b101641ab382c9897/openstack/cloud/_baremetal.py#L598-L611
pybuilder/pybuilder
12ea2f54e04f97daada375dc3309a3f525f1b5e1
src/main/python/pybuilder/_vendor/importlib_metadata/__init__.py
python
SelectableGroups.names
(self)
return self._all.names
for coverage: >>> SelectableGroups().names set()
for coverage: >>> SelectableGroups().names set()
[ "for", "coverage", ":", ">>>", "SelectableGroups", "()", ".", "names", "set", "()" ]
def names(self): """ for coverage: >>> SelectableGroups().names set() """ return self._all.names
[ "def", "names", "(", "self", ")", ":", "return", "self", ".", "_all", ".", "names" ]
https://github.com/pybuilder/pybuilder/blob/12ea2f54e04f97daada375dc3309a3f525f1b5e1/src/main/python/pybuilder/_vendor/importlib_metadata/__init__.py#L470-L476
rucio/rucio
6d0d358e04f5431f0b9a98ae40f31af0ddff4833
lib/rucio/client/accountclient.py
python
AccountClient.del_identity
(self, account, identity, authtype)
Delete an identity's membership association with an account. :param account: The account name. :param identity: The identity key name. For example x509 DN, or a username. :param authtype: The type of the authentication (x509, gss, userpass). :param default: If True, the account should be used by default with the provided identity.
Delete an identity's membership association with an account.
[ "Delete", "an", "identity", "s", "membership", "association", "with", "an", "account", "." ]
def del_identity(self, account, identity, authtype): """ Delete an identity's membership association with an account. :param account: The account name. :param identity: The identity key name. For example x509 DN, or a username. :param authtype: The type of the authentication (x509, gss, userpass). :param default: If True, the account should be used by default with the provided identity. """ data = dumps({'identity': identity, 'authtype': authtype}) path = '/'.join([self.ACCOUNTS_BASEURL, account, 'identities']) url = build_url(choice(self.list_hosts), path=path) res = self._send_request(url, type_='DEL', data=data) if res.status_code == codes.ok: return True else: exc_cls, exc_msg = self._get_exception(headers=res.headers, status_code=res.status_code, data=res.content) raise exc_cls(exc_msg)
[ "def", "del_identity", "(", "self", ",", "account", ",", "identity", ",", "authtype", ")", ":", "data", "=", "dumps", "(", "{", "'identity'", ":", "identity", ",", "'authtype'", ":", "authtype", "}", ")", "path", "=", "'/'", ".", "join", "(", "[", "s...
https://github.com/rucio/rucio/blob/6d0d358e04f5431f0b9a98ae40f31af0ddff4833/lib/rucio/client/accountclient.py#L193-L214
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/appengine/datastore/datastore_query.py
python
CompositeOrder.size
(self)
return len(self._orders)
Returns the number of sub-orders the instance contains.
Returns the number of sub-orders the instance contains.
[ "Returns", "the", "number", "of", "sub", "-", "orders", "the", "instance", "contains", "." ]
def size(self): """Returns the number of sub-orders the instance contains.""" return len(self._orders)
[ "def", "size", "(", "self", ")", ":", "return", "len", "(", "self", ".", "_orders", ")" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/datastore/datastore_query.py#L1206-L1208
golismero/golismero
7d605b937e241f51c1ca4f47b20f755eeefb9d76
golismero/managers/pluginmanager.py
python
PluginInfo.author
(self)
return self.__author
:returns: Author of this plugin. :rtype: str
:returns: Author of this plugin. :rtype: str
[ ":", "returns", ":", "Author", "of", "this", "plugin", ".", ":", "rtype", ":", "str" ]
def author(self): """ :returns: Author of this plugin. :rtype: str """ return self.__author
[ "def", "author", "(", "self", ")", ":", "return", "self", ".", "__author" ]
https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/golismero/managers/pluginmanager.py#L214-L219
Georce/lepus
5b01bae82b5dc1df00c9e058989e2eb9b89ff333
lepus/pymongo-2.7/pymongo/mongo_replica_set_client.py
python
MongoReplicaSetClient.min_wire_version
(self)
return common.MIN_WIRE_VERSION
The minWireVersion reported by the server. Returns ``0`` when connected to server versions prior to MongoDB 2.6. .. versionadded:: 2.7
The minWireVersion reported by the server.
[ "The", "minWireVersion", "reported", "by", "the", "server", "." ]
def min_wire_version(self): """The minWireVersion reported by the server. Returns ``0`` when connected to server versions prior to MongoDB 2.6. .. versionadded:: 2.7 """ rs_state = self.__rs_state if rs_state.primary_member: return rs_state.primary_member.min_wire_version return common.MIN_WIRE_VERSION
[ "def", "min_wire_version", "(", "self", ")", ":", "rs_state", "=", "self", ".", "__rs_state", "if", "rs_state", ".", "primary_member", ":", "return", "rs_state", ".", "primary_member", ".", "min_wire_version", "return", "common", ".", "MIN_WIRE_VERSION" ]
https://github.com/Georce/lepus/blob/5b01bae82b5dc1df00c9e058989e2eb9b89ff333/lepus/pymongo-2.7/pymongo/mongo_replica_set_client.py#L964-L974
NVIDIA/DeepLearningExamples
589604d49e016cd9ef4525f7abcc9c7b826cfc5e
TensorFlow/Detection/SSD/models/research/object_detection/predictors/heads/head.py
python
Head.__init__
(self)
Constructor.
Constructor.
[ "Constructor", "." ]
def __init__(self): """Constructor.""" pass
[ "def", "__init__", "(", "self", ")", ":", "pass" ]
https://github.com/NVIDIA/DeepLearningExamples/blob/589604d49e016cd9ef4525f7abcc9c7b826cfc5e/TensorFlow/Detection/SSD/models/research/object_detection/predictors/heads/head.py#L45-L47
NaNShaner/repoll
2016d08d038b3b92a43fa30e893dba4ece9fccdd
polls/admin.py
python
RedisSentienlConfAdmin.has_add_permission
(self, request)
return False
禁用添加按钮 :param request: :return:
禁用添加按钮 :param request: :return:
[ "禁用添加按钮", ":", "param", "request", ":", ":", "return", ":" ]
def has_add_permission(self, request): """ 禁用添加按钮 :param request: :return: """ return False
[ "def", "has_add_permission", "(", "self", ",", "request", ")", ":", "return", "False" ]
https://github.com/NaNShaner/repoll/blob/2016d08d038b3b92a43fa30e893dba4ece9fccdd/polls/admin.py#L663-L669
wagtail/wagtail
ba8207a5d82c8a1de8f5f9693a7cd07421762999
wagtail/admin/views/generic/multiple_upload.py
python
AddView.get_invalid_response_data
(self, form)
return { 'success': False, 'error_message': '\n'.join(form.errors['file']), }
Return the JSON response data for an invalid form submission
Return the JSON response data for an invalid form submission
[ "Return", "the", "JSON", "response", "data", "for", "an", "invalid", "form", "submission" ]
def get_invalid_response_data(self, form): """ Return the JSON response data for an invalid form submission """ return { 'success': False, 'error_message': '\n'.join(form.errors['file']), }
[ "def", "get_invalid_response_data", "(", "self", ",", "form", ")", ":", "return", "{", "'success'", ":", "False", ",", "'error_message'", ":", "'\\n'", ".", "join", "(", "form", ".", "errors", "[", "'file'", "]", ")", ",", "}" ]
https://github.com/wagtail/wagtail/blob/ba8207a5d82c8a1de8f5f9693a7cd07421762999/wagtail/admin/views/generic/multiple_upload.py#L112-L119
apache/tvm
6eb4ed813ebcdcd9558f0906a1870db8302ff1e0
python/tvm/contrib/sparse.py
python
CSRNDArray.numpy
(self)
return full
Construct a full matrix and convert it to numpy array.
Construct a full matrix and convert it to numpy array.
[ "Construct", "a", "full", "matrix", "and", "convert", "it", "to", "numpy", "array", "." ]
def numpy(self): """Construct a full matrix and convert it to numpy array.""" full = _np.zeros(self.shape, self.dtype) ridx = _np.diff(self.indptr.numpy()) ridx = _np.hstack((_np.ones((v,), itype) * i for i, v in enumerate(ridx))) full[ridx, self.indices.numpy().astype(itype)] = self.data.numpy() return full
[ "def", "numpy", "(", "self", ")", ":", "full", "=", "_np", ".", "zeros", "(", "self", ".", "shape", ",", "self", ".", "dtype", ")", "ridx", "=", "_np", ".", "diff", "(", "self", ".", "indptr", ".", "numpy", "(", ")", ")", "ridx", "=", "_np", ...
https://github.com/apache/tvm/blob/6eb4ed813ebcdcd9558f0906a1870db8302ff1e0/python/tvm/contrib/sparse.py#L94-L100