nwo
stringlengths 5
58
| sha
stringlengths 40
40
| path
stringlengths 5
172
| language
stringclasses 1
value | identifier
stringlengths 1
100
| parameters
stringlengths 2
3.5k
| argument_list
stringclasses 1
value | return_statement
stringlengths 0
21.5k
| docstring
stringlengths 2
17k
| docstring_summary
stringlengths 0
6.58k
| docstring_tokens
sequence | function
stringlengths 35
55.6k
| function_tokens
sequence | url
stringlengths 89
269
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
scottgchin/delta5_race_timer | fe4e0f46307b05c9384f3124189edc402d812ade | src/delta5server/server.py | python | rainbow | (strip, wait_ms=2, iterations=1) | Draw rainbow that fades across all pixels at once. | Draw rainbow that fades across all pixels at once. | [
"Draw",
"rainbow",
"that",
"fades",
"across",
"all",
"pixels",
"at",
"once",
"."
] | def rainbow(strip, wait_ms=2, iterations=1):
"""Draw rainbow that fades across all pixels at once."""
for j in range(256*iterations):
for i in range(strip.numPixels()):
strip.setPixelColor(i, wheel((i+j) & 255))
strip.show()
time.sleep(wait_ms/1000.0) | [
"def",
"rainbow",
"(",
"strip",
",",
"wait_ms",
"=",
"2",
",",
"iterations",
"=",
"1",
")",
":",
"for",
"j",
"in",
"range",
"(",
"256",
"*",
"iterations",
")",
":",
"for",
"i",
"in",
"range",
"(",
"strip",
".",
"numPixels",
"(",
")",
")",
":",
"strip",
".",
"setPixelColor",
"(",
"i",
",",
"wheel",
"(",
"(",
"i",
"+",
"j",
")",
"&",
"255",
")",
")",
"strip",
".",
"show",
"(",
")",
"time",
".",
"sleep",
"(",
"wait_ms",
"/",
"1000.0",
")"
] | https://github.com/scottgchin/delta5_race_timer/blob/fe4e0f46307b05c9384f3124189edc402d812ade/src/delta5server/server.py#L87-L93 |
||
potch/glow | 653fc29ccff5b72a01a03cc1dd2e2f5f1ebfebe3 | shapefile/shapefile.py | python | Writer.mbox | (self) | return self.__mbox(self._shapes) | Returns the current m extremes for the shapefile. | Returns the current m extremes for the shapefile. | [
"Returns",
"the",
"current",
"m",
"extremes",
"for",
"the",
"shapefile",
"."
] | def mbox(self):
"""Returns the current m extremes for the shapefile."""
return self.__mbox(self._shapes) | [
"def",
"mbox",
"(",
"self",
")",
":",
"return",
"self",
".",
"__mbox",
"(",
"self",
".",
"_shapes",
")"
] | https://github.com/potch/glow/blob/653fc29ccff5b72a01a03cc1dd2e2f5f1ebfebe3/shapefile/shapefile.py#L471-L473 |
|
nodejs/node-chakracore | 770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43 | tools/jinja2/debug.py | python | translate_exception | (exc_info, initial_skip=0) | return ProcessedTraceback(exc_info[0], exc_info[1], frames) | If passed an exc_info it will automatically rewrite the exceptions
all the way down to the correct line numbers and frames. | If passed an exc_info it will automatically rewrite the exceptions
all the way down to the correct line numbers and frames. | [
"If",
"passed",
"an",
"exc_info",
"it",
"will",
"automatically",
"rewrite",
"the",
"exceptions",
"all",
"the",
"way",
"down",
"to",
"the",
"correct",
"line",
"numbers",
"and",
"frames",
"."
] | def translate_exception(exc_info, initial_skip=0):
"""If passed an exc_info it will automatically rewrite the exceptions
all the way down to the correct line numbers and frames.
"""
tb = exc_info[2]
frames = []
# skip some internal frames if wanted
for x in range(initial_skip):
if tb is not None:
tb = tb.tb_next
initial_tb = tb
while tb is not None:
# skip frames decorated with @internalcode. These are internal
# calls we can't avoid and that are useless in template debugging
# output.
if tb.tb_frame.f_code in internal_code:
tb = tb.tb_next
continue
# save a reference to the next frame if we override the current
# one with a faked one.
next = tb.tb_next
# fake template exceptions
template = tb.tb_frame.f_globals.get('__jinja_template__')
if template is not None:
lineno = template.get_corresponding_lineno(tb.tb_lineno)
tb = fake_exc_info(exc_info[:2] + (tb,), template.filename,
lineno)[2]
frames.append(make_frame_proxy(tb))
tb = next
# if we don't have any exceptions in the frames left, we have to
# reraise it unchanged.
# XXX: can we backup here? when could this happen?
if not frames:
reraise(exc_info[0], exc_info[1], exc_info[2])
return ProcessedTraceback(exc_info[0], exc_info[1], frames) | [
"def",
"translate_exception",
"(",
"exc_info",
",",
"initial_skip",
"=",
"0",
")",
":",
"tb",
"=",
"exc_info",
"[",
"2",
"]",
"frames",
"=",
"[",
"]",
"# skip some internal frames if wanted",
"for",
"x",
"in",
"range",
"(",
"initial_skip",
")",
":",
"if",
"tb",
"is",
"not",
"None",
":",
"tb",
"=",
"tb",
".",
"tb_next",
"initial_tb",
"=",
"tb",
"while",
"tb",
"is",
"not",
"None",
":",
"# skip frames decorated with @internalcode. These are internal",
"# calls we can't avoid and that are useless in template debugging",
"# output.",
"if",
"tb",
".",
"tb_frame",
".",
"f_code",
"in",
"internal_code",
":",
"tb",
"=",
"tb",
".",
"tb_next",
"continue",
"# save a reference to the next frame if we override the current",
"# one with a faked one.",
"next",
"=",
"tb",
".",
"tb_next",
"# fake template exceptions",
"template",
"=",
"tb",
".",
"tb_frame",
".",
"f_globals",
".",
"get",
"(",
"'__jinja_template__'",
")",
"if",
"template",
"is",
"not",
"None",
":",
"lineno",
"=",
"template",
".",
"get_corresponding_lineno",
"(",
"tb",
".",
"tb_lineno",
")",
"tb",
"=",
"fake_exc_info",
"(",
"exc_info",
"[",
":",
"2",
"]",
"+",
"(",
"tb",
",",
")",
",",
"template",
".",
"filename",
",",
"lineno",
")",
"[",
"2",
"]",
"frames",
".",
"append",
"(",
"make_frame_proxy",
"(",
"tb",
")",
")",
"tb",
"=",
"next",
"# if we don't have any exceptions in the frames left, we have to",
"# reraise it unchanged.",
"# XXX: can we backup here? when could this happen?",
"if",
"not",
"frames",
":",
"reraise",
"(",
"exc_info",
"[",
"0",
"]",
",",
"exc_info",
"[",
"1",
"]",
",",
"exc_info",
"[",
"2",
"]",
")",
"return",
"ProcessedTraceback",
"(",
"exc_info",
"[",
"0",
"]",
",",
"exc_info",
"[",
"1",
"]",
",",
"frames",
")"
] | https://github.com/nodejs/node-chakracore/blob/770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43/tools/jinja2/debug.py#L154-L195 |
|
shobrook/BitVision | 6345fcaa83e2d94fe4d0aa30ee0a569587696a3e | services/trader.py | python | TradingClient._expect_true | (self, response) | A shortcut that raises a :class:`BitstampError` if the response didn't
just contain the text 'true'. | A shortcut that raises a :class:`BitstampError` if the response didn't
just contain the text 'true'. | [
"A",
"shortcut",
"that",
"raises",
"a",
":",
"class",
":",
"BitstampError",
"if",
"the",
"response",
"didn",
"t",
"just",
"contain",
"the",
"text",
"true",
"."
] | def _expect_true(self, response):
"""
A shortcut that raises a :class:`BitstampError` if the response didn't
just contain the text 'true'.
"""
if response.text == u'true':
return True
raise BitstampError("Unexpected response") | [
"def",
"_expect_true",
"(",
"self",
",",
"response",
")",
":",
"if",
"response",
".",
"text",
"==",
"u'true'",
":",
"return",
"True",
"raise",
"BitstampError",
"(",
"\"Unexpected response\"",
")"
] | https://github.com/shobrook/BitVision/blob/6345fcaa83e2d94fe4d0aa30ee0a569587696a3e/services/trader.py#L207-L215 |
||
EmpireProject/Empire-GUI | 7cad6c48e7f6858c0f389c93d3dbd4f6198e9f26 | node_modules/dmg-builder/vendor/mac_alias/bookmark.py | python | Bookmark.from_bytes | (cls, data) | return cls(tocs) | Create a :class:`Bookmark` given byte data. | Create a :class:`Bookmark` given byte data. | [
"Create",
"a",
":",
"class",
":",
"Bookmark",
"given",
"byte",
"data",
"."
] | def from_bytes(cls, data):
"""Create a :class:`Bookmark` given byte data."""
if len(data) < 16:
raise ValueError('Not a bookmark file (too short)')
if isinstance(data, bytearray):
data = bytes(data)
magic,size,dummy,hdrsize = struct.unpack(b'<4sIII', data[0:16])
if magic != b'book':
raise ValueError('Not a bookmark file (bad magic) %r' % magic)
if hdrsize < 16:
raise ValueError('Not a bookmark file (header size too short)')
if hdrsize > size:
raise ValueError('Not a bookmark file (header size too large)')
if size != len(data):
raise ValueError('Not a bookmark file (truncated)')
tocoffset, = struct.unpack(b'<I', data[hdrsize:hdrsize+4])
tocs = []
while tocoffset != 0:
tocbase = hdrsize + tocoffset
if tocoffset > size - hdrsize \
or size - tocbase < 20:
raise ValueError('TOC offset out of range')
tocsize,tocmagic,tocid,nexttoc,toccount \
= struct.unpack(b'<IIIII',
data[tocbase:tocbase+20])
if tocmagic != 0xfffffffe:
break
tocsize += 8
if size - tocbase < tocsize:
raise ValueError('TOC truncated')
if tocsize < 12 * toccount:
raise ValueError('TOC entries overrun TOC size')
toc = {}
for n in xrange(0,toccount):
ebase = tocbase + 20 + 12 * n
eid,eoffset,edummy = struct.unpack(b'<III',
data[ebase:ebase+12])
if eid & 0x80000000:
eid = cls._get_item(data, hdrsize, eid & 0x7fffffff)
toc[eid] = cls._get_item(data, hdrsize, eoffset)
tocs.append((tocid, toc))
tocoffset = nexttoc
return cls(tocs) | [
"def",
"from_bytes",
"(",
"cls",
",",
"data",
")",
":",
"if",
"len",
"(",
"data",
")",
"<",
"16",
":",
"raise",
"ValueError",
"(",
"'Not a bookmark file (too short)'",
")",
"if",
"isinstance",
"(",
"data",
",",
"bytearray",
")",
":",
"data",
"=",
"bytes",
"(",
"data",
")",
"magic",
",",
"size",
",",
"dummy",
",",
"hdrsize",
"=",
"struct",
".",
"unpack",
"(",
"b'<4sIII'",
",",
"data",
"[",
"0",
":",
"16",
"]",
")",
"if",
"magic",
"!=",
"b'book'",
":",
"raise",
"ValueError",
"(",
"'Not a bookmark file (bad magic) %r'",
"%",
"magic",
")",
"if",
"hdrsize",
"<",
"16",
":",
"raise",
"ValueError",
"(",
"'Not a bookmark file (header size too short)'",
")",
"if",
"hdrsize",
">",
"size",
":",
"raise",
"ValueError",
"(",
"'Not a bookmark file (header size too large)'",
")",
"if",
"size",
"!=",
"len",
"(",
"data",
")",
":",
"raise",
"ValueError",
"(",
"'Not a bookmark file (truncated)'",
")",
"tocoffset",
",",
"=",
"struct",
".",
"unpack",
"(",
"b'<I'",
",",
"data",
"[",
"hdrsize",
":",
"hdrsize",
"+",
"4",
"]",
")",
"tocs",
"=",
"[",
"]",
"while",
"tocoffset",
"!=",
"0",
":",
"tocbase",
"=",
"hdrsize",
"+",
"tocoffset",
"if",
"tocoffset",
">",
"size",
"-",
"hdrsize",
"or",
"size",
"-",
"tocbase",
"<",
"20",
":",
"raise",
"ValueError",
"(",
"'TOC offset out of range'",
")",
"tocsize",
",",
"tocmagic",
",",
"tocid",
",",
"nexttoc",
",",
"toccount",
"=",
"struct",
".",
"unpack",
"(",
"b'<IIIII'",
",",
"data",
"[",
"tocbase",
":",
"tocbase",
"+",
"20",
"]",
")",
"if",
"tocmagic",
"!=",
"0xfffffffe",
":",
"break",
"tocsize",
"+=",
"8",
"if",
"size",
"-",
"tocbase",
"<",
"tocsize",
":",
"raise",
"ValueError",
"(",
"'TOC truncated'",
")",
"if",
"tocsize",
"<",
"12",
"*",
"toccount",
":",
"raise",
"ValueError",
"(",
"'TOC entries overrun TOC size'",
")",
"toc",
"=",
"{",
"}",
"for",
"n",
"in",
"xrange",
"(",
"0",
",",
"toccount",
")",
":",
"ebase",
"=",
"tocbase",
"+",
"20",
"+",
"12",
"*",
"n",
"eid",
",",
"eoffset",
",",
"edummy",
"=",
"struct",
".",
"unpack",
"(",
"b'<III'",
",",
"data",
"[",
"ebase",
":",
"ebase",
"+",
"12",
"]",
")",
"if",
"eid",
"&",
"0x80000000",
":",
"eid",
"=",
"cls",
".",
"_get_item",
"(",
"data",
",",
"hdrsize",
",",
"eid",
"&",
"0x7fffffff",
")",
"toc",
"[",
"eid",
"]",
"=",
"cls",
".",
"_get_item",
"(",
"data",
",",
"hdrsize",
",",
"eoffset",
")",
"tocs",
".",
"append",
"(",
"(",
"tocid",
",",
"toc",
")",
")",
"tocoffset",
"=",
"nexttoc",
"return",
"cls",
"(",
"tocs",
")"
] | https://github.com/EmpireProject/Empire-GUI/blob/7cad6c48e7f6858c0f389c93d3dbd4f6198e9f26/node_modules/dmg-builder/vendor/mac_alias/bookmark.py#L314-L377 |
|
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/closured/lib/python2.7/lib2to3/pytree.py | python | Node.clone | (self) | return Node(self.type, [ch.clone() for ch in self.children],
fixers_applied=self.fixers_applied) | Return a cloned (deep) copy of self. | Return a cloned (deep) copy of self. | [
"Return",
"a",
"cloned",
"(",
"deep",
")",
"copy",
"of",
"self",
"."
] | def clone(self):
"""Return a cloned (deep) copy of self."""
return Node(self.type, [ch.clone() for ch in self.children],
fixers_applied=self.fixers_applied) | [
"def",
"clone",
"(",
"self",
")",
":",
"return",
"Node",
"(",
"self",
".",
"type",
",",
"[",
"ch",
".",
"clone",
"(",
")",
"for",
"ch",
"in",
"self",
".",
"children",
"]",
",",
"fixers_applied",
"=",
"self",
".",
"fixers_applied",
")"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/closured/lib/python2.7/lib2to3/pytree.py#L289-L292 |
|
arschles/go-in-5-minutes | c02918d1def999b2d59c060818e8adb735e24719 | episode24/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings._GetAndMunge | (self, field, path, default, prefix, append, map) | return _AppendOrReturn(append, result) | Retrieve a value from |field| at |path| or return |default|. If
|append| is specified, and the item is found, it will be appended to that
object instead of returned. If |map| is specified, results will be
remapped through |map| before being returned or appended. | Retrieve a value from |field| at |path| or return |default|. If
|append| is specified, and the item is found, it will be appended to that
object instead of returned. If |map| is specified, results will be
remapped through |map| before being returned or appended. | [
"Retrieve",
"a",
"value",
"from",
"|field|",
"at",
"|path|",
"or",
"return",
"|default|",
".",
"If",
"|append|",
"is",
"specified",
"and",
"the",
"item",
"is",
"found",
"it",
"will",
"be",
"appended",
"to",
"that",
"object",
"instead",
"of",
"returned",
".",
"If",
"|map|",
"is",
"specified",
"results",
"will",
"be",
"remapped",
"through",
"|map|",
"before",
"being",
"returned",
"or",
"appended",
"."
] | def _GetAndMunge(self, field, path, default, prefix, append, map):
"""Retrieve a value from |field| at |path| or return |default|. If
|append| is specified, and the item is found, it will be appended to that
object instead of returned. If |map| is specified, results will be
remapped through |map| before being returned or appended."""
result = _GenericRetrieve(field, default, path)
result = _DoRemapping(result, map)
result = _AddPrefix(result, prefix)
return _AppendOrReturn(append, result) | [
"def",
"_GetAndMunge",
"(",
"self",
",",
"field",
",",
"path",
",",
"default",
",",
"prefix",
",",
"append",
",",
"map",
")",
":",
"result",
"=",
"_GenericRetrieve",
"(",
"field",
",",
"default",
",",
"path",
")",
"result",
"=",
"_DoRemapping",
"(",
"result",
",",
"map",
")",
"result",
"=",
"_AddPrefix",
"(",
"result",
",",
"prefix",
")",
"return",
"_AppendOrReturn",
"(",
"append",
",",
"result",
")"
] | https://github.com/arschles/go-in-5-minutes/blob/c02918d1def999b2d59c060818e8adb735e24719/episode24/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py#L274-L282 |
|
chris-barry/darkweb-everywhere | be6ce01b26028c8bec99c9d0307f489a6abe31be | deprecated-extension/utils/single_rule_response.py | python | test_response_no_redirect | (to) | return ret | destination may not support HTTPS. | destination may not support HTTPS. | [
"destination",
"may",
"not",
"support",
"HTTPS",
"."
] | def test_response_no_redirect(to):
"""destination may not support HTTPS."""
ret = True
try:
response = request(to, allow_redirects=False)
if response.status_code in (300, 301, 302, 307, 308):
find_redirect(to)
ret = False
if response.status_code != 200:
ret = False
del response
except SSLError:
# sys.stdout.write("failure: %s certificate validity check failed.\n" % to)
certificate.append(to)
ret = False
except (ConnectionError, Timeout):
# sys.stdout.write("failure: %s can not be reached.\n" % to)
timeout.append('%s - timeout' % to)
ret = False
except Exception:
ret = False
return ret | [
"def",
"test_response_no_redirect",
"(",
"to",
")",
":",
"ret",
"=",
"True",
"try",
":",
"response",
"=",
"request",
"(",
"to",
",",
"allow_redirects",
"=",
"False",
")",
"if",
"response",
".",
"status_code",
"in",
"(",
"300",
",",
"301",
",",
"302",
",",
"307",
",",
"308",
")",
":",
"find_redirect",
"(",
"to",
")",
"ret",
"=",
"False",
"if",
"response",
".",
"status_code",
"!=",
"200",
":",
"ret",
"=",
"False",
"del",
"response",
"except",
"SSLError",
":",
"# sys.stdout.write(\"failure: %s certificate validity check failed.\\n\" % to)",
"certificate",
".",
"append",
"(",
"to",
")",
"ret",
"=",
"False",
"except",
"(",
"ConnectionError",
",",
"Timeout",
")",
":",
"# sys.stdout.write(\"failure: %s can not be reached.\\n\" % to)",
"timeout",
".",
"append",
"(",
"'%s - timeout'",
"%",
"to",
")",
"ret",
"=",
"False",
"except",
"Exception",
":",
"ret",
"=",
"False",
"return",
"ret"
] | https://github.com/chris-barry/darkweb-everywhere/blob/be6ce01b26028c8bec99c9d0307f489a6abe31be/deprecated-extension/utils/single_rule_response.py#L39-L60 |
|
finos/perspective | 910799a5c981ab501fd907f34a21b0ef5a9a914c | python/perspective/perspective/manager/manager.py | python | PerspectiveManager.unlock | (self) | Unblock messages that can mutate the state of
:obj:`~perspective.Table` objects under management. | Unblock messages that can mutate the state of
:obj:`~perspective.Table` objects under management. | [
"Unblock",
"messages",
"that",
"can",
"mutate",
"the",
"state",
"of",
":",
"obj",
":",
"~perspective",
".",
"Table",
"objects",
"under",
"management",
"."
] | def unlock(self):
"""Unblock messages that can mutate the state of
:obj:`~perspective.Table` objects under management."""
self._lock = False | [
"def",
"unlock",
"(",
"self",
")",
":",
"self",
".",
"_lock",
"=",
"False"
] | https://github.com/finos/perspective/blob/910799a5c981ab501fd907f34a21b0ef5a9a914c/python/perspective/perspective/manager/manager.py#L63-L66 |
||
wotermelon/toJump | 3dcec5cb5d91387d415b805d015ab8d2e6ffcf5f | lib/win/systrace/catapult/third_party/pyserial/serial/serialcli.py | python | IronSerial._reconfigurePort | (self) | Set communication parameters on opened port. | Set communication parameters on opened port. | [
"Set",
"communication",
"parameters",
"on",
"opened",
"port",
"."
] | def _reconfigurePort(self):
"""Set communication parameters on opened port."""
if not self._port_handle:
raise SerialException("Can only operate on a valid port handle")
#~ self._port_handle.ReceivedBytesThreshold = 1
if self._timeout is None:
self._port_handle.ReadTimeout = System.IO.Ports.SerialPort.InfiniteTimeout
else:
self._port_handle.ReadTimeout = int(self._timeout*1000)
# if self._timeout != 0 and self._interCharTimeout is not None:
# timeouts = (int(self._interCharTimeout * 1000),) + timeouts[1:]
if self._writeTimeout is None:
self._port_handle.WriteTimeout = System.IO.Ports.SerialPort.InfiniteTimeout
else:
self._port_handle.WriteTimeout = int(self._writeTimeout*1000)
# Setup the connection info.
try:
self._port_handle.BaudRate = self._baudrate
except IOError, e:
# catch errors from illegal baudrate settings
raise ValueError(str(e))
if self._bytesize == FIVEBITS:
self._port_handle.DataBits = 5
elif self._bytesize == SIXBITS:
self._port_handle.DataBits = 6
elif self._bytesize == SEVENBITS:
self._port_handle.DataBits = 7
elif self._bytesize == EIGHTBITS:
self._port_handle.DataBits = 8
else:
raise ValueError("Unsupported number of data bits: %r" % self._bytesize)
if self._parity == PARITY_NONE:
self._port_handle.Parity = getattr(System.IO.Ports.Parity, 'None') # reserved keyword in Py3k
elif self._parity == PARITY_EVEN:
self._port_handle.Parity = System.IO.Ports.Parity.Even
elif self._parity == PARITY_ODD:
self._port_handle.Parity = System.IO.Ports.Parity.Odd
elif self._parity == PARITY_MARK:
self._port_handle.Parity = System.IO.Ports.Parity.Mark
elif self._parity == PARITY_SPACE:
self._port_handle.Parity = System.IO.Ports.Parity.Space
else:
raise ValueError("Unsupported parity mode: %r" % self._parity)
if self._stopbits == STOPBITS_ONE:
self._port_handle.StopBits = System.IO.Ports.StopBits.One
elif self._stopbits == STOPBITS_ONE_POINT_FIVE:
self._port_handle.StopBits = System.IO.Ports.StopBits.OnePointFive
elif self._stopbits == STOPBITS_TWO:
self._port_handle.StopBits = System.IO.Ports.StopBits.Two
else:
raise ValueError("Unsupported number of stop bits: %r" % self._stopbits)
if self._rtscts and self._xonxoff:
self._port_handle.Handshake = System.IO.Ports.Handshake.RequestToSendXOnXOff
elif self._rtscts:
self._port_handle.Handshake = System.IO.Ports.Handshake.RequestToSend
elif self._xonxoff:
self._port_handle.Handshake = System.IO.Ports.Handshake.XOnXOff
else:
self._port_handle.Handshake = getattr(System.IO.Ports.Handshake, 'None') | [
"def",
"_reconfigurePort",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_port_handle",
":",
"raise",
"SerialException",
"(",
"\"Can only operate on a valid port handle\"",
")",
"#~ self._port_handle.ReceivedBytesThreshold = 1",
"if",
"self",
".",
"_timeout",
"is",
"None",
":",
"self",
".",
"_port_handle",
".",
"ReadTimeout",
"=",
"System",
".",
"IO",
".",
"Ports",
".",
"SerialPort",
".",
"InfiniteTimeout",
"else",
":",
"self",
".",
"_port_handle",
".",
"ReadTimeout",
"=",
"int",
"(",
"self",
".",
"_timeout",
"*",
"1000",
")",
"# if self._timeout != 0 and self._interCharTimeout is not None:",
"# timeouts = (int(self._interCharTimeout * 1000),) + timeouts[1:]",
"if",
"self",
".",
"_writeTimeout",
"is",
"None",
":",
"self",
".",
"_port_handle",
".",
"WriteTimeout",
"=",
"System",
".",
"IO",
".",
"Ports",
".",
"SerialPort",
".",
"InfiniteTimeout",
"else",
":",
"self",
".",
"_port_handle",
".",
"WriteTimeout",
"=",
"int",
"(",
"self",
".",
"_writeTimeout",
"*",
"1000",
")",
"# Setup the connection info.",
"try",
":",
"self",
".",
"_port_handle",
".",
"BaudRate",
"=",
"self",
".",
"_baudrate",
"except",
"IOError",
",",
"e",
":",
"# catch errors from illegal baudrate settings",
"raise",
"ValueError",
"(",
"str",
"(",
"e",
")",
")",
"if",
"self",
".",
"_bytesize",
"==",
"FIVEBITS",
":",
"self",
".",
"_port_handle",
".",
"DataBits",
"=",
"5",
"elif",
"self",
".",
"_bytesize",
"==",
"SIXBITS",
":",
"self",
".",
"_port_handle",
".",
"DataBits",
"=",
"6",
"elif",
"self",
".",
"_bytesize",
"==",
"SEVENBITS",
":",
"self",
".",
"_port_handle",
".",
"DataBits",
"=",
"7",
"elif",
"self",
".",
"_bytesize",
"==",
"EIGHTBITS",
":",
"self",
".",
"_port_handle",
".",
"DataBits",
"=",
"8",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unsupported number of data bits: %r\"",
"%",
"self",
".",
"_bytesize",
")",
"if",
"self",
".",
"_parity",
"==",
"PARITY_NONE",
":",
"self",
".",
"_port_handle",
".",
"Parity",
"=",
"getattr",
"(",
"System",
".",
"IO",
".",
"Ports",
".",
"Parity",
",",
"'None'",
")",
"# reserved keyword in Py3k",
"elif",
"self",
".",
"_parity",
"==",
"PARITY_EVEN",
":",
"self",
".",
"_port_handle",
".",
"Parity",
"=",
"System",
".",
"IO",
".",
"Ports",
".",
"Parity",
".",
"Even",
"elif",
"self",
".",
"_parity",
"==",
"PARITY_ODD",
":",
"self",
".",
"_port_handle",
".",
"Parity",
"=",
"System",
".",
"IO",
".",
"Ports",
".",
"Parity",
".",
"Odd",
"elif",
"self",
".",
"_parity",
"==",
"PARITY_MARK",
":",
"self",
".",
"_port_handle",
".",
"Parity",
"=",
"System",
".",
"IO",
".",
"Ports",
".",
"Parity",
".",
"Mark",
"elif",
"self",
".",
"_parity",
"==",
"PARITY_SPACE",
":",
"self",
".",
"_port_handle",
".",
"Parity",
"=",
"System",
".",
"IO",
".",
"Ports",
".",
"Parity",
".",
"Space",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unsupported parity mode: %r\"",
"%",
"self",
".",
"_parity",
")",
"if",
"self",
".",
"_stopbits",
"==",
"STOPBITS_ONE",
":",
"self",
".",
"_port_handle",
".",
"StopBits",
"=",
"System",
".",
"IO",
".",
"Ports",
".",
"StopBits",
".",
"One",
"elif",
"self",
".",
"_stopbits",
"==",
"STOPBITS_ONE_POINT_FIVE",
":",
"self",
".",
"_port_handle",
".",
"StopBits",
"=",
"System",
".",
"IO",
".",
"Ports",
".",
"StopBits",
".",
"OnePointFive",
"elif",
"self",
".",
"_stopbits",
"==",
"STOPBITS_TWO",
":",
"self",
".",
"_port_handle",
".",
"StopBits",
"=",
"System",
".",
"IO",
".",
"Ports",
".",
"StopBits",
".",
"Two",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unsupported number of stop bits: %r\"",
"%",
"self",
".",
"_stopbits",
")",
"if",
"self",
".",
"_rtscts",
"and",
"self",
".",
"_xonxoff",
":",
"self",
".",
"_port_handle",
".",
"Handshake",
"=",
"System",
".",
"IO",
".",
"Ports",
".",
"Handshake",
".",
"RequestToSendXOnXOff",
"elif",
"self",
".",
"_rtscts",
":",
"self",
".",
"_port_handle",
".",
"Handshake",
"=",
"System",
".",
"IO",
".",
"Ports",
".",
"Handshake",
".",
"RequestToSend",
"elif",
"self",
".",
"_xonxoff",
":",
"self",
".",
"_port_handle",
".",
"Handshake",
"=",
"System",
".",
"IO",
".",
"Ports",
".",
"Handshake",
".",
"XOnXOff",
"else",
":",
"self",
".",
"_port_handle",
".",
"Handshake",
"=",
"getattr",
"(",
"System",
".",
"IO",
".",
"Ports",
".",
"Handshake",
",",
"'None'",
")"
] | https://github.com/wotermelon/toJump/blob/3dcec5cb5d91387d415b805d015ab8d2e6ffcf5f/lib/win/systrace/catapult/third_party/pyserial/serial/serialcli.py#L54-L122 |
||
KhronosGroup/Vulkan-Docs | ee155139142a2a71b56238419bf0a6859f7b0a93 | scripts/spec_tools/base_printer.py | python | BasePrinter.formatContext | (self, context, _message_type=None) | return self.formatContextBrief(context) | Format a message context in a verbose way, if applicable.
May override, default implementation delegates to
self.formatContextBrief(). | Format a message context in a verbose way, if applicable. | [
"Format",
"a",
"message",
"context",
"in",
"a",
"verbose",
"way",
"if",
"applicable",
"."
] | def formatContext(self, context, _message_type=None):
"""Format a message context in a verbose way, if applicable.
May override, default implementation delegates to
self.formatContextBrief().
"""
return self.formatContextBrief(context) | [
"def",
"formatContext",
"(",
"self",
",",
"context",
",",
"_message_type",
"=",
"None",
")",
":",
"return",
"self",
".",
"formatContextBrief",
"(",
"context",
")"
] | https://github.com/KhronosGroup/Vulkan-Docs/blob/ee155139142a2a71b56238419bf0a6859f7b0a93/scripts/spec_tools/base_printer.py#L150-L156 |
|
nodejs/quic | 5baab3f3a05548d3b51bea98868412b08766e34d | tools/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings.HasExplicitAsmRules | (self, spec) | return self._HasExplicitRuleForExtension(spec, 'asm') | Determine if there's an explicit rule for asm files. When there isn't we
need to generate implicit rules to assemble .asm files. | Determine if there's an explicit rule for asm files. When there isn't we
need to generate implicit rules to assemble .asm files. | [
"Determine",
"if",
"there",
"s",
"an",
"explicit",
"rule",
"for",
"asm",
"files",
".",
"When",
"there",
"isn",
"t",
"we",
"need",
"to",
"generate",
"implicit",
"rules",
"to",
"assemble",
".",
"asm",
"files",
"."
] | def HasExplicitAsmRules(self, spec):
"""Determine if there's an explicit rule for asm files. When there isn't we
need to generate implicit rules to assemble .asm files."""
return self._HasExplicitRuleForExtension(spec, 'asm') | [
"def",
"HasExplicitAsmRules",
"(",
"self",
",",
"spec",
")",
":",
"return",
"self",
".",
"_HasExplicitRuleForExtension",
"(",
"spec",
",",
"'asm'",
")"
] | https://github.com/nodejs/quic/blob/5baab3f3a05548d3b51bea98868412b08766e34d/tools/gyp/pylib/gyp/msvs_emulation.py#L858-L861 |
|
minorua/Qgis2threejs | fc9586adb4a25ad2b80a37ae718044d5306a483c | mapextent.py | python | MapExtent.square | (self) | return self | square the extent | square the extent | [
"square",
"the",
"extent"
] | def square(self):
"""square the extent"""
self._width = self._height = max(self._width, self._height)
self._updateDerived()
return self | [
"def",
"square",
"(",
"self",
")",
":",
"self",
".",
"_width",
"=",
"self",
".",
"_height",
"=",
"max",
"(",
"self",
".",
"_width",
",",
"self",
".",
"_height",
")",
"self",
".",
"_updateDerived",
"(",
")",
"return",
"self"
] | https://github.com/minorua/Qgis2threejs/blob/fc9586adb4a25ad2b80a37ae718044d5306a483c/mapextent.py#L140-L144 |
|
chibicitiberiu/ytsm | 89499c75addc198be44be5ab9462ab58f3b983eb | app/external/pytaw/pytaw/youtube.py | python | ListResponse._fetch_next | (self) | Fetch the next page of the API response and load into memory. | Fetch the next page of the API response and load into memory. | [
"Fetch",
"the",
"next",
"page",
"of",
"the",
"API",
"response",
"and",
"load",
"into",
"memory",
"."
] | def _fetch_next(self):
"""Fetch the next page of the API response and load into memory."""
if self._no_more_pages:
# we should only get here if results stop at a page boundary
log.debug(f"exhausted all results at item {self._item_count} at page boundary "
f"(item {self._list_index + 1} on page {self._page_count})")
raise StopIteration()
# pass the next page token if this is not the first page we're fetching
params = dict()
if self._next_page_token:
params['pageToken'] = self._next_page_token
# execute query to get raw response dictionary
raw = self.query.execute(api_params=params)
# the following data shouldn't change, so store only if it's not been set yet
# (i.e. this is the first fetch)
if None in (self.kind, self.total_results, self.results_per_page):
# don't use get() because if this data doesn't exist in the api response something
# has gone wrong and we'd like an exception
self.kind = raw['kind'].replace('youtube#', '')
self.total_results = int(raw['pageInfo']['totalResults'])
self.results_per_page = int(raw['pageInfo']['resultsPerPage'])
# whereever we are in the list response we need the next page token. if it's not there,
# set a flag so that we know there's no more to be fetched (note _next_page_token is also
# None at initialisation so we can't check it that way).
self._next_page_token = raw.get('nextPageToken', None)
if self._next_page_token is None:
self._no_more_pages = True
# store items in raw format for processing by __next__()
self._listing = raw['items'] # would like a KeyError if this fails (it shouldn't)
self._list_index = 0
self._page_count += 1 | [
"def",
"_fetch_next",
"(",
"self",
")",
":",
"if",
"self",
".",
"_no_more_pages",
":",
"# we should only get here if results stop at a page boundary",
"log",
".",
"debug",
"(",
"f\"exhausted all results at item {self._item_count} at page boundary \"",
"f\"(item {self._list_index + 1} on page {self._page_count})\"",
")",
"raise",
"StopIteration",
"(",
")",
"# pass the next page token if this is not the first page we're fetching",
"params",
"=",
"dict",
"(",
")",
"if",
"self",
".",
"_next_page_token",
":",
"params",
"[",
"'pageToken'",
"]",
"=",
"self",
".",
"_next_page_token",
"# execute query to get raw response dictionary",
"raw",
"=",
"self",
".",
"query",
".",
"execute",
"(",
"api_params",
"=",
"params",
")",
"# the following data shouldn't change, so store only if it's not been set yet",
"# (i.e. this is the first fetch)",
"if",
"None",
"in",
"(",
"self",
".",
"kind",
",",
"self",
".",
"total_results",
",",
"self",
".",
"results_per_page",
")",
":",
"# don't use get() because if this data doesn't exist in the api response something",
"# has gone wrong and we'd like an exception",
"self",
".",
"kind",
"=",
"raw",
"[",
"'kind'",
"]",
".",
"replace",
"(",
"'youtube#'",
",",
"''",
")",
"self",
".",
"total_results",
"=",
"int",
"(",
"raw",
"[",
"'pageInfo'",
"]",
"[",
"'totalResults'",
"]",
")",
"self",
".",
"results_per_page",
"=",
"int",
"(",
"raw",
"[",
"'pageInfo'",
"]",
"[",
"'resultsPerPage'",
"]",
")",
"# whereever we are in the list response we need the next page token. if it's not there,",
"# set a flag so that we know there's no more to be fetched (note _next_page_token is also",
"# None at initialisation so we can't check it that way).",
"self",
".",
"_next_page_token",
"=",
"raw",
".",
"get",
"(",
"'nextPageToken'",
",",
"None",
")",
"if",
"self",
".",
"_next_page_token",
"is",
"None",
":",
"self",
".",
"_no_more_pages",
"=",
"True",
"# store items in raw format for processing by __next__()",
"self",
".",
"_listing",
"=",
"raw",
"[",
"'items'",
"]",
"# would like a KeyError if this fails (it shouldn't)",
"self",
".",
"_list_index",
"=",
"0",
"self",
".",
"_page_count",
"+=",
"1"
] | https://github.com/chibicitiberiu/ytsm/blob/89499c75addc198be44be5ab9462ab58f3b983eb/app/external/pytaw/pytaw/youtube.py#L584-L619 |
||
AllAboutCode/EduBlocks | 901675d2a0efa2ed10a71bca33c2e3325a8f1a34 | ui/closure-library/closure/bin/build/depstree.py | python | DepsTree._ResolveDependencies | (required_namespace, deps_list, provides_map,
traversal_path) | return deps_list | Resolve dependencies for Closure source files.
Follows the dependency tree down and builds a list of sources in dependency
order. This function will recursively call itself to fill all dependencies
below the requested namespaces, and then append its sources at the end of
the list.
Args:
required_namespace: String of required namespace.
deps_list: List of sources in dependency order. This function will append
the required source once all of its dependencies are satisfied.
provides_map: Map from namespace to source that provides it.
traversal_path: List of namespaces of our path from the root down the
dependency/recursion tree. Used to identify cyclical dependencies.
This is a list used as a stack -- when the function is entered, the
current namespace is pushed and popped right before returning.
Each recursive call will check that the current namespace does not
appear in the list, throwing a CircularDependencyError if it does.
Returns:
The given deps_list object filled with sources in dependency order.
Raises:
NamespaceNotFoundError: A namespace is requested but doesn't exist.
CircularDependencyError: A cycle is detected in the dependency tree. | Resolve dependencies for Closure source files. | [
"Resolve",
"dependencies",
"for",
"Closure",
"source",
"files",
"."
] | def _ResolveDependencies(required_namespace, deps_list, provides_map,
traversal_path):
"""Resolve dependencies for Closure source files.
Follows the dependency tree down and builds a list of sources in dependency
order. This function will recursively call itself to fill all dependencies
below the requested namespaces, and then append its sources at the end of
the list.
Args:
required_namespace: String of required namespace.
deps_list: List of sources in dependency order. This function will append
the required source once all of its dependencies are satisfied.
provides_map: Map from namespace to source that provides it.
traversal_path: List of namespaces of our path from the root down the
dependency/recursion tree. Used to identify cyclical dependencies.
This is a list used as a stack -- when the function is entered, the
current namespace is pushed and popped right before returning.
Each recursive call will check that the current namespace does not
appear in the list, throwing a CircularDependencyError if it does.
Returns:
The given deps_list object filled with sources in dependency order.
Raises:
NamespaceNotFoundError: A namespace is requested but doesn't exist.
CircularDependencyError: A cycle is detected in the dependency tree.
"""
source = provides_map.get(required_namespace)
if not source:
raise NamespaceNotFoundError(required_namespace)
if required_namespace in traversal_path:
traversal_path.append(required_namespace) # do this *after* the test
# This must be a cycle.
raise CircularDependencyError(traversal_path)
# If we don't have the source yet, we'll have to visit this namespace and
# add the required dependencies to deps_list.
if source not in deps_list:
traversal_path.append(required_namespace)
for require in source.requires:
# Append all other dependencies before we append our own.
DepsTree._ResolveDependencies(require, deps_list, provides_map,
traversal_path)
deps_list.append(source)
traversal_path.pop()
return deps_list | [
"def",
"_ResolveDependencies",
"(",
"required_namespace",
",",
"deps_list",
",",
"provides_map",
",",
"traversal_path",
")",
":",
"source",
"=",
"provides_map",
".",
"get",
"(",
"required_namespace",
")",
"if",
"not",
"source",
":",
"raise",
"NamespaceNotFoundError",
"(",
"required_namespace",
")",
"if",
"required_namespace",
"in",
"traversal_path",
":",
"traversal_path",
".",
"append",
"(",
"required_namespace",
")",
"# do this *after* the test",
"# This must be a cycle.",
"raise",
"CircularDependencyError",
"(",
"traversal_path",
")",
"# If we don't have the source yet, we'll have to visit this namespace and",
"# add the required dependencies to deps_list.",
"if",
"source",
"not",
"in",
"deps_list",
":",
"traversal_path",
".",
"append",
"(",
"required_namespace",
")",
"for",
"require",
"in",
"source",
".",
"requires",
":",
"# Append all other dependencies before we append our own.",
"DepsTree",
".",
"_ResolveDependencies",
"(",
"require",
",",
"deps_list",
",",
"provides_map",
",",
"traversal_path",
")",
"deps_list",
".",
"append",
"(",
"source",
")",
"traversal_path",
".",
"pop",
"(",
")",
"return",
"deps_list"
] | https://github.com/AllAboutCode/EduBlocks/blob/901675d2a0efa2ed10a71bca33c2e3325a8f1a34/ui/closure-library/closure/bin/build/depstree.py#L87-L140 |
|
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/closured/lib/python2.7/email/feedparser.py | python | FeedParser.close | (self) | return root | Parse all remaining data and return the root message object. | Parse all remaining data and return the root message object. | [
"Parse",
"all",
"remaining",
"data",
"and",
"return",
"the",
"root",
"message",
"object",
"."
] | def close(self):
"""Parse all remaining data and return the root message object."""
self._input.close()
self._call_parse()
root = self._pop_message()
assert not self._msgstack
# Look for final set of defects
if root.get_content_maintype() == 'multipart' \
and not root.is_multipart():
root.defects.append(errors.MultipartInvariantViolationDefect())
return root | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"_input",
".",
"close",
"(",
")",
"self",
".",
"_call_parse",
"(",
")",
"root",
"=",
"self",
".",
"_pop_message",
"(",
")",
"assert",
"not",
"self",
".",
"_msgstack",
"# Look for final set of defects",
"if",
"root",
".",
"get_content_maintype",
"(",
")",
"==",
"'multipart'",
"and",
"not",
"root",
".",
"is_multipart",
"(",
")",
":",
"root",
".",
"defects",
".",
"append",
"(",
"errors",
".",
"MultipartInvariantViolationDefect",
"(",
")",
")",
"return",
"root"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/closured/lib/python2.7/email/feedparser.py#L165-L175 |
|
yetone/collipa | 20a23a412585a2f66e2cdc7a2959bd7d3d933e6c | collipa/libs/tornadomail/message.py | python | forbid_multi_line_headers | (name, val, encoding) | return name, val | Forbids multi-line headers, to prevent header injection. | Forbids multi-line headers, to prevent header injection. | [
"Forbids",
"multi",
"-",
"line",
"headers",
"to",
"prevent",
"header",
"injection",
"."
] | def forbid_multi_line_headers(name, val, encoding):
"""Forbids multi-line headers, to prevent header injection."""
encoding = encoding or DEFAULT_CHARSET
val = force_unicode(val)
if '\n' in val or '\r' in val:
raise BadHeaderError("Header values can't contain newlines (got %r for header %r)" % (val, name))
try:
val = val.encode('ascii')
except UnicodeEncodeError:
if name.lower() in ADDRESS_HEADERS:
val = ', '.join(sanitize_address(addr, encoding)
for addr in getaddresses((val,)))
else:
val = str(Header(val, encoding))
else:
if name.lower() == 'subject':
val = Header(val)
return name, val | [
"def",
"forbid_multi_line_headers",
"(",
"name",
",",
"val",
",",
"encoding",
")",
":",
"encoding",
"=",
"encoding",
"or",
"DEFAULT_CHARSET",
"val",
"=",
"force_unicode",
"(",
"val",
")",
"if",
"'\\n'",
"in",
"val",
"or",
"'\\r'",
"in",
"val",
":",
"raise",
"BadHeaderError",
"(",
"\"Header values can't contain newlines (got %r for header %r)\"",
"%",
"(",
"val",
",",
"name",
")",
")",
"try",
":",
"val",
"=",
"val",
".",
"encode",
"(",
"'ascii'",
")",
"except",
"UnicodeEncodeError",
":",
"if",
"name",
".",
"lower",
"(",
")",
"in",
"ADDRESS_HEADERS",
":",
"val",
"=",
"', '",
".",
"join",
"(",
"sanitize_address",
"(",
"addr",
",",
"encoding",
")",
"for",
"addr",
"in",
"getaddresses",
"(",
"(",
"val",
",",
")",
")",
")",
"else",
":",
"val",
"=",
"str",
"(",
"Header",
"(",
"val",
",",
"encoding",
")",
")",
"else",
":",
"if",
"name",
".",
"lower",
"(",
")",
"==",
"'subject'",
":",
"val",
"=",
"Header",
"(",
"val",
")",
"return",
"name",
",",
"val"
] | https://github.com/yetone/collipa/blob/20a23a412585a2f66e2cdc7a2959bd7d3d933e6c/collipa/libs/tornadomail/message.py#L85-L102 |
|
mceSystems/node-jsc | 90634f3064fab8e89a85b3942f0cc5054acc86fa | tools/gyp/pylib/gyp/generator/analyzer.py | python | Config.Init | (self, params) | Initializes Config. This is a separate method as it raises an exception
if there is a parse error. | Initializes Config. This is a separate method as it raises an exception
if there is a parse error. | [
"Initializes",
"Config",
".",
"This",
"is",
"a",
"separate",
"method",
"as",
"it",
"raises",
"an",
"exception",
"if",
"there",
"is",
"a",
"parse",
"error",
"."
] | def Init(self, params):
"""Initializes Config. This is a separate method as it raises an exception
if there is a parse error."""
generator_flags = params.get('generator_flags', {})
config_path = generator_flags.get('config_path', None)
if not config_path:
return
try:
f = open(config_path, 'r')
config = json.load(f)
f.close()
except IOError:
raise Exception('Unable to open file ' + config_path)
except ValueError as e:
raise Exception('Unable to parse config file ' + config_path + str(e))
if not isinstance(config, dict):
raise Exception('config_path must be a JSON file containing a dictionary')
self.files = config.get('files', [])
self.additional_compile_target_names = set(
config.get('additional_compile_targets', []))
self.test_target_names = set(config.get('test_targets', [])) | [
"def",
"Init",
"(",
"self",
",",
"params",
")",
":",
"generator_flags",
"=",
"params",
".",
"get",
"(",
"'generator_flags'",
",",
"{",
"}",
")",
"config_path",
"=",
"generator_flags",
".",
"get",
"(",
"'config_path'",
",",
"None",
")",
"if",
"not",
"config_path",
":",
"return",
"try",
":",
"f",
"=",
"open",
"(",
"config_path",
",",
"'r'",
")",
"config",
"=",
"json",
".",
"load",
"(",
"f",
")",
"f",
".",
"close",
"(",
")",
"except",
"IOError",
":",
"raise",
"Exception",
"(",
"'Unable to open file '",
"+",
"config_path",
")",
"except",
"ValueError",
"as",
"e",
":",
"raise",
"Exception",
"(",
"'Unable to parse config file '",
"+",
"config_path",
"+",
"str",
"(",
"e",
")",
")",
"if",
"not",
"isinstance",
"(",
"config",
",",
"dict",
")",
":",
"raise",
"Exception",
"(",
"'config_path must be a JSON file containing a dictionary'",
")",
"self",
".",
"files",
"=",
"config",
".",
"get",
"(",
"'files'",
",",
"[",
"]",
")",
"self",
".",
"additional_compile_target_names",
"=",
"set",
"(",
"config",
".",
"get",
"(",
"'additional_compile_targets'",
",",
"[",
"]",
")",
")",
"self",
".",
"test_target_names",
"=",
"set",
"(",
"config",
".",
"get",
"(",
"'test_targets'",
",",
"[",
"]",
")",
")"
] | https://github.com/mceSystems/node-jsc/blob/90634f3064fab8e89a85b3942f0cc5054acc86fa/tools/gyp/pylib/gyp/generator/analyzer.py#L252-L272 |
||
korolr/dotfiles | 8e46933503ecb8d8651739ffeb1d2d4f0f5c6524 | .config/sublime-text-3/Backup/20181226200442/mdpopups/st3/mdpopups/rgba.py | python | RGBA.colorize | (self, deg) | Colorize the color with the given hue. | Colorize the color with the given hue. | [
"Colorize",
"the",
"color",
"with",
"the",
"given",
"hue",
"."
] | def colorize(self, deg):
"""Colorize the color with the given hue."""
h, l, s = self.tohls()
h = clamp(deg * HUE_SCALE, 0.0, 1.0)
self.fromhls(h, l, s) | [
"def",
"colorize",
"(",
"self",
",",
"deg",
")",
":",
"h",
",",
"l",
",",
"s",
"=",
"self",
".",
"tohls",
"(",
")",
"h",
"=",
"clamp",
"(",
"deg",
"*",
"HUE_SCALE",
",",
"0.0",
",",
"1.0",
")",
"self",
".",
"fromhls",
"(",
"h",
",",
"l",
",",
"s",
")"
] | https://github.com/korolr/dotfiles/blob/8e46933503ecb8d8651739ffeb1d2d4f0f5c6524/.config/sublime-text-3/Backup/20181226200442/mdpopups/st3/mdpopups/rgba.py#L183-L188 |
||
odoo/odoo | 8de8c196a137f4ebbf67d7c7c83fee36f873f5c8 | odoo/addons/base/models/ir_actions.py | python | IrActions._for_xml_id | (self, full_xml_id) | return {
field: value
for field, value in action.items()
if field in record._get_readable_fields()
} | Returns the action content for the provided xml_id
:param xml_id: the namespace-less id of the action (the @id
attribute from the XML file)
:return: A read() view of the ir.actions.action safe for web use | Returns the action content for the provided xml_id | [
"Returns",
"the",
"action",
"content",
"for",
"the",
"provided",
"xml_id"
] | def _for_xml_id(self, full_xml_id):
""" Returns the action content for the provided xml_id
:param xml_id: the namespace-less id of the action (the @id
attribute from the XML file)
:return: A read() view of the ir.actions.action safe for web use
"""
record = self.env.ref(full_xml_id)
assert isinstance(self.env[record._name], type(self))
action = record.sudo().read()[0]
return {
field: value
for field, value in action.items()
if field in record._get_readable_fields()
} | [
"def",
"_for_xml_id",
"(",
"self",
",",
"full_xml_id",
")",
":",
"record",
"=",
"self",
".",
"env",
".",
"ref",
"(",
"full_xml_id",
")",
"assert",
"isinstance",
"(",
"self",
".",
"env",
"[",
"record",
".",
"_name",
"]",
",",
"type",
"(",
"self",
")",
")",
"action",
"=",
"record",
".",
"sudo",
"(",
")",
".",
"read",
"(",
")",
"[",
"0",
"]",
"return",
"{",
"field",
":",
"value",
"for",
"field",
",",
"value",
"in",
"action",
".",
"items",
"(",
")",
"if",
"field",
"in",
"record",
".",
"_get_readable_fields",
"(",
")",
"}"
] | https://github.com/odoo/odoo/blob/8de8c196a137f4ebbf67d7c7c83fee36f873f5c8/odoo/addons/base/models/ir_actions.py#L138-L152 |
|
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/reloop-closured/lib/python2.7/cgi.py | python | parse_header | (line) | return key, pdict | Parse a Content-type like header.
Return the main content-type and a dictionary of options. | Parse a Content-type like header. | [
"Parse",
"a",
"Content",
"-",
"type",
"like",
"header",
"."
] | def parse_header(line):
"""Parse a Content-type like header.
Return the main content-type and a dictionary of options.
"""
parts = _parseparam(';' + line)
key = parts.next()
pdict = {}
for p in parts:
i = p.find('=')
if i >= 0:
name = p[:i].strip().lower()
value = p[i+1:].strip()
if len(value) >= 2 and value[0] == value[-1] == '"':
value = value[1:-1]
value = value.replace('\\\\', '\\').replace('\\"', '"')
pdict[name] = value
return key, pdict | [
"def",
"parse_header",
"(",
"line",
")",
":",
"parts",
"=",
"_parseparam",
"(",
"';'",
"+",
"line",
")",
"key",
"=",
"parts",
".",
"next",
"(",
")",
"pdict",
"=",
"{",
"}",
"for",
"p",
"in",
"parts",
":",
"i",
"=",
"p",
".",
"find",
"(",
"'='",
")",
"if",
"i",
">=",
"0",
":",
"name",
"=",
"p",
"[",
":",
"i",
"]",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"value",
"=",
"p",
"[",
"i",
"+",
"1",
":",
"]",
".",
"strip",
"(",
")",
"if",
"len",
"(",
"value",
")",
">=",
"2",
"and",
"value",
"[",
"0",
"]",
"==",
"value",
"[",
"-",
"1",
"]",
"==",
"'\"'",
":",
"value",
"=",
"value",
"[",
"1",
":",
"-",
"1",
"]",
"value",
"=",
"value",
".",
"replace",
"(",
"'\\\\\\\\'",
",",
"'\\\\'",
")",
".",
"replace",
"(",
"'\\\\\"'",
",",
"'\"'",
")",
"pdict",
"[",
"name",
"]",
"=",
"value",
"return",
"key",
",",
"pdict"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/reloop-closured/lib/python2.7/cgi.py#L304-L322 |
|
HumanCompatibleAI/overcooked_ai | 7e774a1aa29c28b7b69dc0a8903822ac2c6b4f23 | src/overcooked_ai_py/mdp/overcooked_mdp.py | python | OvercookedGridworld.is_dish_drop_useful | (self, state, pot_states, player_index) | return all_non_full and not other_player_holding_onion | NOTE: this only works if self.num_players == 2
Useful if:
- Onion is needed (all pots are non-full)
- Nobody is holding onions | NOTE: this only works if self.num_players == 2
Useful if:
- Onion is needed (all pots are non-full)
- Nobody is holding onions | [
"NOTE",
":",
"this",
"only",
"works",
"if",
"self",
".",
"num_players",
"==",
"2",
"Useful",
"if",
":",
"-",
"Onion",
"is",
"needed",
"(",
"all",
"pots",
"are",
"non",
"-",
"full",
")",
"-",
"Nobody",
"is",
"holding",
"onions"
] | def is_dish_drop_useful(self, state, pot_states, player_index):
"""
NOTE: this only works if self.num_players == 2
Useful if:
- Onion is needed (all pots are non-full)
- Nobody is holding onions
"""
if self.num_players != 2: return False
all_non_full = len(self.get_full_pots(pot_states)) == 0
other_player = state.players[1 - player_index]
other_player_holding_onion = other_player.has_object() and other_player.get_object().name == "onion"
return all_non_full and not other_player_holding_onion | [
"def",
"is_dish_drop_useful",
"(",
"self",
",",
"state",
",",
"pot_states",
",",
"player_index",
")",
":",
"if",
"self",
".",
"num_players",
"!=",
"2",
":",
"return",
"False",
"all_non_full",
"=",
"len",
"(",
"self",
".",
"get_full_pots",
"(",
"pot_states",
")",
")",
"==",
"0",
"other_player",
"=",
"state",
".",
"players",
"[",
"1",
"-",
"player_index",
"]",
"other_player_holding_onion",
"=",
"other_player",
".",
"has_object",
"(",
")",
"and",
"other_player",
".",
"get_object",
"(",
")",
".",
"name",
"==",
"\"onion\"",
"return",
"all_non_full",
"and",
"not",
"other_player_holding_onion"
] | https://github.com/HumanCompatibleAI/overcooked_ai/blob/7e774a1aa29c28b7b69dc0a8903822ac2c6b4f23/src/overcooked_ai_py/mdp/overcooked_mdp.py#L1698-L1709 |
|
korolr/dotfiles | 8e46933503ecb8d8651739ffeb1d2d4f0f5c6524 | .config/sublime-text-3/Backup/20181226200442/mdpopups/st3/mdpopups/rgba.py | python | round_int | (dec) | return int(decimal.Decimal(dec).quantize(decimal.Decimal('0'), decimal.ROUND_HALF_UP)) | Round float to nearest int using expected rounding. | Round float to nearest int using expected rounding. | [
"Round",
"float",
"to",
"nearest",
"int",
"using",
"expected",
"rounding",
"."
] | def round_int(dec):
"""Round float to nearest int using expected rounding."""
return int(decimal.Decimal(dec).quantize(decimal.Decimal('0'), decimal.ROUND_HALF_UP)) | [
"def",
"round_int",
"(",
"dec",
")",
":",
"return",
"int",
"(",
"decimal",
".",
"Decimal",
"(",
"dec",
")",
".",
"quantize",
"(",
"decimal",
".",
"Decimal",
"(",
"'0'",
")",
",",
"decimal",
".",
"ROUND_HALF_UP",
")",
")"
] | https://github.com/korolr/dotfiles/blob/8e46933503ecb8d8651739ffeb1d2d4f0f5c6524/.config/sublime-text-3/Backup/20181226200442/mdpopups/st3/mdpopups/rgba.py#L21-L24 |
|
xtk/X | 04c1aa856664a8517d23aefd94c470d47130aead | lib/selenium/selenium/webdriver/opera/webdriver.py | python | WebDriver.__init__ | (self, executable_path=None, port=0,
desired_capabilities=DesiredCapabilities.OPERA) | Creates a new instance of the Opera driver.
Starts the service and then creates new instance of Opera Driver.
:Args:
- executable_path - path to the executable. If the default is used it assumes the executable is in the
Environment Variable SELENIUM_SERVER_JAR
- port - port you would like the service to run, if left as 0, a free port will be found.
- desired_capabilities: Dictionary object with desired capabilities (Can be used to provide various Opera switches). | Creates a new instance of the Opera driver. | [
"Creates",
"a",
"new",
"instance",
"of",
"the",
"Opera",
"driver",
"."
] | def __init__(self, executable_path=None, port=0,
desired_capabilities=DesiredCapabilities.OPERA):
"""
Creates a new instance of the Opera driver.
Starts the service and then creates new instance of Opera Driver.
:Args:
- executable_path - path to the executable. If the default is used it assumes the executable is in the
Environment Variable SELENIUM_SERVER_JAR
- port - port you would like the service to run, if left as 0, a free port will be found.
- desired_capabilities: Dictionary object with desired capabilities (Can be used to provide various Opera switches).
"""
if executable_path is None:
try:
executable_path = os.environ["SELENIUM_SERVER_JAR"]
except:
raise Exception("No executable path given, please add one to Environment Variable \
'SELENIUM_SERVER_JAR'")
self.service = Service(executable_path, port=port)
self.service.start()
RemoteWebDriver.__init__(self,
command_executor=self.service.service_url,
desired_capabilities=desired_capabilities)
self._is_remote = False | [
"def",
"__init__",
"(",
"self",
",",
"executable_path",
"=",
"None",
",",
"port",
"=",
"0",
",",
"desired_capabilities",
"=",
"DesiredCapabilities",
".",
"OPERA",
")",
":",
"if",
"executable_path",
"is",
"None",
":",
"try",
":",
"executable_path",
"=",
"os",
".",
"environ",
"[",
"\"SELENIUM_SERVER_JAR\"",
"]",
"except",
":",
"raise",
"Exception",
"(",
"\"No executable path given, please add one to Environment Variable \\\n 'SELENIUM_SERVER_JAR'\"",
")",
"self",
".",
"service",
"=",
"Service",
"(",
"executable_path",
",",
"port",
"=",
"port",
")",
"self",
".",
"service",
".",
"start",
"(",
")",
"RemoteWebDriver",
".",
"__init__",
"(",
"self",
",",
"command_executor",
"=",
"self",
".",
"service",
".",
"service_url",
",",
"desired_capabilities",
"=",
"desired_capabilities",
")",
"self",
".",
"_is_remote",
"=",
"False"
] | https://github.com/xtk/X/blob/04c1aa856664a8517d23aefd94c470d47130aead/lib/selenium/selenium/webdriver/opera/webdriver.py#L31-L56 |
||
concentricsky/django-tastypie-swagger | 9ca55c0a01df207551c935230244c00e2294151c | tastypie_swagger/mapping.py | python | ResourceSwaggerMapping.get_operation_summary | (self, detail=True, method='get') | return '' | Get a basic summary string for a single operation | Get a basic summary string for a single operation | [
"Get",
"a",
"basic",
"summary",
"string",
"for",
"a",
"single",
"operation"
] | def get_operation_summary(self, detail=True, method='get'):
"""
Get a basic summary string for a single operation
"""
key = '%s-%s' % (method.lower(), detail and 'detail' or 'list')
plural = not detail and method is 'get'
verbose_name = self.get_resource_verbose_name(plural=plural)
summary = self.OPERATION_SUMMARIES.get(key, '')
if summary:
return summary % verbose_name
return '' | [
"def",
"get_operation_summary",
"(",
"self",
",",
"detail",
"=",
"True",
",",
"method",
"=",
"'get'",
")",
":",
"key",
"=",
"'%s-%s'",
"%",
"(",
"method",
".",
"lower",
"(",
")",
",",
"detail",
"and",
"'detail'",
"or",
"'list'",
")",
"plural",
"=",
"not",
"detail",
"and",
"method",
"is",
"'get'",
"verbose_name",
"=",
"self",
".",
"get_resource_verbose_name",
"(",
"plural",
"=",
"plural",
")",
"summary",
"=",
"self",
".",
"OPERATION_SUMMARIES",
".",
"get",
"(",
"key",
",",
"''",
")",
"if",
"summary",
":",
"return",
"summary",
"%",
"verbose_name",
"return",
"''"
] | https://github.com/concentricsky/django-tastypie-swagger/blob/9ca55c0a01df207551c935230244c00e2294151c/tastypie_swagger/mapping.py#L91-L101 |
|
mozilla/spidernode | aafa9e5273f954f272bb4382fc007af14674b4c2 | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py | python | MacTool.ExecCompileXcassets | (self, keys, *inputs) | Compiles multiple .xcassets files into a single .car file.
This invokes 'actool' to compile all the inputs .xcassets files. The
|keys| arguments is a json-encoded dictionary of extra arguments to
pass to 'actool' when the asset catalogs contains an application icon
or a launch image.
Note that 'actool' does not create the Assets.car file if the asset
catalogs does not contains imageset. | Compiles multiple .xcassets files into a single .car file. | [
"Compiles",
"multiple",
".",
"xcassets",
"files",
"into",
"a",
"single",
".",
"car",
"file",
"."
] | def ExecCompileXcassets(self, keys, *inputs):
"""Compiles multiple .xcassets files into a single .car file.
This invokes 'actool' to compile all the inputs .xcassets files. The
|keys| arguments is a json-encoded dictionary of extra arguments to
pass to 'actool' when the asset catalogs contains an application icon
or a launch image.
Note that 'actool' does not create the Assets.car file if the asset
catalogs does not contains imageset.
"""
command_line = [
'xcrun', 'actool', '--output-format', 'human-readable-text',
'--compress-pngs', '--notices', '--warnings', '--errors',
]
is_iphone_target = 'IPHONEOS_DEPLOYMENT_TARGET' in os.environ
if is_iphone_target:
platform = os.environ['CONFIGURATION'].split('-')[-1]
if platform not in ('iphoneos', 'iphonesimulator'):
platform = 'iphonesimulator'
command_line.extend([
'--platform', platform, '--target-device', 'iphone',
'--target-device', 'ipad', '--minimum-deployment-target',
os.environ['IPHONEOS_DEPLOYMENT_TARGET'], '--compile',
os.path.abspath(os.environ['CONTENTS_FOLDER_PATH']),
])
else:
command_line.extend([
'--platform', 'macosx', '--target-device', 'mac',
'--minimum-deployment-target', os.environ['MACOSX_DEPLOYMENT_TARGET'],
'--compile',
os.path.abspath(os.environ['UNLOCALIZED_RESOURCES_FOLDER_PATH']),
])
if keys:
keys = json.loads(keys)
for key, value in keys.iteritems():
arg_name = '--' + key
if isinstance(value, bool):
if value:
command_line.append(arg_name)
elif isinstance(value, list):
for v in value:
command_line.append(arg_name)
command_line.append(str(v))
else:
command_line.append(arg_name)
command_line.append(str(value))
# Note: actool crashes if inputs path are relative, so use os.path.abspath
# to get absolute path name for inputs.
command_line.extend(map(os.path.abspath, inputs))
subprocess.check_call(command_line) | [
"def",
"ExecCompileXcassets",
"(",
"self",
",",
"keys",
",",
"*",
"inputs",
")",
":",
"command_line",
"=",
"[",
"'xcrun'",
",",
"'actool'",
",",
"'--output-format'",
",",
"'human-readable-text'",
",",
"'--compress-pngs'",
",",
"'--notices'",
",",
"'--warnings'",
",",
"'--errors'",
",",
"]",
"is_iphone_target",
"=",
"'IPHONEOS_DEPLOYMENT_TARGET'",
"in",
"os",
".",
"environ",
"if",
"is_iphone_target",
":",
"platform",
"=",
"os",
".",
"environ",
"[",
"'CONFIGURATION'",
"]",
".",
"split",
"(",
"'-'",
")",
"[",
"-",
"1",
"]",
"if",
"platform",
"not",
"in",
"(",
"'iphoneos'",
",",
"'iphonesimulator'",
")",
":",
"platform",
"=",
"'iphonesimulator'",
"command_line",
".",
"extend",
"(",
"[",
"'--platform'",
",",
"platform",
",",
"'--target-device'",
",",
"'iphone'",
",",
"'--target-device'",
",",
"'ipad'",
",",
"'--minimum-deployment-target'",
",",
"os",
".",
"environ",
"[",
"'IPHONEOS_DEPLOYMENT_TARGET'",
"]",
",",
"'--compile'",
",",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"environ",
"[",
"'CONTENTS_FOLDER_PATH'",
"]",
")",
",",
"]",
")",
"else",
":",
"command_line",
".",
"extend",
"(",
"[",
"'--platform'",
",",
"'macosx'",
",",
"'--target-device'",
",",
"'mac'",
",",
"'--minimum-deployment-target'",
",",
"os",
".",
"environ",
"[",
"'MACOSX_DEPLOYMENT_TARGET'",
"]",
",",
"'--compile'",
",",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"environ",
"[",
"'UNLOCALIZED_RESOURCES_FOLDER_PATH'",
"]",
")",
",",
"]",
")",
"if",
"keys",
":",
"keys",
"=",
"json",
".",
"loads",
"(",
"keys",
")",
"for",
"key",
",",
"value",
"in",
"keys",
".",
"iteritems",
"(",
")",
":",
"arg_name",
"=",
"'--'",
"+",
"key",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"if",
"value",
":",
"command_line",
".",
"append",
"(",
"arg_name",
")",
"elif",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"for",
"v",
"in",
"value",
":",
"command_line",
".",
"append",
"(",
"arg_name",
")",
"command_line",
".",
"append",
"(",
"str",
"(",
"v",
")",
")",
"else",
":",
"command_line",
".",
"append",
"(",
"arg_name",
")",
"command_line",
".",
"append",
"(",
"str",
"(",
"value",
")",
")",
"# Note: actool crashes if inputs path are relative, so use os.path.abspath",
"# to get absolute path name for inputs.",
"command_line",
".",
"extend",
"(",
"map",
"(",
"os",
".",
"path",
".",
"abspath",
",",
"inputs",
")",
")",
"subprocess",
".",
"check_call",
"(",
"command_line",
")"
] | https://github.com/mozilla/spidernode/blob/aafa9e5273f954f272bb4382fc007af14674b4c2/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py#L292-L342 |
||
iSECPartners/Introspy-Analyzer | ceb2b2429a974a32690ac2d454e0a91f7e817e36 | introspy/DBAnalyzer.py | python | DBAnalyzer.get_findings_as_JSON | (self) | return dumps(findings_dict, default=self._json_serialize) | Returns the list of findings as JSON. | Returns the list of findings as JSON. | [
"Returns",
"the",
"list",
"of",
"findings",
"as",
"JSON",
"."
] | def get_findings_as_JSON(self):
"""Returns the list of findings as JSON."""
findings_dict = {}
findings_dict['findings'] = []
for (sig, tracedCalls) in self.findings:
if tracedCalls:
findings_dict['findings'].append({'signature' : sig,
'calls' : tracedCalls})
return dumps(findings_dict, default=self._json_serialize) | [
"def",
"get_findings_as_JSON",
"(",
"self",
")",
":",
"findings_dict",
"=",
"{",
"}",
"findings_dict",
"[",
"'findings'",
"]",
"=",
"[",
"]",
"for",
"(",
"sig",
",",
"tracedCalls",
")",
"in",
"self",
".",
"findings",
":",
"if",
"tracedCalls",
":",
"findings_dict",
"[",
"'findings'",
"]",
".",
"append",
"(",
"{",
"'signature'",
":",
"sig",
",",
"'calls'",
":",
"tracedCalls",
"}",
")",
"return",
"dumps",
"(",
"findings_dict",
",",
"default",
"=",
"self",
".",
"_json_serialize",
")"
] | https://github.com/iSECPartners/Introspy-Analyzer/blob/ceb2b2429a974a32690ac2d454e0a91f7e817e36/introspy/DBAnalyzer.py#L39-L48 |
|
agoravoting/agora-ciudadana | a7701035ea77d7a91baa9b5c2d0c05d91d1b4262 | userena/managers.py | python | UserenaManager.delete_expired_users | (self) | return deleted_users | Checks for expired users and delete's the ``User`` associated with
it. Skips if the user ``is_staff``.
:return: A list containing the deleted users. | Checks for expired users and delete's the ``User`` associated with
it. Skips if the user ``is_staff``. | [
"Checks",
"for",
"expired",
"users",
"and",
"delete",
"s",
"the",
"User",
"associated",
"with",
"it",
".",
"Skips",
"if",
"the",
"user",
"is_staff",
"."
] | def delete_expired_users(self):
"""
Checks for expired users and delete's the ``User`` associated with
it. Skips if the user ``is_staff``.
:return: A list containing the deleted users.
"""
deleted_users = []
for user in User.objects.filter(is_staff=False,
is_active=False):
if user.userena_signup.activation_key_expired():
deleted_users.append(user)
user.delete()
return deleted_users | [
"def",
"delete_expired_users",
"(",
"self",
")",
":",
"deleted_users",
"=",
"[",
"]",
"for",
"user",
"in",
"User",
".",
"objects",
".",
"filter",
"(",
"is_staff",
"=",
"False",
",",
"is_active",
"=",
"False",
")",
":",
"if",
"user",
".",
"userena_signup",
".",
"activation_key_expired",
"(",
")",
":",
"deleted_users",
".",
"append",
"(",
"user",
")",
"user",
".",
"delete",
"(",
")",
"return",
"deleted_users"
] | https://github.com/agoravoting/agora-ciudadana/blob/a7701035ea77d7a91baa9b5c2d0c05d91d1b4262/userena/managers.py#L185-L199 |
|
jam-py/jam-py | 0821492cdff8665928e0f093a4435aa64285a45c | jam/third_party/werkzeug/wrappers/base_request.py | python | BaseRequest.url | (self) | return get_current_url(self.environ, trusted_hosts=self.trusted_hosts) | The reconstructed current URL as IRI.
See also: :attr:`trusted_hosts`. | The reconstructed current URL as IRI.
See also: :attr:`trusted_hosts`. | [
"The",
"reconstructed",
"current",
"URL",
"as",
"IRI",
".",
"See",
"also",
":",
":",
"attr",
":",
"trusted_hosts",
"."
] | def url(self):
"""The reconstructed current URL as IRI.
See also: :attr:`trusted_hosts`.
"""
return get_current_url(self.environ, trusted_hosts=self.trusted_hosts) | [
"def",
"url",
"(",
"self",
")",
":",
"return",
"get_current_url",
"(",
"self",
".",
"environ",
",",
"trusted_hosts",
"=",
"self",
".",
"trusted_hosts",
")"
] | https://github.com/jam-py/jam-py/blob/0821492cdff8665928e0f093a4435aa64285a45c/jam/third_party/werkzeug/wrappers/base_request.py#L560-L564 |
|
thisismedium/python-xmpp-server | 8e6e009eabfecf4bbe36bdf2960455f0481a2ec1 | xmpp/core.py | python | Core.writer | (method) | return queue_write | Push writes through the scheduled jobs queue. | Push writes through the scheduled jobs queue. | [
"Push",
"writes",
"through",
"the",
"scheduled",
"jobs",
"queue",
"."
] | def writer(method):
"""Push writes through the scheduled jobs queue."""
@wraps(method)
def queue_write(self, *args, **kwargs):
self.state.run(method, self, *args, **kwargs)
return self
return queue_write | [
"def",
"writer",
"(",
"method",
")",
":",
"@",
"wraps",
"(",
"method",
")",
"def",
"queue_write",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"state",
".",
"run",
"(",
"method",
",",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
"return",
"queue_write"
] | https://github.com/thisismedium/python-xmpp-server/blob/8e6e009eabfecf4bbe36bdf2960455f0481a2ec1/xmpp/core.py#L118-L126 |
|
philogb/jit | 9966fbb6843538e6019fa8b233068ba0e7d283a8 | webpy/web/db.py | python | _interpolate | (format) | return chunks | Takes a format string and returns a list of 2-tuples of the form
(boolean, string) where boolean says whether string should be evaled
or not.
from <http://lfw.org/python/Itpl.py> (public domain, Ka-Ping Yee) | Takes a format string and returns a list of 2-tuples of the form
(boolean, string) where boolean says whether string should be evaled
or not. | [
"Takes",
"a",
"format",
"string",
"and",
"returns",
"a",
"list",
"of",
"2",
"-",
"tuples",
"of",
"the",
"form",
"(",
"boolean",
"string",
")",
"where",
"boolean",
"says",
"whether",
"string",
"should",
"be",
"evaled",
"or",
"not",
"."
] | def _interpolate(format):
"""
Takes a format string and returns a list of 2-tuples of the form
(boolean, string) where boolean says whether string should be evaled
or not.
from <http://lfw.org/python/Itpl.py> (public domain, Ka-Ping Yee)
"""
from tokenize import tokenprog
def matchorfail(text, pos):
match = tokenprog.match(text, pos)
if match is None:
raise _ItplError(text, pos)
return match, match.end()
namechars = "abcdefghijklmnopqrstuvwxyz" \
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
chunks = []
pos = 0
while 1:
dollar = format.find("$", pos)
if dollar < 0:
break
nextchar = format[dollar + 1]
if nextchar == "{":
chunks.append((0, format[pos:dollar]))
pos, level = dollar + 2, 1
while level:
match, pos = matchorfail(format, pos)
tstart, tend = match.regs[3]
token = format[tstart:tend]
if token == "{":
level = level + 1
elif token == "}":
level = level - 1
chunks.append((1, format[dollar + 2:pos - 1]))
elif nextchar in namechars:
chunks.append((0, format[pos:dollar]))
match, pos = matchorfail(format, dollar + 1)
while pos < len(format):
if format[pos] == "." and \
pos + 1 < len(format) and format[pos + 1] in namechars:
match, pos = matchorfail(format, pos + 1)
elif format[pos] in "([":
pos, level = pos + 1, 1
while level:
match, pos = matchorfail(format, pos)
tstart, tend = match.regs[3]
token = format[tstart:tend]
if token[0] in "([":
level = level + 1
elif token[0] in ")]":
level = level - 1
else:
break
chunks.append((1, format[dollar + 1:pos]))
else:
chunks.append((0, format[pos:dollar + 1]))
pos = dollar + 1 + (nextchar == "$")
if pos < len(format):
chunks.append((0, format[pos:]))
return chunks | [
"def",
"_interpolate",
"(",
"format",
")",
":",
"from",
"tokenize",
"import",
"tokenprog",
"def",
"matchorfail",
"(",
"text",
",",
"pos",
")",
":",
"match",
"=",
"tokenprog",
".",
"match",
"(",
"text",
",",
"pos",
")",
"if",
"match",
"is",
"None",
":",
"raise",
"_ItplError",
"(",
"text",
",",
"pos",
")",
"return",
"match",
",",
"match",
".",
"end",
"(",
")",
"namechars",
"=",
"\"abcdefghijklmnopqrstuvwxyz\"",
"\"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\"",
"chunks",
"=",
"[",
"]",
"pos",
"=",
"0",
"while",
"1",
":",
"dollar",
"=",
"format",
".",
"find",
"(",
"\"$\"",
",",
"pos",
")",
"if",
"dollar",
"<",
"0",
":",
"break",
"nextchar",
"=",
"format",
"[",
"dollar",
"+",
"1",
"]",
"if",
"nextchar",
"==",
"\"{\"",
":",
"chunks",
".",
"append",
"(",
"(",
"0",
",",
"format",
"[",
"pos",
":",
"dollar",
"]",
")",
")",
"pos",
",",
"level",
"=",
"dollar",
"+",
"2",
",",
"1",
"while",
"level",
":",
"match",
",",
"pos",
"=",
"matchorfail",
"(",
"format",
",",
"pos",
")",
"tstart",
",",
"tend",
"=",
"match",
".",
"regs",
"[",
"3",
"]",
"token",
"=",
"format",
"[",
"tstart",
":",
"tend",
"]",
"if",
"token",
"==",
"\"{\"",
":",
"level",
"=",
"level",
"+",
"1",
"elif",
"token",
"==",
"\"}\"",
":",
"level",
"=",
"level",
"-",
"1",
"chunks",
".",
"append",
"(",
"(",
"1",
",",
"format",
"[",
"dollar",
"+",
"2",
":",
"pos",
"-",
"1",
"]",
")",
")",
"elif",
"nextchar",
"in",
"namechars",
":",
"chunks",
".",
"append",
"(",
"(",
"0",
",",
"format",
"[",
"pos",
":",
"dollar",
"]",
")",
")",
"match",
",",
"pos",
"=",
"matchorfail",
"(",
"format",
",",
"dollar",
"+",
"1",
")",
"while",
"pos",
"<",
"len",
"(",
"format",
")",
":",
"if",
"format",
"[",
"pos",
"]",
"==",
"\".\"",
"and",
"pos",
"+",
"1",
"<",
"len",
"(",
"format",
")",
"and",
"format",
"[",
"pos",
"+",
"1",
"]",
"in",
"namechars",
":",
"match",
",",
"pos",
"=",
"matchorfail",
"(",
"format",
",",
"pos",
"+",
"1",
")",
"elif",
"format",
"[",
"pos",
"]",
"in",
"\"([\"",
":",
"pos",
",",
"level",
"=",
"pos",
"+",
"1",
",",
"1",
"while",
"level",
":",
"match",
",",
"pos",
"=",
"matchorfail",
"(",
"format",
",",
"pos",
")",
"tstart",
",",
"tend",
"=",
"match",
".",
"regs",
"[",
"3",
"]",
"token",
"=",
"format",
"[",
"tstart",
":",
"tend",
"]",
"if",
"token",
"[",
"0",
"]",
"in",
"\"([\"",
":",
"level",
"=",
"level",
"+",
"1",
"elif",
"token",
"[",
"0",
"]",
"in",
"\")]\"",
":",
"level",
"=",
"level",
"-",
"1",
"else",
":",
"break",
"chunks",
".",
"append",
"(",
"(",
"1",
",",
"format",
"[",
"dollar",
"+",
"1",
":",
"pos",
"]",
")",
")",
"else",
":",
"chunks",
".",
"append",
"(",
"(",
"0",
",",
"format",
"[",
"pos",
":",
"dollar",
"+",
"1",
"]",
")",
")",
"pos",
"=",
"dollar",
"+",
"1",
"+",
"(",
"nextchar",
"==",
"\"$\"",
")",
"if",
"pos",
"<",
"len",
"(",
"format",
")",
":",
"chunks",
".",
"append",
"(",
"(",
"0",
",",
"format",
"[",
"pos",
":",
"]",
")",
")",
"return",
"chunks"
] | https://github.com/philogb/jit/blob/9966fbb6843538e6019fa8b233068ba0e7d283a8/webpy/web/db.py#L1052-L1118 |
|
atom-community/ide-python | c046f9c2421713b34baa22648235541c5bb284fe | dist/debugger/VendorLib/vs-py-debugger/pythonFiles/jedi/api/classes.py | python | Completion.name_with_symbols | (self) | return self._complete(False) | Similar to :attr:`name`, but like :attr:`name` returns also the
symbols, for example assuming the following function definition::
def foo(param=0):
pass
completing ``foo(`` would give a ``Completion`` which
``name_with_symbols`` would be "param=". | Similar to :attr:`name`, but like :attr:`name` returns also the
symbols, for example assuming the following function definition:: | [
"Similar",
"to",
":",
"attr",
":",
"name",
"but",
"like",
":",
"attr",
":",
"name",
"returns",
"also",
"the",
"symbols",
"for",
"example",
"assuming",
"the",
"following",
"function",
"definition",
"::"
] | def name_with_symbols(self):
"""
Similar to :attr:`name`, but like :attr:`name` returns also the
symbols, for example assuming the following function definition::
def foo(param=0):
pass
completing ``foo(`` would give a ``Completion`` which
``name_with_symbols`` would be "param=".
"""
return self._complete(False) | [
"def",
"name_with_symbols",
"(",
"self",
")",
":",
"return",
"self",
".",
"_complete",
"(",
"False",
")"
] | https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/dist/debugger/VendorLib/vs-py-debugger/pythonFiles/jedi/api/classes.py#L439-L451 |
|
silklabs/silk | 08c273949086350aeddd8e23e92f0f79243f446f | node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py | python | StringToCMakeTargetName | (a) | return a.translate(string.maketrans(' /():."', '_______')) | Converts the given string 'a' to a valid CMake target name.
All invalid characters are replaced by '_'.
Invalid for cmake: ' ', '/', '(', ')', '"'
Invalid for make: ':'
Invalid for unknown reasons but cause failures: '.' | Converts the given string 'a' to a valid CMake target name. | [
"Converts",
"the",
"given",
"string",
"a",
"to",
"a",
"valid",
"CMake",
"target",
"name",
"."
] | def StringToCMakeTargetName(a):
"""Converts the given string 'a' to a valid CMake target name.
All invalid characters are replaced by '_'.
Invalid for cmake: ' ', '/', '(', ')', '"'
Invalid for make: ':'
Invalid for unknown reasons but cause failures: '.'
"""
return a.translate(string.maketrans(' /():."', '_______')) | [
"def",
"StringToCMakeTargetName",
"(",
"a",
")",
":",
"return",
"a",
".",
"translate",
"(",
"string",
".",
"maketrans",
"(",
"' /():.\"'",
",",
"'_______'",
")",
")"
] | https://github.com/silklabs/silk/blob/08c273949086350aeddd8e23e92f0f79243f446f/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py#L232-L240 |
|
Nexedi/erp5 | 44df1959c0e21576cf5e9803d602d95efb4b695b | product/ERP5Form/ImageField.py | python | ImageFieldWidget.render_odg_view | (self, field, value, as_string, ooo_builder, REQUEST,
render_prefix, attr_dict, local_name) | return draw_frame_node | return an image xml node rendered in odg format
if as_string is True (default) the returned value is a string (xml
reprensation of the node), if it's False, the value returned is the node
object.
attr_dict can be used for additional parameters (like style). | return an image xml node rendered in odg format
if as_string is True (default) the returned value is a string (xml
reprensation of the node), if it's False, the value returned is the node
object.
attr_dict can be used for additional parameters (like style). | [
"return",
"an",
"image",
"xml",
"node",
"rendered",
"in",
"odg",
"format",
"if",
"as_string",
"is",
"True",
"(",
"default",
")",
"the",
"returned",
"value",
"is",
"a",
"string",
"(",
"xml",
"reprensation",
"of",
"the",
"node",
")",
"if",
"it",
"s",
"False",
"the",
"value",
"returned",
"is",
"the",
"node",
"object",
".",
"attr_dict",
"can",
"be",
"used",
"for",
"additional",
"parameters",
"(",
"like",
"style",
")",
"."
] | def render_odg_view(self, field, value, as_string, ooo_builder, REQUEST,
render_prefix, attr_dict, local_name):
"""
return an image xml node rendered in odg format
if as_string is True (default) the returned value is a string (xml
reprensation of the node), if it's False, the value returned is the node
object.
attr_dict can be used for additional parameters (like style).
"""
if attr_dict is None:
attr_dict = {}
draw_frame_node = None
if value in ('', None):
return None
path = '/'.join(REQUEST.physicalPathFromURL(value))
path = path.encode()
image_object = field.getPortalObject().restrictedTraverse(path)
display = field.get_value('image_display')
format = field.get_value('image_format')
quality = field.get_value('image_quality')
image_parameter_dict = {'format': format}
if display:
image_parameter_dict['display'] = display
if quality:
image_parameter_dict['quality'] = quality
# convert the image using fields parameters. In this way, if an image
# is displayed in the form as a thumbnail, it will be added in the odg
# document as thumbnail size/quality
content_type, image_data = image_object.convert(**image_parameter_dict)
image = OFSImage('', '', image_data)
width = image.width
height = image.height
if image_data is None:
return draw_frame_node
# Big images are cut into smaller chunks, so it's required to cast to
# str. See OFS/Image -> _read_data method for more information
image_data = str(image_data)
format = content_type.split('/')[-1]
# add the image to the odg document
picture_path = ooo_builder.addImage(image=image_data,
format=format,
content_type=content_type)
# create the xml nodes related to the image
draw_frame_tag_name = '{%s}%s' % (DRAW_URI, 'frame')
draw_frame_node = Element(draw_frame_tag_name, nsmap=NSMAP)
draw_frame_node.attrib.update(attr_dict.get(draw_frame_tag_name,
{}).pop(0))
# set the size of the image
if display is not None:
# if the image width and height are not on defined, use current
# width and height
if (image_object.getWidth(), image_object.getHeight()) not in \
((-1, -1), (0,0)):
width, height = image_object._getAspectRatioSize(width, height)
if draw_frame_node.attrib.get('{%s}width' % SVG_URI) and \
draw_frame_node.attrib.get('{%s}height' % SVG_URI):
# if a size already exist from attr_dict, try to resize the image to
# fit this size (image should not be biger than size from attr_dict)
# devide the value by 20 to have cm instead of px
width, height = self._getPictureSize(width/20., height/20.,
target_width=draw_frame_node.attrib.get('{%s}width' % SVG_URI, ''),
target_height=draw_frame_node.attrib.get('{%s}height' % SVG_URI, ''))
draw_frame_node.set('{%s}width' % SVG_URI, str(width))
draw_frame_node.set('{%s}height' % SVG_URI, str(height))
image_tag_name = '{%s}%s' % (DRAW_URI, 'image')
image_node = Element(image_tag_name, nsmap=NSMAP)
image_node.attrib.update(attr_dict.get(image_tag_name, []).pop())
image_node.set('{%s}href' % XLINK_URI, picture_path)
draw_frame_node.append(image_node)
if as_string:
return etree.tostring(draw_frame_node)
return draw_frame_node | [
"def",
"render_odg_view",
"(",
"self",
",",
"field",
",",
"value",
",",
"as_string",
",",
"ooo_builder",
",",
"REQUEST",
",",
"render_prefix",
",",
"attr_dict",
",",
"local_name",
")",
":",
"if",
"attr_dict",
"is",
"None",
":",
"attr_dict",
"=",
"{",
"}",
"draw_frame_node",
"=",
"None",
"if",
"value",
"in",
"(",
"''",
",",
"None",
")",
":",
"return",
"None",
"path",
"=",
"'/'",
".",
"join",
"(",
"REQUEST",
".",
"physicalPathFromURL",
"(",
"value",
")",
")",
"path",
"=",
"path",
".",
"encode",
"(",
")",
"image_object",
"=",
"field",
".",
"getPortalObject",
"(",
")",
".",
"restrictedTraverse",
"(",
"path",
")",
"display",
"=",
"field",
".",
"get_value",
"(",
"'image_display'",
")",
"format",
"=",
"field",
".",
"get_value",
"(",
"'image_format'",
")",
"quality",
"=",
"field",
".",
"get_value",
"(",
"'image_quality'",
")",
"image_parameter_dict",
"=",
"{",
"'format'",
":",
"format",
"}",
"if",
"display",
":",
"image_parameter_dict",
"[",
"'display'",
"]",
"=",
"display",
"if",
"quality",
":",
"image_parameter_dict",
"[",
"'quality'",
"]",
"=",
"quality",
"# convert the image using fields parameters. In this way, if an image",
"# is displayed in the form as a thumbnail, it will be added in the odg",
"# document as thumbnail size/quality",
"content_type",
",",
"image_data",
"=",
"image_object",
".",
"convert",
"(",
"*",
"*",
"image_parameter_dict",
")",
"image",
"=",
"OFSImage",
"(",
"''",
",",
"''",
",",
"image_data",
")",
"width",
"=",
"image",
".",
"width",
"height",
"=",
"image",
".",
"height",
"if",
"image_data",
"is",
"None",
":",
"return",
"draw_frame_node",
"# Big images are cut into smaller chunks, so it's required to cast to",
"# str. See OFS/Image -> _read_data method for more information",
"image_data",
"=",
"str",
"(",
"image_data",
")",
"format",
"=",
"content_type",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"# add the image to the odg document",
"picture_path",
"=",
"ooo_builder",
".",
"addImage",
"(",
"image",
"=",
"image_data",
",",
"format",
"=",
"format",
",",
"content_type",
"=",
"content_type",
")",
"# create the xml nodes related to the image",
"draw_frame_tag_name",
"=",
"'{%s}%s'",
"%",
"(",
"DRAW_URI",
",",
"'frame'",
")",
"draw_frame_node",
"=",
"Element",
"(",
"draw_frame_tag_name",
",",
"nsmap",
"=",
"NSMAP",
")",
"draw_frame_node",
".",
"attrib",
".",
"update",
"(",
"attr_dict",
".",
"get",
"(",
"draw_frame_tag_name",
",",
"{",
"}",
")",
".",
"pop",
"(",
"0",
")",
")",
"# set the size of the image",
"if",
"display",
"is",
"not",
"None",
":",
"# if the image width and height are not on defined, use current",
"# width and height",
"if",
"(",
"image_object",
".",
"getWidth",
"(",
")",
",",
"image_object",
".",
"getHeight",
"(",
")",
")",
"not",
"in",
"(",
"(",
"-",
"1",
",",
"-",
"1",
")",
",",
"(",
"0",
",",
"0",
")",
")",
":",
"width",
",",
"height",
"=",
"image_object",
".",
"_getAspectRatioSize",
"(",
"width",
",",
"height",
")",
"if",
"draw_frame_node",
".",
"attrib",
".",
"get",
"(",
"'{%s}width'",
"%",
"SVG_URI",
")",
"and",
"draw_frame_node",
".",
"attrib",
".",
"get",
"(",
"'{%s}height'",
"%",
"SVG_URI",
")",
":",
"# if a size already exist from attr_dict, try to resize the image to",
"# fit this size (image should not be biger than size from attr_dict)",
"# devide the value by 20 to have cm instead of px",
"width",
",",
"height",
"=",
"self",
".",
"_getPictureSize",
"(",
"width",
"/",
"20.",
",",
"height",
"/",
"20.",
",",
"target_width",
"=",
"draw_frame_node",
".",
"attrib",
".",
"get",
"(",
"'{%s}width'",
"%",
"SVG_URI",
",",
"''",
")",
",",
"target_height",
"=",
"draw_frame_node",
".",
"attrib",
".",
"get",
"(",
"'{%s}height'",
"%",
"SVG_URI",
",",
"''",
")",
")",
"draw_frame_node",
".",
"set",
"(",
"'{%s}width'",
"%",
"SVG_URI",
",",
"str",
"(",
"width",
")",
")",
"draw_frame_node",
".",
"set",
"(",
"'{%s}height'",
"%",
"SVG_URI",
",",
"str",
"(",
"height",
")",
")",
"image_tag_name",
"=",
"'{%s}%s'",
"%",
"(",
"DRAW_URI",
",",
"'image'",
")",
"image_node",
"=",
"Element",
"(",
"image_tag_name",
",",
"nsmap",
"=",
"NSMAP",
")",
"image_node",
".",
"attrib",
".",
"update",
"(",
"attr_dict",
".",
"get",
"(",
"image_tag_name",
",",
"[",
"]",
")",
".",
"pop",
"(",
")",
")",
"image_node",
".",
"set",
"(",
"'{%s}href'",
"%",
"XLINK_URI",
",",
"picture_path",
")",
"draw_frame_node",
".",
"append",
"(",
"image_node",
")",
"if",
"as_string",
":",
"return",
"etree",
".",
"tostring",
"(",
"draw_frame_node",
")",
"return",
"draw_frame_node"
] | https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/product/ERP5Form/ImageField.py#L130-L208 |
|
redapple0204/my-boring-python | 1ab378e9d4f39ad920ff542ef3b2db68f0575a98 | pythonenv3.8/lib/python3.8/site-packages/setuptools/dist.py | python | check_extras | (dist, attr, value) | Verify that extras_require mapping is valid | Verify that extras_require mapping is valid | [
"Verify",
"that",
"extras_require",
"mapping",
"is",
"valid"
] | def check_extras(dist, attr, value):
"""Verify that extras_require mapping is valid"""
try:
list(itertools.starmap(_check_extra, value.items()))
except (TypeError, ValueError, AttributeError):
raise DistutilsSetupError(
"'extras_require' must be a dictionary whose values are "
"strings or lists of strings containing valid project/version "
"requirement specifiers."
) | [
"def",
"check_extras",
"(",
"dist",
",",
"attr",
",",
"value",
")",
":",
"try",
":",
"list",
"(",
"itertools",
".",
"starmap",
"(",
"_check_extra",
",",
"value",
".",
"items",
"(",
")",
")",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
",",
"AttributeError",
")",
":",
"raise",
"DistutilsSetupError",
"(",
"\"'extras_require' must be a dictionary whose values are \"",
"\"strings or lists of strings containing valid project/version \"",
"\"requirement specifiers.\"",
")"
] | https://github.com/redapple0204/my-boring-python/blob/1ab378e9d4f39ad920ff542ef3b2db68f0575a98/pythonenv3.8/lib/python3.8/site-packages/setuptools/dist.py#L247-L256 |
||
facebookarchive/nuclide | 2a2a0a642d136768b7d2a6d35a652dc5fb77d70a | modules/atom-ide-debugger-python/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/module.py | python | _ModuleContainer.get_symbols | (self) | return symbols | Returns the debugging symbols for all modules in this snapshot.
The symbols are automatically loaded when needed.
@rtype: list of tuple( str, int, int )
@return: List of symbols.
Each symbol is represented by a tuple that contains:
- Symbol name
- Symbol memory address
- Symbol size in bytes | Returns the debugging symbols for all modules in this snapshot.
The symbols are automatically loaded when needed. | [
"Returns",
"the",
"debugging",
"symbols",
"for",
"all",
"modules",
"in",
"this",
"snapshot",
".",
"The",
"symbols",
"are",
"automatically",
"loaded",
"when",
"needed",
"."
] | def get_symbols(self):
"""
Returns the debugging symbols for all modules in this snapshot.
The symbols are automatically loaded when needed.
@rtype: list of tuple( str, int, int )
@return: List of symbols.
Each symbol is represented by a tuple that contains:
- Symbol name
- Symbol memory address
- Symbol size in bytes
"""
symbols = list()
for aModule in self.iter_modules():
for symbol in aModule.iter_symbols():
symbols.append(symbol)
return symbols | [
"def",
"get_symbols",
"(",
"self",
")",
":",
"symbols",
"=",
"list",
"(",
")",
"for",
"aModule",
"in",
"self",
".",
"iter_modules",
"(",
")",
":",
"for",
"symbol",
"in",
"aModule",
".",
"iter_symbols",
"(",
")",
":",
"symbols",
".",
"append",
"(",
"symbol",
")",
"return",
"symbols"
] | https://github.com/facebookarchive/nuclide/blob/2a2a0a642d136768b7d2a6d35a652dc5fb77d70a/modules/atom-ide-debugger-python/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/module.py#L1798-L1814 |
|
Nexedi/erp5 | 44df1959c0e21576cf5e9803d602d95efb4b695b | product/ERP5Type/Core/Folder.py | python | Folder.callMethodOnObjectList | (self, object_path_list, method_id, *args, **kw) | return result_list | Very useful if we want to activate the call of a method
on many objects at a time. Like this we could prevent creating
too many activities at a time, and we may have only the path | Very useful if we want to activate the call of a method
on many objects at a time. Like this we could prevent creating
too many activities at a time, and we may have only the path | [
"Very",
"useful",
"if",
"we",
"want",
"to",
"activate",
"the",
"call",
"of",
"a",
"method",
"on",
"many",
"objects",
"at",
"a",
"time",
".",
"Like",
"this",
"we",
"could",
"prevent",
"creating",
"too",
"many",
"activities",
"at",
"a",
"time",
"and",
"we",
"may",
"have",
"only",
"the",
"path"
] | def callMethodOnObjectList(self, object_path_list, method_id, *args, **kw):
"""
Very useful if we want to activate the call of a method
on many objects at a time. Like this we could prevent creating
too many activities at a time, and we may have only the path
"""
result_list = []
traverse = self.getPortalObject().unrestrictedTraverse
for object_path in object_path_list:
result = getattr(traverse(object_path), method_id)(*args, **kw)
if type(result) in (list, tuple):
result_list += result
return result_list | [
"def",
"callMethodOnObjectList",
"(",
"self",
",",
"object_path_list",
",",
"method_id",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"result_list",
"=",
"[",
"]",
"traverse",
"=",
"self",
".",
"getPortalObject",
"(",
")",
".",
"unrestrictedTraverse",
"for",
"object_path",
"in",
"object_path_list",
":",
"result",
"=",
"getattr",
"(",
"traverse",
"(",
"object_path",
")",
",",
"method_id",
")",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"if",
"type",
"(",
"result",
")",
"in",
"(",
"list",
",",
"tuple",
")",
":",
"result_list",
"+=",
"result",
"return",
"result_list"
] | https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/product/ERP5Type/Core/Folder.py#L1622-L1634 |
|
googlearchive/drive-dredit | b916358d8e5ca14687667c5fff2463165253a53f | python/lib/gflags.py | python | FlagValues.FlagValuesDict | (self) | return flag_values | Returns: a dictionary that maps flag names to flag values. | Returns: a dictionary that maps flag names to flag values. | [
"Returns",
":",
"a",
"dictionary",
"that",
"maps",
"flag",
"names",
"to",
"flag",
"values",
"."
] | def FlagValuesDict(self):
"""Returns: a dictionary that maps flag names to flag values."""
flag_values = {}
for flag_name in self.RegisteredFlags():
flag = self.FlagDict()[flag_name]
flag_values[flag_name] = flag.value
return flag_values | [
"def",
"FlagValuesDict",
"(",
"self",
")",
":",
"flag_values",
"=",
"{",
"}",
"for",
"flag_name",
"in",
"self",
".",
"RegisteredFlags",
"(",
")",
":",
"flag",
"=",
"self",
".",
"FlagDict",
"(",
")",
"[",
"flag_name",
"]",
"flag_values",
"[",
"flag_name",
"]",
"=",
"flag",
".",
"value",
"return",
"flag_values"
] | https://github.com/googlearchive/drive-dredit/blob/b916358d8e5ca14687667c5fff2463165253a53f/python/lib/gflags.py#L1345-L1353 |
|
opencoweb/coweb | 7b3a87ee9eda735a859447d404ee16edde1c5671 | servers/python/coweb/bot/wrapper/base.py | python | BotWrapperBase.publish | (self, data) | Sends a public reply to bot subscribers. Data is a JSON encodable
object. | Sends a public reply to bot subscribers. Data is a JSON encodable
object. | [
"Sends",
"a",
"public",
"reply",
"to",
"bot",
"subscribers",
".",
"Data",
"is",
"a",
"JSON",
"encodable",
"object",
"."
] | def publish(self, data):
'''
Sends a public reply to bot subscribers. Data is a JSON encodable
object.
'''
raise NotImplementedError | [
"def",
"publish",
"(",
"self",
",",
"data",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/opencoweb/coweb/blob/7b3a87ee9eda735a859447d404ee16edde1c5671/servers/python/coweb/bot/wrapper/base.py#L15-L20 |
||
atom-community/ide-python | c046f9c2421713b34baa22648235541c5bb284fe | lib/debugger/VendorLib/vs-py-debugger/pythonFiles/jedi/api/classes.py | python | BaseDefinition.name | (self) | return self._name.string_name | Name of variable/function/class/module.
For example, for ``x = None`` it returns ``'x'``.
:rtype: str or None | Name of variable/function/class/module. | [
"Name",
"of",
"variable",
"/",
"function",
"/",
"class",
"/",
"module",
"."
] | def name(self):
"""
Name of variable/function/class/module.
For example, for ``x = None`` it returns ``'x'``.
:rtype: str or None
"""
return self._name.string_name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name",
".",
"string_name"
] | https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/lib/debugger/VendorLib/vs-py-debugger/pythonFiles/jedi/api/classes.py#L74-L82 |
|
nodejs/quic | 5baab3f3a05548d3b51bea98868412b08766e34d | deps/v8/tools/run-clang-tidy.py | python | ClangTidyRunFull | (build_folder, skip_output_filter, checks, auto_fix) | Run clang-tidy on the full codebase and print warnings. | Run clang-tidy on the full codebase and print warnings. | [
"Run",
"clang",
"-",
"tidy",
"on",
"the",
"full",
"codebase",
"and",
"print",
"warnings",
"."
] | def ClangTidyRunFull(build_folder, skip_output_filter, checks, auto_fix):
"""
Run clang-tidy on the full codebase and print warnings.
"""
extra_args = []
if auto_fix:
extra_args.append('-fix')
if checks is not None:
extra_args.append('-checks')
extra_args.append('-*, ' + checks)
with open(os.devnull, 'w') as DEVNULL:
ct_process = subprocess.Popen(
['run-clang-tidy', '-j' + str(THREADS), '-p', '.']
+ ['-header-filter'] + HEADER_REGEX + extra_args
+ FILE_REGEXS,
cwd=build_folder,
stdout=subprocess.PIPE,
stderr=DEVNULL)
removing_check_header = False
empty_lines = 0
while True:
line = ct_process.stdout.readline()
if line == '':
break
# Skip all lines after Enbale checks and before two newlines,
# i.e., skip clang-tidy check list.
if line.startswith('Enabled checks'):
removing_check_header = True
if removing_check_header and not skip_output_filter:
if line == '\n':
empty_lines += 1
if empty_lines == 2:
removing_check_header = False
continue
# Different lines get removed to ease output reading.
if not skip_output_filter and skip_line(line):
continue
# Print line, because no filter was matched.
if line != '\n':
sys.stdout.write(line) | [
"def",
"ClangTidyRunFull",
"(",
"build_folder",
",",
"skip_output_filter",
",",
"checks",
",",
"auto_fix",
")",
":",
"extra_args",
"=",
"[",
"]",
"if",
"auto_fix",
":",
"extra_args",
".",
"append",
"(",
"'-fix'",
")",
"if",
"checks",
"is",
"not",
"None",
":",
"extra_args",
".",
"append",
"(",
"'-checks'",
")",
"extra_args",
".",
"append",
"(",
"'-*, '",
"+",
"checks",
")",
"with",
"open",
"(",
"os",
".",
"devnull",
",",
"'w'",
")",
"as",
"DEVNULL",
":",
"ct_process",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"'run-clang-tidy'",
",",
"'-j'",
"+",
"str",
"(",
"THREADS",
")",
",",
"'-p'",
",",
"'.'",
"]",
"+",
"[",
"'-header-filter'",
"]",
"+",
"HEADER_REGEX",
"+",
"extra_args",
"+",
"FILE_REGEXS",
",",
"cwd",
"=",
"build_folder",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"DEVNULL",
")",
"removing_check_header",
"=",
"False",
"empty_lines",
"=",
"0",
"while",
"True",
":",
"line",
"=",
"ct_process",
".",
"stdout",
".",
"readline",
"(",
")",
"if",
"line",
"==",
"''",
":",
"break",
"# Skip all lines after Enbale checks and before two newlines,",
"# i.e., skip clang-tidy check list.",
"if",
"line",
".",
"startswith",
"(",
"'Enabled checks'",
")",
":",
"removing_check_header",
"=",
"True",
"if",
"removing_check_header",
"and",
"not",
"skip_output_filter",
":",
"if",
"line",
"==",
"'\\n'",
":",
"empty_lines",
"+=",
"1",
"if",
"empty_lines",
"==",
"2",
":",
"removing_check_header",
"=",
"False",
"continue",
"# Different lines get removed to ease output reading.",
"if",
"not",
"skip_output_filter",
"and",
"skip_line",
"(",
"line",
")",
":",
"continue",
"# Print line, because no filter was matched.",
"if",
"line",
"!=",
"'\\n'",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"line",
")"
] | https://github.com/nodejs/quic/blob/5baab3f3a05548d3b51bea98868412b08766e34d/deps/v8/tools/run-clang-tidy.py#L91-L136 |
||
web2py/py4web | 39858a6cb70c6eebee19d9aa6007768902bac5d7 | py4web/core.py | python | get_error_snapshot | (depth=5) | return data | Return a dict describing a given traceback (based on cgitb.text). | Return a dict describing a given traceback (based on cgitb.text). | [
"Return",
"a",
"dict",
"describing",
"a",
"given",
"traceback",
"(",
"based",
"on",
"cgitb",
".",
"text",
")",
"."
] | def get_error_snapshot(depth=5):
"""Return a dict describing a given traceback (based on cgitb.text)."""
tb = traceback.format_exc()
errorlog = os.environ.get("PY4WEB_ERRORLOG")
if errorlog:
msg = f"[{datetime.datetime.now().isoformat()}]: {tb}\n"
if errorlog == ":stderr":
sys.stderr.write(msg)
elif errorlog == ":stdout":
sys.stdout.write(msg)
elif errorlog == "tickets_only":
pass
else:
with portalocker.Lock(errorlog, "a", timeout=2) as fp:
fp.write(msg)
etype, evalue, etb = sys.exc_info()
if isinstance(etype, type):
etype = etype.__name__
data = {}
data["timestamp"] = datetime.datetime.utcnow().isoformat().replace("T", " ")
data["python_version"] = sys.version
platform_keys = [
"machine",
"node",
"platform",
"processor",
"python_branch",
"python_build",
"python_compiler",
"python_implementation",
"python_revision",
"python_version",
"python_version_tuple",
"release",
"system",
"uname",
"version",
]
data["platform_info"] = {key: getattr(platform, key)() for key in platform_keys}
data["os_environ"] = {key: str(value) for key, value in os.environ.items()}
data["traceback"] = tb
data["exception_type"] = str(etype)
data["exception_value"] = str(evalue)
# Loopover the stack frames
items = inspect.getinnerframes(etb, depth)
del etb # Prevent circular references that would cause memory leaks
data["stackframes"] = stackframes = []
for frame, file, lnum, func, lines, idx in items:
file = file and os.path.abspath(file) or "?"
args, varargs, varkw, locals = inspect.getargvalues(frame)
# Basic frame information
f = {"file": file, "func": func, "lnum": lnum}
f["code"] = lines
# FIXME: disable this for now until we understand why this goes into infinite loop
if False:
line_vars = cgitb.scanvars(
lambda: linecache.getline(file, lnum), frame, locals
)
# Dump local variables (referenced in current line only)
f["vars"] = {
key: repr(value)
for key, value in locals.items()
if not key.startswith("__")
}
stackframes.append(f)
return data | [
"def",
"get_error_snapshot",
"(",
"depth",
"=",
"5",
")",
":",
"tb",
"=",
"traceback",
".",
"format_exc",
"(",
")",
"errorlog",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"PY4WEB_ERRORLOG\"",
")",
"if",
"errorlog",
":",
"msg",
"=",
"f\"[{datetime.datetime.now().isoformat()}]: {tb}\\n\"",
"if",
"errorlog",
"==",
"\":stderr\"",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"msg",
")",
"elif",
"errorlog",
"==",
"\":stdout\"",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"msg",
")",
"elif",
"errorlog",
"==",
"\"tickets_only\"",
":",
"pass",
"else",
":",
"with",
"portalocker",
".",
"Lock",
"(",
"errorlog",
",",
"\"a\"",
",",
"timeout",
"=",
"2",
")",
"as",
"fp",
":",
"fp",
".",
"write",
"(",
"msg",
")",
"etype",
",",
"evalue",
",",
"etb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"if",
"isinstance",
"(",
"etype",
",",
"type",
")",
":",
"etype",
"=",
"etype",
".",
"__name__",
"data",
"=",
"{",
"}",
"data",
"[",
"\"timestamp\"",
"]",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"isoformat",
"(",
")",
".",
"replace",
"(",
"\"T\"",
",",
"\" \"",
")",
"data",
"[",
"\"python_version\"",
"]",
"=",
"sys",
".",
"version",
"platform_keys",
"=",
"[",
"\"machine\"",
",",
"\"node\"",
",",
"\"platform\"",
",",
"\"processor\"",
",",
"\"python_branch\"",
",",
"\"python_build\"",
",",
"\"python_compiler\"",
",",
"\"python_implementation\"",
",",
"\"python_revision\"",
",",
"\"python_version\"",
",",
"\"python_version_tuple\"",
",",
"\"release\"",
",",
"\"system\"",
",",
"\"uname\"",
",",
"\"version\"",
",",
"]",
"data",
"[",
"\"platform_info\"",
"]",
"=",
"{",
"key",
":",
"getattr",
"(",
"platform",
",",
"key",
")",
"(",
")",
"for",
"key",
"in",
"platform_keys",
"}",
"data",
"[",
"\"os_environ\"",
"]",
"=",
"{",
"key",
":",
"str",
"(",
"value",
")",
"for",
"key",
",",
"value",
"in",
"os",
".",
"environ",
".",
"items",
"(",
")",
"}",
"data",
"[",
"\"traceback\"",
"]",
"=",
"tb",
"data",
"[",
"\"exception_type\"",
"]",
"=",
"str",
"(",
"etype",
")",
"data",
"[",
"\"exception_value\"",
"]",
"=",
"str",
"(",
"evalue",
")",
"# Loopover the stack frames",
"items",
"=",
"inspect",
".",
"getinnerframes",
"(",
"etb",
",",
"depth",
")",
"del",
"etb",
"# Prevent circular references that would cause memory leaks",
"data",
"[",
"\"stackframes\"",
"]",
"=",
"stackframes",
"=",
"[",
"]",
"for",
"frame",
",",
"file",
",",
"lnum",
",",
"func",
",",
"lines",
",",
"idx",
"in",
"items",
":",
"file",
"=",
"file",
"and",
"os",
".",
"path",
".",
"abspath",
"(",
"file",
")",
"or",
"\"?\"",
"args",
",",
"varargs",
",",
"varkw",
",",
"locals",
"=",
"inspect",
".",
"getargvalues",
"(",
"frame",
")",
"# Basic frame information",
"f",
"=",
"{",
"\"file\"",
":",
"file",
",",
"\"func\"",
":",
"func",
",",
"\"lnum\"",
":",
"lnum",
"}",
"f",
"[",
"\"code\"",
"]",
"=",
"lines",
"# FIXME: disable this for now until we understand why this goes into infinite loop",
"if",
"False",
":",
"line_vars",
"=",
"cgitb",
".",
"scanvars",
"(",
"lambda",
":",
"linecache",
".",
"getline",
"(",
"file",
",",
"lnum",
")",
",",
"frame",
",",
"locals",
")",
"# Dump local variables (referenced in current line only)",
"f",
"[",
"\"vars\"",
"]",
"=",
"{",
"key",
":",
"repr",
"(",
"value",
")",
"for",
"key",
",",
"value",
"in",
"locals",
".",
"items",
"(",
")",
"if",
"not",
"key",
".",
"startswith",
"(",
"\"__\"",
")",
"}",
"stackframes",
".",
"append",
"(",
"f",
")",
"return",
"data"
] | https://github.com/web2py/py4web/blob/39858a6cb70c6eebee19d9aa6007768902bac5d7/py4web/core.py#L1041-L1113 |
|
nprapps/dailygraphics | c83ca22322d8bc069389daed6f38d5f238a14d9b | render_utils.py | python | flatten_app_config | () | return config | Returns a copy of app_config containing only
configuration variables. | Returns a copy of app_config containing only
configuration variables. | [
"Returns",
"a",
"copy",
"of",
"app_config",
"containing",
"only",
"configuration",
"variables",
"."
] | def flatten_app_config():
"""
Returns a copy of app_config containing only
configuration variables.
"""
config = {}
# Only all-caps [constant] vars get included
for k, v in app_config.__dict__.items():
if k.upper() == k:
config[k] = v
return config | [
"def",
"flatten_app_config",
"(",
")",
":",
"config",
"=",
"{",
"}",
"# Only all-caps [constant] vars get included",
"for",
"k",
",",
"v",
"in",
"app_config",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"k",
".",
"upper",
"(",
")",
"==",
"k",
":",
"config",
"[",
"k",
"]",
"=",
"v",
"return",
"config"
] | https://github.com/nprapps/dailygraphics/blob/c83ca22322d8bc069389daed6f38d5f238a14d9b/render_utils.py#L182-L194 |
|
jam-py/jam-py | 0821492cdff8665928e0f093a4435aa64285a45c | jam/third_party/sqlalchemy/sql/elements.py | python | ColumnElement.anon_label | (self) | return self._anon_label(getattr(self, "name", None)) | provides a constant 'anonymous label' for this ColumnElement.
This is a label() expression which will be named at compile time.
The same label() is returned each time anon_label is called so
that expressions can reference anon_label multiple times, producing
the same label name at compile time.
the compiler uses this function automatically at compile time
for expressions that are known to be 'unnamed' like binary
expressions and function calls. | provides a constant 'anonymous label' for this ColumnElement. | [
"provides",
"a",
"constant",
"anonymous",
"label",
"for",
"this",
"ColumnElement",
"."
] | def anon_label(self):
"""provides a constant 'anonymous label' for this ColumnElement.
This is a label() expression which will be named at compile time.
The same label() is returned each time anon_label is called so
that expressions can reference anon_label multiple times, producing
the same label name at compile time.
the compiler uses this function automatically at compile time
for expressions that are known to be 'unnamed' like binary
expressions and function calls.
"""
return self._anon_label(getattr(self, "name", None)) | [
"def",
"anon_label",
"(",
"self",
")",
":",
"return",
"self",
".",
"_anon_label",
"(",
"getattr",
"(",
"self",
",",
"\"name\"",
",",
"None",
")",
")"
] | https://github.com/jam-py/jam-py/blob/0821492cdff8665928e0f093a4435aa64285a45c/jam/third_party/sqlalchemy/sql/elements.py#L922-L935 |
|
odoo/odoo | 8de8c196a137f4ebbf67d7c7c83fee36f873f5c8 | addons/account/models/company.py | python | ResCompany.action_close_account_invoice_onboarding | (self) | Mark the invoice onboarding panel as closed. | Mark the invoice onboarding panel as closed. | [
"Mark",
"the",
"invoice",
"onboarding",
"panel",
"as",
"closed",
"."
] | def action_close_account_invoice_onboarding(self):
""" Mark the invoice onboarding panel as closed. """
self.env.company.account_invoice_onboarding_state = 'closed' | [
"def",
"action_close_account_invoice_onboarding",
"(",
"self",
")",
":",
"self",
".",
"env",
".",
"company",
".",
"account_invoice_onboarding_state",
"=",
"'closed'"
] | https://github.com/odoo/odoo/blob/8de8c196a137f4ebbf67d7c7c83fee36f873f5c8/addons/account/models/company.py#L462-L464 |
||
nodejs/node-chakracore | 770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43 | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/input.py | python | Filter | (l, item) | return [res.setdefault(e, e) for e in l if e != item] | Removes item from l. | Removes item from l. | [
"Removes",
"item",
"from",
"l",
"."
] | def Filter(l, item):
"""Removes item from l."""
res = {}
return [res.setdefault(e, e) for e in l if e != item] | [
"def",
"Filter",
"(",
"l",
",",
"item",
")",
":",
"res",
"=",
"{",
"}",
"return",
"[",
"res",
".",
"setdefault",
"(",
"e",
",",
"e",
")",
"for",
"e",
"in",
"l",
"if",
"e",
"!=",
"item",
"]"
] | https://github.com/nodejs/node-chakracore/blob/770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/input.py#L1490-L1493 |
|
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/closured/lib/python2.7/email/header.py | python | Header.append | (self, s, charset=None, errors='strict') | Append a string to the MIME header.
Optional charset, if given, should be a Charset instance or the name
of a character set (which will be converted to a Charset instance). A
value of None (the default) means that the charset given in the
constructor is used.
s may be a byte string or a Unicode string. If it is a byte string
(i.e. isinstance(s, str) is true), then charset is the encoding of
that byte string, and a UnicodeError will be raised if the string
cannot be decoded with that charset. If s is a Unicode string, then
charset is a hint specifying the character set of the characters in
the string. In this case, when producing an RFC 2822 compliant header
using RFC 2047 rules, the Unicode string will be encoded using the
following charsets in order: us-ascii, the charset hint, utf-8. The
first character set not to provoke a UnicodeError is used.
Optional `errors' is passed as the third argument to any unicode() or
ustr.encode() call. | Append a string to the MIME header. | [
"Append",
"a",
"string",
"to",
"the",
"MIME",
"header",
"."
] | def append(self, s, charset=None, errors='strict'):
"""Append a string to the MIME header.
Optional charset, if given, should be a Charset instance or the name
of a character set (which will be converted to a Charset instance). A
value of None (the default) means that the charset given in the
constructor is used.
s may be a byte string or a Unicode string. If it is a byte string
(i.e. isinstance(s, str) is true), then charset is the encoding of
that byte string, and a UnicodeError will be raised if the string
cannot be decoded with that charset. If s is a Unicode string, then
charset is a hint specifying the character set of the characters in
the string. In this case, when producing an RFC 2822 compliant header
using RFC 2047 rules, the Unicode string will be encoded using the
following charsets in order: us-ascii, the charset hint, utf-8. The
first character set not to provoke a UnicodeError is used.
Optional `errors' is passed as the third argument to any unicode() or
ustr.encode() call.
"""
if charset is None:
charset = self._charset
elif not isinstance(charset, Charset):
charset = Charset(charset)
# If the charset is our faux 8bit charset, leave the string unchanged
if charset != '8bit':
# We need to test that the string can be converted to unicode and
# back to a byte string, given the input and output codecs of the
# charset.
if isinstance(s, str):
# Possibly raise UnicodeError if the byte string can't be
# converted to a unicode with the input codec of the charset.
incodec = charset.input_codec or 'us-ascii'
ustr = unicode(s, incodec, errors)
# Now make sure that the unicode could be converted back to a
# byte string with the output codec, which may be different
# than the iput coded. Still, use the original byte string.
outcodec = charset.output_codec or 'us-ascii'
ustr.encode(outcodec, errors)
elif isinstance(s, unicode):
# Now we have to be sure the unicode string can be converted
# to a byte string with a reasonable output codec. We want to
# use the byte string in the chunk.
for charset in USASCII, charset, UTF8:
try:
outcodec = charset.output_codec or 'us-ascii'
s = s.encode(outcodec, errors)
break
except UnicodeError:
pass
else:
assert False, 'utf-8 conversion failed'
self._chunks.append((s, charset)) | [
"def",
"append",
"(",
"self",
",",
"s",
",",
"charset",
"=",
"None",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"charset",
"is",
"None",
":",
"charset",
"=",
"self",
".",
"_charset",
"elif",
"not",
"isinstance",
"(",
"charset",
",",
"Charset",
")",
":",
"charset",
"=",
"Charset",
"(",
"charset",
")",
"# If the charset is our faux 8bit charset, leave the string unchanged",
"if",
"charset",
"!=",
"'8bit'",
":",
"# We need to test that the string can be converted to unicode and",
"# back to a byte string, given the input and output codecs of the",
"# charset.",
"if",
"isinstance",
"(",
"s",
",",
"str",
")",
":",
"# Possibly raise UnicodeError if the byte string can't be",
"# converted to a unicode with the input codec of the charset.",
"incodec",
"=",
"charset",
".",
"input_codec",
"or",
"'us-ascii'",
"ustr",
"=",
"unicode",
"(",
"s",
",",
"incodec",
",",
"errors",
")",
"# Now make sure that the unicode could be converted back to a",
"# byte string with the output codec, which may be different",
"# than the iput coded. Still, use the original byte string.",
"outcodec",
"=",
"charset",
".",
"output_codec",
"or",
"'us-ascii'",
"ustr",
".",
"encode",
"(",
"outcodec",
",",
"errors",
")",
"elif",
"isinstance",
"(",
"s",
",",
"unicode",
")",
":",
"# Now we have to be sure the unicode string can be converted",
"# to a byte string with a reasonable output codec. We want to",
"# use the byte string in the chunk.",
"for",
"charset",
"in",
"USASCII",
",",
"charset",
",",
"UTF8",
":",
"try",
":",
"outcodec",
"=",
"charset",
".",
"output_codec",
"or",
"'us-ascii'",
"s",
"=",
"s",
".",
"encode",
"(",
"outcodec",
",",
"errors",
")",
"break",
"except",
"UnicodeError",
":",
"pass",
"else",
":",
"assert",
"False",
",",
"'utf-8 conversion failed'",
"self",
".",
"_chunks",
".",
"append",
"(",
"(",
"s",
",",
"charset",
")",
")"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/closured/lib/python2.7/email/header.py#L233-L286 |
||
redapple0204/my-boring-python | 1ab378e9d4f39ad920ff542ef3b2db68f0575a98 | pythonenv3.8/lib/python3.8/site-packages/pip/_vendor/urllib3/filepost.py | python | encode_multipart_formdata | (fields, boundary=None) | return body.getvalue(), content_type | Encode a dictionary of ``fields`` using the multipart/form-data MIME format.
:param fields:
Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`).
:param boundary:
If not specified, then a random boundary will be generated using
:func:`urllib3.filepost.choose_boundary`. | Encode a dictionary of ``fields`` using the multipart/form-data MIME format. | [
"Encode",
"a",
"dictionary",
"of",
"fields",
"using",
"the",
"multipart",
"/",
"form",
"-",
"data",
"MIME",
"format",
"."
] | def encode_multipart_formdata(fields, boundary=None):
"""
Encode a dictionary of ``fields`` using the multipart/form-data MIME format.
:param fields:
Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`).
:param boundary:
If not specified, then a random boundary will be generated using
:func:`urllib3.filepost.choose_boundary`.
"""
body = BytesIO()
if boundary is None:
boundary = choose_boundary()
for field in iter_field_objects(fields):
body.write(b('--%s\r\n' % (boundary)))
writer(body).write(field.render_headers())
data = field.data
if isinstance(data, int):
data = str(data) # Backwards compatibility
if isinstance(data, six.text_type):
writer(body).write(data)
else:
body.write(data)
body.write(b'\r\n')
body.write(b('--%s--\r\n' % (boundary)))
content_type = str('multipart/form-data; boundary=%s' % boundary)
return body.getvalue(), content_type | [
"def",
"encode_multipart_formdata",
"(",
"fields",
",",
"boundary",
"=",
"None",
")",
":",
"body",
"=",
"BytesIO",
"(",
")",
"if",
"boundary",
"is",
"None",
":",
"boundary",
"=",
"choose_boundary",
"(",
")",
"for",
"field",
"in",
"iter_field_objects",
"(",
"fields",
")",
":",
"body",
".",
"write",
"(",
"b",
"(",
"'--%s\\r\\n'",
"%",
"(",
"boundary",
")",
")",
")",
"writer",
"(",
"body",
")",
".",
"write",
"(",
"field",
".",
"render_headers",
"(",
")",
")",
"data",
"=",
"field",
".",
"data",
"if",
"isinstance",
"(",
"data",
",",
"int",
")",
":",
"data",
"=",
"str",
"(",
"data",
")",
"# Backwards compatibility",
"if",
"isinstance",
"(",
"data",
",",
"six",
".",
"text_type",
")",
":",
"writer",
"(",
"body",
")",
".",
"write",
"(",
"data",
")",
"else",
":",
"body",
".",
"write",
"(",
"data",
")",
"body",
".",
"write",
"(",
"b'\\r\\n'",
")",
"body",
".",
"write",
"(",
"b",
"(",
"'--%s--\\r\\n'",
"%",
"(",
"boundary",
")",
")",
")",
"content_type",
"=",
"str",
"(",
"'multipart/form-data; boundary=%s'",
"%",
"boundary",
")",
"return",
"body",
".",
"getvalue",
"(",
")",
",",
"content_type"
] | https://github.com/redapple0204/my-boring-python/blob/1ab378e9d4f39ad920ff542ef3b2db68f0575a98/pythonenv3.8/lib/python3.8/site-packages/pip/_vendor/urllib3/filepost.py#L63-L98 |
|
Nexedi/erp5 | 44df1959c0e21576cf5e9803d602d95efb4b695b | product/Formulator/PatternChecker.py | python | PatternChecker.make_regex_from_pattern | (self, pattern) | return '^ *' + regex + ' *$' | Replaces all symbol occurences and creates a complete regex
string. | Replaces all symbol occurences and creates a complete regex
string. | [
"Replaces",
"all",
"symbol",
"occurences",
"and",
"creates",
"a",
"complete",
"regex",
"string",
"."
] | def make_regex_from_pattern(self, pattern):
"""Replaces all symbol occurences and creates a complete regex
string.
"""
regex = self._escape_special_characters(pattern)
for symbol in [NUMBERSYMBOL, CHARSYMBOL, NUMCHARSYMBOL]:
regex = re.sub(symbol+'{1,}\*?', self._replace_symbol_by_regex, regex)
return '^ *' + regex + ' *$' | [
"def",
"make_regex_from_pattern",
"(",
"self",
",",
"pattern",
")",
":",
"regex",
"=",
"self",
".",
"_escape_special_characters",
"(",
"pattern",
")",
"for",
"symbol",
"in",
"[",
"NUMBERSYMBOL",
",",
"CHARSYMBOL",
",",
"NUMCHARSYMBOL",
"]",
":",
"regex",
"=",
"re",
".",
"sub",
"(",
"symbol",
"+",
"'{1,}\\*?'",
",",
"self",
".",
"_replace_symbol_by_regex",
",",
"regex",
")",
"return",
"'^ *'",
"+",
"regex",
"+",
"' *$'"
] | https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/product/Formulator/PatternChecker.py#L59-L66 |
|
duo-labs/cloudmapper | 21136e80f9ae5f39a195a22b94773745816d41ff | commands/iam_report.py | python | iam_report | (accounts, config, args) | Create IAM report | Create IAM report | [
"Create",
"IAM",
"report"
] | def iam_report(accounts, config, args):
"""Create IAM report"""
principal_stats = {}
json_account_auth_details = None
# Ensure only one account is given
if len(accounts) > 1:
raise Exception("This command only works with one account at a time")
account = accounts.pop()
# Create directory for output file if it doesn't already exists
try:
os.mkdir(os.path.dirname(REPORT_OUTPUT_FILE))
except OSError:
# Already exists
pass
# Read template
with open(os.path.join("templates", "iam_report.html"), "r") as report_template:
template = Template(report_template.read())
# Data to be passed to the template
t = {}
account = Account(None, account)
principal_stats = {}
print("Creating IAM report for: {}".format(account.name))
t["account_name"] = account.name
t["account_id"] = account.local_id
t["report_generated_time"] = datetime.datetime.now().strftime("%Y-%m-%d")
t["graph"] = ""
if args.show_graph:
t["graph"] = '<br><iframe width=700 height=700 src="./map.html"></iframe>'
for region_json in get_regions(account):
region = Region(account, region_json)
if region.name == "us-east-1":
json_account_auth_details = query_aws(
region.account, "iam-get-account-authorization-details", region
)
get_access_advisor(region, principal_stats, json_account_auth_details, args)
users = []
roles = []
inactive_principals = []
for principal, stats in principal_stats.items():
if "RoleName" in stats["auth"]:
stats["short_name"] = stats["auth"]["RoleName"]
stats["type"] = "role"
if stats["is_inactive"]:
inactive_principals.append(principal)
continue
roles.append(principal)
else:
stats["short_name"] = stats["auth"]["UserName"]
stats["type"] = "user"
if stats["is_inactive"]:
inactive_principals.append(principal)
continue
users.append(principal)
print("* Generating IAM graph")
# This needs to be generated even if we don't show the graph,
# because this data is needed for other functionality in this command
iam_graph = get_iam_graph(json_account_auth_details)
cytoscape_json = build_cytoscape_graph(iam_graph)
with open(os.path.join("web", "account-data", "data.json"), "w") as outfile:
json.dump(cytoscape_json, outfile, indent=4)
print("* Generating the rest of the report")
t["users"] = []
for principal in sorted(users):
service_counts = get_service_count_and_used(
principal_stats[principal]["last_access"]["ServicesLastAccessed"]
)
t["users"].append(
{
"arn": principal,
"name": principal_stats[principal]["auth"]["UserName"],
"services_used": service_counts["service_used_count"],
"services_granted": service_counts["service_count"],
}
)
t["roles"] = []
for principal in sorted(roles):
service_counts = get_service_count_and_used(
principal_stats[principal]["last_access"]["ServicesLastAccessed"]
)
t["roles"].append(
{
"arn": principal,
"name": principal_stats[principal]["auth"]["RoleName"],
"services_used": service_counts["service_used_count"],
"services_granted": service_counts["service_count"],
}
)
t["inactive_principals"] = []
for principal in sorted(inactive_principals):
# Choose icon
icon = '<i class="fas fa-user-astronaut"></i>'
if principal_stats[principal]["type"] == "user":
icon = '<i class="fas fa-user"></i>'
t["inactive_principals"].append(
{
"arn": principal,
"icon": icon,
"name": principal_stats[principal]["short_name"],
}
)
t["principals"] = []
for principal, stats in principal_stats.items():
if stats["is_inactive"]:
continue
p = {}
p["arn"] = principal
if "RoleName" in stats["auth"]:
p["icon"] = '<i class="fas fa-user-astronaut"></i>'
p["arn"] = stats["auth"]["Arn"]
p["name"] = stats["auth"]["RoleName"]
if "UserName" in stats["auth"]:
p["icon"] = '<i class="fas fa-user"></i>'
p["arn"] = stats["auth"]["Arn"]
p["name"] = stats["auth"]["UserName"]
principal_node = iam_graph[stats["auth"]["Arn"]]
privilege_sources = principal_node.get_services_allowed()
# Show access advisor info
# Get collection date
report_date = datetime.datetime.strptime(
stats["last_access"]["JobCompletionDate"][0:10], "%Y-%m-%d"
)
# Show services
p["services"] = []
for service in stats["last_access"]["ServicesLastAccessed"]:
last_use = "-"
if service.get("LastAuthenticated", "-") != "-":
last_use = (
report_date
- datetime.datetime.strptime(
service["LastAuthenticated"][0:10], "%Y-%m-%d"
)
).days
style = ""
if last_use == "-" or last_use > 90:
style = "bad"
source = privilege_sources.get(service["ServiceNamespace"], ["unknown"])
source = ";".join(source)
p["services"].append(
{
"style": style,
"name": service["ServiceName"],
"last_use": last_use,
"source": source,
}
)
# List groups
groups = stats["auth"].get("GroupList", [])
p["groups"] = []
arn_prefix = stats["auth"]["Arn"][0:26]
for group in groups:
p["groups"].append(
{"link_id": tolink(arn_prefix + "group/" + group), "name": group}
)
# List attached policies
policies = stats["auth"]["AttachedManagedPolicies"]
p["managed_policies"] = []
for policy in policies:
p["managed_policies"].append(
{"link_id": tolink(policy["PolicyArn"]), "name": policy["PolicyName"]}
)
# Show inline policies
policies = stats["auth"].get("UserPolicyList", [])
policies.extend(stats["auth"].get("RolePolicyList", []))
p["inline_policies"] = []
for policy in policies:
p["inline_policies"].append(
{
"name": policy["PolicyName"],
"document": json.dumps(policy["PolicyDocument"], indent=4),
}
)
# Show AssumeRolePolicyDocument
if "RoleName" in stats["auth"]:
p["assume_role"] = json.dumps(
stats["auth"]["AssumeRolePolicyDocument"], indent=4
)
t["principals"].append(p)
t["groups"] = []
for group in json_account_auth_details["GroupDetailList"]:
g = {"link_id": tolink(group["Arn"]), "name": group["GroupName"]}
# List members
group_node = iam_graph[group["Arn"]]
g["members"] = []
for parent in group_node.parents():
g["members"].append(
{"link_id": tolink(parent.key()), "name": parent.name()}
)
g["managed_policies"] = []
for policy in group["AttachedManagedPolicies"]:
g["managed_policies"].append(
{"link_id": tolink(policy["PolicyArn"]), "name": policy["PolicyName"]}
)
g["inline_policies"] = []
for policy in group["GroupPolicyList"]:
g["inline_policies"].append(
{
"name": policy["PolicyName"],
"document": json.dumps(policy["PolicyDocument"], indent=4),
}
)
t["groups"].append(g)
t["policies"] = []
for policy in json_account_auth_details["Policies"]:
p = {
"link_id": tolink(policy["Arn"]),
"name": policy["PolicyName"],
"managed": "",
}
if "arn:aws:iam::aws:policy" in policy["Arn"]:
p["managed"] = '<i class="fab fa-amazon"></i>AWS managed policy<br>'
# Attachments
policy_node = iam_graph[policy["Arn"]]
p["attachments"] = []
for parent in policy_node.parents():
p["attachments"].append(
{"link_id": tolink(parent.key()), "name": parent.name()}
)
for version in policy["PolicyVersionList"]:
if version["IsDefaultVersion"]:
p["document"] = json.dumps(version["Document"], indent=4)
t["policies"].append(p)
# Generate report from template
if args.requested_output == OutputFormat.html:
with open("{}.html".format(REPORT_OUTPUT_FILE), "w") as f:
f.write(template.render(t=t))
elif args.requested_output == OutputFormat.json:
with open("{}.json".format(REPORT_OUTPUT_FILE), "w") as f:
json.dump(t, f)
print(
"Report written to {}.{}".format(
REPORT_OUTPUT_FILE, args.requested_output.value
)
) | [
"def",
"iam_report",
"(",
"accounts",
",",
"config",
",",
"args",
")",
":",
"principal_stats",
"=",
"{",
"}",
"json_account_auth_details",
"=",
"None",
"# Ensure only one account is given",
"if",
"len",
"(",
"accounts",
")",
">",
"1",
":",
"raise",
"Exception",
"(",
"\"This command only works with one account at a time\"",
")",
"account",
"=",
"accounts",
".",
"pop",
"(",
")",
"# Create directory for output file if it doesn't already exists",
"try",
":",
"os",
".",
"mkdir",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"REPORT_OUTPUT_FILE",
")",
")",
"except",
"OSError",
":",
"# Already exists",
"pass",
"# Read template",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"\"templates\"",
",",
"\"iam_report.html\"",
")",
",",
"\"r\"",
")",
"as",
"report_template",
":",
"template",
"=",
"Template",
"(",
"report_template",
".",
"read",
"(",
")",
")",
"# Data to be passed to the template",
"t",
"=",
"{",
"}",
"account",
"=",
"Account",
"(",
"None",
",",
"account",
")",
"principal_stats",
"=",
"{",
"}",
"print",
"(",
"\"Creating IAM report for: {}\"",
".",
"format",
"(",
"account",
".",
"name",
")",
")",
"t",
"[",
"\"account_name\"",
"]",
"=",
"account",
".",
"name",
"t",
"[",
"\"account_id\"",
"]",
"=",
"account",
".",
"local_id",
"t",
"[",
"\"report_generated_time\"",
"]",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"\"%Y-%m-%d\"",
")",
"t",
"[",
"\"graph\"",
"]",
"=",
"\"\"",
"if",
"args",
".",
"show_graph",
":",
"t",
"[",
"\"graph\"",
"]",
"=",
"'<br><iframe width=700 height=700 src=\"./map.html\"></iframe>'",
"for",
"region_json",
"in",
"get_regions",
"(",
"account",
")",
":",
"region",
"=",
"Region",
"(",
"account",
",",
"region_json",
")",
"if",
"region",
".",
"name",
"==",
"\"us-east-1\"",
":",
"json_account_auth_details",
"=",
"query_aws",
"(",
"region",
".",
"account",
",",
"\"iam-get-account-authorization-details\"",
",",
"region",
")",
"get_access_advisor",
"(",
"region",
",",
"principal_stats",
",",
"json_account_auth_details",
",",
"args",
")",
"users",
"=",
"[",
"]",
"roles",
"=",
"[",
"]",
"inactive_principals",
"=",
"[",
"]",
"for",
"principal",
",",
"stats",
"in",
"principal_stats",
".",
"items",
"(",
")",
":",
"if",
"\"RoleName\"",
"in",
"stats",
"[",
"\"auth\"",
"]",
":",
"stats",
"[",
"\"short_name\"",
"]",
"=",
"stats",
"[",
"\"auth\"",
"]",
"[",
"\"RoleName\"",
"]",
"stats",
"[",
"\"type\"",
"]",
"=",
"\"role\"",
"if",
"stats",
"[",
"\"is_inactive\"",
"]",
":",
"inactive_principals",
".",
"append",
"(",
"principal",
")",
"continue",
"roles",
".",
"append",
"(",
"principal",
")",
"else",
":",
"stats",
"[",
"\"short_name\"",
"]",
"=",
"stats",
"[",
"\"auth\"",
"]",
"[",
"\"UserName\"",
"]",
"stats",
"[",
"\"type\"",
"]",
"=",
"\"user\"",
"if",
"stats",
"[",
"\"is_inactive\"",
"]",
":",
"inactive_principals",
".",
"append",
"(",
"principal",
")",
"continue",
"users",
".",
"append",
"(",
"principal",
")",
"print",
"(",
"\"* Generating IAM graph\"",
")",
"# This needs to be generated even if we don't show the graph,",
"# because this data is needed for other functionality in this command",
"iam_graph",
"=",
"get_iam_graph",
"(",
"json_account_auth_details",
")",
"cytoscape_json",
"=",
"build_cytoscape_graph",
"(",
"iam_graph",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"\"web\"",
",",
"\"account-data\"",
",",
"\"data.json\"",
")",
",",
"\"w\"",
")",
"as",
"outfile",
":",
"json",
".",
"dump",
"(",
"cytoscape_json",
",",
"outfile",
",",
"indent",
"=",
"4",
")",
"print",
"(",
"\"* Generating the rest of the report\"",
")",
"t",
"[",
"\"users\"",
"]",
"=",
"[",
"]",
"for",
"principal",
"in",
"sorted",
"(",
"users",
")",
":",
"service_counts",
"=",
"get_service_count_and_used",
"(",
"principal_stats",
"[",
"principal",
"]",
"[",
"\"last_access\"",
"]",
"[",
"\"ServicesLastAccessed\"",
"]",
")",
"t",
"[",
"\"users\"",
"]",
".",
"append",
"(",
"{",
"\"arn\"",
":",
"principal",
",",
"\"name\"",
":",
"principal_stats",
"[",
"principal",
"]",
"[",
"\"auth\"",
"]",
"[",
"\"UserName\"",
"]",
",",
"\"services_used\"",
":",
"service_counts",
"[",
"\"service_used_count\"",
"]",
",",
"\"services_granted\"",
":",
"service_counts",
"[",
"\"service_count\"",
"]",
",",
"}",
")",
"t",
"[",
"\"roles\"",
"]",
"=",
"[",
"]",
"for",
"principal",
"in",
"sorted",
"(",
"roles",
")",
":",
"service_counts",
"=",
"get_service_count_and_used",
"(",
"principal_stats",
"[",
"principal",
"]",
"[",
"\"last_access\"",
"]",
"[",
"\"ServicesLastAccessed\"",
"]",
")",
"t",
"[",
"\"roles\"",
"]",
".",
"append",
"(",
"{",
"\"arn\"",
":",
"principal",
",",
"\"name\"",
":",
"principal_stats",
"[",
"principal",
"]",
"[",
"\"auth\"",
"]",
"[",
"\"RoleName\"",
"]",
",",
"\"services_used\"",
":",
"service_counts",
"[",
"\"service_used_count\"",
"]",
",",
"\"services_granted\"",
":",
"service_counts",
"[",
"\"service_count\"",
"]",
",",
"}",
")",
"t",
"[",
"\"inactive_principals\"",
"]",
"=",
"[",
"]",
"for",
"principal",
"in",
"sorted",
"(",
"inactive_principals",
")",
":",
"# Choose icon",
"icon",
"=",
"'<i class=\"fas fa-user-astronaut\"></i>'",
"if",
"principal_stats",
"[",
"principal",
"]",
"[",
"\"type\"",
"]",
"==",
"\"user\"",
":",
"icon",
"=",
"'<i class=\"fas fa-user\"></i>'",
"t",
"[",
"\"inactive_principals\"",
"]",
".",
"append",
"(",
"{",
"\"arn\"",
":",
"principal",
",",
"\"icon\"",
":",
"icon",
",",
"\"name\"",
":",
"principal_stats",
"[",
"principal",
"]",
"[",
"\"short_name\"",
"]",
",",
"}",
")",
"t",
"[",
"\"principals\"",
"]",
"=",
"[",
"]",
"for",
"principal",
",",
"stats",
"in",
"principal_stats",
".",
"items",
"(",
")",
":",
"if",
"stats",
"[",
"\"is_inactive\"",
"]",
":",
"continue",
"p",
"=",
"{",
"}",
"p",
"[",
"\"arn\"",
"]",
"=",
"principal",
"if",
"\"RoleName\"",
"in",
"stats",
"[",
"\"auth\"",
"]",
":",
"p",
"[",
"\"icon\"",
"]",
"=",
"'<i class=\"fas fa-user-astronaut\"></i>'",
"p",
"[",
"\"arn\"",
"]",
"=",
"stats",
"[",
"\"auth\"",
"]",
"[",
"\"Arn\"",
"]",
"p",
"[",
"\"name\"",
"]",
"=",
"stats",
"[",
"\"auth\"",
"]",
"[",
"\"RoleName\"",
"]",
"if",
"\"UserName\"",
"in",
"stats",
"[",
"\"auth\"",
"]",
":",
"p",
"[",
"\"icon\"",
"]",
"=",
"'<i class=\"fas fa-user\"></i>'",
"p",
"[",
"\"arn\"",
"]",
"=",
"stats",
"[",
"\"auth\"",
"]",
"[",
"\"Arn\"",
"]",
"p",
"[",
"\"name\"",
"]",
"=",
"stats",
"[",
"\"auth\"",
"]",
"[",
"\"UserName\"",
"]",
"principal_node",
"=",
"iam_graph",
"[",
"stats",
"[",
"\"auth\"",
"]",
"[",
"\"Arn\"",
"]",
"]",
"privilege_sources",
"=",
"principal_node",
".",
"get_services_allowed",
"(",
")",
"# Show access advisor info",
"# Get collection date",
"report_date",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"stats",
"[",
"\"last_access\"",
"]",
"[",
"\"JobCompletionDate\"",
"]",
"[",
"0",
":",
"10",
"]",
",",
"\"%Y-%m-%d\"",
")",
"# Show services",
"p",
"[",
"\"services\"",
"]",
"=",
"[",
"]",
"for",
"service",
"in",
"stats",
"[",
"\"last_access\"",
"]",
"[",
"\"ServicesLastAccessed\"",
"]",
":",
"last_use",
"=",
"\"-\"",
"if",
"service",
".",
"get",
"(",
"\"LastAuthenticated\"",
",",
"\"-\"",
")",
"!=",
"\"-\"",
":",
"last_use",
"=",
"(",
"report_date",
"-",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"service",
"[",
"\"LastAuthenticated\"",
"]",
"[",
"0",
":",
"10",
"]",
",",
"\"%Y-%m-%d\"",
")",
")",
".",
"days",
"style",
"=",
"\"\"",
"if",
"last_use",
"==",
"\"-\"",
"or",
"last_use",
">",
"90",
":",
"style",
"=",
"\"bad\"",
"source",
"=",
"privilege_sources",
".",
"get",
"(",
"service",
"[",
"\"ServiceNamespace\"",
"]",
",",
"[",
"\"unknown\"",
"]",
")",
"source",
"=",
"\";\"",
".",
"join",
"(",
"source",
")",
"p",
"[",
"\"services\"",
"]",
".",
"append",
"(",
"{",
"\"style\"",
":",
"style",
",",
"\"name\"",
":",
"service",
"[",
"\"ServiceName\"",
"]",
",",
"\"last_use\"",
":",
"last_use",
",",
"\"source\"",
":",
"source",
",",
"}",
")",
"# List groups",
"groups",
"=",
"stats",
"[",
"\"auth\"",
"]",
".",
"get",
"(",
"\"GroupList\"",
",",
"[",
"]",
")",
"p",
"[",
"\"groups\"",
"]",
"=",
"[",
"]",
"arn_prefix",
"=",
"stats",
"[",
"\"auth\"",
"]",
"[",
"\"Arn\"",
"]",
"[",
"0",
":",
"26",
"]",
"for",
"group",
"in",
"groups",
":",
"p",
"[",
"\"groups\"",
"]",
".",
"append",
"(",
"{",
"\"link_id\"",
":",
"tolink",
"(",
"arn_prefix",
"+",
"\"group/\"",
"+",
"group",
")",
",",
"\"name\"",
":",
"group",
"}",
")",
"# List attached policies",
"policies",
"=",
"stats",
"[",
"\"auth\"",
"]",
"[",
"\"AttachedManagedPolicies\"",
"]",
"p",
"[",
"\"managed_policies\"",
"]",
"=",
"[",
"]",
"for",
"policy",
"in",
"policies",
":",
"p",
"[",
"\"managed_policies\"",
"]",
".",
"append",
"(",
"{",
"\"link_id\"",
":",
"tolink",
"(",
"policy",
"[",
"\"PolicyArn\"",
"]",
")",
",",
"\"name\"",
":",
"policy",
"[",
"\"PolicyName\"",
"]",
"}",
")",
"# Show inline policies",
"policies",
"=",
"stats",
"[",
"\"auth\"",
"]",
".",
"get",
"(",
"\"UserPolicyList\"",
",",
"[",
"]",
")",
"policies",
".",
"extend",
"(",
"stats",
"[",
"\"auth\"",
"]",
".",
"get",
"(",
"\"RolePolicyList\"",
",",
"[",
"]",
")",
")",
"p",
"[",
"\"inline_policies\"",
"]",
"=",
"[",
"]",
"for",
"policy",
"in",
"policies",
":",
"p",
"[",
"\"inline_policies\"",
"]",
".",
"append",
"(",
"{",
"\"name\"",
":",
"policy",
"[",
"\"PolicyName\"",
"]",
",",
"\"document\"",
":",
"json",
".",
"dumps",
"(",
"policy",
"[",
"\"PolicyDocument\"",
"]",
",",
"indent",
"=",
"4",
")",
",",
"}",
")",
"# Show AssumeRolePolicyDocument",
"if",
"\"RoleName\"",
"in",
"stats",
"[",
"\"auth\"",
"]",
":",
"p",
"[",
"\"assume_role\"",
"]",
"=",
"json",
".",
"dumps",
"(",
"stats",
"[",
"\"auth\"",
"]",
"[",
"\"AssumeRolePolicyDocument\"",
"]",
",",
"indent",
"=",
"4",
")",
"t",
"[",
"\"principals\"",
"]",
".",
"append",
"(",
"p",
")",
"t",
"[",
"\"groups\"",
"]",
"=",
"[",
"]",
"for",
"group",
"in",
"json_account_auth_details",
"[",
"\"GroupDetailList\"",
"]",
":",
"g",
"=",
"{",
"\"link_id\"",
":",
"tolink",
"(",
"group",
"[",
"\"Arn\"",
"]",
")",
",",
"\"name\"",
":",
"group",
"[",
"\"GroupName\"",
"]",
"}",
"# List members",
"group_node",
"=",
"iam_graph",
"[",
"group",
"[",
"\"Arn\"",
"]",
"]",
"g",
"[",
"\"members\"",
"]",
"=",
"[",
"]",
"for",
"parent",
"in",
"group_node",
".",
"parents",
"(",
")",
":",
"g",
"[",
"\"members\"",
"]",
".",
"append",
"(",
"{",
"\"link_id\"",
":",
"tolink",
"(",
"parent",
".",
"key",
"(",
")",
")",
",",
"\"name\"",
":",
"parent",
".",
"name",
"(",
")",
"}",
")",
"g",
"[",
"\"managed_policies\"",
"]",
"=",
"[",
"]",
"for",
"policy",
"in",
"group",
"[",
"\"AttachedManagedPolicies\"",
"]",
":",
"g",
"[",
"\"managed_policies\"",
"]",
".",
"append",
"(",
"{",
"\"link_id\"",
":",
"tolink",
"(",
"policy",
"[",
"\"PolicyArn\"",
"]",
")",
",",
"\"name\"",
":",
"policy",
"[",
"\"PolicyName\"",
"]",
"}",
")",
"g",
"[",
"\"inline_policies\"",
"]",
"=",
"[",
"]",
"for",
"policy",
"in",
"group",
"[",
"\"GroupPolicyList\"",
"]",
":",
"g",
"[",
"\"inline_policies\"",
"]",
".",
"append",
"(",
"{",
"\"name\"",
":",
"policy",
"[",
"\"PolicyName\"",
"]",
",",
"\"document\"",
":",
"json",
".",
"dumps",
"(",
"policy",
"[",
"\"PolicyDocument\"",
"]",
",",
"indent",
"=",
"4",
")",
",",
"}",
")",
"t",
"[",
"\"groups\"",
"]",
".",
"append",
"(",
"g",
")",
"t",
"[",
"\"policies\"",
"]",
"=",
"[",
"]",
"for",
"policy",
"in",
"json_account_auth_details",
"[",
"\"Policies\"",
"]",
":",
"p",
"=",
"{",
"\"link_id\"",
":",
"tolink",
"(",
"policy",
"[",
"\"Arn\"",
"]",
")",
",",
"\"name\"",
":",
"policy",
"[",
"\"PolicyName\"",
"]",
",",
"\"managed\"",
":",
"\"\"",
",",
"}",
"if",
"\"arn:aws:iam::aws:policy\"",
"in",
"policy",
"[",
"\"Arn\"",
"]",
":",
"p",
"[",
"\"managed\"",
"]",
"=",
"'<i class=\"fab fa-amazon\"></i>AWS managed policy<br>'",
"# Attachments",
"policy_node",
"=",
"iam_graph",
"[",
"policy",
"[",
"\"Arn\"",
"]",
"]",
"p",
"[",
"\"attachments\"",
"]",
"=",
"[",
"]",
"for",
"parent",
"in",
"policy_node",
".",
"parents",
"(",
")",
":",
"p",
"[",
"\"attachments\"",
"]",
".",
"append",
"(",
"{",
"\"link_id\"",
":",
"tolink",
"(",
"parent",
".",
"key",
"(",
")",
")",
",",
"\"name\"",
":",
"parent",
".",
"name",
"(",
")",
"}",
")",
"for",
"version",
"in",
"policy",
"[",
"\"PolicyVersionList\"",
"]",
":",
"if",
"version",
"[",
"\"IsDefaultVersion\"",
"]",
":",
"p",
"[",
"\"document\"",
"]",
"=",
"json",
".",
"dumps",
"(",
"version",
"[",
"\"Document\"",
"]",
",",
"indent",
"=",
"4",
")",
"t",
"[",
"\"policies\"",
"]",
".",
"append",
"(",
"p",
")",
"# Generate report from template",
"if",
"args",
".",
"requested_output",
"==",
"OutputFormat",
".",
"html",
":",
"with",
"open",
"(",
"\"{}.html\"",
".",
"format",
"(",
"REPORT_OUTPUT_FILE",
")",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"template",
".",
"render",
"(",
"t",
"=",
"t",
")",
")",
"elif",
"args",
".",
"requested_output",
"==",
"OutputFormat",
".",
"json",
":",
"with",
"open",
"(",
"\"{}.json\"",
".",
"format",
"(",
"REPORT_OUTPUT_FILE",
")",
",",
"\"w\"",
")",
"as",
"f",
":",
"json",
".",
"dump",
"(",
"t",
",",
"f",
")",
"print",
"(",
"\"Report written to {}.{}\"",
".",
"format",
"(",
"REPORT_OUTPUT_FILE",
",",
"args",
".",
"requested_output",
".",
"value",
")",
")"
] | https://github.com/duo-labs/cloudmapper/blob/21136e80f9ae5f39a195a22b94773745816d41ff/commands/iam_report.py#L363-L639 |
||
redapple0204/my-boring-python | 1ab378e9d4f39ad920ff542ef3b2db68f0575a98 | pythonenv3.8/lib/python3.8/site-packages/pip/_vendor/urllib3/contrib/securetransport.py | python | inject_into_urllib3 | () | Monkey-patch urllib3 with SecureTransport-backed SSL-support. | Monkey-patch urllib3 with SecureTransport-backed SSL-support. | [
"Monkey",
"-",
"patch",
"urllib3",
"with",
"SecureTransport",
"-",
"backed",
"SSL",
"-",
"support",
"."
] | def inject_into_urllib3():
"""
Monkey-patch urllib3 with SecureTransport-backed SSL-support.
"""
util.SSLContext = SecureTransportContext
util.ssl_.SSLContext = SecureTransportContext
util.HAS_SNI = HAS_SNI
util.ssl_.HAS_SNI = HAS_SNI
util.IS_SECURETRANSPORT = True
util.ssl_.IS_SECURETRANSPORT = True | [
"def",
"inject_into_urllib3",
"(",
")",
":",
"util",
".",
"SSLContext",
"=",
"SecureTransportContext",
"util",
".",
"ssl_",
".",
"SSLContext",
"=",
"SecureTransportContext",
"util",
".",
"HAS_SNI",
"=",
"HAS_SNI",
"util",
".",
"ssl_",
".",
"HAS_SNI",
"=",
"HAS_SNI",
"util",
".",
"IS_SECURETRANSPORT",
"=",
"True",
"util",
".",
"ssl_",
".",
"IS_SECURETRANSPORT",
"=",
"True"
] | https://github.com/redapple0204/my-boring-python/blob/1ab378e9d4f39ad920ff542ef3b2db68f0575a98/pythonenv3.8/lib/python3.8/site-packages/pip/_vendor/urllib3/contrib/securetransport.py#L175-L184 |
||
atom-community/ide-python | c046f9c2421713b34baa22648235541c5bb284fe | dist/debugger/VendorLib/vs-py-debugger/pythonFiles/jedi/evaluate/context/iterable.py | python | FakeSequence.__init__ | (self, evaluator, array_type, lazy_context_list) | type should be one of "tuple", "list" | type should be one of "tuple", "list" | [
"type",
"should",
"be",
"one",
"of",
"tuple",
"list"
] | def __init__(self, evaluator, array_type, lazy_context_list):
"""
type should be one of "tuple", "list"
"""
super(FakeSequence, self).__init__(evaluator, None, array_type)
self._lazy_context_list = lazy_context_list | [
"def",
"__init__",
"(",
"self",
",",
"evaluator",
",",
"array_type",
",",
"lazy_context_list",
")",
":",
"super",
"(",
"FakeSequence",
",",
"self",
")",
".",
"__init__",
"(",
"evaluator",
",",
"None",
",",
"array_type",
")",
"self",
".",
"_lazy_context_list",
"=",
"lazy_context_list"
] | https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/dist/debugger/VendorLib/vs-py-debugger/pythonFiles/jedi/evaluate/context/iterable.py#L408-L413 |
||
jasonsanjose/brackets-sass | 88b351f2ebc3aaa514494eac368d197f63438caf | node/2.0.3/node_modules/node-sass/node_modules/pangyp/gyp/pylib/gyp/msvs_emulation.py | python | VerifyMissingSources | (sources, build_dir, generator_flags, gyp_to_ninja) | Emulate behavior of msvs_error_on_missing_sources present in the msvs
generator: Check that all regular source files, i.e. not created at run time,
exist on disk. Missing files cause needless recompilation when building via
VS, and we want this check to match for people/bots that build using ninja,
so they're not surprised when the VS build fails. | Emulate behavior of msvs_error_on_missing_sources present in the msvs
generator: Check that all regular source files, i.e. not created at run time,
exist on disk. Missing files cause needless recompilation when building via
VS, and we want this check to match for people/bots that build using ninja,
so they're not surprised when the VS build fails. | [
"Emulate",
"behavior",
"of",
"msvs_error_on_missing_sources",
"present",
"in",
"the",
"msvs",
"generator",
":",
"Check",
"that",
"all",
"regular",
"source",
"files",
"i",
".",
"e",
".",
"not",
"created",
"at",
"run",
"time",
"exist",
"on",
"disk",
".",
"Missing",
"files",
"cause",
"needless",
"recompilation",
"when",
"building",
"via",
"VS",
"and",
"we",
"want",
"this",
"check",
"to",
"match",
"for",
"people",
"/",
"bots",
"that",
"build",
"using",
"ninja",
"so",
"they",
"re",
"not",
"surprised",
"when",
"the",
"VS",
"build",
"fails",
"."
] | def VerifyMissingSources(sources, build_dir, generator_flags, gyp_to_ninja):
"""Emulate behavior of msvs_error_on_missing_sources present in the msvs
generator: Check that all regular source files, i.e. not created at run time,
exist on disk. Missing files cause needless recompilation when building via
VS, and we want this check to match for people/bots that build using ninja,
so they're not surprised when the VS build fails."""
if int(generator_flags.get('msvs_error_on_missing_sources', 0)):
no_specials = filter(lambda x: '$' not in x, sources)
relative = [os.path.join(build_dir, gyp_to_ninja(s)) for s in no_specials]
missing = filter(lambda x: not os.path.exists(x), relative)
if missing:
# They'll look like out\Release\..\..\stuff\things.cc, so normalize the
# path for a slightly less crazy looking output.
cleaned_up = [os.path.normpath(x) for x in missing]
raise Exception('Missing input files:\n%s' % '\n'.join(cleaned_up)) | [
"def",
"VerifyMissingSources",
"(",
"sources",
",",
"build_dir",
",",
"generator_flags",
",",
"gyp_to_ninja",
")",
":",
"if",
"int",
"(",
"generator_flags",
".",
"get",
"(",
"'msvs_error_on_missing_sources'",
",",
"0",
")",
")",
":",
"no_specials",
"=",
"filter",
"(",
"lambda",
"x",
":",
"'$'",
"not",
"in",
"x",
",",
"sources",
")",
"relative",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"build_dir",
",",
"gyp_to_ninja",
"(",
"s",
")",
")",
"for",
"s",
"in",
"no_specials",
"]",
"missing",
"=",
"filter",
"(",
"lambda",
"x",
":",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"x",
")",
",",
"relative",
")",
"if",
"missing",
":",
"# They'll look like out\\Release\\..\\..\\stuff\\things.cc, so normalize the",
"# path for a slightly less crazy looking output.",
"cleaned_up",
"=",
"[",
"os",
".",
"path",
".",
"normpath",
"(",
"x",
")",
"for",
"x",
"in",
"missing",
"]",
"raise",
"Exception",
"(",
"'Missing input files:\\n%s'",
"%",
"'\\n'",
".",
"join",
"(",
"cleaned_up",
")",
")"
] | https://github.com/jasonsanjose/brackets-sass/blob/88b351f2ebc3aaa514494eac368d197f63438caf/node/2.0.3/node_modules/node-sass/node_modules/pangyp/gyp/pylib/gyp/msvs_emulation.py#L926-L940 |
||
Juniper/wistar | 39638acccbb84a673cb55ee85c685867491e27c4 | webConsole/bin/websocket_local.py | python | WebSocketServer.vmsg | (self, *args, **kwargs) | Same as msg() but as debug. | Same as msg() but as debug. | [
"Same",
"as",
"msg",
"()",
"but",
"as",
"debug",
"."
] | def vmsg(self, *args, **kwargs):
""" Same as msg() but as debug. """
self.logger.log(logging.DEBUG, *args, **kwargs) | [
"def",
"vmsg",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"logger",
".",
"log",
"(",
"logging",
".",
"DEBUG",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/Juniper/wistar/blob/39638acccbb84a673cb55ee85c685867491e27c4/webConsole/bin/websocket_local.py#L822-L824 |
||
JoneXiong/DjangoX | c2a723e209ef13595f571923faac7eb29e4c8150 | xadmin/plugins/wizard.py | python | WizardFormPlugin.get_step_index | (self, step=None) | return self.get_form_list().keyOrder.index(step) | Returns the index for the given `step` name. If no step is given,
the current step will be used to get the index. | Returns the index for the given `step` name. If no step is given,
the current step will be used to get the index. | [
"Returns",
"the",
"index",
"for",
"the",
"given",
"step",
"name",
".",
"If",
"no",
"step",
"is",
"given",
"the",
"current",
"step",
"will",
"be",
"used",
"to",
"get",
"the",
"index",
"."
] | def get_step_index(self, step=None):
"""
Returns the index for the given `step` name. If no step is given,
the current step will be used to get the index.
"""
if step is None:
step = self.steps.current
return self.get_form_list().keyOrder.index(step) | [
"def",
"get_step_index",
"(",
"self",
",",
"step",
"=",
"None",
")",
":",
"if",
"step",
"is",
"None",
":",
"step",
"=",
"self",
".",
"steps",
".",
"current",
"return",
"self",
".",
"get_form_list",
"(",
")",
".",
"keyOrder",
".",
"index",
"(",
"step",
")"
] | https://github.com/JoneXiong/DjangoX/blob/c2a723e209ef13595f571923faac7eb29e4c8150/xadmin/plugins/wizard.py#L294-L301 |
|
npm/cli | 892b66eba9f21dbfbc250572d437141e39a6de24 | node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py | python | NinjaWriter.GetPostbuildCommand | (self, spec, output, output_binary, is_command_start) | Returns a shell command that runs all the postbuilds, and removes
|output| if any of them fails. If |is_command_start| is False, then the
returned string will start with ' && '. | Returns a shell command that runs all the postbuilds, and removes
|output| if any of them fails. If |is_command_start| is False, then the
returned string will start with ' && '. | [
"Returns",
"a",
"shell",
"command",
"that",
"runs",
"all",
"the",
"postbuilds",
"and",
"removes",
"|output|",
"if",
"any",
"of",
"them",
"fails",
".",
"If",
"|is_command_start|",
"is",
"False",
"then",
"the",
"returned",
"string",
"will",
"start",
"with",
"&&",
"."
] | def GetPostbuildCommand(self, spec, output, output_binary, is_command_start):
"""Returns a shell command that runs all the postbuilds, and removes
|output| if any of them fails. If |is_command_start| is False, then the
returned string will start with ' && '."""
if not self.xcode_settings or spec["type"] == "none" or not output:
return ""
output = QuoteShellArgument(output, self.flavor)
postbuilds = gyp.xcode_emulation.GetSpecPostbuildCommands(spec, quiet=True)
if output_binary is not None:
postbuilds = self.xcode_settings.AddImplicitPostbuilds(
self.config_name,
os.path.normpath(os.path.join(self.base_to_build, output)),
QuoteShellArgument(
os.path.normpath(os.path.join(self.base_to_build, output_binary)),
self.flavor,
),
postbuilds,
quiet=True,
)
if not postbuilds:
return ""
# Postbuilds expect to be run in the gyp file's directory, so insert an
# implicit postbuild to cd to there.
postbuilds.insert(
0, gyp.common.EncodePOSIXShellList(["cd", self.build_to_base])
)
env = self.ComputeExportEnvString(self.GetSortedXcodePostbuildEnv())
# G will be non-null if any postbuild fails. Run all postbuilds in a
# subshell.
commands = (
env
+ " ("
+ " && ".join([ninja_syntax.escape(command) for command in postbuilds])
)
command_string = (
commands
+ "); G=$$?; "
# Remove the final output if any postbuild failed.
"((exit $$G) || rm -rf %s) " % output
+ "&& exit $$G)"
)
if is_command_start:
return "(" + command_string + " && "
else:
return "$ && (" + command_string | [
"def",
"GetPostbuildCommand",
"(",
"self",
",",
"spec",
",",
"output",
",",
"output_binary",
",",
"is_command_start",
")",
":",
"if",
"not",
"self",
".",
"xcode_settings",
"or",
"spec",
"[",
"\"type\"",
"]",
"==",
"\"none\"",
"or",
"not",
"output",
":",
"return",
"\"\"",
"output",
"=",
"QuoteShellArgument",
"(",
"output",
",",
"self",
".",
"flavor",
")",
"postbuilds",
"=",
"gyp",
".",
"xcode_emulation",
".",
"GetSpecPostbuildCommands",
"(",
"spec",
",",
"quiet",
"=",
"True",
")",
"if",
"output_binary",
"is",
"not",
"None",
":",
"postbuilds",
"=",
"self",
".",
"xcode_settings",
".",
"AddImplicitPostbuilds",
"(",
"self",
".",
"config_name",
",",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"base_to_build",
",",
"output",
")",
")",
",",
"QuoteShellArgument",
"(",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"base_to_build",
",",
"output_binary",
")",
")",
",",
"self",
".",
"flavor",
",",
")",
",",
"postbuilds",
",",
"quiet",
"=",
"True",
",",
")",
"if",
"not",
"postbuilds",
":",
"return",
"\"\"",
"# Postbuilds expect to be run in the gyp file's directory, so insert an",
"# implicit postbuild to cd to there.",
"postbuilds",
".",
"insert",
"(",
"0",
",",
"gyp",
".",
"common",
".",
"EncodePOSIXShellList",
"(",
"[",
"\"cd\"",
",",
"self",
".",
"build_to_base",
"]",
")",
")",
"env",
"=",
"self",
".",
"ComputeExportEnvString",
"(",
"self",
".",
"GetSortedXcodePostbuildEnv",
"(",
")",
")",
"# G will be non-null if any postbuild fails. Run all postbuilds in a",
"# subshell.",
"commands",
"=",
"(",
"env",
"+",
"\" (\"",
"+",
"\" && \"",
".",
"join",
"(",
"[",
"ninja_syntax",
".",
"escape",
"(",
"command",
")",
"for",
"command",
"in",
"postbuilds",
"]",
")",
")",
"command_string",
"=",
"(",
"commands",
"+",
"\"); G=$$?; \"",
"# Remove the final output if any postbuild failed.",
"\"((exit $$G) || rm -rf %s) \"",
"%",
"output",
"+",
"\"&& exit $$G)\"",
")",
"if",
"is_command_start",
":",
"return",
"\"(\"",
"+",
"command_string",
"+",
"\" && \"",
"else",
":",
"return",
"\"$ && (\"",
"+",
"command_string"
] | https://github.com/npm/cli/blob/892b66eba9f21dbfbc250572d437141e39a6de24/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py#L1724-L1769 |
||
PublicMapping/districtbuilder-classic | 6e4b9d644043082eb0499f5aa77e777fff73a67c | django/publicmapping/redistricting/calculators.py | python | LengthWidthCompactness.html | (self) | Generate an HTML representation of the compactness score. This
is represented as a percentage or "n/a"
@return: A number formatted similar to "1.00%", or "n/a" | Generate an HTML representation of the compactness score. This
is represented as a percentage or "n/a" | [
"Generate",
"an",
"HTML",
"representation",
"of",
"the",
"compactness",
"score",
".",
"This",
"is",
"represented",
"as",
"a",
"percentage",
"or",
"n",
"/",
"a"
] | def html(self):
"""
Generate an HTML representation of the compactness score. This
is represented as a percentage or "n/a"
@return: A number formatted similar to "1.00%", or "n/a"
"""
if not self.result is None and 'value' in self.result:
return self.percentage()
else:
return _("n/a") | [
"def",
"html",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"result",
"is",
"None",
"and",
"'value'",
"in",
"self",
".",
"result",
":",
"return",
"self",
".",
"percentage",
"(",
")",
"else",
":",
"return",
"_",
"(",
"\"n/a\"",
")"
] | https://github.com/PublicMapping/districtbuilder-classic/blob/6e4b9d644043082eb0499f5aa77e777fff73a67c/django/publicmapping/redistricting/calculators.py#L838-L848 |
||
depjs/dep | cb8def92812d80b1fd8e5ffbbc1ae129a207fff6 | node_modules/node-gyp/gyp/pylib/gyp/input.py | python | ProcessListFiltersInDict | (name, the_dict) | Process regular expression and exclusion-based filters on lists.
An exclusion list is in a dict key named with a trailing "!", like
"sources!". Every item in such a list is removed from the associated
main list, which in this example, would be "sources". Removed items are
placed into a "sources_excluded" list in the dict.
Regular expression (regex) filters are contained in dict keys named with a
trailing "/", such as "sources/" to operate on the "sources" list. Regex
filters in a dict take the form:
'sources/': [ ['exclude', '_(linux|mac|win)\\.cc$'],
['include', '_mac\\.cc$'] ],
The first filter says to exclude all files ending in _linux.cc, _mac.cc, and
_win.cc. The second filter then includes all files ending in _mac.cc that
are now or were once in the "sources" list. Items matching an "exclude"
filter are subject to the same processing as would occur if they were listed
by name in an exclusion list (ending in "!"). Items matching an "include"
filter are brought back into the main list if previously excluded by an
exclusion list or exclusion regex filter. Subsequent matching "exclude"
patterns can still cause items to be excluded after matching an "include". | Process regular expression and exclusion-based filters on lists. | [
"Process",
"regular",
"expression",
"and",
"exclusion",
"-",
"based",
"filters",
"on",
"lists",
"."
] | def ProcessListFiltersInDict(name, the_dict):
"""Process regular expression and exclusion-based filters on lists.
An exclusion list is in a dict key named with a trailing "!", like
"sources!". Every item in such a list is removed from the associated
main list, which in this example, would be "sources". Removed items are
placed into a "sources_excluded" list in the dict.
Regular expression (regex) filters are contained in dict keys named with a
trailing "/", such as "sources/" to operate on the "sources" list. Regex
filters in a dict take the form:
'sources/': [ ['exclude', '_(linux|mac|win)\\.cc$'],
['include', '_mac\\.cc$'] ],
The first filter says to exclude all files ending in _linux.cc, _mac.cc, and
_win.cc. The second filter then includes all files ending in _mac.cc that
are now or were once in the "sources" list. Items matching an "exclude"
filter are subject to the same processing as would occur if they were listed
by name in an exclusion list (ending in "!"). Items matching an "include"
filter are brought back into the main list if previously excluded by an
exclusion list or exclusion regex filter. Subsequent matching "exclude"
patterns can still cause items to be excluded after matching an "include".
"""
# Look through the dictionary for any lists whose keys end in "!" or "/".
# These are lists that will be treated as exclude lists and regular
# expression-based exclude/include lists. Collect the lists that are
# needed first, looking for the lists that they operate on, and assemble
# then into |lists|. This is done in a separate loop up front, because
# the _included and _excluded keys need to be added to the_dict, and that
# can't be done while iterating through it.
lists = []
del_lists = []
for key, value in the_dict.items():
operation = key[-1]
if operation != "!" and operation != "/":
continue
if type(value) is not list:
raise ValueError(
name + " key " + key + " must be list, not " + value.__class__.__name__
)
list_key = key[:-1]
if list_key not in the_dict:
# This happens when there's a list like "sources!" but no corresponding
# "sources" list. Since there's nothing for it to operate on, queue up
# the "sources!" list for deletion now.
del_lists.append(key)
continue
if type(the_dict[list_key]) is not list:
value = the_dict[list_key]
raise ValueError(
name
+ " key "
+ list_key
+ " must be list, not "
+ value.__class__.__name__
+ " when applying "
+ {"!": "exclusion", "/": "regex"}[operation]
)
if list_key not in lists:
lists.append(list_key)
# Delete the lists that are known to be unneeded at this point.
for del_list in del_lists:
del the_dict[del_list]
for list_key in lists:
the_list = the_dict[list_key]
# Initialize the list_actions list, which is parallel to the_list. Each
# item in list_actions identifies whether the corresponding item in
# the_list should be excluded, unconditionally preserved (included), or
# whether no exclusion or inclusion has been applied. Items for which
# no exclusion or inclusion has been applied (yet) have value -1, items
# excluded have value 0, and items included have value 1. Includes and
# excludes override previous actions. All items in list_actions are
# initialized to -1 because no excludes or includes have been processed
# yet.
list_actions = list((-1,) * len(the_list))
exclude_key = list_key + "!"
if exclude_key in the_dict:
for exclude_item in the_dict[exclude_key]:
for index, list_item in enumerate(the_list):
if exclude_item == list_item:
# This item matches the exclude_item, so set its action to 0
# (exclude).
list_actions[index] = 0
# The "whatever!" list is no longer needed, dump it.
del the_dict[exclude_key]
regex_key = list_key + "/"
if regex_key in the_dict:
for regex_item in the_dict[regex_key]:
[action, pattern] = regex_item
pattern_re = re.compile(pattern)
if action == "exclude":
# This item matches an exclude regex, so set its value to 0 (exclude).
action_value = 0
elif action == "include":
# This item matches an include regex, so set its value to 1 (include).
action_value = 1
else:
# This is an action that doesn't make any sense.
raise ValueError(
"Unrecognized action "
+ action
+ " in "
+ name
+ " key "
+ regex_key
)
for index, list_item in enumerate(the_list):
if list_actions[index] == action_value:
# Even if the regex matches, nothing will change so continue (regex
# searches are expensive).
continue
if pattern_re.search(list_item):
# Regular expression match.
list_actions[index] = action_value
# The "whatever/" list is no longer needed, dump it.
del the_dict[regex_key]
# Add excluded items to the excluded list.
#
# Note that exclude_key ("sources!") is different from excluded_key
# ("sources_excluded"). The exclude_key list is input and it was already
# processed and deleted; the excluded_key list is output and it's about
# to be created.
excluded_key = list_key + "_excluded"
if excluded_key in the_dict:
raise GypError(
name + " key " + excluded_key + " must not be present prior "
" to applying exclusion/regex filters for " + list_key
)
excluded_list = []
# Go backwards through the list_actions list so that as items are deleted,
# the indices of items that haven't been seen yet don't shift. That means
# that things need to be prepended to excluded_list to maintain them in the
# same order that they existed in the_list.
for index in range(len(list_actions) - 1, -1, -1):
if list_actions[index] == 0:
# Dump anything with action 0 (exclude). Keep anything with action 1
# (include) or -1 (no include or exclude seen for the item).
excluded_list.insert(0, the_list[index])
del the_list[index]
# If anything was excluded, put the excluded list into the_dict at
# excluded_key.
if len(excluded_list) > 0:
the_dict[excluded_key] = excluded_list
# Now recurse into subdicts and lists that may contain dicts.
for key, value in the_dict.items():
if type(value) is dict:
ProcessListFiltersInDict(key, value)
elif type(value) is list:
ProcessListFiltersInList(key, value) | [
"def",
"ProcessListFiltersInDict",
"(",
"name",
",",
"the_dict",
")",
":",
"# Look through the dictionary for any lists whose keys end in \"!\" or \"/\".",
"# These are lists that will be treated as exclude lists and regular",
"# expression-based exclude/include lists. Collect the lists that are",
"# needed first, looking for the lists that they operate on, and assemble",
"# then into |lists|. This is done in a separate loop up front, because",
"# the _included and _excluded keys need to be added to the_dict, and that",
"# can't be done while iterating through it.",
"lists",
"=",
"[",
"]",
"del_lists",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"the_dict",
".",
"items",
"(",
")",
":",
"operation",
"=",
"key",
"[",
"-",
"1",
"]",
"if",
"operation",
"!=",
"\"!\"",
"and",
"operation",
"!=",
"\"/\"",
":",
"continue",
"if",
"type",
"(",
"value",
")",
"is",
"not",
"list",
":",
"raise",
"ValueError",
"(",
"name",
"+",
"\" key \"",
"+",
"key",
"+",
"\" must be list, not \"",
"+",
"value",
".",
"__class__",
".",
"__name__",
")",
"list_key",
"=",
"key",
"[",
":",
"-",
"1",
"]",
"if",
"list_key",
"not",
"in",
"the_dict",
":",
"# This happens when there's a list like \"sources!\" but no corresponding",
"# \"sources\" list. Since there's nothing for it to operate on, queue up",
"# the \"sources!\" list for deletion now.",
"del_lists",
".",
"append",
"(",
"key",
")",
"continue",
"if",
"type",
"(",
"the_dict",
"[",
"list_key",
"]",
")",
"is",
"not",
"list",
":",
"value",
"=",
"the_dict",
"[",
"list_key",
"]",
"raise",
"ValueError",
"(",
"name",
"+",
"\" key \"",
"+",
"list_key",
"+",
"\" must be list, not \"",
"+",
"value",
".",
"__class__",
".",
"__name__",
"+",
"\" when applying \"",
"+",
"{",
"\"!\"",
":",
"\"exclusion\"",
",",
"\"/\"",
":",
"\"regex\"",
"}",
"[",
"operation",
"]",
")",
"if",
"list_key",
"not",
"in",
"lists",
":",
"lists",
".",
"append",
"(",
"list_key",
")",
"# Delete the lists that are known to be unneeded at this point.",
"for",
"del_list",
"in",
"del_lists",
":",
"del",
"the_dict",
"[",
"del_list",
"]",
"for",
"list_key",
"in",
"lists",
":",
"the_list",
"=",
"the_dict",
"[",
"list_key",
"]",
"# Initialize the list_actions list, which is parallel to the_list. Each",
"# item in list_actions identifies whether the corresponding item in",
"# the_list should be excluded, unconditionally preserved (included), or",
"# whether no exclusion or inclusion has been applied. Items for which",
"# no exclusion or inclusion has been applied (yet) have value -1, items",
"# excluded have value 0, and items included have value 1. Includes and",
"# excludes override previous actions. All items in list_actions are",
"# initialized to -1 because no excludes or includes have been processed",
"# yet.",
"list_actions",
"=",
"list",
"(",
"(",
"-",
"1",
",",
")",
"*",
"len",
"(",
"the_list",
")",
")",
"exclude_key",
"=",
"list_key",
"+",
"\"!\"",
"if",
"exclude_key",
"in",
"the_dict",
":",
"for",
"exclude_item",
"in",
"the_dict",
"[",
"exclude_key",
"]",
":",
"for",
"index",
",",
"list_item",
"in",
"enumerate",
"(",
"the_list",
")",
":",
"if",
"exclude_item",
"==",
"list_item",
":",
"# This item matches the exclude_item, so set its action to 0",
"# (exclude).",
"list_actions",
"[",
"index",
"]",
"=",
"0",
"# The \"whatever!\" list is no longer needed, dump it.",
"del",
"the_dict",
"[",
"exclude_key",
"]",
"regex_key",
"=",
"list_key",
"+",
"\"/\"",
"if",
"regex_key",
"in",
"the_dict",
":",
"for",
"regex_item",
"in",
"the_dict",
"[",
"regex_key",
"]",
":",
"[",
"action",
",",
"pattern",
"]",
"=",
"regex_item",
"pattern_re",
"=",
"re",
".",
"compile",
"(",
"pattern",
")",
"if",
"action",
"==",
"\"exclude\"",
":",
"# This item matches an exclude regex, so set its value to 0 (exclude).",
"action_value",
"=",
"0",
"elif",
"action",
"==",
"\"include\"",
":",
"# This item matches an include regex, so set its value to 1 (include).",
"action_value",
"=",
"1",
"else",
":",
"# This is an action that doesn't make any sense.",
"raise",
"ValueError",
"(",
"\"Unrecognized action \"",
"+",
"action",
"+",
"\" in \"",
"+",
"name",
"+",
"\" key \"",
"+",
"regex_key",
")",
"for",
"index",
",",
"list_item",
"in",
"enumerate",
"(",
"the_list",
")",
":",
"if",
"list_actions",
"[",
"index",
"]",
"==",
"action_value",
":",
"# Even if the regex matches, nothing will change so continue (regex",
"# searches are expensive).",
"continue",
"if",
"pattern_re",
".",
"search",
"(",
"list_item",
")",
":",
"# Regular expression match.",
"list_actions",
"[",
"index",
"]",
"=",
"action_value",
"# The \"whatever/\" list is no longer needed, dump it.",
"del",
"the_dict",
"[",
"regex_key",
"]",
"# Add excluded items to the excluded list.",
"#",
"# Note that exclude_key (\"sources!\") is different from excluded_key",
"# (\"sources_excluded\"). The exclude_key list is input and it was already",
"# processed and deleted; the excluded_key list is output and it's about",
"# to be created.",
"excluded_key",
"=",
"list_key",
"+",
"\"_excluded\"",
"if",
"excluded_key",
"in",
"the_dict",
":",
"raise",
"GypError",
"(",
"name",
"+",
"\" key \"",
"+",
"excluded_key",
"+",
"\" must not be present prior \"",
"\" to applying exclusion/regex filters for \"",
"+",
"list_key",
")",
"excluded_list",
"=",
"[",
"]",
"# Go backwards through the list_actions list so that as items are deleted,",
"# the indices of items that haven't been seen yet don't shift. That means",
"# that things need to be prepended to excluded_list to maintain them in the",
"# same order that they existed in the_list.",
"for",
"index",
"in",
"range",
"(",
"len",
"(",
"list_actions",
")",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"if",
"list_actions",
"[",
"index",
"]",
"==",
"0",
":",
"# Dump anything with action 0 (exclude). Keep anything with action 1",
"# (include) or -1 (no include or exclude seen for the item).",
"excluded_list",
".",
"insert",
"(",
"0",
",",
"the_list",
"[",
"index",
"]",
")",
"del",
"the_list",
"[",
"index",
"]",
"# If anything was excluded, put the excluded list into the_dict at",
"# excluded_key.",
"if",
"len",
"(",
"excluded_list",
")",
">",
"0",
":",
"the_dict",
"[",
"excluded_key",
"]",
"=",
"excluded_list",
"# Now recurse into subdicts and lists that may contain dicts.",
"for",
"key",
",",
"value",
"in",
"the_dict",
".",
"items",
"(",
")",
":",
"if",
"type",
"(",
"value",
")",
"is",
"dict",
":",
"ProcessListFiltersInDict",
"(",
"key",
",",
"value",
")",
"elif",
"type",
"(",
"value",
")",
"is",
"list",
":",
"ProcessListFiltersInList",
"(",
"key",
",",
"value",
")"
] | https://github.com/depjs/dep/blob/cb8def92812d80b1fd8e5ffbbc1ae129a207fff6/node_modules/node-gyp/gyp/pylib/gyp/input.py#L2541-L2708 |
||
facebookarchive/nuclide | 2a2a0a642d136768b7d2a6d35a652dc5fb77d70a | modules/atom-ide-debugger-python/VendorLib/vs-py-debugger/pythonFiles/PythonTools/visualstudio_py_repl.py | python | BasicReplBackend.execution_loop | (self) | loop on the main thread which is responsible for executing code | loop on the main thread which is responsible for executing code | [
"loop",
"on",
"the",
"main",
"thread",
"which",
"is",
"responsible",
"for",
"executing",
"code"
] | def execution_loop(self):
"""loop on the main thread which is responsible for executing code"""
if sys.platform == 'cli' and sys.version_info[:3] < (2, 7, 1):
# IronPython doesn't support thread.interrupt_main until 2.7.1
import System
self.main_thread = System.Threading.Thread.CurrentThread
# save ourselves so global lookups continue to work (required pre-2.6)...
cur_modules = set()
try:
cur_ps1 = sys.ps1
cur_ps2 = sys.ps2
except:
# CPython/IronPython don't set sys.ps1 for non-interactive sessions, Jython and PyPy do
sys.ps1 = cur_ps1 = '>>> '
sys.ps2 = cur_ps2 = '... '
self.send_prompt(cur_ps1, cur_ps2, allow_multiple_statements=False)
while True:
exit, cur_modules, cur_ps1, cur_ps2 = self.run_one_command(cur_modules, cur_ps1, cur_ps2)
if exit:
return | [
"def",
"execution_loop",
"(",
"self",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"'cli'",
"and",
"sys",
".",
"version_info",
"[",
":",
"3",
"]",
"<",
"(",
"2",
",",
"7",
",",
"1",
")",
":",
"# IronPython doesn't support thread.interrupt_main until 2.7.1",
"import",
"System",
"self",
".",
"main_thread",
"=",
"System",
".",
"Threading",
".",
"Thread",
".",
"CurrentThread",
"# save ourselves so global lookups continue to work (required pre-2.6)...",
"cur_modules",
"=",
"set",
"(",
")",
"try",
":",
"cur_ps1",
"=",
"sys",
".",
"ps1",
"cur_ps2",
"=",
"sys",
".",
"ps2",
"except",
":",
"# CPython/IronPython don't set sys.ps1 for non-interactive sessions, Jython and PyPy do",
"sys",
".",
"ps1",
"=",
"cur_ps1",
"=",
"'>>> '",
"sys",
".",
"ps2",
"=",
"cur_ps2",
"=",
"'... '",
"self",
".",
"send_prompt",
"(",
"cur_ps1",
",",
"cur_ps2",
",",
"allow_multiple_statements",
"=",
"False",
")",
"while",
"True",
":",
"exit",
",",
"cur_modules",
",",
"cur_ps1",
",",
"cur_ps2",
"=",
"self",
".",
"run_one_command",
"(",
"cur_modules",
",",
"cur_ps1",
",",
"cur_ps2",
")",
"if",
"exit",
":",
"return"
] | https://github.com/facebookarchive/nuclide/blob/2a2a0a642d136768b7d2a6d35a652dc5fb77d70a/modules/atom-ide-debugger-python/VendorLib/vs-py-debugger/pythonFiles/PythonTools/visualstudio_py_repl.py#L737-L760 |
||
sabeechen/hassio-google-drive-backup | 210bb73e366771361c112041eac13264bab13f08 | hassio-google-drive-backup/dev/apiingress.py | python | _response_header | (response: aiohttp.ClientResponse) | return headers | Create response header. | Create response header. | [
"Create",
"response",
"header",
"."
] | def _response_header(response: aiohttp.ClientResponse) -> Dict[str, str]:
"""Create response header."""
headers = {}
for name, value in response.headers.items():
if name in (
hdrs.TRANSFER_ENCODING,
hdrs.CONTENT_LENGTH,
hdrs.CONTENT_TYPE,
hdrs.CONTENT_ENCODING
):
continue
headers[name] = value
return headers | [
"def",
"_response_header",
"(",
"response",
":",
"aiohttp",
".",
"ClientResponse",
")",
"->",
"Dict",
"[",
"str",
",",
"str",
"]",
":",
"headers",
"=",
"{",
"}",
"for",
"name",
",",
"value",
"in",
"response",
".",
"headers",
".",
"items",
"(",
")",
":",
"if",
"name",
"in",
"(",
"hdrs",
".",
"TRANSFER_ENCODING",
",",
"hdrs",
".",
"CONTENT_LENGTH",
",",
"hdrs",
".",
"CONTENT_TYPE",
",",
"hdrs",
".",
"CONTENT_ENCODING",
")",
":",
"continue",
"headers",
"[",
"name",
"]",
"=",
"value",
"return",
"headers"
] | https://github.com/sabeechen/hassio-google-drive-backup/blob/210bb73e366771361c112041eac13264bab13f08/hassio-google-drive-backup/dev/apiingress.py#L361-L375 |
|
RASSec/A_Scan_Framework | 4a46cf14b8c717dc0196071bbfd27e2d9c85bb17 | pocscan/plugins/tangscan/tangscan/thirdparty/requests/packages/urllib3/fields.py | python | RequestField._render_part | (self, name, value) | return format_header_param(name, value) | Overridable helper function to format a single header parameter.
:param name:
The name of the parameter, a string expected to be ASCII only.
:param value:
The value of the parameter, provided as a unicode string. | Overridable helper function to format a single header parameter. | [
"Overridable",
"helper",
"function",
"to",
"format",
"a",
"single",
"header",
"parameter",
"."
] | def _render_part(self, name, value):
"""
Overridable helper function to format a single header parameter.
:param name:
The name of the parameter, a string expected to be ASCII only.
:param value:
The value of the parameter, provided as a unicode string.
"""
return format_header_param(name, value) | [
"def",
"_render_part",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"return",
"format_header_param",
"(",
"name",
",",
"value",
")"
] | https://github.com/RASSec/A_Scan_Framework/blob/4a46cf14b8c717dc0196071bbfd27e2d9c85bb17/pocscan/plugins/tangscan/tangscan/thirdparty/requests/packages/urllib3/fields.py#L104-L113 |
|
raiden-network/microraiden | 2d51e78afaf3c0a8ddab87e59a5260c0064cdbdd | microraiden/client/session.py | python | Session._request_resource | (
self,
method: str,
url: str,
**kwargs
) | Performs a simple GET request to the HTTP server with headers representing the given
channel state. | Performs a simple GET request to the HTTP server with headers representing the given
channel state. | [
"Performs",
"a",
"simple",
"GET",
"request",
"to",
"the",
"HTTP",
"server",
"with",
"headers",
"representing",
"the",
"given",
"channel",
"state",
"."
] | def _request_resource(
self,
method: str,
url: str,
**kwargs
) -> Tuple[Union[None, Response], bool]:
"""
Performs a simple GET request to the HTTP server with headers representing the given
channel state.
"""
headers = Munch()
headers.contract_address = self.client.context.channel_manager.address
if self.channel is not None:
headers.balance = str(self.channel.balance)
headers.balance_signature = encode_hex(self.channel.balance_sig)
headers.sender_address = self.channel.sender
headers.receiver_address = self.channel.receiver
headers.open_block = str(self.channel.block)
headers = HTTPHeaders.serialize(headers)
if 'headers' in kwargs:
headers.update(kwargs['headers'])
kwargs['headers'] = headers
else:
kwargs['headers'] = headers
response = requests.Session.request(self, method, url, **kwargs)
if self.on_http_response(method, url, response, **kwargs) is False:
return response, False # user requested abort
if response.status_code == requests.codes.OK:
return response, self.on_success(method, url, response, **kwargs)
elif response.status_code == requests.codes.PAYMENT_REQUIRED:
if HTTPHeaders.NONEXISTING_CHANNEL in response.headers:
return response, self.on_nonexisting_channel(method, url, response, **kwargs)
elif HTTPHeaders.INSUF_CONFS in response.headers:
return response, self.on_insufficient_confirmations(
method,
url,
response,
**kwargs
)
elif HTTPHeaders.INVALID_PROOF in response.headers:
return response, self.on_invalid_balance_proof(method, url, response, **kwargs)
elif HTTPHeaders.CONTRACT_ADDRESS not in response.headers or not is_same_address(
response.headers.get(HTTPHeaders.CONTRACT_ADDRESS),
self.client.context.channel_manager.address
):
return response, self.on_invalid_contract_address(method, url, response, **kwargs)
elif HTTPHeaders.INVALID_AMOUNT in response.headers:
return response, self.on_invalid_amount(method, url, response, **kwargs)
else:
return response, self.on_payment_requested(method, url, response, **kwargs)
else:
return response, self.on_http_error(method, url, response, **kwargs) | [
"def",
"_request_resource",
"(",
"self",
",",
"method",
":",
"str",
",",
"url",
":",
"str",
",",
"*",
"*",
"kwargs",
")",
"->",
"Tuple",
"[",
"Union",
"[",
"None",
",",
"Response",
"]",
",",
"bool",
"]",
":",
"headers",
"=",
"Munch",
"(",
")",
"headers",
".",
"contract_address",
"=",
"self",
".",
"client",
".",
"context",
".",
"channel_manager",
".",
"address",
"if",
"self",
".",
"channel",
"is",
"not",
"None",
":",
"headers",
".",
"balance",
"=",
"str",
"(",
"self",
".",
"channel",
".",
"balance",
")",
"headers",
".",
"balance_signature",
"=",
"encode_hex",
"(",
"self",
".",
"channel",
".",
"balance_sig",
")",
"headers",
".",
"sender_address",
"=",
"self",
".",
"channel",
".",
"sender",
"headers",
".",
"receiver_address",
"=",
"self",
".",
"channel",
".",
"receiver",
"headers",
".",
"open_block",
"=",
"str",
"(",
"self",
".",
"channel",
".",
"block",
")",
"headers",
"=",
"HTTPHeaders",
".",
"serialize",
"(",
"headers",
")",
"if",
"'headers'",
"in",
"kwargs",
":",
"headers",
".",
"update",
"(",
"kwargs",
"[",
"'headers'",
"]",
")",
"kwargs",
"[",
"'headers'",
"]",
"=",
"headers",
"else",
":",
"kwargs",
"[",
"'headers'",
"]",
"=",
"headers",
"response",
"=",
"requests",
".",
"Session",
".",
"request",
"(",
"self",
",",
"method",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
"on_http_response",
"(",
"method",
",",
"url",
",",
"response",
",",
"*",
"*",
"kwargs",
")",
"is",
"False",
":",
"return",
"response",
",",
"False",
"# user requested abort",
"if",
"response",
".",
"status_code",
"==",
"requests",
".",
"codes",
".",
"OK",
":",
"return",
"response",
",",
"self",
".",
"on_success",
"(",
"method",
",",
"url",
",",
"response",
",",
"*",
"*",
"kwargs",
")",
"elif",
"response",
".",
"status_code",
"==",
"requests",
".",
"codes",
".",
"PAYMENT_REQUIRED",
":",
"if",
"HTTPHeaders",
".",
"NONEXISTING_CHANNEL",
"in",
"response",
".",
"headers",
":",
"return",
"response",
",",
"self",
".",
"on_nonexisting_channel",
"(",
"method",
",",
"url",
",",
"response",
",",
"*",
"*",
"kwargs",
")",
"elif",
"HTTPHeaders",
".",
"INSUF_CONFS",
"in",
"response",
".",
"headers",
":",
"return",
"response",
",",
"self",
".",
"on_insufficient_confirmations",
"(",
"method",
",",
"url",
",",
"response",
",",
"*",
"*",
"kwargs",
")",
"elif",
"HTTPHeaders",
".",
"INVALID_PROOF",
"in",
"response",
".",
"headers",
":",
"return",
"response",
",",
"self",
".",
"on_invalid_balance_proof",
"(",
"method",
",",
"url",
",",
"response",
",",
"*",
"*",
"kwargs",
")",
"elif",
"HTTPHeaders",
".",
"CONTRACT_ADDRESS",
"not",
"in",
"response",
".",
"headers",
"or",
"not",
"is_same_address",
"(",
"response",
".",
"headers",
".",
"get",
"(",
"HTTPHeaders",
".",
"CONTRACT_ADDRESS",
")",
",",
"self",
".",
"client",
".",
"context",
".",
"channel_manager",
".",
"address",
")",
":",
"return",
"response",
",",
"self",
".",
"on_invalid_contract_address",
"(",
"method",
",",
"url",
",",
"response",
",",
"*",
"*",
"kwargs",
")",
"elif",
"HTTPHeaders",
".",
"INVALID_AMOUNT",
"in",
"response",
".",
"headers",
":",
"return",
"response",
",",
"self",
".",
"on_invalid_amount",
"(",
"method",
",",
"url",
",",
"response",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"return",
"response",
",",
"self",
".",
"on_payment_requested",
"(",
"method",
",",
"url",
",",
"response",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"return",
"response",
",",
"self",
".",
"on_http_error",
"(",
"method",
",",
"url",
",",
"response",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/raiden-network/microraiden/blob/2d51e78afaf3c0a8ddab87e59a5260c0064cdbdd/microraiden/client/session.py#L106-L166 |
||
atom-community/ide-python | c046f9c2421713b34baa22648235541c5bb284fe | dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/breakpoint.py | python | Hook.__postCallAction | (self, event) | Calls the "post" callback.
@type event: L{ExceptionEvent}
@param event: Breakpoint hit event. | Calls the "post" callback. | [
"Calls",
"the",
"post",
"callback",
"."
] | def __postCallAction(self, event):
"""
Calls the "post" callback.
@type event: L{ExceptionEvent}
@param event: Breakpoint hit event.
"""
aThread = event.get_thread()
retval = self._get_return_value(aThread)
self.__callHandler(self.__postCB, event, retval) | [
"def",
"__postCallAction",
"(",
"self",
",",
"event",
")",
":",
"aThread",
"=",
"event",
".",
"get_thread",
"(",
")",
"retval",
"=",
"self",
".",
"_get_return_value",
"(",
"aThread",
")",
"self",
".",
"__callHandler",
"(",
"self",
".",
"__postCB",
",",
"event",
",",
"retval",
")"
] | https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/breakpoint.py#L1303-L1312 |
||
korolr/dotfiles | 8e46933503ecb8d8651739ffeb1d2d4f0f5c6524 | .config/sublime-text-3/Backup/20170602095117/mdpopups/st3/mdpopups/mdx/superfences.py | python | SuperFencesHiliteTreeprocessor.__init__ | (self, md) | Initialize. | Initialize. | [
"Initialize",
"."
] | def __init__(self, md):
"""Initialize."""
super(SuperFencesHiliteTreeprocessor, self).__init__(md)
self.markdown = md
self.checked_for_codehilite = False
self.codehilite_conf = {} | [
"def",
"__init__",
"(",
"self",
",",
"md",
")",
":",
"super",
"(",
"SuperFencesHiliteTreeprocessor",
",",
"self",
")",
".",
"__init__",
"(",
"md",
")",
"self",
".",
"markdown",
"=",
"md",
"self",
".",
"checked_for_codehilite",
"=",
"False",
"self",
".",
"codehilite_conf",
"=",
"{",
"}"
] | https://github.com/korolr/dotfiles/blob/8e46933503ecb8d8651739ffeb1d2d4f0f5c6524/.config/sublime-text-3/Backup/20170602095117/mdpopups/st3/mdpopups/mdx/superfences.py#L635-L641 |
||
windmill/windmill | 994bd992b17f3f2d6f6b276fe17391fea08f32c3 | windmill/browser/ie.py | python | InternetExplorer.stop | (self) | Stop IE | Stop IE | [
"Stop",
"IE"
] | def stop(self):
"""Stop IE"""
self.unset_proxy()
try:
self.p_handle.kill(group=True)
except:
logger.error('Cannot kill Internet Explorer') | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"unset_proxy",
"(",
")",
"try",
":",
"self",
".",
"p_handle",
".",
"kill",
"(",
"group",
"=",
"True",
")",
"except",
":",
"logger",
".",
"error",
"(",
"'Cannot kill Internet Explorer'",
")"
] | https://github.com/windmill/windmill/blob/994bd992b17f3f2d6f6b276fe17391fea08f32c3/windmill/browser/ie.py#L84-L91 |
||
jxcore/jxcore | b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410 | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py | python | WinTool.ExecClCompile | (self, project_dir, selected_files) | return subprocess.call(cmd, shell=True, cwd=BASE_DIR) | Executed by msvs-ninja projects when the 'ClCompile' target is used to
build selected C/C++ files. | Executed by msvs-ninja projects when the 'ClCompile' target is used to
build selected C/C++ files. | [
"Executed",
"by",
"msvs",
"-",
"ninja",
"projects",
"when",
"the",
"ClCompile",
"target",
"is",
"used",
"to",
"build",
"selected",
"C",
"/",
"C",
"++",
"files",
"."
] | def ExecClCompile(self, project_dir, selected_files):
"""Executed by msvs-ninja projects when the 'ClCompile' target is used to
build selected C/C++ files."""
project_dir = os.path.relpath(project_dir, BASE_DIR)
selected_files = selected_files.split(';')
ninja_targets = [os.path.join(project_dir, filename) + '^^'
for filename in selected_files]
cmd = ['ninja.exe']
cmd.extend(ninja_targets)
return subprocess.call(cmd, shell=True, cwd=BASE_DIR) | [
"def",
"ExecClCompile",
"(",
"self",
",",
"project_dir",
",",
"selected_files",
")",
":",
"project_dir",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"project_dir",
",",
"BASE_DIR",
")",
"selected_files",
"=",
"selected_files",
".",
"split",
"(",
"';'",
")",
"ninja_targets",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"project_dir",
",",
"filename",
")",
"+",
"'^^'",
"for",
"filename",
"in",
"selected_files",
"]",
"cmd",
"=",
"[",
"'ninja.exe'",
"]",
"cmd",
".",
"extend",
"(",
"ninja_targets",
")",
"return",
"subprocess",
".",
"call",
"(",
"cmd",
",",
"shell",
"=",
"True",
",",
"cwd",
"=",
"BASE_DIR",
")"
] | https://github.com/jxcore/jxcore/blob/b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py#L300-L309 |
|
mozilla/arewefastyet | 0e2160885d0ca693577d54f1bbbe572f052282c6 | server/tables.py | python | camelcase | (string) | return class_.join('', map(class_.capitalize, splitted_string)) | Convert string or unicode from lower-case underscore to camel-case | Convert string or unicode from lower-case underscore to camel-case | [
"Convert",
"string",
"or",
"unicode",
"from",
"lower",
"-",
"case",
"underscore",
"to",
"camel",
"-",
"case"
] | def camelcase(string):
"""Convert string or unicode from lower-case underscore to camel-case"""
splitted_string = string.split('_')
# use string's class to work on the string to keep its type
class_ = string.__class__
return class_.join('', map(class_.capitalize, splitted_string)) | [
"def",
"camelcase",
"(",
"string",
")",
":",
"splitted_string",
"=",
"string",
".",
"split",
"(",
"'_'",
")",
"# use string's class to work on the string to keep its type",
"class_",
"=",
"string",
".",
"__class__",
"return",
"class_",
".",
"join",
"(",
"''",
",",
"map",
"(",
"class_",
".",
"capitalize",
",",
"splitted_string",
")",
")"
] | https://github.com/mozilla/arewefastyet/blob/0e2160885d0ca693577d54f1bbbe572f052282c6/server/tables.py#L21-L26 |
|
xl7dev/BurpSuite | d1d4bd4981a87f2f4c0c9744ad7c476336c813da | Extender/Sqlmap/thirdparty/odict/odict.py | python | Values.__getitem__ | (self, index) | Fetch the value at position i. | Fetch the value at position i. | [
"Fetch",
"the",
"value",
"at",
"position",
"i",
"."
] | def __getitem__(self, index):
"""Fetch the value at position i."""
if isinstance(index, types.SliceType):
return [self._main[key] for key in self._main._sequence[index]]
else:
return self._main[self._main._sequence[index]] | [
"def",
"__getitem__",
"(",
"self",
",",
"index",
")",
":",
"if",
"isinstance",
"(",
"index",
",",
"types",
".",
"SliceType",
")",
":",
"return",
"[",
"self",
".",
"_main",
"[",
"key",
"]",
"for",
"key",
"in",
"self",
".",
"_main",
".",
"_sequence",
"[",
"index",
"]",
"]",
"else",
":",
"return",
"self",
".",
"_main",
"[",
"self",
".",
"_main",
".",
"_sequence",
"[",
"index",
"]",
"]"
] | https://github.com/xl7dev/BurpSuite/blob/d1d4bd4981a87f2f4c0c9744ad7c476336c813da/Extender/Sqlmap/thirdparty/odict/odict.py#L1094-L1099 |
||
Skycrab/leakScan | 5ab4f4162a060ed5954e8272291eb05201f8fd5f | scanner/thirdparty/requests/packages/urllib3/contrib/pyopenssl.py | python | inject_into_urllib3 | () | Monkey-patch urllib3 with PyOpenSSL-backed SSL-support. | Monkey-patch urllib3 with PyOpenSSL-backed SSL-support. | [
"Monkey",
"-",
"patch",
"urllib3",
"with",
"PyOpenSSL",
"-",
"backed",
"SSL",
"-",
"support",
"."
] | def inject_into_urllib3():
'Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.'
connection.ssl_wrap_socket = ssl_wrap_socket
util.HAS_SNI = HAS_SNI | [
"def",
"inject_into_urllib3",
"(",
")",
":",
"connection",
".",
"ssl_wrap_socket",
"=",
"ssl_wrap_socket",
"util",
".",
"HAS_SNI",
"=",
"HAS_SNI"
] | https://github.com/Skycrab/leakScan/blob/5ab4f4162a060ed5954e8272291eb05201f8fd5f/scanner/thirdparty/requests/packages/urllib3/contrib/pyopenssl.py#L102-L106 |
||
ayojs/ayo | 45a1c8cf6384f5bcc81d834343c3ed9d78b97df3 | tools/gyp/pylib/gyp/generator/eclipse.py | python | GenerateClasspathFile | (target_list, target_dicts, toplevel_dir,
toplevel_build, out_name) | Generates a classpath file suitable for symbol navigation and code
completion of Java code (such as in Android projects) by finding all
.java and .jar files used as action inputs. | Generates a classpath file suitable for symbol navigation and code
completion of Java code (such as in Android projects) by finding all
.java and .jar files used as action inputs. | [
"Generates",
"a",
"classpath",
"file",
"suitable",
"for",
"symbol",
"navigation",
"and",
"code",
"completion",
"of",
"Java",
"code",
"(",
"such",
"as",
"in",
"Android",
"projects",
")",
"by",
"finding",
"all",
".",
"java",
"and",
".",
"jar",
"files",
"used",
"as",
"action",
"inputs",
"."
] | def GenerateClasspathFile(target_list, target_dicts, toplevel_dir,
toplevel_build, out_name):
'''Generates a classpath file suitable for symbol navigation and code
completion of Java code (such as in Android projects) by finding all
.java and .jar files used as action inputs.'''
gyp.common.EnsureDirExists(out_name)
result = ET.Element('classpath')
def AddElements(kind, paths):
# First, we need to normalize the paths so they are all relative to the
# toplevel dir.
rel_paths = set()
for path in paths:
if os.path.isabs(path):
rel_paths.add(os.path.relpath(path, toplevel_dir))
else:
rel_paths.add(path)
for path in sorted(rel_paths):
entry_element = ET.SubElement(result, 'classpathentry')
entry_element.set('kind', kind)
entry_element.set('path', path)
AddElements('lib', GetJavaJars(target_list, target_dicts, toplevel_dir))
AddElements('src', GetJavaSourceDirs(target_list, target_dicts, toplevel_dir))
# Include the standard JRE container and a dummy out folder
AddElements('con', ['org.eclipse.jdt.launching.JRE_CONTAINER'])
# Include a dummy out folder so that Eclipse doesn't use the default /bin
# folder in the root of the project.
AddElements('output', [os.path.join(toplevel_build, '.eclipse-java-build')])
ET.ElementTree(result).write(out_name) | [
"def",
"GenerateClasspathFile",
"(",
"target_list",
",",
"target_dicts",
",",
"toplevel_dir",
",",
"toplevel_build",
",",
"out_name",
")",
":",
"gyp",
".",
"common",
".",
"EnsureDirExists",
"(",
"out_name",
")",
"result",
"=",
"ET",
".",
"Element",
"(",
"'classpath'",
")",
"def",
"AddElements",
"(",
"kind",
",",
"paths",
")",
":",
"# First, we need to normalize the paths so they are all relative to the",
"# toplevel dir.",
"rel_paths",
"=",
"set",
"(",
")",
"for",
"path",
"in",
"paths",
":",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"path",
")",
":",
"rel_paths",
".",
"add",
"(",
"os",
".",
"path",
".",
"relpath",
"(",
"path",
",",
"toplevel_dir",
")",
")",
"else",
":",
"rel_paths",
".",
"add",
"(",
"path",
")",
"for",
"path",
"in",
"sorted",
"(",
"rel_paths",
")",
":",
"entry_element",
"=",
"ET",
".",
"SubElement",
"(",
"result",
",",
"'classpathentry'",
")",
"entry_element",
".",
"set",
"(",
"'kind'",
",",
"kind",
")",
"entry_element",
".",
"set",
"(",
"'path'",
",",
"path",
")",
"AddElements",
"(",
"'lib'",
",",
"GetJavaJars",
"(",
"target_list",
",",
"target_dicts",
",",
"toplevel_dir",
")",
")",
"AddElements",
"(",
"'src'",
",",
"GetJavaSourceDirs",
"(",
"target_list",
",",
"target_dicts",
",",
"toplevel_dir",
")",
")",
"# Include the standard JRE container and a dummy out folder",
"AddElements",
"(",
"'con'",
",",
"[",
"'org.eclipse.jdt.launching.JRE_CONTAINER'",
"]",
")",
"# Include a dummy out folder so that Eclipse doesn't use the default /bin",
"# folder in the root of the project.",
"AddElements",
"(",
"'output'",
",",
"[",
"os",
".",
"path",
".",
"join",
"(",
"toplevel_build",
",",
"'.eclipse-java-build'",
")",
"]",
")",
"ET",
".",
"ElementTree",
"(",
"result",
")",
".",
"write",
"(",
"out_name",
")"
] | https://github.com/ayojs/ayo/blob/45a1c8cf6384f5bcc81d834343c3ed9d78b97df3/tools/gyp/pylib/gyp/generator/eclipse.py#L337-L368 |
||
crits/crits | 6b357daa5c3060cf622d3a3b0c7b41a9ca69c049 | crits/signatures/handlers.py | python | generate_signature_jtable | (request, option) | Generate the jtable data for rendering in the list template.
:param request: The request for this jtable.
:type request: :class:`django.http.HttpRequest`
:param option: Action to take.
:type option: str of either 'jtlist', 'jtdelete', or 'inline'.
:returns: :class:`django.http.HttpResponse` | Generate the jtable data for rendering in the list template. | [
"Generate",
"the",
"jtable",
"data",
"for",
"rendering",
"in",
"the",
"list",
"template",
"."
] | def generate_signature_jtable(request, option):
"""
Generate the jtable data for rendering in the list template.
:param request: The request for this jtable.
:type request: :class:`django.http.HttpRequest`
:param option: Action to take.
:type option: str of either 'jtlist', 'jtdelete', or 'inline'.
:returns: :class:`django.http.HttpResponse`
"""
obj_type = Signature
type_ = "signature"
mapper = obj_type._meta['jtable_opts']
if option == "jtlist":
# Sets display url
details_url = mapper['details_url']
details_url_key = mapper['details_url_key']
fields = mapper['fields']
response = jtable_ajax_list(obj_type,
details_url,
details_url_key,
request,
includes=fields)
return HttpResponse(json.dumps(response,
default=json_handler),
content_type="application/json")
if option == "jtdelete":
response = {"Result": "ERROR"}
if jtable_ajax_delete(obj_type,request):
response = {"Result": "OK"}
return HttpResponse(json.dumps(response,
default=json_handler),
content_type="application/json")
jtopts = {
'title': "Signature",
'default_sort': mapper['default_sort'],
'listurl': reverse('crits-%ss-views-%ss_listing' % (type_,
type_),
args=('jtlist',)),
'deleteurl': reverse('crits-%ss-views-%ss_listing' % (type_,
type_),
args=('jtdelete',)),
'searchurl': reverse(mapper['searchurl']),
'fields': mapper['jtopts_fields'],
'hidden_fields': mapper['hidden_fields'],
'linked_fields': mapper['linked_fields'],
'details_link': mapper['details_link'],
'no_sort': mapper['no_sort']
}
jtable = build_jtable(jtopts,request)
jtable['toolbar'] = [
{
'tooltip': "'All Signatures'",
'text': "'All'",
'click': "function () {$('#signature_listing').jtable('load', {'refresh': 'yes'});}",
'cssClass': "'jtable-toolbar-center'",
},
{
'tooltip': "'New Signature'",
'text': "'New'",
'click': "function () {$('#signature_listing').jtable('load', {'refresh': 'yes', 'status': 'New'});}",
'cssClass': "'jtable-toolbar-center'",
},
{
'tooltip': "'In Progress Signatures'",
'text': "'In Progress'",
'click': "function () {$('#signature_listing').jtable('load', {'refresh': 'yes', 'status': 'In Progress'});}",
'cssClass': "'jtable-toolbar-center'",
},
{
'tooltip': "'Analyzed Signatures'",
'text': "'Analyzed'",
'click': "function () {$('#signature_listing').jtable('load', {'refresh': 'yes', 'status': 'Analyzed'});}",
'cssClass': "'jtable-toolbar-center'",
},
{
'tooltip': "'Deprecated Signatures'",
'text': "'Deprecated'",
'click': "function () {$('#signature_listing').jtable('load', {'refresh': 'yes', 'status': 'Deprecated'});}",
'cssClass': "'jtable-toolbar-center'",
},
{
'tooltip': "'Add Signature'",
'text': "'Add Signature'",
'click': "function () {$('#new-signature').click()}",
},
]
if option == "inline":
return render(request, "jtable.html",
{'jtable': jtable,
'jtid': '%s_listing' % type_,
'button' : '%s_tab' % type_})
else:
return render(request, "%s_listing.html" % type_,
{'jtable': jtable,
'jtid': '%s_listing' % type_}) | [
"def",
"generate_signature_jtable",
"(",
"request",
",",
"option",
")",
":",
"obj_type",
"=",
"Signature",
"type_",
"=",
"\"signature\"",
"mapper",
"=",
"obj_type",
".",
"_meta",
"[",
"'jtable_opts'",
"]",
"if",
"option",
"==",
"\"jtlist\"",
":",
"# Sets display url",
"details_url",
"=",
"mapper",
"[",
"'details_url'",
"]",
"details_url_key",
"=",
"mapper",
"[",
"'details_url_key'",
"]",
"fields",
"=",
"mapper",
"[",
"'fields'",
"]",
"response",
"=",
"jtable_ajax_list",
"(",
"obj_type",
",",
"details_url",
",",
"details_url_key",
",",
"request",
",",
"includes",
"=",
"fields",
")",
"return",
"HttpResponse",
"(",
"json",
".",
"dumps",
"(",
"response",
",",
"default",
"=",
"json_handler",
")",
",",
"content_type",
"=",
"\"application/json\"",
")",
"if",
"option",
"==",
"\"jtdelete\"",
":",
"response",
"=",
"{",
"\"Result\"",
":",
"\"ERROR\"",
"}",
"if",
"jtable_ajax_delete",
"(",
"obj_type",
",",
"request",
")",
":",
"response",
"=",
"{",
"\"Result\"",
":",
"\"OK\"",
"}",
"return",
"HttpResponse",
"(",
"json",
".",
"dumps",
"(",
"response",
",",
"default",
"=",
"json_handler",
")",
",",
"content_type",
"=",
"\"application/json\"",
")",
"jtopts",
"=",
"{",
"'title'",
":",
"\"Signature\"",
",",
"'default_sort'",
":",
"mapper",
"[",
"'default_sort'",
"]",
",",
"'listurl'",
":",
"reverse",
"(",
"'crits-%ss-views-%ss_listing'",
"%",
"(",
"type_",
",",
"type_",
")",
",",
"args",
"=",
"(",
"'jtlist'",
",",
")",
")",
",",
"'deleteurl'",
":",
"reverse",
"(",
"'crits-%ss-views-%ss_listing'",
"%",
"(",
"type_",
",",
"type_",
")",
",",
"args",
"=",
"(",
"'jtdelete'",
",",
")",
")",
",",
"'searchurl'",
":",
"reverse",
"(",
"mapper",
"[",
"'searchurl'",
"]",
")",
",",
"'fields'",
":",
"mapper",
"[",
"'jtopts_fields'",
"]",
",",
"'hidden_fields'",
":",
"mapper",
"[",
"'hidden_fields'",
"]",
",",
"'linked_fields'",
":",
"mapper",
"[",
"'linked_fields'",
"]",
",",
"'details_link'",
":",
"mapper",
"[",
"'details_link'",
"]",
",",
"'no_sort'",
":",
"mapper",
"[",
"'no_sort'",
"]",
"}",
"jtable",
"=",
"build_jtable",
"(",
"jtopts",
",",
"request",
")",
"jtable",
"[",
"'toolbar'",
"]",
"=",
"[",
"{",
"'tooltip'",
":",
"\"'All Signatures'\"",
",",
"'text'",
":",
"\"'All'\"",
",",
"'click'",
":",
"\"function () {$('#signature_listing').jtable('load', {'refresh': 'yes'});}\"",
",",
"'cssClass'",
":",
"\"'jtable-toolbar-center'\"",
",",
"}",
",",
"{",
"'tooltip'",
":",
"\"'New Signature'\"",
",",
"'text'",
":",
"\"'New'\"",
",",
"'click'",
":",
"\"function () {$('#signature_listing').jtable('load', {'refresh': 'yes', 'status': 'New'});}\"",
",",
"'cssClass'",
":",
"\"'jtable-toolbar-center'\"",
",",
"}",
",",
"{",
"'tooltip'",
":",
"\"'In Progress Signatures'\"",
",",
"'text'",
":",
"\"'In Progress'\"",
",",
"'click'",
":",
"\"function () {$('#signature_listing').jtable('load', {'refresh': 'yes', 'status': 'In Progress'});}\"",
",",
"'cssClass'",
":",
"\"'jtable-toolbar-center'\"",
",",
"}",
",",
"{",
"'tooltip'",
":",
"\"'Analyzed Signatures'\"",
",",
"'text'",
":",
"\"'Analyzed'\"",
",",
"'click'",
":",
"\"function () {$('#signature_listing').jtable('load', {'refresh': 'yes', 'status': 'Analyzed'});}\"",
",",
"'cssClass'",
":",
"\"'jtable-toolbar-center'\"",
",",
"}",
",",
"{",
"'tooltip'",
":",
"\"'Deprecated Signatures'\"",
",",
"'text'",
":",
"\"'Deprecated'\"",
",",
"'click'",
":",
"\"function () {$('#signature_listing').jtable('load', {'refresh': 'yes', 'status': 'Deprecated'});}\"",
",",
"'cssClass'",
":",
"\"'jtable-toolbar-center'\"",
",",
"}",
",",
"{",
"'tooltip'",
":",
"\"'Add Signature'\"",
",",
"'text'",
":",
"\"'Add Signature'\"",
",",
"'click'",
":",
"\"function () {$('#new-signature').click()}\"",
",",
"}",
",",
"]",
"if",
"option",
"==",
"\"inline\"",
":",
"return",
"render",
"(",
"request",
",",
"\"jtable.html\"",
",",
"{",
"'jtable'",
":",
"jtable",
",",
"'jtid'",
":",
"'%s_listing'",
"%",
"type_",
",",
"'button'",
":",
"'%s_tab'",
"%",
"type_",
"}",
")",
"else",
":",
"return",
"render",
"(",
"request",
",",
"\"%s_listing.html\"",
"%",
"type_",
",",
"{",
"'jtable'",
":",
"jtable",
",",
"'jtid'",
":",
"'%s_listing'",
"%",
"type_",
"}",
")"
] | https://github.com/crits/crits/blob/6b357daa5c3060cf622d3a3b0c7b41a9ca69c049/crits/signatures/handlers.py#L173-L270 |
||
googleglass/mirror-quickstart-python | e34077bae91657170c305702471f5c249eb1b686 | lib/oauth2client/multistore_file.py | python | _MultiStore._update_credential | (self, key, cred) | Update a credential and write the multistore.
This must be called when the multistore is locked.
Args:
key: The key used to retrieve the credential
cred: The OAuth2Credential to update/set | Update a credential and write the multistore. | [
"Update",
"a",
"credential",
"and",
"write",
"the",
"multistore",
"."
] | def _update_credential(self, key, cred):
"""Update a credential and write the multistore.
This must be called when the multistore is locked.
Args:
key: The key used to retrieve the credential
cred: The OAuth2Credential to update/set
"""
self._data[key] = cred
self._write() | [
"def",
"_update_credential",
"(",
"self",
",",
"key",
",",
"cred",
")",
":",
"self",
".",
"_data",
"[",
"key",
"]",
"=",
"cred",
"self",
".",
"_write",
"(",
")"
] | https://github.com/googleglass/mirror-quickstart-python/blob/e34077bae91657170c305702471f5c249eb1b686/lib/oauth2client/multistore_file.py#L372-L382 |
||
nodejs/quic | 5baab3f3a05548d3b51bea98868412b08766e34d | tools/inspector_protocol/jinja2/environment.py | python | get_spontaneous_environment | (*args) | return env | Return a new spontaneous environment. A spontaneous environment is an
unnamed and unaccessible (in theory) environment that is used for
templates generated from a string and not from the file system. | Return a new spontaneous environment. A spontaneous environment is an
unnamed and unaccessible (in theory) environment that is used for
templates generated from a string and not from the file system. | [
"Return",
"a",
"new",
"spontaneous",
"environment",
".",
"A",
"spontaneous",
"environment",
"is",
"an",
"unnamed",
"and",
"unaccessible",
"(",
"in",
"theory",
")",
"environment",
"that",
"is",
"used",
"for",
"templates",
"generated",
"from",
"a",
"string",
"and",
"not",
"from",
"the",
"file",
"system",
"."
] | def get_spontaneous_environment(*args):
"""Return a new spontaneous environment. A spontaneous environment is an
unnamed and unaccessible (in theory) environment that is used for
templates generated from a string and not from the file system.
"""
try:
env = _spontaneous_environments.get(args)
except TypeError:
return Environment(*args)
if env is not None:
return env
_spontaneous_environments[args] = env = Environment(*args)
env.shared = True
return env | [
"def",
"get_spontaneous_environment",
"(",
"*",
"args",
")",
":",
"try",
":",
"env",
"=",
"_spontaneous_environments",
".",
"get",
"(",
"args",
")",
"except",
"TypeError",
":",
"return",
"Environment",
"(",
"*",
"args",
")",
"if",
"env",
"is",
"not",
"None",
":",
"return",
"env",
"_spontaneous_environments",
"[",
"args",
"]",
"=",
"env",
"=",
"Environment",
"(",
"*",
"args",
")",
"env",
".",
"shared",
"=",
"True",
"return",
"env"
] | https://github.com/nodejs/quic/blob/5baab3f3a05548d3b51bea98868412b08766e34d/tools/inspector_protocol/jinja2/environment.py#L44-L57 |
|
nodejs/quic | 5baab3f3a05548d3b51bea98868412b08766e34d | tools/inspector_protocol/jinja2/environment.py | python | load_extensions | (environment, extensions) | return result | Load the extensions from the list and bind it to the environment.
Returns a dict of instantiated environments. | Load the extensions from the list and bind it to the environment.
Returns a dict of instantiated environments. | [
"Load",
"the",
"extensions",
"from",
"the",
"list",
"and",
"bind",
"it",
"to",
"the",
"environment",
".",
"Returns",
"a",
"dict",
"of",
"instantiated",
"environments",
"."
] | def load_extensions(environment, extensions):
"""Load the extensions from the list and bind it to the environment.
Returns a dict of instantiated environments.
"""
result = {}
for extension in extensions:
if isinstance(extension, string_types):
extension = import_string(extension)
result[extension.identifier] = extension(environment)
return result | [
"def",
"load_extensions",
"(",
"environment",
",",
"extensions",
")",
":",
"result",
"=",
"{",
"}",
"for",
"extension",
"in",
"extensions",
":",
"if",
"isinstance",
"(",
"extension",
",",
"string_types",
")",
":",
"extension",
"=",
"import_string",
"(",
"extension",
")",
"result",
"[",
"extension",
".",
"identifier",
"]",
"=",
"extension",
"(",
"environment",
")",
"return",
"result"
] | https://github.com/nodejs/quic/blob/5baab3f3a05548d3b51bea98868412b08766e34d/tools/inspector_protocol/jinja2/environment.py#L78-L87 |
|
booktype/Booktype | a1fe45e873ca4381b0eee8ea1b2ee3489b8fbbc2 | lib/booktype/api/security.py | python | BooktypeBookSecurity.has_object_permission | (self, request, view, obj) | return all(perms_list) | Takes the list of required permissions from the view and
check if user has them all | Takes the list of required permissions from the view and
check if user has them all | [
"Takes",
"the",
"list",
"of",
"required",
"permissions",
"from",
"the",
"view",
"and",
"check",
"if",
"user",
"has",
"them",
"all"
] | def has_object_permission(self, request, view, obj):
"""Takes the list of required permissions from the view and
check if user has them all"""
required_perms = self.get_required_perms(view)
if not required_perms:
return True
book_security = security.get_security_for_book(request.user, obj)
perms_list = [book_security.has_perm(x) for x in required_perms]
return all(perms_list) | [
"def",
"has_object_permission",
"(",
"self",
",",
"request",
",",
"view",
",",
"obj",
")",
":",
"required_perms",
"=",
"self",
".",
"get_required_perms",
"(",
"view",
")",
"if",
"not",
"required_perms",
":",
"return",
"True",
"book_security",
"=",
"security",
".",
"get_security_for_book",
"(",
"request",
".",
"user",
",",
"obj",
")",
"perms_list",
"=",
"[",
"book_security",
".",
"has_perm",
"(",
"x",
")",
"for",
"x",
"in",
"required_perms",
"]",
"return",
"all",
"(",
"perms_list",
")"
] | https://github.com/booktype/Booktype/blob/a1fe45e873ca4381b0eee8ea1b2ee3489b8fbbc2/lib/booktype/api/security.py#L79-L90 |
|
redapple0204/my-boring-python | 1ab378e9d4f39ad920ff542ef3b2db68f0575a98 | pythonenv3.8/lib/python3.8/site-packages/pip/_vendor/requests/adapters.py | python | HTTPAdapter.add_headers | (self, request, **kwargs) | Add any headers needed by the connection. As of v2.0 this does
nothing by default, but is left for overriding by users that subclass
the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
This should not be called from user code, and is only exposed for use
when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.
:param kwargs: The keyword arguments from the call to send(). | Add any headers needed by the connection. As of v2.0 this does
nothing by default, but is left for overriding by users that subclass
the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. | [
"Add",
"any",
"headers",
"needed",
"by",
"the",
"connection",
".",
"As",
"of",
"v2",
".",
"0",
"this",
"does",
"nothing",
"by",
"default",
"but",
"is",
"left",
"for",
"overriding",
"by",
"users",
"that",
"subclass",
"the",
":",
"class",
":",
"HTTPAdapter",
"<requests",
".",
"adapters",
".",
"HTTPAdapter",
">",
"."
] | def add_headers(self, request, **kwargs):
"""Add any headers needed by the connection. As of v2.0 this does
nothing by default, but is left for overriding by users that subclass
the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
This should not be called from user code, and is only exposed for use
when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.
:param kwargs: The keyword arguments from the call to send().
"""
pass | [
"def",
"add_headers",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"pass"
] | https://github.com/redapple0204/my-boring-python/blob/1ab378e9d4f39ad920ff542ef3b2db68f0575a98/pythonenv3.8/lib/python3.8/site-packages/pip/_vendor/requests/adapters.py#L358-L370 |
||
mozilla/spidernode | aafa9e5273f954f272bb4382fc007af14674b4c2 | tools/cpplint.py | python | IsBlankLine | (line) | return not line or line.isspace() | Returns true if the given line is blank.
We consider a line to be blank if the line is empty or consists of
only white spaces.
Args:
line: A line of a string.
Returns:
True, if the given line is blank. | Returns true if the given line is blank. | [
"Returns",
"true",
"if",
"the",
"given",
"line",
"is",
"blank",
"."
] | def IsBlankLine(line):
"""Returns true if the given line is blank.
We consider a line to be blank if the line is empty or consists of
only white spaces.
Args:
line: A line of a string.
Returns:
True, if the given line is blank.
"""
return not line or line.isspace() | [
"def",
"IsBlankLine",
"(",
"line",
")",
":",
"return",
"not",
"line",
"or",
"line",
".",
"isspace",
"(",
")"
] | https://github.com/mozilla/spidernode/blob/aafa9e5273f954f272bb4382fc007af14674b4c2/tools/cpplint.py#L2876-L2888 |
|
depjs/dep | cb8def92812d80b1fd8e5ffbbc1ae129a207fff6 | node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py | python | NinjaWriter.ComputeMacBundleOutput | (self) | return self.ExpandSpecial(
os.path.join(path, self.xcode_settings.GetWrapperName())
) | Return the 'output' (full output path) to a bundle output directory. | Return the 'output' (full output path) to a bundle output directory. | [
"Return",
"the",
"output",
"(",
"full",
"output",
"path",
")",
"to",
"a",
"bundle",
"output",
"directory",
"."
] | def ComputeMacBundleOutput(self):
"""Return the 'output' (full output path) to a bundle output directory."""
assert self.is_mac_bundle
path = generator_default_variables["PRODUCT_DIR"]
return self.ExpandSpecial(
os.path.join(path, self.xcode_settings.GetWrapperName())
) | [
"def",
"ComputeMacBundleOutput",
"(",
"self",
")",
":",
"assert",
"self",
".",
"is_mac_bundle",
"path",
"=",
"generator_default_variables",
"[",
"\"PRODUCT_DIR\"",
"]",
"return",
"self",
".",
"ExpandSpecial",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"self",
".",
"xcode_settings",
".",
"GetWrapperName",
"(",
")",
")",
")"
] | https://github.com/depjs/dep/blob/cb8def92812d80b1fd8e5ffbbc1ae129a207fff6/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py#L1786-L1792 |
|
jumpserver/jumpserver | acdde5a236db1bfdb84268a1871b572ef4849974 | apps/common/api.py | python | LogTailApi.filter_line | (self, line) | return line | 过滤行,可能替换一些信息
:param line:
:return: | 过滤行,可能替换一些信息
:param line:
:return: | [
"过滤行,可能替换一些信息",
":",
"param",
"line",
":",
":",
"return",
":"
] | def filter_line(self, line):
"""
过滤行,可能替换一些信息
:param line:
:return:
"""
return line | [
"def",
"filter_line",
"(",
"self",
",",
"line",
")",
":",
"return",
"line"
] | https://github.com/jumpserver/jumpserver/blob/acdde5a236db1bfdb84268a1871b572ef4849974/apps/common/api.py#L50-L56 |
|
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/closured/lib/python2.7/timeit.py | python | Timer.timeit | (self, number=default_number) | return timing | Time 'number' executions of the main statement.
To be precise, this executes the setup statement once, and
then returns the time it takes to execute the main statement
a number of times, as a float measured in seconds. The
argument is the number of times through the loop, defaulting
to one million. The main statement, the setup statement and
the timer function to be used are passed to the constructor. | Time 'number' executions of the main statement. | [
"Time",
"number",
"executions",
"of",
"the",
"main",
"statement",
"."
] | def timeit(self, number=default_number):
"""Time 'number' executions of the main statement.
To be precise, this executes the setup statement once, and
then returns the time it takes to execute the main statement
a number of times, as a float measured in seconds. The
argument is the number of times through the loop, defaulting
to one million. The main statement, the setup statement and
the timer function to be used are passed to the constructor.
"""
if itertools:
it = itertools.repeat(None, number)
else:
it = [None] * number
gcold = gc.isenabled()
gc.disable()
timing = self.inner(it, self.timer)
if gcold:
gc.enable()
return timing | [
"def",
"timeit",
"(",
"self",
",",
"number",
"=",
"default_number",
")",
":",
"if",
"itertools",
":",
"it",
"=",
"itertools",
".",
"repeat",
"(",
"None",
",",
"number",
")",
"else",
":",
"it",
"=",
"[",
"None",
"]",
"*",
"number",
"gcold",
"=",
"gc",
".",
"isenabled",
"(",
")",
"gc",
".",
"disable",
"(",
")",
"timing",
"=",
"self",
".",
"inner",
"(",
"it",
",",
"self",
".",
"timer",
")",
"if",
"gcold",
":",
"gc",
".",
"enable",
"(",
")",
"return",
"timing"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/closured/lib/python2.7/timeit.py#L178-L197 |
|
booktype/Booktype | a1fe45e873ca4381b0eee8ea1b2ee3489b8fbbc2 | lib/booki/editor/views.py | python | upload_cover | (request, bookid, version=None) | return HttpResponse('<html><body><script> parent.jQuery.booki.editor.showCovers(); </script></body></html>') | Uploades attachments. Used from Upload dialog.
@param request: Django Request
@param bookid: Book ID
@param version: Book version or None | Uploades attachments. Used from Upload dialog. | [
"Uploades",
"attachments",
".",
"Used",
"from",
"Upload",
"dialog",
"."
] | def upload_cover(request, bookid, version=None):
"""
Uploades attachments. Used from Upload dialog.
@param request: Django Request
@param bookid: Book ID
@param version: Book version or None
"""
import datetime
try:
book = models.Book.objects.get(url_title__iexact=bookid)
except models.Book.DoesNotExist:
return views.ErrorPage(request, "errors/book_does_not_exist.html", {"book_name": bookid})
book_version = book.getVersion(version)
stat = models.BookStatus.objects.filter(book = book)[0]
operationResult = True
# check this for transactions
try:
for name, fileData in request.FILES.items():
if True:
import hashlib
h = hashlib.sha1()
h.update(unidecode.unidecode(name))
h.update(request.POST.get('format', ''))
h.update(request.POST.get('license', ''))
h.update(str(datetime.datetime.now()))
license = models.License.objects.get(abbrevation=request.POST.get('license', ''))
frm = request.POST.get('format', '').split(',')
try:
width = int(request.POST.get('width', '0'))
except ValueError:
width = 0
try:
height = int(request.POST.get('height', '0'))
except ValueError:
height = 0
import unidecode
try:
filename = unidecode.unidecode(request.FILES[name].name)
except:
filename = ''
title = request.POST.get('title', '').strip()[:250]
cov = models.BookCover(book = book,
user = request.user,
cid = h.hexdigest(),
title = title,
filename = filename[:250],
width = width,
height = height,
unit = request.POST.get('unit', 'mm'),
booksize = request.POST.get('booksize', ''),
cover_type = request.POST.get('type', ''),
creator = request.POST.get('creator', '')[:40],
license = license,
notes = request.POST.get('notes', '')[:500],
approved = False,
is_book = 'book' in frm,
is_ebook = 'ebook' in frm,
is_pdf = 'pdf' in frm,
created = datetime.datetime.now())
cov.save()
cov.attachment.save(request.FILES[name].name, fileData, save = False)
cov.save()
from booki.utils import log
log.logBookHistory(book = book,
version = book_version,
args = {'filename': filename[:250], 'title': title, 'cid': cov.pk},
user = request.user,
kind = 'cover_upload'
)
# TODO:
# must write info about this to log!
except IOError:
operationResult = False
transaction.rollback()
except:
from booki.utils import log
log.printStack()
oprerationResult = False
transaction.rollback()
else:
# maybe check file name now and save with new name
transaction.commit()
return HttpResponse('<html><body><script> parent.jQuery.booki.editor.showCovers(); </script></body></html>') | [
"def",
"upload_cover",
"(",
"request",
",",
"bookid",
",",
"version",
"=",
"None",
")",
":",
"import",
"datetime",
"try",
":",
"book",
"=",
"models",
".",
"Book",
".",
"objects",
".",
"get",
"(",
"url_title__iexact",
"=",
"bookid",
")",
"except",
"models",
".",
"Book",
".",
"DoesNotExist",
":",
"return",
"views",
".",
"ErrorPage",
"(",
"request",
",",
"\"errors/book_does_not_exist.html\"",
",",
"{",
"\"book_name\"",
":",
"bookid",
"}",
")",
"book_version",
"=",
"book",
".",
"getVersion",
"(",
"version",
")",
"stat",
"=",
"models",
".",
"BookStatus",
".",
"objects",
".",
"filter",
"(",
"book",
"=",
"book",
")",
"[",
"0",
"]",
"operationResult",
"=",
"True",
"# check this for transactions",
"try",
":",
"for",
"name",
",",
"fileData",
"in",
"request",
".",
"FILES",
".",
"items",
"(",
")",
":",
"if",
"True",
":",
"import",
"hashlib",
"h",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"h",
".",
"update",
"(",
"unidecode",
".",
"unidecode",
"(",
"name",
")",
")",
"h",
".",
"update",
"(",
"request",
".",
"POST",
".",
"get",
"(",
"'format'",
",",
"''",
")",
")",
"h",
".",
"update",
"(",
"request",
".",
"POST",
".",
"get",
"(",
"'license'",
",",
"''",
")",
")",
"h",
".",
"update",
"(",
"str",
"(",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
")",
")",
"license",
"=",
"models",
".",
"License",
".",
"objects",
".",
"get",
"(",
"abbrevation",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"'license'",
",",
"''",
")",
")",
"frm",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"'format'",
",",
"''",
")",
".",
"split",
"(",
"','",
")",
"try",
":",
"width",
"=",
"int",
"(",
"request",
".",
"POST",
".",
"get",
"(",
"'width'",
",",
"'0'",
")",
")",
"except",
"ValueError",
":",
"width",
"=",
"0",
"try",
":",
"height",
"=",
"int",
"(",
"request",
".",
"POST",
".",
"get",
"(",
"'height'",
",",
"'0'",
")",
")",
"except",
"ValueError",
":",
"height",
"=",
"0",
"import",
"unidecode",
"try",
":",
"filename",
"=",
"unidecode",
".",
"unidecode",
"(",
"request",
".",
"FILES",
"[",
"name",
"]",
".",
"name",
")",
"except",
":",
"filename",
"=",
"''",
"title",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"'title'",
",",
"''",
")",
".",
"strip",
"(",
")",
"[",
":",
"250",
"]",
"cov",
"=",
"models",
".",
"BookCover",
"(",
"book",
"=",
"book",
",",
"user",
"=",
"request",
".",
"user",
",",
"cid",
"=",
"h",
".",
"hexdigest",
"(",
")",
",",
"title",
"=",
"title",
",",
"filename",
"=",
"filename",
"[",
":",
"250",
"]",
",",
"width",
"=",
"width",
",",
"height",
"=",
"height",
",",
"unit",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"'unit'",
",",
"'mm'",
")",
",",
"booksize",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"'booksize'",
",",
"''",
")",
",",
"cover_type",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"'type'",
",",
"''",
")",
",",
"creator",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"'creator'",
",",
"''",
")",
"[",
":",
"40",
"]",
",",
"license",
"=",
"license",
",",
"notes",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"'notes'",
",",
"''",
")",
"[",
":",
"500",
"]",
",",
"approved",
"=",
"False",
",",
"is_book",
"=",
"'book'",
"in",
"frm",
",",
"is_ebook",
"=",
"'ebook'",
"in",
"frm",
",",
"is_pdf",
"=",
"'pdf'",
"in",
"frm",
",",
"created",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
")",
"cov",
".",
"save",
"(",
")",
"cov",
".",
"attachment",
".",
"save",
"(",
"request",
".",
"FILES",
"[",
"name",
"]",
".",
"name",
",",
"fileData",
",",
"save",
"=",
"False",
")",
"cov",
".",
"save",
"(",
")",
"from",
"booki",
".",
"utils",
"import",
"log",
"log",
".",
"logBookHistory",
"(",
"book",
"=",
"book",
",",
"version",
"=",
"book_version",
",",
"args",
"=",
"{",
"'filename'",
":",
"filename",
"[",
":",
"250",
"]",
",",
"'title'",
":",
"title",
",",
"'cid'",
":",
"cov",
".",
"pk",
"}",
",",
"user",
"=",
"request",
".",
"user",
",",
"kind",
"=",
"'cover_upload'",
")",
"# TODO:",
"# must write info about this to log!",
"except",
"IOError",
":",
"operationResult",
"=",
"False",
"transaction",
".",
"rollback",
"(",
")",
"except",
":",
"from",
"booki",
".",
"utils",
"import",
"log",
"log",
".",
"printStack",
"(",
")",
"oprerationResult",
"=",
"False",
"transaction",
".",
"rollback",
"(",
")",
"else",
":",
"# maybe check file name now and save with new name",
"transaction",
".",
"commit",
"(",
")",
"return",
"HttpResponse",
"(",
"'<html><body><script> parent.jQuery.booki.editor.showCovers(); </script></body></html>'",
")"
] | https://github.com/booktype/Booktype/blob/a1fe45e873ca4381b0eee8ea1b2ee3489b8fbbc2/lib/booki/editor/views.py#L345-L450 |
|
nodejs/node | ac3c33c1646bf46104c15ae035982c06364da9b8 | tools/gyp/pylib/gyp/win_tool.py | python | WinTool.ExecLinkWrapper | (self, arch, use_separate_mspdbsrv, *args) | return link.returncode | Filter diagnostic output from link that looks like:
' Creating library ui.dll.lib and object ui.dll.exp'
This happens when there are exports from the dll or exe. | Filter diagnostic output from link that looks like:
' Creating library ui.dll.lib and object ui.dll.exp'
This happens when there are exports from the dll or exe. | [
"Filter",
"diagnostic",
"output",
"from",
"link",
"that",
"looks",
"like",
":",
"Creating",
"library",
"ui",
".",
"dll",
".",
"lib",
"and",
"object",
"ui",
".",
"dll",
".",
"exp",
"This",
"happens",
"when",
"there",
"are",
"exports",
"from",
"the",
"dll",
"or",
"exe",
"."
] | def ExecLinkWrapper(self, arch, use_separate_mspdbsrv, *args):
"""Filter diagnostic output from link that looks like:
' Creating library ui.dll.lib and object ui.dll.exp'
This happens when there are exports from the dll or exe.
"""
env = self._GetEnv(arch)
if use_separate_mspdbsrv == "True":
self._UseSeparateMspdbsrv(env, args)
if sys.platform == "win32":
args = list(args) # *args is a tuple by default, which is read-only.
args[0] = args[0].replace("/", "\\")
# https://docs.python.org/2/library/subprocess.html:
# "On Unix with shell=True [...] if args is a sequence, the first item
# specifies the command string, and any additional items will be treated as
# additional arguments to the shell itself. That is to say, Popen does the
# equivalent of:
# Popen(['/bin/sh', '-c', args[0], args[1], ...])"
# For that reason, since going through the shell doesn't seem necessary on
# non-Windows don't do that there.
link = subprocess.Popen(
args,
shell=sys.platform == "win32",
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
out = link.communicate()[0].decode("utf-8")
for line in out.splitlines():
if (
not line.startswith(" Creating library ")
and not line.startswith("Generating code")
and not line.startswith("Finished generating code")
):
print(line)
return link.returncode | [
"def",
"ExecLinkWrapper",
"(",
"self",
",",
"arch",
",",
"use_separate_mspdbsrv",
",",
"*",
"args",
")",
":",
"env",
"=",
"self",
".",
"_GetEnv",
"(",
"arch",
")",
"if",
"use_separate_mspdbsrv",
"==",
"\"True\"",
":",
"self",
".",
"_UseSeparateMspdbsrv",
"(",
"env",
",",
"args",
")",
"if",
"sys",
".",
"platform",
"==",
"\"win32\"",
":",
"args",
"=",
"list",
"(",
"args",
")",
"# *args is a tuple by default, which is read-only.",
"args",
"[",
"0",
"]",
"=",
"args",
"[",
"0",
"]",
".",
"replace",
"(",
"\"/\"",
",",
"\"\\\\\"",
")",
"# https://docs.python.org/2/library/subprocess.html:",
"# \"On Unix with shell=True [...] if args is a sequence, the first item",
"# specifies the command string, and any additional items will be treated as",
"# additional arguments to the shell itself. That is to say, Popen does the",
"# equivalent of:",
"# Popen(['/bin/sh', '-c', args[0], args[1], ...])\"",
"# For that reason, since going through the shell doesn't seem necessary on",
"# non-Windows don't do that there.",
"link",
"=",
"subprocess",
".",
"Popen",
"(",
"args",
",",
"shell",
"=",
"sys",
".",
"platform",
"==",
"\"win32\"",
",",
"env",
"=",
"env",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
",",
")",
"out",
"=",
"link",
".",
"communicate",
"(",
")",
"[",
"0",
"]",
".",
"decode",
"(",
"\"utf-8\"",
")",
"for",
"line",
"in",
"out",
".",
"splitlines",
"(",
")",
":",
"if",
"(",
"not",
"line",
".",
"startswith",
"(",
"\" Creating library \"",
")",
"and",
"not",
"line",
".",
"startswith",
"(",
"\"Generating code\"",
")",
"and",
"not",
"line",
".",
"startswith",
"(",
"\"Finished generating code\"",
")",
")",
":",
"print",
"(",
"line",
")",
"return",
"link",
".",
"returncode"
] | https://github.com/nodejs/node/blob/ac3c33c1646bf46104c15ae035982c06364da9b8/tools/gyp/pylib/gyp/win_tool.py#L116-L150 |
|
Southpaw-TACTIC/TACTIC | ba9b87aef0ee3b3ea51446f25b285ebbca06f62c | 3rd_party/python3/site-packages/dateutil/tz/win.py | python | valuestodict | (key) | return dout | Convert a registry key's values to a dictionary. | Convert a registry key's values to a dictionary. | [
"Convert",
"a",
"registry",
"key",
"s",
"values",
"to",
"a",
"dictionary",
"."
] | def valuestodict(key):
"""Convert a registry key's values to a dictionary."""
dout = {}
size = winreg.QueryInfoKey(key)[1]
tz_res = None
for i in range(size):
key_name, value, dtype = winreg.EnumValue(key, i)
if dtype == winreg.REG_DWORD or dtype == winreg.REG_DWORD_LITTLE_ENDIAN:
# If it's a DWORD (32-bit integer), it's stored as unsigned - convert
# that to a proper signed integer
if value & (1 << 31):
value = value - (1 << 32)
elif dtype == winreg.REG_SZ:
# If it's a reference to the tzres DLL, load the actual string
if value.startswith('@tzres'):
tz_res = tz_res or tzres()
value = tz_res.name_from_string(value)
value = value.rstrip('\x00') # Remove trailing nulls
dout[key_name] = value
return dout | [
"def",
"valuestodict",
"(",
"key",
")",
":",
"dout",
"=",
"{",
"}",
"size",
"=",
"winreg",
".",
"QueryInfoKey",
"(",
"key",
")",
"[",
"1",
"]",
"tz_res",
"=",
"None",
"for",
"i",
"in",
"range",
"(",
"size",
")",
":",
"key_name",
",",
"value",
",",
"dtype",
"=",
"winreg",
".",
"EnumValue",
"(",
"key",
",",
"i",
")",
"if",
"dtype",
"==",
"winreg",
".",
"REG_DWORD",
"or",
"dtype",
"==",
"winreg",
".",
"REG_DWORD_LITTLE_ENDIAN",
":",
"# If it's a DWORD (32-bit integer), it's stored as unsigned - convert",
"# that to a proper signed integer",
"if",
"value",
"&",
"(",
"1",
"<<",
"31",
")",
":",
"value",
"=",
"value",
"-",
"(",
"1",
"<<",
"32",
")",
"elif",
"dtype",
"==",
"winreg",
".",
"REG_SZ",
":",
"# If it's a reference to the tzres DLL, load the actual string",
"if",
"value",
".",
"startswith",
"(",
"'@tzres'",
")",
":",
"tz_res",
"=",
"tz_res",
"or",
"tzres",
"(",
")",
"value",
"=",
"tz_res",
".",
"name_from_string",
"(",
"value",
")",
"value",
"=",
"value",
".",
"rstrip",
"(",
"'\\x00'",
")",
"# Remove trailing nulls",
"dout",
"[",
"key_name",
"]",
"=",
"value",
"return",
"dout"
] | https://github.com/Southpaw-TACTIC/TACTIC/blob/ba9b87aef0ee3b3ea51446f25b285ebbca06f62c/3rd_party/python3/site-packages/dateutil/tz/win.py#L347-L370 |
|
googlearchive/ChromeWebLab | 60f964b3f283c15704b7a04b7bb50cb15791e2e4 | Sketchbots/sw/labqueue/pytz/tzinfo.py | python | StaticTzInfo.normalize | (self, dt, is_dst=False) | return dt.replace(tzinfo=self) | Correct the timezone information on the given datetime | Correct the timezone information on the given datetime | [
"Correct",
"the",
"timezone",
"information",
"on",
"the",
"given",
"datetime"
] | def normalize(self, dt, is_dst=False):
'''Correct the timezone information on the given datetime'''
if dt.tzinfo is None:
raise ValueError, 'Naive time - no tzinfo set'
return dt.replace(tzinfo=self) | [
"def",
"normalize",
"(",
"self",
",",
"dt",
",",
"is_dst",
"=",
"False",
")",
":",
"if",
"dt",
".",
"tzinfo",
"is",
"None",
":",
"raise",
"ValueError",
",",
"'Naive time - no tzinfo set'",
"return",
"dt",
".",
"replace",
"(",
"tzinfo",
"=",
"self",
")"
] | https://github.com/googlearchive/ChromeWebLab/blob/60f964b3f283c15704b7a04b7bb50cb15791e2e4/Sketchbots/sw/labqueue/pytz/tzinfo.py#L120-L124 |
|
nodejs/node-convergence-archive | e11fe0c2777561827cdb7207d46b0917ef3c42a7 | tools/gyp/pylib/gyp/xcode_emulation.py | python | GetXcodeArchsDefault | () | return XCODE_ARCHS_DEFAULT_CACHE | Returns the |XcodeArchsDefault| object to use to expand ARCHS for the
installed version of Xcode. The default values used by Xcode for ARCHS
and the expansion of the variables depends on the version of Xcode used.
For all version anterior to Xcode 5.0 or posterior to Xcode 5.1 included
uses $(ARCHS_STANDARD) if ARCHS is unset, while Xcode 5.0 to 5.0.2 uses
$(ARCHS_STANDARD_INCLUDING_64_BIT). This variable was added to Xcode 5.0
and deprecated with Xcode 5.1.
For "macosx" SDKROOT, all version starting with Xcode 5.0 includes 64-bit
architecture as part of $(ARCHS_STANDARD) and default to only building it.
For "iphoneos" and "iphonesimulator" SDKROOT, 64-bit architectures are part
of $(ARCHS_STANDARD_INCLUDING_64_BIT) from Xcode 5.0. From Xcode 5.1, they
are also part of $(ARCHS_STANDARD).
All thoses rules are coded in the construction of the |XcodeArchsDefault|
object to use depending on the version of Xcode detected. The object is
for performance reason. | Returns the |XcodeArchsDefault| object to use to expand ARCHS for the
installed version of Xcode. The default values used by Xcode for ARCHS
and the expansion of the variables depends on the version of Xcode used. | [
"Returns",
"the",
"|XcodeArchsDefault|",
"object",
"to",
"use",
"to",
"expand",
"ARCHS",
"for",
"the",
"installed",
"version",
"of",
"Xcode",
".",
"The",
"default",
"values",
"used",
"by",
"Xcode",
"for",
"ARCHS",
"and",
"the",
"expansion",
"of",
"the",
"variables",
"depends",
"on",
"the",
"version",
"of",
"Xcode",
"used",
"."
] | def GetXcodeArchsDefault():
"""Returns the |XcodeArchsDefault| object to use to expand ARCHS for the
installed version of Xcode. The default values used by Xcode for ARCHS
and the expansion of the variables depends on the version of Xcode used.
For all version anterior to Xcode 5.0 or posterior to Xcode 5.1 included
uses $(ARCHS_STANDARD) if ARCHS is unset, while Xcode 5.0 to 5.0.2 uses
$(ARCHS_STANDARD_INCLUDING_64_BIT). This variable was added to Xcode 5.0
and deprecated with Xcode 5.1.
For "macosx" SDKROOT, all version starting with Xcode 5.0 includes 64-bit
architecture as part of $(ARCHS_STANDARD) and default to only building it.
For "iphoneos" and "iphonesimulator" SDKROOT, 64-bit architectures are part
of $(ARCHS_STANDARD_INCLUDING_64_BIT) from Xcode 5.0. From Xcode 5.1, they
are also part of $(ARCHS_STANDARD).
All thoses rules are coded in the construction of the |XcodeArchsDefault|
object to use depending on the version of Xcode detected. The object is
for performance reason."""
global XCODE_ARCHS_DEFAULT_CACHE
if XCODE_ARCHS_DEFAULT_CACHE:
return XCODE_ARCHS_DEFAULT_CACHE
xcode_version, _ = XcodeVersion()
if xcode_version < '0500':
XCODE_ARCHS_DEFAULT_CACHE = XcodeArchsDefault(
'$(ARCHS_STANDARD)',
XcodeArchsVariableMapping(['i386']),
XcodeArchsVariableMapping(['i386']),
XcodeArchsVariableMapping(['armv7']))
elif xcode_version < '0510':
XCODE_ARCHS_DEFAULT_CACHE = XcodeArchsDefault(
'$(ARCHS_STANDARD_INCLUDING_64_BIT)',
XcodeArchsVariableMapping(['x86_64'], ['x86_64']),
XcodeArchsVariableMapping(['i386'], ['i386', 'x86_64']),
XcodeArchsVariableMapping(
['armv7', 'armv7s'],
['armv7', 'armv7s', 'arm64']))
else:
XCODE_ARCHS_DEFAULT_CACHE = XcodeArchsDefault(
'$(ARCHS_STANDARD)',
XcodeArchsVariableMapping(['x86_64'], ['x86_64']),
XcodeArchsVariableMapping(['i386', 'x86_64'], ['i386', 'x86_64']),
XcodeArchsVariableMapping(
['armv7', 'armv7s', 'arm64'],
['armv7', 'armv7s', 'arm64']))
return XCODE_ARCHS_DEFAULT_CACHE | [
"def",
"GetXcodeArchsDefault",
"(",
")",
":",
"global",
"XCODE_ARCHS_DEFAULT_CACHE",
"if",
"XCODE_ARCHS_DEFAULT_CACHE",
":",
"return",
"XCODE_ARCHS_DEFAULT_CACHE",
"xcode_version",
",",
"_",
"=",
"XcodeVersion",
"(",
")",
"if",
"xcode_version",
"<",
"'0500'",
":",
"XCODE_ARCHS_DEFAULT_CACHE",
"=",
"XcodeArchsDefault",
"(",
"'$(ARCHS_STANDARD)'",
",",
"XcodeArchsVariableMapping",
"(",
"[",
"'i386'",
"]",
")",
",",
"XcodeArchsVariableMapping",
"(",
"[",
"'i386'",
"]",
")",
",",
"XcodeArchsVariableMapping",
"(",
"[",
"'armv7'",
"]",
")",
")",
"elif",
"xcode_version",
"<",
"'0510'",
":",
"XCODE_ARCHS_DEFAULT_CACHE",
"=",
"XcodeArchsDefault",
"(",
"'$(ARCHS_STANDARD_INCLUDING_64_BIT)'",
",",
"XcodeArchsVariableMapping",
"(",
"[",
"'x86_64'",
"]",
",",
"[",
"'x86_64'",
"]",
")",
",",
"XcodeArchsVariableMapping",
"(",
"[",
"'i386'",
"]",
",",
"[",
"'i386'",
",",
"'x86_64'",
"]",
")",
",",
"XcodeArchsVariableMapping",
"(",
"[",
"'armv7'",
",",
"'armv7s'",
"]",
",",
"[",
"'armv7'",
",",
"'armv7s'",
",",
"'arm64'",
"]",
")",
")",
"else",
":",
"XCODE_ARCHS_DEFAULT_CACHE",
"=",
"XcodeArchsDefault",
"(",
"'$(ARCHS_STANDARD)'",
",",
"XcodeArchsVariableMapping",
"(",
"[",
"'x86_64'",
"]",
",",
"[",
"'x86_64'",
"]",
")",
",",
"XcodeArchsVariableMapping",
"(",
"[",
"'i386'",
",",
"'x86_64'",
"]",
",",
"[",
"'i386'",
",",
"'x86_64'",
"]",
")",
",",
"XcodeArchsVariableMapping",
"(",
"[",
"'armv7'",
",",
"'armv7s'",
",",
"'arm64'",
"]",
",",
"[",
"'armv7'",
",",
"'armv7s'",
",",
"'arm64'",
"]",
")",
")",
"return",
"XCODE_ARCHS_DEFAULT_CACHE"
] | https://github.com/nodejs/node-convergence-archive/blob/e11fe0c2777561827cdb7207d46b0917ef3c42a7/tools/gyp/pylib/gyp/xcode_emulation.py#L95-L141 |
|
stdlib-js/stdlib | e3c14dd9a7985ed1cd1cc80e83b6659aeabeb7df | lib/node_modules/@stdlib/math/base/special/beta/benchmark/python/scipy/benchmark.py | python | print_summary | (total, passing) | Print the benchmark summary.
# Arguments
* `total`: total number of tests
* `passing`: number of passing tests | Print the benchmark summary. | [
"Print",
"the",
"benchmark",
"summary",
"."
] | def print_summary(total, passing):
"""Print the benchmark summary.
# Arguments
* `total`: total number of tests
* `passing`: number of passing tests
"""
print("#")
print("1.." + str(total)) # TAP plan
print("# total " + str(total))
print("# pass " + str(passing))
print("#")
print("# ok") | [
"def",
"print_summary",
"(",
"total",
",",
"passing",
")",
":",
"print",
"(",
"\"#\"",
")",
"print",
"(",
"\"1..\"",
"+",
"str",
"(",
"total",
")",
")",
"# TAP plan",
"print",
"(",
"\"# total \"",
"+",
"str",
"(",
"total",
")",
")",
"print",
"(",
"\"# pass \"",
"+",
"str",
"(",
"passing",
")",
")",
"print",
"(",
"\"#\"",
")",
"print",
"(",
"\"# ok\"",
")"
] | https://github.com/stdlib-js/stdlib/blob/e3c14dd9a7985ed1cd1cc80e83b6659aeabeb7df/lib/node_modules/@stdlib/math/base/special/beta/benchmark/python/scipy/benchmark.py#L34-L48 |
||
odoo/odoo | 8de8c196a137f4ebbf67d7c7c83fee36f873f5c8 | addons/pad/py_etherpad/__init__.py | python | EtherpadLiteClient.createGroup | (self) | return self.call("createGroup") | creates a new group | creates a new group | [
"creates",
"a",
"new",
"group"
] | def createGroup(self):
"""creates a new group"""
return self.call("createGroup") | [
"def",
"createGroup",
"(",
"self",
")",
":",
"return",
"self",
".",
"call",
"(",
"\"createGroup\"",
")"
] | https://github.com/odoo/odoo/blob/8de8c196a137f4ebbf67d7c7c83fee36f873f5c8/addons/pad/py_etherpad/__init__.py#L66-L68 |
|
GoogleCloudPlatform/PerfKitExplorer | 9efa61015d50c25f6d753f0212ad3bf16876d496 | third_party/py/httplib2/socks.py | python | socksocket.connect | (self, destpair) | connect(self, despair)
Connects to the specified destination through a proxy.
destpar - A tuple of the IP/DNS address and the port number.
(identical to socket's connect).
To select the proxy server use setproxy(). | connect(self, despair)
Connects to the specified destination through a proxy.
destpar - A tuple of the IP/DNS address and the port number.
(identical to socket's connect).
To select the proxy server use setproxy(). | [
"connect",
"(",
"self",
"despair",
")",
"Connects",
"to",
"the",
"specified",
"destination",
"through",
"a",
"proxy",
".",
"destpar",
"-",
"A",
"tuple",
"of",
"the",
"IP",
"/",
"DNS",
"address",
"and",
"the",
"port",
"number",
".",
"(",
"identical",
"to",
"socket",
"s",
"connect",
")",
".",
"To",
"select",
"the",
"proxy",
"server",
"use",
"setproxy",
"()",
"."
] | def connect(self, destpair):
"""connect(self, despair)
Connects to the specified destination through a proxy.
destpar - A tuple of the IP/DNS address and the port number.
(identical to socket's connect).
To select the proxy server use setproxy().
"""
# Do a minimal input check first
if (not type(destpair) in (list,tuple)) or (len(destpair) < 2) or (not isinstance(destpair[0], basestring)) or (type(destpair[1]) != int):
raise GeneralProxyError((5, _generalerrors[5]))
if self.__proxy[0] == PROXY_TYPE_SOCKS5:
if self.__proxy[2] != None:
portnum = self.__proxy[2]
else:
portnum = 1080
_orgsocket.connect(self, (self.__proxy[1], portnum))
self.__negotiatesocks5(destpair[0], destpair[1])
elif self.__proxy[0] == PROXY_TYPE_SOCKS4:
if self.__proxy[2] != None:
portnum = self.__proxy[2]
else:
portnum = 1080
_orgsocket.connect(self,(self.__proxy[1], portnum))
self.__negotiatesocks4(destpair[0], destpair[1])
elif self.__proxy[0] == PROXY_TYPE_HTTP:
if self.__proxy[2] != None:
portnum = self.__proxy[2]
else:
portnum = 8080
_orgsocket.connect(self,(self.__proxy[1], portnum))
self.__negotiatehttp(destpair[0], destpair[1])
elif self.__proxy[0] == PROXY_TYPE_HTTP_NO_TUNNEL:
if self.__proxy[2] != None:
portnum = self.__proxy[2]
else:
portnum = 8080
_orgsocket.connect(self,(self.__proxy[1],portnum))
if destpair[1] == 443:
self.__negotiatehttp(destpair[0],destpair[1])
else:
self.__httptunnel = False
elif self.__proxy[0] == None:
_orgsocket.connect(self, (destpair[0], destpair[1]))
else:
raise GeneralProxyError((4, _generalerrors[4])) | [
"def",
"connect",
"(",
"self",
",",
"destpair",
")",
":",
"# Do a minimal input check first",
"if",
"(",
"not",
"type",
"(",
"destpair",
")",
"in",
"(",
"list",
",",
"tuple",
")",
")",
"or",
"(",
"len",
"(",
"destpair",
")",
"<",
"2",
")",
"or",
"(",
"not",
"isinstance",
"(",
"destpair",
"[",
"0",
"]",
",",
"basestring",
")",
")",
"or",
"(",
"type",
"(",
"destpair",
"[",
"1",
"]",
")",
"!=",
"int",
")",
":",
"raise",
"GeneralProxyError",
"(",
"(",
"5",
",",
"_generalerrors",
"[",
"5",
"]",
")",
")",
"if",
"self",
".",
"__proxy",
"[",
"0",
"]",
"==",
"PROXY_TYPE_SOCKS5",
":",
"if",
"self",
".",
"__proxy",
"[",
"2",
"]",
"!=",
"None",
":",
"portnum",
"=",
"self",
".",
"__proxy",
"[",
"2",
"]",
"else",
":",
"portnum",
"=",
"1080",
"_orgsocket",
".",
"connect",
"(",
"self",
",",
"(",
"self",
".",
"__proxy",
"[",
"1",
"]",
",",
"portnum",
")",
")",
"self",
".",
"__negotiatesocks5",
"(",
"destpair",
"[",
"0",
"]",
",",
"destpair",
"[",
"1",
"]",
")",
"elif",
"self",
".",
"__proxy",
"[",
"0",
"]",
"==",
"PROXY_TYPE_SOCKS4",
":",
"if",
"self",
".",
"__proxy",
"[",
"2",
"]",
"!=",
"None",
":",
"portnum",
"=",
"self",
".",
"__proxy",
"[",
"2",
"]",
"else",
":",
"portnum",
"=",
"1080",
"_orgsocket",
".",
"connect",
"(",
"self",
",",
"(",
"self",
".",
"__proxy",
"[",
"1",
"]",
",",
"portnum",
")",
")",
"self",
".",
"__negotiatesocks4",
"(",
"destpair",
"[",
"0",
"]",
",",
"destpair",
"[",
"1",
"]",
")",
"elif",
"self",
".",
"__proxy",
"[",
"0",
"]",
"==",
"PROXY_TYPE_HTTP",
":",
"if",
"self",
".",
"__proxy",
"[",
"2",
"]",
"!=",
"None",
":",
"portnum",
"=",
"self",
".",
"__proxy",
"[",
"2",
"]",
"else",
":",
"portnum",
"=",
"8080",
"_orgsocket",
".",
"connect",
"(",
"self",
",",
"(",
"self",
".",
"__proxy",
"[",
"1",
"]",
",",
"portnum",
")",
")",
"self",
".",
"__negotiatehttp",
"(",
"destpair",
"[",
"0",
"]",
",",
"destpair",
"[",
"1",
"]",
")",
"elif",
"self",
".",
"__proxy",
"[",
"0",
"]",
"==",
"PROXY_TYPE_HTTP_NO_TUNNEL",
":",
"if",
"self",
".",
"__proxy",
"[",
"2",
"]",
"!=",
"None",
":",
"portnum",
"=",
"self",
".",
"__proxy",
"[",
"2",
"]",
"else",
":",
"portnum",
"=",
"8080",
"_orgsocket",
".",
"connect",
"(",
"self",
",",
"(",
"self",
".",
"__proxy",
"[",
"1",
"]",
",",
"portnum",
")",
")",
"if",
"destpair",
"[",
"1",
"]",
"==",
"443",
":",
"self",
".",
"__negotiatehttp",
"(",
"destpair",
"[",
"0",
"]",
",",
"destpair",
"[",
"1",
"]",
")",
"else",
":",
"self",
".",
"__httptunnel",
"=",
"False",
"elif",
"self",
".",
"__proxy",
"[",
"0",
"]",
"==",
"None",
":",
"_orgsocket",
".",
"connect",
"(",
"self",
",",
"(",
"destpair",
"[",
"0",
"]",
",",
"destpair",
"[",
"1",
"]",
")",
")",
"else",
":",
"raise",
"GeneralProxyError",
"(",
"(",
"4",
",",
"_generalerrors",
"[",
"4",
"]",
")",
")"
] | https://github.com/GoogleCloudPlatform/PerfKitExplorer/blob/9efa61015d50c25f6d753f0212ad3bf16876d496/third_party/py/httplib2/socks.py#L394-L438 |
||
zhouxinkai/awesome-python3-webapp | 3535cb65e7b4acaca31a4c32a8ca706d6d6253f3 | www/markdown2.py | python | Markdown._find_balanced | (self, text, start, open_c, close_c) | return i | Returns the index where the open_c and close_c characters balance
out - the same number of open_c and close_c are encountered - or the
end of string if it's reached before the balance point is found. | Returns the index where the open_c and close_c characters balance
out - the same number of open_c and close_c are encountered - or the
end of string if it's reached before the balance point is found. | [
"Returns",
"the",
"index",
"where",
"the",
"open_c",
"and",
"close_c",
"characters",
"balance",
"out",
"-",
"the",
"same",
"number",
"of",
"open_c",
"and",
"close_c",
"are",
"encountered",
"-",
"or",
"the",
"end",
"of",
"string",
"if",
"it",
"s",
"reached",
"before",
"the",
"balance",
"point",
"is",
"found",
"."
] | def _find_balanced(self, text, start, open_c, close_c):
"""Returns the index where the open_c and close_c characters balance
out - the same number of open_c and close_c are encountered - or the
end of string if it's reached before the balance point is found.
"""
i = start
l = len(text)
count = 1
while count > 0 and i < l:
if text[i] == open_c:
count += 1
elif text[i] == close_c:
count -= 1
i += 1
return i | [
"def",
"_find_balanced",
"(",
"self",
",",
"text",
",",
"start",
",",
"open_c",
",",
"close_c",
")",
":",
"i",
"=",
"start",
"l",
"=",
"len",
"(",
"text",
")",
"count",
"=",
"1",
"while",
"count",
">",
"0",
"and",
"i",
"<",
"l",
":",
"if",
"text",
"[",
"i",
"]",
"==",
"open_c",
":",
"count",
"+=",
"1",
"elif",
"text",
"[",
"i",
"]",
"==",
"close_c",
":",
"count",
"-=",
"1",
"i",
"+=",
"1",
"return",
"i"
] | https://github.com/zhouxinkai/awesome-python3-webapp/blob/3535cb65e7b4acaca31a4c32a8ca706d6d6253f3/www/markdown2.py#L1105-L1119 |
|
zhao94254/fun | 491acf6a7d9594f91a8cd717a403d9e1e5d0f386 | pweb/server/pweb.py | python | Response.delete_cookie | (self, key, path='/', domain=None) | 删掉cookie | 删掉cookie | [
"删掉cookie"
] | def delete_cookie(self, key, path='/', domain=None):
"""删掉cookie"""
self.set_cookie(key, expires=0, max_age=0, path=path, domain=domain) | [
"def",
"delete_cookie",
"(",
"self",
",",
"key",
",",
"path",
"=",
"'/'",
",",
"domain",
"=",
"None",
")",
":",
"self",
".",
"set_cookie",
"(",
"key",
",",
"expires",
"=",
"0",
",",
"max_age",
"=",
"0",
",",
"path",
"=",
"path",
",",
"domain",
"=",
"domain",
")"
] | https://github.com/zhao94254/fun/blob/491acf6a7d9594f91a8cd717a403d9e1e5d0f386/pweb/server/pweb.py#L444-L446 |
||
Unmanic/unmanic | 655b18b5fd80c814e45ec38929d1046da93114c3 | unmanic/libs/foreman.py | python | Foreman.update_remote_worker_availability_status | (self) | Updates the list of available remote managers that can be started
:return: | Updates the list of available remote managers that can be started | [
"Updates",
"the",
"list",
"of",
"available",
"remote",
"managers",
"that",
"can",
"be",
"started"
] | def update_remote_worker_availability_status(self):
"""
Updates the list of available remote managers that can be started
:return:
"""
available_workers = self.links.check_remote_installation_for_available_workers()
for installation_uuid in available_workers:
remote_address = available_workers[installation_uuid].get('address', '')
workers_in_installation = available_workers[installation_uuid].get('workers', [])
available_worker_count = len(workers_in_installation)
worker_number = 0
for worker_number in range(available_worker_count):
remote_manager_id = "{}|M{}".format(installation_uuid, worker_number)
if remote_manager_id in self.available_remote_managers or remote_manager_id in self.remote_task_manager_threads:
# This worker is already managed by a link manager thread or is already in the list of available workers
continue
# Add this remote worker ID to the list of available remote managers
self.available_remote_managers[remote_manager_id] = {
'uuid': installation_uuid,
'address': remote_address,
}
# Check if this installation is configured for preloading
if available_workers[installation_uuid].get('enable_task_preloading'):
# Add an extra manager so that we can preload the remote pending task queue with one file and save
# network transfer time
remote_manager_id = "{}|M{}".format(installation_uuid, (worker_number + 1))
if remote_manager_id in self.available_remote_managers or remote_manager_id in self.remote_task_manager_threads:
# This worker is already managed by a link manager thread or is already in the list of available workers
continue
self.available_remote_managers[remote_manager_id] = {
'uuid': installation_uuid,
'address': remote_address,
} | [
"def",
"update_remote_worker_availability_status",
"(",
"self",
")",
":",
"available_workers",
"=",
"self",
".",
"links",
".",
"check_remote_installation_for_available_workers",
"(",
")",
"for",
"installation_uuid",
"in",
"available_workers",
":",
"remote_address",
"=",
"available_workers",
"[",
"installation_uuid",
"]",
".",
"get",
"(",
"'address'",
",",
"''",
")",
"workers_in_installation",
"=",
"available_workers",
"[",
"installation_uuid",
"]",
".",
"get",
"(",
"'workers'",
",",
"[",
"]",
")",
"available_worker_count",
"=",
"len",
"(",
"workers_in_installation",
")",
"worker_number",
"=",
"0",
"for",
"worker_number",
"in",
"range",
"(",
"available_worker_count",
")",
":",
"remote_manager_id",
"=",
"\"{}|M{}\"",
".",
"format",
"(",
"installation_uuid",
",",
"worker_number",
")",
"if",
"remote_manager_id",
"in",
"self",
".",
"available_remote_managers",
"or",
"remote_manager_id",
"in",
"self",
".",
"remote_task_manager_threads",
":",
"# This worker is already managed by a link manager thread or is already in the list of available workers",
"continue",
"# Add this remote worker ID to the list of available remote managers",
"self",
".",
"available_remote_managers",
"[",
"remote_manager_id",
"]",
"=",
"{",
"'uuid'",
":",
"installation_uuid",
",",
"'address'",
":",
"remote_address",
",",
"}",
"# Check if this installation is configured for preloading",
"if",
"available_workers",
"[",
"installation_uuid",
"]",
".",
"get",
"(",
"'enable_task_preloading'",
")",
":",
"# Add an extra manager so that we can preload the remote pending task queue with one file and save",
"# network transfer time",
"remote_manager_id",
"=",
"\"{}|M{}\"",
".",
"format",
"(",
"installation_uuid",
",",
"(",
"worker_number",
"+",
"1",
")",
")",
"if",
"remote_manager_id",
"in",
"self",
".",
"available_remote_managers",
"or",
"remote_manager_id",
"in",
"self",
".",
"remote_task_manager_threads",
":",
"# This worker is already managed by a link manager thread or is already in the list of available workers",
"continue",
"self",
".",
"available_remote_managers",
"[",
"remote_manager_id",
"]",
"=",
"{",
"'uuid'",
":",
"installation_uuid",
",",
"'address'",
":",
"remote_address",
",",
"}"
] | https://github.com/Unmanic/unmanic/blob/655b18b5fd80c814e45ec38929d1046da93114c3/unmanic/libs/foreman.py#L305-L338 |
||
triaquae/MadKing | 3bec8bf972335535818c669e93c95de01e31edd6 | assets/myauth.py | python | UserManager.create_user | (self, email, name, password=None) | return user | Creates and saves a User with the given email, date of
birth and password. | Creates and saves a User with the given email, date of
birth and password. | [
"Creates",
"and",
"saves",
"a",
"User",
"with",
"the",
"given",
"email",
"date",
"of",
"birth",
"and",
"password",
"."
] | def create_user(self, email, name, password=None):
"""
Creates and saves a User with the given email, date of
birth and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
name=name,
#token=token,
#department=department,
#tel=tel,
#memo=memo,
)
user.set_password(password)
user.save(using=self._db)
return user | [
"def",
"create_user",
"(",
"self",
",",
"email",
",",
"name",
",",
"password",
"=",
"None",
")",
":",
"if",
"not",
"email",
":",
"raise",
"ValueError",
"(",
"'Users must have an email address'",
")",
"user",
"=",
"self",
".",
"model",
"(",
"email",
"=",
"self",
".",
"normalize_email",
"(",
"email",
")",
",",
"name",
"=",
"name",
",",
"#token=token,",
"#department=department,",
"#tel=tel,",
"#memo=memo,",
")",
"user",
".",
"set_password",
"(",
"password",
")",
"user",
".",
"save",
"(",
"using",
"=",
"self",
".",
"_db",
")",
"return",
"user"
] | https://github.com/triaquae/MadKing/blob/3bec8bf972335535818c669e93c95de01e31edd6/assets/myauth.py#L12-L32 |
|
GoogleCloudPlatform/PerfKitExplorer | 9efa61015d50c25f6d753f0212ad3bf16876d496 | server/perfkit/common/big_query_client.py | python | BigQueryClient._InitializeHttp | (self) | Sets the http handler for the client. | Sets the http handler for the client. | [
"Sets",
"the",
"http",
"handler",
"for",
"the",
"client",
"."
] | def _InitializeHttp(self):
"""Sets the http handler for the client."""
self._http = credentials_lib.GetAuthorizedCredentials(
self._credential_file, self.env) | [
"def",
"_InitializeHttp",
"(",
"self",
")",
":",
"self",
".",
"_http",
"=",
"credentials_lib",
".",
"GetAuthorizedCredentials",
"(",
"self",
".",
"_credential_file",
",",
"self",
".",
"env",
")"
] | https://github.com/GoogleCloudPlatform/PerfKitExplorer/blob/9efa61015d50c25f6d753f0212ad3bf16876d496/server/perfkit/common/big_query_client.py#L169-L172 |
||
NORMA-Inc/AtEar | 245ec8d1d13aea2d0acfa0481e5814b80b84e333 | run.py | python | main_app.wids | (self) | @brief Return the collected information from wids module. | [] | def wids(self):
'''
@brief Return the collected information from wids module.
'''
# 먼저 진행 중이던 작업을 취소.
if self.pentesting:
self.pentesting.stop()
self.pentesting = None
if self.scanner:
self.scanner.stop()
self.scanner = None
if self.fake_ap:
self.fake_ap.stop()
self.fake_ap = None
if not self.wids_handle:
self.wids_handle = Wireless_IDS('atear_wids')
self.wids_handle.start()
if request.method == 'GET':
try:
return_value = ast.literal_eval(self.wids_handle.get_values())
return json.dumps(return_value, ensure_ascii=False, encoding='EUC-KR')
except:
return json.dumps([{}]) | [
"def",
"wids",
"(",
"self",
")",
":",
"# 먼저 진행 중이던 작업을 취소.",
"if",
"self",
".",
"pentesting",
":",
"self",
".",
"pentesting",
".",
"stop",
"(",
")",
"self",
".",
"pentesting",
"=",
"None",
"if",
"self",
".",
"scanner",
":",
"self",
".",
"scanner",
".",
"stop",
"(",
")",
"self",
".",
"scanner",
"=",
"None",
"if",
"self",
".",
"fake_ap",
":",
"self",
".",
"fake_ap",
".",
"stop",
"(",
")",
"self",
".",
"fake_ap",
"=",
"None",
"if",
"not",
"self",
".",
"wids_handle",
":",
"self",
".",
"wids_handle",
"=",
"Wireless_IDS",
"(",
"'atear_wids'",
")",
"self",
".",
"wids_handle",
".",
"start",
"(",
")",
"if",
"request",
".",
"method",
"==",
"'GET'",
":",
"try",
":",
"return_value",
"=",
"ast",
".",
"literal_eval",
"(",
"self",
".",
"wids_handle",
".",
"get_values",
"(",
")",
")",
"return",
"json",
".",
"dumps",
"(",
"return_value",
",",
"ensure_ascii",
"=",
"False",
",",
"encoding",
"=",
"'EUC-KR'",
")",
"except",
":",
"return",
"json",
".",
"dumps",
"(",
"[",
"{",
"}",
"]",
")"
] | https://github.com/NORMA-Inc/AtEar/blob/245ec8d1d13aea2d0acfa0481e5814b80b84e333/run.py#L176-L201 |
|||
abourget/gevent-socketio | 1cdb1594a315326987a17ce0924ea448a82fab01 | socketio/virtsocket.py | python | Socket.spawn | (self, fn, *args, **kwargs) | return job | Spawn a new Greenlet, attached to this Socket instance.
It will be monitored by the "watcher" method | Spawn a new Greenlet, attached to this Socket instance. | [
"Spawn",
"a",
"new",
"Greenlet",
"attached",
"to",
"this",
"Socket",
"instance",
"."
] | def spawn(self, fn, *args, **kwargs):
"""Spawn a new Greenlet, attached to this Socket instance.
It will be monitored by the "watcher" method
"""
log.debug("Spawning sub-Socket Greenlet: %s" % fn.__name__)
job = gevent.spawn(fn, *args, **kwargs)
self.jobs.append(job)
return job | [
"def",
"spawn",
"(",
"self",
",",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
".",
"debug",
"(",
"\"Spawning sub-Socket Greenlet: %s\"",
"%",
"fn",
".",
"__name__",
")",
"job",
"=",
"gevent",
".",
"spawn",
"(",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"jobs",
".",
"append",
"(",
"job",
")",
"return",
"job"
] | https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/virtsocket.py#L336-L345 |
|
ElasticHQ/elasticsearch-HQ | 8197e21d09b1312492dcb6998a2349d73b06efc6 | elastichq/vendor/elasticsearch/client/cat.py | python | CatClient.snapshots | (self, repository, params=None) | return self.transport.perform_request('GET', _make_path('_cat',
'snapshots', repository), params=params) | `<https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-snapshots.html>`_
:arg repository: Name of repository from which to fetch the snapshot
information
:arg format: a short version of the Accept header, e.g. json, yaml
:arg h: Comma-separated list of column names to display
:arg help: Return help information, default False
:arg ignore_unavailable: Set to true to ignore unavailable snapshots,
default False
:arg master_timeout: Explicit operation timeout for connection to master
node
:arg s: Comma-separated list of column names or column aliases to sort
by
:arg v: Verbose mode. Display column headers, default False | [] | def snapshots(self, repository, params=None):
"""
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-snapshots.html>`_
:arg repository: Name of repository from which to fetch the snapshot
information
:arg format: a short version of the Accept header, e.g. json, yaml
:arg h: Comma-separated list of column names to display
:arg help: Return help information, default False
:arg ignore_unavailable: Set to true to ignore unavailable snapshots,
default False
:arg master_timeout: Explicit operation timeout for connection to master
node
:arg s: Comma-separated list of column names or column aliases to sort
by
:arg v: Verbose mode. Display column headers, default False
"""
if repository in SKIP_IN_PATH:
raise ValueError("Empty value passed for a required argument 'repository'.")
return self.transport.perform_request('GET', _make_path('_cat',
'snapshots', repository), params=params) | [
"def",
"snapshots",
"(",
"self",
",",
"repository",
",",
"params",
"=",
"None",
")",
":",
"if",
"repository",
"in",
"SKIP_IN_PATH",
":",
"raise",
"ValueError",
"(",
"\"Empty value passed for a required argument 'repository'.\"",
")",
"return",
"self",
".",
"transport",
".",
"perform_request",
"(",
"'GET'",
",",
"_make_path",
"(",
"'_cat'",
",",
"'snapshots'",
",",
"repository",
")",
",",
"params",
"=",
"params",
")"
] | https://github.com/ElasticHQ/elasticsearch-HQ/blob/8197e21d09b1312492dcb6998a2349d73b06efc6/elastichq/vendor/elasticsearch/client/cat.py#L382-L403 |
||
hongzimao/pensieve | 1120bb173958dc9bc9f2ebff1a8fe688b6f4e93c | rl_server/a3c.py | python | discount | (x, gamma) | return out | Given vector x, computes a vector y such that
y[i] = x[i] + gamma * x[i+1] + gamma^2 x[i+2] + ... | Given vector x, computes a vector y such that
y[i] = x[i] + gamma * x[i+1] + gamma^2 x[i+2] + ... | [
"Given",
"vector",
"x",
"computes",
"a",
"vector",
"y",
"such",
"that",
"y",
"[",
"i",
"]",
"=",
"x",
"[",
"i",
"]",
"+",
"gamma",
"*",
"x",
"[",
"i",
"+",
"1",
"]",
"+",
"gamma^2",
"x",
"[",
"i",
"+",
"2",
"]",
"+",
"..."
] | def discount(x, gamma):
"""
Given vector x, computes a vector y such that
y[i] = x[i] + gamma * x[i+1] + gamma^2 x[i+2] + ...
"""
out = np.zeros(len(x))
out[-1] = x[-1]
for i in reversed(xrange(len(x)-1)):
out[i] = x[i] + gamma*out[i+1]
assert x.ndim >= 1
# More efficient version:
# scipy.signal.lfilter([1],[1,-gamma],x[::-1], axis=0)[::-1]
return out | [
"def",
"discount",
"(",
"x",
",",
"gamma",
")",
":",
"out",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"x",
")",
")",
"out",
"[",
"-",
"1",
"]",
"=",
"x",
"[",
"-",
"1",
"]",
"for",
"i",
"in",
"reversed",
"(",
"xrange",
"(",
"len",
"(",
"x",
")",
"-",
"1",
")",
")",
":",
"out",
"[",
"i",
"]",
"=",
"x",
"[",
"i",
"]",
"+",
"gamma",
"*",
"out",
"[",
"i",
"+",
"1",
"]",
"assert",
"x",
".",
"ndim",
">=",
"1",
"# More efficient version:",
"# scipy.signal.lfilter([1],[1,-gamma],x[::-1], axis=0)[::-1]",
"return",
"out"
] | https://github.com/hongzimao/pensieve/blob/1120bb173958dc9bc9f2ebff1a8fe688b6f4e93c/rl_server/a3c.py#L248-L260 |
|
odoo/odoo | 8de8c196a137f4ebbf67d7c7c83fee36f873f5c8 | odoo/http.py | python | WebRequest._handle_exception | (self, exception) | Called within an except block to allow converting exceptions
to abitrary responses. Anything returned (except None) will
be used as response. | Called within an except block to allow converting exceptions
to abitrary responses. Anything returned (except None) will
be used as response. | [
"Called",
"within",
"an",
"except",
"block",
"to",
"allow",
"converting",
"exceptions",
"to",
"abitrary",
"responses",
".",
"Anything",
"returned",
"(",
"except",
"None",
")",
"will",
"be",
"used",
"as",
"response",
"."
] | def _handle_exception(self, exception):
"""Called within an except block to allow converting exceptions
to abitrary responses. Anything returned (except None) will
be used as response."""
self._failed = exception # prevent tx commit
if not isinstance(exception, NO_POSTMORTEM) \
and not isinstance(exception, werkzeug.exceptions.HTTPException):
odoo.tools.debugger.post_mortem(
odoo.tools.config, sys.exc_info())
# WARNING: do not inline or it breaks: raise...from evaluates strictly
# LTR so would first remove traceback then copy lack of traceback
new_cause = Exception().with_traceback(exception.__traceback__)
new_cause.__cause__ = exception.__cause__ or exception.__context__
# tries to provide good chained tracebacks, just re-raising exception
# generates a weird message as stacks just get concatenated, exceptions
# not guaranteed to copy.copy cleanly & we want `exception` as leaf (for
# callers to check & look at)
raise exception.with_traceback(None) from new_cause | [
"def",
"_handle_exception",
"(",
"self",
",",
"exception",
")",
":",
"self",
".",
"_failed",
"=",
"exception",
"# prevent tx commit",
"if",
"not",
"isinstance",
"(",
"exception",
",",
"NO_POSTMORTEM",
")",
"and",
"not",
"isinstance",
"(",
"exception",
",",
"werkzeug",
".",
"exceptions",
".",
"HTTPException",
")",
":",
"odoo",
".",
"tools",
".",
"debugger",
".",
"post_mortem",
"(",
"odoo",
".",
"tools",
".",
"config",
",",
"sys",
".",
"exc_info",
"(",
")",
")",
"# WARNING: do not inline or it breaks: raise...from evaluates strictly",
"# LTR so would first remove traceback then copy lack of traceback",
"new_cause",
"=",
"Exception",
"(",
")",
".",
"with_traceback",
"(",
"exception",
".",
"__traceback__",
")",
"new_cause",
".",
"__cause__",
"=",
"exception",
".",
"__cause__",
"or",
"exception",
".",
"__context__",
"# tries to provide good chained tracebacks, just re-raising exception",
"# generates a weird message as stacks just get concatenated, exceptions",
"# not guaranteed to copy.copy cleanly & we want `exception` as leaf (for",
"# callers to check & look at)",
"raise",
"exception",
".",
"with_traceback",
"(",
"None",
")",
"from",
"new_cause"
] | https://github.com/odoo/odoo/blob/8de8c196a137f4ebbf67d7c7c83fee36f873f5c8/odoo/http.py#L284-L302 |
||
ayojs/ayo | 45a1c8cf6384f5bcc81d834343c3ed9d78b97df3 | tools/gyp/pylib/gyp/generator/make.py | python | Linkable | (filename) | return filename.endswith('.o') | Return true if the file is linkable (should be on the link line). | Return true if the file is linkable (should be on the link line). | [
"Return",
"true",
"if",
"the",
"file",
"is",
"linkable",
"(",
"should",
"be",
"on",
"the",
"link",
"line",
")",
"."
] | def Linkable(filename):
"""Return true if the file is linkable (should be on the link line)."""
return filename.endswith('.o') | [
"def",
"Linkable",
"(",
"filename",
")",
":",
"return",
"filename",
".",
"endswith",
"(",
"'.o'",
")"
] | https://github.com/ayojs/ayo/blob/45a1c8cf6384f5bcc81d834343c3ed9d78b97df3/tools/gyp/pylib/gyp/generator/make.py#L572-L574 |
|
odoo/odoo | 8de8c196a137f4ebbf67d7c7c83fee36f873f5c8 | addons/mail/models/mail_message.py | python | Message._message_fetch | (self, domain, max_id=None, min_id=None, limit=30) | return self.search(domain, limit=limit).message_format() | Get a limited amount of formatted messages with provided domain.
:param domain: the domain to filter messages;
:param min_id: messages must be more recent than this id
:param max_id: message must be less recent than this id
:param limit: the maximum amount of messages to get;
:returns list(dict). | Get a limited amount of formatted messages with provided domain.
:param domain: the domain to filter messages;
:param min_id: messages must be more recent than this id
:param max_id: message must be less recent than this id
:param limit: the maximum amount of messages to get;
:returns list(dict). | [
"Get",
"a",
"limited",
"amount",
"of",
"formatted",
"messages",
"with",
"provided",
"domain",
".",
":",
"param",
"domain",
":",
"the",
"domain",
"to",
"filter",
"messages",
";",
":",
"param",
"min_id",
":",
"messages",
"must",
"be",
"more",
"recent",
"than",
"this",
"id",
":",
"param",
"max_id",
":",
"message",
"must",
"be",
"less",
"recent",
"than",
"this",
"id",
":",
"param",
"limit",
":",
"the",
"maximum",
"amount",
"of",
"messages",
"to",
"get",
";",
":",
"returns",
"list",
"(",
"dict",
")",
"."
] | def _message_fetch(self, domain, max_id=None, min_id=None, limit=30):
""" Get a limited amount of formatted messages with provided domain.
:param domain: the domain to filter messages;
:param min_id: messages must be more recent than this id
:param max_id: message must be less recent than this id
:param limit: the maximum amount of messages to get;
:returns list(dict).
"""
if max_id:
domain = expression.AND([domain, [('id', '<', max_id)]])
if min_id:
domain = expression.AND([domain, [('id', '>', min_id)]])
return self.search(domain, limit=limit).message_format() | [
"def",
"_message_fetch",
"(",
"self",
",",
"domain",
",",
"max_id",
"=",
"None",
",",
"min_id",
"=",
"None",
",",
"limit",
"=",
"30",
")",
":",
"if",
"max_id",
":",
"domain",
"=",
"expression",
".",
"AND",
"(",
"[",
"domain",
",",
"[",
"(",
"'id'",
",",
"'<'",
",",
"max_id",
")",
"]",
"]",
")",
"if",
"min_id",
":",
"domain",
"=",
"expression",
".",
"AND",
"(",
"[",
"domain",
",",
"[",
"(",
"'id'",
",",
"'>'",
",",
"min_id",
")",
"]",
"]",
")",
"return",
"self",
".",
"search",
"(",
"domain",
",",
"limit",
"=",
"limit",
")",
".",
"message_format",
"(",
")"
] | https://github.com/odoo/odoo/blob/8de8c196a137f4ebbf67d7c7c83fee36f873f5c8/addons/mail/models/mail_message.py#L902-L914 |