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
fortharris/Pcode
147962d160a834c219e12cb456abc130826468e4
rope/base/builtins.py
python
_zip_function
(args)
return get_list(tuple)
[]
def _zip_function(args): args = args.get_pynames(['sequence']) objects = [] for seq in args: if seq is None: holding = None else: holding = _infer_sequence_for_pyname(seq) objects.append(holding) tuple = get_tuple(*objects) return get_list(tuple)
[ "def", "_zip_function", "(", "args", ")", ":", "args", "=", "args", ".", "get_pynames", "(", "[", "'sequence'", "]", ")", "objects", "=", "[", "]", "for", "seq", "in", "args", ":", "if", "seq", "is", "None", ":", "holding", "=", "None", "else", ":"...
https://github.com/fortharris/Pcode/blob/147962d160a834c219e12cb456abc130826468e4/rope/base/builtins.py#L727-L737
devitocodes/devito
6abd441e3f5f091775ad332be6b95e017b8cbd16
devito/types/dimension.py
python
Dimension._arg_values
(self, interval, grid, args=None, **kwargs)
return {self.min_name: loc_minv, self.max_name: loc_maxv}
Produce a map of argument values after evaluating user input. If no user input is provided, get a known value in ``args`` and adjust it so that no out-of-bounds memory accesses will be performeed. The adjustment exploits the information in ``interval``, an Interval describing the Dimension data space. If no value is available in ``args``, use a default value. Parameters ---------- interval : Interval Description of the Dimension data space. grid : Grid Used for spacing overriding and MPI execution; if ``self`` is a distributed Dimension, then ``grid`` is used to translate user input into rank-local indices. **kwargs Dictionary of user-provided argument overrides.
Produce a map of argument values after evaluating user input. If no user input is provided, get a known value in ``args`` and adjust it so that no out-of-bounds memory accesses will be performeed. The adjustment exploits the information in ``interval``, an Interval describing the Dimension data space. If no value is available in ``args``, use a default value.
[ "Produce", "a", "map", "of", "argument", "values", "after", "evaluating", "user", "input", ".", "If", "no", "user", "input", "is", "provided", "get", "a", "known", "value", "in", "args", "and", "adjust", "it", "so", "that", "no", "out", "-", "of", "-",...
def _arg_values(self, interval, grid, args=None, **kwargs): """ Produce a map of argument values after evaluating user input. If no user input is provided, get a known value in ``args`` and adjust it so that no out-of-bounds memory accesses will be performeed. The adjustment exploits the information in ``interval``, an Interval describing the Dimension data space. If no value is available in ``args``, use a default value. Parameters ---------- interval : Interval Description of the Dimension data space. grid : Grid Used for spacing overriding and MPI execution; if ``self`` is a distributed Dimension, then ``grid`` is used to translate user input into rank-local indices. **kwargs Dictionary of user-provided argument overrides. """ # Fetch user input and convert into rank-local values glb_minv = kwargs.pop(self.min_name, None) glb_maxv = kwargs.pop(self.max_name, kwargs.pop(self.name, None)) if grid is not None and grid.is_distributed(self): loc_minv, loc_maxv = grid.distributor.glb_to_loc(self, (glb_minv, glb_maxv)) else: loc_minv, loc_maxv = glb_minv, glb_maxv # If no user-override provided, use a suitable default value defaults = self._arg_defaults() if glb_minv is None: loc_minv = args.get(self.min_name, defaults[self.min_name]) try: loc_minv -= min(interval.lower, 0) except (AttributeError, TypeError): pass if glb_maxv is None: loc_maxv = args.get(self.max_name, defaults[self.max_name]) try: loc_maxv -= max(interval.upper, 0) except (AttributeError, TypeError): pass return {self.min_name: loc_minv, self.max_name: loc_maxv}
[ "def", "_arg_values", "(", "self", ",", "interval", ",", "grid", ",", "args", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Fetch user input and convert into rank-local values", "glb_minv", "=", "kwargs", ".", "pop", "(", "self", ".", "min_name", ",", "...
https://github.com/devitocodes/devito/blob/6abd441e3f5f091775ad332be6b95e017b8cbd16/devito/types/dimension.py#L229-L271
styxit/HTPC-Manager
490697460b4fa1797106aece27d873bc256b2ff1
libs/cherrypy/lib/static.py
python
staticdir
(section, dir, root="", match="", content_types=None, index="", debug=False)
return handled
Serve a static resource from the given (root +) dir. match If given, request.path_info will be searched for the given regular expression before attempting to serve static content. content_types If given, it should be a Python dictionary of {file-extension: content-type} pairs, where 'file-extension' is a string (e.g. "gif") and 'content-type' is the value to write out in the Content-Type response header (e.g. "image/gif"). index If provided, it should be the (relative) name of a file to serve for directory requests. For example, if the dir argument is '/home/me', the Request-URI is 'myapp', and the index arg is 'index.html', the file '/home/me/myapp/index.html' will be sought.
Serve a static resource from the given (root +) dir. match If given, request.path_info will be searched for the given regular expression before attempting to serve static content. content_types If given, it should be a Python dictionary of {file-extension: content-type} pairs, where 'file-extension' is a string (e.g. "gif") and 'content-type' is the value to write out in the Content-Type response header (e.g. "image/gif"). index If provided, it should be the (relative) name of a file to serve for directory requests. For example, if the dir argument is '/home/me', the Request-URI is 'myapp', and the index arg is 'index.html', the file '/home/me/myapp/index.html' will be sought.
[ "Serve", "a", "static", "resource", "from", "the", "given", "(", "root", "+", ")", "dir", ".", "match", "If", "given", "request", ".", "path_info", "will", "be", "searched", "for", "the", "given", "regular", "expression", "before", "attempting", "to", "ser...
def staticdir(section, dir, root="", match="", content_types=None, index="", debug=False): """Serve a static resource from the given (root +) dir. match If given, request.path_info will be searched for the given regular expression before attempting to serve static content. content_types If given, it should be a Python dictionary of {file-extension: content-type} pairs, where 'file-extension' is a string (e.g. "gif") and 'content-type' is the value to write out in the Content-Type response header (e.g. "image/gif"). index If provided, it should be the (relative) name of a file to serve for directory requests. For example, if the dir argument is '/home/me', the Request-URI is 'myapp', and the index arg is 'index.html', the file '/home/me/myapp/index.html' will be sought. """ request = cherrypy.serving.request if request.method not in ('GET', 'HEAD'): if debug: cherrypy.log('request.method not GET or HEAD', 'TOOLS.STATICDIR') return False if match and not re.search(match, request.path_info): if debug: cherrypy.log('request.path_info %r does not match pattern %r' % (request.path_info, match), 'TOOLS.STATICDIR') return False # Allow the use of '~' to refer to a user's home directory. dir = os.path.expanduser(dir) # If dir is relative, make absolute using "root". if not os.path.isabs(dir): if not root: msg = "Static dir requires an absolute dir (or root)." if debug: cherrypy.log(msg, 'TOOLS.STATICDIR') raise ValueError(msg) dir = os.path.join(root, dir) # Determine where we are in the object tree relative to 'section' # (where the static tool was defined). if section == 'global': section = "/" section = section.rstrip(r"\/") branch = request.path_info[len(section) + 1:] branch = unquote(branch.lstrip(r"\/")) # If branch is "", filename will end in a slash filename = os.path.join(dir, branch) if debug: cherrypy.log('Checking file %r to fulfill %r' % (filename, request.path_info), 'TOOLS.STATICDIR') # There's a chance that the branch pulled from the URL might # have ".." or similar uplevel attacks in it. Check that the final # filename is a child of dir. if not os.path.normpath(filename).startswith(os.path.normpath(dir)): raise cherrypy.HTTPError(403) # Forbidden handled = _attempt(filename, content_types) if not handled: # Check for an index file if a folder was requested. if index: handled = _attempt(os.path.join(filename, index), content_types) if handled: request.is_index = filename[-1] in (r"\/") return handled
[ "def", "staticdir", "(", "section", ",", "dir", ",", "root", "=", "\"\"", ",", "match", "=", "\"\"", ",", "content_types", "=", "None", ",", "index", "=", "\"\"", ",", "debug", "=", "False", ")", ":", "request", "=", "cherrypy", ".", "serving", ".", ...
https://github.com/styxit/HTPC-Manager/blob/490697460b4fa1797106aece27d873bc256b2ff1/libs/cherrypy/lib/static.py#L255-L326
francisck/DanderSpritz_docs
86bb7caca5a957147f120b18bb5c31f299914904
Python/Core/Lib/mimetypes.py
python
guess_type
(url, strict=True)
return _db.guess_type(url, strict)
Guess the type of a file based on its URL. Return value is a tuple (type, encoding) where type is None if the type can't be guessed (no or unknown suffix) or a string of the form type/subtype, usable for a MIME Content-type header; and encoding is None for no encoding or the name of the program used to encode (e.g. compress or gzip). The mappings are table driven. Encoding suffixes are case sensitive; type suffixes are first tried case sensitive, then case insensitive. The suffixes .tgz, .taz and .tz (case sensitive!) are all mapped to ".tar.gz". (This is table-driven too, using the dictionary suffix_map). Optional `strict' argument when false adds a bunch of commonly found, but non-standard types.
Guess the type of a file based on its URL. Return value is a tuple (type, encoding) where type is None if the type can't be guessed (no or unknown suffix) or a string of the form type/subtype, usable for a MIME Content-type header; and encoding is None for no encoding or the name of the program used to encode (e.g. compress or gzip). The mappings are table driven. Encoding suffixes are case sensitive; type suffixes are first tried case sensitive, then case insensitive. The suffixes .tgz, .taz and .tz (case sensitive!) are all mapped to ".tar.gz". (This is table-driven too, using the dictionary suffix_map). Optional `strict' argument when false adds a bunch of commonly found, but non-standard types.
[ "Guess", "the", "type", "of", "a", "file", "based", "on", "its", "URL", ".", "Return", "value", "is", "a", "tuple", "(", "type", "encoding", ")", "where", "type", "is", "None", "if", "the", "type", "can", "t", "be", "guessed", "(", "no", "or", "unk...
def guess_type(url, strict=True): """Guess the type of a file based on its URL. Return value is a tuple (type, encoding) where type is None if the type can't be guessed (no or unknown suffix) or a string of the form type/subtype, usable for a MIME Content-type header; and encoding is None for no encoding or the name of the program used to encode (e.g. compress or gzip). The mappings are table driven. Encoding suffixes are case sensitive; type suffixes are first tried case sensitive, then case insensitive. The suffixes .tgz, .taz and .tz (case sensitive!) are all mapped to ".tar.gz". (This is table-driven too, using the dictionary suffix_map). Optional `strict' argument when false adds a bunch of commonly found, but non-standard types. """ global _db if _db is None: init() return _db.guess_type(url, strict)
[ "def", "guess_type", "(", "url", ",", "strict", "=", "True", ")", ":", "global", "_db", "if", "_db", "is", "None", ":", "init", "(", ")", "return", "_db", ".", "guess_type", "(", "url", ",", "strict", ")" ]
https://github.com/francisck/DanderSpritz_docs/blob/86bb7caca5a957147f120b18bb5c31f299914904/Python/Core/Lib/mimetypes.py#L276-L297
prompt-toolkit/python-prompt-toolkit
e9eac2eb59ec385e81742fa2ac623d4b8de00925
prompt_toolkit/input/win32_pipe.py
python
Win32PipeInput.send_text
(self, text: str)
Send text to the input.
Send text to the input.
[ "Send", "text", "to", "the", "input", "." ]
def send_text(self, text: str) -> None: "Send text to the input." # Pass it through our vt100 parser. self.vt100_parser.feed(text) # Set event. windll.kernel32.SetEvent(self._event)
[ "def", "send_text", "(", "self", ",", "text", ":", "str", ")", "->", "None", ":", "# Pass it through our vt100 parser.", "self", ".", "vt100_parser", ".", "feed", "(", "text", ")", "# Set event.", "windll", ".", "kernel32", ".", "SetEvent", "(", "self", ".",...
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/e9eac2eb59ec385e81742fa2ac623d4b8de00925/prompt_toolkit/input/win32_pipe.py#L112-L118
csujedihy/lc-all-solutions
b9fd938a7b3c164f28096361993600e338c399c3
357.count-numbers-with-unique-digits/count-numbers-with-unique-digits.py
python
Solution.countNumbersWithUniqueDigits
(self, n)
return sum(dp) + 1
:type n: int :rtype: int4
:type n: int :rtype: int4
[ ":", "type", "n", ":", "int", ":", "rtype", ":", "int4" ]
def countNumbersWithUniqueDigits(self, n): """ :type n: int :rtype: int4 """ if n <= 1: return 10 ** n dp = [0] * (n + 1) dp[0] = 0 dp[1] = 9 k = 9 for i in range(2, n + 1): dp[i] = max(dp[i - 1] * k, 0) k -= 1 return sum(dp) + 1
[ "def", "countNumbersWithUniqueDigits", "(", "self", ",", "n", ")", ":", "if", "n", "<=", "1", ":", "return", "10", "**", "n", "dp", "=", "[", "0", "]", "*", "(", "n", "+", "1", ")", "dp", "[", "0", "]", "=", "0", "dp", "[", "1", "]", "=", ...
https://github.com/csujedihy/lc-all-solutions/blob/b9fd938a7b3c164f28096361993600e338c399c3/357.count-numbers-with-unique-digits/count-numbers-with-unique-digits.py#L2-L16
Yukinoshita47/Yuki-Chan-The-Auto-Pentest
bea1af4e1d544eadc166f728be2f543ea10af191
Module/metagoofil/hachoir_core/tools.py
python
timestampMac32
(value)
return MAC_TIMESTAMP_T0 + timedelta(seconds=value)
Convert an Mac (32-bit) timestamp to string. The format is the number of seconds since the 1st January 1904 (to 2040). Returns unicode string. >>> timestampMac32(0) datetime.datetime(1904, 1, 1, 0, 0) >>> timestampMac32(2843043290) datetime.datetime(1994, 2, 2, 14, 14, 50)
Convert an Mac (32-bit) timestamp to string. The format is the number of seconds since the 1st January 1904 (to 2040). Returns unicode string.
[ "Convert", "an", "Mac", "(", "32", "-", "bit", ")", "timestamp", "to", "string", ".", "The", "format", "is", "the", "number", "of", "seconds", "since", "the", "1st", "January", "1904", "(", "to", "2040", ")", ".", "Returns", "unicode", "string", "." ]
def timestampMac32(value): """ Convert an Mac (32-bit) timestamp to string. The format is the number of seconds since the 1st January 1904 (to 2040). Returns unicode string. >>> timestampMac32(0) datetime.datetime(1904, 1, 1, 0, 0) >>> timestampMac32(2843043290) datetime.datetime(1994, 2, 2, 14, 14, 50) """ if not isinstance(value, (float, int, long)): raise TypeError("an integer or float is required") if not(0 <= value <= 4294967295): return _("invalid Mac timestamp (%s)") % value return MAC_TIMESTAMP_T0 + timedelta(seconds=value)
[ "def", "timestampMac32", "(", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "(", "float", ",", "int", ",", "long", ")", ")", ":", "raise", "TypeError", "(", "\"an integer or float is required\"", ")", "if", "not", "(", "0", "<=", "valu...
https://github.com/Yukinoshita47/Yuki-Chan-The-Auto-Pentest/blob/bea1af4e1d544eadc166f728be2f543ea10af191/Module/metagoofil/hachoir_core/tools.py#L473-L487
google/apis-client-generator
f09f0ba855c3845d315b811c6234fd3996f33172
src/googleapis/codegen/cpp_generator.py
python
CppGenerator.AnnotateProperty
(self, unused_api, prop, unused_schema)
Annotate a Property with C++ specific elements.
Annotate a Property with C++ specific elements.
[ "Annotate", "a", "Property", "with", "C", "++", "specific", "elements", "." ]
def AnnotateProperty(self, unused_api, prop, unused_schema): """Annotate a Property with C++ specific elements.""" super(CppGenerator, self).AnnotateProperty(unused_api, prop, unused_schema) prop.SetTemplateValue('isPrimitive', self._IsPrimitiveType(prop.data_type)) base_type = prop.data_type if base_type.GetTemplateValue('isContainer'): base_type = base_type.GetTemplateValue('baseType') try: has_parent = base_type.parent except AttributeError: has_parent = False if not base_type.GetTemplateValue('builtIn') and not has_parent: # Since the property's base type doesn't have a parent, the # base type may be safely used by a split accessor definition # at the top-level scope. # # Since the property's base type is not a built-in type, it # might be part of a set of mutually recursive types, which # can *only* be safely used by a split accessor definition at # the top-level scope, after all of the potentially recursive # class definitions have been emitted. # # So: we set the useSplitAccessor template value, causing C++ # template expansion to declare the accessor methods for this # property as part of the object, but to define them separately # at the top-level scope. prop.SetTemplateValue('useSplitAccessor', True) self._HandleImports(prop) self.AnnotateDocumentation(prop)
[ "def", "AnnotateProperty", "(", "self", ",", "unused_api", ",", "prop", ",", "unused_schema", ")", ":", "super", "(", "CppGenerator", ",", "self", ")", ".", "AnnotateProperty", "(", "unused_api", ",", "prop", ",", "unused_schema", ")", "prop", ".", "SetTempl...
https://github.com/google/apis-client-generator/blob/f09f0ba855c3845d315b811c6234fd3996f33172/src/googleapis/codegen/cpp_generator.py#L298-L329
poljar/matrix-nio
ecb548144a5c4f6a5d18e23b6a844374526c1bd1
nio/client/async_client.py
python
AsyncClient.send
( self, method: str, path: str, data: Union[None, str, AsyncDataT] = None, headers: Optional[Dict[str, str]] = None, trace_context: Any = None, timeout: Optional[float] = None, )
return await self.client_session.request( method, self.homeserver + path, data=data, ssl=self.ssl, headers=headers, trace_request_ctx=trace_context, timeout=self.config.request_timeout if timeout is None else timeout, )
Send a request to the homeserver. This function does not call receive_response(). Args: method (str): The request method that should be used. One of get, post, put, delete. path (str): The URL path of the request. data (str, optional): Data that will be posted with the request. headers (Dict[str,str] , optional): Additional request headers that should be used with the request. trace_context (Any, optional): An object to use for the ClientSession TraceConfig context timeout (int, optional): How many seconds the request has before raising `asyncio.TimeoutError`. Overrides `AsyncClient.config.request_timeout` if not `None`.
Send a request to the homeserver.
[ "Send", "a", "request", "to", "the", "homeserver", "." ]
async def send( self, method: str, path: str, data: Union[None, str, AsyncDataT] = None, headers: Optional[Dict[str, str]] = None, trace_context: Any = None, timeout: Optional[float] = None, ) -> ClientResponse: """Send a request to the homeserver. This function does not call receive_response(). Args: method (str): The request method that should be used. One of get, post, put, delete. path (str): The URL path of the request. data (str, optional): Data that will be posted with the request. headers (Dict[str,str] , optional): Additional request headers that should be used with the request. trace_context (Any, optional): An object to use for the ClientSession TraceConfig context timeout (int, optional): How many seconds the request has before raising `asyncio.TimeoutError`. Overrides `AsyncClient.config.request_timeout` if not `None`. """ assert self.client_session return await self.client_session.request( method, self.homeserver + path, data=data, ssl=self.ssl, headers=headers, trace_request_ctx=trace_context, timeout=self.config.request_timeout if timeout is None else timeout, )
[ "async", "def", "send", "(", "self", ",", "method", ":", "str", ",", "path", ":", "str", ",", "data", ":", "Union", "[", "None", ",", "str", ",", "AsyncDataT", "]", "=", "None", ",", "headers", ":", "Optional", "[", "Dict", "[", "str", ",", "str"...
https://github.com/poljar/matrix-nio/blob/ecb548144a5c4f6a5d18e23b6a844374526c1bd1/nio/client/async_client.py#L788-L826
WikidPad/WikidPad
558109638807bc76b4672922686e416ab2d5f79c
WikidPad/lib/pwiki/timeView/DatedWikiWordFilters.py
python
DatedWikiWordFilterBase._getMinMaxDaysFromTimeT
(self, timeMinMax)
return (self._getDayFromTimeT(timeMinMax[0]), self._getNextDayFromTimeT(timeMinMax[1]))
Helper to convert time_t min/max values from WikiDocument to wx.DateTime objects.
Helper to convert time_t min/max values from WikiDocument to wx.DateTime objects.
[ "Helper", "to", "convert", "time_t", "min", "/", "max", "values", "from", "WikiDocument", "to", "wx", ".", "DateTime", "objects", "." ]
def _getMinMaxDaysFromTimeT(self, timeMinMax): """ Helper to convert time_t min/max values from WikiDocument to wx.DateTime objects. """ if timeMinMax == (None, None): return (None, None) return (self._getDayFromTimeT(timeMinMax[0]), self._getNextDayFromTimeT(timeMinMax[1]))
[ "def", "_getMinMaxDaysFromTimeT", "(", "self", ",", "timeMinMax", ")", ":", "if", "timeMinMax", "==", "(", "None", ",", "None", ")", ":", "return", "(", "None", ",", "None", ")", "return", "(", "self", ".", "_getDayFromTimeT", "(", "timeMinMax", "[", "0"...
https://github.com/WikidPad/WikidPad/blob/558109638807bc76b4672922686e416ab2d5f79c/WikidPad/lib/pwiki/timeView/DatedWikiWordFilters.py#L81-L90
amimo/dcc
114326ab5a082a42c7728a375726489e4709ca29
androguard/gui/sourcewindow.py
python
MyHighlighter._clear_caches
(self)
Clear caches for brushes and formats.
Clear caches for brushes and formats.
[ "Clear", "caches", "for", "brushes", "and", "formats", "." ]
def _clear_caches(self): """ Clear caches for brushes and formats. """ self._brushes = {} self._formats = {}
[ "def", "_clear_caches", "(", "self", ")", ":", "self", ".", "_brushes", "=", "{", "}", "self", ".", "_formats", "=", "{", "}" ]
https://github.com/amimo/dcc/blob/114326ab5a082a42c7728a375726489e4709ca29/androguard/gui/sourcewindow.py#L224-L228
wusaifei/garbage_classify
107b0c02499828e72978b6fe0aa704ecb9457d30
deploy_scripts/customize_service.py
python
garbage_classify_service.preprocess_img
(self, img)
return img
image preprocessing you can add your special preprocess method here
image preprocessing you can add your special preprocess method here
[ "image", "preprocessing", "you", "can", "add", "your", "special", "preprocess", "method", "here" ]
def preprocess_img(self, img): """ image preprocessing you can add your special preprocess method here """ resize_scale = self.input_size / max(img.size[:2]) img = img.resize((int(img.size[0] * resize_scale), int(img.size[1] * resize_scale))) img = img.convert('RGB') img = np.array(img) img = img[:, :, ::-1] img = self.center_img(img, self.input_size) return img
[ "def", "preprocess_img", "(", "self", ",", "img", ")", ":", "resize_scale", "=", "self", ".", "input_size", "/", "max", "(", "img", ".", "size", "[", ":", "2", "]", ")", "img", "=", "img", ".", "resize", "(", "(", "int", "(", "img", ".", "size", ...
https://github.com/wusaifei/garbage_classify/blob/107b0c02499828e72978b6fe0aa704ecb9457d30/deploy_scripts/customize_service.py#L93-L104
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/_layout.py
python
Layout.meta
(self)
return self["meta"]
Assigns extra meta information that can be used in various `text` attributes. Attributes such as the graph, axis and colorbar `title.text`, annotation `text` `trace.name` in legend items, `rangeselector`, `updatemenus` and `sliders` `label` text all support `meta`. One can access `meta` fields using template strings: `%{meta[i]}` where `i` is the index of the `meta` item in question. `meta` can also be an object for example `{key: value}` which can be accessed %{meta[key]}. The 'meta' property accepts values of any type Returns ------- Any|numpy.ndarray
Assigns extra meta information that can be used in various `text` attributes. Attributes such as the graph, axis and colorbar `title.text`, annotation `text` `trace.name` in legend items, `rangeselector`, `updatemenus` and `sliders` `label` text all support `meta`. One can access `meta` fields using template strings: `%{meta[i]}` where `i` is the index of the `meta` item in question. `meta` can also be an object for example `{key: value}` which can be accessed %{meta[key]}. The 'meta' property accepts values of any type
[ "Assigns", "extra", "meta", "information", "that", "can", "be", "used", "in", "various", "text", "attributes", ".", "Attributes", "such", "as", "the", "graph", "axis", "and", "colorbar", "title", ".", "text", "annotation", "text", "trace", ".", "name", "in",...
def meta(self): """ Assigns extra meta information that can be used in various `text` attributes. Attributes such as the graph, axis and colorbar `title.text`, annotation `text` `trace.name` in legend items, `rangeselector`, `updatemenus` and `sliders` `label` text all support `meta`. One can access `meta` fields using template strings: `%{meta[i]}` where `i` is the index of the `meta` item in question. `meta` can also be an object for example `{key: value}` which can be accessed %{meta[key]}. The 'meta' property accepts values of any type Returns ------- Any|numpy.ndarray """ return self["meta"]
[ "def", "meta", "(", "self", ")", ":", "return", "self", "[", "\"meta\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/_layout.py#L2175-L2192
FORTH-ICS-INSPIRE/artemis
f0774af8abc25ef5c6b307960c048ff7528d8a9c
backend-services/mitigation/core/mitigation.py
python
MitigationDataWorker.stop_consumer_loop
(self, message: Dict)
Callback function that stop the current consumer loop
Callback function that stop the current consumer loop
[ "Callback", "function", "that", "stop", "the", "current", "consumer", "loop" ]
def stop_consumer_loop(self, message: Dict) -> NoReturn: """ Callback function that stop the current consumer loop """ message.ack() self.should_stop = True
[ "def", "stop_consumer_loop", "(", "self", ",", "message", ":", "Dict", ")", "->", "NoReturn", ":", "message", ".", "ack", "(", ")", "self", ".", "should_stop", "=", "True" ]
https://github.com/FORTH-ICS-INSPIRE/artemis/blob/f0774af8abc25ef5c6b307960c048ff7528d8a9c/backend-services/mitigation/core/mitigation.py#L339-L344
rwth-i6/returnn
f2d718a197a280b0d5f0fd91a7fcb8658560dddb
returnn/sprint/cache.py
python
FileArchive.file_list
(self)
return self.ft.keys()
:rtype: list[str]
:rtype: list[str]
[ ":", "rtype", ":", "list", "[", "str", "]" ]
def file_list(self): """ :rtype: list[str] """ return self.ft.keys()
[ "def", "file_list", "(", "self", ")", ":", "return", "self", ".", "ft", ".", "keys", "(", ")" ]
https://github.com/rwth-i6/returnn/blob/f2d718a197a280b0d5f0fd91a7fcb8658560dddb/returnn/sprint/cache.py#L208-L212
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/Lib/logging/handlers.py
python
WatchedFileHandler.emit
(self, record)
Emit a record. First check if the underlying file has changed, and if it has, close the old stream and reopen the file to get the current stream.
Emit a record.
[ "Emit", "a", "record", "." ]
def emit(self, record): """ Emit a record. First check if the underlying file has changed, and if it has, close the old stream and reopen the file to get the current stream. """ if not os.path.exists(self.baseFilename): stat = None changed = 1 else: stat = os.stat(self.baseFilename) changed = (stat[ST_DEV] != self.dev) or (stat[ST_INO] != self.ino) if changed and self.stream is not None: self.stream.flush() self.stream.close() self.stream = self._open() if stat is None: stat = os.stat(self.baseFilename) self.dev, self.ino = stat[ST_DEV], stat[ST_INO] logging.FileHandler.emit(self, record)
[ "def", "emit", "(", "self", ",", "record", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "baseFilename", ")", ":", "stat", "=", "None", "changed", "=", "1", "else", ":", "stat", "=", "os", ".", "stat", "(", "self", ...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/Lib/logging/handlers.py#L393-L414
chemlab/chemlab
c8730966316d101e24f39ac3b96b51282aba0abe
chemlab/graphics/qt/qttrajectory.py
python
QtTrajectoryViewer.add_ui
(self, klass, *args, **kwargs)
return ui
Add an UI element for the current scene. The approach is the same as renderers. .. warning:: The UI api is not yet finalized
Add an UI element for the current scene. The approach is the same as renderers.
[ "Add", "an", "UI", "element", "for", "the", "current", "scene", ".", "The", "approach", "is", "the", "same", "as", "renderers", "." ]
def add_ui(self, klass, *args, **kwargs): '''Add an UI element for the current scene. The approach is the same as renderers. .. warning:: The UI api is not yet finalized ''' ui = klass(self.widget, *args, **kwargs) self.widget.uis.append(ui) return ui
[ "def", "add_ui", "(", "self", ",", "klass", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ui", "=", "klass", "(", "self", ".", "widget", ",", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "widget", ".", "uis", ".", "append", ...
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/qt/qttrajectory.py#L351-L361
ewels/MultiQC
9b953261d3d684c24eef1827a5ce6718c847a5af
multiqc/modules/picard/VariantCallingMetrics.py
python
table_in
(filehandle, pre_header_string)
Generator that assumes a table starts the line after a given string
Generator that assumes a table starts the line after a given string
[ "Generator", "that", "assumes", "a", "table", "starts", "the", "line", "after", "a", "given", "string" ]
def table_in(filehandle, pre_header_string): """Generator that assumes a table starts the line after a given string""" in_histogram = False next_is_header = False headers = list() for line in stripped(filehandle): if not in_histogram and line.startswith(pre_header_string): in_histogram = True next_is_header = True elif in_histogram and next_is_header: next_is_header = False headers = line.split("\t") elif in_histogram: values = line.split("\t") if values != [""]: for couple in zip(headers, values): yield couple
[ "def", "table_in", "(", "filehandle", ",", "pre_header_string", ")", ":", "in_histogram", "=", "False", "next_is_header", "=", "False", "headers", "=", "list", "(", ")", "for", "line", "in", "stripped", "(", "filehandle", ")", ":", "if", "not", "in_histogram...
https://github.com/ewels/MultiQC/blob/9b953261d3d684c24eef1827a5ce6718c847a5af/multiqc/modules/picard/VariantCallingMetrics.py#L133-L150
harvimt/quamash
d9520f44ee19701769178bfa8b02bfd7b9904f78
quamash/_windows.py
python
_ProactorEventLoop._process_events
(self, events)
Process events from proactor.
Process events from proactor.
[ "Process", "events", "from", "proactor", "." ]
def _process_events(self, events): """Process events from proactor.""" for f, callback, transferred, key, ov in events: try: self._logger.debug('Invoking event callback {}'.format(callback)) value = callback(transferred, key, ov) except OSError: self._logger.warning('Event callback failed', exc_info=sys.exc_info()) else: f.set_result(value)
[ "def", "_process_events", "(", "self", ",", "events", ")", ":", "for", "f", ",", "callback", ",", "transferred", ",", "key", ",", "ov", "in", "events", ":", "try", ":", "self", ".", "_logger", ".", "debug", "(", "'Invoking event callback {}'", ".", "form...
https://github.com/harvimt/quamash/blob/d9520f44ee19701769178bfa8b02bfd7b9904f78/quamash/_windows.py#L37-L46
open-mmlab/mmdetection3d
c7272063e818bcf33aebc498a017a95c8d065143
tools/create_data.py
python
s3dis_data_prep
(root_path, info_prefix, out_dir, workers)
Prepare the info file for s3dis dataset. Args: root_path (str): Path of dataset root. info_prefix (str): The prefix of info filenames. out_dir (str): Output directory of the generated info file. workers (int): Number of threads to be used.
Prepare the info file for s3dis dataset.
[ "Prepare", "the", "info", "file", "for", "s3dis", "dataset", "." ]
def s3dis_data_prep(root_path, info_prefix, out_dir, workers): """Prepare the info file for s3dis dataset. Args: root_path (str): Path of dataset root. info_prefix (str): The prefix of info filenames. out_dir (str): Output directory of the generated info file. workers (int): Number of threads to be used. """ indoor.create_indoor_info_file( root_path, info_prefix, out_dir, workers=workers)
[ "def", "s3dis_data_prep", "(", "root_path", ",", "info_prefix", ",", "out_dir", ",", "workers", ")", ":", "indoor", ".", "create_indoor_info_file", "(", "root_path", ",", "info_prefix", ",", "out_dir", ",", "workers", "=", "workers", ")" ]
https://github.com/open-mmlab/mmdetection3d/blob/c7272063e818bcf33aebc498a017a95c8d065143/tools/create_data.py#L116-L126
MeanEYE/Sunflower
1024bbdde3b8e202ddad3553b321a7b6230bffc9
sunflower/plugins/file_list/gio_extension.py
python
DavExtension.__populate_list
(self)
Populate list with stored mounts
Populate list with stored mounts
[ "Populate", "list", "with", "stored", "mounts" ]
def __populate_list(self): """Populate list with stored mounts""" entries = self._application.mount_options.get(self.scheme) # no entries found, nothing to do here if entries is None: return # clear store self._store.clear() # add entries to the list store for entry in entries: self._store.append(( entry['name'], entry['server'], entry['server_type'], entry['directory'], entry['username'], entry['requires_login'], self.__form_uri(entry['server'], entry['server_type'], entry['username'], entry['directory']) ))
[ "def", "__populate_list", "(", "self", ")", ":", "entries", "=", "self", ".", "_application", ".", "mount_options", ".", "get", "(", "self", ".", "scheme", ")", "# no entries found, nothing to do here", "if", "entries", "is", "None", ":", "return", "# clear stor...
https://github.com/MeanEYE/Sunflower/blob/1024bbdde3b8e202ddad3553b321a7b6230bffc9/sunflower/plugins/file_list/gio_extension.py#L932-L953
007gzs/dingtalk-sdk
7979da2e259fdbc571728cae2425a04dbc65850a
dingtalk/client/api/taobao.py
python
TbWuDaoKou.taobao_wdk_equipment_conveyor_wcsbtoc_containerscannedbyconveyor
( self, warehouse_code='', wcs_num='' )
return self._top_request( "taobao.wdk.equipment.conveyor.wcsbtoc.containerscannedbyconveyor", { "warehouse_code": warehouse_code, "wcs_num": wcs_num } )
容器被悬挂链扫描 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=31283 :param warehouse_code: warehouse_code :param wcs_num: wcs_num
容器被悬挂链扫描 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=31283
[ "容器被悬挂链扫描", "文档地址:https", ":", "//", "open", "-", "doc", ".", "dingtalk", ".", "com", "/", "docs", "/", "api", ".", "htm?apiId", "=", "31283" ]
def taobao_wdk_equipment_conveyor_wcsbtoc_containerscannedbyconveyor( self, warehouse_code='', wcs_num='' ): """ 容器被悬挂链扫描 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=31283 :param warehouse_code: warehouse_code :param wcs_num: wcs_num """ return self._top_request( "taobao.wdk.equipment.conveyor.wcsbtoc.containerscannedbyconveyor", { "warehouse_code": warehouse_code, "wcs_num": wcs_num } )
[ "def", "taobao_wdk_equipment_conveyor_wcsbtoc_containerscannedbyconveyor", "(", "self", ",", "warehouse_code", "=", "''", ",", "wcs_num", "=", "''", ")", ":", "return", "self", ".", "_top_request", "(", "\"taobao.wdk.equipment.conveyor.wcsbtoc.containerscannedbyconveyor\"", "...
https://github.com/007gzs/dingtalk-sdk/blob/7979da2e259fdbc571728cae2425a04dbc65850a/dingtalk/client/api/taobao.py#L62468-L62486
znxlwm/UGATIT-pytorch
b8c4251823673189999484d07e97fdcb9300e9e0
networks.py
python
Discriminator.__init__
(self, input_nc, ndf=64, n_layers=5)
[]
def __init__(self, input_nc, ndf=64, n_layers=5): super(Discriminator, self).__init__() model = [nn.ReflectionPad2d(1), nn.utils.spectral_norm( nn.Conv2d(input_nc, ndf, kernel_size=4, stride=2, padding=0, bias=True)), nn.LeakyReLU(0.2, True)] for i in range(1, n_layers - 2): mult = 2 ** (i - 1) model += [nn.ReflectionPad2d(1), nn.utils.spectral_norm( nn.Conv2d(ndf * mult, ndf * mult * 2, kernel_size=4, stride=2, padding=0, bias=True)), nn.LeakyReLU(0.2, True)] mult = 2 ** (n_layers - 2 - 1) model += [nn.ReflectionPad2d(1), nn.utils.spectral_norm( nn.Conv2d(ndf * mult, ndf * mult * 2, kernel_size=4, stride=1, padding=0, bias=True)), nn.LeakyReLU(0.2, True)] # Class Activation Map mult = 2 ** (n_layers - 2) self.gap_fc = nn.utils.spectral_norm(nn.Linear(ndf * mult, 1, bias=False)) self.gmp_fc = nn.utils.spectral_norm(nn.Linear(ndf * mult, 1, bias=False)) self.conv1x1 = nn.Conv2d(ndf * mult * 2, ndf * mult, kernel_size=1, stride=1, bias=True) self.leaky_relu = nn.LeakyReLU(0.2, True) self.pad = nn.ReflectionPad2d(1) self.conv = nn.utils.spectral_norm( nn.Conv2d(ndf * mult, 1, kernel_size=4, stride=1, padding=0, bias=False)) self.model = nn.Sequential(*model)
[ "def", "__init__", "(", "self", ",", "input_nc", ",", "ndf", "=", "64", ",", "n_layers", "=", "5", ")", ":", "super", "(", "Discriminator", ",", "self", ")", ".", "__init__", "(", ")", "model", "=", "[", "nn", ".", "ReflectionPad2d", "(", "1", ")",...
https://github.com/znxlwm/UGATIT-pytorch/blob/b8c4251823673189999484d07e97fdcb9300e9e0/networks.py#L198-L229
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/polys/monomials.py
python
monomial_max
(*monoms)
return tuple(M)
Returns maximal degree for each variable in a set of monomials. Consider monomials `x**3*y**4*z**5`, `y**5*z` and `x**6*y**3*z**9`. We wish to find out what is the maximal degree for each of `x`, `y` and `z` variables:: >>> from sympy.polys.monomials import monomial_max >>> monomial_max((3,4,5), (0,5,1), (6,3,9)) (6, 5, 9)
Returns maximal degree for each variable in a set of monomials.
[ "Returns", "maximal", "degree", "for", "each", "variable", "in", "a", "set", "of", "monomials", "." ]
def monomial_max(*monoms): """ Returns maximal degree for each variable in a set of monomials. Consider monomials `x**3*y**4*z**5`, `y**5*z` and `x**6*y**3*z**9`. We wish to find out what is the maximal degree for each of `x`, `y` and `z` variables:: >>> from sympy.polys.monomials import monomial_max >>> monomial_max((3,4,5), (0,5,1), (6,3,9)) (6, 5, 9) """ M = list(monoms[0]) for N in monoms[1:]: for i, n in enumerate(N): M[i] = max(M[i], n) return tuple(M)
[ "def", "monomial_max", "(", "*", "monoms", ")", ":", "M", "=", "list", "(", "monoms", "[", "0", "]", ")", "for", "N", "in", "monoms", "[", "1", ":", "]", ":", "for", "i", ",", "n", "in", "enumerate", "(", "N", ")", ":", "M", "[", "i", "]", ...
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/polys/monomials.py#L204-L224
pytorch/captum
38b57082d22854013c0a0b80a51c0b85269afdaf
captum/attr/_core/noise_tunnel.py
python
NoiseTunnel.__init__
(self, attribution_method: Attribution)
r""" Args: attribution_method (Attribution): An instance of any attribution algorithm of type `Attribution`. E.g. Integrated Gradients, Conductance or Saliency.
r""" Args: attribution_method (Attribution): An instance of any attribution algorithm of type `Attribution`. E.g. Integrated Gradients, Conductance or Saliency.
[ "r", "Args", ":", "attribution_method", "(", "Attribution", ")", ":", "An", "instance", "of", "any", "attribution", "algorithm", "of", "type", "Attribution", ".", "E", ".", "g", ".", "Integrated", "Gradients", "Conductance", "or", "Saliency", "." ]
def __init__(self, attribution_method: Attribution) -> None: r""" Args: attribution_method (Attribution): An instance of any attribution algorithm of type `Attribution`. E.g. Integrated Gradients, Conductance or Saliency. """ self.attribution_method = attribution_method self.is_delta_supported = self.attribution_method.has_convergence_delta() self._multiply_by_inputs = self.attribution_method.multiplies_by_inputs self.is_gradient_method = isinstance( self.attribution_method, GradientAttribution ) Attribution.__init__(self, self.attribution_method.forward_func)
[ "def", "__init__", "(", "self", ",", "attribution_method", ":", "Attribution", ")", "->", "None", ":", "self", ".", "attribution_method", "=", "attribution_method", "self", ".", "is_delta_supported", "=", "self", ".", "attribution_method", ".", "has_convergence_delt...
https://github.com/pytorch/captum/blob/38b57082d22854013c0a0b80a51c0b85269afdaf/captum/attr/_core/noise_tunnel.py#L57-L70
apache/tvm
6eb4ed813ebcdcd9558f0906a1870db8302ff1e0
python/tvm/contrib/hexagon/build.py
python
HexagonLauncher.hexagon_setup
(self)
Upload Hexagon artifacts on Android.
Upload Hexagon artifacts on Android.
[ "Upload", "Hexagon", "artifacts", "on", "Android", "." ]
def hexagon_setup(self): """Upload Hexagon artifacts on Android.""" for item in HEXAGON_FILES: src_path = get_hexagon_rpc_dir() / item dst_path = f"{self._workspace}/{item}" subprocess.check_call(self._adb_device_sub_cmd + ["push", src_path, dst_path])
[ "def", "hexagon_setup", "(", "self", ")", ":", "for", "item", "in", "HEXAGON_FILES", ":", "src_path", "=", "get_hexagon_rpc_dir", "(", ")", "/", "item", "dst_path", "=", "f\"{self._workspace}/{item}\"", "subprocess", ".", "check_call", "(", "self", ".", "_adb_de...
https://github.com/apache/tvm/blob/6eb4ed813ebcdcd9558f0906a1870db8302ff1e0/python/tvm/contrib/hexagon/build.py#L179-L184
iiau-tracker/SPLT
a196e603798e9be969d9d985c087c11cad1cda43
lib/object_detection/core/anchor_generator.py
python
AnchorGenerator.generate
(self, feature_map_shape_list, **params)
Generates a collection of bounding boxes to be used as anchors. TODO: remove **params from argument list and make stride and offsets (for multiple_grid_anchor_generator) constructor arguments. Args: feature_map_shape_list: list of (height, width) pairs in the format [(height_0, width_0), (height_1, width_1), ...] that the generated anchors must align with. Pairs can be provided as 1-dimensional integer tensors of length 2 or simply as tuples of integers. **params: parameters for anchor generation op Returns: boxes: a BoxList holding a collection of N anchor boxes Raises: ValueError: if the number of feature map shapes does not match the length of NumAnchorsPerLocation.
Generates a collection of bounding boxes to be used as anchors.
[ "Generates", "a", "collection", "of", "bounding", "boxes", "to", "be", "used", "as", "anchors", "." ]
def generate(self, feature_map_shape_list, **params): """Generates a collection of bounding boxes to be used as anchors. TODO: remove **params from argument list and make stride and offsets (for multiple_grid_anchor_generator) constructor arguments. Args: feature_map_shape_list: list of (height, width) pairs in the format [(height_0, width_0), (height_1, width_1), ...] that the generated anchors must align with. Pairs can be provided as 1-dimensional integer tensors of length 2 or simply as tuples of integers. **params: parameters for anchor generation op Returns: boxes: a BoxList holding a collection of N anchor boxes Raises: ValueError: if the number of feature map shapes does not match the length of NumAnchorsPerLocation. """ if self.check_num_anchors and ( len(feature_map_shape_list) != len(self.num_anchors_per_location())): raise ValueError('Number of feature maps is expected to equal the length ' 'of `num_anchors_per_location`.') with tf.name_scope(self.name_scope()): anchors = self._generate(feature_map_shape_list, **params) if self.check_num_anchors: with tf.control_dependencies([ self._assert_correct_number_of_anchors( anchors, feature_map_shape_list)]): anchors.set(tf.identity(anchors.get())) return anchors
[ "def", "generate", "(", "self", ",", "feature_map_shape_list", ",", "*", "*", "params", ")", ":", "if", "self", ".", "check_num_anchors", "and", "(", "len", "(", "feature_map_shape_list", ")", "!=", "len", "(", "self", ".", "num_anchors_per_location", "(", "...
https://github.com/iiau-tracker/SPLT/blob/a196e603798e9be969d9d985c087c11cad1cda43/lib/object_detection/core/anchor_generator.py#L77-L107
FORTH-ICS-INSPIRE/artemis
f0774af8abc25ef5c6b307960c048ff7528d8a9c
backend-services/fileobserver/core/observer.py
python
HealthHandler.get
(self)
Extract the status of a service via a GET request. :return: {"status" : <unconfigured|running|stopped><,reconfiguring>}
Extract the status of a service via a GET request. :return: {"status" : <unconfigured|running|stopped><,reconfiguring>}
[ "Extract", "the", "status", "of", "a", "service", "via", "a", "GET", "request", ".", ":", "return", ":", "{", "status", ":", "<unconfigured|running|stopped", ">", "<", "reconfiguring", ">", "}" ]
def get(self): """ Extract the status of a service via a GET request. :return: {"status" : <unconfigured|running|stopped><,reconfiguring>} """ status = "stopped" shared_memory_locks["data_worker"].acquire() if self.shared_memory_manager_dict["data_worker_running"]: status = "running" shared_memory_locks["data_worker"].release() if self.shared_memory_manager_dict["service_reconfiguring"]: status += ",reconfiguring" self.write({"status": status})
[ "def", "get", "(", "self", ")", ":", "status", "=", "\"stopped\"", "shared_memory_locks", "[", "\"data_worker\"", "]", ".", "acquire", "(", ")", "if", "self", ".", "shared_memory_manager_dict", "[", "\"data_worker_running\"", "]", ":", "status", "=", "\"running\...
https://github.com/FORTH-ICS-INSPIRE/artemis/blob/f0774af8abc25ef5c6b307960c048ff7528d8a9c/backend-services/fileobserver/core/observer.py#L67-L79
prody/ProDy
b24bbf58aa8fffe463c8548ae50e3955910e5b7f
prody/database/quartataweb.py
python
QuartataWebBrowser.goToWorkDir
(self)
Go to working directory
Go to working directory
[ "Go", "to", "working", "directory" ]
def goToWorkDir(self): """Go to working directory""" if self.job_id is None: self.viewResults() url = 'http://quartata.csb.pitt.edu/work/{0}'.format(self.job_id) self.browser.visit(url)
[ "def", "goToWorkDir", "(", "self", ")", ":", "if", "self", ".", "job_id", "is", "None", ":", "self", ".", "viewResults", "(", ")", "url", "=", "'http://quartata.csb.pitt.edu/work/{0}'", ".", "format", "(", "self", ".", "job_id", ")", "self", ".", "browser"...
https://github.com/prody/ProDy/blob/b24bbf58aa8fffe463c8548ae50e3955910e5b7f/prody/database/quartataweb.py#L409-L415
Cadene/tensorflow-model-zoo.torch
990b10ffc22d4c8eacb2a502f20415b4f70c74c2
models/research/object_detection/inference/detection_inference.py
python
build_input
(tfrecord_paths)
return serialized_example_tensor, image_tensor
Builds the graph's input. Args: tfrecord_paths: List of paths to the input TFRecords Returns: serialized_example_tensor: The next serialized example. String scalar Tensor image_tensor: The decoded image of the example. Uint8 tensor, shape=[1, None, None,3]
Builds the graph's input.
[ "Builds", "the", "graph", "s", "input", "." ]
def build_input(tfrecord_paths): """Builds the graph's input. Args: tfrecord_paths: List of paths to the input TFRecords Returns: serialized_example_tensor: The next serialized example. String scalar Tensor image_tensor: The decoded image of the example. Uint8 tensor, shape=[1, None, None,3] """ filename_queue = tf.train.string_input_producer( tfrecord_paths, shuffle=False, num_epochs=1) tf_record_reader = tf.TFRecordReader() _, serialized_example_tensor = tf_record_reader.read(filename_queue) features = tf.parse_single_example( serialized_example_tensor, features={ standard_fields.TfExampleFields.image_encoded: tf.FixedLenFeature([], tf.string), }) encoded_image = features[standard_fields.TfExampleFields.image_encoded] image_tensor = tf.image.decode_image(encoded_image, channels=3) image_tensor.set_shape([None, None, 3]) image_tensor = tf.expand_dims(image_tensor, 0) return serialized_example_tensor, image_tensor
[ "def", "build_input", "(", "tfrecord_paths", ")", ":", "filename_queue", "=", "tf", ".", "train", ".", "string_input_producer", "(", "tfrecord_paths", ",", "shuffle", "=", "False", ",", "num_epochs", "=", "1", ")", "tf_record_reader", "=", "tf", ".", "TFRecord...
https://github.com/Cadene/tensorflow-model-zoo.torch/blob/990b10ffc22d4c8eacb2a502f20415b4f70c74c2/models/research/object_detection/inference/detection_inference.py#L23-L50
VIS-VAR/LGSC-for-FAS
bac93ab8d35973271178b9fa0422054769ea52ea
utils/eval.py
python
eval_acer
(results, is_print=False)
return 100 - acer
:param results: np.array shape of (N, 2) [pred, label] :param is_print: print eval score :return: score
:param results: np.array shape of (N, 2) [pred, label] :param is_print: print eval score :return: score
[ ":", "param", "results", ":", "np", ".", "array", "shape", "of", "(", "N", "2", ")", "[", "pred", "label", "]", ":", "param", "is_print", ":", "print", "eval", "score", ":", "return", ":", "score" ]
def eval_acer(results, is_print=False): """ :param results: np.array shape of (N, 2) [pred, label] :param is_print: print eval score :return: score """ ind_n = (results[:, 1] == 0) ind_p = (results[:, 1] == 1) fp = (results[ind_n, 0] == 1).sum() fn = (results[ind_p, 0] == 0).sum() apcer = fp / ind_n.sum() * 100 bpcer = fn / ind_p.sum() * 100 acer = (apcer + bpcer) / 2 if is_print: print('***************************************') print('APCER BPCER ACER') print('{:.4f} {:.4f} {:.4f}'.format(apcer, bpcer, acer)) print('***************************************') return 100 - acer
[ "def", "eval_acer", "(", "results", ",", "is_print", "=", "False", ")", ":", "ind_n", "=", "(", "results", "[", ":", ",", "1", "]", "==", "0", ")", "ind_p", "=", "(", "results", "[", ":", ",", "1", "]", "==", "1", ")", "fp", "=", "(", "result...
https://github.com/VIS-VAR/LGSC-for-FAS/blob/bac93ab8d35973271178b9fa0422054769ea52ea/utils/eval.py#L9-L27
sisl/MADRL
4a6d780e8cf111f312b757cca1b9f83441644958
madrl_environments/walker/multi_walker.py
python
BipedalWalker.apply_action
(self, action)
[]
def apply_action(self, action): self.joints[0].motorSpeed = float(SPEED_HIP * np.sign(action[0])) self.joints[0].maxMotorTorque = float(MOTORS_TORQUE * np.clip(np.abs(action[0]), 0, 1)) self.joints[1].motorSpeed = float(SPEED_KNEE * np.sign(action[1])) self.joints[1].maxMotorTorque = float(MOTORS_TORQUE * np.clip(np.abs(action[1]), 0, 1)) self.joints[2].motorSpeed = float(SPEED_HIP * np.sign(action[2])) self.joints[2].maxMotorTorque = float(MOTORS_TORQUE * np.clip(np.abs(action[2]), 0, 1)) self.joints[3].motorSpeed = float(SPEED_KNEE * np.sign(action[3])) self.joints[3].maxMotorTorque = float(MOTORS_TORQUE * np.clip(np.abs(action[3]), 0, 1))
[ "def", "apply_action", "(", "self", ",", "action", ")", ":", "self", ".", "joints", "[", "0", "]", ".", "motorSpeed", "=", "float", "(", "SPEED_HIP", "*", "np", ".", "sign", "(", "action", "[", "0", "]", ")", ")", "self", ".", "joints", "[", "0",...
https://github.com/sisl/MADRL/blob/4a6d780e8cf111f312b757cca1b9f83441644958/madrl_environments/walker/multi_walker.py#L194-L203
avalonstrel/GatedConvolution_pytorch
0a49013a70e77cc484ab45a5da535c2ac003b252
models/deepimageanalogy/patchmatch/PatchMatchOrig.py
python
PatchMatch.upsample_update
(self, a, aa, b, bb)
[]
def upsample_update(self, a, aa, b, bb): assert a.shape == b.shape == aa.shape == bb.shape, "Dimensions were unequal for patch-matching input" self.A = a.copy(order='C') self.B = b.copy(order='C') self.AA = aa.copy(order='C') self.BB = bb.copy(order='C') self.nnf = self.upsample_nnf(a.shape[:2]).copy("C") self.nnd = np.zeros(shape=(self.A.shape[0], self.A.shape[1])) for i in range(self.A.shape[0]): for j in range(self.A.shape[1]): pos = self.nnf[i, j] self.nnd[i, j] = self.cal_dist(i, j, pos[0], pos[1])
[ "def", "upsample_update", "(", "self", ",", "a", ",", "aa", ",", "b", ",", "bb", ")", ":", "assert", "a", ".", "shape", "==", "b", ".", "shape", "==", "aa", ".", "shape", "==", "bb", ".", "shape", ",", "\"Dimensions were unequal for patch-matching input\...
https://github.com/avalonstrel/GatedConvolution_pytorch/blob/0a49013a70e77cc484ab45a5da535c2ac003b252/models/deepimageanalogy/patchmatch/PatchMatchOrig.py#L61-L73
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/cpdp/v20190820/models.py
python
UnifiedOrderInSubOrderList.__init__
(self)
r""" :param SubMchIncome: 子订单结算应收金额,单位: 分 :type SubMchIncome: int :param PlatformIncome: 子订单平台应收金额,单位:分 :type PlatformIncome: int :param ProductDetail: 子订单商品详情 :type ProductDetail: str :param ProductName: 子订单商品名称 :type ProductName: str :param SubAppId: 聚鑫计费SubAppId,代表子商户 :type SubAppId: str :param SubOutTradeNo: 子订单号 :type SubOutTradeNo: str :param Amt: 子订单支付金额 :type Amt: int :param Metadata: 发货标识,由业务在调用聚鑫下单接口的 时候下发 :type Metadata: str :param OriginalAmt: 子订单原始金额 :type OriginalAmt: int
r""" :param SubMchIncome: 子订单结算应收金额,单位: 分 :type SubMchIncome: int :param PlatformIncome: 子订单平台应收金额,单位:分 :type PlatformIncome: int :param ProductDetail: 子订单商品详情 :type ProductDetail: str :param ProductName: 子订单商品名称 :type ProductName: str :param SubAppId: 聚鑫计费SubAppId,代表子商户 :type SubAppId: str :param SubOutTradeNo: 子订单号 :type SubOutTradeNo: str :param Amt: 子订单支付金额 :type Amt: int :param Metadata: 发货标识,由业务在调用聚鑫下单接口的 时候下发 :type Metadata: str :param OriginalAmt: 子订单原始金额 :type OriginalAmt: int
[ "r", ":", "param", "SubMchIncome", ":", "子订单结算应收金额,单位:", "分", ":", "type", "SubMchIncome", ":", "int", ":", "param", "PlatformIncome", ":", "子订单平台应收金额,单位:分", ":", "type", "PlatformIncome", ":", "int", ":", "param", "ProductDetail", ":", "子订单商品详情", ":", "type",...
def __init__(self): r""" :param SubMchIncome: 子订单结算应收金额,单位: 分 :type SubMchIncome: int :param PlatformIncome: 子订单平台应收金额,单位:分 :type PlatformIncome: int :param ProductDetail: 子订单商品详情 :type ProductDetail: str :param ProductName: 子订单商品名称 :type ProductName: str :param SubAppId: 聚鑫计费SubAppId,代表子商户 :type SubAppId: str :param SubOutTradeNo: 子订单号 :type SubOutTradeNo: str :param Amt: 子订单支付金额 :type Amt: int :param Metadata: 发货标识,由业务在调用聚鑫下单接口的 时候下发 :type Metadata: str :param OriginalAmt: 子订单原始金额 :type OriginalAmt: int """ self.SubMchIncome = None self.PlatformIncome = None self.ProductDetail = None self.ProductName = None self.SubAppId = None self.SubOutTradeNo = None self.Amt = None self.Metadata = None self.OriginalAmt = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "SubMchIncome", "=", "None", "self", ".", "PlatformIncome", "=", "None", "self", ".", "ProductDetail", "=", "None", "self", ".", "ProductName", "=", "None", "self", ".", "SubAppId", "=", "None", "sel...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/cpdp/v20190820/models.py#L17054-L17083
translate/virtaal
8b0a6fbf764ed92cc44a189499dec399c6423761
virtaal/models/storemodel.py
python
StoreModel._correct_header
(self, store)
This ensures that the file has a header if it is a poheader type of file, and fixes the statistics if we had to add a header.
This ensures that the file has a header if it is a poheader type of file, and fixes the statistics if we had to add a header.
[ "This", "ensures", "that", "the", "file", "has", "a", "header", "if", "it", "is", "a", "poheader", "type", "of", "file", "and", "fixes", "the", "statistics", "if", "we", "had", "to", "add", "a", "header", "." ]
def _correct_header(self, store): """This ensures that the file has a header if it is a poheader type of file, and fixes the statistics if we had to add a header.""" # Copied as-is from Document._correct_header() from translate.storage.poheader import poheader if isinstance(store, poheader) and not store.header(): store.updateheader(add=True) new_stats = {} for key, values in self.stats.iteritems(): new_stats[key] = [value+1 for value in values] self.stats = new_stats
[ "def", "_correct_header", "(", "self", ",", "store", ")", ":", "# Copied as-is from Document._correct_header()", "from", "translate", ".", "storage", ".", "poheader", "import", "poheader", "if", "isinstance", "(", "store", ",", "poheader", ")", "and", "not", "stor...
https://github.com/translate/virtaal/blob/8b0a6fbf764ed92cc44a189499dec399c6423761/virtaal/models/storemodel.py#L239-L249
nicolargo/glances
00c65933ae1d0ebd3e72dc30fc3c215a83dfaae2
glances/static_list.py
python
GlancesStaticServer.set_server
(self, server_pos, key, value)
Set the key to the value for the server_pos (position in the list).
Set the key to the value for the server_pos (position in the list).
[ "Set", "the", "key", "to", "the", "value", "for", "the", "server_pos", "(", "position", "in", "the", "list", ")", "." ]
def set_server(self, server_pos, key, value): """Set the key to the value for the server_pos (position in the list).""" self._server_list[server_pos][key] = value
[ "def", "set_server", "(", "self", ",", "server_pos", ",", "key", ",", "value", ")", ":", "self", ".", "_server_list", "[", "server_pos", "]", "[", "key", "]", "=", "value" ]
https://github.com/nicolargo/glances/blob/00c65933ae1d0ebd3e72dc30fc3c215a83dfaae2/glances/static_list.py#L90-L92
intelxed/xed
d57a3bd0a8ad7a1f0c6e2a1b58060d9014021098
pysrc/generator.py
python
all_generator_info_t.dump_generated_files
(self)
For mbuild dependence checking, we need an accurate list of the files the generator created. This file is read by xed_mbuild.py
For mbuild dependence checking, we need an accurate list of the files the generator created. This file is read by xed_mbuild.py
[ "For", "mbuild", "dependence", "checking", "we", "need", "an", "accurate", "list", "of", "the", "files", "the", "generator", "created", ".", "This", "file", "is", "read", "by", "xed_mbuild", ".", "py" ]
def dump_generated_files(self): """For mbuild dependence checking, we need an accurate list of the files the generator created. This file is read by xed_mbuild.py""" output_file_list = mbuild.join(self.common.options.gendir, "DECGEN-OUTPUT-FILES.txt") f = base_open_file(output_file_list,"w") for fn in self.hdr_files + self.src_files: f.write(fn+"\n") f.close()
[ "def", "dump_generated_files", "(", "self", ")", ":", "output_file_list", "=", "mbuild", ".", "join", "(", "self", ".", "common", ".", "options", ".", "gendir", ",", "\"DECGEN-OUTPUT-FILES.txt\"", ")", "f", "=", "base_open_file", "(", "output_file_list", ",", ...
https://github.com/intelxed/xed/blob/d57a3bd0a8ad7a1f0c6e2a1b58060d9014021098/pysrc/generator.py#L5130-L5139
spotify/snakebite
6a456e6100b0c1be66cc1f7f9d7f50494f369da3
snakebite/client.py
python
HAClient._ha_gen_method
(func)
return wrapped
Method decorator for 'generator type' methods
Method decorator for 'generator type' methods
[ "Method", "decorator", "for", "generator", "type", "methods" ]
def _ha_gen_method(func): ''' Method decorator for 'generator type' methods ''' def wrapped(self, *args, **kw): self._reset_retries() while(True): # switch between all namenodes try: results = func(self, *args, **kw) while(True): # yield all results yield results.next() except RequestError as e: self.__handle_request_error(e) except socket.error as e: self.__handle_socket_error(e) return wrapped
[ "def", "_ha_gen_method", "(", "func", ")", ":", "def", "wrapped", "(", "self", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "self", ".", "_reset_retries", "(", ")", "while", "(", "True", ")", ":", "# switch between all namenodes", "try", ":", "resu...
https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/client.py#L1532-L1545
haiwen/seafile-docker
2d2461d4c8cab3458ec9832611c419d47506c300
scripts_8.0/start.py
python
main
()
[]
def main(): if not exists(shared_seafiledir): os.mkdir(shared_seafiledir) if not exists(generated_dir): os.makedirs(generated_dir) if is_https(): init_letsencrypt() generate_local_nginx_conf() call('nginx -s reload') wait_for_mysql() init_seafile_server() check_upgrade() os.chdir(installdir) admin_pw = { 'email': get_conf('SEAFILE_ADMIN_EMAIL', 'me@example.com'), 'password': get_conf('SEAFILE_ADMIN_PASSWORD', 'asecret'), } password_file = join(topdir, 'conf', 'admin.txt') with open(password_file, 'w') as fp: json.dump(admin_pw, fp) try: call('{} start'.format(get_script('seafile.sh'))) call('{} start'.format(get_script('seahub.sh'))) finally: if exists(password_file): os.unlink(password_file) print('seafile server is running now.') try: watch_controller() except KeyboardInterrupt: print('Stopping seafile server.') sys.exit(0)
[ "def", "main", "(", ")", ":", "if", "not", "exists", "(", "shared_seafiledir", ")", ":", "os", ".", "mkdir", "(", "shared_seafiledir", ")", "if", "not", "exists", "(", "generated_dir", ")", ":", "os", ".", "makedirs", "(", "generated_dir", ")", "if", "...
https://github.com/haiwen/seafile-docker/blob/2d2461d4c8cab3458ec9832611c419d47506c300/scripts_8.0/start.py#L44-L82
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/app_manager/models.py
python
Application.create_all_files
(self, build_profile_id=None)
return files
[]
def create_all_files(self, build_profile_id=None): self.set_form_versions() self.set_media_versions() prefix = '' if not build_profile_id else build_profile_id + '/' files = { '{}profile.xml'.format(prefix): self.create_profile(is_odk=False, build_profile_id=build_profile_id), '{}profile.ccpr'.format(prefix): self.create_profile(is_odk=True, build_profile_id=build_profile_id), '{}media_profile.xml'.format(prefix): self.create_profile(is_odk=False, with_media=True, build_profile_id=build_profile_id), '{}media_profile.ccpr'.format(prefix): self.create_profile(is_odk=True, with_media=True, build_profile_id=build_profile_id), '{}suite.xml'.format(prefix): self.create_suite(build_profile_id), '{}media_suite.xml'.format(prefix): self.create_media_suite(build_profile_id), } if self.commcare_flavor: files['{}profile-{}.xml'.format(prefix, self.commcare_flavor)] = self.create_profile( is_odk=False, build_profile_id=build_profile_id, commcare_flavor=self.commcare_flavor, ) files['{}profile-{}.ccpr'.format(prefix, self.commcare_flavor)] = self.create_profile( is_odk=True, build_profile_id=build_profile_id, commcare_flavor=self.commcare_flavor, ) files['{}media_profile-{}.xml'.format(prefix, self.commcare_flavor)] = self.create_profile( is_odk=False, with_media=True, build_profile_id=build_profile_id, commcare_flavor=self.commcare_flavor, ) files['{}media_profile-{}.ccpr'.format(prefix, self.commcare_flavor)] = self.create_profile( is_odk=True, with_media=True, build_profile_id=build_profile_id, commcare_flavor=self.commcare_flavor, ) practice_user_restore = self.create_practice_user_restore(build_profile_id) if practice_user_restore: files.update({ '{}practice_user_restore.xml'.format(prefix): practice_user_restore }) files.update(self._make_language_files(prefix, build_profile_id)) files.update(self._get_form_files(prefix, build_profile_id)) return files
[ "def", "create_all_files", "(", "self", ",", "build_profile_id", "=", "None", ")", ":", "self", ".", "set_form_versions", "(", ")", "self", ".", "set_media_versions", "(", ")", "prefix", "=", "''", "if", "not", "build_profile_id", "else", "build_profile_id", "...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/app_manager/models.py#L5165-L5211
nipy/nibabel
4703f4d8e32be4cec30e829c2d93ebe54759bb62
nibabel/quaternions.py
python
eye
()
return np.array([1.0, 0, 0, 0])
Return identity quaternion
Return identity quaternion
[ "Return", "identity", "quaternion" ]
def eye(): """ Return identity quaternion """ return np.array([1.0, 0, 0, 0])
[ "def", "eye", "(", ")", ":", "return", "np", ".", "array", "(", "[", "1.0", ",", "0", ",", "0", ",", "0", "]", ")" ]
https://github.com/nipy/nibabel/blob/4703f4d8e32be4cec30e829c2d93ebe54759bb62/nibabel/quaternions.py#L299-L301
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/ply-3.11/example/GardenSnake/GardenSnake.py
python
p_file_input_end
(p)
file_input_end : file_input ENDMARKER
file_input_end : file_input ENDMARKER
[ "file_input_end", ":", "file_input", "ENDMARKER" ]
def p_file_input_end(p): """file_input_end : file_input ENDMARKER""" p[0] = ast.Stmt(p[1])
[ "def", "p_file_input_end", "(", "p", ")", ":", "p", "[", "0", "]", "=", "ast", ".", "Stmt", "(", "p", "[", "1", "]", ")" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/ply-3.11/example/GardenSnake/GardenSnake.py#L386-L388
art-programmer/PlaneNet
ccc4423d278388d01cb3300be992b951b90acc7a
code/html.py
python
TestCase.test_doc_newlines
(self)
default document adding newlines between tags
default document adding newlines between tags
[ "default", "document", "adding", "newlines", "between", "tags" ]
def test_doc_newlines(self): 'default document adding newlines between tags' h = HTML() h.br h.br self.assertEquals(str(h), '<br>\n<br>')
[ "def", "test_doc_newlines", "(", "self", ")", ":", "h", "=", "HTML", "(", ")", "h", ".", "br", "h", ".", "br", "self", ".", "assertEquals", "(", "str", "(", "h", ")", ",", "'<br>\\n<br>'", ")" ]
https://github.com/art-programmer/PlaneNet/blob/ccc4423d278388d01cb3300be992b951b90acc7a/code/html.py#L553-L558
openstack/horizon
12bb9fe5184c9dd3329ba17b3d03c90887dbcc3d
horizon/tables/base.py
python
DataTable.calculate_row_status
(self, statuses)
return True
Returns a boolean value determining the overall row status. It is detremined based on the dictionary of column name to status mappings passed in. By default, it uses the following logic: #. If any statuses are ``False``, return ``False``. #. If no statuses are ``False`` but any or ``None``, return ``None``. #. If all statuses are ``True``, return ``True``. This provides the greatest protection against false positives without weighting any particular columns. The ``statuses`` parameter is passed in as a dictionary mapping column names to their statuses in order to allow this function to be overridden in such a way as to weight one column's status over another should that behavior be desired.
Returns a boolean value determining the overall row status.
[ "Returns", "a", "boolean", "value", "determining", "the", "overall", "row", "status", "." ]
def calculate_row_status(self, statuses): """Returns a boolean value determining the overall row status. It is detremined based on the dictionary of column name to status mappings passed in. By default, it uses the following logic: #. If any statuses are ``False``, return ``False``. #. If no statuses are ``False`` but any or ``None``, return ``None``. #. If all statuses are ``True``, return ``True``. This provides the greatest protection against false positives without weighting any particular columns. The ``statuses`` parameter is passed in as a dictionary mapping column names to their statuses in order to allow this function to be overridden in such a way as to weight one column's status over another should that behavior be desired. """ values = statuses.values() if any([status is False for status in values]): return False if any([status is None for status in values]): return None return True
[ "def", "calculate_row_status", "(", "self", ",", "statuses", ")", ":", "values", "=", "statuses", ".", "values", "(", ")", "if", "any", "(", "[", "status", "is", "False", "for", "status", "in", "values", "]", ")", ":", "return", "False", "if", "any", ...
https://github.com/openstack/horizon/blob/12bb9fe5184c9dd3329ba17b3d03c90887dbcc3d/horizon/tables/base.py#L1884-L1909
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/models/gptj/modeling_flax_gptj.py
python
FlaxGPTJAttention.setup
(self)
[]
def setup(self): config = self.config self.embed_dim = config.hidden_size self.num_heads = config.num_attention_heads self.head_dim = self.embed_dim // self.num_heads self.rotary_dim = config.rotary_dim dense = partial( nn.Dense, self.embed_dim, use_bias=False, dtype=self.dtype, kernel_init=jax.nn.initializers.normal(self.config.initializer_range), ) self.q_proj, self.k_proj, self.v_proj = dense(), dense(), dense() self.out_proj = dense() self.resid_dropout = nn.Dropout(rate=config.resid_pdrop) self.causal_mask = make_causal_mask(jnp.ones((1, config.max_position_embeddings), dtype="bool"), dtype="bool") pos_embd_dim = self.rotary_dim or self.embed_dim self.embed_positions = create_sinusoidal_positions(config.max_position_embeddings, pos_embd_dim)
[ "def", "setup", "(", "self", ")", ":", "config", "=", "self", ".", "config", "self", ".", "embed_dim", "=", "config", ".", "hidden_size", "self", ".", "num_heads", "=", "config", ".", "num_attention_heads", "self", ".", "head_dim", "=", "self", ".", "emb...
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/models/gptj/modeling_flax_gptj.py#L143-L167
omniti-labs/pg_extractor
6a64eb018704d43a4c549505d85703807aafa6c3
pg_extractor.py
python
PGExtractor._run_pg_dump
(self, o, output_file)
Run pg_dump for a single object obtained from parsing a pg_restore -l list * o: a single object in the dictionary format generated by build_main_object_list * output_file: target output file that pg_dump writes to
Run pg_dump for a single object obtained from parsing a pg_restore -l list
[ "Run", "pg_dump", "for", "a", "single", "object", "obtained", "from", "parsing", "a", "pg_restore", "-", "l", "list" ]
def _run_pg_dump(self, o, output_file): """ Run pg_dump for a single object obtained from parsing a pg_restore -l list * o: a single object in the dictionary format generated by build_main_object_list * output_file: target output file that pg_dump writes to """ pg_dump_cmd = ["pg_dump", "--file=" + output_file] pg_dump_cmd.append(r'--table="' + o.get('objschema') + r'"."' + o.get('objname') + r'"') if self.args and self.args.Fc: pg_dump_cmd.append("--format=custom") else: pg_dump_cmd.append("--format=plain") if self.args and not self.args.getdata: pg_dump_cmd.append("--schema-only") if self.args and self.args.clean: pg_dump_cmd.append("--clean") if self.args and self.args.no_acl: pg_dump_cmd.append("--no-acl") if self.args and self.args.no_owner: pg_dump_cmd.append("--no-owner") if self.args and self.args.inserts: pg_dump_cmd.append("--inserts") if self.args and self.args.column_inserts: pg_dump_cmd.append("--column-inserts") if self.args.debug: self._debug_print("EXTRACT DUMP: " + str(pg_dump_cmd)) try: subprocess.check_output(pg_dump_cmd, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as e: print("Error in pg_dump command while creating extract file: " + str(e.output, encoding='utf-8').rstrip() + "\nSubprocess command called: " + str(e.cmd)) sys.exit(2) if self.args.wait > 0: time.sleep(self.args.wait)
[ "def", "_run_pg_dump", "(", "self", ",", "o", ",", "output_file", ")", ":", "pg_dump_cmd", "=", "[", "\"pg_dump\"", ",", "\"--file=\"", "+", "output_file", "]", "pg_dump_cmd", ".", "append", "(", "r'--table=\"'", "+", "o", ".", "get", "(", "'objschema'", "...
https://github.com/omniti-labs/pg_extractor/blob/6a64eb018704d43a4c549505d85703807aafa6c3/pg_extractor.py#L1308-L1342
FSecureLABS/Jandroid
e31d0dab58a2bfd6ed8e0a387172b8bd7c893436
libs/platform-tools/platform-tools_linux/systrace/catapult/common/py_vulcanize/py_vulcanize/strip_js_comments.py
python
_TokenizeJS
(text)
Splits source code text into segments in preparation for comment stripping. Note that this doesn't tokenize for parsing. There is no notion of statements, variables, etc. The only tokens of interest are comment-related tokens. Args: text: The contents of a JavaScript file. Yields: A succession of strings in the file, including all comment-related symbols.
Splits source code text into segments in preparation for comment stripping.
[ "Splits", "source", "code", "text", "into", "segments", "in", "preparation", "for", "comment", "stripping", "." ]
def _TokenizeJS(text): """Splits source code text into segments in preparation for comment stripping. Note that this doesn't tokenize for parsing. There is no notion of statements, variables, etc. The only tokens of interest are comment-related tokens. Args: text: The contents of a JavaScript file. Yields: A succession of strings in the file, including all comment-related symbols. """ rest = text tokens = ['//', '/*', '*/', '\n'] next_tok = re.compile('|'.join(re.escape(x) for x in tokens)) while len(rest): m = next_tok.search(rest) if not m: # end of string yield rest return min_index = m.start() end_index = m.end() if min_index > 0: yield rest[:min_index] yield rest[min_index:end_index] rest = rest[end_index:]
[ "def", "_TokenizeJS", "(", "text", ")", ":", "rest", "=", "text", "tokens", "=", "[", "'//'", ",", "'/*'", ",", "'*/'", ",", "'\\n'", "]", "next_tok", "=", "re", ".", "compile", "(", "'|'", ".", "join", "(", "re", ".", "escape", "(", "x", ")", ...
https://github.com/FSecureLABS/Jandroid/blob/e31d0dab58a2bfd6ed8e0a387172b8bd7c893436/libs/platform-tools/platform-tools_linux/systrace/catapult/common/py_vulcanize/py_vulcanize/strip_js_comments.py#L10-L38
EricSteinberger/PokerRL
e02ea667061b96912e424231da071b6f20a262f7
PokerRL/game/_/rl_env/poker_types/DiscretizedPokerEnv.py
python
DiscretizedPokerEnv.get_hand_rank_all_hands_on_given_boards
(self, boards_1d, lut_holder)
For docs, refer to PokerEnv.get_hand_rank_all_hands_on_given_boards()
For docs, refer to PokerEnv.get_hand_rank_all_hands_on_given_boards()
[ "For", "docs", "refer", "to", "PokerEnv", ".", "get_hand_rank_all_hands_on_given_boards", "()" ]
def get_hand_rank_all_hands_on_given_boards(self, boards_1d, lut_holder): """ For docs, refer to PokerEnv.get_hand_rank_all_hands_on_given_boards() """ raise NotImplementedError
[ "def", "get_hand_rank_all_hands_on_given_boards", "(", "self", ",", "boards_1d", ",", "lut_holder", ")", ":", "raise", "NotImplementedError" ]
https://github.com/EricSteinberger/PokerRL/blob/e02ea667061b96912e424231da071b6f20a262f7/PokerRL/game/_/rl_env/poker_types/DiscretizedPokerEnv.py#L143-L147
dvlab-research/GridMask
b2439a7ddec41d6b0917a9b91c3ec8687c871239
detection_grid/maskrcnn_benchmark/modeling/rpn/rpn.py
python
build_rpn
(cfg, in_channels)
return RPNModule(cfg, in_channels)
This gives the gist of it. Not super important because it doesn't change as much
This gives the gist of it. Not super important because it doesn't change as much
[ "This", "gives", "the", "gist", "of", "it", ".", "Not", "super", "important", "because", "it", "doesn", "t", "change", "as", "much" ]
def build_rpn(cfg, in_channels): """ This gives the gist of it. Not super important because it doesn't change as much """ if cfg.MODEL.RETINANET_ON: return build_retinanet(cfg, in_channels) return RPNModule(cfg, in_channels)
[ "def", "build_rpn", "(", "cfg", ",", "in_channels", ")", ":", "if", "cfg", ".", "MODEL", ".", "RETINANET_ON", ":", "return", "build_retinanet", "(", "cfg", ",", "in_channels", ")", "return", "RPNModule", "(", "cfg", ",", "in_channels", ")" ]
https://github.com/dvlab-research/GridMask/blob/b2439a7ddec41d6b0917a9b91c3ec8687c871239/detection_grid/maskrcnn_benchmark/modeling/rpn/rpn.py#L200-L207
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
examples/showoci/showoci_service.py
python
ShowOCIService.get_logging_log
(self, resource_id)
[]
def get_logging_log(self, resource_id): data = [] try: if self.C_SECURITY not in self.data: return data if self.C_SECURITY_LOGGING not in self.data[self.C_SECURITY]: return data array = self.data[self.C_SECURITY][self.C_SECURITY_LOGGING] for item in array: if 'logs' in item: for log in item['logs']: if 'source_resource' in log and 'lifecycle_state' in log: if log['source_resource'] == resource_id and log['lifecycle_state'] == 'ACTIVE': data.append(log) return data except Exception as e: self.__print_error("get_logging_log", e)
[ "def", "get_logging_log", "(", "self", ",", "resource_id", ")", ":", "data", "=", "[", "]", "try", ":", "if", "self", ".", "C_SECURITY", "not", "in", "self", ".", "data", ":", "return", "data", "if", "self", ".", "C_SECURITY_LOGGING", "not", "in", "sel...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/examples/showoci/showoci_service.py#L602-L621
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/twisted/twisted/scripts/tkunzip.py
python
compiler
(path)
A generator for compiling files to .pyc
A generator for compiling files to .pyc
[ "A", "generator", "for", "compiling", "files", "to", ".", "pyc" ]
def compiler(path): """A generator for compiling files to .pyc""" def justlist(arg, directory, names): pynames=[os.path.join(directory, n) for n in names if n.endswith('.py')] arg.extend(pynames) all=[] os.path.walk(path, justlist, all) remaining=len(all) i=zip(all, range(remaining-1, -1, -1)) for f, remaining in i: py_compile.compile(f) yield remaining
[ "def", "compiler", "(", "path", ")", ":", "def", "justlist", "(", "arg", ",", "directory", ",", "names", ")", ":", "pynames", "=", "[", "os", ".", "path", ".", "join", "(", "directory", ",", "n", ")", "for", "n", "in", "names", "if", "n", ".", ...
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/twisted/twisted/scripts/tkunzip.py#L167-L180
zhangxiaosong18/FreeAnchor
afad43a7c48034301d981d831fa61e42d9b6ddad
maskrcnn_benchmark/layers/sigmoid_focal_loss.py
python
SigmoidFocalLoss.forward
(self, logits, targets)
return loss.sum()
[]
def forward(self, logits, targets): loss = sigmoid_focalloss( logits, targets, self.num_classes, self.gamma, self.alpha ) return loss.sum()
[ "def", "forward", "(", "self", ",", "logits", ",", "targets", ")", ":", "loss", "=", "sigmoid_focalloss", "(", "logits", ",", "targets", ",", "self", ".", "num_classes", ",", "self", ".", "gamma", ",", "self", ".", "alpha", ")", "return", "loss", ".", ...
https://github.com/zhangxiaosong18/FreeAnchor/blob/afad43a7c48034301d981d831fa61e42d9b6ddad/maskrcnn_benchmark/layers/sigmoid_focal_loss.py#L46-L50
google/ci_edit
ffaa52473673cc7ec2080bc59996d61414d662c9
app/actions.py
python
Actions.find_replace
(self, cmd)
Replace (substitute) text using regex in entire document. In a command such as `substitute/a/b/flags`, the `substitute` should already be removed. The remaining |cmd| of `/a/b/flags` implies a separator of '/' since that is the first character. The values between separators are: - 'a': search string (regex) - 'b': replacement string (may contain back references into the regex) - 'flags': regex flags string to be parsed by |find_replace_flags()|.
Replace (substitute) text using regex in entire document.
[ "Replace", "(", "substitute", ")", "text", "using", "regex", "in", "entire", "document", "." ]
def find_replace(self, cmd): """Replace (substitute) text using regex in entire document. In a command such as `substitute/a/b/flags`, the `substitute` should already be removed. The remaining |cmd| of `/a/b/flags` implies a separator of '/' since that is the first character. The values between separators are: - 'a': search string (regex) - 'b': replacement string (may contain back references into the regex) - 'flags': regex flags string to be parsed by |find_replace_flags()|. """ if not len(cmd): return separator = cmd[0] splitCmd = cmd.split(separator, 3) if len(splitCmd) < 4: self.set_message(u"An exchange needs three " + separator + u" separators") return _, find, replace, flags = splitCmd data = self.find_replace_text(find, replace, flags, self.parser.data) self.apply_document_update(data)
[ "def", "find_replace", "(", "self", ",", "cmd", ")", ":", "if", "not", "len", "(", "cmd", ")", ":", "return", "separator", "=", "cmd", "[", "0", "]", "splitCmd", "=", "cmd", ".", "split", "(", "separator", ",", "3", ")", "if", "len", "(", "splitC...
https://github.com/google/ci_edit/blob/ffaa52473673cc7ec2080bc59996d61414d662c9/app/actions.py#L1335-L1355
abrignoni/iLEAPP
5376dc82b7fd0a27896088167b5b0b250a39a8be
scripts/ilapfuncs.py
python
does_table_exist
(db, table_name)
return False
Checks if a table with specified name exists in an sqlite db
Checks if a table with specified name exists in an sqlite db
[ "Checks", "if", "a", "table", "with", "specified", "name", "exists", "in", "an", "sqlite", "db" ]
def does_table_exist(db, table_name): '''Checks if a table with specified name exists in an sqlite db''' try: query = f"SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}'" cursor = db.execute(query) for row in cursor: return True except sqlite3Error as ex: logfunc(f"Query error, query={query} Error={str(ex)}") return False
[ "def", "does_table_exist", "(", "db", ",", "table_name", ")", ":", "try", ":", "query", "=", "f\"SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}'\"", "cursor", "=", "db", ".", "execute", "(", "query", ")", "for", "row", "in", "cursor", ":", ...
https://github.com/abrignoni/iLEAPP/blob/5376dc82b7fd0a27896088167b5b0b250a39a8be/scripts/ilapfuncs.py#L106-L115
parkouss/webmacs
35f174303af8c9147825c45ad41ff35706fa8bfa
webmacs/commands/webbuffer.py
python
revive_buffer
(ctx)
Revive a previously killed buffer in the current view.
Revive a previously killed buffer in the current view.
[ "Revive", "a", "previously", "killed", "buffer", "in", "the", "current", "view", "." ]
def revive_buffer(ctx): """ Revive a previously killed buffer in the current view. """ killed_buffer = ctx.minibuffer.do_prompt(KilledBufferListPrompt(ctx)) if killed_buffer: buff = killed_buffer.revive() ctx.window.current_webview().setBuffer(buff)
[ "def", "revive_buffer", "(", "ctx", ")", ":", "killed_buffer", "=", "ctx", ".", "minibuffer", ".", "do_prompt", "(", "KilledBufferListPrompt", "(", "ctx", ")", ")", "if", "killed_buffer", ":", "buff", "=", "killed_buffer", ".", "revive", "(", ")", "ctx", "...
https://github.com/parkouss/webmacs/blob/35f174303af8c9147825c45ad41ff35706fa8bfa/webmacs/commands/webbuffer.py#L518-L525
gammapy/gammapy
735b25cd5bbed35e2004d633621896dcd5295e8b
gammapy/maps/axes.py
python
MapAxis.nbin_per_decade
(self)
return (self._nbin / ndecades).value
Return number of bins.
Return number of bins.
[ "Return", "number", "of", "bins", "." ]
def nbin_per_decade(self): """Return number of bins.""" if self.interp != "log": raise ValueError("Bins per decade can only be computed for log-spaced axes") if self.node_type == "edges": values = self.edges else: values = self.center ndecades = np.log10(values.max() / values.min()) return (self._nbin / ndecades).value
[ "def", "nbin_per_decade", "(", "self", ")", ":", "if", "self", ".", "interp", "!=", "\"log\"", ":", "raise", "ValueError", "(", "\"Bins per decade can only be computed for log-spaced axes\"", ")", "if", "self", ".", "node_type", "==", "\"edges\"", ":", "values", "...
https://github.com/gammapy/gammapy/blob/735b25cd5bbed35e2004d633621896dcd5295e8b/gammapy/maps/axes.py#L329-L340
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/gen/plug/docgen/stylesheet.py
python
StyleSheet.add_table_style
(self, name, style)
Add a table style to the style sheet. :param name: The name of the :class:`.TableStyle` :param style: :class:`.TableStyle` instance to be added.
Add a table style to the style sheet.
[ "Add", "a", "table", "style", "to", "the", "style", "sheet", "." ]
def add_table_style(self, name, style): """ Add a table style to the style sheet. :param name: The name of the :class:`.TableStyle` :param style: :class:`.TableStyle` instance to be added. """ self.table_styles[name] = TableStyle(style)
[ "def", "add_table_style", "(", "self", ",", "name", ",", "style", ")", ":", "self", ".", "table_styles", "[", "name", "]", "=", "TableStyle", "(", "style", ")" ]
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/gen/plug/docgen/stylesheet.py#L393-L400
wxWidgets/Phoenix
b2199e299a6ca6d866aa6f3d0888499136ead9d6
wx/lib/pubsub/core/topicdefnprovider.py
python
TopicDefnDeserialClass.__getTopicClasses
(self, pyClassObj, parentNameTuple=())
return topicClasses
Returns a list of pairs, (topicNameTuple, memberClassObj)
Returns a list of pairs, (topicNameTuple, memberClassObj)
[ "Returns", "a", "list", "of", "pairs", "(", "topicNameTuple", "memberClassObj", ")" ]
def __getTopicClasses(self, pyClassObj, parentNameTuple=()): """Returns a list of pairs, (topicNameTuple, memberClassObj)""" memberNames = dir(pyClassObj) topicClasses = [] for memberName in memberNames: if memberName.startswith('_'): continue # ignore special and non-public methods member = getattr(pyClassObj, memberName) if inspect.isclass( member ): topicNameTuple = parentNameTuple + (memberName,) topicClasses.append( (topicNameTuple, member) ) return topicClasses
[ "def", "__getTopicClasses", "(", "self", ",", "pyClassObj", ",", "parentNameTuple", "=", "(", ")", ")", ":", "memberNames", "=", "dir", "(", "pyClassObj", ")", "topicClasses", "=", "[", "]", "for", "memberName", "in", "memberNames", ":", "if", "memberName", ...
https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/pubsub/core/topicdefnprovider.py#L195-L206
KhronosGroup/NNEF-Tools
c913758ca687dab8cb7b49e8f1556819a2d0ca25
nnef_tools/execute.py
python
RandomInputSource.__call__
(self, name, shape, dtype)
return self._distribution(shape).astype(dtype)
[]
def __call__(self, name, shape, dtype): return self._distribution(shape).astype(dtype)
[ "def", "__call__", "(", "self", ",", "name", ",", "shape", ",", "dtype", ")", ":", "return", "self", ".", "_distribution", "(", "shape", ")", ".", "astype", "(", "dtype", ")" ]
https://github.com/KhronosGroup/NNEF-Tools/blob/c913758ca687dab8cb7b49e8f1556819a2d0ca25/nnef_tools/execute.py#L121-L122
sharppy/SHARPpy
19175269ab11fe06c917b5d10376862a4716e1db
sharppy/viz/stp.py
python
backgroundSTP.draw_frame
(self, qp)
Draw the background frame. qp: QtGui.QPainter object
Draw the background frame. qp: QtGui.QPainter object
[ "Draw", "the", "background", "frame", ".", "qp", ":", "QtGui", ".", "QPainter", "object" ]
def draw_frame(self, qp): ''' Draw the background frame. qp: QtGui.QPainter object ''' ## set a new pen to draw with pen = QtGui.QPen(self.fg_color, 2, QtCore.Qt.SolidLine) qp.setPen(pen) qp.setFont(self.plot_font) # Left, top, width, height rect1 = QtCore.QRectF(0,5, self.brx, self.plot_height) qp.drawText(rect1, QtCore.Qt.TextDontClip | QtCore.Qt.AlignCenter, 'Effective Layer STP (with CIN)') pen = QtGui.QPen(QtCore.Qt.blue, 1, QtCore.Qt.DashLine) qp.setPen(pen) ytick_fontsize = round(self.font_ratio * self.hgt) + 1 y_ticks_font = QtGui.QFont('Helvetica', ytick_fontsize) qp.setFont(y_ticks_font) stp_inset_data = inset_data.stpData() texts = stp_inset_data['stp_ytexts'] # Plot the y-tick labels for the box and whisker plots for i in range(len(texts)): pen = QtGui.QPen(self.line_color, 1, QtCore.Qt.DashLine) qp.setPen(pen) tick_pxl = self.stp_to_pix(int(texts[i])) qp.drawLine(self.tlx, tick_pxl, self.brx, tick_pxl) color = QtGui.QColor(self.bg_color) pen = QtGui.QPen(color, 1, QtCore.Qt.SolidLine) qp.setPen(pen) ypos = tick_pxl - ytick_fontsize/2 rect = QtCore.QRect(self.tlx, ypos, 20, ytick_fontsize) pen = QtGui.QPen(self.fg_color, 1, QtCore.Qt.SolidLine) qp.setPen(pen) qp.drawText(rect, QtCore.Qt.TextDontClip | QtCore.Qt.AlignCenter, texts[i]) # Draw the box and whisker plots and the x-tick labels ef = stp_inset_data['ef'] width = self.brx / 14 spacing = self.brx / 7 center = np.arange(spacing, self.brx, spacing) texts = stp_inset_data['stp_xtexts'] ef = self.stp_to_pix(ef) qp.setFont(QtGui.QFont('Helvetica', round(self.font_ratio * self.hgt))) for i in range(ef.shape[0]): # Set green pen to draw box and whisker plots pen = QtGui.QPen(self.box_color, 2, QtCore.Qt.SolidLine) qp.setPen(pen) # Draw lower whisker qp.drawLine(center[i], ef[i,0], center[i], ef[i,1]) # Draw box qp.drawLine(center[i] - width/2., ef[i,3], center[i] + width/2., ef[i,3]) qp.drawLine(center[i] - width/2., ef[i,1], center[i] + width/2., ef[i,1]) qp.drawLine(center[i] - width/2., ef[i,1], center[i] - width/2., ef[i,3]) qp.drawLine(center[i] + width/2., ef[i,1], center[i] + width/2., ef[i,3]) # Draw median qp.drawLine(center[i] - width/2., ef[i,2], center[i] + width/2., ef[i,2]) # Draw upper whisker qp.drawLine(center[i], ef[i,3], center[i], ef[i,4]) # Set black transparent pen to draw a rectangle color = QtGui.QColor(self.bg_color) color.setAlpha(0) pen = QtGui.QPen(color, 1, QtCore.Qt.SolidLine) rect = QtCore.QRectF(center[i] - width/2., self.bry + round(self.bpad/2), width, self.bpad) # Change to a white pen to draw the text below the box and whisker plot pen = QtGui.QPen(self.fg_color, 1, QtCore.Qt.SolidLine) qp.setPen(pen) qp.drawText(rect, QtCore.Qt.TextDontClip | QtCore.Qt.AlignCenter, texts[i])
[ "def", "draw_frame", "(", "self", ",", "qp", ")", ":", "## set a new pen to draw with", "pen", "=", "QtGui", ".", "QPen", "(", "self", ".", "fg_color", ",", "2", ",", "QtCore", ".", "Qt", ".", "SolidLine", ")", "qp", ".", "setPen", "(", "pen", ")", "...
https://github.com/sharppy/SHARPpy/blob/19175269ab11fe06c917b5d10376862a4716e1db/sharppy/viz/stp.py#L81-L150
Cloud-CV/EvalAI
1884811e7759e0d095f7afb68188a7f010fa65dc
apps/challenges/utils.py
python
get_missing_keys_from_dict
(dictionary, keys)
return missing_keys
Function to get a list of missing keys from a python dict. Parameters: dict: keys-> 'dictionary': A python dictionary. 'keys': List of keys to check for in the dictionary. Returns: list: A list of keys missing from the dictionary object.
Function to get a list of missing keys from a python dict.
[ "Function", "to", "get", "a", "list", "of", "missing", "keys", "from", "a", "python", "dict", "." ]
def get_missing_keys_from_dict(dictionary, keys): """ Function to get a list of missing keys from a python dict. Parameters: dict: keys-> 'dictionary': A python dictionary. 'keys': List of keys to check for in the dictionary. Returns: list: A list of keys missing from the dictionary object. """ missing_keys = [] for key in keys: if key not in dictionary.keys(): missing_keys.append(key) return missing_keys
[ "def", "get_missing_keys_from_dict", "(", "dictionary", ",", "keys", ")", ":", "missing_keys", "=", "[", "]", "for", "key", "in", "keys", ":", "if", "key", "not", "in", "dictionary", ".", "keys", "(", ")", ":", "missing_keys", ".", "append", "(", "key", ...
https://github.com/Cloud-CV/EvalAI/blob/1884811e7759e0d095f7afb68188a7f010fa65dc/apps/challenges/utils.py#L44-L59
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
chap19/monitor/monitor/build/lib.linux-x86_64-2.7/monitor/api/openstack/wsgi.py
python
XMLDeserializer.find_children_named
(self, parent, name)
Return all of a nodes children who have the given name
Return all of a nodes children who have the given name
[ "Return", "all", "of", "a", "nodes", "children", "who", "have", "the", "given", "name" ]
def find_children_named(self, parent, name): """Return all of a nodes children who have the given name""" for node in parent.childNodes: if node.nodeName == name: yield node
[ "def", "find_children_named", "(", "self", ",", "parent", ",", "name", ")", ":", "for", "node", "in", "parent", ".", "childNodes", ":", "if", "node", ".", "nodeName", "==", "name", ":", "yield", "node" ]
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/chap19/monitor/monitor/build/lib.linux-x86_64-2.7/monitor/api/openstack/wsgi.py#L189-L193
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/PyWebDAV-0.9.8-py2.7.egg/pywebdav/lib/iface.py
python
dav_interface.moveone
(self,src,dst,overwrite)
return moveone(self,src,dst,overwrite)
move one resource with Depth=0
move one resource with Depth=0
[ "move", "one", "resource", "with", "Depth", "=", "0" ]
def moveone(self,src,dst,overwrite): """ move one resource with Depth=0 """ return moveone(self,src,dst,overwrite)
[ "def", "moveone", "(", "self", ",", "src", ",", "dst", ",", "overwrite", ")", ":", "return", "moveone", "(", "self", ",", "src", ",", "dst", ",", "overwrite", ")" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/PyWebDAV-0.9.8-py2.7.egg/pywebdav/lib/iface.py#L231-L233
diefenbach/django-lfs
3bbcb3453d324c181ec68d11d5d35115a60a2fd5
lfs/plugins.py
python
PriceCalculator.get_for_sale_price_net
(self, with_properties=True, amount=1)
Returns the sale net price for the product. **Parameters:** with_properties If the instance is a configurable product and with_properties is True the prices of the default properties are added to the price. amount The amount of products for which the price is calculated.
Returns the sale net price for the product.
[ "Returns", "the", "sale", "net", "price", "for", "the", "product", "." ]
def get_for_sale_price_net(self, with_properties=True, amount=1): """ Returns the sale net price for the product. **Parameters:** with_properties If the instance is a configurable product and with_properties is True the prices of the default properties are added to the price. amount The amount of products for which the price is calculated. """ raise NotImplementedError
[ "def", "get_for_sale_price_net", "(", "self", ",", "with_properties", "=", "True", ",", "amount", "=", "1", ")", ":", "raise", "NotImplementedError" ]
https://github.com/diefenbach/django-lfs/blob/3bbcb3453d324c181ec68d11d5d35115a60a2fd5/lfs/plugins.py#L336-L349
kvos/CoastSat
d1a934c9e4a5eb4ebb295a8a455bd55218fbaf01
coastsat/SDS_shoreline.py
python
extract_shorelines
(metadata, settings)
return output
Main function to extract shorelines from satellite images KV WRL 2018 Arguments: ----------- metadata: dict contains all the information about the satellite images that were downloaded settings: dict with the following keys 'inputs': dict input parameters (sitename, filepath, polygon, dates, sat_list) 'cloud_thresh': float value between 0 and 1 indicating the maximum cloud fraction in the cropped image that is accepted 'cloud_mask_issue': boolean True if there is an issue with the cloud mask and sand pixels are erroneously being masked on the images 'buffer_size': int size of the buffer (m) around the sandy pixels over which the pixels are considered in the thresholding algorithm 'min_beach_area': int minimum allowable object area (in metres^2) for the class 'sand', the area is converted to number of connected pixels 'min_length_sl': int minimum length (in metres) of shoreline contour to be valid 'sand_color': str default', 'dark' (for grey/black sand beaches) or 'bright' (for white sand beaches) 'output_epsg': int output spatial reference system as EPSG code 'check_detection': bool if True, lets user manually accept/reject the mapped shorelines 'save_figure': bool if True, saves a -jpg file for each mapped shoreline 'adjust_detection': bool if True, allows user to manually adjust the detected shoreline Returns: ----------- output: dict contains the extracted shorelines and corresponding dates + metadata
Main function to extract shorelines from satellite images
[ "Main", "function", "to", "extract", "shorelines", "from", "satellite", "images" ]
def extract_shorelines(metadata, settings): """ Main function to extract shorelines from satellite images KV WRL 2018 Arguments: ----------- metadata: dict contains all the information about the satellite images that were downloaded settings: dict with the following keys 'inputs': dict input parameters (sitename, filepath, polygon, dates, sat_list) 'cloud_thresh': float value between 0 and 1 indicating the maximum cloud fraction in the cropped image that is accepted 'cloud_mask_issue': boolean True if there is an issue with the cloud mask and sand pixels are erroneously being masked on the images 'buffer_size': int size of the buffer (m) around the sandy pixels over which the pixels are considered in the thresholding algorithm 'min_beach_area': int minimum allowable object area (in metres^2) for the class 'sand', the area is converted to number of connected pixels 'min_length_sl': int minimum length (in metres) of shoreline contour to be valid 'sand_color': str default', 'dark' (for grey/black sand beaches) or 'bright' (for white sand beaches) 'output_epsg': int output spatial reference system as EPSG code 'check_detection': bool if True, lets user manually accept/reject the mapped shorelines 'save_figure': bool if True, saves a -jpg file for each mapped shoreline 'adjust_detection': bool if True, allows user to manually adjust the detected shoreline Returns: ----------- output: dict contains the extracted shorelines and corresponding dates + metadata """ sitename = settings['inputs']['sitename'] filepath_data = settings['inputs']['filepath'] filepath_models = os.path.join(os.getcwd(), 'classification', 'models') # initialise output structure output = dict([]) # create a subfolder to store the .jpg images showing the detection filepath_jpg = os.path.join(filepath_data, sitename, 'jpg_files', 'detection') if not os.path.exists(filepath_jpg): os.makedirs(filepath_jpg) # close all open figures plt.close('all') print('Mapping shorelines:') # loop through satellite list for satname in metadata.keys(): # get images filepath = SDS_tools.get_filepath(settings['inputs'],satname) filenames = metadata[satname]['filenames'] # initialise the output variables output_timestamp = [] # datetime at which the image was acquired (UTC time) output_shoreline = [] # vector of shoreline points output_filename = [] # filename of the images from which the shorelines where derived output_cloudcover = [] # cloud cover of the images output_geoaccuracy = []# georeferencing accuracy of the images output_idxkeep = [] # index that were kept during the analysis (cloudy images are skipped) output_t_mndwi = [] # MNDWI threshold used to map the shoreline # load classifiers (if sklearn version above 0.20, learn the new files) str_new = '' if not sklearn.__version__[:4] == '0.20': str_new = '_new' if satname in ['L5','L7','L8']: pixel_size = 15 if settings['sand_color'] == 'dark': clf = joblib.load(os.path.join(filepath_models, 'NN_4classes_Landsat_dark%s.pkl'%str_new)) elif settings['sand_color'] == 'bright': clf = joblib.load(os.path.join(filepath_models, 'NN_4classes_Landsat_bright%s.pkl'%str_new)) else: clf = joblib.load(os.path.join(filepath_models, 'NN_4classes_Landsat%s.pkl'%str_new)) elif satname == 'S2': pixel_size = 10 clf = joblib.load(os.path.join(filepath_models, 'NN_4classes_S2%s.pkl'%str_new)) # convert settings['min_beach_area'] and settings['buffer_size'] from metres to pixels buffer_size_pixels = np.ceil(settings['buffer_size']/pixel_size) min_beach_area_pixels = np.ceil(settings['min_beach_area']/pixel_size**2) # loop through the images for i in range(len(filenames)): print('\r%s: %d%%' % (satname,int(((i+1)/len(filenames))*100)), end='') # get image filename fn = SDS_tools.get_filenames(filenames[i],filepath, satname) # preprocess image (cloud mask + pansharpening/downsampling) im_ms, georef, cloud_mask, im_extra, im_QA, im_nodata = SDS_preprocess.preprocess_single(fn, satname, settings['cloud_mask_issue']) # get image spatial reference system (epsg code) from metadata dict image_epsg = metadata[satname]['epsg'][i] # compute cloud_cover percentage (with no data pixels) cloud_cover_combined = np.divide(sum(sum(cloud_mask.astype(int))), (cloud_mask.shape[0]*cloud_mask.shape[1])) if cloud_cover_combined > 0.99: # if 99% of cloudy pixels in image skip continue # remove no data pixels from the cloud mask # (for example L7 bands of no data should not be accounted for) cloud_mask_adv = np.logical_xor(cloud_mask, im_nodata) # compute updated cloud cover percentage (without no data pixels) cloud_cover = np.divide(sum(sum(cloud_mask_adv.astype(int))), (sum(sum((~im_nodata).astype(int))))) # skip image if cloud cover is above user-defined threshold if cloud_cover > settings['cloud_thresh']: continue # calculate a buffer around the reference shoreline (if any has been digitised) im_ref_buffer = create_shoreline_buffer(cloud_mask.shape, georef, image_epsg, pixel_size, settings) # classify image in 4 classes (sand, whitewater, water, other) with NN classifier im_classif, im_labels = classify_image_NN(im_ms, im_extra, cloud_mask, min_beach_area_pixels, clf) # if adjust_detection is True, let the user adjust the detected shoreline if settings['adjust_detection']: date = filenames[i][:19] skip_image, shoreline, t_mndwi = adjust_detection(im_ms, cloud_mask, im_labels, im_ref_buffer, image_epsg, georef, settings, date, satname, buffer_size_pixels) # if the user decides to skip the image, continue and do not save the mapped shoreline if skip_image: continue # otherwise map the contours automatically with one of the two following functions: # if there are pixels in the 'sand' class --> use find_wl_contours2 (enhanced) # otherwise use find_wl_contours2 (traditional) else: try: # use try/except structure for long runs if sum(sum(im_labels[:,:,0])) < 10 : # minimum number of sand pixels # compute MNDWI image (SWIR-G) im_mndwi = SDS_tools.nd_index(im_ms[:,:,4], im_ms[:,:,1], cloud_mask) # find water contours on MNDWI grayscale image contours_mwi, t_mndwi = find_wl_contours1(im_mndwi, cloud_mask, im_ref_buffer) else: # use classification to refine threshold and extract the sand/water interface contours_mwi, t_mndwi = find_wl_contours2(im_ms, im_labels, cloud_mask, buffer_size_pixels, im_ref_buffer) except: print('Could not map shoreline for this image: ' + filenames[i]) continue # process the water contours into a shoreline shoreline = process_shoreline(contours_mwi, cloud_mask, georef, image_epsg, settings) # visualise the mapped shorelines, there are two options: # if settings['check_detection'] = True, shows the detection to the user for accept/reject # if settings['save_figure'] = True, saves a figure for each mapped shoreline if settings['check_detection'] or settings['save_figure']: date = filenames[i][:19] if not settings['check_detection']: plt.ioff() # turning interactive plotting off skip_image = show_detection(im_ms, cloud_mask, im_labels, shoreline, image_epsg, georef, settings, date, satname) # if the user decides to skip the image, continue and do not save the mapped shoreline if skip_image: continue # append to output variables output_timestamp.append(metadata[satname]['dates'][i]) output_shoreline.append(shoreline) output_filename.append(filenames[i]) output_cloudcover.append(cloud_cover) output_geoaccuracy.append(metadata[satname]['acc_georef'][i]) output_idxkeep.append(i) output_t_mndwi.append(t_mndwi) # create dictionnary of output output[satname] = { 'dates': output_timestamp, 'shorelines': output_shoreline, 'filename': output_filename, 'cloud_cover': output_cloudcover, 'geoaccuracy': output_geoaccuracy, 'idx': output_idxkeep, 'MNDWI_threshold': output_t_mndwi, } print('') # close figure window if still open if plt.get_fignums(): plt.close() # change the format to have one list sorted by date with all the shorelines (easier to use) output = SDS_tools.merge_output(output) # save outputput structure as output.pkl filepath = os.path.join(filepath_data, sitename) with open(os.path.join(filepath, sitename + '_output.pkl'), 'wb') as f: pickle.dump(output, f) return output
[ "def", "extract_shorelines", "(", "metadata", ",", "settings", ")", ":", "sitename", "=", "settings", "[", "'inputs'", "]", "[", "'sitename'", "]", "filepath_data", "=", "settings", "[", "'inputs'", "]", "[", "'filepath'", "]", "filepath_models", "=", "os", ...
https://github.com/kvos/CoastSat/blob/d1a934c9e4a5eb4ebb295a8a455bd55218fbaf01/coastsat/SDS_shoreline.py#L42-L250
mjpost/sacrebleu
65a8a9eeccd8c0c7875e875e12edf10db33ab0ba
sacrebleu/metrics/chrf.py
python
CHRF._extract_reference_info
(self, refs: Sequence[str])
return {'ref_ngrams': ngrams}
Given a list of reference segments, extract the character and word n-grams. :param refs: A sequence of reference segments. :return: A list where each element contains n-grams per reference segment.
Given a list of reference segments, extract the character and word n-grams.
[ "Given", "a", "list", "of", "reference", "segments", "extract", "the", "character", "and", "word", "n", "-", "grams", "." ]
def _extract_reference_info(self, refs: Sequence[str]) -> Dict[str, List[List[Counter]]]: """Given a list of reference segments, extract the character and word n-grams. :param refs: A sequence of reference segments. :return: A list where each element contains n-grams per reference segment. """ ngrams = [] for ref in refs: # extract character n-grams stats = extract_all_char_ngrams(ref, self.char_order, self.whitespace) # Check chrF+ mode if self.word_order > 0: ref_words = self._remove_punctuation(ref) for n in range(self.word_order): stats.append(extract_word_ngrams(ref_words, n + 1)) ngrams.append(stats) return {'ref_ngrams': ngrams}
[ "def", "_extract_reference_info", "(", "self", ",", "refs", ":", "Sequence", "[", "str", "]", ")", "->", "Dict", "[", "str", ",", "List", "[", "List", "[", "Counter", "]", "]", "]", ":", "ngrams", "=", "[", "]", "for", "ref", "in", "refs", ":", "...
https://github.com/mjpost/sacrebleu/blob/65a8a9eeccd8c0c7875e875e12edf10db33ab0ba/sacrebleu/metrics/chrf.py#L223-L244
google/tf-quant-finance
8fd723689ebf27ff4bb2bd2acb5f6091c5e07309
tf_quant_finance/datetime/schedules.py
python
PeriodicSchedule.generate_backwards
(self)
return self._backward
Returns whether the schedule is generated from the end date.
Returns whether the schedule is generated from the end date.
[ "Returns", "whether", "the", "schedule", "is", "generated", "from", "the", "end", "date", "." ]
def generate_backwards(self): """Returns whether the schedule is generated from the end date.""" return self._backward
[ "def", "generate_backwards", "(", "self", ")", ":", "return", "self", ".", "_backward" ]
https://github.com/google/tf-quant-finance/blob/8fd723689ebf27ff4bb2bd2acb5f6091c5e07309/tf_quant_finance/datetime/schedules.py#L208-L210
OpenCobolIDE/OpenCobolIDE
c78d0d335378e5fe0a5e74f53c19b68b55e85388
open_cobol_ide/extlibs/future/backports/email/parser.py
python
HeaderParser.parse
(self, fp, headersonly=True)
return Parser.parse(self, fp, True)
[]
def parse(self, fp, headersonly=True): return Parser.parse(self, fp, True)
[ "def", "parse", "(", "self", ",", "fp", ",", "headersonly", "=", "True", ")", ":", "return", "Parser", ".", "parse", "(", "self", ",", "fp", ",", "True", ")" ]
https://github.com/OpenCobolIDE/OpenCobolIDE/blob/c78d0d335378e5fe0a5e74f53c19b68b55e85388/open_cobol_ide/extlibs/future/backports/email/parser.py#L78-L79
dmlc/gluon-cv
709bc139919c02f7454cb411311048be188cde64
gluoncv/data/transforms/pose.py
python
count_visible
(ul, br, joints_3d)
return np.sum(vis), vis
Count number of visible joints given bound ul, br
Count number of visible joints given bound ul, br
[ "Count", "number", "of", "visible", "joints", "given", "bound", "ul", "br" ]
def count_visible(ul, br, joints_3d): """Count number of visible joints given bound ul, br""" vis = np.logical_and.reduce(( joints_3d[:, 0, 0] > 0, joints_3d[:, 0, 0] > ul[0], joints_3d[:, 0, 0] < br[0], joints_3d[:, 1, 0] > 0, joints_3d[:, 1, 0] > ul[1], joints_3d[:, 1, 0] < br[1], joints_3d[:, 0, 1] > 0, joints_3d[:, 1, 1] > 0 )) return np.sum(vis), vis
[ "def", "count_visible", "(", "ul", ",", "br", ",", "joints_3d", ")", ":", "vis", "=", "np", ".", "logical_and", ".", "reduce", "(", "(", "joints_3d", "[", ":", ",", "0", ",", "0", "]", ">", "0", ",", "joints_3d", "[", ":", ",", "0", ",", "0", ...
https://github.com/dmlc/gluon-cv/blob/709bc139919c02f7454cb411311048be188cde64/gluoncv/data/transforms/pose.py#L357-L369
nneonneo/2048-ai
5b892173be44f482e521fd028799a3a605b68404
gamectrl.py
python
Fast2048Control.get_status
(self)
return self.execute(''' if(GameManager._instance.over) {"ended"} else if(GameManager._instance.won && !GameManager._instance.keepPlaying) {"won"} else {"running"} ''')
Check if the game is in an unusual state.
Check if the game is in an unusual state.
[ "Check", "if", "the", "game", "is", "in", "an", "unusual", "state", "." ]
def get_status(self): ''' Check if the game is in an unusual state. ''' return self.execute(''' if(GameManager._instance.over) {"ended"} else if(GameManager._instance.won && !GameManager._instance.keepPlaying) {"won"} else {"running"} ''')
[ "def", "get_status", "(", "self", ")", ":", "return", "self", ".", "execute", "(", "'''\n if(GameManager._instance.over) {\"ended\"}\n else if(GameManager._instance.won && !GameManager._instance.keepPlaying) {\"won\"}\n else {\"running\"}\n '''", "...
https://github.com/nneonneo/2048-ai/blob/5b892173be44f482e521fd028799a3a605b68404/gamectrl.py#L76-L82
MartinThoma/algorithms
6199cfa3446e1056c7b4d75ca6e306e9e56fd95b
ML/50-mlps/02-keras-validation-curve/hasy_tools.py
python
_get_colors
(data, verbose=False)
return color_count
Get how often each color is used in data. Parameters ---------- data : dict with key 'path' pointing to an image verbose : bool, optional Returns ------- color_count : dict Maps a grayscale value (0..255) to how often it was in `data`
Get how often each color is used in data.
[ "Get", "how", "often", "each", "color", "is", "used", "in", "data", "." ]
def _get_colors(data, verbose=False): """ Get how often each color is used in data. Parameters ---------- data : dict with key 'path' pointing to an image verbose : bool, optional Returns ------- color_count : dict Maps a grayscale value (0..255) to how often it was in `data` """ color_count = {} for i in range(256): color_count[i] = 0 for i, data_item in enumerate(data): if i % 1000 == 0 and i > 0 and verbose: print("%i of %i done" % (i, len(data))) fname = os.path.join('.', data_item['path']) img = scipy.ndimage.imread(fname, flatten=False, mode='L') for row in img: for pixel in row: color_count[pixel] += 1 return color_count
[ "def", "_get_colors", "(", "data", ",", "verbose", "=", "False", ")", ":", "color_count", "=", "{", "}", "for", "i", "in", "range", "(", "256", ")", ":", "color_count", "[", "i", "]", "=", "0", "for", "i", ",", "data_item", "in", "enumerate", "(", ...
https://github.com/MartinThoma/algorithms/blob/6199cfa3446e1056c7b4d75ca6e306e9e56fd95b/ML/50-mlps/02-keras-validation-curve/hasy_tools.py#L612-L638
open-mmlab/mmclassification
5232965b17b6c050f9b328b3740c631ed4034624
mmcls/datasets/base_dataset.py
python
BaseDataset.get_cat_ids
(self, idx: int)
return [int(self.data_infos[idx]['gt_label'])]
Get category id by index. Args: idx (int): Index of data. Returns: cat_ids (List[int]): Image category of specified index.
Get category id by index.
[ "Get", "category", "id", "by", "index", "." ]
def get_cat_ids(self, idx: int) -> List[int]: """Get category id by index. Args: idx (int): Index of data. Returns: cat_ids (List[int]): Image category of specified index. """ return [int(self.data_infos[idx]['gt_label'])]
[ "def", "get_cat_ids", "(", "self", ",", "idx", ":", "int", ")", "->", "List", "[", "int", "]", ":", "return", "[", "int", "(", "self", ".", "data_infos", "[", "idx", "]", "[", "'gt_label'", "]", ")", "]" ]
https://github.com/open-mmlab/mmclassification/blob/5232965b17b6c050f9b328b3740c631ed4034624/mmcls/datasets/base_dataset.py#L68-L78
qiueer/zabbix
31983dedbd59d917ecd71bb6f36b35302673a783
Memcache/qiueer/python/cmds.py
python
cmds.code
(self)
return self.retcode
[]
def code(self): return self.retcode
[ "def", "code", "(", "self", ")", ":", "return", "self", ".", "retcode" ]
https://github.com/qiueer/zabbix/blob/31983dedbd59d917ecd71bb6f36b35302673a783/Memcache/qiueer/python/cmds.py#L68-L69
samuelclay/NewsBlur
2c45209df01a1566ea105e04d499367f32ac9ad2
apps/analyzer/models.py
python
MPopularityQuery.ensure_sent
(self, queue=True)
[]
def ensure_sent(self, queue=True): if self.is_emailed: logging.debug(" ---> Already sent %s" % self) return if queue: self.queue_email() else: self.send_email()
[ "def", "ensure_sent", "(", "self", ",", "queue", "=", "True", ")", ":", "if", "self", ".", "is_emailed", ":", "logging", ".", "debug", "(", "\" ---> Already sent %s\"", "%", "self", ")", "return", "if", "queue", ":", "self", ".", "queue_email", "(", ")",...
https://github.com/samuelclay/NewsBlur/blob/2c45209df01a1566ea105e04d499367f32ac9ad2/apps/analyzer/models.py#L55-L63
Qiskit/qiskit-terra
b66030e3b9192efdd3eb95cf25c6545fe0a13da4
qiskit/circuit/instruction.py
python
Instruction.name
(self, name)
Set the name.
Set the name.
[ "Set", "the", "name", "." ]
def name(self, name): """Set the name.""" self._name = name
[ "def", "name", "(", "self", ",", "name", ")", ":", "self", ".", "_name", "=", "name" ]
https://github.com/Qiskit/qiskit-terra/blob/b66030e3b9192efdd3eb95cf25c6545fe0a13da4/qiskit/circuit/instruction.py#L556-L558
google/rekall
55d1925f2df9759a989b35271b4fa48fc54a1c86
rekall-core/rekall/session.py
python
InteractiveSession.__init__
(self, env=None, use_config_file=True, **kwargs)
Creates an interactive session. Args: env: If passed we use this dict as the local environment. use_config_file: If True we merge the system's config file into the session. This helps set the correct profile paths for example. kwargs: Arbitrary parameters to store in the session. Returns: an interactive session object.
Creates an interactive session.
[ "Creates", "an", "interactive", "session", "." ]
def __init__(self, env=None, use_config_file=True, **kwargs): """Creates an interactive session. Args: env: If passed we use this dict as the local environment. use_config_file: If True we merge the system's config file into the session. This helps set the correct profile paths for example. kwargs: Arbitrary parameters to store in the session. Returns: an interactive session object. """ # When this session was created. self._start_time = time.time() # These keep track of the last run plugin. self._last_plugin = None # Fill the session with helpful defaults. self.pager = obj.NoneObject("Set this to your favourite pager.") # Set the session name self.session_name = kwargs.pop("session_name", u"Default session") super(InteractiveSession, self).__init__() # Prepare the local namespace for the interactive session. self.locals = DynamicNameSpace( session=self, # Prepopulate the namespace with our most important modules. v=self.v, # Some useful modules which should be available always. sys=sys, os=os, # A list of sessions. session_list=self.session_list, # Pass additional environment. **(env or {}) ) with self.state: self.state.Set("session_list", self.session_list) self.state.Set("session_name", self.session_name) self.state.Set("session_id", self._new_session_id()) # Configure the session from the config file and kwargs. if use_config_file: with self.state: config.MergeConfigOptions(self.state, self) with self.state: for k, v in list(kwargs.items()): self.state.Set(k, v)
[ "def", "__init__", "(", "self", ",", "env", "=", "None", ",", "use_config_file", "=", "True", ",", "*", "*", "kwargs", ")", ":", "# When this session was created.", "self", ".", "_start_time", "=", "time", ".", "time", "(", ")", "# These keep track of the last...
https://github.com/google/rekall/blob/55d1925f2df9759a989b35271b4fa48fc54a1c86/rekall-core/rekall/session.py#L1217-L1273
rolczynski/Automatic-Speech-Recognition
ee06aba33ba9a3f431bc1d2a5bfa74d929406caa
automatic_speech_recognition/text/alphabet.py
python
Alphabet.get_batch_transcripts
(self, sequences: List[np.ndarray])
return [''.join(self.string_from_label(char_label) for char_label in sequence if char_label not in (-1, self.blank_token)) for sequence in sequences]
Convert label sequences to transcripts. The `-1` also means the blank tag
Convert label sequences to transcripts. The `-1` also means the blank tag
[ "Convert", "label", "sequences", "to", "transcripts", ".", "The", "-", "1", "also", "means", "the", "blank", "tag" ]
def get_batch_transcripts(self, sequences: List[np.ndarray]) -> List[str]: """ Convert label sequences to transcripts. The `-1` also means the blank tag """ return [''.join(self.string_from_label(char_label) for char_label in sequence if char_label not in (-1, self.blank_token)) for sequence in sequences]
[ "def", "get_batch_transcripts", "(", "self", ",", "sequences", ":", "List", "[", "np", ".", "ndarray", "]", ")", "->", "List", "[", "str", "]", ":", "return", "[", "''", ".", "join", "(", "self", ".", "string_from_label", "(", "char_label", ")", "for",...
https://github.com/rolczynski/Automatic-Speech-Recognition/blob/ee06aba33ba9a3f431bc1d2a5bfa74d929406caa/automatic_speech_recognition/text/alphabet.py#L65-L71
maxjiang93/ugscnn
89cdd512e21a2d0cbb884e52ee75645c39ad6ed7
experiments/exp3_2d3ds/stats.py
python
StatsRecorder.__init__
(self, data=None)
data: ndarray, shape (nobservations, ndimensions)
data: ndarray, shape (nobservations, ndimensions)
[ "data", ":", "ndarray", "shape", "(", "nobservations", "ndimensions", ")" ]
def __init__(self, data=None): """ data: ndarray, shape (nobservations, ndimensions) """ if data is not None: data = np.atleast_2d(data) self.mean = data.mean(axis=0) self.std = data.std(axis=0) self.nobservations = data.shape[0] self.ndimensions = data.shape[1] else: self.nobservations = 0
[ "def", "__init__", "(", "self", ",", "data", "=", "None", ")", ":", "if", "data", "is", "not", "None", ":", "data", "=", "np", ".", "atleast_2d", "(", "data", ")", "self", ".", "mean", "=", "data", ".", "mean", "(", "axis", "=", "0", ")", "self...
https://github.com/maxjiang93/ugscnn/blob/89cdd512e21a2d0cbb884e52ee75645c39ad6ed7/experiments/exp3_2d3ds/stats.py#L11-L22
alex-berard/seq2seq
1b5c6bf19a39ef27c059811b85a061f20d68ac32
translate/utils.py
python
create_logger
(log_file=None)
return logger
Initialize global logger and return it. :param log_file: log to this file, or to standard output if None :return: created logger
Initialize global logger and return it.
[ "Initialize", "global", "logger", "and", "return", "it", "." ]
def create_logger(log_file=None): """ Initialize global logger and return it. :param log_file: log to this file, or to standard output if None :return: created logger """ formatter = logging.Formatter(fmt='%(asctime)s %(message)s', datefmt='%m/%d %H:%M:%S') if log_file is not None: os.makedirs(os.path.dirname(log_file), exist_ok=True) handler = logging.FileHandler(log_file) handler.setFormatter(formatter) logger = logging.getLogger(__name__) logger.addHandler(handler) handler = logging.StreamHandler() handler.setFormatter(formatter) logger = logging.getLogger(__name__) logger.addHandler(handler) return logger
[ "def", "create_logger", "(", "log_file", "=", "None", ")", ":", "formatter", "=", "logging", ".", "Formatter", "(", "fmt", "=", "'%(asctime)s %(message)s'", ",", "datefmt", "=", "'%m/%d %H:%M:%S'", ")", "if", "log_file", "is", "not", "None", ":", "os", ".", ...
https://github.com/alex-berard/seq2seq/blob/1b5c6bf19a39ef27c059811b85a061f20d68ac32/translate/utils.py#L497-L516
firedm/FireDM
d27d3d27c869625f75520ca2bacfa9ebd11caf2f
firedm/controller.py
python
write_timestamp
(d)
write server timestamp to downloaded file try to figure out the timestamp of the remote file, and if available make the local file get that same timestamp. Args: d (ObservableDownloadItem): download item
write server timestamp to downloaded file
[ "write", "server", "timestamp", "to", "downloaded", "file" ]
def write_timestamp(d): """write server timestamp to downloaded file try to figure out the timestamp of the remote file, and if available make the local file get that same timestamp. Args: d (ObservableDownloadItem): download item """ try: if d.status == Status.completed: timestamp = '' try: # assume this is a video file, get upload date upload_date = d.vid_info.get('upload_date') # YYYYMMDD e.g. 20201009 timestamp = time.mktime(time.strptime(upload_date, '%Y%m%d')) except: pass if not timestamp: # get last modified timestamp from server, eg. 'last-modified': 'Fri, 22 Feb 2019 09:30:09 GMT' headers = get_headers(d.eff_url, http_headers=d.http_headers) last_modified = headers.get('last-modified') if last_modified: # parse timestamp dt = parsedate_to_datetime(last_modified) timestamp = dt.timestamp() # will correct for local time if timestamp: log(f'writing timestamp "{timestamp}" to file: {d.name}', log_level=2) os.utime(d.target_file, (timestamp, timestamp)) # modify creation time on windows, # credit: https://github.com/Delgan/win32-setctime/blob/master/win32_setctime.py if config.operating_system == 'Windows': # Convert Unix timestamp to Windows FileTime using some magic numbers timestamp = int((timestamp * 10000000) + 116444736000000000) ctime = wintypes.FILETIME(timestamp & 0xFFFFFFFF, timestamp >> 32) # Call Win32 API to modify the file creation date handle = windll.kernel32.CreateFileW(d.target_file, 256, 0, None, 3, 128, None) windll.kernel32.SetFileTime(handle, byref(ctime), None, None) windll.kernel32.CloseHandle(handle) except Exception as e: log('controller.write_timestamp()> error:', e) if config.test_mode: raise e
[ "def", "write_timestamp", "(", "d", ")", ":", "try", ":", "if", "d", ".", "status", "==", "Status", ".", "completed", ":", "timestamp", "=", "''", "try", ":", "# assume this is a video file, get upload date", "upload_date", "=", "d", ".", "vid_info", ".", "g...
https://github.com/firedm/FireDM/blob/d27d3d27c869625f75520ca2bacfa9ebd11caf2f/firedm/controller.py#L119-L169
uwdata/termite-data-server
1085571407c627bdbbd21c352e793fed65d09599
web2py/gluon/contrib/memdb.py
python
test_all
()
How to run from web2py dir: export PYTHONPATH=.:YOUR_PLATFORMS_APPENGINE_PATH python gluon/contrib/memdb.py Setup the UTC timezone and database stubs >>> import os >>> os.environ['TZ'] = 'UTC' >>> import time >>> if hasattr(time, 'tzset'): ... time.tzset() >>> >>> from google.appengine.api import apiproxy_stub_map >>> from google.appengine.api.memcache import memcache_stub >>> apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap() >>> apiproxy_stub_map.apiproxy.RegisterStub('memcache', memcache_stub.MemcacheServiceStub()) Create a table with all possible field types >>> from google.appengine.api.memcache import Client >>> db=MEMDB(Client()) >>> tmp=db.define_table('users', Field('stringf','string',length=32,required=True), Field('booleanf','boolean',default=False), Field('passwordf','password',notnull=True), Field('blobf','blob'), Field('uploadf','upload'), Field('integerf','integer',unique=True), Field('doublef','double',unique=True,notnull=True), Field('datef','date',default=datetime.date.today()), Field('timef','time'), Field('datetimef','datetime'), migrate='test_user.table') Insert a field >>> user_id = db.users.insert(stringf='a',booleanf=True,passwordf='p',blobf='0A', uploadf=None, integerf=5,doublef=3.14, datef=datetime.date(2001,1,1), timef=datetime.time(12,30,15), datetimef=datetime.datetime(2002,2,2,12,30,15)) >>> user_id != None True Select all # >>> all = db().select(db.users.ALL) Drop the table # >>> db.users.drop() Select many entities >>> tmp = db.define_table(\"posts\", Field('body','text'), Field('total','integer'), Field('created_at','datetime')) >>> many = 20 #2010 # more than 1000 single fetch limit (it can be slow) >>> few = 5 >>> most = many - few >>> 0 < few < most < many True >>> for i in range(many): ... f=db.posts.insert(body='', total=i,created_at=datetime.datetime(2008, 7, 6, 14, 15, 42, i)) >>> # test timezones >>> class TZOffset(datetime.tzinfo): ... def __init__(self,offset=0): ... self.offset = offset ... def utcoffset(self, dt): return datetime.timedelta(hours=self.offset) ... def dst(self, dt): return datetime.timedelta(0) ... def tzname(self, dt): return 'UTC' + str(self.offset) ... >>> SERVER_OFFSET = -8 >>> >>> stamp = datetime.datetime(2008, 7, 6, 14, 15, 42, 828201) >>> post_id = db.posts.insert(created_at=stamp,body='body1') >>> naive_stamp = db(db.posts.id==post_id).select()[0].created_at >>> utc_stamp=naive_stamp.replace(tzinfo=TZOffset()) >>> server_stamp = utc_stamp.astimezone(TZOffset(SERVER_OFFSET)) >>> stamp == naive_stamp True >>> utc_stamp == server_stamp True >>> rows = db(db.posts.id==post_id).select() >>> len(rows) == 1 True >>> rows[0].body == 'body1' True >>> db(db.posts.id==post_id).delete() >>> rows = db(db.posts.id==post_id).select() >>> len(rows) == 0 True >>> id = db.posts.insert(total='0') # coerce str to integer >>> rows = db(db.posts.id==id).select() >>> len(rows) == 1 True >>> rows[0].total == 0 True Examples of insert, select, update, delete >>> tmp=db.define_table('person', Field('name'), Field('birth','date'), migrate='test_person.table') >>> marco_id=db.person.insert(name=\"Marco\",birth='2005-06-22') >>> person_id=db.person.insert(name=\"Massimo\",birth='1971-12-21') >>> me=db(db.person.id==person_id).select()[0] # test select >>> me.name 'Massimo' >>> db(db.person.id==person_id).update(name='massimo') # test update >>> me = db(db.person.id==person_id).select()[0] >>> me.name 'massimo' >>> str(me.birth) '1971-12-21' # resave date to ensure it comes back the same >>> me=db(db.person.id==person_id).update(birth=me.birth) # test update >>> me = db(db.person.id==person_id).select()[0] >>> me.birth datetime.date(1971, 12, 21) >>> db(db.person.id==marco_id).delete() # test delete >>> len(db(db.person.id==marco_id).select()) 0 Update a single record >>> me.update_record(name=\"Max\") >>> me.name 'Max' >>> me = db(db.person.id == person_id).select()[0] >>> me.name 'Max'
How to run from web2py dir: export PYTHONPATH=.:YOUR_PLATFORMS_APPENGINE_PATH python gluon/contrib/memdb.py
[ "How", "to", "run", "from", "web2py", "dir", ":", "export", "PYTHONPATH", "=", ".", ":", "YOUR_PLATFORMS_APPENGINE_PATH", "python", "gluon", "/", "contrib", "/", "memdb", ".", "py" ]
def test_all(): """ How to run from web2py dir: export PYTHONPATH=.:YOUR_PLATFORMS_APPENGINE_PATH python gluon/contrib/memdb.py Setup the UTC timezone and database stubs >>> import os >>> os.environ['TZ'] = 'UTC' >>> import time >>> if hasattr(time, 'tzset'): ... time.tzset() >>> >>> from google.appengine.api import apiproxy_stub_map >>> from google.appengine.api.memcache import memcache_stub >>> apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap() >>> apiproxy_stub_map.apiproxy.RegisterStub('memcache', memcache_stub.MemcacheServiceStub()) Create a table with all possible field types >>> from google.appengine.api.memcache import Client >>> db=MEMDB(Client()) >>> tmp=db.define_table('users', Field('stringf','string',length=32,required=True), Field('booleanf','boolean',default=False), Field('passwordf','password',notnull=True), Field('blobf','blob'), Field('uploadf','upload'), Field('integerf','integer',unique=True), Field('doublef','double',unique=True,notnull=True), Field('datef','date',default=datetime.date.today()), Field('timef','time'), Field('datetimef','datetime'), migrate='test_user.table') Insert a field >>> user_id = db.users.insert(stringf='a',booleanf=True,passwordf='p',blobf='0A', uploadf=None, integerf=5,doublef=3.14, datef=datetime.date(2001,1,1), timef=datetime.time(12,30,15), datetimef=datetime.datetime(2002,2,2,12,30,15)) >>> user_id != None True Select all # >>> all = db().select(db.users.ALL) Drop the table # >>> db.users.drop() Select many entities >>> tmp = db.define_table(\"posts\", Field('body','text'), Field('total','integer'), Field('created_at','datetime')) >>> many = 20 #2010 # more than 1000 single fetch limit (it can be slow) >>> few = 5 >>> most = many - few >>> 0 < few < most < many True >>> for i in range(many): ... f=db.posts.insert(body='', total=i,created_at=datetime.datetime(2008, 7, 6, 14, 15, 42, i)) >>> # test timezones >>> class TZOffset(datetime.tzinfo): ... def __init__(self,offset=0): ... self.offset = offset ... def utcoffset(self, dt): return datetime.timedelta(hours=self.offset) ... def dst(self, dt): return datetime.timedelta(0) ... def tzname(self, dt): return 'UTC' + str(self.offset) ... >>> SERVER_OFFSET = -8 >>> >>> stamp = datetime.datetime(2008, 7, 6, 14, 15, 42, 828201) >>> post_id = db.posts.insert(created_at=stamp,body='body1') >>> naive_stamp = db(db.posts.id==post_id).select()[0].created_at >>> utc_stamp=naive_stamp.replace(tzinfo=TZOffset()) >>> server_stamp = utc_stamp.astimezone(TZOffset(SERVER_OFFSET)) >>> stamp == naive_stamp True >>> utc_stamp == server_stamp True >>> rows = db(db.posts.id==post_id).select() >>> len(rows) == 1 True >>> rows[0].body == 'body1' True >>> db(db.posts.id==post_id).delete() >>> rows = db(db.posts.id==post_id).select() >>> len(rows) == 0 True >>> id = db.posts.insert(total='0') # coerce str to integer >>> rows = db(db.posts.id==id).select() >>> len(rows) == 1 True >>> rows[0].total == 0 True Examples of insert, select, update, delete >>> tmp=db.define_table('person', Field('name'), Field('birth','date'), migrate='test_person.table') >>> marco_id=db.person.insert(name=\"Marco\",birth='2005-06-22') >>> person_id=db.person.insert(name=\"Massimo\",birth='1971-12-21') >>> me=db(db.person.id==person_id).select()[0] # test select >>> me.name 'Massimo' >>> db(db.person.id==person_id).update(name='massimo') # test update >>> me = db(db.person.id==person_id).select()[0] >>> me.name 'massimo' >>> str(me.birth) '1971-12-21' # resave date to ensure it comes back the same >>> me=db(db.person.id==person_id).update(birth=me.birth) # test update >>> me = db(db.person.id==person_id).select()[0] >>> me.birth datetime.date(1971, 12, 21) >>> db(db.person.id==marco_id).delete() # test delete >>> len(db(db.person.id==marco_id).select()) 0 Update a single record >>> me.update_record(name=\"Max\") >>> me.name 'Max' >>> me = db(db.person.id == person_id).select()[0] >>> me.name 'Max' """
[ "def", "test_all", "(", ")", ":" ]
https://github.com/uwdata/termite-data-server/blob/1085571407c627bdbbd21c352e793fed65d09599/web2py/gluon/contrib/memdb.py#L772-L891
wistbean/fxxkpython
88e16d79d8dd37236ba6ecd0d0ff11d63143968c
vip/qyxuan/projects/Snake/venv/lib/python3.6/site-packages/pygame/examples/sound_array_demos.py
python
main
(arraytype=None)
play various sndarray effects If arraytype is provided then use that array package. Valid values are 'numeric' or 'numpy'. Otherwise default to NumPy, or fall back on Numeric if NumPy is not installed.
play various sndarray effects
[ "play", "various", "sndarray", "effects" ]
def main(arraytype=None): """play various sndarray effects If arraytype is provided then use that array package. Valid values are 'numeric' or 'numpy'. Otherwise default to NumPy, or fall back on Numeric if NumPy is not installed. """ main_dir = os.path.split(os.path.abspath(__file__))[0] if arraytype not in ('numpy', None): raise ValueError('Array type not supported: %r' % arraytype) print ("Using %s array package" % sndarray.get_arraytype()) print ("mixer.get_init %s" % (mixer.get_init(),)) inited = mixer.get_init() samples_per_second = pygame.mixer.get_init()[0] print (("-" * 30) + "\n") print ("loading sound") sound = mixer.Sound(os.path.join(main_dir, 'data', 'car_door.wav')) print ("-" * 30) print ("start positions") print ("-" * 30) start_pos = 0.1 sound2 = sound_from_pos(sound, start_pos, samples_per_second) print ("sound.get_length %s" % (sound.get_length(),)) print ("sound2.get_length %s" % (sound2.get_length(),)) sound2.play() while mixer.get_busy(): pygame.time.wait(200) print ("waiting 2 seconds") pygame.time.wait(2000) print ("playing original sound") sound.play() while mixer.get_busy(): pygame.time.wait(200) print ("waiting 2 seconds") pygame.time.wait(2000) if 0: #TODO: this is broken. print (("-" * 30) + "\n") print ("Slow down the original sound.") rate = 0.2 slowed_sound = slow_down_sound(sound, rate) slowed_sound.play() while mixer.get_busy(): pygame.time.wait(200) print ("-" * 30) print ("echoing") print ("-" * 30) t1 = time.time() sound2 = make_echo(sound, samples_per_second) print ("time to make echo %i" % (time.time() - t1,)) print ("original sound") sound.play() while mixer.get_busy(): pygame.time.wait(200) print ("echoed sound") sound2.play() while mixer.get_busy(): pygame.time.wait(200) sound = mixer.Sound(os.path.join(main_dir, 'data', 'secosmic_lo.wav')) t1 = time.time() sound3 = make_echo(sound, samples_per_second) print ("time to make echo %i" % (time.time() - t1,)) print ("original sound") sound.play() while mixer.get_busy(): pygame.time.wait(200) print ("echoed sound") sound3.play() while mixer.get_busy(): pygame.time.wait(200)
[ "def", "main", "(", "arraytype", "=", "None", ")", ":", "main_dir", "=", "os", ".", "path", ".", "split", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", "[", "0", "]", "if", "arraytype", "not", "in", "(", "'numpy'", ",", "None...
https://github.com/wistbean/fxxkpython/blob/88e16d79d8dd37236ba6ecd0d0ff11d63143968c/vip/qyxuan/projects/Snake/venv/lib/python3.6/site-packages/pygame/examples/sound_array_demos.py#L158-L259
pytroll/satpy
09e51f932048f98cce7919a4ff8bd2ec01e1ae98
satpy/readers/slstr_l1b.py
python
NCSLSTRFlag.get_dataset
(self, key, info)
return variable
Load a dataset.
Load a dataset.
[ "Load", "a", "dataset", "." ]
def get_dataset(self, key, info): """Load a dataset.""" if (self.stripe != key['stripe'].name or self.view != key['view'].name): return logger.debug('Reading %s.', key['name']) file_key = info['file_key'].format(view=key['view'].name[0], stripe=key['stripe'].name) variable = self.nc[file_key] info = info.copy() info.update(variable.attrs) info.update(key.to_dict()) info.update(dict(platform_name=self.platform_name, sensor=self.sensor)) variable.attrs = info return variable
[ "def", "get_dataset", "(", "self", ",", "key", ",", "info", ")", ":", "if", "(", "self", ".", "stripe", "!=", "key", "[", "'stripe'", "]", ".", "name", "or", "self", ".", "view", "!=", "key", "[", "'view'", "]", ".", "name", ")", ":", "return", ...
https://github.com/pytroll/satpy/blob/09e51f932048f98cce7919a4ff8bd2ec01e1ae98/satpy/readers/slstr_l1b.py#L352-L369
Billwilliams1952/PiCameraApp
61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0
Source/Exposure.py
python
Exposure.DrcChecked
( self, DrcEnabled )
[]
def DrcChecked ( self, DrcEnabled ): if DrcEnabled == False: self.camera.drc_strength = 'off' self.DrcCombo.config(state = 'disabled') else: self.DrcStrengthChanged(None) self.DrcCombo.config(state = 'readonly') self.DrcCombo.focus_set()
[ "def", "DrcChecked", "(", "self", ",", "DrcEnabled", ")", ":", "if", "DrcEnabled", "==", "False", ":", "self", ".", "camera", ".", "drc_strength", "=", "'off'", "self", ".", "DrcCombo", ".", "config", "(", "state", "=", "'disabled'", ")", "else", ":", ...
https://github.com/Billwilliams1952/PiCameraApp/blob/61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0/Source/Exposure.py#L360-L367
NoGameNoLife00/mybolg
afe17ea5bfe405e33766e5682c43a4262232ee12
libs/werkzeug/debug/tbtools.py
python
Frame.render
(self)
return FRAME_HTML % { 'id': self.id, 'filename': escape(self.filename), 'lineno': self.lineno, 'function_name': escape(self.function_name), 'current_line': escape(self.current_line.strip()) }
Render a single frame in a traceback.
Render a single frame in a traceback.
[ "Render", "a", "single", "frame", "in", "a", "traceback", "." ]
def render(self): """Render a single frame in a traceback.""" return FRAME_HTML % { 'id': self.id, 'filename': escape(self.filename), 'lineno': self.lineno, 'function_name': escape(self.function_name), 'current_line': escape(self.current_line.strip()) }
[ "def", "render", "(", "self", ")", ":", "return", "FRAME_HTML", "%", "{", "'id'", ":", "self", ".", "id", ",", "'filename'", ":", "escape", "(", "self", ".", "filename", ")", ",", "'lineno'", ":", "self", ".", "lineno", ",", "'function_name'", ":", "...
https://github.com/NoGameNoLife00/mybolg/blob/afe17ea5bfe405e33766e5682c43a4262232ee12/libs/werkzeug/debug/tbtools.py#L396-L404
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/types.py
python
_GeneratorWrapper.__next__
(self)
return next(self.__wrapped)
[]
def __next__(self): return next(self.__wrapped)
[ "def", "__next__", "(", "self", ")", ":", "return", "next", "(", "self", ".", "__wrapped", ")" ]
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/types.py#L241-L242
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.5/django/utils/encoding.py
python
force_bytes
(s, encoding='utf-8', strings_only=False, errors='strict')
Similar to smart_bytes, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects.
Similar to smart_bytes, except that lazy instances are resolved to strings, rather than kept as lazy objects.
[ "Similar", "to", "smart_bytes", "except", "that", "lazy", "instances", "are", "resolved", "to", "strings", "rather", "than", "kept", "as", "lazy", "objects", "." ]
def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'): """ Similar to smart_bytes, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ if isinstance(s, bytes): if encoding == 'utf-8': return s else: return s.decode('utf-8', errors).encode(encoding, errors) if strings_only and (s is None or isinstance(s, int)): return s if isinstance(s, Promise): return six.text_type(s).encode(encoding, errors) if not isinstance(s, six.string_types): try: if six.PY3: return six.text_type(s).encode(encoding) else: return bytes(s) except UnicodeEncodeError: if isinstance(s, Exception): # An Exception subclass containing non-ASCII data that doesn't # know how to print itself properly. We shouldn't raise a # further exception. return b' '.join([force_bytes(arg, encoding, strings_only, errors) for arg in s]) return six.text_type(s).encode(encoding, errors) else: return s.encode(encoding, errors)
[ "def", "force_bytes", "(", "s", ",", "encoding", "=", "'utf-8'", ",", "strings_only", "=", "False", ",", "errors", "=", "'strict'", ")", ":", "if", "isinstance", "(", "s", ",", "bytes", ")", ":", "if", "encoding", "==", "'utf-8'", ":", "return", "s", ...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.5/django/utils/encoding.py#L138-L169
vladris/tinkerer
e6459e501ec14094e0448c5b0f628ef8666a3ac9
tinkerer/utils.py
python
name_from_title
(title)
return UNICODE_ALNUM_PTN.sub(word_sep, title).lower().strip(word_sep)
Returns a doc name from a title by replacing all groups of characters which are not alphanumeric or '_' with the word separator character.
Returns a doc name from a title by replacing all groups of characters which are not alphanumeric or '_' with the word separator character.
[ "Returns", "a", "doc", "name", "from", "a", "title", "by", "replacing", "all", "groups", "of", "characters", "which", "are", "not", "alphanumeric", "or", "_", "with", "the", "word", "separator", "character", "." ]
def name_from_title(title): ''' Returns a doc name from a title by replacing all groups of characters which are not alphanumeric or '_' with the word separator character. ''' try: word_sep = get_conf().slug_word_separator except Exception: word_sep = "_" return UNICODE_ALNUM_PTN.sub(word_sep, title).lower().strip(word_sep)
[ "def", "name_from_title", "(", "title", ")", ":", "try", ":", "word_sep", "=", "get_conf", "(", ")", ".", "slug_word_separator", "except", "Exception", ":", "word_sep", "=", "\"_\"", "return", "UNICODE_ALNUM_PTN", ".", "sub", "(", "word_sep", ",", "title", "...
https://github.com/vladris/tinkerer/blob/e6459e501ec14094e0448c5b0f628ef8666a3ac9/tinkerer/utils.py#L20-L31
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/asyncore.py
python
dispatcher.handle_expt_event
(self)
[]
def handle_expt_event(self): # handle_expt_event() is called if there might be an error on the # socket, or if there is OOB data # check for the error condition first err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) if err != 0: # we can get here when select.select() says that there is an # exceptional condition on the socket # since there is an error, we'll go ahead and close the socket # like we would in a subclassed handle_read() that received no # data self.handle_close() else: self.handle_expt()
[ "def", "handle_expt_event", "(", "self", ")", ":", "# handle_expt_event() is called if there might be an error on the", "# socket, or if there is OOB data", "# check for the error condition first", "err", "=", "self", ".", "socket", ".", "getsockopt", "(", "socket", ".", "SOL_S...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/asyncore.py#L468-L481
SeuTao/kaggle-competition-solutions
784a2ec2812b2079a49b913bf8ffaa9d58657858
CVPR19_iMetCollection_7th_solution/models/resnet_sge.py
python
conv1x1
(in_planes, out_planes, stride=1)
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
1x1 convolution
1x1 convolution
[ "1x1", "convolution" ]
def conv1x1(in_planes, out_planes, stride=1): """1x1 convolution""" return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
[ "def", "conv1x1", "(", "in_planes", ",", "out_planes", ",", "stride", "=", "1", ")", ":", "return", "nn", ".", "Conv2d", "(", "in_planes", ",", "out_planes", ",", "kernel_size", "=", "1", ",", "stride", "=", "stride", ",", "bias", "=", "False", ")" ]
https://github.com/SeuTao/kaggle-competition-solutions/blob/784a2ec2812b2079a49b913bf8ffaa9d58657858/CVPR19_iMetCollection_7th_solution/models/resnet_sge.py#L43-L45
ahmetcemturan/SFACT
7576e29ba72b33e5058049b77b7b558875542747
skeinforge_application/skeinforge_plugins/craft_plugins/skirt.py
python
getNewRepository
()
return SkirtRepository()
Get new repository.
Get new repository.
[ "Get", "new", "repository", "." ]
def getNewRepository(): 'Get new repository.' return SkirtRepository()
[ "def", "getNewRepository", "(", ")", ":", "return", "SkirtRepository", "(", ")" ]
https://github.com/ahmetcemturan/SFACT/blob/7576e29ba72b33e5058049b77b7b558875542747/skeinforge_application/skeinforge_plugins/craft_plugins/skirt.py#L104-L106
msracver/Deformable-ConvNets
6aeda878a95bcb55eadffbe125804e730574de8d
faster_rcnn/core/rcnn.py
python
get_rcnn_testbatch
(roidb, cfg)
return data, label, im_info
return a dict of testbatch :param roidb: ['image', 'flipped'] + ['boxes'] :return: data, label, im_info
return a dict of testbatch :param roidb: ['image', 'flipped'] + ['boxes'] :return: data, label, im_info
[ "return", "a", "dict", "of", "testbatch", ":", "param", "roidb", ":", "[", "image", "flipped", "]", "+", "[", "boxes", "]", ":", "return", ":", "data", "label", "im_info" ]
def get_rcnn_testbatch(roidb, cfg): """ return a dict of testbatch :param roidb: ['image', 'flipped'] + ['boxes'] :return: data, label, im_info """ # assert len(roidb) == 1, 'Single batch only' imgs, roidb = get_image(roidb, cfg) im_array = imgs im_info = [np.array([roidb[i]['im_info']], dtype=np.float32) for i in range(len(roidb))] im_rois = [roidb[i]['boxes'] for i in range(len(roidb))] rois = im_rois rois_array = [np.hstack((0 * np.ones((rois[i].shape[0], 1)), rois[i])) for i in range(len(rois))] data = [{'data': im_array[i], 'rois': rois_array[i]} for i in range(len(roidb))] label = {} return data, label, im_info
[ "def", "get_rcnn_testbatch", "(", "roidb", ",", "cfg", ")", ":", "# assert len(roidb) == 1, 'Single batch only'", "imgs", ",", "roidb", "=", "get_image", "(", "roidb", ",", "cfg", ")", "im_array", "=", "imgs", "im_info", "=", "[", "np", ".", "array", "(", "[...
https://github.com/msracver/Deformable-ConvNets/blob/6aeda878a95bcb55eadffbe125804e730574de8d/faster_rcnn/core/rcnn.py#L35-L54
spectacles/CodeComplice
8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62
libs/process.py
python
AbortableProcessHelper.ProcessAbort
(self)
Kill the process if it is still running.
Kill the process if it is still running.
[ "Kill", "the", "process", "if", "it", "is", "still", "running", "." ]
def ProcessAbort(self): """Kill the process if it is still running.""" self._process_status_lock.acquire() try: self._process_status = self.STATUS_ABORTED if self._process: self._process.kill() self._process = None finally: self._process_status_lock.release()
[ "def", "ProcessAbort", "(", "self", ")", ":", "self", ".", "_process_status_lock", ".", "acquire", "(", ")", "try", ":", "self", ".", "_process_status", "=", "self", ".", "STATUS_ABORTED", "if", "self", ".", "_process", ":", "self", ".", "_process", ".", ...
https://github.com/spectacles/CodeComplice/blob/8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62/libs/process.py#L565-L574
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python-modules/twisted/twisted/web/iweb.py
python
IRequest.addCookie
(k, v, expires=None, domain=None, path=None, max_age=None, comment=None, secure=None)
Set an outgoing HTTP cookie. In general, you should consider using sessions instead of cookies, see L{twisted.web.server.Request.getSession} and the L{twisted.web.server.Session} class for details.
Set an outgoing HTTP cookie.
[ "Set", "an", "outgoing", "HTTP", "cookie", "." ]
def addCookie(k, v, expires=None, domain=None, path=None, max_age=None, comment=None, secure=None): """ Set an outgoing HTTP cookie. In general, you should consider using sessions instead of cookies, see L{twisted.web.server.Request.getSession} and the L{twisted.web.server.Session} class for details. """
[ "def", "addCookie", "(", "k", ",", "v", ",", "expires", "=", "None", ",", "domain", "=", "None", ",", "path", "=", "None", ",", "max_age", "=", "None", ",", "comment", "=", "None", ",", "secure", "=", "None", ")", ":" ]
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-modules/twisted/twisted/web/iweb.py#L221-L228
mesalock-linux/mesapy
ed546d59a21b36feb93e2309d5c6b75aa0ad95c9
lib-python/2.7/posixpath.py
python
lexists
(path)
return True
Test whether a path exists. Returns True for broken symbolic links
Test whether a path exists. Returns True for broken symbolic links
[ "Test", "whether", "a", "path", "exists", ".", "Returns", "True", "for", "broken", "symbolic", "links" ]
def lexists(path): """Test whether a path exists. Returns True for broken symbolic links""" try: os.lstat(path) except os.error: return False return True
[ "def", "lexists", "(", "path", ")", ":", "try", ":", "os", ".", "lstat", "(", "path", ")", "except", "os", ".", "error", ":", "return", "False", "return", "True" ]
https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/lib-python/2.7/posixpath.py#L142-L148
Suor/sublime-reform
605c240501d7ff9e38c38ec4a3a9c37d11561776
scopes.py
python
_expand_def
(view, adef)
[]
def _expand_def(view, adef): lang = source(view, adef.begin()) if lang == 'python': next_line = newline_f(view, adef.end()) adef = adef.cover(view.indented_region(next_line)) prefix = re_find(r'^[ \t]*', view.substr(view.line(adef.begin()))) while True: p = line_b_begin(view, adef.begin()) if p is None: break line_b_str = view.substr(view.line(p)) if line_b_str.startswith(prefix) and re_test(r'meta.(annotation|\w+.decorator)', scope_name(view, p + len(prefix))): adef = adef.cover(sublime.Region(p, p)) else: break return adef elif lang in ('js', 'cs', 'java'): # Extend to matching bracket start_bracket = view.find(r'{', adef.end(), sublime.LITERAL) end_bracket = find_closing_curly(view, start_bracket.b) adef = adef.cover(view.full_line(end_bracket)) # Match , or ; in case it's an expression if lang == 'js': punct = view.find(r'\s*[,;]', adef.end()) if punct and punct.a == adef.b: adef = adef.cover(punct) else: adef = adef.cover(view.line(adef.begin())) return adef else: # Heuristics based on indentation for all other languages next_line = newline_f(view, adef.end()) indented = view.indented_region(next_line) last_line = view.line(indented.end()) return adef.cover(last_line)
[ "def", "_expand_def", "(", "view", ",", "adef", ")", ":", "lang", "=", "source", "(", "view", ",", "adef", ".", "begin", "(", ")", ")", "if", "lang", "==", "'python'", ":", "next_line", "=", "newline_f", "(", "view", ",", "adef", ".", "end", "(", ...
https://github.com/Suor/sublime-reform/blob/605c240501d7ff9e38c38ec4a3a9c37d11561776/scopes.py#L313-L351
nccgroup/PMapper
a79e332ff8e93f4c55be2ca8fd8e9348a86acdc4
principalmapper/util/arns.py
python
get_partition
(arn: str)
return arn.split(':')[1]
Returns the partition from a string ARN.
Returns the partition from a string ARN.
[ "Returns", "the", "partition", "from", "a", "string", "ARN", "." ]
def get_partition(arn: str): """Returns the partition from a string ARN.""" return arn.split(':')[1]
[ "def", "get_partition", "(", "arn", ":", "str", ")", ":", "return", "arn", ".", "split", "(", "':'", ")", "[", "1", "]" ]
https://github.com/nccgroup/PMapper/blob/a79e332ff8e93f4c55be2ca8fd8e9348a86acdc4/principalmapper/util/arns.py#L27-L29
nvaccess/nvda
20d5a25dced4da34338197f0ef6546270ebca5d0
source/textInfos/__init__.py
python
TextInfo._get_obj
(self)
return self._obj()
The object containing the range of text being represented.
The object containing the range of text being represented.
[ "The", "object", "containing", "the", "range", "of", "text", "being", "represented", "." ]
def _get_obj(self) -> "NVDAObjects.NVDAObject": """The object containing the range of text being represented.""" return self._obj()
[ "def", "_get_obj", "(", "self", ")", "->", "\"NVDAObjects.NVDAObject\"", ":", "return", "self", ".", "_obj", "(", ")" ]
https://github.com/nvaccess/nvda/blob/20d5a25dced4da34338197f0ef6546270ebca5d0/source/textInfos/__init__.py#L342-L344
IntelPython/sdc
1ebf55c00ef38dfbd401a70b3945e352a5a38b87
examples/series/series_mul.py
python
series_mul
()
return out_series
[]
def series_mul(): s1 = pd.Series([1, 3, 100]) s2 = pd.Series([0, 1, 2]) out_series = s1.mul(s2) return out_series
[ "def", "series_mul", "(", ")", ":", "s1", "=", "pd", ".", "Series", "(", "[", "1", ",", "3", ",", "100", "]", ")", "s2", "=", "pd", ".", "Series", "(", "[", "0", ",", "1", ",", "2", "]", ")", "out_series", "=", "s1", ".", "mul", "(", "s2"...
https://github.com/IntelPython/sdc/blob/1ebf55c00ef38dfbd401a70b3945e352a5a38b87/examples/series/series_mul.py#L32-L37
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/packaging/specifiers.py
python
_IndividualSpecifier.__init__
(self, spec="", prereleases=None)
[]
def __init__(self, spec="", prereleases=None): match = self._regex.search(spec) if not match: raise InvalidSpecifier("Invalid specifier: '{0}'".format(spec)) self._spec = ( match.group("operator").strip(), match.group("version").strip(), ) # Store whether or not this Specifier should accept prereleases self._prereleases = prereleases
[ "def", "__init__", "(", "self", ",", "spec", "=", "\"\"", ",", "prereleases", "=", "None", ")", ":", "match", "=", "self", ".", "_regex", ".", "search", "(", "spec", ")", "if", "not", "match", ":", "raise", "InvalidSpecifier", "(", "\"Invalid specifier: ...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/packaging/specifiers.py#L82-L93