nwo
stringlengths
5
91
sha
stringlengths
40
40
path
stringlengths
5
174
language
stringclasses
1 value
identifier
stringlengths
1
120
parameters
stringlengths
0
3.15k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
24.1k
docstring
stringlengths
0
27.3k
docstring_summary
stringlengths
0
13.8k
docstring_tokens
sequence
function
stringlengths
22
139k
function_tokens
sequence
url
stringlengths
87
283
aceisace/Inkycal
552744bc5d80769c1015d48fd8b13201683ee679
inkycal/display/drivers/epd_7_in_5_v2.py
python
EPD.send_data
(self, data)
[]
def send_data(self, data): epdconfig.digital_write(self.dc_pin, 1) epdconfig.digital_write(self.cs_pin, 0) epdconfig.spi_writebyte([data]) epdconfig.digital_write(self.cs_pin, 1)
[ "def", "send_data", "(", "self", ",", "data", ")", ":", "epdconfig", ".", "digital_write", "(", "self", ".", "dc_pin", ",", "1", ")", "epdconfig", ".", "digital_write", "(", "self", ".", "cs_pin", ",", "0", ")", "epdconfig", ".", "spi_writebyte", "(", "[", "data", "]", ")", "epdconfig", ".", "digital_write", "(", "self", ".", "cs_pin", ",", "1", ")" ]
https://github.com/aceisace/Inkycal/blob/552744bc5d80769c1015d48fd8b13201683ee679/inkycal/display/drivers/epd_7_in_5_v2.py#L62-L66
golismero/golismero
7d605b937e241f51c1ca4f47b20f755eeefb9d76
tools/sqlmap/lib/core/common.py
python
Backend.getErrorParsedDBMSes
()
return kb.htmlFp if kb.get("heuristicTest") == HEURISTIC_TEST.POSITIVE else []
Returns array with parsed DBMS names till now This functions is called to: 1. Sort the tests, getSortedInjectionTests() - detection phase. 2. Ask user whether or not skip specific DBMS tests in detection phase, lib/controller/checks.py - detection phase. 3. Sort the fingerprint of the DBMS, lib/controller/handler.py - fingerprint phase.
Returns array with parsed DBMS names till now
[ "Returns", "array", "with", "parsed", "DBMS", "names", "till", "now" ]
def getErrorParsedDBMSes(): """ Returns array with parsed DBMS names till now This functions is called to: 1. Sort the tests, getSortedInjectionTests() - detection phase. 2. Ask user whether or not skip specific DBMS tests in detection phase, lib/controller/checks.py - detection phase. 3. Sort the fingerprint of the DBMS, lib/controller/handler.py - fingerprint phase. """ return kb.htmlFp if kb.get("heuristicTest") == HEURISTIC_TEST.POSITIVE else []
[ "def", "getErrorParsedDBMSes", "(", ")", ":", "return", "kb", ".", "htmlFp", "if", "kb", ".", "get", "(", "\"heuristicTest\"", ")", "==", "HEURISTIC_TEST", ".", "POSITIVE", "else", "[", "]" ]
https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/tools/sqlmap/lib/core/common.py#L422-L435
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-windows/x86/tornado/httputil.py
python
HTTPConnection.write_headers
( self, start_line: Union["RequestStartLine", "ResponseStartLine"], headers: HTTPHeaders, chunk: bytes = None, )
Write an HTTP header block. :arg start_line: a `.RequestStartLine` or `.ResponseStartLine`. :arg headers: a `.HTTPHeaders` instance. :arg chunk: the first (optional) chunk of data. This is an optimization so that small responses can be written in the same call as their headers. The ``version`` field of ``start_line`` is ignored. Returns a future for flow control. .. versionchanged:: 6.0 The ``callback`` argument was removed.
Write an HTTP header block.
[ "Write", "an", "HTTP", "header", "block", "." ]
def write_headers( self, start_line: Union["RequestStartLine", "ResponseStartLine"], headers: HTTPHeaders, chunk: bytes = None, ) -> "Future[None]": """Write an HTTP header block. :arg start_line: a `.RequestStartLine` or `.ResponseStartLine`. :arg headers: a `.HTTPHeaders` instance. :arg chunk: the first (optional) chunk of data. This is an optimization so that small responses can be written in the same call as their headers. The ``version`` field of ``start_line`` is ignored. Returns a future for flow control. .. versionchanged:: 6.0 The ``callback`` argument was removed. """ raise NotImplementedError()
[ "def", "write_headers", "(", "self", ",", "start_line", ":", "Union", "[", "\"RequestStartLine\"", ",", "\"ResponseStartLine\"", "]", ",", "headers", ":", "HTTPHeaders", ",", "chunk", ":", "bytes", "=", "None", ",", ")", "->", "\"Future[None]\"", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-windows/x86/tornado/httputil.py#L590-L612
xinntao/EDVR
b02e63a0fc5854cad7b11a87f74601612e356eff
basicsr/models/archs/stylegan2_arch.py
python
ToRGB.forward
(self, x, style, skip=None)
return out
Forward function. Args: x (Tensor): Feature tensor with shape (b, c, h, w). style (Tensor): Tensor with shape (b, num_style_feat). skip (Tensor): Base/skip tensor. Default: None. Returns: Tensor: RGB images.
Forward function.
[ "Forward", "function", "." ]
def forward(self, x, style, skip=None): """Forward function. Args: x (Tensor): Feature tensor with shape (b, c, h, w). style (Tensor): Tensor with shape (b, num_style_feat). skip (Tensor): Base/skip tensor. Default: None. Returns: Tensor: RGB images. """ out = self.modulated_conv(x, style) out = out + self.bias if skip is not None: if self.upsample: skip = self.upsample(skip) out = out + skip return out
[ "def", "forward", "(", "self", ",", "x", ",", "style", ",", "skip", "=", "None", ")", ":", "out", "=", "self", ".", "modulated_conv", "(", "x", ",", "style", ")", "out", "=", "out", "+", "self", ".", "bias", "if", "skip", "is", "not", "None", ":", "if", "self", ".", "upsample", ":", "skip", "=", "self", ".", "upsample", "(", "skip", ")", "out", "=", "out", "+", "skip", "return", "out" ]
https://github.com/xinntao/EDVR/blob/b02e63a0fc5854cad7b11a87f74601612e356eff/basicsr/models/archs/stylegan2_arch.py#L407-L424
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/nntplib.py
python
NNTP.last
(self)
return self.statcmd('LAST')
Process a LAST command. No arguments. Return as for STAT.
Process a LAST command. No arguments. Return as for STAT.
[ "Process", "a", "LAST", "command", ".", "No", "arguments", ".", "Return", "as", "for", "STAT", "." ]
def last(self): """Process a LAST command. No arguments. Return as for STAT.""" return self.statcmd('LAST')
[ "def", "last", "(", "self", ")", ":", "return", "self", ".", "statcmd", "(", "'LAST'", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/nntplib.py#L410-L412
axcore/tartube
36dd493642923fe8b9190a41db596c30c043ae90
tartube/config.py
python
SystemPrefWin.on_json_button_toggled
(self, checkbutton)
Called from callback in self.setup_operations_downloads_tab(). Enables/disables applying a 60-second timeout when fetching a video's JSON data. Args: checkbutton (Gtk.CheckButton): The widget clicked
Called from callback in self.setup_operations_downloads_tab().
[ "Called", "from", "callback", "in", "self", ".", "setup_operations_downloads_tab", "()", "." ]
def on_json_button_toggled(self, checkbutton): """Called from callback in self.setup_operations_downloads_tab(). Enables/disables applying a 60-second timeout when fetching a video's JSON data. Args: checkbutton (Gtk.CheckButton): The widget clicked """ if checkbutton.get_active() \ and not self.app_obj.apply_json_timeout_flag: self.app_obj.set_apply_json_timeout_flag(True) elif not checkbutton.get_active() \ and self.app_obj.apply_json_timeout_flag: self.app_obj.set_apply_json_timeout_flag(False)
[ "def", "on_json_button_toggled", "(", "self", ",", "checkbutton", ")", ":", "if", "checkbutton", ".", "get_active", "(", ")", "and", "not", "self", ".", "app_obj", ".", "apply_json_timeout_flag", ":", "self", ".", "app_obj", ".", "set_apply_json_timeout_flag", "(", "True", ")", "elif", "not", "checkbutton", ".", "get_active", "(", ")", "and", "self", ".", "app_obj", ".", "apply_json_timeout_flag", ":", "self", ".", "app_obj", ".", "set_apply_json_timeout_flag", "(", "False", ")" ]
https://github.com/axcore/tartube/blob/36dd493642923fe8b9190a41db596c30c043ae90/tartube/config.py#L25900-L25918
viewfinderco/viewfinder
453845b5d64ab5b3b826c08b02546d1ca0a07c14
backend/op/update_viewpoint_op.py
python
UpdateViewpointOperation._Notify
(self)
Creates notifications: 1. Notifies removed followers that conversation has new activity. 2. Notifies existing followers of the viewpoint that metadata has changed.
Creates notifications: 1. Notifies removed followers that conversation has new activity. 2. Notifies existing followers of the viewpoint that metadata has changed.
[ "Creates", "notifications", ":", "1", ".", "Notifies", "removed", "followers", "that", "conversation", "has", "new", "activity", ".", "2", ".", "Notifies", "existing", "followers", "of", "the", "viewpoint", "that", "metadata", "has", "changed", "." ]
def _Notify(self): """Creates notifications: 1. Notifies removed followers that conversation has new activity. 2. Notifies existing followers of the viewpoint that metadata has changed. """ # Creates notifications for any revived followers. yield NotificationManager.NotifyReviveFollowers(self._client, self._viewpoint_id, self._revive_follower_ids, self._op.timestamp) # Notifies followers that viewpoint metadata has changed. yield NotificationManager.NotifyUpdateViewpoint(self._client, self._vp_dict, self._followers, self._prev_values, self._act_dict)
[ "def", "_Notify", "(", "self", ")", ":", "# Creates notifications for any revived followers.", "yield", "NotificationManager", ".", "NotifyReviveFollowers", "(", "self", ".", "_client", ",", "self", ".", "_viewpoint_id", ",", "self", ".", "_revive_follower_ids", ",", "self", ".", "_op", ".", "timestamp", ")", "# Notifies followers that viewpoint metadata has changed.", "yield", "NotificationManager", ".", "NotifyUpdateViewpoint", "(", "self", ".", "_client", ",", "self", ".", "_vp_dict", ",", "self", ".", "_followers", ",", "self", ".", "_prev_values", ",", "self", ".", "_act_dict", ")" ]
https://github.com/viewfinderco/viewfinder/blob/453845b5d64ab5b3b826c08b02546d1ca0a07c14/backend/op/update_viewpoint_op.py#L162-L178
ICLRandD/Blackstone
4dadee00bc1f9bc3b44ba93f2d03b5e8a40516aa
blackstone/utils/legislation_linker.py
python
filter_spans
(spans)
return result
Filter out overlapping spans. Returns a list of Spans.
Filter out overlapping spans. Returns a list of Spans.
[ "Filter", "out", "overlapping", "spans", ".", "Returns", "a", "list", "of", "Spans", "." ]
def filter_spans(spans) -> List[Span]: """ Filter out overlapping spans. Returns a list of Spans. """ def get_sort_key(span: Span): return (span.end - span.start, span.start) sorted_spans = sorted(spans, key=get_sort_key, reverse=True) result = [] seen_tokens = set() for span in sorted_spans: if span.start not in seen_tokens and span.end - 1 not in seen_tokens: result.append(span) seen_tokens.update(range(span.start, span.end)) return result
[ "def", "filter_spans", "(", "spans", ")", "->", "List", "[", "Span", "]", ":", "def", "get_sort_key", "(", "span", ":", "Span", ")", ":", "return", "(", "span", ".", "end", "-", "span", ".", "start", ",", "span", ".", "start", ")", "sorted_spans", "=", "sorted", "(", "spans", ",", "key", "=", "get_sort_key", ",", "reverse", "=", "True", ")", "result", "=", "[", "]", "seen_tokens", "=", "set", "(", ")", "for", "span", "in", "sorted_spans", ":", "if", "span", ".", "start", "not", "in", "seen_tokens", "and", "span", ".", "end", "-", "1", "not", "in", "seen_tokens", ":", "result", ".", "append", "(", "span", ")", "seen_tokens", ".", "update", "(", "range", "(", "span", ".", "start", ",", "span", ".", "end", ")", ")", "return", "result" ]
https://github.com/ICLRandD/Blackstone/blob/4dadee00bc1f9bc3b44ba93f2d03b5e8a40516aa/blackstone/utils/legislation_linker.py#L27-L42
jupyterhub/dockerspawner
87938e64fd3ca9a3e6170144fa6395502e3dba34
dockerspawner/dockerspawner.py
python
DockerSpawner.docker
(self, method, *args, **kwargs)
return asyncio.wrap_future( self.executor.submit(self._docker, method, *args, **kwargs) )
Call a docker method in a background thread returns a Future
Call a docker method in a background thread
[ "Call", "a", "docker", "method", "in", "a", "background", "thread" ]
def docker(self, method, *args, **kwargs): """Call a docker method in a background thread returns a Future """ return asyncio.wrap_future( self.executor.submit(self._docker, method, *args, **kwargs) )
[ "def", "docker", "(", "self", ",", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "asyncio", ".", "wrap_future", "(", "self", ".", "executor", ".", "submit", "(", "self", ".", "_docker", ",", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/jupyterhub/dockerspawner/blob/87938e64fd3ca9a3e6170144fa6395502e3dba34/dockerspawner/dockerspawner.py#L960-L967
mesalock-linux/mesapy
ed546d59a21b36feb93e2309d5c6b75aa0ad95c9
lib_pypy/cffi/_pycparser/c_parser.py
python
CParser.p_declaration_specifiers_3
(self, p)
declaration_specifiers : storage_class_specifier declaration_specifiers_opt
declaration_specifiers : storage_class_specifier declaration_specifiers_opt
[ "declaration_specifiers", ":", "storage_class_specifier", "declaration_specifiers_opt" ]
def p_declaration_specifiers_3(self, p): """ declaration_specifiers : storage_class_specifier declaration_specifiers_opt """ p[0] = self._add_declaration_specifier(p[2], p[1], 'storage')
[ "def", "p_declaration_specifiers_3", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "self", ".", "_add_declaration_specifier", "(", "p", "[", "2", "]", ",", "p", "[", "1", "]", ",", "'storage'", ")" ]
https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/lib_pypy/cffi/_pycparser/c_parser.py#L688-L691
kbandla/ImmunityDebugger
2abc03fb15c8f3ed0914e1175c4d8933977c73e3
1.74/PyCommands/funsniff.py
python
RtlAllocateHeapHook.run
(self,regs)
This will be executed when hooktype happens
This will be executed when hooktype happens
[ "This", "will", "be", "executed", "when", "hooktype", "happens" ]
def run(self,regs): """This will be executed when hooktype happens""" imm = immlib.Debugger() readaddr="" size="" res=imm.readMemory( regs['EBP'] + 8, 0xc) if len(res) != 0xc or not res: imm.log("RtlAllocateHeap: ESP seems to broken, unable to get args") return 0x0 (heap, flags, size) = struct.unpack("LLL", res) #imm.log("RtlAllocateHeap(0x%08x, 0x%08x, 0x%08x)" % (heap, flags, size)) called = imm.getKnowledge( "heap_%08x" % self.hookaddr ) if not called: called = [] try: callstack = imm.readLong( regs['EBP'] + 4) except Exception: callstack = 0x0 called.append( (1, callstack, heap, flags, size, regs['EAX'] ) ) imm.addKnowledge("heap_%08x" % self.hookaddr, called, force_add = 0x1)
[ "def", "run", "(", "self", ",", "regs", ")", ":", "imm", "=", "immlib", ".", "Debugger", "(", ")", "readaddr", "=", "\"\"", "size", "=", "\"\"", "res", "=", "imm", ".", "readMemory", "(", "regs", "[", "'EBP'", "]", "+", "8", ",", "0xc", ")", "if", "len", "(", "res", ")", "!=", "0xc", "or", "not", "res", ":", "imm", ".", "log", "(", "\"RtlAllocateHeap: ESP seems to broken, unable to get args\"", ")", "return", "0x0", "(", "heap", ",", "flags", ",", "size", ")", "=", "struct", ".", "unpack", "(", "\"LLL\"", ",", "res", ")", "#imm.log(\"RtlAllocateHeap(0x%08x, 0x%08x, 0x%08x)\" % (heap, flags, size)) ", "called", "=", "imm", ".", "getKnowledge", "(", "\"heap_%08x\"", "%", "self", ".", "hookaddr", ")", "if", "not", "called", ":", "called", "=", "[", "]", "try", ":", "callstack", "=", "imm", ".", "readLong", "(", "regs", "[", "'EBP'", "]", "+", "4", ")", "except", "Exception", ":", "callstack", "=", "0x0", "called", ".", "append", "(", "(", "1", ",", "callstack", ",", "heap", ",", "flags", ",", "size", ",", "regs", "[", "'EAX'", "]", ")", ")", "imm", ".", "addKnowledge", "(", "\"heap_%08x\"", "%", "self", ".", "hookaddr", ",", "called", ",", "force_add", "=", "0x1", ")" ]
https://github.com/kbandla/ImmunityDebugger/blob/2abc03fb15c8f3ed0914e1175c4d8933977c73e3/1.74/PyCommands/funsniff.py#L31-L52
thu-coai/CrossWOZ
265e97379b34221f5949beb46f3eec0e2dc943c4
convlab2/util/allennlp_file_utils.py
python
s3_get
(url: str, temp_file: IO)
Pull a file directly from S3.
Pull a file directly from S3.
[ "Pull", "a", "file", "directly", "from", "S3", "." ]
def s3_get(url: str, temp_file: IO) -> None: """Pull a file directly from S3.""" s3_resource = get_s3_resource() bucket_name, s3_path = split_s3_path(url) s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)
[ "def", "s3_get", "(", "url", ":", "str", ",", "temp_file", ":", "IO", ")", "->", "None", ":", "s3_resource", "=", "get_s3_resource", "(", ")", "bucket_name", ",", "s3_path", "=", "split_s3_path", "(", "url", ")", "s3_resource", ".", "Bucket", "(", "bucket_name", ")", ".", "download_fileobj", "(", "s3_path", ",", "temp_file", ")" ]
https://github.com/thu-coai/CrossWOZ/blob/265e97379b34221f5949beb46f3eec0e2dc943c4/convlab2/util/allennlp_file_utils.py#L218-L222
taoxugit/AttnGAN
0d000e652b407e976cb88fab299e8566f3de8a37
code/miscc/config.py
python
_merge_a_into_b
(a, b)
Merge config dictionary a into config dictionary b, clobbering the options in b whenever they are also specified in a.
Merge config dictionary a into config dictionary b, clobbering the options in b whenever they are also specified in a.
[ "Merge", "config", "dictionary", "a", "into", "config", "dictionary", "b", "clobbering", "the", "options", "in", "b", "whenever", "they", "are", "also", "specified", "in", "a", "." ]
def _merge_a_into_b(a, b): """Merge config dictionary a into config dictionary b, clobbering the options in b whenever they are also specified in a. """ if type(a) is not edict: return for k, v in a.iteritems(): # a must specify keys that are in b if not b.has_key(k): raise KeyError('{} is not a valid config key'.format(k)) # the types must match, too old_type = type(b[k]) if old_type is not type(v): if isinstance(b[k], np.ndarray): v = np.array(v, dtype=b[k].dtype) else: raise ValueError(('Type mismatch ({} vs. {}) ' 'for config key: {}').format(type(b[k]), type(v), k)) # recursively merge dicts if type(v) is edict: try: _merge_a_into_b(a[k], b[k]) except: print('Error under config key: {}'.format(k)) raise else: b[k] = v
[ "def", "_merge_a_into_b", "(", "a", ",", "b", ")", ":", "if", "type", "(", "a", ")", "is", "not", "edict", ":", "return", "for", "k", ",", "v", "in", "a", ".", "iteritems", "(", ")", ":", "# a must specify keys that are in b", "if", "not", "b", ".", "has_key", "(", "k", ")", ":", "raise", "KeyError", "(", "'{} is not a valid config key'", ".", "format", "(", "k", ")", ")", "# the types must match, too", "old_type", "=", "type", "(", "b", "[", "k", "]", ")", "if", "old_type", "is", "not", "type", "(", "v", ")", ":", "if", "isinstance", "(", "b", "[", "k", "]", ",", "np", ".", "ndarray", ")", ":", "v", "=", "np", ".", "array", "(", "v", ",", "dtype", "=", "b", "[", "k", "]", ".", "dtype", ")", "else", ":", "raise", "ValueError", "(", "(", "'Type mismatch ({} vs. {}) '", "'for config key: {}'", ")", ".", "format", "(", "type", "(", "b", "[", "k", "]", ")", ",", "type", "(", "v", ")", ",", "k", ")", ")", "# recursively merge dicts", "if", "type", "(", "v", ")", "is", "edict", ":", "try", ":", "_merge_a_into_b", "(", "a", "[", "k", "]", ",", "b", "[", "k", "]", ")", "except", ":", "print", "(", "'Error under config key: {}'", ".", "format", "(", "k", ")", ")", "raise", "else", ":", "b", "[", "k", "]", "=", "v" ]
https://github.com/taoxugit/AttnGAN/blob/0d000e652b407e976cb88fab299e8566f3de8a37/code/miscc/config.py#L66-L96
aarongarrett/inspyred
f744e3655afb3534eb3a6ae478a5e0d725e91594
travis_pypi_setup.py
python
prepend_line
(filepath, line)
Rewrite a file adding a line to its beginning.
Rewrite a file adding a line to its beginning.
[ "Rewrite", "a", "file", "adding", "a", "line", "to", "its", "beginning", "." ]
def prepend_line(filepath, line): """Rewrite a file adding a line to its beginning. """ with open(filepath) as f: lines = f.readlines() lines.insert(0, line) with open(filepath, 'w') as f: f.writelines(lines)
[ "def", "prepend_line", "(", "filepath", ",", "line", ")", ":", "with", "open", "(", "filepath", ")", "as", "f", ":", "lines", "=", "f", ".", "readlines", "(", ")", "lines", ".", "insert", "(", "0", ",", "line", ")", "with", "open", "(", "filepath", ",", "'w'", ")", "as", "f", ":", "f", ".", "writelines", "(", "lines", ")" ]
https://github.com/aarongarrett/inspyred/blob/f744e3655afb3534eb3a6ae478a5e0d725e91594/travis_pypi_setup.py#L69-L78
TengXiaoDai/DistributedCrawling
f5c2439e6ce68dd9b49bde084d76473ff9ed4963
Lib/site-packages/pkg_resources/__init__.py
python
EntryPoint.parse_map
(cls, data, dist=None)
return maps
Parse a map of entry point groups
Parse a map of entry point groups
[ "Parse", "a", "map", "of", "entry", "point", "groups" ]
def parse_map(cls, data, dist=None): """Parse a map of entry point groups""" if isinstance(data, dict): data = data.items() else: data = split_sections(data) maps = {} for group, lines in data: if group is None: if not lines: continue raise ValueError("Entry points must be listed in groups") group = group.strip() if group in maps: raise ValueError("Duplicate group name", group) maps[group] = cls.parse_group(group, lines, dist) return maps
[ "def", "parse_map", "(", "cls", ",", "data", ",", "dist", "=", "None", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "data", "=", "data", ".", "items", "(", ")", "else", ":", "data", "=", "split_sections", "(", "data", ")", "maps", "=", "{", "}", "for", "group", ",", "lines", "in", "data", ":", "if", "group", "is", "None", ":", "if", "not", "lines", ":", "continue", "raise", "ValueError", "(", "\"Entry points must be listed in groups\"", ")", "group", "=", "group", ".", "strip", "(", ")", "if", "group", "in", "maps", ":", "raise", "ValueError", "(", "\"Duplicate group name\"", ",", "group", ")", "maps", "[", "group", "]", "=", "cls", ".", "parse_group", "(", "group", ",", "lines", ",", "dist", ")", "return", "maps" ]
https://github.com/TengXiaoDai/DistributedCrawling/blob/f5c2439e6ce68dd9b49bde084d76473ff9ed4963/Lib/site-packages/pkg_resources/__init__.py#L2379-L2395
cangermueller/deepcpg
7f58da5423121168edabb27202c234df0f0e460d
deepcpg/metrics.py
python
cat_acc
(y, z)
return _acc
Compute categorical accuracy given one-hot matrices.
Compute categorical accuracy given one-hot matrices.
[ "Compute", "categorical", "accuracy", "given", "one", "-", "hot", "matrices", "." ]
def cat_acc(y, z): """Compute categorical accuracy given one-hot matrices.""" weights = _cat_sample_weights(y) _acc = K.cast(K.equal(K.argmax(y, axis=-1), K.argmax(z, axis=-1)), K.floatx()) _acc = K.sum(_acc * weights) / K.sum(weights) return _acc
[ "def", "cat_acc", "(", "y", ",", "z", ")", ":", "weights", "=", "_cat_sample_weights", "(", "y", ")", "_acc", "=", "K", ".", "cast", "(", "K", ".", "equal", "(", "K", ".", "argmax", "(", "y", ",", "axis", "=", "-", "1", ")", ",", "K", ".", "argmax", "(", "z", ",", "axis", "=", "-", "1", ")", ")", ",", "K", ".", "floatx", "(", ")", ")", "_acc", "=", "K", ".", "sum", "(", "_acc", "*", "weights", ")", "/", "K", ".", "sum", "(", "weights", ")", "return", "_acc" ]
https://github.com/cangermueller/deepcpg/blob/7f58da5423121168edabb27202c234df0f0e460d/deepcpg/metrics.py#L102-L109
bikalims/bika.lims
35e4bbdb5a3912cae0b5eb13e51097c8b0486349
bika/lims/exportimport/instruments/shimadzu/icpe/multitype.py
python
ICPEMultitypeCSVParser.__init__
(self, csv)
[]
def __init__(self, csv): InstrumentCSVResultsFileParser.__init__(self, csv) self._end_header = False self._quantitationresultsheader = [] self._numline = 0
[ "def", "__init__", "(", "self", ",", "csv", ")", ":", "InstrumentCSVResultsFileParser", ".", "__init__", "(", "self", ",", "csv", ")", "self", ".", "_end_header", "=", "False", "self", ".", "_quantitationresultsheader", "=", "[", "]", "self", ".", "_numline", "=", "0" ]
https://github.com/bikalims/bika.lims/blob/35e4bbdb5a3912cae0b5eb13e51097c8b0486349/bika/lims/exportimport/instruments/shimadzu/icpe/multitype.py#L110-L114
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/polynet.py
python
ReductionB.__init__
(self)
[]
def __init__(self): super(ReductionB, self).__init__() self.path0 = nn.Sequential( BasicConv2d(1152, 256, kernel_size=1), BasicConv2d(256, 256, kernel_size=3, padding=1), BasicConv2d(256, 256, kernel_size=3, stride=2), ) self.path1 = nn.Sequential( BasicConv2d(1152, 256, kernel_size=1), BasicConv2d(256, 256, kernel_size=3, stride=2), ) self.path2 = nn.Sequential( BasicConv2d(1152, 256, kernel_size=1), BasicConv2d(256, 384, kernel_size=3, stride=2), ) self.path3 = nn.MaxPool2d(3, stride=2)
[ "def", "__init__", "(", "self", ")", ":", "super", "(", "ReductionB", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "path0", "=", "nn", ".", "Sequential", "(", "BasicConv2d", "(", "1152", ",", "256", ",", "kernel_size", "=", "1", ")", ",", "BasicConv2d", "(", "256", ",", "256", ",", "kernel_size", "=", "3", ",", "padding", "=", "1", ")", ",", "BasicConv2d", "(", "256", ",", "256", ",", "kernel_size", "=", "3", ",", "stride", "=", "2", ")", ",", ")", "self", ".", "path1", "=", "nn", ".", "Sequential", "(", "BasicConv2d", "(", "1152", ",", "256", ",", "kernel_size", "=", "1", ")", ",", "BasicConv2d", "(", "256", ",", "256", ",", "kernel_size", "=", "3", ",", "stride", "=", "2", ")", ",", ")", "self", ".", "path2", "=", "nn", ".", "Sequential", "(", "BasicConv2d", "(", "1152", ",", "256", ",", "kernel_size", "=", "1", ")", ",", "BasicConv2d", "(", "256", ",", "384", ",", "kernel_size", "=", "3", ",", "stride", "=", "2", ")", ",", ")", "self", ".", "path3", "=", "nn", ".", "MaxPool2d", "(", "3", ",", "stride", "=", "2", ")" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/polynet.py#L203-L218
savon-noir/python-libnmap
8f442747a7a16969309d6f7653ad1b13a3a99bae
libnmap/objects/os.py
python
NmapOSMatch.name
(self)
return self._name
Accessor for name attribute (e.g.: Linux 2.4.26 (Slackware 10.0.0))
Accessor for name attribute (e.g.: Linux 2.4.26 (Slackware 10.0.0))
[ "Accessor", "for", "name", "attribute", "(", "e", ".", "g", ".", ":", "Linux", "2", ".", "4", ".", "26", "(", "Slackware", "10", ".", "0", ".", "0", "))" ]
def name(self): """ Accessor for name attribute (e.g.: Linux 2.4.26 (Slackware 10.0.0)) """ return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
https://github.com/savon-noir/python-libnmap/blob/8f442747a7a16969309d6f7653ad1b13a3a99bae/libnmap/objects/os.py#L108-L112
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/rest_framework/utils/formatting.py
python
camelcase_to_spaces
(content)
return ' '.join(content.split('_')).title()
Translate 'CamelCaseNames' to 'Camel Case Names'. Used when generating names from view classes.
Translate 'CamelCaseNames' to 'Camel Case Names'. Used when generating names from view classes.
[ "Translate", "CamelCaseNames", "to", "Camel", "Case", "Names", ".", "Used", "when", "generating", "names", "from", "view", "classes", "." ]
def camelcase_to_spaces(content): """ Translate 'CamelCaseNames' to 'Camel Case Names'. Used when generating names from view classes. """ camelcase_boundary = '(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))' content = re.sub(camelcase_boundary, ' \\1', content).strip() return ' '.join(content.split('_')).title()
[ "def", "camelcase_to_spaces", "(", "content", ")", ":", "camelcase_boundary", "=", "'(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))'", "content", "=", "re", ".", "sub", "(", "camelcase_boundary", ",", "' \\\\1'", ",", "content", ")", ".", "strip", "(", ")", "return", "' '", ".", "join", "(", "content", ".", "split", "(", "'_'", ")", ")", ".", "title", "(", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/rest_framework/utils/formatting.py#L50-L57
turicas/brasil.io
f1c371fe828a090510259a5027b49e2e651936b4
covid19/spreadsheet_validator.py
python
_get_column_name
(field_names, options)
return valid_columns[0]
[]
def _get_column_name(field_names, options): # XXX: this function expects all keys already in lowercase and slugified by `rows` library valid_columns = [key for key in field_names if key in options] if not valid_columns: raise ValueError(f"A coluna '{options[0]}' não existe") elif len(valid_columns) > 1: raise ValueError(f"Foi encontrada mais de uma coluna possível para '{options[0]}'") return valid_columns[0]
[ "def", "_get_column_name", "(", "field_names", ",", "options", ")", ":", "# XXX: this function expects all keys already in lowercase and slugified by `rows` library", "valid_columns", "=", "[", "key", "for", "key", "in", "field_names", "if", "key", "in", "options", "]", "if", "not", "valid_columns", ":", "raise", "ValueError", "(", "f\"A coluna '{options[0]}' não existe\")", "", "elif", "len", "(", "valid_columns", ")", ">", "1", ":", "raise", "ValueError", "(", "f\"Foi encontrada mais de uma coluna possível para '{options[0]}'\")", "", "return", "valid_columns", "[", "0", "]" ]
https://github.com/turicas/brasil.io/blob/f1c371fe828a090510259a5027b49e2e651936b4/covid19/spreadsheet_validator.py#L149-L156
nsupdate-info/nsupdate.info
7285eca1446de5aff60f82315fc1367e454e9032
src/nsupdate/main/iptools.py
python
normalize_mapped_address
(ipaddr)
return str(ipaddr)
Converts a IPv4-mapped IPv6 address into a IPv4 address. Handles both the ::ffff:192.0.2.128 format as well as the deprecated ::192.0.2.128 format. :param ipaddr: IP address [str] :return: normalized IP address [str]
Converts a IPv4-mapped IPv6 address into a IPv4 address. Handles both the ::ffff:192.0.2.128 format as well as the deprecated ::192.0.2.128 format.
[ "Converts", "a", "IPv4", "-", "mapped", "IPv6", "address", "into", "a", "IPv4", "address", ".", "Handles", "both", "the", "::", "ffff", ":", "192", ".", "0", ".", "2", ".", "128", "format", "as", "well", "as", "the", "deprecated", "::", "192", ".", "0", ".", "2", ".", "128", "format", "." ]
def normalize_mapped_address(ipaddr): """ Converts a IPv4-mapped IPv6 address into a IPv4 address. Handles both the ::ffff:192.0.2.128 format as well as the deprecated ::192.0.2.128 format. :param ipaddr: IP address [str] :return: normalized IP address [str] """ ipaddr = IPAddress(ipaddr) if ipaddr.is_ipv4_compat() or ipaddr.is_ipv4_mapped(): ipaddr = ipaddr.ipv4() return str(ipaddr)
[ "def", "normalize_mapped_address", "(", "ipaddr", ")", ":", "ipaddr", "=", "IPAddress", "(", "ipaddr", ")", "if", "ipaddr", ".", "is_ipv4_compat", "(", ")", "or", "ipaddr", ".", "is_ipv4_mapped", "(", ")", ":", "ipaddr", "=", "ipaddr", ".", "ipv4", "(", ")", "return", "str", "(", "ipaddr", ")" ]
https://github.com/nsupdate-info/nsupdate.info/blob/7285eca1446de5aff60f82315fc1367e454e9032/src/nsupdate/main/iptools.py#L8-L19
rll/rllab
ba78e4c16dc492982e648f117875b22af3965579
rllab/algos/cma_es_lib.py
python
Sections.do
(self, repetitions=1, locations=np.arange(-0.5, 0.6, 0.2), plot=True)
return self
generates, plots and saves function values ``func(y)``, where ``y`` is 'close' to `x` (see `__init__()`). The data are stored in the ``res`` attribute and the class instance is saved in a file with (the weired) name ``str(func)``. Parameters ---------- `repetitions` for each point, only for noisy functions is >1 useful. For ``repetitions==0`` only already generated data are plotted. `locations` coordinated wise deviations from the middle point given in `__init__`
generates, plots and saves function values ``func(y)``, where ``y`` is 'close' to `x` (see `__init__()`). The data are stored in the ``res`` attribute and the class instance is saved in a file with (the weired) name ``str(func)``.
[ "generates", "plots", "and", "saves", "function", "values", "func", "(", "y", ")", "where", "y", "is", "close", "to", "x", "(", "see", "__init__", "()", ")", ".", "The", "data", "are", "stored", "in", "the", "res", "attribute", "and", "the", "class", "instance", "is", "saved", "in", "a", "file", "with", "(", "the", "weired", ")", "name", "str", "(", "func", ")", "." ]
def do(self, repetitions=1, locations=np.arange(-0.5, 0.6, 0.2), plot=True): """generates, plots and saves function values ``func(y)``, where ``y`` is 'close' to `x` (see `__init__()`). The data are stored in the ``res`` attribute and the class instance is saved in a file with (the weired) name ``str(func)``. Parameters ---------- `repetitions` for each point, only for noisy functions is >1 useful. For ``repetitions==0`` only already generated data are plotted. `locations` coordinated wise deviations from the middle point given in `__init__` """ if not repetitions: self.plot() return res = self.res for i in range(len(self.basis)): # i-th coordinate if i not in res: res[i] = {} # xx = np.array(self.x) # TODO: store res[i]['dx'] = self.basis[i] here? for dx in locations: xx = self.x + dx * self.basis[i] xkey = dx # xx[i] if (self.basis == np.eye(len(self.basis))).all() else dx if xkey not in res[i]: res[i][xkey] = [] n = repetitions while n > 0: n -= 1 res[i][xkey].append(self.func(xx, *self.args)) if plot: self.plot() self.save() return self
[ "def", "do", "(", "self", ",", "repetitions", "=", "1", ",", "locations", "=", "np", ".", "arange", "(", "-", "0.5", ",", "0.6", ",", "0.2", ")", ",", "plot", "=", "True", ")", ":", "if", "not", "repetitions", ":", "self", ".", "plot", "(", ")", "return", "res", "=", "self", ".", "res", "for", "i", "in", "range", "(", "len", "(", "self", ".", "basis", ")", ")", ":", "# i-th coordinate", "if", "i", "not", "in", "res", ":", "res", "[", "i", "]", "=", "{", "}", "# xx = np.array(self.x)", "# TODO: store res[i]['dx'] = self.basis[i] here?", "for", "dx", "in", "locations", ":", "xx", "=", "self", ".", "x", "+", "dx", "*", "self", ".", "basis", "[", "i", "]", "xkey", "=", "dx", "# xx[i] if (self.basis == np.eye(len(self.basis))).all() else dx", "if", "xkey", "not", "in", "res", "[", "i", "]", ":", "res", "[", "i", "]", "[", "xkey", "]", "=", "[", "]", "n", "=", "repetitions", "while", "n", ">", "0", ":", "n", "-=", "1", "res", "[", "i", "]", "[", "xkey", "]", ".", "append", "(", "self", ".", "func", "(", "xx", ",", "*", "self", ".", "args", ")", ")", "if", "plot", ":", "self", ".", "plot", "(", ")", "self", ".", "save", "(", ")", "return", "self" ]
https://github.com/rll/rllab/blob/ba78e4c16dc492982e648f117875b22af3965579/rllab/algos/cma_es_lib.py#L7212-L7249
angr/angr
4b04d56ace135018083d36d9083805be8146688b
angr/analyses/propagator/propagator.py
python
Equivalence.__hash__
(self)
return hash((Equivalence, self.codeloc, self.atom0, self.atom1))
[]
def __hash__(self): return hash((Equivalence, self.codeloc, self.atom0, self.atom1))
[ "def", "__hash__", "(", "self", ")", ":", "return", "hash", "(", "(", "Equivalence", ",", "self", ".", "codeloc", ",", "self", ".", "atom0", ",", "self", ".", "atom1", ")", ")" ]
https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/analyses/propagator/propagator.py#L257-L258
easezyc/deep-transfer-learning
9af0921f4f21bc2ccea61be53cf8e8a49873d613
UDA/pytorch1.0/MRAN/ResNet.py
python
ResNet.__init__
(self, block, layers, num_classes=1000)
[]
def __init__(self, block, layers, num_classes=1000): self.inplanes = 64 super(ResNet, self).__init__() self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(block, 64, layers[0]) self.layer2 = self._make_layer(block, 128, layers[1], stride=2) self.layer3 = self._make_layer(block, 256, layers[2], stride=2) self.layer4 = self._make_layer(block, 512, layers[3], stride=2) self.avgpool = nn.AvgPool2d(8, stride=1) self.baselayer = [self.conv1, self.bn1, self.layer1, self.layer2, self.layer3, self.layer4] self.fc = nn.Linear(512 * block.expansion, num_classes) for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_()
[ "def", "__init__", "(", "self", ",", "block", ",", "layers", ",", "num_classes", "=", "1000", ")", ":", "self", ".", "inplanes", "=", "64", "super", "(", "ResNet", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "conv1", "=", "nn", ".", "Conv2d", "(", "3", ",", "64", ",", "kernel_size", "=", "7", ",", "stride", "=", "2", ",", "padding", "=", "3", ",", "bias", "=", "False", ")", "self", ".", "bn1", "=", "nn", ".", "BatchNorm2d", "(", "64", ")", "self", ".", "relu", "=", "nn", ".", "ReLU", "(", "inplace", "=", "True", ")", "self", ".", "maxpool", "=", "nn", ".", "MaxPool2d", "(", "kernel_size", "=", "3", ",", "stride", "=", "2", ",", "padding", "=", "1", ")", "self", ".", "layer1", "=", "self", ".", "_make_layer", "(", "block", ",", "64", ",", "layers", "[", "0", "]", ")", "self", ".", "layer2", "=", "self", ".", "_make_layer", "(", "block", ",", "128", ",", "layers", "[", "1", "]", ",", "stride", "=", "2", ")", "self", ".", "layer3", "=", "self", ".", "_make_layer", "(", "block", ",", "256", ",", "layers", "[", "2", "]", ",", "stride", "=", "2", ")", "self", ".", "layer4", "=", "self", ".", "_make_layer", "(", "block", ",", "512", ",", "layers", "[", "3", "]", ",", "stride", "=", "2", ")", "self", ".", "avgpool", "=", "nn", ".", "AvgPool2d", "(", "8", ",", "stride", "=", "1", ")", "self", ".", "baselayer", "=", "[", "self", ".", "conv1", ",", "self", ".", "bn1", ",", "self", ".", "layer1", ",", "self", ".", "layer2", ",", "self", ".", "layer3", ",", "self", ".", "layer4", "]", "self", ".", "fc", "=", "nn", ".", "Linear", "(", "512", "*", "block", ".", "expansion", ",", "num_classes", ")", "for", "m", "in", "self", ".", "modules", "(", ")", ":", "if", "isinstance", "(", "m", ",", "nn", ".", "Conv2d", ")", ":", "n", "=", "m", ".", "kernel_size", "[", "0", "]", "*", "m", ".", "kernel_size", "[", "1", "]", "*", "m", ".", "out_channels", "m", ".", "weight", ".", "data", ".", "normal_", "(", "0", ",", "math", ".", "sqrt", "(", "2.", "/", "n", ")", ")", "elif", "isinstance", "(", "m", ",", "nn", ".", "BatchNorm2d", ")", ":", "m", ".", "weight", ".", "data", ".", "fill_", "(", "1", ")", "m", ".", "bias", ".", "data", ".", "zero_", "(", ")" ]
https://github.com/easezyc/deep-transfer-learning/blob/9af0921f4f21bc2ccea61be53cf8e8a49873d613/UDA/pytorch1.0/MRAN/ResNet.py#L97-L119
mapnik/python-mapnik
a2c2a86eec954b42d7f00093da03807d0834b1b4
mapnik/__init__.py
python
_Coord.inverse
(self, projection)
return inverse_(self, projection)
Projects the point from the cartesian space into the geographic space. The x component is considered to be the easting, the y component to be the northing. Returns the longitude (x) and latitude (y) as a coordinate pair. Example: Project the cartesian coordinates of the city center of Stuttgart in the local map projection (GK Zone 3/DHDN, EPSG 31467) into geographic coordinates: >>> p = Projection('+init=epsg:31467') >>> Coord(3507360.12813,5395719.2749).inverse(p) Coord(9.1, 48.7)
Projects the point from the cartesian space into the geographic space. The x component is considered to be the easting, the y component to be the northing.
[ "Projects", "the", "point", "from", "the", "cartesian", "space", "into", "the", "geographic", "space", ".", "The", "x", "component", "is", "considered", "to", "be", "the", "easting", "the", "y", "component", "to", "be", "the", "northing", "." ]
def inverse(self, projection): """ Projects the point from the cartesian space into the geographic space. The x component is considered to be the easting, the y component to be the northing. Returns the longitude (x) and latitude (y) as a coordinate pair. Example: Project the cartesian coordinates of the city center of Stuttgart in the local map projection (GK Zone 3/DHDN, EPSG 31467) into geographic coordinates: >>> p = Projection('+init=epsg:31467') >>> Coord(3507360.12813,5395719.2749).inverse(p) Coord(9.1, 48.7) """ return inverse_(self, projection)
[ "def", "inverse", "(", "self", ",", "projection", ")", ":", "return", "inverse_", "(", "self", ",", "projection", ")" ]
https://github.com/mapnik/python-mapnik/blob/a2c2a86eec954b42d7f00093da03807d0834b1b4/mapnik/__init__.py#L165-L183
qibinlou/SinaWeibo-Emotion-Classification
f336fc104abd68b0ec4180fe2ed80fafe49cb790
nltk/downloader.py
python
md5_hexdigest
(file)
return md5_digest.hexdigest()
Calculate and return the MD5 checksum for a given file. ``file`` may either be a filename or an open stream.
Calculate and return the MD5 checksum for a given file. ``file`` may either be a filename or an open stream.
[ "Calculate", "and", "return", "the", "MD5", "checksum", "for", "a", "given", "file", ".", "file", "may", "either", "be", "a", "filename", "or", "an", "open", "stream", "." ]
def md5_hexdigest(file): """ Calculate and return the MD5 checksum for a given file. ``file`` may either be a filename or an open stream. """ if isinstance(file, basestring): file = open(file, 'rb') md5_digest = md5() while True: block = file.read(1024*16) # 16k blocks if not block: break md5_digest.update(block) return md5_digest.hexdigest()
[ "def", "md5_hexdigest", "(", "file", ")", ":", "if", "isinstance", "(", "file", ",", "basestring", ")", ":", "file", "=", "open", "(", "file", ",", "'rb'", ")", "md5_digest", "=", "md5", "(", ")", "while", "True", ":", "block", "=", "file", ".", "read", "(", "1024", "*", "16", ")", "# 16k blocks", "if", "not", "block", ":", "break", "md5_digest", ".", "update", "(", "block", ")", "return", "md5_digest", ".", "hexdigest", "(", ")" ]
https://github.com/qibinlou/SinaWeibo-Emotion-Classification/blob/f336fc104abd68b0ec4180fe2ed80fafe49cb790/nltk/downloader.py#L1942-L1955
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/CPython/27/Lib/lib-tk/Tix.py
python
TixWidget.config_all
(self, option, value)
Set configuration options for all subwidgets (and self).
Set configuration options for all subwidgets (and self).
[ "Set", "configuration", "options", "for", "all", "subwidgets", "(", "and", "self", ")", "." ]
def config_all(self, option, value): """Set configuration options for all subwidgets (and self).""" if option == '': return elif not isinstance(option, StringType): option = repr(option) if not isinstance(value, StringType): value = repr(value) names = self._subwidget_names() for name in names: self.tk.call(name, 'configure', '-' + option, value)
[ "def", "config_all", "(", "self", ",", "option", ",", "value", ")", ":", "if", "option", "==", "''", ":", "return", "elif", "not", "isinstance", "(", "option", ",", "StringType", ")", ":", "option", "=", "repr", "(", "option", ")", "if", "not", "isinstance", "(", "value", ",", "StringType", ")", ":", "value", "=", "repr", "(", "value", ")", "names", "=", "self", ".", "_subwidget_names", "(", ")", "for", "name", "in", "names", ":", "self", ".", "tk", ".", "call", "(", "name", ",", "'configure'", ",", "'-'", "+", "option", ",", "value", ")" ]
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/CPython/27/Lib/lib-tk/Tix.py#L387-L397
yuxiaokui/Intranet-Penetration
f57678a204840c83cbf3308e3470ae56c5ff514b
proxy/XX-Net/code/default/gae_proxy/server/lib/google/appengine/tools/appcfg.py
python
IndexDefinitionUpload.DoUpload
(self)
Uploads the index definitions.
Uploads the index definitions.
[ "Uploads", "the", "index", "definitions", "." ]
def DoUpload(self): """Uploads the index definitions.""" StatusUpdate('Uploading index definitions.', self.error_fh) with TempChangeField(self.definitions, 'application', None) as app_id: self.rpcserver.Send('/api/datastore/index/add', app_id=app_id, payload=self.definitions.ToYAML())
[ "def", "DoUpload", "(", "self", ")", ":", "StatusUpdate", "(", "'Uploading index definitions.'", ",", "self", ".", "error_fh", ")", "with", "TempChangeField", "(", "self", ".", "definitions", ",", "'application'", ",", "None", ")", "as", "app_id", ":", "self", ".", "rpcserver", ".", "Send", "(", "'/api/datastore/index/add'", ",", "app_id", "=", "app_id", ",", "payload", "=", "self", ".", "definitions", ".", "ToYAML", "(", ")", ")" ]
https://github.com/yuxiaokui/Intranet-Penetration/blob/f57678a204840c83cbf3308e3470ae56c5ff514b/proxy/XX-Net/code/default/gae_proxy/server/lib/google/appengine/tools/appcfg.py#L606-L613
pygments/pygments
cd3ad20dfc8a6cb43e2c0b22b14446dcc0a554d7
pygments/scanner.py
python
Scanner.__init__
(self, text, flags=0)
:param text: The text which should be scanned :param flags: default regular expression flags
:param text: The text which should be scanned :param flags: default regular expression flags
[ ":", "param", "text", ":", "The", "text", "which", "should", "be", "scanned", ":", "param", "flags", ":", "default", "regular", "expression", "flags" ]
def __init__(self, text, flags=0): """ :param text: The text which should be scanned :param flags: default regular expression flags """ self.data = text self.data_length = len(text) self.start_pos = 0 self.pos = 0 self.flags = flags self.last = None self.match = None self._re_cache = {}
[ "def", "__init__", "(", "self", ",", "text", ",", "flags", "=", "0", ")", ":", "self", ".", "data", "=", "text", "self", ".", "data_length", "=", "len", "(", "text", ")", "self", ".", "start_pos", "=", "0", "self", ".", "pos", "=", "0", "self", ".", "flags", "=", "flags", "self", ".", "last", "=", "None", "self", ".", "match", "=", "None", "self", ".", "_re_cache", "=", "{", "}" ]
https://github.com/pygments/pygments/blob/cd3ad20dfc8a6cb43e2c0b22b14446dcc0a554d7/pygments/scanner.py#L35-L47
shiweibsw/Translation-Tools
2fbbf902364e557fa7017f9a74a8797b7440c077
venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/_vendor/distro.py
python
LinuxDistribution.info
(self, pretty=False, best=False)
return dict( id=self.id(), version=self.version(pretty, best), version_parts=dict( major=self.major_version(best), minor=self.minor_version(best), build_number=self.build_number(best) ), like=self.like(), codename=self.codename(), )
Return certain machine-readable information about the Linux distribution. For details, see :func:`distro.info`.
Return certain machine-readable information about the Linux distribution.
[ "Return", "certain", "machine", "-", "readable", "information", "about", "the", "Linux", "distribution", "." ]
def info(self, pretty=False, best=False): """ Return certain machine-readable information about the Linux distribution. For details, see :func:`distro.info`. """ return dict( id=self.id(), version=self.version(pretty, best), version_parts=dict( major=self.major_version(best), minor=self.minor_version(best), build_number=self.build_number(best) ), like=self.like(), codename=self.codename(), )
[ "def", "info", "(", "self", ",", "pretty", "=", "False", ",", "best", "=", "False", ")", ":", "return", "dict", "(", "id", "=", "self", ".", "id", "(", ")", ",", "version", "=", "self", ".", "version", "(", "pretty", ",", "best", ")", ",", "version_parts", "=", "dict", "(", "major", "=", "self", ".", "major_version", "(", "best", ")", ",", "minor", "=", "self", ".", "minor_version", "(", "best", ")", ",", "build_number", "=", "self", ".", "build_number", "(", "best", ")", ")", ",", "like", "=", "self", ".", "like", "(", ")", ",", "codename", "=", "self", ".", "codename", "(", ")", ",", ")" ]
https://github.com/shiweibsw/Translation-Tools/blob/2fbbf902364e557fa7017f9a74a8797b7440c077/venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/_vendor/distro.py#L761-L778
marionmari/pyGPs
792f3c6cb91126ade9f23a8e39d9cbcd30cfbc7b
pyGPs/Core/mean.py
python
Mean.getDerMatrix
(self, x=None, der=None)
Compute derivatives wrt. hyperparameters. :param x: training inputs :param int der: index of hyperparameter whose derivative to be computed :return: the corresponding derivative matrix
Compute derivatives wrt. hyperparameters.
[ "Compute", "derivatives", "wrt", ".", "hyperparameters", "." ]
def getDerMatrix(self, x=None, der=None): ''' Compute derivatives wrt. hyperparameters. :param x: training inputs :param int der: index of hyperparameter whose derivative to be computed :return: the corresponding derivative matrix ''' pass
[ "def", "getDerMatrix", "(", "self", ",", "x", "=", "None", ",", "der", "=", "None", ")", ":", "pass" ]
https://github.com/marionmari/pyGPs/blob/792f3c6cb91126ade9f23a8e39d9cbcd30cfbc7b/pyGPs/Core/mean.py#L127-L136
facebookresearch/ParlAI
e4d59c30eef44f1f67105961b82a83fd28d7d78b
parlai/core/mutators.py
python
EpisodeMutator.episode_mutation
(self, episode: List[Message])
Abstract episode mutation. The main method to implement when implementing an EpisodeMutator. The "episode_done" field will be automatically stripped before providing as input, and automatically added back to the finalized episode. :param messages: All the messages in one episode. You may manipulate any or all of them, or change the ordering entirely. :returns: The new, mutated episode.
Abstract episode mutation.
[ "Abstract", "episode", "mutation", "." ]
def episode_mutation(self, episode: List[Message]) -> List[Message]: """ Abstract episode mutation. The main method to implement when implementing an EpisodeMutator. The "episode_done" field will be automatically stripped before providing as input, and automatically added back to the finalized episode. :param messages: All the messages in one episode. You may manipulate any or all of them, or change the ordering entirely. :returns: The new, mutated episode. """ pass
[ "def", "episode_mutation", "(", "self", ",", "episode", ":", "List", "[", "Message", "]", ")", "->", "List", "[", "Message", "]", ":", "pass" ]
https://github.com/facebookresearch/ParlAI/blob/e4d59c30eef44f1f67105961b82a83fd28d7d78b/parlai/core/mutators.py#L198-L213
Qiskit/qiskit-terra
b66030e3b9192efdd3eb95cf25c6545fe0a13da4
qiskit/pulse/parameter_manager.py
python
ParameterGetter.visit_ScheduleBlock
(self, node: ScheduleBlock)
Visit ``ScheduleBlock``. Recursively visit context blocks and search parameters. .. note:: ``ScheduleBlock`` can have parameters in blocks and its alignment.
Visit ``ScheduleBlock``. Recursively visit context blocks and search parameters.
[ "Visit", "ScheduleBlock", ".", "Recursively", "visit", "context", "blocks", "and", "search", "parameters", "." ]
def visit_ScheduleBlock(self, node: ScheduleBlock): """Visit ``ScheduleBlock``. Recursively visit context blocks and search parameters. .. note:: ``ScheduleBlock`` can have parameters in blocks and its alignment. """ for parameter in node.parameters: self.parameters.add(parameter)
[ "def", "visit_ScheduleBlock", "(", "self", ",", "node", ":", "ScheduleBlock", ")", ":", "for", "parameter", "in", "node", ".", "parameters", ":", "self", ".", "parameters", ".", "add", "(", "parameter", ")" ]
https://github.com/Qiskit/qiskit-terra/blob/b66030e3b9192efdd3eb95cf25c6545fe0a13da4/qiskit/pulse/parameter_manager.py#L277-L283
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/lib-tk/Tkinter.py
python
Menu.insert_checkbutton
(self, index, cnf={}, **kw)
Add checkbutton menu item at INDEX.
Add checkbutton menu item at INDEX.
[ "Add", "checkbutton", "menu", "item", "at", "INDEX", "." ]
def insert_checkbutton(self, index, cnf={}, **kw): """Add checkbutton menu item at INDEX.""" self.insert(index, 'checkbutton', cnf or kw)
[ "def", "insert_checkbutton", "(", "self", ",", "index", ",", "cnf", "=", "{", "}", ",", "*", "*", "kw", ")", ":", "self", ".", "insert", "(", "index", ",", "'checkbutton'", ",", "cnf", "or", "kw", ")" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/lib-tk/Tkinter.py#L2697-L2699
chadmv/cmt
1b1a9a4fb154d1d10e73373cf899e4d83c95a6a1
scripts/cmt/rig/control.py
python
documentation
()
[]
def documentation(): webbrowser.open(HELP_URL)
[ "def", "documentation", "(", ")", ":", "webbrowser", ".", "open", "(", "HELP_URL", ")" ]
https://github.com/chadmv/cmt/blob/1b1a9a4fb154d1d10e73373cf899e4d83c95a6a1/scripts/cmt/rig/control.py#L411-L412
FederatedAI/FATE
32540492623568ecd1afcb367360133616e02fa3
python/fate_arch/federation/pulsar/_pulsar_manager.py
python
PulsarManager.get_cluster
(self, cluster_name: str = '')
return response
[]
def get_cluster(self, cluster_name: str = ''): session = self._create_session() response = session.get( self.service_url + CLUSTER.format(cluster_name)) return response
[ "def", "get_cluster", "(", "self", ",", "cluster_name", ":", "str", "=", "''", ")", ":", "session", "=", "self", ".", "_create_session", "(", ")", "response", "=", "session", ".", "get", "(", "self", ".", "service_url", "+", "CLUSTER", ".", "format", "(", "cluster_name", ")", ")", "return", "response" ]
https://github.com/FederatedAI/FATE/blob/32540492623568ecd1afcb367360133616e02fa3/python/fate_arch/federation/pulsar/_pulsar_manager.py#L55-L59
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-47/fabmetheus_utilities/fabmetheus_tools/interpret_plugins/xml.py
python
getPluginsDirectoryPath
()
return archive.getInterpretPluginsPath('xml_plugins')
Get the plugins directory path.
Get the plugins directory path.
[ "Get", "the", "plugins", "directory", "path", "." ]
def getPluginsDirectoryPath(): "Get the plugins directory path." return archive.getInterpretPluginsPath('xml_plugins')
[ "def", "getPluginsDirectoryPath", "(", ")", ":", "return", "archive", ".", "getInterpretPluginsPath", "(", "'xml_plugins'", ")" ]
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-47/fabmetheus_utilities/fabmetheus_tools/interpret_plugins/xml.py#L118-L120
bookwyrm-social/bookwyrm
0c2537e27a2cdbc0136880dfbbf170d5fec72986
bookwyrm/utils/isni.py
python
request_isni_data
(search_index, search_term, max_records=5)
return result.text
Request data from the ISNI API
Request data from the ISNI API
[ "Request", "data", "from", "the", "ISNI", "API" ]
def request_isni_data(search_index, search_term, max_records=5): """Request data from the ISNI API""" search_string = f'{search_index}="{search_term}"' query_params = { "query": search_string, "version": "1.1", "operation": "searchRetrieve", "recordSchema": "isni-b", "maximumRecords": max_records, "startRecord": "1", "recordPacking": "xml", "sortKeys": "RLV,pica,0,,", } result = requests.get("http://isni.oclc.org/sru/", params=query_params, timeout=15) # the OCLC ISNI server asserts the payload is encoded # in latin1, but we know better result.encoding = "utf-8" return result.text
[ "def", "request_isni_data", "(", "search_index", ",", "search_term", ",", "max_records", "=", "5", ")", ":", "search_string", "=", "f'{search_index}=\"{search_term}\"'", "query_params", "=", "{", "\"query\"", ":", "search_string", ",", "\"version\"", ":", "\"1.1\"", ",", "\"operation\"", ":", "\"searchRetrieve\"", ",", "\"recordSchema\"", ":", "\"isni-b\"", ",", "\"maximumRecords\"", ":", "max_records", ",", "\"startRecord\"", ":", "\"1\"", ",", "\"recordPacking\"", ":", "\"xml\"", ",", "\"sortKeys\"", ":", "\"RLV,pica,0,,\"", ",", "}", "result", "=", "requests", ".", "get", "(", "\"http://isni.oclc.org/sru/\"", ",", "params", "=", "query_params", ",", "timeout", "=", "15", ")", "# the OCLC ISNI server asserts the payload is encoded", "# in latin1, but we know better", "result", ".", "encoding", "=", "\"utf-8\"", "return", "result", ".", "text" ]
https://github.com/bookwyrm-social/bookwyrm/blob/0c2537e27a2cdbc0136880dfbbf170d5fec72986/bookwyrm/utils/isni.py#L8-L26
vulscanteam/vulscan
787397e267c4e6469522ee0abe55b3e98f968d4a
pocsuite/thirdparty/requests/packages/urllib3/response.py
python
HTTPResponse.from_httplib
(ResponseCls, r, **response_kw)
return resp
Given an :class:`httplib.HTTPResponse` instance ``r``, return a corresponding :class:`urllib3.response.HTTPResponse` object. Remaining parameters are passed to the HTTPResponse constructor, along with ``original_response=r``.
Given an :class:`httplib.HTTPResponse` instance ``r``, return a corresponding :class:`urllib3.response.HTTPResponse` object.
[ "Given", "an", ":", "class", ":", "httplib", ".", "HTTPResponse", "instance", "r", "return", "a", "corresponding", ":", "class", ":", "urllib3", ".", "response", ".", "HTTPResponse", "object", "." ]
def from_httplib(ResponseCls, r, **response_kw): """ Given an :class:`httplib.HTTPResponse` instance ``r``, return a corresponding :class:`urllib3.response.HTTPResponse` object. Remaining parameters are passed to the HTTPResponse constructor, along with ``original_response=r``. """ headers = r.msg if not isinstance(headers, HTTPHeaderDict): if PY3: # Python 3 headers = HTTPHeaderDict(headers.items()) else: # Python 2 headers = HTTPHeaderDict.from_httplib(headers) # HTTPResponse objects in Python 3 don't have a .strict attribute strict = getattr(r, 'strict', 0) resp = ResponseCls(body=r, headers=headers, status=r.status, version=r.version, reason=r.reason, strict=strict, original_response=r, **response_kw) return resp
[ "def", "from_httplib", "(", "ResponseCls", ",", "r", ",", "*", "*", "response_kw", ")", ":", "headers", "=", "r", ".", "msg", "if", "not", "isinstance", "(", "headers", ",", "HTTPHeaderDict", ")", ":", "if", "PY3", ":", "# Python 3", "headers", "=", "HTTPHeaderDict", "(", "headers", ".", "items", "(", ")", ")", "else", ":", "# Python 2", "headers", "=", "HTTPHeaderDict", ".", "from_httplib", "(", "headers", ")", "# HTTPResponse objects in Python 3 don't have a .strict attribute", "strict", "=", "getattr", "(", "r", ",", "'strict'", ",", "0", ")", "resp", "=", "ResponseCls", "(", "body", "=", "r", ",", "headers", "=", "headers", ",", "status", "=", "r", ".", "status", ",", "version", "=", "r", ".", "version", ",", "reason", "=", "r", ".", "reason", ",", "strict", "=", "strict", ",", "original_response", "=", "r", ",", "*", "*", "response_kw", ")", "return", "resp" ]
https://github.com/vulscanteam/vulscan/blob/787397e267c4e6469522ee0abe55b3e98f968d4a/pocsuite/thirdparty/requests/packages/urllib3/response.py#L313-L338
frictionlessdata/datapackage-py
52416bd5be2e146490ee91f51b80d9b2178e0070
datapackage/resource.py
python
Resource.multipart
(self)
return self.__source_inspection.get('multipart', False)
Whether resource multipart # Returns bool: returns true if resource is multipart
Whether resource multipart
[ "Whether", "resource", "multipart" ]
def multipart(self): """Whether resource multipart # Returns bool: returns true if resource is multipart """ return self.__source_inspection.get('multipart', False)
[ "def", "multipart", "(", "self", ")", ":", "return", "self", ".", "__source_inspection", ".", "get", "(", "'multipart'", ",", "False", ")" ]
https://github.com/frictionlessdata/datapackage-py/blob/52416bd5be2e146490ee91f51b80d9b2178e0070/datapackage/resource.py#L198-L205
google/timesketch
1ce6b60e125d104e6644947c6f1dbe1b82ac76b6
timesketch/lib/aggregators/interface.py
python
BaseAggregator.run
(self, *args, **kwargs)
Entry point for the aggregator.
Entry point for the aggregator.
[ "Entry", "point", "for", "the", "aggregator", "." ]
def run(self, *args, **kwargs): """Entry point for the aggregator.""" raise NotImplementedError
[ "def", "run", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError" ]
https://github.com/google/timesketch/blob/1ce6b60e125d104e6644947c6f1dbe1b82ac76b6/timesketch/lib/aggregators/interface.py#L362-L364
OpenTSDB/tcollector
37ae920d83c1002da66b5201a5311b1714cb5c14
collectors/0/mysql.py
python
DB.close
(self)
Closes the connection to this MySQL server.
Closes the connection to this MySQL server.
[ "Closes", "the", "connection", "to", "this", "MySQL", "server", "." ]
def close(self): """Closes the connection to this MySQL server.""" if self.cursor: self.cursor.close() self.cursor = None if self.db: self.db.close() self.db = None
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "cursor", ":", "self", ".", "cursor", ".", "close", "(", ")", "self", ".", "cursor", "=", "None", "if", "self", ".", "db", ":", "self", ".", "db", ".", "close", "(", ")", "self", ".", "db", "=", "None" ]
https://github.com/OpenTSDB/tcollector/blob/37ae920d83c1002da66b5201a5311b1714cb5c14/collectors/0/mysql.py#L105-L112
python/mypy
17850b3bd77ae9efb5d21f656c4e4e05ac48d894
mypy/messages.py
python
MessageBuilder.has_no_attr
(self, original_type: Type, typ: Type, member: str, context: Context, module_symbol_table: Optional[SymbolTable] = None)
return AnyType(TypeOfAny.from_error)
Report a missing or non-accessible member. original_type is the top-level type on which the error occurred. typ is the actual type that is missing the member. These can be different, e.g., in a union, original_type will be the union and typ will be the specific item in the union that does not have the member attribute. 'module_symbol_table' is passed to this function if the type for which we are trying to get a member was originally a module. The SymbolTable allows us to look up and suggests attributes of the module since they are not directly available on original_type If member corresponds to an operator, use the corresponding operator name in the messages. Return type Any.
Report a missing or non-accessible member.
[ "Report", "a", "missing", "or", "non", "-", "accessible", "member", "." ]
def has_no_attr(self, original_type: Type, typ: Type, member: str, context: Context, module_symbol_table: Optional[SymbolTable] = None) -> Type: """Report a missing or non-accessible member. original_type is the top-level type on which the error occurred. typ is the actual type that is missing the member. These can be different, e.g., in a union, original_type will be the union and typ will be the specific item in the union that does not have the member attribute. 'module_symbol_table' is passed to this function if the type for which we are trying to get a member was originally a module. The SymbolTable allows us to look up and suggests attributes of the module since they are not directly available on original_type If member corresponds to an operator, use the corresponding operator name in the messages. Return type Any. """ original_type = get_proper_type(original_type) typ = get_proper_type(typ) if (isinstance(original_type, Instance) and original_type.type.has_readable_member(member)): self.fail('Member "{}" is not assignable'.format(member), context) elif member == '__contains__': self.fail('Unsupported right operand type for in ({})'.format( format_type(original_type)), context, code=codes.OPERATOR) elif member in op_methods.values(): # Access to a binary operator member (e.g. _add). This case does # not handle indexing operations. for op, method in op_methods.items(): if method == member: self.unsupported_left_operand(op, original_type, context) break elif member == '__neg__': self.fail('Unsupported operand type for unary - ({})'.format( format_type(original_type)), context, code=codes.OPERATOR) elif member == '__pos__': self.fail('Unsupported operand type for unary + ({})'.format( format_type(original_type)), context, code=codes.OPERATOR) elif member == '__invert__': self.fail('Unsupported operand type for ~ ({})'.format( format_type(original_type)), context, code=codes.OPERATOR) elif member == '__getitem__': # Indexed get. # TODO: Fix this consistently in format_type if isinstance(original_type, CallableType) and original_type.is_type_obj(): self.fail('The type {} is not generic and not indexable'.format( format_type(original_type)), context) else: self.fail('Value of type {} is not indexable'.format( format_type(original_type)), context, code=codes.INDEX) elif member == '__setitem__': # Indexed set. self.fail('Unsupported target for indexed assignment ({})'.format( format_type(original_type)), context, code=codes.INDEX) elif member == '__call__': if isinstance(original_type, Instance) and \ (original_type.type.fullname == 'builtins.function'): # "'function' not callable" is a confusing error message. # Explain that the problem is that the type of the function is not known. self.fail('Cannot call function of unknown type', context, code=codes.OPERATOR) else: self.fail(message_registry.NOT_CALLABLE.format( format_type(original_type)), context, code=codes.OPERATOR) else: # The non-special case: a missing ordinary attribute. extra = '' if member == '__iter__': extra = ' (not iterable)' elif member == '__aiter__': extra = ' (not async iterable)' if not self.disable_type_names_count: failed = False if isinstance(original_type, Instance) and original_type.type.names: alternatives = set(original_type.type.names.keys()) if module_symbol_table is not None: alternatives |= {key for key in module_symbol_table.keys()} # in some situations, the member is in the alternatives set # but since we're in this function, we shouldn't suggest it if member in alternatives: alternatives.remove(member) matches = [m for m in COMMON_MISTAKES.get(member, []) if m in alternatives] matches.extend(best_matches(member, alternatives)[:3]) if member == '__aiter__' and matches == ['__iter__']: matches = [] # Avoid misleading suggestion if member == '__div__' and matches == ['__truediv__']: # TODO: Handle differences in division between Python 2 and 3 more cleanly matches = [] if matches: self.fail( '{} has no attribute "{}"; maybe {}?{}'.format( format_type(original_type), member, pretty_seq(matches, "or"), extra, ), context, code=codes.ATTR_DEFINED) failed = True if not failed: self.fail( '{} has no attribute "{}"{}'.format( format_type(original_type), member, extra), context, code=codes.ATTR_DEFINED) elif isinstance(original_type, UnionType): # The checker passes "object" in lieu of "None" for attribute # checks, so we manually convert it back. typ_format, orig_type_format = format_type_distinctly(typ, original_type) if typ_format == '"object"' and \ any(type(item) == NoneType for item in original_type.items): typ_format = '"None"' self.fail('Item {} of {} has no attribute "{}"{}'.format( typ_format, orig_type_format, member, extra), context, code=codes.UNION_ATTR) elif isinstance(original_type, TypeVarType): bound = get_proper_type(original_type.upper_bound) if isinstance(bound, UnionType): typ_fmt, bound_fmt = format_type_distinctly(typ, bound) original_type_fmt = format_type(original_type) self.fail( 'Item {} of the upper bound {} of type variable {} has no ' 'attribute "{}"{}'.format( typ_fmt, bound_fmt, original_type_fmt, member, extra), context, code=codes.UNION_ATTR) return AnyType(TypeOfAny.from_error)
[ "def", "has_no_attr", "(", "self", ",", "original_type", ":", "Type", ",", "typ", ":", "Type", ",", "member", ":", "str", ",", "context", ":", "Context", ",", "module_symbol_table", ":", "Optional", "[", "SymbolTable", "]", "=", "None", ")", "->", "Type", ":", "original_type", "=", "get_proper_type", "(", "original_type", ")", "typ", "=", "get_proper_type", "(", "typ", ")", "if", "(", "isinstance", "(", "original_type", ",", "Instance", ")", "and", "original_type", ".", "type", ".", "has_readable_member", "(", "member", ")", ")", ":", "self", ".", "fail", "(", "'Member \"{}\" is not assignable'", ".", "format", "(", "member", ")", ",", "context", ")", "elif", "member", "==", "'__contains__'", ":", "self", ".", "fail", "(", "'Unsupported right operand type for in ({})'", ".", "format", "(", "format_type", "(", "original_type", ")", ")", ",", "context", ",", "code", "=", "codes", ".", "OPERATOR", ")", "elif", "member", "in", "op_methods", ".", "values", "(", ")", ":", "# Access to a binary operator member (e.g. _add). This case does", "# not handle indexing operations.", "for", "op", ",", "method", "in", "op_methods", ".", "items", "(", ")", ":", "if", "method", "==", "member", ":", "self", ".", "unsupported_left_operand", "(", "op", ",", "original_type", ",", "context", ")", "break", "elif", "member", "==", "'__neg__'", ":", "self", ".", "fail", "(", "'Unsupported operand type for unary - ({})'", ".", "format", "(", "format_type", "(", "original_type", ")", ")", ",", "context", ",", "code", "=", "codes", ".", "OPERATOR", ")", "elif", "member", "==", "'__pos__'", ":", "self", ".", "fail", "(", "'Unsupported operand type for unary + ({})'", ".", "format", "(", "format_type", "(", "original_type", ")", ")", ",", "context", ",", "code", "=", "codes", ".", "OPERATOR", ")", "elif", "member", "==", "'__invert__'", ":", "self", ".", "fail", "(", "'Unsupported operand type for ~ ({})'", ".", "format", "(", "format_type", "(", "original_type", ")", ")", ",", "context", ",", "code", "=", "codes", ".", "OPERATOR", ")", "elif", "member", "==", "'__getitem__'", ":", "# Indexed get.", "# TODO: Fix this consistently in format_type", "if", "isinstance", "(", "original_type", ",", "CallableType", ")", "and", "original_type", ".", "is_type_obj", "(", ")", ":", "self", ".", "fail", "(", "'The type {} is not generic and not indexable'", ".", "format", "(", "format_type", "(", "original_type", ")", ")", ",", "context", ")", "else", ":", "self", ".", "fail", "(", "'Value of type {} is not indexable'", ".", "format", "(", "format_type", "(", "original_type", ")", ")", ",", "context", ",", "code", "=", "codes", ".", "INDEX", ")", "elif", "member", "==", "'__setitem__'", ":", "# Indexed set.", "self", ".", "fail", "(", "'Unsupported target for indexed assignment ({})'", ".", "format", "(", "format_type", "(", "original_type", ")", ")", ",", "context", ",", "code", "=", "codes", ".", "INDEX", ")", "elif", "member", "==", "'__call__'", ":", "if", "isinstance", "(", "original_type", ",", "Instance", ")", "and", "(", "original_type", ".", "type", ".", "fullname", "==", "'builtins.function'", ")", ":", "# \"'function' not callable\" is a confusing error message.", "# Explain that the problem is that the type of the function is not known.", "self", ".", "fail", "(", "'Cannot call function of unknown type'", ",", "context", ",", "code", "=", "codes", ".", "OPERATOR", ")", "else", ":", "self", ".", "fail", "(", "message_registry", ".", "NOT_CALLABLE", ".", "format", "(", "format_type", "(", "original_type", ")", ")", ",", "context", ",", "code", "=", "codes", ".", "OPERATOR", ")", "else", ":", "# The non-special case: a missing ordinary attribute.", "extra", "=", "''", "if", "member", "==", "'__iter__'", ":", "extra", "=", "' (not iterable)'", "elif", "member", "==", "'__aiter__'", ":", "extra", "=", "' (not async iterable)'", "if", "not", "self", ".", "disable_type_names_count", ":", "failed", "=", "False", "if", "isinstance", "(", "original_type", ",", "Instance", ")", "and", "original_type", ".", "type", ".", "names", ":", "alternatives", "=", "set", "(", "original_type", ".", "type", ".", "names", ".", "keys", "(", ")", ")", "if", "module_symbol_table", "is", "not", "None", ":", "alternatives", "|=", "{", "key", "for", "key", "in", "module_symbol_table", ".", "keys", "(", ")", "}", "# in some situations, the member is in the alternatives set", "# but since we're in this function, we shouldn't suggest it", "if", "member", "in", "alternatives", ":", "alternatives", ".", "remove", "(", "member", ")", "matches", "=", "[", "m", "for", "m", "in", "COMMON_MISTAKES", ".", "get", "(", "member", ",", "[", "]", ")", "if", "m", "in", "alternatives", "]", "matches", ".", "extend", "(", "best_matches", "(", "member", ",", "alternatives", ")", "[", ":", "3", "]", ")", "if", "member", "==", "'__aiter__'", "and", "matches", "==", "[", "'__iter__'", "]", ":", "matches", "=", "[", "]", "# Avoid misleading suggestion", "if", "member", "==", "'__div__'", "and", "matches", "==", "[", "'__truediv__'", "]", ":", "# TODO: Handle differences in division between Python 2 and 3 more cleanly", "matches", "=", "[", "]", "if", "matches", ":", "self", ".", "fail", "(", "'{} has no attribute \"{}\"; maybe {}?{}'", ".", "format", "(", "format_type", "(", "original_type", ")", ",", "member", ",", "pretty_seq", "(", "matches", ",", "\"or\"", ")", ",", "extra", ",", ")", ",", "context", ",", "code", "=", "codes", ".", "ATTR_DEFINED", ")", "failed", "=", "True", "if", "not", "failed", ":", "self", ".", "fail", "(", "'{} has no attribute \"{}\"{}'", ".", "format", "(", "format_type", "(", "original_type", ")", ",", "member", ",", "extra", ")", ",", "context", ",", "code", "=", "codes", ".", "ATTR_DEFINED", ")", "elif", "isinstance", "(", "original_type", ",", "UnionType", ")", ":", "# The checker passes \"object\" in lieu of \"None\" for attribute", "# checks, so we manually convert it back.", "typ_format", ",", "orig_type_format", "=", "format_type_distinctly", "(", "typ", ",", "original_type", ")", "if", "typ_format", "==", "'\"object\"'", "and", "any", "(", "type", "(", "item", ")", "==", "NoneType", "for", "item", "in", "original_type", ".", "items", ")", ":", "typ_format", "=", "'\"None\"'", "self", ".", "fail", "(", "'Item {} of {} has no attribute \"{}\"{}'", ".", "format", "(", "typ_format", ",", "orig_type_format", ",", "member", ",", "extra", ")", ",", "context", ",", "code", "=", "codes", ".", "UNION_ATTR", ")", "elif", "isinstance", "(", "original_type", ",", "TypeVarType", ")", ":", "bound", "=", "get_proper_type", "(", "original_type", ".", "upper_bound", ")", "if", "isinstance", "(", "bound", ",", "UnionType", ")", ":", "typ_fmt", ",", "bound_fmt", "=", "format_type_distinctly", "(", "typ", ",", "bound", ")", "original_type_fmt", "=", "format_type", "(", "original_type", ")", "self", ".", "fail", "(", "'Item {} of the upper bound {} of type variable {} has no '", "'attribute \"{}\"{}'", ".", "format", "(", "typ_fmt", ",", "bound_fmt", ",", "original_type_fmt", ",", "member", ",", "extra", ")", ",", "context", ",", "code", "=", "codes", ".", "UNION_ATTR", ")", "return", "AnyType", "(", "TypeOfAny", ".", "from_error", ")" ]
https://github.com/python/mypy/blob/17850b3bd77ae9efb5d21f656c4e4e05ac48d894/mypy/messages.py#L233-L366
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.4/django/forms/fields.py
python
Field.clean
(self, value)
return value
Validates the given value and returns its "cleaned" value as an appropriate Python object. Raises ValidationError for any errors.
Validates the given value and returns its "cleaned" value as an appropriate Python object.
[ "Validates", "the", "given", "value", "and", "returns", "its", "cleaned", "value", "as", "an", "appropriate", "Python", "object", "." ]
def clean(self, value): """ Validates the given value and returns its "cleaned" value as an appropriate Python object. Raises ValidationError for any errors. """ value = self.to_python(value) self.validate(value) self.run_validators(value) return value
[ "def", "clean", "(", "self", ",", "value", ")", ":", "value", "=", "self", ".", "to_python", "(", "value", ")", "self", ".", "validate", "(", "value", ")", "self", ".", "run_validators", "(", "value", ")", "return", "value" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.4/django/forms/fields.py#L146-L156
spyder-ide/spyder-notebook
e955d4e9ecaaf2efebdec9a1219175e1302f9d17
spyder_notebook/widgets/client.py
python
NotebookWidget.show_message
(self, page)
Show a message page with the given .html file.
Show a message page with the given .html file.
[ "Show", "a", "message", "page", "with", "the", "given", ".", "html", "file", "." ]
def show_message(self, page): """Show a message page with the given .html file.""" self.setHtml(page)
[ "def", "show_message", "(", "self", ",", "page", ")", ":", "self", ".", "setHtml", "(", "page", ")" ]
https://github.com/spyder-ide/spyder-notebook/blob/e955d4e9ecaaf2efebdec9a1219175e1302f9d17/spyder_notebook/widgets/client.py#L184-L186
ScriptSmith/socialreaper
87fcc3b74bbed6c4f8e7f49a5f0eb8a616cf38da
socialreaper/tools.py
python
to_csv
(data, field_names=None, filename='data.csv', overwrite=True, write_headers=True, append=False, flat=True, primary_fields=None, sort_fields=True)
DEPRECATED Write a list of dicts to a csv file :param data: List of dicts :param field_names: The list column names :param filename: The name of the file :param overwrite: Overwrite the file if exists :param write_headers: Write the headers to the csv file :param append: Write new rows if the file exists :param flat: Flatten the dictionary before saving :param primary_fields: The first columns of the csv file :param sort_fields: Sort the field names alphabetically :return: None
DEPRECATED Write a list of dicts to a csv file
[ "DEPRECATED", "Write", "a", "list", "of", "dicts", "to", "a", "csv", "file" ]
def to_csv(data, field_names=None, filename='data.csv', overwrite=True, write_headers=True, append=False, flat=True, primary_fields=None, sort_fields=True): """ DEPRECATED Write a list of dicts to a csv file :param data: List of dicts :param field_names: The list column names :param filename: The name of the file :param overwrite: Overwrite the file if exists :param write_headers: Write the headers to the csv file :param append: Write new rows if the file exists :param flat: Flatten the dictionary before saving :param primary_fields: The first columns of the csv file :param sort_fields: Sort the field names alphabetically :return: None """ # Don't overwrite if not specified if not overwrite and path.isfile(filename): raise FileExistsError('The file already exists') # Replace file if append not specified write_type = 'w' if not append else 'a' # Flatten if flat is specified, or there are no predefined field names if flat or not field_names: data = [flatten(datum) for datum in data] # Fill in gaps between dicts with empty string if not field_names: field_names, data = fill_gaps(data) # Sort fields if specified if sort_fields: field_names.sort() # If there are primary fields, move the field names to the front and sort # based on first field if primary_fields: for key in primary_fields[::-1]: field_names.insert(0, field_names.pop(field_names.index(key))) data = sorted(data, key=lambda k: k[field_names[0]], reverse=True) # Write the file with open(filename, write_type, encoding='utf-8') as f: writer = csv.DictWriter(f, fieldnames=field_names, lineterminator='\n') if not append or write_headers: writer.writeheader() # Write rows containing fields in field names for datum in data: for key in list(datum.keys()): if key not in field_names: del datum[key] elif type(datum[key]) is str: datum[key] = datum[key].strip() datum[key] = str(datum[key]) writer.writerow(datum)
[ "def", "to_csv", "(", "data", ",", "field_names", "=", "None", ",", "filename", "=", "'data.csv'", ",", "overwrite", "=", "True", ",", "write_headers", "=", "True", ",", "append", "=", "False", ",", "flat", "=", "True", ",", "primary_fields", "=", "None", ",", "sort_fields", "=", "True", ")", ":", "# Don't overwrite if not specified", "if", "not", "overwrite", "and", "path", ".", "isfile", "(", "filename", ")", ":", "raise", "FileExistsError", "(", "'The file already exists'", ")", "# Replace file if append not specified", "write_type", "=", "'w'", "if", "not", "append", "else", "'a'", "# Flatten if flat is specified, or there are no predefined field names", "if", "flat", "or", "not", "field_names", ":", "data", "=", "[", "flatten", "(", "datum", ")", "for", "datum", "in", "data", "]", "# Fill in gaps between dicts with empty string", "if", "not", "field_names", ":", "field_names", ",", "data", "=", "fill_gaps", "(", "data", ")", "# Sort fields if specified", "if", "sort_fields", ":", "field_names", ".", "sort", "(", ")", "# If there are primary fields, move the field names to the front and sort", "# based on first field", "if", "primary_fields", ":", "for", "key", "in", "primary_fields", "[", ":", ":", "-", "1", "]", ":", "field_names", ".", "insert", "(", "0", ",", "field_names", ".", "pop", "(", "field_names", ".", "index", "(", "key", ")", ")", ")", "data", "=", "sorted", "(", "data", ",", "key", "=", "lambda", "k", ":", "k", "[", "field_names", "[", "0", "]", "]", ",", "reverse", "=", "True", ")", "# Write the file", "with", "open", "(", "filename", ",", "write_type", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "writer", "=", "csv", ".", "DictWriter", "(", "f", ",", "fieldnames", "=", "field_names", ",", "lineterminator", "=", "'\\n'", ")", "if", "not", "append", "or", "write_headers", ":", "writer", ".", "writeheader", "(", ")", "# Write rows containing fields in field names", "for", "datum", "in", "data", ":", "for", "key", "in", "list", "(", "datum", ".", "keys", "(", ")", ")", ":", "if", "key", "not", "in", "field_names", ":", "del", "datum", "[", "key", "]", "elif", "type", "(", "datum", "[", "key", "]", ")", "is", "str", ":", "datum", "[", "key", "]", "=", "datum", "[", "key", "]", ".", "strip", "(", ")", "datum", "[", "key", "]", "=", "str", "(", "datum", "[", "key", "]", ")", "writer", ".", "writerow", "(", "datum", ")" ]
https://github.com/ScriptSmith/socialreaper/blob/87fcc3b74bbed6c4f8e7f49a5f0eb8a616cf38da/socialreaper/tools.py#L132-L194
MISP/misp-warninglists
c348d041f68523b50644deb9df3e4794bf0f8ffc
tools/generate-cisco.py
python
generate
(sites, warninglist, dst)
[]
def generate(sites, warninglist, dst): warninglist['version'] = get_version() warninglist['type'] = 'string' warninglist['matching_attributes'] = [ 'hostname', 'domain', 'url', 'domain|ip'] warninglist['list'] = [] for site in sites: v = site.decode('UTF-8').split(',')[1] warninglist['list'].append(v.strip().replace('\\r\\n', '')) write_to_file(warninglist, dst)
[ "def", "generate", "(", "sites", ",", "warninglist", ",", "dst", ")", ":", "warninglist", "[", "'version'", "]", "=", "get_version", "(", ")", "warninglist", "[", "'type'", "]", "=", "'string'", "warninglist", "[", "'matching_attributes'", "]", "=", "[", "'hostname'", ",", "'domain'", ",", "'url'", ",", "'domain|ip'", "]", "warninglist", "[", "'list'", "]", "=", "[", "]", "for", "site", "in", "sites", ":", "v", "=", "site", ".", "decode", "(", "'UTF-8'", ")", ".", "split", "(", "','", ")", "[", "1", "]", "warninglist", "[", "'list'", "]", ".", "append", "(", "v", ".", "strip", "(", ")", ".", "replace", "(", "'\\\\r\\\\n'", ",", "''", ")", ")", "write_to_file", "(", "warninglist", ",", "dst", ")" ]
https://github.com/MISP/misp-warninglists/blob/c348d041f68523b50644deb9df3e4794bf0f8ffc/tools/generate-cisco.py#L41-L52
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/PIL/ImageStat.py
python
Stat._getextrema
(self)
return v
Get min/max values for each band in the image
Get min/max values for each band in the image
[ "Get", "min", "/", "max", "values", "for", "each", "band", "in", "the", "image" ]
def _getextrema(self): "Get min/max values for each band in the image" def minmax(histogram): n = 255 x = 0 for i in range(256): if histogram[i]: n = min(n, i) x = max(x, i) return n, x # returns (255, 0) if there's no data in the histogram v = [] for i in range(0, len(self.h), 256): v.append(minmax(self.h[i:])) return v
[ "def", "_getextrema", "(", "self", ")", ":", "def", "minmax", "(", "histogram", ")", ":", "n", "=", "255", "x", "=", "0", "for", "i", "in", "range", "(", "256", ")", ":", "if", "histogram", "[", "i", "]", ":", "n", "=", "min", "(", "n", ",", "i", ")", "x", "=", "max", "(", "x", ",", "i", ")", "return", "n", ",", "x", "# returns (255, 0) if there's no data in the histogram", "v", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "self", ".", "h", ")", ",", "256", ")", ":", "v", ".", "append", "(", "minmax", "(", "self", ".", "h", "[", "i", ":", "]", ")", ")", "return", "v" ]
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/PIL/ImageStat.py#L52-L67
pulp/pulp
a0a28d804f997b6f81c391378aff2e4c90183df9
client_lib/pulp/client/extensions/exceptions.py
python
ExceptionHandler._log_server_exception
(self, e)
Dumps all information from an exception that came from the server to the log. :type e: RequestException
Dumps all information from an exception that came from the server to the log.
[ "Dumps", "all", "information", "from", "an", "exception", "that", "came", "from", "the", "server", "to", "the", "log", "." ]
def _log_server_exception(self, e): """ Dumps all information from an exception that came from the server to the log. :type e: RequestException """ template = """Exception occurred: href: %(h)s method: %(m)s status: %(s)s error: %(e)s traceback: %(t)s data: %(d)s """ data = {'h': e.href, 'm': e.http_request_method, 's': e.http_status, 'e': e.error_message, 't': e.traceback, 'd': e.extra_data} _logger.error(template % data)
[ "def", "_log_server_exception", "(", "self", ",", "e", ")", ":", "template", "=", "\"\"\"Exception occurred:\n href: %(h)s\n method: %(m)s\n status: %(s)s\n error: %(e)s\n traceback: %(t)s\n data: %(d)s\n \"\"\"", "data", "=", "{", "'h'", ":", "e", ".", "href", ",", "'m'", ":", "e", ".", "http_request_method", ",", "'s'", ":", "e", ".", "http_status", ",", "'e'", ":", "e", ".", "error_message", ",", "'t'", ":", "e", ".", "traceback", ",", "'d'", ":", "e", ".", "extra_data", "}", "_logger", ".", "error", "(", "template", "%", "data", ")" ]
https://github.com/pulp/pulp/blob/a0a28d804f997b6f81c391378aff2e4c90183df9/client_lib/pulp/client/extensions/exceptions.py#L432-L455
intel/virtual-storage-manager
00706ab9701acbd0d5e04b19cc80c6b66a2973b8
source/vsm/vsm/agent/cephconfigutils.py
python
CephConfigParser.get
(self, section, option, default=None)
return self._parser.get(section, option, default)
Return the value of a specified option in a specified section, the specified default value if the specified section and/or option are not found in the configuration content. :param section: the section in which to look. :param option: the option for which to look. :param default: the default value to use in case section and/or option are missing. :return: the desired section/option value, or the default is missing.
Return the value of a specified option in a specified section, the specified default value if the specified section and/or option are not found in the configuration content. :param section: the section in which to look. :param option: the option for which to look. :param default: the default value to use in case section and/or option are missing. :return: the desired section/option value, or the default is missing.
[ "Return", "the", "value", "of", "a", "specified", "option", "in", "a", "specified", "section", "the", "specified", "default", "value", "if", "the", "specified", "section", "and", "/", "or", "option", "are", "not", "found", "in", "the", "configuration", "content", ".", ":", "param", "section", ":", "the", "section", "in", "which", "to", "look", ".", ":", "param", "option", ":", "the", "option", "for", "which", "to", "look", ".", ":", "param", "default", ":", "the", "default", "value", "to", "use", "in", "case", "section", "and", "/", "or", "option", "are", "missing", ".", ":", "return", ":", "the", "desired", "section", "/", "option", "value", "or", "the", "default", "is", "missing", "." ]
def get(self, section, option, default=None): """ Return the value of a specified option in a specified section, the specified default value if the specified section and/or option are not found in the configuration content. :param section: the section in which to look. :param option: the option for which to look. :param default: the default value to use in case section and/or option are missing. :return: the desired section/option value, or the default is missing. """ return self._parser.get(section, option, default)
[ "def", "get", "(", "self", ",", "section", ",", "option", ",", "default", "=", "None", ")", ":", "return", "self", ".", "_parser", ".", "get", "(", "section", ",", "option", ",", "default", ")" ]
https://github.com/intel/virtual-storage-manager/blob/00706ab9701acbd0d5e04b19cc80c6b66a2973b8/source/vsm/vsm/agent/cephconfigutils.py#L282-L291
google/rekall
55d1925f2df9759a989b35271b4fa48fc54a1c86
rekall-core/rekall/plugins/response/windows_processes.py
python
APIVad.merge_ranges
(self, pid)
Generate merged ranges.
Generate merged ranges.
[ "Generate", "merged", "ranges", "." ]
def merge_ranges(self, pid): """Generate merged ranges.""" old_vad = None for vad in self.generate_vads(pid): # Try to merge this range with the previous range. if (old_vad and old_vad.end == vad.start and old_vad.protection == vad.protection and old_vad.filename == vad.filename): old_vad.end = vad.end continue # Yield the old range: if old_vad: yield old_vad old_vad = vad # Emit the last range. if old_vad: yield old_vad
[ "def", "merge_ranges", "(", "self", ",", "pid", ")", ":", "old_vad", "=", "None", "for", "vad", "in", "self", ".", "generate_vads", "(", "pid", ")", ":", "# Try to merge this range with the previous range.", "if", "(", "old_vad", "and", "old_vad", ".", "end", "==", "vad", ".", "start", "and", "old_vad", ".", "protection", "==", "vad", ".", "protection", "and", "old_vad", ".", "filename", "==", "vad", ".", "filename", ")", ":", "old_vad", ".", "end", "=", "vad", ".", "end", "continue", "# Yield the old range:", "if", "old_vad", ":", "yield", "old_vad", "old_vad", "=", "vad", "# Emit the last range.", "if", "old_vad", ":", "yield", "old_vad" ]
https://github.com/google/rekall/blob/55d1925f2df9759a989b35271b4fa48fc54a1c86/rekall-core/rekall/plugins/response/windows_processes.py#L214-L235
microsoft/botbuilder-python
3d410365461dc434df59bdfeaa2f16d28d9df868
libraries/botbuilder-ai/botbuilder/ai/luis/luis_application.py
python
LuisApplication.__init__
(self, application_id: str, endpoint_key: str, endpoint: str)
Initializes a new instance of the :class:`LuisApplication` class. :param application_id: LUIS application ID. :type application_id: str :param endpoint_key: LUIS subscription or endpoint key. :type endpoint_key: str :param endpoint: LUIS endpoint to use, like https://westus.api.cognitive.microsoft.com. :type endpoint: str :raises ValueError: :raises ValueError: :raises ValueError:
Initializes a new instance of the :class:`LuisApplication` class.
[ "Initializes", "a", "new", "instance", "of", "the", ":", "class", ":", "LuisApplication", "class", "." ]
def __init__(self, application_id: str, endpoint_key: str, endpoint: str): """Initializes a new instance of the :class:`LuisApplication` class. :param application_id: LUIS application ID. :type application_id: str :param endpoint_key: LUIS subscription or endpoint key. :type endpoint_key: str :param endpoint: LUIS endpoint to use, like https://westus.api.cognitive.microsoft.com. :type endpoint: str :raises ValueError: :raises ValueError: :raises ValueError: """ _, valid = LuisApplication._try_parse_uuid4(application_id) if not valid: raise ValueError(f'"{application_id}" is not a valid LUIS application id.') _, valid = LuisApplication._try_parse_uuid4(endpoint_key) if not valid: raise ValueError(f'"{endpoint_key}" is not a valid LUIS subscription key.') if not endpoint or endpoint.isspace(): endpoint = "https://westus.api.cognitive.microsoft.com" _, valid = LuisApplication._try_parse_url(endpoint) if not valid: raise ValueError(f'"{endpoint}" is not a valid LUIS endpoint.') self.application_id = application_id self.endpoint_key = endpoint_key self.endpoint = endpoint
[ "def", "__init__", "(", "self", ",", "application_id", ":", "str", ",", "endpoint_key", ":", "str", ",", "endpoint", ":", "str", ")", ":", "_", ",", "valid", "=", "LuisApplication", ".", "_try_parse_uuid4", "(", "application_id", ")", "if", "not", "valid", ":", "raise", "ValueError", "(", "f'\"{application_id}\" is not a valid LUIS application id.'", ")", "_", ",", "valid", "=", "LuisApplication", ".", "_try_parse_uuid4", "(", "endpoint_key", ")", "if", "not", "valid", ":", "raise", "ValueError", "(", "f'\"{endpoint_key}\" is not a valid LUIS subscription key.'", ")", "if", "not", "endpoint", "or", "endpoint", ".", "isspace", "(", ")", ":", "endpoint", "=", "\"https://westus.api.cognitive.microsoft.com\"", "_", ",", "valid", "=", "LuisApplication", ".", "_try_parse_url", "(", "endpoint", ")", "if", "not", "valid", ":", "raise", "ValueError", "(", "f'\"{endpoint}\" is not a valid LUIS endpoint.'", ")", "self", ".", "application_id", "=", "application_id", "self", ".", "endpoint_key", "=", "endpoint_key", "self", ".", "endpoint", "=", "endpoint" ]
https://github.com/microsoft/botbuilder-python/blob/3d410365461dc434df59bdfeaa2f16d28d9df868/libraries/botbuilder-ai/botbuilder/ai/luis/luis_application.py#L15-L46
tensorflow/lingvo
ce10019243d954c3c3ebe739f7589b5eebfdf907
lingvo/jax/layers/attentions.py
python
RelativeBias.Params
(cls)
return p
Params for `RelativeBias`.
Params for `RelativeBias`.
[ "Params", "for", "RelativeBias", "." ]
def Params(cls) -> InstantiableParams: """Params for `RelativeBias`.""" p = super().Params() p.Define('num_heads', 1, 'Num of attention heads.') p.Define('relative_attention_num_buckets', 32, 'Relative attention num buckets.') p.Define('relative_attention_max_distance', 128, 'Max relative distance (outer bucket boundary).') return p
[ "def", "Params", "(", "cls", ")", "->", "InstantiableParams", ":", "p", "=", "super", "(", ")", ".", "Params", "(", ")", "p", ".", "Define", "(", "'num_heads'", ",", "1", ",", "'Num of attention heads.'", ")", "p", ".", "Define", "(", "'relative_attention_num_buckets'", ",", "32", ",", "'Relative attention num buckets.'", ")", "p", ".", "Define", "(", "'relative_attention_max_distance'", ",", "128", ",", "'Max relative distance (outer bucket boundary).'", ")", "return", "p" ]
https://github.com/tensorflow/lingvo/blob/ce10019243d954c3c3ebe739f7589b5eebfdf907/lingvo/jax/layers/attentions.py#L224-L232
tav/pylibs
3c16b843681f54130ee6a022275289cadb2f2a69
BeautifulSoup.py
python
Tag.__iter__
(self)
return iter(self.contents)
Iterating over a tag iterates over its contents.
Iterating over a tag iterates over its contents.
[ "Iterating", "over", "a", "tag", "iterates", "over", "its", "contents", "." ]
def __iter__(self): "Iterating over a tag iterates over its contents." return iter(self.contents)
[ "def", "__iter__", "(", "self", ")", ":", "return", "iter", "(", "self", ".", "contents", ")" ]
https://github.com/tav/pylibs/blob/3c16b843681f54130ee6a022275289cadb2f2a69/BeautifulSoup.py#L603-L605
NordicSemiconductor/pc-nrfutil
d08e742128f2a3dac522601bc6b9f9b2b63952df
nordicsemi/lister/windows/structures.py
python
_GUID.__init__
(self, guid="{00000000-0000-0000-0000-000000000000}")
[]
def __init__(self, guid="{00000000-0000-0000-0000-000000000000}"): super().__init__() if isinstance(guid, str): ret = _ole32.CLSIDFromString(ctypes.create_unicode_buffer(guid), ctypes.byref(self)) if ret < 0: err_no = ctypes.GetLastError() raise WindowsError(err_no, ctypes.FormatError(err_no), guid) else: ctypes.memmove(ctypes.byref(self), bytes(guid), ctypes.sizeof(self))
[ "def", "__init__", "(", "self", ",", "guid", "=", "\"{00000000-0000-0000-0000-000000000000}\"", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "if", "isinstance", "(", "guid", ",", "str", ")", ":", "ret", "=", "_ole32", ".", "CLSIDFromString", "(", "ctypes", ".", "create_unicode_buffer", "(", "guid", ")", ",", "ctypes", ".", "byref", "(", "self", ")", ")", "if", "ret", "<", "0", ":", "err_no", "=", "ctypes", ".", "GetLastError", "(", ")", "raise", "WindowsError", "(", "err_no", ",", "ctypes", ".", "FormatError", "(", "err_no", ")", ",", "guid", ")", "else", ":", "ctypes", ".", "memmove", "(", "ctypes", ".", "byref", "(", "self", ")", ",", "bytes", "(", "guid", ")", ",", "ctypes", ".", "sizeof", "(", "self", ")", ")" ]
https://github.com/NordicSemiconductor/pc-nrfutil/blob/d08e742128f2a3dac522601bc6b9f9b2b63952df/nordicsemi/lister/windows/structures.py#L38-L46
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.4/django/db/models/loading.py
python
AppCache._populate
(self)
Fill in all the cache information. This method is threadsafe, in the sense that every caller will see the same state upon return, and if the cache is already initialised, it does no work.
Fill in all the cache information. This method is threadsafe, in the sense that every caller will see the same state upon return, and if the cache is already initialised, it does no work.
[ "Fill", "in", "all", "the", "cache", "information", ".", "This", "method", "is", "threadsafe", "in", "the", "sense", "that", "every", "caller", "will", "see", "the", "same", "state", "upon", "return", "and", "if", "the", "cache", "is", "already", "initialised", "it", "does", "no", "work", "." ]
def _populate(self): """ Fill in all the cache information. This method is threadsafe, in the sense that every caller will see the same state upon return, and if the cache is already initialised, it does no work. """ if self.loaded: return self.write_lock.acquire() try: if self.loaded: return for app_name in settings.INSTALLED_APPS: if app_name in self.handled: continue self.load_app(app_name, True) if not self.nesting_level: for app_name in self.postponed: self.load_app(app_name) self.loaded = True finally: self.write_lock.release()
[ "def", "_populate", "(", "self", ")", ":", "if", "self", ".", "loaded", ":", "return", "self", ".", "write_lock", ".", "acquire", "(", ")", "try", ":", "if", "self", ".", "loaded", ":", "return", "for", "app_name", "in", "settings", ".", "INSTALLED_APPS", ":", "if", "app_name", "in", "self", ".", "handled", ":", "continue", "self", ".", "load_app", "(", "app_name", ",", "True", ")", "if", "not", "self", ".", "nesting_level", ":", "for", "app_name", "in", "self", ".", "postponed", ":", "self", ".", "load_app", "(", "app_name", ")", "self", ".", "loaded", "=", "True", "finally", ":", "self", ".", "write_lock", ".", "release", "(", ")" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.4/django/db/models/loading.py#L49-L70
mesonbuild/meson
a22d0f9a0a787df70ce79b05d0c45de90a970048
mesonbuild/mesonlib/universal.py
python
OrderedSet.difference_update
(self, iterable: T.Iterable[_T])
[]
def difference_update(self, iterable: T.Iterable[_T]) -> None: for item in iterable: self.discard(item)
[ "def", "difference_update", "(", "self", ",", "iterable", ":", "T", ".", "Iterable", "[", "_T", "]", ")", "->", "None", ":", "for", "item", "in", "iterable", ":", "self", ".", "discard", "(", "item", ")" ]
https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/mesonbuild/mesonlib/universal.py#L1759-L1761
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/twisted/twisted/names/client.py
python
lookupService
(name, timeout=None)
return getResolver().lookupService(name, timeout)
Perform an SRV record lookup. @type name: C{str} @param name: DNS name to resolve. @type timeout: Sequence of C{int} @param timeout: Number of seconds after which to reissue the query. When the last timeout expires, the query is considered failed. @rtype: C{Deferred}
Perform an SRV record lookup.
[ "Perform", "an", "SRV", "record", "lookup", "." ]
def lookupService(name, timeout=None): """ Perform an SRV record lookup. @type name: C{str} @param name: DNS name to resolve. @type timeout: Sequence of C{int} @param timeout: Number of seconds after which to reissue the query. When the last timeout expires, the query is considered failed. @rtype: C{Deferred} """ return getResolver().lookupService(name, timeout)
[ "def", "lookupService", "(", "name", ",", "timeout", "=", "None", ")", ":", "return", "getResolver", "(", ")", ".", "lookupService", "(", "name", ",", "timeout", ")" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/twisted/twisted/names/client.py#L794-L807
mpdavis/python-jose
cfbb868efffe05352546f064a47e6d90a53bbae0
jose/jws.py
python
sign
(payload, key, headers=None, algorithm=ALGORITHMS.HS256)
return signed_output
Signs a claims set and returns a JWS string. Args: payload (str or dict): A string to sign key (str or dict): The key to use for signing the claim set. Can be individual JWK or JWK set. headers (dict, optional): A set of headers that will be added to the default headers. Any headers that are added as additional headers will override the default headers. algorithm (str, optional): The algorithm to use for signing the the claims. Defaults to HS256. Returns: str: The string representation of the header, claims, and signature. Raises: JWSError: If there is an error signing the token. Examples: >>> jws.sign({'a': 'b'}, 'secret', algorithm='HS256') 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
Signs a claims set and returns a JWS string.
[ "Signs", "a", "claims", "set", "and", "returns", "a", "JWS", "string", "." ]
def sign(payload, key, headers=None, algorithm=ALGORITHMS.HS256): """Signs a claims set and returns a JWS string. Args: payload (str or dict): A string to sign key (str or dict): The key to use for signing the claim set. Can be individual JWK or JWK set. headers (dict, optional): A set of headers that will be added to the default headers. Any headers that are added as additional headers will override the default headers. algorithm (str, optional): The algorithm to use for signing the the claims. Defaults to HS256. Returns: str: The string representation of the header, claims, and signature. Raises: JWSError: If there is an error signing the token. Examples: >>> jws.sign({'a': 'b'}, 'secret', algorithm='HS256') 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8' """ if algorithm not in ALGORITHMS.SUPPORTED: raise JWSError("Algorithm %s not supported." % algorithm) encoded_header = _encode_header(algorithm, additional_headers=headers) encoded_payload = _encode_payload(payload) signed_output = _sign_header_and_claims(encoded_header, encoded_payload, algorithm, key) return signed_output
[ "def", "sign", "(", "payload", ",", "key", ",", "headers", "=", "None", ",", "algorithm", "=", "ALGORITHMS", ".", "HS256", ")", ":", "if", "algorithm", "not", "in", "ALGORITHMS", ".", "SUPPORTED", ":", "raise", "JWSError", "(", "\"Algorithm %s not supported.\"", "%", "algorithm", ")", "encoded_header", "=", "_encode_header", "(", "algorithm", ",", "additional_headers", "=", "headers", ")", "encoded_payload", "=", "_encode_payload", "(", "payload", ")", "signed_output", "=", "_sign_header_and_claims", "(", "encoded_header", ",", "encoded_payload", ",", "algorithm", ",", "key", ")", "return", "signed_output" ]
https://github.com/mpdavis/python-jose/blob/cfbb868efffe05352546f064a47e6d90a53bbae0/jose/jws.py#L12-L45
scrapy/scrapy
b04cfa48328d5d5749dca6f50fa34e0cfc664c89
scrapy/core/scraper.py
python
Slot.__init__
(self, max_active_size: int = 5000000)
[]
def __init__(self, max_active_size: int = 5000000): self.max_active_size = max_active_size self.queue: Deque[QueueTuple] = deque() self.active: Set[Request] = set() self.active_size: int = 0 self.itemproc_size: int = 0 self.closing: Optional[Deferred] = None
[ "def", "__init__", "(", "self", ",", "max_active_size", ":", "int", "=", "5000000", ")", ":", "self", ".", "max_active_size", "=", "max_active_size", "self", ".", "queue", ":", "Deque", "[", "QueueTuple", "]", "=", "deque", "(", ")", "self", ".", "active", ":", "Set", "[", "Request", "]", "=", "set", "(", ")", "self", ".", "active_size", ":", "int", "=", "0", "self", ".", "itemproc_size", ":", "int", "=", "0", "self", ".", "closing", ":", "Optional", "[", "Deferred", "]", "=", "None" ]
https://github.com/scrapy/scrapy/blob/b04cfa48328d5d5749dca6f50fa34e0cfc664c89/scrapy/core/scraper.py#L33-L39
robclewley/pydstool
939e3abc9dd1f180d35152bacbde57e24c85ff26
PyDSTool/ModelTools.py
python
GenTransform.remove
(self, obj)
Remove component, parameter, variable, input, function
Remove component, parameter, variable, input, function
[ "Remove", "component", "parameter", "variable", "input", "function" ]
def remove(self, obj): """Remove component, parameter, variable, input, function""" self.trans_gen.modelspec.remove(obj) self.changelog.append(common.args(action='remove', target=obj.name))
[ "def", "remove", "(", "self", ",", "obj", ")", ":", "self", ".", "trans_gen", ".", "modelspec", ".", "remove", "(", "obj", ")", "self", ".", "changelog", ".", "append", "(", "common", ".", "args", "(", "action", "=", "'remove'", ",", "target", "=", "obj", ".", "name", ")", ")" ]
https://github.com/robclewley/pydstool/blob/939e3abc9dd1f180d35152bacbde57e24c85ff26/PyDSTool/ModelTools.py#L2182-L2185
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/kubernetes/client/models/v1_affinity.py
python
V1Affinity.__repr__
(self)
return self.to_str()
For `print` and `pprint`
For `print` and `pprint`
[ "For", "print", "and", "pprint" ]
def __repr__(self): """ For `print` and `pprint` """ return self.to_str()
[ "def", "__repr__", "(", "self", ")", ":", "return", "self", ".", "to_str", "(", ")" ]
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/models/v1_affinity.py#L150-L154
CvvT/dumpDex
92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1
python/idaapi.py
python
tag_strlen
(*args)
return _idaapi.tag_strlen(*args)
tag_strlen(line) -> ssize_t
tag_strlen(line) -> ssize_t
[ "tag_strlen", "(", "line", ")", "-", ">", "ssize_t" ]
def tag_strlen(*args): """ tag_strlen(line) -> ssize_t """ return _idaapi.tag_strlen(*args)
[ "def", "tag_strlen", "(", "*", "args", ")", ":", "return", "_idaapi", ".", "tag_strlen", "(", "*", "args", ")" ]
https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idaapi.py#L46243-L46247
SymbiFlow/prjxray
5349556bc2c230801d6df0cf11bccb9cfd171639
prjxray/node_model.py
python
NodeModel.get_nodes
(self)
return self.nodes.keys()
Return a set of node names.
Return a set of node names.
[ "Return", "a", "set", "of", "node", "names", "." ]
def get_nodes(self): """ Return a set of node names. """ if self.nodes is None: self._build_nodes() return self.nodes.keys()
[ "def", "get_nodes", "(", "self", ")", ":", "if", "self", ".", "nodes", "is", "None", ":", "self", ".", "_build_nodes", "(", ")", "return", "self", ".", "nodes", ".", "keys", "(", ")" ]
https://github.com/SymbiFlow/prjxray/blob/5349556bc2c230801d6df0cf11bccb9cfd171639/prjxray/node_model.py#L131-L136
rizar/attention-lvcsr
1ae52cafdd8419874846f9544a299eef9c758f3b
libs/Theano/theano/tensor/basic.py
python
horizontal_stack
(*args)
return concatenate(args, axis=1)
Horizontally stack two L{TensorType}s. Stack two L{TensorType}s along the second axis (column wise). These L{TensorType}s must have the same shape along all dimensions but the second.
Horizontally stack two L{TensorType}s.
[ "Horizontally", "stack", "two", "L", "{", "TensorType", "}", "s", "." ]
def horizontal_stack(*args): """ Horizontally stack two L{TensorType}s. Stack two L{TensorType}s along the second axis (column wise). These L{TensorType}s must have the same shape along all dimensions but the second. """ # Note: 'horizontal_stack' and 'vertical_stack' do not behave exactly like # Numpy's hstack and vstack functions. This is intended, because Numpy's # functions have potentially confusing/incoherent behavior (try them on 1D # arrays). If this is fixed in a future version of Numpy, it may be worth # trying to get closer to Numpy's way of doing things. In the meantime, # better keep different names to emphasize the implementation divergences. assert len(args) >= 2 for arg in args: assert arg.type.ndim == 2 return concatenate(args, axis=1)
[ "def", "horizontal_stack", "(", "*", "args", ")", ":", "# Note: 'horizontal_stack' and 'vertical_stack' do not behave exactly like", "# Numpy's hstack and vstack functions. This is intended, because Numpy's", "# functions have potentially confusing/incoherent behavior (try them on 1D", "# arrays). If this is fixed in a future version of Numpy, it may be worth", "# trying to get closer to Numpy's way of doing things. In the meantime,", "# better keep different names to emphasize the implementation divergences.", "assert", "len", "(", "args", ")", ">=", "2", "for", "arg", "in", "args", ":", "assert", "arg", ".", "type", ".", "ndim", "==", "2", "return", "concatenate", "(", "args", ",", "axis", "=", "1", ")" ]
https://github.com/rizar/attention-lvcsr/blob/1ae52cafdd8419874846f9544a299eef9c758f3b/libs/Theano/theano/tensor/basic.py#L4304-L4322
Critical-Start/pastebin_scraper
196270249b0706bbeaf27fc2df379e4a2bb9fb5e
pastebin_scraper.py
python
monitor
()
monitor() - Main function... creates and starts threads
monitor() - Main function... creates and starts threads
[ "monitor", "()", "-", "Main", "function", "...", "creates", "and", "starts", "threads" ]
def monitor(): ''' monitor() - Main function... creates and starts threads ''' import argparse parser = argparse.ArgumentParser() parser.add_argument("-v", "--verbose", help="more verbose", action="store_true") args = parser.parse_args() level = logging.INFO if args.verbose: level = logging.DEBUG #logging to both stdout and file file_handler = logging.FileHandler(log_file) handlers = [file_handler] if PRINT_LOG: stdout_handler = logging.StreamHandler(sys.stdout) handlers.append(stdout_handler) logging.basicConfig( level=level, format='%(asctime)s [%(levelname)s] %(message)s', handlers=handlers ) logging.info('Monitoring...') paste_lock = threading.Lock() pastebin_thread = threading.Thread(target=Pastebin().monitor, args=[paste_lock]) # changed threading to not be in a for loop # we're only monitoring one site now - Moe pastebin_thread.daemon = True pastebin_thread.start() # Let threads run try: while(1): sleep(5) except KeyboardInterrupt: logging.warning('Stopped.')
[ "def", "monitor", "(", ")", ":", "import", "argparse", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "\"-v\"", ",", "\"--verbose\"", ",", "help", "=", "\"more verbose\"", ",", "action", "=", "\"store_true\"", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "level", "=", "logging", ".", "INFO", "if", "args", ".", "verbose", ":", "level", "=", "logging", ".", "DEBUG", "#logging to both stdout and file", "file_handler", "=", "logging", ".", "FileHandler", "(", "log_file", ")", "handlers", "=", "[", "file_handler", "]", "if", "PRINT_LOG", ":", "stdout_handler", "=", "logging", ".", "StreamHandler", "(", "sys", ".", "stdout", ")", "handlers", ".", "append", "(", "stdout_handler", ")", "logging", ".", "basicConfig", "(", "level", "=", "level", ",", "format", "=", "'%(asctime)s [%(levelname)s] %(message)s'", ",", "handlers", "=", "handlers", ")", "logging", ".", "info", "(", "'Monitoring...'", ")", "paste_lock", "=", "threading", ".", "Lock", "(", ")", "pastebin_thread", "=", "threading", ".", "Thread", "(", "target", "=", "Pastebin", "(", ")", ".", "monitor", ",", "args", "=", "[", "paste_lock", "]", ")", "# changed threading to not be in a for loop", "# we're only monitoring one site now - Moe", "pastebin_thread", ".", "daemon", "=", "True", "pastebin_thread", ".", "start", "(", ")", "# Let threads run", "try", ":", "while", "(", "1", ")", ":", "sleep", "(", "5", ")", "except", "KeyboardInterrupt", ":", "logging", ".", "warning", "(", "'Stopped.'", ")" ]
https://github.com/Critical-Start/pastebin_scraper/blob/196270249b0706bbeaf27fc2df379e4a2bb9fb5e/pastebin_scraper.py#L17-L55
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/graphs/generators/smallgraphs.py
python
HigmanSimsGraph
(relabel=True)
return HS
r""" Return the Higman-Sims graph. The Higman-Sims graph is a remarkable strongly regular graph of degree 22 on 100 vertices. For example, it can be split into two sets of 50 vertices each, so that each half induces a subgraph isomorphic to the Hoffman-Singleton graph (:meth:`~HoffmanSingletonGraph`). This can be done in 352 ways (see `Higman-Sims graph <https://www.win.tue.nl/~aeb/graphs/Higman-Sims.html>`_ by Andries E. Brouwer, accessed 24 October 2009.) Its most famous property is that the automorphism group has an index 2 subgroup which is one of the 26 sporadic groups [HS1968]_. The construction used here follows [Haf2004]_. See also the :wikipedia:`Higman–Sims_graph`. INPUT: - ``relabel`` -- boolean (default: ``True``); whether to relabel the vertices with consecutive integers. If ``False`` the labels are strings that are three digits long. "xyz" means the vertex is in group `x` (zero through three), pentagon or pentagram `y` (zero through four), and is vertex `z` (zero through four) of that pentagon or pentagram. See [Haf2004]_ for more. OUTPUT: The Higman-Sims graph. EXAMPLES: A split into the first 50 and last 50 vertices will induce two copies of the Hoffman-Singleton graph, and we illustrate another such split, which is obvious based on the construction used:: sage: H = graphs.HigmanSimsGraph() sage: A = H.subgraph(range(0,50)) sage: B = H.subgraph(range(50,100)) sage: K = graphs.HoffmanSingletonGraph() sage: K.is_isomorphic(A) and K.is_isomorphic(B) True sage: C = H.subgraph(range(25,75)) sage: D = H.subgraph(list(range(0,25))+list(range(75,100))) sage: K.is_isomorphic(C) and K.is_isomorphic(D) True The automorphism group contains only one nontrivial proper normal subgroup, which is of index 2 and is simple. It is known as the Higman-Sims group:: sage: H = graphs.HigmanSimsGraph() sage: G = H.automorphism_group() sage: g=G.order(); g 88704000 sage: K = G.normal_subgroups()[1] sage: K.is_simple() True sage: g//K.order() 2 AUTHOR: - Rob Beezer (2009-10-24)
r""" Return the Higman-Sims graph.
[ "r", "Return", "the", "Higman", "-", "Sims", "graph", "." ]
def HigmanSimsGraph(relabel=True): r""" Return the Higman-Sims graph. The Higman-Sims graph is a remarkable strongly regular graph of degree 22 on 100 vertices. For example, it can be split into two sets of 50 vertices each, so that each half induces a subgraph isomorphic to the Hoffman-Singleton graph (:meth:`~HoffmanSingletonGraph`). This can be done in 352 ways (see `Higman-Sims graph <https://www.win.tue.nl/~aeb/graphs/Higman-Sims.html>`_ by Andries E. Brouwer, accessed 24 October 2009.) Its most famous property is that the automorphism group has an index 2 subgroup which is one of the 26 sporadic groups [HS1968]_. The construction used here follows [Haf2004]_. See also the :wikipedia:`Higman–Sims_graph`. INPUT: - ``relabel`` -- boolean (default: ``True``); whether to relabel the vertices with consecutive integers. If ``False`` the labels are strings that are three digits long. "xyz" means the vertex is in group `x` (zero through three), pentagon or pentagram `y` (zero through four), and is vertex `z` (zero through four) of that pentagon or pentagram. See [Haf2004]_ for more. OUTPUT: The Higman-Sims graph. EXAMPLES: A split into the first 50 and last 50 vertices will induce two copies of the Hoffman-Singleton graph, and we illustrate another such split, which is obvious based on the construction used:: sage: H = graphs.HigmanSimsGraph() sage: A = H.subgraph(range(0,50)) sage: B = H.subgraph(range(50,100)) sage: K = graphs.HoffmanSingletonGraph() sage: K.is_isomorphic(A) and K.is_isomorphic(B) True sage: C = H.subgraph(range(25,75)) sage: D = H.subgraph(list(range(0,25))+list(range(75,100))) sage: K.is_isomorphic(C) and K.is_isomorphic(D) True The automorphism group contains only one nontrivial proper normal subgroup, which is of index 2 and is simple. It is known as the Higman-Sims group:: sage: H = graphs.HigmanSimsGraph() sage: G = H.automorphism_group() sage: g=G.order(); g 88704000 sage: K = G.normal_subgroups()[1] sage: K.is_simple() True sage: g//K.order() 2 AUTHOR: - Rob Beezer (2009-10-24) """ HS = Graph() HS.name('Higman-Sims graph') # Four groups of either five pentagons, or five pentagrams 4 x 5 x 5 = 100 # vertices # First digit is "group", second is "penta{gon|gram}", third is "vertex" vlist = ['%d%d%d'%(g, p, v) for g in range(4) for p in range(5) for v in range(5)] HS.add_vertices(vlist) # Edges: Within groups 0 and 2, joined as pentagons # Edges: Within groups 1 and 3, joined as pentagrams for g in range(4): shift = 1 if g in [1, 3]: shift += 1 for p in range(5): for v in range(5): HS.add_edge(('%d%d%d'%(g, p, v), '%d%d%d'%(g, p, (v + shift) % 5))) # Edges: group 0 to group 1 for x in range(5): for m in range(5): for c in range(5): y = (m * x + c) % 5 HS.add_edge(('0%d%d'%(x, y), '1%d%d'%(m, c))) # Edges: group 1 to group 2 for m in range(5): for A in range(5): for B in range(5): c = (2 * (m - A) * (m - A) + B) % 5 HS.add_edge(('1%d%d'%(m, c), '2%d%d'%(A, B))) # Edges: group 2 to group 3 for A in range(5): for a in range(5): for b in range(5): B = (2*A*A + 3*a*A - a*a+b) % 5 HS.add_edge(('2%d%d'%(A, B), '3%d%d'%(a, b))) # Edges: group 3 to group 0 for a in range(5): for b in range(5): for x in range(5): y = ((x - a) * (x - a) + b)%5 HS.add_edge(('3%d%d'%(a, b), '0%d%d'%(x, y))) # Edges: group 0 to group 2 for x in range(5): for A in range(5): for B in range(5): y = (3*x*x + A*x + B + 1) % 5 HS.add_edge(('0%d%d'%(x, y), '2%d%d'%(A, B))) y = (3*x*x + A*x + B - 1) % 5 HS.add_edge(('0%d%d'%(x, y), '2%d%d'%(A, B))) # Edges: group 1 to group 3 for m in range(5): for a in range(5): for b in range(5): c = (m*(m-a) + b + 2) % 5 HS.add_edge(('1%d%d'%(m, c), '3%d%d'%(a, b))) c = (m*(m-a) + b - 2) % 5 HS.add_edge(('1%d%d'%(m, c), '3%d%d'%(a, b))) # Layout vertices in a circle, in the order given in vlist HS._circle_embedding(vlist, radius=10, angle=pi/2) if relabel: HS.relabel(range(100)) return HS
[ "def", "HigmanSimsGraph", "(", "relabel", "=", "True", ")", ":", "HS", "=", "Graph", "(", ")", "HS", ".", "name", "(", "'Higman-Sims graph'", ")", "# Four groups of either five pentagons, or five pentagrams 4 x 5 x 5 = 100", "# vertices", "# First digit is \"group\", second is \"penta{gon|gram}\", third is \"vertex\"", "vlist", "=", "[", "'%d%d%d'", "%", "(", "g", ",", "p", ",", "v", ")", "for", "g", "in", "range", "(", "4", ")", "for", "p", "in", "range", "(", "5", ")", "for", "v", "in", "range", "(", "5", ")", "]", "HS", ".", "add_vertices", "(", "vlist", ")", "# Edges: Within groups 0 and 2, joined as pentagons", "# Edges: Within groups 1 and 3, joined as pentagrams", "for", "g", "in", "range", "(", "4", ")", ":", "shift", "=", "1", "if", "g", "in", "[", "1", ",", "3", "]", ":", "shift", "+=", "1", "for", "p", "in", "range", "(", "5", ")", ":", "for", "v", "in", "range", "(", "5", ")", ":", "HS", ".", "add_edge", "(", "(", "'%d%d%d'", "%", "(", "g", ",", "p", ",", "v", ")", ",", "'%d%d%d'", "%", "(", "g", ",", "p", ",", "(", "v", "+", "shift", ")", "%", "5", ")", ")", ")", "# Edges: group 0 to group 1", "for", "x", "in", "range", "(", "5", ")", ":", "for", "m", "in", "range", "(", "5", ")", ":", "for", "c", "in", "range", "(", "5", ")", ":", "y", "=", "(", "m", "*", "x", "+", "c", ")", "%", "5", "HS", ".", "add_edge", "(", "(", "'0%d%d'", "%", "(", "x", ",", "y", ")", ",", "'1%d%d'", "%", "(", "m", ",", "c", ")", ")", ")", "# Edges: group 1 to group 2", "for", "m", "in", "range", "(", "5", ")", ":", "for", "A", "in", "range", "(", "5", ")", ":", "for", "B", "in", "range", "(", "5", ")", ":", "c", "=", "(", "2", "*", "(", "m", "-", "A", ")", "*", "(", "m", "-", "A", ")", "+", "B", ")", "%", "5", "HS", ".", "add_edge", "(", "(", "'1%d%d'", "%", "(", "m", ",", "c", ")", ",", "'2%d%d'", "%", "(", "A", ",", "B", ")", ")", ")", "# Edges: group 2 to group 3", "for", "A", "in", "range", "(", "5", ")", ":", "for", "a", "in", "range", "(", "5", ")", ":", "for", "b", "in", "range", "(", "5", ")", ":", "B", "=", "(", "2", "*", "A", "*", "A", "+", "3", "*", "a", "*", "A", "-", "a", "*", "a", "+", "b", ")", "%", "5", "HS", ".", "add_edge", "(", "(", "'2%d%d'", "%", "(", "A", ",", "B", ")", ",", "'3%d%d'", "%", "(", "a", ",", "b", ")", ")", ")", "# Edges: group 3 to group 0", "for", "a", "in", "range", "(", "5", ")", ":", "for", "b", "in", "range", "(", "5", ")", ":", "for", "x", "in", "range", "(", "5", ")", ":", "y", "=", "(", "(", "x", "-", "a", ")", "*", "(", "x", "-", "a", ")", "+", "b", ")", "%", "5", "HS", ".", "add_edge", "(", "(", "'3%d%d'", "%", "(", "a", ",", "b", ")", ",", "'0%d%d'", "%", "(", "x", ",", "y", ")", ")", ")", "# Edges: group 0 to group 2", "for", "x", "in", "range", "(", "5", ")", ":", "for", "A", "in", "range", "(", "5", ")", ":", "for", "B", "in", "range", "(", "5", ")", ":", "y", "=", "(", "3", "*", "x", "*", "x", "+", "A", "*", "x", "+", "B", "+", "1", ")", "%", "5", "HS", ".", "add_edge", "(", "(", "'0%d%d'", "%", "(", "x", ",", "y", ")", ",", "'2%d%d'", "%", "(", "A", ",", "B", ")", ")", ")", "y", "=", "(", "3", "*", "x", "*", "x", "+", "A", "*", "x", "+", "B", "-", "1", ")", "%", "5", "HS", ".", "add_edge", "(", "(", "'0%d%d'", "%", "(", "x", ",", "y", ")", ",", "'2%d%d'", "%", "(", "A", ",", "B", ")", ")", ")", "# Edges: group 1 to group 3", "for", "m", "in", "range", "(", "5", ")", ":", "for", "a", "in", "range", "(", "5", ")", ":", "for", "b", "in", "range", "(", "5", ")", ":", "c", "=", "(", "m", "*", "(", "m", "-", "a", ")", "+", "b", "+", "2", ")", "%", "5", "HS", ".", "add_edge", "(", "(", "'1%d%d'", "%", "(", "m", ",", "c", ")", ",", "'3%d%d'", "%", "(", "a", ",", "b", ")", ")", ")", "c", "=", "(", "m", "*", "(", "m", "-", "a", ")", "+", "b", "-", "2", ")", "%", "5", "HS", ".", "add_edge", "(", "(", "'1%d%d'", "%", "(", "m", ",", "c", ")", ",", "'3%d%d'", "%", "(", "a", ",", "b", ")", ")", ")", "# Layout vertices in a circle, in the order given in vlist", "HS", ".", "_circle_embedding", "(", "vlist", ",", "radius", "=", "10", ",", "angle", "=", "pi", "/", "2", ")", "if", "relabel", ":", "HS", ".", "relabel", "(", "range", "(", "100", ")", ")", "return", "HS" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/graphs/generators/smallgraphs.py#L2863-L2999
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
mycpp/debug_pass.py
python
Print.visit_mypy_file
(self, o: 'mypy.nodes.MypyFile')
[]
def visit_mypy_file(self, o: 'mypy.nodes.MypyFile') -> T: # Skip some stdlib stuff. A lot of it is brought in by 'import # typing'. if o.fullname() in ( '__future__', 'sys', 'types', 'typing', 'abc', '_ast', 'ast', '_weakrefset', 'collections', 'cStringIO', 're', 'builtins'): # These module are special; their contents are currently all # built-in primitives. return self.log('') self.log('mypyfile %s', o.fullname()) self.module_path = o.path self.indent += 1 for node in o.defs: self.accept(node) self.indent -= 1
[ "def", "visit_mypy_file", "(", "self", ",", "o", ":", "'mypy.nodes.MypyFile'", ")", "->", "T", ":", "# Skip some stdlib stuff. A lot of it is brought in by 'import", "# typing'.", "if", "o", ".", "fullname", "(", ")", "in", "(", "'__future__'", ",", "'sys'", ",", "'types'", ",", "'typing'", ",", "'abc'", ",", "'_ast'", ",", "'ast'", ",", "'_weakrefset'", ",", "'collections'", ",", "'cStringIO'", ",", "'re'", ",", "'builtins'", ")", ":", "# These module are special; their contents are currently all", "# built-in primitives.", "return", "self", ".", "log", "(", "''", ")", "self", ".", "log", "(", "'mypyfile %s'", ",", "o", ".", "fullname", "(", ")", ")", "self", ".", "module_path", "=", "o", ".", "path", "self", ".", "indent", "+=", "1", "for", "node", "in", "o", ".", "defs", ":", "self", ".", "accept", "(", "node", ")", "self", ".", "indent", "-=", "1" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/mycpp/debug_pass.py#L63-L82
angr/angr
4b04d56ace135018083d36d9083805be8146688b
angr/analyses/vfg.py
python
VFG._widen_jobs
(self, *jobs)
return new_job
:param iterable jobs: :return:
[]
def _widen_jobs(self, *jobs): """ :param iterable jobs: :return: """ job_0, job_1 = jobs[-2:] # type: VFGJob # update jobs for job in jobs: if job in self._top_function_analysis_task.jobs: self._top_function_analysis_task.jobs.remove(job) l.debug("Widening %s", job_1) new_state, _ = self._widen_states(job_0.state, job_1.state) # print "job_0.state.eax =", job_0.state.regs.eax._model_vsa, "job_1.state.eax =", job_1.state.regs.eax._model_vsa # print "new_job.state.eax =", new_state.regs.eax._model_vsa new_job = VFGJob(jobs[0].addr, new_state, self._context_sensitivity_level, jumpkind=jobs[0].jumpkind, block_id=jobs[0].block_id, call_stack=jobs[0].call_stack, src_block_id=jobs[0].src_block_id, src_exit_stmt_idx=jobs[0].src_exit_stmt_idx, src_ins_addr=jobs[0].src_ins_addr, ) self._top_function_analysis_task.jobs.append(new_job) return new_job
[ "def", "_widen_jobs", "(", "self", ",", "*", "jobs", ")", ":", "job_0", ",", "job_1", "=", "jobs", "[", "-", "2", ":", "]", "# type: VFGJob", "# update jobs", "for", "job", "in", "jobs", ":", "if", "job", "in", "self", ".", "_top_function_analysis_task", ".", "jobs", ":", "self", ".", "_top_function_analysis_task", ".", "jobs", ".", "remove", "(", "job", ")", "l", ".", "debug", "(", "\"Widening %s\"", ",", "job_1", ")", "new_state", ",", "_", "=", "self", ".", "_widen_states", "(", "job_0", ".", "state", ",", "job_1", ".", "state", ")", "# print \"job_0.state.eax =\", job_0.state.regs.eax._model_vsa, \"job_1.state.eax =\", job_1.state.regs.eax._model_vsa", "# print \"new_job.state.eax =\", new_state.regs.eax._model_vsa", "new_job", "=", "VFGJob", "(", "jobs", "[", "0", "]", ".", "addr", ",", "new_state", ",", "self", ".", "_context_sensitivity_level", ",", "jumpkind", "=", "jobs", "[", "0", "]", ".", "jumpkind", ",", "block_id", "=", "jobs", "[", "0", "]", ".", "block_id", ",", "call_stack", "=", "jobs", "[", "0", "]", ".", "call_stack", ",", "src_block_id", "=", "jobs", "[", "0", "]", ".", "src_block_id", ",", "src_exit_stmt_idx", "=", "jobs", "[", "0", "]", ".", "src_exit_stmt_idx", ",", "src_ins_addr", "=", "jobs", "[", "0", "]", ".", "src_ins_addr", ",", ")", "self", ".", "_top_function_analysis_task", ".", "jobs", ".", "append", "(", "new_job", ")", "return", "new_job" ]
https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/analyses/vfg.py#L1022-L1048
OSInside/kiwi
9618cf33f510ddf302ad1d4e0df35f75b00eb152
kiwi/xml_state.py
python
XMLState.copy_drivers_sections
(self, target_state: Any)
Copy drivers sections from this xml state to the target xml state :param object target_state: XMLState instance
Copy drivers sections from this xml state to the target xml state
[ "Copy", "drivers", "sections", "from", "this", "xml", "state", "to", "the", "target", "xml", "state" ]
def copy_drivers_sections(self, target_state: Any) -> None: """ Copy drivers sections from this xml state to the target xml state :param object target_state: XMLState instance """ drivers_sections = self._profiled( self.xml_data.get_drivers() ) if drivers_sections: for drivers_section in drivers_sections: target_state.xml_data.add_drivers(drivers_section)
[ "def", "copy_drivers_sections", "(", "self", ",", "target_state", ":", "Any", ")", "->", "None", ":", "drivers_sections", "=", "self", ".", "_profiled", "(", "self", ".", "xml_data", ".", "get_drivers", "(", ")", ")", "if", "drivers_sections", ":", "for", "drivers_section", "in", "drivers_sections", ":", "target_state", ".", "xml_data", ".", "add_drivers", "(", "drivers_section", ")" ]
https://github.com/OSInside/kiwi/blob/9618cf33f510ddf302ad1d4e0df35f75b00eb152/kiwi/xml_state.py#L1899-L1910
xillwillx/skiptracer
fbc1f8c88907db3014c6c64d08b7ded814a9c172
src/skiptracer/plugins/true_people/__init__.py
python
TruePeopleGrabber.grab_age
(self)
Grab the user age from the DOM
Grab the user age from the DOM
[ "Grab", "the", "user", "age", "from", "the", "DOM" ]
def grab_age(self): """ Grab the user age from the DOM """ age = "Unknown" try: age1 = self.soup2.find('span', {'class': 'content-value'}) age2 = " ".join(str(age1).split()) age = age2.split(">")[1].split("<")[0].split()[1] print((" [" + bc.CGRN + "+" + bc.CEND + "] " + bc.CRED + "Age: " + bc.CEND + "%s") % (age)) except Exception as e: print(e) finally: return age
[ "def", "grab_age", "(", "self", ")", ":", "age", "=", "\"Unknown\"", "try", ":", "age1", "=", "self", ".", "soup2", ".", "find", "(", "'span'", ",", "{", "'class'", ":", "'content-value'", "}", ")", "age2", "=", "\" \"", ".", "join", "(", "str", "(", "age1", ")", ".", "split", "(", ")", ")", "age", "=", "age2", ".", "split", "(", "\">\"", ")", "[", "1", "]", ".", "split", "(", "\"<\"", ")", "[", "0", "]", ".", "split", "(", ")", "[", "1", "]", "print", "(", "(", "\" [\"", "+", "bc", ".", "CGRN", "+", "\"+\"", "+", "bc", ".", "CEND", "+", "\"] \"", "+", "bc", ".", "CRED", "+", "\"Age: \"", "+", "bc", ".", "CEND", "+", "\"%s\"", ")", "%", "(", "age", ")", ")", "except", "Exception", "as", "e", ":", "print", "(", "e", ")", "finally", ":", "return", "age" ]
https://github.com/xillwillx/skiptracer/blob/fbc1f8c88907db3014c6c64d08b7ded814a9c172/src/skiptracer/plugins/true_people/__init__.py#L204-L219
pytest-dev/pytest-xdist
5749a347b998448c55e5db94bcee7fa1d4378fa6
src/xdist/dsession.py
python
get_default_max_worker_restart
(config)
return result
gets the default value of --max-worker-restart option if it is not provided. Use a reasonable default to avoid workers from restarting endlessly due to crashing collections (#226).
gets the default value of --max-worker-restart option if it is not provided.
[ "gets", "the", "default", "value", "of", "--", "max", "-", "worker", "-", "restart", "option", "if", "it", "is", "not", "provided", "." ]
def get_default_max_worker_restart(config): """gets the default value of --max-worker-restart option if it is not provided. Use a reasonable default to avoid workers from restarting endlessly due to crashing collections (#226). """ result = config.option.maxworkerrestart if result is not None: result = int(result) elif config.option.numprocesses: # if --max-worker-restart was not provided, use a reasonable default (#226) result = config.option.numprocesses * 4 return result
[ "def", "get_default_max_worker_restart", "(", "config", ")", ":", "result", "=", "config", ".", "option", ".", "maxworkerrestart", "if", "result", "is", "not", "None", ":", "result", "=", "int", "(", "result", ")", "elif", "config", ".", "option", ".", "numprocesses", ":", "# if --max-worker-restart was not provided, use a reasonable default (#226)", "result", "=", "config", ".", "option", ".", "numprocesses", "*", "4", "return", "result" ]
https://github.com/pytest-dev/pytest-xdist/blob/5749a347b998448c55e5db94bcee7fa1d4378fa6/src/xdist/dsession.py#L438-L449
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/gdata/alt/appengine.py
python
run_on_appengine
(gdata_service, store_tokens=True, single_user_mode=False, deadline=None)
return gdata_service
Modifies a GDataService object to allow it to run on App Engine. Args: gdata_service: An instance of AtomService, GDataService, or any of their subclasses which has an http_client member and a token_store member. store_tokens: Boolean, defaults to True. If True, the gdata_service will attempt to add each token to it's token_store when SetClientLoginToken or SetAuthSubToken is called. If False the tokens will not automatically be added to the token_store. single_user_mode: Boolean, defaults to False. If True, the current_token member of gdata_service will be set when SetClientLoginToken or SetAuthTubToken is called. If set to True, the current_token is set in the gdata_service and anyone who accesses the object will use the same token. Note: If store_tokens is set to False and single_user_mode is set to False, all tokens will be ignored, since the library assumes: the tokens should not be stored in the datastore and they should not be stored in the gdata_service object. This will make it impossible to make requests which require authorization. deadline: int (optional) The number of seconds to wait for a response before timing out on the HTTP request. If no deadline is specified, the deafault deadline for HTTP requests from App Engine is used. The maximum is currently 10 (for 10 seconds). The default deadline for App Engine is 5 seconds.
Modifies a GDataService object to allow it to run on App Engine.
[ "Modifies", "a", "GDataService", "object", "to", "allow", "it", "to", "run", "on", "App", "Engine", "." ]
def run_on_appengine(gdata_service, store_tokens=True, single_user_mode=False, deadline=None): """Modifies a GDataService object to allow it to run on App Engine. Args: gdata_service: An instance of AtomService, GDataService, or any of their subclasses which has an http_client member and a token_store member. store_tokens: Boolean, defaults to True. If True, the gdata_service will attempt to add each token to it's token_store when SetClientLoginToken or SetAuthSubToken is called. If False the tokens will not automatically be added to the token_store. single_user_mode: Boolean, defaults to False. If True, the current_token member of gdata_service will be set when SetClientLoginToken or SetAuthTubToken is called. If set to True, the current_token is set in the gdata_service and anyone who accesses the object will use the same token. Note: If store_tokens is set to False and single_user_mode is set to False, all tokens will be ignored, since the library assumes: the tokens should not be stored in the datastore and they should not be stored in the gdata_service object. This will make it impossible to make requests which require authorization. deadline: int (optional) The number of seconds to wait for a response before timing out on the HTTP request. If no deadline is specified, the deafault deadline for HTTP requests from App Engine is used. The maximum is currently 10 (for 10 seconds). The default deadline for App Engine is 5 seconds. """ gdata_service.http_client = AppEngineHttpClient(deadline=deadline) gdata_service.token_store = AppEngineTokenStore() gdata_service.auto_store_tokens = store_tokens gdata_service.auto_set_current_token = single_user_mode return gdata_service
[ "def", "run_on_appengine", "(", "gdata_service", ",", "store_tokens", "=", "True", ",", "single_user_mode", "=", "False", ",", "deadline", "=", "None", ")", ":", "gdata_service", ".", "http_client", "=", "AppEngineHttpClient", "(", "deadline", "=", "deadline", ")", "gdata_service", ".", "token_store", "=", "AppEngineTokenStore", "(", ")", "gdata_service", ".", "auto_store_tokens", "=", "store_tokens", "gdata_service", ".", "auto_set_current_token", "=", "single_user_mode", "return", "gdata_service" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/gdata/alt/appengine.py#L45-L81
jm33-m0/mec
d9cef9e5718d47f2e2b47a03501f00a5b15355d0
lib/tools/zoomeye.py
python
ZoomEyeAPI.login
(self)
login using given username and password
login using given username and password
[ "login", "using", "given", "username", "and", "password" ]
def login(self): ''' login using given username and password ''' data = { 'username': self.user, 'password': self.passwd } data_encoded = json.dumps(data) try: r_post = requests.post( url='https://api.zoomeye.org/user/login', data=data_encoded, timeout=30) r_decoded = json.loads(r_post.text) return r_decoded['access_token'] except requests.exceptions.RequestException as exc: console.print_error( f"Login error: request failed: {exc}") return "" except KeyError: console.print_error( f"Login error: {r_post.status_code}: {r_post.text}") return "" except KeyboardInterrupt: return "" except BaseException: console.debug_except()
[ "def", "login", "(", "self", ")", ":", "data", "=", "{", "'username'", ":", "self", ".", "user", ",", "'password'", ":", "self", ".", "passwd", "}", "data_encoded", "=", "json", ".", "dumps", "(", "data", ")", "try", ":", "r_post", "=", "requests", ".", "post", "(", "url", "=", "'https://api.zoomeye.org/user/login'", ",", "data", "=", "data_encoded", ",", "timeout", "=", "30", ")", "r_decoded", "=", "json", ".", "loads", "(", "r_post", ".", "text", ")", "return", "r_decoded", "[", "'access_token'", "]", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "exc", ":", "console", ".", "print_error", "(", "f\"Login error: request failed: {exc}\"", ")", "return", "\"\"", "except", "KeyError", ":", "console", ".", "print_error", "(", "f\"Login error: {r_post.status_code}: {r_post.text}\"", ")", "return", "\"\"", "except", "KeyboardInterrupt", ":", "return", "\"\"", "except", "BaseException", ":", "console", ".", "debug_except", "(", ")" ]
https://github.com/jm33-m0/mec/blob/d9cef9e5718d47f2e2b47a03501f00a5b15355d0/lib/tools/zoomeye.py#L57-L87
ganeti/ganeti
d340a9ddd12f501bef57da421b5f9b969a4ba905
qa/qa_cluster.py
python
TestClusterCommand
()
gnt-cluster command
gnt-cluster command
[ "gnt", "-", "cluster", "command" ]
def TestClusterCommand(): """gnt-cluster command""" uniqueid = utils.NewUUID() rfile = "/tmp/gnt%s" % utils.NewUUID() rcmd = utils.ShellQuoteArgs(["echo", "-n", uniqueid]) cmd = utils.ShellQuoteArgs(["gnt-cluster", "command", "%s >%s" % (rcmd, rfile)]) try: AssertCommand(cmd) _CheckFileOnAllNodes(rfile, uniqueid) finally: _RemoveFileFromAllNodes(rfile)
[ "def", "TestClusterCommand", "(", ")", ":", "uniqueid", "=", "utils", ".", "NewUUID", "(", ")", "rfile", "=", "\"/tmp/gnt%s\"", "%", "utils", ".", "NewUUID", "(", ")", "rcmd", "=", "utils", ".", "ShellQuoteArgs", "(", "[", "\"echo\"", ",", "\"-n\"", ",", "uniqueid", "]", ")", "cmd", "=", "utils", ".", "ShellQuoteArgs", "(", "[", "\"gnt-cluster\"", ",", "\"command\"", ",", "\"%s >%s\"", "%", "(", "rcmd", ",", "rfile", ")", "]", ")", "try", ":", "AssertCommand", "(", "cmd", ")", "_CheckFileOnAllNodes", "(", "rfile", ",", "uniqueid", ")", "finally", ":", "_RemoveFileFromAllNodes", "(", "rfile", ")" ]
https://github.com/ganeti/ganeti/blob/d340a9ddd12f501bef57da421b5f9b969a4ba905/qa/qa_cluster.py#L1613-L1625
jarvisteach/appJar
0b59ce041da2197dcff3410e20f298676f1f7266
appJar/appjar.py
python
gui.text
(self, title, value=None, *args, **kwargs)
return self.textArea(title, value, *args, **kwargs)
simpleGUI - shortner for textArea()
simpleGUI - shortner for textArea()
[ "simpleGUI", "-", "shortner", "for", "textArea", "()" ]
def text(self, title, value=None, *args, **kwargs): """ simpleGUI - shortner for textArea() """ return self.textArea(title, value, *args, **kwargs)
[ "def", "text", "(", "self", ",", "title", ",", "value", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "textArea", "(", "title", ",", "value", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/jarvisteach/appJar/blob/0b59ce041da2197dcff3410e20f298676f1f7266/appJar/appjar.py#L9160-L9162
NeuralEnsemble/python-neo
34d4db8fb0dc950dbbc6defd7fb75e99ea877286
neo/rawio/blackrockrawio.py
python
BlackrockRawIO.__read_nev_header_variant_a
(self)
return self.__read_nev_header(ext_header_variants)
Extract nev header information from a 2.1 .nev file
Extract nev header information from a 2.1 .nev file
[ "Extract", "nev", "header", "information", "from", "a", "2", ".", "1", ".", "nev", "file" ]
def __read_nev_header_variant_a(self): """ Extract nev header information from a 2.1 .nev file """ ext_header_variants = { b'NEUEVWAV': 'a', b'ARRAYNME': 'a', b'ECOMMENT': 'a', b'CCOMMENT': 'a', b'MAPFILE': 'a', b'NSASEXEV': 'a'} return self.__read_nev_header(ext_header_variants)
[ "def", "__read_nev_header_variant_a", "(", "self", ")", ":", "ext_header_variants", "=", "{", "b'NEUEVWAV'", ":", "'a'", ",", "b'ARRAYNME'", ":", "'a'", ",", "b'ECOMMENT'", ":", "'a'", ",", "b'CCOMMENT'", ":", "'a'", ",", "b'MAPFILE'", ":", "'a'", ",", "b'NSASEXEV'", ":", "'a'", "}", "return", "self", ".", "__read_nev_header", "(", "ext_header_variants", ")" ]
https://github.com/NeuralEnsemble/python-neo/blob/34d4db8fb0dc950dbbc6defd7fb75e99ea877286/neo/rawio/blackrockrawio.py#L1018-L1031
ansible-collections/community.general
3faffe8f47968a2400ba3c896c8901c03001a194
plugins/modules/cloud/centurylink/clc_alert_policy.py
python
ClcAlertPolicy._get_alert_policy_id
(self, module, alert_policy_name)
return alert_policy_id
retrieves the alert policy id of the account based on the name of the policy :param module: the AnsibleModule object :param alert_policy_name: the alert policy name :return: alert_policy_id: The alert policy id
retrieves the alert policy id of the account based on the name of the policy :param module: the AnsibleModule object :param alert_policy_name: the alert policy name :return: alert_policy_id: The alert policy id
[ "retrieves", "the", "alert", "policy", "id", "of", "the", "account", "based", "on", "the", "name", "of", "the", "policy", ":", "param", "module", ":", "the", "AnsibleModule", "object", ":", "param", "alert_policy_name", ":", "the", "alert", "policy", "name", ":", "return", ":", "alert_policy_id", ":", "The", "alert", "policy", "id" ]
def _get_alert_policy_id(self, module, alert_policy_name): """ retrieves the alert policy id of the account based on the name of the policy :param module: the AnsibleModule object :param alert_policy_name: the alert policy name :return: alert_policy_id: The alert policy id """ alert_policy_id = None for policy_id in self.policy_dict: if self.policy_dict.get(policy_id).get('name') == alert_policy_name: if not alert_policy_id: alert_policy_id = policy_id else: return module.fail_json( msg='multiple alert policies were found with policy name : %s' % alert_policy_name) return alert_policy_id
[ "def", "_get_alert_policy_id", "(", "self", ",", "module", ",", "alert_policy_name", ")", ":", "alert_policy_id", "=", "None", "for", "policy_id", "in", "self", ".", "policy_dict", ":", "if", "self", ".", "policy_dict", ".", "get", "(", "policy_id", ")", ".", "get", "(", "'name'", ")", "==", "alert_policy_name", ":", "if", "not", "alert_policy_id", ":", "alert_policy_id", "=", "policy_id", "else", ":", "return", "module", ".", "fail_json", "(", "msg", "=", "'multiple alert policies were found with policy name : %s'", "%", "alert_policy_name", ")", "return", "alert_policy_id" ]
https://github.com/ansible-collections/community.general/blob/3faffe8f47968a2400ba3c896c8901c03001a194/plugins/modules/cloud/centurylink/clc_alert_policy.py#L490-L505
numba/numba
bf480b9e0da858a65508c2b17759a72ee6a44c51
numba/core/fastmathpass.py
python
rewrite_module
(mod, options)
Rewrite the given LLVM module to use fastmath everywhere.
Rewrite the given LLVM module to use fastmath everywhere.
[ "Rewrite", "the", "given", "LLVM", "module", "to", "use", "fastmath", "everywhere", "." ]
def rewrite_module(mod, options): """ Rewrite the given LLVM module to use fastmath everywhere. """ flags = options.flags FastFloatBinOpVisitor(flags).visit(mod) FastFloatCallVisitor(flags).visit(mod)
[ "def", "rewrite_module", "(", "mod", ",", "options", ")", ":", "flags", "=", "options", ".", "flags", "FastFloatBinOpVisitor", "(", "flags", ")", ".", "visit", "(", "mod", ")", "FastFloatCallVisitor", "(", "flags", ")", ".", "visit", "(", "mod", ")" ]
https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/core/fastmathpass.py#L37-L43
LabPy/lantz
3e878e3f765a4295b0089d04e241d4beb7b8a65b
lantz/drivers/legacy/visalib.py
python
VisaLibrary.vxi_command_query
(self, session, mode, command)
return response.value
Sends the device a miscellaneous command or query and/or retrieves the response to a previous query. :param session: Unique logical identifier to a session. :param mode: Specifies whether to issue a command and/or retrieve a response. (Constants.VXI_CMD*, .VXI_RESP*) :param command: The miscellaneous command to send. :return: The response retrieved from the device.
Sends the device a miscellaneous command or query and/or retrieves the response to a previous query.
[ "Sends", "the", "device", "a", "miscellaneous", "command", "or", "query", "and", "/", "or", "retrieves", "the", "response", "to", "a", "previous", "query", "." ]
def vxi_command_query(self, session, mode, command): """Sends the device a miscellaneous command or query and/or retrieves the response to a previous query. :param session: Unique logical identifier to a session. :param mode: Specifies whether to issue a command and/or retrieve a response. (Constants.VXI_CMD*, .VXI_RESP*) :param command: The miscellaneous command to send. :return: The response retrieved from the device. """ response = Types.UInt32() self.lib.viVxiCommandQuery(session, mode, command, ct.byref(response)) return response.value
[ "def", "vxi_command_query", "(", "self", ",", "session", ",", "mode", ",", "command", ")", ":", "response", "=", "Types", ".", "UInt32", "(", ")", "self", ".", "lib", ".", "viVxiCommandQuery", "(", "session", ",", "mode", ",", "command", ",", "ct", ".", "byref", "(", "response", ")", ")", "return", "response", ".", "value" ]
https://github.com/LabPy/lantz/blob/3e878e3f765a4295b0089d04e241d4beb7b8a65b/lantz/drivers/legacy/visalib.py#L1516-L1526
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/patched/notpip/_vendor/six.py
python
add_metaclass
(metaclass)
return wrapper
Class decorator for creating a class with a metaclass.
Class decorator for creating a class with a metaclass.
[ "Class", "decorator", "for", "creating", "a", "class", "with", "a", "metaclass", "." ]
def add_metaclass(metaclass): """Class decorator for creating a class with a metaclass.""" def wrapper(cls): orig_vars = cls.__dict__.copy() slots = orig_vars.get('__slots__') if slots is not None: if isinstance(slots, str): slots = [slots] for slots_var in slots: orig_vars.pop(slots_var) orig_vars.pop('__dict__', None) orig_vars.pop('__weakref__', None) if hasattr(cls, '__qualname__'): orig_vars['__qualname__'] = cls.__qualname__ return metaclass(cls.__name__, cls.__bases__, orig_vars) return wrapper
[ "def", "add_metaclass", "(", "metaclass", ")", ":", "def", "wrapper", "(", "cls", ")", ":", "orig_vars", "=", "cls", ".", "__dict__", ".", "copy", "(", ")", "slots", "=", "orig_vars", ".", "get", "(", "'__slots__'", ")", "if", "slots", "is", "not", "None", ":", "if", "isinstance", "(", "slots", ",", "str", ")", ":", "slots", "=", "[", "slots", "]", "for", "slots_var", "in", "slots", ":", "orig_vars", ".", "pop", "(", "slots_var", ")", "orig_vars", ".", "pop", "(", "'__dict__'", ",", "None", ")", "orig_vars", ".", "pop", "(", "'__weakref__'", ",", "None", ")", "if", "hasattr", "(", "cls", ",", "'__qualname__'", ")", ":", "orig_vars", "[", "'__qualname__'", "]", "=", "cls", ".", "__qualname__", "return", "metaclass", "(", "cls", ".", "__name__", ",", "cls", ".", "__bases__", ",", "orig_vars", ")", "return", "wrapper" ]
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/patched/notpip/_vendor/six.py#L880-L895
tdamdouni/Pythonista
3e082d53b6b9b501a3c8cf3251a8ad4c8be9c2ad
rawphoto/RawPhotoEditor.py
python
DisplayCIImage.__init__
(self, *args, **kwargs)
Set a (reusable) drawing context and provide default values for the image and image size
Set a (reusable) drawing context and provide default values for the image and image size
[ "Set", "a", "(", "reusable", ")", "drawing", "context", "and", "provide", "default", "values", "for", "the", "image", "and", "image", "size" ]
def __init__(self, *args, **kwargs): ''' Set a (reusable) drawing context and provide default values for the image and image size ''' super().__init__(*args, **kwargs) CIContext = ObjCClass('CIContext') self._ctx = CIContext.contextWithOptions_(None) ci_img = ObjCClass('CIImage').imageWithContentsOfURL_(nsurl('photosplash.png')) self.rect = CGRect((0.0, 0.0), (640, 427)) self.ci_img = ci_img
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", ")", ".", "__init__", "(", "*", "args", ",", "*", "*", "kwargs", ")", "CIContext", "=", "ObjCClass", "(", "'CIContext'", ")", "self", ".", "_ctx", "=", "CIContext", ".", "contextWithOptions_", "(", "None", ")", "ci_img", "=", "ObjCClass", "(", "'CIImage'", ")", ".", "imageWithContentsOfURL_", "(", "nsurl", "(", "'photosplash.png'", ")", ")", "self", ".", "rect", "=", "CGRect", "(", "(", "0.0", ",", "0.0", ")", ",", "(", "640", ",", "427", ")", ")", "self", ".", "ci_img", "=", "ci_img" ]
https://github.com/tdamdouni/Pythonista/blob/3e082d53b6b9b501a3c8cf3251a8ad4c8be9c2ad/rawphoto/RawPhotoEditor.py#L360-L369
researchmm/tasn
5dba8ccc096cedc63913730eeea14a9647911129
tasn-mxnet/python/mxnet/symbol/symbol.py
python
Symbol.one_hot
(self, *args, **kwargs)
return op.one_hot(self, *args, **kwargs)
Convenience fluent method for :py:func:`one_hot`. The arguments are the same as for :py:func:`one_hot`, with this array as data.
Convenience fluent method for :py:func:`one_hot`.
[ "Convenience", "fluent", "method", "for", ":", "py", ":", "func", ":", "one_hot", "." ]
def one_hot(self, *args, **kwargs): """Convenience fluent method for :py:func:`one_hot`. The arguments are the same as for :py:func:`one_hot`, with this array as data. """ return op.one_hot(self, *args, **kwargs)
[ "def", "one_hot", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "op", ".", "one_hot", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/researchmm/tasn/blob/5dba8ccc096cedc63913730eeea14a9647911129/tasn-mxnet/python/mxnet/symbol/symbol.py#L1890-L1896
DayBreak-u/Thundernet_Pytorch
ac359d128a44e566ba5852a830c0a2154e10edb2
lib/model/utils/logger.py
python
Logger.scalar_summary
(self, tag, value, step)
Log a scalar variable.
Log a scalar variable.
[ "Log", "a", "scalar", "variable", "." ]
def scalar_summary(self, tag, value, step): """Log a scalar variable.""" summary = tf.Summary( value=[tf.Summary.Value(tag=tag, simple_value=value)]) self.writer.add_summary(summary, step)
[ "def", "scalar_summary", "(", "self", ",", "tag", ",", "value", ",", "step", ")", ":", "summary", "=", "tf", ".", "Summary", "(", "value", "=", "[", "tf", ".", "Summary", ".", "Value", "(", "tag", "=", "tag", ",", "simple_value", "=", "value", ")", "]", ")", "self", ".", "writer", ".", "add_summary", "(", "summary", ",", "step", ")" ]
https://github.com/DayBreak-u/Thundernet_Pytorch/blob/ac359d128a44e566ba5852a830c0a2154e10edb2/lib/model/utils/logger.py#L16-L20
erickrf/nlpnet
60368e079591d9cbef6044dca72ffe46ec9c572e
nlpnet/attributes.py
python
Affix.get_suffix
(cls, word, size)
return code
Return the suffix code for the given word. Consider a suffix of the given size.
Return the suffix code for the given word. Consider a suffix of the given size.
[ "Return", "the", "suffix", "code", "for", "the", "given", "word", ".", "Consider", "a", "suffix", "of", "the", "given", "size", "." ]
def get_suffix(cls, word, size): """ Return the suffix code for the given word. Consider a suffix of the given size. """ if word == WD.padding_left or word == WD.padding_right: return cls.padding if len(word) <= size: return cls.other suffix = word[-size:].lower() code = cls.suffix_codes[size].get(suffix, cls.other) return code
[ "def", "get_suffix", "(", "cls", ",", "word", ",", "size", ")", ":", "if", "word", "==", "WD", ".", "padding_left", "or", "word", "==", "WD", ".", "padding_right", ":", "return", "cls", ".", "padding", "if", "len", "(", "word", ")", "<=", "size", ":", "return", "cls", ".", "other", "suffix", "=", "word", "[", "-", "size", ":", "]", ".", "lower", "(", ")", "code", "=", "cls", ".", "suffix_codes", "[", "size", "]", ".", "get", "(", "suffix", ",", "cls", ".", "other", ")", "return", "code" ]
https://github.com/erickrf/nlpnet/blob/60368e079591d9cbef6044dca72ffe46ec9c572e/nlpnet/attributes.py#L108-L121
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
check_server/check.py
python
get_score
()
return user_scores
[]
def get_score(): res = http('get',flag_server,8080,'/score.php?key=%s'%key,'',headers) print res user_scores = res.split('|') print "******************************************************************" res = '' i = 0 for user_score in user_scores: res += (user_id[i] + ":" + user_score).ljust(20,'*') i += 1 print res print "******************************************************************" return user_scores
[ "def", "get_score", "(", ")", ":", "res", "=", "http", "(", "'get'", ",", "flag_server", ",", "8080", ",", "'/score.php?key=%s'", "%", "key", ",", "''", ",", "headers", ")", "print", "res", "user_scores", "=", "res", ".", "split", "(", "'|'", ")", "print", "\"******************************************************************\"", "res", "=", "''", "i", "=", "0", "for", "user_score", "in", "user_scores", ":", "res", "+=", "(", "user_id", "[", "i", "]", "+", "\":\"", "+", "user_score", ")", ".", "ljust", "(", "20", ",", "'*'", ")", "i", "+=", "1", "print", "res", "print", "\"******************************************************************\"", "return", "user_scores" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/check_server/check.py#L53-L65
airlab-unibas/airlab
1a715766e17c812803624d95196092291fa2241d
airlab/transformation/pairwise.py
python
RigidTransformation.set_parameters
(self, t, phi, rotation_center=None)
Set parameters manually t (array): 2 or 3 dimensional array specifying the spatial translation phi (array): 1 or 3 dimensional array specifying the rotation angles rotation_center (array): 2 or 3 dimensional array specifying the rotation center (default is zeros)
Set parameters manually
[ "Set", "parameters", "manually" ]
def set_parameters(self, t, phi, rotation_center=None): """ Set parameters manually t (array): 2 or 3 dimensional array specifying the spatial translation phi (array): 1 or 3 dimensional array specifying the rotation angles rotation_center (array): 2 or 3 dimensional array specifying the rotation center (default is zeros) """ self._t_x = Parameter(th.tensor(t[0]).to(dtype=self._dtype, device=self._device)) self._t_y = Parameter(th.tensor(t[1]).to(dtype=self._dtype, device=self._device)) self._phi_z = Parameter(th.tensor(phi[0]).to(dtype=self._dtype, device=self._device)) if rotation_center is not None: self._center_mass_x = rotation_center[0] self._center_mass_y = rotation_center[1] if len(t) == 2: self._compute_transformation_2d() else: self._t_z = Parameter(th.tensor(t[2]).to(dtype=self._dtype, device=self._device)) self._phi_x = Parameter(th.tensor(phi[1]).to(dtype=self._dtype, device=self._device)) self._phi_y = Parameter(th.tensor(phi[2]).to(dtype=self._dtype, device=self._device)) if rotation_center is not None: self._center_mass_z = rotation_center[1] self._compute_transformation_3d()
[ "def", "set_parameters", "(", "self", ",", "t", ",", "phi", ",", "rotation_center", "=", "None", ")", ":", "self", ".", "_t_x", "=", "Parameter", "(", "th", ".", "tensor", "(", "t", "[", "0", "]", ")", ".", "to", "(", "dtype", "=", "self", ".", "_dtype", ",", "device", "=", "self", ".", "_device", ")", ")", "self", ".", "_t_y", "=", "Parameter", "(", "th", ".", "tensor", "(", "t", "[", "1", "]", ")", ".", "to", "(", "dtype", "=", "self", ".", "_dtype", ",", "device", "=", "self", ".", "_device", ")", ")", "self", ".", "_phi_z", "=", "Parameter", "(", "th", ".", "tensor", "(", "phi", "[", "0", "]", ")", ".", "to", "(", "dtype", "=", "self", ".", "_dtype", ",", "device", "=", "self", ".", "_device", ")", ")", "if", "rotation_center", "is", "not", "None", ":", "self", ".", "_center_mass_x", "=", "rotation_center", "[", "0", "]", "self", ".", "_center_mass_y", "=", "rotation_center", "[", "1", "]", "if", "len", "(", "t", ")", "==", "2", ":", "self", ".", "_compute_transformation_2d", "(", ")", "else", ":", "self", ".", "_t_z", "=", "Parameter", "(", "th", ".", "tensor", "(", "t", "[", "2", "]", ")", ".", "to", "(", "dtype", "=", "self", ".", "_dtype", ",", "device", "=", "self", ".", "_device", ")", ")", "self", ".", "_phi_x", "=", "Parameter", "(", "th", ".", "tensor", "(", "phi", "[", "1", "]", ")", ".", "to", "(", "dtype", "=", "self", ".", "_dtype", ",", "device", "=", "self", ".", "_device", ")", ")", "self", ".", "_phi_y", "=", "Parameter", "(", "th", ".", "tensor", "(", "phi", "[", "2", "]", ")", ".", "to", "(", "dtype", "=", "self", ".", "_dtype", ",", "device", "=", "self", ".", "_device", ")", ")", "if", "rotation_center", "is", "not", "None", ":", "self", ".", "_center_mass_z", "=", "rotation_center", "[", "1", "]", "self", ".", "_compute_transformation_3d", "(", ")" ]
https://github.com/airlab-unibas/airlab/blob/1a715766e17c812803624d95196092291fa2241d/airlab/transformation/pairwise.py#L194-L219
Textualize/rich
d39626143036188cb2c9e1619e836540f5b627f8
examples/fullscreen.py
python
make_layout
()
return layout
Define the layout.
Define the layout.
[ "Define", "the", "layout", "." ]
def make_layout() -> Layout: """Define the layout.""" layout = Layout(name="root") layout.split( Layout(name="header", size=3), Layout(name="main", ratio=1), Layout(name="footer", size=7), ) layout["main"].split_row( Layout(name="side"), Layout(name="body", ratio=2, minimum_size=60), ) layout["side"].split(Layout(name="box1"), Layout(name="box2")) return layout
[ "def", "make_layout", "(", ")", "->", "Layout", ":", "layout", "=", "Layout", "(", "name", "=", "\"root\"", ")", "layout", ".", "split", "(", "Layout", "(", "name", "=", "\"header\"", ",", "size", "=", "3", ")", ",", "Layout", "(", "name", "=", "\"main\"", ",", "ratio", "=", "1", ")", ",", "Layout", "(", "name", "=", "\"footer\"", ",", "size", "=", "7", ")", ",", ")", "layout", "[", "\"main\"", "]", ".", "split_row", "(", "Layout", "(", "name", "=", "\"side\"", ")", ",", "Layout", "(", "name", "=", "\"body\"", ",", "ratio", "=", "2", ",", "minimum_size", "=", "60", ")", ",", ")", "layout", "[", "\"side\"", "]", ".", "split", "(", "Layout", "(", "name", "=", "\"box1\"", ")", ",", "Layout", "(", "name", "=", "\"box2\"", ")", ")", "return", "layout" ]
https://github.com/Textualize/rich/blob/d39626143036188cb2c9e1619e836540f5b627f8/examples/fullscreen.py#L21-L35
python-zk/kazoo
f585d605eea0a37a08aae95a8cc259b80da2ecf0
kazoo/handlers/eventlet.py
python
SequentialEventletHandler.__init__
(self)
Create a :class:`SequentialEventletHandler` instance
Create a :class:`SequentialEventletHandler` instance
[ "Create", "a", ":", "class", ":", "SequentialEventletHandler", "instance" ]
def __init__(self): """Create a :class:`SequentialEventletHandler` instance""" self.callback_queue = self.queue_impl() self.completion_queue = self.queue_impl() self._workers = [] self._started = False
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "callback_queue", "=", "self", ".", "queue_impl", "(", ")", "self", ".", "completion_queue", "=", "self", ".", "queue_impl", "(", ")", "self", ".", "_workers", "=", "[", "]", "self", ".", "_started", "=", "False" ]
https://github.com/python-zk/kazoo/blob/f585d605eea0a37a08aae95a8cc259b80da2ecf0/kazoo/handlers/eventlet.py#L82-L87
CityOfZion/neo-python
99783bc8310982a5380081ec41a6ee07ba843f3f
neo/logging.py
python
LogManager.config_stdio
(self, log_configurations: Optional[List[LogConfiguration]] = None, default_level=logging.INFO)
Configure the stdio `StreamHandler` levels on the specified loggers. If no log configurations are specified then the `default_level` will be applied to all handlers. Args: log_configurations: a list of (component name, log level) tuples default_level: logging level to apply when no log_configurations are specified
Configure the stdio `StreamHandler` levels on the specified loggers. If no log configurations are specified then the `default_level` will be applied to all handlers.
[ "Configure", "the", "stdio", "StreamHandler", "levels", "on", "the", "specified", "loggers", ".", "If", "no", "log", "configurations", "are", "specified", "then", "the", "default_level", "will", "be", "applied", "to", "all", "handlers", "." ]
def config_stdio(self, log_configurations: Optional[List[LogConfiguration]] = None, default_level=logging.INFO) -> None: """ Configure the stdio `StreamHandler` levels on the specified loggers. If no log configurations are specified then the `default_level` will be applied to all handlers. Args: log_configurations: a list of (component name, log level) tuples default_level: logging level to apply when no log_configurations are specified """ # no configuration specified, apply `default_level` to the stdio handler of all known loggers if not log_configurations: for logger in self.loggers.values(): self._restrict_output(logger, default_level) # only apply specified configuration to the stdio `StreamHandler` of the specific component else: for component, level in log_configurations: try: logger = self.loggers[self.root + component] except KeyError: raise ValueError("Failed to configure component. Invalid name: {}".format(component)) self._restrict_output(logger, level)
[ "def", "config_stdio", "(", "self", ",", "log_configurations", ":", "Optional", "[", "List", "[", "LogConfiguration", "]", "]", "=", "None", ",", "default_level", "=", "logging", ".", "INFO", ")", "->", "None", ":", "# no configuration specified, apply `default_level` to the stdio handler of all known loggers", "if", "not", "log_configurations", ":", "for", "logger", "in", "self", ".", "loggers", ".", "values", "(", ")", ":", "self", ".", "_restrict_output", "(", "logger", ",", "default_level", ")", "# only apply specified configuration to the stdio `StreamHandler` of the specific component", "else", ":", "for", "component", ",", "level", "in", "log_configurations", ":", "try", ":", "logger", "=", "self", ".", "loggers", "[", "self", ".", "root", "+", "component", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "\"Failed to configure component. Invalid name: {}\"", ".", "format", "(", "component", ")", ")", "self", ".", "_restrict_output", "(", "logger", ",", "level", ")" ]
https://github.com/CityOfZion/neo-python/blob/99783bc8310982a5380081ec41a6ee07ba843f3f/neo/logging.py#L63-L83
cobrateam/splinter
a3f30f53d886709e60218e46b521cbd87e9caadd
splinter/driver/__init__.py
python
DriverAPI.back
(self)
The browser will navigate to the previous URL in the history. If there is no previous URL, this method does nothing.
The browser will navigate to the previous URL in the history.
[ "The", "browser", "will", "navigate", "to", "the", "previous", "URL", "in", "the", "history", "." ]
def back(self): """The browser will navigate to the previous URL in the history. If there is no previous URL, this method does nothing. """ raise NotImplementedError( "%s doesn't support moving back in history." % self.driver_name )
[ "def", "back", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "\"%s doesn't support moving back in history.\"", "%", "self", ".", "driver_name", ")" ]
https://github.com/cobrateam/splinter/blob/a3f30f53d886709e60218e46b521cbd87e9caadd/splinter/driver/__init__.py#L70-L77
openstack/neutron
fb229fb527ac8b95526412f7762d90826ac41428
neutron/plugins/ml2/drivers/ovn/mech_driver/ovsdb/impl_idl_ovn.py
python
OvsdbNbOvnIdl.transaction
(self, *args, **kwargs)
A wrapper on the ovsdbapp transaction to work with revisions. This method is just a wrapper around the ovsdbapp transaction to handle revision conflicts correctly.
A wrapper on the ovsdbapp transaction to work with revisions.
[ "A", "wrapper", "on", "the", "ovsdbapp", "transaction", "to", "work", "with", "revisions", "." ]
def transaction(self, *args, **kwargs): """A wrapper on the ovsdbapp transaction to work with revisions. This method is just a wrapper around the ovsdbapp transaction to handle revision conflicts correctly. """ try: with super(OvsdbNbOvnIdl, self).transaction(*args, **kwargs) as t: yield t except ovn_exc.RevisionConflict as e: LOG.info('Transaction aborted. Reason: %s', e)
[ "def", "transaction", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "with", "super", "(", "OvsdbNbOvnIdl", ",", "self", ")", ".", "transaction", "(", "*", "args", ",", "*", "*", "kwargs", ")", "as", "t", ":", "yield", "t", "except", "ovn_exc", ".", "RevisionConflict", "as", "e", ":", "LOG", ".", "info", "(", "'Transaction aborted. Reason: %s'", ",", "e", ")" ]
https://github.com/openstack/neutron/blob/fb229fb527ac8b95526412f7762d90826ac41428/neutron/plugins/ml2/drivers/ovn/mech_driver/ovsdb/impl_idl_ovn.py#L266-L276
yueduan/DeepBinDiff
ee359607ce3df860141f287ea8af0aa2c97e3bb3
src/libnrl/gcn/gcnAPI.py
python
GCN.construct_feed_dict
(self, labels_mask)
return feed_dict
Construct feed dictionary.
Construct feed dictionary.
[ "Construct", "feed", "dictionary", "." ]
def construct_feed_dict(self, labels_mask): """Construct feed dictionary.""" feed_dict = dict() feed_dict.update({self.placeholders['labels']: self.labels}) feed_dict.update({self.placeholders['labels_mask']: labels_mask}) feed_dict.update({self.placeholders['features']: self.features}) feed_dict.update({self.placeholders['support'][i]: self.support[i] for i in range(len(self.support))}) feed_dict.update({self.placeholders['num_features_nonzero']: self.features[1].shape}) return feed_dict
[ "def", "construct_feed_dict", "(", "self", ",", "labels_mask", ")", ":", "feed_dict", "=", "dict", "(", ")", "feed_dict", ".", "update", "(", "{", "self", ".", "placeholders", "[", "'labels'", "]", ":", "self", ".", "labels", "}", ")", "feed_dict", ".", "update", "(", "{", "self", ".", "placeholders", "[", "'labels_mask'", "]", ":", "labels_mask", "}", ")", "feed_dict", ".", "update", "(", "{", "self", ".", "placeholders", "[", "'features'", "]", ":", "self", ".", "features", "}", ")", "feed_dict", ".", "update", "(", "{", "self", ".", "placeholders", "[", "'support'", "]", "[", "i", "]", ":", "self", ".", "support", "[", "i", "]", "for", "i", "in", "range", "(", "len", "(", "self", ".", "support", ")", ")", "}", ")", "feed_dict", ".", "update", "(", "{", "self", ".", "placeholders", "[", "'num_features_nonzero'", "]", ":", "self", ".", "features", "[", "1", "]", ".", "shape", "}", ")", "return", "feed_dict" ]
https://github.com/yueduan/DeepBinDiff/blob/ee359607ce3df860141f287ea8af0aa2c97e3bb3/src/libnrl/gcn/gcnAPI.py#L157-L165
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/telnetlib.py
python
Telnet.read_sb_data
(self)
return buf
Return any data available in the SB ... SE queue. Return b'' if no SB ... SE available. Should only be called after seeing a SB or SE command. When a new SB command is found, old unread SB data will be discarded. Don't block.
Return any data available in the SB ... SE queue.
[ "Return", "any", "data", "available", "in", "the", "SB", "...", "SE", "queue", "." ]
def read_sb_data(self): """Return any data available in the SB ... SE queue. Return b'' if no SB ... SE available. Should only be called after seeing a SB or SE command. When a new SB command is found, old unread SB data will be discarded. Don't block. """ buf = self.sbdataq self.sbdataq = b'' return buf
[ "def", "read_sb_data", "(", "self", ")", ":", "buf", "=", "self", ".", "sbdataq", "self", ".", "sbdataq", "=", "b''", "return", "buf" ]
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/telnetlib.py#L408-L418
mandiant/capa
c0851fc643793c012f5dd764482133c25c3216c8
capa/ida/plugin/proxy.py
python
CapaExplorerRangeProxyModel.__init__
(self, parent=None)
initialize proxy filter
initialize proxy filter
[ "initialize", "proxy", "filter" ]
def __init__(self, parent=None): """initialize proxy filter""" super(CapaExplorerRangeProxyModel, self).__init__(parent) self.min_ea = None self.max_ea = None
[ "def", "__init__", "(", "self", ",", "parent", "=", "None", ")", ":", "super", "(", "CapaExplorerRangeProxyModel", ",", "self", ")", ".", "__init__", "(", "parent", ")", "self", ".", "min_ea", "=", "None", "self", ".", "max_ea", "=", "None" ]
https://github.com/mandiant/capa/blob/c0851fc643793c012f5dd764482133c25c3216c8/capa/ida/plugin/proxy.py#L23-L27
nltk/nltk_contrib
c9da2c29777ca9df650740145f1f4a375ccac961
nltk_contrib/tiger/query/ast.py
python
_NodeRelationOperator.create
(cls, parse_result)
return cls(parse_result.leftOperand, parse_result.rightOperand, **modifiers)
Creates an operator AST node from a parse result.
Creates an operator AST node from a parse result.
[ "Creates", "an", "operator", "AST", "node", "from", "a", "parse", "result", "." ]
def create(cls, parse_result): """Creates an operator AST node from a parse result.""" cls.__converters__["negated"] = lambda o: o.negated != "" modifiers = dict( (name, cls.__converters__[name](parse_result.operator)) for name in cls.__modifiers__) return cls(parse_result.leftOperand, parse_result.rightOperand, **modifiers)
[ "def", "create", "(", "cls", ",", "parse_result", ")", ":", "cls", ".", "__converters__", "[", "\"negated\"", "]", "=", "lambda", "o", ":", "o", ".", "negated", "!=", "\"\"", "modifiers", "=", "dict", "(", "(", "name", ",", "cls", ".", "__converters__", "[", "name", "]", "(", "parse_result", ".", "operator", ")", ")", "for", "name", "in", "cls", ".", "__modifiers__", ")", "return", "cls", "(", "parse_result", ".", "leftOperand", ",", "parse_result", ".", "rightOperand", ",", "*", "*", "modifiers", ")" ]
https://github.com/nltk/nltk_contrib/blob/c9da2c29777ca9df650740145f1f4a375ccac961/nltk_contrib/tiger/query/ast.py#L259-L266
compas-dev/compas
0b33f8786481f710115fb1ae5fe79abc2a9a5175
src/compas/utilities/ssh.py
python
SSH.sync_folder
(self, local_folder, remote_folder)
Sync using rsync, a local folder to a remote folder on the server. Parameters ---------- local_folder : str Path of the local folder to sync from. remote_folder : str Path of the remote folder to sync to.
Sync using rsync, a local folder to a remote folder on the server.
[ "Sync", "using", "rsync", "a", "local", "folder", "to", "a", "remote", "folder", "on", "the", "server", "." ]
def sync_folder(self, local_folder, remote_folder): """Sync using rsync, a local folder to a remote folder on the server. Parameters ---------- local_folder : str Path of the local folder to sync from. remote_folder : str Path of the remote folder to sync to. """ command = 'rsync -Pa {0} {1}@{2}:{3}'.format(local_folder, self.username, self.server, remote_folder) self.local_command(command=command)
[ "def", "sync_folder", "(", "self", ",", "local_folder", ",", "remote_folder", ")", ":", "command", "=", "'rsync -Pa {0} {1}@{2}:{3}'", ".", "format", "(", "local_folder", ",", "self", ".", "username", ",", "self", ".", "server", ",", "remote_folder", ")", "self", ".", "local_command", "(", "command", "=", "command", ")" ]
https://github.com/compas-dev/compas/blob/0b33f8786481f710115fb1ae5fe79abc2a9a5175/src/compas/utilities/ssh.py#L97-L109
HymanLiuTS/flaskTs
286648286976e85d9b9a5873632331efcafe0b21
flasky/lib/python2.7/site-packages/requests/utils.py
python
guess_filename
(obj)
Tries to guess the filename of the given object.
Tries to guess the filename of the given object.
[ "Tries", "to", "guess", "the", "filename", "of", "the", "given", "object", "." ]
def guess_filename(obj): """Tries to guess the filename of the given object.""" name = getattr(obj, 'name', None) if (name and isinstance(name, basestring) and name[0] != '<' and name[-1] != '>'): return os.path.basename(name)
[ "def", "guess_filename", "(", "obj", ")", ":", "name", "=", "getattr", "(", "obj", ",", "'name'", ",", "None", ")", "if", "(", "name", "and", "isinstance", "(", "name", ",", "basestring", ")", "and", "name", "[", "0", "]", "!=", "'<'", "and", "name", "[", "-", "1", "]", "!=", "'>'", ")", ":", "return", "os", ".", "path", ".", "basename", "(", "name", ")" ]
https://github.com/HymanLiuTS/flaskTs/blob/286648286976e85d9b9a5873632331efcafe0b21/flasky/lib/python2.7/site-packages/requests/utils.py#L160-L165
datafolklabs/cement
2d44d2c1821bda6bdfcfe605d244dc2dfb0b19a6
cement/ext/ext_mustache.py
python
MustacheTemplateHandler.render
(self, content, data)
return stache.render(content, data)
Render the given ``content`` as template with the ``data`` dictionary. Args: content (str): The template content to render. data (dict): The data dictionary to render. Returns: str: The rendered template text
Render the given ``content`` as template with the ``data`` dictionary.
[ "Render", "the", "given", "content", "as", "template", "with", "the", "data", "dictionary", "." ]
def render(self, content, data): """ Render the given ``content`` as template with the ``data`` dictionary. Args: content (str): The template content to render. data (dict): The data dictionary to render. Returns: str: The rendered template text """ stache = Renderer(partials=self._partials_loader) return stache.render(content, data)
[ "def", "render", "(", "self", ",", "content", ",", "data", ")", ":", "stache", "=", "Renderer", "(", "partials", "=", "self", ".", "_partials_loader", ")", "return", "stache", ".", "render", "(", "content", ",", "data", ")" ]
https://github.com/datafolklabs/cement/blob/2d44d2c1821bda6bdfcfe605d244dc2dfb0b19a6/cement/ext/ext_mustache.py#L107-L121