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
ofek/hatch
ff67fb61056a5b682951c9d2f6e9ef935d6181f6
backend/hatchling/build.py
python
get_requires_for_build_editable
(config_settings=None)
return builder.config.dependencies
https://www.python.org/dev/peps/pep-0660/#get-requires-for-build-editable
https://www.python.org/dev/peps/pep-0660/#get-requires-for-build-editable
[ "https", ":", "//", "www", ".", "python", ".", "org", "/", "dev", "/", "peps", "/", "pep", "-", "0660", "/", "#get", "-", "requires", "-", "for", "-", "build", "-", "editable" ]
def get_requires_for_build_editable(config_settings=None): """ https://www.python.org/dev/peps/pep-0660/#get-requires-for-build-editable """ from .builders.wheel import WheelBuilder builder = WheelBuilder(os.getcwd()) return builder.config.dependencies
[ "def", "get_requires_for_build_editable", "(", "config_settings", "=", "None", ")", ":", "from", ".", "builders", ".", "wheel", "import", "WheelBuilder", "builder", "=", "WheelBuilder", "(", "os", ".", "getcwd", "(", ")", ")", "return", "builder", ".", "config...
https://github.com/ofek/hatch/blob/ff67fb61056a5b682951c9d2f6e9ef935d6181f6/backend/hatchling/build.py#L44-L51
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-windows/x86/PIL/ImageMath.py
python
_Operand.__ror__
(self, other)
return self.apply("or", other, self)
[]
def __ror__(self, other): return self.apply("or", other, self)
[ "def", "__ror__", "(", "self", ",", "other", ")", ":", "return", "self", ".", "apply", "(", "\"or\"", ",", "other", ",", "self", ")" ]
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-windows/x86/PIL/ImageMath.py#L157-L158
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit /scripts/sshbackdoors/rpyc/utils/classic.py
python
MockClassicConnection.getmodule
(self, name)
return __import__(name, None, None, "*")
[]
def getmodule(self, name): return __import__(name, None, None, "*")
[ "def", "getmodule", "(", "self", ",", "name", ")", ":", "return", "__import__", "(", "name", ",", "None", ",", "None", ",", "\"*\"", ")" ]
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit /scripts/sshbackdoors/rpyc/utils/classic.py#L348-L349
PaddlePaddle/PaddleHub
107ee7e1a49d15e9c94da3956475d88a53fc165f
modules/image/classification/efficientnetb1_imagenet/module.py
python
BlockDecoder.encode
(blocks_args: list)
return block_strings
Encodes a list of BlockArgs to a list of strings. :param blocks_args: a list of BlockArgs namedtuples of block args :return: a list of strings, each string is a notation of block
Encodes a list of BlockArgs to a list of strings.
[ "Encodes", "a", "list", "of", "BlockArgs", "to", "a", "list", "of", "strings", "." ]
def encode(blocks_args: list): """ Encodes a list of BlockArgs to a list of strings. :param blocks_args: a list of BlockArgs namedtuples of block args :return: a list of strings, each string is a notation of block """ block_strings = [] for block in blocks_args: block_strings.append(BlockDecoder._encode_block_string(block)) return block_strings
[ "def", "encode", "(", "blocks_args", ":", "list", ")", ":", "block_strings", "=", "[", "]", "for", "block", "in", "blocks_args", ":", "block_strings", ".", "append", "(", "BlockDecoder", ".", "_encode_block_string", "(", "block", ")", ")", "return", "block_s...
https://github.com/PaddlePaddle/PaddleHub/blob/107ee7e1a49d15e9c94da3956475d88a53fc165f/modules/image/classification/efficientnetb1_imagenet/module.py#L190-L200
dit/dit
2853cb13110c5a5b2fa7ad792e238e2177013da2
dit/algorithms/distribution_optimizers.py
python
BaseDistOptimizer.construct_vector
(self, x)
return self._vpmf
Expand the `x` argument to the full pmf. Parameters ---------- x : np.ndarray An optimization vector. Returns ------- vpmf : np.array The full pmf as a vector.
Expand the `x` argument to the full pmf.
[ "Expand", "the", "x", "argument", "to", "the", "full", "pmf", "." ]
def construct_vector(self, x): """ Expand the `x` argument to the full pmf. Parameters ---------- x : np.ndarray An optimization vector. Returns ------- vpmf : np.array The full pmf as a vector. """ if self._free: self._vpmf[self._free] = x return self._vpmf
[ "def", "construct_vector", "(", "self", ",", "x", ")", ":", "if", "self", ".", "_free", ":", "self", ".", "_vpmf", "[", "self", ".", "_free", "]", "=", "x", "return", "self", ".", "_vpmf" ]
https://github.com/dit/dit/blob/2853cb13110c5a5b2fa7ad792e238e2177013da2/dit/algorithms/distribution_optimizers.py#L146-L162
CxxTest/cxxtest
48bf84df8a84794cbc3919281f7f95663db9217a
admin/virtualenv_1.7.py
python
create_environment
(home_dir, site_packages=False, clear=False, unzip_setuptools=False, use_distribute=False, prompt=None, search_dirs=None, never_download=False)
Creates a new environment in ``home_dir``. If ``site_packages`` is true, then the global ``site-packages/`` directory will be on the path. If ``clear`` is true (default False) then the environment will first be cleared.
Creates a new environment in ``home_dir``.
[ "Creates", "a", "new", "environment", "in", "home_dir", "." ]
def create_environment(home_dir, site_packages=False, clear=False, unzip_setuptools=False, use_distribute=False, prompt=None, search_dirs=None, never_download=False): """ Creates a new environment in ``home_dir``. If ``site_packages`` is true, then the global ``site-packages/`` directory will be on the path. If ``clear`` is true (default False) then the environment will first be cleared. """ home_dir, lib_dir, inc_dir, bin_dir = path_locations(home_dir) py_executable = os.path.abspath(install_python( home_dir, lib_dir, inc_dir, bin_dir, site_packages=site_packages, clear=clear)) install_distutils(home_dir) # use_distribute also is True if VIRTUALENV_DISTRIBUTE env var is set # we also check VIRTUALENV_USE_DISTRIBUTE for backwards compatibility if use_distribute or os.environ.get('VIRTUALENV_USE_DISTRIBUTE'): install_distribute(py_executable, unzip=unzip_setuptools, search_dirs=search_dirs, never_download=never_download) else: install_setuptools(py_executable, unzip=unzip_setuptools, search_dirs=search_dirs, never_download=never_download) install_pip(py_executable, search_dirs=search_dirs, never_download=never_download) install_activate(home_dir, bin_dir, prompt)
[ "def", "create_environment", "(", "home_dir", ",", "site_packages", "=", "False", ",", "clear", "=", "False", ",", "unzip_setuptools", "=", "False", ",", "use_distribute", "=", "False", ",", "prompt", "=", "None", ",", "search_dirs", "=", "None", ",", "never...
https://github.com/CxxTest/cxxtest/blob/48bf84df8a84794cbc3919281f7f95663db9217a/admin/virtualenv_1.7.py#L1013-L1044
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
sl4atools/fullscreenwrapper2/examples/fullscreenwrapper2demo/fullscreenwrapper2.py
python
View.remove_event
(self,event_name)
removes an event added previously by matching the event_name. Use this to temporarily disable a view's click event
removes an event added previously by matching the event_name. Use this to temporarily disable a view's click event
[ "removes", "an", "event", "added", "previously", "by", "matching", "the", "event_name", ".", "Use", "this", "to", "temporarily", "disable", "a", "view", "s", "click", "event" ]
def remove_event(self,event_name): ''' removes an event added previously by matching the event_name. Use this to temporarily disable a view's click event ''' self._events.pop(event_name)
[ "def", "remove_event", "(", "self", ",", "event_name", ")", ":", "self", ".", "_events", ".", "pop", "(", "event_name", ")" ]
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/sl4atools/fullscreenwrapper2/examples/fullscreenwrapper2demo/fullscreenwrapper2.py#L251-L255
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
build/sage_bootstrap/package.py
python
Package.patchlevel
(self)
return self.__patchlevel
Return the patchlevel OUTPUT: Integer. The patchlevel of the package. Excludes the "p" prefix.
Return the patchlevel
[ "Return", "the", "patchlevel" ]
def patchlevel(self): """ Return the patchlevel OUTPUT: Integer. The patchlevel of the package. Excludes the "p" prefix. """ return self.__patchlevel
[ "def", "patchlevel", "(", "self", ")", ":", "return", "self", ".", "__patchlevel" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/build/sage_bootstrap/package.py#L214-L223
gnome-terminator/terminator
ca335e45eb1a4ea7c22fe0d515bb270e9a0e12a1
terminatorlib/prefseditor.py
python
PrefsEditor.on_profileaddbutton_clicked
(self, _button)
Add a new profile to the list
Add a new profile to the list
[ "Add", "a", "new", "profile", "to", "the", "list" ]
def on_profileaddbutton_clicked(self, _button): """Add a new profile to the list""" self.addprofile(_('New Profile'), None)
[ "def", "on_profileaddbutton_clicked", "(", "self", ",", "_button", ")", ":", "self", ".", "addprofile", "(", "_", "(", "'New Profile'", ")", ",", "None", ")" ]
https://github.com/gnome-terminator/terminator/blob/ca335e45eb1a4ea7c22fe0d515bb270e9a0e12a1/terminatorlib/prefseditor.py#L1368-L1370
FrancescoCeruti/linux-show-player
39aba4674d9a2caa365687906640d192e2b47e0f
lisp/cues/cue.py
python
Cue.__interrupt__
(self, fade=False)
Implement the cue `interrupt` behavior. Long running task should block this function without releasing `_st_lock`. :param fade: True if a fade should be performed (when supported) :type fade: bool
Implement the cue `interrupt` behavior.
[ "Implement", "the", "cue", "interrupt", "behavior", "." ]
def __interrupt__(self, fade=False): """Implement the cue `interrupt` behavior. Long running task should block this function without releasing `_st_lock`. :param fade: True if a fade should be performed (when supported) :type fade: bool """
[ "def", "__interrupt__", "(", "self", ",", "fade", "=", "False", ")", ":" ]
https://github.com/FrancescoCeruti/linux-show-player/blob/39aba4674d9a2caa365687906640d192e2b47e0f/lisp/cues/cue.py#L441-L449
CGCookie/retopoflow
3d8b3a47d1d661f99ab0aeb21d31370bf15de35e
addon_common/common/ui_core.py
python
load_image_apng
(path)
return img
[]
def load_image_apng(path): im_apng = APNG.open(path) print('load_image_apng', path, im_apng, im_apng.frames, im_apng.num_plays) im,control = im_apng.frames[0] w,h = control.width,control.height img = [[r[i:i+4] for i in range(0,w*4,4)] for r in d] return img
[ "def", "load_image_apng", "(", "path", ")", ":", "im_apng", "=", "APNG", ".", "open", "(", "path", ")", "print", "(", "'load_image_apng'", ",", "path", ",", "im_apng", ",", "im_apng", ".", "frames", ",", "im_apng", ".", "num_plays", ")", "im", ",", "co...
https://github.com/CGCookie/retopoflow/blob/3d8b3a47d1d661f99ab0aeb21d31370bf15de35e/addon_common/common/ui_core.py#L227-L233
walkr/oi
d9d8491d0bc920e493d8f716d6078762b8b2c6d3
oi/core.py
python
Response._show
(self, res, err, prefix='', colored=False)
Show result or error
Show result or error
[ "Show", "result", "or", "error" ]
def _show(self, res, err, prefix='', colored=False): """ Show result or error """ if self.kind is 'local': what = res if not err else err print(what) return if self.kind is 'remote': if colored: red, green, reset = Fore.RED, Fore.GREEN, Fore.RESET else: red = green = reset = '' if err: what = prefix + red + 'remote err: {}'.format(err) + reset else: what = prefix + green + str(res) + reset print(what)
[ "def", "_show", "(", "self", ",", "res", ",", "err", ",", "prefix", "=", "''", ",", "colored", "=", "False", ")", ":", "if", "self", ".", "kind", "is", "'local'", ":", "what", "=", "res", "if", "not", "err", "else", "err", "print", "(", "what", ...
https://github.com/walkr/oi/blob/d9d8491d0bc920e493d8f716d6078762b8b2c6d3/oi/core.py#L210-L227
psychopy/psychopy
01b674094f38d0e0bd51c45a6f66f671d7041696
psychopy/app/coder/coder.py
python
CodeEditor.ShowCalltip
(self)
Show a calltip at the current caret position.
Show a calltip at the current caret position.
[ "Show", "a", "calltip", "at", "the", "current", "caret", "position", "." ]
def ShowCalltip(self): """Show a calltip at the current caret position.""" if _hasJedi and self.getFileType() == 'Python': self.coder.SetStatusText('Retrieving calltip, please wait ...', 0) thisObj = jedi.Script(self.getTextUptoCaret()) if hasattr(thisObj, 'get_signatures'): foundRefs = thisObj.get_signatures() elif hasattr(thisObj, 'call_signatures'): # call_signatures deprecated in jedi 0.16.0 (2020) foundRefs = thisObj.call_signatures() else: foundRefs = None self.coder.SetStatusText('', 0) if foundRefs: # enable text wrapping calltipText = foundRefs[0].to_string() if calltipText: calltipText = '\n '.join( textwrap.wrap(calltipText, 76)) # 80 cols after indent y, x = foundRefs[0].bracket_start callTipPos = self.XYToPosition(x, y) self.CallTipShow(callTipPos, calltipText)
[ "def", "ShowCalltip", "(", "self", ")", ":", "if", "_hasJedi", "and", "self", ".", "getFileType", "(", ")", "==", "'Python'", ":", "self", ".", "coder", ".", "SetStatusText", "(", "'Retrieving calltip, please wait ...'", ",", "0", ")", "thisObj", "=", "jedi"...
https://github.com/psychopy/psychopy/blob/01b674094f38d0e0bd51c45a6f66f671d7041696/psychopy/app/coder/coder.py#L886-L908
dropbox/PyHive
b21c507a24ed2f2b0cf15b0b6abb1c43f31d3ee0
TCLIService/TCLIService.py
python
GetDelegationToken_args.validate
(self)
return
[]
def validate(self): return
[ "def", "validate", "(", "self", ")", ":", "return" ]
https://github.com/dropbox/PyHive/blob/b21c507a24ed2f2b0cf15b0b6abb1c43f31d3ee0/TCLIService/TCLIService.py#L3551-L3552
Jajcus/pyxmpp2
59e5fd7c8837991ac265dc6aad23a6bd256768a7
pyxmpp2/sasl/scram.py
python
SCRAMOperations.Hi
(self, str_, salt, i)
return result
The Hi(str, salt, i) function.
The Hi(str, salt, i) function.
[ "The", "Hi", "(", "str", "salt", "i", ")", "function", "." ]
def Hi(self, str_, salt, i): """The Hi(str, salt, i) function.""" # pylint: disable=C0103 Uj = self.HMAC(str_, salt + b"\000\000\000\001") # U1 result = Uj for _ in range(2, i + 1): Uj = self.HMAC(str_, Uj) # Uj = HMAC(str, Uj-1) result = self.XOR(result, Uj) # ... XOR Uj-1 XOR Uj return result
[ "def", "Hi", "(", "self", ",", "str_", ",", "salt", ",", "i", ")", ":", "# pylint: disable=C0103", "Uj", "=", "self", ".", "HMAC", "(", "str_", ",", "salt", "+", "b\"\\000\\000\\000\\001\"", ")", "# U1", "result", "=", "Uj", "for", "_", "in", "range", ...
https://github.com/Jajcus/pyxmpp2/blob/59e5fd7c8837991ac265dc6aad23a6bd256768a7/pyxmpp2/sasl/scram.py#L126-L134
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/models/hubert/modeling_tf_hubert.py
python
_scatter_values_on_batch_indices
(values, batch_indices, output_shape)
return tf.scatter_nd(pair_indices, tf.reshape(values, [-1]), output_shape)
Scatter function as in PyTorch with indices in format (batch_dim, indixes)
Scatter function as in PyTorch with indices in format (batch_dim, indixes)
[ "Scatter", "function", "as", "in", "PyTorch", "with", "indices", "in", "format", "(", "batch_dim", "indixes", ")" ]
def _scatter_values_on_batch_indices(values, batch_indices, output_shape): """ Scatter function as in PyTorch with indices in format (batch_dim, indixes) """ indices_shape = shape_list(batch_indices) # broadcast batch dim to indices_shape broad_casted_batch_dims = tf.reshape( tf.broadcast_to(tf.expand_dims(tf.range(indices_shape[0]), axis=-1), indices_shape), [1, -1] ) # transform batch_indices to pair_indices pair_indices = tf.transpose(tf.concat([broad_casted_batch_dims, tf.reshape(batch_indices, [1, -1])], 0)) # scatter values to pair indices return tf.scatter_nd(pair_indices, tf.reshape(values, [-1]), output_shape)
[ "def", "_scatter_values_on_batch_indices", "(", "values", ",", "batch_indices", ",", "output_shape", ")", ":", "indices_shape", "=", "shape_list", "(", "batch_indices", ")", "# broadcast batch dim to indices_shape", "broad_casted_batch_dims", "=", "tf", ".", "reshape", "(...
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/models/hubert/modeling_tf_hubert.py#L181-L193
Q2h1Cg/CMS-Exploit-Framework
6bc54e33f316c81f97e16e10b12c7da589efbbd4
lib/threadpool.py
python
ThreadPool.putRequest
(self, request, block=True, timeout=None)
Put work request into work queue and save its id for later.
Put work request into work queue and save its id for later.
[ "Put", "work", "request", "into", "work", "queue", "and", "save", "its", "id", "for", "later", "." ]
def putRequest(self, request, block=True, timeout=None): """Put work request into work queue and save its id for later.""" assert isinstance(request, WorkRequest) # don't reuse old work requests assert not getattr(request, 'exception', None) self._requests_queue.put(request, block, timeout) self.workRequests[request.requestID] = request
[ "def", "putRequest", "(", "self", ",", "request", ",", "block", "=", "True", ",", "timeout", "=", "None", ")", ":", "assert", "isinstance", "(", "request", ",", "WorkRequest", ")", "# don't reuse old work requests", "assert", "not", "getattr", "(", "request", ...
https://github.com/Q2h1Cg/CMS-Exploit-Framework/blob/6bc54e33f316c81f97e16e10b12c7da589efbbd4/lib/threadpool.py#L290-L296
zim-desktop-wiki/zim-desktop-wiki
fe717d7ee64e5c06d90df90eb87758e5e72d25c5
zim/plugins/tableeditor.py
python
TableViewWidget.on_add_row
(self, action)
Context menu: Add a row
Context menu: Add a row
[ "Context", "menu", ":", "Add", "a", "row" ]
def on_add_row(self, action): ''' Context menu: Add a row ''' selection = self.treeview.get_selection() model, treeiter = selection.get_selected() if not treeiter: # no selected item self.selection_info() return # Set default sorting. model.set_sort_column_id(-1, Gtk.SortType.ASCENDING) row = len(self.treeview.get_columns()) * [''] path = model.insert_after(treeiter, row)
[ "def", "on_add_row", "(", "self", ",", "action", ")", ":", "selection", "=", "self", ".", "treeview", ".", "get_selection", "(", ")", "model", ",", "treeiter", "=", "selection", ".", "get_selected", "(", ")", "if", "not", "treeiter", ":", "# no selected it...
https://github.com/zim-desktop-wiki/zim-desktop-wiki/blob/fe717d7ee64e5c06d90df90eb87758e5e72d25c5/zim/plugins/tableeditor.py#L644-L656
eyaltrabelsi/pandas-log
5ea73d91856cee28096bdd0272dead2a639b137d
pandas_log/patched_logs_functions.py
python
log_nlargest
(output_df, input_df, n, columns, keep="first", **kwargs)
return logs, tips
[]
def log_nlargest(output_df, input_df, n, columns, keep="first", **kwargs): # todo maybe wrong logs = NLARGEST_MSG.format(n=n, cols=columns) tips = SHOULD_REDUCED_ROW_TIP if is_same_rows(input_df, output_df) else "" return logs, tips
[ "def", "log_nlargest", "(", "output_df", ",", "input_df", ",", "n", ",", "columns", ",", "keep", "=", "\"first\"", ",", "*", "*", "kwargs", ")", ":", "# todo maybe wrong", "logs", "=", "NLARGEST_MSG", ".", "format", "(", "n", "=", "n", ",", "cols", "="...
https://github.com/eyaltrabelsi/pandas-log/blob/5ea73d91856cee28096bdd0272dead2a639b137d/pandas_log/patched_logs_functions.py#L541-L545
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_vendored_deps/library/oc_clusterrole.py
python
Yedit.separator
(self, inc_sep)
setter method for separator
setter method for separator
[ "setter", "method", "for", "separator" ]
def separator(self, inc_sep): ''' setter method for separator ''' self._separator = inc_sep
[ "def", "separator", "(", "self", ",", "inc_sep", ")", ":", "self", ".", "_separator", "=", "inc_sep" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_vendored_deps/library/oc_clusterrole.py#L167-L169
happinesslz/TANet
2d4b2ab99b8e57c03671b0f1531eab7dca8f3c1f
second.pytorch_with_TANet/second/utils/bbox_plot.py
python
_pltcolor_to_qtcolor
(color)
return color_map[color]
[]
def _pltcolor_to_qtcolor(color): color_map = { 'r': QtCore.Qt.red, 'g': QtCore.Qt.green, 'b': QtCore.Qt.blue, 'k': QtCore.Qt.black, 'w': QtCore.Qt.white, 'y': QtCore.Qt.yellow, 'c': QtCore.Qt.cyan, 'm': QtCore.Qt.magenta, } return color_map[color]
[ "def", "_pltcolor_to_qtcolor", "(", "color", ")", ":", "color_map", "=", "{", "'r'", ":", "QtCore", ".", "Qt", ".", "red", ",", "'g'", ":", "QtCore", ".", "Qt", ".", "green", ",", "'b'", ":", "QtCore", ".", "Qt", ".", "blue", ",", "'k'", ":", "Qt...
https://github.com/happinesslz/TANet/blob/2d4b2ab99b8e57c03671b0f1531eab7dca8f3c1f/second.pytorch_with_TANet/second/utils/bbox_plot.py#L312-L323
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit - MAC OSX/tools/inject/thirdparty/bottle/bottle.py
python
BaseResponse.status_line
(self)
return self._status_line
The HTTP status line as a string (e.g. ``404 Not Found``).
The HTTP status line as a string (e.g. ``404 Not Found``).
[ "The", "HTTP", "status", "line", "as", "a", "string", "(", "e", ".", "g", ".", "404", "Not", "Found", ")", "." ]
def status_line(self): ''' The HTTP status line as a string (e.g. ``404 Not Found``).''' return self._status_line
[ "def", "status_line", "(", "self", ")", ":", "return", "self", ".", "_status_line" ]
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/tools/inject/thirdparty/bottle/bottle.py#L1315-L1317
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/states/file.py
python
_validate_str_list
(arg, encoding=None)
return ret
ensure ``arg`` is a list of strings
ensure ``arg`` is a list of strings
[ "ensure", "arg", "is", "a", "list", "of", "strings" ]
def _validate_str_list(arg, encoding=None): """ ensure ``arg`` is a list of strings """ if isinstance(arg, bytes): ret = [salt.utils.stringutils.to_unicode(arg, encoding=encoding)] elif isinstance(arg, str): ret = [arg] elif isinstance(arg, Iterable) and not isinstance(arg, Mapping): ret = [] for item in arg: if isinstance(item, str): ret.append(item) else: ret.append(str(item)) else: ret = [str(arg)] return ret
[ "def", "_validate_str_list", "(", "arg", ",", "encoding", "=", "None", ")", ":", "if", "isinstance", "(", "arg", ",", "bytes", ")", ":", "ret", "=", "[", "salt", ".", "utils", ".", "stringutils", ".", "to_unicode", "(", "arg", ",", "encoding", "=", "...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/states/file.py#L1162-L1179
Fuyukai/Kyoukai
44d47f4b0ece1c509fc5116275982df63ca09438
kyoukai/app.py
python
Kyoukai.process_request
(self, request: Request, parent_context: Context)
Processes a Request and returns a Response object. This is the main processing method of Kyoukai, and is meant to be used by one of the HTTP server backends, and not by client code. :param request: \ The :class:`werkzeug.wrappers.Request` object to process. A new :class:`~.HTTPRequestContext` will be provided to wrap this request inside of \ to client code. :param parent_context: \ The :class:`asphalt.core.Context` that is the parent context for this particular app. It will be used as the parent for the HTTPRequestContext. :return: A :class:`werkzeug.wrappers.Response` object that can be written to the client \ as a response.
Processes a Request and returns a Response object.
[ "Processes", "a", "Request", "and", "returns", "a", "Response", "object", "." ]
async def process_request(self, request: Request, parent_context: Context) -> Response: """ Processes a Request and returns a Response object. This is the main processing method of Kyoukai, and is meant to be used by one of the HTTP server backends, and not by client code. :param request: \ The :class:`werkzeug.wrappers.Request` object to process. A new :class:`~.HTTPRequestContext` will be provided to wrap this request inside of \ to client code. :param parent_context: \ The :class:`asphalt.core.Context` that is the parent context for this particular app. It will be used as the parent for the HTTPRequestContext. :return: A :class:`werkzeug.wrappers.Response` object that can be written to the client \ as a response. """ if not self.root.finalized: raise RuntimeError("App was not finalized") # Create a new HTTPRequestContext. ctx = self.context_class(parent_context, request) ctx.app = self async with ctx: # Call match on our Blueprint to find the request. try: matched, params, rule = self.root.match(request.environ) ctx.params = params ctx.rule = rule except NotFound as e: # No route matched. self.log_route(ctx.request, 404) logger.debug("Could not resolve route for {request.path}." .format(request=request)) return await self.handle_httpexception(ctx, e, request.environ) except MethodNotAllowed as e: # 405 method not allowed self.log_route(ctx.request, 405) logger.debug("Could not resolve valid method for " "{request.path} ({request.method})".format(request=request)) return await self.handle_httpexception(ctx, e, request.environ) except RequestRedirect as e: # slashes etc # user code is not allowed to handle this self.log_route(ctx.request, 307) e.code = 307 return e.get_response(request.environ) else: ctx.route_matched.dispatch(ctx=ctx) ctx.route = matched ctx.bp = ctx.route.bp result = None # Invoke the route. try: ctx.route_invoked.dispatch(ctx=ctx) # INTERCEPT if ctx.request.method.upper() == "OPTIONS": # NO USER CODE HERE HEHEHEHEHE # instead, we need to return an Allow: header # kyoukai autocalcs this result = Response(status=204) result.headers["Allow"] = ",".join(x for x in ctx.rule.methods if x != "OPTIONS") else: result = await matched.invoke(ctx, params=params) except BadRequestKeyError as e: logger.info("BadRequestKeyError: {}".format(' '.join(e.args)), exc_info=True) result = await self.handle_httpexception(ctx, e, request.environ) except HTTPException as e: fmtted = traceback.format_exception(type(e), e, e.__traceback__) logger.debug(''.join(fmtted)) logger.info( "Hit HTTPException ({}) inside function, delegating.".format(str(e)) ) result = await self.handle_httpexception(ctx, e, request.environ) except Exception as e: logger.exception("Unhandled exception in route function") new_e = InternalServerError() new_e.__cause__ = e result = await self.handle_httpexception(ctx, new_e, request.environ) else: ctx.route_completed.dispatch(ctx=ctx, result=result) finally: # result = wrap_response(result, self.response_class) if result: # edge cases self.log_route(ctx.request, result.status_code) # Update the Server header. result.headers["Server"] = version_format # list means wsgi response probably if not isinstance(result.response, (bytes, str, list)): result.set_data(str(result.response)) result.headers["X-Powered-By"] = version_format # Return the new Response. return result
[ "async", "def", "process_request", "(", "self", ",", "request", ":", "Request", ",", "parent_context", ":", "Context", ")", "->", "Response", ":", "if", "not", "self", ".", "root", ".", "finalized", ":", "raise", "RuntimeError", "(", "\"App was not finalized\"...
https://github.com/Fuyukai/Kyoukai/blob/44d47f4b0ece1c509fc5116275982df63ca09438/kyoukai/app.py#L245-L348
moonnejs/uiKLine
08646956bd1d729c88d5d2617bf0599eb3efb3d1
uiKLine.py
python
KLineWidget.plotVol
(self,redraw=False,xmin=0,xmax=-1)
重画成交量子图
重画成交量子图
[ "重画成交量子图" ]
def plotVol(self,redraw=False,xmin=0,xmax=-1): """重画成交量子图""" if self.initCompleted: self.volume.generatePicture(self.listVol[xmin:xmax],redraw)
[ "def", "plotVol", "(", "self", ",", "redraw", "=", "False", ",", "xmin", "=", "0", ",", "xmax", "=", "-", "1", ")", ":", "if", "self", ".", "initCompleted", ":", "self", ".", "volume", ".", "generatePicture", "(", "self", ".", "listVol", "[", "xmin...
https://github.com/moonnejs/uiKLine/blob/08646956bd1d729c88d5d2617bf0599eb3efb3d1/uiKLine.py#L446-L449
yujiali/gmmn
6cab7eb72dbe6c1893adb11f4c81f469663b0a25
eval_mmd_generative_model.py
python
linear_classifier_discrimination
(model, data, C_range=[1], verbose=True, samples=None)
return best_acc, best_classifier
Compute the logistic regression classification accuracy.
Compute the logistic regression classification accuracy.
[ "Compute", "the", "logistic", "regression", "classification", "accuracy", "." ]
def linear_classifier_discrimination(model, data, C_range=[1], verbose=True, samples=None): """ Compute the logistic regression classification accuracy. """ import sklearn.linear_model as lm n_examples = data.shape[0] if samples is None: gnp.seed_rand(8) samples = model.generate_samples(n_samples=n_examples).asarray() x = np.r_[data, samples] t = np.r_[np.zeros(n_examples, dtype=np.int), np.ones(samples.shape[0], dtype=np.int)] best_acc = 0 best_classifier = None for C in C_range: t_start = time.time() lr = lm.LogisticRegression(C=C, dual=False, random_state=8) lr.fit(x,t) acc = (lr.predict(x) == t).mean() if verbose: print 'C=%g acc=%.4f' % (C, acc), if acc > best_acc: best_acc = acc best_classifier = lr if verbose: print '*', else: if verbose: print ' ', if verbose: print 'time=%.2f' % (time.time() - t_start) return best_acc, best_classifier
[ "def", "linear_classifier_discrimination", "(", "model", ",", "data", ",", "C_range", "=", "[", "1", "]", ",", "verbose", "=", "True", ",", "samples", "=", "None", ")", ":", "import", "sklearn", ".", "linear_model", "as", "lm", "n_examples", "=", "data", ...
https://github.com/yujiali/gmmn/blob/6cab7eb72dbe6c1893adb11f4c81f469663b0a25/eval_mmd_generative_model.py#L30-L66
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/polys/modulargcd.py
python
_gf_gcd
(fp, gp, p)
return fp.mul_ground(dom.invert(fp.LC, p)).trunc_ground(p)
r""" Compute the GCD of two univariate polynomials in `\mathbb{Z}_p[x]`.
r""" Compute the GCD of two univariate polynomials in `\mathbb{Z}_p[x]`.
[ "r", "Compute", "the", "GCD", "of", "two", "univariate", "polynomials", "in", "\\", "mathbb", "{", "Z", "}", "_p", "[", "x", "]", "." ]
def _gf_gcd(fp, gp, p): r""" Compute the GCD of two univariate polynomials in `\mathbb{Z}_p[x]`. """ dom = fp.ring.domain while gp: rem = fp deg = gp.degree() lcinv = dom.invert(gp.LC, p) while True: degrem = rem.degree() if degrem < deg: break rem = (rem - gp.mul_monom((degrem - deg,)).mul_ground(lcinv * rem.LC)).trunc_ground(p) fp = gp gp = rem return fp.mul_ground(dom.invert(fp.LC, p)).trunc_ground(p)
[ "def", "_gf_gcd", "(", "fp", ",", "gp", ",", "p", ")", ":", "dom", "=", "fp", ".", "ring", ".", "domain", "while", "gp", ":", "rem", "=", "fp", "deg", "=", "gp", ".", "degree", "(", ")", "lcinv", "=", "dom", ".", "invert", "(", "gp", ".", "...
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/polys/modulargcd.py#L37-L57
celiao/tmdbsimple
2c046367866667102b78247db708c0ac275f805d
tmdbsimple/tv.py
python
Networks.info
(self, **kwargs)
return response
Get the details of a network. Args: None Returns: A dict respresentation of the JSON returned from the API.
Get the details of a network.
[ "Get", "the", "details", "of", "a", "network", "." ]
def info(self, **kwargs): """ Get the details of a network. Args: None Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_id_path('info') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
[ "def", "info", "(", "self", ",", "*", "*", "kwargs", ")", ":", "path", "=", "self", ".", "_get_id_path", "(", "'info'", ")", "response", "=", "self", ".", "_GET", "(", "path", ",", "kwargs", ")", "self", ".", "_set_attrs_to_values", "(", "response", ...
https://github.com/celiao/tmdbsimple/blob/2c046367866667102b78247db708c0ac275f805d/tmdbsimple/tv.py#L966-L980
rytilahti/python-miio
b6e53dd16fac77915426e7592e2528b78ef65190
miio/fan_miot.py
python
FanZA5.set_led_brightness
(self, brightness: int)
return self.set_property("light", brightness)
Set LED brightness.
Set LED brightness.
[ "Set", "LED", "brightness", "." ]
def set_led_brightness(self, brightness: int): """Set LED brightness.""" if brightness < 0 or brightness > 100: raise FanException("Invalid brightness: %s" % brightness) return self.set_property("light", brightness)
[ "def", "set_led_brightness", "(", "self", ",", "brightness", ":", "int", ")", ":", "if", "brightness", "<", "0", "or", "brightness", ">", "100", ":", "raise", "FanException", "(", "\"Invalid brightness: %s\"", "%", "brightness", ")", "return", "self", ".", "...
https://github.com/rytilahti/python-miio/blob/b6e53dd16fac77915426e7592e2528b78ef65190/miio/fan_miot.py#L798-L803
gevent/gevent
ae2cb5aeb2aea8987efcb90a4c50ca4e1ee12c31
src/gevent/greenlet.py
python
Greenlet._run
(self)
return
Subclasses may override this method to take any number of arguments and keyword arguments. .. versionadded:: 1.1a3 Previously, if no callable object was passed to the constructor, the spawned greenlet would later fail with an AttributeError.
Subclasses may override this method to take any number of arguments and keyword arguments.
[ "Subclasses", "may", "override", "this", "method", "to", "take", "any", "number", "of", "arguments", "and", "keyword", "arguments", "." ]
def _run(self): """ Subclasses may override this method to take any number of arguments and keyword arguments. .. versionadded:: 1.1a3 Previously, if no callable object was passed to the constructor, the spawned greenlet would later fail with an AttributeError. """ # We usually override this in __init__ # pylint: disable=method-hidden return
[ "def", "_run", "(", "self", ")", ":", "# We usually override this in __init__", "# pylint: disable=method-hidden", "return" ]
https://github.com/gevent/gevent/blob/ae2cb5aeb2aea8987efcb90a4c50ca4e1ee12c31/src/gevent/greenlet.py#L926-L938
Netflix/repokid
376aa82ed31fe66ac4b1aecc3c22b0fc4fcfc0ea
repokid/utils/dynamo.py
python
get_all_role_ids_for_account
( account_number: str, dynamo_table: Optional[Table] = None )
return role_ids
Get a set of all role IDs in a given account by querying the Dynamo secondary index 'account' Args: account_number (string) dynamo_table (Table) Returns: list: role ids in given account
Get a set of all role IDs in a given account by querying the Dynamo secondary index 'account'
[ "Get", "a", "set", "of", "all", "role", "IDs", "in", "a", "given", "account", "by", "querying", "the", "Dynamo", "secondary", "index", "account" ]
def get_all_role_ids_for_account( account_number: str, dynamo_table: Optional[Table] = None ) -> Set[str]: """ Get a set of all role IDs in a given account by querying the Dynamo secondary index 'account' Args: account_number (string) dynamo_table (Table) Returns: list: role ids in given account """ table = dynamo_table or ROLE_TABLE role_ids: Set[str] = set() results = table.query( IndexName="Account", KeyConditionExpression=Key("Account").eq(account_number), ) items = results.get("Items") if not items: return set() role_ids.update([str(return_dict["RoleId"]) for return_dict in items]) while "LastEvaluatedKey" in results: results = table.query( IndexName="Account", KeyConditionExpression="Account = :act", ExpressionAttributeValues={":act": account_number}, ExclusiveStartKey=results.get("LastEvaluatedKey") or {}, ) items = results.get("Items") if not items: continue role_ids.update([str(return_dict["RoleId"]) for return_dict in items]) return role_ids
[ "def", "get_all_role_ids_for_account", "(", "account_number", ":", "str", ",", "dynamo_table", ":", "Optional", "[", "Table", "]", "=", "None", ")", "->", "Set", "[", "str", "]", ":", "table", "=", "dynamo_table", "or", "ROLE_TABLE", "role_ids", ":", "Set", ...
https://github.com/Netflix/repokid/blob/376aa82ed31fe66ac4b1aecc3c22b0fc4fcfc0ea/repokid/utils/dynamo.py#L339-L376
sympy/sympy
d822fcba181155b85ff2b29fe525adbafb22b448
sympy/geometry/plane.py
python
Plane.perpendicular_plane
(self, *pts)
return Plane(p1, p2, p3)
Return a perpendicular passing through the given points. If the direction ratio between the points is the same as the Plane's normal vector then, to select from the infinite number of possible planes, a third point will be chosen on the z-axis (or the y-axis if the normal vector is already parallel to the z-axis). If less than two points are given they will be supplied as follows: if no point is given then pt1 will be self.p1; if a second point is not given it will be a point through pt1 on a line parallel to the z-axis (if the normal is not already the z-axis, otherwise on the line parallel to the y-axis). Parameters ========== pts: 0, 1 or 2 Point3D Returns ======= Plane Examples ======== >>> from sympy import Plane, Point3D >>> a, b = Point3D(0, 0, 0), Point3D(0, 1, 0) >>> Z = (0, 0, 1) >>> p = Plane(a, normal_vector=Z) >>> p.perpendicular_plane(a, b) Plane(Point3D(0, 0, 0), (1, 0, 0))
Return a perpendicular passing through the given points. If the direction ratio between the points is the same as the Plane's normal vector then, to select from the infinite number of possible planes, a third point will be chosen on the z-axis (or the y-axis if the normal vector is already parallel to the z-axis). If less than two points are given they will be supplied as follows: if no point is given then pt1 will be self.p1; if a second point is not given it will be a point through pt1 on a line parallel to the z-axis (if the normal is not already the z-axis, otherwise on the line parallel to the y-axis).
[ "Return", "a", "perpendicular", "passing", "through", "the", "given", "points", ".", "If", "the", "direction", "ratio", "between", "the", "points", "is", "the", "same", "as", "the", "Plane", "s", "normal", "vector", "then", "to", "select", "from", "the", "...
def perpendicular_plane(self, *pts): """ Return a perpendicular passing through the given points. If the direction ratio between the points is the same as the Plane's normal vector then, to select from the infinite number of possible planes, a third point will be chosen on the z-axis (or the y-axis if the normal vector is already parallel to the z-axis). If less than two points are given they will be supplied as follows: if no point is given then pt1 will be self.p1; if a second point is not given it will be a point through pt1 on a line parallel to the z-axis (if the normal is not already the z-axis, otherwise on the line parallel to the y-axis). Parameters ========== pts: 0, 1 or 2 Point3D Returns ======= Plane Examples ======== >>> from sympy import Plane, Point3D >>> a, b = Point3D(0, 0, 0), Point3D(0, 1, 0) >>> Z = (0, 0, 1) >>> p = Plane(a, normal_vector=Z) >>> p.perpendicular_plane(a, b) Plane(Point3D(0, 0, 0), (1, 0, 0)) """ if len(pts) > 2: raise ValueError('No more than 2 pts should be provided.') pts = list(pts) if len(pts) == 0: pts.append(self.p1) if len(pts) == 1: x, y, z = self.normal_vector if x == y == 0: dir = (0, 1, 0) else: dir = (0, 0, 1) pts.append(pts[0] + Point3D(*dir)) p1, p2 = [Point(i, dim=3) for i in pts] l = Line3D(p1, p2) n = Line3D(p1, direction_ratio=self.normal_vector) if l in n: # XXX should an error be raised instead? # there are infinitely many perpendicular planes; x, y, z = self.normal_vector if x == y == 0: # the z axis is the normal so pick a pt on the y-axis p3 = Point3D(0, 1, 0) # case 1 else: # else pick a pt on the z axis p3 = Point3D(0, 0, 1) # case 2 # in case that point is already given, move it a bit if p3 in l: p3 *= 2 # case 3 else: p3 = p1 + Point3D(*self.normal_vector) # case 4 return Plane(p1, p2, p3)
[ "def", "perpendicular_plane", "(", "self", ",", "*", "pts", ")", ":", "if", "len", "(", "pts", ")", ">", "2", ":", "raise", "ValueError", "(", "'No more than 2 pts should be provided.'", ")", "pts", "=", "list", "(", "pts", ")", "if", "len", "(", "pts", ...
https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/geometry/plane.py#L637-L701
khanhnamle1994/natural-language-processing
01d450d5ac002b0156ef4cf93a07cb508c1bcdc5
assignment1/.env/lib/python2.7/site-packages/IPython/core/ultratb.py
python
TBTools.stb2text
(self, stb)
return '\n'.join(stb)
Convert a structured traceback (a list) to a string.
Convert a structured traceback (a list) to a string.
[ "Convert", "a", "structured", "traceback", "(", "a", "list", ")", "to", "a", "string", "." ]
def stb2text(self, stb): """Convert a structured traceback (a list) to a string.""" return '\n'.join(stb)
[ "def", "stb2text", "(", "self", ",", "stb", ")", ":", "return", "'\\n'", ".", "join", "(", "stb", ")" ]
https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/IPython/core/ultratb.py#L414-L416
accelero-cloud/appkernel
1be8707f535e9f8ad78ef944f2631b15ce03e8f3
appkernel/reflection.py
python
is_dictionary_subclass
(obj)
return (hasattr(obj, '__class__') and issubclass(obj.__class__, dict) and not is_dictionary(obj))
Returns True if *obj* is a subclass of the dict type. *obj* must be a subclass and not the actual builtin dict. >>> class Temp(dict): pass >>> is_dictionary_subclass(Temp()) True
Returns True if *obj* is a subclass of the dict type. *obj* must be a subclass and not the actual builtin dict. >>> class Temp(dict): pass >>> is_dictionary_subclass(Temp()) True
[ "Returns", "True", "if", "*", "obj", "*", "is", "a", "subclass", "of", "the", "dict", "type", ".", "*", "obj", "*", "must", "be", "a", "subclass", "and", "not", "the", "actual", "builtin", "dict", ".", ">>>", "class", "Temp", "(", "dict", ")", ":",...
def is_dictionary_subclass(obj): """Returns True if *obj* is a subclass of the dict type. *obj* must be a subclass and not the actual builtin dict. >>> class Temp(dict): pass >>> is_dictionary_subclass(Temp()) True """ return (hasattr(obj, '__class__') and issubclass(obj.__class__, dict) and not is_dictionary(obj))
[ "def", "is_dictionary_subclass", "(", "obj", ")", ":", "return", "(", "hasattr", "(", "obj", ",", "'__class__'", ")", "and", "issubclass", "(", "obj", ".", "__class__", ",", "dict", ")", "and", "not", "is_dictionary", "(", "obj", ")", ")" ]
https://github.com/accelero-cloud/appkernel/blob/1be8707f535e9f8ad78ef944f2631b15ce03e8f3/appkernel/reflection.py#L148-L156
catalyst-team/catalyst
678dc06eda1848242df010b7f34adb572def2598
catalyst/data/ddp_loader.py
python
BatchSamplerShard.__len__
(self)
return length if self.drop_last else length + 1
Docs.
Docs.
[ "Docs", "." ]
def __len__(self): """Docs.""" if len(self.batch_sampler) % self.num_processes == 0: return len(self.batch_sampler) // self.num_processes length = len(self.batch_sampler) // self.num_processes return length if self.drop_last else length + 1
[ "def", "__len__", "(", "self", ")", ":", "if", "len", "(", "self", ".", "batch_sampler", ")", "%", "self", ".", "num_processes", "==", "0", ":", "return", "len", "(", "self", ".", "batch_sampler", ")", "//", "self", ".", "num_processes", "length", "=",...
https://github.com/catalyst-team/catalyst/blob/678dc06eda1848242df010b7f34adb572def2598/catalyst/data/ddp_loader.py#L56-L61
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/django/core/management/commands/flush.py
python
Command.handle
(self, **options)
[]
def handle(self, **options): database = options['database'] connection = connections[database] verbosity = options['verbosity'] interactive = options['interactive'] # The following are stealth options used by Django's internals. reset_sequences = options.get('reset_sequences', True) allow_cascade = options.get('allow_cascade', False) inhibit_post_migrate = options.get('inhibit_post_migrate', False) self.style = no_style() # Import the 'management' module within each installed app, to register # dispatcher events. for app_config in apps.get_app_configs(): try: import_module('.management', app_config.name) except ImportError: pass sql_list = sql_flush(self.style, connection, only_django=True, reset_sequences=reset_sequences, allow_cascade=allow_cascade) if interactive: confirm = input("""You have requested a flush of the database. This will IRREVERSIBLY DESTROY all data currently in the %r database, and return each table to an empty state. Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: """ % connection.settings_dict['NAME']) else: confirm = 'yes' if confirm == 'yes': try: with transaction.atomic(using=database, savepoint=connection.features.can_rollback_ddl): with connection.cursor() as cursor: for sql in sql_list: cursor.execute(sql) except Exception as e: new_msg = ( "Database %s couldn't be flushed. Possible reasons:\n" " * The database isn't running or isn't configured correctly.\n" " * At least one of the expected database tables doesn't exist.\n" " * The SQL was invalid.\n" "Hint: Look at the output of 'django-admin sqlflush'. " "That's the SQL this command wasn't able to run.\n" "The full error: %s") % (connection.settings_dict['NAME'], e) six.reraise(CommandError, CommandError(new_msg), sys.exc_info()[2]) # Empty sql_list may signify an empty database and post_migrate would then crash if sql_list and not inhibit_post_migrate: # Emit the post migrate signal. This allows individual applications to # respond as if the database had been migrated from scratch. emit_post_migrate_signal(verbosity, interactive, database) else: self.stdout.write("Flush cancelled.\n")
[ "def", "handle", "(", "self", ",", "*", "*", "options", ")", ":", "database", "=", "options", "[", "'database'", "]", "connection", "=", "connections", "[", "database", "]", "verbosity", "=", "options", "[", "'verbosity'", "]", "interactive", "=", "options...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/core/management/commands/flush.py#L32-L90
CANToolz/CANToolz
82d330b835b90598f7289cdfe083f7f66309f915
cantoolz/ui/cli.py
python
CANToolzCLI.do_edit
(self, arg)
Edit parameters for a module. edit <module id> <configuration dictionary> Example: edit 0 {'action': 'write', 'pipe': 'Cabin'}
Edit parameters for a module.
[ "Edit", "parameters", "for", "a", "module", "." ]
def do_edit(self, arg): """Edit parameters for a module. edit <module id> <configuration dictionary> Example: edit 0 {'action': 'write', 'pipe': 'Cabin'} """ match = re.match(r'(\d+)\s+(.+)', arg, re.IGNORECASE) if not match: print('Missing/invalid required parameters. See: help edit') return module = int(match.group(1).strip()) _paramz = match.group(2).strip() try: paramz = ast.literal_eval(_paramz) self.can_engine.edit_module(module, paramz) except Exception: print('Error when edit the module with {}:'.format(arg)) traceback.print_exc() return print('Edited module: {}'.format(self.can_engine.actions[module][0])) print('Added params: {}'.format(self.can_engine.actions[module][2])) active = self.can_engine.actions[module][1].is_active if active: self.can_engine.actions[module][1].do_activate(0, 0) if self.can_engine.status_loop: self.can_engine.actions[module][1].do_stop(paramz) self.can_engine.actions[module][1].do_start(paramz) if active: self.can_engine.actions[module][1].do_activate(0, 1)
[ "def", "do_edit", "(", "self", ",", "arg", ")", ":", "match", "=", "re", ".", "match", "(", "r'(\\d+)\\s+(.+)'", ",", "arg", ",", "re", ".", "IGNORECASE", ")", "if", "not", "match", ":", "print", "(", "'Missing/invalid required parameters. See: help edit'", ...
https://github.com/CANToolz/CANToolz/blob/82d330b835b90598f7289cdfe083f7f66309f915/cantoolz/ui/cli.py#L49-L80
dayorbyte/MongoAlchemy
e64ef0c87feff385637459707fe6090bd789e116
mongoalchemy/query.py
python
Query.ascending
(self, qfield)
return self.__sort(qfield, ASCENDING)
Sort the result based on ``qfield`` in ascending order. These calls can be chained to sort by multiple fields. :param qfield: Instance of :class:``mongoalchemy.query.QueryField`` \ specifying which field to sort by.
Sort the result based on ``qfield`` in ascending order. These calls can be chained to sort by multiple fields.
[ "Sort", "the", "result", "based", "on", "qfield", "in", "ascending", "order", ".", "These", "calls", "can", "be", "chained", "to", "sort", "by", "multiple", "fields", "." ]
def ascending(self, qfield): ''' Sort the result based on ``qfield`` in ascending order. These calls can be chained to sort by multiple fields. :param qfield: Instance of :class:``mongoalchemy.query.QueryField`` \ specifying which field to sort by. ''' return self.__sort(qfield, ASCENDING)
[ "def", "ascending", "(", "self", ",", "qfield", ")", ":", "return", "self", ".", "__sort", "(", "qfield", ",", "ASCENDING", ")" ]
https://github.com/dayorbyte/MongoAlchemy/blob/e64ef0c87feff385637459707fe6090bd789e116/mongoalchemy/query.py#L259-L266
GoogleCloudPlatform/PerfKitBenchmarker
6e3412d7d5e414b8ca30ed5eaf970cef1d919a67
perfkitbenchmarker/background_tasks.py
python
_RunParallelTasks
(target_arg_tuples, max_concurrency, get_task_manager, parallel_exception_class, post_task_delay=0)
return results
Executes function calls concurrently in separate threads or processes. Args: target_arg_tuples: list of (target, args, kwargs) tuples. Each tuple contains the function to call and the arguments to pass it. max_concurrency: int or None. The maximum number of concurrent new threads or processes. get_task_manager: Callable that accepts an int max_concurrency arg and returns a _TaskManager. parallel_exception_class: Type of exception to raise upon an exception in one of the called functions. post_task_delay: Delay in seconds between parallel task invocations. Returns: list of function return values in the order corresponding to the order of target_arg_tuples. Raises: parallel_exception_class: When an exception occurred in any of the called functions.
Executes function calls concurrently in separate threads or processes.
[ "Executes", "function", "calls", "concurrently", "in", "separate", "threads", "or", "processes", "." ]
def _RunParallelTasks(target_arg_tuples, max_concurrency, get_task_manager, parallel_exception_class, post_task_delay=0): """Executes function calls concurrently in separate threads or processes. Args: target_arg_tuples: list of (target, args, kwargs) tuples. Each tuple contains the function to call and the arguments to pass it. max_concurrency: int or None. The maximum number of concurrent new threads or processes. get_task_manager: Callable that accepts an int max_concurrency arg and returns a _TaskManager. parallel_exception_class: Type of exception to raise upon an exception in one of the called functions. post_task_delay: Delay in seconds between parallel task invocations. Returns: list of function return values in the order corresponding to the order of target_arg_tuples. Raises: parallel_exception_class: When an exception occurred in any of the called functions. """ thread_context = _BackgroundTaskThreadContext() max_concurrency = min(max_concurrency, len(target_arg_tuples)) error_strings = [] started_task_count = 0 active_task_count = 0 with get_task_manager(max_concurrency) as task_manager: try: while started_task_count < len(target_arg_tuples) or active_task_count: if (started_task_count < len(target_arg_tuples) and active_task_count < max_concurrency): # Start a new task. target, args, kwargs = target_arg_tuples[started_task_count] task_manager.StartTask(target, args, kwargs, thread_context) started_task_count += 1 active_task_count += 1 if post_task_delay: time.sleep(post_task_delay) continue # Wait for a task to complete. task_id = task_manager.AwaitAnyTask() active_task_count -= 1 # If the task failed, it may still be a long time until all remaining # tasks complete. Log the failure immediately before continuing to wait # for other tasks. stacktrace = task_manager.tasks[task_id].traceback if stacktrace: msg = ('Exception occurred while calling {0}:{1}{2}'.format( _GetCallString(target_arg_tuples[task_id]), os.linesep, stacktrace)) logging.error(msg) error_strings.append(msg) except KeyboardInterrupt: logging.error( 'Received KeyboardInterrupt while executing parallel tasks. Waiting ' 'for %s tasks to clean up.', active_task_count) task_manager.HandleKeyboardInterrupt() raise if error_strings: # TODO(skschneider): Combine errors.VmUtil.ThreadException and # errors.VmUtil.CalledProcessException so this can be a single exception # type. raise parallel_exception_class( 'The following exceptions occurred during parallel execution:' '{0}{1}'.format(os.linesep, os.linesep.join(error_strings))) results = [task.return_value for task in task_manager.tasks] assert len(target_arg_tuples) == len(results), (target_arg_tuples, results) return results
[ "def", "_RunParallelTasks", "(", "target_arg_tuples", ",", "max_concurrency", ",", "get_task_manager", ",", "parallel_exception_class", ",", "post_task_delay", "=", "0", ")", ":", "thread_context", "=", "_BackgroundTaskThreadContext", "(", ")", "max_concurrency", "=", "...
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/6e3412d7d5e414b8ca30ed5eaf970cef1d919a67/perfkitbenchmarker/background_tasks.py#L489-L561
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/GoogleCloudTranslate/Integrations/GoogleCloudTranslate/GoogleCloudTranslate.py
python
translate_text
(client, args)
return ( readable_output, outputs, result # raw response - the original response )
Translates text Args: client (Client): instance of the Client class args (dict): dictionary of arguments. The argument text is the text to be translated, target is the ISO 2 letter code of the target language (default: en), source is the ISO 2 letter code of the source language (default: auto detect) Returns: The list of supported languages readable_output (str): This will be presented in the war room - should be in markdown syntax - human readable outputs (dict): Dictionary/JSON - saved in the incident context in order to be used as inputs for other tasks in the playbook raw_response (dict): Used for debugging/troubleshooting purposes - will be shown only if the command executed with raw-response=true
Translates text
[ "Translates", "text" ]
def translate_text(client, args): """Translates text Args: client (Client): instance of the Client class args (dict): dictionary of arguments. The argument text is the text to be translated, target is the ISO 2 letter code of the target language (default: en), source is the ISO 2 letter code of the source language (default: auto detect) Returns: The list of supported languages readable_output (str): This will be presented in the war room - should be in markdown syntax - human readable outputs (dict): Dictionary/JSON - saved in the incident context in order to be used as inputs for other tasks in the playbook raw_response (dict): Used for debugging/troubleshooting purposes - will be shown only if the command executed with raw-response=true """ text = args.get('text', '') target = args.get('target', 'en') source = args.get('source', None) result = client.translate_text( text, target, source=source ) readable_output = 'Translation: {}\nSource Language Detected: {}'.format( result['translated_text'], result['detected_language_code'] ) id_ = hashlib.md5(f'{target}-{source}-{text}'.encode('utf-8')).hexdigest() outputs = { 'GoogleCloudTranslate.TranslateText(val.ID && val.ID==obj.ID)': { 'ID': id_, 'text': text, 'translated_text': result['translated_text'], 'source_language_code': source, 'detected_language_code': result['detected_language_code'], 'target_language_code': target } } return ( readable_output, outputs, result # raw response - the original response )
[ "def", "translate_text", "(", "client", ",", "args", ")", ":", "text", "=", "args", ".", "get", "(", "'text'", ",", "''", ")", "target", "=", "args", ".", "get", "(", "'target'", ",", "'en'", ")", "source", "=", "args", ".", "get", "(", "'source'",...
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/GoogleCloudTranslate/Integrations/GoogleCloudTranslate/GoogleCloudTranslate.py#L151-L202
mesonbuild/meson
a22d0f9a0a787df70ce79b05d0c45de90a970048
mesonbuild/linkers/linkers.py
python
SolarisDynamicLinker.get_link_whole_for
(self, args: T.List[str])
return self._apply_prefix('--whole-archive') + args + self._apply_prefix('--no-whole-archive')
[]
def get_link_whole_for(self, args: T.List[str]) -> T.List[str]: if not args: return args return self._apply_prefix('--whole-archive') + args + self._apply_prefix('--no-whole-archive')
[ "def", "get_link_whole_for", "(", "self", ",", "args", ":", "T", ".", "List", "[", "str", "]", ")", "->", "T", ".", "List", "[", "str", "]", ":", "if", "not", "args", ":", "return", "args", "return", "self", ".", "_apply_prefix", "(", "'--whole-archi...
https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/mesonbuild/linkers/linkers.py#L1292-L1295
eerimoq/asn1tools
30eb88e287cc1616903858aa96ee8791a4d7bf1c
asn1tools/codecs/__init__.py
python
generalized_time_from_datetime
(date)
return string
Convert given ``datetime.datetime`` object `date` to an ASN.1 generalized time string.
Convert given ``datetime.datetime`` object `date` to an ASN.1 generalized time string.
[ "Convert", "given", "datetime", ".", "datetime", "object", "date", "to", "an", "ASN", ".", "1", "generalized", "time", "string", "." ]
def generalized_time_from_datetime(date): """Convert given ``datetime.datetime`` object `date` to an ASN.1 generalized time string. """ if date.second == 0: if date.microsecond > 0: string = date.strftime('%Y%m%d%H%M.%f').rstrip('0') else: string = date.strftime('%Y%m%d%H%M') else: if date.microsecond > 0: string = date.strftime('%Y%m%d%H%M%S.%f').rstrip('0') else: string = date.strftime('%Y%m%d%H%M%S') if date.tzinfo is not None: if date.utcoffset(): string += date.strftime('%z') else: string += 'Z' return string
[ "def", "generalized_time_from_datetime", "(", "date", ")", ":", "if", "date", ".", "second", "==", "0", ":", "if", "date", ".", "microsecond", ">", "0", ":", "string", "=", "date", ".", "strftime", "(", "'%Y%m%d%H%M.%f'", ")", ".", "rstrip", "(", "'0'", ...
https://github.com/eerimoq/asn1tools/blob/30eb88e287cc1616903858aa96ee8791a4d7bf1c/asn1tools/codecs/__init__.py#L304-L327
shiyanlou/louplus-python
4c61697259e286e3d9116c3299f170d019ba3767
taobei/challenge-07/tbweb/handlers/user.py
python
avatar
()
return render_template('user/avatar.html', form=form)
设置头像
设置头像
[ "设置头像" ]
def avatar(): """设置头像 """ form = AvatarForm() if form.validate_on_submit(): # 上传头像文件到文件服务,获得一个文件 ID f = form.avatar.data resp = TbFile(current_app).post_json('/files', files={ 'file': (secure_filename(f.filename), f, f.mimetype), }, check_code=False) if resp['code'] != 0: flash(resp['message'], 'danger') return render_template('user/avatar.html', form=form) # 将前面获得的文件 ID 通过用户服务接口更新到用户资料里 resp = TbUser(current_app).post_json( '/users/{}'.format(current_user.get_id()), json={ 'avatar': resp['data']['id'], }, check_code=False) if resp['code'] != 0: flash(resp['message'], 'danger') return render_template('user/avatar.html', form=form) return redirect(url_for('common.index')) return render_template('user/avatar.html', form=form)
[ "def", "avatar", "(", ")", ":", "form", "=", "AvatarForm", "(", ")", "if", "form", ".", "validate_on_submit", "(", ")", ":", "# 上传头像文件到文件服务,获得一个文件 ID", "f", "=", "form", ".", "avatar", ".", "data", "resp", "=", "TbFile", "(", "current_app", ")", ".", "...
https://github.com/shiyanlou/louplus-python/blob/4c61697259e286e3d9116c3299f170d019ba3767/taobei/challenge-07/tbweb/handlers/user.py#L91-L117
jindongwang/transferlearning
74a8914eed52c6f0759f39c0239d7e8b5baa6245
code/traditional/GFK/GFK.py
python
GFK.principal_angles
(self, Ps, Pt)
return np.sum(thetas_squared)
Compute the principal angles between source (:math:`P_s`) and target (:math:`P_t`) subspaces in a Grassman which is defined as the following: :math:`d^{2}(P_s, P_t) = \sum_{i}( \theta_i^{2} )`,
Compute the principal angles between source (:math:`P_s`) and target (:math:`P_t`) subspaces in a Grassman which is defined as the following:
[ "Compute", "the", "principal", "angles", "between", "source", "(", ":", "math", ":", "P_s", ")", "and", "target", "(", ":", "math", ":", "P_t", ")", "subspaces", "in", "a", "Grassman", "which", "is", "defined", "as", "the", "following", ":" ]
def principal_angles(self, Ps, Pt): """ Compute the principal angles between source (:math:`P_s`) and target (:math:`P_t`) subspaces in a Grassman which is defined as the following: :math:`d^{2}(P_s, P_t) = \sum_{i}( \theta_i^{2} )`, """ # S = cos(theta_1, theta_2, ..., theta_n) _, S, _ = np.linalg.svd(np.dot(Ps.T, Pt)) thetas_squared = np.arccos(S) ** 2 return np.sum(thetas_squared)
[ "def", "principal_angles", "(", "self", ",", "Ps", ",", "Pt", ")", ":", "# S = cos(theta_1, theta_2, ..., theta_n)", "_", ",", "S", ",", "_", "=", "np", ".", "linalg", ".", "svd", "(", "np", ".", "dot", "(", "Ps", ".", "T", ",", "Pt", ")", ")", "th...
https://github.com/jindongwang/transferlearning/blob/74a8914eed52c6f0759f39c0239d7e8b5baa6245/code/traditional/GFK/GFK.py#L113-L124
timonwong/OmniMarkupPreviewer
21921ac7a99d2b5924a2219b33679a5b53621392
OmniMarkupLib/Renderers/libs/python3/docutils/utils/math/math2html.py
python
NumberGenerator.getlevel
(self, type)
return level - DocumentParameters.startinglevel
Get the level that corresponds to a layout type.
Get the level that corresponds to a layout type.
[ "Get", "the", "level", "that", "corresponds", "to", "a", "layout", "type", "." ]
def getlevel(self, type): "Get the level that corresponds to a layout type." if self.isunique(type): return 0 if not self.isinordered(type): Trace.error('Unknown layout type ' + type) return 0 type = self.deasterisk(type).lower() level = self.orderedlayouts.index(type) + 1 return level - DocumentParameters.startinglevel
[ "def", "getlevel", "(", "self", ",", "type", ")", ":", "if", "self", ".", "isunique", "(", "type", ")", ":", "return", "0", "if", "not", "self", ".", "isinordered", "(", "type", ")", ":", "Trace", ".", "error", "(", "'Unknown layout type '", "+", "ty...
https://github.com/timonwong/OmniMarkupPreviewer/blob/21921ac7a99d2b5924a2219b33679a5b53621392/OmniMarkupLib/Renderers/libs/python3/docutils/utils/math/math2html.py#L3228-L3237
poodarchu/Det3D
01258d8cb26656c5b950f8d41f9dcc1dd62a391e
det3d/torchie/utils/progressbar.py
python
ProgressBar.__init__
(self, task_num=0, bar_width=50, start=True)
[]
def __init__(self, task_num=0, bar_width=50, start=True): self.task_num = task_num max_bar_width = self._get_max_bar_width() self.bar_width = bar_width if bar_width <= max_bar_width else max_bar_width self.completed = 0 if start: self.start()
[ "def", "__init__", "(", "self", ",", "task_num", "=", "0", ",", "bar_width", "=", "50", ",", "start", "=", "True", ")", ":", "self", ".", "task_num", "=", "task_num", "max_bar_width", "=", "self", ".", "_get_max_bar_width", "(", ")", "self", ".", "bar_...
https://github.com/poodarchu/Det3D/blob/01258d8cb26656c5b950f8d41f9dcc1dd62a391e/det3d/torchie/utils/progressbar.py#L11-L17
OpenMDAO/OpenMDAO
f47eb5485a0bb5ea5d2ae5bd6da4b94dc6b296bd
openmdao/solvers/linear/linear_runonce.py
python
LinearRunOnce.solve
(self, mode, rel_systems=None)
Run the solver. Parameters ---------- mode : str 'fwd' or 'rev'. rel_systems : set of str Names of systems relevant to the current solve.
Run the solver.
[ "Run", "the", "solver", "." ]
def solve(self, mode, rel_systems=None): """ Run the solver. Parameters ---------- mode : str 'fwd' or 'rev'. rel_systems : set of str Names of systems relevant to the current solve. """ self._mode = mode self._rel_systems = rel_systems self._update_rhs_vec() # Single iteration of GS self._single_iteration()
[ "def", "solve", "(", "self", ",", "mode", ",", "rel_systems", "=", "None", ")", ":", "self", ".", "_mode", "=", "mode", "self", ".", "_rel_systems", "=", "rel_systems", "self", ".", "_update_rhs_vec", "(", ")", "# Single iteration of GS", "self", ".", "_si...
https://github.com/OpenMDAO/OpenMDAO/blob/f47eb5485a0bb5ea5d2ae5bd6da4b94dc6b296bd/openmdao/solvers/linear/linear_runonce.py#L20-L37
tkrajina/gpxpy
208fcd625760a73b7d1b7167c4053547084268c9
gpxpy/gpx.py
python
GPXTrack.reduce_points
(self, min_distance: float)
Reduces the number of points in the track. Segment points will be updated in place. Parameters ---------- min_distance : float The minimum separation in meters between points
Reduces the number of points in the track. Segment points will be updated in place.
[ "Reduces", "the", "number", "of", "points", "in", "the", "track", ".", "Segment", "points", "will", "be", "updated", "in", "place", "." ]
def reduce_points(self, min_distance: float) -> None: """ Reduces the number of points in the track. Segment points will be updated in place. Parameters ---------- min_distance : float The minimum separation in meters between points """ for segment in self.segments: segment.reduce_points(min_distance)
[ "def", "reduce_points", "(", "self", ",", "min_distance", ":", "float", ")", "->", "None", ":", "for", "segment", "in", "self", ".", "segments", ":", "segment", ".", "reduce_points", "(", "min_distance", ")" ]
https://github.com/tkrajina/gpxpy/blob/208fcd625760a73b7d1b7167c4053547084268c9/gpxpy/gpx.py#L1437-L1448
hildogjr/KiCost
227f246d8c0f5dab145390d15c94ee2c3d6c790c
kicost/sexpdata.py
python
SExpBase.tosexp
(self, tosexp=tosexp)
Decode this object into an S-expression string. :arg tosexp: A function to be used when converting sub S-expression.
Decode this object into an S-expression string.
[ "Decode", "this", "object", "into", "an", "S", "-", "expression", "string", "." ]
def tosexp(self, tosexp=tosexp): """ Decode this object into an S-expression string. :arg tosexp: A function to be used when converting sub S-expression. """ raise NotImplementedError
[ "def", "tosexp", "(", "self", ",", "tosexp", "=", "tosexp", ")", ":", "raise", "NotImplementedError" ]
https://github.com/hildogjr/KiCost/blob/227f246d8c0f5dab145390d15c94ee2c3d6c790c/kicost/sexpdata.py#L434-L441
learningequality/ka-lite
571918ea668013dcf022286ea85eff1c5333fb8b
kalite/packages/bundled/django/views/generic/detail.py
python
SingleObjectMixin.get_context_data
(self, **kwargs)
return super(SingleObjectMixin, self).get_context_data(**context)
Insert the single object into the context dict.
Insert the single object into the context dict.
[ "Insert", "the", "single", "object", "into", "the", "context", "dict", "." ]
def get_context_data(self, **kwargs): """ Insert the single object into the context dict. """ context = {} context_object_name = self.get_context_object_name(self.object) if context_object_name: context[context_object_name] = self.object context.update(kwargs) return super(SingleObjectMixin, self).get_context_data(**context)
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "{", "}", "context_object_name", "=", "self", ".", "get_context_object_name", "(", "self", ".", "object", ")", "if", "context_object_name", ":", "context", "[", "conte...
https://github.com/learningequality/ka-lite/blob/571918ea668013dcf022286ea85eff1c5333fb8b/kalite/packages/bundled/django/views/generic/detail.py#L91-L100
openwisp/django-freeradius
3369ab046637cc4e2f9756926b98e01e1ab100d6
django_freeradius/social/views.py
python
RedirectCaptivePageView.get_redirect_url
(self, request)
return '{0}?username={1}&token={2}&radius_user_token={3}'.format(cp, user.username, token.key, rad_token.key)
refreshes token and returns the captive page URL
refreshes token and returns the captive page URL
[ "refreshes", "token", "and", "returns", "the", "captive", "page", "URL" ]
def get_redirect_url(self, request): """ refreshes token and returns the captive page URL """ cp = request.GET.get('cp') user = request.user Token.objects.filter(user=user).delete() RadiusToken.objects.filter(user=user).delete() token = Token.objects.create(user=user) rad_token = RadiusToken.objects.create(user=user) return '{0}?username={1}&token={2}&radius_user_token={3}'.format(cp, user.username, token.key, rad_token.key)
[ "def", "get_redirect_url", "(", "self", ",", "request", ")", ":", "cp", "=", "request", ".", "GET", ".", "get", "(", "'cp'", ")", "user", "=", "request", ".", "user", "Token", ".", "objects", ".", "filter", "(", "user", "=", "user", ")", ".", "dele...
https://github.com/openwisp/django-freeradius/blob/3369ab046637cc4e2f9756926b98e01e1ab100d6/django_freeradius/social/views.py#L34-L47
rowliny/DiffHelper
ab3a96f58f9579d0023aed9ebd785f4edf26f8af
Tool/SitePackages/urllib3/request.py
python
RequestMethods.request_encode_body
(self, method, url, fields=None, headers=None, encode_multipart=True, multipart_boundary=None, **urlopen_kw)
return self.urlopen(method, url, **extra_kw)
Make a request using :meth:`urlopen` with the ``fields`` encoded in the body. This is useful for request methods like POST, PUT, PATCH, etc. When ``encode_multipart=True`` (default), then :meth:`urllib3.filepost.encode_multipart_formdata` is used to encode the payload with the appropriate content type. Otherwise :meth:`urllib.urlencode` is used with the 'application/x-www-form-urlencoded' content type. Multipart encoding must be used when posting files, and it's reasonably safe to use it in other times too. However, it may break request signing, such as with OAuth. Supports an optional ``fields`` parameter of key/value strings AND key/filetuple. A filetuple is a (filename, data, MIME type) tuple where the MIME type is optional. For example:: fields = { 'foo': 'bar', 'fakefile': ('foofile.txt', 'contents of foofile'), 'realfile': ('barfile.txt', open('realfile').read()), 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), 'nonamefile': 'contents of nonamefile field', } When uploading a file, providing a filename (the first parameter of the tuple) is optional but recommended to best mimic behavior of browsers. Note that if ``headers`` are supplied, the 'Content-Type' header will be overwritten because it depends on the dynamic random boundary string which is used to compose the body of the request. The random boundary string can be explicitly set with the ``multipart_boundary`` parameter.
Make a request using :meth:`urlopen` with the ``fields`` encoded in the body. This is useful for request methods like POST, PUT, PATCH, etc.
[ "Make", "a", "request", "using", ":", "meth", ":", "urlopen", "with", "the", "fields", "encoded", "in", "the", "body", ".", "This", "is", "useful", "for", "request", "methods", "like", "POST", "PUT", "PATCH", "etc", "." ]
def request_encode_body(self, method, url, fields=None, headers=None, encode_multipart=True, multipart_boundary=None, **urlopen_kw): """ Make a request using :meth:`urlopen` with the ``fields`` encoded in the body. This is useful for request methods like POST, PUT, PATCH, etc. When ``encode_multipart=True`` (default), then :meth:`urllib3.filepost.encode_multipart_formdata` is used to encode the payload with the appropriate content type. Otherwise :meth:`urllib.urlencode` is used with the 'application/x-www-form-urlencoded' content type. Multipart encoding must be used when posting files, and it's reasonably safe to use it in other times too. However, it may break request signing, such as with OAuth. Supports an optional ``fields`` parameter of key/value strings AND key/filetuple. A filetuple is a (filename, data, MIME type) tuple where the MIME type is optional. For example:: fields = { 'foo': 'bar', 'fakefile': ('foofile.txt', 'contents of foofile'), 'realfile': ('barfile.txt', open('realfile').read()), 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), 'nonamefile': 'contents of nonamefile field', } When uploading a file, providing a filename (the first parameter of the tuple) is optional but recommended to best mimic behavior of browsers. Note that if ``headers`` are supplied, the 'Content-Type' header will be overwritten because it depends on the dynamic random boundary string which is used to compose the body of the request. The random boundary string can be explicitly set with the ``multipart_boundary`` parameter. """ if headers is None: headers = self.headers extra_kw = {'headers': {}} if fields: if 'body' in urlopen_kw: raise TypeError( "request got values for both 'fields' and 'body', can only specify one.") if encode_multipart: body, content_type = encode_multipart_formdata(fields, boundary=multipart_boundary) else: body, content_type = urlencode(fields), 'application/x-www-form-urlencoded' extra_kw['body'] = body extra_kw['headers'] = {'Content-Type': content_type} extra_kw['headers'].update(headers) extra_kw.update(urlopen_kw) return self.urlopen(method, url, **extra_kw)
[ "def", "request_encode_body", "(", "self", ",", "method", ",", "url", ",", "fields", "=", "None", ",", "headers", "=", "None", ",", "encode_multipart", "=", "True", ",", "multipart_boundary", "=", "None", ",", "*", "*", "urlopen_kw", ")", ":", "if", "hea...
https://github.com/rowliny/DiffHelper/blob/ab3a96f58f9579d0023aed9ebd785f4edf26f8af/Tool/SitePackages/urllib3/request.py#L91-L150
gem/oq-engine
1bdb88f3914e390abcbd285600bfd39477aae47c
openquake/hazardlib/gsim/hassani_atkinson_2020.py
python
_fkp_ha18
(kappa, C, mag, dsigma)
return 3 * ek0[0] - 9 * ek0[1] + 27 * ek0[2] - 81 * ek0[3] \ + ek0[0] * l10kp + ek0[1] * l10kp ** 2 \ + ek0[2] * l10kp ** 3 + ek0[3] * l10kp ** 4
Kappa factor for B/C site condition of Japan.
Kappa factor for B/C site condition of Japan.
[ "Kappa", "factor", "for", "B", "/", "C", "site", "condition", "of", "Japan", "." ]
def _fkp_ha18(kappa, C, mag, dsigma): """ Kappa factor for B/C site condition of Japan. """ l10kp = math.log10(kappa) p = np.zeros(4) ek0 = np.zeros(4) for i in range(4): for j in range(4): p[j] = np.polyval([C[f'd{i}{j}2'], C[f'd{i}{j}1'], C[f'd{i}{j}0']], math.log10(dsigma)) ek0[i] = np.polyval(p[::-1], math.log10(mag)) return 3 * ek0[0] - 9 * ek0[1] + 27 * ek0[2] - 81 * ek0[3] \ + ek0[0] * l10kp + ek0[1] * l10kp ** 2 \ + ek0[2] * l10kp ** 3 + ek0[3] * l10kp ** 4
[ "def", "_fkp_ha18", "(", "kappa", ",", "C", ",", "mag", ",", "dsigma", ")", ":", "l10kp", "=", "math", ".", "log10", "(", "kappa", ")", "p", "=", "np", ".", "zeros", "(", "4", ")", "ek0", "=", "np", ".", "zeros", "(", "4", ")", "for", "i", ...
https://github.com/gem/oq-engine/blob/1bdb88f3914e390abcbd285600bfd39477aae47c/openquake/hazardlib/gsim/hassani_atkinson_2020.py#L117-L132
giantbranch/python-hacker-code
addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d
我手敲的代码(中文注释)/chapter11/volatility-2.3/volatility/obj.py
python
CType.v
(self)
return long(self.obj_offset)
When a struct is evaluated we just return our offset.
When a struct is evaluated we just return our offset.
[ "When", "a", "struct", "is", "evaluated", "we", "just", "return", "our", "offset", "." ]
def v(self): """ When a struct is evaluated we just return our offset. """ # Ensure that proxied offsets are converted to longs # to avoid integer boundaries when doing __rand__ proxying # (see issue 265) return long(self.obj_offset)
[ "def", "v", "(", "self", ")", ":", "# Ensure that proxied offsets are converted to longs", "# to avoid integer boundaries when doing __rand__ proxying", "# (see issue 265)", "return", "long", "(", "self", ".", "obj_offset", ")" ]
https://github.com/giantbranch/python-hacker-code/blob/addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d/我手敲的代码(中文注释)/chapter11/volatility-2.3/volatility/obj.py#L697-L703
themix-project/oomox
1bb0f3033736c56652e25c7d7b47c7fc499bfeb1
plugins/theme_materia/oomox_plugin.py
python
_monkeypatch_update_preview_colors
(preview_object)
[]
def _monkeypatch_update_preview_colors(preview_object): _monkeypatch_id = '_materia_update_colors_monkeypatched' if getattr(preview_object, _monkeypatch_id, None): return old_update_preview_colors = preview_object.update_preview_colors def _update_preview_colors(colorscheme): old_update_preview_colors(colorscheme) if colorscheme["THEME_STYLE"] == "materia": preview_object.override_widget_color( preview_object.gtk_preview.sel_label, preview_object.BG, convert_theme_color_to_gdk( mix_theme_colors( colorscheme["SEL_BG"], colorscheme["BG"], colorscheme["MATERIA_SELECTION_OPACITY"] ) ) ) preview_object.override_widget_color( preview_object.gtk_preview.entry, preview_object.BG, convert_theme_color_to_gdk( mix_theme_colors( colorscheme["FG"], colorscheme["BG"], 0.04 ) ) ) preview_object.update_preview_colors = _update_preview_colors setattr(preview_object, _monkeypatch_id, True)
[ "def", "_monkeypatch_update_preview_colors", "(", "preview_object", ")", ":", "_monkeypatch_id", "=", "'_materia_update_colors_monkeypatched'", "if", "getattr", "(", "preview_object", ",", "_monkeypatch_id", ",", "None", ")", ":", "return", "old_update_preview_colors", "=",...
https://github.com/themix-project/oomox/blob/1bb0f3033736c56652e25c7d7b47c7fc499bfeb1/plugins/theme_materia/oomox_plugin.py#L58-L91
FDA/openfda
7893f58ae02e8fa549eee2f7d2268234617321d9
openfda/annotation_table/extract_unii.py
python
extract_unii
(tree)
return first_match_or_empty_string(tree.getroot().xpath(unii_xpath))
Extracts the UNII from Pharmalogical Indexing XML
Extracts the UNII from Pharmalogical Indexing XML
[ "Extracts", "the", "UNII", "from", "Pharmalogical", "Indexing", "XML" ]
def extract_unii(tree): """Extracts the UNII from Pharmalogical Indexing XML""" unii_xpath = '//id[@root="%s"]/@extension' % UNII_OID return first_match_or_empty_string(tree.getroot().xpath(unii_xpath))
[ "def", "extract_unii", "(", "tree", ")", ":", "unii_xpath", "=", "'//id[@root=\"%s\"]/@extension'", "%", "UNII_OID", "return", "first_match_or_empty_string", "(", "tree", ".", "getroot", "(", ")", ".", "xpath", "(", "unii_xpath", ")", ")" ]
https://github.com/FDA/openfda/blob/7893f58ae02e8fa549eee2f7d2268234617321d9/openfda/annotation_table/extract_unii.py#L71-L74
windelbouwman/ppci
915c069e0667042c085ec42c78e9e3c9a5295324
ppci/lang/c/lexer.py
python
CLexer.lex_text
(self, txt)
return self.lex(f, source_file)
Create tokens from the given text
Create tokens from the given text
[ "Create", "tokens", "from", "the", "given", "text" ]
def lex_text(self, txt): """ Create tokens from the given text """ f = io.StringIO(txt) filename = None source_file = SourceFile(filename) return self.lex(f, source_file)
[ "def", "lex_text", "(", "self", ",", "txt", ")", ":", "f", "=", "io", ".", "StringIO", "(", "txt", ")", "filename", "=", "None", "source_file", "=", "SourceFile", "(", "filename", ")", "return", "self", ".", "lex", "(", "f", ",", "source_file", ")" ]
https://github.com/windelbouwman/ppci/blob/915c069e0667042c085ec42c78e9e3c9a5295324/ppci/lang/c/lexer.py#L124-L129
LoRexxar/Kunlun-M
06a68cf308f3d38be223d1d891465abcac9db88a
core/core_engine/php/parser.py
python
analysis_objectproperry_node
(node, back_node, vul_function, vul_lineno, function_params=None, file_path=None)
处理_objectproperry类型节点-->取出参数-->回溯判断参数是否可控-->输出结果 :param file_path: :param node: :param back_node: :param vul_function: :param vul_lineno: :param function_params: :return:
处理_objectproperry类型节点-->取出参数-->回溯判断参数是否可控-->输出结果 :param file_path: :param node: :param back_node: :param vul_function: :param vul_lineno: :param function_params: :return:
[ "处理_objectproperry类型节点", "--", ">", "取出参数", "--", ">", "回溯判断参数是否可控", "--", ">", "输出结果", ":", "param", "file_path", ":", ":", "param", "node", ":", ":", "param", "back_node", ":", ":", "param", "vul_function", ":", ":", "param", "vul_lineno", ":", ":", "p...
def analysis_objectproperry_node(node, back_node, vul_function, vul_lineno, function_params=None, file_path=None): """ 处理_objectproperry类型节点-->取出参数-->回溯判断参数是否可控-->输出结果 :param file_path: :param node: :param back_node: :param vul_function: :param vul_lineno: :param function_params: :return: """ logger.debug('[AST] vul_function:{v}'.format(v=vul_function)) param = node param_lineno = node.lineno # is_co, cp, expr_lineno = parameters_back(param, back_node, function_params) if file_path is not None: # with open(file_path, 'r') as fi: # fi = codecs.open(file_path, 'r', encoding='utf-8', errors='ignore') # code_content = fi.read() is_co, cp, expr_lineno, chain = anlysis_params(param, file_path, param_lineno, vul_function=vul_function) else: count = 0 is_co, cp, expr_lineno = deep_parameters_back(node, back_node, function_params, count, vul_function=vul_function) set_scan_results(is_co, cp, expr_lineno, vul_function, param, vul_lineno)
[ "def", "analysis_objectproperry_node", "(", "node", ",", "back_node", ",", "vul_function", ",", "vul_lineno", ",", "function_params", "=", "None", ",", "file_path", "=", "None", ")", ":", "logger", ".", "debug", "(", "'[AST] vul_function:{v}'", ".", "format", "(...
https://github.com/LoRexxar/Kunlun-M/blob/06a68cf308f3d38be223d1d891465abcac9db88a/core/core_engine/php/parser.py#L1719-L1747
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
pypy/module/struct/interp_struct.py
python
calcsize
(space, format)
return space.newint(_calcsize(space, format))
Return size of C struct described by format string fmt.
Return size of C struct described by format string fmt.
[ "Return", "size", "of", "C", "struct", "described", "by", "format", "string", "fmt", "." ]
def calcsize(space, format): """Return size of C struct described by format string fmt.""" return space.newint(_calcsize(space, format))
[ "def", "calcsize", "(", "space", ",", "format", ")", ":", "return", "space", ".", "newint", "(", "_calcsize", "(", "space", ",", "format", ")", ")" ]
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/pypy/module/struct/interp_struct.py#L38-L40
B16f00t/whapa
b843f1d3fd15578025dcca21d5f1cf094e2978bf
libs/whacloud.py
python
createSettingsFile
()
Function that creates the settings file
Function that creates the settings file
[ "Function", "that", "creates", "the", "settings", "file" ]
def createSettingsFile(): """ Function that creates the settings file """ cfg_file = system_slash(r'{}/cfg/settings.cfg'.format(whapa_path)) with open(cfg_file, 'w') as cfg: cfg.write(dedent(""" [report] company = record = unit = examiner = notes = [google-auth] gmail = alias@gmail.com # Optional. The account password or app password when using 2FA. password = # Optional. The result of "adb shell settings get secure android_id". android_id = 0000000000000000 # Optional. Enter the backup country code + phonenumber be synchronized, otherwise it synchronizes all backups. # You can specify a list of celnumbr = BackupNumber1, BackupNumber2, ... celnumbr = [icloud-auth] icloud = alias@icloud.com passw = yourpassword """).lstrip())
[ "def", "createSettingsFile", "(", ")", ":", "cfg_file", "=", "system_slash", "(", "r'{}/cfg/settings.cfg'", ".", "format", "(", "whapa_path", ")", ")", "with", "open", "(", "cfg_file", ",", "'w'", ")", "as", "cfg", ":", "cfg", ".", "write", "(", "dedent", ...
https://github.com/B16f00t/whapa/blob/b843f1d3fd15578025dcca21d5f1cf094e2978bf/libs/whacloud.py#L55-L81
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/importlib/abc.py
python
InspectLoader.source_to_code
(data, path='<string>')
return compile(data, path, 'exec', dont_inherit=True)
Compile 'data' into a code object. The 'data' argument can be anything that compile() can handle. The'path' argument should be where the data was retrieved (when applicable).
Compile 'data' into a code object.
[ "Compile", "data", "into", "a", "code", "object", "." ]
def source_to_code(data, path='<string>'): """Compile 'data' into a code object. The 'data' argument can be anything that compile() can handle. The'path' argument should be where the data was retrieved (when applicable).""" return compile(data, path, 'exec', dont_inherit=True)
[ "def", "source_to_code", "(", "data", ",", "path", "=", "'<string>'", ")", ":", "return", "compile", "(", "data", ",", "path", ",", "'exec'", ",", "dont_inherit", "=", "True", ")" ]
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/importlib/abc.py#L239-L244
polyaxon/polyaxon
e28d82051c2b61a84d06ce4d2388a40fc8565469
src/core/polyaxon/polytune/search_managers/bayesian_optimization/acquisition_function.py
python
UtilityFunction.max_compute
(self, y_max, bounds, num_warmup=100000, num_iterations=250)
return np.clip(x_max, bounds[:, 0], bounds[:, 1])
A function to find the maximum of the acquisition function It uses a combination of random sampling (cheap) and the 'L-BFGS-B' optimization method. First by sampling `num_warmup` (1e5) points at random, and then running L-BFGS-B from `num_iterations` (250) random starting points. Params: y_max: The current maximum known value of the target function. bounds: The variables bounds to limit the search of the acq max. num_warmup: The number of times to randomly sample the acquisition function num_iterations: The number of times to run scipy.minimize Returns x_max: The arg max of the acquisition function.
A function to find the maximum of the acquisition function
[ "A", "function", "to", "find", "the", "maximum", "of", "the", "acquisition", "function" ]
def max_compute(self, y_max, bounds, num_warmup=100000, num_iterations=250): """A function to find the maximum of the acquisition function It uses a combination of random sampling (cheap) and the 'L-BFGS-B' optimization method. First by sampling `num_warmup` (1e5) points at random, and then running L-BFGS-B from `num_iterations` (250) random starting points. Params: y_max: The current maximum known value of the target function. bounds: The variables bounds to limit the search of the acq max. num_warmup: The number of times to randomly sample the acquisition function num_iterations: The number of times to run scipy.minimize Returns x_max: The arg max of the acquisition function. """ # Warm up with random points x_tries = self.random_generator.uniform( bounds[:, 0], bounds[:, 1], size=(num_warmup, bounds.shape[0]) ) ys = self.compute(x_tries, y_max=y_max) x_max = x_tries[ys.argmax()] max_acq = ys.max() # Explore the parameter space more throughly x_seeds = self.random_generator.uniform( bounds[:, 0], bounds[:, 1], size=(num_iterations, bounds.shape[0]) ) for x_try in x_seeds: # Find the minimum of minus the acquisition function res = minimize( lambda x: -self.compute(x.reshape(1, -1), y_max=y_max), x_try.reshape(1, -1), bounds=bounds, method="L-BFGS-B", ) # See if success if not res.success: continue # Store it if better than previous minimum(maximum). if max_acq is None or -res.fun[0] >= max_acq: x_max = res.x max_acq = -res.fun[0] # Clip output to make sure it lies within the bounds. Due to floating # point technicalities this is not always the case. return np.clip(x_max, bounds[:, 0], bounds[:, 1])
[ "def", "max_compute", "(", "self", ",", "y_max", ",", "bounds", ",", "num_warmup", "=", "100000", ",", "num_iterations", "=", "250", ")", ":", "# Warm up with random points", "x_tries", "=", "self", ".", "random_generator", ".", "uniform", "(", "bounds", "[", ...
https://github.com/polyaxon/polyaxon/blob/e28d82051c2b61a84d06ce4d2388a40fc8565469/src/core/polyaxon/polytune/search_managers/bayesian_optimization/acquisition_function.py#L85-L134
n1nj4sec/pupy
a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39
pupy/modules/igd.py
python
IGDCMDClient.getExtIP
(self, args)
[]
def getExtIP(self, args): extip = self.igdc.GetExternalIP() self.show(extip)
[ "def", "getExtIP", "(", "self", ",", "args", ")", ":", "extip", "=", "self", ".", "igdc", ".", "GetExternalIP", "(", ")", "self", ".", "show", "(", "extip", ")" ]
https://github.com/n1nj4sec/pupy/blob/a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39/pupy/modules/igd.py#L80-L82
lukalabs/cakechat
844507281b30d81b3fe3674895fe27826dba8438
cakechat/dialog_model/keras_model.py
python
AbstractKerasModel._to_keras_callbacks
(callbacks)
return keras_callbacks
Casts AbstractKerasModel callbacks (see `cakechat.dialog_model.callbacks`) to the keras-based ones (instances of `keras.callbacks.Callback`) :param callbacks: :return:
Casts AbstractKerasModel callbacks (see `cakechat.dialog_model.callbacks`) to the keras-based ones (instances of `keras.callbacks.Callback`) :param callbacks: :return:
[ "Casts", "AbstractKerasModel", "callbacks", "(", "see", "cakechat", ".", "dialog_model", ".", "callbacks", ")", "to", "the", "keras", "-", "based", "ones", "(", "instances", "of", "keras", ".", "callbacks", ".", "Callback", ")", ":", "param", "callbacks", ":...
def _to_keras_callbacks(callbacks): """ Casts AbstractKerasModel callbacks (see `cakechat.dialog_model.callbacks`) to the keras-based ones (instances of `keras.callbacks.Callback`) :param callbacks: :return: """ keras_callbacks = [] for custom_callback in callbacks: if isinstance(custom_callback, AbstractKerasModelCallback): keras_callback = _KerasCallbackAdapter(custom_callback) elif isinstance(custom_callback, ParametrizedCallback): keras_callback = custom_callback.callback else: raise ValueError('Unsupported callback type: {}'.format(type(custom_callback))) keras_callbacks.append(keras_callback) return keras_callbacks
[ "def", "_to_keras_callbacks", "(", "callbacks", ")", ":", "keras_callbacks", "=", "[", "]", "for", "custom_callback", "in", "callbacks", ":", "if", "isinstance", "(", "custom_callback", ",", "AbstractKerasModelCallback", ")", ":", "keras_callback", "=", "_KerasCallb...
https://github.com/lukalabs/cakechat/blob/844507281b30d81b3fe3674895fe27826dba8438/cakechat/dialog_model/keras_model.py#L164-L182
theotherp/nzbhydra
4b03d7f769384b97dfc60dade4806c0fc987514e
libs/cherrypy/lib/auth.py
python
check_auth
(users, encrypt=None, realm=None)
return False
If an authorization header contains credentials, return True or False.
If an authorization header contains credentials, return True or False.
[ "If", "an", "authorization", "header", "contains", "credentials", "return", "True", "or", "False", "." ]
def check_auth(users, encrypt=None, realm=None): """If an authorization header contains credentials, return True or False. """ request = cherrypy.serving.request if 'authorization' in request.headers: # make sure the provided credentials are correctly set ah = httpauth.parseAuthorization(request.headers['authorization']) if ah is None: raise cherrypy.HTTPError(400, 'Bad Request') if not encrypt: encrypt = httpauth.DIGEST_AUTH_ENCODERS[httpauth.MD5] if hasattr(users, '__call__'): try: # backward compatibility users = users() # expect it to return a dictionary if not isinstance(users, dict): raise ValueError( "Authentication users must be a dictionary") # fetch the user password password = users.get(ah["username"], None) except TypeError: # returns a password (encrypted or clear text) password = users(ah["username"]) else: if not isinstance(users, dict): raise ValueError("Authentication users must be a dictionary") # fetch the user password password = users.get(ah["username"], None) # validate the authorization by re-computing it here # and compare it with what the user-agent provided if httpauth.checkResponse(ah, password, method=request.method, encrypt=encrypt, realm=realm): request.login = ah["username"] return True request.login = False return False
[ "def", "check_auth", "(", "users", ",", "encrypt", "=", "None", ",", "realm", "=", "None", ")", ":", "request", "=", "cherrypy", ".", "serving", ".", "request", "if", "'authorization'", "in", "request", ".", "headers", ":", "# make sure the provided credential...
https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/cherrypy/lib/auth.py#L5-L47
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/sympy/physics/mechanics/functions.py
python
_sub_func
(expr, sub_dict)
Perform direct matching substitution, ignoring derivatives.
Perform direct matching substitution, ignoring derivatives.
[ "Perform", "direct", "matching", "substitution", "ignoring", "derivatives", "." ]
def _sub_func(expr, sub_dict): """Perform direct matching substitution, ignoring derivatives.""" if expr in sub_dict: return sub_dict[expr] elif not expr.args or expr.is_Derivative: return expr
[ "def", "_sub_func", "(", "expr", ",", "sub_dict", ")", ":", "if", "expr", "in", "sub_dict", ":", "return", "sub_dict", "[", "expr", "]", "elif", "not", "expr", ".", "args", "or", "expr", ".", "is_Derivative", ":", "return", "expr" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/physics/mechanics/functions.py#L607-L612
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/tcss/v20201101/models.py
python
DescribeAbnormalProcessEventsExportRequest.__init__
(self)
r""" :param ExportField: 导出字段 :type ExportField: list of str :param Limit: 需要返回的数量,默认为10,最大值为100 :type Limit: int :param Offset: 偏移量,默认为0。 :type Offset: int :param Filters: 过滤参数,"Filters":[{"Name":"Status","Values":["2"]}] :type Filters: list of RunTimeFilters :param Order: 升序降序,asc desc :type Order: str :param By: 排序字段 :type By: str
r""" :param ExportField: 导出字段 :type ExportField: list of str :param Limit: 需要返回的数量,默认为10,最大值为100 :type Limit: int :param Offset: 偏移量,默认为0。 :type Offset: int :param Filters: 过滤参数,"Filters":[{"Name":"Status","Values":["2"]}] :type Filters: list of RunTimeFilters :param Order: 升序降序,asc desc :type Order: str :param By: 排序字段 :type By: str
[ "r", ":", "param", "ExportField", ":", "导出字段", ":", "type", "ExportField", ":", "list", "of", "str", ":", "param", "Limit", ":", "需要返回的数量,默认为10,最大值为100", ":", "type", "Limit", ":", "int", ":", "param", "Offset", ":", "偏移量,默认为0。", ":", "type", "Offset", "...
def __init__(self): r""" :param ExportField: 导出字段 :type ExportField: list of str :param Limit: 需要返回的数量,默认为10,最大值为100 :type Limit: int :param Offset: 偏移量,默认为0。 :type Offset: int :param Filters: 过滤参数,"Filters":[{"Name":"Status","Values":["2"]}] :type Filters: list of RunTimeFilters :param Order: 升序降序,asc desc :type Order: str :param By: 排序字段 :type By: str """ self.ExportField = None self.Limit = None self.Offset = None self.Filters = None self.Order = None self.By = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "ExportField", "=", "None", "self", ".", "Limit", "=", "None", "self", ".", "Offset", "=", "None", "self", ".", "Filters", "=", "None", "self", ".", "Order", "=", "None", "self", ".", "By", "="...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/tcss/v20201101/models.py#L3607-L3627
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/SQLAlchemy-1.3.17/examples/versioned_rows/versioned_map.py
python
ConfigValueAssociation.new_version
(self, session)
Expire all pending state, as ConfigValueAssociation is immutable.
Expire all pending state, as ConfigValueAssociation is immutable.
[ "Expire", "all", "pending", "state", "as", "ConfigValueAssociation", "is", "immutable", "." ]
def new_version(self, session): """Expire all pending state, as ConfigValueAssociation is immutable.""" session.expire(self)
[ "def", "new_version", "(", "self", ",", "session", ")", ":", "session", ".", "expire", "(", "self", ")" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/SQLAlchemy-1.3.17/examples/versioned_rows/versioned_map.py#L173-L176
nvaccess/nvda
20d5a25dced4da34338197f0ef6546270ebca5d0
source/addonHandler/__init__.py
python
terminate
()
Terminates the add-ons subsystem.
Terminates the add-ons subsystem.
[ "Terminates", "the", "add", "-", "ons", "subsystem", "." ]
def terminate(): """ Terminates the add-ons subsystem. """ pass
[ "def", "terminate", "(", ")", ":", "pass" ]
https://github.com/nvaccess/nvda/blob/20d5a25dced4da34338197f0ef6546270ebca5d0/source/addonHandler/__init__.py#L183-L185
MeanEYE/Sunflower
1024bbdde3b8e202ddad3553b321a7b6230bffc9
sunflower/gui/input_dialog.py
python
CreateToolbarWidgetDialog.get_response
(self)
return code, name, widget_type
Return dialog response and self-destruct
Return dialog response and self-destruct
[ "Return", "dialog", "response", "and", "self", "-", "destruct" ]
def get_response(self): """Return dialog response and self-destruct""" name = None widget_type = None # clear text entry before showing self._entry_name.set_text('') # show dialog code = self._dialog.run() # get name and type if code == Gtk.ResponseType.ACCEPT and len(self._type_list) > 0: name = self._entry_name.get_text() widget_type = self._type_list[self._combobox_type.get_active()][0] self._dialog.destroy() return code, name, widget_type
[ "def", "get_response", "(", "self", ")", ":", "name", "=", "None", "widget_type", "=", "None", "# clear text entry before showing", "self", ".", "_entry_name", ".", "set_text", "(", "''", ")", "# show dialog", "code", "=", "self", ".", "_dialog", ".", "run", ...
https://github.com/MeanEYE/Sunflower/blob/1024bbdde3b8e202ddad3553b321a7b6230bffc9/sunflower/gui/input_dialog.py#L1569-L1587
williamSYSU/TextGAN-PyTorch
891635af6845edfee382de147faa4fc00c7e90eb
visual/visual_temp_appendix.py
python
plt_data
(data, length, title, c_id, ls, marker, start=0)
[]
def plt_data(data, length, title, c_id, ls, marker, start=0): x = np.arange(start, start + length, 1) data = data[start:start + length] plt.plot(x, data, color=color_list[c_id], label=title, lw=1.0, ls=ls, marker=marker) if length < 100: plt.xticks(np.arange(start, start + length + 1, 5))
[ "def", "plt_data", "(", "data", ",", "length", ",", "title", ",", "c_id", ",", "ls", ",", "marker", ",", "start", "=", "0", ")", ":", "x", "=", "np", ".", "arange", "(", "start", ",", "start", "+", "length", ",", "1", ")", "data", "=", "data", ...
https://github.com/williamSYSU/TextGAN-PyTorch/blob/891635af6845edfee382de147faa4fc00c7e90eb/visual/visual_temp_appendix.py#L21-L26
cea-sec/miasm
09376c524aedc7920a7eda304d6095e12f6958f4
miasm/expression/smt2_helper.py
python
smt2_eq
(a, b)
return "(= {} {})".format(a, b)
Assignment: a = b
Assignment: a = b
[ "Assignment", ":", "a", "=", "b" ]
def smt2_eq(a, b): """ Assignment: a = b """ return "(= {} {})".format(a, b)
[ "def", "smt2_eq", "(", "a", ",", "b", ")", ":", "return", "\"(= {} {})\"", ".", "format", "(", "a", ",", "b", ")" ]
https://github.com/cea-sec/miasm/blob/09376c524aedc7920a7eda304d6095e12f6958f4/miasm/expression/smt2_helper.py#L12-L16
invesalius/invesalius3
0616d3e73bfe0baf7525877dbf6acab697395eb9
invesalius/data/editor.py
python
Editor.PixelThresholdLevel
(self, x, y, z)
Erase or Fill with Threshold level
Erase or Fill with Threshold level
[ "Erase", "or", "Fill", "with", "Threshold", "level" ]
def PixelThresholdLevel(self, x, y, z): """ Erase or Fill with Threshold level """ pixel_colour = self.image.GetScalarComponentAsDouble(x, y, z, 0) thres_i = self.w[0] thres_f = self.w[1] if (pixel_colour >= thres_i) and (pixel_colour <= thres_f): if (pixel_colour <= 0): self.FillPixel(x, y, z, 1) else: self.FillPixel(x, y, z, pixel_colour) else: self.ErasePixel(x, y, z)
[ "def", "PixelThresholdLevel", "(", "self", ",", "x", ",", "y", ",", "z", ")", ":", "pixel_colour", "=", "self", ".", "image", ".", "GetScalarComponentAsDouble", "(", "x", ",", "y", ",", "z", ",", "0", ")", "thres_i", "=", "self", ".", "w", "[", "0"...
https://github.com/invesalius/invesalius3/blob/0616d3e73bfe0baf7525877dbf6acab697395eb9/invesalius/data/editor.py#L198-L215
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/xml/dom/minidom.py
python
Attr._set_value
(self, value)
[]
def _set_value(self, value): d = self.__dict__ d['value'] = d['nodeValue'] = value if self.ownerElement: _clear_id_cache(self.ownerElement) self.childNodes[0].data = value
[ "def", "_set_value", "(", "self", ",", "value", ")", ":", "d", "=", "self", ".", "__dict__", "d", "[", "'value'", "]", "=", "d", "[", "'nodeValue'", "]", "=", "value", "if", "self", ".", "ownerElement", ":", "_clear_id_cache", "(", "self", ".", "owne...
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/xml/dom/minidom.py#L395-L400
meraki/dashboard-api-python
aef5e6fe5d23a40d435d5c64ff30580a28af07f1
meraki/aio/api/camera.py
python
AsyncCamera.getDeviceCameraAnalyticsLive
(self, serial: str)
return self._session.get(metadata, resource)
**Returns live state from camera of analytics zones** https://developer.cisco.com/meraki/api-v1/#!get-device-camera-analytics-live - serial (string): (required)
**Returns live state from camera of analytics zones** https://developer.cisco.com/meraki/api-v1/#!get-device-camera-analytics-live
[ "**", "Returns", "live", "state", "from", "camera", "of", "analytics", "zones", "**", "https", ":", "//", "developer", ".", "cisco", ".", "com", "/", "meraki", "/", "api", "-", "v1", "/", "#!get", "-", "device", "-", "camera", "-", "analytics", "-", ...
def getDeviceCameraAnalyticsLive(self, serial: str): """ **Returns live state from camera of analytics zones** https://developer.cisco.com/meraki/api-v1/#!get-device-camera-analytics-live - serial (string): (required) """ metadata = { 'tags': ['camera', 'monitor', 'analytics', 'live'], 'operation': 'getDeviceCameraAnalyticsLive' } resource = f'/devices/{serial}/camera/analytics/live' return self._session.get(metadata, resource)
[ "def", "getDeviceCameraAnalyticsLive", "(", "self", ",", "serial", ":", "str", ")", ":", "metadata", "=", "{", "'tags'", ":", "[", "'camera'", ",", "'monitor'", ",", "'analytics'", ",", "'live'", "]", ",", "'operation'", ":", "'getDeviceCameraAnalyticsLive'", ...
https://github.com/meraki/dashboard-api-python/blob/aef5e6fe5d23a40d435d5c64ff30580a28af07f1/meraki/aio/api/camera.py#L8-L22
joxeankoret/multiav
8a2bc4ae3ad043a73c7982116aa579f6e1dd5559
multiav/web/application.py
python
application.add_processor
(self, processor)
Adds a processor to the application. >>> urls = ("/(.*)", "echo") >>> app = application(urls, globals()) >>> class echo: ... def GET(self, name): return name ... >>> >>> def hello(handler): return "hello, " + handler() ... >>> app.add_processor(hello) >>> app.request("/web.py").data 'hello, web.py'
Adds a processor to the application. >>> urls = ("/(.*)", "echo") >>> app = application(urls, globals()) >>> class echo: ... def GET(self, name): return name ... >>> >>> def hello(handler): return "hello, " + handler() ... >>> app.add_processor(hello) >>> app.request("/web.py").data 'hello, web.py'
[ "Adds", "a", "processor", "to", "the", "application", ".", ">>>", "urls", "=", "(", "/", "(", ".", "*", ")", "echo", ")", ">>>", "app", "=", "application", "(", "urls", "globals", "()", ")", ">>>", "class", "echo", ":", "...", "def", "GET", "(", ...
def add_processor(self, processor): """ Adds a processor to the application. >>> urls = ("/(.*)", "echo") >>> app = application(urls, globals()) >>> class echo: ... def GET(self, name): return name ... >>> >>> def hello(handler): return "hello, " + handler() ... >>> app.add_processor(hello) >>> app.request("/web.py").data 'hello, web.py' """ self.processors.append(processor)
[ "def", "add_processor", "(", "self", ",", "processor", ")", ":", "self", ".", "processors", ".", "append", "(", "processor", ")" ]
https://github.com/joxeankoret/multiav/blob/8a2bc4ae3ad043a73c7982116aa579f6e1dd5559/multiav/web/application.py#L120-L136
jopohl/urh
9a7836698b8156687c0ed2d16f56d653cb847c22
src/urh/signalprocessing/ProtocolAnalyzerContainer.py
python
ProtocolAnalyzerContainer.fuzz_successive
(self, default_pause=None)
return self.fuzz(FuzzMode.successive, default_pause=default_pause)
Führt ein sukzessives Fuzzing über alle aktiven Fuzzing Label durch. Sequentiell heißt, ein Label wird durchgefuzzt und alle anderen Labels bleiben auf Standardwert. Das entspricht dem Vorgang nacheinander immer nur ein Label aktiv zu setzen.
Führt ein sukzessives Fuzzing über alle aktiven Fuzzing Label durch. Sequentiell heißt, ein Label wird durchgefuzzt und alle anderen Labels bleiben auf Standardwert. Das entspricht dem Vorgang nacheinander immer nur ein Label aktiv zu setzen.
[ "Führt", "ein", "sukzessives", "Fuzzing", "über", "alle", "aktiven", "Fuzzing", "Label", "durch", ".", "Sequentiell", "heißt", "ein", "Label", "wird", "durchgefuzzt", "und", "alle", "anderen", "Labels", "bleiben", "auf", "Standardwert", ".", "Das", "entspricht", ...
def fuzz_successive(self, default_pause=None): """ Führt ein sukzessives Fuzzing über alle aktiven Fuzzing Label durch. Sequentiell heißt, ein Label wird durchgefuzzt und alle anderen Labels bleiben auf Standardwert. Das entspricht dem Vorgang nacheinander immer nur ein Label aktiv zu setzen. """ return self.fuzz(FuzzMode.successive, default_pause=default_pause)
[ "def", "fuzz_successive", "(", "self", ",", "default_pause", "=", "None", ")", ":", "return", "self", ".", "fuzz", "(", "FuzzMode", ".", "successive", ",", "default_pause", "=", "default_pause", ")" ]
https://github.com/jopohl/urh/blob/9a7836698b8156687c0ed2d16f56d653cb847c22/src/urh/signalprocessing/ProtocolAnalyzerContainer.py#L121-L127
fooying/3102
0faee38c30b2e24154f41e68457cfd8f7a61c040
thirdparty/dns/name.py
python
Name.to_wire
(self, file = None, compress = None, origin = None)
Convert name to wire format, possibly compressing it. @param file: the file where the name is emitted (typically a cStringIO file). If None, a string containing the wire name will be returned. @type file: file or None @param compress: The compression table. If None (the default) names will not be compressed. @type compress: dict @param origin: If the name is relative and origin is not None, then origin will be appended to it. @type origin: dns.name.Name object @raises NeedAbsoluteNameOrOrigin: All names in wire format are absolute. If self is a relative name, then an origin must be supplied; if it is missing, then this exception is raised
Convert name to wire format, possibly compressing it.
[ "Convert", "name", "to", "wire", "format", "possibly", "compressing", "it", "." ]
def to_wire(self, file = None, compress = None, origin = None): """Convert name to wire format, possibly compressing it. @param file: the file where the name is emitted (typically a cStringIO file). If None, a string containing the wire name will be returned. @type file: file or None @param compress: The compression table. If None (the default) names will not be compressed. @type compress: dict @param origin: If the name is relative and origin is not None, then origin will be appended to it. @type origin: dns.name.Name object @raises NeedAbsoluteNameOrOrigin: All names in wire format are absolute. If self is a relative name, then an origin must be supplied; if it is missing, then this exception is raised """ if file is None: file = cStringIO.StringIO() want_return = True else: want_return = False if not self.is_absolute(): if origin is None or not origin.is_absolute(): raise NeedAbsoluteNameOrOrigin labels = list(self.labels) labels.extend(list(origin.labels)) else: labels = self.labels i = 0 for label in labels: n = Name(labels[i:]) i += 1 if not compress is None: pos = compress.get(n) else: pos = None if not pos is None: value = 0xc000 + pos s = struct.pack('!H', value) file.write(s) break else: if not compress is None and len(n) > 1: pos = file.tell() if pos <= 0x3fff: compress[n] = pos l = len(label) file.write(chr(l)) if l > 0: file.write(label) if want_return: return file.getvalue()
[ "def", "to_wire", "(", "self", ",", "file", "=", "None", ",", "compress", "=", "None", ",", "origin", "=", "None", ")", ":", "if", "file", "is", "None", ":", "file", "=", "cStringIO", ".", "StringIO", "(", ")", "want_return", "=", "True", "else", "...
https://github.com/fooying/3102/blob/0faee38c30b2e24154f41e68457cfd8f7a61c040/thirdparty/dns/name.py#L387-L441
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/grappelli/dashboard/utils.py
python
AppListElementMixin._get_admin_add_url
(self, model, context)
return reverse('%s:%s_%s_add' % (get_admin_site_name(context), app_label, model.__name__.lower()))
Returns the admin add url.
Returns the admin add url.
[ "Returns", "the", "admin", "add", "url", "." ]
def _get_admin_add_url(self, model, context): """ Returns the admin add url. """ app_label = model._meta.app_label return reverse('%s:%s_%s_add' % (get_admin_site_name(context), app_label, model.__name__.lower()))
[ "def", "_get_admin_add_url", "(", "self", ",", "model", ",", "context", ")", ":", "app_label", "=", "model", ".", "_meta", ".", "app_label", "return", "reverse", "(", "'%s:%s_%s_add'", "%", "(", "get_admin_site_name", "(", "context", ")", ",", "app_label", "...
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/grappelli/dashboard/utils.py#L155-L162
EmuKit/emukit
cdcb0d070d7f1c5585260266160722b636786859
emukit/core/optimization/local_search_acquisition_optimizer.py
python
LocalSearchAcquisitionOptimizer._neighbours_per_parameter
(self, all_features: np.ndarray, parameters: Sequence[Parameter])
return neighbours
Generates parameter encodings for one-exchange neighbours of parameters encoded in parameter feature vector :param all_features: The encoded parameter point (1d-array) :return: List of numpy arrays. Each array contains all one-exchange encodings of a parameter
Generates parameter encodings for one-exchange neighbours of parameters encoded in parameter feature vector
[ "Generates", "parameter", "encodings", "for", "one", "-", "exchange", "neighbours", "of", "parameters", "encoded", "in", "parameter", "feature", "vector" ]
def _neighbours_per_parameter(self, all_features: np.ndarray, parameters: Sequence[Parameter]) -> List[np.ndarray]: """ Generates parameter encodings for one-exchange neighbours of parameters encoded in parameter feature vector :param all_features: The encoded parameter point (1d-array) :return: List of numpy arrays. Each array contains all one-exchange encodings of a parameter """ neighbours = [] current_feature = 0 for parameter in parameters: features = parameter.round( all_features[current_feature:(current_feature + parameter.dimension)] .reshape(1, -1)).ravel() if isinstance(parameter, CategoricalParameter): if isinstance(parameter.encoding, OrdinalEncoding): left_right = np.unique([parameter.encoding.round_row(features - 1), parameter.encoding.round_row(features + 1)]) neighbours.append(left_right[left_right != features].reshape(-1, 1)) elif isinstance(parameter.encoding, OneHotEncoding): # All categories apart from current one are valid neighbours with one hot encoding neighbours.append(parameter.encodings[ (parameter.encodings != features).any(axis=1)]) else: raise TypeError("{} not a supported parameter encoding." .format(type(parameter.encoding))) elif isinstance(parameter, DiscreteParameter): # Find current position in domain while being robust to numerical precision problems current_index = np.argmin(np.abs( np.subtract(parameter.domain, features.item()))) this_neighbours = [] if current_index > 0: this_neighbours.append([parameter.domain[current_index - 1]]) if current_index < len(parameter.domain) - 1: this_neighbours.append([parameter.domain[current_index + 1]]) neighbours.append(np.asarray(this_neighbours).reshape(-1, 1)) elif isinstance(parameter, ContinuousParameter): samples, param_range = [], parameter.max - parameter.min while len(samples) < self.num_continuous: sample = np.random.normal(features.item(), self.std_dev * param_range, (1, 1)) if parameter.min <= sample <= parameter.max: samples.append(sample) neighbours.append(np.vstack(samples)) else: raise TypeError("{} not a supported parameter type." .format(type(parameter))) current_feature += parameter.dimension return neighbours
[ "def", "_neighbours_per_parameter", "(", "self", ",", "all_features", ":", "np", ".", "ndarray", ",", "parameters", ":", "Sequence", "[", "Parameter", "]", ")", "->", "List", "[", "np", ".", "ndarray", "]", ":", "neighbours", "=", "[", "]", "current_featur...
https://github.com/EmuKit/emukit/blob/cdcb0d070d7f1c5585260266160722b636786859/emukit/core/optimization/local_search_acquisition_optimizer.py#L64-L110
fake-name/ReadableWebProxy
ed5c7abe38706acc2684a1e6cd80242a03c5f010
WebMirror/management/rss_parser_funcs/feed_parse_extractYellowkittiesxBlogspotCom.py
python
extractYellowkittiesxBlogspotCom
(item)
return False
Parser for 'yellowkittiesx.blogspot.com'
Parser for 'yellowkittiesx.blogspot.com'
[ "Parser", "for", "yellowkittiesx", ".", "blogspot", ".", "com" ]
def extractYellowkittiesxBlogspotCom(item): ''' Parser for 'yellowkittiesx.blogspot.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
[ "def", "extractYellowkittiesxBlogspotCom", "(", "item", ")", ":", "vol", ",", "chp", ",", "frag", ",", "postfix", "=", "extractVolChapterFragmentPostfix", "(", "item", "[", "'title'", "]", ")", "if", "not", "(", "chp", "or", "vol", ")", "or", "\"preview\"", ...
https://github.com/fake-name/ReadableWebProxy/blob/ed5c7abe38706acc2684a1e6cd80242a03c5f010/WebMirror/management/rss_parser_funcs/feed_parse_extractYellowkittiesxBlogspotCom.py#L2-L21
donnemartin/gitsome
d7c57abc7cb66e9c910a844f15d4536866da3310
xonsh/built_ins.py
python
_convert_kind_flag
(x)
return kind
Puts a kind flag (string) a canonical form.
Puts a kind flag (string) a canonical form.
[ "Puts", "a", "kind", "flag", "(", "string", ")", "a", "canonical", "form", "." ]
def _convert_kind_flag(x): """Puts a kind flag (string) a canonical form.""" x = x.lower() kind = MACRO_FLAG_KINDS.get(x, None) if kind is None: raise TypeError("{0!r} not a recognized macro type.".format(x)) return kind
[ "def", "_convert_kind_flag", "(", "x", ")", ":", "x", "=", "x", ".", "lower", "(", ")", "kind", "=", "MACRO_FLAG_KINDS", ".", "get", "(", "x", ",", "None", ")", "if", "kind", "is", "None", ":", "raise", "TypeError", "(", "\"{0!r} not a recognized macro t...
https://github.com/donnemartin/gitsome/blob/d7c57abc7cb66e9c910a844f15d4536866da3310/xonsh/built_ins.py#L1052-L1058
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/swapoff.py
python
check_swap_in_fstab
(module)
Check for uncommented swap entries in fstab
Check for uncommented swap entries in fstab
[ "Check", "for", "uncommented", "swap", "entries", "in", "fstab" ]
def check_swap_in_fstab(module): '''Check for uncommented swap entries in fstab''' res = subprocess.call(['grep', '^[^#].*swap', '/etc/fstab']) if res == 2: # rc 2 == cannot open file. result = {'failed': True, 'changed': False, 'msg': 'unable to read /etc/fstab', 'state': 'unknown'} module.fail_json(**result) elif res == 1: # No grep match, fstab looks good. return False elif res == 0: # There is an uncommented entry for fstab. return True else: # Some other grep error code, we shouldn't get here. result = {'failed': True, 'changed': False, 'msg': 'unknow problem with grep "^[^#].*swap" /etc/fstab ', 'state': 'unknown'} module.fail_json(**result)
[ "def", "check_swap_in_fstab", "(", "module", ")", ":", "res", "=", "subprocess", ".", "call", "(", "[", "'grep'", ",", "'^[^#].*swap'", ",", "'/etc/fstab'", "]", ")", "if", "res", "==", "2", ":", "# rc 2 == cannot open file.", "result", "=", "{", "'failed'",...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/swapoff.py#L46-L69
Calysto/calysto_scheme
15bf81987870bcae1264e5a0a06feb9a8ee12b8b
calysto_scheme/scheme.py
python
char_initial_q
(c)
return (char_alphabetic_q(c)) or (char_is__q(c, make_char('!'))) or (char_is__q(c, make_char('$'))) or (char_is__q(c, make_char('%'))) or (char_is__q(c, make_char('&'))) or (char_is__q(c, make_char('*'))) or (char_is__q(c, make_char('/'))) or (char_is__q(c, make_char(':'))) or (char_is__q(c, make_char('<'))) or (char_is__q(c, make_char('='))) or (char_is__q(c, make_char('>'))) or (char_is__q(c, make_char('?'))) or (char_is__q(c, make_char('^'))) or (char_is__q(c, make_char('_'))) or (char_is__q(c, make_char('~')))
[]
def char_initial_q(c): return (char_alphabetic_q(c)) or (char_is__q(c, make_char('!'))) or (char_is__q(c, make_char('$'))) or (char_is__q(c, make_char('%'))) or (char_is__q(c, make_char('&'))) or (char_is__q(c, make_char('*'))) or (char_is__q(c, make_char('/'))) or (char_is__q(c, make_char(':'))) or (char_is__q(c, make_char('<'))) or (char_is__q(c, make_char('='))) or (char_is__q(c, make_char('>'))) or (char_is__q(c, make_char('?'))) or (char_is__q(c, make_char('^'))) or (char_is__q(c, make_char('_'))) or (char_is__q(c, make_char('~')))
[ "def", "char_initial_q", "(", "c", ")", ":", "return", "(", "char_alphabetic_q", "(", "c", ")", ")", "or", "(", "char_is__q", "(", "c", ",", "make_char", "(", "'!'", ")", ")", ")", "or", "(", "char_is__q", "(", "c", ",", "make_char", "(", "'$'", ")...
https://github.com/Calysto/calysto_scheme/blob/15bf81987870bcae1264e5a0a06feb9a8ee12b8b/calysto_scheme/scheme.py#L5910-L5911
noiselabs/box-linux-sync
4ba133e43be506f21a3d22e892491df445b5269e
src/noiselabs/box/pms/pacman.py
python
Pacman.install
(self, pkg)
return "pacman -S %s" % pkg
[]
def install(self, pkg): return "pacman -S %s" % pkg
[ "def", "install", "(", "self", ",", "pkg", ")", ":", "return", "\"pacman -S %s\"", "%", "pkg" ]
https://github.com/noiselabs/box-linux-sync/blob/4ba133e43be506f21a3d22e892491df445b5269e/src/noiselabs/box/pms/pacman.py#L34-L35
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/polys/densetools.py
python
_rec_diff_eval
(g, m, a, v, i, j, K)
return dmp_strip([ _rec_diff_eval(c, m, a, v, i, j, K) for c in g ], v)
Recursive helper for :func:`dmp_diff_eval`.
Recursive helper for :func:`dmp_diff_eval`.
[ "Recursive", "helper", "for", ":", "func", ":", "dmp_diff_eval", "." ]
def _rec_diff_eval(g, m, a, v, i, j, K): """Recursive helper for :func:`dmp_diff_eval`.""" if i == j: return dmp_eval(dmp_diff(g, m, v, K), a, v, K) v, i = v - 1, i + 1 return dmp_strip([ _rec_diff_eval(c, m, a, v, i, j, K) for c in g ], v)
[ "def", "_rec_diff_eval", "(", "g", ",", "m", ",", "a", ",", "v", ",", "i", ",", "j", ",", "K", ")", ":", "if", "i", "==", "j", ":", "return", "dmp_eval", "(", "dmp_diff", "(", "g", ",", "m", ",", "v", ",", "K", ")", ",", "a", ",", "v", ...
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/polys/densetools.py#L402-L409
aws/sagemaker-python-sdk
9d259b316f7f43838c16f35c10e98a110b56735b
src/sagemaker/lineage/query.py
python
LineageQuery._convert_api_response
(self, response)
return converted
Convert the lineage query API response to its Python representation.
Convert the lineage query API response to its Python representation.
[ "Convert", "the", "lineage", "query", "API", "response", "to", "its", "Python", "representation", "." ]
def _convert_api_response(self, response) -> LineageQueryResult: """Convert the lineage query API response to its Python representation.""" converted = LineageQueryResult() converted.edges = [self._get_edge(edge) for edge in response["Edges"]] converted.vertices = [self._get_vertex(vertex) for vertex in response["Vertices"]] edge_set = set() for edge in converted.edges: if edge in edge_set: converted.edges.remove(edge) edge_set.add(edge) vertex_set = set() for vertex in converted.vertices: if vertex in vertex_set: converted.vertices.remove(vertex) vertex_set.add(vertex) return converted
[ "def", "_convert_api_response", "(", "self", ",", "response", ")", "->", "LineageQueryResult", ":", "converted", "=", "LineageQueryResult", "(", ")", "converted", ".", "edges", "=", "[", "self", ".", "_get_edge", "(", "edge", ")", "for", "edge", "in", "respo...
https://github.com/aws/sagemaker-python-sdk/blob/9d259b316f7f43838c16f35c10e98a110b56735b/src/sagemaker/lineage/query.py#L251-L269
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/es/v20180416/models.py
python
LocalDiskInfo.__init__
(self)
r""" :param LocalDiskType: 本地盘类型<li>LOCAL_SATA:大数据型</li><li>NVME_SSD:高IO型</li> :type LocalDiskType: str :param LocalDiskSize: 本地盘单盘大小 :type LocalDiskSize: int :param LocalDiskCount: 本地盘块数 :type LocalDiskCount: int
r""" :param LocalDiskType: 本地盘类型<li>LOCAL_SATA:大数据型</li><li>NVME_SSD:高IO型</li> :type LocalDiskType: str :param LocalDiskSize: 本地盘单盘大小 :type LocalDiskSize: int :param LocalDiskCount: 本地盘块数 :type LocalDiskCount: int
[ "r", ":", "param", "LocalDiskType", ":", "本地盘类型<li", ">", "LOCAL_SATA:大数据型<", "/", "li", ">", "<li", ">", "NVME_SSD:高IO型<", "/", "li", ">", ":", "type", "LocalDiskType", ":", "str", ":", "param", "LocalDiskSize", ":", "本地盘单盘大小", ":", "type", "LocalDiskSize",...
def __init__(self): r""" :param LocalDiskType: 本地盘类型<li>LOCAL_SATA:大数据型</li><li>NVME_SSD:高IO型</li> :type LocalDiskType: str :param LocalDiskSize: 本地盘单盘大小 :type LocalDiskSize: int :param LocalDiskCount: 本地盘块数 :type LocalDiskCount: int """ self.LocalDiskType = None self.LocalDiskSize = None self.LocalDiskCount = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "LocalDiskType", "=", "None", "self", ".", "LocalDiskSize", "=", "None", "self", ".", "LocalDiskCount", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/es/v20180416/models.py#L1487-L1498
cuthbertLab/music21
bd30d4663e52955ed922c10fdf541419d8c67671
music21/stream/iterator.py
python
StreamIterator.variants
(self)
return self.addFilter(filters.ClassFilter('Variant'))
Deprecated in version 7 Adds a ClassFilter for Variant
Deprecated in version 7
[ "Deprecated", "in", "version", "7" ]
def variants(self): ''' Deprecated in version 7 Adds a ClassFilter for Variant ''' return self.addFilter(filters.ClassFilter('Variant'))
[ "def", "variants", "(", "self", ")", ":", "return", "self", ".", "addFilter", "(", "filters", ".", "ClassFilter", "(", "'Variant'", ")", ")" ]
https://github.com/cuthbertLab/music21/blob/bd30d4663e52955ed922c10fdf541419d8c67671/music21/stream/iterator.py#L1386-L1392
Azure/blobxfer
c6c6c143e8ee413d09a1110abafdb92e9e8afc39
blobxfer/models/upload.py
python
Descriptor._resume
(self)
Resume upload :param Descriptor self: this :rtype: int :return: resume bytes
Resume upload :param Descriptor self: this :rtype: int :return: resume bytes
[ "Resume", "upload", ":", "param", "Descriptor", "self", ":", "this", ":", "rtype", ":", "int", ":", "return", ":", "resume", "bytes" ]
def _resume(self): # type: (Descriptor) -> int """Resume upload :param Descriptor self: this :rtype: int :return: resume bytes """ if self._resume_mgr is None or self._offset > 0: return None # check if path exists in resume db rr = self._resume_mgr.get_record(self._ase) if rr is None: logger.debug('no resume record for {}'.format(self._ase.path)) return None # ensure lengths are the same if rr.length != self._ase.size: logger.warning('resume length mismatch {} -> {}'.format( rr.length, self._ase.size)) return None # compute replica factor if blobxfer.util.is_not_empty(self._ase.replica_targets): replica_factor = 1 + len(self._ase.replica_targets) else: replica_factor = 1 # set offsets if completed if rr.completed: with self._meta_lock: logger.debug('{} upload already completed'.format( self._ase.path)) self._offset = rr.total_chunks * rr.chunk_size self._chunk_num = rr.total_chunks self._chunk_size = rr.chunk_size self._total_chunks = rr.total_chunks self._completed_chunks.int = rr.completed_chunks self._outstanding_ops = 0 return self._ase.size * replica_factor # encrypted files are not resumable due to hmac requirement if self._ase.is_encrypted: logger.debug('cannot resume encrypted entity {}'.format( self._ase.path)) return None # check if path exists if not pathlib.Path(rr.local_path).exists(): logger.warning('resume from local path {} does not exist'.format( rr.local_path)) return None # re-hash from 0 to offset if needed _cc = bitstring.BitArray(length=rr.total_chunks) _cc.int = rr.completed_chunks curr_chunk = _cc.find('0b0')[0] del _cc _fd_offset = 0 _end_offset = min((curr_chunk * rr.chunk_size, rr.length)) if self.md5 is not None and curr_chunk > 0: _blocksize = blobxfer.util.MEGABYTE << 2 logger.debug( 'integrity checking existing file {} offset {} -> {}'.format( self._ase.path, self.local_path.view.fd_start, self.local_path.view.fd_start + _end_offset) ) with self._hasher_lock: with self.local_path.absolute_path.open('rb') as filedesc: filedesc.seek(self.local_path.view.fd_start, 0) while _fd_offset < _end_offset: if (_fd_offset + _blocksize) > _end_offset: _blocksize = _end_offset - _fd_offset _buf = filedesc.read(_blocksize) self.md5.update(_buf) _fd_offset += _blocksize del _blocksize # compare hashes hexdigest = self.md5.hexdigest() if rr.md5hexdigest != hexdigest: logger.warning( 'MD5 mismatch resume={} computed={} for {}'.format( rr.md5hexdigest, hexdigest, self._ase.path)) # reset hasher self.md5 = blobxfer.util.new_md5_hasher() return None # set values from resume with self._meta_lock: self._offset = _end_offset self._chunk_num = curr_chunk self._chunk_size = rr.chunk_size self._total_chunks = rr.total_chunks self._completed_chunks = bitstring.BitArray(length=rr.total_chunks) self._completed_chunks.set(True, range(0, curr_chunk + 1)) self._outstanding_ops = ( (rr.total_chunks - curr_chunk) * replica_factor ) logger.debug( ('resuming file {} from byte={} chunk={} chunk_size={} ' 'total_chunks={} outstanding_ops={}').format( self._ase.path, self._offset, self._chunk_num, self._chunk_size, self._total_chunks, self._outstanding_ops)) return _end_offset * replica_factor
[ "def", "_resume", "(", "self", ")", ":", "# type: (Descriptor) -> int", "if", "self", ".", "_resume_mgr", "is", "None", "or", "self", ".", "_offset", ">", "0", ":", "return", "None", "# check if path exists in resume db", "rr", "=", "self", ".", "_resume_mgr", ...
https://github.com/Azure/blobxfer/blob/c6c6c143e8ee413d09a1110abafdb92e9e8afc39/blobxfer/models/upload.py#L783-L880
sideeffects/SideFXLabs
956bc1eef6710882ae8d3a31b4a33dd631a56d5f
scripts/python/pyper/widgets/spreadsheet/ui.py
python
CustomLineEdit.__init__
(self)
[]
def __init__(self): super(CustomLineEdit, self).__init__()
[ "def", "__init__", "(", "self", ")", ":", "super", "(", "CustomLineEdit", ",", "self", ")", ".", "__init__", "(", ")" ]
https://github.com/sideeffects/SideFXLabs/blob/956bc1eef6710882ae8d3a31b4a33dd631a56d5f/scripts/python/pyper/widgets/spreadsheet/ui.py#L49-L50
nschaetti/EchoTorch
cba209c49e0fda73172d2e853b85c747f9f5117e
echotorch/data/datasets/HenonAttractor.py
python
HenonAttractor.__len__
(self)
return self.n_samples
Length :return:
Length :return:
[ "Length", ":", "return", ":" ]
def __len__(self): """ Length :return: """ return self.n_samples
[ "def", "__len__", "(", "self", ")", ":", "return", "self", ".", "n_samples" ]
https://github.com/nschaetti/EchoTorch/blob/cba209c49e0fda73172d2e853b85c747f9f5117e/echotorch/data/datasets/HenonAttractor.py#L133-L138
cmyr/anagramatron
048ab1a2b2aa3bb075ff1e5d8019c426d809eea0
anagramatron/simpledatastore.py
python
AnagramSimpleStore.save
(self)
pickles the data currently in the cache. doesn't save hit_count. we don't want to keep briefly popular items in cache indefinitely
pickles the data currently in the cache. doesn't save hit_count. we don't want to keep briefly popular items in cache indefinitely
[ "pickles", "the", "data", "currently", "in", "the", "cache", ".", "doesn", "t", "save", "hit_count", ".", "we", "don", "t", "want", "to", "keep", "briefly", "popular", "items", "in", "cache", "indefinitely" ]
def save(self): """ pickles the data currently in the cache. doesn't save hit_count. we don't want to keep briefly popular items in cache indefinitely """ if self.path: to_save = [self.datastore[t]['tweet'] for t in self.datastore] try: pickle.dump(to_save, open(self.path, 'wb')) print('saved cache to disk with %i items' % len(to_save)) except: logging.error('unable to save cache')
[ "def", "save", "(", "self", ")", ":", "if", "self", ".", "path", ":", "to_save", "=", "[", "self", ".", "datastore", "[", "t", "]", "[", "'tweet'", "]", "for", "t", "in", "self", ".", "datastore", "]", "try", ":", "pickle", ".", "dump", "(", "t...
https://github.com/cmyr/anagramatron/blob/048ab1a2b2aa3bb075ff1e5d8019c426d809eea0/anagramatron/simpledatastore.py#L56-L68
tsileo/microblog.pub
a775e272e1560f0a6b1014f4542632295f14b12b
blueprints/well_known.py
python
wellknown_webfinger
()
return jsonify(out, "application/jrd+json; charset=utf-8")
Exposes/servers WebFinger data.
Exposes/servers WebFinger data.
[ "Exposes", "/", "servers", "WebFinger", "data", "." ]
def wellknown_webfinger() -> Any: """Exposes/servers WebFinger data.""" resource = request.args.get("resource") if resource not in [f"acct:{config.USERNAME}@{config.DOMAIN}", config.ID]: abort(404) out = { "subject": f"acct:{config.USERNAME}@{config.DOMAIN}", "aliases": [config.ID], "links": [ { "rel": "http://webfinger.net/rel/profile-page", "type": "text/html", "href": config.ID, }, {"rel": "self", "type": "application/activity+json", "href": config.ID}, { "rel": "http://ostatus.org/schema/1.0/subscribe", "template": config.BASE_URL + "/authorize_follow?profile={uri}", }, {"rel": "magic-public-key", "href": config.KEY.to_magic_key()}, { "href": config.ICON_URL, "rel": "http://webfinger.net/rel/avatar", "type": mimetypes.guess_type(config.ICON_URL)[0], }, ], } return jsonify(out, "application/jrd+json; charset=utf-8")
[ "def", "wellknown_webfinger", "(", ")", "->", "Any", ":", "resource", "=", "request", ".", "args", ".", "get", "(", "\"resource\"", ")", "if", "resource", "not", "in", "[", "f\"acct:{config.USERNAME}@{config.DOMAIN}\"", ",", "config", ".", "ID", "]", ":", "a...
https://github.com/tsileo/microblog.pub/blob/a775e272e1560f0a6b1014f4542632295f14b12b/blueprints/well_known.py#L18-L47
dask/dask
c2b962fec1ba45440fe928869dc64cfe9cc36506
dask/array/rechunk.py
python
format_plan
(plan)
return [format_chunks(c) for c in plan]
>>> format_plan([((10, 10, 10), (15, 15)), ((30,), (10, 10, 10))]) [(3*[10], 2*[15]), ([30], 3*[10])]
>>> format_plan([((10, 10, 10), (15, 15)), ((30,), (10, 10, 10))]) [(3*[10], 2*[15]), ([30], 3*[10])]
[ ">>>", "format_plan", "(", "[", "((", "10", "10", "10", ")", "(", "15", "15", "))", "((", "30", ")", "(", "10", "10", "10", "))", "]", ")", "[", "(", "3", "*", "[", "10", "]", "2", "*", "[", "15", "]", ")", "(", "[", "30", "]", "3", "...
def format_plan(plan): """ >>> format_plan([((10, 10, 10), (15, 15)), ((30,), (10, 10, 10))]) [(3*[10], 2*[15]), ([30], 3*[10])] """ return [format_chunks(c) for c in plan]
[ "def", "format_plan", "(", "plan", ")", ":", "return", "[", "format_chunks", "(", "c", ")", "for", "c", "in", "plan", "]" ]
https://github.com/dask/dask/blob/c2b962fec1ba45440fe928869dc64cfe9cc36506/dask/array/rechunk.py#L683-L688
PythonJS/PythonJS
591a80afd8233fb715493591db2b68f1748558d9
pythonjs/lib/python2.7/ast.py
python
dump
(node, annotate_fields=True, include_attributes=False)
return _format(node)
Return a formatted dump of the tree in *node*. This is mainly useful for debugging purposes. The returned string will show the names and the values for fields. This makes the code impossible to evaluate, so if evaluation is wanted *annotate_fields* must be set to False. Attributes such as line numbers and column offsets are not dumped by default. If this is wanted, *include_attributes* can be set to True.
Return a formatted dump of the tree in *node*. This is mainly useful for debugging purposes. The returned string will show the names and the values for fields. This makes the code impossible to evaluate, so if evaluation is wanted *annotate_fields* must be set to False. Attributes such as line numbers and column offsets are not dumped by default. If this is wanted, *include_attributes* can be set to True.
[ "Return", "a", "formatted", "dump", "of", "the", "tree", "in", "*", "node", "*", ".", "This", "is", "mainly", "useful", "for", "debugging", "purposes", ".", "The", "returned", "string", "will", "show", "the", "names", "and", "the", "values", "for", "fiel...
def dump(node, annotate_fields=True, include_attributes=False): """ Return a formatted dump of the tree in *node*. This is mainly useful for debugging purposes. The returned string will show the names and the values for fields. This makes the code impossible to evaluate, so if evaluation is wanted *annotate_fields* must be set to False. Attributes such as line numbers and column offsets are not dumped by default. If this is wanted, *include_attributes* can be set to True. """ def _format(node): if isinstance(node, AST): fields = [(a, _format(b)) for a, b in iter_fields(node)] rv = '%s(%s' % (node.__class__.__name__, ', '.join( ('%s=%s' % field for field in fields) if annotate_fields else (b for a, b in fields) )) if include_attributes and node._attributes: rv += fields and ', ' or ' ' rv += ', '.join('%s=%s' % (a, _format(getattr(node, a))) for a in node._attributes) return rv + ')' elif isinstance(node, list): return '[%s]' % ', '.join(_format(x) for x in node) return repr(node) if not isinstance(node, AST): raise TypeError('expected AST, got %r' % node.__class__.__name__) return _format(node)
[ "def", "dump", "(", "node", ",", "annotate_fields", "=", "True", ",", "include_attributes", "=", "False", ")", ":", "def", "_format", "(", "node", ")", ":", "if", "isinstance", "(", "node", ",", "AST", ")", ":", "fields", "=", "[", "(", "a", ",", "...
https://github.com/PythonJS/PythonJS/blob/591a80afd8233fb715493591db2b68f1748558d9/pythonjs/lib/python2.7/ast.py#L83-L110
general03/flask-autoindex
424246242c9f40aeb9ac2c8c63f4d2234024256e
.eggs/Werkzeug-1.0.1-py3.7.egg/werkzeug/wrappers/base_response.py
python
BaseResponse.set_data
(self, value)
Sets a new string as response. The value set must be either a unicode or bytestring. If a unicode string is set it's encoded automatically to the charset of the response (utf-8 by default). .. versionadded:: 0.9
Sets a new string as response. The value set must be either a unicode or bytestring. If a unicode string is set it's encoded automatically to the charset of the response (utf-8 by default).
[ "Sets", "a", "new", "string", "as", "response", ".", "The", "value", "set", "must", "be", "either", "a", "unicode", "or", "bytestring", ".", "If", "a", "unicode", "string", "is", "set", "it", "s", "encoded", "automatically", "to", "the", "charset", "of",...
def set_data(self, value): """Sets a new string as response. The value set must be either a unicode or bytestring. If a unicode string is set it's encoded automatically to the charset of the response (utf-8 by default). .. versionadded:: 0.9 """ # if an unicode string is set, it's encoded directly so that we # can set the content length if isinstance(value, text_type): value = value.encode(self.charset) else: value = bytes(value) self.response = [value] if self.automatically_set_content_length: self.headers["Content-Length"] = str(len(value))
[ "def", "set_data", "(", "self", ",", "value", ")", ":", "# if an unicode string is set, it's encoded directly so that we", "# can set the content length", "if", "isinstance", "(", "value", ",", "text_type", ")", ":", "value", "=", "value", ".", "encode", "(", "self", ...
https://github.com/general03/flask-autoindex/blob/424246242c9f40aeb9ac2c8c63f4d2234024256e/.eggs/Werkzeug-1.0.1-py3.7.egg/werkzeug/wrappers/base_response.py#L341-L356
dalibo/pg_activity
6577f5c502407e9714202aca01a4a9813e357aea
pgactivity/data.py
python
pg_get_short_version
(text_version: str)
return res.group(0)
Return PostgreSQL short version from a string (SELECT version()). >>> pg_get_short_version('PostgreSQL 11.9') 'PostgreSQL 11.9' >>> pg_get_short_version('EnterpriseDB 11.9 (Debian 11.9-0+deb10u1)') 'EnterpriseDB 11.9' >>> pg_get_short_version("PostgreSQL 9.3.24 on x86_64-pc-linux-gnu (Debian 9.3.24-1.pgdg80+1), compiled by gcc (Debian 4.9.2-10+deb8u1) 4.9.2, 64-bit") 'PostgreSQL 9.3.24' >>> pg_get_short_version("PostgreSQL 9.1.4 on x86_64-unknown-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-39), 64-bit") 'PostgreSQL 9.1.4' >>> pg_get_short_version("PostgreSQL 14devel on x86_64-pc-linux-gnu, compiled by gcc (GCC) 9.3.1 20200408 (Red Hat 9.3.1-2), 64-bit") 'PostgreSQL 14devel' >>> pg_get_short_version("PostgreSQL 13beta1 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 9.3.1 20200408 (Red Hat 9.3.1-2), 64-bit") 'PostgreSQL 13beta1' >>> pg_get_short_version("PostgreSQL 13rc1 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 9.3.1 20200408 (Red Hat 9.3.1-2), 64-bit") 'PostgreSQL 13rc1' >>> pg_get_short_version("PostgreSQL 9.6rc1 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 9.3.1 20200408 (Red Hat 9.3.1-2), 64-bit") 'PostgreSQL 9.6rc1'
Return PostgreSQL short version from a string (SELECT version()).
[ "Return", "PostgreSQL", "short", "version", "from", "a", "string", "(", "SELECT", "version", "()", ")", "." ]
def pg_get_short_version(text_version: str) -> str: """Return PostgreSQL short version from a string (SELECT version()). >>> pg_get_short_version('PostgreSQL 11.9') 'PostgreSQL 11.9' >>> pg_get_short_version('EnterpriseDB 11.9 (Debian 11.9-0+deb10u1)') 'EnterpriseDB 11.9' >>> pg_get_short_version("PostgreSQL 9.3.24 on x86_64-pc-linux-gnu (Debian 9.3.24-1.pgdg80+1), compiled by gcc (Debian 4.9.2-10+deb8u1) 4.9.2, 64-bit") 'PostgreSQL 9.3.24' >>> pg_get_short_version("PostgreSQL 9.1.4 on x86_64-unknown-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-39), 64-bit") 'PostgreSQL 9.1.4' >>> pg_get_short_version("PostgreSQL 14devel on x86_64-pc-linux-gnu, compiled by gcc (GCC) 9.3.1 20200408 (Red Hat 9.3.1-2), 64-bit") 'PostgreSQL 14devel' >>> pg_get_short_version("PostgreSQL 13beta1 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 9.3.1 20200408 (Red Hat 9.3.1-2), 64-bit") 'PostgreSQL 13beta1' >>> pg_get_short_version("PostgreSQL 13rc1 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 9.3.1 20200408 (Red Hat 9.3.1-2), 64-bit") 'PostgreSQL 13rc1' >>> pg_get_short_version("PostgreSQL 9.6rc1 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 9.3.1 20200408 (Red Hat 9.3.1-2), 64-bit") 'PostgreSQL 9.6rc1' """ res = re.match( r"^\w+ [\d\.]+(devel|beta[0-9]+|rc[0-9]+)?", text_version, ) if not res: raise Exception(f"Undefined PostgreSQL version: {text_version}") return res.group(0)
[ "def", "pg_get_short_version", "(", "text_version", ":", "str", ")", "->", "str", ":", "res", "=", "re", ".", "match", "(", "r\"^\\w+ [\\d\\.]+(devel|beta[0-9]+|rc[0-9]+)?\"", ",", "text_version", ",", ")", "if", "not", "res", ":", "raise", "Exception", "(", "...
https://github.com/dalibo/pg_activity/blob/6577f5c502407e9714202aca01a4a9813e357aea/pgactivity/data.py#L40-L68
stopstalk/stopstalk-deployment
10c3ab44c4ece33ae515f6888c15033db2004bb1
aws_lambda/spoj_aws_lambda_function/lambda_code/pip/_vendor/requests/models.py
python
Response.raise_for_status
(self)
Raises stored :class:`HTTPError`, if one occurred.
Raises stored :class:`HTTPError`, if one occurred.
[ "Raises", "stored", ":", "class", ":", "HTTPError", "if", "one", "occurred", "." ]
def raise_for_status(self): """Raises stored :class:`HTTPError`, if one occurred.""" http_error_msg = '' if isinstance(self.reason, bytes): # We attempt to decode utf-8 first because some servers # choose to localize their reason strings. If the string # isn't utf-8, we fall back to iso-8859-1 for all other # encodings. (See PR #3538) try: reason = self.reason.decode('utf-8') except UnicodeDecodeError: reason = self.reason.decode('iso-8859-1') else: reason = self.reason if 400 <= self.status_code < 500: http_error_msg = u'%s Client Error: %s for url: %s' % (self.status_code, reason, self.url) elif 500 <= self.status_code < 600: http_error_msg = u'%s Server Error: %s for url: %s' % (self.status_code, reason, self.url) if http_error_msg: raise HTTPError(http_error_msg, response=self)
[ "def", "raise_for_status", "(", "self", ")", ":", "http_error_msg", "=", "''", "if", "isinstance", "(", "self", ".", "reason", ",", "bytes", ")", ":", "# We attempt to decode utf-8 first because some servers", "# choose to localize their reason strings. If the string", "# i...
https://github.com/stopstalk/stopstalk-deployment/blob/10c3ab44c4ece33ae515f6888c15033db2004bb1/aws_lambda/spoj_aws_lambda_function/lambda_code/pip/_vendor/requests/models.py#L916-L939
capaulson/pyKriging
5d9b4480e097811e7d21bccfc152c36733164636
pyKriging/krige.py
python
kriging.train
(self, optimizer='pso')
The function trains the hyperparameters of the Kriging model. :param optimizer: Two optimizers are implemented, a Particle Swarm Optimizer or a GA
The function trains the hyperparameters of the Kriging model. :param optimizer: Two optimizers are implemented, a Particle Swarm Optimizer or a GA
[ "The", "function", "trains", "the", "hyperparameters", "of", "the", "Kriging", "model", ".", ":", "param", "optimizer", ":", "Two", "optimizers", "are", "implemented", "a", "Particle", "Swarm", "Optimizer", "or", "a", "GA" ]
def train(self, optimizer='pso'): ''' The function trains the hyperparameters of the Kriging model. :param optimizer: Two optimizers are implemented, a Particle Swarm Optimizer or a GA ''' # First make sure our data is up-to-date self.updateData() # Establish the bounds for optimization for theta and p values lowerBound = [self.thetamin] * self.k + [self.pmin] * self.k upperBound = [self.thetamax] * self.k + [self.pmax] * self.k #Create a random seed for our optimizer to use rand = Random() rand.seed(int(time())) # If the optimizer option is PSO, run the PSO algorithm if optimizer == 'pso': ea = inspyred.swarm.PSO(Random()) ea.terminator = self.no_improvement_termination ea.topology = inspyred.swarm.topologies.ring_topology # ea.observer = inspyred.ec.observers.stats_observer final_pop = ea.evolve(generator=self.generate_population, evaluator=self.fittingObjective, pop_size=300, maximize=False, bounder=ec.Bounder(lowerBound, upperBound), max_evaluations=30000, neighborhood_size=20, num_inputs=self.k) # Sort and print the best individual, who will be at index 0. final_pop.sort(reverse=True) # If not using a PSO search, run the GA elif optimizer == 'ga': ea = inspyred.ec.GA(Random()) ea.terminator = self.no_improvement_termination final_pop = ea.evolve(generator=self.generate_population, evaluator=self.fittingObjective, pop_size=300, maximize=False, bounder=ec.Bounder(lowerBound, upperBound), max_evaluations=30000, num_elites=10, mutation_rate=.05) # This code updates the model with the hyperparameters found in the global search for entry in final_pop: newValues = entry.candidate preLOP = copy.deepcopy(newValues) locOP_bounds = [] for i in range(self.k): locOP_bounds.append( [self.thetamin, self.thetamax] ) for i in range(self.k): locOP_bounds.append( [self.pmin, self.pmax] ) # Let's quickly double check that we're at the optimal value by running a quick local optimizaiton lopResults = minimize(self.fittingObjective_local, newValues, method='SLSQP', bounds=locOP_bounds, options={'disp': False}) newValues = lopResults['x'] # Finally, set our new theta and pl values and update the model again for i in range(self.k): self.theta[i] = newValues[i] for i in range(self.k): self.pl[i] = newValues[i + self.k] try: self.updateModel() except: pass else: break
[ "def", "train", "(", "self", ",", "optimizer", "=", "'pso'", ")", ":", "# First make sure our data is up-to-date", "self", ".", "updateData", "(", ")", "# Establish the bounds for optimization for theta and p values", "lowerBound", "=", "[", "self", ".", "thetamin", "]"...
https://github.com/capaulson/pyKriging/blob/5d9b4480e097811e7d21bccfc152c36733164636/pyKriging/krige.py#L355-L427