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
vslavik/bakefile
0757295c3e4ac23cd1e0767c77c14c2256ed16e1
src/bkl/model.py
python
ModelPart.is_variable_null
(self, name)
return var.value.is_null()
Returns true if the variable is unset or null (which amounts to not being set in this toolset / under current condition).
Returns true if the variable is unset or null (which amounts to not being set in this toolset / under current condition).
[ "Returns", "true", "if", "the", "variable", "is", "unset", "or", "null", "(", "which", "amounts", "to", "not", "being", "set", "in", "this", "toolset", "/", "under", "current", "condition", ")", "." ]
def is_variable_null(self, name): """ Returns true if the variable is unset or null (which amounts to not being set in this toolset / under current condition). """ var = self.resolve_variable(name) if var is None: return True return var.value.is_null()
[ "def", "is_variable_null", "(", "self", ",", "name", ")", ":", "var", "=", "self", ".", "resolve_variable", "(", "name", ")", "if", "var", "is", "None", ":", "return", "True", "return", "var", ".", "value", ".", "is_null", "(", ")" ]
https://github.com/vslavik/bakefile/blob/0757295c3e4ac23cd1e0767c77c14c2256ed16e1/src/bkl/model.py#L404-L412
withdk/badusb2-mitm-poc
db2bfdb1dc9ad371aa665b292183c45577adfbaa
GoodFETMAXUSB.py
python
GoodFETMAXUSB.wreg
(self,reg,value)
return value
Poke 8 bits into a register.
Poke 8 bits into a register.
[ "Poke", "8", "bits", "into", "a", "register", "." ]
def wreg(self,reg,value): """Poke 8 bits into a register.""" data=[(reg<<3)|2,value]; self.writecmd(self.MAXUSBAPP,0x00,len(data),data); return value;
[ "def", "wreg", "(", "self", ",", "reg", ",", "value", ")", ":", "data", "=", "[", "(", "reg", "<<", "3", ")", "|", "2", ",", "value", "]", "self", ".", "writecmd", "(", "self", ".", "MAXUSBAPP", ",", "0x00", ",", "len", "(", "data", ")", ",",...
https://github.com/withdk/badusb2-mitm-poc/blob/db2bfdb1dc9ad371aa665b292183c45577adfbaa/GoodFETMAXUSB.py#L325-L329
KalleHallden/AutoTimer
2d954216700c4930baa154e28dbddc34609af7ce
env/lib/python2.7/site-packages/pip/_internal/vcs/bazaar.py
python
Bazaar.get_revision
(cls, location)
return revision.splitlines()[-1]
[]
def get_revision(cls, location): revision = cls.run_command( ['revno'], show_stdout=False, cwd=location, ) return revision.splitlines()[-1]
[ "def", "get_revision", "(", "cls", ",", "location", ")", ":", "revision", "=", "cls", ".", "run_command", "(", "[", "'revno'", "]", ",", "show_stdout", "=", "False", ",", "cwd", "=", "location", ",", ")", "return", "revision", ".", "splitlines", "(", "...
https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/pip/_internal/vcs/bazaar.py#L89-L93
wbond/package_control
cfaaeb57612023e3679ecb7f8cd7ceac9f57990d
package_control/deps/asn1crypto/keys.py
python
PrivateKeyInfo.public_key_info
(self)
:return: A PublicKeyInfo object derived from this private key.
:return: A PublicKeyInfo object derived from this private key.
[ ":", "return", ":", "A", "PublicKeyInfo", "object", "derived", "from", "this", "private", "key", "." ]
def public_key_info(self): """ :return: A PublicKeyInfo object derived from this private key. """ raise APIException( 'asn1crypto.keys.PrivateKeyInfo().public_key_info has been removed, ' 'please use oscrypto.asymmetric.PrivateKey().public_key.asn1 instead')
[ "def", "public_key_info", "(", "self", ")", ":", "raise", "APIException", "(", "'asn1crypto.keys.PrivateKeyInfo().public_key_info has been removed, '", "'please use oscrypto.asymmetric.PrivateKey().public_key.asn1 instead'", ")" ]
https://github.com/wbond/package_control/blob/cfaaeb57612023e3679ecb7f8cd7ceac9f57990d/package_control/deps/asn1crypto/keys.py#L934-L942
CoinAlpha/hummingbot
36f6149c1644c07cd36795b915f38b8f49b798e7
hummingbot/connector/exchange/ndax/ndax_exchange.py
python
NdaxExchange.buy
(self, trading_pair: str, amount: Decimal, order_type: OrderType = OrderType.MARKET, price: Decimal = s_decimal_NaN, **kwargs)
return order_id
Buys an amount of base asset as specified in the trading pair. This function returns immediately. To see an actual order, wait for a BuyOrderCreatedEvent. :param trading_pair: The market (e.g. BTC-CAD) to buy from :param amount: The amount in base token value :param order_type: The order type :param price: The price in which the order is to be placed at :returns A new client order id
Buys an amount of base asset as specified in the trading pair. This function returns immediately. To see an actual order, wait for a BuyOrderCreatedEvent. :param trading_pair: The market (e.g. BTC-CAD) to buy from :param amount: The amount in base token value :param order_type: The order type :param price: The price in which the order is to be placed at :returns A new client order id
[ "Buys", "an", "amount", "of", "base", "asset", "as", "specified", "in", "the", "trading", "pair", ".", "This", "function", "returns", "immediately", ".", "To", "see", "an", "actual", "order", "wait", "for", "a", "BuyOrderCreatedEvent", ".", ":", "param", "...
def buy(self, trading_pair: str, amount: Decimal, order_type: OrderType = OrderType.MARKET, price: Decimal = s_decimal_NaN, **kwargs) -> str: """ Buys an amount of base asset as specified in the trading pair. This function returns immediately. To see an actual order, wait for a BuyOrderCreatedEvent. :param trading_pair: The market (e.g. BTC-CAD) to buy from :param amount: The amount in base token value :param order_type: The order type :param price: The price in which the order is to be placed at :returns A new client order id """ order_id: str = ndax_utils.get_new_client_order_id(True, trading_pair) safe_ensure_future(self._create_order(trade_type=TradeType.BUY, trading_pair=trading_pair, order_id=order_id, amount=amount, price=price, order_type=order_type, )) return order_id
[ "def", "buy", "(", "self", ",", "trading_pair", ":", "str", ",", "amount", ":", "Decimal", ",", "order_type", ":", "OrderType", "=", "OrderType", ".", "MARKET", ",", "price", ":", "Decimal", "=", "s_decimal_NaN", ",", "*", "*", "kwargs", ")", "->", "st...
https://github.com/CoinAlpha/hummingbot/blob/36f6149c1644c07cd36795b915f38b8f49b798e7/hummingbot/connector/exchange/ndax/ndax_exchange.py#L481-L500
bigaidream-projects/drmad
a4bb6010595d956f29c5a42a095bab76a60b29eb
cpu_ver/hyperserver/initial_cifar10.py
python
Logger.__init__
(self, filename="Default.log")
[]
def __init__(self, filename="Default.log"): self.terminal = sys.stdout self.log = open(filename, "a")
[ "def", "__init__", "(", "self", ",", "filename", "=", "\"Default.log\"", ")", ":", "self", ".", "terminal", "=", "sys", ".", "stdout", "self", ".", "log", "=", "open", "(", "filename", ",", "\"a\"", ")" ]
https://github.com/bigaidream-projects/drmad/blob/a4bb6010595d956f29c5a42a095bab76a60b29eb/cpu_ver/hyperserver/initial_cifar10.py#L186-L188
mne-tools/mne-python
f90b303ce66a8415e64edd4605b09ac0179c1ebf
mne/io/ctf/res4.py
python
_read_double
(fid, n=1)
return np.fromfile(fid, '>f8', n)
Read a double.
Read a double.
[ "Read", "a", "double", "." ]
def _read_double(fid, n=1): """Read a double.""" return np.fromfile(fid, '>f8', n)
[ "def", "_read_double", "(", "fid", ",", "n", "=", "1", ")", ":", "return", "np", ".", "fromfile", "(", "fid", ",", "'>f8'", ",", "n", ")" ]
https://github.com/mne-tools/mne-python/blob/f90b303ce66a8415e64edd4605b09ac0179c1ebf/mne/io/ctf/res4.py#L27-L29
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/Django/django/contrib/gis/geoip/base.py
python
GeoIP.country_code
(self, query)
Returns the country code for the given IP Address or FQDN.
Returns the country code for the given IP Address or FQDN.
[ "Returns", "the", "country", "code", "for", "the", "given", "IP", "Address", "or", "FQDN", "." ]
def country_code(self, query): "Returns the country code for the given IP Address or FQDN." query = self._check_query(query, city_or_country=True) if self._country: if ipv4_re.match(query): return GeoIP_country_code_by_addr(self._country, query) else: return GeoIP_country_code_by_name(self._country, query) else: return self.city(query)['country_code']
[ "def", "country_code", "(", "self", ",", "query", ")", ":", "query", "=", "self", ".", "_check_query", "(", "query", ",", "city_or_country", "=", "True", ")", "if", "self", ".", "_country", ":", "if", "ipv4_re", ".", "match", "(", "query", ")", ":", ...
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/Django/django/contrib/gis/geoip/base.py#L165-L174
deepmind/dm_control
806a10e896e7c887635328bfa8352604ad0fedae
dm_control/autowrap/c_declarations.py
python
Function.docstring
(self)
return "\n".join(lines)
Generates a docstring.
Generates a docstring.
[ "Generates", "a", "docstring", "." ]
def docstring(self): """Generates a docstring.""" indent = codegen_util.Indenter() lines = textwrap.wrap(self.comment, width=80) if self.arguments: lines.append("\nArgs:") with indent: for a in self.arguments.values(): s = "{a.name}: {a.arg}{const}".format( a=a, const=(" <const>" if a.is_const else "")) lines.append(indent(s)) if self.return_value: lines.append("\nReturns:") with indent: lines.append(indent(self.return_value.arg)) lines.append("") # Force a newline at the end of the docstring. return "\n".join(lines)
[ "def", "docstring", "(", "self", ")", ":", "indent", "=", "codegen_util", ".", "Indenter", "(", ")", "lines", "=", "textwrap", ".", "wrap", "(", "self", ".", "comment", ",", "width", "=", "80", ")", "if", "self", ".", "arguments", ":", "lines", ".", ...
https://github.com/deepmind/dm_control/blob/806a10e896e7c887635328bfa8352604ad0fedae/dm_control/autowrap/c_declarations.py#L431-L447
FrancescoCeruti/linux-show-player
39aba4674d9a2caa365687906640d192e2b47e0f
lisp/core/fade_functions.py
python
fadeout_quad
(t, a, b)
return a * (t * (2 - t)) + b
Quadratic (t^2) fade out: decelerating to zero velocity.
Quadratic (t^2) fade out: decelerating to zero velocity.
[ "Quadratic", "(", "t^2", ")", "fade", "out", ":", "decelerating", "to", "zero", "velocity", "." ]
def fadeout_quad(t, a, b): """Quadratic (t^2) fade out: decelerating to zero velocity.""" return a * (t * (2 - t)) + b
[ "def", "fadeout_quad", "(", "t", ",", "a", ",", "b", ")", ":", "return", "a", "*", "(", "t", "*", "(", "2", "-", "t", ")", ")", "+", "b" ]
https://github.com/FrancescoCeruti/linux-show-player/blob/39aba4674d9a2caa365687906640d192e2b47e0f/lisp/core/fade_functions.py#L45-L47
daoluan/decode-Django
d46a858b45b56de48b0355f50dd9e45402d04cfd
Django-1.5.1/django/core/serializers/xml_serializer.py
python
Serializer.handle_field
(self, obj, field)
Called to handle each field on an object (except for ForeignKeys and ManyToManyFields)
Called to handle each field on an object (except for ForeignKeys and ManyToManyFields)
[ "Called", "to", "handle", "each", "field", "on", "an", "object", "(", "except", "for", "ForeignKeys", "and", "ManyToManyFields", ")" ]
def handle_field(self, obj, field): """ Called to handle each field on an object (except for ForeignKeys and ManyToManyFields) """ self.indent(2) self.xml.startElement("field", { "name" : field.name, "type" : field.get_internal_type() }) # Get a "string version" of the object's data. if getattr(obj, field.name) is not None: self.xml.characters(field.value_to_string(obj)) else: self.xml.addQuickElement("None") self.xml.endElement("field")
[ "def", "handle_field", "(", "self", ",", "obj", ",", "field", ")", ":", "self", ".", "indent", "(", "2", ")", "self", ".", "xml", ".", "startElement", "(", "\"field\"", ",", "{", "\"name\"", ":", "field", ".", "name", ",", "\"type\"", ":", "field", ...
https://github.com/daoluan/decode-Django/blob/d46a858b45b56de48b0355f50dd9e45402d04cfd/Django-1.5.1/django/core/serializers/xml_serializer.py#L67-L84
wrobstory/vincent
c5a06e50179015fbb788a7a42e4570ff4467a9e9
vincent/transforms.py
python
Transform.wordbreak
(value)
bool: If true, the truncation algorithm will truncate along word boundaries.
bool: If true, the truncation algorithm will truncate along word boundaries.
[ "bool", ":", "If", "true", "the", "truncation", "algorithm", "will", "truncate", "along", "word", "boundaries", "." ]
def wordbreak(value): """bool: If true, the truncation algorithm will truncate along word boundaries. """
[ "def", "wordbreak", "(", "value", ")", ":" ]
https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/transforms.py#L367-L370
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
txdav/common/datastore/sql.py
python
CommonObjectResource.fromTrash
(self)
[]
def fromTrash(self): originalCollection = yield self.originalCollection() yield self.moveTo(originalCollection) self._original_collection = None self._trashed = None yield self._updateFromTrashQuery.on( self._txn, resourceID=self._resourceID ) returnValue(self._name)
[ "def", "fromTrash", "(", "self", ")", ":", "originalCollection", "=", "yield", "self", ".", "originalCollection", "(", ")", "yield", "self", ".", "moveTo", "(", "originalCollection", ")", "self", ".", "_original_collection", "=", "None", "self", ".", "_trashed...
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/txdav/common/datastore/sql.py#L4950-L4959
sfepy/sfepy
02ec7bb2ab39ee1dfe1eb4cd509f0ffb7dcc8b25
sfepy/discrete/conditions.py
python
Conditions.zero_dofs
(self)
Set all boundary condition values to zero, if applicable.
Set all boundary condition values to zero, if applicable.
[ "Set", "all", "boundary", "condition", "values", "to", "zero", "if", "applicable", "." ]
def zero_dofs(self): """ Set all boundary condition values to zero, if applicable. """ for cond in self: if isinstance(cond, EssentialBC): cond.zero_dofs()
[ "def", "zero_dofs", "(", "self", ")", ":", "for", "cond", "in", "self", ":", "if", "isinstance", "(", "cond", ",", "EssentialBC", ")", ":", "cond", ".", "zero_dofs", "(", ")" ]
https://github.com/sfepy/sfepy/blob/02ec7bb2ab39ee1dfe1eb4cd509f0ffb7dcc8b25/sfepy/discrete/conditions.py#L153-L159
biocore/qiime
76d633c0389671e93febbe1338b5ded658eba31f
qiime/split.py
python
subset_mapping_data
(mdata, samples_of_interest)
return mdata[in1d(mdata[:, 0], samples_of_interest)]
Remove rows of mdata that are not from samples_of_interest. Parameters ---------- mdata : np.array 2-d array, containing data from mapping file cast as array of strings. Usually derived from parse_mapping_file. samples_of_interest : list A list of strings that are a strict subset of the samples found in the first column of mdata. Returns ------- subset of mdata Examples -------- >>> from qiime.split import subset_mapping_data >>> from numpy import array >>> mdata = array([['s0', 'blue', 'hot', '13'], ['s1', 'blue', 'cold', '1'], ['s2', 'green', 'cold', '12'], ['s3', 'cyan', 'hot', '1'], ['s4', 'blue', '0', '0']], dtype='|S5') >>> subset_mapping_data(mdata, ['s0', 's2']) array([['s0', 'blue', 'hot', '13'], ['s2', 'green', 'cold', '12']], dtype='|S5')
Remove rows of mdata that are not from samples_of_interest.
[ "Remove", "rows", "of", "mdata", "that", "are", "not", "from", "samples_of_interest", "." ]
def subset_mapping_data(mdata, samples_of_interest): '''Remove rows of mdata that are not from samples_of_interest. Parameters ---------- mdata : np.array 2-d array, containing data from mapping file cast as array of strings. Usually derived from parse_mapping_file. samples_of_interest : list A list of strings that are a strict subset of the samples found in the first column of mdata. Returns ------- subset of mdata Examples -------- >>> from qiime.split import subset_mapping_data >>> from numpy import array >>> mdata = array([['s0', 'blue', 'hot', '13'], ['s1', 'blue', 'cold', '1'], ['s2', 'green', 'cold', '12'], ['s3', 'cyan', 'hot', '1'], ['s4', 'blue', '0', '0']], dtype='|S5') >>> subset_mapping_data(mdata, ['s0', 's2']) array([['s0', 'blue', 'hot', '13'], ['s2', 'green', 'cold', '12']], dtype='|S5') ''' return mdata[in1d(mdata[:, 0], samples_of_interest)]
[ "def", "subset_mapping_data", "(", "mdata", ",", "samples_of_interest", ")", ":", "return", "mdata", "[", "in1d", "(", "mdata", "[", ":", ",", "0", "]", ",", "samples_of_interest", ")", "]" ]
https://github.com/biocore/qiime/blob/76d633c0389671e93febbe1338b5ded658eba31f/qiime/split.py#L180-L211
n1nj4sec/pupy
a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39
pupy/modules/socks5proxy.py
python
Socks5Server.__init__
(self, server_address, RequestHandlerClass, bind_and_activate=True, rpyc_client=None, module=None)
[]
def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True, rpyc_client=None, module=None): self.rpyc_client=rpyc_client self.module=module SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate)
[ "def", "__init__", "(", "self", ",", "server_address", ",", "RequestHandlerClass", ",", "bind_and_activate", "=", "True", ",", "rpyc_client", "=", "None", ",", "module", "=", "None", ")", ":", "self", ".", "rpyc_client", "=", "rpyc_client", "self", ".", "mod...
https://github.com/n1nj4sec/pupy/blob/a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39/pupy/modules/socks5proxy.py#L184-L187
jbjorne/TEES
caf19a4a1352ac59f5dc13a8684cc42ce4342d9d
Tools/Parser.py
python
Parser.getCorpus
(self, input)
return corpusTree, corpusRoot
[]
def getCorpus(self, input): print >> sys.stderr, "Loading corpus", input corpusTree = ETUtils.ETFromObj(input) print >> sys.stderr, "Corpus file loaded" corpusRoot = corpusTree.getroot() return corpusTree, corpusRoot
[ "def", "getCorpus", "(", "self", ",", "input", ")", ":", "print", ">>", "sys", ".", "stderr", ",", "\"Loading corpus\"", ",", "input", "corpusTree", "=", "ETUtils", ".", "ETFromObj", "(", "input", ")", "print", ">>", "sys", ".", "stderr", ",", "\"Corpus ...
https://github.com/jbjorne/TEES/blob/caf19a4a1352ac59f5dc13a8684cc42ce4342d9d/Tools/Parser.py#L42-L47
open-mmlab/mmpose
0376d51efdd93b3c8f3338211130753fed808bb9
mmpose/datasets/datasets/base/kpt_3d_mview_rgb_img_direct_dataset.py
python
Kpt3dMviewRgbImgDirectDataset.__len__
(self)
return len(self.db) // self.num_cameras
Get the size of the dataset.
Get the size of the dataset.
[ "Get", "the", "size", "of", "the", "dataset", "." ]
def __len__(self): """Get the size of the dataset.""" return len(self.db) // self.num_cameras
[ "def", "__len__", "(", "self", ")", ":", "return", "len", "(", "self", ".", "db", ")", "//", "self", ".", "num_cameras" ]
https://github.com/open-mmlab/mmpose/blob/0376d51efdd93b3c8f3338211130753fed808bb9/mmpose/datasets/datasets/base/kpt_3d_mview_rgb_img_direct_dataset.py#L131-L133
jensl/critic
c2d962b909ff7ef2f09bccbeb636333920b3659e
src/api/commit.py
python
Commit.getFileLines
(self, file)
return self._impl.getFileLines(file)
Fetch the lines of a file in the commit Much like getFileContents(), but splits the returned string into a list of strings in a consistent way that matches how other parts of Critic treats line breaks, and thus compatible with stored line numbers. Note: commit.getFileContents(...).splitlines() is *not* correct!
Fetch the lines of a file in the commit
[ "Fetch", "the", "lines", "of", "a", "file", "in", "the", "commit" ]
def getFileLines(self, file): """Fetch the lines of a file in the commit Much like getFileContents(), but splits the returned string into a list of strings in a consistent way that matches how other parts of Critic treats line breaks, and thus compatible with stored line numbers. Note: commit.getFileContents(...).splitlines() is *not* correct!""" assert isinstance(file, api.file.File) return self._impl.getFileLines(file)
[ "def", "getFileLines", "(", "self", ",", "file", ")", ":", "assert", "isinstance", "(", "file", ",", "api", ".", "file", ".", "File", ")", "return", "self", ".", "_impl", ".", "getFileLines", "(", "file", ")" ]
https://github.com/jensl/critic/blob/c2d962b909ff7ef2f09bccbeb636333920b3659e/src/api/commit.py#L179-L189
s-leger/archipack
5a6243bf1edf08a6b429661ce291dacb551e5f8a
archipack_manipulator.py
python
Manipulator.__init__
(self, context, o, datablock, manipulator, snap_callback=None)
o : object to manipulate datablock : object data to manipulate manipulator: object archipack_manipulator datablock snap_callback: on snap enabled manipulators, will be called when drag occurs
o : object to manipulate datablock : object data to manipulate manipulator: object archipack_manipulator datablock snap_callback: on snap enabled manipulators, will be called when drag occurs
[ "o", ":", "object", "to", "manipulate", "datablock", ":", "object", "data", "to", "manipulate", "manipulator", ":", "object", "archipack_manipulator", "datablock", "snap_callback", ":", "on", "snap", "enabled", "manipulators", "will", "be", "called", "when", "drag...
def __init__(self, context, o, datablock, manipulator, snap_callback=None): """ o : object to manipulate datablock : object data to manipulate manipulator: object archipack_manipulator datablock snap_callback: on snap enabled manipulators, will be called when drag occurs """ self.keymap = Keymaps(context) self.feedback = FeedbackPanel() self.active = False self.selectable = False self.selected = False # active text input value for manipulator self.keyboard_input_active = False self.label_value = 0 # unit for keyboard input value self.value_type = 'LENGTH' self.pts_mode = 'SIZE' # must hold those data here self.o = o self.datablock = datablock self.manipulator = manipulator self.snap_callback = snap_callback self.origin = self.o.matrix_world.translation.copy() self.mouse_pos = Vector((0, 0)) self.length_entered = "" self.line_pos = 0 args = (self, context) self._handle = bpy.types.SpaceView3D.draw_handler_add(self.draw_callback, args, 'WINDOW', 'POST_PIXEL')
[ "def", "__init__", "(", "self", ",", "context", ",", "o", ",", "datablock", ",", "manipulator", ",", "snap_callback", "=", "None", ")", ":", "self", ".", "keymap", "=", "Keymaps", "(", "context", ")", "self", ".", "feedback", "=", "FeedbackPanel", "(", ...
https://github.com/s-leger/archipack/blob/5a6243bf1edf08a6b429661ce291dacb551e5f8a/archipack_manipulator.py#L240-L270
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_openshift/library/oc_pvc.py
python
Utils.create_tmp_files_from_contents
(content, content_type=None)
return files
Turn an array of dict: filename, content into a files array
Turn an array of dict: filename, content into a files array
[ "Turn", "an", "array", "of", "dict", ":", "filename", "content", "into", "a", "files", "array" ]
def create_tmp_files_from_contents(content, content_type=None): '''Turn an array of dict: filename, content into a files array''' if not isinstance(content, list): content = [content] files = [] for item in content: path = Utils.create_tmp_file_from_contents(item['path'] + '-', item['data'], ftype=content_type) files.append({'name': os.path.basename(item['path']), 'path': path}) return files
[ "def", "create_tmp_files_from_contents", "(", "content", ",", "content_type", "=", "None", ")", ":", "if", "not", "isinstance", "(", "content", ",", "list", ")", ":", "content", "=", "[", "content", "]", "files", "=", "[", "]", "for", "item", "in", "cont...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_openshift/library/oc_pvc.py#L1227-L1238
selinon/selinon
3613153566d454022a138639f0375c63f490c4cb
selinon/builtin_predicate.py
python
AlwaysTruePredicate.__init__
(self, flow)
Instantiate predicate that holds always True. :param flow: flow for which this predicate is used
Instantiate predicate that holds always True.
[ "Instantiate", "predicate", "that", "holds", "always", "True", "." ]
def __init__(self, flow): """Instantiate predicate that holds always True. :param flow: flow for which this predicate is used """ super().__init__() self.flow = flow
[ "def", "__init__", "(", "self", ",", "flow", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "self", ".", "flow", "=", "flow" ]
https://github.com/selinon/selinon/blob/3613153566d454022a138639f0375c63f490c4cb/selinon/builtin_predicate.py#L259-L265
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Tools/msi/msilib.py
python
Dialog.text
(self, name, x, y, w, h, attr, text)
return self.control(name, "Text", x, y, w, h, attr, None, text, None, None)
[]
def text(self, name, x, y, w, h, attr, text): return self.control(name, "Text", x, y, w, h, attr, None, text, None, None)
[ "def", "text", "(", "self", ",", "name", ",", "x", ",", "y", ",", "w", ",", "h", ",", "attr", ",", "text", ")", ":", "return", "self", ".", "control", "(", "name", ",", "\"Text\"", ",", "x", ",", "y", ",", "w", ",", "h", ",", "attr", ",", ...
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Tools/msi/msilib.py#L637-L639
robotframework/robotframework
e4f66e7bbe02b1741224ad4ab3fbfe9e1cb51ecf
src/robot/libraries/OperatingSystem.py
python
OperatingSystem.directory_should_exist
(self, path, msg=None)
Fails unless the given path points to an existing directory. The path can be given as an exact path or as a glob pattern. See the `Glob patterns` section for details about the supported syntax. The default error message can be overridden with the ``msg`` argument.
Fails unless the given path points to an existing directory.
[ "Fails", "unless", "the", "given", "path", "points", "to", "an", "existing", "directory", "." ]
def directory_should_exist(self, path, msg=None): """Fails unless the given path points to an existing directory. The path can be given as an exact path or as a glob pattern. See the `Glob patterns` section for details about the supported syntax. The default error message can be overridden with the ``msg`` argument. """ path = self._absnorm(path) matches = [p for p in self._glob(path) if os.path.isdir(p)] if not matches: self._fail(msg, "Directory '%s' does not exist." % path) self._link("Directory '%s' exists.", path)
[ "def", "directory_should_exist", "(", "self", ",", "path", ",", "msg", "=", "None", ")", ":", "path", "=", "self", ".", "_absnorm", "(", "path", ")", "matches", "=", "[", "p", "for", "p", "in", "self", ".", "_glob", "(", "path", ")", "if", "os", ...
https://github.com/robotframework/robotframework/blob/e4f66e7bbe02b1741224ad4ab3fbfe9e1cb51ecf/src/robot/libraries/OperatingSystem.py#L429-L441
kalliope-project/kalliope
7b2bb4671c8fbfa0ea9f768c84994fe75da974eb
kalliope/core/ConfigurationManager/SettingLoader.py
python
SettingLoader._get_default_speech_to_text
(settings)
Get the default speech to text defined in the settings.yml file :param settings: The YAML settings file :type settings: dict :return: the default speech to text :rtype: str :Example: default_stt_name = cls._get_default_speech_to_text(settings) .. seealso:: Stt .. raises:: NullSettingException, SettingNotFound .. warnings:: Static and Private
Get the default speech to text defined in the settings.yml file
[ "Get", "the", "default", "speech", "to", "text", "defined", "in", "the", "settings", ".", "yml", "file" ]
def _get_default_speech_to_text(settings): """ Get the default speech to text defined in the settings.yml file :param settings: The YAML settings file :type settings: dict :return: the default speech to text :rtype: str :Example: default_stt_name = cls._get_default_speech_to_text(settings) .. seealso:: Stt .. raises:: NullSettingException, SettingNotFound .. warnings:: Static and Private """ try: default_speech_to_text = settings["default_speech_to_text"] if default_speech_to_text is None: raise NullSettingException("Attribute default_speech_to_text is null") logger.debug("Default STT: %s" % default_speech_to_text) return default_speech_to_text except KeyError as e: raise SettingNotFound("%s setting not found" % e)
[ "def", "_get_default_speech_to_text", "(", "settings", ")", ":", "try", ":", "default_speech_to_text", "=", "settings", "[", "\"default_speech_to_text\"", "]", "if", "default_speech_to_text", "is", "None", ":", "raise", "NullSettingException", "(", "\"Attribute default_sp...
https://github.com/kalliope-project/kalliope/blob/7b2bb4671c8fbfa0ea9f768c84994fe75da974eb/kalliope/core/ConfigurationManager/SettingLoader.py#L140-L165
sqall01/alertR
e1d1a83e54f876cc4cd7bd87387e05cb75d4dc13
sensorClientGPS/lib/sensor/core.py
python
_PollingSensor.exit
(self)
Exits sensor thread.
Exits sensor thread.
[ "Exits", "sensor", "thread", "." ]
def exit(self): """ Exits sensor thread. """ self._exit_flag = True
[ "def", "exit", "(", "self", ")", ":", "self", ".", "_exit_flag", "=", "True" ]
https://github.com/sqall01/alertR/blob/e1d1a83e54f876cc4cd7bd87387e05cb75d4dc13/sensorClientGPS/lib/sensor/core.py#L241-L245
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/interfaces/polymake.py
python
PolymakeElement.__len__
(self)
return int(P.eval('print scalar {};'.format(name)))
EXAMPLES:: sage: p = polymake.rand_sphere(3, 12, seed=15) # optional - polymake sage: len(p.FACETS) # optional - polymake 20 sage: len(p.list_properties()) >= 12 # optional - polymake True
EXAMPLES::
[ "EXAMPLES", "::" ]
def __len__(self): """ EXAMPLES:: sage: p = polymake.rand_sphere(3, 12, seed=15) # optional - polymake sage: len(p.FACETS) # optional - polymake 20 sage: len(p.list_properties()) >= 12 # optional - polymake True """ P = self._check_valid() T1, T2 = self.typeof() name = self._name if T2 == 'ARRAY': return int(P.eval('print scalar @{+%s};' % name)) if T2 == 'HASH': return int(P.eval('print scalar keys %' + ('{+%s};' % name))) if T1: raise TypeError("Don't know how to compute the length of {} object".format(T1)) return int(P.eval('print scalar {};'.format(name)))
[ "def", "__len__", "(", "self", ")", ":", "P", "=", "self", ".", "_check_valid", "(", ")", "T1", ",", "T2", "=", "self", ".", "typeof", "(", ")", "name", "=", "self", ".", "_name", "if", "T2", "==", "'ARRAY'", ":", "return", "int", "(", "P", "."...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/interfaces/polymake.py#L1446-L1466
runawayhorse001/LearningApacheSpark
67f3879dce17553195f094f5728b94a01badcf24
pyspark/streaming/kafka.py
python
OffsetRange.__init__
(self, topic, partition, fromOffset, untilOffset)
Create an OffsetRange to represent range of offsets :param topic: Kafka topic name. :param partition: Kafka partition id. :param fromOffset: Inclusive starting offset. :param untilOffset: Exclusive ending offset.
Create an OffsetRange to represent range of offsets :param topic: Kafka topic name. :param partition: Kafka partition id. :param fromOffset: Inclusive starting offset. :param untilOffset: Exclusive ending offset.
[ "Create", "an", "OffsetRange", "to", "represent", "range", "of", "offsets", ":", "param", "topic", ":", "Kafka", "topic", "name", ".", ":", "param", "partition", ":", "Kafka", "partition", "id", ".", ":", "param", "fromOffset", ":", "Inclusive", "starting", ...
def __init__(self, topic, partition, fromOffset, untilOffset): """ Create an OffsetRange to represent range of offsets :param topic: Kafka topic name. :param partition: Kafka partition id. :param fromOffset: Inclusive starting offset. :param untilOffset: Exclusive ending offset. """ warnings.warn( "Deprecated in 2.3.0. Kafka 0.8 support is deprecated as of Spark 2.3.0. " "See SPARK-21893.", DeprecationWarning) self.topic = topic self.partition = partition self.fromOffset = fromOffset self.untilOffset = untilOffset
[ "def", "__init__", "(", "self", ",", "topic", ",", "partition", ",", "fromOffset", ",", "untilOffset", ")", ":", "warnings", ".", "warn", "(", "\"Deprecated in 2.3.0. Kafka 0.8 support is deprecated as of Spark 2.3.0. \"", "\"See SPARK-21893.\"", ",", "DeprecationWarning", ...
https://github.com/runawayhorse001/LearningApacheSpark/blob/67f3879dce17553195f094f5728b94a01badcf24/pyspark/streaming/kafka.py#L254-L269
salabim/salabim
e0de846b042daf2dc71aaf43d8adc6486b57f376
salabim_exp.py
python
test62
()
[]
def test62(): class X1(sim.Component): def process(self): yield self.hold(100) class X2(sim.Component): def process(self): yield self.request(res, fail_at=100) yield self.hold(50) class X3(sim.Component): def process(self): yield self.passivate() class X4(sim.Component): def process(self): while True: yield self.standby() class X5(sim.Component): def process(self): yield self.wait(st, fail_at=100) yield self.hold(50) class Z(sim.Component): def process(self): for i in range(20): yield self.hold(1) class Y(sim.Component): def process(self): yield self.hold(4) x1.remaining_duration(100) yield self.hold(1) x1.interrupt() x2.interrupt() x2.interrupt() x3.interrupt() x4.interrupt() x5.interrupt() yield self.hold(2) res.set_capacity(0) st.set() yield self.hold(3) x1.resume() x2.resume() x3.resume() x4.resume() x5.resume() x2.resume() env = sim.Environment(trace=True) env.suppress_trace_standby(False) x1 = X1() x1.name("abc") x2 = X2() x3 = X3() x4 = X4() x5 = X5() y = Y() z = Z() res = sim.Resource("res", capacity=0) st = sim.State("st") env.run(urgent=True)
[ "def", "test62", "(", ")", ":", "class", "X1", "(", "sim", ".", "Component", ")", ":", "def", "process", "(", "self", ")", ":", "yield", "self", ".", "hold", "(", "100", ")", "class", "X2", "(", "sim", ".", "Component", ")", ":", "def", "process"...
https://github.com/salabim/salabim/blob/e0de846b042daf2dc71aaf43d8adc6486b57f376/salabim_exp.py#L2441-L2506
RenYurui/StructureFlow
1ac8f559475452e6b674699671c6b34f000d9ebd
src/data.py
python
Dataset.create_iterator
(self, batch_size)
[]
def create_iterator(self, batch_size): while True: sample_loader = DataLoader( dataset=self, batch_size=batch_size, drop_last=True ) for item in sample_loader: yield item
[ "def", "create_iterator", "(", "self", ",", "batch_size", ")", ":", "while", "True", ":", "sample_loader", "=", "DataLoader", "(", "dataset", "=", "self", ",", "batch_size", "=", "batch_size", ",", "drop_last", "=", "True", ")", "for", "item", "in", "sampl...
https://github.com/RenYurui/StructureFlow/blob/1ac8f559475452e6b674699671c6b34f000d9ebd/src/data.py#L142-L151
OpenEIT/OpenEIT
0448694e8092361ae5ccb45fba81dee543a6244b
OpenEIT/reconstruction/pyeit/mesh/shape.py
python
rectangle
(pts, p1=None, p2=None)
return np.maximum(pd_left, pd_right)
Distance function for the rectangle p1=[x1, y1] and p2=[x2, y2] Note ---- p1 should be bottom-left, p2 should be top-right if p in rect(p1, p2), then (p-p1)_x and (p-p2)_x must have opposite sign Parameters ---------- pts : array_like p1 : array_like, optional bottom left coordinates p2 : array_like, optional top tight coordinates Returns ------- array_like distance
Distance function for the rectangle p1=[x1, y1] and p2=[x2, y2]
[ "Distance", "function", "for", "the", "rectangle", "p1", "=", "[", "x1", "y1", "]", "and", "p2", "=", "[", "x2", "y2", "]" ]
def rectangle(pts, p1=None, p2=None): """ Distance function for the rectangle p1=[x1, y1] and p2=[x2, y2] Note ---- p1 should be bottom-left, p2 should be top-right if p in rect(p1, p2), then (p-p1)_x and (p-p2)_x must have opposite sign Parameters ---------- pts : array_like p1 : array_like, optional bottom left coordinates p2 : array_like, optional top tight coordinates Returns ------- array_like distance """ if p1 is None: p1 = [0, 0] if p2 is None: p2 = [1, 1] if pts.ndim == 1: pts = pts[np.newaxis] pd_left = [-min(row) for row in pts - p1] pd_right = [max(row) for row in pts - p2] return np.maximum(pd_left, pd_right)
[ "def", "rectangle", "(", "pts", ",", "p1", "=", "None", ",", "p2", "=", "None", ")", ":", "if", "p1", "is", "None", ":", "p1", "=", "[", "0", ",", "0", "]", "if", "p2", "is", "None", ":", "p2", "=", "[", "1", ",", "1", "]", "if", "pts", ...
https://github.com/OpenEIT/OpenEIT/blob/0448694e8092361ae5ccb45fba81dee543a6244b/OpenEIT/reconstruction/pyeit/mesh/shape.py#L87-L118
paarthneekhara/byteNet-tensorflow
9bba9352e5f8a89a32ab14e9546a158750cdbfaf
ByteNet/translator.py
python
ByteNet_Translator.__init__
(self, options)
[]
def __init__(self, options): self.options = options embedding_channels = 2 * options['residual_channels'] self.w_source_embedding = tf.get_variable('w_source_embedding', [options['source_vocab_size'], embedding_channels], initializer=tf.truncated_normal_initializer(stddev=0.02)) self.w_target_embedding = tf.get_variable('w_target_embedding', [options['target_vocab_size'], embedding_channels], initializer=tf.truncated_normal_initializer(stddev=0.02))
[ "def", "__init__", "(", "self", ",", "options", ")", ":", "self", ".", "options", "=", "options", "embedding_channels", "=", "2", "*", "options", "[", "'residual_channels'", "]", "self", ".", "w_source_embedding", "=", "tf", ".", "get_variable", "(", "'w_sou...
https://github.com/paarthneekhara/byteNet-tensorflow/blob/9bba9352e5f8a89a32ab14e9546a158750cdbfaf/ByteNet/translator.py#L5-L15
pymedusa/Medusa
1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38
ext/boto/ec2/image.py
python
Image.run
(self, min_count=1, max_count=1, key_name=None, security_groups=None, user_data=None, addressing_type=None, instance_type='m1.small', placement=None, kernel_id=None, ramdisk_id=None, monitoring_enabled=False, subnet_id=None, block_device_map=None, disable_api_termination=False, instance_initiated_shutdown_behavior=None, private_ip_address=None, placement_group=None, security_group_ids=None, additional_info=None, instance_profile_name=None, instance_profile_arn=None, tenancy=None, dry_run=False)
return self.connection.run_instances(self.id, min_count, max_count, key_name, security_groups, user_data, addressing_type, instance_type, placement, kernel_id, ramdisk_id, monitoring_enabled, subnet_id, block_device_map, disable_api_termination, instance_initiated_shutdown_behavior, private_ip_address, placement_group, security_group_ids=security_group_ids, additional_info=additional_info, instance_profile_name=instance_profile_name, instance_profile_arn=instance_profile_arn, tenancy=tenancy, dry_run=dry_run)
Runs this instance. :type min_count: int :param min_count: The minimum number of instances to start :type max_count: int :param max_count: The maximum number of instances to start :type key_name: string :param key_name: The name of the key pair with which to launch instances. :type security_groups: list of strings :param security_groups: The names of the security groups with which to associate instances. :type user_data: string :param user_data: The Base64-encoded MIME user data to be made available to the instance(s) in this reservation. :type instance_type: string :param instance_type: The type of instance to run: * t1.micro * m1.small * m1.medium * m1.large * m1.xlarge * m3.medium * m3.large * m3.xlarge * m3.2xlarge * c1.medium * c1.xlarge * m2.xlarge * m2.2xlarge * m2.4xlarge * cr1.8xlarge * hi1.4xlarge * hs1.8xlarge * cc1.4xlarge * cg1.4xlarge * cc2.8xlarge * g2.2xlarge * c3.large * c3.xlarge * c3.2xlarge * c3.4xlarge * c3.8xlarge * c4.large * c4.xlarge * c4.2xlarge * c4.4xlarge * c4.8xlarge * i2.xlarge * i2.2xlarge * i2.4xlarge * i2.8xlarge * t2.micro * t2.small * t2.medium :type placement: string :param placement: The Availability Zone to launch the instance into. :type kernel_id: string :param kernel_id: The ID of the kernel with which to launch the instances. :type ramdisk_id: string :param ramdisk_id: The ID of the RAM disk with which to launch the instances. :type monitoring_enabled: bool :param monitoring_enabled: Enable CloudWatch monitoring on the instance. :type subnet_id: string :param subnet_id: The subnet ID within which to launch the instances for VPC. :type private_ip_address: string :param private_ip_address: If you're using VPC, you can optionally use this parameter to assign the instance a specific available IP address from the subnet (e.g., 10.0.0.25). :type block_device_map: :class:`boto.ec2.blockdevicemapping.BlockDeviceMapping` :param block_device_map: A BlockDeviceMapping data structure describing the EBS volumes associated with the Image. :type disable_api_termination: bool :param disable_api_termination: If True, the instances will be locked and will not be able to be terminated via the API. :type instance_initiated_shutdown_behavior: string :param instance_initiated_shutdown_behavior: Specifies whether the instance stops or terminates on instance-initiated shutdown. Valid values are: * stop * terminate :type placement_group: string :param placement_group: If specified, this is the name of the placement group in which the instance(s) will be launched. :type additional_info: string :param additional_info: Specifies additional information to make available to the instance(s). :type security_group_ids: list of strings :param security_group_ids: The ID of the VPC security groups with which to associate instances. :type instance_profile_name: string :param instance_profile_name: The name of the IAM Instance Profile (IIP) to associate with the instances. :type instance_profile_arn: string :param instance_profile_arn: The Amazon resource name (ARN) of the IAM Instance Profile (IIP) to associate with the instances. :type tenancy: string :param tenancy: The tenancy of the instance you want to launch. An instance with a tenancy of 'dedicated' runs on single-tenant hardware and can only be launched into a VPC. Valid values are:"default" or "dedicated". NOTE: To use dedicated tenancy you MUST specify a VPC subnet-ID as well. :rtype: Reservation :return: The :class:`boto.ec2.instance.Reservation` associated with the request for machines
Runs this instance.
[ "Runs", "this", "instance", "." ]
def run(self, min_count=1, max_count=1, key_name=None, security_groups=None, user_data=None, addressing_type=None, instance_type='m1.small', placement=None, kernel_id=None, ramdisk_id=None, monitoring_enabled=False, subnet_id=None, block_device_map=None, disable_api_termination=False, instance_initiated_shutdown_behavior=None, private_ip_address=None, placement_group=None, security_group_ids=None, additional_info=None, instance_profile_name=None, instance_profile_arn=None, tenancy=None, dry_run=False): """ Runs this instance. :type min_count: int :param min_count: The minimum number of instances to start :type max_count: int :param max_count: The maximum number of instances to start :type key_name: string :param key_name: The name of the key pair with which to launch instances. :type security_groups: list of strings :param security_groups: The names of the security groups with which to associate instances. :type user_data: string :param user_data: The Base64-encoded MIME user data to be made available to the instance(s) in this reservation. :type instance_type: string :param instance_type: The type of instance to run: * t1.micro * m1.small * m1.medium * m1.large * m1.xlarge * m3.medium * m3.large * m3.xlarge * m3.2xlarge * c1.medium * c1.xlarge * m2.xlarge * m2.2xlarge * m2.4xlarge * cr1.8xlarge * hi1.4xlarge * hs1.8xlarge * cc1.4xlarge * cg1.4xlarge * cc2.8xlarge * g2.2xlarge * c3.large * c3.xlarge * c3.2xlarge * c3.4xlarge * c3.8xlarge * c4.large * c4.xlarge * c4.2xlarge * c4.4xlarge * c4.8xlarge * i2.xlarge * i2.2xlarge * i2.4xlarge * i2.8xlarge * t2.micro * t2.small * t2.medium :type placement: string :param placement: The Availability Zone to launch the instance into. :type kernel_id: string :param kernel_id: The ID of the kernel with which to launch the instances. :type ramdisk_id: string :param ramdisk_id: The ID of the RAM disk with which to launch the instances. :type monitoring_enabled: bool :param monitoring_enabled: Enable CloudWatch monitoring on the instance. :type subnet_id: string :param subnet_id: The subnet ID within which to launch the instances for VPC. :type private_ip_address: string :param private_ip_address: If you're using VPC, you can optionally use this parameter to assign the instance a specific available IP address from the subnet (e.g., 10.0.0.25). :type block_device_map: :class:`boto.ec2.blockdevicemapping.BlockDeviceMapping` :param block_device_map: A BlockDeviceMapping data structure describing the EBS volumes associated with the Image. :type disable_api_termination: bool :param disable_api_termination: If True, the instances will be locked and will not be able to be terminated via the API. :type instance_initiated_shutdown_behavior: string :param instance_initiated_shutdown_behavior: Specifies whether the instance stops or terminates on instance-initiated shutdown. Valid values are: * stop * terminate :type placement_group: string :param placement_group: If specified, this is the name of the placement group in which the instance(s) will be launched. :type additional_info: string :param additional_info: Specifies additional information to make available to the instance(s). :type security_group_ids: list of strings :param security_group_ids: The ID of the VPC security groups with which to associate instances. :type instance_profile_name: string :param instance_profile_name: The name of the IAM Instance Profile (IIP) to associate with the instances. :type instance_profile_arn: string :param instance_profile_arn: The Amazon resource name (ARN) of the IAM Instance Profile (IIP) to associate with the instances. :type tenancy: string :param tenancy: The tenancy of the instance you want to launch. An instance with a tenancy of 'dedicated' runs on single-tenant hardware and can only be launched into a VPC. Valid values are:"default" or "dedicated". NOTE: To use dedicated tenancy you MUST specify a VPC subnet-ID as well. :rtype: Reservation :return: The :class:`boto.ec2.instance.Reservation` associated with the request for machines """ return self.connection.run_instances(self.id, min_count, max_count, key_name, security_groups, user_data, addressing_type, instance_type, placement, kernel_id, ramdisk_id, monitoring_enabled, subnet_id, block_device_map, disable_api_termination, instance_initiated_shutdown_behavior, private_ip_address, placement_group, security_group_ids=security_group_ids, additional_info=additional_info, instance_profile_name=instance_profile_name, instance_profile_arn=instance_profile_arn, tenancy=tenancy, dry_run=dry_run)
[ "def", "run", "(", "self", ",", "min_count", "=", "1", ",", "max_count", "=", "1", ",", "key_name", "=", "None", ",", "security_groups", "=", "None", ",", "user_data", "=", "None", ",", "addressing_type", "=", "None", ",", "instance_type", "=", "'m1.smal...
https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/boto/ec2/image.py#L170-L334
pyqt/examples
843bb982917cecb2350b5f6d7f42c9b7fb142ec1
src/pyqt-official/tutorials/addressbook/part2.py
python
SortedDict.__iter__
(self)
return SortedDict.Iterator(self)
[]
def __iter__(self): return SortedDict.Iterator(self)
[ "def", "__iter__", "(", "self", ")", ":", "return", "SortedDict", ".", "Iterator", "(", "self", ")" ]
https://github.com/pyqt/examples/blob/843bb982917cecb2350b5f6d7f42c9b7fb142ec1/src/pyqt-official/tutorials/addressbook/part2.py#L72-L73
matsoftware/swift-code-metrics
248fe457ca76df30651e50d3d71a2c5499447809
swift_code_metrics/_graphs_presenter.py
python
GraphPresenter.sorted_data_plot
(self, title, list_of_frameworks, f_of_framework)
Renders framework related data to a bar plot.
Renders framework related data to a bar plot.
[ "Renders", "framework", "related", "data", "to", "a", "bar", "plot", "." ]
def sorted_data_plot(self, title, list_of_frameworks, f_of_framework): """ Renders framework related data to a bar plot. """ sorted_data = sorted(list(map(lambda f: (f_of_framework(f), f.name), list_of_frameworks)), key=lambda tup: tup[0]) plot_data = (list(map(lambda f: f[0], sorted_data)), list(map(lambda f: f[1], sorted_data))) self.graph.bar_plot(title, plot_data)
[ "def", "sorted_data_plot", "(", "self", ",", "title", ",", "list_of_frameworks", ",", "f_of_framework", ")", ":", "sorted_data", "=", "sorted", "(", "list", "(", "map", "(", "lambda", "f", ":", "(", "f_of_framework", "(", "f", ")", ",", "f", ".", "name",...
https://github.com/matsoftware/swift-code-metrics/blob/248fe457ca76df30651e50d3d71a2c5499447809/swift_code_metrics/_graphs_presenter.py#L11-L21
equalitie/learn2ban
d45420c9d2eea2c81972c778a96a2ca42b318b6f
src/tools/learn2bantools.py
python
Learn2BanTools.random_slicer
(self, data_size, train_portion=0.5)
return random_selector, complement_selector
Return two arrays with random true and false and complement of each other, used for slicing a set into trainig and testing INPUT: data_size: size of the array to return train_portion: between 0,1 indicate the portion for the True entry
Return two arrays with random true and false and complement of each other, used for slicing a set into trainig and testing
[ "Return", "two", "arrays", "with", "random", "true", "and", "false", "and", "complement", "of", "each", "other", "used", "for", "slicing", "a", "set", "into", "trainig", "and", "testing" ]
def random_slicer(self, data_size, train_portion=0.5): """ Return two arrays with random true and false and complement of each other, used for slicing a set into trainig and testing INPUT: data_size: size of the array to return train_portion: between 0,1 indicate the portion for the True entry """ from random import random random_selector = [random() < train_portion for i in range(0, data_size)] complement_selector = np.logical_not(random_selector) return random_selector, complement_selector
[ "def", "random_slicer", "(", "self", ",", "data_size", ",", "train_portion", "=", "0.5", ")", ":", "from", "random", "import", "random", "random_selector", "=", "[", "random", "(", ")", "<", "train_portion", "for", "i", "in", "range", "(", "0", ",", "dat...
https://github.com/equalitie/learn2ban/blob/d45420c9d2eea2c81972c778a96a2ca42b318b6f/src/tools/learn2bantools.py#L250-L264
jerryli27/TwinGAN
4e5593445778dfb77af9f815b3f4fcafc35758dc
datasets/convert_general_image_data.py
python
GeneralImageDataConverter.__init__
(self)
Converts general images into tfrecord format. Intended to be inherited for more specific uses.
Converts general images into tfrecord format. Intended to be inherited for more specific uses.
[ "Converts", "general", "images", "into", "tfrecord", "format", ".", "Intended", "to", "be", "inherited", "for", "more", "specific", "uses", "." ]
def __init__(self): """Converts general images into tfrecord format. Intended to be inherited for more specific uses.""" self.coder = self.get_coder() self.session = tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) self.coder.set_session(session=self.session)
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "coder", "=", "self", ".", "get_coder", "(", ")", "self", ".", "session", "=", "tf", ".", "Session", "(", "config", "=", "tf", ".", "ConfigProto", "(", "allow_soft_placement", "=", "True", ")", "...
https://github.com/jerryli27/TwinGAN/blob/4e5593445778dfb77af9f815b3f4fcafc35758dc/datasets/convert_general_image_data.py#L74-L78
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/site-packages/pandas-0.17.0-py3.3-win-amd64.egg/pandas/io/pytables.py
python
Fixed.set_version
(self)
compute and set our version
compute and set our version
[ "compute", "and", "set", "our", "version" ]
def set_version(self): """ compute and set our version """ version = _ensure_decoded( getattr(self.group._v_attrs, 'pandas_version', None)) try: self.version = tuple([int(x) for x in version.split('.')]) if len(self.version) == 2: self.version = self.version + (0,) except: self.version = (0, 0, 0)
[ "def", "set_version", "(", "self", ")", ":", "version", "=", "_ensure_decoded", "(", "getattr", "(", "self", ".", "group", ".", "_v_attrs", ",", "'pandas_version'", ",", "None", ")", ")", "try", ":", "self", ".", "version", "=", "tuple", "(", "[", "int...
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/pandas-0.17.0-py3.3-win-amd64.egg/pandas/io/pytables.py#L2141-L2150
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/scipy/signal/_peak_finding.py
python
_identify_ridge_lines
(matr, max_distances, gap_thresh)
return out_lines
Identify ridges in the 2-D matrix. Expect that the width of the wavelet feature increases with increasing row number. Parameters ---------- matr : 2-D ndarray Matrix in which to identify ridge lines. max_distances : 1-D sequence At each row, a ridge line is only connected if the relative max at row[n] is within `max_distances`[n] from the relative max at row[n+1]. gap_thresh : int If a relative maximum is not found within `max_distances`, there will be a gap. A ridge line is discontinued if there are more than `gap_thresh` points without connecting a new relative maximum. Returns ------- ridge_lines : tuple Tuple of 2 1-D sequences. `ridge_lines`[ii][0] are the rows of the ii-th ridge-line, `ridge_lines`[ii][1] are the columns. Empty if none found. Each ridge-line will be sorted by row (increasing), but the order of the ridge lines is not specified. References ---------- Bioinformatics (2006) 22 (17): 2059-2065. doi: 10.1093/bioinformatics/btl355 http://bioinformatics.oxfordjournals.org/content/22/17/2059.long Examples -------- >>> data = np.random.rand(5,5) >>> ridge_lines = _identify_ridge_lines(data, 1, 1) Notes ----- This function is intended to be used in conjunction with `cwt` as part of `find_peaks_cwt`.
Identify ridges in the 2-D matrix.
[ "Identify", "ridges", "in", "the", "2", "-", "D", "matrix", "." ]
def _identify_ridge_lines(matr, max_distances, gap_thresh): """ Identify ridges in the 2-D matrix. Expect that the width of the wavelet feature increases with increasing row number. Parameters ---------- matr : 2-D ndarray Matrix in which to identify ridge lines. max_distances : 1-D sequence At each row, a ridge line is only connected if the relative max at row[n] is within `max_distances`[n] from the relative max at row[n+1]. gap_thresh : int If a relative maximum is not found within `max_distances`, there will be a gap. A ridge line is discontinued if there are more than `gap_thresh` points without connecting a new relative maximum. Returns ------- ridge_lines : tuple Tuple of 2 1-D sequences. `ridge_lines`[ii][0] are the rows of the ii-th ridge-line, `ridge_lines`[ii][1] are the columns. Empty if none found. Each ridge-line will be sorted by row (increasing), but the order of the ridge lines is not specified. References ---------- Bioinformatics (2006) 22 (17): 2059-2065. doi: 10.1093/bioinformatics/btl355 http://bioinformatics.oxfordjournals.org/content/22/17/2059.long Examples -------- >>> data = np.random.rand(5,5) >>> ridge_lines = _identify_ridge_lines(data, 1, 1) Notes ----- This function is intended to be used in conjunction with `cwt` as part of `find_peaks_cwt`. """ if(len(max_distances) < matr.shape[0]): raise ValueError('Max_distances must have at least as many rows ' 'as matr') all_max_cols = _boolrelextrema(matr, np.greater, axis=1, order=1) # Highest row for which there are any relative maxima has_relmax = np.where(all_max_cols.any(axis=1))[0] if(len(has_relmax) == 0): return [] start_row = has_relmax[-1] # Each ridge line is a 3-tuple: # rows, cols,Gap number ridge_lines = [[[start_row], [col], 0] for col in np.where(all_max_cols[start_row])[0]] final_lines = [] rows = np.arange(start_row - 1, -1, -1) cols = np.arange(0, matr.shape[1]) for row in rows: this_max_cols = cols[all_max_cols[row]] # Increment gap number of each line, # set it to zero later if appropriate for line in ridge_lines: line[2] += 1 # XXX These should always be all_max_cols[row] # But the order might be different. Might be an efficiency gain # to make sure the order is the same and avoid this iteration prev_ridge_cols = np.array([line[1][-1] for line in ridge_lines]) # Look through every relative maximum found at current row # Attempt to connect them with existing ridge lines. for ind, col in enumerate(this_max_cols): # If there is a previous ridge line within # the max_distance to connect to, do so. # Otherwise start a new one. line = None if(len(prev_ridge_cols) > 0): diffs = np.abs(col - prev_ridge_cols) closest = np.argmin(diffs) if diffs[closest] <= max_distances[row]: line = ridge_lines[closest] if(line is not None): # Found a point close enough, extend current ridge line line[1].append(col) line[0].append(row) line[2] = 0 else: new_line = [[row], [col], 0] ridge_lines.append(new_line) # Remove the ridge lines with gap_number too high # XXX Modifying a list while iterating over it. # Should be safe, since we iterate backwards, but # still tacky. for ind in xrange(len(ridge_lines) - 1, -1, -1): line = ridge_lines[ind] if line[2] > gap_thresh: final_lines.append(line) del ridge_lines[ind] out_lines = [] for line in (final_lines + ridge_lines): sortargs = np.array(np.argsort(line[0])) rows, cols = np.zeros_like(sortargs), np.zeros_like(sortargs) rows[sortargs] = line[0] cols[sortargs] = line[1] out_lines.append([rows, cols]) return out_lines
[ "def", "_identify_ridge_lines", "(", "matr", ",", "max_distances", ",", "gap_thresh", ")", ":", "if", "(", "len", "(", "max_distances", ")", "<", "matr", ".", "shape", "[", "0", "]", ")", ":", "raise", "ValueError", "(", "'Max_distances must have at least as m...
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/scipy/signal/_peak_finding.py#L236-L353
tensorflow/tensorboard
61d11d99ef034c30ba20b6a7840c8eededb9031c
tensorboard/uploader/upload_tracker.py
python
UploadTracker._single_line_message
(self, message)
Write a timestamped single line, with newline, to stdout.
Write a timestamped single line, with newline, to stdout.
[ "Write", "a", "timestamped", "single", "line", "with", "newline", "to", "stdout", "." ]
def _single_line_message(self, message): """Write a timestamped single line, with newline, to stdout.""" if not self._verbosity: return start_message = "%s[%s]%s %s\n" % ( _STYLE_BOLD, readable_time_string(), _STYLE_RESET, message, ) sys.stdout.write(start_message) sys.stdout.flush()
[ "def", "_single_line_message", "(", "self", ",", "message", ")", ":", "if", "not", "self", ".", "_verbosity", ":", "return", "start_message", "=", "\"%s[%s]%s %s\\n\"", "%", "(", "_STYLE_BOLD", ",", "readable_time_string", "(", ")", ",", "_STYLE_RESET", ",", "...
https://github.com/tensorflow/tensorboard/blob/61d11d99ef034c30ba20b6a7840c8eededb9031c/tensorboard/uploader/upload_tracker.py#L288-L299
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/mystrom/binary_sensor.py
python
MyStromView._handle
(self, hass, data)
Handle requests to the myStrom endpoint.
Handle requests to the myStrom endpoint.
[ "Handle", "requests", "to", "the", "myStrom", "endpoint", "." ]
async def _handle(self, hass, data): """Handle requests to the myStrom endpoint.""" button_action = next( (parameter for parameter in data if parameter in self.supported_actions), None, ) if button_action is None: _LOGGER.error("Received unidentified message from myStrom button: %s", data) return ( f"Received unidentified message: {data}", HTTPStatus.UNPROCESSABLE_ENTITY, ) button_id = data[button_action] entity_id = f"{DOMAIN}.{button_id}_{button_action}" if entity_id not in self.buttons: _LOGGER.info( "New myStrom button/action detected: %s/%s", button_id, button_action ) self.buttons[entity_id] = MyStromBinarySensor( f"{button_id}_{button_action}" ) self.add_entities([self.buttons[entity_id]]) else: new_state = self.buttons[entity_id].state == "off" self.buttons[entity_id].async_on_update(new_state)
[ "async", "def", "_handle", "(", "self", ",", "hass", ",", "data", ")", ":", "button_action", "=", "next", "(", "(", "parameter", "for", "parameter", "in", "data", "if", "parameter", "in", "self", ".", "supported_actions", ")", ",", "None", ",", ")", "i...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/mystrom/binary_sensor.py#L43-L69
pysathq/pysat
07bf3a5a4428d40eca804e7ebdf4f496aadf4213
pysat/solvers.py
python
MinisatGH.propagate
(self, assumptions=[], phase_saving=0)
Propagate a given set of assumption literals.
Propagate a given set of assumption literals.
[ "Propagate", "a", "given", "set", "of", "assumption", "literals", "." ]
def propagate(self, assumptions=[], phase_saving=0): """ Propagate a given set of assumption literals. """ if self.minisat: if self.use_timer: start_time = process_time() st, props = pysolvers.minisatgh_propagate(self.minisat, assumptions, phase_saving, int(MainThread.check())) if self.use_timer: self.call_time = process_time() - start_time self.accu_time += self.call_time return bool(st), props if props != None else []
[ "def", "propagate", "(", "self", ",", "assumptions", "=", "[", "]", ",", "phase_saving", "=", "0", ")", ":", "if", "self", ".", "minisat", ":", "if", "self", ".", "use_timer", ":", "start_time", "=", "process_time", "(", ")", "st", ",", "props", "=",...
https://github.com/pysathq/pysat/blob/07bf3a5a4428d40eca804e7ebdf4f496aadf4213/pysat/solvers.py#L4915-L4931
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/macpath.py
python
lexists
(path)
return True
Test whether a path exists. Returns True for broken symbolic links
Test whether a path exists. Returns True for broken symbolic links
[ "Test", "whether", "a", "path", "exists", ".", "Returns", "True", "for", "broken", "symbolic", "links" ]
def lexists(path): """Test whether a path exists. Returns True for broken symbolic links""" try: st = os.lstat(path) except os.error: return False return True
[ "def", "lexists", "(", "path", ")", ":", "try", ":", "st", "=", "os", ".", "lstat", "(", "path", ")", "except", "os", ".", "error", ":", "return", "False", "return", "True" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/macpath.py#L111-L118
maihde/quant
593d23760833233874032b557c2e4ea1b5333092
simulation.py
python
simulate
(strategy_name, portfolio, start_date, end_date, output="~/.quant/simulation.h5", strategy_params="{}")
A simple simulator that simulates a strategy that only makes decisions at closing. Only BUY and SELL orders are supported. Orders are only good for the next day. A price type of MARKET is executed at the open price the next day. A price type of MARKET_ON_CLOSE is executed at the close price the next day. A price type of LIMIT will be executed at the LIMIT price the next day if LIMIT is between the low and high prices of the day. A price type of STOP will be executed at the STOP price the next day if STOP is between the low and high prices of the day. A price type of STOP_LIMIT will be executed at the LIMIT price the next day if STOP is between the low and high prices of the day.
A simple simulator that simulates a strategy that only makes decisions at closing. Only BUY and SELL orders are supported. Orders are only good for the next day.
[ "A", "simple", "simulator", "that", "simulates", "a", "strategy", "that", "only", "makes", "decisions", "at", "closing", ".", "Only", "BUY", "and", "SELL", "orders", "are", "supported", ".", "Orders", "are", "only", "good", "for", "the", "next", "day", "."...
def simulate(strategy_name, portfolio, start_date, end_date, output="~/.quant/simulation.h5", strategy_params="{}"): """A simple simulator that simulates a strategy that only makes decisions at closing. Only BUY and SELL orders are supported. Orders are only good for the next day. A price type of MARKET is executed at the open price the next day. A price type of MARKET_ON_CLOSE is executed at the close price the next day. A price type of LIMIT will be executed at the LIMIT price the next day if LIMIT is between the low and high prices of the day. A price type of STOP will be executed at the STOP price the next day if STOP is between the low and high prices of the day. A price type of STOP_LIMIT will be executed at the LIMIT price the next day if STOP is between the low and high prices of the day. """ outputFile = openOutputFile(output) # Get some of the tables from the output file order_tbl = outputFile.getNode("/Orders") postion_tbl = outputFile.getNode("/Position") performance_tbl = outputFile.getNode("/Performance") start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d") end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d") # Start the simulation at closing of the previous trading day now = getPrevTradingDay(start_date) try: position = initialize_position(portfolio, now) # Pre-cache some info to make the simulation faster ticker = MARKET["^DJI"].updateHistory(start_date, end_date) for symbol in position.keys(): if symbol != '$': MARKET[symbol].updateHistory(start=start_date, end=end_date) days = (end_date - start_date).days # Initialize the strategy params = yaml.load(strategy_params) strategy_clazz = load_strategy(strategy_name) strategy = strategy_clazz(start_date, end_date, position, MARKET, params, outputFile) p = ProgressBar(maxValue=days, totalWidth=80) print "Starting Simulation" while now <= end_date: # Write the initial position to the database write_position(postion_tbl, position, now) write_performance(performance_tbl, position, now) # Remember 'now' is after closing, so the strategy # can use any information from 'now' or earlier orders = strategy.evaluate(now, position, MARKET) # Go to the next day to evalute the orders now += ONE_DAY while not isTradingDay(now): now += ONE_DAY p.performWork(1) continue # Execute orders execute_orders(order_tbl, position, now, orders) # Flush the data to disk outputFile.flush() p.performWork(1) print p, '\r', p.updateAmount(p.max) print p, '\r', print '\n' # End the progress bar here before calling finalize orders = strategy.finalize() finally: outputFile.close()
[ "def", "simulate", "(", "strategy_name", ",", "portfolio", ",", "start_date", ",", "end_date", ",", "output", "=", "\"~/.quant/simulation.h5\"", ",", "strategy_params", "=", "\"{}\"", ")", ":", "outputFile", "=", "openOutputFile", "(", "output", ")", "# Get some o...
https://github.com/maihde/quant/blob/593d23760833233874032b557c2e4ea1b5333092/simulation.py#L215-L293
rlabbe/filterpy
a437893597957764fb6b415bfb5640bb117f5b99
filterpy/kalman/sigma_points.py
python
MerweScaledSigmaPoints._compute_weights
(self)
Computes the weights for the scaled unscented Kalman filter.
Computes the weights for the scaled unscented Kalman filter.
[ "Computes", "the", "weights", "for", "the", "scaled", "unscented", "Kalman", "filter", "." ]
def _compute_weights(self): """ Computes the weights for the scaled unscented Kalman filter. """ n = self.n lambda_ = self.alpha**2 * (n +self.kappa) - n c = .5 / (n + lambda_) self.Wc = np.full(2*n + 1, c) self.Wm = np.full(2*n + 1, c) self.Wc[0] = lambda_ / (n + lambda_) + (1 - self.alpha**2 + self.beta) self.Wm[0] = lambda_ / (n + lambda_)
[ "def", "_compute_weights", "(", "self", ")", ":", "n", "=", "self", ".", "n", "lambda_", "=", "self", ".", "alpha", "**", "2", "*", "(", "n", "+", "self", ".", "kappa", ")", "-", "n", "c", "=", ".5", "/", "(", "n", "+", "lambda_", ")", "self"...
https://github.com/rlabbe/filterpy/blob/a437893597957764fb6b415bfb5640bb117f5b99/filterpy/kalman/sigma_points.py#L180-L192
ales-tsurko/cells
4cf7e395cd433762bea70cdc863a346f3a6fe1d0
packaging/macos/python/lib/python3.7/json/__init__.py
python
load
(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
return loads(fp.read(), cls=cls, object_hook=object_hook, parse_float=parse_float, parse_int=parse_int, parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
Deserialize ``fp`` (a ``.read()``-supporting file-like object containing a JSON document) to a Python object. ``object_hook`` is an optional function that will be called with the result of any object literal decode (a ``dict``). The return value of ``object_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting). ``object_pairs_hook`` is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of ``object_pairs_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders. If ``object_hook`` is also defined, the ``object_pairs_hook`` takes priority. To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg; otherwise ``JSONDecoder`` is used.
Deserialize ``fp`` (a ``.read()``-supporting file-like object containing a JSON document) to a Python object.
[ "Deserialize", "fp", "(", "a", ".", "read", "()", "-", "supporting", "file", "-", "like", "object", "containing", "a", "JSON", "document", ")", "to", "a", "Python", "object", "." ]
def load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw): """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing a JSON document) to a Python object. ``object_hook`` is an optional function that will be called with the result of any object literal decode (a ``dict``). The return value of ``object_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting). ``object_pairs_hook`` is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of ``object_pairs_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders. If ``object_hook`` is also defined, the ``object_pairs_hook`` takes priority. To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg; otherwise ``JSONDecoder`` is used. """ return loads(fp.read(), cls=cls, object_hook=object_hook, parse_float=parse_float, parse_int=parse_int, parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
[ "def", "load", "(", "fp", ",", "*", ",", "cls", "=", "None", ",", "object_hook", "=", "None", ",", "parse_float", "=", "None", ",", "parse_int", "=", "None", ",", "parse_constant", "=", "None", ",", "object_pairs_hook", "=", "None", ",", "*", "*", "k...
https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/json/__init__.py#L274-L296
Qiskit/qiskit-terra
b66030e3b9192efdd3eb95cf25c6545fe0a13da4
qiskit/algorithms/optimizers/spsa.py
python
SPSA.estimate_stddev
( loss: Callable[[np.ndarray], float], initial_point: np.ndarray, avg: int = 25, max_evals_grouped: int = 1, )
return np.std(losses)
Estimate the standard deviation of the loss function.
Estimate the standard deviation of the loss function.
[ "Estimate", "the", "standard", "deviation", "of", "the", "loss", "function", "." ]
def estimate_stddev( loss: Callable[[np.ndarray], float], initial_point: np.ndarray, avg: int = 25, max_evals_grouped: int = 1, ) -> float: """Estimate the standard deviation of the loss function.""" losses = _batch_evaluate(loss, avg * [initial_point], max_evals_grouped) return np.std(losses)
[ "def", "estimate_stddev", "(", "loss", ":", "Callable", "[", "[", "np", ".", "ndarray", "]", ",", "float", "]", ",", "initial_point", ":", "np", ".", "ndarray", ",", "avg", ":", "int", "=", "25", ",", "max_evals_grouped", ":", "int", "=", "1", ",", ...
https://github.com/Qiskit/qiskit-terra/blob/b66030e3b9192efdd3eb95cf25c6545fe0a13da4/qiskit/algorithms/optimizers/spsa.py#L370-L378
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/bin/x86/Debug/Lib/lib2to3/fixer_util.py
python
ArgList
(args, lparen=LParen(), rparen=RParen())
return node
A parenthesised argument list, used by Call()
A parenthesised argument list, used by Call()
[ "A", "parenthesised", "argument", "list", "used", "by", "Call", "()" ]
def ArgList(args, lparen=LParen(), rparen=RParen()): """A parenthesised argument list, used by Call()""" node = Node(syms.trailer, [lparen.clone(), rparen.clone()]) if args: node.insert_child(1, Node(syms.arglist, args)) return node
[ "def", "ArgList", "(", "args", ",", "lparen", "=", "LParen", "(", ")", ",", "rparen", "=", "RParen", "(", ")", ")", ":", "node", "=", "Node", "(", "syms", ".", "trailer", ",", "[", "lparen", ".", "clone", "(", ")", ",", "rparen", ".", "clone", ...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/bin/x86/Debug/Lib/lib2to3/fixer_util.py#L54-L59
joerick/pyinstrument
d3c45164a385021f366c1081baec18a1a226a573
examples/django_example/django_example/views.py
python
hello_world
(request)
return HttpResponse("Hello, world!")
[]
def hello_world(request): # do some useless work to delay this call a bit y = 1 for x in range(1, 10000): y *= x time.sleep(0.1) return HttpResponse("Hello, world!")
[ "def", "hello_world", "(", "request", ")", ":", "# do some useless work to delay this call a bit", "y", "=", "1", "for", "x", "in", "range", "(", "1", ",", "10000", ")", ":", "y", "*=", "x", "time", ".", "sleep", "(", "0.1", ")", "return", "HttpResponse", ...
https://github.com/joerick/pyinstrument/blob/d3c45164a385021f366c1081baec18a1a226a573/examples/django_example/django_example/views.py#L6-L13
facebookresearch/VMZ
4cc542d58c1c560571e1e962426e858e00de28d2
c2/lib/utils/model_helper.py
python
GetModelWeights
(model, gpu_id=0)
return weight_dict
function that returns all the model weights in a dict
function that returns all the model weights in a dict
[ "function", "that", "returns", "all", "the", "model", "weights", "in", "a", "dict" ]
def GetModelWeights(model, gpu_id=0): ''' function that returns all the model weights in a dict ''' model_ops = model.net.Proto().op master_gpu = 'gpu_{}'.format(gpu_id) param_ops = [] for idx in range(len(model_ops)): op_type = model.net.Proto().op[idx].type op_input = model.net.Proto().op[idx].input[0] if op_type in ['Conv', 'FC'] and op_input.find(master_gpu) >= 0: param_ops.append(model.net.Proto().op[idx]) weight_dict = {} for idx in range(len(param_ops)): # op_type = op.type op_inputs = param_ops[idx].input # op_output = param_ops[idx].output[0] for op_input in op_inputs: param_blob = op_input weights = np.array(workspace.FetchBlob(str(param_blob))) weight_dict[param_blob] = weights return weight_dict
[ "def", "GetModelWeights", "(", "model", ",", "gpu_id", "=", "0", ")", ":", "model_ops", "=", "model", ".", "net", ".", "Proto", "(", ")", ".", "op", "master_gpu", "=", "'gpu_{}'", ".", "format", "(", "gpu_id", ")", "param_ops", "=", "[", "]", "for", ...
https://github.com/facebookresearch/VMZ/blob/4cc542d58c1c560571e1e962426e858e00de28d2/c2/lib/utils/model_helper.py#L212-L234
fooying/3102
0faee38c30b2e24154f41e68457cfd8f7a61c040
thirdparty/dns/message.py
python
Message.__ne__
(self, other)
return not self.__eq__(other)
Are two messages not equal? @rtype: bool
Are two messages not equal?
[ "Are", "two", "messages", "not", "equal?" ]
def __ne__(self, other): """Are two messages not equal? @rtype: bool""" return not self.__eq__(other)
[ "def", "__ne__", "(", "self", ",", "other", ")", ":", "return", "not", "self", ".", "__eq__", "(", "other", ")" ]
https://github.com/fooying/3102/blob/0faee38c30b2e24154f41e68457cfd8f7a61c040/thirdparty/dns/message.py#L262-L265
llSourcell/AI_Artist
3038c06c2e389b9c919c881c9a169efe2fd7810e
lib/python2.7/site-packages/pip/vcs/__init__.py
python
VersionControl.check_destination
(self, dest, url, rev_options, rev_display)
return checkout
Prepare a location to receive a checkout/clone. Return True if the location is ready for (and requires) a checkout/clone, False otherwise.
Prepare a location to receive a checkout/clone.
[ "Prepare", "a", "location", "to", "receive", "a", "checkout", "/", "clone", "." ]
def check_destination(self, dest, url, rev_options, rev_display): """ Prepare a location to receive a checkout/clone. Return True if the location is ready for (and requires) a checkout/clone, False otherwise. """ checkout = True prompt = False if os.path.exists(dest): checkout = False if os.path.exists(os.path.join(dest, self.dirname)): existing_url = self.get_url(dest) if self.compare_urls(existing_url, url): logger.debug( '%s in %s exists, and has correct URL (%s)', self.repo_name.title(), display_path(dest), url, ) if not self.check_version(dest, rev_options): logger.info( 'Updating %s %s%s', display_path(dest), self.repo_name, rev_display, ) self.update(dest, rev_options) else: logger.info( 'Skipping because already up-to-date.') else: logger.warning( '%s %s in %s exists with URL %s', self.name, self.repo_name, display_path(dest), existing_url, ) prompt = ('(s)witch, (i)gnore, (w)ipe, (b)ackup ', ('s', 'i', 'w', 'b')) else: logger.warning( 'Directory %s already exists, and is not a %s %s.', dest, self.name, self.repo_name, ) prompt = ('(i)gnore, (w)ipe, (b)ackup ', ('i', 'w', 'b')) if prompt: logger.warning( 'The plan is to install the %s repository %s', self.name, url, ) response = ask_path_exists('What to do? %s' % prompt[0], prompt[1]) if response == 's': logger.info( 'Switching %s %s to %s%s', self.repo_name, display_path(dest), url, rev_display, ) self.switch(dest, url, rev_options) elif response == 'i': # do nothing pass elif response == 'w': logger.warning('Deleting %s', display_path(dest)) rmtree(dest) checkout = True elif response == 'b': dest_dir = backup_dir(dest) logger.warning( 'Backing up %s to %s', display_path(dest), dest_dir, ) shutil.move(dest, dest_dir) checkout = True return checkout
[ "def", "check_destination", "(", "self", ",", "dest", ",", "url", ",", "rev_options", ",", "rev_display", ")", ":", "checkout", "=", "True", "prompt", "=", "False", "if", "os", ".", "path", ".", "exists", "(", "dest", ")", ":", "checkout", "=", "False"...
https://github.com/llSourcell/AI_Artist/blob/3038c06c2e389b9c919c881c9a169efe2fd7810e/lib/python2.7/site-packages/pip/vcs/__init__.py#L193-L274
NVIDIA/DeepLearningExamples
589604d49e016cd9ef4525f7abcc9c7b826cfc5e
TensorFlow/Translation/GNMT/attention_wrapper.py
python
AttentionWrapper.call
(self, inputs, state)
Perform a step of attention-wrapped RNN. - Step 1: Mix the `inputs` and previous step's `attention` output via `cell_input_fn`. - Step 2: Call the wrapped `cell` with this input and its previous state. - Step 3: Score the cell's output with `attention_mechanism`. - Step 4: Calculate the alignments by passing the score through the `normalizer`. - Step 5: Calculate the context vector as the inner product between the alignments and the attention_mechanism's values (memory). - Step 6: Calculate the attention output by concatenating the cell output and context through the attention layer (a linear layer with `attention_layer_size` outputs). Args: inputs: (Possibly nested tuple of) Tensor, the input at this time step. state: An instance of `AttentionWrapperState` containing tensors from the previous time step. Returns: A tuple `(attention_or_cell_output, next_state)`, where: - `attention_or_cell_output` depending on `output_attention`. - `next_state` is an instance of `AttentionWrapperState` containing the state calculated at this time step. Raises: TypeError: If `state` is not an instance of `AttentionWrapperState`.
Perform a step of attention-wrapped RNN.
[ "Perform", "a", "step", "of", "attention", "-", "wrapped", "RNN", "." ]
def call(self, inputs, state): """Perform a step of attention-wrapped RNN. - Step 1: Mix the `inputs` and previous step's `attention` output via `cell_input_fn`. - Step 2: Call the wrapped `cell` with this input and its previous state. - Step 3: Score the cell's output with `attention_mechanism`. - Step 4: Calculate the alignments by passing the score through the `normalizer`. - Step 5: Calculate the context vector as the inner product between the alignments and the attention_mechanism's values (memory). - Step 6: Calculate the attention output by concatenating the cell output and context through the attention layer (a linear layer with `attention_layer_size` outputs). Args: inputs: (Possibly nested tuple of) Tensor, the input at this time step. state: An instance of `AttentionWrapperState` containing tensors from the previous time step. Returns: A tuple `(attention_or_cell_output, next_state)`, where: - `attention_or_cell_output` depending on `output_attention`. - `next_state` is an instance of `AttentionWrapperState` containing the state calculated at this time step. Raises: TypeError: If `state` is not an instance of `AttentionWrapperState`. """ if not isinstance(state, AttentionWrapperState): raise TypeError("Expected state to be instance of AttentionWrapperState. " "Received type %s instead." % type(state)) # Step 1: Calculate the true inputs to the cell based on the # previous attention value. cell_inputs = self._cell_input_fn(inputs, state.attention) cell_state = state.cell_state cell_output, next_cell_state = self._cell(cell_inputs, cell_state) cell_batch_size = ( cell_output.shape[0].value or tf.shape(cell_output)[0]) error_message = ( "When applying AttentionWrapper %s: " % self.name + "Non-matching batch sizes between the memory " "(encoder output) and the query (decoder output). Are you using " "the BeamSearchDecoder? You may need to tile your memory input via " "the tf.contrib.seq2seq.tile_batch function with argument " "multiple=beam_width.") with tf.control_dependencies( self._batch_size_checks(cell_batch_size, error_message)): cell_output = tf.identity( cell_output, name="checked_cell_output") if self._is_multi: previous_attention_state = state.attention_state previous_alignment_history = state.alignment_history else: previous_attention_state = [state.attention_state] previous_alignment_history = [state.alignment_history] all_alignments = [] all_attentions = [] all_attention_states = [] maybe_all_histories = [] for i, attention_mechanism in enumerate(self._attention_mechanisms): attention, alignments, next_attention_state = _compute_attention( attention_mechanism, cell_output, previous_attention_state[i], self._attention_layers[i] if self._attention_layers else None) alignment_history = previous_alignment_history[i].write( state.time, alignments) if self._alignment_history else () all_attention_states.append(next_attention_state) all_alignments.append(alignments) all_attentions.append(attention) maybe_all_histories.append(alignment_history) attention = tf.concat(all_attentions, 1) next_state = AttentionWrapperState( time=state.time + 1, cell_state=next_cell_state, attention=attention, attention_state=self._item_or_tuple(all_attention_states), alignments=self._item_or_tuple(all_alignments), alignment_history=self._item_or_tuple(maybe_all_histories)) if self._output_attention: return attention, next_state else: return cell_output, next_state
[ "def", "call", "(", "self", ",", "inputs", ",", "state", ")", ":", "if", "not", "isinstance", "(", "state", ",", "AttentionWrapperState", ")", ":", "raise", "TypeError", "(", "\"Expected state to be instance of AttentionWrapperState. \"", "\"Received type %s instead.\""...
https://github.com/NVIDIA/DeepLearningExamples/blob/589604d49e016cd9ef4525f7abcc9c7b826cfc5e/TensorFlow/Translation/GNMT/attention_wrapper.py#L869-L958
pabigot/pyxb
14737c23a125fd12c954823ad64fc4497816fae3
pyxb/utils/domutils.py
python
BindingDOMSupport.addXMLNSDeclaration
(self, element, namespace, prefix=None)
return prefix
Manually add an XMLNS declaration to the document element. @param namespace: a L{pyxb.namespace.Namespace} instance @param prefix: the prefix by which the namespace is known. If C{None}, the default prefix as previously declared will be used; if C{''} (empty string) a declaration for C{namespace} as the default namespace will be generated. @return: C{prefix} as used in the added declaration.
Manually add an XMLNS declaration to the document element.
[ "Manually", "add", "an", "XMLNS", "declaration", "to", "the", "document", "element", "." ]
def addXMLNSDeclaration (self, element, namespace, prefix=None): """Manually add an XMLNS declaration to the document element. @param namespace: a L{pyxb.namespace.Namespace} instance @param prefix: the prefix by which the namespace is known. If C{None}, the default prefix as previously declared will be used; if C{''} (empty string) a declaration for C{namespace} as the default namespace will be generated. @return: C{prefix} as used in the added declaration. """ if not isinstance(namespace, pyxb.namespace.Namespace): raise pyxb.UsageError('addXMLNSdeclaration: must be given a namespace instance') if namespace.isAbsentNamespace(): raise pyxb.UsageError('addXMLNSdeclaration: namespace must not be an absent namespace') if prefix is None: prefix = self.namespacePrefix(namespace) if not prefix: # None or empty string an = 'xmlns' else: an = 'xmlns:' + prefix element.setAttributeNS(pyxb.namespace.XMLNamespaces.uri(), an, namespace.uri()) return prefix
[ "def", "addXMLNSDeclaration", "(", "self", ",", "element", ",", "namespace", ",", "prefix", "=", "None", ")", ":", "if", "not", "isinstance", "(", "namespace", ",", "pyxb", ".", "namespace", ".", "Namespace", ")", ":", "raise", "pyxb", ".", "UsageError", ...
https://github.com/pabigot/pyxb/blob/14737c23a125fd12c954823ad64fc4497816fae3/pyxb/utils/domutils.py#L425-L448
Tencent/GAutomator
0ac9f849d1ca2c59760a91c5c94d3db375a380cd
GAutomatorIos/ga2/device/iOS/wda/__init__.py
python
Selector.click_exists
(self, timeout=0)
return True
Wait element and perform click Args: timeout (float): timeout for wait Returns: bool: if successfully clicked
Wait element and perform click
[ "Wait", "element", "and", "perform", "click" ]
def click_exists(self, timeout=0): """ Wait element and perform click Args: timeout (float): timeout for wait Returns: bool: if successfully clicked """ e = self.get(timeout=timeout, raise_error=False) if e is None: return False e.click() return True
[ "def", "click_exists", "(", "self", ",", "timeout", "=", "0", ")", ":", "e", "=", "self", ".", "get", "(", "timeout", "=", "timeout", ",", "raise_error", "=", "False", ")", "if", "e", "is", "None", ":", "return", "False", "e", ".", "click", "(", ...
https://github.com/Tencent/GAutomator/blob/0ac9f849d1ca2c59760a91c5c94d3db375a380cd/GAutomatorIos/ga2/device/iOS/wda/__init__.py#L868-L882
pallets/jinja
077b7918a7642ff6742fe48a32e54d7875140894
src/jinja2/sandbox.py
python
is_internal_attribute
(obj: t.Any, attr: str)
return attr.startswith("__")
Test if the attribute given is an internal python attribute. For example this function returns `True` for the `func_code` attribute of python objects. This is useful if the environment method :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden. >>> from jinja2.sandbox import is_internal_attribute >>> is_internal_attribute(str, "mro") True >>> is_internal_attribute(str, "upper") False
Test if the attribute given is an internal python attribute. For example this function returns `True` for the `func_code` attribute of python objects. This is useful if the environment method :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.
[ "Test", "if", "the", "attribute", "given", "is", "an", "internal", "python", "attribute", ".", "For", "example", "this", "function", "returns", "True", "for", "the", "func_code", "attribute", "of", "python", "objects", ".", "This", "is", "useful", "if", "the...
def is_internal_attribute(obj: t.Any, attr: str) -> bool: """Test if the attribute given is an internal python attribute. For example this function returns `True` for the `func_code` attribute of python objects. This is useful if the environment method :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden. >>> from jinja2.sandbox import is_internal_attribute >>> is_internal_attribute(str, "mro") True >>> is_internal_attribute(str, "upper") False """ if isinstance(obj, types.FunctionType): if attr in UNSAFE_FUNCTION_ATTRIBUTES: return True elif isinstance(obj, types.MethodType): if attr in UNSAFE_FUNCTION_ATTRIBUTES or attr in UNSAFE_METHOD_ATTRIBUTES: return True elif isinstance(obj, type): if attr == "mro": return True elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)): return True elif isinstance(obj, types.GeneratorType): if attr in UNSAFE_GENERATOR_ATTRIBUTES: return True elif hasattr(types, "CoroutineType") and isinstance(obj, types.CoroutineType): if attr in UNSAFE_COROUTINE_ATTRIBUTES: return True elif hasattr(types, "AsyncGeneratorType") and isinstance( obj, types.AsyncGeneratorType ): if attr in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES: return True return attr.startswith("__")
[ "def", "is_internal_attribute", "(", "obj", ":", "t", ".", "Any", ",", "attr", ":", "str", ")", "->", "bool", ":", "if", "isinstance", "(", "obj", ",", "types", ".", "FunctionType", ")", ":", "if", "attr", "in", "UNSAFE_FUNCTION_ATTRIBUTES", ":", "return...
https://github.com/pallets/jinja/blob/077b7918a7642ff6742fe48a32e54d7875140894/src/jinja2/sandbox.py#L125-L159
pabigot/pyxb
14737c23a125fd12c954823ad64fc4497816fae3
pyxb/binding/content.py
python
ElementDeclaration.__init__
(self, name, id, key, is_plural, location, element_binding=None)
Create an ElementDeclaration instance. @param name: The name by which the element is referenced in the XML @type name: L{pyxb.namespace.ExpandedName} @param id: The Python name for the element within the containing L{pyxb.basis.binding.complexTypeDefinition}. This is a public identifier, albeit modified to be unique, and is usually used as the name of the element's inspector method or property. @type id: C{str} @param key: The string used to store the element value in the dictionary of the containing L{pyxb.basis.binding.complexTypeDefinition}. This is mangled so that it is unique among and is treated as a Python private member. @type key: C{str} @param is_plural: If C{True}, documents for the corresponding type may have multiple instances of this element. As a consequence, the value of the element will be a list. If C{False}, the value will be C{None} if the element is absent, and a reference to an instance of the type identified by L{pyxb.binding.basis.element.typeDefinition} if present. @type is_plural: C{bool} @param element_binding: Reference to the class that serves as the binding for the element.
Create an ElementDeclaration instance.
[ "Create", "an", "ElementDeclaration", "instance", "." ]
def __init__ (self, name, id, key, is_plural, location, element_binding=None): """Create an ElementDeclaration instance. @param name: The name by which the element is referenced in the XML @type name: L{pyxb.namespace.ExpandedName} @param id: The Python name for the element within the containing L{pyxb.basis.binding.complexTypeDefinition}. This is a public identifier, albeit modified to be unique, and is usually used as the name of the element's inspector method or property. @type id: C{str} @param key: The string used to store the element value in the dictionary of the containing L{pyxb.basis.binding.complexTypeDefinition}. This is mangled so that it is unique among and is treated as a Python private member. @type key: C{str} @param is_plural: If C{True}, documents for the corresponding type may have multiple instances of this element. As a consequence, the value of the element will be a list. If C{False}, the value will be C{None} if the element is absent, and a reference to an instance of the type identified by L{pyxb.binding.basis.element.typeDefinition} if present. @type is_plural: C{bool} @param element_binding: Reference to the class that serves as the binding for the element. """ self.__name = name self.__id = id self.__key = key self.__isPlural = is_plural self.__elementBinding = element_binding super(ElementDeclaration, self).__init__()
[ "def", "__init__", "(", "self", ",", "name", ",", "id", ",", "key", ",", "is_plural", ",", "location", ",", "element_binding", "=", "None", ")", ":", "self", ".", "__name", "=", "name", "self", ".", "__id", "=", "id", "self", ".", "__key", "=", "ke...
https://github.com/pabigot/pyxb/blob/14737c23a125fd12c954823ad64fc4497816fae3/pyxb/binding/content.py#L963-L996
openstack/manila
142990edc027e14839d5deaf4954dd6fc88de15e
manila/api/views/share_groups.py
python
ShareGroupViewBuilder.detail_list
(self, request, share_groups)
return self._list_view(self.detail, request, share_groups)
Detailed view of a list of share groups.
Detailed view of a list of share groups.
[ "Detailed", "view", "of", "a", "list", "of", "share", "groups", "." ]
def detail_list(self, request, share_groups): """Detailed view of a list of share groups.""" return self._list_view(self.detail, request, share_groups)
[ "def", "detail_list", "(", "self", ",", "request", ",", "share_groups", ")", ":", "return", "self", ".", "_list_view", "(", "self", ".", "detail", ",", "request", ",", "share_groups", ")" ]
https://github.com/openstack/manila/blob/142990edc027e14839d5deaf4954dd6fc88de15e/manila/api/views/share_groups.py#L31-L33
CLUEbenchmark/CLUEPretrainedModels
b384fd41665a8261f9c689c940cf750b3bc21fce
baselines/models/bert/tokenization.py
python
BasicTokenizer._run_split_on_punc
(self, text)
return ["".join(x) for x in output]
Splits punctuation on a piece of text.
Splits punctuation on a piece of text.
[ "Splits", "punctuation", "on", "a", "piece", "of", "text", "." ]
def _run_split_on_punc(self, text): """Splits punctuation on a piece of text.""" chars = list(text) i = 0 start_new_word = True output = [] while i < len(chars): char = chars[i] if _is_punctuation(char): output.append([char]) start_new_word = True else: if start_new_word: output.append([]) start_new_word = False output[-1].append(char) i += 1 return ["".join(x) for x in output]
[ "def", "_run_split_on_punc", "(", "self", ",", "text", ")", ":", "chars", "=", "list", "(", "text", ")", "i", "=", "0", "start_new_word", "=", "True", "output", "=", "[", "]", "while", "i", "<", "len", "(", "chars", ")", ":", "char", "=", "chars", ...
https://github.com/CLUEbenchmark/CLUEPretrainedModels/blob/b384fd41665a8261f9c689c940cf750b3bc21fce/baselines/models/bert/tokenization.py#L231-L249
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-linux/x64/mako/pyparser.py
python
parse
(code, mode="exec", **exception_kwargs)
Parse an expression into AST
Parse an expression into AST
[ "Parse", "an", "expression", "into", "AST" ]
def parse(code, mode="exec", **exception_kwargs): """Parse an expression into AST""" try: return _ast_util.parse(code, "<unknown>", mode) except Exception: raise exceptions.SyntaxException( "(%s) %s (%r)" % ( compat.exception_as().__class__.__name__, compat.exception_as(), code[0:50], ), **exception_kwargs )
[ "def", "parse", "(", "code", ",", "mode", "=", "\"exec\"", ",", "*", "*", "exception_kwargs", ")", ":", "try", ":", "return", "_ast_util", ".", "parse", "(", "code", ",", "\"<unknown>\"", ",", "mode", ")", "except", "Exception", ":", "raise", "exceptions...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-linux/x64/mako/pyparser.py#L41-L55
django-nonrel/django-nonrel
4fbfe7344481a5eab8698f79207f09124310131b
django/contrib/gis/gdal/driver.py
python
Driver.driver_count
(self)
return capi.get_driver_count()
Returns the number of OGR data source drivers registered.
Returns the number of OGR data source drivers registered.
[ "Returns", "the", "number", "of", "OGR", "data", "source", "drivers", "registered", "." ]
def driver_count(self): "Returns the number of OGR data source drivers registered." return capi.get_driver_count()
[ "def", "driver_count", "(", "self", ")", ":", "return", "capi", ".", "get_driver_count", "(", ")" ]
https://github.com/django-nonrel/django-nonrel/blob/4fbfe7344481a5eab8698f79207f09124310131b/django/contrib/gis/gdal/driver.py#L63-L65
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/multiprocessing/dummy/__init__.py
python
active_children
()
return list(children)
[]
def active_children(): children = current_process()._children for p in list(children): if not p.is_alive(): children.pop(p, None) return list(children)
[ "def", "active_children", "(", ")", ":", "children", "=", "current_process", "(", ")", ".", "_children", "for", "p", "in", "list", "(", "children", ")", ":", "if", "not", "p", ".", "is_alive", "(", ")", ":", "children", ".", "pop", "(", "p", ",", "...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/multiprocessing/dummy/__init__.py#L102-L107
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/polys/polyutils.py
python
_sort_gens
(gens, **args)
return tuple(gens)
Sort generators in a reasonably intelligent way.
Sort generators in a reasonably intelligent way.
[ "Sort", "generators", "in", "a", "reasonably", "intelligent", "way", "." ]
def _sort_gens(gens, **args): """Sort generators in a reasonably intelligent way. """ opt = build_options(args) gens_order, wrt = {}, None if opt is not None: gens_order, wrt = {}, opt.wrt for i, gen in enumerate(opt.sort): gens_order[gen] = i + 1 def order_key(gen): gen = str(gen) if wrt is not None: try: return (-len(wrt) + wrt.index(gen), gen, 0) except ValueError: pass name, index = _re_gen.match(gen).groups() if index: index = int(index) else: index = 0 try: return ( gens_order[name], name, index) except KeyError: pass try: return (_gens_order[name], name, index) except KeyError: pass return (_max_order, name, index) try: gens = sorted(gens, key=order_key) except TypeError: # pragma: no cover pass return tuple(gens)
[ "def", "_sort_gens", "(", "gens", ",", "*", "*", "args", ")", ":", "opt", "=", "build_options", "(", "args", ")", "gens_order", ",", "wrt", "=", "{", "}", ",", "None", "if", "opt", "is", "not", "None", ":", "gens_order", ",", "wrt", "=", "{", "}"...
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/polys/polyutils.py#L32-L77
machow/siuba
f5b36f840401225416f937900cb945923ced1629
siuba/dply/vector.py
python
desc
(x)
return x.sort_values(ascending = False).reset_index(drop = True)
Return array sorted in descending order.
Return array sorted in descending order.
[ "Return", "array", "sorted", "in", "descending", "order", "." ]
def desc(x): """Return array sorted in descending order.""" return x.sort_values(ascending = False).reset_index(drop = True)
[ "def", "desc", "(", "x", ")", ":", "return", "x", ".", "sort_values", "(", "ascending", "=", "False", ")", ".", "reset_index", "(", "drop", "=", "True", ")" ]
https://github.com/machow/siuba/blob/f5b36f840401225416f937900cb945923ced1629/siuba/dply/vector.py#L99-L101
respeaker/get_started_with_respeaker
ec859759fcec7e683a5e09328a8ea307046f353d
files/usr/lib/python2.7/site-packages/concurrent/futures/_base.py
python
Executor.map
(self, fn, *iterables, **kwargs)
Returns a iterator equivalent to map(fn, iter). Args: fn: A callable that will take as many arguments as there are passed iterables. timeout: The maximum number of seconds to wait. If None, then there is no limit on the wait time. Returns: An iterator equivalent to: map(func, *iterables) but the calls may be evaluated out-of-order. Raises: TimeoutError: If the entire result iterator could not be generated before the given timeout. Exception: If fn(*args) raises for any values.
Returns a iterator equivalent to map(fn, iter).
[ "Returns", "a", "iterator", "equivalent", "to", "map", "(", "fn", "iter", ")", "." ]
def map(self, fn, *iterables, **kwargs): """Returns a iterator equivalent to map(fn, iter). Args: fn: A callable that will take as many arguments as there are passed iterables. timeout: The maximum number of seconds to wait. If None, then there is no limit on the wait time. Returns: An iterator equivalent to: map(func, *iterables) but the calls may be evaluated out-of-order. Raises: TimeoutError: If the entire result iterator could not be generated before the given timeout. Exception: If fn(*args) raises for any values. """ timeout = kwargs.get('timeout') if timeout is not None: end_time = timeout + time.time() fs = [self.submit(fn, *args) for args in zip(*iterables)] try: for future in fs: if timeout is None: yield future.result() else: yield future.result(end_time - time.time()) finally: for future in fs: future.cancel()
[ "def", "map", "(", "self", ",", "fn", ",", "*", "iterables", ",", "*", "*", "kwargs", ")", ":", "timeout", "=", "kwargs", ".", "get", "(", "'timeout'", ")", "if", "timeout", "is", "not", "None", ":", "end_time", "=", "timeout", "+", "time", ".", ...
https://github.com/respeaker/get_started_with_respeaker/blob/ec859759fcec7e683a5e09328a8ea307046f353d/files/usr/lib/python2.7/site-packages/concurrent/futures/_base.py#L522-L554
pycontribs/pyrax
a0c022981f76a4cba96a22ecc19bb52843ac4fbe
pyrax/clouddns.py
python
CloudDNSManager._get_ptr_details
(self, device, device_type)
return (href, svc_name)
Takes a device and device type and returns the corresponding HREF link and service name for use with PTR record management.
Takes a device and device type and returns the corresponding HREF link and service name for use with PTR record management.
[ "Takes", "a", "device", "and", "device", "type", "and", "returns", "the", "corresponding", "HREF", "link", "and", "service", "name", "for", "use", "with", "PTR", "record", "management", "." ]
def _get_ptr_details(self, device, device_type): """ Takes a device and device type and returns the corresponding HREF link and service name for use with PTR record management. """ context = self.api.identity region = self.api.region_name if device_type.lower().startswith("load"): ep = pyrax._get_service_endpoint(context, "load_balancer", region) svc = "loadbalancers" svc_name = "cloudLoadBalancers" else: ep = pyrax._get_service_endpoint(context, "compute", region) svc = "servers" svc_name = "cloudServersOpenStack" href = "%s/%s/%s" % (ep, svc, utils.get_id(device)) return (href, svc_name)
[ "def", "_get_ptr_details", "(", "self", ",", "device", ",", "device_type", ")", ":", "context", "=", "self", ".", "api", ".", "identity", "region", "=", "self", ".", "api", ".", "region_name", "if", "device_type", ".", "lower", "(", ")", ".", "startswith...
https://github.com/pycontribs/pyrax/blob/a0c022981f76a4cba96a22ecc19bb52843ac4fbe/pyrax/clouddns.py#L906-L922
django-nonrel/djangotoolbox
7e2c47e2ab5ee98d0c0f47c5ccce08e75feda48a
djangotoolbox/db/basecompiler.py
python
NonrelQuery._normalize_lookup_value
(self, lookup_type, value, field, annotation)
return self.ops.value_for_db(value, field, lookup_type)
Undoes preparations done by `Field.get_db_prep_lookup` not suitable for nonrel back-ends and passes the lookup argument through nonrel's `value_for_db`. TODO: Blank `Field.get_db_prep_lookup` and remove this method.
Undoes preparations done by `Field.get_db_prep_lookup` not suitable for nonrel back-ends and passes the lookup argument through nonrel's `value_for_db`.
[ "Undoes", "preparations", "done", "by", "Field", ".", "get_db_prep_lookup", "not", "suitable", "for", "nonrel", "back", "-", "ends", "and", "passes", "the", "lookup", "argument", "through", "nonrel", "s", "value_for_db", "." ]
def _normalize_lookup_value(self, lookup_type, value, field, annotation): """ Undoes preparations done by `Field.get_db_prep_lookup` not suitable for nonrel back-ends and passes the lookup argument through nonrel's `value_for_db`. TODO: Blank `Field.get_db_prep_lookup` and remove this method. """ # Undo Field.get_db_prep_lookup putting most values in a list # (a subclass may override this, so check if it's a list) and # losing the (True / False) argument to the "isnull" lookup. if lookup_type not in ('in', 'range', 'year') and \ isinstance(value, (tuple, list)): if len(value) > 1: raise DatabaseError("Filter lookup type was %s; expected the " "filter argument not to be a list. Only " "'in'-filters can be used with lists." % lookup_type) elif lookup_type == 'isnull': value = annotation else: value = value[0] # Remove percents added by Field.get_db_prep_lookup (useful # if one were to use the value in a LIKE expression). if lookup_type in ('startswith', 'istartswith'): value = value[:-1] elif lookup_type in ('endswith', 'iendswith'): value = value[1:] elif lookup_type in ('contains', 'icontains'): value = value[1:-1] # Prepare the value for a database using the nonrel framework. return self.ops.value_for_db(value, field, lookup_type)
[ "def", "_normalize_lookup_value", "(", "self", ",", "lookup_type", ",", "value", ",", "field", ",", "annotation", ")", ":", "# Undo Field.get_db_prep_lookup putting most values in a list", "# (a subclass may override this, so check if it's a list) and", "# losing the (True / False) a...
https://github.com/django-nonrel/djangotoolbox/blob/7e2c47e2ab5ee98d0c0f47c5ccce08e75feda48a/djangotoolbox/db/basecompiler.py#L244-L278
giantbranch/python-hacker-code
addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d
我手敲的代码(中文注释)/chapter11/volatility-2.3/contrib/plugins/malware/zeusscan.py
python
ZeusScan1._zeus_filter
(self, vad)
return (vad.u.VadFlags.PrivateMemory == 0 and prot == "PAGE_NO_ACCESS" and vad.Tag == "VadS")
This is a callback that's executed by get_vads() when searching for zeus injections. @param vad: an MMVAD object. @returns: True if the MMVAD looks like it might contain a zeus image. We want the memory to be executable, but right now we can only get the original protection not the current protection...and the original protection can be anything. This version of zeus happens to use PAGE_NOACCESS so that's what we'll look for instead.
This is a callback that's executed by get_vads() when searching for zeus injections.
[ "This", "is", "a", "callback", "that", "s", "executed", "by", "get_vads", "()", "when", "searching", "for", "zeus", "injections", "." ]
def _zeus_filter(self, vad): """ This is a callback that's executed by get_vads() when searching for zeus injections. @param vad: an MMVAD object. @returns: True if the MMVAD looks like it might contain a zeus image. We want the memory to be executable, but right now we can only get the original protection not the current protection...and the original protection can be anything. This version of zeus happens to use PAGE_NOACCESS so that's what we'll look for instead. """ prot = vad.u.VadFlags.Protection.v() prot = vadinfo.PROTECT_FLAGS.get(prot, "") return (vad.u.VadFlags.PrivateMemory == 0 and prot == "PAGE_NO_ACCESS" and vad.Tag == "VadS")
[ "def", "_zeus_filter", "(", "self", ",", "vad", ")", ":", "prot", "=", "vad", ".", "u", ".", "VadFlags", ".", "Protection", ".", "v", "(", ")", "prot", "=", "vadinfo", ".", "PROTECT_FLAGS", ".", "get", "(", "prot", ",", "\"\"", ")", "return", "(", ...
https://github.com/giantbranch/python-hacker-code/blob/addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d/我手敲的代码(中文注释)/chapter11/volatility-2.3/contrib/plugins/malware/zeusscan.py#L99-L121
CGCookie/retopoflow
3d8b3a47d1d661f99ab0aeb21d31370bf15de35e
addon_common/cookiecutter/cookiecutter_debug.py
python
CookieCutter_Debug.debug_print_actions
(self, *args, **kwargs)
[]
def debug_print_actions(self, *args, **kwargs): self.debug_print( 'Action', *args, override_enabled=self.cc_debug_actions_enabled, **kwargs )
[ "def", "debug_print_actions", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "debug_print", "(", "'Action'", ",", "*", "args", ",", "override_enabled", "=", "self", ".", "cc_debug_actions_enabled", ",", "*", "*", "kwargs", ...
https://github.com/CGCookie/retopoflow/blob/3d8b3a47d1d661f99ab0aeb21d31370bf15de35e/addon_common/cookiecutter/cookiecutter_debug.py#L39-L45
benoitc/restkit
1af7d69838428acfb97271d5444992872b71e70c
restkit/resource.py
python
Resource.clone
(self)
return obj
if you want to add a path to resource uri, you can do: .. code-block:: python resr2 = res.clone()
if you want to add a path to resource uri, you can do:
[ "if", "you", "want", "to", "add", "a", "path", "to", "resource", "uri", "you", "can", "do", ":" ]
def clone(self): """if you want to add a path to resource uri, you can do: .. code-block:: python resr2 = res.clone() """ obj = self.__class__(self.initial['uri'], **self.initial['client_opts']) return obj
[ "def", "clone", "(", "self", ")", ":", "obj", "=", "self", ".", "__class__", "(", "self", ".", "initial", "[", "'uri'", "]", ",", "*", "*", "self", ".", "initial", "[", "'client_opts'", "]", ")", "return", "obj" ]
https://github.com/benoitc/restkit/blob/1af7d69838428acfb97271d5444992872b71e70c/restkit/resource.py#L77-L87
koz4k/dni-pytorch
b14a07cab049a72c104b57dcdb56730ab8dbafb1
examples/mnist-mlp/main.py
python
one_hot
(indexes, n_classes)
return Variable(result)
[]
def one_hot(indexes, n_classes): result = torch.FloatTensor(indexes.size() + (n_classes,)) if args.cuda: result = result.cuda() result.zero_() indexes_rank = len(indexes.size()) result.scatter_( dim=indexes_rank, index=indexes.data.unsqueeze(dim=indexes_rank), value=1 ) return Variable(result)
[ "def", "one_hot", "(", "indexes", ",", "n_classes", ")", ":", "result", "=", "torch", ".", "FloatTensor", "(", "indexes", ".", "size", "(", ")", "+", "(", "n_classes", ",", ")", ")", "if", "args", ".", "cuda", ":", "result", "=", "result", ".", "cu...
https://github.com/koz4k/dni-pytorch/blob/b14a07cab049a72c104b57dcdb56730ab8dbafb1/examples/mnist-mlp/main.py#L55-L66
coderholic/pyradio
cd3ee2d6b369fedfd009371a59aca23ab39b020f
pyradio/themes.py
python
PyRadioThemeReadWrite._get_max_color
(self, a_theme_name, max_color)
return num_of_colors
[]
def _get_max_color(self, a_theme_name, max_color): checks = ('_8', '_16', '_256') num_of_colors = 0 for a_check in checks: if a_theme_name.endswith(a_check): try: num_of_colors = int(a_check[1:]) - 1 except: pass break checks = (8, 16, 256) if num_of_colors == 0 or num_of_colors not in checks: num_of_colors = max_color for check in checks: if num_of_colors < check: return check return num_of_colors
[ "def", "_get_max_color", "(", "self", ",", "a_theme_name", ",", "max_color", ")", ":", "checks", "=", "(", "'_8'", ",", "'_16'", ",", "'_256'", ")", "num_of_colors", "=", "0", "for", "a_check", "in", "checks", ":", "if", "a_theme_name", ".", "endswith", ...
https://github.com/coderholic/pyradio/blob/cd3ee2d6b369fedfd009371a59aca23ab39b020f/pyradio/themes.py#L391-L407
chaoss/grimoirelab-perceval
ba19bfd5e40bffdd422ca8e68526326b47f97491
perceval/backends/core/github.py
python
GitHubClient._get_token_rate_limit
(self, token)
return remaining
Return token's remaining API points
Return token's remaining API points
[ "Return", "token", "s", "remaining", "API", "points" ]
def _get_token_rate_limit(self, token): """Return token's remaining API points""" rate_url = urijoin(self.base_url, self.RRATE_LIMIT) self.session.headers.update({self.HAUTHORIZATION: 'token ' + token}) remaining = 0 try: headers = super().fetch(rate_url).headers if self.rate_limit_header in headers: remaining = int(headers[self.rate_limit_header]) except requests.exceptions.HTTPError as error: logger.warning("Rate limit not initialized: %s", error) return remaining
[ "def", "_get_token_rate_limit", "(", "self", ",", "token", ")", ":", "rate_url", "=", "urijoin", "(", "self", ".", "base_url", ",", "self", ".", "RRATE_LIMIT", ")", "self", ".", "session", ".", "headers", ".", "update", "(", "{", "self", ".", "HAUTHORIZA...
https://github.com/chaoss/grimoirelab-perceval/blob/ba19bfd5e40bffdd422ca8e68526326b47f97491/perceval/backends/core/github.py#L939-L951
tenpy/tenpy
bbdd3dbbdb511948eb0e6ba7ff619ac6ca657fff
tenpy/networks/mps.py
python
MPSEnvironment.set_LP
(self, i, LP, age)
Store part to the left of site `i`.
Store part to the left of site `i`.
[ "Store", "part", "to", "the", "left", "of", "site", "i", "." ]
def set_LP(self, i, LP, age): """Store part to the left of site `i`.""" i = self._to_valid_index(i) self.cache[self._LP_keys[i]] = LP self._LP_age[i] = age
[ "def", "set_LP", "(", "self", ",", "i", ",", "LP", ",", "age", ")", ":", "i", "=", "self", ".", "_to_valid_index", "(", "i", ")", "self", ".", "cache", "[", "self", ".", "_LP_keys", "[", "i", "]", "]", "=", "LP", "self", ".", "_LP_age", "[", ...
https://github.com/tenpy/tenpy/blob/bbdd3dbbdb511948eb0e6ba7ff619ac6ca657fff/tenpy/networks/mps.py#L4344-L4348
hctomkins/caffe-gui-tool
4037259d37691a203385edebf8630a4d54ae947a
IOwriteprototxt.py
python
script.make
(self)
return string
[]
def make(self): if hasattr(self,'extra_paths'): pathadd = 'PYTHONPATH=$PYTHONPATH:'+':'.join(self.extra_paths) else: pathadd = '' gpustring = '' usedcount = 0 extrastring = '' if self.solver == 'GPU' and self.gpus: extrastring = '--gpu=%s' % self.gpus[-1] solverstring = self.configpath + '%s_solver.prototxt' % self.solvername caffestring = self.caffepath + 'caffe' string = "#!/usr/bin/env sh \n%s '%s' train --solver='%s' %s" % (pathadd,caffestring, solverstring, extrastring) return string
[ "def", "make", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'extra_paths'", ")", ":", "pathadd", "=", "'PYTHONPATH=$PYTHONPATH:'", "+", "':'", ".", "join", "(", "self", ".", "extra_paths", ")", "else", ":", "pathadd", "=", "''", "gpustring"...
https://github.com/hctomkins/caffe-gui-tool/blob/4037259d37691a203385edebf8630a4d54ae947a/IOwriteprototxt.py#L394-L410
rlabbe/filterpy
a437893597957764fb6b415bfb5640bb117f5b99
filterpy/kalman/square_root.py
python
SquareRootKalmanFilter.update
(self, z, R2=None)
Add a new measurement (z) to the kalman filter. If z is None, nothing is changed. Parameters ---------- z : np.array measurement for this update. R2 : np.array, scalar, or None Sqrt of meaaurement noize. Optionally provide to override the measurement noise for this one call, otherwise self.R2 will be used.
Add a new measurement (z) to the kalman filter. If z is None, nothing is changed.
[ "Add", "a", "new", "measurement", "(", "z", ")", "to", "the", "kalman", "filter", ".", "If", "z", "is", "None", "nothing", "is", "changed", "." ]
def update(self, z, R2=None): """ Add a new measurement (z) to the kalman filter. If z is None, nothing is changed. Parameters ---------- z : np.array measurement for this update. R2 : np.array, scalar, or None Sqrt of meaaurement noize. Optionally provide to override the measurement noise for this one call, otherwise self.R2 will be used. """ if z is None: self.z = np.array([[None]*self.dim_z]).T self.x_post = self.x.copy() self._P1_2_post = np.copy(self._P1_2) return if R2 is None: R2 = self._R1_2 elif np.isscalar(R2): R2 = eye(self.dim_z) * R2 # rename for convienance dim_z = self.dim_z M = self.M M[0:dim_z, 0:dim_z] = R2.T M[dim_z:, 0:dim_z] = dot(self.H, self._P1_2).T M[dim_z:, dim_z:] = self._P1_2.T _, self.S = qr(M) self.K = self.S[0:dim_z, dim_z:].T N = self.S[0:dim_z, 0:dim_z].T # y = z - Hx # error (residual) between measurement and prediction self.y = z - dot(self.H, self.x) # x = x + Ky # predict new x with residual scaled by the kalman gain self.x += dot(self.K, pinv(N)).dot(self.y) self._P1_2 = self.S[dim_z:, dim_z:].T self.z = deepcopy(z) self.x_post = self.x.copy() self._P1_2_post = np.copy(self._P1_2)
[ "def", "update", "(", "self", ",", "z", ",", "R2", "=", "None", ")", ":", "if", "z", "is", "None", ":", "self", ".", "z", "=", "np", ".", "array", "(", "[", "[", "None", "]", "*", "self", ".", "dim_z", "]", ")", ".", "T", "self", ".", "x_...
https://github.com/rlabbe/filterpy/blob/a437893597957764fb6b415bfb5640bb117f5b99/filterpy/kalman/square_root.py#L174-L225
jeanfeydy/geomloss
e0c52369ddd489e66ead204a43b7af4a3509924c
geomloss/examples/brain_tractograms/tract_io.py
python
vtkPolyData_to_tracts
(polydata)
return tracts, data
[]
def vtkPolyData_to_tracts(polydata): result = {} result["lines"] = ns.vtk_to_numpy(polydata.GetLines().GetData()) result["points"] = ns.vtk_to_numpy(polydata.GetPoints().GetData()) result["numberOfLines"] = polydata.GetNumberOfLines() data = {} if polydata.GetPointData().GetScalars(): data["ActiveScalars"] = polydata.GetPointData().GetScalars().GetName() result["Scalars"] = polydata.GetPointData().GetScalars() if polydata.GetPointData().GetVectors(): data["ActiveVectors"] = polydata.GetPointData().GetVectors().GetName() if polydata.GetPointData().GetTensors(): data["ActiveTensors"] = polydata.GetPointData().GetTensors().GetName() for i in xrange(polydata.GetPointData().GetNumberOfArrays()): array = polydata.GetPointData().GetArray(i) np_array = ns.vtk_to_numpy(array) if np_array.ndim == 1: np_array = np_array.reshape(len(np_array), 1) data[polydata.GetPointData().GetArrayName(i)] = np_array result["pointData"] = data tracts, data = vtkPolyData_dictionary_to_tracts_and_data(result) return tracts, data
[ "def", "vtkPolyData_to_tracts", "(", "polydata", ")", ":", "result", "=", "{", "}", "result", "[", "\"lines\"", "]", "=", "ns", ".", "vtk_to_numpy", "(", "polydata", ".", "GetLines", "(", ")", ".", "GetData", "(", ")", ")", "result", "[", "\"points\"", ...
https://github.com/jeanfeydy/geomloss/blob/e0c52369ddd489e66ead204a43b7af4a3509924c/geomloss/examples/brain_tractograms/tract_io.py#L47-L73
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/Centos_5.9/paramiko/transport.py
python
Transport.close
(self)
Close this session, and any open channels that are tied to it.
Close this session, and any open channels that are tied to it.
[ "Close", "this", "session", "and", "any", "open", "channels", "that", "are", "tied", "to", "it", "." ]
def close(self): """ Close this session, and any open channels that are tied to it. """ if not self.active: return self.stop_thread() for chan in self._channels.values(): chan._unlink() self.sock.close()
[ "def", "close", "(", "self", ")", ":", "if", "not", "self", ".", "active", ":", "return", "self", ".", "stop_thread", "(", ")", "for", "chan", "in", "self", ".", "_channels", ".", "values", "(", ")", ":", "chan", ".", "_unlink", "(", ")", "self", ...
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/Centos_5.9/paramiko/transport.py#L612-L621
Alexey-T/CudaText
6a8b9a974c5d5029c6c273bde83198c83b3a5fb9
app/py/sys/urllib3/util/wait.py
python
wait_for_read
(sock, timeout=None)
return wait_for_socket(sock, read=True, timeout=timeout)
Waits for reading to be available on a given socket. Returns True if the socket is readable, or False if the timeout expired.
Waits for reading to be available on a given socket. Returns True if the socket is readable, or False if the timeout expired.
[ "Waits", "for", "reading", "to", "be", "available", "on", "a", "given", "socket", ".", "Returns", "True", "if", "the", "socket", "is", "readable", "or", "False", "if", "the", "timeout", "expired", "." ]
def wait_for_read(sock, timeout=None): """Waits for reading to be available on a given socket. Returns True if the socket is readable, or False if the timeout expired. """ return wait_for_socket(sock, read=True, timeout=timeout)
[ "def", "wait_for_read", "(", "sock", ",", "timeout", "=", "None", ")", ":", "return", "wait_for_socket", "(", "sock", ",", "read", "=", "True", ",", "timeout", "=", "timeout", ")" ]
https://github.com/Alexey-T/CudaText/blob/6a8b9a974c5d5029c6c273bde83198c83b3a5fb9/app/py/sys/urllib3/util/wait.py#L142-L146
pybrain/pybrain
dcdf32ba1805490cefbc0bdeb227260d304fdb42
pybrain/structure/evolvables/maskedparameters.py
python
MaskedParameters._applyMask
(self)
apply the mask to the module.
apply the mask to the module.
[ "apply", "the", "mask", "to", "the", "module", "." ]
def _applyMask(self): """ apply the mask to the module. """ self.pcontainer._params[:] = self.mask*self.maskableParams
[ "def", "_applyMask", "(", "self", ")", ":", "self", ".", "pcontainer", ".", "_params", "[", ":", "]", "=", "self", ".", "mask", "*", "self", ".", "maskableParams" ]
https://github.com/pybrain/pybrain/blob/dcdf32ba1805490cefbc0bdeb227260d304fdb42/pybrain/structure/evolvables/maskedparameters.py#L35-L37
IronLanguages/ironpython2
51fdedeeda15727717fb8268a805f71b06c0b9f1
Src/StdLib/repackage/setuptools/pkg_resources/__init__.py
python
ResourceManager.set_extraction_path
(self, path)
Set the base path where resources will be extracted to, if needed. If you do not call this routine before any extractions take place, the path defaults to the return value of ``get_default_cache()``. (Which is based on the ``PYTHON_EGG_CACHE`` environment variable, with various platform-specific fallbacks. See that routine's documentation for more details.) Resources are extracted to subdirectories of this path based upon information given by the ``IResourceProvider``. You may set this to a temporary directory, but then you must call ``cleanup_resources()`` to delete the extracted files when done. There is no guarantee that ``cleanup_resources()`` will be able to remove all extracted files. (Note: you may not change the extraction path for a given resource manager once resources have been extracted, unless you first call ``cleanup_resources()``.)
Set the base path where resources will be extracted to, if needed.
[ "Set", "the", "base", "path", "where", "resources", "will", "be", "extracted", "to", "if", "needed", "." ]
def set_extraction_path(self, path): """Set the base path where resources will be extracted to, if needed. If you do not call this routine before any extractions take place, the path defaults to the return value of ``get_default_cache()``. (Which is based on the ``PYTHON_EGG_CACHE`` environment variable, with various platform-specific fallbacks. See that routine's documentation for more details.) Resources are extracted to subdirectories of this path based upon information given by the ``IResourceProvider``. You may set this to a temporary directory, but then you must call ``cleanup_resources()`` to delete the extracted files when done. There is no guarantee that ``cleanup_resources()`` will be able to remove all extracted files. (Note: you may not change the extraction path for a given resource manager once resources have been extracted, unless you first call ``cleanup_resources()``.) """ if self.cached_files: raise ValueError( "Can't change extraction path, files already extracted" ) self.extraction_path = path
[ "def", "set_extraction_path", "(", "self", ",", "path", ")", ":", "if", "self", ".", "cached_files", ":", "raise", "ValueError", "(", "\"Can't change extraction path, files already extracted\"", ")", "self", ".", "extraction_path", "=", "path" ]
https://github.com/IronLanguages/ironpython2/blob/51fdedeeda15727717fb8268a805f71b06c0b9f1/Src/StdLib/repackage/setuptools/pkg_resources/__init__.py#L1265-L1289
trailofbits/manticore
b050fdf0939f6c63f503cdf87ec0ab159dd41159
manticore/platforms/linux_syscall_stubs.py
python
SyscallStubs.sys_sync_file_range
(self, fd, offset, bytes, flags)
return self.simple_returns()
AUTOGENERATED UNIMPLEMENTED STUB
AUTOGENERATED UNIMPLEMENTED STUB
[ "AUTOGENERATED", "UNIMPLEMENTED", "STUB" ]
def sys_sync_file_range(self, fd, offset, bytes, flags) -> int: """ AUTOGENERATED UNIMPLEMENTED STUB """ return self.simple_returns()
[ "def", "sys_sync_file_range", "(", "self", ",", "fd", ",", "offset", ",", "bytes", ",", "flags", ")", "->", "int", ":", "return", "self", ".", "simple_returns", "(", ")" ]
https://github.com/trailofbits/manticore/blob/b050fdf0939f6c63f503cdf87ec0ab159dd41159/manticore/platforms/linux_syscall_stubs.py#L1052-L1054
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/astropy-4.0-py3.7-macosx-10.9-x86_64.egg/astropy/units/core.py
python
UnitBase.to_string
(self, format=unit_format.Generic)
return f.to_string(self)
Output the unit in the given format as a string. Parameters ---------- format : `astropy.units.format.Base` instance or str The name of a format or a formatter object. If not provided, defaults to the generic format.
Output the unit in the given format as a string.
[ "Output", "the", "unit", "in", "the", "given", "format", "as", "a", "string", "." ]
def to_string(self, format=unit_format.Generic): """ Output the unit in the given format as a string. Parameters ---------- format : `astropy.units.format.Base` instance or str The name of a format or a formatter object. If not provided, defaults to the generic format. """ f = unit_format.get_format(format) return f.to_string(self)
[ "def", "to_string", "(", "self", ",", "format", "=", "unit_format", ".", "Generic", ")", ":", "f", "=", "unit_format", ".", "get_format", "(", "format", ")", "return", "f", ".", "to_string", "(", "self", ")" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/astropy-4.0-py3.7-macosx-10.9-x86_64.egg/astropy/units/core.py#L593-L605
dmlc/gluon-cv
709bc139919c02f7454cb411311048be188cde64
gluoncv/model_zoo/yolo/yolo3.py
python
yolo3_darknet53_coco
(pretrained_base=True, pretrained=False, norm_layer=BatchNorm, norm_kwargs=None, **kwargs)
return get_yolov3( 'darknet53', stages, [512, 256, 128], anchors, strides, classes, 'coco', pretrained=pretrained, norm_layer=norm_layer, norm_kwargs=norm_kwargs, **kwargs)
YOLO3 multi-scale with darknet53 base network on COCO dataset. Parameters ---------- pretrained_base : boolean Whether fetch and load pretrained weights for base network. pretrained : bool or str Boolean value controls whether to load the default pretrained weights for model. String value represents the hashtag for a certain version of pretrained weights. norm_layer : object Normalization layer used (default: :class:`mxnet.gluon.nn.BatchNorm`) Can be :class:`mxnet.gluon.nn.BatchNorm` or :class:`mxnet.gluon.contrib.nn.SyncBatchNorm`. norm_kwargs : dict Additional `norm_layer` arguments, for example `num_devices=4` for :class:`mxnet.gluon.contrib.nn.SyncBatchNorm`. Returns ------- mxnet.gluon.HybridBlock Fully hybrid yolo3 network.
YOLO3 multi-scale with darknet53 base network on COCO dataset. Parameters ---------- pretrained_base : boolean Whether fetch and load pretrained weights for base network. pretrained : bool or str Boolean value controls whether to load the default pretrained weights for model. String value represents the hashtag for a certain version of pretrained weights. norm_layer : object Normalization layer used (default: :class:`mxnet.gluon.nn.BatchNorm`) Can be :class:`mxnet.gluon.nn.BatchNorm` or :class:`mxnet.gluon.contrib.nn.SyncBatchNorm`. norm_kwargs : dict Additional `norm_layer` arguments, for example `num_devices=4` for :class:`mxnet.gluon.contrib.nn.SyncBatchNorm`. Returns ------- mxnet.gluon.HybridBlock Fully hybrid yolo3 network.
[ "YOLO3", "multi", "-", "scale", "with", "darknet53", "base", "network", "on", "COCO", "dataset", ".", "Parameters", "----------", "pretrained_base", ":", "boolean", "Whether", "fetch", "and", "load", "pretrained", "weights", "for", "base", "network", ".", "pretr...
def yolo3_darknet53_coco(pretrained_base=True, pretrained=False, norm_layer=BatchNorm, norm_kwargs=None, **kwargs): """YOLO3 multi-scale with darknet53 base network on COCO dataset. Parameters ---------- pretrained_base : boolean Whether fetch and load pretrained weights for base network. pretrained : bool or str Boolean value controls whether to load the default pretrained weights for model. String value represents the hashtag for a certain version of pretrained weights. norm_layer : object Normalization layer used (default: :class:`mxnet.gluon.nn.BatchNorm`) Can be :class:`mxnet.gluon.nn.BatchNorm` or :class:`mxnet.gluon.contrib.nn.SyncBatchNorm`. norm_kwargs : dict Additional `norm_layer` arguments, for example `num_devices=4` for :class:`mxnet.gluon.contrib.nn.SyncBatchNorm`. Returns ------- mxnet.gluon.HybridBlock Fully hybrid yolo3 network. """ from ...data import COCODetection pretrained_base = False if pretrained else pretrained_base base_net = darknet53( pretrained=pretrained_base, norm_layer=norm_layer, norm_kwargs=norm_kwargs, **kwargs) stages = [base_net.features[:15], base_net.features[15:24], base_net.features[24:]] anchors = [[10, 13, 16, 30, 33, 23], [30, 61, 62, 45, 59, 119], [116, 90, 156, 198, 373, 326]] strides = [8, 16, 32] classes = COCODetection.CLASSES return get_yolov3( 'darknet53', stages, [512, 256, 128], anchors, strides, classes, 'coco', pretrained=pretrained, norm_layer=norm_layer, norm_kwargs=norm_kwargs, **kwargs)
[ "def", "yolo3_darknet53_coco", "(", "pretrained_base", "=", "True", ",", "pretrained", "=", "False", ",", "norm_layer", "=", "BatchNorm", ",", "norm_kwargs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", ".", ".", ".", "data", "import", "COCODete...
https://github.com/dmlc/gluon-cv/blob/709bc139919c02f7454cb411311048be188cde64/gluoncv/model_zoo/yolo/yolo3.py#L661-L692
eblot/pyftdi
72797e5ae0945d6f771f13102d7fccac255d83d7
pyftdi/serialext/protocol_ftdi.py
python
FtdiSerial.usb_path
(self)
return self.udev.usb_path
Return the physical location as a triplet. * bus is the USB bus * address is the address on the USB bus * interface is the interface number on the FTDI debice :return: (bus, address, interface) :rtype: tuple(int)
Return the physical location as a triplet. * bus is the USB bus * address is the address on the USB bus * interface is the interface number on the FTDI debice
[ "Return", "the", "physical", "location", "as", "a", "triplet", ".", "*", "bus", "is", "the", "USB", "bus", "*", "address", "is", "the", "address", "on", "the", "USB", "bus", "*", "interface", "is", "the", "interface", "number", "on", "the", "FTDI", "de...
def usb_path(self): """Return the physical location as a triplet. * bus is the USB bus * address is the address on the USB bus * interface is the interface number on the FTDI debice :return: (bus, address, interface) :rtype: tuple(int) """ return self.udev.usb_path
[ "def", "usb_path", "(", "self", ")", ":", "return", "self", ".", "udev", ".", "usb_path" ]
https://github.com/eblot/pyftdi/blob/72797e5ae0945d6f771f13102d7fccac255d83d7/pyftdi/serialext/protocol_ftdi.py#L116-L125
kedro-org/kedro
e78990c6b606a27830f0d502afa0f639c0830950
kedro/framework/cli/pipeline.py
python
_safe_parse_requirements
( requirements: Union[str, Iterable[str]] )
return parseable_requirements
Safely parse a requirement or set of requirements. This effectively replaces pkg_resources.parse_requirements, which blows up with a ValueError as soon as it encounters a requirement it cannot parse (e.g. `-r requirements.txt`). This way we can still extract all the parseable requirements out of a set containing some unparseable requirements.
Safely parse a requirement or set of requirements. This effectively replaces pkg_resources.parse_requirements, which blows up with a ValueError as soon as it encounters a requirement it cannot parse (e.g. `-r requirements.txt`). This way we can still extract all the parseable requirements out of a set containing some unparseable requirements.
[ "Safely", "parse", "a", "requirement", "or", "set", "of", "requirements", ".", "This", "effectively", "replaces", "pkg_resources", ".", "parse_requirements", "which", "blows", "up", "with", "a", "ValueError", "as", "soon", "as", "it", "encounters", "a", "require...
def _safe_parse_requirements( requirements: Union[str, Iterable[str]] ) -> Set[pkg_resources.Requirement]: """Safely parse a requirement or set of requirements. This effectively replaces pkg_resources.parse_requirements, which blows up with a ValueError as soon as it encounters a requirement it cannot parse (e.g. `-r requirements.txt`). This way we can still extract all the parseable requirements out of a set containing some unparseable requirements. """ parseable_requirements = set() for requirement in pkg_resources.yield_lines(requirements): try: parseable_requirements.add(pkg_resources.Requirement.parse(requirement)) except ValueError: continue return parseable_requirements
[ "def", "_safe_parse_requirements", "(", "requirements", ":", "Union", "[", "str", ",", "Iterable", "[", "str", "]", "]", ")", "->", "Set", "[", "pkg_resources", ".", "Requirement", "]", ":", "parseable_requirements", "=", "set", "(", ")", "for", "requirement...
https://github.com/kedro-org/kedro/blob/e78990c6b606a27830f0d502afa0f639c0830950/kedro/framework/cli/pipeline.py#L1129-L1144
tensorflow/tensorboard
61d11d99ef034c30ba20b6a7840c8eededb9031c
tensorboard/data/provider.py
python
TensorDatum.step
(self)
return self._step
[]
def step(self): return self._step
[ "def", "step", "(", "self", ")", ":", "return", "self", ".", "_step" ]
https://github.com/tensorflow/tensorboard/blob/61d11d99ef034c30ba20b6a7840c8eededb9031c/tensorboard/data/provider.py#L724-L725
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/distlib/_backport/tarfile.py
python
TarInfo._proc_sparse
(self, tarfile)
return self
Process a GNU sparse header plus extra headers.
Process a GNU sparse header plus extra headers.
[ "Process", "a", "GNU", "sparse", "header", "plus", "extra", "headers", "." ]
def _proc_sparse(self, tarfile): """Process a GNU sparse header plus extra headers. """ # We already collected some sparse structures in frombuf(). structs, isextended, origsize = self._sparse_structs del self._sparse_structs # Collect sparse structures from extended header blocks. while isextended: buf = tarfile.fileobj.read(BLOCKSIZE) pos = 0 for i in range(21): try: offset = nti(buf[pos:pos + 12]) numbytes = nti(buf[pos + 12:pos + 24]) except ValueError: break if offset and numbytes: structs.append((offset, numbytes)) pos += 24 isextended = bool(buf[504]) self.sparse = structs self.offset_data = tarfile.fileobj.tell() tarfile.offset = self.offset_data + self._block(self.size) self.size = origsize return self
[ "def", "_proc_sparse", "(", "self", ",", "tarfile", ")", ":", "# We already collected some sparse structures in frombuf().", "structs", ",", "isextended", ",", "origsize", "=", "self", ".", "_sparse_structs", "del", "self", ".", "_sparse_structs", "# Collect sparse struct...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/distlib/_backport/tarfile.py#L1355-L1381
NervanaSystems/ngraph-python
ac032c83c7152b615a9ad129d54d350f9d6a2986
ngraph/util/names.py
python
NameableValue.name
(self)
return self.__name
The name.
The name.
[ "The", "name", "." ]
def name(self): """The name.""" return self.__name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "__name" ]
https://github.com/NervanaSystems/ngraph-python/blob/ac032c83c7152b615a9ad129d54d350f9d6a2986/ngraph/util/names.py#L74-L76
mrJean1/PyGeodesy
7da5ca71aa3edb7bc49e219e0b8190686e1a7965
pygeodesy/points.py
python
LatLon_.philam
(self)
return PhiLam2Tuple(radians(self.lat), radians(self.lon), name=self.name)
Get the lat- and longitude in C{radians} (L{PhiLam2Tuple}C{(phi, lam)}).
Get the lat- and longitude in C{radians} (L{PhiLam2Tuple}C{(phi, lam)}).
[ "Get", "the", "lat", "-", "and", "longitude", "in", "C", "{", "radians", "}", "(", "L", "{", "PhiLam2Tuple", "}", "C", "{", "(", "phi", "lam", ")", "}", ")", "." ]
def philam(self): '''Get the lat- and longitude in C{radians} (L{PhiLam2Tuple}C{(phi, lam)}). ''' return PhiLam2Tuple(radians(self.lat), radians(self.lon), name=self.name)
[ "def", "philam", "(", "self", ")", ":", "return", "PhiLam2Tuple", "(", "radians", "(", "self", ".", "lat", ")", ",", "radians", "(", "self", ".", "lon", ")", ",", "name", "=", "self", ".", "name", ")" ]
https://github.com/mrJean1/PyGeodesy/blob/7da5ca71aa3edb7bc49e219e0b8190686e1a7965/pygeodesy/points.py#L259-L262
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/wagtail_bak/wagtailadmin/views/pages.py
python
PreviewOnEdit.session_key
(self)
return self.session_key_prefix + ','.join(self.args)
[]
def session_key(self): return self.session_key_prefix + ','.join(self.args)
[ "def", "session_key", "(", "self", ")", ":", "return", "self", ".", "session_key_prefix", "+", "','", ".", "join", "(", "self", ".", "args", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/wagtail_bak/wagtailadmin/views/pages.py#L565-L566
opendatacube/datacube-core
b062184be61c140a168de94510bc3661748f112e
datacube/utils/dates.py
python
_parse_time_ciso8601
(time: Union[str, datetime])
Convert string to datetime object This function deals with ISO8601 dates fast, and fallbacks to python for other formats. Calling this on datetime object is a no-op.
Convert string to datetime object
[ "Convert", "string", "to", "datetime", "object" ]
def _parse_time_ciso8601(time: Union[str, datetime]) -> datetime: """Convert string to datetime object This function deals with ISO8601 dates fast, and fallbacks to python for other formats. Calling this on datetime object is a no-op. """ from ciso8601 import parse_datetime if isinstance(time, datetime): return time try: return parse_datetime(time) except Exception: # pylint: disable=broad-except return _parse_time_generic(time)
[ "def", "_parse_time_ciso8601", "(", "time", ":", "Union", "[", "str", ",", "datetime", "]", ")", "->", "datetime", ":", "from", "ciso8601", "import", "parse_datetime", "if", "isinstance", "(", "time", ",", "datetime", ")", ":", "return", "time", "try", ":"...
https://github.com/opendatacube/datacube-core/blob/b062184be61c140a168de94510bc3661748f112e/datacube/utils/dates.py#L85-L101
kiibohd/kll
b6d997b810006326d31fc570c89d396fd0b70569
kll/extern/funcparserlib/parser.py
python
some
(pred)
return _some
(a -> bool) -> Parser(a, a) Returns a parser that parses a token if it satisfies a predicate pred.
(a -> bool) -> Parser(a, a)
[ "(", "a", "-", ">", "bool", ")", "-", ">", "Parser", "(", "a", "a", ")" ]
def some(pred): """(a -> bool) -> Parser(a, a) Returns a parser that parses a token if it satisfies a predicate pred. """ @Parser def _some(tokens, s): if s.pos >= len(tokens): raise NoParseError('no tokens left in the stream', s) else: t = tokens[s.pos] if pred(t): pos = s.pos + 1 s2 = State(pos, max(pos, s.max)) if debug: log.debug('*matched* "%s", new state = %s' % (t, s2)) return t, s2 else: if debug: log.debug('failed "%s", state = %s' % (t, s)) raise NoParseError('got unexpected token', s, t) _some.name = '(some)' return _some
[ "def", "some", "(", "pred", ")", ":", "@", "Parser", "def", "_some", "(", "tokens", ",", "s", ")", ":", "if", "s", ".", "pos", ">=", "len", "(", "tokens", ")", ":", "raise", "NoParseError", "(", "'no tokens left in the stream'", ",", "s", ")", "else"...
https://github.com/kiibohd/kll/blob/b6d997b810006326d31fc570c89d396fd0b70569/kll/extern/funcparserlib/parser.py#L327-L351
ztosec/hunter
4ee5cca8dc5fc5d7e631e935517bd0f493c30a37
SqlmapCelery/sqlmap/thirdparty/pydes/pyDes.py
python
_baseDes.setMode
(self, mode)
Sets the type of crypting mode, pyDes.ECB or pyDes.CBC
Sets the type of crypting mode, pyDes.ECB or pyDes.CBC
[ "Sets", "the", "type", "of", "crypting", "mode", "pyDes", ".", "ECB", "or", "pyDes", ".", "CBC" ]
def setMode(self, mode): """Sets the type of crypting mode, pyDes.ECB or pyDes.CBC""" self._mode = mode
[ "def", "setMode", "(", "self", ",", "mode", ")", ":", "self", ".", "_mode", "=", "mode" ]
https://github.com/ztosec/hunter/blob/4ee5cca8dc5fc5d7e631e935517bd0f493c30a37/SqlmapCelery/sqlmap/thirdparty/pydes/pyDes.py#L139-L141
PaddlePaddle/PaddleX
2bab73f81ab54e328204e7871e6ae4a82e719f5d
paddlex/ppcls/arch/backbone/model_zoo/levit.py
python
b16
(n, activation, resolution=224)
return nn.Sequential( Conv2d_BN( 3, n // 8, 3, 2, 1, resolution=resolution), activation(), Conv2d_BN( n // 8, n // 4, 3, 2, 1, resolution=resolution // 2), activation(), Conv2d_BN( n // 4, n // 2, 3, 2, 1, resolution=resolution // 4), activation(), Conv2d_BN( n // 2, n, 3, 2, 1, resolution=resolution // 8))
[]
def b16(n, activation, resolution=224): return nn.Sequential( Conv2d_BN( 3, n // 8, 3, 2, 1, resolution=resolution), activation(), Conv2d_BN( n // 8, n // 4, 3, 2, 1, resolution=resolution // 2), activation(), Conv2d_BN( n // 4, n // 2, 3, 2, 1, resolution=resolution // 4), activation(), Conv2d_BN( n // 2, n, 3, 2, 1, resolution=resolution // 8))
[ "def", "b16", "(", "n", ",", "activation", ",", "resolution", "=", "224", ")", ":", "return", "nn", ".", "Sequential", "(", "Conv2d_BN", "(", "3", ",", "n", "//", "8", ",", "3", ",", "2", ",", "1", ",", "resolution", "=", "resolution", ")", ",", ...
https://github.com/PaddlePaddle/PaddleX/blob/2bab73f81ab54e328204e7871e6ae4a82e719f5d/paddlex/ppcls/arch/backbone/model_zoo/levit.py#L110-L122
ninthDevilHAUNSTER/ArknightsAutoHelper
a27a930502d6e432368d9f62595a1d69a992f4e6
vendor/penguin_client/penguin_client/models/stage.py
python
Stage.to_dict
(self)
return result
Returns the model properties as a dict
Returns the model properties as a dict
[ "Returns", "the", "model", "properties", "as", "a", "dict" ]
def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(Stage, dict): for key, value in self.items(): result[key] = value return result
[ "def", "to_dict", "(", "self", ")", ":", "result", "=", "{", "}", "for", "attr", ",", "_", "in", "six", ".", "iteritems", "(", "self", ".", "swagger_types", ")", ":", "value", "=", "getattr", "(", "self", ",", "attr", ")", "if", "isinstance", "(", ...
https://github.com/ninthDevilHAUNSTER/ArknightsAutoHelper/blob/a27a930502d6e432368d9f62595a1d69a992f4e6/vendor/penguin_client/penguin_client/models/stage.py#L331-L356
Hexxeh/libpebble
e935e9aa50fe7dde25bbee8cbe0e7606378edbb8
pebble/pebble.py
python
Pebble.set_nowplaying_metadata
(self, track, album, artist)
Update the song metadata displayed in Pebble's music app.
Update the song metadata displayed in Pebble's music app.
[ "Update", "the", "song", "metadata", "displayed", "in", "Pebble", "s", "music", "app", "." ]
def set_nowplaying_metadata(self, track, album, artist): """Update the song metadata displayed in Pebble's music app.""" parts = [artist[:30], album[:30], track[:30]] self._send_message("MUSIC_CONTROL", self._pack_message_data(16, parts))
[ "def", "set_nowplaying_metadata", "(", "self", ",", "track", ",", "album", ",", "artist", ")", ":", "parts", "=", "[", "artist", "[", ":", "30", "]", ",", "album", "[", ":", "30", "]", ",", "track", "[", ":", "30", "]", "]", "self", ".", "_send_m...
https://github.com/Hexxeh/libpebble/blob/e935e9aa50fe7dde25bbee8cbe0e7606378edbb8/pebble/pebble.py#L459-L464
OpenMDAO/OpenMDAO-Framework
f2e37b7de3edeaaeb2d251b375917adec059db9b
openmdao.lib/src/openmdao/lib/datatypes/domain/plot3d.py
python
_read_plot3d_fvars
(zone, stream, dim, nvars, varnames, planes, logger)
Reads 'function' variables.
Reads 'function' variables.
[ "Reads", "function", "variables", "." ]
def _read_plot3d_fvars(zone, stream, dim, nvars, varnames, planes, logger): """ Reads 'function' variables. """ if planes: raise NotImplementedError('planar format not supported yet') shape = zone.shape dim = len(shape) if stream.unformatted: if dim > 2: imax, jmax, kmax = shape total = nvars * imax * jmax * kmax else: imax, jmax = shape total = nvars * imax * jmax reclen = stream.read_recordmark() expected = stream.reclen_floats(total) if reclen != expected: logger.warning('unexpected F variables recordlength' ' %d vs. %d', reclen, expected) for i in range(nvars): if varnames and i < len(varnames): name = varnames[i] else: name = 'f_%d' % (i+1) arr = stream.read_floats(shape, order='Fortran') zone.flow_solution.add_array(name, arr) logger.debug(' %s min %g, max %g', name, arr.min(), arr.max()) if stream.unformatted: reclen2 = stream.read_recordmark() if reclen2 != reclen: logger.warning('mismatched F variables recordlength' ' %d vs. %d', reclen2, reclen)
[ "def", "_read_plot3d_fvars", "(", "zone", ",", "stream", ",", "dim", ",", "nvars", ",", "varnames", ",", "planes", ",", "logger", ")", ":", "if", "planes", ":", "raise", "NotImplementedError", "(", "'planar format not supported yet'", ")", "shape", "=", "zone"...
https://github.com/OpenMDAO/OpenMDAO-Framework/blob/f2e37b7de3edeaaeb2d251b375917adec059db9b/openmdao.lib/src/openmdao/lib/datatypes/domain/plot3d.py#L417-L450
isce-framework/isce2
0e5114a8bede3caf1d533d98e44dfe4b983e3f48
components/isceobj/TopsProc/runVerifyGeocodeDEM.py
python
runVerifyGeocodeDEM
(self)
return demimg.filename
Make sure that a DEM is available for processing the given data.
Make sure that a DEM is available for processing the given data.
[ "Make", "sure", "that", "a", "DEM", "is", "available", "for", "processing", "the", "given", "data", "." ]
def runVerifyGeocodeDEM(self): ''' Make sure that a DEM is available for processing the given data. ''' self.demStitcher.noFilling = False ###If provided in the input XML file if self.geocodeDemFilename not in ['',None]: demimg = isceobj.createDemImage() demimg.load(self.geocodeDemFilename + '.xml') if not os.path.exists(self.geocodeDemFilename + '.vrt'): demimg.renderVRT() if demimg.reference.upper() == 'EGM96': wgsdemname = self.geocodeDemFilename + '.wgs84' if os.path.exists(wgsdemname) and os.path.exists(wgsdemname + '.xml'): demimg = isceobj.createDemImage() demimg.load(wgsdemname + '.xml') if demimg.reference.upper() == 'EGM96': raise Exception('WGS84 version of dem found by reference set to EGM96') else: demimg = self.demStitcher.correct(demimg) elif demimg.reference.upper() != 'WGS84': raise Exception('Unknown reference system for DEM: {0}'.format(demimg.reference)) ##Fall back to DEM used for running topo else: self.geocodeDemFilename = self.verifyDEM() demimg = isceobj.createDemImage() demimg.load(self.geocodeDemFilename + '.xml') if demimg.reference.upper() == 'EGM96': raise Exception('EGM96 DEM returned by verifyDEM') return demimg.filename
[ "def", "runVerifyGeocodeDEM", "(", "self", ")", ":", "self", ".", "demStitcher", ".", "noFilling", "=", "False", "###If provided in the input XML file", "if", "self", ".", "geocodeDemFilename", "not", "in", "[", "''", ",", "None", "]", ":", "demimg", "=", "isc...
https://github.com/isce-framework/isce2/blob/0e5114a8bede3caf1d533d98e44dfe4b983e3f48/components/isceobj/TopsProc/runVerifyGeocodeDEM.py#L21-L62
bspaans/python-mingus
6558cacffeaab4f084a3eedda12b0e86fd24c430
mingus/containers/composition.py
python
Composition.__repr__
(self)
return result
Return a string representing the class.
Return a string representing the class.
[ "Return", "a", "string", "representing", "the", "class", "." ]
def __repr__(self): """Return a string representing the class.""" result = "" for x in self.tracks: result += str(x) return result
[ "def", "__repr__", "(", "self", ")", ":", "result", "=", "\"\"", "for", "x", "in", "self", ".", "tracks", ":", "result", "+=", "str", "(", "x", ")", "return", "result" ]
https://github.com/bspaans/python-mingus/blob/6558cacffeaab4f084a3eedda12b0e86fd24c430/mingus/containers/composition.py#L110-L115