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
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
ansible/roles/lib_oa_openshift/library/oc_adm_router.py
python
DeploymentConfig.delete_volume_by_name
(self, volume)
return modified
delete a volume
delete a volume
[ "delete", "a", "volume" ]
def delete_volume_by_name(self, volume): '''delete a volume ''' modified = False exist_volume_mounts = self.get_volume_mounts() exist_volumes = self.get_volumes() del_idx = None for idx, exist_volume in enumerate(exist_volumes): if 'name' in exist_volume and exist_volume['name'] == volume['name']: del_idx = idx break if del_idx != None: del exist_volumes[del_idx] modified = True del_idx = None for idx, exist_volume_mount in enumerate(exist_volume_mounts): if 'name' in exist_volume_mount and exist_volume_mount['name'] == volume['name']: del_idx = idx break if del_idx != None: del exist_volume_mounts[idx] modified = True return modified
[ "def", "delete_volume_by_name", "(", "self", ",", "volume", ")", ":", "modified", "=", "False", "exist_volume_mounts", "=", "self", ".", "get_volume_mounts", "(", ")", "exist_volumes", "=", "self", ".", "get_volumes", "(", ")", "del_idx", "=", "None", "for", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_oa_openshift/library/oc_adm_router.py#L2013-L2038
jython/jython3
def4f8ec47cb7a9c799ea4c745f12badf92c5769
Lib/xml/sax/_exceptions.py
python
SAXException.__getitem__
(self, ix)
Avoids weird error messages if someone does exception[ix] by mistake, since Exception has __getitem__ defined.
Avoids weird error messages if someone does exception[ix] by mistake, since Exception has __getitem__ defined.
[ "Avoids", "weird", "error", "messages", "if", "someone", "does", "exception", "[", "ix", "]", "by", "mistake", "since", "Exception", "has", "__getitem__", "defined", "." ]
def __getitem__(self, ix): """Avoids weird error messages if someone does exception[ix] by mistake, since Exception has __getitem__ defined.""" raise AttributeError("__getitem__")
[ "def", "__getitem__", "(", "self", ",", "ix", ")", ":", "raise", "AttributeError", "(", "\"__getitem__\"", ")" ]
https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/Lib/xml/sax/_exceptions.py#L34-L37
fonttools/fonttools
892322aaff6a89bea5927379ec06bc0da3dfb7df
Lib/fontTools/afmLib.py
python
AFM.write
(self, path, sep='\r')
Writes out an AFM font to the given path.
Writes out an AFM font to the given path.
[ "Writes", "out", "an", "AFM", "font", "to", "the", "given", "path", "." ]
def write(self, path, sep='\r'): """Writes out an AFM font to the given path.""" import time lines = [ "StartFontMetrics 2.0", "Comment Generated by afmLib; at %s" % ( time.strftime("%m/%d/%Y %H:%M:%S", time.localtime(time.time())))] # write comments, assuming (possibly wrongly!) they should # all appear at the top for comment in self._comments: lines.append("Comment " + comment) # write attributes, first the ones we know about, in # a preferred order attrs = self._attrs for attr in preferredAttributeOrder: if attr in attrs: value = attrs[attr] if attr == "FontBBox": value = "%s %s %s %s" % value lines.append(attr + " " + str(value)) # then write the attributes we don't know about, # in alphabetical order items = sorted(attrs.items()) for attr, value in items: if attr in preferredAttributeOrder: continue lines.append(attr + " " + str(value)) # write char metrics lines.append("StartCharMetrics " + repr(len(self._chars))) items = [(charnum, (charname, width, box)) for charname, (charnum, width, box) in self._chars.items()] def myKey(a): """Custom key function to make sure unencoded chars (-1) end up at the end of the list after sorting.""" if a[0] == -1: a = (0xffff,) + a[1:] # 0xffff is an arbitrary large number return a items.sort(key=myKey) for charnum, (charname, width, (l, b, r, t)) in items: lines.append("C %d ; WX %d ; N %s ; B %d %d %d %d ;" % (charnum, width, charname, l, b, r, t)) lines.append("EndCharMetrics") # write kerning info lines.append("StartKernData") lines.append("StartKernPairs " + repr(len(self._kerning))) items = sorted(self._kerning.items()) for (leftchar, rightchar), value in items: lines.append("KPX %s %s %d" % (leftchar, rightchar, value)) lines.append("EndKernPairs") lines.append("EndKernData") if self._composites: composites = sorted(self._composites.items()) lines.append("StartComposites %s" % len(self._composites)) for charname, components in composites: line = "CC %s %s ;" % (charname, len(components)) for basechar, xoffset, yoffset in components: line = line + " PCC %s %s %s ;" % (basechar, xoffset, yoffset) lines.append(line) lines.append("EndComposites") lines.append("EndFontMetrics") writelines(path, lines, sep)
[ "def", "write", "(", "self", ",", "path", ",", "sep", "=", "'\\r'", ")", ":", "import", "time", "lines", "=", "[", "\"StartFontMetrics 2.0\"", ",", "\"Comment Generated by afmLib; at %s\"", "%", "(", "time", ".", "strftime", "(", "\"%m/%d/%Y %H:%M:%S\"", ",", ...
https://github.com/fonttools/fonttools/blob/892322aaff6a89bea5927379ec06bc0da3dfb7df/Lib/fontTools/afmLib.py#L238-L306
Asana/python-asana
9b54ab99423208bd6aa87dbfaa628c069430b127
asana/resources/custom_fields.py
python
CustomFields.insert_enum_option
(self, custom_field, params={}, **options)
return self.client.post(path, params, **options)
Moves a particular enum option to be either before or after another specified enum option in the custom field. Locked custom fields can only be reordered by the user who locked the field. Parameters ---------- custom_field : {Gid} Globally unique identifier for the custom field. [data] : {Object} Data for the request - enum_option : {Gid} The ID of the enum option to relocate. - name : {String} The name of the enum option. - [color] : {String} The color of the enum option. Defaults to 'none'. - [before_enum_option] : {Gid} An existing enum option within this custom field before which the new enum option should be inserted. Cannot be provided together with after_enum_option. - [after_enum_option] : {Gid} An existing enum option within this custom field after which the new enum option should be inserted. Cannot be provided together with before_enum_option.
Moves a particular enum option to be either before or after another specified enum option in the custom field.
[ "Moves", "a", "particular", "enum", "option", "to", "be", "either", "before", "or", "after", "another", "specified", "enum", "option", "in", "the", "custom", "field", "." ]
def insert_enum_option(self, custom_field, params={}, **options): """Moves a particular enum option to be either before or after another specified enum option in the custom field. Locked custom fields can only be reordered by the user who locked the field. Parameters ---------- custom_field : {Gid} Globally unique identifier for the custom field. [data] : {Object} Data for the request - enum_option : {Gid} The ID of the enum option to relocate. - name : {String} The name of the enum option. - [color] : {String} The color of the enum option. Defaults to 'none'. - [before_enum_option] : {Gid} An existing enum option within this custom field before which the new enum option should be inserted. Cannot be provided together with after_enum_option. - [after_enum_option] : {Gid} An existing enum option within this custom field after which the new enum option should be inserted. Cannot be provided together with before_enum_option. """ path = "/custom_fields/%s/enum_options/insert" % (custom_field) return self.client.post(path, params, **options)
[ "def", "insert_enum_option", "(", "self", ",", "custom_field", ",", "params", "=", "{", "}", ",", "*", "*", "options", ")", ":", "path", "=", "\"/custom_fields/%s/enum_options/insert\"", "%", "(", "custom_field", ")", "return", "self", ".", "client", ".", "p...
https://github.com/Asana/python-asana/blob/9b54ab99423208bd6aa87dbfaa628c069430b127/asana/resources/custom_fields.py#L124-L140
ricequant/rqalpha-mod-ctp
bfd40801f9a182226a911cac74660f62993eb6db
rqalpha_mod_ctp/ctp/pyctp/linux64_36/__init__.py
python
TraderApi.OnRtnRepealFromFutureToBankByBank
(self, pRspRepeal)
银行发起冲正期货转银行通知
银行发起冲正期货转银行通知
[ "银行发起冲正期货转银行通知" ]
def OnRtnRepealFromFutureToBankByBank(self, pRspRepeal): """银行发起冲正期货转银行通知"""
[ "def", "OnRtnRepealFromFutureToBankByBank", "(", "self", ",", "pRspRepeal", ")", ":" ]
https://github.com/ricequant/rqalpha-mod-ctp/blob/bfd40801f9a182226a911cac74660f62993eb6db/rqalpha_mod_ctp/ctp/pyctp/linux64_36/__init__.py#L756-L757
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/gse/v20191112/gse_client.py
python
GseClient.DescribeFleetRelatedResources
(self, request)
本接口(DescribeFleetRelatedResources)用于获取与游戏服务器舰队关联的资源信息,如别名、队列 :param request: Request instance for DescribeFleetRelatedResources. :type request: :class:`tencentcloud.gse.v20191112.models.DescribeFleetRelatedResourcesRequest` :rtype: :class:`tencentcloud.gse.v20191112.models.DescribeFleetRelatedResourcesResponse`
本接口(DescribeFleetRelatedResources)用于获取与游戏服务器舰队关联的资源信息,如别名、队列
[ "本接口(DescribeFleetRelatedResources)用于获取与游戏服务器舰队关联的资源信息,如别名、队列" ]
def DescribeFleetRelatedResources(self, request): """本接口(DescribeFleetRelatedResources)用于获取与游戏服务器舰队关联的资源信息,如别名、队列 :param request: Request instance for DescribeFleetRelatedResources. :type request: :class:`tencentcloud.gse.v20191112.models.DescribeFleetRelatedResourcesRequest` :rtype: :class:`tencentcloud.gse.v20191112.models.DescribeFleetRelatedResourcesResponse` """ try: params = request._serialize() body = self.call("DescribeFleetRelatedResources", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeFleetRelatedResourcesResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message)
[ "def", "DescribeFleetRelatedResources", "(", "self", ",", "request", ")", ":", "try", ":", "params", "=", "request", ".", "_serialize", "(", ")", "body", "=", "self", ".", "call", "(", "\"DescribeFleetRelatedResources\"", ",", "params", ")", "response", "=", ...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/gse/v20191112/gse_client.py#L688-L713
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/printing/precedence.py
python
precedence_FracElement
(item)
[]
def precedence_FracElement(item): if item.denom == 1: return precedence_PolyElement(item.numer) else: return PRECEDENCE["Mul"]
[ "def", "precedence_FracElement", "(", "item", ")", ":", "if", "item", ".", "denom", "==", "1", ":", "return", "precedence_PolyElement", "(", "item", ".", "numer", ")", "else", ":", "return", "PRECEDENCE", "[", "\"Mul\"", "]" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/printing/precedence.py#L85-L89
pnprog/goreviewpartner
cbcc486cd4c51fb6fc3bc0a1eab61ff34298dadf
mss/linux.py
python
MSS.grab
(self, monitor)
return self.cls_image(data, monitor)
Retrieve all pixels from a monitor. Pixels have to be RGB.
Retrieve all pixels from a monitor. Pixels have to be RGB.
[ "Retrieve", "all", "pixels", "from", "a", "monitor", ".", "Pixels", "have", "to", "be", "RGB", "." ]
def grab(self, monitor): # type: (Dict[str, int]) -> ScreenShot """ Retrieve all pixels from a monitor. Pixels have to be RGB. """ # Convert PIL bbox style if isinstance(monitor, tuple): monitor = { 'left': monitor[0], 'top': monitor[1], 'width': monitor[2] - monitor[0], 'height': monitor[3] - monitor[1], } # Fix for XGetImage: # expected LP_Display instance instead of LP_XWindowAttributes root = ctypes.cast(self.root, ctypes.POINTER(Display)) ximage = self.xlib.XGetImage(self.display, root, monitor['left'], monitor['top'], monitor['width'], monitor['height'], 0x00ffffff, 2) # ZPIXMAP if not ximage: raise ScreenShotError('xlib.XGetImage() failed.', locals()) bits_per_pixel = ximage.contents.bits_per_pixel if bits_per_pixel != 32: raise ScreenShotError(('[XImage] bits per pixel value ' 'not (yet?) implemented.'), locals()) data = ctypes.cast(ximage.contents.data, ctypes.POINTER( ctypes.c_ubyte * monitor['height'] * monitor['width'] * 4)) data = bytearray(data.contents) # Free self.xlib.XDestroyImage(ximage) ximage = None return self.cls_image(data, monitor)
[ "def", "grab", "(", "self", ",", "monitor", ")", ":", "# type: (Dict[str, int]) -> ScreenShot", "# Convert PIL bbox style", "if", "isinstance", "(", "monitor", ",", "tuple", ")", ":", "monitor", "=", "{", "'left'", ":", "monitor", "[", "0", "]", ",", "'top'", ...
https://github.com/pnprog/goreviewpartner/blob/cbcc486cd4c51fb6fc3bc0a1eab61ff34298dadf/mss/linux.py#L272-L309
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
tokumx/datadog_checks/tokumx/vendor/pymongo/common.py
python
partition_node
(node)
return host, port
Split a host:port string into (host, int(port)) pair.
Split a host:port string into (host, int(port)) pair.
[ "Split", "a", "host", ":", "port", "string", "into", "(", "host", "int", "(", "port", "))", "pair", "." ]
def partition_node(node): """Split a host:port string into (host, int(port)) pair.""" host = node port = 27017 idx = node.rfind(':') if idx != -1: host, port = node[:idx], int(node[idx + 1:]) if host.startswith('['): host = host[1:-1] return host, port
[ "def", "partition_node", "(", "node", ")", ":", "host", "=", "node", "port", "=", "27017", "idx", "=", "node", ".", "rfind", "(", "':'", ")", "if", "idx", "!=", "-", "1", ":", "host", ",", "port", "=", "node", "[", ":", "idx", "]", ",", "int", ...
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/tokumx/datadog_checks/tokumx/vendor/pymongo/common.py#L91-L100
FSecureLABS/Jandroid
e31d0dab58a2bfd6ed8e0a387172b8bd7c893436
libs/platform-tools/platform-tools_darwin/systrace/catapult/devil/devil/android/device_utils.py
python
DeviceUtils._GetDumpsysOutput
(self, extra_args, pattern=None)
Runs |dumpsys| command on the device and returns its output. This private method implements support for filtering the output by a given |pattern|, but does not do any output parsing.
Runs |dumpsys| command on the device and returns its output.
[ "Runs", "|dumpsys|", "command", "on", "the", "device", "and", "returns", "its", "output", "." ]
def _GetDumpsysOutput(self, extra_args, pattern=None): """Runs |dumpsys| command on the device and returns its output. This private method implements support for filtering the output by a given |pattern|, but does not do any output parsing. """ try: cmd = ['dumpsys'] + extra_args if pattern: cmd = ' '.join(cmd_helper.SingleQuote(s) for s in cmd) return self._RunPipedShellCommand( '%s | grep -F %s' % (cmd, cmd_helper.SingleQuote(pattern))) else: cmd = ['dumpsys'] + extra_args return self.RunShellCommand(cmd, check_return=True, large_output=True) except device_errors.AdbShellCommandFailedError as e: if e.status and isinstance(e.status, list) and not e.status[0]: # If dumpsys succeeded but grep failed, there were no lines matching # the given pattern. return [] else: raise
[ "def", "_GetDumpsysOutput", "(", "self", ",", "extra_args", ",", "pattern", "=", "None", ")", ":", "try", ":", "cmd", "=", "[", "'dumpsys'", "]", "+", "extra_args", "if", "pattern", ":", "cmd", "=", "' '", ".", "join", "(", "cmd_helper", ".", "SingleQu...
https://github.com/FSecureLABS/Jandroid/blob/e31d0dab58a2bfd6ed8e0a387172b8bd7c893436/libs/platform-tools/platform-tools_darwin/systrace/catapult/devil/devil/android/device_utils.py#L2498-L2519
anki/vector-python-sdk
d61fdb07c6278deba750f987b20441fff2df865f
examples/apps/remote_control/lib/flask_helpers.py
python
_delayed_open_web_browser
(url, delay, new=0, autoraise=True, specific_browser=None)
Spawn a thread and call sleep_and_open_web_browser from within it so that main thread can keep executing at the same time. Insert a small sleep before opening a web-browser this gives Flask a chance to start running before the browser starts requesting data from Flask.
Spawn a thread and call sleep_and_open_web_browser from within it so that main thread can keep executing at the same time. Insert a small sleep before opening a web-browser this gives Flask a chance to start running before the browser starts requesting data from Flask.
[ "Spawn", "a", "thread", "and", "call", "sleep_and_open_web_browser", "from", "within", "it", "so", "that", "main", "thread", "can", "keep", "executing", "at", "the", "same", "time", ".", "Insert", "a", "small", "sleep", "before", "opening", "a", "web", "-", ...
def _delayed_open_web_browser(url, delay, new=0, autoraise=True, specific_browser=None): """ Spawn a thread and call sleep_and_open_web_browser from within it so that main thread can keep executing at the same time. Insert a small sleep before opening a web-browser this gives Flask a chance to start running before the browser starts requesting data from Flask. """ def _sleep_and_open_web_browser(url, delay, new, autoraise, specific_browser): sleep(delay) browser = webbrowser # E.g. On OSX the following would use the Chrome browser app from that location # specific_browser = 'open -a /Applications/Google\ Chrome.app %s' if specific_browser: browser = webbrowser.get(specific_browser) browser.open(url, new=new, autoraise=autoraise) thread = Thread(target=_sleep_and_open_web_browser, kwargs=dict(url=url, new=new, autoraise=autoraise, delay=delay, specific_browser=specific_browser)) thread.daemon = True # Force to quit on main quitting thread.start()
[ "def", "_delayed_open_web_browser", "(", "url", ",", "delay", ",", "new", "=", "0", ",", "autoraise", "=", "True", ",", "specific_browser", "=", "None", ")", ":", "def", "_sleep_and_open_web_browser", "(", "url", ",", "delay", ",", "new", ",", "autoraise", ...
https://github.com/anki/vector-python-sdk/blob/d61fdb07c6278deba750f987b20441fff2df865f/examples/apps/remote_control/lib/flask_helpers.py#L33-L54
yqyao/FCOS_PLUS
0d20ba34ccc316650d8c30febb2eb40cb6eaae37
maskrcnn_benchmark/data/build.py
python
build_dataset
(dataset_list, transforms, dataset_catalog, is_train=True)
return [dataset]
Arguments: dataset_list (list[str]): Contains the names of the datasets, i.e., coco_2014_trian, coco_2014_val, etc transforms (callable): transforms to apply to each (image, target) sample dataset_catalog (DatasetCatalog): contains the information on how to construct a dataset. is_train (bool): whether to setup the dataset for training or testing
Arguments: dataset_list (list[str]): Contains the names of the datasets, i.e., coco_2014_trian, coco_2014_val, etc transforms (callable): transforms to apply to each (image, target) sample dataset_catalog (DatasetCatalog): contains the information on how to construct a dataset. is_train (bool): whether to setup the dataset for training or testing
[ "Arguments", ":", "dataset_list", "(", "list", "[", "str", "]", ")", ":", "Contains", "the", "names", "of", "the", "datasets", "i", ".", "e", ".", "coco_2014_trian", "coco_2014_val", "etc", "transforms", "(", "callable", ")", ":", "transforms", "to", "appl...
def build_dataset(dataset_list, transforms, dataset_catalog, is_train=True): """ Arguments: dataset_list (list[str]): Contains the names of the datasets, i.e., coco_2014_trian, coco_2014_val, etc transforms (callable): transforms to apply to each (image, target) sample dataset_catalog (DatasetCatalog): contains the information on how to construct a dataset. is_train (bool): whether to setup the dataset for training or testing """ if not isinstance(dataset_list, (list, tuple)): raise RuntimeError( "dataset_list should be a list of strings, got {}".format(dataset_list) ) datasets = [] for dataset_name in dataset_list: data = dataset_catalog.get(dataset_name) factory = getattr(D, data["factory"]) args = data["args"] # for COCODataset, we want to remove images without annotations # during training if data["factory"] == "COCODataset": args["remove_images_without_annotations"] = is_train if data["factory"] == "PascalVOCDataset": args["use_difficult"] = not is_train args["transforms"] = transforms # make dataset from factory dataset = factory(**args) datasets.append(dataset) # for testing, return a list of datasets if not is_train: return datasets # for training, concatenate all datasets into a single one dataset = datasets[0] if len(datasets) > 1: dataset = D.ConcatDataset(datasets) return [dataset]
[ "def", "build_dataset", "(", "dataset_list", ",", "transforms", ",", "dataset_catalog", ",", "is_train", "=", "True", ")", ":", "if", "not", "isinstance", "(", "dataset_list", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "RuntimeError", "(", "\"...
https://github.com/yqyao/FCOS_PLUS/blob/0d20ba34ccc316650d8c30febb2eb40cb6eaae37/maskrcnn_benchmark/data/build.py#L17-L56
decalage2/ViperMonkey
631d242f43108226bb25ed91e773a274012dc8c2
vipermonkey/api.py
python
Module.__init__
(self, lines, deobfuscate=False)
Initializes a VBA module (or collection of loose lines) :param lines: String or list lines representing the code. :param deobfuscate: Whether to deobfuscate the code first which may speed up processing.
Initializes a VBA module (or collection of loose lines)
[ "Initializes", "a", "VBA", "module", "(", "or", "collection", "of", "loose", "lines", ")" ]
def __init__(self, lines, deobfuscate=False): """ Initializes a VBA module (or collection of loose lines) :param lines: String or list lines representing the code. :param deobfuscate: Whether to deobfuscate the code first which may speed up processing. """ # TODO: pp spec for module? # Instead of having a pyparsing spec, we are going to manually create the # parsed object from code blocks. super(Module, self).__init__(None, lines, deobfuscate=deobfuscate) # We are also going to include a dummy first line so that _iter_code_blocks() # doesn't skip the first line and last line. self.lines = [''] + self.lines + ['']
[ "def", "__init__", "(", "self", ",", "lines", ",", "deobfuscate", "=", "False", ")", ":", "# TODO: pp spec for module?", "# Instead of having a pyparsing spec, we are going to manually create the", "# parsed object from code blocks.", "super", "(", "Module", ",", "self", ")",...
https://github.com/decalage2/ViperMonkey/blob/631d242f43108226bb25ed91e773a274012dc8c2/vipermonkey/api.py#L336-L350
getdock/whitelist
704bb41552f71d1a91ecf35e373d8f0b7434f144
app/errors.py
python
AppError.__init__
(self, key: str = None, details: Any = None, code: int = None)
[]
def __init__(self, key: str = None, details: Any = None, code: int = None): super(AppError, self).__init__() self.key = key if code: self.code = code self.details = details
[ "def", "__init__", "(", "self", ",", "key", ":", "str", "=", "None", ",", "details", ":", "Any", "=", "None", ",", "code", ":", "int", "=", "None", ")", ":", "super", "(", "AppError", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "k...
https://github.com/getdock/whitelist/blob/704bb41552f71d1a91ecf35e373d8f0b7434f144/app/errors.py#L13-L18
getsentry/sentry
83b1f25aac3e08075e0e2495bc29efaf35aca18a
src/sentry/digests/backends/base.py
python
Backend.add
( self, key: str, record: "Record", increment_delay: Optional[int] = None, maximum_delay: Optional[int] = None, timestamp: Optional[float] = None, )
Add a record to a timeline. Adding a record to a timeline also causes it to be added to the schedule, if it is not already present. If another record exists in the timeline with the same record key, it will be overwritten. The return value this function indicates whether or not the timeline is ready for immediate digestion.
Add a record to a timeline.
[ "Add", "a", "record", "to", "a", "timeline", "." ]
def add( self, key: str, record: "Record", increment_delay: Optional[int] = None, maximum_delay: Optional[int] = None, timestamp: Optional[float] = None, ) -> bool: """ Add a record to a timeline. Adding a record to a timeline also causes it to be added to the schedule, if it is not already present. If another record exists in the timeline with the same record key, it will be overwritten. The return value this function indicates whether or not the timeline is ready for immediate digestion. """ raise NotImplementedError
[ "def", "add", "(", "self", ",", "key", ":", "str", ",", "record", ":", "\"Record\"", ",", "increment_delay", ":", "Optional", "[", "int", "]", "=", "None", ",", "maximum_delay", ":", "Optional", "[", "int", "]", "=", "None", ",", "timestamp", ":", "O...
https://github.com/getsentry/sentry/blob/83b1f25aac3e08075e0e2495bc29efaf35aca18a/src/sentry/digests/backends/base.py#L114-L134
androguard/androguard
8d091cbb309c0c50bf239f805cc1e0931b8dcddc
androguard/core/analysis/auto.py
python
DefaultAndroAnalysis.create_adex
(self, log, dexobj)
return vm_analysis
This method is called in order to create an Analysis object :param log: an object which corresponds to a unique app :param androguard.core.bytecodes.dvm.DalvikVMFormat dexobj: a :class:`DalvikVMFormat` object :rytpe: a :class:`~androguard.core.analysis.analysis.Analysis` object
This method is called in order to create an Analysis object
[ "This", "method", "is", "called", "in", "order", "to", "create", "an", "Analysis", "object" ]
def create_adex(self, log, dexobj): """ This method is called in order to create an Analysis object :param log: an object which corresponds to a unique app :param androguard.core.bytecodes.dvm.DalvikVMFormat dexobj: a :class:`DalvikVMFormat` object :rytpe: a :class:`~androguard.core.analysis.analysis.Analysis` object """ vm_analysis = analysis.Analysis(dexobj) vm_analysis.create_xref() return vm_analysis
[ "def", "create_adex", "(", "self", ",", "log", ",", "dexobj", ")", ":", "vm_analysis", "=", "analysis", ".", "Analysis", "(", "dexobj", ")", "vm_analysis", ".", "create_xref", "(", ")", "return", "vm_analysis" ]
https://github.com/androguard/androguard/blob/8d091cbb309c0c50bf239f805cc1e0931b8dcddc/androguard/core/analysis/auto.py#L292-L303
DamnWidget/anaconda
a9998fb362320f907d5ccbc6fcf5b62baca677c0
anaconda_lib/autopep/autopep8_lib/autopep8.py
python
Reindenter.getline
(self)
return line
Line-getter for tokenize.
Line-getter for tokenize.
[ "Line", "-", "getter", "for", "tokenize", "." ]
def getline(self): """Line-getter for tokenize.""" if self.index >= len(self.lines): line = '' else: line = self.lines[self.index] self.index += 1 return line
[ "def", "getline", "(", "self", ")", ":", "if", "self", ".", "index", ">=", "len", "(", "self", ".", "lines", ")", ":", "line", "=", "''", "else", ":", "line", "=", "self", ".", "lines", "[", "self", ".", "index", "]", "self", ".", "index", "+="...
https://github.com/DamnWidget/anaconda/blob/a9998fb362320f907d5ccbc6fcf5b62baca677c0/anaconda_lib/autopep/autopep8_lib/autopep8.py#L2785-L2792
VirtueSecurity/aws-extender
d123b7e1a845847709ba3a481f11996bddc68a1c
BappModules/s3transfer/utils.py
python
CountCallbackInvoker.increment
(self)
Increment the count by one
Increment the count by one
[ "Increment", "the", "count", "by", "one" ]
def increment(self): """Increment the count by one""" with self._lock: if self._is_finalized: raise RuntimeError( 'Counter has been finalized it can no longer be ' 'incremented.' ) self._count += 1
[ "def", "increment", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "if", "self", ".", "_is_finalized", ":", "raise", "RuntimeError", "(", "'Counter has been finalized it can no longer be '", "'incremented.'", ")", "self", ".", "_count", "+=", "1" ]
https://github.com/VirtueSecurity/aws-extender/blob/d123b7e1a845847709ba3a481f11996bddc68a1c/BappModules/s3transfer/utils.py#L194-L202
ageitgey/face_recognition
87a8449a359fbc0598e95b820e920ce285b8a9d9
examples/facerec_ipcamera_knn.py
python
train
(train_dir, model_save_path=None, n_neighbors=None, knn_algo='ball_tree', verbose=False)
return knn_clf
Trains a k-nearest neighbors classifier for face recognition. :param train_dir: directory that contains a sub-directory for each known person, with its name. (View in source code to see train_dir example tree structure) Structure: <train_dir>/ ├── <person1>/ │ ├── <somename1>.jpeg │ ├── <somename2>.jpeg │ ├── ... ├── <person2>/ │ ├── <somename1>.jpeg │ └── <somename2>.jpeg └── ... :param model_save_path: (optional) path to save model on disk :param n_neighbors: (optional) number of neighbors to weigh in classification. Chosen automatically if not specified :param knn_algo: (optional) underlying data structure to support knn.default is ball_tree :param verbose: verbosity of training :return: returns knn classifier that was trained on the given data.
Trains a k-nearest neighbors classifier for face recognition.
[ "Trains", "a", "k", "-", "nearest", "neighbors", "classifier", "for", "face", "recognition", "." ]
def train(train_dir, model_save_path=None, n_neighbors=None, knn_algo='ball_tree', verbose=False): """ Trains a k-nearest neighbors classifier for face recognition. :param train_dir: directory that contains a sub-directory for each known person, with its name. (View in source code to see train_dir example tree structure) Structure: <train_dir>/ ├── <person1>/ │ ├── <somename1>.jpeg │ ├── <somename2>.jpeg │ ├── ... ├── <person2>/ │ ├── <somename1>.jpeg │ └── <somename2>.jpeg └── ... :param model_save_path: (optional) path to save model on disk :param n_neighbors: (optional) number of neighbors to weigh in classification. Chosen automatically if not specified :param knn_algo: (optional) underlying data structure to support knn.default is ball_tree :param verbose: verbosity of training :return: returns knn classifier that was trained on the given data. """ X = [] y = [] # Loop through each person in the training set for class_dir in os.listdir(train_dir): if not os.path.isdir(os.path.join(train_dir, class_dir)): continue # Loop through each training image for the current person for img_path in image_files_in_folder(os.path.join(train_dir, class_dir)): image = face_recognition.load_image_file(img_path) face_bounding_boxes = face_recognition.face_locations(image) if len(face_bounding_boxes) != 1: # If there are no people (or too many people) in a training image, skip the image. if verbose: print("Image {} not suitable for training: {}".format(img_path, "Didn't find a face" if len(face_bounding_boxes) < 1 else "Found more than one face")) else: # Add face encoding for current image to the training set X.append(face_recognition.face_encodings(image, known_face_locations=face_bounding_boxes)[0]) y.append(class_dir) # Determine how many neighbors to use for weighting in the KNN classifier if n_neighbors is None: n_neighbors = int(round(math.sqrt(len(X)))) if verbose: print("Chose n_neighbors automatically:", n_neighbors) # Create and train the KNN classifier knn_clf = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, algorithm=knn_algo, weights='distance') knn_clf.fit(X, y) # Save the trained KNN classifier if model_save_path is not None: with open(model_save_path, 'wb') as f: pickle.dump(knn_clf, f) return knn_clf
[ "def", "train", "(", "train_dir", ",", "model_save_path", "=", "None", ",", "n_neighbors", "=", "None", ",", "knn_algo", "=", "'ball_tree'", ",", "verbose", "=", "False", ")", ":", "X", "=", "[", "]", "y", "=", "[", "]", "# Loop through each person in the ...
https://github.com/ageitgey/face_recognition/blob/87a8449a359fbc0598e95b820e920ce285b8a9d9/examples/facerec_ipcamera_knn.py#L51-L113
leancloud/satori
701caccbd4fe45765001ca60435c0cb499477c03
satori-rules/plugin/libs/redis/sentinel.py
python
SentinelManagedConnection.connect_to
(self, address)
[]
def connect_to(self, address): self.host, self.port = address super(SentinelManagedConnection, self).connect() if self.connection_pool.check_connection: self.send_command('PING') if nativestr(self.read_response()) != 'PONG': raise ConnectionError('PING failed')
[ "def", "connect_to", "(", "self", ",", "address", ")", ":", "self", ".", "host", ",", "self", ".", "port", "=", "address", "super", "(", "SentinelManagedConnection", ",", "self", ")", ".", "connect", "(", ")", "if", "self", ".", "connection_pool", ".", ...
https://github.com/leancloud/satori/blob/701caccbd4fe45765001ca60435c0cb499477c03/satori-rules/plugin/libs/redis/sentinel.py#L32-L38
NVIDIA/NeMo
5b0c0b4dec12d87d3cd960846de4105309ce938e
nemo/collections/nlp/modules/common/bert_module.py
python
BertModule.input_example
(self)
return tuple([input_ids, token_type_ids, attention_mask])
Generates input examples for tracing etc. Returns: A tuple of input examples.
Generates input examples for tracing etc. Returns: A tuple of input examples.
[ "Generates", "input", "examples", "for", "tracing", "etc", ".", "Returns", ":", "A", "tuple", "of", "input", "examples", "." ]
def input_example(self): """ Generates input examples for tracing etc. Returns: A tuple of input examples. """ sample = next(self.parameters()) input_ids = torch.randint(low=0, high=2048, size=(2, 16), device=sample.device) token_type_ids = torch.randint(low=0, high=1, size=(2, 16), device=sample.device) attention_mask = torch.randint(low=0, high=1, size=(2, 16), device=sample.device) return tuple([input_ids, token_type_ids, attention_mask])
[ "def", "input_example", "(", "self", ")", ":", "sample", "=", "next", "(", "self", ".", "parameters", "(", ")", ")", "input_ids", "=", "torch", ".", "randint", "(", "low", "=", "0", ",", "high", "=", "2048", ",", "size", "=", "(", "2", ",", "16",...
https://github.com/NVIDIA/NeMo/blob/5b0c0b4dec12d87d3cd960846de4105309ce938e/nemo/collections/nlp/modules/common/bert_module.py#L74-L84
pulp/pulp
a0a28d804f997b6f81c391378aff2e4c90183df9
server/pulp/server/logs.py
python
_blacklist_loggers
()
Disable all the loggers in the LOG_BLACKLIST.
Disable all the loggers in the LOG_BLACKLIST.
[ "Disable", "all", "the", "loggers", "in", "the", "LOG_BLACKLIST", "." ]
def _blacklist_loggers(): """ Disable all the loggers in the LOG_BLACKLIST. """ for logger_name in LOG_BLACKLIST: logger = logging.getLogger(logger_name) logger.disabled = True logger.propagate = False
[ "def", "_blacklist_loggers", "(", ")", ":", "for", "logger_name", "in", "LOG_BLACKLIST", ":", "logger", "=", "logging", ".", "getLogger", "(", "logger_name", ")", "logger", ".", "disabled", "=", "True", "logger", ".", "propagate", "=", "False" ]
https://github.com/pulp/pulp/blob/a0a28d804f997b6f81c391378aff2e4c90183df9/server/pulp/server/logs.py#L28-L35
fedden/poker_ai
73fb394b26623c897459ffa3e66d7a5cb47e9962
poker_ai/games/short_deck/state.py
python
ShortDeckPokerState.is_terminal
(self)
return self._betting_stage in {"show_down", "terminal"}
Returns whether this state is terminal or not. The state is terminal once all rounds of betting are complete and we are at the show down stage of the game or if all players have folded.
Returns whether this state is terminal or not.
[ "Returns", "whether", "this", "state", "is", "terminal", "or", "not", "." ]
def is_terminal(self) -> bool: """Returns whether this state is terminal or not. The state is terminal once all rounds of betting are complete and we are at the show down stage of the game or if all players have folded. """ return self._betting_stage in {"show_down", "terminal"}
[ "def", "is_terminal", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "_betting_stage", "in", "{", "\"show_down\"", ",", "\"terminal\"", "}" ]
https://github.com/fedden/poker_ai/blob/73fb394b26623c897459ffa3e66d7a5cb47e9962/poker_ai/games/short_deck/state.py#L429-L435
Pymol-Scripts/Pymol-script-repo
bcd7bb7812dc6db1595953dfa4471fa15fb68c77
modules/idlelib/CodeContext.py
python
CodeContext.update_code_context
(self)
Update context information and lines visible in the context pane.
Update context information and lines visible in the context pane.
[ "Update", "context", "information", "and", "lines", "visible", "in", "the", "context", "pane", "." ]
def update_code_context(self): """Update context information and lines visible in the context pane.""" new_topvisible = int(self.text.index("@0,0").split('.')[0]) if self.topvisible == new_topvisible: # haven't scrolled return if self.topvisible < new_topvisible: # scroll down lines, lastindent = self.get_context(new_topvisible, self.topvisible) # retain only context info applicable to the region # between topvisible and new_topvisible: while self.info[-1][1] >= lastindent: del self.info[-1] elif self.topvisible > new_topvisible: # scroll up stopindent = self.info[-1][1] + 1 # retain only context info associated # with lines above new_topvisible: while self.info[-1][0] >= new_topvisible: stopindent = self.info[-1][1] del self.info[-1] lines, lastindent = self.get_context(new_topvisible, self.info[-1][0] + 1, stopindent) self.info.extend(lines) self.topvisible = new_topvisible # empty lines in context pane: context_strings = [""] * max(0, self.context_depth - len(self.info)) # followed by the context hint lines: context_strings += [x[2] for x in self.info[-self.context_depth:]] self.label["text"] = '\n'.join(context_strings)
[ "def", "update_code_context", "(", "self", ")", ":", "new_topvisible", "=", "int", "(", "self", ".", "text", ".", "index", "(", "\"@0,0\"", ")", ".", "split", "(", "'.'", ")", "[", "0", "]", ")", "if", "self", ".", "topvisible", "==", "new_topvisible",...
https://github.com/Pymol-Scripts/Pymol-script-repo/blob/bcd7bb7812dc6db1595953dfa4471fa15fb68c77/modules/idlelib/CodeContext.py#L125-L151
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/numpy-1.16.0-py3.7-macosx-10.9-x86_64.egg/numpy/ma/mrecords.py
python
MaskedRecords.soften_mask
(self)
Forces the mask to soft
Forces the mask to soft
[ "Forces", "the", "mask", "to", "soft" ]
def soften_mask(self): """ Forces the mask to soft """ self._hardmask = False
[ "def", "soften_mask", "(", "self", ")", ":", "self", ".", "_hardmask", "=", "False" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/numpy-1.16.0-py3.7-macosx-10.9-x86_64.egg/numpy/ma/mrecords.py#L416-L421
tahoe-lafs/tahoe-lafs
766a53b5208c03c45ca0a98e97eee76870276aa1
src/allmydata/web/root.py
python
RootElement._describe_server
(server)
return { "peerid": peerid, "nickname": nickname, "version": version, "available_space": available_space, }
Return a dict containing server stats.
Return a dict containing server stats.
[ "Return", "a", "dict", "containing", "server", "stats", "." ]
def _describe_server(server): """Return a dict containing server stats.""" peerid = server.get_longname() nickname = server.get_nickname() version = server.get_announcement().get("my-version", "") space = server.get_available_space() if space is not None: available_space = abbreviate_size(space) else: available_space = "N/A" return { "peerid": peerid, "nickname": nickname, "version": version, "available_space": available_space, }
[ "def", "_describe_server", "(", "server", ")", ":", "peerid", "=", "server", ".", "get_longname", "(", ")", "nickname", "=", "server", ".", "get_nickname", "(", ")", "version", "=", "server", ".", "get_announcement", "(", ")", ".", "get", "(", "\"my-versio...
https://github.com/tahoe-lafs/tahoe-lafs/blob/766a53b5208c03c45ca0a98e97eee76870276aa1/src/allmydata/web/root.py#L484-L501
projecthamster/hamster-gtk
f51b45a77bcc343514ac1439d42ec024ef751a82
hamster_gtk/overview/widgets/fact_grid.py
python
FactBox.__init__
(self, fact)
Initialize widget.
Initialize widget.
[ "Initialize", "widget", "." ]
def __init__(self, fact): """Initialize widget.""" super(FactBox, self).__init__(orientation=Gtk.Orientation.VERTICAL) self.set_name('OverviewFactBox') # [FIXME] # Switch to Grid based design self.pack_start(self._get_activity_widget(fact), True, True, 0) self.pack_start(self._get_tags_widget(fact), True, True, 0) if fact.description: self.pack_start(self._get_description_widget(fact), False, False, 0)
[ "def", "__init__", "(", "self", ",", "fact", ")", ":", "super", "(", "FactBox", ",", "self", ")", ".", "__init__", "(", "orientation", "=", "Gtk", ".", "Orientation", ".", "VERTICAL", ")", "self", ".", "set_name", "(", "'OverviewFactBox'", ")", "# [FIXME...
https://github.com/projecthamster/hamster-gtk/blob/f51b45a77bcc343514ac1439d42ec024ef751a82/hamster_gtk/overview/widgets/fact_grid.py#L191-L200
securityclippy/elasticintel
aa08d3e9f5ab1c000128e95161139ce97ff0e334
ingest_feed_lambda/pandas/core/internals.py
python
SingleBlockManager.fast_xs
(self, loc)
return self._block.values[loc]
fast path for getting a cross-section return a view of the data
fast path for getting a cross-section return a view of the data
[ "fast", "path", "for", "getting", "a", "cross", "-", "section", "return", "a", "view", "of", "the", "data" ]
def fast_xs(self, loc): """ fast path for getting a cross-section return a view of the data """ return self._block.values[loc]
[ "def", "fast_xs", "(", "self", ",", "loc", ")", ":", "return", "self", ".", "_block", ".", "values", "[", "loc", "]" ]
https://github.com/securityclippy/elasticintel/blob/aa08d3e9f5ab1c000128e95161139ce97ff0e334/ingest_feed_lambda/pandas/core/internals.py#L4547-L4552
HewlettPackard/dlcookbook-dlbs
863ac1d7e72ad2fcafc78d8a13f67d35bc00c235
docker/build.py
python
DockerImage.__init__
(self, prefix: t.Optional[t.Text], name: t.Text, tag: t.Text)
Args: prefix: Image prefix (user name). name: Image name (repository). tag: Image tag. Full name is PREFIX/NAME:VERSION
Args: prefix: Image prefix (user name). name: Image name (repository). tag: Image tag. Full name is PREFIX/NAME:VERSION
[ "Args", ":", "prefix", ":", "Image", "prefix", "(", "user", "name", ")", ".", "name", ":", "Image", "name", "(", "repository", ")", ".", "tag", ":", "Image", "tag", ".", "Full", "name", "is", "PREFIX", "/", "NAME", ":", "VERSION" ]
def __init__(self, prefix: t.Optional[t.Text], name: t.Text, tag: t.Text) -> None: """ Args: prefix: Image prefix (user name). name: Image name (repository). tag: Image tag. Full name is PREFIX/NAME:VERSION """ self.prefix = prefix or DockerImage.Prefix.DLBS self.name = name self.tag = tag
[ "def", "__init__", "(", "self", ",", "prefix", ":", "t", ".", "Optional", "[", "t", ".", "Text", "]", ",", "name", ":", "t", ".", "Text", ",", "tag", ":", "t", ".", "Text", ")", "->", "None", ":", "self", ".", "prefix", "=", "prefix", "or", "...
https://github.com/HewlettPackard/dlcookbook-dlbs/blob/863ac1d7e72ad2fcafc78d8a13f67d35bc00c235/docker/build.py#L47-L57
scikit-multiflow/scikit-multiflow
d073a706b5006cba2584761286b7fa17e74e87be
src/skmultiflow/lazy/knn_adwin.py
python
KNNADWINClassifier.reset
(self)
return super().reset()
Reset the estimator. Resets the ADWIN Drift detector as well as the KNN model. Returns ------- KNNADWINClassifier self
Reset the estimator.
[ "Reset", "the", "estimator", "." ]
def reset(self): """ Reset the estimator. Resets the ADWIN Drift detector as well as the KNN model. Returns ------- KNNADWINClassifier self """ self.adwin = ADWIN() return super().reset()
[ "def", "reset", "(", "self", ")", ":", "self", ".", "adwin", "=", "ADWIN", "(", ")", "return", "super", "(", ")", ".", "reset", "(", ")" ]
https://github.com/scikit-multiflow/scikit-multiflow/blob/d073a706b5006cba2584761286b7fa17e74e87be/src/skmultiflow/lazy/knn_adwin.py#L100-L112
openstack/oslo.config
64c82a0829c6c5356ed2a44f14c1ea675aa493b7
oslo_config/iniparser.py
python
BaseParser.new_section
(self, section)
Called when a new section is started.
Called when a new section is started.
[ "Called", "when", "a", "new", "section", "is", "started", "." ]
def new_section(self, section): """Called when a new section is started.""" raise NotImplementedError()
[ "def", "new_section", "(", "self", ",", "section", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/openstack/oslo.config/blob/64c82a0829c6c5356ed2a44f14c1ea675aa493b7/oslo_config/iniparser.py#L103-L105
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/tkinter/ttk.py
python
Style.theme_names
(self)
return self.tk.splitlist(self.tk.call(self._name, "theme", "names"))
Returns a list of all known themes.
Returns a list of all known themes.
[ "Returns", "a", "list", "of", "all", "known", "themes", "." ]
def theme_names(self): """Returns a list of all known themes.""" return self.tk.splitlist(self.tk.call(self._name, "theme", "names"))
[ "def", "theme_names", "(", "self", ")", ":", "return", "self", ".", "tk", ".", "splitlist", "(", "self", ".", "tk", ".", "call", "(", "self", ".", "_name", ",", "\"theme\"", ",", "\"names\"", ")", ")" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/tkinter/ttk.py#L512-L514
zllrunning/SiameseX.PyTorch
36fec1e20ac04798d93d98b8b9618a5cf13e04ba
demo_rpn_utils/vot.py
python
VOT.__init__
(self, region_format)
Constructor Args: region_format: Region format options
Constructor
[ "Constructor" ]
def __init__(self, region_format): """ Constructor Args: region_format: Region format options """ assert(region_format in ['rectangle', 'polygon']) if TRAX: options = trax.server.ServerOptions(region_format, trax.image.PATH) self._trax = trax.server.Server(options) request = self._trax.wait() assert(request.type == 'initialize') if request.region.type == 'polygon': self._region = Polygon([Point(x[0], x[1]) for x in request.region.points]) else: self._region = Rectangle(request.region.x, request.region.y, request.region.width, request.region.height) self._image = str(request.image) self._trax.status(request.region) else: self._files = [x.strip('\n') for x in open('images.txt', 'r').readlines()] self._frame = 0 self._region = convert_region(parse_region(open('region.txt', 'r').readline()), region_format) self._result = []
[ "def", "__init__", "(", "self", ",", "region_format", ")", ":", "assert", "(", "region_format", "in", "[", "'rectangle'", ",", "'polygon'", "]", ")", "if", "TRAX", ":", "options", "=", "trax", ".", "server", ".", "ServerOptions", "(", "region_format", ",",...
https://github.com/zllrunning/SiameseX.PyTorch/blob/36fec1e20ac04798d93d98b8b9618a5cf13e04ba/demo_rpn_utils/vot.py#L84-L107
wwqgtxx/wwqLyParse
33136508e52821babd9294fdecffbdf02d73a6fc
wwqLyParse/lib/fallback_lib_py352/pycparser/c_lexer.py
python
CLexer.t_ppline_NEWLINE
(self, t)
r'\n
r'\n
[ "r", "\\", "n" ]
def t_ppline_NEWLINE(self, t): r'\n' if self.pp_line is None: self._error('line number missing in #line', t) else: self.lexer.lineno = int(self.pp_line) if self.pp_filename is not None: self.filename = self.pp_filename t.lexer.begin('INITIAL')
[ "def", "t_ppline_NEWLINE", "(", "self", ",", "t", ")", ":", "if", "self", ".", "pp_line", "is", "None", ":", "self", ".", "_error", "(", "'line number missing in #line'", ",", "t", ")", "else", ":", "self", ".", "lexer", ".", "lineno", "=", "int", "(",...
https://github.com/wwqgtxx/wwqLyParse/blob/33136508e52821babd9294fdecffbdf02d73a6fc/wwqLyParse/lib/fallback_lib_py352/pycparser/c_lexer.py#L277-L287
zenodo/zenodo
3c45e52a742ad5a0a7788a67b02fbbc15ab4d8d5
zenodo/modules/utils/grants.py
python
OpenAIREGrantsDump.__init__
(self, path, rows_write_chunk_size=10000)
Initialize the OpenAIRE grants dump.
Initialize the OpenAIRE grants dump.
[ "Initialize", "the", "OpenAIRE", "grants", "dump", "." ]
def __init__(self, path, rows_write_chunk_size=10000): """Initialize the OpenAIRE grants dump.""" self.path = path self.rows_write_chunk_size = rows_write_chunk_size
[ "def", "__init__", "(", "self", ",", "path", ",", "rows_write_chunk_size", "=", "10000", ")", ":", "self", ".", "path", "=", "path", "self", ".", "rows_write_chunk_size", "=", "rows_write_chunk_size" ]
https://github.com/zenodo/zenodo/blob/3c45e52a742ad5a0a7788a67b02fbbc15ab4d8d5/zenodo/modules/utils/grants.py#L44-L47
mandiant/capa
c0851fc643793c012f5dd764482133c25c3216c8
capa/features/extractors/viv/basicblock.py
python
extract_stackstring
(f, bb)
check basic block for stackstring indicators
check basic block for stackstring indicators
[ "check", "basic", "block", "for", "stackstring", "indicators" ]
def extract_stackstring(f, bb): """check basic block for stackstring indicators""" if _bb_has_stackstring(f, bb): yield Characteristic("stack string"), bb.va
[ "def", "extract_stackstring", "(", "f", ",", "bb", ")", ":", "if", "_bb_has_stackstring", "(", "f", ",", "bb", ")", ":", "yield", "Characteristic", "(", "\"stack string\"", ")", ",", "bb", ".", "va" ]
https://github.com/mandiant/capa/blob/c0851fc643793c012f5dd764482133c25c3216c8/capa/features/extractors/viv/basicblock.py#L70-L73
jparkhill/TensorMol
d52104dc7ee46eec8301d332a95d672270ac0bd1
TensorMol/Containers/Mol.py
python
Mol.ForceFromXYZ
(self, path)
Reads the forces from the comment line in the md_dataset, and if no forces exist sets them to zero. Switched on by has_force=True in the ReadGDB9Unpacked routine
Reads the forces from the comment line in the md_dataset, and if no forces exist sets them to zero. Switched on by has_force=True in the ReadGDB9Unpacked routine
[ "Reads", "the", "forces", "from", "the", "comment", "line", "in", "the", "md_dataset", "and", "if", "no", "forces", "exist", "sets", "them", "to", "zero", ".", "Switched", "on", "by", "has_force", "=", "True", "in", "the", "ReadGDB9Unpacked", "routine" ]
def ForceFromXYZ(self, path): """ Reads the forces from the comment line in the md_dataset, and if no forces exist sets them to zero. Switched on by has_force=True in the ReadGDB9Unpacked routine """ try: f = open(path, 'r') lines = f.readlines() natoms = int(lines[0]) forces=np.zeros((natoms,3)) read_forces = ((lines[1].strip().split(';'))[1]).replace("],[", ",").replace("[","").replace("]","").split(",") for j in range(natoms): for k in range(3): forces[j,k] = float(read_forces[j*3+k]) self.properties['forces'] = forces except Exception as Ex: print("Reading Force Failed.", Ex)
[ "def", "ForceFromXYZ", "(", "self", ",", "path", ")", ":", "try", ":", "f", "=", "open", "(", "path", ",", "'r'", ")", "lines", "=", "f", ".", "readlines", "(", ")", "natoms", "=", "int", "(", "lines", "[", "0", "]", ")", "forces", "=", "np", ...
https://github.com/jparkhill/TensorMol/blob/d52104dc7ee46eec8301d332a95d672270ac0bd1/TensorMol/Containers/Mol.py#L761-L778
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
packages/source/cinder/cinder/utils.py
python
check_isinstance
(obj, cls)
return cls()
Checks that obj is of type cls, and lets PyLint infer types.
Checks that obj is of type cls, and lets PyLint infer types.
[ "Checks", "that", "obj", "is", "of", "type", "cls", "and", "lets", "PyLint", "infer", "types", "." ]
def check_isinstance(obj, cls): """Checks that obj is of type cls, and lets PyLint infer types.""" if isinstance(obj, cls): return obj raise Exception(_('Expected object of type: %s') % (str(cls))) # TODO(justinsb): Can we make this better?? return cls()
[ "def", "check_isinstance", "(", "obj", ",", "cls", ")", ":", "if", "isinstance", "(", "obj", ",", "cls", ")", ":", "return", "obj", "raise", "Exception", "(", "_", "(", "'Expected object of type: %s'", ")", "%", "(", "str", "(", "cls", ")", ")", ")", ...
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/cinder/cinder/utils.py#L790-L796
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/prettytable/prettytable/v0_7_2/__init__.py
python
PrettyTable._get_sortby
(self)
return self._sortby
Name of field by which to sort rows Arguments: sortby - field name to sort by
Name of field by which to sort rows
[ "Name", "of", "field", "by", "which", "to", "sort", "rows" ]
def _get_sortby(self): """Name of field by which to sort rows Arguments: sortby - field name to sort by""" return self._sortby
[ "def", "_get_sortby", "(", "self", ")", ":", "return", "self", ".", "_sortby" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/prettytable/prettytable/v0_7_2/__init__.py#L497-L503
openstack/oslo.config
64c82a0829c6c5356ed2a44f14c1ea675aa493b7
oslo_config/cfg.py
python
_Namespace._check_deprecated
(self, name, current, deprecated)
Check for usage of deprecated names. :param name: A tuple of the form (group, name) representing the group and name where an opt value was found. :param current: A tuple of the form (group, name) representing the current name for an option. :param deprecated: A list of tuples with the same format as the name param which represent any deprecated names for an option. If the name param matches any entries in this list a deprecation warning will be logged.
Check for usage of deprecated names.
[ "Check", "for", "usage", "of", "deprecated", "names", "." ]
def _check_deprecated(self, name, current, deprecated): """Check for usage of deprecated names. :param name: A tuple of the form (group, name) representing the group and name where an opt value was found. :param current: A tuple of the form (group, name) representing the current name for an option. :param deprecated: A list of tuples with the same format as the name param which represent any deprecated names for an option. If the name param matches any entries in this list a deprecation warning will be logged. """ if name in deprecated and name not in self._emitted_deprecations: self._emitted_deprecations.add(name) current = (current[0] or 'DEFAULT', current[1]) format_dict = {'dep_option': name[1], 'dep_group': name[0], 'option': current[1], 'group': current[0]} _report_deprecation(self._deprecated_opt_message, format_dict)
[ "def", "_check_deprecated", "(", "self", ",", "name", ",", "current", ",", "deprecated", ")", ":", "if", "name", "in", "deprecated", "and", "name", "not", "in", "self", ".", "_emitted_deprecations", ":", "self", ".", "_emitted_deprecations", ".", "add", "(",...
https://github.com/openstack/oslo.config/blob/64c82a0829c6c5356ed2a44f14c1ea675aa493b7/oslo_config/cfg.py#L1812-L1829
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/django/contrib/gis/gdal/geometries.py
python
OGRGeometry.__del__
(self)
Deletes this Geometry.
Deletes this Geometry.
[ "Deletes", "this", "Geometry", "." ]
def __del__(self): "Deletes this Geometry." if self._ptr: capi.destroy_geom(self._ptr)
[ "def", "__del__", "(", "self", ")", ":", "if", "self", ".", "_ptr", ":", "capi", ".", "destroy_geom", "(", "self", ".", "_ptr", ")" ]
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/django/contrib/gis/gdal/geometries.py#L130-L132
buildbot/buildbot
b9c558217c72e4c2463eedc7ec6d56736f7b01a8
master/buildbot/www/change_hook.py
python
ChangeHookResource.makeHandler
(self, dialect)
return self._dialect_handlers[dialect]
create and cache the handler object for this dialect
create and cache the handler object for this dialect
[ "create", "and", "cache", "the", "handler", "object", "for", "this", "dialect" ]
def makeHandler(self, dialect): """create and cache the handler object for this dialect""" if dialect not in self.dialects: m = "The dialect specified, '{}', wasn't whitelisted in change_hook".format(dialect) log.msg(m) log.msg("Note: if dialect is 'base' then it's possible your URL is " "malformed and we didn't regex it properly") raise ValueError(m) if dialect not in self._dialect_handlers: if dialect not in self._plugins: m = ("The dialect specified, '{}', is not registered as " "a buildbot.webhook plugin").format(dialect) log.msg(m) raise ValueError(m) options = self.dialects[dialect] if isinstance(options, dict) and 'custom_class' in options: klass = options['custom_class'] else: klass = self._plugins.get(dialect) self._dialect_handlers[dialect] = klass(self.master, self.dialects[dialect]) return self._dialect_handlers[dialect]
[ "def", "makeHandler", "(", "self", ",", "dialect", ")", ":", "if", "dialect", "not", "in", "self", ".", "dialects", ":", "m", "=", "\"The dialect specified, '{}', wasn't whitelisted in change_hook\"", ".", "format", "(", "dialect", ")", "log", ".", "msg", "(", ...
https://github.com/buildbot/buildbot/blob/b9c558217c72e4c2463eedc7ec6d56736f7b01a8/master/buildbot/www/change_hook.py#L113-L135
GeekLiB/caffe-model
f21e52032c92f36eb6622846f6e6710bcd3f2054
inception_v1.py
python
factorization_conv_bn_scale_relu
(bottom, num_output=64, kernel_size=3, stride=1, pad=0)
return conv, conv_bn, conv_scale, conv_relu
[]
def factorization_conv_bn_scale_relu(bottom, num_output=64, kernel_size=3, stride=1, pad=0): conv = L.Convolution(bottom, num_output=num_output, kernel_size=kernel_size, stride=stride, pad=pad, param=[dict(lr_mult=1, decay_mult=1), dict(lr_mult=2, decay_mult=0)], weight_filler=dict(type='xavier', std=1), bias_filler=dict(type='constant', value=0.2)) conv_bn = L.BatchNorm(conv, use_global_stats=False, in_place=True) conv_scale = L.Scale(conv, scale_param=dict(bias_term=True), in_place=True) conv_relu = L.ReLU(conv, in_place=True) return conv, conv_bn, conv_scale, conv_relu
[ "def", "factorization_conv_bn_scale_relu", "(", "bottom", ",", "num_output", "=", "64", ",", "kernel_size", "=", "3", ",", "stride", "=", "1", ",", "pad", "=", "0", ")", ":", "conv", "=", "L", ".", "Convolution", "(", "bottom", ",", "num_output", "=", ...
https://github.com/GeekLiB/caffe-model/blob/f21e52032c92f36eb6622846f6e6710bcd3f2054/inception_v1.py#L17-L26
1012598167/flask_mongodb_game
60c7e0351586656ec38f851592886338e50b4110
python_flask/venv/Lib/site-packages/pip-19.0.3-py3.6.egg/pip/_internal/wheel.py
python
wheel_version
(source_dir)
Return the Wheel-Version of an extracted wheel, if possible. Otherwise, return None if we couldn't parse / extract it.
Return the Wheel-Version of an extracted wheel, if possible.
[ "Return", "the", "Wheel", "-", "Version", "of", "an", "extracted", "wheel", "if", "possible", "." ]
def wheel_version(source_dir): # type: (Optional[str]) -> Optional[Tuple[int, ...]] """ Return the Wheel-Version of an extracted wheel, if possible. Otherwise, return None if we couldn't parse / extract it. """ try: dist = [d for d in pkg_resources.find_on_path(None, source_dir)][0] wheel_data = dist.get_metadata('WHEEL') wheel_data = Parser().parsestr(wheel_data) version = wheel_data['Wheel-Version'].strip() version = tuple(map(int, version.split('.'))) return version except Exception: return None
[ "def", "wheel_version", "(", "source_dir", ")", ":", "# type: (Optional[str]) -> Optional[Tuple[int, ...]]", "try", ":", "dist", "=", "[", "d", "for", "d", "in", "pkg_resources", ".", "find_on_path", "(", "None", ",", "source_dir", ")", "]", "[", "0", "]", "wh...
https://github.com/1012598167/flask_mongodb_game/blob/60c7e0351586656ec38f851592886338e50b4110/python_flask/venv/Lib/site-packages/pip-19.0.3-py3.6.egg/pip/_internal/wheel.py#L616-L633
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/wifizoo/WifiZooEntities.py
python
AccessPoint.addClient
(self, aWifiClient)
return
[]
def addClient(self, aWifiClient): self._ClientsList.append( aWifiClient ) return
[ "def", "addClient", "(", "self", ",", "aWifiClient", ")", ":", "self", ".", "_ClientsList", ".", "append", "(", "aWifiClient", ")", "return" ]
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/wifizoo/WifiZooEntities.py#L102-L104
slackapi/python-slack-sdk
2dee6656ffacb7de0c29bb2a6c2b51ec6b5dbce7
slack_sdk/web/legacy_client.py
python
LegacyWebClient.chat_getPermalink
( self, *, channel: str, message_ts: str, **kwargs, )
return self.api_call("chat.getPermalink", http_verb="GET", params=kwargs)
Retrieve a permalink URL for a specific extant message https://api.slack.com/methods/chat.getPermalink
Retrieve a permalink URL for a specific extant message https://api.slack.com/methods/chat.getPermalink
[ "Retrieve", "a", "permalink", "URL", "for", "a", "specific", "extant", "message", "https", ":", "//", "api", ".", "slack", ".", "com", "/", "methods", "/", "chat", ".", "getPermalink" ]
def chat_getPermalink( self, *, channel: str, message_ts: str, **kwargs, ) -> Union[Future, SlackResponse]: """Retrieve a permalink URL for a specific extant message https://api.slack.com/methods/chat.getPermalink """ kwargs.update({"channel": channel, "message_ts": message_ts}) return self.api_call("chat.getPermalink", http_verb="GET", params=kwargs)
[ "def", "chat_getPermalink", "(", "self", ",", "*", ",", "channel", ":", "str", ",", "message_ts", ":", "str", ",", "*", "*", "kwargs", ",", ")", "->", "Union", "[", "Future", ",", "SlackResponse", "]", ":", "kwargs", ".", "update", "(", "{", "\"chann...
https://github.com/slackapi/python-slack-sdk/blob/2dee6656ffacb7de0c29bb2a6c2b51ec6b5dbce7/slack_sdk/web/legacy_client.py#L1877-L1888
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/pip/_vendor/distlib/version.py
python
SemanticVersion.parse
(self, s)
return _semantic_key(s)
[]
def parse(self, s): return _semantic_key(s)
[ "def", "parse", "(", "self", ",", "s", ")", ":", "return", "_semantic_key", "(", "s", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/pip/_vendor/distlib/version.py#L681-L682
robhagemans/pcbasic
c3a043b46af66623a801e18a38175be077251ada
pcbasic/basic/memory/scalars.py
python
Scalars.__iter__
(self)
return iterkeys(self._vars)
Return an iterable over all scalar names.
Return an iterable over all scalar names.
[ "Return", "an", "iterable", "over", "all", "scalar", "names", "." ]
def __iter__(self): """Return an iterable over all scalar names.""" return iterkeys(self._vars)
[ "def", "__iter__", "(", "self", ")", ":", "return", "iterkeys", "(", "self", ".", "_vars", ")" ]
https://github.com/robhagemans/pcbasic/blob/c3a043b46af66623a801e18a38175be077251ada/pcbasic/basic/memory/scalars.py#L30-L32
ctxis/canape
5f0e03424577296bcc60c2008a60a98ec5307e4b
CANAPE.Scripting/Lib/pprint.py
python
pformat
(object, indent=1, width=80, depth=None)
return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)
Format a Python object into a pretty-printed representation.
Format a Python object into a pretty-printed representation.
[ "Format", "a", "Python", "object", "into", "a", "pretty", "-", "printed", "representation", "." ]
def pformat(object, indent=1, width=80, depth=None): """Format a Python object into a pretty-printed representation.""" return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)
[ "def", "pformat", "(", "object", ",", "indent", "=", "1", ",", "width", "=", "80", ",", "depth", "=", "None", ")", ":", "return", "PrettyPrinter", "(", "indent", "=", "indent", ",", "width", "=", "width", ",", "depth", "=", "depth", ")", ".", "pfor...
https://github.com/ctxis/canape/blob/5f0e03424577296bcc60c2008a60a98ec5307e4b/CANAPE.Scripting/Lib/pprint.py#L58-L60
pymedusa/Medusa
1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38
ext/github/__init__.py
python
enable_console_debug_logging
()
This function sets up a very simple logging configuration (log everything on standard output) that is useful for troubleshooting.
This function sets up a very simple logging configuration (log everything on standard output) that is useful for troubleshooting.
[ "This", "function", "sets", "up", "a", "very", "simple", "logging", "configuration", "(", "log", "everything", "on", "standard", "output", ")", "that", "is", "useful", "for", "troubleshooting", "." ]
def enable_console_debug_logging(): # pragma no cover (Function useful only outside test environment) """ This function sets up a very simple logging configuration (log everything on standard output) that is useful for troubleshooting. """ logger = logging.getLogger("github") logger.setLevel(logging.DEBUG) logger.addHandler(logging.StreamHandler())
[ "def", "enable_console_debug_logging", "(", ")", ":", "# pragma no cover (Function useful only outside test environment)", "logger", "=", "logging", ".", "getLogger", "(", "\"github\"", ")", "logger", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "logger", ".", ...
https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/github/__init__.py#L60-L67
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/celery/app/utils.py
python
Settings.humanize
(self, with_defaults=False, censored=True)
return '\n'.join( '{0}: {1}'.format(key, pretty(value, width=50)) for key, value in items(self.table(with_defaults, censored)))
Return a human readable text showing configuration changes.
Return a human readable text showing configuration changes.
[ "Return", "a", "human", "readable", "text", "showing", "configuration", "changes", "." ]
def humanize(self, with_defaults=False, censored=True): """Return a human readable text showing configuration changes.""" return '\n'.join( '{0}: {1}'.format(key, pretty(value, width=50)) for key, value in items(self.table(with_defaults, censored)))
[ "def", "humanize", "(", "self", ",", "with_defaults", "=", "False", ",", "censored", "=", "True", ")", ":", "return", "'\\n'", ".", "join", "(", "'{0}: {1}'", ".", "format", "(", "key", ",", "pretty", "(", "value", ",", "width", "=", "50", ")", ")", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/celery/app/utils.py#L185-L189
certbot/certbot
30b066f08260b73fc26256b5484a180468b9d0a6
certbot/certbot/interfaces.py
python
AccountStorage.load
(self, account_id: str)
Load an account by its id. :raises .AccountNotFound: if account could not be found :raises .AccountStorageError: if account could not be loaded :returns: The account loaded :rtype: .Account
Load an account by its id.
[ "Load", "an", "account", "by", "its", "id", "." ]
def load(self, account_id: str) -> 'Account': # pragma: no cover """Load an account by its id. :raises .AccountNotFound: if account could not be found :raises .AccountStorageError: if account could not be loaded :returns: The account loaded :rtype: .Account """ raise NotImplementedError()
[ "def", "load", "(", "self", ",", "account_id", ":", "str", ")", "->", "'Account'", ":", "# pragma: no cover", "raise", "NotImplementedError", "(", ")" ]
https://github.com/certbot/certbot/blob/30b066f08260b73fc26256b5484a180468b9d0a6/certbot/certbot/interfaces.py#L43-L53
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
txweb2/stream.py
python
ProducerStream.finish
(self, failure=None)
Called by producer when it is done. If the optional failure argument is passed a Failure instance, the stream will return it as errback on next Deferred.
Called by producer when it is done.
[ "Called", "by", "producer", "when", "it", "is", "done", "." ]
def finish(self, failure=None): """Called by producer when it is done. If the optional failure argument is passed a Failure instance, the stream will return it as errback on next Deferred. """ self.closed = True if not self.buffer: self.length = 0 if self.deferred is not None: deferred = self.deferred self.deferred = None if failure is not None: self.failed = True deferred.errback(failure) else: deferred.callback(None) else: if failure is not None: self.failed = True self.failure = failure
[ "def", "finish", "(", "self", ",", "failure", "=", "None", ")", ":", "self", ".", "closed", "=", "True", "if", "not", "self", ".", "buffer", ":", "self", ".", "length", "=", "0", "if", "self", ".", "deferred", "is", "not", "None", ":", "deferred", ...
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/txweb2/stream.py#L719-L739
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/waf/waf_client.py
python
WafClient.list_network_address_lists
(self, compartment_id, **kwargs)
Gets a list of all NetworkAddressLists in a compartment. :param str compartment_id: (required) The `OCID`__ of the compartment in which to list resources. __ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm :param list[NetworkAddressListLifecycleState] lifecycle_state: (optional) A filter to return only resources that match the given lifecycleState. :param str display_name: (optional) A filter to return only resources that match the entire display name given. :param str id: (optional) A filter to return only the NetworkAddressList with the given `OCID`__. __ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm :param int limit: (optional) The maximum number of items to return. :param str page: (optional) A token representing the position at which to start retrieving results. This must come from the `opc-next-page` header field of a previous response. :param str sort_order: (optional) The sort order to use, either 'ASC' or 'DESC'. Allowed values are: "ASC", "DESC" :param str sort_by: (optional) The field to sort by. Only one sort order may be provided. Default order for timeCreated is descending. Default order for displayName is ascending. If no value is specified timeCreated is default. Allowed values are: "timeCreated", "displayName" :param str opc_request_id: (optional) The client request ID for tracing. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.waf.models.NetworkAddressListCollection` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/waf/list_network_address_lists.py.html>`__ to see an example of how to use list_network_address_lists API.
Gets a list of all NetworkAddressLists in a compartment.
[ "Gets", "a", "list", "of", "all", "NetworkAddressLists", "in", "a", "compartment", "." ]
def list_network_address_lists(self, compartment_id, **kwargs): """ Gets a list of all NetworkAddressLists in a compartment. :param str compartment_id: (required) The `OCID`__ of the compartment in which to list resources. __ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm :param list[NetworkAddressListLifecycleState] lifecycle_state: (optional) A filter to return only resources that match the given lifecycleState. :param str display_name: (optional) A filter to return only resources that match the entire display name given. :param str id: (optional) A filter to return only the NetworkAddressList with the given `OCID`__. __ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm :param int limit: (optional) The maximum number of items to return. :param str page: (optional) A token representing the position at which to start retrieving results. This must come from the `opc-next-page` header field of a previous response. :param str sort_order: (optional) The sort order to use, either 'ASC' or 'DESC'. Allowed values are: "ASC", "DESC" :param str sort_by: (optional) The field to sort by. Only one sort order may be provided. Default order for timeCreated is descending. Default order for displayName is ascending. If no value is specified timeCreated is default. Allowed values are: "timeCreated", "displayName" :param str opc_request_id: (optional) The client request ID for tracing. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.waf.models.NetworkAddressListCollection` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/waf/list_network_address_lists.py.html>`__ to see an example of how to use list_network_address_lists API. """ resource_path = "/networkAddressLists" method = "GET" # Don't accept unknown kwargs expected_kwargs = [ "retry_strategy", "lifecycle_state", "display_name", "id", "limit", "page", "sort_order", "sort_by", "opc_request_id" ] extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs] if extra_kwargs: raise ValueError( "list_network_address_lists got unknown kwargs: {!r}".format(extra_kwargs)) if 'sort_order' in kwargs: sort_order_allowed_values = ["ASC", "DESC"] if kwargs['sort_order'] not in sort_order_allowed_values: raise ValueError( "Invalid value for `sort_order`, must be one of {0}".format(sort_order_allowed_values) ) if 'sort_by' in kwargs: sort_by_allowed_values = ["timeCreated", "displayName"] if kwargs['sort_by'] not in sort_by_allowed_values: raise ValueError( "Invalid value for `sort_by`, must be one of {0}".format(sort_by_allowed_values) ) query_params = { "compartmentId": compartment_id, "lifecycleState": self.base_client.generate_collection_format_param(kwargs.get("lifecycle_state", missing), 'multi'), "displayName": kwargs.get("display_name", missing), "id": kwargs.get("id", missing), "limit": kwargs.get("limit", missing), "page": kwargs.get("page", missing), "sortOrder": kwargs.get("sort_order", missing), "sortBy": kwargs.get("sort_by", missing) } query_params = {k: v for (k, v) in six.iteritems(query_params) if v is not missing and v is not None} header_params = { "accept": "application/json", "content-type": "application/json", "opc-request-id": kwargs.get("opc_request_id", missing) } header_params = {k: v for (k, v) in six.iteritems(header_params) if v is not missing and v is not None} retry_strategy = self.base_client.get_preferred_retry_strategy( operation_retry_strategy=kwargs.get('retry_strategy'), client_retry_strategy=self.retry_strategy ) if retry_strategy: if not isinstance(retry_strategy, retry.NoneRetryStrategy): self.base_client.add_opc_client_retries_header(header_params) retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback) return retry_strategy.make_retrying_call( self.base_client.call_api, resource_path=resource_path, method=method, query_params=query_params, header_params=header_params, response_type="NetworkAddressListCollection") else: return self.base_client.call_api( resource_path=resource_path, method=method, query_params=query_params, header_params=header_params, response_type="NetworkAddressListCollection")
[ "def", "list_network_address_lists", "(", "self", ",", "compartment_id", ",", "*", "*", "kwargs", ")", ":", "resource_path", "=", "\"/networkAddressLists\"", "method", "=", "\"GET\"", "# Don't accept unknown kwargs", "expected_kwargs", "=", "[", "\"retry_strategy\"", ",...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/waf/waf_client.py#L1194-L1327
gunthercox/ChatterBot
4ff8af28567ed446ae796d37c246bb6a14032fe7
chatterbot/comparisons.py
python
LevenshteinDistance.compare
(self, statement_a, statement_b)
return percent
Compare the two input statements. :return: The percent of similarity between the text of the statements. :rtype: float
Compare the two input statements.
[ "Compare", "the", "two", "input", "statements", "." ]
def compare(self, statement_a, statement_b): """ Compare the two input statements. :return: The percent of similarity between the text of the statements. :rtype: float """ # Return 0 if either statement has a falsy text value if not statement_a.text or not statement_b.text: return 0 # Get the lowercase version of both strings statement_a_text = str(statement_a.text.lower()) statement_b_text = str(statement_b.text.lower()) similarity = SequenceMatcher( None, statement_a_text, statement_b_text ) # Calculate a decimal percent of the similarity percent = round(similarity.ratio(), 2) return percent
[ "def", "compare", "(", "self", ",", "statement_a", ",", "statement_b", ")", ":", "# Return 0 if either statement has a falsy text value", "if", "not", "statement_a", ".", "text", "or", "not", "statement_b", ".", "text", ":", "return", "0", "# Get the lowercase version...
https://github.com/gunthercox/ChatterBot/blob/4ff8af28567ed446ae796d37c246bb6a14032fe7/chatterbot/comparisons.py#L32-L57
biopython/biopython
2dd97e71762af7b046d7f7f8a4f1e38db6b06c86
Bio/Phylo/_utils.py
python
to_networkx
(tree)
return G
Convert a Tree object to a networkx graph. The result is useful for graph-oriented analysis, and also interactive plotting with pylab, matplotlib or pygraphviz, though the resulting diagram is usually not ideal for displaying a phylogeny. Requires NetworkX version 0.99 or later.
Convert a Tree object to a networkx graph.
[ "Convert", "a", "Tree", "object", "to", "a", "networkx", "graph", "." ]
def to_networkx(tree): """Convert a Tree object to a networkx graph. The result is useful for graph-oriented analysis, and also interactive plotting with pylab, matplotlib or pygraphviz, though the resulting diagram is usually not ideal for displaying a phylogeny. Requires NetworkX version 0.99 or later. """ try: import networkx except ImportError: raise MissingPythonDependencyError( "Install NetworkX if you want to use to_networkx." ) from None # NB (1/2010): the networkx API stabilized at v.1.0 # 1.0+: edges accept arbitrary data as kwargs, weights are floats # 0.99: edges accept weight as a string, nothing else # pre-0.99: edges accept no additional data # Ubuntu Lucid LTS uses v0.99, let's support everything if networkx.__version__ >= "1.0": def add_edge(graph, n1, n2): graph.add_edge(n1, n2, weight=n2.branch_length or 1.0) # Copy branch color value as hex, if available if hasattr(n2, "color") and n2.color is not None: graph[n1][n2]["color"] = n2.color.to_hex() elif hasattr(n1, "color") and n1.color is not None: # Cascading color attributes graph[n1][n2]["color"] = n1.color.to_hex() n2.color = n1.color # Copy branch weight value (float) if available if hasattr(n2, "width") and n2.width is not None: graph[n1][n2]["width"] = n2.width elif hasattr(n1, "width") and n1.width is not None: # Cascading width attributes graph[n1][n2]["width"] = n1.width n2.width = n1.width elif networkx.__version__ >= "0.99": def add_edge(graph, n1, n2): graph.add_edge(n1, n2, (n2.branch_length or 1.0)) else: def add_edge(graph, n1, n2): graph.add_edge(n1, n2) def build_subgraph(graph, top): """Walk down the Tree, building graphs, edges and nodes.""" for clade in top: graph.add_node(clade.root) add_edge(graph, top.root, clade.root) build_subgraph(graph, clade) if tree.rooted: G = networkx.DiGraph() else: G = networkx.Graph() G.add_node(tree.root) build_subgraph(G, tree.root) return G
[ "def", "to_networkx", "(", "tree", ")", ":", "try", ":", "import", "networkx", "except", "ImportError", ":", "raise", "MissingPythonDependencyError", "(", "\"Install NetworkX if you want to use to_networkx.\"", ")", "from", "None", "# NB (1/2010): the networkx API stabilized ...
https://github.com/biopython/biopython/blob/2dd97e71762af7b046d7f7f8a4f1e38db6b06c86/Bio/Phylo/_utils.py#L19-L82
theotherp/nzbhydra
4b03d7f769384b97dfc60dade4806c0fc987514e
libs/urllib.py
python
urlencode
(query, doseq=0)
return '&'.join(l)
Encode a sequence of two-element tuples or dictionary into a URL query string. If any values in the query arg are sequences and doseq is true, each sequence element is converted to a separate parameter. If the query arg is a sequence of two-element tuples, the order of the parameters in the output will match the order of parameters in the input.
Encode a sequence of two-element tuples or dictionary into a URL query string.
[ "Encode", "a", "sequence", "of", "two", "-", "element", "tuples", "or", "dictionary", "into", "a", "URL", "query", "string", "." ]
def urlencode(query, doseq=0): """Encode a sequence of two-element tuples or dictionary into a URL query string. If any values in the query arg are sequences and doseq is true, each sequence element is converted to a separate parameter. If the query arg is a sequence of two-element tuples, the order of the parameters in the output will match the order of parameters in the input. """ if hasattr(query,"items"): # mapping objects query = query.items() else: # it's a bother at times that strings and string-like objects are # sequences... try: # non-sequence items should not work with len() # non-empty strings will fail this if len(query) and not isinstance(query[0], tuple): raise TypeError # zero-length sequences of all types will get here and succeed, # but that's a minor nit - since the original implementation # allowed empty dicts that type of behavior probably should be # preserved for consistency except TypeError: ty,va,tb = sys.exc_info() raise TypeError, "not a valid non-string sequence or mapping object", tb l = [] if not doseq: # preserve old behavior for k, v in query: k = quote_plus(str(k)) v = quote_plus(str(v)) l.append(k + '=' + v) else: for k, v in query: k = quote_plus(str(k)) if isinstance(v, str): v = quote_plus(v) l.append(k + '=' + v) elif _is_unicode(v): # is there a reasonable way to convert to ASCII? # encode generates a string, but "replace" or "ignore" # lose information and "strict" can raise UnicodeError v = quote_plus(v.encode("ASCII","replace")) l.append(k + '=' + v) else: try: # is this a sufficient test for sequence-ness? len(v) except TypeError: # not a sequence v = quote_plus(str(v)) l.append(k + '=' + v) else: # loop over the sequence for elt in v: l.append(k + '=' + quote_plus(str(elt))) return '&'.join(l)
[ "def", "urlencode", "(", "query", ",", "doseq", "=", "0", ")", ":", "if", "hasattr", "(", "query", ",", "\"items\"", ")", ":", "# mapping objects", "query", "=", "query", ".", "items", "(", ")", "else", ":", "# it's a bother at times that strings and string-li...
https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/urllib.py#L1312-L1373
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/multiprocessing/process.py
python
BaseProcess.terminate
(self)
Terminate process; sends SIGTERM signal or uses TerminateProcess()
Terminate process; sends SIGTERM signal or uses TerminateProcess()
[ "Terminate", "process", ";", "sends", "SIGTERM", "signal", "or", "uses", "TerminateProcess", "()" ]
def terminate(self): ''' Terminate process; sends SIGTERM signal or uses TerminateProcess() ''' self._check_closed() self._popen.terminate()
[ "def", "terminate", "(", "self", ")", ":", "self", ".", "_check_closed", "(", ")", "self", ".", "_popen", ".", "terminate", "(", ")" ]
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/multiprocessing/process.py#L139-L144
CGATOxford/cgat
326aad4694bdfae8ddc194171bb5d73911243947
CGAT/IndexedGenome.py
python
Quicksect.get
(self, contig, start, end)
return [(x.start, x.end, x.value) for x in self.mIndex[contig].find(start, end)]
return intervals overlapping with key.
return intervals overlapping with key.
[ "return", "intervals", "overlapping", "with", "key", "." ]
def get(self, contig, start, end): '''return intervals overlapping with key.''' if contig not in self.mIndex: raise KeyError("contig %s not in index" % contig) return [(x.start, x.end, x.value) for x in self.mIndex[contig].find(start, end)]
[ "def", "get", "(", "self", ",", "contig", ",", "start", ",", "end", ")", ":", "if", "contig", "not", "in", "self", ".", "mIndex", ":", "raise", "KeyError", "(", "\"contig %s not in index\"", "%", "contig", ")", "return", "[", "(", "x", ".", "start", ...
https://github.com/CGATOxford/cgat/blob/326aad4694bdfae8ddc194171bb5d73911243947/CGAT/IndexedGenome.py#L119-L125
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/pip/_internal/operations/prepare.py
python
RequirementPreparer.__init__
(self, build_dir, download_dir, src_dir, wheel_download_dir, progress_bar, build_isolation, req_tracker)
[]
def __init__(self, build_dir, download_dir, src_dir, wheel_download_dir, progress_bar, build_isolation, req_tracker): super(RequirementPreparer, self).__init__() self.src_dir = src_dir self.build_dir = build_dir self.req_tracker = req_tracker # Where still packed archives should be written to. If None, they are # not saved, and are deleted immediately after unpacking. self.download_dir = download_dir # Where still-packed .whl files should be written to. If None, they are # written to the download_dir parameter. Separate to download_dir to # permit only keeping wheel archives for pip wheel. if wheel_download_dir: wheel_download_dir = normalize_path(wheel_download_dir) self.wheel_download_dir = wheel_download_dir # NOTE # download_dir and wheel_download_dir overlap semantically and may # be combined if we're willing to have non-wheel archives present in # the wheelhouse output by 'pip wheel'. self.progress_bar = progress_bar # Is build isolation allowed? self.build_isolation = build_isolation
[ "def", "__init__", "(", "self", ",", "build_dir", ",", "download_dir", ",", "src_dir", ",", "wheel_download_dir", ",", "progress_bar", ",", "build_isolation", ",", "req_tracker", ")", ":", "super", "(", "RequirementPreparer", ",", "self", ")", ".", "__init__", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pip/_internal/operations/prepare.py#L143-L170
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/packages/site-packages/docutils/parsers/rst/directives/__init__.py
python
choice
(argument, values)
Directive option utility function, supplied to enable options whose argument must be a member of a finite set of possible values (must be lower case). A custom conversion function must be written to use it. For example:: from docutils.parsers.rst import directives def yesno(argument): return directives.choice(argument, ('yes', 'no')) Raise ``ValueError`` if no argument is found or if the argument's value is not valid (not an entry in the supplied list).
Directive option utility function, supplied to enable options whose argument must be a member of a finite set of possible values (must be lower case). A custom conversion function must be written to use it. For example::
[ "Directive", "option", "utility", "function", "supplied", "to", "enable", "options", "whose", "argument", "must", "be", "a", "member", "of", "a", "finite", "set", "of", "possible", "values", "(", "must", "be", "lower", "case", ")", ".", "A", "custom", "con...
def choice(argument, values): """ Directive option utility function, supplied to enable options whose argument must be a member of a finite set of possible values (must be lower case). A custom conversion function must be written to use it. For example:: from docutils.parsers.rst import directives def yesno(argument): return directives.choice(argument, ('yes', 'no')) Raise ``ValueError`` if no argument is found or if the argument's value is not valid (not an entry in the supplied list). """ try: value = argument.lower().strip() except AttributeError: raise ValueError('must supply an argument; choose from %s' % format_values(values)) if value in values: return value else: raise ValueError('"%s" unknown; choose from %s' % (argument, format_values(values)))
[ "def", "choice", "(", "argument", ",", "values", ")", ":", "try", ":", "value", "=", "argument", ".", "lower", "(", ")", ".", "strip", "(", ")", "except", "AttributeError", ":", "raise", "ValueError", "(", "'must supply an argument; choose from %s'", "%", "f...
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/packages/site-packages/docutils/parsers/rst/directives/__init__.py#L376-L400
mesonbuild/meson
a22d0f9a0a787df70ce79b05d0c45de90a970048
mesonbuild/compilers/c.py
python
Xc16CCompiler.get_include_args
(self, path: str, is_system: bool)
return ['-I' + path]
[]
def get_include_args(self, path: str, is_system: bool) -> T.List[str]: if path == '': path = '.' return ['-I' + path]
[ "def", "get_include_args", "(", "self", ",", "path", ":", "str", ",", "is_system", ":", "bool", ")", "->", "T", ".", "List", "[", "str", "]", ":", "if", "path", "==", "''", ":", "path", "=", "'.'", "return", "[", "'-I'", "+", "path", "]" ]
https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/mesonbuild/compilers/c.py#L637-L640
espnet/espnet
ea411f3f627b8f101c211e107d0ff7053344ac80
espnet2/lm/seq_rnn_lm.py
python
SequentialRNNLM.score
( self, y: torch.Tensor, state: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]], x: torch.Tensor, )
return logp, new_state
Score new token. Args: y: 1D torch.int64 prefix tokens. state: Scorer state for prefix tokens x: 2D encoder feature that generates ys. Returns: Tuple of torch.float32 scores for next token (n_vocab) and next state for ys
Score new token.
[ "Score", "new", "token", "." ]
def score( self, y: torch.Tensor, state: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]], x: torch.Tensor, ) -> Tuple[torch.Tensor, Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]]: """Score new token. Args: y: 1D torch.int64 prefix tokens. state: Scorer state for prefix tokens x: 2D encoder feature that generates ys. Returns: Tuple of torch.float32 scores for next token (n_vocab) and next state for ys """ y, new_state = self(y[-1].view(1, 1), state) logp = y.log_softmax(dim=-1).view(-1) return logp, new_state
[ "def", "score", "(", "self", ",", "y", ":", "torch", ".", "Tensor", ",", "state", ":", "Union", "[", "torch", ".", "Tensor", ",", "Tuple", "[", "torch", ".", "Tensor", ",", "torch", ".", "Tensor", "]", "]", ",", "x", ":", "torch", ".", "Tensor", ...
https://github.com/espnet/espnet/blob/ea411f3f627b8f101c211e107d0ff7053344ac80/espnet2/lm/seq_rnn_lm.py#L107-L128
k0retux/fuddly
fd2c4d0c9c7db49e4de654ce545f1661e6c4e8fd
framework/node_builder.py
python
State.init_specific
(self)
Can be overridden to express additional initializations
Can be overridden to express additional initializations
[ "Can", "be", "overridden", "to", "express", "additional", "initializations" ]
def init_specific(self): """ Can be overridden to express additional initializations """ pass
[ "def", "init_specific", "(", "self", ")", ":", "pass" ]
https://github.com/k0retux/fuddly/blob/fd2c4d0c9c7db49e4de654ce545f1661e6c4e8fd/framework/node_builder.py#L769-L773
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/arrow/locales.py
python
OdiaLocale._ordinal_number
(self, n: int)
return ""
[]
def _ordinal_number(self, n: int) -> str: if n > 10 or n == 0: return f"{n}ତମ" if n in [1, 5, 7, 8, 9, 10]: return f"{n}ମ" if n in [2, 3]: return f"{n}ୟ" if n == 4: return f"{n}ର୍ଥ" if n == 6: return f"{n}ଷ୍ଠ" return ""
[ "def", "_ordinal_number", "(", "self", ",", "n", ":", "int", ")", "->", "str", ":", "if", "n", ">", "10", "or", "n", "==", "0", ":", "return", "f\"{n}ତମ\"", "if", "n", "in", "[", "1", ",", "5", ",", "7", ",", "8", ",", "9", ",", "10", "]", ...
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/arrow/locales.py#L5180-L5191
zim-desktop-wiki/zim-desktop-wiki
fe717d7ee64e5c06d90df90eb87758e5e72d25c5
zim/gui/applications.py
python
edit_config_file
(widget, configfile)
Edit a config file in an external editor. See L{edit_file()} for details. @param widget: a C{gtk} widget to use as parent for dialogs or C{None} @param configfile: a L{ConfigFile} object
Edit a config file in an external editor. See L{edit_file()} for details.
[ "Edit", "a", "config", "file", "in", "an", "external", "editor", ".", "See", "L", "{", "edit_file", "()", "}", "for", "details", "." ]
def edit_config_file(widget, configfile): '''Edit a config file in an external editor. See L{edit_file()} for details. @param widget: a C{gtk} widget to use as parent for dialogs or C{None} @param configfile: a L{ConfigFile} object ''' configfile.touch() edit_file(widget, configfile.file, istextfile=True)
[ "def", "edit_config_file", "(", "widget", ",", "configfile", ")", ":", "configfile", ".", "touch", "(", ")", "edit_file", "(", "widget", ",", "configfile", ".", "file", ",", "istextfile", "=", "True", ")" ]
https://github.com/zim-desktop-wiki/zim-desktop-wiki/blob/fe717d7ee64e5c06d90df90eb87758e5e72d25c5/zim/gui/applications.py#L681-L688
SCSSoftware/BlenderTools
96f323d3bdf2d8cb8ed7f882dcdf036277a802dd
addon/io_scs_tools/exp/pip/sign.py
python
Sign.set_position
(self, position)
Sets position of the sign. :param position: position of the sign :type position: tuple | mathutils.Vector
Sets position of the sign.
[ "Sets", "position", "of", "the", "sign", "." ]
def set_position(self, position): """Sets position of the sign. :param position: position of the sign :type position: tuple | mathutils.Vector """ self.__position = position
[ "def", "set_position", "(", "self", ",", "position", ")", ":", "self", ".", "__position", "=", "position" ]
https://github.com/SCSSoftware/BlenderTools/blob/96f323d3bdf2d8cb8ed7f882dcdf036277a802dd/addon/io_scs_tools/exp/pip/sign.py#L53-L59
cagbal/ros_people_object_detection_tensorflow
982ffd4a54b8059638f5cd4aa167299c7fc9e61f
src/object_detection/eval_util.py
python
visualize_detection_results
(result_dict, tag, global_step, categories, summary_dir='', export_dir='', agnostic_mode=False, show_groundtruth=False, groundtruth_box_visualization_color='black', min_score_thresh=.5, max_num_predictions=20, skip_scores=False, skip_labels=False, keep_image_id_for_visualization_export=False)
Visualizes detection results and writes visualizations to image summaries. This function visualizes an image with its detected bounding boxes and writes to image summaries which can be viewed on tensorboard. It optionally also writes images to a directory. In the case of missing entry in the label map, unknown class name in the visualization is shown as "N/A". Args: result_dict: a dictionary holding groundtruth and detection data corresponding to each image being evaluated. The following keys are required: 'original_image': a numpy array representing the image with shape [1, height, width, 3] 'detection_boxes': a numpy array of shape [N, 4] 'detection_scores': a numpy array of shape [N] 'detection_classes': a numpy array of shape [N] The following keys are optional: 'groundtruth_boxes': a numpy array of shape [N, 4] 'groundtruth_keypoints': a numpy array of shape [N, num_keypoints, 2] Detections are assumed to be provided in decreasing order of score and for display, and we assume that scores are probabilities between 0 and 1. tag: tensorboard tag (string) to associate with image. global_step: global step at which the visualization are generated. categories: a list of dictionaries representing all possible categories. Each dict in this list has the following keys: 'id': (required) an integer id uniquely identifying this category 'name': (required) string representing category name e.g., 'cat', 'dog', 'pizza' 'supercategory': (optional) string representing the supercategory e.g., 'animal', 'vehicle', 'food', etc summary_dir: the output directory to which the image summaries are written. export_dir: the output directory to which images are written. If this is empty (default), then images are not exported. agnostic_mode: boolean (default: False) controlling whether to evaluate in class-agnostic mode or not. show_groundtruth: boolean (default: False) controlling whether to show groundtruth boxes in addition to detected boxes groundtruth_box_visualization_color: box color for visualizing groundtruth boxes min_score_thresh: minimum score threshold for a box to be visualized max_num_predictions: maximum number of detections to visualize skip_scores: whether to skip score when drawing a single detection skip_labels: whether to skip label when drawing a single detection keep_image_id_for_visualization_export: whether to keep image identifier in filename when exported to export_dir Raises: ValueError: if result_dict does not contain the expected keys (i.e., 'original_image', 'detection_boxes', 'detection_scores', 'detection_classes')
Visualizes detection results and writes visualizations to image summaries.
[ "Visualizes", "detection", "results", "and", "writes", "visualizations", "to", "image", "summaries", "." ]
def visualize_detection_results(result_dict, tag, global_step, categories, summary_dir='', export_dir='', agnostic_mode=False, show_groundtruth=False, groundtruth_box_visualization_color='black', min_score_thresh=.5, max_num_predictions=20, skip_scores=False, skip_labels=False, keep_image_id_for_visualization_export=False): """Visualizes detection results and writes visualizations to image summaries. This function visualizes an image with its detected bounding boxes and writes to image summaries which can be viewed on tensorboard. It optionally also writes images to a directory. In the case of missing entry in the label map, unknown class name in the visualization is shown as "N/A". Args: result_dict: a dictionary holding groundtruth and detection data corresponding to each image being evaluated. The following keys are required: 'original_image': a numpy array representing the image with shape [1, height, width, 3] 'detection_boxes': a numpy array of shape [N, 4] 'detection_scores': a numpy array of shape [N] 'detection_classes': a numpy array of shape [N] The following keys are optional: 'groundtruth_boxes': a numpy array of shape [N, 4] 'groundtruth_keypoints': a numpy array of shape [N, num_keypoints, 2] Detections are assumed to be provided in decreasing order of score and for display, and we assume that scores are probabilities between 0 and 1. tag: tensorboard tag (string) to associate with image. global_step: global step at which the visualization are generated. categories: a list of dictionaries representing all possible categories. Each dict in this list has the following keys: 'id': (required) an integer id uniquely identifying this category 'name': (required) string representing category name e.g., 'cat', 'dog', 'pizza' 'supercategory': (optional) string representing the supercategory e.g., 'animal', 'vehicle', 'food', etc summary_dir: the output directory to which the image summaries are written. export_dir: the output directory to which images are written. If this is empty (default), then images are not exported. agnostic_mode: boolean (default: False) controlling whether to evaluate in class-agnostic mode or not. show_groundtruth: boolean (default: False) controlling whether to show groundtruth boxes in addition to detected boxes groundtruth_box_visualization_color: box color for visualizing groundtruth boxes min_score_thresh: minimum score threshold for a box to be visualized max_num_predictions: maximum number of detections to visualize skip_scores: whether to skip score when drawing a single detection skip_labels: whether to skip label when drawing a single detection keep_image_id_for_visualization_export: whether to keep image identifier in filename when exported to export_dir Raises: ValueError: if result_dict does not contain the expected keys (i.e., 'original_image', 'detection_boxes', 'detection_scores', 'detection_classes') """ detection_fields = fields.DetectionResultFields input_fields = fields.InputDataFields if not set([ input_fields.original_image, detection_fields.detection_boxes, detection_fields.detection_scores, detection_fields.detection_classes, ]).issubset(set(result_dict.keys())): raise ValueError('result_dict does not contain all expected keys.') if show_groundtruth and input_fields.groundtruth_boxes not in result_dict: raise ValueError('If show_groundtruth is enabled, result_dict must contain ' 'groundtruth_boxes.') logging.info('Creating detection visualizations.') category_index = label_map_util.create_category_index(categories) image = np.squeeze(result_dict[input_fields.original_image], axis=0) detection_boxes = result_dict[detection_fields.detection_boxes] detection_scores = result_dict[detection_fields.detection_scores] detection_classes = np.int32((result_dict[ detection_fields.detection_classes])) detection_keypoints = result_dict.get(detection_fields.detection_keypoints) detection_masks = result_dict.get(detection_fields.detection_masks) detection_boundaries = result_dict.get(detection_fields.detection_boundaries) # Plot groundtruth underneath detections if show_groundtruth: groundtruth_boxes = result_dict[input_fields.groundtruth_boxes] groundtruth_keypoints = result_dict.get(input_fields.groundtruth_keypoints) vis_utils.visualize_boxes_and_labels_on_image_array( image=image, boxes=groundtruth_boxes, classes=None, scores=None, category_index=category_index, keypoints=groundtruth_keypoints, use_normalized_coordinates=False, max_boxes_to_draw=None, groundtruth_box_visualization_color=groundtruth_box_visualization_color) vis_utils.visualize_boxes_and_labels_on_image_array( image, detection_boxes, detection_classes, detection_scores, category_index, instance_masks=detection_masks, instance_boundaries=detection_boundaries, keypoints=detection_keypoints, use_normalized_coordinates=False, max_boxes_to_draw=max_num_predictions, min_score_thresh=min_score_thresh, agnostic_mode=agnostic_mode, skip_scores=skip_scores, skip_labels=skip_labels) if export_dir: if keep_image_id_for_visualization_export and result_dict[fields. InputDataFields() .key]: export_path = os.path.join(export_dir, 'export-{}-{}.png'.format( tag, result_dict[fields.InputDataFields().key])) else: export_path = os.path.join(export_dir, 'export-{}.png'.format(tag)) vis_utils.save_image_array_as_png(image, export_path) summary = tf.Summary(value=[ tf.Summary.Value( tag=tag, image=tf.Summary.Image( encoded_image_string=vis_utils.encode_image_array_as_png_str( image))) ]) summary_writer = tf.summary.FileWriterCache.get(summary_dir) summary_writer.add_summary(summary, global_step) logging.info('Detection visualizations written to summary with tag %s.', tag)
[ "def", "visualize_detection_results", "(", "result_dict", ",", "tag", ",", "global_step", ",", "categories", ",", "summary_dir", "=", "''", ",", "export_dir", "=", "''", ",", "agnostic_mode", "=", "False", ",", "show_groundtruth", "=", "False", ",", "groundtruth...
https://github.com/cagbal/ros_people_object_detection_tensorflow/blob/982ffd4a54b8059638f5cd4aa167299c7fc9e61f/src/object_detection/eval_util.py#L56-L194
modflowpy/flopy
eecd1ad193c5972093c9712e5c4b7a83284f0688
flopy/utils/postprocessing.py
python
get_specific_discharge
( vectors, model, head=None, position="centers", )
return qx, qy, qz
Get the discharge vector at cell centers at a given time. For "classical" MODFLOW versions, we calculate it from the flow rate across cell faces. For MODFLOW 6, we directly take it from MODFLOW output (this requires setting the option "save_specific_discharge" in the NPF package). Parameters ---------- vectors : tuple, np.recarray either a tuple of (flow right face, flow front face, flow lower face) numpy arrays from a MODFLOW-2005 compatible Cell Budget File or a specific discharge recarray from a MODFLOW 6 Cell Budget File model : object flopy model object head : np.ndarray numpy array of head values for a specific model position : str Position at which the specific discharge will be calculated. Possible values are "centers" (default), "faces" and "vertices". Returns ------- (qx, qy, qz) : tuple Discharge vector. qx, qy, qz are ndarrays of size (nlay, nrow, ncol) for a structured grid or size (nlay, ncpl) for an unstructured grid. The sign of qy is such that the y axis is considered to increase in the north direction. The sign of qz is such that the z axis is considered to increase in the upward direction. Note: if a head array is provided, inactive and dry cells are set to NaN.
Get the discharge vector at cell centers at a given time. For "classical" MODFLOW versions, we calculate it from the flow rate across cell faces. For MODFLOW 6, we directly take it from MODFLOW output (this requires setting the option "save_specific_discharge" in the NPF package).
[ "Get", "the", "discharge", "vector", "at", "cell", "centers", "at", "a", "given", "time", ".", "For", "classical", "MODFLOW", "versions", "we", "calculate", "it", "from", "the", "flow", "rate", "across", "cell", "faces", ".", "For", "MODFLOW", "6", "we", ...
def get_specific_discharge( vectors, model, head=None, position="centers", ): """ Get the discharge vector at cell centers at a given time. For "classical" MODFLOW versions, we calculate it from the flow rate across cell faces. For MODFLOW 6, we directly take it from MODFLOW output (this requires setting the option "save_specific_discharge" in the NPF package). Parameters ---------- vectors : tuple, np.recarray either a tuple of (flow right face, flow front face, flow lower face) numpy arrays from a MODFLOW-2005 compatible Cell Budget File or a specific discharge recarray from a MODFLOW 6 Cell Budget File model : object flopy model object head : np.ndarray numpy array of head values for a specific model position : str Position at which the specific discharge will be calculated. Possible values are "centers" (default), "faces" and "vertices". Returns ------- (qx, qy, qz) : tuple Discharge vector. qx, qy, qz are ndarrays of size (nlay, nrow, ncol) for a structured grid or size (nlay, ncpl) for an unstructured grid. The sign of qy is such that the y axis is considered to increase in the north direction. The sign of qz is such that the z axis is considered to increase in the upward direction. Note: if a head array is provided, inactive and dry cells are set to NaN. """ classical_budget = False spdis, tqx, tqy, tqz = None, None, None, None modelgrid = model.modelgrid if head is not None: head.shape = modelgrid.shape if isinstance(vectors, (list, tuple)): classical_budget = True for ix, vector in enumerate(vectors): if vector is None: continue else: tshp = list(modelgrid.shape)[::-1] tshp[ix] += 1 ext_shape = tuple(tshp[::-1]) break if vectors[ix].shape == modelgrid.shape: tqx = np.zeros( (modelgrid.nlay, modelgrid.nrow, modelgrid.ncol + 1), dtype=np.float32, ) tqy = np.zeros( (modelgrid.nlay, modelgrid.nrow + 1, modelgrid.ncol), dtype=np.float32, ) tqz = np.zeros( (modelgrid.nlay + 1, modelgrid.nrow, modelgrid.ncol), dtype=np.float32, ) if vectors[0] is not None: tqx[:, :, 1:] = vectors[0] if vectors[1] is not None: tqy[:, 1:, :] = -vectors[1] if len(vectors) > 2 and vectors[2] is not None: tqz[1:, :, :] = -vectors[2] elif vectors[ix].shape == ext_shape: if vectors[0] is not None: tqx = vectors[0] if vectors[1] is not None: tqy = vectors[1] if len(vectors) > 2 and vectors[2] is not None: tqz = vectors[2] else: raise IndexError( "Classical budget components must have " "the same shape as the modelgrid" ) else: spdis = vectors if classical_budget: # get saturated thickness (head - bottom elev for unconfined layer) if head is None: sat_thk = modelgrid.remove_confining_beds(modelgrid.thick) else: sat_thk = modelgrid.saturated_thick( head, mask=[model.hdry, model.hnoflo] ) sat_thk.shape = modelgrid.shape # inform modelgrid of no-flow and dry cells modelgrid = model.modelgrid if modelgrid._idomain is None: modelgrid._idomain = model.dis.ibound if head is not None: noflo_or_dry = np.logical_or( head == model.hnoflo, head == model.hdry ) modelgrid._idomain[noflo_or_dry] = 0 # get cross section areas along x delc = np.reshape(modelgrid.delc, (1, modelgrid.nrow, 1)) cross_area_x = delc * sat_thk # get cross section areas along y delr = np.reshape(modelgrid.delr, (1, 1, modelgrid.ncol)) cross_area_y = delr * sat_thk # get cross section areas along z cross_area_z = np.ones(modelgrid.shape) * delc * delr # calculate qx, qy, qz if position == "centers": qx = np.zeros(modelgrid.shape, dtype=np.float32) qy = np.zeros(modelgrid.shape, dtype=np.float32) cross_area_x = ( delc[:] * 0.5 * (sat_thk[:, :, :-1] + sat_thk[:, :, 1:]) ) cross_area_y = ( delr * 0.5 * (sat_thk[:, 1:, :] + sat_thk[:, :-1, :]) ) qx[:, :, 1:] = ( 0.5 * (tqx[:, :, 2:] + tqx[:, :, 1:-1]) / cross_area_x ) qx[:, :, 0] = 0.5 * tqx[:, :, 1] / cross_area_x[:, :, 0] qy[:, 1:, :] = ( 0.5 * (tqy[:, 2:, :] + tqy[:, 1:-1, :]) / cross_area_y ) qy[:, 0, :] = 0.5 * tqy[:, 1, :] / cross_area_y[:, 0, :] qz = 0.5 * (tqz[1:, :, :] + tqz[:-1, :, :]) / cross_area_z elif position == "faces" or position == "vertices": cross_area_x = modelgrid.array_at_faces(cross_area_x, "x") cross_area_y = modelgrid.array_at_faces(cross_area_y, "y") cross_area_z = modelgrid.array_at_faces(cross_area_z, "z") qx = tqx / cross_area_x qy = tqy / cross_area_y qz = tqz / cross_area_z else: raise ValueError(f'"{position}" is not a valid value for position') if position == "vertices": qx = modelgrid.array_at_verts(qx) qy = modelgrid.array_at_verts(qy) qz = modelgrid.array_at_verts(qz) else: nnodes = model.modelgrid.nnodes qx = np.full((nnodes), np.nan, dtype=np.float64) qy = np.full((nnodes), np.nan, dtype=np.float64) qz = np.full((nnodes), np.nan, dtype=np.float64) idx = np.array(spdis["node"]) - 1 qx[idx] = spdis["qx"] qy[idx] = spdis["qy"] qz[idx] = spdis["qz"] qx.shape = modelgrid.shape qy.shape = modelgrid.shape qz.shape = modelgrid.shape # set no-flow and dry cells to NaN if head is not None and position == "centers": noflo_or_dry = np.logical_or(head == model.hnoflo, head == model.hdry) qx[noflo_or_dry] = np.nan qy[noflo_or_dry] = np.nan qz[noflo_or_dry] = np.nan return qx, qy, qz
[ "def", "get_specific_discharge", "(", "vectors", ",", "model", ",", "head", "=", "None", ",", "position", "=", "\"centers\"", ",", ")", ":", "classical_budget", "=", "False", "spdis", ",", "tqx", ",", "tqy", ",", "tqz", "=", "None", ",", "None", ",", "...
https://github.com/modflowpy/flopy/blob/eecd1ad193c5972093c9712e5c4b7a83284f0688/flopy/utils/postprocessing.py#L543-L724
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/modular/modform/cuspidal_submodule.py
python
CuspidalSubmodule_wt1_gH._transformation_matrix
(self)
return self.__transformation_matrix
r""" Return the transformation matrix between a basis of Galois orbits of forms with character, and the echelon-form basis. EXAMPLES:: sage: CuspForms(GammaH(31, [7]), 1)._transformation_matrix() [1] sage: CuspForms(GammaH(124, [33]), 1)._transformation_matrix() # long time [ 1 1 0 0 0 0 1] [ 0 0 0 0 0 1 0] [ 1 0 1 1 -1 -1 1] [ 0 0 0 0 0 0 1] [ 0 1 0 0 0 0 0] [ 1 0 0 0 -1 0 1] [ 0 0 1 0 0 -1 0]
r""" Return the transformation matrix between a basis of Galois orbits of forms with character, and the echelon-form basis.
[ "r", "Return", "the", "transformation", "matrix", "between", "a", "basis", "of", "Galois", "orbits", "of", "forms", "with", "character", "and", "the", "echelon", "-", "form", "basis", "." ]
def _transformation_matrix(self): r""" Return the transformation matrix between a basis of Galois orbits of forms with character, and the echelon-form basis. EXAMPLES:: sage: CuspForms(GammaH(31, [7]), 1)._transformation_matrix() [1] sage: CuspForms(GammaH(124, [33]), 1)._transformation_matrix() # long time [ 1 1 0 0 0 0 1] [ 0 0 0 0 0 1 0] [ 1 0 1 1 -1 -1 1] [ 0 0 0 0 0 0 1] [ 0 1 0 0 0 0 0] [ 1 0 0 0 -1 0 1] [ 0 0 1 0 0 -1 0] """ self.q_expansion_basis() # triggers iterative computation return self.__transformation_matrix
[ "def", "_transformation_matrix", "(", "self", ")", ":", "self", ".", "q_expansion_basis", "(", ")", "# triggers iterative computation", "return", "self", ".", "__transformation_matrix" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/modular/modform/cuspidal_submodule.py#L436-L455
gem/oq-engine
1bdb88f3914e390abcbd285600bfd39477aae47c
openquake/hazardlib/mfd/truncated_gr.py
python
TruncatedGRMFD._set_a
(self, tmr)
Recalculate an ``a`` value preserving a total moment rate ``tmr`` :: a = (log10((tmr * bi) / (10 ** (bi*max_mag) - 10 ** (bi*min_mag))) - 9.05 - log10(b)) where ``bi = 1.5 - b``. If ``bi == 0`` the following formula is used: a = log10(tmr / (max_mag - min_mag)) - 9.05 - log10(b)
Recalculate an ``a`` value preserving a total moment rate ``tmr`` ::
[ "Recalculate", "an", "a", "value", "preserving", "a", "total", "moment", "rate", "tmr", "::" ]
def _set_a(self, tmr): """ Recalculate an ``a`` value preserving a total moment rate ``tmr`` :: a = (log10((tmr * bi) / (10 ** (bi*max_mag) - 10 ** (bi*min_mag))) - 9.05 - log10(b)) where ``bi = 1.5 - b``. If ``bi == 0`` the following formula is used: a = log10(tmr / (max_mag - min_mag)) - 9.05 - log10(b) """ bi = 1.5 - self.b_val if bi == 0.0: self.a_val = (math.log10(tmr / (self.max_mag - self.min_mag)) - 9.05 - math.log10(self.b_val)) else: self.a_val = (math.log10(tmr * bi / (10 ** (bi * self.max_mag) - 10 ** (bi * self.min_mag))) - 9.05 - math.log10(self.b_val))
[ "def", "_set_a", "(", "self", ",", "tmr", ")", ":", "bi", "=", "1.5", "-", "self", ".", "b_val", "if", "bi", "==", "0.0", ":", "self", ".", "a_val", "=", "(", "math", ".", "log10", "(", "tmr", "/", "(", "self", ".", "max_mag", "-", "self", "....
https://github.com/gem/oq-engine/blob/1bdb88f3914e390abcbd285600bfd39477aae47c/openquake/hazardlib/mfd/truncated_gr.py#L189-L209
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/Ubuntu_12/paramiko/channel.py
python
Channel.resize_pty
(self, width=80, height=24, width_pixels=0, height_pixels=0)
Resize the pseudo-terminal. This can be used to change the width and height of the terminal emulation created in a previous L{get_pty} call. @param width: new width (in characters) of the terminal screen @type width: int @param height: new height (in characters) of the terminal screen @type height: int @param width_pixels: new width (in pixels) of the terminal screen @type width_pixels: int @param height_pixels: new height (in pixels) of the terminal screen @type height_pixels: int @raise SSHException: if the request was rejected or the channel was closed
Resize the pseudo-terminal. This can be used to change the width and height of the terminal emulation created in a previous L{get_pty} call.
[ "Resize", "the", "pseudo", "-", "terminal", ".", "This", "can", "be", "used", "to", "change", "the", "width", "and", "height", "of", "the", "terminal", "emulation", "created", "in", "a", "previous", "L", "{", "get_pty", "}", "call", "." ]
def resize_pty(self, width=80, height=24, width_pixels=0, height_pixels=0): """ Resize the pseudo-terminal. This can be used to change the width and height of the terminal emulation created in a previous L{get_pty} call. @param width: new width (in characters) of the terminal screen @type width: int @param height: new height (in characters) of the terminal screen @type height: int @param width_pixels: new width (in pixels) of the terminal screen @type width_pixels: int @param height_pixels: new height (in pixels) of the terminal screen @type height_pixels: int @raise SSHException: if the request was rejected or the channel was closed """ if self.closed or self.eof_received or self.eof_sent or not self.active: raise SSHException('Channel is not open') m = Message() m.add_byte(chr(MSG_CHANNEL_REQUEST)) m.add_int(self.remote_chanid) m.add_string('window-change') m.add_boolean(False) m.add_int(width) m.add_int(height) m.add_int(width_pixels) m.add_int(height_pixels) self.transport._send_user_message(m)
[ "def", "resize_pty", "(", "self", ",", "width", "=", "80", ",", "height", "=", "24", ",", "width_pixels", "=", "0", ",", "height_pixels", "=", "0", ")", ":", "if", "self", ".", "closed", "or", "self", ".", "eof_received", "or", "self", ".", "eof_sent...
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/Ubuntu_12/paramiko/channel.py#L247-L275
wistbean/learn_python3_spider
73c873f4845f4385f097e5057407d03dd37a117b
stackoverflow/venv/lib/python3.6/site-packages/pymongo/collection.py
python
Collection.delete_many
(self, filter, collation=None, session=None)
return DeleteResult( self._delete_retryable( filter, True, write_concern=write_concern, collation=collation, session=session), write_concern.acknowledged)
Delete one or more documents matching the filter. >>> db.test.count_documents({'x': 1}) 3 >>> result = db.test.delete_many({'x': 1}) >>> result.deleted_count 3 >>> db.test.count_documents({'x': 1}) 0 :Parameters: - `filter`: A query that matches the documents to delete. - `collation` (optional): An instance of :class:`~pymongo.collation.Collation`. This option is only supported on MongoDB 3.4 and above. - `session` (optional): a :class:`~pymongo.client_session.ClientSession`. :Returns: - An instance of :class:`~pymongo.results.DeleteResult`. .. versionchanged:: 3.6 Added ``session`` parameter. .. versionchanged:: 3.4 Added the `collation` option. .. versionadded:: 3.0
Delete one or more documents matching the filter.
[ "Delete", "one", "or", "more", "documents", "matching", "the", "filter", "." ]
def delete_many(self, filter, collation=None, session=None): """Delete one or more documents matching the filter. >>> db.test.count_documents({'x': 1}) 3 >>> result = db.test.delete_many({'x': 1}) >>> result.deleted_count 3 >>> db.test.count_documents({'x': 1}) 0 :Parameters: - `filter`: A query that matches the documents to delete. - `collation` (optional): An instance of :class:`~pymongo.collation.Collation`. This option is only supported on MongoDB 3.4 and above. - `session` (optional): a :class:`~pymongo.client_session.ClientSession`. :Returns: - An instance of :class:`~pymongo.results.DeleteResult`. .. versionchanged:: 3.6 Added ``session`` parameter. .. versionchanged:: 3.4 Added the `collation` option. .. versionadded:: 3.0 """ write_concern = self._write_concern_for(session) return DeleteResult( self._delete_retryable( filter, True, write_concern=write_concern, collation=collation, session=session), write_concern.acknowledged)
[ "def", "delete_many", "(", "self", ",", "filter", ",", "collation", "=", "None", ",", "session", "=", "None", ")", ":", "write_concern", "=", "self", ".", "_write_concern_for", "(", "session", ")", "return", "DeleteResult", "(", "self", ".", "_delete_retryab...
https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/pymongo/collection.py#L1205-L1241
fossasia/x-mario-center
fe67afe28d995dcf4e2498e305825a4859566172
softwarecenter/ui/gtk3/dialogs/dependency_dialogs.py
python
confirm_install
(parent, datadir, app, db, icons)
return _confirm_internal(parent, datadir, app, db, icons, primary, button_text, depends, cache)
Confirm install of the given app (currently only shows a dialog if a installed app needs to be removed in order to install the application)
Confirm install of the given app
[ "Confirm", "install", "of", "the", "given", "app" ]
def confirm_install(parent, datadir, app, db, icons): """Confirm install of the given app (currently only shows a dialog if a installed app needs to be removed in order to install the application) """ cache = db._aptcache distro = get_distro() appdetails = app.get_details(db) if not appdetails.pkg: return True depends = cache.get_packages_removed_on_install(appdetails.pkg) if not depends: return True (primary, button_text) = distro.get_install_warning_text(cache, appdetails.pkg, app.name, depends) return _confirm_internal(parent, datadir, app, db, icons, primary, button_text, depends, cache)
[ "def", "confirm_install", "(", "parent", ",", "datadir", ",", "app", ",", "db", ",", "icons", ")", ":", "cache", "=", "db", ".", "_aptcache", "distro", "=", "get_distro", "(", ")", "appdetails", "=", "app", ".", "get_details", "(", "db", ")", "if", "...
https://github.com/fossasia/x-mario-center/blob/fe67afe28d995dcf4e2498e305825a4859566172/softwarecenter/ui/gtk3/dialogs/dependency_dialogs.py#L41-L59
ConnorJL/GPT2
936fe2a21fad221cb07d0157c00fbb0780c7d114
experimental/tpu_survival.py
python
TPUSurvival.tpu_name
(self)
return '{}'.format(self.prefix)
Format tpu_name to be used in creation and deletion calls.
Format tpu_name to be used in creation and deletion calls.
[ "Format", "tpu_name", "to", "be", "used", "in", "creation", "and", "deletion", "calls", "." ]
def tpu_name(self): """Format tpu_name to be used in creation and deletion calls.""" return '{}'.format(self.prefix)
[ "def", "tpu_name", "(", "self", ")", ":", "return", "'{}'", ".", "format", "(", "self", ".", "prefix", ")" ]
https://github.com/ConnorJL/GPT2/blob/936fe2a21fad221cb07d0157c00fbb0780c7d114/experimental/tpu_survival.py#L53-L55
naftaliharris/tauthon
5587ceec329b75f7caf6d65a036db61ac1bae214
Lib/lib-tk/Tkinter.py
python
Canvas.addtag_above
(self, newtag, tagOrId)
Add tag NEWTAG to all items above TAGORID.
Add tag NEWTAG to all items above TAGORID.
[ "Add", "tag", "NEWTAG", "to", "all", "items", "above", "TAGORID", "." ]
def addtag_above(self, newtag, tagOrId): """Add tag NEWTAG to all items above TAGORID.""" self.addtag(newtag, 'above', tagOrId)
[ "def", "addtag_above", "(", "self", ",", "newtag", ",", "tagOrId", ")", ":", "self", ".", "addtag", "(", "newtag", ",", "'above'", ",", "tagOrId", ")" ]
https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/lib-tk/Tkinter.py#L2245-L2247
Bitmessage/PyBitmessage
97612b049e0453867d6d90aa628f8e7b007b4d85
src/bitmessageqt/settings.py
python
SettingsDialog.adjust_from_config
(self, config)
Adjust all widgets state according to config settings
Adjust all widgets state according to config settings
[ "Adjust", "all", "widgets", "state", "according", "to", "config", "settings" ]
def adjust_from_config(self, config): """Adjust all widgets state according to config settings""" # pylint: disable=too-many-branches,too-many-statements if not self.parent.tray.isSystemTrayAvailable(): self.groupBoxTray.setEnabled(False) self.groupBoxTray.setTitle(_translate( "MainWindow", "Tray (not available in your system)")) for setting in ( 'minimizetotray', 'trayonclose', 'startintray'): config.set('bitmessagesettings', setting, 'false') else: self.checkBoxMinimizeToTray.setChecked( config.getboolean('bitmessagesettings', 'minimizetotray')) self.checkBoxTrayOnClose.setChecked( config.safeGetBoolean('bitmessagesettings', 'trayonclose')) self.checkBoxStartInTray.setChecked( config.getboolean('bitmessagesettings', 'startintray')) self.checkBoxHideTrayConnectionNotifications.setChecked( config.getboolean( 'bitmessagesettings', 'hidetrayconnectionnotifications')) self.checkBoxShowTrayNotifications.setChecked( config.getboolean('bitmessagesettings', 'showtraynotifications')) self.checkBoxStartOnLogon.setChecked( config.getboolean('bitmessagesettings', 'startonlogon')) self.checkBoxWillinglySendToMobile.setChecked( config.safeGetBoolean( 'bitmessagesettings', 'willinglysendtomobile')) self.checkBoxUseIdenticons.setChecked( config.safeGetBoolean('bitmessagesettings', 'useidenticons')) self.checkBoxReplyBelow.setChecked( config.safeGetBoolean('bitmessagesettings', 'replybelow')) if state.appdata == paths.lookupExeFolder(): self.checkBoxPortableMode.setChecked(True) else: try: tempfile.NamedTemporaryFile( dir=paths.lookupExeFolder(), delete=True ).close() # should autodelete except Exception: self.checkBoxPortableMode.setDisabled(True) if 'darwin' in sys.platform: self.checkBoxMinimizeToTray.setDisabled(True) self.checkBoxMinimizeToTray.setText(_translate( "MainWindow", "Minimize-to-tray not yet supported on your OS.")) self.checkBoxShowTrayNotifications.setDisabled(True) self.checkBoxShowTrayNotifications.setText(_translate( "MainWindow", "Tray notifications not yet supported on your OS.")) if 'win' not in sys.platform and not self.parent.desktop: self.checkBoxStartOnLogon.setDisabled(True) self.checkBoxStartOnLogon.setText(_translate( "MainWindow", "Start-on-login not yet supported on your OS.")) # On the Network settings tab: self.lineEditTCPPort.setText(str( config.get('bitmessagesettings', 'port'))) self.checkBoxUPnP.setChecked( config.safeGetBoolean('bitmessagesettings', 'upnp')) self.checkBoxUDP.setChecked( config.safeGetBoolean('bitmessagesettings', 'udp')) self.checkBoxAuthentication.setChecked( config.getboolean('bitmessagesettings', 'socksauthentication')) self.checkBoxSocksListen.setChecked( config.getboolean('bitmessagesettings', 'sockslisten')) self.checkBoxOnionOnly.setChecked( config.safeGetBoolean('bitmessagesettings', 'onionservicesonly')) self._proxy_type = getSOCKSProxyType(config) self.comboBoxProxyType.setCurrentIndex( 0 if not self._proxy_type else self.comboBoxProxyType.findText(self._proxy_type)) self.comboBoxProxyTypeChanged(self.comboBoxProxyType.currentIndex()) self.lineEditSocksHostname.setText( config.get('bitmessagesettings', 'sockshostname')) self.lineEditSocksPort.setText(str( config.get('bitmessagesettings', 'socksport'))) self.lineEditSocksUsername.setText( config.get('bitmessagesettings', 'socksusername')) self.lineEditSocksPassword.setText( config.get('bitmessagesettings', 'sockspassword')) self.lineEditMaxDownloadRate.setText(str( config.get('bitmessagesettings', 'maxdownloadrate'))) self.lineEditMaxUploadRate.setText(str( config.get('bitmessagesettings', 'maxuploadrate'))) self.lineEditMaxOutboundConnections.setText(str( config.get('bitmessagesettings', 'maxoutboundconnections'))) # Demanded difficulty tab self.lineEditTotalDifficulty.setText(str((float( config.getint( 'bitmessagesettings', 'defaultnoncetrialsperbyte') ) / defaults.networkDefaultProofOfWorkNonceTrialsPerByte))) self.lineEditSmallMessageDifficulty.setText(str((float( config.getint( 'bitmessagesettings', 'defaultpayloadlengthextrabytes') ) / defaults.networkDefaultPayloadLengthExtraBytes))) # Max acceptable difficulty tab self.lineEditMaxAcceptableTotalDifficulty.setText(str((float( config.getint( 'bitmessagesettings', 'maxacceptablenoncetrialsperbyte') ) / defaults.networkDefaultProofOfWorkNonceTrialsPerByte))) self.lineEditMaxAcceptableSmallMessageDifficulty.setText(str((float( config.getint( 'bitmessagesettings', 'maxacceptablepayloadlengthextrabytes') ) / defaults.networkDefaultPayloadLengthExtraBytes))) # OpenCL self.comboBoxOpenCL.setEnabled(openclpow.openclAvailable()) self.comboBoxOpenCL.clear() self.comboBoxOpenCL.addItem("None") self.comboBoxOpenCL.addItems(openclpow.vendors) self.comboBoxOpenCL.setCurrentIndex(0) for i in range(self.comboBoxOpenCL.count()): if self.comboBoxOpenCL.itemText(i) == config.safeGet( 'bitmessagesettings', 'opencl'): self.comboBoxOpenCL.setCurrentIndex(i) break # Namecoin integration tab nmctype = config.get('bitmessagesettings', 'namecoinrpctype') self.lineEditNamecoinHost.setText( config.get('bitmessagesettings', 'namecoinrpchost')) self.lineEditNamecoinPort.setText(str( config.get('bitmessagesettings', 'namecoinrpcport'))) self.lineEditNamecoinUser.setText( config.get('bitmessagesettings', 'namecoinrpcuser')) self.lineEditNamecoinPassword.setText( config.get('bitmessagesettings', 'namecoinrpcpassword')) if nmctype == "namecoind": self.radioButtonNamecoinNamecoind.setChecked(True) elif nmctype == "nmcontrol": self.radioButtonNamecoinNmcontrol.setChecked(True) self.lineEditNamecoinUser.setEnabled(False) self.labelNamecoinUser.setEnabled(False) self.lineEditNamecoinPassword.setEnabled(False) self.labelNamecoinPassword.setEnabled(False) else: assert False # Message Resend tab self.lineEditDays.setText(str( config.get('bitmessagesettings', 'stopresendingafterxdays'))) self.lineEditMonths.setText(str( config.get('bitmessagesettings', 'stopresendingafterxmonths')))
[ "def", "adjust_from_config", "(", "self", ",", "config", ")", ":", "# pylint: disable=too-many-branches,too-many-statements", "if", "not", "self", ".", "parent", ".", "tray", ".", "isSystemTrayAvailable", "(", ")", ":", "self", ".", "groupBoxTray", ".", "setEnabled"...
https://github.com/Bitmessage/PyBitmessage/blob/97612b049e0453867d6d90aa628f8e7b007b4d85/src/bitmessageqt/settings.py#L83-L237
llSourcell/Neural_Network_Voices
6ab8ccf92138c2b2a91afee4fd406cbb5d70d1a6
data_load.py
python
get_mfccs_and_spectrogram
(wav_file, trim=True, duration=None, random_crop=False)
return _get_mfcc_log_spec_and_log_mel_spec(wav, hp_default.preemphasis, hp_default.n_fft, hp_default.win_length, hp_default.hop_length)
This is applied in `train2`, `test2` or `convert` phase.
This is applied in `train2`, `test2` or `convert` phase.
[ "This", "is", "applied", "in", "train2", "test2", "or", "convert", "phase", "." ]
def get_mfccs_and_spectrogram(wav_file, trim=True, duration=None, random_crop=False): '''This is applied in `train2`, `test2` or `convert` phase. ''' # Load wav, _ = librosa.load(wav_file, sr=hp_default.sr) # Trim if trim: wav, _ = librosa.effects.trim(wav) if random_crop: wav = wav_random_crop(wav, hp_default.sr, duration) # Padding or crop if duration: length = hp_default.sr * duration wav = librosa.util.fix_length(wav, length) return _get_mfcc_log_spec_and_log_mel_spec(wav, hp_default.preemphasis, hp_default.n_fft, hp_default.win_length, hp_default.hop_length)
[ "def", "get_mfccs_and_spectrogram", "(", "wav_file", ",", "trim", "=", "True", ",", "duration", "=", "None", ",", "random_crop", "=", "False", ")", ":", "# Load", "wav", ",", "_", "=", "librosa", ".", "load", "(", "wav_file", ",", "sr", "=", "hp_default"...
https://github.com/llSourcell/Neural_Network_Voices/blob/6ab8ccf92138c2b2a91afee4fd406cbb5d70d1a6/data_load.py#L67-L87
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/irc/irc/server.py
python
IRCClient.handle_join
(self, params)
Handle the JOINing of a user to a channel. Valid channel names start with a # and consist of a-z, A-Z, 0-9 and/or '_'.
Handle the JOINing of a user to a channel. Valid channel names start with a # and consist of a-z, A-Z, 0-9 and/or '_'.
[ "Handle", "the", "JOINing", "of", "a", "user", "to", "a", "channel", ".", "Valid", "channel", "names", "start", "with", "a", "#", "and", "consist", "of", "a", "-", "z", "A", "-", "Z", "0", "-", "9", "and", "/", "or", "_", "." ]
def handle_join(self, params): """ Handle the JOINing of a user to a channel. Valid channel names start with a # and consist of a-z, A-Z, 0-9 and/or '_'. """ channel_names = params.split(' ', 1)[0] # Ignore keys for channel_name in channel_names.split(','): r_channel_name = channel_name.strip() # Valid channel name? if not re.match('^#([a-zA-Z0-9_])+$', r_channel_name): raise IRCError.from_name('nosuchchannel', '%s :No such channel' % r_channel_name) # Add user to the channel (create new channel if not exists) channel = self.server.channels.setdefault(r_channel_name, IRCChannel(r_channel_name)) channel.clients.add(self) # Add channel to user's channel list self.channels[channel.name] = channel # Send the topic response_join = ':%s TOPIC %s :%s' % (channel.topic_by, channel.name, channel.topic) self.send_queue.append(response_join) # Send join message to everybody in the channel, including yourself and # send user list of the channel back to the user. response_join = ':%s JOIN :%s' % (self.client_ident(), r_channel_name) for client in channel.clients: client.send_queue.append(response_join) nicks = [client.nick for client in channel.clients] response_userlist = ':%s 353 %s = %s :%s' % (self.server.servername, self.nick, channel.name, ' '.join(nicks)) self.send_queue.append(response_userlist) response = ':%s 366 %s %s :End of /NAMES list' % (self.server.servername, self.nick, channel.name) self.send_queue.append(response)
[ "def", "handle_join", "(", "self", ",", "params", ")", ":", "channel_names", "=", "params", ".", "split", "(", "' '", ",", "1", ")", "[", "0", "]", "# Ignore keys", "for", "channel_name", "in", "channel_names", ".", "split", "(", "','", ")", ":", "r_ch...
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/irc/irc/server.py#L275-L311
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/ply-3.11/example/ansic/cparse.py
python
p_enum_specifier_2
(t)
enum_specifier : ENUM LBRACE enumerator_list RBRACE
enum_specifier : ENUM LBRACE enumerator_list RBRACE
[ "enum_specifier", ":", "ENUM", "LBRACE", "enumerator_list", "RBRACE" ]
def p_enum_specifier_2(t): 'enum_specifier : ENUM LBRACE enumerator_list RBRACE' pass
[ "def", "p_enum_specifier_2", "(", "t", ")", ":", "pass" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/ply-3.11/example/ansic/cparse.py#L283-L285
YvanYin/VNL_Monocular_Depth_Prediction
a11b1efd4b91714e27fd2799d2c01fced4dc2f9e
tools/train_nyu_metric.py
python
train
(train_dataloader, model, epoch, loss_func, optimizer, scheduler, training_stats, val_dataloader=None, val_err=[], ignore_step=-1)
Train the model in steps
Train the model in steps
[ "Train", "the", "model", "in", "steps" ]
def train(train_dataloader, model, epoch, loss_func, optimizer, scheduler, training_stats, val_dataloader=None, val_err=[], ignore_step=-1): """ Train the model in steps """ model.train() epoch_steps = math.ceil(len(train_dataloader) / cfg.TRAIN.BATCHSIZE) base_steps = epoch_steps * epoch + ignore_step if ignore_step != -1 else epoch_steps * epoch for i, data in enumerate(train_dataloader): if ignore_step != -1 and i > epoch_steps - ignore_step: return scheduler.step() # decay lr every iteration training_stats.IterTic() out = model(data) losses = loss_func.criterion(out['b_fake_softmax'], out['b_fake_logit'], data, epoch) optimizer.optim(losses) step = base_steps + i + 1 training_stats.UpdateIterStats(losses) training_stats.IterToc() training_stats.LogIterStats(step, epoch, optimizer.optimizer, val_err[0]) # validate the model if step % cfg.TRAIN.VAL_STEP == 0 and step != 0 and val_dataloader is not None: model.eval() val_err[0] = val(val_dataloader, model) # training mode model.train() # save checkpoint if step % cfg.TRAIN.SNAPSHOT_ITERS == 0 and step != 0: save_ckpt(train_args, step, epoch, model, optimizer.optimizer, scheduler, val_err[0])
[ "def", "train", "(", "train_dataloader", ",", "model", ",", "epoch", ",", "loss_func", ",", "optimizer", ",", "scheduler", ",", "training_stats", ",", "val_dataloader", "=", "None", ",", "val_err", "=", "[", "]", ",", "ignore_step", "=", "-", "1", ")", "...
https://github.com/YvanYin/VNL_Monocular_Depth_Prediction/blob/a11b1efd4b91714e27fd2799d2c01fced4dc2f9e/tools/train_nyu_metric.py#L27-L57
wikimedia/pywikibot
81a01ffaec7271bf5b4b170f85a80388420a4e78
scripts/coordinate_import.py
python
CoordImportRobot.try_import_coordinates_from_page
(self, page, item)
Try import coordinate from the given page to the given item. :return: whether any coordinates were found and the import was successful
Try import coordinate from the given page to the given item.
[ "Try", "import", "coordinate", "from", "the", "given", "page", "to", "the", "given", "item", "." ]
def try_import_coordinates_from_page(self, page, item) -> bool: """ Try import coordinate from the given page to the given item. :return: whether any coordinates were found and the import was successful """ coordinate = page.coordinates(primary_only=True) if not coordinate: return False newclaim = pywikibot.Claim(self.repo, self.prop) newclaim.setTarget(coordinate) source = self.getSource(page.site) if source: newclaim.addSource(source) pywikibot.output('Adding {}, {} to {}'.format( coordinate.lat, coordinate.lon, item.title())) # todo: handle exceptions using self.user_add_claim try: item.addClaim(newclaim) except CoordinateGlobeUnknownError as e: pywikibot.output('Skipping unsupported globe: {}'.format(e.args)) return False else: return True
[ "def", "try_import_coordinates_from_page", "(", "self", ",", "page", ",", "item", ")", "->", "bool", ":", "coordinate", "=", "page", ".", "coordinates", "(", "primary_only", "=", "True", ")", "if", "not", "coordinate", ":", "return", "False", "newclaim", "="...
https://github.com/wikimedia/pywikibot/blob/81a01ffaec7271bf5b4b170f85a80388420a4e78/scripts/coordinate_import.py#L129-L154
geofront-auth/geofront
1db8d3c1a7ae1d59caa3a5bb2a36a6e466b226f6
geofront/backends/dbapi.py
python
DatabaseKeyStore._execute
(self, cursor, sql: str, params: Tuple[str, ...])
To support various paramstyles. See the following specification: http://legacy.python.org/dev/peps/pep-0249/#paramstyle
To support various paramstyles. See the following specification:
[ "To", "support", "various", "paramstyles", ".", "See", "the", "following", "specification", ":" ]
def _execute(self, cursor, sql: str, params: Tuple[str, ...]) -> None: """To support various paramstyles. See the following specification: http://legacy.python.org/dev/peps/pep-0249/#paramstyle """ final_params = cast(Union[Tuple[str, ...], Mapping[str, str]], params) paramstyle = self.db_module.paramstyle # type: ignore if paramstyle == 'format': sql = sql.replace('?', '%s') elif paramstyle != 'qmark': if paramstyle == 'numeric': fmt = ':{}' i = 1 else: if paramstyle == 'named': fmt = ':p{}' else: # pyformat fmt = '%(p{})s' final_params = \ {'p' + str(i): val for i, val in enumerate(params)} i = 0 while '?' in sql: sql = sql.replace('?', fmt.format(i), 1) i += 1 cursor.execute(sql, final_params)
[ "def", "_execute", "(", "self", ",", "cursor", ",", "sql", ":", "str", ",", "params", ":", "Tuple", "[", "str", ",", "...", "]", ")", "->", "None", ":", "final_params", "=", "cast", "(", "Union", "[", "Tuple", "[", "str", ",", "...", "]", ",", ...
https://github.com/geofront-auth/geofront/blob/1db8d3c1a7ae1d59caa3a5bb2a36a6e466b226f6/geofront/backends/dbapi.py#L95-L120
secynic/ipwhois
a5d5b65ce3b1d4b2c20bba2e981968f54e1b5e9e
ipwhois/scripts/ipwhois_cli.py
python
IPWhoisCLI.generate_output_network
(self, json_data=None, hr=True, show_name=False, colorize=True)
return output
The function for generating CLI output RDAP network results. Args: json_data (:obj:`dict`): The data to process. Defaults to None. hr (:obj:`bool`): Enable human readable key translations. Defaults to True. show_name (:obj:`bool`): Show human readable name (default is to only show short). Defaults to False. colorize (:obj:`bool`): Colorize the console output with ANSI colors. Defaults to True. Returns: str: The generated output.
The function for generating CLI output RDAP network results.
[ "The", "function", "for", "generating", "CLI", "output", "RDAP", "network", "results", "." ]
def generate_output_network(self, json_data=None, hr=True, show_name=False, colorize=True): """ The function for generating CLI output RDAP network results. Args: json_data (:obj:`dict`): The data to process. Defaults to None. hr (:obj:`bool`): Enable human readable key translations. Defaults to True. show_name (:obj:`bool`): Show human readable name (default is to only show short). Defaults to False. colorize (:obj:`bool`): Colorize the console output with ANSI colors. Defaults to True. Returns: str: The generated output. """ if json_data is None: json_data = {} output = generate_output( line='0', short=HR_RDAP['network']['_short'] if hr else 'network', name=HR_RDAP['network']['_name'] if (hr and show_name) else None, is_parent=True, colorize=colorize ) for key, val in json_data['network'].items(): if key in ['links', 'status']: output += self.generate_output_list( source='network', key=key, val=val, line='1', hr=hr, show_name=show_name, colorize=colorize ) elif key in ['notices', 'remarks']: output += self.generate_output_notices( source='network', key=key, val=val, line='1', hr=hr, show_name=show_name, colorize=colorize ) elif key == 'events': output += self.generate_output_events( source='network', key=key, val=val, line='1', hr=hr, show_name=show_name, colorize=colorize ) elif key not in ['raw']: output += generate_output( line='1', short=HR_RDAP['network'][key]['_short'] if hr else key, name=HR_RDAP['network'][key]['_name'] if ( hr and show_name) else None, value=val, colorize=colorize ) return output
[ "def", "generate_output_network", "(", "self", ",", "json_data", "=", "None", ",", "hr", "=", "True", ",", "show_name", "=", "False", ",", "colorize", "=", "True", ")", ":", "if", "json_data", "is", "None", ":", "json_data", "=", "{", "}", "output", "=...
https://github.com/secynic/ipwhois/blob/a5d5b65ce3b1d4b2c20bba2e981968f54e1b5e9e/ipwhois/scripts/ipwhois_cli.py#L751-L829
hypothesis/h
25ef1b8d94889df86ace5a084f1aa0effd9f4e25
h/search/config.py
python
delete_index
(client, index_name)
Delete an unused index. This must be an actual index and not an alias.
Delete an unused index.
[ "Delete", "an", "unused", "index", "." ]
def delete_index(client, index_name): """ Delete an unused index. This must be an actual index and not an alias. """ client.conn.indices.delete(index=index_name)
[ "def", "delete_index", "(", "client", ",", "index_name", ")", ":", "client", ".", "conn", ".", "indices", ".", "delete", "(", "index", "=", "index_name", ")" ]
https://github.com/hypothesis/h/blob/25ef1b8d94889df86ace5a084f1aa0effd9f4e25/h/search/config.py#L179-L186
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/pygments/lexers/graphics.py
python
_shortened
(word)
return '|'.join(word[:dpos] + word[dpos+1:i] + r'\b' for i in range(len(word), dpos, -1))
[]
def _shortened(word): dpos = word.find('$') return '|'.join(word[:dpos] + word[dpos+1:i] + r'\b' for i in range(len(word), dpos, -1))
[ "def", "_shortened", "(", "word", ")", ":", "dpos", "=", "word", ".", "find", "(", "'$'", ")", "return", "'|'", ".", "join", "(", "word", "[", ":", "dpos", "]", "+", "word", "[", "dpos", "+", "1", ":", "i", "]", "+", "r'\\b'", "for", "i", "in...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pygments/lexers/graphics.py#L293-L296
seppius-xbmc-repo/ru
d0879d56ec8243b2c7af44fda5cf3d1ff77fd2e2
plugin.video.online.anidub.com/resources/lib/BeautifulSoup.py
python
PageElement.findAllPrevious
(self, name=None, attrs={}, text=None, limit=None, **kwargs)
return self._findAll(name, attrs, text, limit, self.previousGenerator, **kwargs)
Returns all items that match the given criteria and appear before this Tag in the document.
Returns all items that match the given criteria and appear before this Tag in the document.
[ "Returns", "all", "items", "that", "match", "the", "given", "criteria", "and", "appear", "before", "this", "Tag", "in", "the", "document", "." ]
def findAllPrevious(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns all items that match the given criteria and appear before this Tag in the document.""" return self._findAll(name, attrs, text, limit, self.previousGenerator, **kwargs)
[ "def", "findAllPrevious", "(", "self", ",", "name", "=", "None", ",", "attrs", "=", "{", "}", ",", "text", "=", "None", ",", "limit", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_findAll", "(", "name", ",", "attrs", ",...
https://github.com/seppius-xbmc-repo/ru/blob/d0879d56ec8243b2c7af44fda5cf3d1ff77fd2e2/plugin.video.online.anidub.com/resources/lib/BeautifulSoup.py#L283-L288
eerimoq/asn1tools
30eb88e287cc1616903858aa96ee8791a4d7bf1c
asn1tools/codecs/compiler.py
python
Compiler.pre_process_components_of
(self, type_descriptors, module_name)
COMPONENTS OF expansion.
COMPONENTS OF expansion.
[ "COMPONENTS", "OF", "expansion", "." ]
def pre_process_components_of(self, type_descriptors, module_name): """COMPONENTS OF expansion. """ for type_descriptor in type_descriptors: self.pre_process_components_of_type(type_descriptor, module_name)
[ "def", "pre_process_components_of", "(", "self", ",", "type_descriptors", ",", "module_name", ")", ":", "for", "type_descriptor", "in", "type_descriptors", ":", "self", ".", "pre_process_components_of_type", "(", "type_descriptor", ",", "module_name", ")" ]
https://github.com/eerimoq/asn1tools/blob/30eb88e287cc1616903858aa96ee8791a4d7bf1c/asn1tools/codecs/compiler.py#L267-L274
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/com.oracle.graal.python.benchmarks/python/meso/srad_rodinia-sized2.py
python
srad
(nIter, size_R, cols, rows, J, dN, dS, dE, dW, c, r1, r2, c1, c2, Lambda)
[]
def srad(nIter, size_R, cols, rows, J, dN, dS, dE, dW, c, r1, r2, c1, c2, Lambda): for ii in range(nIter): Sum = 0. Sum2 = 0. for i in range(r1, r2+1): for j in range(c1, c2+1): tmp = J[i * cols + j] Sum += tmp Sum2 += tmp*tmp meanROI = Sum / size_R varROI = (Sum2 / size_R) - meanROI*meanROI q0sqr = varROI / (meanROI*meanROI) srad_1(q0sqr, cols, rows, J, dN, dS, dE, dW, c) srad_2(cols, rows, J, dN, dS, dE, dW, c, Lambda)
[ "def", "srad", "(", "nIter", ",", "size_R", ",", "cols", ",", "rows", ",", "J", ",", "dN", ",", "dS", ",", "dE", ",", "dW", ",", "c", ",", "r1", ",", "r2", ",", "c1", ",", "c2", ",", "Lambda", ")", ":", "for", "ii", "in", "range", "(", "n...
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/com.oracle.graal.python.benchmarks/python/meso/srad_rodinia-sized2.py#L94-L109
mrlesmithjr/Ansible
d44f0dc0d942bdf3bf7334b307e6048f0ee16e36
roles/ansible-vsphere-management/scripts/pdns/lib/python2.7/site-packages/pip/_vendor/distlib/locators.py
python
Locator.prefer_url
(self, url1, url2)
return result
Choose one of two URLs where both are candidates for distribution archives for the same version of a distribution (for example, .tar.gz vs. zip). The current implementation favours https:// URLs over http://, archives from PyPI over those from other locations, wheel compatibility (if a wheel) and then the archive name.
Choose one of two URLs where both are candidates for distribution archives for the same version of a distribution (for example, .tar.gz vs. zip).
[ "Choose", "one", "of", "two", "URLs", "where", "both", "are", "candidates", "for", "distribution", "archives", "for", "the", "same", "version", "of", "a", "distribution", "(", "for", "example", ".", "tar", ".", "gz", "vs", ".", "zip", ")", "." ]
def prefer_url(self, url1, url2): """ Choose one of two URLs where both are candidates for distribution archives for the same version of a distribution (for example, .tar.gz vs. zip). The current implementation favours https:// URLs over http://, archives from PyPI over those from other locations, wheel compatibility (if a wheel) and then the archive name. """ result = url2 if url1: s1 = self.score_url(url1) s2 = self.score_url(url2) if s1 > s2: result = url1 if result != url2: logger.debug('Not replacing %r with %r', url1, url2) else: logger.debug('Replacing %r with %r', url1, url2) return result
[ "def", "prefer_url", "(", "self", ",", "url1", ",", "url2", ")", ":", "result", "=", "url2", "if", "url1", ":", "s1", "=", "self", ".", "score_url", "(", "url1", ")", "s2", "=", "self", ".", "score_url", "(", "url2", ")", "if", "s1", ">", "s2", ...
https://github.com/mrlesmithjr/Ansible/blob/d44f0dc0d942bdf3bf7334b307e6048f0ee16e36/roles/ansible-vsphere-management/scripts/pdns/lib/python2.7/site-packages/pip/_vendor/distlib/locators.py#L199-L219
markj3d/Red9_StudioPack
1d40a8bf84c45ce7eaefdd9ccfa3cdbeb1471919
core/Red9_Meta.py
python
MetaHUDNode.getHudDisplays
(self)
return ['MetaHUDConnector%s' % attr for attr in self.monitorAttrs]
each line in the HUD is actually a separate HUD in itself so we need to carefully manage this list
each line in the HUD is actually a separate HUD in itself so we need to carefully manage this list
[ "each", "line", "in", "the", "HUD", "is", "actually", "a", "separate", "HUD", "in", "itself", "so", "we", "need", "to", "carefully", "manage", "this", "list" ]
def getHudDisplays(self): ''' each line in the HUD is actually a separate HUD in itself so we need to carefully manage this list ''' return ['MetaHUDConnector%s' % attr for attr in self.monitorAttrs]
[ "def", "getHudDisplays", "(", "self", ")", ":", "return", "[", "'MetaHUDConnector%s'", "%", "attr", "for", "attr", "in", "self", ".", "monitorAttrs", "]" ]
https://github.com/markj3d/Red9_StudioPack/blob/1d40a8bf84c45ce7eaefdd9ccfa3cdbeb1471919/core/Red9_Meta.py#L5446-L5451
quic/aimet
dae9bae9a77ca719aa7553fefde4768270fc3518
TrainingExtensions/torch/src/python/aimet_torch/adaround/adaround_optimizer.py
python
AdaroundOptimizer.adaround_module
(cls, module: torch.nn.Module, quant_module: StaticGridQuantWrapper, orig_model: torch.nn.Module, quant_model: torch.nn.Module, act_func: Union[torch.nn.Module, None], cached_dataset: Dataset, opt_params: AdaroundHyperParameters)
Adaround module :param module: Original module :param quant_module: Quantized wrapper module :param orig_model: The original, un quantized, model :param quant_model: QuantSim model :param act_func: Activation function :param cached_dataset: Cached dataset :param opt_params: Optimization parameters
Adaround module :param module: Original module :param quant_module: Quantized wrapper module :param orig_model: The original, un quantized, model :param quant_model: QuantSim model :param act_func: Activation function :param cached_dataset: Cached dataset :param opt_params: Optimization parameters
[ "Adaround", "module", ":", "param", "module", ":", "Original", "module", ":", "param", "quant_module", ":", "Quantized", "wrapper", "module", ":", "param", "orig_model", ":", "The", "original", "un", "quantized", "model", ":", "param", "quant_model", ":", "Qua...
def adaround_module(cls, module: torch.nn.Module, quant_module: StaticGridQuantWrapper, orig_model: torch.nn.Module, quant_model: torch.nn.Module, act_func: Union[torch.nn.Module, None], cached_dataset: Dataset, opt_params: AdaroundHyperParameters): """ Adaround module :param module: Original module :param quant_module: Quantized wrapper module :param orig_model: The original, un quantized, model :param quant_model: QuantSim model :param act_func: Activation function :param cached_dataset: Cached dataset :param opt_params: Optimization parameters """ assert isinstance(quant_module, StaticGridQuantWrapper), '%s is not wrapper module.' % quant_module assert quant_module.param_quantizers['weight'], '%s does not have weight quantizer.' % quant_module # Get input and output data of batch size to compute reconstruction error of output activations # before and after optimization iterator = iter(cached_dataset) inp_data, out_data = ActivationSampler.sample_activation(module, quant_module, orig_model, quant_model, iterator, num_batches=1) recons_err_hard, recons_err_soft = cls._compute_recons_metrics(quant_module, act_func, inp_data, out_data) logger.debug("Before opt, Recons. error metrics using soft rounding=%f and hard rounding=%f", recons_err_soft, recons_err_hard) # Optimize weight rounding cls._optimize_rounding(module, quant_module, orig_model, quant_model, act_func, cached_dataset, opt_params) recons_err_hard, recons_err_soft = cls._compute_recons_metrics(quant_module, act_func, inp_data, out_data) logger.debug("After opt, Recons. error metrics using soft rounding=%f and hard rounding=%f", recons_err_soft, recons_err_hard) # After optimization, set the optimized layer's rounding mode to "Hard rounding" quant_module.param_quantizers['weight'].use_soft_rounding = False
[ "def", "adaround_module", "(", "cls", ",", "module", ":", "torch", ".", "nn", ".", "Module", ",", "quant_module", ":", "StaticGridQuantWrapper", ",", "orig_model", ":", "torch", ".", "nn", ".", "Module", ",", "quant_model", ":", "torch", ".", "nn", ".", ...
https://github.com/quic/aimet/blob/dae9bae9a77ca719aa7553fefde4768270fc3518/TrainingExtensions/torch/src/python/aimet_torch/adaround/adaround_optimizer.py#L61-L96
Ultimaker/Uranium
66da853cd9a04edd3a8a03526fac81e83c03f5aa
UM/SortedList.py
python
SortedList.bisect_right
(self, value)
return self._loc(pos, idx)
Return an index to insert `value` in the sorted list. Similar to `bisect_left`, but if `value` is already present, the insertion point with be after (to the right of) any existing values. Similar to the `bisect` module in the standard library. Runtime complexity: `O(log(n))` -- approximate. >>> sl = SortedList([10, 11, 12, 13, 14]) >>> sl.bisect_right(12) 3 :param value: insertion index of value in sorted list :return: index
Return an index to insert `value` in the sorted list.
[ "Return", "an", "index", "to", "insert", "value", "in", "the", "sorted", "list", "." ]
def bisect_right(self, value): """Return an index to insert `value` in the sorted list. Similar to `bisect_left`, but if `value` is already present, the insertion point with be after (to the right of) any existing values. Similar to the `bisect` module in the standard library. Runtime complexity: `O(log(n))` -- approximate. >>> sl = SortedList([10, 11, 12, 13, 14]) >>> sl.bisect_right(12) 3 :param value: insertion index of value in sorted list :return: index """ _maxes = self._maxes if not _maxes: return 0 pos = bisect_right(_maxes, value) if pos == len(_maxes): return self._len idx = bisect_right(self._lists[pos], value) return self._loc(pos, idx)
[ "def", "bisect_right", "(", "self", ",", "value", ")", ":", "_maxes", "=", "self", ".", "_maxes", "if", "not", "_maxes", ":", "return", "0", "pos", "=", "bisect_right", "(", "_maxes", ",", "value", ")", "if", "pos", "==", "len", "(", "_maxes", ")", ...
https://github.com/Ultimaker/Uranium/blob/66da853cd9a04edd3a8a03526fac81e83c03f5aa/UM/SortedList.py#L1223-L1252
ukBaz/python-bluezero
e6b4e96342de6c66571a6660d711c018f8c6b470
bluezero/central.py
python
Central.services_available
(self)
return self.rmt_device.services_available
Get a list of Service UUIDs available on this device
Get a list of Service UUIDs available on this device
[ "Get", "a", "list", "of", "Service", "UUIDs", "available", "on", "this", "device" ]
def services_available(self): """Get a list of Service UUIDs available on this device""" return self.rmt_device.services_available
[ "def", "services_available", "(", "self", ")", ":", "return", "self", ".", "rmt_device", ".", "services_available" ]
https://github.com/ukBaz/python-bluezero/blob/e6b4e96342de6c66571a6660d711c018f8c6b470/bluezero/central.py#L66-L68
SebKuzminsky/pycam
55e3129f518e470040e79bb00515b4bfcf36c172
pycam/Utils/threading.py
python
ProcessStatistics.__str__
(self)
return os.linesep.join([str(item) for item in self.processes.values() + self.queues.values()])
[]
def __str__(self): return os.linesep.join([str(item) for item in self.processes.values() + self.queues.values()])
[ "def", "__str__", "(", "self", ")", ":", "return", "os", ".", "linesep", ".", "join", "(", "[", "str", "(", "item", ")", "for", "item", "in", "self", ".", "processes", ".", "values", "(", ")", "+", "self", ".", "queues", ".", "values", "(", ")", ...
https://github.com/SebKuzminsky/pycam/blob/55e3129f518e470040e79bb00515b4bfcf36c172/pycam/Utils/threading.py#L697-L699
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/lib-tk/turtle.py
python
_Root.set_geometry
(self, width, height, startx, starty)
[]
def set_geometry(self, width, height, startx, starty): self.geometry("%dx%d%+d%+d"%(width, height, startx, starty))
[ "def", "set_geometry", "(", "self", ",", "width", ",", "height", ",", "startx", ",", "starty", ")", ":", "self", ".", "geometry", "(", "\"%dx%d%+d%+d\"", "%", "(", "width", ",", "height", ",", "startx", ",", "starty", ")", ")" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/lib-tk/turtle.py#L467-L468
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/ex-submodules/pillowtop/management/commands/ptop_run_docs.py
python
Command.log
(self, string)
[]
def log(self, string): timestamp = datetime.datetime.utcnow().replace(microsecond=0) print("[{}] {}".format(timestamp, string))
[ "def", "log", "(", "self", ",", "string", ")", ":", "timestamp", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "replace", "(", "microsecond", "=", "0", ")", "print", "(", "\"[{}] {}\"", ".", "format", "(", "timestamp", ",", "string", ...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/ex-submodules/pillowtop/management/commands/ptop_run_docs.py#L60-L62
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/categories/baseclasses.py
python
Morphism.__mul__
(self, other)
return self.compose(other)
r""" Composes self with the supplied morphism. The semantics of this operation is given by the following equation: ``g * f == g.compose(f)`` for composable morphisms ``g`` and ``f``. See Also ======== compose
r""" Composes self with the supplied morphism.
[ "r", "Composes", "self", "with", "the", "supplied", "morphism", "." ]
def __mul__(self, other): r""" Composes self with the supplied morphism. The semantics of this operation is given by the following equation: ``g * f == g.compose(f)`` for composable morphisms ``g`` and ``f``. See Also ======== compose """ return self.compose(other)
[ "def", "__mul__", "(", "self", ",", "other", ")", ":", "return", "self", ".", "compose", "(", "other", ")" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/categories/baseclasses.py#L122-L135
NVIDIA/DeepLearningExamples
589604d49e016cd9ef4525f7abcc9c7b826cfc5e
TensorFlow/LanguageModeling/BERT/tokenization.py
python
_is_control
(char)
return False
Checks whether `chars` is a control character.
Checks whether `chars` is a control character.
[ "Checks", "whether", "chars", "is", "a", "control", "character", "." ]
def _is_control(char): """Checks whether `chars` is a control character.""" # These are technically control characters but we count them as whitespace # characters. if char == "\t" or char == "\n" or char == "\r": return False cat = unicodedata.category(char) if cat.startswith("C"): return True return False
[ "def", "_is_control", "(", "char", ")", ":", "# These are technically control characters but we count them as whitespace", "# characters.", "if", "char", "==", "\"\\t\"", "or", "char", "==", "\"\\n\"", "or", "char", "==", "\"\\r\"", ":", "return", "False", "cat", "=",...
https://github.com/NVIDIA/DeepLearningExamples/blob/589604d49e016cd9ef4525f7abcc9c7b826cfc5e/TensorFlow/LanguageModeling/BERT/tokenization.py#L426-L435
learningequality/ka-lite
571918ea668013dcf022286ea85eff1c5333fb8b
kalite/packages/bundled/django/core/serializers/__init__.py
python
_load_serializers
()
Register built-in and settings-defined serializers. This is done lazily so that user code has a chance to (e.g.) set up custom settings without needing to be careful of import order.
Register built-in and settings-defined serializers. This is done lazily so that user code has a chance to (e.g.) set up custom settings without needing to be careful of import order.
[ "Register", "built", "-", "in", "and", "settings", "-", "defined", "serializers", ".", "This", "is", "done", "lazily", "so", "that", "user", "code", "has", "a", "chance", "to", "(", "e", ".", "g", ".", ")", "set", "up", "custom", "settings", "without",...
def _load_serializers(): """ Register built-in and settings-defined serializers. This is done lazily so that user code has a chance to (e.g.) set up custom settings without needing to be careful of import order. """ global _serializers serializers = {} for format in BUILTIN_SERIALIZERS: register_serializer(format, BUILTIN_SERIALIZERS[format], serializers) if hasattr(settings, "SERIALIZATION_MODULES"): for format in settings.SERIALIZATION_MODULES: register_serializer(format, settings.SERIALIZATION_MODULES[format], serializers) _serializers = serializers
[ "def", "_load_serializers", "(", ")", ":", "global", "_serializers", "serializers", "=", "{", "}", "for", "format", "in", "BUILTIN_SERIALIZERS", ":", "register_serializer", "(", "format", ",", "BUILTIN_SERIALIZERS", "[", "format", "]", ",", "serializers", ")", "...
https://github.com/learningequality/ka-lite/blob/571918ea668013dcf022286ea85eff1c5333fb8b/kalite/packages/bundled/django/core/serializers/__init__.py#L112-L125