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
scrapinghub/splash
802d8391984bae049ef95a3fe1a74feaee95a233
splash/network_manager.py
python
ProxiedQNetworkAccessManager._get_har
(self, request=None)
return self._get_webpage_attribute(request, "har")
Return HarBuilder instance. :rtype: splash.har_builder.HarBuilder | None
Return HarBuilder instance. :rtype: splash.har_builder.HarBuilder | None
[ "Return", "HarBuilder", "instance", ".", ":", "rtype", ":", "splash", ".", "har_builder", ".", "HarBuilder", "|", "None" ]
def _get_har(self, request=None): """ Return HarBuilder instance. :rtype: splash.har_builder.HarBuilder | None """ if request is None: request = self.sender().request() return self._get_webpage_attribute(request, "har")
[ "def", "_get_har", "(", "self", ",", "request", "=", "None", ")", ":", "if", "request", "is", "None", ":", "request", "=", "self", ".", "sender", "(", ")", ".", "request", "(", ")", "return", "self", ".", "_get_webpage_attribute", "(", "request", ",", ...
https://github.com/scrapinghub/splash/blob/802d8391984bae049ef95a3fe1a74feaee95a233/splash/network_manager.py#L345-L352
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/packages/site-packages/sqlalchemy/engine/result.py
python
ResultProxy.close
(self)
Close this ResultProxy. This closes out the underlying DBAPI cursor corresonding to the statement execution, if one is still present. Note that the DBAPI cursor is automatically released when the :class:`.ResultProxy` exhausts all available rows. :meth:`.ResultProxy.close` is generally an optional method except in the case when discarding a :class:`.ResultProxy` that still has additional rows pending for fetch. In the case of a result that is the product of :ref:`connectionless execution <dbengine_implicit>`, the underyling :class:`.Connection` object is also closed, which :term:`releases` DBAPI connection resources. After this method is called, it is no longer valid to call upon the fetch methods, which will raise a :class:`.ResourceClosedError` on subsequent use. .. versionchanged:: 1.0.0 - the :meth:`.ResultProxy.close` method has been separated out from the process that releases the underlying DBAPI cursor resource. The "auto close" feature of the :class:`.Connection` now performs a so-called "soft close", which releases the underlying DBAPI cursor, but allows the :class:`.ResultProxy` to still behave as an open-but-exhausted result set; the actual :meth:`.ResultProxy.close` method is never called. It is still safe to discard a :class:`.ResultProxy` that has been fully exhausted without calling this method. .. seealso:: :ref:`connections_toplevel` :meth:`.ResultProxy._soft_close`
Close this ResultProxy.
[ "Close", "this", "ResultProxy", "." ]
def close(self): """Close this ResultProxy. This closes out the underlying DBAPI cursor corresonding to the statement execution, if one is still present. Note that the DBAPI cursor is automatically released when the :class:`.ResultProxy` exhausts all available rows. :meth:`.ResultProxy.close` is generally an optional method except in the case when discarding a :class:`.ResultProxy` that still has additional rows pending for fetch. In the case of a result that is the product of :ref:`connectionless execution <dbengine_implicit>`, the underyling :class:`.Connection` object is also closed, which :term:`releases` DBAPI connection resources. After this method is called, it is no longer valid to call upon the fetch methods, which will raise a :class:`.ResourceClosedError` on subsequent use. .. versionchanged:: 1.0.0 - the :meth:`.ResultProxy.close` method has been separated out from the process that releases the underlying DBAPI cursor resource. The "auto close" feature of the :class:`.Connection` now performs a so-called "soft close", which releases the underlying DBAPI cursor, but allows the :class:`.ResultProxy` to still behave as an open-but-exhausted result set; the actual :meth:`.ResultProxy.close` method is never called. It is still safe to discard a :class:`.ResultProxy` that has been fully exhausted without calling this method. .. seealso:: :ref:`connections_toplevel` :meth:`.ResultProxy._soft_close` """ if not self.closed: self._soft_close() self.closed = True
[ "def", "close", "(", "self", ")", ":", "if", "not", "self", ".", "closed", ":", "self", ".", "_soft_close", "(", ")", "self", ".", "closed", "=", "True" ]
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/packages/site-packages/sqlalchemy/engine/result.py#L672-L711
frostming/legit
5119c0a81cb0e87974255dd29463a60b22916baa
legit/utils.py
python
git_version
()
return g.version_info
Return the git version tuple (major, minor, patch)
Return the git version tuple (major, minor, patch)
[ "Return", "the", "git", "version", "tuple", "(", "major", "minor", "patch", ")" ]
def git_version(): """Return the git version tuple (major, minor, patch)""" from git import Git g = Git() return g.version_info
[ "def", "git_version", "(", ")", ":", "from", "git", "import", "Git", "g", "=", "Git", "(", ")", "return", "g", ".", "version_info" ]
https://github.com/frostming/legit/blob/5119c0a81cb0e87974255dd29463a60b22916baa/legit/utils.py#L127-L132
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/converters/nastran/gui/nastran_io.py
python
NastranIO_._fill_bar_yz
(self, unused_dim_max, model, icase, cases, form, debug=False)
return icase
plots the y, z vectors for CBAR & CBEAM elements
plots the y, z vectors for CBAR & CBEAM elements
[ "plots", "the", "y", "z", "vectors", "for", "CBAR", "&", "CBEAM", "elements" ]
def _fill_bar_yz(self, unused_dim_max, model, icase, cases, form, debug=False): """ plots the y, z vectors for CBAR & CBEAM elements """ card_types = ['CBAR', 'CBEAM'] out = model.get_card_ids_by_card_types(card_types=card_types) bar_beam_eids = out['CBAR'] + out['CBEAM'] bar_pid_to_eids = get_beam_sections_map(model, bar_beam_eids) bar_nids = get_bar_nids(model, bar_beam_eids) #ugrid_temp = create_3d_beams(model, bar_pid_to_eids) self.bar_eids = {} self.bar_lines = {} if len(bar_beam_eids) == 0: return icase scale = 0.15 # TODO: this should be reworked bar_nids, bar_types, nid_release_map = self._get_bar_yz_arrays( model, bar_beam_eids, bar_pid_to_eids, scale, debug) self.nid_release_map = nid_release_map bar_nids = list(bar_nids) self.gui.create_alternate_vtk_grid( 'Bar Nodes', color=RED_FLOAT, line_width=1, opacity=1., point_size=5, representation='point', bar_scale=0., is_visible=False) msg = ", which is required by 'Bar Nodes'" self._add_nastran_nodes_to_grid('Bar Nodes', bar_nids, model, msg) geo_form = form[2] bar_form = ('CBAR / CBEAM', None, []) #print('geo_form =', geo_form) #bar_types2 = {} bar_eids = [] for bar_type, data in sorted(bar_types.items()): eids, lines_bar_y, lines_bar_z = data if len(eids): bar_eids.append(eids) ibars = 0 if bar_eids: bar_eids = np.hstack(bar_eids) ibars = np.searchsorted(self.element_ids, bar_eids) for bar_type, data in sorted(bar_types.items()): eids, lines_bar_y, lines_bar_z = data if len(eids): if debug: # pragma: no cover print('bar_type = %r' % bar_type) print('eids = %r' % eids) print('all_eids = %r' % self.element_ids.tolist()) # if bar_type not in ['ROD', 'TUBE']: bar_y = bar_type + '_y' bar_z = bar_type + '_z' self.gui.create_alternate_vtk_grid( bar_y, color=GREEN_FLOAT, line_width=5, opacity=1., point_size=5, representation='bar', bar_scale=scale, is_visible=False) self.gui.create_alternate_vtk_grid( bar_z, color=BLUE_FLOAT, line_width=5, opacity=1., point_size=5, representation='bar', bar_scale=scale, is_visible=False) self._add_nastran_lines_xyz_to_grid(bar_y, lines_bar_y, eids) self._add_nastran_lines_xyz_to_grid(bar_z, lines_bar_z, eids) # form = ['Geometry', None, []] i = np.searchsorted(self.element_ids, eids) is_type = np.full(self.element_ids.shape, -1, dtype='int32') is_type[ibars] = 0 try: is_type[i] = 1 except Exception: #print('self.element_ids =', self.element_ids) #print('eids =', eids) ii = np.where(i == len(self.element_ids))[0] print('ii = %s' % ii) print('failed eids =', eids[ii]) #assert self.element_ids[i] == eids raise bar_form[2].append(['is_%s' % bar_type, icase, []]) msg = 'is_%s' % bar_type type_res = GuiResult(0, header=msg, title=msg, location='centroid', scalar=is_type, mask_value=-1) cases[icase] = (type_res, (0, msg)) icase += 1 # print(geo_form) if len(bar_form[2]): geo_form.append(bar_form) return icase
[ "def", "_fill_bar_yz", "(", "self", ",", "unused_dim_max", ",", "model", ",", "icase", ",", "cases", ",", "form", ",", "debug", "=", "False", ")", ":", "card_types", "=", "[", "'CBAR'", ",", "'CBEAM'", "]", "out", "=", "model", ".", "get_card_ids_by_card...
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/converters/nastran/gui/nastran_io.py#L2087-L2179
statsmodels/statsmodels
debbe7ea6ba28fe5bdb78f09f8cac694bef98722
statsmodels/sandbox/panel/sandwich_covariance_generic.py
python
S_all_hac
(x, d, nlags=1)
return aggregate_cov(x, d, r=r, weights=weights)
HAC independent of categorical group membership
HAC independent of categorical group membership
[ "HAC", "independent", "of", "categorical", "group", "membership" ]
def S_all_hac(x, d, nlags=1): '''HAC independent of categorical group membership ''' r = np.zeros(d.shape[1]) r[0] = 1 weights = weights_bartlett(nlags) return aggregate_cov(x, d, r=r, weights=weights)
[ "def", "S_all_hac", "(", "x", ",", "d", ",", "nlags", "=", "1", ")", ":", "r", "=", "np", ".", "zeros", "(", "d", ".", "shape", "[", "1", "]", ")", "r", "[", "0", "]", "=", "1", "weights", "=", "weights_bartlett", "(", "nlags", ")", "return",...
https://github.com/statsmodels/statsmodels/blob/debbe7ea6ba28fe5bdb78f09f8cac694bef98722/statsmodels/sandbox/panel/sandwich_covariance_generic.py#L96-L102
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit - MAC OSX/scripts/sshbackdoors/rpyc/core/stream.py
python
SocketStream.read
(self, count)
return BYTES_LITERAL("").join(data)
[]
def read(self, count): data = [] while count > 0: try: buf = self.sock.recv(min(self.MAX_IO_CHUNK, count)) except socket.timeout: continue except socket.error: ex = sys.exc_info()[1] if get_exc_errno(ex) in retry_errnos: # windows just has to be a bitch continue self.close() raise EOFError(ex) if not buf: self.close() raise EOFError("connection closed by peer") data.append(buf) count -= len(buf) return BYTES_LITERAL("").join(data)
[ "def", "read", "(", "self", ",", "count", ")", ":", "data", "=", "[", "]", "while", "count", ">", "0", ":", "try", ":", "buf", "=", "self", ".", "sock", ".", "recv", "(", "min", "(", "self", ".", "MAX_IO_CHUNK", ",", "count", ")", ")", "except"...
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/scripts/sshbackdoors/rpyc/core/stream.py#L179-L198
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter8-Regression/venv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/ipaddress.py
python
get_mixed_type_key
(obj)
return NotImplemented
Return a key suitable for sorting between networks and addresses. Address and Network objects are not sortable by default; they're fundamentally different so the expression IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24') doesn't make any sense. There are some times however, where you may wish to have ipaddress sort these for you anyway. If you need to do this, you can use this function as the key= argument to sorted(). Args: obj: either a Network or Address object. Returns: appropriate key.
Return a key suitable for sorting between networks and addresses.
[ "Return", "a", "key", "suitable", "for", "sorting", "between", "networks", "and", "addresses", "." ]
def get_mixed_type_key(obj): """Return a key suitable for sorting between networks and addresses. Address and Network objects are not sortable by default; they're fundamentally different so the expression IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24') doesn't make any sense. There are some times however, where you may wish to have ipaddress sort these for you anyway. If you need to do this, you can use this function as the key= argument to sorted(). Args: obj: either a Network or Address object. Returns: appropriate key. """ if isinstance(obj, _BaseNetwork): return obj._get_networks_key() elif isinstance(obj, _BaseAddress): return obj._get_address_key() return NotImplemented
[ "def", "get_mixed_type_key", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "_BaseNetwork", ")", ":", "return", "obj", ".", "_get_networks_key", "(", ")", "elif", "isinstance", "(", "obj", ",", "_BaseAddress", ")", ":", "return", "obj", ".", ...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter8-Regression/venv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/ipaddress.py#L478-L500
cisco/mindmeld
809c36112e9ea8019fe29d54d136ca14eb4fd8db
mindmeld/augmentation.py
python
MultiLingualParaphraser._prepare_inputs
(self, processed_queries)
return unannotated_queries
Removes any markdown formatting in the query Args: queries (list(str)): List of queries to be paraphrased Returns: unannotated queries (list(str))
Removes any markdown formatting in the query
[ "Removes", "any", "markdown", "formatting", "in", "the", "query" ]
def _prepare_inputs(self, processed_queries): """Removes any markdown formatting in the query Args: queries (list(str)): List of queries to be paraphrased Returns: unannotated queries (list(str)) """ unannotated_queries = [processed_query.query.text.strip() for processed_query in processed_queries] return unannotated_queries
[ "def", "_prepare_inputs", "(", "self", ",", "processed_queries", ")", ":", "unannotated_queries", "=", "[", "processed_query", ".", "query", ".", "text", ".", "strip", "(", ")", "for", "processed_query", "in", "processed_queries", "]", "return", "unannotated_queri...
https://github.com/cisco/mindmeld/blob/809c36112e9ea8019fe29d54d136ca14eb4fd8db/mindmeld/augmentation.py#L590-L602
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Tools/msi/msilib.py
python
Directory.start_component
(self, component = None, feature = None, flags = None, keyfile = None, uuid=None)
Add an entry to the Component table, and make this component the current for this directory. If no component name is given, the directory name is used. If no feature is given, the current feature is used. If no flags are given, the directory's default flags are used. If no keyfile is given, the KeyPath is left null in the Component table.
Add an entry to the Component table, and make this component the current for this directory. If no component name is given, the directory name is used. If no feature is given, the current feature is used. If no flags are given, the directory's default flags are used. If no keyfile is given, the KeyPath is left null in the Component table.
[ "Add", "an", "entry", "to", "the", "Component", "table", "and", "make", "this", "component", "the", "current", "for", "this", "directory", ".", "If", "no", "component", "name", "is", "given", "the", "directory", "name", "is", "used", ".", "If", "no", "fe...
def start_component(self, component = None, feature = None, flags = None, keyfile = None, uuid=None): """Add an entry to the Component table, and make this component the current for this directory. If no component name is given, the directory name is used. If no feature is given, the current feature is used. If no flags are given, the directory's default flags are used. If no keyfile is given, the KeyPath is left null in the Component table.""" if flags is None: flags = self.componentflags if uuid is None: uuid = gen_uuid() else: uuid = uuid.upper() if component is None: component = self.logical self.component = component if Win64: flags |= 256 if keyfile: keyid = self.cab.gen_id(self.absolute, keyfile) self.keyfiles[keyfile] = keyid else: keyid = None add_data(self.db, "Component", [(component, uuid, self.logical, flags, None, keyid)]) if feature is None: feature = current_feature add_data(self.db, "FeatureComponents", [(feature.id, component)])
[ "def", "start_component", "(", "self", ",", "component", "=", "None", ",", "feature", "=", "None", ",", "flags", "=", "None", ",", "keyfile", "=", "None", ",", "uuid", "=", "None", ")", ":", "if", "flags", "is", "None", ":", "flags", "=", "self", "...
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Tools/msi/msilib.py#L438-L465
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v7/services/services/group_placement_view_service/client.py
python
GroupPlacementViewServiceClient.parse_common_project_path
(path: str)
return m.groupdict() if m else {}
Parse a project path into its component segments.
Parse a project path into its component segments.
[ "Parse", "a", "project", "path", "into", "its", "component", "segments", "." ]
def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P<project>.+?)$", path) return m.groupdict() if m else {}
[ "def", "parse_common_project_path", "(", "path", ":", "str", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "m", "=", "re", ".", "match", "(", "r\"^projects/(?P<project>.+?)$\"", ",", "path", ")", "return", "m", ".", "groupdict", "(", ")", "if", ...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v7/services/services/group_placement_view_service/client.py#L224-L227
vlomme/Multi-Tacotron-Voice-Cloning
62598a52260146a3da51b9044881e54a99525e53
synthesizer/models/custom_decoder.py
python
CustomDecoder.__init__
(self, cell, helper, initial_state, output_layer=None)
Initialize CustomDecoder. Args: cell: An `RNNCell` instance. helper: A `Helper` instance. initial_state: A (possibly nested tuple of...) tensors and TensorArrays. The initial state of the RNNCell. output_layer: (Optional) An instance of `tf.layers.Layer`, i.e., `tf.layers.Dense`. Optional layer to apply to the RNN output prior to storing the result or sampling. Raises: TypeError: if `cell`, `helper` or `output_layer` have an incorrect type.
Initialize CustomDecoder. Args: cell: An `RNNCell` instance. helper: A `Helper` instance. initial_state: A (possibly nested tuple of...) tensors and TensorArrays. The initial state of the RNNCell. output_layer: (Optional) An instance of `tf.layers.Layer`, i.e., `tf.layers.Dense`. Optional layer to apply to the RNN output prior to storing the result or sampling. Raises: TypeError: if `cell`, `helper` or `output_layer` have an incorrect type.
[ "Initialize", "CustomDecoder", ".", "Args", ":", "cell", ":", "An", "RNNCell", "instance", ".", "helper", ":", "A", "Helper", "instance", ".", "initial_state", ":", "A", "(", "possibly", "nested", "tuple", "of", "...", ")", "tensors", "and", "TensorArrays", ...
def __init__(self, cell, helper, initial_state, output_layer=None): """Initialize CustomDecoder. Args: cell: An `RNNCell` instance. helper: A `Helper` instance. initial_state: A (possibly nested tuple of...) tensors and TensorArrays. The initial state of the RNNCell. output_layer: (Optional) An instance of `tf.layers.Layer`, i.e., `tf.layers.Dense`. Optional layer to apply to the RNN output prior to storing the result or sampling. Raises: TypeError: if `cell`, `helper` or `output_layer` have an incorrect type. """ rnn_cell_impl.assert_like_rnncell(type(cell), cell) if not isinstance(helper, helper_py.Helper): raise TypeError("helper must be a Helper, received: %s" % type(helper)) if (output_layer is not None and not isinstance(output_layer, layers_base.Layer)): raise TypeError( "output_layer must be a Layer, received: %s" % type(output_layer)) self._cell = cell self._helper = helper self._initial_state = initial_state self._output_layer = output_layer
[ "def", "__init__", "(", "self", ",", "cell", ",", "helper", ",", "initial_state", ",", "output_layer", "=", "None", ")", ":", "rnn_cell_impl", ".", "assert_like_rnncell", "(", "type", "(", "cell", ")", ",", "cell", ")", "if", "not", "isinstance", "(", "h...
https://github.com/vlomme/Multi-Tacotron-Voice-Cloning/blob/62598a52260146a3da51b9044881e54a99525e53/synthesizer/models/custom_decoder.py#L28-L51
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter8-Regression/venv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/pyparsing.py
python
And.__init__
( self, exprs, savelist = True )
[]
def __init__( self, exprs, savelist = True ): super(And,self).__init__(exprs, savelist) self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs) self.setWhitespaceChars( self.exprs[0].whiteChars ) self.skipWhitespace = self.exprs[0].skipWhitespace self.callPreparse = True
[ "def", "__init__", "(", "self", ",", "exprs", ",", "savelist", "=", "True", ")", ":", "super", "(", "And", ",", "self", ")", ".", "__init__", "(", "exprs", ",", "savelist", ")", "self", ".", "mayReturnEmpty", "=", "all", "(", "e", ".", "mayReturnEmpt...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter8-Regression/venv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/pyparsing.py#L3349-L3354
Skycrab/weixin-knife
0cea6f645d1a94e45f394c32364dfb545f32b6b6
weixin/lib.py
python
CurlClient.postXmlSSL
(self, xml, url, second=30, cert=True, post=True)
return buff.getvalue()
使用证书
使用证书
[ "使用证书" ]
def postXmlSSL(self, xml, url, second=30, cert=True, post=True): """使用证书""" self.curl.setopt(pycurl.URL, url) self.curl.setopt(pycurl.TIMEOUT, second) #设置证书 #使用证书:cert 与 key 分别属于两个.pem文件 #默认格式为PEM,可以注释 if cert: self.curl.setopt(pycurl.SSLKEYTYPE, "PEM") self.curl.setopt(pycurl.SSLKEY, WxPayConf_pub.SSLKEY_PATH) self.curl.setopt(pycurl.SSLCERTTYPE, "PEM") self.curl.setopt(pycurl.SSLCERT, WxPayConf_pub.SSLCERT_PATH) #post提交方式 if post: self.curl.setopt(pycurl.POST, True) self.curl.setopt(pycurl.POSTFIELDS, xml) buff = StringIO() self.curl.setopt(pycurl.WRITEFUNCTION, buff.write) self.curl.perform() return buff.getvalue()
[ "def", "postXmlSSL", "(", "self", ",", "xml", ",", "url", ",", "second", "=", "30", ",", "cert", "=", "True", ",", "post", "=", "True", ")", ":", "self", ".", "curl", ".", "setopt", "(", "pycurl", ".", "URL", ",", "url", ")", "self", ".", "curl...
https://github.com/Skycrab/weixin-knife/blob/0cea6f645d1a94e45f394c32364dfb545f32b6b6/weixin/lib.py#L134-L154
tensorflow/lingvo
ce10019243d954c3c3ebe739f7589b5eebfdf907
lingvo/tasks/car/point_detector.py
python
PointDetectorBase._Placeholders
(self)
return result
Return a NestedMap of placeholders to fill in for inference. Runs the configured input pipeline to generate the expected shapes and types of the inputs. Returns: A NestedMap of placeholders matching the input structure of the inference model.
Return a NestedMap of placeholders to fill in for inference.
[ "Return", "a", "NestedMap", "of", "placeholders", "to", "fill", "in", "for", "inference", "." ]
def _Placeholders(self): """Return a NestedMap of placeholders to fill in for inference. Runs the configured input pipeline to generate the expected shapes and types of the inputs. Returns: A NestedMap of placeholders matching the input structure of the inference model. """ p = self.params with tf.Graph().as_default(): inputs = self.params.input.Instantiate() # Turn those inputs into placeholders. placeholders = [] for input_shape, dtype in zip(inputs.Shape().Flatten(), inputs.DType().Flatten()): batched_input_shape = [p.inference_batch_size] + input_shape.as_list() placeholders.append(tf.placeholder(dtype, batched_input_shape)) result = inputs.DType().Pack(placeholders) return result
[ "def", "_Placeholders", "(", "self", ")", ":", "p", "=", "self", ".", "params", "with", "tf", ".", "Graph", "(", ")", ".", "as_default", "(", ")", ":", "inputs", "=", "self", ".", "params", ".", "input", ".", "Instantiate", "(", ")", "# Turn those in...
https://github.com/tensorflow/lingvo/blob/ce10019243d954c3c3ebe739f7589b5eebfdf907/lingvo/tasks/car/point_detector.py#L103-L125
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/mpmath/ctx_mp_python.py
python
PythonMPContext.make_mpc
(ctx, v)
return a
[]
def make_mpc(ctx, v): a = new(ctx.mpc) a._mpc_ = v return a
[ "def", "make_mpc", "(", "ctx", ",", "v", ")", ":", "a", "=", "new", "(", "ctx", ".", "mpc", ")", "a", ".", "_mpc_", "=", "v", "return", "a" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/mpmath/ctx_mp_python.py#L600-L603
open-covid-19/data
d7a495f340ec1f82511e6de949a8d799d0a8568c
src/lib/io.py
python
pbar
(*args, **kwargs)
return tqdm(*args, **{**kwargs, **{"disable": os.getenv(GLOBAL_DISABLE_PROGRESS)}})
Helper function used to display a tqdm progress bar respecting global settings for whether all progress bars should be disabled. All arguments are passed through to tqdm but the "disable" option is set accordingly.
Helper function used to display a tqdm progress bar respecting global settings for whether all progress bars should be disabled. All arguments are passed through to tqdm but the "disable" option is set accordingly.
[ "Helper", "function", "used", "to", "display", "a", "tqdm", "progress", "bar", "respecting", "global", "settings", "for", "whether", "all", "progress", "bars", "should", "be", "disabled", ".", "All", "arguments", "are", "passed", "through", "to", "tqdm", "but"...
def pbar(*args, **kwargs) -> tqdm: """ Helper function used to display a tqdm progress bar respecting global settings for whether all progress bars should be disabled. All arguments are passed through to tqdm but the "disable" option is set accordingly. """ return tqdm(*args, **{**kwargs, **{"disable": os.getenv(GLOBAL_DISABLE_PROGRESS)}})
[ "def", "pbar", "(", "*", "args", ",", "*", "*", "kwargs", ")", "->", "tqdm", ":", "return", "tqdm", "(", "*", "args", ",", "*", "*", "{", "*", "*", "kwargs", ",", "*", "*", "{", "\"disable\"", ":", "os", ".", "getenv", "(", "GLOBAL_DISABLE_PROGRE...
https://github.com/open-covid-19/data/blob/d7a495f340ec1f82511e6de949a8d799d0a8568c/src/lib/io.py#L234-L240
thunguyenphuoc/RenderNet
f7e2ec12524820907f4adeae1c645d45f32a76e7
tools/binvox_rw.py
python
dense_to_sparse
(voxel_data, dtype=np.int)
return np.asarray(np.nonzero(voxel_data), dtype)
From dense representation to sparse (coordinate) representation. No coordinate reordering.
From dense representation to sparse (coordinate) representation. No coordinate reordering.
[ "From", "dense", "representation", "to", "sparse", "(", "coordinate", ")", "representation", ".", "No", "coordinate", "reordering", "." ]
def dense_to_sparse(voxel_data, dtype=np.int): """ From dense representation to sparse (coordinate) representation. No coordinate reordering. """ if voxel_data.ndim!=3: raise ValueError('voxel_data is wrong shape; should be 3D array.') return np.asarray(np.nonzero(voxel_data), dtype)
[ "def", "dense_to_sparse", "(", "voxel_data", ",", "dtype", "=", "np", ".", "int", ")", ":", "if", "voxel_data", ".", "ndim", "!=", "3", ":", "raise", "ValueError", "(", "'voxel_data is wrong shape; should be 3D array.'", ")", "return", "np", ".", "asarray", "(...
https://github.com/thunguyenphuoc/RenderNet/blob/f7e2ec12524820907f4adeae1c645d45f32a76e7/tools/binvox_rw.py#L146-L153
glue-viz/glue
840b4c1364b0fa63bf67c914540c93dd71df41e1
glue/core/visual.py
python
VisualAttributes.color
(self)
return self._color
Color specified using Matplotlib notation Specifically, it can be: * A string with a common color (e.g. 'black', 'red', 'orange') * A string containing a float in the rng [0:1] for a shade of gray ('0.0' = black,'1.0' = white) * A tuple of three floats in the rng [0:1] for (R, G, B) * An HTML hexadecimal string (e.g. '#eeefff')
Color specified using Matplotlib notation
[ "Color", "specified", "using", "Matplotlib", "notation" ]
def color(self): """ Color specified using Matplotlib notation Specifically, it can be: * A string with a common color (e.g. 'black', 'red', 'orange') * A string containing a float in the rng [0:1] for a shade of gray ('0.0' = black,'1.0' = white) * A tuple of three floats in the rng [0:1] for (R, G, B) * An HTML hexadecimal string (e.g. '#eeefff') """ return self._color
[ "def", "color", "(", "self", ")", ":", "return", "self", ".", "_color" ]
https://github.com/glue-viz/glue/blob/840b4c1364b0fa63bf67c914540c93dd71df41e1/glue/core/visual.py#L80-L92
Delta-ML/delta
31dfebc8f20b7cb282b62f291ff25a87e403cc86
egs/conll2003/pretrain/v1/local/modeling.py
python
embedding_lookup
(input_ids, vocab_size, embedding_size=128, initializer_range=0.02, word_embedding_name="word_embeddings", use_one_hot_embeddings=False)
return (output, embedding_table)
Looks up words embeddings for id tensor. Args: input_ids: int32 Tensor of shape [batch_size, seq_length] containing word ids. vocab_size: int. Size of the embedding vocabulary. embedding_size: int. Width of the word embeddings. initializer_range: float. Embedding initialization range. word_embedding_name: string. Name of the embedding table. use_one_hot_embeddings: bool. If True, use one-hot method for word embeddings. If False, use `tf.gather()`. Returns: float Tensor of shape [batch_size, seq_length, embedding_size].
Looks up words embeddings for id tensor.
[ "Looks", "up", "words", "embeddings", "for", "id", "tensor", "." ]
def embedding_lookup(input_ids, vocab_size, embedding_size=128, initializer_range=0.02, word_embedding_name="word_embeddings", use_one_hot_embeddings=False): """Looks up words embeddings for id tensor. Args: input_ids: int32 Tensor of shape [batch_size, seq_length] containing word ids. vocab_size: int. Size of the embedding vocabulary. embedding_size: int. Width of the word embeddings. initializer_range: float. Embedding initialization range. word_embedding_name: string. Name of the embedding table. use_one_hot_embeddings: bool. If True, use one-hot method for word embeddings. If False, use `tf.gather()`. Returns: float Tensor of shape [batch_size, seq_length, embedding_size]. """ # This function assumes that the input is of shape [batch_size, seq_length, # num_inputs]. # # If the input is a 2D tensor of shape [batch_size, seq_length], we # reshape to [batch_size, seq_length, 1]. if input_ids.shape.ndims == 2: input_ids = tf.expand_dims(input_ids, axis=[-1]) embedding_table = tf.compat.v1.get_variable( name=word_embedding_name, shape=[vocab_size, embedding_size], initializer=create_initializer(initializer_range)) flat_input_ids = tf.reshape(input_ids, [-1]) if use_one_hot_embeddings: one_hot_input_ids = tf.one_hot(flat_input_ids, depth=vocab_size) output = tf.matmul(one_hot_input_ids, embedding_table) else: output = tf.gather(embedding_table, flat_input_ids) input_shape = get_shape_list(input_ids) output = tf.reshape(output, input_shape[0:-1] + [input_shape[-1] * embedding_size]) return (output, embedding_table)
[ "def", "embedding_lookup", "(", "input_ids", ",", "vocab_size", ",", "embedding_size", "=", "128", ",", "initializer_range", "=", "0.02", ",", "word_embedding_name", "=", "\"word_embeddings\"", ",", "use_one_hot_embeddings", "=", "False", ")", ":", "# This function as...
https://github.com/Delta-ML/delta/blob/31dfebc8f20b7cb282b62f291ff25a87e403cc86/egs/conll2003/pretrain/v1/local/modeling.py#L383-L428
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
packages/source/nova/nova/service.py
python
Launcher.launch_server
(self, server)
Load and start the given server. :param server: The server you would like to start. :returns: None
Load and start the given server.
[ "Load", "and", "start", "the", "given", "server", "." ]
def launch_server(self, server): """Load and start the given server. :param server: The server you would like to start. :returns: None """ if self.backdoor_port is not None: server.backdoor_port = self.backdoor_port gt = eventlet.spawn(self.run_server, server) self._services.append(gt)
[ "def", "launch_server", "(", "self", ",", "server", ")", ":", "if", "self", ".", "backdoor_port", "is", "not", "None", ":", "server", ".", "backdoor_port", "=", "self", ".", "backdoor_port", "gt", "=", "eventlet", ".", "spawn", "(", "self", ".", "run_ser...
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/nova/nova/service.py#L150-L160
holoviz/holoviews
cc6b27f01710402fdfee2aeef1507425ca78c91f
holoviews/core/data/spatialpandas.py
python
from_shapely
(data)
return data
Converts shapely based data formats to spatialpandas.GeoDataFrame. Args: data: A list of shapely objects or dictionaries containing shapely objects Returns: A GeoDataFrame containing the shapely geometry data.
Converts shapely based data formats to spatialpandas.GeoDataFrame.
[ "Converts", "shapely", "based", "data", "formats", "to", "spatialpandas", ".", "GeoDataFrame", "." ]
def from_shapely(data): """Converts shapely based data formats to spatialpandas.GeoDataFrame. Args: data: A list of shapely objects or dictionaries containing shapely objects Returns: A GeoDataFrame containing the shapely geometry data. """ from spatialpandas import GeoDataFrame, GeoSeries from shapely.geometry.base import BaseGeometry if not data: pass elif all(isinstance(d, BaseGeometry) for d in data): data = GeoSeries(data).to_frame() elif all(isinstance(d, dict) and 'geometry' in d and isinstance(d['geometry'], BaseGeometry) for d in data): new_data = {col: [] for col in data[0]} for d in data: for col, val in d.items(): new_data[col].append(val if isscalar(val) or isinstance(val, BaseGeometry) else np.asarray(val)) new_data['geometry'] = GeoSeries(new_data['geometry']) data = GeoDataFrame(new_data) return data
[ "def", "from_shapely", "(", "data", ")", ":", "from", "spatialpandas", "import", "GeoDataFrame", ",", "GeoSeries", "from", "shapely", ".", "geometry", ".", "base", "import", "BaseGeometry", "if", "not", "data", ":", "pass", "elif", "all", "(", "isinstance", ...
https://github.com/holoviz/holoviews/blob/cc6b27f01710402fdfee2aeef1507425ca78c91f/holoviews/core/data/spatialpandas.py#L854-L880
ckan/ckan
b3b01218ad88ed3fb914b51018abe8b07b07bff3
ckan/plugins/interfaces.py
python
IDatasetForm.new_template
(self, package_type)
u'''Return the path to the template for the new dataset page. The path should be relative to the plugin's templates dir, e.g. ``'package/new.html'``. :rtype: string
u'''Return the path to the template for the new dataset page.
[ "u", "Return", "the", "path", "to", "the", "template", "for", "the", "new", "dataset", "page", "." ]
def new_template(self, package_type): u'''Return the path to the template for the new dataset page. The path should be relative to the plugin's templates dir, e.g. ``'package/new.html'``. :rtype: string '''
[ "def", "new_template", "(", "self", ",", "package_type", ")", ":" ]
https://github.com/ckan/ckan/blob/b3b01218ad88ed3fb914b51018abe8b07b07bff3/ckan/plugins/interfaces.py#L1217-L1225
daveleroy/sublime_debugger
3e4d2cf6519ec846cf655b30d8da4732807de54e
modules/libs/pywinpty/st3_windows_x32/winpty/ptyprocess.py
python
PtyProcess.spawn
(cls, argv, cwd=None, env=None, dimensions=(24, 80))
return inst
Start the given command in a child process in a pseudo terminal. This does all the setting up the pty, and returns an instance of PtyProcess. Dimensions of the psuedoterminal used for the subprocess can be specified as a tuple (rows, cols), or the default (24, 80) will be used.
Start the given command in a child process in a pseudo terminal.
[ "Start", "the", "given", "command", "in", "a", "child", "process", "in", "a", "pseudo", "terminal", "." ]
def spawn(cls, argv, cwd=None, env=None, dimensions=(24, 80)): """Start the given command in a child process in a pseudo terminal. This does all the setting up the pty, and returns an instance of PtyProcess. Dimensions of the psuedoterminal used for the subprocess can be specified as a tuple (rows, cols), or the default (24, 80) will be used. """ if isinstance(argv, str): argv = shlex.split(argv, posix=False) if not isinstance(argv, (list, tuple)): raise TypeError("Expected a list or tuple for argv, got %r" % argv) # Shallow copy of argv so we can modify it argv = argv[:] command = argv[0] env = env or os.environ path = env.get('PATH', os.defpath) command_with_path = which(command, path=path) if command_with_path is None: raise FileNotFoundError( 'The command was not found or was not ' + 'executable: %s.' % command ) command = command_with_path argv[0] = command cmdline = ' ' + subprocess.list2cmdline(argv[1:]) cwd = cwd or os.getcwd() proc = PTY(dimensions[1], dimensions[0]) # Create the environemnt string. envStrs = [] for (key, value) in env.items(): envStrs.append('%s=%s' % (key, value)) env = '\0'.join(envStrs) + '\0' if PY2: command = _unicode(command) cwd = _unicode(cwd) cmdline = _unicode(cmdline) env = _unicode(env) if len(argv) == 1: proc.spawn(command, cwd=cwd, env=env) else: proc.spawn(command, cwd=cwd, env=env, cmdline=cmdline) inst = cls(proc) inst._winsize = dimensions # Set some informational attributes inst.argv = argv if env is not None: inst.env = env if cwd is not None: inst.launch_dir = cwd return inst
[ "def", "spawn", "(", "cls", ",", "argv", ",", "cwd", "=", "None", ",", "env", "=", "None", ",", "dimensions", "=", "(", "24", ",", "80", ")", ")", ":", "if", "isinstance", "(", "argv", ",", "str", ")", ":", "argv", "=", "shlex", ".", "split", ...
https://github.com/daveleroy/sublime_debugger/blob/3e4d2cf6519ec846cf655b30d8da4732807de54e/modules/libs/pywinpty/st3_windows_x32/winpty/ptyprocess.py#L63-L125
Samsung/cotopaxi
d19178b1235017257fec20d0a41edc918de55574
cotopaxi/http_utils.py
python
HTTPTester.response_parser
()
return HTTPResponse
Provide Scapy class implementing parsing of protocol responses.
Provide Scapy class implementing parsing of protocol responses.
[ "Provide", "Scapy", "class", "implementing", "parsing", "of", "protocol", "responses", "." ]
def response_parser(): """Provide Scapy class implementing parsing of protocol responses.""" return HTTPResponse
[ "def", "response_parser", "(", ")", ":", "return", "HTTPResponse" ]
https://github.com/Samsung/cotopaxi/blob/d19178b1235017257fec20d0a41edc918de55574/cotopaxi/http_utils.py#L72-L74
IBM/pytorchpipe
9cb17271666061cb19fe24197ecd5e4c8d32c5da
ptp/components/losses/loss.py
python
Loss.collect_statistics
(self, stat_col, data_streams)
Collects statistics (loss) for given episode. :param stat_col: ``StatisticsCollector``.
Collects statistics (loss) for given episode.
[ "Collects", "statistics", "(", "loss", ")", "for", "given", "episode", "." ]
def collect_statistics(self, stat_col, data_streams): """ Collects statistics (loss) for given episode. :param stat_col: ``StatisticsCollector``. """ stat_col[self.key_loss] = data_streams[self.key_loss].item()
[ "def", "collect_statistics", "(", "self", ",", "stat_col", ",", "data_streams", ")", ":", "stat_col", "[", "self", ".", "key_loss", "]", "=", "data_streams", "[", "self", ".", "key_loss", "]", ".", "item", "(", ")" ]
https://github.com/IBM/pytorchpipe/blob/9cb17271666061cb19fe24197ecd5e4c8d32c5da/ptp/components/losses/loss.py#L73-L80
rcorcs/NatI
fdf014f4292afdc95250add7b6658468043228e1
en/parser/nltk_lite/contrib/toolbox/lexicon.py
python
Lexicon.get_entries
(self)
This method obtains all of the entries found in a parsed Shoebox lexicon. @return: all of the entries in the Lexicon @rtype: list of Entry objects
This method obtains all of the entries found in a parsed Shoebox lexicon.
[ "This", "method", "obtains", "all", "of", "the", "entries", "found", "in", "a", "parsed", "Shoebox", "lexicon", "." ]
def get_entries(self): """ This method obtains all of the entries found in a parsed Shoebox lexicon. @return: all of the entries in the Lexicon @rtype: list of Entry objects """ keys = self._entries.keys() keys.sort() for k in keys : v = self._entries[k] for e in v : yield e
[ "def", "get_entries", "(", "self", ")", ":", "keys", "=", "self", ".", "_entries", ".", "keys", "(", ")", "keys", ".", "sort", "(", ")", "for", "k", "in", "keys", ":", "v", "=", "self", ".", "_entries", "[", "k", "]", "for", "e", "in", "v", "...
https://github.com/rcorcs/NatI/blob/fdf014f4292afdc95250add7b6658468043228e1/en/parser/nltk_lite/contrib/toolbox/lexicon.py#L62-L75
nipreps/mriqc
ad8813035136acc1a80c96ac1fbbdde1d82b14ee
mriqc/reports/group.py
python
_format_labels
(row, id_labels)
return "_".join(crow)
format participant labels
format participant labels
[ "format", "participant", "labels" ]
def _format_labels(row, id_labels): """format participant labels""" crow = [] for col_id, prefix in list(BIDS_COMP.items()): if col_id in id_labels: crow.append("%s-%s" % (prefix, row[[col_id]].values[0])) return "_".join(crow)
[ "def", "_format_labels", "(", "row", ",", "id_labels", ")", ":", "crow", "=", "[", "]", "for", "col_id", ",", "prefix", "in", "list", "(", "BIDS_COMP", ".", "items", "(", ")", ")", ":", "if", "col_id", "in", "id_labels", ":", "crow", ".", "append", ...
https://github.com/nipreps/mriqc/blob/ad8813035136acc1a80c96ac1fbbdde1d82b14ee/mriqc/reports/group.py#L294-L301
google-research/sound-separation
0b23ae22123b041b9538295f32a92151cb77bff9
models/train/signal_util.py
python
static_or_dynamic_dim_size
(tensor, i)
return (static_shape[i].value if hasattr(static_shape[i], 'value') else static_shape[i]) or dyn_shape[i]
Static size for dimension `i` if available, otherwise dynamic size.
Static size for dimension `i` if available, otherwise dynamic size.
[ "Static", "size", "for", "dimension", "i", "if", "available", "otherwise", "dynamic", "size", "." ]
def static_or_dynamic_dim_size(tensor, i): """Static size for dimension `i` if available, otherwise dynamic size.""" static_shape = tensor.shape dyn_shape = tf.shape(tensor) return (static_shape[i].value if hasattr(static_shape[i], 'value') else static_shape[i]) or dyn_shape[i]
[ "def", "static_or_dynamic_dim_size", "(", "tensor", ",", "i", ")", ":", "static_shape", "=", "tensor", ".", "shape", "dyn_shape", "=", "tf", ".", "shape", "(", "tensor", ")", "return", "(", "static_shape", "[", "i", "]", ".", "value", "if", "hasattr", "(...
https://github.com/google-research/sound-separation/blob/0b23ae22123b041b9538295f32a92151cb77bff9/models/train/signal_util.py#L20-L25
NoGameNoLife00/mybolg
afe17ea5bfe405e33766e5682c43a4262232ee12
libs/jinja2/environment.py
python
Environment._generate
(self, source, name, filename, defer_init=False)
return generate(source, self, name, filename, defer_init=defer_init)
Internal hook that can be overridden to hook a different generate method in. .. versionadded:: 2.5
Internal hook that can be overridden to hook a different generate method in.
[ "Internal", "hook", "that", "can", "be", "overridden", "to", "hook", "a", "different", "generate", "method", "in", "." ]
def _generate(self, source, name, filename, defer_init=False): """Internal hook that can be overridden to hook a different generate method in. .. versionadded:: 2.5 """ return generate(source, self, name, filename, defer_init=defer_init)
[ "def", "_generate", "(", "self", ",", "source", ",", "name", ",", "filename", ",", "defer_init", "=", "False", ")", ":", "return", "generate", "(", "source", ",", "self", ",", "name", ",", "filename", ",", "defer_init", "=", "defer_init", ")" ]
https://github.com/NoGameNoLife00/mybolg/blob/afe17ea5bfe405e33766e5682c43a4262232ee12/libs/jinja2/environment.py#L498-L504
jtriley/StarCluster
bc7c950e73f193eac9aab986b6764939cfdad978
starcluster/cluster.py
python
ClusterValidator.validate_zone
(self)
return True
Validates that the cluster's availability zone exists and is available. The 'zone' property additionally checks that all EBS volumes are in the same zone and that the cluster's availability zone setting, if specified, matches the EBS volume(s) zone.
Validates that the cluster's availability zone exists and is available. The 'zone' property additionally checks that all EBS volumes are in the same zone and that the cluster's availability zone setting, if specified, matches the EBS volume(s) zone.
[ "Validates", "that", "the", "cluster", "s", "availability", "zone", "exists", "and", "is", "available", ".", "The", "zone", "property", "additionally", "checks", "that", "all", "EBS", "volumes", "are", "in", "the", "same", "zone", "and", "that", "the", "clus...
def validate_zone(self): """ Validates that the cluster's availability zone exists and is available. The 'zone' property additionally checks that all EBS volumes are in the same zone and that the cluster's availability zone setting, if specified, matches the EBS volume(s) zone. """ zone = self.cluster.zone if zone and zone.state != 'available': raise exception.ClusterValidationError( "The '%s' availability zone is not available at this time" % zone.name) return True
[ "def", "validate_zone", "(", "self", ")", ":", "zone", "=", "self", ".", "cluster", ".", "zone", "if", "zone", "and", "zone", ".", "state", "!=", "'available'", ":", "raise", "exception", ".", "ClusterValidationError", "(", "\"The '%s' availability zone is not a...
https://github.com/jtriley/StarCluster/blob/bc7c950e73f193eac9aab986b6764939cfdad978/starcluster/cluster.py#L1919-L1931
PokemonGoF/PokemonGo-Bot-Desktop
4bfa94f0183406c6a86f93645eff7abd3ad4ced8
build/pywin/Lib/posixpath.py
python
realpath
(filename)
return abspath(path)
Return the canonical path of the specified filename, eliminating any symbolic links encountered in the path.
Return the canonical path of the specified filename, eliminating any symbolic links encountered in the path.
[ "Return", "the", "canonical", "path", "of", "the", "specified", "filename", "eliminating", "any", "symbolic", "links", "encountered", "in", "the", "path", "." ]
def realpath(filename): """Return the canonical path of the specified filename, eliminating any symbolic links encountered in the path.""" path, ok = _joinrealpath('', filename, {}) return abspath(path)
[ "def", "realpath", "(", "filename", ")", ":", "path", ",", "ok", "=", "_joinrealpath", "(", "''", ",", "filename", ",", "{", "}", ")", "return", "abspath", "(", "path", ")" ]
https://github.com/PokemonGoF/PokemonGo-Bot-Desktop/blob/4bfa94f0183406c6a86f93645eff7abd3ad4ced8/build/pywin/Lib/posixpath.py#L372-L376
llSourcell/AI_Artist
3038c06c2e389b9c919c881c9a169efe2fd7810e
lib/python2.7/site-packages/pip/req/req_install.py
python
InstallRequirement.remove_temporary_source
(self)
Remove the source files from this requirement, if they are marked for deletion
Remove the source files from this requirement, if they are marked for deletion
[ "Remove", "the", "source", "files", "from", "this", "requirement", "if", "they", "are", "marked", "for", "deletion" ]
def remove_temporary_source(self): """Remove the source files from this requirement, if they are marked for deletion""" if self.source_dir and os.path.exists( os.path.join(self.source_dir, PIP_DELETE_MARKER_FILENAME)): logger.debug('Removing source in %s', self.source_dir) rmtree(self.source_dir) self.source_dir = None if self._temp_build_dir and os.path.exists(self._temp_build_dir): rmtree(self._temp_build_dir) self._temp_build_dir = None
[ "def", "remove_temporary_source", "(", "self", ")", ":", "if", "self", ".", "source_dir", "and", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "self", ".", "source_dir", ",", "PIP_DELETE_MARKER_FILENAME", ")", ")", ":", "log...
https://github.com/llSourcell/AI_Artist/blob/3038c06c2e389b9c919c881c9a169efe2fd7810e/lib/python2.7/site-packages/pip/req/req_install.py#L945-L955
Blizzard/heroprotocol
3d36eaf44fc4c8ff3331c2ae2f1dc08a94535f1c
heroprotocol/versions/protocol80293.py
python
decode_replay_header
(contents)
return decoder.instance(replay_header_typeid)
Decodes and return the replay header from the contents byte string.
Decodes and return the replay header from the contents byte string.
[ "Decodes", "and", "return", "the", "replay", "header", "from", "the", "contents", "byte", "string", "." ]
def decode_replay_header(contents): """Decodes and return the replay header from the contents byte string.""" decoder = VersionedDecoder(contents, typeinfos) return decoder.instance(replay_header_typeid)
[ "def", "decode_replay_header", "(", "contents", ")", ":", "decoder", "=", "VersionedDecoder", "(", "contents", ",", "typeinfos", ")", "return", "decoder", ".", "instance", "(", "replay_header_typeid", ")" ]
https://github.com/Blizzard/heroprotocol/blob/3d36eaf44fc4c8ff3331c2ae2f1dc08a94535f1c/heroprotocol/versions/protocol80293.py#L434-L437
akanazawa/hmr
f149abeb0a7e2a3412eb68274a94a9232f7cb667
src/tf_smpl/batch_lbs.py
python
batch_global_rigid_transformation
(Rs, Js, parent, rotate_base=False)
Computes absolute joint locations given pose. rotate_base: if True, rotates the global rotation by 90 deg in x axis. if False, this is the original SMPL coordinate. Args: Rs: N x 24 x 3 x 3 rotation vector of K joints Js: N x 24 x 3, joint locations before posing parent: 24 holding the parent id for each index Returns new_J : `Tensor`: N x 24 x 3 location of absolute joints A : `Tensor`: N x 24 4 x 4 relative joint transformations for LBS.
Computes absolute joint locations given pose.
[ "Computes", "absolute", "joint", "locations", "given", "pose", "." ]
def batch_global_rigid_transformation(Rs, Js, parent, rotate_base=False): """ Computes absolute joint locations given pose. rotate_base: if True, rotates the global rotation by 90 deg in x axis. if False, this is the original SMPL coordinate. Args: Rs: N x 24 x 3 x 3 rotation vector of K joints Js: N x 24 x 3, joint locations before posing parent: 24 holding the parent id for each index Returns new_J : `Tensor`: N x 24 x 3 location of absolute joints A : `Tensor`: N x 24 4 x 4 relative joint transformations for LBS. """ with tf.name_scope("batch_forward_kinematics", [Rs, Js]): N = Rs.shape[0].value if rotate_base: print('Flipping the SMPL coordinate frame!!!!') rot_x = tf.constant( [[1, 0, 0], [0, -1, 0], [0, 0, -1]], dtype=Rs.dtype) rot_x = tf.reshape(tf.tile(rot_x, [N, 1]), [N, 3, 3]) root_rotation = tf.matmul(Rs[:, 0, :, :], rot_x) else: root_rotation = Rs[:, 0, :, :] # Now Js is N x 24 x 3 x 1 Js = tf.expand_dims(Js, -1) def make_A(R, t, name=None): # Rs is N x 3 x 3, ts is N x 3 x 1 with tf.name_scope(name, "Make_A", [R, t]): R_homo = tf.pad(R, [[0, 0], [0, 1], [0, 0]]) t_homo = tf.concat([t, tf.ones([N, 1, 1])], 1) return tf.concat([R_homo, t_homo], 2) A0 = make_A(root_rotation, Js[:, 0]) results = [A0] for i in range(1, parent.shape[0]): j_here = Js[:, i] - Js[:, parent[i]] A_here = make_A(Rs[:, i], j_here) res_here = tf.matmul( results[parent[i]], A_here, name="propA%d" % i) results.append(res_here) # 10 x 24 x 4 x 4 results = tf.stack(results, axis=1) new_J = results[:, :, :3, 3] # --- Compute relative A: Skinning is based on # how much the bone moved (not the final location of the bone) # but (final_bone - init_bone) # --- Js_w0 = tf.concat([Js, tf.zeros([N, 24, 1, 1])], 2) init_bone = tf.matmul(results, Js_w0) # Append empty 4 x 3: init_bone = tf.pad(init_bone, [[0, 0], [0, 0], [0, 0], [3, 0]]) A = results - init_bone return new_J, A
[ "def", "batch_global_rigid_transformation", "(", "Rs", ",", "Js", ",", "parent", ",", "rotate_base", "=", "False", ")", ":", "with", "tf", ".", "name_scope", "(", "\"batch_forward_kinematics\"", ",", "[", "Rs", ",", "Js", "]", ")", ":", "N", "=", "Rs", "...
https://github.com/akanazawa/hmr/blob/f149abeb0a7e2a3412eb68274a94a9232f7cb667/src/tf_smpl/batch_lbs.py#L91-L152
jimmysong/programmingbitcoin
3fba6b992ece443e4256df057595cfbe91edda75
code-ch11/tx.py
python
TxIn.script_pubkey
(self, testnet=False)
return tx.tx_outs[self.prev_index].script_pubkey
Get the ScriptPubKey by looking up the tx hash Returns a Script object
Get the ScriptPubKey by looking up the tx hash Returns a Script object
[ "Get", "the", "ScriptPubKey", "by", "looking", "up", "the", "tx", "hash", "Returns", "a", "Script", "object" ]
def script_pubkey(self, testnet=False): '''Get the ScriptPubKey by looking up the tx hash Returns a Script object ''' # use self.fetch_tx to get the transaction tx = self.fetch_tx(testnet=testnet) # get the output at self.prev_index # return the script_pubkey property return tx.tx_outs[self.prev_index].script_pubkey
[ "def", "script_pubkey", "(", "self", ",", "testnet", "=", "False", ")", ":", "# use self.fetch_tx to get the transaction", "tx", "=", "self", ".", "fetch_tx", "(", "testnet", "=", "testnet", ")", "# get the output at self.prev_index", "# return the script_pubkey property"...
https://github.com/jimmysong/programmingbitcoin/blob/3fba6b992ece443e4256df057595cfbe91edda75/code-ch11/tx.py#L344-L352
osmr/imgclsmob
f2993d3ce73a2f7ddba05da3891defb08547d504
tensorflow_/tensorflowcv/models/mobilenetv2.py
python
linear_bottleneck
(x, in_channels, out_channels, strides, expansion, training, data_format, name="linear_bottleneck")
return x
So-called 'Linear Bottleneck' layer. It is used as a MobileNetV2 unit. Parameters: ---------- x : Tensor Input tensor. in_channels : int Number of input channels. out_channels : int Number of output channels. strides : int or tuple/list of 2 int Strides of the convolution. expansion : bool Whether do expansion of channels. training : bool, or a TensorFlow boolean scalar tensor Whether to return the output in training mode or in inference mode. data_format : str The ordering of the dimensions in tensors. name : str, default 'linear_bottleneck' Unit name. Returns: ------- Tensor Resulted tensor.
So-called 'Linear Bottleneck' layer. It is used as a MobileNetV2 unit.
[ "So", "-", "called", "Linear", "Bottleneck", "layer", ".", "It", "is", "used", "as", "a", "MobileNetV2", "unit", "." ]
def linear_bottleneck(x, in_channels, out_channels, strides, expansion, training, data_format, name="linear_bottleneck"): """ So-called 'Linear Bottleneck' layer. It is used as a MobileNetV2 unit. Parameters: ---------- x : Tensor Input tensor. in_channels : int Number of input channels. out_channels : int Number of output channels. strides : int or tuple/list of 2 int Strides of the convolution. expansion : bool Whether do expansion of channels. training : bool, or a TensorFlow boolean scalar tensor Whether to return the output in training mode or in inference mode. data_format : str The ordering of the dimensions in tensors. name : str, default 'linear_bottleneck' Unit name. Returns: ------- Tensor Resulted tensor. """ residual = (in_channels == out_channels) and (strides == 1) mid_channels = in_channels * 6 if expansion else in_channels if residual: identity = x x = conv1x1_block( x=x, in_channels=in_channels, out_channels=mid_channels, activation="relu6", training=training, data_format=data_format, name=name + "/conv1") x = dwconv3x3_block( x=x, in_channels=mid_channels, out_channels=mid_channels, strides=strides, activation="relu6", training=training, data_format=data_format, name=name + "/conv2") x = conv1x1_block( x=x, in_channels=mid_channels, out_channels=out_channels, activation=None, training=training, data_format=data_format, name=name + "/conv3") if residual: x = x + identity return x
[ "def", "linear_bottleneck", "(", "x", ",", "in_channels", ",", "out_channels", ",", "strides", ",", "expansion", ",", "training", ",", "data_format", ",", "name", "=", "\"linear_bottleneck\"", ")", ":", "residual", "=", "(", "in_channels", "==", "out_channels", ...
https://github.com/osmr/imgclsmob/blob/f2993d3ce73a2f7ddba05da3891defb08547d504/tensorflow_/tensorflowcv/models/mobilenetv2.py#L13-L83
edfungus/Crouton
ada98b3930192938a48909072b45cb84b945f875
clients/esp8266_clients/venv/lib/python2.7/site-packages/pkg_resources/__init__.py
python
get_provider
(moduleOrReq)
return _find_adapter(_provider_factories, loader)(module)
Return an IResourceProvider for the named module or requirement
Return an IResourceProvider for the named module or requirement
[ "Return", "an", "IResourceProvider", "for", "the", "named", "module", "or", "requirement" ]
def get_provider(moduleOrReq): """Return an IResourceProvider for the named module or requirement""" if isinstance(moduleOrReq, Requirement): return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0] try: module = sys.modules[moduleOrReq] except KeyError: __import__(moduleOrReq) module = sys.modules[moduleOrReq] loader = getattr(module, '__loader__', None) return _find_adapter(_provider_factories, loader)(module)
[ "def", "get_provider", "(", "moduleOrReq", ")", ":", "if", "isinstance", "(", "moduleOrReq", ",", "Requirement", ")", ":", "return", "working_set", ".", "find", "(", "moduleOrReq", ")", "or", "require", "(", "str", "(", "moduleOrReq", ")", ")", "[", "0", ...
https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/esp8266_clients/venv/lib/python2.7/site-packages/pkg_resources/__init__.py#L428-L438
graalvm/mx
29c0debab406352df3af246be2f8973be5db69ae
mx_compat.py
python
MxCompatibility500.__str__
(self)
return str("MxCompatibility({})".format(self.version()))
[]
def __str__(self): return str("MxCompatibility({})".format(self.version()))
[ "def", "__str__", "(", "self", ")", ":", "return", "str", "(", "\"MxCompatibility({})\"", ".", "format", "(", "self", ".", "version", "(", ")", ")", ")" ]
https://github.com/graalvm/mx/blob/29c0debab406352df3af246be2f8973be5db69ae/mx_compat.py#L157-L158
nopernik/mpDNS
b17dc39e7068406df82cb3431b3042e74e520cf9
circuits/web/parsers/multipart.py
python
MultiDict.__contains__
(self, key)
return key in self.dict
[]
def __contains__(self, key): return key in self.dict
[ "def", "__contains__", "(", "self", ",", "key", ")", ":", "return", "key", "in", "self", ".", "dict" ]
https://github.com/nopernik/mpDNS/blob/b17dc39e7068406df82cb3431b3042e74e520cf9/circuits/web/parsers/multipart.py#L80-L81
plotdevice/plotdevice
598f66a19cd58b8cfea8295024998b322ed66adf
plotdevice/lib/foundry.py
python
parse_display_name
(dname)
return weight, wgt_val, width, wid_val, variant
Try to extract style attributes from the font's display name
Try to extract style attributes from the font's display name
[ "Try", "to", "extract", "style", "attributes", "from", "the", "font", "s", "display", "name" ]
def parse_display_name(dname): """Try to extract style attributes from the font's display name""" # break the string on spaces and on lc/uc transitions elts = filter(None, re.sub(r'(?<=[^ ])([A-Z][a-z]+)',r' \1',dname).split(' ')) # disregard the first italic-y word in the name (if any) for i in xrange(len(elts)-1,-1,-1): # look for full italic/oblique/slanted spellings first if italicky(elts[i], strict=True): elts.pop(i) break else: # if one wasn't found, settle for an it/a/l/ic/s fragment for i in xrange(len(elts)-1,-1,-1): if italicky(elts[i], strict=False): elts.pop(i) break # next search for width-y words width = None wid_val = 0 for i in xrange(len(elts)-2,-1,-1): # first look for modifier+width combinations prefix, suffix = elts[i:i+2] if widthy(prefix+suffix) and sanitized(prefix) in wid_mods: if sanitized(prefix)=='semi': width = prefix + suffix.lower() else: width = " ".join([prefix,suffix]) _, wid_val = standardized('width', width) del elts[i:i+2] break else: # otherwise just look for a single-word width (leave width==None if no match) for i in xrange(len(elts)-1,-1,-1): if widthy(elts[i]): width = elts[i] _, wid_val = standardized('width', width) elts.pop(i) break else: wid_val = 0 # search for weighty words in what's left weight = None wgt_val = 5 for i in xrange(len(elts)-2,-1,-1): # first look for modifier+weight combinations prefix, suffix = elts[i:i+2] if weighty(prefix+suffix) and sanitized(prefix) in wgt_mods: spacer = '' if prefix.lower() in ('semi','demi') else ' ' weight = spacer.join([prefix,suffix]).title() _, wgt_val = standardized('weight', weight) del elts[i:i+2] break else: # otherwise just look for a single-word weight (leave weight==None if no match) for i in xrange(len(elts)-1,-1,-1): if weighty(elts[i]): weight = elts[i] _, wgt_val = standardized('weight', weight) # the standard weights allow leaving out the `bold' and just using # a modifier name. fill that back in... if sanitized(weight) in wgt_mods: suffix = 'bold' if sanitized(weight) in ('semi','demi') else ' Bold' weight += suffix elts.pop(i) break # concat all the non-filtered text as the `variant` variant = None if elts: variant = "".join(elts) return weight, wgt_val, width, wid_val, variant
[ "def", "parse_display_name", "(", "dname", ")", ":", "# break the string on spaces and on lc/uc transitions", "elts", "=", "filter", "(", "None", ",", "re", ".", "sub", "(", "r'(?<=[^ ])([A-Z][a-z]+)'", ",", "r' \\1'", ",", "dname", ")", ".", "split", "(", "' '", ...
https://github.com/plotdevice/plotdevice/blob/598f66a19cd58b8cfea8295024998b322ed66adf/plotdevice/lib/foundry.py#L447-L521
lambdaji/tf_repos
b531ff12cdab65acc9551025f73fade2b6f425a7
DeepMTL/Model_pipeline/DeepCvrMTL.py
python
input_fn
(filenames, batch_size=32, num_epochs=1, perform_shuffle=False)
return batch_features, batch_labels
[]
def input_fn(filenames, batch_size=32, num_epochs=1, perform_shuffle=False): print('Parsing', filenames) def _parse_fn(record): features = { "y": tf.FixedLenFeature([], tf.float32), "z": tf.FixedLenFeature([], tf.float32), "feat_ids": tf.FixedLenFeature([FLAGS.field_size], tf.int64), #"feat_vals": tf.FixedLenFeature([None], tf.float32), "u_catids": tf.VarLenFeature(tf.int64), "u_catvals": tf.VarLenFeature(tf.float32), "u_shopids": tf.VarLenFeature(tf.int64), "u_shopvals": tf.VarLenFeature(tf.float32), "u_intids": tf.VarLenFeature(tf.int64), "u_intvals": tf.VarLenFeature(tf.float32), "u_brandids": tf.VarLenFeature(tf.int64), "u_brandvals": tf.VarLenFeature(tf.float32), "a_catids": tf.FixedLenFeature([], tf.int64), "a_shopids": tf.FixedLenFeature([], tf.int64), "a_brandids": tf.FixedLenFeature([], tf.int64), "a_intids": tf.VarLenFeature(tf.int64) } parsed = tf.parse_single_example(record, features) y = parsed.pop('y') z = parsed.pop('z') return parsed, {"y": y, "z": z} # Extract lines from input files using the Dataset API, can pass one filename or filename list dataset = tf.data.TFRecordDataset(filenames).map(_parse_fn, num_parallel_calls=10).prefetch(500000) # multi-thread pre-process then prefetch # Randomizes input using a window of 256 elements (read into memory) if perform_shuffle: dataset = dataset.shuffle(buffer_size=256) # epochs from blending together. dataset = dataset.repeat(num_epochs) dataset = dataset.batch(batch_size) # Batch size to use #dataset = dataset.padded_batch(batch_size, padded_shapes=({"feeds_ids": [None], "feeds_vals": [None], "title_ids": [None]}, [None])) #不定长补齐 #return dataset.make_one_shot_iterator() iterator = dataset.make_one_shot_iterator() batch_features, batch_labels = iterator.get_next() #return tf.reshape(batch_ids,shape=[-1,field_size]), tf.reshape(batch_vals,shape=[-1,field_size]), batch_labels return batch_features, batch_labels
[ "def", "input_fn", "(", "filenames", ",", "batch_size", "=", "32", ",", "num_epochs", "=", "1", ",", "perform_shuffle", "=", "False", ")", ":", "print", "(", "'Parsing'", ",", "filenames", ")", "def", "_parse_fn", "(", "record", ")", ":", "features", "="...
https://github.com/lambdaji/tf_repos/blob/b531ff12cdab65acc9551025f73fade2b6f425a7/DeepMTL/Model_pipeline/DeepCvrMTL.py#L63-L105
tensorflow/models
6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3
official/legacy/detection/utils/box_utils.py
python
yxyx_to_xywh
(boxes)
return new_boxes
Converts boxes from ymin, xmin, ymax, xmax to xmin, ymin, width, height. Args: boxes: a numpy array whose last dimension is 4 representing the coordinates of boxes in ymin, xmin, ymax, xmax order. Returns: boxes: a numpy array whose shape is the same as `boxes` in new format. Raises: ValueError: If the last dimension of boxes is not 4.
Converts boxes from ymin, xmin, ymax, xmax to xmin, ymin, width, height.
[ "Converts", "boxes", "from", "ymin", "xmin", "ymax", "xmax", "to", "xmin", "ymin", "width", "height", "." ]
def yxyx_to_xywh(boxes): """Converts boxes from ymin, xmin, ymax, xmax to xmin, ymin, width, height. Args: boxes: a numpy array whose last dimension is 4 representing the coordinates of boxes in ymin, xmin, ymax, xmax order. Returns: boxes: a numpy array whose shape is the same as `boxes` in new format. Raises: ValueError: If the last dimension of boxes is not 4. """ if boxes.shape[-1] != 4: raise ValueError('boxes.shape[-1] is {:d}, but must be 4.'.format( boxes.shape[-1])) boxes_ymin = boxes[..., 0] boxes_xmin = boxes[..., 1] boxes_width = boxes[..., 3] - boxes[..., 1] boxes_height = boxes[..., 2] - boxes[..., 0] new_boxes = np.stack([boxes_xmin, boxes_ymin, boxes_width, boxes_height], axis=-1) return new_boxes
[ "def", "yxyx_to_xywh", "(", "boxes", ")", ":", "if", "boxes", ".", "shape", "[", "-", "1", "]", "!=", "4", ":", "raise", "ValueError", "(", "'boxes.shape[-1] is {:d}, but must be 4.'", ".", "format", "(", "boxes", ".", "shape", "[", "-", "1", "]", ")", ...
https://github.com/tensorflow/models/blob/6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3/official/legacy/detection/utils/box_utils.py#L44-L68
nature-of-code/noc-examples-python
a6d823b6998304daa972a21affbf3e13444fe093
chp04_systems/NOC_4_06_ParticleSystemForces/particle_system.py
python
ParticleSystem.apply_force
(self, f)
A function to apply force to all particles
A function to apply force to all particles
[ "A", "function", "to", "apply", "force", "to", "all", "particles" ]
def apply_force(self, f): """A function to apply force to all particles""" for p in self.particles: p.apply_force(f)
[ "def", "apply_force", "(", "self", ",", "f", ")", ":", "for", "p", "in", "self", ".", "particles", ":", "p", ".", "apply_force", "(", "f", ")" ]
https://github.com/nature-of-code/noc-examples-python/blob/a6d823b6998304daa972a21affbf3e13444fe093/chp04_systems/NOC_4_06_ParticleSystemForces/particle_system.py#L20-L23
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/gdata/tlslite/utils/cipherfactory.py
python
createTripleDES
(key, IV, implList=None)
Create a new 3DES object. @type key: str @param key: A 24 byte string. @type IV: str @param IV: An 8 byte string @rtype: L{tlslite.utils.TripleDES} @return: A 3DES object.
Create a new 3DES object.
[ "Create", "a", "new", "3DES", "object", "." ]
def createTripleDES(key, IV, implList=None): """Create a new 3DES object. @type key: str @param key: A 24 byte string. @type IV: str @param IV: An 8 byte string @rtype: L{tlslite.utils.TripleDES} @return: A 3DES object. """ if implList == None: implList = ["cryptlib", "openssl", "pycrypto"] for impl in implList: if impl == "cryptlib" and cryptomath.cryptlibpyLoaded: return Cryptlib_TripleDES.new(key, 2, IV) elif impl == "openssl" and cryptomath.m2cryptoLoaded: return OpenSSL_TripleDES.new(key, 2, IV) elif impl == "pycrypto" and cryptomath.pycryptoLoaded: return PyCrypto_TripleDES.new(key, 2, IV) raise NotImplementedError()
[ "def", "createTripleDES", "(", "key", ",", "IV", ",", "implList", "=", "None", ")", ":", "if", "implList", "==", "None", ":", "implList", "=", "[", "\"cryptlib\"", ",", "\"openssl\"", ",", "\"pycrypto\"", "]", "for", "impl", "in", "implList", ":", "if", ...
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/gdata/tlslite/utils/cipherfactory.py#L89-L111
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_adm_policy_group.py
python
OpenShiftCLI.__init__
(self, namespace, kubeconfig='/etc/origin/master/admin.kubeconfig', verbose=False, all_namespaces=False)
Constructor for OpenshiftCLI
Constructor for OpenshiftCLI
[ "Constructor", "for", "OpenshiftCLI" ]
def __init__(self, namespace, kubeconfig='/etc/origin/master/admin.kubeconfig', verbose=False, all_namespaces=False): ''' Constructor for OpenshiftCLI ''' self.namespace = namespace self.verbose = verbose self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig) self.all_namespaces = all_namespaces self.oc_binary = locate_oc_binary()
[ "def", "__init__", "(", "self", ",", "namespace", ",", "kubeconfig", "=", "'/etc/origin/master/admin.kubeconfig'", ",", "verbose", "=", "False", ",", "all_namespaces", "=", "False", ")", ":", "self", ".", "namespace", "=", "namespace", "self", ".", "verbose", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_adm_policy_group.py#L873-L883
hclhkbu/dlbench
978b034e9c34e6aaa38782bb1e4a2cea0c01d0f9
tools/tensorflow/cnn/alexnet/cifar10_eval.py
python
evaluate
()
Eval CIFAR-10 for a number of steps.
Eval CIFAR-10 for a number of steps.
[ "Eval", "CIFAR", "-", "10", "for", "a", "number", "of", "steps", "." ]
def evaluate(): """Eval CIFAR-10 for a number of steps.""" with tf.Graph().as_default() as g: # Get images and labels for CIFAR-10. eval_data = FLAGS.eval_data == 'test' images, labels = cifar10_input.inputs(eval_data, FLAGS.data_dir, FLAGS.batch_size) # Build a Graph that computes the logits predictions from the # inference model. logits = inference(images) # Calculate predictions. top_k_op = tf.nn.in_top_k(logits, labels, 1) # Restore the moving average version of the learned variables for eval. #variable_averages = tf.train.ExponentialMovingAverage( # cifar10.MOVING_AVERAGE_DECAY) #variables_to_restore = variable_averages.variables_to_restore() #saver = tf.train.Saver(variables_to_restore) saver = tf.train.Saver() # Build the summary operation based on the TF collection of Summaries. summary_op = tf.merge_all_summaries() summary_writer = tf.train.SummaryWriter(FLAGS.eval_dir, g) while True: eval_once(saver, summary_writer, top_k_op, summary_op) if FLAGS.run_once: break time.sleep(FLAGS.eval_interval_secs)
[ "def", "evaluate", "(", ")", ":", "with", "tf", ".", "Graph", "(", ")", ".", "as_default", "(", ")", "as", "g", ":", "# Get images and labels for CIFAR-10.", "eval_data", "=", "FLAGS", ".", "eval_data", "==", "'test'", "images", ",", "labels", "=", "cifar1...
https://github.com/hclhkbu/dlbench/blob/978b034e9c34e6aaa38782bb1e4a2cea0c01d0f9/tools/tensorflow/cnn/alexnet/cifar10_eval.py#L118-L148
joeferraro/MavensMate-SublimeText
af36de7ffaa9b0541f446145736a48b1c66ac0cf
mavensmate.py
python
GetOrgWideTestCoverageCommand.run
(self)
[]
def run(self): mm.call('get-coverage', True, context=self, body={'global': True}, message="Retrieving org-wide test coverage...")
[ "def", "run", "(", "self", ")", ":", "mm", ".", "call", "(", "'get-coverage'", ",", "True", ",", "context", "=", "self", ",", "body", "=", "{", "'global'", ":", "True", "}", ",", "message", "=", "\"Retrieving org-wide test coverage...\"", ")" ]
https://github.com/joeferraro/MavensMate-SublimeText/blob/af36de7ffaa9b0541f446145736a48b1c66ac0cf/mavensmate.py#L862-L863
graalvm/mx
29c0debab406352df3af246be2f8973be5db69ae
mx_benchmark.py
python
BenchmarkSuite.workingDirectory
(self, benchmarks, bmSuiteArgs)
return None
Returns the desired working directory for running the benchmark. By default it returns `None`, meaning that the working directory is not be changed. It is meant to be overridden in subclasses when necessary.
Returns the desired working directory for running the benchmark.
[ "Returns", "the", "desired", "working", "directory", "for", "running", "the", "benchmark", "." ]
def workingDirectory(self, benchmarks, bmSuiteArgs): """Returns the desired working directory for running the benchmark. By default it returns `None`, meaning that the working directory is not be changed. It is meant to be overridden in subclasses when necessary. """ return None
[ "def", "workingDirectory", "(", "self", ",", "benchmarks", ",", "bmSuiteArgs", ")", ":", "return", "None" ]
https://github.com/graalvm/mx/blob/29c0debab406352df3af246be2f8973be5db69ae/mx_benchmark.py#L605-L611
pymedusa/Medusa
1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38
ext/mako/runtime.py
python
supports_caller
(func)
return wrap_stackframe
Apply a caller_stack compatibility decorator to a plain Python function. See the example in :ref:`namespaces_python_modules`.
Apply a caller_stack compatibility decorator to a plain Python function.
[ "Apply", "a", "caller_stack", "compatibility", "decorator", "to", "a", "plain", "Python", "function", "." ]
def supports_caller(func): """Apply a caller_stack compatibility decorator to a plain Python function. See the example in :ref:`namespaces_python_modules`. """ def wrap_stackframe(context, *args, **kwargs): context.caller_stack._push_frame() try: return func(context, *args, **kwargs) finally: context.caller_stack._pop_frame() return wrap_stackframe
[ "def", "supports_caller", "(", "func", ")", ":", "def", "wrap_stackframe", "(", "context", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "context", ".", "caller_stack", ".", "_push_frame", "(", ")", "try", ":", "return", "func", "(", "context", ...
https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/mako/runtime.py#L709-L724
voicy-ai/DialogStateTracking
a102672be468a5246c8c1183f15f55fa320f33c8
src/memn2n/main.py
python
prepare_data
(args, task_id)
[]
def prepare_data(args, task_id): # get candidates (restaurants) candidates, candid2idx, idx2candid = data_utils.load_candidates(task_id=task_id, candidates_f= DATA_DIR + 'dialog-babi-candidates.txt') # get data train, test, val = data_utils.load_dialog_task( data_dir= DATA_DIR, task_id= task_id, candid_dic= candid2idx, isOOV= False) ## # get metadata metadata = data_utils.build_vocab(train + test + val, candidates) ### # write data to file data_ = { 'candidates' : candidates, 'train' : train, 'test' : test, 'val' : val } with open(P_DATA_DIR + str(task_id) + '.data.pkl', 'wb') as f: pkl.dump(data_, f) ### # save metadata to disk metadata['candid2idx'] = candid2idx metadata['idx2candid'] = idx2candid with open(P_DATA_DIR + str(task_id) + '.metadata.pkl', 'wb') as f: pkl.dump(metadata, f)
[ "def", "prepare_data", "(", "args", ",", "task_id", ")", ":", "# get candidates (restaurants)", "candidates", ",", "candid2idx", ",", "idx2candid", "=", "data_utils", ".", "load_candidates", "(", "task_id", "=", "task_id", ",", "candidates_f", "=", "DATA_DIR", "+"...
https://github.com/voicy-ai/DialogStateTracking/blob/a102672be468a5246c8c1183f15f55fa320f33c8/src/memn2n/main.py#L48-L79
renatoviolin/Question-Answering-Albert-Electra
8ca885c27c89af16bb2484ea0e6aeb960801259a
electra/model/modeling.py
python
embedding_lookup
(input_ids, vocab_size, embedding_size=128, initializer_range=0.02, word_embedding_name="word_embeddings", use_one_hot_embeddings=False)
return output, embedding_table
Looks up words embeddings for id tensor. Args: input_ids: int32 Tensor of shape [batch_size, seq_length] containing word ids. vocab_size: int. Size of the embedding vocabulary. embedding_size: int. Width of the word embeddings. initializer_range: float. Embedding initialization range. word_embedding_name: string. Name of the embedding table. use_one_hot_embeddings: bool. If True, use one-hot method for word embeddings. If False, use `tf.nn.embedding_lookup()`. One hot is better for TPUs. Returns: float Tensor of shape [batch_size, seq_length, embedding_size].
Looks up words embeddings for id tensor.
[ "Looks", "up", "words", "embeddings", "for", "id", "tensor", "." ]
def embedding_lookup(input_ids, vocab_size, embedding_size=128, initializer_range=0.02, word_embedding_name="word_embeddings", use_one_hot_embeddings=False): """Looks up words embeddings for id tensor. Args: input_ids: int32 Tensor of shape [batch_size, seq_length] containing word ids. vocab_size: int. Size of the embedding vocabulary. embedding_size: int. Width of the word embeddings. initializer_range: float. Embedding initialization range. word_embedding_name: string. Name of the embedding table. use_one_hot_embeddings: bool. If True, use one-hot method for word embeddings. If False, use `tf.nn.embedding_lookup()`. One hot is better for TPUs. Returns: float Tensor of shape [batch_size, seq_length, embedding_size]. """ # This function assumes that the input is of shape [batch_size, seq_length, # num_inputs]. # # If the input is a 2D tensor of shape [batch_size, seq_length], we # reshape to [batch_size, seq_length, 1]. original_dims = input_ids.shape.ndims if original_dims == 2: input_ids = tf.expand_dims(input_ids, axis=[-1]) embedding_table = tf.get_variable( name=word_embedding_name, shape=[vocab_size, embedding_size], initializer=create_initializer(initializer_range)) if original_dims == 3: input_shape = get_shape_list(input_ids) tf.reshape(input_ids, [-1, input_shape[-1]]) output = tf.matmul(input_ids, embedding_table) output = tf.reshape(output, [input_shape[0], input_shape[1], embedding_size]) else: if use_one_hot_embeddings: flat_input_ids = tf.reshape(input_ids, [-1]) one_hot_input_ids = tf.one_hot(flat_input_ids, depth=vocab_size) output = tf.matmul(one_hot_input_ids, embedding_table) else: output = tf.nn.embedding_lookup(embedding_table, input_ids) input_shape = get_shape_list(input_ids) output = tf.reshape(output, input_shape[0:-1] + [input_shape[-1] * embedding_size]) return output, embedding_table
[ "def", "embedding_lookup", "(", "input_ids", ",", "vocab_size", ",", "embedding_size", "=", "128", ",", "initializer_range", "=", "0.02", ",", "word_embedding_name", "=", "\"word_embeddings\"", ",", "use_one_hot_embeddings", "=", "False", ")", ":", "# This function as...
https://github.com/renatoviolin/Question-Answering-Albert-Electra/blob/8ca885c27c89af16bb2484ea0e6aeb960801259a/electra/model/modeling.py#L396-L450
mrDoctorWho/vk4xmpp
e8f25a16832adb6b93fe8b50afdc9547e429389b
extensions/.example.py
python
evt07_handler
(user)
Linear handler Called when user is connecting (if authenticated) Parameters: user: User class object
Linear handler Called when user is connecting (if authenticated) Parameters: user: User class object
[ "Linear", "handler", "Called", "when", "user", "is", "connecting", "(", "if", "authenticated", ")", "Parameters", ":", "user", ":", "User", "class", "object" ]
def evt07_handler(user): """ Linear handler Called when user is connecting (if authenticated) Parameters: user: User class object """ print "User", user.source, "is authenticated!"
[ "def", "evt07_handler", "(", "user", ")", ":", "print", "\"User\"", ",", "user", ".", "source", ",", "\"is authenticated!\"" ]
https://github.com/mrDoctorWho/vk4xmpp/blob/e8f25a16832adb6b93fe8b50afdc9547e429389b/extensions/.example.py#L106-L113
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/mps/v20190612/models.py
python
ProhibitedConfigureInfo.__init__
(self)
r""" :param AsrReviewInfo: 语音违禁控制参数。 注意:此字段可能返回 null,表示取不到有效值。 :type AsrReviewInfo: :class:`tencentcloud.mps.v20190612.models.ProhibitedAsrReviewTemplateInfo` :param OcrReviewInfo: 文本违禁控制参数。 注意:此字段可能返回 null,表示取不到有效值。 :type OcrReviewInfo: :class:`tencentcloud.mps.v20190612.models.ProhibitedOcrReviewTemplateInfo`
r""" :param AsrReviewInfo: 语音违禁控制参数。 注意:此字段可能返回 null,表示取不到有效值。 :type AsrReviewInfo: :class:`tencentcloud.mps.v20190612.models.ProhibitedAsrReviewTemplateInfo` :param OcrReviewInfo: 文本违禁控制参数。 注意:此字段可能返回 null,表示取不到有效值。 :type OcrReviewInfo: :class:`tencentcloud.mps.v20190612.models.ProhibitedOcrReviewTemplateInfo`
[ "r", ":", "param", "AsrReviewInfo", ":", "语音违禁控制参数。", "注意:此字段可能返回", "null,表示取不到有效值。", ":", "type", "AsrReviewInfo", ":", ":", "class", ":", "tencentcloud", ".", "mps", ".", "v20190612", ".", "models", ".", "ProhibitedAsrReviewTemplateInfo", ":", "param", "OcrRevie...
def __init__(self): r""" :param AsrReviewInfo: 语音违禁控制参数。 注意:此字段可能返回 null,表示取不到有效值。 :type AsrReviewInfo: :class:`tencentcloud.mps.v20190612.models.ProhibitedAsrReviewTemplateInfo` :param OcrReviewInfo: 文本违禁控制参数。 注意:此字段可能返回 null,表示取不到有效值。 :type OcrReviewInfo: :class:`tencentcloud.mps.v20190612.models.ProhibitedOcrReviewTemplateInfo` """ self.AsrReviewInfo = None self.OcrReviewInfo = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "AsrReviewInfo", "=", "None", "self", ".", "OcrReviewInfo", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/mps/v20190612/models.py#L12071-L12081
google/clusterfuzz
f358af24f414daa17a3649b143e71ea71871ef59
src/clusterfuzz/_internal/bot/fuzzers/libFuzzer/stats.py
python
calculate_log_lines
(log_lines)
return other_lines_count, libfuzzer_lines_count, ignored_lines_count
Calculate number of logs lines of different kind in the given log.
Calculate number of logs lines of different kind in the given log.
[ "Calculate", "number", "of", "logs", "lines", "of", "different", "kind", "in", "the", "given", "log", "." ]
def calculate_log_lines(log_lines): """Calculate number of logs lines of different kind in the given log.""" # Counters to be returned. libfuzzer_lines_count = 0 other_lines_count = 0 ignored_lines_count = 0 lines_after_last_libfuzzer_line_count = 0 libfuzzer_inited = False found_libfuzzer_crash = False for line in log_lines: if not libfuzzer_inited: # Skip to start of libFuzzer log output. if LIBFUZZER_LOG_START_INITED_REGEX.match(line): libfuzzer_inited = True else: ignored_lines_count += 1 continue if LIBFUZZER_LOG_IGNORE_REGEX.match(line): # We should ignore lines like sanitizer warnings, etc. ignored_lines_count += 1 continue if LIBFUZZER_ANY_CRASH_TYPE_REGEX.match(line): # We should ignore whole block if a libfuzzer crash is found. # E.g. slow units. found_libfuzzer_crash = True elif LIBFUZZER_LOG_LINE_REGEX.match(line): if found_libfuzzer_crash: # Ignore previous block. other_lines_count -= lines_after_last_libfuzzer_line_count ignored_lines_count += lines_after_last_libfuzzer_line_count libfuzzer_lines_count += 1 lines_after_last_libfuzzer_line_count = 0 found_libfuzzer_crash = False elif LIBFUZZER_LOG_END_REGEX.match(line): libfuzzer_lines_count += 1 break else: other_lines_count += 1 lines_after_last_libfuzzer_line_count += 1 # Ignore the lines after the last libfuzzer line. other_lines_count -= lines_after_last_libfuzzer_line_count ignored_lines_count += lines_after_last_libfuzzer_line_count return other_lines_count, libfuzzer_lines_count, ignored_lines_count
[ "def", "calculate_log_lines", "(", "log_lines", ")", ":", "# Counters to be returned.", "libfuzzer_lines_count", "=", "0", "other_lines_count", "=", "0", "ignored_lines_count", "=", "0", "lines_after_last_libfuzzer_line_count", "=", "0", "libfuzzer_inited", "=", "False", ...
https://github.com/google/clusterfuzz/blob/f358af24f414daa17a3649b143e71ea71871ef59/src/clusterfuzz/_internal/bot/fuzzers/libFuzzer/stats.py#L68-L116
openembedded/openembedded-core
9154f71c7267e9731156c1dfd57397103e9e6a2b
scripts/lib/wic/filemap.py
python
FilemapSeek.get_mapped_ranges
(self, start, count)
return self._get_ranges(start, count, _SEEK_DATA, _SEEK_HOLE)
Refer the '_FilemapBase' class for the documentation.
Refer the '_FilemapBase' class for the documentation.
[ "Refer", "the", "_FilemapBase", "class", "for", "the", "documentation", "." ]
def get_mapped_ranges(self, start, count): """Refer the '_FilemapBase' class for the documentation.""" self._log.debug("FilemapSeek: get_mapped_ranges(%d, %d(%d))" % (start, count, start + count - 1)) return self._get_ranges(start, count, _SEEK_DATA, _SEEK_HOLE)
[ "def", "get_mapped_ranges", "(", "self", ",", "start", ",", "count", ")", ":", "self", ".", "_log", ".", "debug", "(", "\"FilemapSeek: get_mapped_ranges(%d, %d(%d))\"", "%", "(", "start", ",", "count", ",", "start", "+", "count", "-", "1", ")", ")", "retu...
https://github.com/openembedded/openembedded-core/blob/9154f71c7267e9731156c1dfd57397103e9e6a2b/scripts/lib/wic/filemap.py#L277-L281
facebookresearch/CrypTen
90bf38b4f80726c808f322efb0ce430dcdf5e5ec
crypten/nn/onnx_converter.py
python
_export_pytorch_model
(f, pytorch_model, dummy_input)
return f
Returns a binary I/O stream containing ONNX-exported pytorch_model that was traced with input `dummy_input`.
Returns a binary I/O stream containing ONNX-exported pytorch_model that was traced with input `dummy_input`.
[ "Returns", "a", "binary", "I", "/", "O", "stream", "containing", "ONNX", "-", "exported", "pytorch_model", "that", "was", "traced", "with", "input", "dummy_input", "." ]
def _export_pytorch_model(f, pytorch_model, dummy_input): """ Returns a binary I/O stream containing ONNX-exported pytorch_model that was traced with input `dummy_input`. """ kwargs = { "do_constant_folding": False, "export_params": True, "enable_onnx_checker": True, "input_names": ["input"], "operator_export_type": OperatorExportTypes.ONNX, "output_names": ["output"], } torch.onnx.export(pytorch_model, dummy_input, f, **kwargs) return f
[ "def", "_export_pytorch_model", "(", "f", ",", "pytorch_model", ",", "dummy_input", ")", ":", "kwargs", "=", "{", "\"do_constant_folding\"", ":", "False", ",", "\"export_params\"", ":", "True", ",", "\"enable_onnx_checker\"", ":", "True", ",", "\"input_names\"", "...
https://github.com/facebookresearch/CrypTen/blob/90bf38b4f80726c808f322efb0ce430dcdf5e5ec/crypten/nn/onnx_converter.py#L122-L136
postgres/pgadmin4
374c5e952fa594d749fadf1f88076c1cba8c5f64
web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/utils.py
python
_get_sql_for_delete_fk_constraint
(data, constraint, sql, template_path, conn)
Get sql for delete foreign key constraints. :param data: :param constraint: :param sql: sql for append :param template_path: template path for sql. :param conn: :return:
Get sql for delete foreign key constraints. :param data: :param constraint: :param sql: sql for append :param template_path: template path for sql. :param conn: :return:
[ "Get", "sql", "for", "delete", "foreign", "key", "constraints", ".", ":", "param", "data", ":", ":", "param", "constraint", ":", ":", "param", "sql", ":", "sql", "for", "append", ":", "param", "template_path", ":", "template", "path", "for", "sql", ".", ...
def _get_sql_for_delete_fk_constraint(data, constraint, sql, template_path, conn): """ Get sql for delete foreign key constraints. :param data: :param constraint: :param sql: sql for append :param template_path: template path for sql. :param conn: :return: """ if 'deleted' in constraint: for c in constraint['deleted']: c['schema'] = data['schema'] c['table'] = data['name'] # Sql for drop sql.append( render_template("/".join( [template_path, 'delete.sql']), data=c, conn=conn).strip('\n') )
[ "def", "_get_sql_for_delete_fk_constraint", "(", "data", ",", "constraint", ",", "sql", ",", "template_path", ",", "conn", ")", ":", "if", "'deleted'", "in", "constraint", ":", "for", "c", "in", "constraint", "[", "'deleted'", "]", ":", "c", "[", "'schema'",...
https://github.com/postgres/pgadmin4/blob/374c5e952fa594d749fadf1f88076c1cba8c5f64/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/foreign_key/utils.py#L162-L184
wistbean/fxxkpython
88e16d79d8dd37236ba6ecd0d0ff11d63143968c
vip/qyxuan/projects/Snake/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/distlib/_backport/tarfile.py
python
_FileInFile.tell
(self)
return self.position
Return the current file position.
Return the current file position.
[ "Return", "the", "current", "file", "position", "." ]
def tell(self): """Return the current file position. """ return self.position
[ "def", "tell", "(", "self", ")", ":", "return", "self", ".", "position" ]
https://github.com/wistbean/fxxkpython/blob/88e16d79d8dd37236ba6ecd0d0ff11d63143968c/vip/qyxuan/projects/Snake/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/distlib/_backport/tarfile.py#L742-L745
nortikin/sverchok
7b460f01317c15f2681bfa3e337c5e7346f3711b
nodes/analyzer/deformation.py
python
SvDeformationNode.ready
(self)
return ready
check if there are the needed links
check if there are the needed links
[ "check", "if", "there", "are", "the", "needed", "links" ]
def ready(self): '''check if there are the needed links''' si = self.inputs so = self.outputs ready = any(s.is_linked for s in so) ready = ready and si[0].is_linked and si[1].is_linked ready = ready and (si[2].is_linked or si[3].is_linked) return ready
[ "def", "ready", "(", "self", ")", ":", "si", "=", "self", ".", "inputs", "so", "=", "self", ".", "outputs", "ready", "=", "any", "(", "s", ".", "is_linked", "for", "s", "in", "so", ")", "ready", "=", "ready", "and", "si", "[", "0", "]", ".", ...
https://github.com/nortikin/sverchok/blob/7b460f01317c15f2681bfa3e337c5e7346f3711b/nodes/analyzer/deformation.py#L210-L217
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit - MAC OSX/scripts/nextpenbox.py
python
xsstracer
()
[]
def xsstracer(): clearScr() print("XSSTracer is a small python script that checks remote web servers for Clickjacking, Cross-Frame Scripting, Cross-Site Tracing and Host Header Injection.") os.system("git clone https://github.com/1N3/XSSTracer.git") clearScr () xsstracerchoice = raw_input("Select a Target: ") os.system("cd XSSTracer && chmod 777 xsstracer.py && python xsstracer.py %s 80"%xsstracerchoice)
[ "def", "xsstracer", "(", ")", ":", "clearScr", "(", ")", "print", "(", "\"XSSTracer is a small python script that checks remote web servers for Clickjacking, Cross-Frame Scripting, Cross-Site Tracing and Host Header Injection.\"", ")", "os", ".", "system", "(", "\"git clone https://g...
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/scripts/nextpenbox.py#L238-L244
andyzsf/TuShare
92787ad0cd492614bdb6389b71a19c80d1c8c9ae
tushare/datayes/macro.py
python
Macro.KoreaDataGDP
(self, indicID='', indicName='', beginDate='', endDate='', field='')
return _ret_data(code, result)
包含韩国GDP数据,具体指标可参见API文档;历史数据从1970年开始,按季更新。
包含韩国GDP数据,具体指标可参见API文档;历史数据从1970年开始,按季更新。
[ "包含韩国GDP数据,具体指标可参见API文档;历史数据从1970年开始,按季更新。" ]
def KoreaDataGDP(self, indicID='', indicName='', beginDate='', endDate='', field=''): """ 包含韩国GDP数据,具体指标可参见API文档;历史数据从1970年开始,按季更新。 """ code, result = self.client.getData(vs.KOREADATAGDP%(indicID, indicName, beginDate, endDate, field)) return _ret_data(code, result)
[ "def", "KoreaDataGDP", "(", "self", ",", "indicID", "=", "''", ",", "indicName", "=", "''", ",", "beginDate", "=", "''", ",", "endDate", "=", "''", ",", "field", "=", "''", ")", ":", "code", ",", "result", "=", "self", ".", "client", ".", "getData"...
https://github.com/andyzsf/TuShare/blob/92787ad0cd492614bdb6389b71a19c80d1c8c9ae/tushare/datayes/macro.py#L521-L526
nfstream/nfstream
aa14fd1606ce4757f8b1589faeb032a0f5a93c5e
nfstream/system.py
python
ConnCache.scan
(self, current_time)
Scan and delete LRU entries based on a defined timeout
Scan and delete LRU entries based on a defined timeout
[ "Scan", "and", "delete", "LRU", "entries", "based", "on", "a", "defined", "timeout" ]
def scan(self, current_time): """ Scan and delete LRU entries based on a defined timeout """ if (current_time - self.last_scan_time) > 10: remaining = True # We suppose that there is something to expire scanned = 0 while remaining and scanned <= 1000: # Each 10 ms we scan with 1000 entries budget try: lru_key = self.get_lru_key() # will return the LRU conn key. lru_last_update_time = self[lru_key] if current_time - lru_last_update_time >= self.timeout: del self[lru_key] self.channel.put(NFSocket(NFEvent.SOCKET_REMOVE, lru_key, None, None)) # Send to streamer scanned += 1 else: remaining = False # LRU flow is not yet idle. except StopIteration: # Empty cache remaining = False self.last_scan_time = current_time
[ "def", "scan", "(", "self", ",", "current_time", ")", ":", "if", "(", "current_time", "-", "self", ".", "last_scan_time", ")", ">", "10", ":", "remaining", "=", "True", "# We suppose that there is something to expire", "scanned", "=", "0", "while", "remaining", ...
https://github.com/nfstream/nfstream/blob/aa14fd1606ce4757f8b1589faeb032a0f5a93c5e/nfstream/system.py#L149-L166
pycontribs/pyrax
a0c022981f76a4cba96a22ecc19bb52843ac4fbe
pyrax/image.py
python
ImageManager.create
(self, name, img_format=None, img_container_format=None, data=None, container=None, obj=None, metadata=None)
Creates a new image with the specified name. The image data can either be supplied directly in the 'data' parameter, or it can be an image stored in the object storage service. In the case of the latter, you can either supply the container and object names, or simply a StorageObject reference. You may specify the image and image container formats; if unspecified, the default of "vhd" for image format and "bare" for image container format will be used. NOTE: This is blocking, and may take a while to complete.
Creates a new image with the specified name. The image data can either be supplied directly in the 'data' parameter, or it can be an image stored in the object storage service. In the case of the latter, you can either supply the container and object names, or simply a StorageObject reference.
[ "Creates", "a", "new", "image", "with", "the", "specified", "name", ".", "The", "image", "data", "can", "either", "be", "supplied", "directly", "in", "the", "data", "parameter", "or", "it", "can", "be", "an", "image", "stored", "in", "the", "object", "st...
def create(self, name, img_format=None, img_container_format=None, data=None, container=None, obj=None, metadata=None): """ Creates a new image with the specified name. The image data can either be supplied directly in the 'data' parameter, or it can be an image stored in the object storage service. In the case of the latter, you can either supply the container and object names, or simply a StorageObject reference. You may specify the image and image container formats; if unspecified, the default of "vhd" for image format and "bare" for image container format will be used. NOTE: This is blocking, and may take a while to complete. """ if img_format is None: img_format = "vhd" if img_container_format is None: img_container_format = "bare" headers = { "X-Image-Meta-name": name, "X-Image-Meta-disk_format": img_format, "X-Image-Meta-container_format": img_container_format, } if data: img_data = data else: ident = self.api.identity region = self.api.region_name clt = ident.get_client("object_store", region) if not isinstance(obj, StorageObject): obj = clt.get_object(container, obj) img_data = obj.fetch() uri = "%s/images" % self.uri_base resp, resp_body = self.api.method_post(uri, headers=headers, data=img_data)
[ "def", "create", "(", "self", ",", "name", ",", "img_format", "=", "None", ",", "img_container_format", "=", "None", ",", "data", "=", "None", ",", "container", "=", "None", ",", "obj", "=", "None", ",", "metadata", "=", "None", ")", ":", "if", "img_...
https://github.com/pycontribs/pyrax/blob/a0c022981f76a4cba96a22ecc19bb52843ac4fbe/pyrax/image.py#L255-L290
StepNeverStop/RLs
25cc97c96cbb19fe859c9387b7547cbada2c89f2
rls/utils/torch_utils.py
python
squash_action
(pi, log_pi, *, is_independent=True)
return pi, log_pi
Enforcing action bounds. squash action to range [-1, 1] and calculate the correct log probability value. Args: pi: sample of gaussian distribution log_pi: log probability of the sample is_independent: todo Return: sample range of [-1, 1] after squashed. the corrected log probability of squashed sample.
Enforcing action bounds. squash action to range [-1, 1] and calculate the correct log probability value. Args: pi: sample of gaussian distribution log_pi: log probability of the sample is_independent: todo Return: sample range of [-1, 1] after squashed. the corrected log probability of squashed sample.
[ "Enforcing", "action", "bounds", ".", "squash", "action", "to", "range", "[", "-", "1", "1", "]", "and", "calculate", "the", "correct", "log", "probability", "value", ".", "Args", ":", "pi", ":", "sample", "of", "gaussian", "distribution", "log_pi", ":", ...
def squash_action(pi, log_pi, *, is_independent=True): """ Enforcing action bounds. squash action to range [-1, 1] and calculate the correct log probability value. Args: pi: sample of gaussian distribution log_pi: log probability of the sample is_independent: todo Return: sample range of [-1, 1] after squashed. the corrected log probability of squashed sample. """ pi = th.tanh(pi) sub = (clip_but_pass_gradient(1 - pi ** 2, l=0, h=1) + th.finfo().eps).log() log_pi = log_pi - sub if is_independent: log_pi = log_pi.sum(-1, keepdim=True) return pi, log_pi
[ "def", "squash_action", "(", "pi", ",", "log_pi", ",", "*", ",", "is_independent", "=", "True", ")", ":", "pi", "=", "th", ".", "tanh", "(", "pi", ")", "sub", "=", "(", "clip_but_pass_gradient", "(", "1", "-", "pi", "**", "2", ",", "l", "=", "0",...
https://github.com/StepNeverStop/RLs/blob/25cc97c96cbb19fe859c9387b7547cbada2c89f2/rls/utils/torch_utils.py#L65-L82
jliljebl/flowblade
995313a509b80e99eb1ad550d945bdda5995093b
flowblade-trunk/Flowblade/extraeditors.py
python
ThreeBandColorBox._press_event
(self, event)
[]
def _press_event(self, event): self.cursor_x, self.cursor_y = self._get_legal_point(event.x, event.y) hit_value = self._check_band_hit(self.cursor_x, self.cursor_y) if hit_value != self.band and hit_value != NO_HIT: self.band = hit_value self.band_change_listerner(self.band) self._save_values() self.edit_listener() self.widget.queue_draw() self.motion_on = True
[ "def", "_press_event", "(", "self", ",", "event", ")", ":", "self", ".", "cursor_x", ",", "self", ".", "cursor_y", "=", "self", ".", "_get_legal_point", "(", "event", ".", "x", ",", "event", ".", "y", ")", "hit_value", "=", "self", ".", "_check_band_hi...
https://github.com/jliljebl/flowblade/blob/995313a509b80e99eb1ad550d945bdda5995093b/flowblade-trunk/Flowblade/extraeditors.py#L315-L324
quodlibet/quodlibet
e3099c89f7aa6524380795d325cc14630031886c
quodlibet/plugins/playlist.py
python
PlaylistPluginHandler.handle
(self, plugin_id, library, browser, playlists)
Start a plugin directly without a menu
Start a plugin directly without a menu
[ "Start", "a", "plugin", "directly", "without", "a", "menu" ]
def handle(self, plugin_id, library, browser, playlists): """Start a plugin directly without a menu""" for plugin in self.__plugins: if plugin.PLUGIN_ID == plugin_id: try: plugin = plugin(playlists, library) except Exception: print_exc() else: parent = get_top_parent(browser) self.__handle(plugin, library, browser, playlists, parent) return
[ "def", "handle", "(", "self", ",", "plugin_id", ",", "library", ",", "browser", ",", "playlists", ")", ":", "for", "plugin", "in", "self", ".", "__plugins", ":", "if", "plugin", ".", "PLUGIN_ID", "==", "plugin_id", ":", "try", ":", "plugin", "=", "plug...
https://github.com/quodlibet/quodlibet/blob/e3099c89f7aa6524380795d325cc14630031886c/quodlibet/plugins/playlist.py#L133-L145
marinho/geraldo
868ebdce67176d9b6205cddc92476f642c783fff
site/newsite/django_1_0/django/dispatch/dispatcher.py
python
_removeSender
(senderkey)
Remove senderkey from connections.
Remove senderkey from connections.
[ "Remove", "senderkey", "from", "connections", "." ]
def _removeSender(senderkey): """Remove senderkey from connections.""" _removeBackrefs(senderkey) connections.pop(senderkey, None) senders.pop(senderkey, None)
[ "def", "_removeSender", "(", "senderkey", ")", ":", "_removeBackrefs", "(", "senderkey", ")", "connections", ".", "pop", "(", "senderkey", ",", "None", ")", "senders", ".", "pop", "(", "senderkey", ",", "None", ")" ]
https://github.com/marinho/geraldo/blob/868ebdce67176d9b6205cddc92476f642c783fff/site/newsite/django_1_0/django/dispatch/dispatcher.py#L434-L439
pantsbuild/pex
473c6ac732ed4bc338b4b20a9ec930d1d722c9b4
pex/vendor/_vendored/pip/pip/_vendor/html5lib/_trie/py.py
python
Trie.__init__
(self, data)
[]
def __init__(self, data): if not all(isinstance(x, text_type) for x in data.keys()): raise TypeError("All keys must be strings") self._data = data self._keys = sorted(data.keys()) self._cachestr = "" self._cachepoints = (0, len(data))
[ "def", "__init__", "(", "self", ",", "data", ")", ":", "if", "not", "all", "(", "isinstance", "(", "x", ",", "text_type", ")", "for", "x", "in", "data", ".", "keys", "(", ")", ")", ":", "raise", "TypeError", "(", "\"All keys must be strings\"", ")", ...
https://github.com/pantsbuild/pex/blob/473c6ac732ed4bc338b4b20a9ec930d1d722c9b4/pex/vendor/_vendored/pip/pip/_vendor/html5lib/_trie/py.py#L10-L17
biolab/orange2
db40a9449cb45b507d63dcd5739b223f9cffb8e6
Orange/classification/bayes.py
python
NaiveClassifier.p
(self, class_, instance)
return self.native_bayes_classifier.p(class_, instance)
Return probability of a single class. Probability is not normalized and can be different from probability returned from __call__. :param class_: class value for which the probability should be output. :type class_: :class:`~Orange.data.Value` :param instance: instance to be classified. :type instance: :class:`~Orange.data.Instance`
Return probability of a single class. Probability is not normalized and can be different from probability returned from __call__. :param class_: class value for which the probability should be output. :type class_: :class:`~Orange.data.Value` :param instance: instance to be classified. :type instance: :class:`~Orange.data.Instance`
[ "Return", "probability", "of", "a", "single", "class", ".", "Probability", "is", "not", "normalized", "and", "can", "be", "different", "from", "probability", "returned", "from", "__call__", ".", ":", "param", "class_", ":", "class", "value", "for", "which", ...
def p(self, class_, instance): """ Return probability of a single class. Probability is not normalized and can be different from probability returned from __call__. :param class_: class value for which the probability should be output. :type class_: :class:`~Orange.data.Value` :param instance: instance to be classified. :type instance: :class:`~Orange.data.Instance` """ return self.native_bayes_classifier.p(class_, instance)
[ "def", "p", "(", "self", ",", "class_", ",", "instance", ")", ":", "return", "self", ".", "native_bayes_classifier", ".", "p", "(", "class_", ",", "instance", ")" ]
https://github.com/biolab/orange2/blob/db40a9449cb45b507d63dcd5739b223f9cffb8e6/Orange/classification/bayes.py#L160-L173
AcidWeb/CurseBreaker
1a8cb60f4db0cc8b7e0702441e1adc0f1829003e
CurseBreaker.py
python
TUI.print_log
(self)
[]
def print_log(self): if self.headless: html = self.console.export_html(inline_styles=True, theme=HEADLESS_TERMINAL_THEME) with open('CurseBreaker.html', 'a+', encoding='utf-8') as log: log.write(html)
[ "def", "print_log", "(", "self", ")", ":", "if", "self", ".", "headless", ":", "html", "=", "self", ".", "console", ".", "export_html", "(", "inline_styles", "=", "True", ",", "theme", "=", "HEADLESS_TERMINAL_THEME", ")", "with", "open", "(", "'CurseBreake...
https://github.com/AcidWeb/CurseBreaker/blob/1a8cb60f4db0cc8b7e0702441e1adc0f1829003e/CurseBreaker.py#L323-L327
pyocd/pyOCD
7d164d99e816c4ef6c99f257014543188a0ca5a6
pyocd/coresight/cortex_m_core_registers.py
python
index_for_reg
(name)
return CortexMCoreRegisterInfo.get(name).index
! @brief Utility to easily convert register name to index.
!
[ "!" ]
def index_for_reg(name): """! @brief Utility to easily convert register name to index.""" return CortexMCoreRegisterInfo.get(name).index
[ "def", "index_for_reg", "(", "name", ")", ":", "return", "CortexMCoreRegisterInfo", ".", "get", "(", "name", ")", ".", "index" ]
https://github.com/pyocd/pyOCD/blob/7d164d99e816c4ef6c99f257014543188a0ca5a6/pyocd/coresight/cortex_m_core_registers.py#L255-L257
django/djangosnippets.org
0b273ce13135e157267009631d460835387d9975
ratings/utils.py
python
query_as_sql
(query)
return query.get_compiler(connection=connection).as_sql()
[]
def query_as_sql(query): return query.get_compiler(connection=connection).as_sql()
[ "def", "query_as_sql", "(", "query", ")", ":", "return", "query", ".", "get_compiler", "(", "connection", "=", "connection", ")", ".", "as_sql", "(", ")" ]
https://github.com/django/djangosnippets.org/blob/0b273ce13135e157267009631d460835387d9975/ratings/utils.py#L18-L19
digidotcom/xbee-python
0757f4be0017530c205175fbee8f9f61be9614d1
digi/xbee/devices.py
python
Connection.scan_counter_b2a
(self, new_scan_counter_b2a)
Configures the scan counter for this connection, discovered by its B node. Args: new_scan_counter_b2a (Integer): The scan counter for this connection, discovered by its B node.
Configures the scan counter for this connection, discovered by its B node.
[ "Configures", "the", "scan", "counter", "for", "this", "connection", "discovered", "by", "its", "B", "node", "." ]
def scan_counter_b2a(self, new_scan_counter_b2a): """ Configures the scan counter for this connection, discovered by its B node. Args: new_scan_counter_b2a (Integer): The scan counter for this connection, discovered by its B node. """ self.__scan_counter_b2a = new_scan_counter_b2a
[ "def", "scan_counter_b2a", "(", "self", ",", "new_scan_counter_b2a", ")", ":", "self", ".", "__scan_counter_b2a", "=", "new_scan_counter_b2a" ]
https://github.com/digidotcom/xbee-python/blob/0757f4be0017530c205175fbee8f9f61be9614d1/digi/xbee/devices.py#L12355-L12363
bokeh/bokeh
a00e59da76beb7b9f83613533cfd3aced1df5f06
bokeh/core/property/descriptors.py
python
DataSpecPropertyDescriptor.set_from_json
(self, obj, json, *, models=None, setter=None)
Sets the value of this property from a JSON value. This method first Args: obj (HasProps) : json (JSON-dict) : models(seq[Model], optional) : setter (ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. (default: None) In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself. Returns: None
Sets the value of this property from a JSON value.
[ "Sets", "the", "value", "of", "this", "property", "from", "a", "JSON", "value", "." ]
def set_from_json(self, obj, json, *, models=None, setter=None): """ Sets the value of this property from a JSON value. This method first Args: obj (HasProps) : json (JSON-dict) : models(seq[Model], optional) : setter (ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. (default: None) In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself. Returns: None """ if isinstance(json, dict): # we want to try to keep the "format" of the data spec as string, dict, or number, # assuming the serialized dict is compatible with that. old = getattr(obj, self.name) if old is not None: try: self.property._type.validate(old, False) if 'value' in json: json = json['value'] except ValueError: if isinstance(old, str) and 'field' in json: json = json['field'] # leave it as a dict if 'old' was a dict super().set_from_json(obj, json, models=models, setter=setter)
[ "def", "set_from_json", "(", "self", ",", "obj", ",", "json", ",", "*", ",", "models", "=", "None", ",", "setter", "=", "None", ")", ":", "if", "isinstance", "(", "json", ",", "dict", ")", ":", "# we want to try to keep the \"format\" of the data spec as strin...
https://github.com/bokeh/bokeh/blob/a00e59da76beb7b9f83613533cfd3aced1df5f06/bokeh/core/property/descriptors.py#L724-L765
explosion/srsly
8617ecc099d1f34a60117b5287bef5424ea2c837
srsly/ruamel_yaml/comments.py
python
CommentedMap.__delitem__
(self, key)
[]
def __delitem__(self, key): # type: (Any) -> None # for merged in getattr(self, merge_attrib, []): # if key in merged[1]: # value = merged[1][key] # break # else: # # not found in merged in stuff # ordereddict.__delitem__(self, key) # for referer in self._ref: # referer.update_key_value(key) # return # # ordereddict.__setitem__(self, key, value) # merge might have different value # self._ok.discard(key) self._ok.discard(key) ordereddict.__delitem__(self, key) for referer in self._ref: referer.update_key_value(key)
[ "def", "__delitem__", "(", "self", ",", "key", ")", ":", "# type: (Any) -> None", "# for merged in getattr(self, merge_attrib, []):", "# if key in merged[1]:", "# value = merged[1][key]", "# break", "# else:", "# # not found in merged in stuff", "# ordereddi...
https://github.com/explosion/srsly/blob/8617ecc099d1f34a60117b5287bef5424ea2c837/srsly/ruamel_yaml/comments.py#L802-L820
mila-iqia/myia
56774a39579b4ec4123f44843ad4ca688acc859b
myia_backend_relay/myia_backend_relay/relay.py
python
CompileGraph.on_constant
(self, node)
return self.make_const(node.value, node.abstract)
Convert a constant node.
Convert a constant node.
[ "Convert", "a", "constant", "node", "." ]
def on_constant(self, node): """Convert a constant node.""" if node.is_constant(Primitive): return self.convert_func( get_prim_graph({}, node.value, node.abstract) ) return self.make_const(node.value, node.abstract)
[ "def", "on_constant", "(", "self", ",", "node", ")", ":", "if", "node", ".", "is_constant", "(", "Primitive", ")", ":", "return", "self", ".", "convert_func", "(", "get_prim_graph", "(", "{", "}", ",", "node", ".", "value", ",", "node", ".", "abstract"...
https://github.com/mila-iqia/myia/blob/56774a39579b4ec4123f44843ad4ca688acc859b/myia_backend_relay/myia_backend_relay/relay.py#L862-L868
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/celery-4.2.1/celery/platforms.py
python
Signals.ignore
(self, *names)
Ignore signal using :const:`SIG_IGN`. Does nothing if the platform has no support for signals, or the specified signal in particular.
Ignore signal using :const:`SIG_IGN`.
[ "Ignore", "signal", "using", ":", "const", ":", "SIG_IGN", "." ]
def ignore(self, *names): """Ignore signal using :const:`SIG_IGN`. Does nothing if the platform has no support for signals, or the specified signal in particular. """ self.update((sig, self.ignored) for sig in names)
[ "def", "ignore", "(", "self", ",", "*", "names", ")", ":", "self", ".", "update", "(", "(", "sig", ",", "self", ".", "ignored", ")", "for", "sig", "in", "names", ")" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/celery-4.2.1/celery/platforms.py#L661-L667
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/docutils/utils/math/math2html.py
python
VerticalSpace.process
(self)
Set the correct tag
Set the correct tag
[ "Set", "the", "correct", "tag" ]
def process(self): "Set the correct tag" self.type = self.header[2] if self.type not in StyleConfig.vspaces: self.output = TaggedOutput().settag('div class="vspace" style="height: ' + self.type + ';"', True) return self.html = [StyleConfig.vspaces[self.type]]
[ "def", "process", "(", "self", ")", ":", "self", ".", "type", "=", "self", ".", "header", "[", "2", "]", "if", "self", ".", "type", "not", "in", "StyleConfig", ".", "vspaces", ":", "self", ".", "output", "=", "TaggedOutput", "(", ")", ".", "settag"...
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/docutils/utils/math/math2html.py#L3589-L3595
noahgolmant/pytorch-hessian-eigenthings
dce2e54a19963b0dfa41b93f531fb7742d46ea04
hessian_eigenthings/power_iter.py
python
deflated_power_iteration
( operator: Operator, num_eigenthings: int = 10, power_iter_steps: int = 20, power_iter_err_threshold: float = 1e-4, momentum: float = 0.0, use_gpu: bool = True, fp16: bool = False, to_numpy: bool = True, )
return eigenvals, eigenvecs
Compute top k eigenvalues by repeatedly subtracting out dyads operator: linear operator that gives us access to matrix vector product num_eigenvals number of eigenvalues to compute power_iter_steps: number of steps per run of power iteration power_iter_err_threshold: early stopping threshold for power iteration returns: np.ndarray of top eigenvalues, np.ndarray of top eigenvectors
Compute top k eigenvalues by repeatedly subtracting out dyads operator: linear operator that gives us access to matrix vector product num_eigenvals number of eigenvalues to compute power_iter_steps: number of steps per run of power iteration power_iter_err_threshold: early stopping threshold for power iteration returns: np.ndarray of top eigenvalues, np.ndarray of top eigenvectors
[ "Compute", "top", "k", "eigenvalues", "by", "repeatedly", "subtracting", "out", "dyads", "operator", ":", "linear", "operator", "that", "gives", "us", "access", "to", "matrix", "vector", "product", "num_eigenvals", "number", "of", "eigenvalues", "to", "compute", ...
def deflated_power_iteration( operator: Operator, num_eigenthings: int = 10, power_iter_steps: int = 20, power_iter_err_threshold: float = 1e-4, momentum: float = 0.0, use_gpu: bool = True, fp16: bool = False, to_numpy: bool = True, ) -> Tuple[np.ndarray, np.ndarray]: """ Compute top k eigenvalues by repeatedly subtracting out dyads operator: linear operator that gives us access to matrix vector product num_eigenvals number of eigenvalues to compute power_iter_steps: number of steps per run of power iteration power_iter_err_threshold: early stopping threshold for power iteration returns: np.ndarray of top eigenvalues, np.ndarray of top eigenvectors """ eigenvals = [] eigenvecs = [] current_op = operator prev_vec = None def _deflate(x, val, vec): return val * vec.dot(x) * vec utils.log("beginning deflated power iteration") for i in range(num_eigenthings): utils.log("computing eigenvalue/vector %d of %d" % (i + 1, num_eigenthings)) eigenval, eigenvec = power_iteration( current_op, power_iter_steps, power_iter_err_threshold, momentum=momentum, use_gpu=use_gpu, fp16=fp16, init_vec=prev_vec, ) utils.log("eigenvalue %d: %.4f" % (i + 1, eigenval)) def _new_op_fn(x, op=current_op, val=eigenval, vec=eigenvec): return utils.maybe_fp16(op.apply(x), fp16) - _deflate(x, val, vec) current_op = LambdaOperator(_new_op_fn, operator.size) prev_vec = eigenvec eigenvals.append(eigenval) eigenvec = eigenvec.cpu() if to_numpy: # Clone so that power_iteration can continue to use torch. numpy_eigenvec = eigenvec.detach().clone().numpy() eigenvecs.append(numpy_eigenvec) else: eigenvecs.append(eigenvec) eigenvals = np.array(eigenvals) eigenvecs = np.array(eigenvecs) # sort them in descending order sorted_inds = np.argsort(eigenvals) eigenvals = eigenvals[sorted_inds][::-1] eigenvecs = eigenvecs[sorted_inds][::-1] return eigenvals, eigenvecs
[ "def", "deflated_power_iteration", "(", "operator", ":", "Operator", ",", "num_eigenthings", ":", "int", "=", "10", ",", "power_iter_steps", ":", "int", "=", "20", ",", "power_iter_err_threshold", ":", "float", "=", "1e-4", ",", "momentum", ":", "float", "=", ...
https://github.com/noahgolmant/pytorch-hessian-eigenthings/blob/dce2e54a19963b0dfa41b93f531fb7742d46ea04/hessian_eigenthings/power_iter.py#L14-L75
anonymous47823493/EagleEye
ba312d99587e4c1b9ffeb4f56ab81d909f2021a0
distiller/utils.py
python
denormalize_module_name
(parallel_model, normalized_name)
Convert back from the normalized form of the layer name, to PyTorch's name which contains "artifacts" if DataParallel is used.
Convert back from the normalized form of the layer name, to PyTorch's name which contains "artifacts" if DataParallel is used.
[ "Convert", "back", "from", "the", "normalized", "form", "of", "the", "layer", "name", "to", "PyTorch", "s", "name", "which", "contains", "artifacts", "if", "DataParallel", "is", "used", "." ]
def denormalize_module_name(parallel_model, normalized_name): """Convert back from the normalized form of the layer name, to PyTorch's name which contains "artifacts" if DataParallel is used. """ fully_qualified_name = [ mod_name for mod_name, _ in parallel_model.named_modules() if normalize_module_name(mod_name) == normalized_name ] if len(fully_qualified_name) > 0: return fully_qualified_name[-1] else: return normalized_name
[ "def", "denormalize_module_name", "(", "parallel_model", ",", "normalized_name", ")", ":", "fully_qualified_name", "=", "[", "mod_name", "for", "mod_name", ",", "_", "in", "parallel_model", ".", "named_modules", "(", ")", "if", "normalize_module_name", "(", "mod_nam...
https://github.com/anonymous47823493/EagleEye/blob/ba312d99587e4c1b9ffeb4f56ab81d909f2021a0/distiller/utils.py#L142-L154
sympy/sympy
d822fcba181155b85ff2b29fe525adbafb22b448
sympy/plotting/plot.py
python
MatplotlibBackend.get_segments
(x, y, z=None)
return np.ma.concatenate([points[:-1], points[1:]], axis=1)
Convert two list of coordinates to a list of segments to be used with Matplotlib's LineCollection. Parameters ========== x: list List of x-coordinates y: list List of y-coordinates z: list List of z-coordinates for a 3D line.
Convert two list of coordinates to a list of segments to be used with Matplotlib's LineCollection.
[ "Convert", "two", "list", "of", "coordinates", "to", "a", "list", "of", "segments", "to", "be", "used", "with", "Matplotlib", "s", "LineCollection", "." ]
def get_segments(x, y, z=None): """ Convert two list of coordinates to a list of segments to be used with Matplotlib's LineCollection. Parameters ========== x: list List of x-coordinates y: list List of y-coordinates z: list List of z-coordinates for a 3D line. """ np = import_module('numpy') if z is not None: dim = 3 points = (x, y, z) else: dim = 2 points = (x, y) points = np.ma.array(points).T.reshape(-1, 1, dim) return np.ma.concatenate([points[:-1], points[1:]], axis=1)
[ "def", "get_segments", "(", "x", ",", "y", ",", "z", "=", "None", ")", ":", "np", "=", "import_module", "(", "'numpy'", ")", "if", "z", "is", "not", "None", ":", "dim", "=", "3", "points", "=", "(", "x", ",", "y", ",", "z", ")", "else", ":", ...
https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/plotting/plot.py#L1314-L1337
auDeep/auDeep
07df37b4fde5b10cd96a0c94d8804a1612c10d6f
audeep/backend/parsers/meta.py
python
MetaParser.__init__
(self, basedir: Path)
Creates and initializes a new MetaParser for the specified data set base directory. Parameters ---------- basedir: pathlib.Path The data set base directory
Creates and initializes a new MetaParser for the specified data set base directory. Parameters ---------- basedir: pathlib.Path The data set base directory
[ "Creates", "and", "initializes", "a", "new", "MetaParser", "for", "the", "specified", "data", "set", "base", "directory", ".", "Parameters", "----------", "basedir", ":", "pathlib", ".", "Path", "The", "data", "set", "base", "directory" ]
def __init__(self, basedir: Path): """ Creates and initializes a new MetaParser for the specified data set base directory. Parameters ---------- basedir: pathlib.Path The data set base directory """ super().__init__(basedir) self._parser = None self._can_parse = None self._parsers = [ DCASEParser(basedir), PartitionedParser(basedir), CrossValidatedParser(basedir), ESCParser(basedir), UrbanSound8KParser(basedir) ]
[ "def", "__init__", "(", "self", ",", "basedir", ":", "Path", ")", ":", "super", "(", ")", ".", "__init__", "(", "basedir", ")", "self", ".", "_parser", "=", "None", "self", ".", "_can_parse", "=", "None", "self", ".", "_parsers", "=", "[", "DCASEPars...
https://github.com/auDeep/auDeep/blob/07df37b4fde5b10cd96a0c94d8804a1612c10d6f/audeep/backend/parsers/meta.py#L40-L60
leo-editor/leo-editor
383d6776d135ef17d73d935a2f0ecb3ac0e99494
leo/core/leoCommands.py
python
Commands.diff_file
(self, fn, rev1='HEAD', rev2='')
Create an outline describing the git diffs for all files changed between rev1 and rev2.
Create an outline describing the git diffs for all files changed between rev1 and rev2.
[ "Create", "an", "outline", "describing", "the", "git", "diffs", "for", "all", "files", "changed", "between", "rev1", "and", "rev2", "." ]
def diff_file(self, fn, rev1='HEAD', rev2=''): """ Create an outline describing the git diffs for all files changed between rev1 and rev2. """ from leo.commands import editFileCommands as efc x = efc.GitDiffController(c=self) x.diff_file(fn=fn, rev1=rev1, rev2=rev2)
[ "def", "diff_file", "(", "self", ",", "fn", ",", "rev1", "=", "'HEAD'", ",", "rev2", "=", "''", ")", ":", "from", "leo", ".", "commands", "import", "editFileCommands", "as", "efc", "x", "=", "efc", ".", "GitDiffController", "(", "c", "=", "self", ")"...
https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/core/leoCommands.py#L2816-L2823
IntelLabs/nlp-architect
60afd0dd1bfd74f01b4ac8f613cb484777b80284
nlp_architect/models/temporal_convolutional_network.py
python
WeightNorm.build
(self, input_shape)
Build `Layer`
Build `Layer`
[ "Build", "Layer" ]
def build(self, input_shape): """Build `Layer`""" input_shape = tensor_shape.TensorShape(input_shape).as_list() self.input_spec = InputSpec(shape=input_shape) if not self.layer.built: self.layer.build(input_shape) self.layer.built = False if not hasattr(self.layer, "kernel"): raise ValueError( "`WeightNorm` must wrap a layer that" " contains a `kernel` for weights" ) # The kernel's filter or unit dimension is -1 self.layer_depth = int(self.layer.kernel.shape[-1]) self.norm_axes = list(range(self.layer.kernel.shape.ndims - 1)) self.layer.v = self.layer.kernel self.layer.g = self.layer.add_variable( name="g", shape=(self.layer_depth,), initializer=initializers.get("ones"), dtype=self.layer.kernel.dtype, trainable=True, ) with ops.control_dependencies([self.layer.g.assign(self._init_norm(self.layer.v))]): self._compute_weights() self.layer.built = True super(WeightNorm, self).build() self.built = True
[ "def", "build", "(", "self", ",", "input_shape", ")", ":", "input_shape", "=", "tensor_shape", ".", "TensorShape", "(", "input_shape", ")", ".", "as_list", "(", ")", "self", ".", "input_spec", "=", "InputSpec", "(", "shape", "=", "input_shape", ")", "if", ...
https://github.com/IntelLabs/nlp-architect/blob/60afd0dd1bfd74f01b4ac8f613cb484777b80284/nlp_architect/models/temporal_convolutional_network.py#L129-L162
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/filecmp.py
python
dircmp.__getattr__
(self, attr)
return getattr(self, attr)
[]
def __getattr__(self, attr): if attr not in self.methodmap: raise AttributeError, attr self.methodmap[attr](self) return getattr(self, attr)
[ "def", "__getattr__", "(", "self", ",", "attr", ")", ":", "if", "attr", "not", "in", "self", ".", "methodmap", ":", "raise", "AttributeError", ",", "attr", "self", ".", "methodmap", "[", "attr", "]", "(", "self", ")", "return", "getattr", "(", "self", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/filecmp.py#L235-L239
open-cogsci/OpenSesame
c4a3641b097a80a76937edbd8c365f036bcc9705
libqtopensesame/extensions/_base_extension.py
python
base_extension.create_action
(self)
desc: Creates a QAction for the extension, and adds it to the menubar and/ or the toolbar.
desc: Creates a QAction for the extension, and adds it to the menubar and/ or the toolbar.
[ "desc", ":", "Creates", "a", "QAction", "for", "the", "extension", "and", "adds", "it", "to", "the", "menubar", "and", "/", "or", "the", "toolbar", "." ]
def create_action(self): """ desc: Creates a QAction for the extension, and adds it to the menubar and/ or the toolbar. """ if self.label() is not None: self.action = self.qaction(self.icon(), self.label(), self._activate, checkable=self.checkable(), tooltip=self.tooltip(), shortcut=self.shortcut()) # Insert the action into the menu if self.menu_pos() is not None: submenu_text, index, separator_before, separator_after = \ self.menu_pos() submenu = self.get_submenu(submenu_text) self.add_action(submenu, self.action, index, separator_before, separator_after) # Insert the action into the toolbar if self.toolbar_pos() is not None: index, separator_before, separator_after = self.toolbar_pos() self.add_action(self.toolbar, self.action, index, separator_before, separator_after) else: self.action = None
[ "def", "create_action", "(", "self", ")", ":", "if", "self", ".", "label", "(", ")", "is", "not", "None", ":", "self", ".", "action", "=", "self", ".", "qaction", "(", "self", ".", "icon", "(", ")", ",", "self", ".", "label", "(", ")", ",", "se...
https://github.com/open-cogsci/OpenSesame/blob/c4a3641b097a80a76937edbd8c365f036bcc9705/libqtopensesame/extensions/_base_extension.py#L469-L494
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/pyparsing.py
python
CharsNotIn.__init__
( self, notChars, min=1, max=0, exact=0 )
[]
def __init__( self, notChars, min=1, max=0, exact=0 ): super(CharsNotIn,self).__init__() self.skipWhitespace = False self.notChars = notChars if min < 1: raise ValueError("cannot specify a minimum length < 1; use Optional(CharsNotIn()) if zero-length char group is permitted") self.minLen = min if max > 0: self.maxLen = max else: self.maxLen = _MAX_INT if exact > 0: self.maxLen = exact self.minLen = exact self.name = _ustr(self) self.errmsg = "Expected " + self.name self.mayReturnEmpty = ( self.minLen == 0 ) self.mayIndexError = False
[ "def", "__init__", "(", "self", ",", "notChars", ",", "min", "=", "1", ",", "max", "=", "0", ",", "exact", "=", "0", ")", ":", "super", "(", "CharsNotIn", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "skipWhitespace", "=", "False", "...
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/pyparsing.py#L2950-L2972
flow-project/flow
a511c41c48e6b928bb2060de8ad1ef3c3e3d9554
flow/networks/ring.py
python
RingNetwork.__init__
(self, name, vehicles, net_params, initial_config=InitialConfig(), traffic_lights=TrafficLightParams())
Initialize a ring scenario.
Initialize a ring scenario.
[ "Initialize", "a", "ring", "scenario", "." ]
def __init__(self, name, vehicles, net_params, initial_config=InitialConfig(), traffic_lights=TrafficLightParams()): """Initialize a ring scenario.""" for p in ADDITIONAL_NET_PARAMS.keys(): if p not in net_params.additional_params: raise KeyError('Network parameter "{}" not supplied'.format(p)) super().__init__(name, vehicles, net_params, initial_config, traffic_lights)
[ "def", "__init__", "(", "self", ",", "name", ",", "vehicles", ",", "net_params", ",", "initial_config", "=", "InitialConfig", "(", ")", ",", "traffic_lights", "=", "TrafficLightParams", "(", ")", ")", ":", "for", "p", "in", "ADDITIONAL_NET_PARAMS", ".", "key...
https://github.com/flow-project/flow/blob/a511c41c48e6b928bb2060de8ad1ef3c3e3d9554/flow/networks/ring.py#L56-L68
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.3/django/contrib/auth/views.py
python
password_reset_confirm
(request, uidb36=None, token=None, template_name='registration/password_reset_confirm.html', token_generator=default_token_generator, set_password_form=SetPasswordForm, post_reset_redirect=None, current_app=None, extra_context=None)
return render_to_response(template_name, context, context_instance=RequestContext(request, current_app=current_app))
View that checks the hash in a password reset link and presents a form for entering a new password.
View that checks the hash in a password reset link and presents a form for entering a new password.
[ "View", "that", "checks", "the", "hash", "in", "a", "password", "reset", "link", "and", "presents", "a", "form", "for", "entering", "a", "new", "password", "." ]
def password_reset_confirm(request, uidb36=None, token=None, template_name='registration/password_reset_confirm.html', token_generator=default_token_generator, set_password_form=SetPasswordForm, post_reset_redirect=None, current_app=None, extra_context=None): """ View that checks the hash in a password reset link and presents a form for entering a new password. """ assert uidb36 is not None and token is not None # checked by URLconf if post_reset_redirect is None: post_reset_redirect = reverse('django.contrib.auth.views.password_reset_complete') try: uid_int = base36_to_int(uidb36) user = User.objects.get(id=uid_int) except (ValueError, User.DoesNotExist): user = None if user is not None and token_generator.check_token(user, token): validlink = True if request.method == 'POST': form = set_password_form(user, request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(post_reset_redirect) else: form = set_password_form(None) else: validlink = False form = None context = { 'form': form, 'validlink': validlink, } context.update(extra_context or {}) return render_to_response(template_name, context, context_instance=RequestContext(request, current_app=current_app))
[ "def", "password_reset_confirm", "(", "request", ",", "uidb36", "=", "None", ",", "token", "=", "None", ",", "template_name", "=", "'registration/password_reset_confirm.html'", ",", "token_generator", "=", "default_token_generator", ",", "set_password_form", "=", "SetPa...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.3/django/contrib/auth/views.py#L176-L213
nose-devs/nose2
e0dc345da06995fdf00abeb3ed4ae65050d552bd
nose2/util.py
python
safe_decode
(string)
Safely decode a byte string into unicode
Safely decode a byte string into unicode
[ "Safely", "decode", "a", "byte", "string", "into", "unicode" ]
def safe_decode(string): """Safely decode a byte string into unicode""" if string is None: return string try: return string.decode() except AttributeError: return string except UnicodeDecodeError: pass try: return string.decode("utf-8") except UnicodeDecodeError: return six.u("<unable to decode>")
[ "def", "safe_decode", "(", "string", ")", ":", "if", "string", "is", "None", ":", "return", "string", "try", ":", "return", "string", ".", "decode", "(", ")", "except", "AttributeError", ":", "return", "string", "except", "UnicodeDecodeError", ":", "pass", ...
https://github.com/nose-devs/nose2/blob/e0dc345da06995fdf00abeb3ed4ae65050d552bd/nose2/util.py#L267-L280
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/library/oc_serviceaccount.py
python
Yedit.write
(self)
return (True, self.yaml_dict)
write to file
write to file
[ "write", "to", "file" ]
def write(self): ''' write to file ''' if not self.filename: raise YeditException('Please specify a filename.') if self.backup and self.file_exists(): shutil.copy(self.filename, '{}{}'.format(self.filename, self.backup_ext)) # Try to set format attributes if supported try: self.yaml_dict.fa.set_block_style() except AttributeError: pass # Try to use RoundTripDumper if supported. if self.content_type == 'yaml': try: Yedit._write(self.filename, yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper)) except AttributeError: Yedit._write(self.filename, yaml.safe_dump(self.yaml_dict, default_flow_style=False)) elif self.content_type == 'json': Yedit._write(self.filename, json.dumps(self.yaml_dict, indent=4, sort_keys=True)) else: raise YeditException('Unsupported content_type: {}.'.format(self.content_type) + 'Please specify a content_type of yaml or json.') return (True, self.yaml_dict)
[ "def", "write", "(", "self", ")", ":", "if", "not", "self", ".", "filename", ":", "raise", "YeditException", "(", "'Please specify a filename.'", ")", "if", "self", ".", "backup", "and", "self", ".", "file_exists", "(", ")", ":", "shutil", ".", "copy", "...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/library/oc_serviceaccount.py#L347-L373
bugcrowd/HUNT
ed3e1adee724bf6c98750f377f6c40cd656c82d3
Burp/lib/issues.py
python
Issues.create_scanner_issues
(self, view, callbacks, helpers, vuln_parameters, request_response)
[]
def create_scanner_issues(self, view, callbacks, helpers, vuln_parameters, request_response): issues = self.issues json = self.json # Takes into account if there is more than one vulnerable parameter for vuln_parameter in vuln_parameters: issue_name = vuln_parameter["vuln_name"] vuln_param = vuln_parameter["vuln_param"] param_name = vuln_parameter["param"] param_value = vuln_parameter["value"] url = helpers.analyzeRequest(request_response).getUrl() url = urlparse.urlsplit(str(url)) hostname = url.hostname path = url.path url = url.scheme + "://" + url.hostname + url.path http_service = request_response.getHttpService() http_messages = [callbacks.applyMarkers(request_response, None, None)] detail = json["issues"][issue_name]["detail"] severity = "Medium" scanner_issue = ScannerIssue(url, issue_name, param_name, vuln_param, param_value, hostname, path, http_service, http_messages, detail, severity, request_response) is_scanner_issue_dupe = self.check_duplicate_issue(scanner_issue) if is_scanner_issue_dupe: continue else: self.set_scanner_issues(scanner_issue) issue_count = self.set_issue_count(issue_name, vuln_param) total_count = self.total_count[issue_name] view.set_scanner_count(issue_name, vuln_param, issue_count, total_count) view.scanner_table_models.set_scanner_table_model(scanner_issue, issue_name, param_name, vuln_param)
[ "def", "create_scanner_issues", "(", "self", ",", "view", ",", "callbacks", ",", "helpers", ",", "vuln_parameters", ",", "request_response", ")", ":", "issues", "=", "self", ".", "issues", "json", "=", "self", ".", "json", "# Takes into account if there is more th...
https://github.com/bugcrowd/HUNT/blob/ed3e1adee724bf6c98750f377f6c40cd656c82d3/Burp/lib/issues.py#L118-L152
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/django_wsgiserver/wsgiserver/wsgiserver2.py
python
ThreadPool.shrink
(self, amount)
Kill off worker threads (not below self.min).
Kill off worker threads (not below self.min).
[ "Kill", "off", "worker", "threads", "(", "not", "below", "self", ".", "min", ")", "." ]
def shrink(self, amount): """Kill off worker threads (not below self.min).""" # Grow/shrink the pool if necessary. # Remove any dead threads from our list for t in self._threads: if not t.isAlive(): self._threads.remove(t) amount -= 1 # calculate the number of threads above the minimum n_extra = max(len(self._threads) - self.min, 0) # don't remove more than amount n_to_remove = min(amount, n_extra) # put shutdown requests on the queue equal to the number of threads # to remove. As each request is processed by a worker, that worker # will terminate and be culled from the list. for n in range(n_to_remove): self._queue.put(_SHUTDOWNREQUEST)
[ "def", "shrink", "(", "self", ",", "amount", ")", ":", "# Grow/shrink the pool if necessary.", "# Remove any dead threads from our list", "for", "t", "in", "self", ".", "_threads", ":", "if", "not", "t", ".", "isAlive", "(", ")", ":", "self", ".", "_threads", ...
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/django_wsgiserver/wsgiserver/wsgiserver2.py#L1527-L1546
rembo10/headphones
b3199605be1ebc83a7a8feab6b1e99b64014187c
lib/apscheduler/schedulers/twisted.py
python
TwistedScheduler._configure
(self, config)
[]
def _configure(self, config): self._reactor = maybe_ref(config.pop('reactor', default_reactor)) super(TwistedScheduler, self)._configure(config)
[ "def", "_configure", "(", "self", ",", "config", ")", ":", "self", ".", "_reactor", "=", "maybe_ref", "(", "config", ".", "pop", "(", "'reactor'", ",", "default_reactor", ")", ")", "super", "(", "TwistedScheduler", ",", "self", ")", ".", "_configure", "(...
https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/apscheduler/schedulers/twisted.py#L34-L36
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/scipy/linalg/basic.py
python
pinvh
(a, cond=None, rcond=None, lower=True, return_rank=False, check_finite=True)
Compute the (Moore-Penrose) pseudo-inverse of a Hermitian matrix. Calculate a generalized inverse of a Hermitian or real symmetric matrix using its eigenvalue decomposition and including all eigenvalues with 'large' absolute value. Parameters ---------- a : (N, N) array_like Real symmetric or complex hermetian matrix to be pseudo-inverted cond, rcond : float or None Cutoff for 'small' eigenvalues. Singular values smaller than rcond * largest_eigenvalue are considered zero. If None or -1, suitable machine precision is used. lower : bool, optional Whether the pertinent array data is taken from the lower or upper triangle of a. (Default: lower) return_rank : bool, optional if True, return the effective rank of the matrix check_finite : bool, optional Whether to check that the input matrix contains only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. Returns ------- B : (N, N) ndarray The pseudo-inverse of matrix `a`. rank : int The effective rank of the matrix. Returned if return_rank == True Raises ------ LinAlgError If eigenvalue does not converge Examples -------- >>> from scipy.linalg import pinvh >>> a = np.random.randn(9, 6) >>> a = np.dot(a, a.T) >>> B = pinvh(a) >>> np.allclose(a, np.dot(a, np.dot(B, a))) True >>> np.allclose(B, np.dot(B, np.dot(a, B))) True
Compute the (Moore-Penrose) pseudo-inverse of a Hermitian matrix.
[ "Compute", "the", "(", "Moore", "-", "Penrose", ")", "pseudo", "-", "inverse", "of", "a", "Hermitian", "matrix", "." ]
def pinvh(a, cond=None, rcond=None, lower=True, return_rank=False, check_finite=True): """ Compute the (Moore-Penrose) pseudo-inverse of a Hermitian matrix. Calculate a generalized inverse of a Hermitian or real symmetric matrix using its eigenvalue decomposition and including all eigenvalues with 'large' absolute value. Parameters ---------- a : (N, N) array_like Real symmetric or complex hermetian matrix to be pseudo-inverted cond, rcond : float or None Cutoff for 'small' eigenvalues. Singular values smaller than rcond * largest_eigenvalue are considered zero. If None or -1, suitable machine precision is used. lower : bool, optional Whether the pertinent array data is taken from the lower or upper triangle of a. (Default: lower) return_rank : bool, optional if True, return the effective rank of the matrix check_finite : bool, optional Whether to check that the input matrix contains only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. Returns ------- B : (N, N) ndarray The pseudo-inverse of matrix `a`. rank : int The effective rank of the matrix. Returned if return_rank == True Raises ------ LinAlgError If eigenvalue does not converge Examples -------- >>> from scipy.linalg import pinvh >>> a = np.random.randn(9, 6) >>> a = np.dot(a, a.T) >>> B = pinvh(a) >>> np.allclose(a, np.dot(a, np.dot(B, a))) True >>> np.allclose(B, np.dot(B, np.dot(a, B))) True """ a = _asarray_validated(a, check_finite=check_finite) s, u = decomp.eigh(a, lower=lower, check_finite=False) if rcond is not None: cond = rcond if cond in [None, -1]: t = u.dtype.char.lower() factor = {'f': 1E3, 'd': 1E6} cond = factor[t] * np.finfo(t).eps # For Hermitian matrices, singular values equal abs(eigenvalues) above_cutoff = (abs(s) > cond * np.max(abs(s))) psigma_diag = 1.0 / s[above_cutoff] u = u[:, above_cutoff] B = np.dot(u * psigma_diag, np.conjugate(u).T) if return_rank: return B, len(psigma_diag) else: return B
[ "def", "pinvh", "(", "a", ",", "cond", "=", "None", ",", "rcond", "=", "None", ",", "lower", "=", "True", ",", "return_rank", "=", "False", ",", "check_finite", "=", "True", ")", ":", "a", "=", "_asarray_validated", "(", "a", ",", "check_finite", "="...
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/scipy/linalg/basic.py#L1054-L1127
josiah-wolf-oberholtzer/supriya
5ca725a6b97edfbe016a75666d420ecfdf49592f
supriya/intervals/Moment.py
python
Moment.start_intervals
(self)
return self._start_intervals
Gets the intervals in this moment which start at this moment's start offset.
Gets the intervals in this moment which start at this moment's start offset.
[ "Gets", "the", "intervals", "in", "this", "moment", "which", "start", "at", "this", "moment", "s", "start", "offset", "." ]
def start_intervals(self): """ Gets the intervals in this moment which start at this moment's start offset. """ return self._start_intervals
[ "def", "start_intervals", "(", "self", ")", ":", "return", "self", ".", "_start_intervals" ]
https://github.com/josiah-wolf-oberholtzer/supriya/blob/5ca725a6b97edfbe016a75666d420ecfdf49592f/supriya/intervals/Moment.py#L119-L124
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/plat-sunos5/IN.py
python
btopr
(x)
return ((((x) + PAGEOFFSET) >> PAGESHIFT))
[]
def btopr(x): return ((((x) + PAGEOFFSET) >> PAGESHIFT))
[ "def", "btopr", "(", "x", ")", ":", "return", "(", "(", "(", "(", "x", ")", "+", "PAGEOFFSET", ")", ">>", "PAGESHIFT", ")", ")" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/plat-sunos5/IN.py#L154-L154
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-windows/x86/ldap3/core/server.py
python
Server._is_ipv6
(host)
return True
[]
def _is_ipv6(host): try: socket.inet_pton(socket.AF_INET6, host) except (socket.error, AttributeError, ValueError): return False return True
[ "def", "_is_ipv6", "(", "host", ")", ":", "try", ":", "socket", ".", "inet_pton", "(", "socket", ".", "AF_INET6", ",", "host", ")", "except", "(", "socket", ".", "error", ",", "AttributeError", ",", "ValueError", ")", ":", "return", "False", "return", ...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-windows/x86/ldap3/core/server.py#L207-L212
wiseman/mavelous
eef41c096cc282bb3acd33a747146a88d2bd1eee
mavproxy.py
python
beep
()
[]
def beep(): f = open("/dev/tty", mode="w") f.write(chr(7)) f.close()
[ "def", "beep", "(", ")", ":", "f", "=", "open", "(", "\"/dev/tty\"", ",", "mode", "=", "\"w\"", ")", "f", ".", "write", "(", "chr", "(", "7", ")", ")", "f", ".", "close", "(", ")" ]
https://github.com/wiseman/mavelous/blob/eef41c096cc282bb3acd33a747146a88d2bd1eee/mavproxy.py#L903-L906
python-discord/bot
26c5587ac13e5414361bb6e7ada42983b81014d2
bot/utils/messages.py
python
send_attachments
( message: discord.Message, destination: Union[discord.TextChannel, discord.Webhook], link_large: bool = True, use_cached: bool = False, **kwargs )
return urls
Re-upload the message's attachments to the destination and return a list of their new URLs. Each attachment is sent as a separate message to more easily comply with the request/file size limit. If link_large is True, attachments which are too large are instead grouped into a single embed which links to them. Extra kwargs will be passed to send() when sending the attachment.
Re-upload the message's attachments to the destination and return a list of their new URLs.
[ "Re", "-", "upload", "the", "message", "s", "attachments", "to", "the", "destination", "and", "return", "a", "list", "of", "their", "new", "URLs", "." ]
async def send_attachments( message: discord.Message, destination: Union[discord.TextChannel, discord.Webhook], link_large: bool = True, use_cached: bool = False, **kwargs ) -> List[str]: """ Re-upload the message's attachments to the destination and return a list of their new URLs. Each attachment is sent as a separate message to more easily comply with the request/file size limit. If link_large is True, attachments which are too large are instead grouped into a single embed which links to them. Extra kwargs will be passed to send() when sending the attachment. """ webhook_send_kwargs = { 'username': message.author.display_name, 'avatar_url': message.author.display_avatar.url, } webhook_send_kwargs.update(kwargs) webhook_send_kwargs['username'] = sub_clyde(webhook_send_kwargs['username']) large = [] urls = [] for attachment in message.attachments: failure_msg = ( f"Failed to re-upload attachment {attachment.filename} from message {message.id}" ) try: # Allow 512 bytes of leeway for the rest of the request. # This should avoid most files that are too large, # but some may get through hence the try-catch. if attachment.size <= destination.guild.filesize_limit - 512: with BytesIO() as file: await attachment.save(file, use_cached=use_cached) attachment_file = discord.File(file, filename=attachment.filename) if isinstance(destination, discord.TextChannel): msg = await destination.send(file=attachment_file, **kwargs) urls.append(msg.attachments[0].url) else: await destination.send(file=attachment_file, **webhook_send_kwargs) elif link_large: large.append(attachment) else: log.info(f"{failure_msg} because it's too large.") except discord.HTTPException as e: if link_large and e.status == 413: large.append(attachment) else: log.warning(f"{failure_msg} with status {e.status}.", exc_info=e) if link_large and large: desc = "\n".join(f"[{attachment.filename}]({attachment.url})" for attachment in large) embed = discord.Embed(description=desc) embed.set_footer(text="Attachments exceed upload size limit.") if isinstance(destination, discord.TextChannel): await destination.send(embed=embed, **kwargs) else: await destination.send(embed=embed, **webhook_send_kwargs) return urls
[ "async", "def", "send_attachments", "(", "message", ":", "discord", ".", "Message", ",", "destination", ":", "Union", "[", "discord", ".", "TextChannel", ",", "discord", ".", "Webhook", "]", ",", "link_large", ":", "bool", "=", "True", ",", "use_cached", "...
https://github.com/python-discord/bot/blob/26c5587ac13e5414361bb6e7ada42983b81014d2/bot/utils/messages.py#L108-L170