nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
baidu/AnyQ | d94d450d2aaa5f7ed73424b10aa4539835b97527 | tools/simnet/train/paddle/layers/paddle_layers.py | python | ElementwiseSubLayer.ops | (self, x, y) | return sub | operation | operation | [
"operation"
] | def ops(self, x, y):
"""
operation
"""
sub = fluid.layers.elementwise_sub(x, y)
return sub | [
"def",
"ops",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"sub",
"=",
"fluid",
".",
"layers",
".",
"elementwise_sub",
"(",
"x",
",",
"y",
")",
"return",
"sub"
] | https://github.com/baidu/AnyQ/blob/d94d450d2aaa5f7ed73424b10aa4539835b97527/tools/simnet/train/paddle/layers/paddle_layers.py#L329-L334 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/Tkinter.py | python | Misc.winfo_name | (self) | return self.tk.call('winfo', 'name', self._w) | Return the name of this widget. | Return the name of this widget. | [
"Return",
"the",
"name",
"of",
"this",
"widget",
"."
] | def winfo_name(self):
"""Return the name of this widget."""
return self.tk.call('winfo', 'name', self._w) | [
"def",
"winfo_name",
"(",
"self",
")",
":",
"return",
"self",
".",
"tk",
".",
"call",
"(",
"'winfo'",
",",
"'name'",
",",
"self",
".",
"_w",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/Tkinter.py#L865-L867 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/excel/_base.py | python | ExcelWriter.engine | (self) | Name of engine. | Name of engine. | [
"Name",
"of",
"engine",
"."
] | def engine(self):
"""Name of engine."""
pass | [
"def",
"engine",
"(",
"self",
")",
":",
"pass"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/excel/_base.py#L653-L655 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/commands/__init__.py | python | get_similar_commands | (name) | Command name auto-correct. | Command name auto-correct. | [
"Command",
"name",
"auto",
"-",
"correct",
"."
] | def get_similar_commands(name):
"""Command name auto-correct."""
from difflib import get_close_matches
name = name.lower()
close_commands = get_close_matches(name, commands_dict.keys())
if close_commands:
return close_commands[0]
else:
return False | [
"def",
"get_similar_commands",
"(",
"name",
")",
":",
"from",
"difflib",
"import",
"get_close_matches",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"close_commands",
"=",
"get_close_matches",
"(",
"name",
",",
"commands_dict",
".",
"keys",
"(",
")",
")",
"if",
"close_commands",
":",
"return",
"close_commands",
"[",
"0",
"]",
"else",
":",
"return",
"False"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/commands/__init__.py#L57-L68 | ||
Cantera/cantera | 0119484b261967ccb55a0066c020599cacc312e4 | site_scons/wxsgen.py | python | indent | (elem, level=0) | in-place prettyprint formatter (from lxml) | in-place prettyprint formatter (from lxml) | [
"in",
"-",
"place",
"prettyprint",
"formatter",
"(",
"from",
"lxml",
")"
] | def indent(elem, level=0):
""" in-place prettyprint formatter (from lxml) """
i = "\n" + level*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indent(elem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i | [
"def",
"indent",
"(",
"elem",
",",
"level",
"=",
"0",
")",
":",
"i",
"=",
"\"\\n\"",
"+",
"level",
"*",
"\" \"",
"if",
"len",
"(",
"elem",
")",
":",
"if",
"not",
"elem",
".",
"text",
"or",
"not",
"elem",
".",
"text",
".",
"strip",
"(",
")",
":",
"elem",
".",
"text",
"=",
"i",
"+",
"\" \"",
"if",
"not",
"elem",
".",
"tail",
"or",
"not",
"elem",
".",
"tail",
".",
"strip",
"(",
")",
":",
"elem",
".",
"tail",
"=",
"i",
"for",
"elem",
"in",
"elem",
":",
"indent",
"(",
"elem",
",",
"level",
"+",
"1",
")",
"if",
"not",
"elem",
".",
"tail",
"or",
"not",
"elem",
".",
"tail",
".",
"strip",
"(",
")",
":",
"elem",
".",
"tail",
"=",
"i",
"else",
":",
"if",
"level",
"and",
"(",
"not",
"elem",
".",
"tail",
"or",
"not",
"elem",
".",
"tail",
".",
"strip",
"(",
")",
")",
":",
"elem",
".",
"tail",
"=",
"i"
] | https://github.com/Cantera/cantera/blob/0119484b261967ccb55a0066c020599cacc312e4/site_scons/wxsgen.py#L185-L199 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/datetime.py | python | datetime._fromtimestamp | (cls, t, utc, tz) | return result | Construct a datetime from a POSIX timestamp (like time.time()).
A timezone info object may be passed in as well. | Construct a datetime from a POSIX timestamp (like time.time()). | [
"Construct",
"a",
"datetime",
"from",
"a",
"POSIX",
"timestamp",
"(",
"like",
"time",
".",
"time",
"()",
")",
"."
] | def _fromtimestamp(cls, t, utc, tz):
"""Construct a datetime from a POSIX timestamp (like time.time()).
A timezone info object may be passed in as well.
"""
frac, t = _math.modf(t)
us = round(frac * 1e6)
if us >= 1000000:
t += 1
us -= 1000000
elif us < 0:
t -= 1
us += 1000000
converter = _time.gmtime if utc else _time.localtime
y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
ss = min(ss, 59) # clamp out leap seconds if the platform has them
result = cls(y, m, d, hh, mm, ss, us, tz)
if tz is None:
# As of version 2015f max fold in IANA database is
# 23 hours at 1969-09-30 13:00:00 in Kwajalein.
# Let's probe 24 hours in the past to detect a transition:
max_fold_seconds = 24 * 3600
# On Windows localtime_s throws an OSError for negative values,
# thus we can't perform fold detection for values of time less
# than the max time fold. See comments in _datetimemodule's
# version of this method for more details.
if t < max_fold_seconds and sys.platform.startswith("win"):
return result
y, m, d, hh, mm, ss = converter(t - max_fold_seconds)[:6]
probe1 = cls(y, m, d, hh, mm, ss, us, tz)
trans = result - probe1 - timedelta(0, max_fold_seconds)
if trans.days < 0:
y, m, d, hh, mm, ss = converter(t + trans // timedelta(0, 1))[:6]
probe2 = cls(y, m, d, hh, mm, ss, us, tz)
if probe2 == result:
result._fold = 1
else:
result = tz.fromutc(result)
return result | [
"def",
"_fromtimestamp",
"(",
"cls",
",",
"t",
",",
"utc",
",",
"tz",
")",
":",
"frac",
",",
"t",
"=",
"_math",
".",
"modf",
"(",
"t",
")",
"us",
"=",
"round",
"(",
"frac",
"*",
"1e6",
")",
"if",
"us",
">=",
"1000000",
":",
"t",
"+=",
"1",
"us",
"-=",
"1000000",
"elif",
"us",
"<",
"0",
":",
"t",
"-=",
"1",
"us",
"+=",
"1000000",
"converter",
"=",
"_time",
".",
"gmtime",
"if",
"utc",
"else",
"_time",
".",
"localtime",
"y",
",",
"m",
",",
"d",
",",
"hh",
",",
"mm",
",",
"ss",
",",
"weekday",
",",
"jday",
",",
"dst",
"=",
"converter",
"(",
"t",
")",
"ss",
"=",
"min",
"(",
"ss",
",",
"59",
")",
"# clamp out leap seconds if the platform has them",
"result",
"=",
"cls",
"(",
"y",
",",
"m",
",",
"d",
",",
"hh",
",",
"mm",
",",
"ss",
",",
"us",
",",
"tz",
")",
"if",
"tz",
"is",
"None",
":",
"# As of version 2015f max fold in IANA database is",
"# 23 hours at 1969-09-30 13:00:00 in Kwajalein.",
"# Let's probe 24 hours in the past to detect a transition:",
"max_fold_seconds",
"=",
"24",
"*",
"3600",
"# On Windows localtime_s throws an OSError for negative values,",
"# thus we can't perform fold detection for values of time less",
"# than the max time fold. See comments in _datetimemodule's",
"# version of this method for more details.",
"if",
"t",
"<",
"max_fold_seconds",
"and",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"win\"",
")",
":",
"return",
"result",
"y",
",",
"m",
",",
"d",
",",
"hh",
",",
"mm",
",",
"ss",
"=",
"converter",
"(",
"t",
"-",
"max_fold_seconds",
")",
"[",
":",
"6",
"]",
"probe1",
"=",
"cls",
"(",
"y",
",",
"m",
",",
"d",
",",
"hh",
",",
"mm",
",",
"ss",
",",
"us",
",",
"tz",
")",
"trans",
"=",
"result",
"-",
"probe1",
"-",
"timedelta",
"(",
"0",
",",
"max_fold_seconds",
")",
"if",
"trans",
".",
"days",
"<",
"0",
":",
"y",
",",
"m",
",",
"d",
",",
"hh",
",",
"mm",
",",
"ss",
"=",
"converter",
"(",
"t",
"+",
"trans",
"//",
"timedelta",
"(",
"0",
",",
"1",
")",
")",
"[",
":",
"6",
"]",
"probe2",
"=",
"cls",
"(",
"y",
",",
"m",
",",
"d",
",",
"hh",
",",
"mm",
",",
"ss",
",",
"us",
",",
"tz",
")",
"if",
"probe2",
"==",
"result",
":",
"result",
".",
"_fold",
"=",
"1",
"else",
":",
"result",
"=",
"tz",
".",
"fromutc",
"(",
"result",
")",
"return",
"result"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/datetime.py#L1583-L1624 | |
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | lldb/examples/customization/pwd-cd-and-system/utils.py | python | chdir | (debugger, args, result, dict) | Change the working directory, or cd to ${HOME}.
You can also issue 'cd -' to change to the previous working directory. | Change the working directory, or cd to ${HOME}.
You can also issue 'cd -' to change to the previous working directory. | [
"Change",
"the",
"working",
"directory",
"or",
"cd",
"to",
"$",
"{",
"HOME",
"}",
".",
"You",
"can",
"also",
"issue",
"cd",
"-",
"to",
"change",
"to",
"the",
"previous",
"working",
"directory",
"."
] | def chdir(debugger, args, result, dict):
"""Change the working directory, or cd to ${HOME}.
You can also issue 'cd -' to change to the previous working directory."""
new_dir = args.strip()
if not new_dir:
new_dir = os.path.expanduser('~')
elif new_dir == '-':
if not Holder.prev_dir():
# Bad directory, not changing.
print("bad directory, not changing")
return
else:
new_dir = Holder.prev_dir()
Holder.swap(os.getcwd())
os.chdir(new_dir)
print("Current working directory: %s" % os.getcwd()) | [
"def",
"chdir",
"(",
"debugger",
",",
"args",
",",
"result",
",",
"dict",
")",
":",
"new_dir",
"=",
"args",
".",
"strip",
"(",
")",
"if",
"not",
"new_dir",
":",
"new_dir",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
"elif",
"new_dir",
"==",
"'-'",
":",
"if",
"not",
"Holder",
".",
"prev_dir",
"(",
")",
":",
"# Bad directory, not changing.",
"print",
"(",
"\"bad directory, not changing\"",
")",
"return",
"else",
":",
"new_dir",
"=",
"Holder",
".",
"prev_dir",
"(",
")",
"Holder",
".",
"swap",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
"os",
".",
"chdir",
"(",
"new_dir",
")",
"print",
"(",
"\"Current working directory: %s\"",
"%",
"os",
".",
"getcwd",
"(",
")",
")"
] | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/lldb/examples/customization/pwd-cd-and-system/utils.py#L24-L40 | ||
pyne/pyne | 0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3 | pyne/dbgen/hashtools.py | python | calc_hash | (node, nuc_data) | return ret | This function calculates the hash of a dataset or group of datasets in a
hdf5 file.
Parameters
----------
node : str
String with the hdf5 node name
nuc_data : str
path to the nuc_data.h5 file | This function calculates the hash of a dataset or group of datasets in a
hdf5 file. | [
"This",
"function",
"calculates",
"the",
"hash",
"of",
"a",
"dataset",
"or",
"group",
"of",
"datasets",
"in",
"a",
"hdf5",
"file",
"."
] | def calc_hash(node, nuc_data):
"""
This function calculates the hash of a dataset or group of datasets in a
hdf5 file.
Parameters
----------
node : str
String with the hdf5 node name
nuc_data : str
path to the nuc_data.h5 file
"""
with tables.open_file(nuc_data) as f:
node = f.get_node(node)
if type(node) == tables.group.Group:
mhash = hashlib.md5()
for item in node:
if type(item[:]) == numpy.ndarray:
mhash.update(item[:].data)
else:
if type(item[0]) == numpy.ndarray:
for tiny_item in item:
mhash.update(tiny_item.data)
else:
for tiny_item in item:
mhash.update(str(tiny_item).encode())
ret = mhash.hexdigest()
else:
ret = hashlib.md5(node[:].data).hexdigest()
return ret | [
"def",
"calc_hash",
"(",
"node",
",",
"nuc_data",
")",
":",
"with",
"tables",
".",
"open_file",
"(",
"nuc_data",
")",
"as",
"f",
":",
"node",
"=",
"f",
".",
"get_node",
"(",
"node",
")",
"if",
"type",
"(",
"node",
")",
"==",
"tables",
".",
"group",
".",
"Group",
":",
"mhash",
"=",
"hashlib",
".",
"md5",
"(",
")",
"for",
"item",
"in",
"node",
":",
"if",
"type",
"(",
"item",
"[",
":",
"]",
")",
"==",
"numpy",
".",
"ndarray",
":",
"mhash",
".",
"update",
"(",
"item",
"[",
":",
"]",
".",
"data",
")",
"else",
":",
"if",
"type",
"(",
"item",
"[",
"0",
"]",
")",
"==",
"numpy",
".",
"ndarray",
":",
"for",
"tiny_item",
"in",
"item",
":",
"mhash",
".",
"update",
"(",
"tiny_item",
".",
"data",
")",
"else",
":",
"for",
"tiny_item",
"in",
"item",
":",
"mhash",
".",
"update",
"(",
"str",
"(",
"tiny_item",
")",
".",
"encode",
"(",
")",
")",
"ret",
"=",
"mhash",
".",
"hexdigest",
"(",
")",
"else",
":",
"ret",
"=",
"hashlib",
".",
"md5",
"(",
"node",
"[",
":",
"]",
".",
"data",
")",
".",
"hexdigest",
"(",
")",
"return",
"ret"
] | https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/dbgen/hashtools.py#L72-L102 | |
qgis/QGIS | 15a77662d4bb712184f6aa60d0bd663010a76a75 | python/plugins/grassprovider/Grass7Utils.py | python | Grass7Utils.grassMapsetFolder | () | return folder | Creates and returns the GRASS temporary DB LOCATION directory. | Creates and returns the GRASS temporary DB LOCATION directory. | [
"Creates",
"and",
"returns",
"the",
"GRASS",
"temporary",
"DB",
"LOCATION",
"directory",
"."
] | def grassMapsetFolder():
"""
Creates and returns the GRASS temporary DB LOCATION directory.
"""
folder = os.path.join(Grass7Utils.grassDataFolder(), 'temp_location')
mkdir(folder)
return folder | [
"def",
"grassMapsetFolder",
"(",
")",
":",
"folder",
"=",
"os",
".",
"path",
".",
"join",
"(",
"Grass7Utils",
".",
"grassDataFolder",
"(",
")",
",",
"'temp_location'",
")",
"mkdir",
"(",
"folder",
")",
"return",
"folder"
] | https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/grassprovider/Grass7Utils.py#L282-L288 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | PRESUBMIT.py | python | _FilesToCheckForIncomingDeps | (re, changed_lines) | return results | Helper method for _CheckAddedDepsHaveTargetApprovals. Returns
a set of DEPS entries that we should look up.
For a directory (rather than a specific filename) we fake a path to
a specific filename by adding /DEPS. This is chosen as a file that
will seldom or never be subject to per-file include_rules. | Helper method for _CheckAddedDepsHaveTargetApprovals. Returns
a set of DEPS entries that we should look up. | [
"Helper",
"method",
"for",
"_CheckAddedDepsHaveTargetApprovals",
".",
"Returns",
"a",
"set",
"of",
"DEPS",
"entries",
"that",
"we",
"should",
"look",
"up",
"."
] | def _FilesToCheckForIncomingDeps(re, changed_lines):
"""Helper method for _CheckAddedDepsHaveTargetApprovals. Returns
a set of DEPS entries that we should look up.
For a directory (rather than a specific filename) we fake a path to
a specific filename by adding /DEPS. This is chosen as a file that
will seldom or never be subject to per-file include_rules.
"""
# We ignore deps entries on auto-generated directories.
AUTO_GENERATED_DIRS = ['grit', 'jni']
# This pattern grabs the path without basename in the first
# parentheses, and the basename (if present) in the second. It
# relies on the simple heuristic that if there is a basename it will
# be a header file ending in ".h".
pattern = re.compile(
r"""['"]\+([^'"]+?)(/[a-zA-Z0-9_]+\.h)?['"].*""")
results = set()
for changed_line in changed_lines:
m = pattern.match(changed_line)
if m:
path = m.group(1)
if path.split('/')[0] not in AUTO_GENERATED_DIRS:
if m.group(2):
results.add('%s%s' % (path, m.group(2)))
else:
results.add('%s/DEPS' % path)
return results | [
"def",
"_FilesToCheckForIncomingDeps",
"(",
"re",
",",
"changed_lines",
")",
":",
"# We ignore deps entries on auto-generated directories.",
"AUTO_GENERATED_DIRS",
"=",
"[",
"'grit'",
",",
"'jni'",
"]",
"# This pattern grabs the path without basename in the first",
"# parentheses, and the basename (if present) in the second. It",
"# relies on the simple heuristic that if there is a basename it will",
"# be a header file ending in \".h\".",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r\"\"\"['\"]\\+([^'\"]+?)(/[a-zA-Z0-9_]+\\.h)?['\"].*\"\"\"",
")",
"results",
"=",
"set",
"(",
")",
"for",
"changed_line",
"in",
"changed_lines",
":",
"m",
"=",
"pattern",
".",
"match",
"(",
"changed_line",
")",
"if",
"m",
":",
"path",
"=",
"m",
".",
"group",
"(",
"1",
")",
"if",
"path",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
"]",
"not",
"in",
"AUTO_GENERATED_DIRS",
":",
"if",
"m",
".",
"group",
"(",
"2",
")",
":",
"results",
".",
"add",
"(",
"'%s%s'",
"%",
"(",
"path",
",",
"m",
".",
"group",
"(",
"2",
")",
")",
")",
"else",
":",
"results",
".",
"add",
"(",
"'%s/DEPS'",
"%",
"path",
")",
"return",
"results"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/PRESUBMIT.py#L786-L813 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/gyp/pylib/gyp/common.py | python | CopyTool | (flavor, out_path, generator_flags={}) | Finds (flock|mac|win)_tool.gyp in the gyp directory and copies it
to |out_path|. | Finds (flock|mac|win)_tool.gyp in the gyp directory and copies it
to |out_path|. | [
"Finds",
"(",
"flock|mac|win",
")",
"_tool",
".",
"gyp",
"in",
"the",
"gyp",
"directory",
"and",
"copies",
"it",
"to",
"|out_path|",
"."
] | def CopyTool(flavor, out_path, generator_flags={}):
"""Finds (flock|mac|win)_tool.gyp in the gyp directory and copies it
to |out_path|."""
# aix and solaris just need flock emulation. mac and win use more complicated
# support scripts.
prefix = {"aix": "flock", "solaris": "flock", "mac": "mac", "win": "win"}.get(
flavor, None
)
if not prefix:
return
# Slurp input file.
source_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "%s_tool.py" % prefix
)
with open(source_path) as source_file:
source = source_file.readlines()
# Set custom header flags.
header = "# Generated by gyp. Do not edit.\n"
mac_toolchain_dir = generator_flags.get("mac_toolchain_dir", None)
if flavor == "mac" and mac_toolchain_dir:
header += "import os;\nos.environ['DEVELOPER_DIR']='%s'\n" % mac_toolchain_dir
# Add header and write it out.
tool_path = os.path.join(out_path, "gyp-%s-tool" % prefix)
with open(tool_path, "w") as tool_file:
tool_file.write("".join([source[0], header] + source[1:]))
# Make file executable.
os.chmod(tool_path, 0o755) | [
"def",
"CopyTool",
"(",
"flavor",
",",
"out_path",
",",
"generator_flags",
"=",
"{",
"}",
")",
":",
"# aix and solaris just need flock emulation. mac and win use more complicated",
"# support scripts.",
"prefix",
"=",
"{",
"\"aix\"",
":",
"\"flock\"",
",",
"\"solaris\"",
":",
"\"flock\"",
",",
"\"mac\"",
":",
"\"mac\"",
",",
"\"win\"",
":",
"\"win\"",
"}",
".",
"get",
"(",
"flavor",
",",
"None",
")",
"if",
"not",
"prefix",
":",
"return",
"# Slurp input file.",
"source_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
",",
"\"%s_tool.py\"",
"%",
"prefix",
")",
"with",
"open",
"(",
"source_path",
")",
"as",
"source_file",
":",
"source",
"=",
"source_file",
".",
"readlines",
"(",
")",
"# Set custom header flags.",
"header",
"=",
"\"# Generated by gyp. Do not edit.\\n\"",
"mac_toolchain_dir",
"=",
"generator_flags",
".",
"get",
"(",
"\"mac_toolchain_dir\"",
",",
"None",
")",
"if",
"flavor",
"==",
"\"mac\"",
"and",
"mac_toolchain_dir",
":",
"header",
"+=",
"\"import os;\\nos.environ['DEVELOPER_DIR']='%s'\\n\"",
"%",
"mac_toolchain_dir",
"# Add header and write it out.",
"tool_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"out_path",
",",
"\"gyp-%s-tool\"",
"%",
"prefix",
")",
"with",
"open",
"(",
"tool_path",
",",
"\"w\"",
")",
"as",
"tool_file",
":",
"tool_file",
".",
"write",
"(",
"\"\"",
".",
"join",
"(",
"[",
"source",
"[",
"0",
"]",
",",
"header",
"]",
"+",
"source",
"[",
"1",
":",
"]",
")",
")",
"# Make file executable.",
"os",
".",
"chmod",
"(",
"tool_path",
",",
"0o755",
")"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/gyp/pylib/gyp/common.py#L461-L491 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/train/dataset_helper.py | python | _dynamic_sink_data | (dataset, dataset_iter) | return False | Special scenario for dataset with sink_size=1. | Special scenario for dataset with sink_size=1. | [
"Special",
"scenario",
"for",
"dataset",
"with",
"sink_size",
"=",
"1",
"."
] | def _dynamic_sink_data(dataset, dataset_iter):
"""Special scenario for dataset with sink_size=1."""
if hasattr(dataset_iter, "sink_size") and \
dataset_iter.sink_size == 1 and \
dataset.get_dataset_size() != 1 and \
hasattr(dataset_iter, "sink_count") and \
dataset_iter.sink_count == 1 and \
context.get_context("device_target") == "Ascend":
return True
return False | [
"def",
"_dynamic_sink_data",
"(",
"dataset",
",",
"dataset_iter",
")",
":",
"if",
"hasattr",
"(",
"dataset_iter",
",",
"\"sink_size\"",
")",
"and",
"dataset_iter",
".",
"sink_size",
"==",
"1",
"and",
"dataset",
".",
"get_dataset_size",
"(",
")",
"!=",
"1",
"and",
"hasattr",
"(",
"dataset_iter",
",",
"\"sink_count\"",
")",
"and",
"dataset_iter",
".",
"sink_count",
"==",
"1",
"and",
"context",
".",
"get_context",
"(",
"\"device_target\"",
")",
"==",
"\"Ascend\"",
":",
"return",
"True",
"return",
"False"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/train/dataset_helper.py#L42-L51 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2.py | python | xmlNode.getSpacePreserve | (self) | return ret | Searches the space preserving behaviour of a node, i.e. the
values of the xml:space attribute or the one carried by the
nearest ancestor. | Searches the space preserving behaviour of a node, i.e. the
values of the xml:space attribute or the one carried by the
nearest ancestor. | [
"Searches",
"the",
"space",
"preserving",
"behaviour",
"of",
"a",
"node",
"i",
".",
"e",
".",
"the",
"values",
"of",
"the",
"xml",
":",
"space",
"attribute",
"or",
"the",
"one",
"carried",
"by",
"the",
"nearest",
"ancestor",
"."
] | def getSpacePreserve(self):
"""Searches the space preserving behaviour of a node, i.e. the
values of the xml:space attribute or the one carried by the
nearest ancestor. """
ret = libxml2mod.xmlNodeGetSpacePreserve(self._o)
return ret | [
"def",
"getSpacePreserve",
"(",
"self",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlNodeGetSpacePreserve",
"(",
"self",
".",
"_o",
")",
"return",
"ret"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L3263-L3268 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/fft/fftpack.py | python | ihfft | (a, n=None, axis=-1, norm=None) | return output * (1 / (sqrt(n) if unitary else n)) | Compute the inverse FFT of a signal that has Hermitian symmetry.
Parameters
----------
a : array_like
Input array.
n : int, optional
Length of the inverse FFT, the number of points along
transformation axis in the input to use. If `n` is smaller than
the length of the input, the input is cropped. If it is larger,
the input is padded with zeros. If `n` is not given, the length of
the input along the axis specified by `axis` is used.
axis : int, optional
Axis over which to compute the inverse FFT. If not given, the last
axis is used.
norm : {None, "ortho"}, optional
Normalization mode (see `numpy.fft`). Default is None.
.. versionadded:: 1.10.0
Returns
-------
out : complex ndarray
The truncated or zero-padded input, transformed along the axis
indicated by `axis`, or the last one if `axis` is not specified.
The length of the transformed axis is ``n//2 + 1``.
See also
--------
hfft, irfft
Notes
-----
`hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the
opposite case: here the signal has Hermitian symmetry in the time
domain and is real in the frequency domain. So here it's `hfft` for
which you must supply the length of the result if it is to be odd:
* even: ``ihfft(hfft(a, 2*len(a) - 2) == a``, within roundoff error,
* odd: ``ihfft(hfft(a, 2*len(a) - 1) == a``, within roundoff error.
Examples
--------
>>> spectrum = np.array([ 15, -4, 0, -1, 0, -4])
>>> np.fft.ifft(spectrum)
array([ 1.+0.j, 2.-0.j, 3.+0.j, 4.+0.j, 3.+0.j, 2.-0.j])
>>> np.fft.ihfft(spectrum)
array([ 1.-0.j, 2.-0.j, 3.-0.j, 4.-0.j]) | Compute the inverse FFT of a signal that has Hermitian symmetry. | [
"Compute",
"the",
"inverse",
"FFT",
"of",
"a",
"signal",
"that",
"has",
"Hermitian",
"symmetry",
"."
] | def ihfft(a, n=None, axis=-1, norm=None):
"""
Compute the inverse FFT of a signal that has Hermitian symmetry.
Parameters
----------
a : array_like
Input array.
n : int, optional
Length of the inverse FFT, the number of points along
transformation axis in the input to use. If `n` is smaller than
the length of the input, the input is cropped. If it is larger,
the input is padded with zeros. If `n` is not given, the length of
the input along the axis specified by `axis` is used.
axis : int, optional
Axis over which to compute the inverse FFT. If not given, the last
axis is used.
norm : {None, "ortho"}, optional
Normalization mode (see `numpy.fft`). Default is None.
.. versionadded:: 1.10.0
Returns
-------
out : complex ndarray
The truncated or zero-padded input, transformed along the axis
indicated by `axis`, or the last one if `axis` is not specified.
The length of the transformed axis is ``n//2 + 1``.
See also
--------
hfft, irfft
Notes
-----
`hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the
opposite case: here the signal has Hermitian symmetry in the time
domain and is real in the frequency domain. So here it's `hfft` for
which you must supply the length of the result if it is to be odd:
* even: ``ihfft(hfft(a, 2*len(a) - 2) == a``, within roundoff error,
* odd: ``ihfft(hfft(a, 2*len(a) - 1) == a``, within roundoff error.
Examples
--------
>>> spectrum = np.array([ 15, -4, 0, -1, 0, -4])
>>> np.fft.ifft(spectrum)
array([ 1.+0.j, 2.-0.j, 3.+0.j, 4.+0.j, 3.+0.j, 2.-0.j])
>>> np.fft.ihfft(spectrum)
array([ 1.-0.j, 2.-0.j, 3.-0.j, 4.-0.j])
"""
# The copy may be required for multithreading.
a = array(a, copy=True, dtype=float)
if n is None:
n = a.shape[axis]
unitary = _unitary(norm)
output = conjugate(rfft(a, n, axis))
return output * (1 / (sqrt(n) if unitary else n)) | [
"def",
"ihfft",
"(",
"a",
",",
"n",
"=",
"None",
",",
"axis",
"=",
"-",
"1",
",",
"norm",
"=",
"None",
")",
":",
"# The copy may be required for multithreading.",
"a",
"=",
"array",
"(",
"a",
",",
"copy",
"=",
"True",
",",
"dtype",
"=",
"float",
")",
"if",
"n",
"is",
"None",
":",
"n",
"=",
"a",
".",
"shape",
"[",
"axis",
"]",
"unitary",
"=",
"_unitary",
"(",
"norm",
")",
"output",
"=",
"conjugate",
"(",
"rfft",
"(",
"a",
",",
"n",
",",
"axis",
")",
")",
"return",
"output",
"*",
"(",
"1",
"/",
"(",
"sqrt",
"(",
"n",
")",
"if",
"unitary",
"else",
"n",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/fft/fftpack.py#L572-L630 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/arrays/categorical.py | python | _get_codes_for_values | (values, categories: Index) | return coerce_indexer_dtype(t.lookup(vals), cats) | utility routine to turn values into codes given the specified categories
If `values` is known to be a Categorical, use recode_for_categories instead. | utility routine to turn values into codes given the specified categories | [
"utility",
"routine",
"to",
"turn",
"values",
"into",
"codes",
"given",
"the",
"specified",
"categories"
] | def _get_codes_for_values(values, categories: Index) -> np.ndarray:
"""
utility routine to turn values into codes given the specified categories
If `values` is known to be a Categorical, use recode_for_categories instead.
"""
dtype_equal = is_dtype_equal(values.dtype, categories.dtype)
if is_extension_array_dtype(categories.dtype) and is_object_dtype(values):
# Support inferring the correct extension dtype from an array of
# scalar objects. e.g.
# Categorical(array[Period, Period], categories=PeriodIndex(...))
cls = categories.dtype.construct_array_type()
values = maybe_cast_to_extension_array(cls, values)
if not isinstance(values, cls):
# exception raised in _from_sequence
values = ensure_object(values)
# error: Incompatible types in assignment (expression has type
# "ndarray", variable has type "Index")
categories = ensure_object(categories) # type: ignore[assignment]
elif not dtype_equal:
values = ensure_object(values)
# error: Incompatible types in assignment (expression has type "ndarray",
# variable has type "Index")
categories = ensure_object(categories) # type: ignore[assignment]
if isinstance(categories, ABCIndex):
return coerce_indexer_dtype(categories.get_indexer_for(values), categories)
# Only hit here when we've already coerced to object dtypee.
hash_klass, vals = get_data_algo(values)
# pandas/core/arrays/categorical.py:2661: error: Argument 1 to "get_data_algo" has
# incompatible type "Index"; expected "Union[ExtensionArray, ndarray]" [arg-type]
_, cats = get_data_algo(categories) # type: ignore[arg-type]
t = hash_klass(len(cats))
t.map_locations(cats)
return coerce_indexer_dtype(t.lookup(vals), cats) | [
"def",
"_get_codes_for_values",
"(",
"values",
",",
"categories",
":",
"Index",
")",
"->",
"np",
".",
"ndarray",
":",
"dtype_equal",
"=",
"is_dtype_equal",
"(",
"values",
".",
"dtype",
",",
"categories",
".",
"dtype",
")",
"if",
"is_extension_array_dtype",
"(",
"categories",
".",
"dtype",
")",
"and",
"is_object_dtype",
"(",
"values",
")",
":",
"# Support inferring the correct extension dtype from an array of",
"# scalar objects. e.g.",
"# Categorical(array[Period, Period], categories=PeriodIndex(...))",
"cls",
"=",
"categories",
".",
"dtype",
".",
"construct_array_type",
"(",
")",
"values",
"=",
"maybe_cast_to_extension_array",
"(",
"cls",
",",
"values",
")",
"if",
"not",
"isinstance",
"(",
"values",
",",
"cls",
")",
":",
"# exception raised in _from_sequence",
"values",
"=",
"ensure_object",
"(",
"values",
")",
"# error: Incompatible types in assignment (expression has type",
"# \"ndarray\", variable has type \"Index\")",
"categories",
"=",
"ensure_object",
"(",
"categories",
")",
"# type: ignore[assignment]",
"elif",
"not",
"dtype_equal",
":",
"values",
"=",
"ensure_object",
"(",
"values",
")",
"# error: Incompatible types in assignment (expression has type \"ndarray\",",
"# variable has type \"Index\")",
"categories",
"=",
"ensure_object",
"(",
"categories",
")",
"# type: ignore[assignment]",
"if",
"isinstance",
"(",
"categories",
",",
"ABCIndex",
")",
":",
"return",
"coerce_indexer_dtype",
"(",
"categories",
".",
"get_indexer_for",
"(",
"values",
")",
",",
"categories",
")",
"# Only hit here when we've already coerced to object dtypee.",
"hash_klass",
",",
"vals",
"=",
"get_data_algo",
"(",
"values",
")",
"# pandas/core/arrays/categorical.py:2661: error: Argument 1 to \"get_data_algo\" has",
"# incompatible type \"Index\"; expected \"Union[ExtensionArray, ndarray]\" [arg-type]",
"_",
",",
"cats",
"=",
"get_data_algo",
"(",
"categories",
")",
"# type: ignore[arg-type]",
"t",
"=",
"hash_klass",
"(",
"len",
"(",
"cats",
")",
")",
"t",
".",
"map_locations",
"(",
"cats",
")",
"return",
"coerce_indexer_dtype",
"(",
"t",
".",
"lookup",
"(",
"vals",
")",
",",
"cats",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/arrays/categorical.py#L2639-L2676 | |
l4ka/pistachio | 8be66aa9b85a774ad1b71dbd3a79c5c745a96273 | contrib/cml2/cmlsystem.py | python | CMLSystem.visit | (self, entry) | Register the fact that we've visited a menu. | Register the fact that we've visited a menu. | [
"Register",
"the",
"fact",
"that",
"we",
"ve",
"visited",
"a",
"menu",
"."
] | def visit(self, entry):
"Register the fact that we've visited a menu."
if not entry.menu or not self.is_visible(entry):
return
self.debug_emit(2,"Visiting %s (%s) starts" % (entry.name, entry.type))
entry.visits = entry.visits + 1
# Set choices defaults -- do it now for the side-effects
# (If you do it sooner you can get weird constraint failures)
if entry.visits==1 and entry.type=="choices" and not entry.frozen():
base = ind = entry.items.index(entry.default)
try:
# Starting from the declared default, or the implicit default
# of first item, seek forward until we find something visible.
while not self.is_visible(entry.items[ind]):
ind += 1
except IndexError:
# Kluge -- if we find no visible items, turn off suppressions
# and drop back to the original default.
self.debug_emit(1, self.lang["NOVISIBLE"] % (`entry`,))
ind = base
self.suppressions = 0
self.set_symbol(entry.items[ind], cml.y)
self.debug_emit(2, "Visiting %s (%s) ends" % (entry.name,entry.type)) | [
"def",
"visit",
"(",
"self",
",",
"entry",
")",
":",
"if",
"not",
"entry",
".",
"menu",
"or",
"not",
"self",
".",
"is_visible",
"(",
"entry",
")",
":",
"return",
"self",
".",
"debug_emit",
"(",
"2",
",",
"\"Visiting %s (%s) starts\"",
"%",
"(",
"entry",
".",
"name",
",",
"entry",
".",
"type",
")",
")",
"entry",
".",
"visits",
"=",
"entry",
".",
"visits",
"+",
"1",
"# Set choices defaults -- do it now for the side-effects",
"# (If you do it sooner you can get weird constraint failures)",
"if",
"entry",
".",
"visits",
"==",
"1",
"and",
"entry",
".",
"type",
"==",
"\"choices\"",
"and",
"not",
"entry",
".",
"frozen",
"(",
")",
":",
"base",
"=",
"ind",
"=",
"entry",
".",
"items",
".",
"index",
"(",
"entry",
".",
"default",
")",
"try",
":",
"# Starting from the declared default, or the implicit default",
"# of first item, seek forward until we find something visible.",
"while",
"not",
"self",
".",
"is_visible",
"(",
"entry",
".",
"items",
"[",
"ind",
"]",
")",
":",
"ind",
"+=",
"1",
"except",
"IndexError",
":",
"# Kluge -- if we find no visible items, turn off suppressions",
"# and drop back to the original default.",
"self",
".",
"debug_emit",
"(",
"1",
",",
"self",
".",
"lang",
"[",
"\"NOVISIBLE\"",
"]",
"%",
"(",
"`entry`",
",",
")",
")",
"ind",
"=",
"base",
"self",
".",
"suppressions",
"=",
"0",
"self",
".",
"set_symbol",
"(",
"entry",
".",
"items",
"[",
"ind",
"]",
",",
"cml",
".",
"y",
")",
"self",
".",
"debug_emit",
"(",
"2",
",",
"\"Visiting %s (%s) ends\"",
"%",
"(",
"entry",
".",
"name",
",",
"entry",
".",
"type",
")",
")"
] | https://github.com/l4ka/pistachio/blob/8be66aa9b85a774ad1b71dbd3a79c5c745a96273/contrib/cml2/cmlsystem.py#L1130-L1152 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_controls.py | python | ToolBarBase.GetToolState | (*args, **kwargs) | return _controls_.ToolBarBase_GetToolState(*args, **kwargs) | GetToolState(self, int id) -> bool | GetToolState(self, int id) -> bool | [
"GetToolState",
"(",
"self",
"int",
"id",
")",
"-",
">",
"bool"
] | def GetToolState(*args, **kwargs):
"""GetToolState(self, int id) -> bool"""
return _controls_.ToolBarBase_GetToolState(*args, **kwargs) | [
"def",
"GetToolState",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"ToolBarBase_GetToolState",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L3823-L3825 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/richtext.py | python | RichTextParagraph.GetCombinedAttributes | (*args, **kwargs) | return _richtext.RichTextParagraph_GetCombinedAttributes(*args, **kwargs) | GetCombinedAttributes(self, RichTextAttr contentStyle=None) -> RichTextAttr | GetCombinedAttributes(self, RichTextAttr contentStyle=None) -> RichTextAttr | [
"GetCombinedAttributes",
"(",
"self",
"RichTextAttr",
"contentStyle",
"=",
"None",
")",
"-",
">",
"RichTextAttr"
] | def GetCombinedAttributes(*args, **kwargs):
"""GetCombinedAttributes(self, RichTextAttr contentStyle=None) -> RichTextAttr"""
return _richtext.RichTextParagraph_GetCombinedAttributes(*args, **kwargs) | [
"def",
"GetCombinedAttributes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextParagraph_GetCombinedAttributes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L2043-L2045 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/lib2to3/refactor.py | python | RefactoringTool.refactor_docstring | (self, input, filename) | return u"".join(result) | Refactors a docstring, looking for doctests.
This returns a modified version of the input string. It looks
for doctests, which start with a ">>>" prompt, and may be
continued with "..." prompts, as long as the "..." is indented
the same as the ">>>".
(Unfortunately we can't use the doctest module's parser,
since, like most parsers, it is not geared towards preserving
the original source.) | Refactors a docstring, looking for doctests. | [
"Refactors",
"a",
"docstring",
"looking",
"for",
"doctests",
"."
] | def refactor_docstring(self, input, filename):
"""Refactors a docstring, looking for doctests.
This returns a modified version of the input string. It looks
for doctests, which start with a ">>>" prompt, and may be
continued with "..." prompts, as long as the "..." is indented
the same as the ">>>".
(Unfortunately we can't use the doctest module's parser,
since, like most parsers, it is not geared towards preserving
the original source.)
"""
result = []
block = None
block_lineno = None
indent = None
lineno = 0
for line in input.splitlines(True):
lineno += 1
if line.lstrip().startswith(self.PS1):
if block is not None:
result.extend(self.refactor_doctest(block, block_lineno,
indent, filename))
block_lineno = lineno
block = [line]
i = line.find(self.PS1)
indent = line[:i]
elif (indent is not None and
(line.startswith(indent + self.PS2) or
line == indent + self.PS2.rstrip() + u"\n")):
block.append(line)
else:
if block is not None:
result.extend(self.refactor_doctest(block, block_lineno,
indent, filename))
block = None
indent = None
result.append(line)
if block is not None:
result.extend(self.refactor_doctest(block, block_lineno,
indent, filename))
return u"".join(result) | [
"def",
"refactor_docstring",
"(",
"self",
",",
"input",
",",
"filename",
")",
":",
"result",
"=",
"[",
"]",
"block",
"=",
"None",
"block_lineno",
"=",
"None",
"indent",
"=",
"None",
"lineno",
"=",
"0",
"for",
"line",
"in",
"input",
".",
"splitlines",
"(",
"True",
")",
":",
"lineno",
"+=",
"1",
"if",
"line",
".",
"lstrip",
"(",
")",
".",
"startswith",
"(",
"self",
".",
"PS1",
")",
":",
"if",
"block",
"is",
"not",
"None",
":",
"result",
".",
"extend",
"(",
"self",
".",
"refactor_doctest",
"(",
"block",
",",
"block_lineno",
",",
"indent",
",",
"filename",
")",
")",
"block_lineno",
"=",
"lineno",
"block",
"=",
"[",
"line",
"]",
"i",
"=",
"line",
".",
"find",
"(",
"self",
".",
"PS1",
")",
"indent",
"=",
"line",
"[",
":",
"i",
"]",
"elif",
"(",
"indent",
"is",
"not",
"None",
"and",
"(",
"line",
".",
"startswith",
"(",
"indent",
"+",
"self",
".",
"PS2",
")",
"or",
"line",
"==",
"indent",
"+",
"self",
".",
"PS2",
".",
"rstrip",
"(",
")",
"+",
"u\"\\n\"",
")",
")",
":",
"block",
".",
"append",
"(",
"line",
")",
"else",
":",
"if",
"block",
"is",
"not",
"None",
":",
"result",
".",
"extend",
"(",
"self",
".",
"refactor_doctest",
"(",
"block",
",",
"block_lineno",
",",
"indent",
",",
"filename",
")",
")",
"block",
"=",
"None",
"indent",
"=",
"None",
"result",
".",
"append",
"(",
"line",
")",
"if",
"block",
"is",
"not",
"None",
":",
"result",
".",
"extend",
"(",
"self",
".",
"refactor_doctest",
"(",
"block",
",",
"block_lineno",
",",
"indent",
",",
"filename",
")",
")",
"return",
"u\"\"",
".",
"join",
"(",
"result",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/lib2to3/refactor.py#L462-L503 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/enum.py | python | unique | (enumeration) | return enumeration | Class decorator for enumerations ensuring unique member values. | Class decorator for enumerations ensuring unique member values. | [
"Class",
"decorator",
"for",
"enumerations",
"ensuring",
"unique",
"member",
"values",
"."
] | def unique(enumeration):
"""Class decorator for enumerations ensuring unique member values."""
duplicates = []
for name, member in enumeration.__members__.items():
if name != member.name:
duplicates.append((name, member.name))
if duplicates:
alias_details = ', '.join(
["%s -> %s" % (alias, name) for (alias, name) in duplicates])
raise ValueError('duplicate values found in %r: %s' %
(enumeration, alias_details))
return enumeration | [
"def",
"unique",
"(",
"enumeration",
")",
":",
"duplicates",
"=",
"[",
"]",
"for",
"name",
",",
"member",
"in",
"enumeration",
".",
"__members__",
".",
"items",
"(",
")",
":",
"if",
"name",
"!=",
"member",
".",
"name",
":",
"duplicates",
".",
"append",
"(",
"(",
"name",
",",
"member",
".",
"name",
")",
")",
"if",
"duplicates",
":",
"alias_details",
"=",
"', '",
".",
"join",
"(",
"[",
"\"%s -> %s\"",
"%",
"(",
"alias",
",",
"name",
")",
"for",
"(",
"alias",
",",
"name",
")",
"in",
"duplicates",
"]",
")",
"raise",
"ValueError",
"(",
"'duplicate values found in %r: %s'",
"%",
"(",
"enumeration",
",",
"alias_details",
")",
")",
"return",
"enumeration"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/enum.py#L864-L875 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/depends.py | python | Require.get_version | (self, paths=None, default="unknown") | return v | Get version number of installed module, 'None', or 'default'
Search 'paths' for module. If not found, return 'None'. If found,
return the extracted version attribute, or 'default' if no version
attribute was specified, or the value cannot be determined without
importing the module. The version is formatted according to the
requirement's version format (if any), unless it is 'None' or the
supplied 'default'. | Get version number of installed module, 'None', or 'default' | [
"Get",
"version",
"number",
"of",
"installed",
"module",
"None",
"or",
"default"
] | def get_version(self, paths=None, default="unknown"):
"""Get version number of installed module, 'None', or 'default'
Search 'paths' for module. If not found, return 'None'. If found,
return the extracted version attribute, or 'default' if no version
attribute was specified, or the value cannot be determined without
importing the module. The version is formatted according to the
requirement's version format (if any), unless it is 'None' or the
supplied 'default'.
"""
if self.attribute is None:
try:
f, p, i = find_module(self.module, paths)
if f:
f.close()
return default
except ImportError:
return None
v = get_module_constant(self.module, self.attribute, default, paths)
if v is not None and v is not default and self.format is not None:
return self.format(v)
return v | [
"def",
"get_version",
"(",
"self",
",",
"paths",
"=",
"None",
",",
"default",
"=",
"\"unknown\"",
")",
":",
"if",
"self",
".",
"attribute",
"is",
"None",
":",
"try",
":",
"f",
",",
"p",
",",
"i",
"=",
"find_module",
"(",
"self",
".",
"module",
",",
"paths",
")",
"if",
"f",
":",
"f",
".",
"close",
"(",
")",
"return",
"default",
"except",
"ImportError",
":",
"return",
"None",
"v",
"=",
"get_module_constant",
"(",
"self",
".",
"module",
",",
"self",
".",
"attribute",
",",
"default",
",",
"paths",
")",
"if",
"v",
"is",
"not",
"None",
"and",
"v",
"is",
"not",
"default",
"and",
"self",
".",
"format",
"is",
"not",
"None",
":",
"return",
"self",
".",
"format",
"(",
"v",
")",
"return",
"v"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/depends.py#L46-L71 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py | python | Metrowerks_Shell_Suite_Events.Get_Project_File | (self, _object, _attributes={}, **_arguments) | Get Project File: Returns a description of a file in the project window.
Required argument: The index of the file within its segment.
Keyword argument Segment: The segment containing the file.
Keyword argument _attributes: AppleEvent attribute dictionary
Returns: undocumented, typecode 'SrcF' | Get Project File: Returns a description of a file in the project window.
Required argument: The index of the file within its segment.
Keyword argument Segment: The segment containing the file.
Keyword argument _attributes: AppleEvent attribute dictionary
Returns: undocumented, typecode 'SrcF' | [
"Get",
"Project",
"File",
":",
"Returns",
"a",
"description",
"of",
"a",
"file",
"in",
"the",
"project",
"window",
".",
"Required",
"argument",
":",
"The",
"index",
"of",
"the",
"file",
"within",
"its",
"segment",
".",
"Keyword",
"argument",
"Segment",
":",
"The",
"segment",
"containing",
"the",
"file",
".",
"Keyword",
"argument",
"_attributes",
":",
"AppleEvent",
"attribute",
"dictionary",
"Returns",
":",
"undocumented",
"typecode",
"SrcF"
] | def Get_Project_File(self, _object, _attributes={}, **_arguments):
"""Get Project File: Returns a description of a file in the project window.
Required argument: The index of the file within its segment.
Keyword argument Segment: The segment containing the file.
Keyword argument _attributes: AppleEvent attribute dictionary
Returns: undocumented, typecode 'SrcF'
"""
_code = 'MMPR'
_subcode = 'GFil'
aetools.keysubst(_arguments, self._argmap_Get_Project_File)
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.get('errn', 0):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----'] | [
"def",
"Get_Project_File",
"(",
"self",
",",
"_object",
",",
"_attributes",
"=",
"{",
"}",
",",
"*",
"*",
"_arguments",
")",
":",
"_code",
"=",
"'MMPR'",
"_subcode",
"=",
"'GFil'",
"aetools",
".",
"keysubst",
"(",
"_arguments",
",",
"self",
".",
"_argmap_Get_Project_File",
")",
"_arguments",
"[",
"'----'",
"]",
"=",
"_object",
"_reply",
",",
"_arguments",
",",
"_attributes",
"=",
"self",
".",
"send",
"(",
"_code",
",",
"_subcode",
",",
"_arguments",
",",
"_attributes",
")",
"if",
"_arguments",
".",
"get",
"(",
"'errn'",
",",
"0",
")",
":",
"raise",
"aetools",
".",
"Error",
",",
"aetools",
".",
"decodeerror",
"(",
"_arguments",
")",
"# XXXX Optionally decode result",
"if",
"_arguments",
".",
"has_key",
"(",
"'----'",
")",
":",
"return",
"_arguments",
"[",
"'----'",
"]"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py#L235-L255 | ||
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/peacock/Input/ParamsTable.py | python | ParamsTable.__init__ | (self, block, params, type_block_map, **kwds) | Constructor.
Input:
block[BlockInfo]: The main block
params[list[ParameterInfo]]: List of parameters to show | Constructor.
Input:
block[BlockInfo]: The main block
params[list[ParameterInfo]]: List of parameters to show | [
"Constructor",
".",
"Input",
":",
"block",
"[",
"BlockInfo",
"]",
":",
"The",
"main",
"block",
"params",
"[",
"list",
"[",
"ParameterInfo",
"]]",
":",
"List",
"of",
"parameters",
"to",
"show"
] | def __init__(self, block, params, type_block_map, **kwds):
"""
Constructor.
Input:
block[BlockInfo]: The main block
params[list[ParameterInfo]]: List of parameters to show
"""
super(ParamsTable, self).__init__(**kwds)
self.block = block
self.params = params
self.setColumnCount(4)
self.setHorizontalHeaderLabels(["Name", "Value", "Options", "Comment"])
self.verticalHeader().hide()
self.updateSizes()
self.param_watch_blocks = {}
self.watch_blocks_params = {}
self.name_param = None
self.removed_params = []
self.type_to_block_map = type_block_map
for p in sorted(self.params, key=functools.cmp_to_key(paramSort)):
self.addParam(p)
self.updateWatchers()
self.cellChanged.connect(self.onCellChanged)
self.editing_delegate = EditingDelegate()
self.setItemDelegate(self.editing_delegate)
self.editing_delegate.startedEditing.connect(self.changed) | [
"def",
"__init__",
"(",
"self",
",",
"block",
",",
"params",
",",
"type_block_map",
",",
"*",
"*",
"kwds",
")",
":",
"super",
"(",
"ParamsTable",
",",
"self",
")",
".",
"__init__",
"(",
"*",
"*",
"kwds",
")",
"self",
".",
"block",
"=",
"block",
"self",
".",
"params",
"=",
"params",
"self",
".",
"setColumnCount",
"(",
"4",
")",
"self",
".",
"setHorizontalHeaderLabels",
"(",
"[",
"\"Name\"",
",",
"\"Value\"",
",",
"\"Options\"",
",",
"\"Comment\"",
"]",
")",
"self",
".",
"verticalHeader",
"(",
")",
".",
"hide",
"(",
")",
"self",
".",
"updateSizes",
"(",
")",
"self",
".",
"param_watch_blocks",
"=",
"{",
"}",
"self",
".",
"watch_blocks_params",
"=",
"{",
"}",
"self",
".",
"name_param",
"=",
"None",
"self",
".",
"removed_params",
"=",
"[",
"]",
"self",
".",
"type_to_block_map",
"=",
"type_block_map",
"for",
"p",
"in",
"sorted",
"(",
"self",
".",
"params",
",",
"key",
"=",
"functools",
".",
"cmp_to_key",
"(",
"paramSort",
")",
")",
":",
"self",
".",
"addParam",
"(",
"p",
")",
"self",
".",
"updateWatchers",
"(",
")",
"self",
".",
"cellChanged",
".",
"connect",
"(",
"self",
".",
"onCellChanged",
")",
"self",
".",
"editing_delegate",
"=",
"EditingDelegate",
"(",
")",
"self",
".",
"setItemDelegate",
"(",
"self",
".",
"editing_delegate",
")",
"self",
".",
"editing_delegate",
".",
"startedEditing",
".",
"connect",
"(",
"self",
".",
"changed",
")"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/Input/ParamsTable.py#L98-L124 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/random_projection.py | python | gaussian_random_matrix | (n_components, n_features, random_state=None) | return components | Generate a dense Gaussian random matrix.
The components of the random matrix are drawn from
N(0, 1.0 / n_components).
Read more in the :ref:`User Guide <gaussian_random_matrix>`.
Parameters
----------
n_components : int,
Dimensionality of the target projection space.
n_features : int,
Dimensionality of the original source space.
random_state : int, RandomState instance or None (default=None)
Control the pseudo random number generator used to generate the
matrix at fit time.
Returns
-------
components : numpy array of shape [n_components, n_features]
The generated Gaussian random matrix.
See Also
--------
GaussianRandomProjection
sparse_random_matrix | Generate a dense Gaussian random matrix. | [
"Generate",
"a",
"dense",
"Gaussian",
"random",
"matrix",
"."
] | def gaussian_random_matrix(n_components, n_features, random_state=None):
""" Generate a dense Gaussian random matrix.
The components of the random matrix are drawn from
N(0, 1.0 / n_components).
Read more in the :ref:`User Guide <gaussian_random_matrix>`.
Parameters
----------
n_components : int,
Dimensionality of the target projection space.
n_features : int,
Dimensionality of the original source space.
random_state : int, RandomState instance or None (default=None)
Control the pseudo random number generator used to generate the
matrix at fit time.
Returns
-------
components : numpy array of shape [n_components, n_features]
The generated Gaussian random matrix.
See Also
--------
GaussianRandomProjection
sparse_random_matrix
"""
_check_input_size(n_components, n_features)
rng = check_random_state(random_state)
components = rng.normal(loc=0.0,
scale=1.0 / np.sqrt(n_components),
size=(n_components, n_features))
return components | [
"def",
"gaussian_random_matrix",
"(",
"n_components",
",",
"n_features",
",",
"random_state",
"=",
"None",
")",
":",
"_check_input_size",
"(",
"n_components",
",",
"n_features",
")",
"rng",
"=",
"check_random_state",
"(",
"random_state",
")",
"components",
"=",
"rng",
".",
"normal",
"(",
"loc",
"=",
"0.0",
",",
"scale",
"=",
"1.0",
"/",
"np",
".",
"sqrt",
"(",
"n_components",
")",
",",
"size",
"=",
"(",
"n_components",
",",
"n_features",
")",
")",
"return",
"components"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/random_projection.py#L157-L193 | |
Slicer/SlicerGitSVNArchive | 65e92bb16c2b32ea47a1a66bee71f238891ee1ca | Utilities/Templates/Modules/Scripted/TemplateKey.py | python | TemplateKeyTest.test_TemplateKey1 | (self) | Ideally you should have several levels of tests. At the lowest level
tests should exercise the functionality of the logic with different inputs
(both valid and invalid). At higher levels your tests should emulate the
way the user would interact with your code and confirm that it still works
the way you intended.
One of the most important features of the tests is that it should alert other
developers when their changes will have an impact on the behavior of your
module. For example, if a developer removes a feature that you depend on,
your test should break so they know that the feature is needed. | Ideally you should have several levels of tests. At the lowest level
tests should exercise the functionality of the logic with different inputs
(both valid and invalid). At higher levels your tests should emulate the
way the user would interact with your code and confirm that it still works
the way you intended.
One of the most important features of the tests is that it should alert other
developers when their changes will have an impact on the behavior of your
module. For example, if a developer removes a feature that you depend on,
your test should break so they know that the feature is needed. | [
"Ideally",
"you",
"should",
"have",
"several",
"levels",
"of",
"tests",
".",
"At",
"the",
"lowest",
"level",
"tests",
"should",
"exercise",
"the",
"functionality",
"of",
"the",
"logic",
"with",
"different",
"inputs",
"(",
"both",
"valid",
"and",
"invalid",
")",
".",
"At",
"higher",
"levels",
"your",
"tests",
"should",
"emulate",
"the",
"way",
"the",
"user",
"would",
"interact",
"with",
"your",
"code",
"and",
"confirm",
"that",
"it",
"still",
"works",
"the",
"way",
"you",
"intended",
".",
"One",
"of",
"the",
"most",
"important",
"features",
"of",
"the",
"tests",
"is",
"that",
"it",
"should",
"alert",
"other",
"developers",
"when",
"their",
"changes",
"will",
"have",
"an",
"impact",
"on",
"the",
"behavior",
"of",
"your",
"module",
".",
"For",
"example",
"if",
"a",
"developer",
"removes",
"a",
"feature",
"that",
"you",
"depend",
"on",
"your",
"test",
"should",
"break",
"so",
"they",
"know",
"that",
"the",
"feature",
"is",
"needed",
"."
] | def test_TemplateKey1(self):
""" Ideally you should have several levels of tests. At the lowest level
tests should exercise the functionality of the logic with different inputs
(both valid and invalid). At higher levels your tests should emulate the
way the user would interact with your code and confirm that it still works
the way you intended.
One of the most important features of the tests is that it should alert other
developers when their changes will have an impact on the behavior of your
module. For example, if a developer removes a feature that you depend on,
your test should break so they know that the feature is needed.
"""
self.delayDisplay("Starting the test")
#
# first, get some data
#
import SampleData
SampleData.downloadFromURL(
nodeNames='FA',
fileNames='FA.nrrd',
uris='http://slicer.kitware.com/midas3/download?items=5767',
checksums='SHA256:12d17fba4f2e1f1a843f0757366f28c3f3e1a8bb38836f0de2a32bb1cd476560')
self.delayDisplay('Finished with download and loading')
volumeNode = slicer.util.getNode(pattern="FA")
logic = TemplateKeyLogic()
self.assertIsNotNone( logic.hasImageData(volumeNode) )
self.delayDisplay('Test passed!') | [
"def",
"test_TemplateKey1",
"(",
"self",
")",
":",
"self",
".",
"delayDisplay",
"(",
"\"Starting the test\"",
")",
"#",
"# first, get some data",
"#",
"import",
"SampleData",
"SampleData",
".",
"downloadFromURL",
"(",
"nodeNames",
"=",
"'FA'",
",",
"fileNames",
"=",
"'FA.nrrd'",
",",
"uris",
"=",
"'http://slicer.kitware.com/midas3/download?items=5767'",
",",
"checksums",
"=",
"'SHA256:12d17fba4f2e1f1a843f0757366f28c3f3e1a8bb38836f0de2a32bb1cd476560'",
")",
"self",
".",
"delayDisplay",
"(",
"'Finished with download and loading'",
")",
"volumeNode",
"=",
"slicer",
".",
"util",
".",
"getNode",
"(",
"pattern",
"=",
"\"FA\"",
")",
"logic",
"=",
"TemplateKeyLogic",
"(",
")",
"self",
".",
"assertIsNotNone",
"(",
"logic",
".",
"hasImageData",
"(",
"volumeNode",
")",
")",
"self",
".",
"delayDisplay",
"(",
"'Test passed!'",
")"
] | https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Utilities/Templates/Modules/Scripted/TemplateKey.py#L219-L246 | ||
htcondor/htcondor | 4829724575176d1d6c936e4693dfd78a728569b0 | src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/client.py | python | IClient.ButtonPressed | (self, Key) | Sends button button pressed to client.
@param Key: Key
@type Key: unicode | Sends button button pressed to client. | [
"Sends",
"button",
"button",
"pressed",
"to",
"client",
"."
] | def ButtonPressed(self, Key):
'''Sends button button pressed to client.
@param Key: Key
@type Key: unicode
'''
self._Skype._DoCommand('BTN_PRESSED %s' % Key) | [
"def",
"ButtonPressed",
"(",
"self",
",",
"Key",
")",
":",
"self",
".",
"_Skype",
".",
"_DoCommand",
"(",
"'BTN_PRESSED %s'",
"%",
"Key",
")"
] | https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/client.py#L22-L28 | ||
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/pyedbglib/protocols/cmsisdap.py | python | CmsisDapDebugger.dap_write_reg | (self, reg, value) | Writes a DAP AP/DP register
:param reg: register to write
:param value: value to write | Writes a DAP AP/DP register | [
"Writes",
"a",
"DAP",
"AP",
"/",
"DP",
"register"
] | def dap_write_reg(self, reg, value):
"""
Writes a DAP AP/DP register
:param reg: register to write
:param value: value to write
"""
self.logger.debug("dap_write_reg (0x%02X) = 0x%08X", reg, value)
cmd = bytearray(4)
cmd[0] = self.ID_DAP_Transfer
cmd[1] = 0x00 # dap
cmd[2] = 0x01 # 1 word
cmd[3] = reg
cmd.extend(binary.pack_le32(value))
rsp = self.dap_command_response(cmd)
self._check_response(cmd, rsp)
if rsp[1] != 1 or rsp[2] != self.DAP_TRANSFER_OK:
raise PyedbglibError("Write reg failed (0x{0:02X}, {1:02X})".format(rsp[1], rsp[2])) | [
"def",
"dap_write_reg",
"(",
"self",
",",
"reg",
",",
"value",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"dap_write_reg (0x%02X) = 0x%08X\"",
",",
"reg",
",",
"value",
")",
"cmd",
"=",
"bytearray",
"(",
"4",
")",
"cmd",
"[",
"0",
"]",
"=",
"self",
".",
"ID_DAP_Transfer",
"cmd",
"[",
"1",
"]",
"=",
"0x00",
"# dap",
"cmd",
"[",
"2",
"]",
"=",
"0x01",
"# 1 word",
"cmd",
"[",
"3",
"]",
"=",
"reg",
"cmd",
".",
"extend",
"(",
"binary",
".",
"pack_le32",
"(",
"value",
")",
")",
"rsp",
"=",
"self",
".",
"dap_command_response",
"(",
"cmd",
")",
"self",
".",
"_check_response",
"(",
"cmd",
",",
"rsp",
")",
"if",
"rsp",
"[",
"1",
"]",
"!=",
"1",
"or",
"rsp",
"[",
"2",
"]",
"!=",
"self",
".",
"DAP_TRANSFER_OK",
":",
"raise",
"PyedbglibError",
"(",
"\"Write reg failed (0x{0:02X}, {1:02X})\"",
".",
"format",
"(",
"rsp",
"[",
"1",
"]",
",",
"rsp",
"[",
"2",
"]",
")",
")"
] | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pyedbglib/protocols/cmsisdap.py#L297-L314 | ||
zju3dv/clean-pvnet | 5870c509e3cc205e1bb28910a7b1a9a3c8add9a8 | lib/networks/dla_dcn.py | python | conv3x3 | (in_planes, out_planes, stride=1) | return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False) | 3x3 convolution with padding | 3x3 convolution with padding | [
"3x3",
"convolution",
"with",
"padding"
] | def conv3x3(in_planes, out_planes, stride=1):
"3x3 convolution with padding"
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False) | [
"def",
"conv3x3",
"(",
"in_planes",
",",
"out_planes",
",",
"stride",
"=",
"1",
")",
":",
"return",
"nn",
".",
"Conv2d",
"(",
"in_planes",
",",
"out_planes",
",",
"kernel_size",
"=",
"3",
",",
"stride",
"=",
"stride",
",",
"padding",
"=",
"1",
",",
"bias",
"=",
"False",
")"
] | https://github.com/zju3dv/clean-pvnet/blob/5870c509e3cc205e1bb28910a7b1a9a3c8add9a8/lib/networks/dla_dcn.py#L26-L29 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/dtypes/dtypes.py | python | PandasExtensionDtype.__repr__ | (self) | return str(self) | Return a string representation for a particular object. | Return a string representation for a particular object. | [
"Return",
"a",
"string",
"representation",
"for",
"a",
"particular",
"object",
"."
] | def __repr__(self) -> str_type:
"""
Return a string representation for a particular object.
"""
return str(self) | [
"def",
"__repr__",
"(",
"self",
")",
"->",
"str_type",
":",
"return",
"str",
"(",
"self",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/dtypes/dtypes.py#L137-L141 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/graphviz/py3/graphviz/files.py | python | File.save | (self, filename=None, directory=None) | return filepath | Save the DOT source to file. Ensure the file ends with a newline.
Args:
filename: Filename for saving the source (defaults to ``name`` + ``'.gv'``)
directory: (Sub)directory for source saving and rendering.
Returns:
The (possibly relative) path of the saved source file. | Save the DOT source to file. Ensure the file ends with a newline. | [
"Save",
"the",
"DOT",
"source",
"to",
"file",
".",
"Ensure",
"the",
"file",
"ends",
"with",
"a",
"newline",
"."
] | def save(self, filename=None, directory=None):
"""Save the DOT source to file. Ensure the file ends with a newline.
Args:
filename: Filename for saving the source (defaults to ``name`` + ``'.gv'``)
directory: (Sub)directory for source saving and rendering.
Returns:
The (possibly relative) path of the saved source file.
"""
if filename is not None:
self.filename = filename
if directory is not None:
self.directory = directory
filepath = self.filepath
tools.mkdirs(filepath)
log.debug('write %d bytes to %r', len(self.source), filepath)
with open(filepath, 'w', encoding=self.encoding) as fd:
fd.write(self.source)
if not self.source.endswith('\n'):
fd.write('\n')
return filepath | [
"def",
"save",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"directory",
"=",
"None",
")",
":",
"if",
"filename",
"is",
"not",
"None",
":",
"self",
".",
"filename",
"=",
"filename",
"if",
"directory",
"is",
"not",
"None",
":",
"self",
".",
"directory",
"=",
"directory",
"filepath",
"=",
"self",
".",
"filepath",
"tools",
".",
"mkdirs",
"(",
"filepath",
")",
"log",
".",
"debug",
"(",
"'write %d bytes to %r'",
",",
"len",
"(",
"self",
".",
"source",
")",
",",
"filepath",
")",
"with",
"open",
"(",
"filepath",
",",
"'w'",
",",
"encoding",
"=",
"self",
".",
"encoding",
")",
"as",
"fd",
":",
"fd",
".",
"write",
"(",
"self",
".",
"source",
")",
"if",
"not",
"self",
".",
"source",
".",
"endswith",
"(",
"'\\n'",
")",
":",
"fd",
".",
"write",
"(",
"'\\n'",
")",
"return",
"filepath"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/graphviz/py3/graphviz/files.py#L176-L200 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/propgrid.py | python | PGProperty.AddChoice | (*args, **kwargs) | return _propgrid.PGProperty_AddChoice(*args, **kwargs) | AddChoice(self, String label, int value=INT_MAX) -> int | AddChoice(self, String label, int value=INT_MAX) -> int | [
"AddChoice",
"(",
"self",
"String",
"label",
"int",
"value",
"=",
"INT_MAX",
")",
"-",
">",
"int"
] | def AddChoice(*args, **kwargs):
"""AddChoice(self, String label, int value=INT_MAX) -> int"""
return _propgrid.PGProperty_AddChoice(*args, **kwargs) | [
"def",
"AddChoice",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PGProperty_AddChoice",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L432-L434 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/zipfile.py | python | ZipFile.printdir | (self) | Print a table of contents for the zip file. | Print a table of contents for the zip file. | [
"Print",
"a",
"table",
"of",
"contents",
"for",
"the",
"zip",
"file",
"."
] | def printdir(self):
"""Print a table of contents for the zip file."""
print "%-46s %19s %12s" % ("File Name", "Modified ", "Size")
for zinfo in self.filelist:
date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time[:6]
print "%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size) | [
"def",
"printdir",
"(",
"self",
")",
":",
"print",
"\"%-46s %19s %12s\"",
"%",
"(",
"\"File Name\"",
",",
"\"Modified \"",
",",
"\"Size\"",
")",
"for",
"zinfo",
"in",
"self",
".",
"filelist",
":",
"date",
"=",
"\"%d-%02d-%02d %02d:%02d:%02d\"",
"%",
"zinfo",
".",
"date_time",
"[",
":",
"6",
"]",
"print",
"\"%-46s %s %12d\"",
"%",
"(",
"zinfo",
".",
"filename",
",",
"date",
",",
"zinfo",
".",
"file_size",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/zipfile.py#L880-L885 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/_pydecimal.py | python | Context.__repr__ | (self) | return ', '.join(s) + ')' | Show the current context. | Show the current context. | [
"Show",
"the",
"current",
"context",
"."
] | def __repr__(self):
"""Show the current context."""
s = []
s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d, '
'clamp=%(clamp)d'
% vars(self))
names = [f.__name__ for f, v in self.flags.items() if v]
s.append('flags=[' + ', '.join(names) + ']')
names = [t.__name__ for t, v in self.traps.items() if v]
s.append('traps=[' + ', '.join(names) + ']')
return ', '.join(s) + ')' | [
"def",
"__repr__",
"(",
"self",
")",
":",
"s",
"=",
"[",
"]",
"s",
".",
"append",
"(",
"'Context(prec=%(prec)d, rounding=%(rounding)s, '",
"'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d, '",
"'clamp=%(clamp)d'",
"%",
"vars",
"(",
"self",
")",
")",
"names",
"=",
"[",
"f",
".",
"__name__",
"for",
"f",
",",
"v",
"in",
"self",
".",
"flags",
".",
"items",
"(",
")",
"if",
"v",
"]",
"s",
".",
"append",
"(",
"'flags=['",
"+",
"', '",
".",
"join",
"(",
"names",
")",
"+",
"']'",
")",
"names",
"=",
"[",
"t",
".",
"__name__",
"for",
"t",
",",
"v",
"in",
"self",
".",
"traps",
".",
"items",
"(",
")",
"if",
"v",
"]",
"s",
".",
"append",
"(",
"'traps=['",
"+",
"', '",
".",
"join",
"(",
"names",
")",
"+",
"']'",
")",
"return",
"', '",
".",
"join",
"(",
"s",
")",
"+",
"')'"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/_pydecimal.py#L3985-L3996 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/kfac/python/ops/estimator.py | python | FisherEstimator.__init__ | (self,
variables,
cov_ema_decay,
damping,
layer_collection,
estimation_mode="gradients") | Create a FisherEstimator object.
Args:
variables: A list of the variables for which to estimate the Fisher. This
must match the variables registered in layer_collection (if it is not
None).
cov_ema_decay: The decay factor used when calculating the covariance
estimate moving averages.
damping: The damping factor used to stabilize training due to errors in
the local approximation with the Fisher information matrix, and to
regularize the update direction by making it closer to the gradient.
(Higher damping means the update looks more like a standard gradient
update - see Tikhonov regularization.)
layer_collection: The layer collection object, which holds the fisher
blocks, kronecker factors, and losses associated with the
graph.
estimation_mode: The type of estimator to use for the Fishers. Can be
'gradients', 'empirical', 'curvature_propagation', or 'exact'.
(Default: 'gradients'). 'gradients' is the basic estimation approach
from the original K-FAC paper. 'empirical' computes the 'empirical'
Fisher information matrix (which uses the data's distribution for the
targets, as opposed to the true Fisher which uses the model's
distribution) and requires that each registered loss have specified
targets. 'curvature_propagation' is a method which estimates the
Fisher using self-products of random 1/-1 vectors times "half-factors"
of the Fisher, as described here: https://arxiv.org/abs/1206.6464 .
Finally, 'exact' is the obvious generalization of Curvature
Propagation to compute the exact Fisher (modulo any additional
diagonal or Kronecker approximations) by looping over one-hot vectors
for each coordinate of the output instead of using 1/-1 vectors. It
is more expensive to compute than the other three options by a factor
equal to the output dimension, roughly speaking.
Raises:
ValueError: If no losses have been registered with layer_collection. | Create a FisherEstimator object. | [
"Create",
"a",
"FisherEstimator",
"object",
"."
] | def __init__(self,
variables,
cov_ema_decay,
damping,
layer_collection,
estimation_mode="gradients"):
"""Create a FisherEstimator object.
Args:
variables: A list of the variables for which to estimate the Fisher. This
must match the variables registered in layer_collection (if it is not
None).
cov_ema_decay: The decay factor used when calculating the covariance
estimate moving averages.
damping: The damping factor used to stabilize training due to errors in
the local approximation with the Fisher information matrix, and to
regularize the update direction by making it closer to the gradient.
(Higher damping means the update looks more like a standard gradient
update - see Tikhonov regularization.)
layer_collection: The layer collection object, which holds the fisher
blocks, kronecker factors, and losses associated with the
graph.
estimation_mode: The type of estimator to use for the Fishers. Can be
'gradients', 'empirical', 'curvature_propagation', or 'exact'.
(Default: 'gradients'). 'gradients' is the basic estimation approach
from the original K-FAC paper. 'empirical' computes the 'empirical'
Fisher information matrix (which uses the data's distribution for the
targets, as opposed to the true Fisher which uses the model's
distribution) and requires that each registered loss have specified
targets. 'curvature_propagation' is a method which estimates the
Fisher using self-products of random 1/-1 vectors times "half-factors"
of the Fisher, as described here: https://arxiv.org/abs/1206.6464 .
Finally, 'exact' is the obvious generalization of Curvature
Propagation to compute the exact Fisher (modulo any additional
diagonal or Kronecker approximations) by looping over one-hot vectors
for each coordinate of the output instead of using 1/-1 vectors. It
is more expensive to compute than the other three options by a factor
equal to the output dimension, roughly speaking.
Raises:
ValueError: If no losses have been registered with layer_collection.
"""
self._variables = variables
self._damping = damping
self._estimation_mode = estimation_mode
self._layers = layer_collection
self._layers.create_subgraph()
self._check_registration(variables)
self._gradient_fns = {
"gradients": self._get_grads_lists_gradients,
"empirical": self._get_grads_lists_empirical,
"curvature_prop": self._get_grads_lists_curvature_prop,
"exact": self._get_grads_lists_exact
}
setup = self._setup(cov_ema_decay)
self.cov_update_op, self.inv_update_op, self.inv_updates_dict = setup | [
"def",
"__init__",
"(",
"self",
",",
"variables",
",",
"cov_ema_decay",
",",
"damping",
",",
"layer_collection",
",",
"estimation_mode",
"=",
"\"gradients\"",
")",
":",
"self",
".",
"_variables",
"=",
"variables",
"self",
".",
"_damping",
"=",
"damping",
"self",
".",
"_estimation_mode",
"=",
"estimation_mode",
"self",
".",
"_layers",
"=",
"layer_collection",
"self",
".",
"_layers",
".",
"create_subgraph",
"(",
")",
"self",
".",
"_check_registration",
"(",
"variables",
")",
"self",
".",
"_gradient_fns",
"=",
"{",
"\"gradients\"",
":",
"self",
".",
"_get_grads_lists_gradients",
",",
"\"empirical\"",
":",
"self",
".",
"_get_grads_lists_empirical",
",",
"\"curvature_prop\"",
":",
"self",
".",
"_get_grads_lists_curvature_prop",
",",
"\"exact\"",
":",
"self",
".",
"_get_grads_lists_exact",
"}",
"setup",
"=",
"self",
".",
"_setup",
"(",
"cov_ema_decay",
")",
"self",
".",
"cov_update_op",
",",
"self",
".",
"inv_update_op",
",",
"self",
".",
"inv_updates_dict",
"=",
"setup"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/kfac/python/ops/estimator.py#L34-L90 | ||
wjakob/tbb | 9e219e24fe223b299783200f217e9d27790a87b0 | python/tbb/pool.py | python | Pool.imap_unordered | (self, func, iterable, chunksize=1) | return iter(collector) | The same as imap() except that the ordering of the results
from the returned iterator should be considered
arbitrary. (Only when there is only one worker process is the
order guaranteed to be "correct".) | The same as imap() except that the ordering of the results
from the returned iterator should be considered
arbitrary. (Only when there is only one worker process is the
order guaranteed to be "correct".) | [
"The",
"same",
"as",
"imap",
"()",
"except",
"that",
"the",
"ordering",
"of",
"the",
"results",
"from",
"the",
"returned",
"iterator",
"should",
"be",
"considered",
"arbitrary",
".",
"(",
"Only",
"when",
"there",
"is",
"only",
"one",
"worker",
"process",
"is",
"the",
"order",
"guaranteed",
"to",
"be",
"correct",
".",
")"
] | def imap_unordered(self, func, iterable, chunksize=1):
"""The same as imap() except that the ordering of the results
from the returned iterator should be considered
arbitrary. (Only when there is only one worker process is the
order guaranteed to be "correct".)"""
collector = UnorderedResultCollector()
self._create_sequences(func, iterable, chunksize, collector)
return iter(collector) | [
"def",
"imap_unordered",
"(",
"self",
",",
"func",
",",
"iterable",
",",
"chunksize",
"=",
"1",
")",
":",
"collector",
"=",
"UnorderedResultCollector",
"(",
")",
"self",
".",
"_create_sequences",
"(",
"func",
",",
"iterable",
",",
"chunksize",
",",
"collector",
")",
"return",
"iter",
"(",
"collector",
")"
] | https://github.com/wjakob/tbb/blob/9e219e24fe223b299783200f217e9d27790a87b0/python/tbb/pool.py#L134-L141 | |
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/import/vissim/tls_vissimXML2SUMOnet_update.py | python | dict_from_node_attributes | (node) | return dict((attn, node.getAttribute(attn)) for attn in
node.attributes.keys()) | takes a xml node and returns a dictionary with its attributes | takes a xml node and returns a dictionary with its attributes | [
"takes",
"a",
"xml",
"node",
"and",
"returns",
"a",
"dictionary",
"with",
"its",
"attributes"
] | def dict_from_node_attributes(node):
"""takes a xml node and returns a dictionary with its attributes"""
return dict((attn, node.getAttribute(attn)) for attn in
node.attributes.keys()) | [
"def",
"dict_from_node_attributes",
"(",
"node",
")",
":",
"return",
"dict",
"(",
"(",
"attn",
",",
"node",
".",
"getAttribute",
"(",
"attn",
")",
")",
"for",
"attn",
"in",
"node",
".",
"attributes",
".",
"keys",
"(",
")",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/import/vissim/tls_vissimXML2SUMOnet_update.py#L37-L40 | |
qgis/QGIS | 15a77662d4bb712184f6aa60d0bd663010a76a75 | python/plugins/db_manager/db_plugins/postgis/connector.py | python | PostGisDBConnector.deleteTable | (self, table) | Deletes table and its reference in either geometry_columns or raster_columns | Deletes table and its reference in either geometry_columns or raster_columns | [
"Deletes",
"table",
"and",
"its",
"reference",
"in",
"either",
"geometry_columns",
"or",
"raster_columns"
] | def deleteTable(self, table):
"""Deletes table and its reference in either geometry_columns or raster_columns """
schema, tablename = self.getSchemaTableName(table)
schema_part = u"%s, " % self.quoteString(schema) if schema is not None else ""
if self.isVectorTable(table):
sql = u"SELECT DropGeometryTable(%s%s)" % (schema_part, self.quoteString(tablename))
elif self.isRasterTable(table):
# Fix #8521: delete raster table and references from raster_columns table
sql = u"DROP TABLE %s" % self.quoteId(table)
else:
sql = u"DROP TABLE %s" % self.quoteId(table)
self._execute_and_commit(sql) | [
"def",
"deleteTable",
"(",
"self",
",",
"table",
")",
":",
"schema",
",",
"tablename",
"=",
"self",
".",
"getSchemaTableName",
"(",
"table",
")",
"schema_part",
"=",
"u\"%s, \"",
"%",
"self",
".",
"quoteString",
"(",
"schema",
")",
"if",
"schema",
"is",
"not",
"None",
"else",
"\"\"",
"if",
"self",
".",
"isVectorTable",
"(",
"table",
")",
":",
"sql",
"=",
"u\"SELECT DropGeometryTable(%s%s)\"",
"%",
"(",
"schema_part",
",",
"self",
".",
"quoteString",
"(",
"tablename",
")",
")",
"elif",
"self",
".",
"isRasterTable",
"(",
"table",
")",
":",
"# Fix #8521: delete raster table and references from raster_columns table",
"sql",
"=",
"u\"DROP TABLE %s\"",
"%",
"self",
".",
"quoteId",
"(",
"table",
")",
"else",
":",
"sql",
"=",
"u\"DROP TABLE %s\"",
"%",
"self",
".",
"quoteId",
"(",
"table",
")",
"self",
".",
"_execute_and_commit",
"(",
"sql",
")"
] | https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/db_manager/db_plugins/postgis/connector.py#L902-L913 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/optimize/optimize.py | python | rosen_hess | (x) | return H | The Hessian matrix of the Rosenbrock function.
Parameters
----------
x : array_like
1-D array of points at which the Hessian matrix is to be computed.
Returns
-------
rosen_hess : ndarray
The Hessian matrix of the Rosenbrock function at `x`.
See Also
--------
rosen, rosen_der, rosen_hess_prod | The Hessian matrix of the Rosenbrock function. | [
"The",
"Hessian",
"matrix",
"of",
"the",
"Rosenbrock",
"function",
"."
] | def rosen_hess(x):
"""
The Hessian matrix of the Rosenbrock function.
Parameters
----------
x : array_like
1-D array of points at which the Hessian matrix is to be computed.
Returns
-------
rosen_hess : ndarray
The Hessian matrix of the Rosenbrock function at `x`.
See Also
--------
rosen, rosen_der, rosen_hess_prod
"""
x = atleast_1d(x)
H = numpy.diag(-400 * x[:-1], 1) - numpy.diag(400 * x[:-1], -1)
diagonal = numpy.zeros(len(x), dtype=x.dtype)
diagonal[0] = 1200 * x[0]**2 - 400 * x[1] + 2
diagonal[-1] = 200
diagonal[1:-1] = 202 + 1200 * x[1:-1]**2 - 400 * x[2:]
H = H + numpy.diag(diagonal)
return H | [
"def",
"rosen_hess",
"(",
"x",
")",
":",
"x",
"=",
"atleast_1d",
"(",
"x",
")",
"H",
"=",
"numpy",
".",
"diag",
"(",
"-",
"400",
"*",
"x",
"[",
":",
"-",
"1",
"]",
",",
"1",
")",
"-",
"numpy",
".",
"diag",
"(",
"400",
"*",
"x",
"[",
":",
"-",
"1",
"]",
",",
"-",
"1",
")",
"diagonal",
"=",
"numpy",
".",
"zeros",
"(",
"len",
"(",
"x",
")",
",",
"dtype",
"=",
"x",
".",
"dtype",
")",
"diagonal",
"[",
"0",
"]",
"=",
"1200",
"*",
"x",
"[",
"0",
"]",
"**",
"2",
"-",
"400",
"*",
"x",
"[",
"1",
"]",
"+",
"2",
"diagonal",
"[",
"-",
"1",
"]",
"=",
"200",
"diagonal",
"[",
"1",
":",
"-",
"1",
"]",
"=",
"202",
"+",
"1200",
"*",
"x",
"[",
"1",
":",
"-",
"1",
"]",
"**",
"2",
"-",
"400",
"*",
"x",
"[",
"2",
":",
"]",
"H",
"=",
"H",
"+",
"numpy",
".",
"diag",
"(",
"diagonal",
")",
"return",
"H"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/optimize/optimize.py#L232-L258 | |
esa/pykep | b410363653623730b577de257c04b0e0289f2014 | pykep/phasing/_knn.py | python | knn.find_neighbours | (self, query_planet, query_type='knn', *args, **kwargs) | return neighb, neighb_ids, dists | Finds the neighbours of a given planet at a given epoch. The user may query for the
k-nearest neighbours or for all neighbours within a given distance
knn.find_neighbours(query_planet, query_type='knn', \*args, \*\*kwargs )
- query_planet: the planet we want to find neighbours of. Can be an integer, in which case it refers to the idx in self.asteroid_list
- query_type: one of 'knn' or 'ball'.
- \*args, \*\*args: according to the query type (read below)
Returns (neighb, neighb_ids, dists), where dist is only computed if 'knn' type query is made
The following kinds of spatial queries are currently implemented:
query_type = 'knn':
The kwarg 'k' determines how many k-nearest neighbours are returned
For arguments, see:
http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.query.html
query_type = 'ball':
The kwarg 'r' determines the distance within which all asteroids are returned.
For arguments, see:
http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.query_ball_point.html | Finds the neighbours of a given planet at a given epoch. The user may query for the
k-nearest neighbours or for all neighbours within a given distance | [
"Finds",
"the",
"neighbours",
"of",
"a",
"given",
"planet",
"at",
"a",
"given",
"epoch",
".",
"The",
"user",
"may",
"query",
"for",
"the",
"k",
"-",
"nearest",
"neighbours",
"or",
"for",
"all",
"neighbours",
"within",
"a",
"given",
"distance"
] | def find_neighbours(self, query_planet, query_type='knn', *args, **kwargs):
"""
Finds the neighbours of a given planet at a given epoch. The user may query for the
k-nearest neighbours or for all neighbours within a given distance
knn.find_neighbours(query_planet, query_type='knn', \*args, \*\*kwargs )
- query_planet: the planet we want to find neighbours of. Can be an integer, in which case it refers to the idx in self.asteroid_list
- query_type: one of 'knn' or 'ball'.
- \*args, \*\*args: according to the query type (read below)
Returns (neighb, neighb_ids, dists), where dist is only computed if 'knn' type query is made
The following kinds of spatial queries are currently implemented:
query_type = 'knn':
The kwarg 'k' determines how many k-nearest neighbours are returned
For arguments, see:
http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.query.html
query_type = 'ball':
The kwarg 'r' determines the distance within which all asteroids are returned.
For arguments, see:
http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.query_ball_point.html
"""
if type(query_planet) == int:
query_planet = self._asteroids[query_planet]
# generate the query vector
x = query_planet.eph(self._t)
if self._metric == 'euclidean':
x = self._eph_normalize(x)
else:
DV1, DV2 = self._orbital_metric(x[0], x[1])
x = DV1 + DV2
if query_type == 'knn':
# Query for the k nearest neighbors
# http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.query.html
dists, idxs = self._kdtree.query(x, *args, **kwargs)
elif query_type == 'ball':
# Query for all neighbors within a sphere of given radius
# http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.query_ball_point.html
idxs = self._kdtree.query_ball_point(x, *args, **kwargs)
dists = [None] * len(idxs)
else:
raise Exception('Unrecognized query type: %s' % str(query_type))
neighb = [
# (ast. object, ast. ID, distance)
(self._asteroids[i], i, d)
for i, d in zip(idxs, dists)
]
# split into three lists, one of objects, one of IDs, and one for
# distances
neighb, neighb_ids, dists = list(
zip(*neighb)) if neighb != [] else ([], [], [])
return neighb, neighb_ids, dists | [
"def",
"find_neighbours",
"(",
"self",
",",
"query_planet",
",",
"query_type",
"=",
"'knn'",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"type",
"(",
"query_planet",
")",
"==",
"int",
":",
"query_planet",
"=",
"self",
".",
"_asteroids",
"[",
"query_planet",
"]",
"# generate the query vector",
"x",
"=",
"query_planet",
".",
"eph",
"(",
"self",
".",
"_t",
")",
"if",
"self",
".",
"_metric",
"==",
"'euclidean'",
":",
"x",
"=",
"self",
".",
"_eph_normalize",
"(",
"x",
")",
"else",
":",
"DV1",
",",
"DV2",
"=",
"self",
".",
"_orbital_metric",
"(",
"x",
"[",
"0",
"]",
",",
"x",
"[",
"1",
"]",
")",
"x",
"=",
"DV1",
"+",
"DV2",
"if",
"query_type",
"==",
"'knn'",
":",
"# Query for the k nearest neighbors",
"# http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.query.html",
"dists",
",",
"idxs",
"=",
"self",
".",
"_kdtree",
".",
"query",
"(",
"x",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"elif",
"query_type",
"==",
"'ball'",
":",
"# Query for all neighbors within a sphere of given radius",
"# http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.query_ball_point.html",
"idxs",
"=",
"self",
".",
"_kdtree",
".",
"query_ball_point",
"(",
"x",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"dists",
"=",
"[",
"None",
"]",
"*",
"len",
"(",
"idxs",
")",
"else",
":",
"raise",
"Exception",
"(",
"'Unrecognized query type: %s'",
"%",
"str",
"(",
"query_type",
")",
")",
"neighb",
"=",
"[",
"# (ast. object, ast. ID, distance)",
"(",
"self",
".",
"_asteroids",
"[",
"i",
"]",
",",
"i",
",",
"d",
")",
"for",
"i",
",",
"d",
"in",
"zip",
"(",
"idxs",
",",
"dists",
")",
"]",
"# split into three lists, one of objects, one of IDs, and one for",
"# distances",
"neighb",
",",
"neighb_ids",
",",
"dists",
"=",
"list",
"(",
"zip",
"(",
"*",
"neighb",
")",
")",
"if",
"neighb",
"!=",
"[",
"]",
"else",
"(",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
")",
"return",
"neighb",
",",
"neighb_ids",
",",
"dists"
] | https://github.com/esa/pykep/blob/b410363653623730b577de257c04b0e0289f2014/pykep/phasing/_knn.py#L124-L183 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/excel/_openpyxl.py | python | _OpenpyxlWriter._convert_to_side | (cls, side_spec) | return Side(**side_kwargs) | Convert ``side_spec`` to an openpyxl v2 Side object.
Parameters
----------
side_spec : str, dict
A string specifying the border style, or a dict with zero or more
of the following keys (or their synonyms).
'style' ('border_style')
'color'
Returns
-------
side : openpyxl.styles.Side | Convert ``side_spec`` to an openpyxl v2 Side object. | [
"Convert",
"side_spec",
"to",
"an",
"openpyxl",
"v2",
"Side",
"object",
"."
] | def _convert_to_side(cls, side_spec):
"""
Convert ``side_spec`` to an openpyxl v2 Side object.
Parameters
----------
side_spec : str, dict
A string specifying the border style, or a dict with zero or more
of the following keys (or their synonyms).
'style' ('border_style')
'color'
Returns
-------
side : openpyxl.styles.Side
"""
from openpyxl.styles import Side
_side_key_map = {"border_style": "style"}
if isinstance(side_spec, str):
return Side(style=side_spec)
side_kwargs = {}
for k, v in side_spec.items():
if k in _side_key_map:
k = _side_key_map[k]
if k == "color":
v = cls._convert_to_color(v)
side_kwargs[k] = v
return Side(**side_kwargs) | [
"def",
"_convert_to_side",
"(",
"cls",
",",
"side_spec",
")",
":",
"from",
"openpyxl",
".",
"styles",
"import",
"Side",
"_side_key_map",
"=",
"{",
"\"border_style\"",
":",
"\"style\"",
"}",
"if",
"isinstance",
"(",
"side_spec",
",",
"str",
")",
":",
"return",
"Side",
"(",
"style",
"=",
"side_spec",
")",
"side_kwargs",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"side_spec",
".",
"items",
"(",
")",
":",
"if",
"k",
"in",
"_side_key_map",
":",
"k",
"=",
"_side_key_map",
"[",
"k",
"]",
"if",
"k",
"==",
"\"color\"",
":",
"v",
"=",
"cls",
".",
"_convert_to_color",
"(",
"v",
")",
"side_kwargs",
"[",
"k",
"]",
"=",
"v",
"return",
"Side",
"(",
"*",
"*",
"side_kwargs",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/excel/_openpyxl.py#L273-L305 | |
balint256/gr-baz | 937834ce3520b730277328d8e0cdebb3f2b1aafc | python/doa_compass_plotter.py | python | compass_plotter.set_profile | (self, key='', color_spec=(0, 0, 0), fill=True, profile=[]) | Set a profile onto the compass rose.
A polar coordinate tuple is of the form (radius, angle).
Where radius is between -1 and 1 and angle is in degrees.
@param key unique identifier for profile
@param color_spec a 3-tuple gl color spec
@param fill true to fill in the polygon or false for outline
@param profile a list of polar coordinate tuples | Set a profile onto the compass rose.
A polar coordinate tuple is of the form (radius, angle).
Where radius is between -1 and 1 and angle is in degrees. | [
"Set",
"a",
"profile",
"onto",
"the",
"compass",
"rose",
".",
"A",
"polar",
"coordinate",
"tuple",
"is",
"of",
"the",
"form",
"(",
"radius",
"angle",
")",
".",
"Where",
"radius",
"is",
"between",
"-",
"1",
"and",
"1",
"and",
"angle",
"is",
"in",
"degrees",
"."
] | def set_profile(self, key='', color_spec=(0, 0, 0), fill=True, profile=[]):
"""
Set a profile onto the compass rose.
A polar coordinate tuple is of the form (radius, angle).
Where radius is between -1 and 1 and angle is in degrees.
@param key unique identifier for profile
@param color_spec a 3-tuple gl color spec
@param fill true to fill in the polygon or false for outline
@param profile a list of polar coordinate tuples
"""
self.lock()
self._profiles[key] = color_spec, fill, profile
self._profile_cache.changed(True)
self.unlock() | [
"def",
"set_profile",
"(",
"self",
",",
"key",
"=",
"''",
",",
"color_spec",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
",",
"fill",
"=",
"True",
",",
"profile",
"=",
"[",
"]",
")",
":",
"self",
".",
"lock",
"(",
")",
"self",
".",
"_profiles",
"[",
"key",
"]",
"=",
"color_spec",
",",
"fill",
",",
"profile",
"self",
".",
"_profile_cache",
".",
"changed",
"(",
"True",
")",
"self",
".",
"unlock",
"(",
")"
] | https://github.com/balint256/gr-baz/blob/937834ce3520b730277328d8e0cdebb3f2b1aafc/python/doa_compass_plotter.py#L141-L154 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/Tkinter.py | python | Tk.__init__ | (self, screenName=None, baseName=None, className='Tk',
useTk=1, sync=0, use=None) | Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
be created. BASENAME will be used for the identification of the profile file (see
readprofile).
It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
is the name of the widget class. | Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
be created. BASENAME will be used for the identification of the profile file (see
readprofile).
It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
is the name of the widget class. | [
"Return",
"a",
"new",
"Toplevel",
"widget",
"on",
"screen",
"SCREENNAME",
".",
"A",
"new",
"Tcl",
"interpreter",
"will",
"be",
"created",
".",
"BASENAME",
"will",
"be",
"used",
"for",
"the",
"identification",
"of",
"the",
"profile",
"file",
"(",
"see",
"readprofile",
")",
".",
"It",
"is",
"constructed",
"from",
"sys",
".",
"argv",
"[",
"0",
"]",
"without",
"extensions",
"if",
"None",
"is",
"given",
".",
"CLASSNAME",
"is",
"the",
"name",
"of",
"the",
"widget",
"class",
"."
] | def __init__(self, screenName=None, baseName=None, className='Tk',
useTk=1, sync=0, use=None):
"""Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
be created. BASENAME will be used for the identification of the profile file (see
readprofile).
It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
is the name of the widget class."""
self.master = None
self.children = {}
self._tkloaded = 0
# to avoid recursions in the getattr code in case of failure, we
# ensure that self.tk is always _something_.
self.tk = None
if baseName is None:
import os
baseName = os.path.basename(sys.argv[0])
baseName, ext = os.path.splitext(baseName)
if ext not in ('.py', '.pyc', '.pyo'):
baseName = baseName + ext
interactive = 0
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
if useTk:
self._loadtk()
if not sys.flags.ignore_environment:
# Issue #16248: Honor the -E flag to avoid code injection.
self.readprofile(baseName, className) | [
"def",
"__init__",
"(",
"self",
",",
"screenName",
"=",
"None",
",",
"baseName",
"=",
"None",
",",
"className",
"=",
"'Tk'",
",",
"useTk",
"=",
"1",
",",
"sync",
"=",
"0",
",",
"use",
"=",
"None",
")",
":",
"self",
".",
"master",
"=",
"None",
"self",
".",
"children",
"=",
"{",
"}",
"self",
".",
"_tkloaded",
"=",
"0",
"# to avoid recursions in the getattr code in case of failure, we",
"# ensure that self.tk is always _something_.",
"self",
".",
"tk",
"=",
"None",
"if",
"baseName",
"is",
"None",
":",
"import",
"os",
"baseName",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
"baseName",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"baseName",
")",
"if",
"ext",
"not",
"in",
"(",
"'.py'",
",",
"'.pyc'",
",",
"'.pyo'",
")",
":",
"baseName",
"=",
"baseName",
"+",
"ext",
"interactive",
"=",
"0",
"self",
".",
"tk",
"=",
"_tkinter",
".",
"create",
"(",
"screenName",
",",
"baseName",
",",
"className",
",",
"interactive",
",",
"wantobjects",
",",
"useTk",
",",
"sync",
",",
"use",
")",
"if",
"useTk",
":",
"self",
".",
"_loadtk",
"(",
")",
"if",
"not",
"sys",
".",
"flags",
".",
"ignore_environment",
":",
"# Issue #16248: Honor the -E flag to avoid code injection.",
"self",
".",
"readprofile",
"(",
"baseName",
",",
"className",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/Tkinter.py#L1805-L1830 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/core/setup.py | python | visibility_define | (config) | Return the define value to use for NPY_VISIBILITY_HIDDEN (may be empty
string). | Return the define value to use for NPY_VISIBILITY_HIDDEN (may be empty
string). | [
"Return",
"the",
"define",
"value",
"to",
"use",
"for",
"NPY_VISIBILITY_HIDDEN",
"(",
"may",
"be",
"empty",
"string",
")",
"."
] | def visibility_define(config):
"""Return the define value to use for NPY_VISIBILITY_HIDDEN (may be empty
string)."""
hide = '__attribute__((visibility("hidden")))'
if config.check_gcc_function_attribute(hide, 'hideme'):
return hide
else:
return '' | [
"def",
"visibility_define",
"(",
"config",
")",
":",
"hide",
"=",
"'__attribute__((visibility(\"hidden\")))'",
"if",
"config",
".",
"check_gcc_function_attribute",
"(",
"hide",
",",
"'hideme'",
")",
":",
"return",
"hide",
"else",
":",
"return",
"''"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/core/setup.py#L386-L393 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/api.py | python | head | (url, **kwargs) | return request('head', url, **kwargs) | Sends a HEAD request.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response | Sends a HEAD request. | [
"Sends",
"a",
"HEAD",
"request",
"."
] | def head(url, **kwargs):
"""Sends a HEAD request.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', False)
return request('head', url, **kwargs) | [
"def",
"head",
"(",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'allow_redirects'",
",",
"False",
")",
"return",
"request",
"(",
"'head'",
",",
"url",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/api.py#L85-L95 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/defchararray.py | python | zfill | (a, width) | return _vec_string(
a_arr, (a_arr.dtype.type, size), 'zfill', (width_arr,)) | Return the numeric string left-filled with zeros
Calls `str.zfill` element-wise.
Parameters
----------
a : array_like, {str, unicode}
Input array.
width : int
Width of string to left-fill elements in `a`.
Returns
-------
out : ndarray, {str, unicode}
Output array of str or unicode, depending on input type
See also
--------
str.zfill | Return the numeric string left-filled with zeros | [
"Return",
"the",
"numeric",
"string",
"left",
"-",
"filled",
"with",
"zeros"
] | def zfill(a, width):
"""
Return the numeric string left-filled with zeros
Calls `str.zfill` element-wise.
Parameters
----------
a : array_like, {str, unicode}
Input array.
width : int
Width of string to left-fill elements in `a`.
Returns
-------
out : ndarray, {str, unicode}
Output array of str or unicode, depending on input type
See also
--------
str.zfill
"""
a_arr = numpy.asarray(a)
width_arr = numpy.asarray(width)
size = long(numpy.max(width_arr.flat))
return _vec_string(
a_arr, (a_arr.dtype.type, size), 'zfill', (width_arr,)) | [
"def",
"zfill",
"(",
"a",
",",
"width",
")",
":",
"a_arr",
"=",
"numpy",
".",
"asarray",
"(",
"a",
")",
"width_arr",
"=",
"numpy",
".",
"asarray",
"(",
"width",
")",
"size",
"=",
"long",
"(",
"numpy",
".",
"max",
"(",
"width_arr",
".",
"flat",
")",
")",
"return",
"_vec_string",
"(",
"a_arr",
",",
"(",
"a_arr",
".",
"dtype",
".",
"type",
",",
"size",
")",
",",
"'zfill'",
",",
"(",
"width_arr",
",",
")",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/defchararray.py#L1576-L1603 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/_abcoll.py | python | Sequence.index | (self, value) | S.index(value) -> integer -- return first index of value.
Raises ValueError if the value is not present. | S.index(value) -> integer -- return first index of value.
Raises ValueError if the value is not present. | [
"S",
".",
"index",
"(",
"value",
")",
"-",
">",
"integer",
"--",
"return",
"first",
"index",
"of",
"value",
".",
"Raises",
"ValueError",
"if",
"the",
"value",
"is",
"not",
"present",
"."
] | def index(self, value):
'''S.index(value) -> integer -- return first index of value.
Raises ValueError if the value is not present.
'''
for i, v in enumerate(self):
if v == value:
return i
raise ValueError | [
"def",
"index",
"(",
"self",
",",
"value",
")",
":",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"self",
")",
":",
"if",
"v",
"==",
"value",
":",
"return",
"i",
"raise",
"ValueError"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/_abcoll.py#L597-L604 | ||
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/common.py | python | BuildFileTargets | (target_list, build_file) | return [p for p in target_list if BuildFile(p) == build_file] | From a target_list, returns the subset from the specified build_file. | From a target_list, returns the subset from the specified build_file. | [
"From",
"a",
"target_list",
"returns",
"the",
"subset",
"from",
"the",
"specified",
"build_file",
"."
] | def BuildFileTargets(target_list, build_file):
"""From a target_list, returns the subset from the specified build_file.
"""
return [p for p in target_list if BuildFile(p) == build_file] | [
"def",
"BuildFileTargets",
"(",
"target_list",
",",
"build_file",
")",
":",
"return",
"[",
"p",
"for",
"p",
"in",
"target_list",
"if",
"BuildFile",
"(",
"p",
")",
"==",
"build_file",
"]"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/common.py#L278-L281 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/asyncio/locks.py | python | Event.clear | (self) | Reset the internal flag to false. Subsequently, coroutines calling
wait() will block until set() is called to set the internal flag
to true again. | Reset the internal flag to false. Subsequently, coroutines calling
wait() will block until set() is called to set the internal flag
to true again. | [
"Reset",
"the",
"internal",
"flag",
"to",
"false",
".",
"Subsequently",
"coroutines",
"calling",
"wait",
"()",
"will",
"block",
"until",
"set",
"()",
"is",
"called",
"to",
"set",
"the",
"internal",
"flag",
"to",
"true",
"again",
"."
] | def clear(self):
"""Reset the internal flag to false. Subsequently, coroutines calling
wait() will block until set() is called to set the internal flag
to true again."""
self._value = False | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"_value",
"=",
"False"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/asyncio/locks.py#L274-L278 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/turtle.py | python | RawTurtle.ondrag | (self, fun, btn=1, add=None) | Bind fun to mouse-move event on this turtle on canvas.
Arguments:
fun -- a function with two arguments, to which will be assigned
the coordinates of the clicked point on the canvas.
btn -- number of the mouse-button defaults to 1 (left mouse button).
Every sequence of mouse-move-events on a turtle is preceded by a
mouse-click event on that turtle.
Example (for a Turtle instance named turtle):
>>> turtle.ondrag(turtle.goto)
Subsequently clicking and dragging a Turtle will move it
across the screen thereby producing handdrawings (if pen is
down). | Bind fun to mouse-move event on this turtle on canvas. | [
"Bind",
"fun",
"to",
"mouse",
"-",
"move",
"event",
"on",
"this",
"turtle",
"on",
"canvas",
"."
] | def ondrag(self, fun, btn=1, add=None):
"""Bind fun to mouse-move event on this turtle on canvas.
Arguments:
fun -- a function with two arguments, to which will be assigned
the coordinates of the clicked point on the canvas.
btn -- number of the mouse-button defaults to 1 (left mouse button).
Every sequence of mouse-move-events on a turtle is preceded by a
mouse-click event on that turtle.
Example (for a Turtle instance named turtle):
>>> turtle.ondrag(turtle.goto)
Subsequently clicking and dragging a Turtle will move it
across the screen thereby producing handdrawings (if pen is
down).
"""
self.screen._ondrag(self.turtle._item, fun, btn, add) | [
"def",
"ondrag",
"(",
"self",
",",
"fun",
",",
"btn",
"=",
"1",
",",
"add",
"=",
"None",
")",
":",
"self",
".",
"screen",
".",
"_ondrag",
"(",
"self",
".",
"turtle",
".",
"_item",
",",
"fun",
",",
"btn",
",",
"add",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/turtle.py#L3461-L3479 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.AutoCompSetCaseInsensitiveBehaviour | (*args, **kwargs) | return _stc.StyledTextCtrl_AutoCompSetCaseInsensitiveBehaviour(*args, **kwargs) | AutoCompSetCaseInsensitiveBehaviour(self, int behaviour) | AutoCompSetCaseInsensitiveBehaviour(self, int behaviour) | [
"AutoCompSetCaseInsensitiveBehaviour",
"(",
"self",
"int",
"behaviour",
")"
] | def AutoCompSetCaseInsensitiveBehaviour(*args, **kwargs):
"""AutoCompSetCaseInsensitiveBehaviour(self, int behaviour)"""
return _stc.StyledTextCtrl_AutoCompSetCaseInsensitiveBehaviour(*args, **kwargs) | [
"def",
"AutoCompSetCaseInsensitiveBehaviour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_AutoCompSetCaseInsensitiveBehaviour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L5542-L5544 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/retdec-3.2/scripts/type_extractor/type_extractor/io.py | python | str_types_sub | (type_text, name) | return str_types_sub_no_array(type_text) | Substitutes type made of few basic types. | Substitutes type made of few basic types. | [
"Substitutes",
"type",
"made",
"of",
"few",
"basic",
"types",
"."
] | def str_types_sub(type_text, name):
"""Substitutes type made of few basic types."""
if '[' in type_text:
return array_sub(type_text)
return str_types_sub_no_array(type_text) | [
"def",
"str_types_sub",
"(",
"type_text",
",",
"name",
")",
":",
"if",
"'['",
"in",
"type_text",
":",
"return",
"array_sub",
"(",
"type_text",
")",
"return",
"str_types_sub_no_array",
"(",
"type_text",
")"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/retdec-3.2/scripts/type_extractor/type_extractor/io.py#L121-L126 | |
neoml-lib/neoml | a0d370fba05269a1b2258cef126f77bbd2054a3e | NeoML/Python/neoml/Dnn/Crf.py | python | Crf.class_count | (self, class_count) | Sets the number of classes in the CRF. | Sets the number of classes in the CRF. | [
"Sets",
"the",
"number",
"of",
"classes",
"in",
"the",
"CRF",
"."
] | def class_count(self, class_count):
"""Sets the number of classes in the CRF.
"""
if int(class_count) < 1:
raise ValueError('The `class_count` must be > 0.')
self._internal.set_class_count(int(class_count)) | [
"def",
"class_count",
"(",
"self",
",",
"class_count",
")",
":",
"if",
"int",
"(",
"class_count",
")",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"'The `class_count` must be > 0.'",
")",
"self",
".",
"_internal",
".",
"set_class_count",
"(",
"int",
"(",
"class_count",
")",
")"
] | https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/Crf.py#L108-L114 | ||
KratosMultiphysics/Kratos | 0000833054ed0503424eb28205d6508d9ca6cbbc | kratos/python_scripts/integration_values_extrapolation_to_nodes_process.py | python | IntegrationValuesExtrapolationToNodesProcess.ExecuteFinalize | (self) | This method is executed at the end of the simulation
Keyword arguments:
self -- It signifies an instance of a class. | This method is executed at the end of the simulation | [
"This",
"method",
"is",
"executed",
"at",
"the",
"end",
"of",
"the",
"simulation"
] | def ExecuteFinalize(self):
""" This method is executed at the end of the simulation
Keyword arguments:
self -- It signifies an instance of a class.
"""
self.integration_values_extrapolation_to_nodes_process.ExecuteFinalize() | [
"def",
"ExecuteFinalize",
"(",
"self",
")",
":",
"self",
".",
"integration_values_extrapolation_to_nodes_process",
".",
"ExecuteFinalize",
"(",
")"
] | https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/kratos/python_scripts/integration_values_extrapolation_to_nodes_process.py#L71-L77 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/lib2to3/pgen2/conv.py | python | Converter.parse_graminit_c | (self, filename) | Parse the .c file written by pgen. (Internal)
The file looks as follows. The first two lines are always this:
#include "pgenheaders.h"
#include "grammar.h"
After that come four blocks:
1) one or more state definitions
2) a table defining dfas
3) a table defining labels
4) a struct defining the grammar
A state definition has the following form:
- one or more arc arrays, each of the form:
static arc arcs_<n>_<m>[<k>] = {
{<i>, <j>},
...
};
- followed by a state array, of the form:
static state states_<s>[<t>] = {
{<k>, arcs_<n>_<m>},
...
}; | Parse the .c file written by pgen. (Internal) | [
"Parse",
"the",
".",
"c",
"file",
"written",
"by",
"pgen",
".",
"(",
"Internal",
")"
] | def parse_graminit_c(self, filename):
"""Parse the .c file written by pgen. (Internal)
The file looks as follows. The first two lines are always this:
#include "pgenheaders.h"
#include "grammar.h"
After that come four blocks:
1) one or more state definitions
2) a table defining dfas
3) a table defining labels
4) a struct defining the grammar
A state definition has the following form:
- one or more arc arrays, each of the form:
static arc arcs_<n>_<m>[<k>] = {
{<i>, <j>},
...
};
- followed by a state array, of the form:
static state states_<s>[<t>] = {
{<k>, arcs_<n>_<m>},
...
};
"""
try:
f = open(filename)
except OSError as err:
print("Can't open %s: %s" % (filename, err))
return False
# The code below essentially uses f's iterator-ness!
lineno = 0
# Expect the two #include lines
lineno, line = lineno+1, next(f)
assert line == '#include "pgenheaders.h"\n', (lineno, line)
lineno, line = lineno+1, next(f)
assert line == '#include "grammar.h"\n', (lineno, line)
# Parse the state definitions
lineno, line = lineno+1, next(f)
allarcs = {}
states = []
while line.startswith("static arc "):
while line.startswith("static arc "):
mo = re.match(r"static arc arcs_(\d+)_(\d+)\[(\d+)\] = {$",
line)
assert mo, (lineno, line)
n, m, k = list(map(int, mo.groups()))
arcs = []
for _ in range(k):
lineno, line = lineno+1, next(f)
mo = re.match(r"\s+{(\d+), (\d+)},$", line)
assert mo, (lineno, line)
i, j = list(map(int, mo.groups()))
arcs.append((i, j))
lineno, line = lineno+1, next(f)
assert line == "};\n", (lineno, line)
allarcs[(n, m)] = arcs
lineno, line = lineno+1, next(f)
mo = re.match(r"static state states_(\d+)\[(\d+)\] = {$", line)
assert mo, (lineno, line)
s, t = list(map(int, mo.groups()))
assert s == len(states), (lineno, line)
state = []
for _ in range(t):
lineno, line = lineno+1, next(f)
mo = re.match(r"\s+{(\d+), arcs_(\d+)_(\d+)},$", line)
assert mo, (lineno, line)
k, n, m = list(map(int, mo.groups()))
arcs = allarcs[n, m]
assert k == len(arcs), (lineno, line)
state.append(arcs)
states.append(state)
lineno, line = lineno+1, next(f)
assert line == "};\n", (lineno, line)
lineno, line = lineno+1, next(f)
self.states = states
# Parse the dfas
dfas = {}
mo = re.match(r"static dfa dfas\[(\d+)\] = {$", line)
assert mo, (lineno, line)
ndfas = int(mo.group(1))
for i in range(ndfas):
lineno, line = lineno+1, next(f)
mo = re.match(r'\s+{(\d+), "(\w+)", (\d+), (\d+), states_(\d+),$',
line)
assert mo, (lineno, line)
symbol = mo.group(2)
number, x, y, z = list(map(int, mo.group(1, 3, 4, 5)))
assert self.symbol2number[symbol] == number, (lineno, line)
assert self.number2symbol[number] == symbol, (lineno, line)
assert x == 0, (lineno, line)
state = states[z]
assert y == len(state), (lineno, line)
lineno, line = lineno+1, next(f)
mo = re.match(r'\s+("(?:\\\d\d\d)*")},$', line)
assert mo, (lineno, line)
first = {}
rawbitset = eval(mo.group(1))
for i, c in enumerate(rawbitset):
byte = ord(c)
for j in range(8):
if byte & (1<<j):
first[i*8 + j] = 1
dfas[number] = (state, first)
lineno, line = lineno+1, next(f)
assert line == "};\n", (lineno, line)
self.dfas = dfas
# Parse the labels
labels = []
lineno, line = lineno+1, next(f)
mo = re.match(r"static label labels\[(\d+)\] = {$", line)
assert mo, (lineno, line)
nlabels = int(mo.group(1))
for i in range(nlabels):
lineno, line = lineno+1, next(f)
mo = re.match(r'\s+{(\d+), (0|"\w+")},$', line)
assert mo, (lineno, line)
x, y = mo.groups()
x = int(x)
if y == "0":
y = None
else:
y = eval(y)
labels.append((x, y))
lineno, line = lineno+1, next(f)
assert line == "};\n", (lineno, line)
self.labels = labels
# Parse the grammar struct
lineno, line = lineno+1, next(f)
assert line == "grammar _PyParser_Grammar = {\n", (lineno, line)
lineno, line = lineno+1, next(f)
mo = re.match(r"\s+(\d+),$", line)
assert mo, (lineno, line)
ndfas = int(mo.group(1))
assert ndfas == len(self.dfas)
lineno, line = lineno+1, next(f)
assert line == "\tdfas,\n", (lineno, line)
lineno, line = lineno+1, next(f)
mo = re.match(r"\s+{(\d+), labels},$", line)
assert mo, (lineno, line)
nlabels = int(mo.group(1))
assert nlabels == len(self.labels), (lineno, line)
lineno, line = lineno+1, next(f)
mo = re.match(r"\s+(\d+)$", line)
assert mo, (lineno, line)
start = int(mo.group(1))
assert start in self.number2symbol, (lineno, line)
self.start = start
lineno, line = lineno+1, next(f)
assert line == "};\n", (lineno, line)
try:
lineno, line = lineno+1, next(f)
except StopIteration:
pass
else:
assert 0, (lineno, line) | [
"def",
"parse_graminit_c",
"(",
"self",
",",
"filename",
")",
":",
"try",
":",
"f",
"=",
"open",
"(",
"filename",
")",
"except",
"OSError",
"as",
"err",
":",
"print",
"(",
"\"Can't open %s: %s\"",
"%",
"(",
"filename",
",",
"err",
")",
")",
"return",
"False",
"# The code below essentially uses f's iterator-ness!",
"lineno",
"=",
"0",
"# Expect the two #include lines",
"lineno",
",",
"line",
"=",
"lineno",
"+",
"1",
",",
"next",
"(",
"f",
")",
"assert",
"line",
"==",
"'#include \"pgenheaders.h\"\\n'",
",",
"(",
"lineno",
",",
"line",
")",
"lineno",
",",
"line",
"=",
"lineno",
"+",
"1",
",",
"next",
"(",
"f",
")",
"assert",
"line",
"==",
"'#include \"grammar.h\"\\n'",
",",
"(",
"lineno",
",",
"line",
")",
"# Parse the state definitions",
"lineno",
",",
"line",
"=",
"lineno",
"+",
"1",
",",
"next",
"(",
"f",
")",
"allarcs",
"=",
"{",
"}",
"states",
"=",
"[",
"]",
"while",
"line",
".",
"startswith",
"(",
"\"static arc \"",
")",
":",
"while",
"line",
".",
"startswith",
"(",
"\"static arc \"",
")",
":",
"mo",
"=",
"re",
".",
"match",
"(",
"r\"static arc arcs_(\\d+)_(\\d+)\\[(\\d+)\\] = {$\"",
",",
"line",
")",
"assert",
"mo",
",",
"(",
"lineno",
",",
"line",
")",
"n",
",",
"m",
",",
"k",
"=",
"list",
"(",
"map",
"(",
"int",
",",
"mo",
".",
"groups",
"(",
")",
")",
")",
"arcs",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"k",
")",
":",
"lineno",
",",
"line",
"=",
"lineno",
"+",
"1",
",",
"next",
"(",
"f",
")",
"mo",
"=",
"re",
".",
"match",
"(",
"r\"\\s+{(\\d+), (\\d+)},$\"",
",",
"line",
")",
"assert",
"mo",
",",
"(",
"lineno",
",",
"line",
")",
"i",
",",
"j",
"=",
"list",
"(",
"map",
"(",
"int",
",",
"mo",
".",
"groups",
"(",
")",
")",
")",
"arcs",
".",
"append",
"(",
"(",
"i",
",",
"j",
")",
")",
"lineno",
",",
"line",
"=",
"lineno",
"+",
"1",
",",
"next",
"(",
"f",
")",
"assert",
"line",
"==",
"\"};\\n\"",
",",
"(",
"lineno",
",",
"line",
")",
"allarcs",
"[",
"(",
"n",
",",
"m",
")",
"]",
"=",
"arcs",
"lineno",
",",
"line",
"=",
"lineno",
"+",
"1",
",",
"next",
"(",
"f",
")",
"mo",
"=",
"re",
".",
"match",
"(",
"r\"static state states_(\\d+)\\[(\\d+)\\] = {$\"",
",",
"line",
")",
"assert",
"mo",
",",
"(",
"lineno",
",",
"line",
")",
"s",
",",
"t",
"=",
"list",
"(",
"map",
"(",
"int",
",",
"mo",
".",
"groups",
"(",
")",
")",
")",
"assert",
"s",
"==",
"len",
"(",
"states",
")",
",",
"(",
"lineno",
",",
"line",
")",
"state",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"t",
")",
":",
"lineno",
",",
"line",
"=",
"lineno",
"+",
"1",
",",
"next",
"(",
"f",
")",
"mo",
"=",
"re",
".",
"match",
"(",
"r\"\\s+{(\\d+), arcs_(\\d+)_(\\d+)},$\"",
",",
"line",
")",
"assert",
"mo",
",",
"(",
"lineno",
",",
"line",
")",
"k",
",",
"n",
",",
"m",
"=",
"list",
"(",
"map",
"(",
"int",
",",
"mo",
".",
"groups",
"(",
")",
")",
")",
"arcs",
"=",
"allarcs",
"[",
"n",
",",
"m",
"]",
"assert",
"k",
"==",
"len",
"(",
"arcs",
")",
",",
"(",
"lineno",
",",
"line",
")",
"state",
".",
"append",
"(",
"arcs",
")",
"states",
".",
"append",
"(",
"state",
")",
"lineno",
",",
"line",
"=",
"lineno",
"+",
"1",
",",
"next",
"(",
"f",
")",
"assert",
"line",
"==",
"\"};\\n\"",
",",
"(",
"lineno",
",",
"line",
")",
"lineno",
",",
"line",
"=",
"lineno",
"+",
"1",
",",
"next",
"(",
"f",
")",
"self",
".",
"states",
"=",
"states",
"# Parse the dfas",
"dfas",
"=",
"{",
"}",
"mo",
"=",
"re",
".",
"match",
"(",
"r\"static dfa dfas\\[(\\d+)\\] = {$\"",
",",
"line",
")",
"assert",
"mo",
",",
"(",
"lineno",
",",
"line",
")",
"ndfas",
"=",
"int",
"(",
"mo",
".",
"group",
"(",
"1",
")",
")",
"for",
"i",
"in",
"range",
"(",
"ndfas",
")",
":",
"lineno",
",",
"line",
"=",
"lineno",
"+",
"1",
",",
"next",
"(",
"f",
")",
"mo",
"=",
"re",
".",
"match",
"(",
"r'\\s+{(\\d+), \"(\\w+)\", (\\d+), (\\d+), states_(\\d+),$'",
",",
"line",
")",
"assert",
"mo",
",",
"(",
"lineno",
",",
"line",
")",
"symbol",
"=",
"mo",
".",
"group",
"(",
"2",
")",
"number",
",",
"x",
",",
"y",
",",
"z",
"=",
"list",
"(",
"map",
"(",
"int",
",",
"mo",
".",
"group",
"(",
"1",
",",
"3",
",",
"4",
",",
"5",
")",
")",
")",
"assert",
"self",
".",
"symbol2number",
"[",
"symbol",
"]",
"==",
"number",
",",
"(",
"lineno",
",",
"line",
")",
"assert",
"self",
".",
"number2symbol",
"[",
"number",
"]",
"==",
"symbol",
",",
"(",
"lineno",
",",
"line",
")",
"assert",
"x",
"==",
"0",
",",
"(",
"lineno",
",",
"line",
")",
"state",
"=",
"states",
"[",
"z",
"]",
"assert",
"y",
"==",
"len",
"(",
"state",
")",
",",
"(",
"lineno",
",",
"line",
")",
"lineno",
",",
"line",
"=",
"lineno",
"+",
"1",
",",
"next",
"(",
"f",
")",
"mo",
"=",
"re",
".",
"match",
"(",
"r'\\s+(\"(?:\\\\\\d\\d\\d)*\")},$'",
",",
"line",
")",
"assert",
"mo",
",",
"(",
"lineno",
",",
"line",
")",
"first",
"=",
"{",
"}",
"rawbitset",
"=",
"eval",
"(",
"mo",
".",
"group",
"(",
"1",
")",
")",
"for",
"i",
",",
"c",
"in",
"enumerate",
"(",
"rawbitset",
")",
":",
"byte",
"=",
"ord",
"(",
"c",
")",
"for",
"j",
"in",
"range",
"(",
"8",
")",
":",
"if",
"byte",
"&",
"(",
"1",
"<<",
"j",
")",
":",
"first",
"[",
"i",
"*",
"8",
"+",
"j",
"]",
"=",
"1",
"dfas",
"[",
"number",
"]",
"=",
"(",
"state",
",",
"first",
")",
"lineno",
",",
"line",
"=",
"lineno",
"+",
"1",
",",
"next",
"(",
"f",
")",
"assert",
"line",
"==",
"\"};\\n\"",
",",
"(",
"lineno",
",",
"line",
")",
"self",
".",
"dfas",
"=",
"dfas",
"# Parse the labels",
"labels",
"=",
"[",
"]",
"lineno",
",",
"line",
"=",
"lineno",
"+",
"1",
",",
"next",
"(",
"f",
")",
"mo",
"=",
"re",
".",
"match",
"(",
"r\"static label labels\\[(\\d+)\\] = {$\"",
",",
"line",
")",
"assert",
"mo",
",",
"(",
"lineno",
",",
"line",
")",
"nlabels",
"=",
"int",
"(",
"mo",
".",
"group",
"(",
"1",
")",
")",
"for",
"i",
"in",
"range",
"(",
"nlabels",
")",
":",
"lineno",
",",
"line",
"=",
"lineno",
"+",
"1",
",",
"next",
"(",
"f",
")",
"mo",
"=",
"re",
".",
"match",
"(",
"r'\\s+{(\\d+), (0|\"\\w+\")},$'",
",",
"line",
")",
"assert",
"mo",
",",
"(",
"lineno",
",",
"line",
")",
"x",
",",
"y",
"=",
"mo",
".",
"groups",
"(",
")",
"x",
"=",
"int",
"(",
"x",
")",
"if",
"y",
"==",
"\"0\"",
":",
"y",
"=",
"None",
"else",
":",
"y",
"=",
"eval",
"(",
"y",
")",
"labels",
".",
"append",
"(",
"(",
"x",
",",
"y",
")",
")",
"lineno",
",",
"line",
"=",
"lineno",
"+",
"1",
",",
"next",
"(",
"f",
")",
"assert",
"line",
"==",
"\"};\\n\"",
",",
"(",
"lineno",
",",
"line",
")",
"self",
".",
"labels",
"=",
"labels",
"# Parse the grammar struct",
"lineno",
",",
"line",
"=",
"lineno",
"+",
"1",
",",
"next",
"(",
"f",
")",
"assert",
"line",
"==",
"\"grammar _PyParser_Grammar = {\\n\"",
",",
"(",
"lineno",
",",
"line",
")",
"lineno",
",",
"line",
"=",
"lineno",
"+",
"1",
",",
"next",
"(",
"f",
")",
"mo",
"=",
"re",
".",
"match",
"(",
"r\"\\s+(\\d+),$\"",
",",
"line",
")",
"assert",
"mo",
",",
"(",
"lineno",
",",
"line",
")",
"ndfas",
"=",
"int",
"(",
"mo",
".",
"group",
"(",
"1",
")",
")",
"assert",
"ndfas",
"==",
"len",
"(",
"self",
".",
"dfas",
")",
"lineno",
",",
"line",
"=",
"lineno",
"+",
"1",
",",
"next",
"(",
"f",
")",
"assert",
"line",
"==",
"\"\\tdfas,\\n\"",
",",
"(",
"lineno",
",",
"line",
")",
"lineno",
",",
"line",
"=",
"lineno",
"+",
"1",
",",
"next",
"(",
"f",
")",
"mo",
"=",
"re",
".",
"match",
"(",
"r\"\\s+{(\\d+), labels},$\"",
",",
"line",
")",
"assert",
"mo",
",",
"(",
"lineno",
",",
"line",
")",
"nlabels",
"=",
"int",
"(",
"mo",
".",
"group",
"(",
"1",
")",
")",
"assert",
"nlabels",
"==",
"len",
"(",
"self",
".",
"labels",
")",
",",
"(",
"lineno",
",",
"line",
")",
"lineno",
",",
"line",
"=",
"lineno",
"+",
"1",
",",
"next",
"(",
"f",
")",
"mo",
"=",
"re",
".",
"match",
"(",
"r\"\\s+(\\d+)$\"",
",",
"line",
")",
"assert",
"mo",
",",
"(",
"lineno",
",",
"line",
")",
"start",
"=",
"int",
"(",
"mo",
".",
"group",
"(",
"1",
")",
")",
"assert",
"start",
"in",
"self",
".",
"number2symbol",
",",
"(",
"lineno",
",",
"line",
")",
"self",
".",
"start",
"=",
"start",
"lineno",
",",
"line",
"=",
"lineno",
"+",
"1",
",",
"next",
"(",
"f",
")",
"assert",
"line",
"==",
"\"};\\n\"",
",",
"(",
"lineno",
",",
"line",
")",
"try",
":",
"lineno",
",",
"line",
"=",
"lineno",
"+",
"1",
",",
"next",
"(",
"f",
")",
"except",
"StopIteration",
":",
"pass",
"else",
":",
"assert",
"0",
",",
"(",
"lineno",
",",
"line",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/lib2to3/pgen2/conv.py#L84-L247 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/multiprocessing/managers.py | python | BaseManager.connect | (self) | Connect manager object to the server process | Connect manager object to the server process | [
"Connect",
"manager",
"object",
"to",
"the",
"server",
"process"
] | def connect(self):
'''
Connect manager object to the server process
'''
Listener, Client = listener_client[self._serializer]
conn = Client(self._address, authkey=self._authkey)
dispatch(conn, None, 'dummy')
self._state.value = State.STARTED | [
"def",
"connect",
"(",
"self",
")",
":",
"Listener",
",",
"Client",
"=",
"listener_client",
"[",
"self",
".",
"_serializer",
"]",
"conn",
"=",
"Client",
"(",
"self",
".",
"_address",
",",
"authkey",
"=",
"self",
".",
"_authkey",
")",
"dispatch",
"(",
"conn",
",",
"None",
",",
"'dummy'",
")",
"self",
".",
"_state",
".",
"value",
"=",
"State",
".",
"STARTED"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/multiprocessing/managers.py#L495-L502 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/email/message.py | python | Message.get_payload | (self, i=None, decode=False) | return payload | Return a reference to the payload.
The payload will either be a list object or a string. If you mutate
the list object, you modify the message's payload in place. Optional
i returns that index into the payload.
Optional decode is a flag indicating whether the payload should be
decoded or not, according to the Content-Transfer-Encoding header
(default is False).
When True and the message is not a multipart, the payload will be
decoded if this header's value is `quoted-printable' or `base64'. If
some other encoding is used, or the header is missing, or if the
payload has bogus data (i.e. bogus base64 or uuencoded data), the
payload is returned as-is.
If the message is a multipart and the decode flag is True, then None
is returned. | Return a reference to the payload. | [
"Return",
"a",
"reference",
"to",
"the",
"payload",
"."
] | def get_payload(self, i=None, decode=False):
"""Return a reference to the payload.
The payload will either be a list object or a string. If you mutate
the list object, you modify the message's payload in place. Optional
i returns that index into the payload.
Optional decode is a flag indicating whether the payload should be
decoded or not, according to the Content-Transfer-Encoding header
(default is False).
When True and the message is not a multipart, the payload will be
decoded if this header's value is `quoted-printable' or `base64'. If
some other encoding is used, or the header is missing, or if the
payload has bogus data (i.e. bogus base64 or uuencoded data), the
payload is returned as-is.
If the message is a multipart and the decode flag is True, then None
is returned.
"""
if i is None:
payload = self._payload
elif not isinstance(self._payload, list):
raise TypeError('Expected list, got %s' % type(self._payload))
else:
payload = self._payload[i]
if decode:
if self.is_multipart():
return None
cte = self.get('content-transfer-encoding', '').lower()
if cte == 'quoted-printable':
return utils._qdecode(payload)
elif cte == 'base64':
try:
return utils._bdecode(payload)
except binascii.Error:
# Incorrect padding
return payload
elif cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'):
sfp = StringIO()
try:
uu.decode(StringIO(payload+'\n'), sfp, quiet=True)
payload = sfp.getvalue()
except uu.Error:
# Some decoding problem
return payload
# Everything else, including encodings with 8bit or 7bit are returned
# unchanged.
return payload | [
"def",
"get_payload",
"(",
"self",
",",
"i",
"=",
"None",
",",
"decode",
"=",
"False",
")",
":",
"if",
"i",
"is",
"None",
":",
"payload",
"=",
"self",
".",
"_payload",
"elif",
"not",
"isinstance",
"(",
"self",
".",
"_payload",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"'Expected list, got %s'",
"%",
"type",
"(",
"self",
".",
"_payload",
")",
")",
"else",
":",
"payload",
"=",
"self",
".",
"_payload",
"[",
"i",
"]",
"if",
"decode",
":",
"if",
"self",
".",
"is_multipart",
"(",
")",
":",
"return",
"None",
"cte",
"=",
"self",
".",
"get",
"(",
"'content-transfer-encoding'",
",",
"''",
")",
".",
"lower",
"(",
")",
"if",
"cte",
"==",
"'quoted-printable'",
":",
"return",
"utils",
".",
"_qdecode",
"(",
"payload",
")",
"elif",
"cte",
"==",
"'base64'",
":",
"try",
":",
"return",
"utils",
".",
"_bdecode",
"(",
"payload",
")",
"except",
"binascii",
".",
"Error",
":",
"# Incorrect padding",
"return",
"payload",
"elif",
"cte",
"in",
"(",
"'x-uuencode'",
",",
"'uuencode'",
",",
"'uue'",
",",
"'x-uue'",
")",
":",
"sfp",
"=",
"StringIO",
"(",
")",
"try",
":",
"uu",
".",
"decode",
"(",
"StringIO",
"(",
"payload",
"+",
"'\\n'",
")",
",",
"sfp",
",",
"quiet",
"=",
"True",
")",
"payload",
"=",
"sfp",
".",
"getvalue",
"(",
")",
"except",
"uu",
".",
"Error",
":",
"# Some decoding problem",
"return",
"payload",
"# Everything else, including encodings with 8bit or 7bit are returned",
"# unchanged.",
"return",
"payload"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/email/message.py#L168-L216 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_pydecimal.py | python | Context.exp | (self, a) | return a.exp(context=self) | Returns e ** a.
>>> c = ExtendedContext.copy()
>>> c.Emin = -999
>>> c.Emax = 999
>>> c.exp(Decimal('-Infinity'))
Decimal('0')
>>> c.exp(Decimal('-1'))
Decimal('0.367879441')
>>> c.exp(Decimal('0'))
Decimal('1')
>>> c.exp(Decimal('1'))
Decimal('2.71828183')
>>> c.exp(Decimal('0.693147181'))
Decimal('2.00000000')
>>> c.exp(Decimal('+Infinity'))
Decimal('Infinity')
>>> c.exp(10)
Decimal('22026.4658') | Returns e ** a. | [
"Returns",
"e",
"**",
"a",
"."
] | def exp(self, a):
"""Returns e ** a.
>>> c = ExtendedContext.copy()
>>> c.Emin = -999
>>> c.Emax = 999
>>> c.exp(Decimal('-Infinity'))
Decimal('0')
>>> c.exp(Decimal('-1'))
Decimal('0.367879441')
>>> c.exp(Decimal('0'))
Decimal('1')
>>> c.exp(Decimal('1'))
Decimal('2.71828183')
>>> c.exp(Decimal('0.693147181'))
Decimal('2.00000000')
>>> c.exp(Decimal('+Infinity'))
Decimal('Infinity')
>>> c.exp(10)
Decimal('22026.4658')
"""
a =_convert_other(a, raiseit=True)
return a.exp(context=self) | [
"def",
"exp",
"(",
"self",
",",
"a",
")",
":",
"a",
"=",
"_convert_other",
"(",
"a",
",",
"raiseit",
"=",
"True",
")",
"return",
"a",
".",
"exp",
"(",
"context",
"=",
"self",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_pydecimal.py#L4439-L4461 | |
ros-planning/moveit | ee48dc5cedc981d0869352aa3db0b41469c2735c | moveit_commander/src/moveit_commander/move_group.py | python | MoveGroupCommander.get_goal_position_tolerance | (self) | return self._g.get_goal_position_tolerance() | When moving to a position goal or to a pose goal, the tolerance for the goal position is specified as the radius a sphere around the target origin of the end-effector | When moving to a position goal or to a pose goal, the tolerance for the goal position is specified as the radius a sphere around the target origin of the end-effector | [
"When",
"moving",
"to",
"a",
"position",
"goal",
"or",
"to",
"a",
"pose",
"goal",
"the",
"tolerance",
"for",
"the",
"goal",
"position",
"is",
"specified",
"as",
"the",
"radius",
"a",
"sphere",
"around",
"the",
"target",
"origin",
"of",
"the",
"end",
"-",
"effector"
] | def get_goal_position_tolerance(self):
""" When moving to a position goal or to a pose goal, the tolerance for the goal position is specified as the radius a sphere around the target origin of the end-effector """
return self._g.get_goal_position_tolerance() | [
"def",
"get_goal_position_tolerance",
"(",
"self",
")",
":",
"return",
"self",
".",
"_g",
".",
"get_goal_position_tolerance",
"(",
")"
] | https://github.com/ros-planning/moveit/blob/ee48dc5cedc981d0869352aa3db0b41469c2735c/moveit_commander/src/moveit_commander/move_group.py#L440-L442 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | Image.SetAlphaBuffer | (*args, **kwargs) | return _core_.Image_SetAlphaBuffer(*args, **kwargs) | SetAlphaBuffer(self, buffer alpha)
Sets the internal image alpha pointer to point at a Python buffer
object. This can save making an extra copy of the data but you must
ensure that the buffer object lives as long as the wx.Image does. | SetAlphaBuffer(self, buffer alpha) | [
"SetAlphaBuffer",
"(",
"self",
"buffer",
"alpha",
")"
] | def SetAlphaBuffer(*args, **kwargs):
"""
SetAlphaBuffer(self, buffer alpha)
Sets the internal image alpha pointer to point at a Python buffer
object. This can save making an extra copy of the data but you must
ensure that the buffer object lives as long as the wx.Image does.
"""
return _core_.Image_SetAlphaBuffer(*args, **kwargs) | [
"def",
"SetAlphaBuffer",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Image_SetAlphaBuffer",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L3423-L3431 | |
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | sdhash-ui/cherrypy/process/wspbus.py | python | Bus.stop | (self) | Stop all services. | Stop all services. | [
"Stop",
"all",
"services",
"."
] | def stop(self):
"""Stop all services."""
self.state = states.STOPPING
self.log('Bus STOPPING')
self.publish('stop')
self.state = states.STOPPED
self.log('Bus STOPPED') | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"state",
"=",
"states",
".",
"STOPPING",
"self",
".",
"log",
"(",
"'Bus STOPPING'",
")",
"self",
".",
"publish",
"(",
"'stop'",
")",
"self",
".",
"state",
"=",
"states",
".",
"STOPPED",
"self",
".",
"log",
"(",
"'Bus STOPPED'",
")"
] | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/cherrypy/process/wspbus.py#L399-L405 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_gdi.py | python | GraphicsContext.EnableOffset | (*args, **kwargs) | return _gdi_.GraphicsContext_EnableOffset(*args, **kwargs) | EnableOffset(self, bool enable=True) | EnableOffset(self, bool enable=True) | [
"EnableOffset",
"(",
"self",
"bool",
"enable",
"=",
"True",
")"
] | def EnableOffset(*args, **kwargs):
"""EnableOffset(self, bool enable=True)"""
return _gdi_.GraphicsContext_EnableOffset(*args, **kwargs) | [
"def",
"EnableOffset",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"GraphicsContext_EnableOffset",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L6514-L6516 | |
tensor-compiler/taco | d0654a84137169883973c40a951dfdb89883fd9c | python_bindings/pytaco/pytensor/taco_tensor.py | python | set_udf_dir | (dir_to_search) | Sets the directory to search for user defined functions.
Parameters
------------
dir_to_search: str
The directory that taco should search when looking for user defined functions. | Sets the directory to search for user defined functions. | [
"Sets",
"the",
"directory",
"to",
"search",
"for",
"user",
"defined",
"functions",
"."
] | def set_udf_dir(dir_to_search):
"""
Sets the directory to search for user defined functions.
Parameters
------------
dir_to_search: str
The directory that taco should search when looking for user defined functions.
"""
raise NotImplementedError | [
"def",
"set_udf_dir",
"(",
"dir_to_search",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/tensor-compiler/taco/blob/d0654a84137169883973c40a951dfdb89883fd9c/python_bindings/pytaco/pytensor/taco_tensor.py#L3117-L3126 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Code/Tools/waf-1.7.13/waflib/TaskGen.py | python | process_rule | (self) | Process the attribute ``rule``. When present, :py:meth:`waflib.TaskGen.process_source` is disabled::
def build(bld):
bld(rule='cp ${SRC} ${TGT}', source='wscript', target='bar.txt') | Process the attribute ``rule``. When present, :py:meth:`waflib.TaskGen.process_source` is disabled:: | [
"Process",
"the",
"attribute",
"rule",
".",
"When",
"present",
":",
"py",
":",
"meth",
":",
"waflib",
".",
"TaskGen",
".",
"process_source",
"is",
"disabled",
"::"
] | def process_rule(self):
"""
Process the attribute ``rule``. When present, :py:meth:`waflib.TaskGen.process_source` is disabled::
def build(bld):
bld(rule='cp ${SRC} ${TGT}', source='wscript', target='bar.txt')
"""
if not getattr(self, 'rule', None):
return
# create the task class
name = str(getattr(self, 'name', None) or self.target or getattr(self.rule, '__name__', self.rule))
# or we can put the class in a cache for performance reasons
try:
cache = self.bld.cache_rule_attr
except AttributeError:
cache = self.bld.cache_rule_attr = {}
cls = None
if getattr(self, 'cache_rule', 'True'):
try:
cls = cache[(name, self.rule)]
except KeyError:
pass
if not cls:
cls = Task.task_factory(name, self.rule,
getattr(self, 'vars', []),
shell=getattr(self, 'shell', True), color=getattr(self, 'color', 'BLUE'),
scan = getattr(self, 'scan', None))
if getattr(self, 'scan', None):
cls.scan = self.scan
elif getattr(self, 'deps', None):
def scan(self):
nodes = []
for x in self.generator.to_list(getattr(self.generator, 'deps', None)):
node = self.generator.path.find_resource(x)
if not node:
self.generator.bld.fatal('Could not find %r (was it declared?)' % x)
nodes.append(node)
return [nodes, []]
cls.scan = scan
if getattr(self, 'update_outputs', None):
Task.update_outputs(cls)
if getattr(self, 'always', None):
Task.always_run(cls)
for x in ['after', 'before', 'ext_in', 'ext_out']:
setattr(cls, x, getattr(self, x, []))
if getattr(self, 'cache_rule', 'True'):
cache[(name, self.rule)] = cls
# now create one instance
tsk = self.create_task(name)
if getattr(self, 'target', None):
if isinstance(self.target, str):
self.target = self.target.split()
if not isinstance(self.target, list):
self.target = [self.target]
for x in self.target:
if isinstance(x, str):
tsk.outputs.append(self.path.find_or_declare(x))
else:
x.parent.mkdir() # if a node was given, create the required folders
tsk.outputs.append(x)
if getattr(self, 'install_path', None):
# from waf 1.5
# although convenient, it does not 1. allow to name the target file and 2. symlinks
# TODO remove in waf 1.7
self.bld.install_files(self.install_path, tsk.outputs)
if getattr(self, 'source', None):
tsk.inputs = self.to_nodes(self.source)
# bypass the execution of process_source by setting the source to an empty list
self.source = []
if getattr(self, 'cwd', None):
tsk.cwd = self.cwd | [
"def",
"process_rule",
"(",
"self",
")",
":",
"if",
"not",
"getattr",
"(",
"self",
",",
"'rule'",
",",
"None",
")",
":",
"return",
"# create the task class",
"name",
"=",
"str",
"(",
"getattr",
"(",
"self",
",",
"'name'",
",",
"None",
")",
"or",
"self",
".",
"target",
"or",
"getattr",
"(",
"self",
".",
"rule",
",",
"'__name__'",
",",
"self",
".",
"rule",
")",
")",
"# or we can put the class in a cache for performance reasons",
"try",
":",
"cache",
"=",
"self",
".",
"bld",
".",
"cache_rule_attr",
"except",
"AttributeError",
":",
"cache",
"=",
"self",
".",
"bld",
".",
"cache_rule_attr",
"=",
"{",
"}",
"cls",
"=",
"None",
"if",
"getattr",
"(",
"self",
",",
"'cache_rule'",
",",
"'True'",
")",
":",
"try",
":",
"cls",
"=",
"cache",
"[",
"(",
"name",
",",
"self",
".",
"rule",
")",
"]",
"except",
"KeyError",
":",
"pass",
"if",
"not",
"cls",
":",
"cls",
"=",
"Task",
".",
"task_factory",
"(",
"name",
",",
"self",
".",
"rule",
",",
"getattr",
"(",
"self",
",",
"'vars'",
",",
"[",
"]",
")",
",",
"shell",
"=",
"getattr",
"(",
"self",
",",
"'shell'",
",",
"True",
")",
",",
"color",
"=",
"getattr",
"(",
"self",
",",
"'color'",
",",
"'BLUE'",
")",
",",
"scan",
"=",
"getattr",
"(",
"self",
",",
"'scan'",
",",
"None",
")",
")",
"if",
"getattr",
"(",
"self",
",",
"'scan'",
",",
"None",
")",
":",
"cls",
".",
"scan",
"=",
"self",
".",
"scan",
"elif",
"getattr",
"(",
"self",
",",
"'deps'",
",",
"None",
")",
":",
"def",
"scan",
"(",
"self",
")",
":",
"nodes",
"=",
"[",
"]",
"for",
"x",
"in",
"self",
".",
"generator",
".",
"to_list",
"(",
"getattr",
"(",
"self",
".",
"generator",
",",
"'deps'",
",",
"None",
")",
")",
":",
"node",
"=",
"self",
".",
"generator",
".",
"path",
".",
"find_resource",
"(",
"x",
")",
"if",
"not",
"node",
":",
"self",
".",
"generator",
".",
"bld",
".",
"fatal",
"(",
"'Could not find %r (was it declared?)'",
"%",
"x",
")",
"nodes",
".",
"append",
"(",
"node",
")",
"return",
"[",
"nodes",
",",
"[",
"]",
"]",
"cls",
".",
"scan",
"=",
"scan",
"if",
"getattr",
"(",
"self",
",",
"'update_outputs'",
",",
"None",
")",
":",
"Task",
".",
"update_outputs",
"(",
"cls",
")",
"if",
"getattr",
"(",
"self",
",",
"'always'",
",",
"None",
")",
":",
"Task",
".",
"always_run",
"(",
"cls",
")",
"for",
"x",
"in",
"[",
"'after'",
",",
"'before'",
",",
"'ext_in'",
",",
"'ext_out'",
"]",
":",
"setattr",
"(",
"cls",
",",
"x",
",",
"getattr",
"(",
"self",
",",
"x",
",",
"[",
"]",
")",
")",
"if",
"getattr",
"(",
"self",
",",
"'cache_rule'",
",",
"'True'",
")",
":",
"cache",
"[",
"(",
"name",
",",
"self",
".",
"rule",
")",
"]",
"=",
"cls",
"# now create one instance",
"tsk",
"=",
"self",
".",
"create_task",
"(",
"name",
")",
"if",
"getattr",
"(",
"self",
",",
"'target'",
",",
"None",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"target",
",",
"str",
")",
":",
"self",
".",
"target",
"=",
"self",
".",
"target",
".",
"split",
"(",
")",
"if",
"not",
"isinstance",
"(",
"self",
".",
"target",
",",
"list",
")",
":",
"self",
".",
"target",
"=",
"[",
"self",
".",
"target",
"]",
"for",
"x",
"in",
"self",
".",
"target",
":",
"if",
"isinstance",
"(",
"x",
",",
"str",
")",
":",
"tsk",
".",
"outputs",
".",
"append",
"(",
"self",
".",
"path",
".",
"find_or_declare",
"(",
"x",
")",
")",
"else",
":",
"x",
".",
"parent",
".",
"mkdir",
"(",
")",
"# if a node was given, create the required folders",
"tsk",
".",
"outputs",
".",
"append",
"(",
"x",
")",
"if",
"getattr",
"(",
"self",
",",
"'install_path'",
",",
"None",
")",
":",
"# from waf 1.5",
"# although convenient, it does not 1. allow to name the target file and 2. symlinks",
"# TODO remove in waf 1.7",
"self",
".",
"bld",
".",
"install_files",
"(",
"self",
".",
"install_path",
",",
"tsk",
".",
"outputs",
")",
"if",
"getattr",
"(",
"self",
",",
"'source'",
",",
"None",
")",
":",
"tsk",
".",
"inputs",
"=",
"self",
".",
"to_nodes",
"(",
"self",
".",
"source",
")",
"# bypass the execution of process_source by setting the source to an empty list",
"self",
".",
"source",
"=",
"[",
"]",
"if",
"getattr",
"(",
"self",
",",
"'cwd'",
",",
"None",
")",
":",
"tsk",
".",
"cwd",
"=",
"self",
".",
"cwd"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/TaskGen.py#L525-L606 | ||
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/mms/fparser.py | python | FParserPrinter._rate_index_position | (self, p) | return p*5 | function to calculate score based on position among indices
This method is used to sort loops in an optimized order, see
CodePrinter._sort_optimized() | function to calculate score based on position among indices | [
"function",
"to",
"calculate",
"score",
"based",
"on",
"position",
"among",
"indices"
] | def _rate_index_position(self, p):
"""function to calculate score based on position among indices
This method is used to sort loops in an optimized order, see
CodePrinter._sort_optimized()
"""
return p*5 | [
"def",
"_rate_index_position",
"(",
"self",
",",
"p",
")",
":",
"return",
"p",
"*",
"5"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/mms/fparser.py#L68-L74 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/calendar.py | python | Calendar.iterweekdays | (self) | Return a iterator for one week of weekday numbers starting with the
configured first one. | Return a iterator for one week of weekday numbers starting with the
configured first one. | [
"Return",
"a",
"iterator",
"for",
"one",
"week",
"of",
"weekday",
"numbers",
"starting",
"with",
"the",
"configured",
"first",
"one",
"."
] | def iterweekdays(self):
"""
Return a iterator for one week of weekday numbers starting with the
configured first one.
"""
for i in range(self.firstweekday, self.firstweekday + 7):
yield i%7 | [
"def",
"iterweekdays",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"firstweekday",
",",
"self",
".",
"firstweekday",
"+",
"7",
")",
":",
"yield",
"i",
"%",
"7"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/calendar.py#L143-L149 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py | python | Distribution._dep_map | (self) | return self.__dep_map | A map of extra to its list of (direct) requirements
for this distribution, including the null extra. | [] | def _dep_map(self):
"""
A map of extra to its list of (direct) requirements
for this distribution, including the null extra.
"""
try:
return self.__dep_map
except AttributeError:
self.__dep_map = self._filter_extras(self._build_dep_map())
return self.__dep_map | [
"def",
"_dep_map",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"__dep_map",
"except",
"AttributeError",
":",
"self",
".",
"__dep_map",
"=",
"self",
".",
"_filter_extras",
"(",
"self",
".",
"_build_dep_map",
"(",
")",
")",
"return",
"self",
".",
"__dep_map"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L5387-L5405 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/feature_column/feature_column.py | python | _LazyBuilder.__init__ | (self, features) | Creates a `_LazyBuilder`.
Args:
features: A mapping from feature column to objects that are `Tensor` or
`SparseTensor`, or can be converted to same via
`sparse_tensor.convert_to_tensor_or_sparse_tensor`. A `string` key
signifies a base feature (not-transformed). A `_FeatureColumn` key
means that this `Tensor` is the output of an existing `_FeatureColumn`
which can be reused. | Creates a `_LazyBuilder`. | [
"Creates",
"a",
"_LazyBuilder",
"."
] | def __init__(self, features):
"""Creates a `_LazyBuilder`.
Args:
features: A mapping from feature column to objects that are `Tensor` or
`SparseTensor`, or can be converted to same via
`sparse_tensor.convert_to_tensor_or_sparse_tensor`. A `string` key
signifies a base feature (not-transformed). A `_FeatureColumn` key
means that this `Tensor` is the output of an existing `_FeatureColumn`
which can be reused.
"""
self._features = features.copy()
self._feature_tensors = {} | [
"def",
"__init__",
"(",
"self",
",",
"features",
")",
":",
"self",
".",
"_features",
"=",
"features",
".",
"copy",
"(",
")",
"self",
".",
"_feature_tensors",
"=",
"{",
"}"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/feature_column/feature_column.py#L1483-L1495 | ||
vslavik/poedit | f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a | deps/boost/tools/build/src/build/project.py | python | ProjectRegistry.initialize | (self, module_name, location=None, basename=None, standalone_path='') | Initialize the module for a project.
module-name is the name of the project module.
location is the location (directory) of the project to initialize.
If not specified, standalone project will be initialized
standalone_path is the path to the source-location.
this should only be called from the python side. | Initialize the module for a project. | [
"Initialize",
"the",
"module",
"for",
"a",
"project",
"."
] | def initialize(self, module_name, location=None, basename=None, standalone_path=''):
"""Initialize the module for a project.
module-name is the name of the project module.
location is the location (directory) of the project to initialize.
If not specified, standalone project will be initialized
standalone_path is the path to the source-location.
this should only be called from the python side.
"""
assert isinstance(module_name, basestring)
assert isinstance(location, basestring) or location is None
assert isinstance(basename, basestring) or basename is None
jamroot = False
parent_module = None
if module_name == "test-config":
# No parent
pass
elif module_name == "site-config":
parent_module = "test-config"
elif module_name == "user-config":
parent_module = "site-config"
elif module_name == "project-config":
parent_module = "user-config"
elif location and not self.is_jamroot(basename):
# We search for parent/project-root only if jamfile was specified
# --- i.e
# if the project is not standalone.
parent_module = self.load_parent(location)
elif location:
# It's either jamroot, or standalone project.
# If it's jamroot, inherit from user-config.
# If project-config module exist, inherit from it.
parent_module = 'user-config'
if 'project-config' in self.module2attributes:
parent_module = 'project-config'
jamroot = True
# TODO: need to consider if standalone projects can do anything but defining
# prebuilt targets. If so, we need to give more sensible "location", so that
# source paths are correct.
if not location:
location = ""
# the call to load_parent() above can end up loading this module again
# make sure we don't reinitialize the module's attributes
if module_name not in self.module2attributes:
if "--debug-loading" in self.manager.argv():
print "Initializing project '%s'" % module_name
attributes = ProjectAttributes(self.manager, location, module_name)
self.module2attributes[module_name] = attributes
python_standalone = False
if location:
attributes.set("source-location", [location], exact=1)
elif not module_name in ["test-config", "site-config", "user-config", "project-config"]:
# This is a standalone project with known location. Set source location
# so that it can declare targets. This is intended so that you can put
# a .jam file in your sources and use it via 'using'. Standard modules
# (in 'tools' subdir) may not assume source dir is set.
source_location = standalone_path
if not source_location:
source_location = self.loaded_tool_module_path_.get(module_name)
if not source_location:
self.manager.errors()('Standalone module path not found for "{}"'
.format(module_name))
attributes.set("source-location", [source_location], exact=1)
python_standalone = True
attributes.set("requirements", property_set.empty(), exact=True)
attributes.set("usage-requirements", property_set.empty(), exact=True)
attributes.set("default-build", property_set.empty(), exact=True)
attributes.set("projects-to-build", [], exact=True)
attributes.set("project-root", None, exact=True)
attributes.set("build-dir", None, exact=True)
self.project_rules_.init_project(module_name, python_standalone)
if parent_module:
self.inherit_attributes(module_name, parent_module)
attributes.set("parent-module", parent_module, exact=1)
if jamroot:
attributes.set("project-root", location, exact=1)
parent = None
if parent_module:
parent = self.target(parent_module)
if module_name not in self.module2target:
target = b2.build.targets.ProjectTarget(self.manager,
module_name, module_name, parent,
self.attribute(module_name, "requirements"),
# FIXME: why we need to pass this? It's not
# passed in jam code.
self.attribute(module_name, "default-build"))
self.module2target[module_name] = target
self.current_project = self.target(module_name) | [
"def",
"initialize",
"(",
"self",
",",
"module_name",
",",
"location",
"=",
"None",
",",
"basename",
"=",
"None",
",",
"standalone_path",
"=",
"''",
")",
":",
"assert",
"isinstance",
"(",
"module_name",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"location",
",",
"basestring",
")",
"or",
"location",
"is",
"None",
"assert",
"isinstance",
"(",
"basename",
",",
"basestring",
")",
"or",
"basename",
"is",
"None",
"jamroot",
"=",
"False",
"parent_module",
"=",
"None",
"if",
"module_name",
"==",
"\"test-config\"",
":",
"# No parent",
"pass",
"elif",
"module_name",
"==",
"\"site-config\"",
":",
"parent_module",
"=",
"\"test-config\"",
"elif",
"module_name",
"==",
"\"user-config\"",
":",
"parent_module",
"=",
"\"site-config\"",
"elif",
"module_name",
"==",
"\"project-config\"",
":",
"parent_module",
"=",
"\"user-config\"",
"elif",
"location",
"and",
"not",
"self",
".",
"is_jamroot",
"(",
"basename",
")",
":",
"# We search for parent/project-root only if jamfile was specified",
"# --- i.e",
"# if the project is not standalone.",
"parent_module",
"=",
"self",
".",
"load_parent",
"(",
"location",
")",
"elif",
"location",
":",
"# It's either jamroot, or standalone project.",
"# If it's jamroot, inherit from user-config.",
"# If project-config module exist, inherit from it.",
"parent_module",
"=",
"'user-config'",
"if",
"'project-config'",
"in",
"self",
".",
"module2attributes",
":",
"parent_module",
"=",
"'project-config'",
"jamroot",
"=",
"True",
"# TODO: need to consider if standalone projects can do anything but defining",
"# prebuilt targets. If so, we need to give more sensible \"location\", so that",
"# source paths are correct.",
"if",
"not",
"location",
":",
"location",
"=",
"\"\"",
"# the call to load_parent() above can end up loading this module again",
"# make sure we don't reinitialize the module's attributes",
"if",
"module_name",
"not",
"in",
"self",
".",
"module2attributes",
":",
"if",
"\"--debug-loading\"",
"in",
"self",
".",
"manager",
".",
"argv",
"(",
")",
":",
"print",
"\"Initializing project '%s'\"",
"%",
"module_name",
"attributes",
"=",
"ProjectAttributes",
"(",
"self",
".",
"manager",
",",
"location",
",",
"module_name",
")",
"self",
".",
"module2attributes",
"[",
"module_name",
"]",
"=",
"attributes",
"python_standalone",
"=",
"False",
"if",
"location",
":",
"attributes",
".",
"set",
"(",
"\"source-location\"",
",",
"[",
"location",
"]",
",",
"exact",
"=",
"1",
")",
"elif",
"not",
"module_name",
"in",
"[",
"\"test-config\"",
",",
"\"site-config\"",
",",
"\"user-config\"",
",",
"\"project-config\"",
"]",
":",
"# This is a standalone project with known location. Set source location",
"# so that it can declare targets. This is intended so that you can put",
"# a .jam file in your sources and use it via 'using'. Standard modules",
"# (in 'tools' subdir) may not assume source dir is set.",
"source_location",
"=",
"standalone_path",
"if",
"not",
"source_location",
":",
"source_location",
"=",
"self",
".",
"loaded_tool_module_path_",
".",
"get",
"(",
"module_name",
")",
"if",
"not",
"source_location",
":",
"self",
".",
"manager",
".",
"errors",
"(",
")",
"(",
"'Standalone module path not found for \"{}\"'",
".",
"format",
"(",
"module_name",
")",
")",
"attributes",
".",
"set",
"(",
"\"source-location\"",
",",
"[",
"source_location",
"]",
",",
"exact",
"=",
"1",
")",
"python_standalone",
"=",
"True",
"attributes",
".",
"set",
"(",
"\"requirements\"",
",",
"property_set",
".",
"empty",
"(",
")",
",",
"exact",
"=",
"True",
")",
"attributes",
".",
"set",
"(",
"\"usage-requirements\"",
",",
"property_set",
".",
"empty",
"(",
")",
",",
"exact",
"=",
"True",
")",
"attributes",
".",
"set",
"(",
"\"default-build\"",
",",
"property_set",
".",
"empty",
"(",
")",
",",
"exact",
"=",
"True",
")",
"attributes",
".",
"set",
"(",
"\"projects-to-build\"",
",",
"[",
"]",
",",
"exact",
"=",
"True",
")",
"attributes",
".",
"set",
"(",
"\"project-root\"",
",",
"None",
",",
"exact",
"=",
"True",
")",
"attributes",
".",
"set",
"(",
"\"build-dir\"",
",",
"None",
",",
"exact",
"=",
"True",
")",
"self",
".",
"project_rules_",
".",
"init_project",
"(",
"module_name",
",",
"python_standalone",
")",
"if",
"parent_module",
":",
"self",
".",
"inherit_attributes",
"(",
"module_name",
",",
"parent_module",
")",
"attributes",
".",
"set",
"(",
"\"parent-module\"",
",",
"parent_module",
",",
"exact",
"=",
"1",
")",
"if",
"jamroot",
":",
"attributes",
".",
"set",
"(",
"\"project-root\"",
",",
"location",
",",
"exact",
"=",
"1",
")",
"parent",
"=",
"None",
"if",
"parent_module",
":",
"parent",
"=",
"self",
".",
"target",
"(",
"parent_module",
")",
"if",
"module_name",
"not",
"in",
"self",
".",
"module2target",
":",
"target",
"=",
"b2",
".",
"build",
".",
"targets",
".",
"ProjectTarget",
"(",
"self",
".",
"manager",
",",
"module_name",
",",
"module_name",
",",
"parent",
",",
"self",
".",
"attribute",
"(",
"module_name",
",",
"\"requirements\"",
")",
",",
"# FIXME: why we need to pass this? It's not",
"# passed in jam code.",
"self",
".",
"attribute",
"(",
"module_name",
",",
"\"default-build\"",
")",
")",
"self",
".",
"module2target",
"[",
"module_name",
"]",
"=",
"target",
"self",
".",
"current_project",
"=",
"self",
".",
"target",
"(",
"module_name",
")"
] | https://github.com/vslavik/poedit/blob/f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a/deps/boost/tools/build/src/build/project.py#L412-L509 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_gdi.py | python | Font.GetNativeFontInfoUserDesc | (*args, **kwargs) | return _gdi_.Font_GetNativeFontInfoUserDesc(*args, **kwargs) | GetNativeFontInfoUserDesc(self) -> String
Returns a human readable version of `GetNativeFontInfoDesc`. | GetNativeFontInfoUserDesc(self) -> String | [
"GetNativeFontInfoUserDesc",
"(",
"self",
")",
"-",
">",
"String"
] | def GetNativeFontInfoUserDesc(*args, **kwargs):
"""
GetNativeFontInfoUserDesc(self) -> String
Returns a human readable version of `GetNativeFontInfoDesc`.
"""
return _gdi_.Font_GetNativeFontInfoUserDesc(*args, **kwargs) | [
"def",
"GetNativeFontInfoUserDesc",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"Font_GetNativeFontInfoUserDesc",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L2281-L2287 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_windows.py | python | VListBox.OnDrawBackground | (*args, **kwargs) | return _windows_.VListBox_OnDrawBackground(*args, **kwargs) | OnDrawBackground(self, DC dc, Rect rect, size_t n) | OnDrawBackground(self, DC dc, Rect rect, size_t n) | [
"OnDrawBackground",
"(",
"self",
"DC",
"dc",
"Rect",
"rect",
"size_t",
"n",
")"
] | def OnDrawBackground(*args, **kwargs):
"""OnDrawBackground(self, DC dc, Rect rect, size_t n)"""
return _windows_.VListBox_OnDrawBackground(*args, **kwargs) | [
"def",
"OnDrawBackground",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"VListBox_OnDrawBackground",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L2700-L2702 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/_vendor/ordered_set.py | python | OrderedSet.difference_update | (self, *sets) | Update this OrderedSet to remove items from one or more other sets.
Example:
>>> this = OrderedSet([1, 2, 3])
>>> this.difference_update(OrderedSet([2, 4]))
>>> print(this)
OrderedSet([1, 3])
>>> this = OrderedSet([1, 2, 3, 4, 5])
>>> this.difference_update(OrderedSet([2, 4]), OrderedSet([1, 4, 6]))
>>> print(this)
OrderedSet([3, 5]) | Update this OrderedSet to remove items from one or more other sets. | [
"Update",
"this",
"OrderedSet",
"to",
"remove",
"items",
"from",
"one",
"or",
"more",
"other",
"sets",
"."
] | def difference_update(self, *sets):
"""
Update this OrderedSet to remove items from one or more other sets.
Example:
>>> this = OrderedSet([1, 2, 3])
>>> this.difference_update(OrderedSet([2, 4]))
>>> print(this)
OrderedSet([1, 3])
>>> this = OrderedSet([1, 2, 3, 4, 5])
>>> this.difference_update(OrderedSet([2, 4]), OrderedSet([1, 4, 6]))
>>> print(this)
OrderedSet([3, 5])
"""
items_to_remove = set()
for other in sets:
items_to_remove |= set(other)
self._update_items([item for item in self.items if item not in items_to_remove]) | [
"def",
"difference_update",
"(",
"self",
",",
"*",
"sets",
")",
":",
"items_to_remove",
"=",
"set",
"(",
")",
"for",
"other",
"in",
"sets",
":",
"items_to_remove",
"|=",
"set",
"(",
"other",
")",
"self",
".",
"_update_items",
"(",
"[",
"item",
"for",
"item",
"in",
"self",
".",
"items",
"if",
"item",
"not",
"in",
"items_to_remove",
"]",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/_vendor/ordered_set.py#L437-L455 | ||
synfig/synfig | a5ec91db5b751dc12e4400ccfb5c063fd6d2d928 | synfig-studio/plugins/lottie-exporter/layers/blur.py | python | gen_layer_blur | (lottie, layers) | This function will be called for each canvas/composition. Main function to
generate all the layers
Args:
lottie (dict) : Lottie Dictionary for blur layers
layers (List) : Dictionary of Synfig format layers
Returns:
(None) | This function will be called for each canvas/composition. Main function to
generate all the layers | [
"This",
"function",
"will",
"be",
"called",
"for",
"each",
"canvas",
"/",
"composition",
".",
"Main",
"function",
"to",
"generate",
"all",
"the",
"layers"
] | def gen_layer_blur(lottie, layers):
"""
This function will be called for each canvas/composition. Main function to
generate all the layers
Args:
lottie (dict) : Lottie Dictionary for blur layers
layers (List) : Dictionary of Synfig format layers
Returns:
(None)
"""
index = Count()
for layer in layers:
blur_dict_x = {}
fill_blur_dict(blur_dict_x,layer,index.inc(),"horizontal")
blur_dict_y = {}
fill_blur_dict(blur_dict_y,layer,index.inc(),"vertical")
lottie.append(blur_dict_x)
lottie.append(blur_dict_y) | [
"def",
"gen_layer_blur",
"(",
"lottie",
",",
"layers",
")",
":",
"index",
"=",
"Count",
"(",
")",
"for",
"layer",
"in",
"layers",
":",
"blur_dict_x",
"=",
"{",
"}",
"fill_blur_dict",
"(",
"blur_dict_x",
",",
"layer",
",",
"index",
".",
"inc",
"(",
")",
",",
"\"horizontal\"",
")",
"blur_dict_y",
"=",
"{",
"}",
"fill_blur_dict",
"(",
"blur_dict_y",
",",
"layer",
",",
"index",
".",
"inc",
"(",
")",
",",
"\"vertical\"",
")",
"lottie",
".",
"append",
"(",
"blur_dict_x",
")",
"lottie",
".",
"append",
"(",
"blur_dict_y",
")"
] | https://github.com/synfig/synfig/blob/a5ec91db5b751dc12e4400ccfb5c063fd6d2d928/synfig-studio/plugins/lottie-exporter/layers/blur.py#L130-L149 | ||
adnanaziz/epicode | e81d4387d2ae442d21631dfc958690d424e1d84d | cpp/cpplint.py | python | ProcessFile | (filename, vlevel, extra_check_functions=[]) | Does google-lint on a single file.
Args:
filename: The name of the file to parse.
vlevel: The level of errors to report. Every error of confidence
>= verbose_level will be reported. 0 is a good default.
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error | Does google-lint on a single file. | [
"Does",
"google",
"-",
"lint",
"on",
"a",
"single",
"file",
"."
] | def ProcessFile(filename, vlevel, extra_check_functions=[]):
"""Does google-lint on a single file.
Args:
filename: The name of the file to parse.
vlevel: The level of errors to report. Every error of confidence
>= verbose_level will be reported. 0 is a good default.
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error
"""
_SetVerboseLevel(vlevel)
try:
# Support the UNIX convention of using "-" for stdin. Note that
# we are not opening the file with universal newline support
# (which codecs doesn't support anyway), so the resulting lines do
# contain trailing '\r' characters if we are reading a file that
# has CRLF endings.
# If after the split a trailing '\r' is present, it is removed
# below. If it is not expected to be present (i.e. os.linesep !=
# '\r\n' as in Windows), a warning is issued below if this file
# is processed.
if filename == '-':
lines = codecs.StreamReaderWriter(sys.stdin,
codecs.getreader('utf8'),
codecs.getwriter('utf8'),
'replace').read().split('\n')
else:
lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
carriage_return_found = False
# Remove trailing '\r'.
for linenum in range(len(lines)):
if lines[linenum].endswith('\r'):
lines[linenum] = lines[linenum].rstrip('\r')
carriage_return_found = True
except IOError:
sys.stderr.write(
"Skipping input '%s': Can't open for reading\n" % filename)
return
# Note, if no dot is found, this will give the entire filename as the ext.
file_extension = filename[filename.rfind('.') + 1:]
# When reading from stdin, the extension is unknown, so no cpplint tests
# should rely on the extension.
if (filename != '-' and file_extension != 'cc' and file_extension != 'h'
and file_extension != 'cpp'):
sys.stderr.write('Ignoring %s; not a .cc or .h file\n' % filename)
else:
ProcessFileData(filename, file_extension, lines, Error,
extra_check_functions)
if carriage_return_found and os.linesep != '\r\n':
# Use 0 for linenum since outputting only one error for potentially
# several lines.
Error(filename, 0, 'whitespace/newline', 1,
'One or more unexpected \\r (^M) found;'
'better to use only a \\n')
sys.stderr.write('Done processing %s\n' % filename) | [
"def",
"ProcessFile",
"(",
"filename",
",",
"vlevel",
",",
"extra_check_functions",
"=",
"[",
"]",
")",
":",
"_SetVerboseLevel",
"(",
"vlevel",
")",
"try",
":",
"# Support the UNIX convention of using \"-\" for stdin. Note that",
"# we are not opening the file with universal newline support",
"# (which codecs doesn't support anyway), so the resulting lines do",
"# contain trailing '\\r' characters if we are reading a file that",
"# has CRLF endings.",
"# If after the split a trailing '\\r' is present, it is removed",
"# below. If it is not expected to be present (i.e. os.linesep !=",
"# '\\r\\n' as in Windows), a warning is issued below if this file",
"# is processed.",
"if",
"filename",
"==",
"'-'",
":",
"lines",
"=",
"codecs",
".",
"StreamReaderWriter",
"(",
"sys",
".",
"stdin",
",",
"codecs",
".",
"getreader",
"(",
"'utf8'",
")",
",",
"codecs",
".",
"getwriter",
"(",
"'utf8'",
")",
",",
"'replace'",
")",
".",
"read",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
"else",
":",
"lines",
"=",
"codecs",
".",
"open",
"(",
"filename",
",",
"'r'",
",",
"'utf8'",
",",
"'replace'",
")",
".",
"read",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
"carriage_return_found",
"=",
"False",
"# Remove trailing '\\r'.",
"for",
"linenum",
"in",
"range",
"(",
"len",
"(",
"lines",
")",
")",
":",
"if",
"lines",
"[",
"linenum",
"]",
".",
"endswith",
"(",
"'\\r'",
")",
":",
"lines",
"[",
"linenum",
"]",
"=",
"lines",
"[",
"linenum",
"]",
".",
"rstrip",
"(",
"'\\r'",
")",
"carriage_return_found",
"=",
"True",
"except",
"IOError",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"Skipping input '%s': Can't open for reading\\n\"",
"%",
"filename",
")",
"return",
"# Note, if no dot is found, this will give the entire filename as the ext.",
"file_extension",
"=",
"filename",
"[",
"filename",
".",
"rfind",
"(",
"'.'",
")",
"+",
"1",
":",
"]",
"# When reading from stdin, the extension is unknown, so no cpplint tests",
"# should rely on the extension.",
"if",
"(",
"filename",
"!=",
"'-'",
"and",
"file_extension",
"!=",
"'cc'",
"and",
"file_extension",
"!=",
"'h'",
"and",
"file_extension",
"!=",
"'cpp'",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Ignoring %s; not a .cc or .h file\\n'",
"%",
"filename",
")",
"else",
":",
"ProcessFileData",
"(",
"filename",
",",
"file_extension",
",",
"lines",
",",
"Error",
",",
"extra_check_functions",
")",
"if",
"carriage_return_found",
"and",
"os",
".",
"linesep",
"!=",
"'\\r\\n'",
":",
"# Use 0 for linenum since outputting only one error for potentially",
"# several lines.",
"Error",
"(",
"filename",
",",
"0",
",",
"'whitespace/newline'",
",",
"1",
",",
"'One or more unexpected \\\\r (^M) found;'",
"'better to use only a \\\\n'",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Done processing %s\\n'",
"%",
"filename",
")"
] | https://github.com/adnanaziz/epicode/blob/e81d4387d2ae442d21631dfc958690d424e1d84d/cpp/cpplint.py#L3200-L3265 | ||
microsoft/ivy | 9f3c7ecc0b2383129fdd0953e10890d98d09a82d | ivy/ivy_logic_utils.py | python | condition_clauses | (clauses,fmla) | return clauses + tc.clauses | return clauses equivalent to fmla -> clauses | return clauses equivalent to fmla -> clauses | [
"return",
"clauses",
"equivalent",
"to",
"fmla",
"-",
">",
"clauses"
] | def condition_clauses(clauses,fmla):
""" return clauses equivalent to fmla -> clauses """
fmla = negate(fmla)
# Note here: clauses may already contain Tseitin symbols
tc = TseitinContext(used_symbols_clauses(clauses))
with tc:
clauses = [cl1 for cl in clauses for cl1 in formula_to_clauses(Or(fmla,clause_to_formula(cl)))]
## print "tseitin: {}".format(clauses + tc.clauses)
return clauses + tc.clauses | [
"def",
"condition_clauses",
"(",
"clauses",
",",
"fmla",
")",
":",
"fmla",
"=",
"negate",
"(",
"fmla",
")",
"# Note here: clauses may already contain Tseitin symbols",
"tc",
"=",
"TseitinContext",
"(",
"used_symbols_clauses",
"(",
"clauses",
")",
")",
"with",
"tc",
":",
"clauses",
"=",
"[",
"cl1",
"for",
"cl",
"in",
"clauses",
"for",
"cl1",
"in",
"formula_to_clauses",
"(",
"Or",
"(",
"fmla",
",",
"clause_to_formula",
"(",
"cl",
")",
")",
")",
"]",
"## print \"tseitin: {}\".format(clauses + tc.clauses)",
"return",
"clauses",
"+",
"tc",
".",
"clauses"
] | https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_logic_utils.py#L861-L869 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | InputStream.tell | (*args, **kwargs) | return _core_.InputStream_tell(*args, **kwargs) | tell(self) -> int | tell(self) -> int | [
"tell",
"(",
"self",
")",
"-",
">",
"int"
] | def tell(*args, **kwargs):
"""tell(self) -> int"""
return _core_.InputStream_tell(*args, **kwargs) | [
"def",
"tell",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"InputStream_tell",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L2186-L2188 | |
avast/retdec | b9879088a5f0278508185ec645494e6c5c57a455 | scripts/retdec-utils.py | python | CmdRunner._get_clean_output_from_measured_output | (output) | return out | Get the original output of the executed command from the measured
output containing additional information.
`/usr/bin/time` format is expected.
The output from `/usr/bin/time -v` looks either like this (success):
[..] (output from the tool)
Command being timed: "tool"
[..] (other data)
or like this (when there was an error):
[..] (output from the tool)
Command exited with non-zero status X
[..] (other data) | Get the original output of the executed command from the measured
output containing additional information. | [
"Get",
"the",
"original",
"output",
"of",
"the",
"executed",
"command",
"from",
"the",
"measured",
"output",
"containing",
"additional",
"information",
"."
] | def _get_clean_output_from_measured_output(output):
"""Get the original output of the executed command from the measured
output containing additional information.
`/usr/bin/time` format is expected.
The output from `/usr/bin/time -v` looks either like this (success):
[..] (output from the tool)
Command being timed: "tool"
[..] (other data)
or like this (when there was an error):
[..] (output from the tool)
Command exited with non-zero status X
[..] (other data)
"""
out = output
out = out.split('Command being timed:')[0]
out = out.split('Command exited with non-zero status')[0]
out = out.rstrip()
return out | [
"def",
"_get_clean_output_from_measured_output",
"(",
"output",
")",
":",
"out",
"=",
"output",
"out",
"=",
"out",
".",
"split",
"(",
"'Command being timed:'",
")",
"[",
"0",
"]",
"out",
"=",
"out",
".",
"split",
"(",
"'Command exited with non-zero status'",
")",
"[",
"0",
"]",
"out",
"=",
"out",
".",
"rstrip",
"(",
")",
"return",
"out"
] | https://github.com/avast/retdec/blob/b9879088a5f0278508185ec645494e6c5c57a455/scripts/retdec-utils.py#L200-L223 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib2to3/pgen2/parse.py | python | Parser.classify | (self, type, value, context) | return ilabel | Turn a token into a label. (Internal) | Turn a token into a label. (Internal) | [
"Turn",
"a",
"token",
"into",
"a",
"label",
".",
"(",
"Internal",
")"
] | def classify(self, type, value, context):
"""Turn a token into a label. (Internal)"""
if type == token.NAME:
# Keep a listing of all used names
self.used_names.add(value)
# Check for reserved words
ilabel = self.grammar.keywords.get(value)
if ilabel is not None:
return ilabel
ilabel = self.grammar.tokens.get(type)
if ilabel is None:
raise ParseError("bad token", type, value, context)
return ilabel | [
"def",
"classify",
"(",
"self",
",",
"type",
",",
"value",
",",
"context",
")",
":",
"if",
"type",
"==",
"token",
".",
"NAME",
":",
"# Keep a listing of all used names",
"self",
".",
"used_names",
".",
"add",
"(",
"value",
")",
"# Check for reserved words",
"ilabel",
"=",
"self",
".",
"grammar",
".",
"keywords",
".",
"get",
"(",
"value",
")",
"if",
"ilabel",
"is",
"not",
"None",
":",
"return",
"ilabel",
"ilabel",
"=",
"self",
".",
"grammar",
".",
"tokens",
".",
"get",
"(",
"type",
")",
"if",
"ilabel",
"is",
"None",
":",
"raise",
"ParseError",
"(",
"\"bad token\"",
",",
"type",
",",
"value",
",",
"context",
")",
"return",
"ilabel"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib2to3/pgen2/parse.py#L161-L173 | |
jolibrain/deepdetect | 9bc840f0b1055426670d64b5285701d6faceabb9 | demo/imgsearch/dd_client.py | python | DD.__init__ | (self,host="localhost",port=8080,proto=0,apiversion="0.1") | DD class constructor
Parameters:
host -- the DeepDetect server host
port -- the DeepDetect server port
proto -- user http (0,default) or https connection | DD class constructor
Parameters:
host -- the DeepDetect server host
port -- the DeepDetect server port
proto -- user http (0,default) or https connection | [
"DD",
"class",
"constructor",
"Parameters",
":",
"host",
"--",
"the",
"DeepDetect",
"server",
"host",
"port",
"--",
"the",
"DeepDetect",
"server",
"port",
"proto",
"--",
"user",
"http",
"(",
"0",
"default",
")",
"or",
"https",
"connection"
] | def __init__(self,host="localhost",port=8080,proto=0,apiversion="0.1"):
""" DD class constructor
Parameters:
host -- the DeepDetect server host
port -- the DeepDetect server port
proto -- user http (0,default) or https connection
"""
self.apiversion = apiversion
self.__urls = API_METHODS_URL[apiversion]
self.__host = host
self.__port = port
self.__proto = proto
self.__returntype=self.RETURN_PYTHON
if proto == self.__HTTP:
self.__ddurl='http://%s:%d'%(host,port)
else:
self.__ddurl='https://%s:%d'%(host,port) | [
"def",
"__init__",
"(",
"self",
",",
"host",
"=",
"\"localhost\"",
",",
"port",
"=",
"8080",
",",
"proto",
"=",
"0",
",",
"apiversion",
"=",
"\"0.1\"",
")",
":",
"self",
".",
"apiversion",
"=",
"apiversion",
"self",
".",
"__urls",
"=",
"API_METHODS_URL",
"[",
"apiversion",
"]",
"self",
".",
"__host",
"=",
"host",
"self",
".",
"__port",
"=",
"port",
"self",
".",
"__proto",
"=",
"proto",
"self",
".",
"__returntype",
"=",
"self",
".",
"RETURN_PYTHON",
"if",
"proto",
"==",
"self",
".",
"__HTTP",
":",
"self",
".",
"__ddurl",
"=",
"'http://%s:%d'",
"%",
"(",
"host",
",",
"port",
")",
"else",
":",
"self",
".",
"__ddurl",
"=",
"'https://%s:%d'",
"%",
"(",
"host",
",",
"port",
")"
] | https://github.com/jolibrain/deepdetect/blob/9bc840f0b1055426670d64b5285701d6faceabb9/demo/imgsearch/dd_client.py#L115-L131 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/tools/gyp/pylib/gyp/xcode_emulation.py | python | GetMacInfoPlist | (product_dir, xcode_settings, gyp_path_to_build_path) | return info_plist, dest_plist, defines, extra_env | Returns (info_plist, dest_plist, defines, extra_env), where:
* |info_plist| is the source plist path, relative to the
build directory,
* |dest_plist| is the destination plist path, relative to the
build directory,
* |defines| is a list of preprocessor defines (empty if the plist
shouldn't be preprocessed,
* |extra_env| is a dict of env variables that should be exported when
invoking |mac_tool copy-info-plist|.
Only call this for mac bundle targets.
Args:
product_dir: Path to the directory containing the output bundle,
relative to the build directory.
xcode_settings: The XcodeSettings of the current target.
gyp_to_build_path: A function that converts paths relative to the
current gyp file to paths relative to the build directory. | Returns (info_plist, dest_plist, defines, extra_env), where:
* |info_plist| is the source plist path, relative to the
build directory,
* |dest_plist| is the destination plist path, relative to the
build directory,
* |defines| is a list of preprocessor defines (empty if the plist
shouldn't be preprocessed,
* |extra_env| is a dict of env variables that should be exported when
invoking |mac_tool copy-info-plist|. | [
"Returns",
"(",
"info_plist",
"dest_plist",
"defines",
"extra_env",
")",
"where",
":",
"*",
"|info_plist|",
"is",
"the",
"source",
"plist",
"path",
"relative",
"to",
"the",
"build",
"directory",
"*",
"|dest_plist|",
"is",
"the",
"destination",
"plist",
"path",
"relative",
"to",
"the",
"build",
"directory",
"*",
"|defines|",
"is",
"a",
"list",
"of",
"preprocessor",
"defines",
"(",
"empty",
"if",
"the",
"plist",
"shouldn",
"t",
"be",
"preprocessed",
"*",
"|extra_env|",
"is",
"a",
"dict",
"of",
"env",
"variables",
"that",
"should",
"be",
"exported",
"when",
"invoking",
"|mac_tool",
"copy",
"-",
"info",
"-",
"plist|",
"."
] | def GetMacInfoPlist(product_dir, xcode_settings, gyp_path_to_build_path):
"""Returns (info_plist, dest_plist, defines, extra_env), where:
* |info_plist| is the source plist path, relative to the
build directory,
* |dest_plist| is the destination plist path, relative to the
build directory,
* |defines| is a list of preprocessor defines (empty if the plist
shouldn't be preprocessed,
* |extra_env| is a dict of env variables that should be exported when
invoking |mac_tool copy-info-plist|.
Only call this for mac bundle targets.
Args:
product_dir: Path to the directory containing the output bundle,
relative to the build directory.
xcode_settings: The XcodeSettings of the current target.
gyp_to_build_path: A function that converts paths relative to the
current gyp file to paths relative to the build directory.
"""
info_plist = xcode_settings.GetPerTargetSetting('INFOPLIST_FILE')
if not info_plist:
return None, None, [], {}
# The make generator doesn't support it, so forbid it everywhere
# to keep the generators more interchangeable.
assert ' ' not in info_plist, (
"Spaces in Info.plist filenames not supported (%s)" % info_plist)
info_plist = gyp_path_to_build_path(info_plist)
# If explicitly set to preprocess the plist, invoke the C preprocessor and
# specify any defines as -D flags.
if xcode_settings.GetPerTargetSetting(
'INFOPLIST_PREPROCESS', default='NO') == 'YES':
# Create an intermediate file based on the path.
defines = shlex.split(xcode_settings.GetPerTargetSetting(
'INFOPLIST_PREPROCESSOR_DEFINITIONS', default=''))
else:
defines = []
dest_plist = os.path.join(product_dir, xcode_settings.GetBundlePlistPath())
extra_env = xcode_settings.GetPerTargetSettings()
return info_plist, dest_plist, defines, extra_env | [
"def",
"GetMacInfoPlist",
"(",
"product_dir",
",",
"xcode_settings",
",",
"gyp_path_to_build_path",
")",
":",
"info_plist",
"=",
"xcode_settings",
".",
"GetPerTargetSetting",
"(",
"'INFOPLIST_FILE'",
")",
"if",
"not",
"info_plist",
":",
"return",
"None",
",",
"None",
",",
"[",
"]",
",",
"{",
"}",
"# The make generator doesn't support it, so forbid it everywhere",
"# to keep the generators more interchangeable.",
"assert",
"' '",
"not",
"in",
"info_plist",
",",
"(",
"\"Spaces in Info.plist filenames not supported (%s)\"",
"%",
"info_plist",
")",
"info_plist",
"=",
"gyp_path_to_build_path",
"(",
"info_plist",
")",
"# If explicitly set to preprocess the plist, invoke the C preprocessor and",
"# specify any defines as -D flags.",
"if",
"xcode_settings",
".",
"GetPerTargetSetting",
"(",
"'INFOPLIST_PREPROCESS'",
",",
"default",
"=",
"'NO'",
")",
"==",
"'YES'",
":",
"# Create an intermediate file based on the path.",
"defines",
"=",
"shlex",
".",
"split",
"(",
"xcode_settings",
".",
"GetPerTargetSetting",
"(",
"'INFOPLIST_PREPROCESSOR_DEFINITIONS'",
",",
"default",
"=",
"''",
")",
")",
"else",
":",
"defines",
"=",
"[",
"]",
"dest_plist",
"=",
"os",
".",
"path",
".",
"join",
"(",
"product_dir",
",",
"xcode_settings",
".",
"GetBundlePlistPath",
"(",
")",
")",
"extra_env",
"=",
"xcode_settings",
".",
"GetPerTargetSettings",
"(",
")",
"return",
"info_plist",
",",
"dest_plist",
",",
"defines",
",",
"extra_env"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/xcode_emulation.py#L1549-L1593 | |
facebookresearch/faiss | eb8781557f556505ca93f6f21fff932e17f0d9e0 | contrib/datasets.py | python | Dataset.get_queries | (self) | return the queries as a (nq, d) array | return the queries as a (nq, d) array | [
"return",
"the",
"queries",
"as",
"a",
"(",
"nq",
"d",
")",
"array"
] | def get_queries(self):
""" return the queries as a (nq, d) array """
raise NotImplementedError() | [
"def",
"get_queries",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/facebookresearch/faiss/blob/eb8781557f556505ca93f6f21fff932e17f0d9e0/contrib/datasets.py#L24-L26 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/base.py | python | try_cast_to_ea | (cls_or_instance, obj, dtype=None) | return result | Call to `_from_sequence` that returns the object unchanged on Exception.
Parameters
----------
cls_or_instance : ExtensionArray subclass or instance
obj : arraylike
Values to pass to cls._from_sequence
dtype : ExtensionDtype, optional
Returns
-------
ExtensionArray or obj | Call to `_from_sequence` that returns the object unchanged on Exception. | [
"Call",
"to",
"_from_sequence",
"that",
"returns",
"the",
"object",
"unchanged",
"on",
"Exception",
"."
] | def try_cast_to_ea(cls_or_instance, obj, dtype=None):
"""
Call to `_from_sequence` that returns the object unchanged on Exception.
Parameters
----------
cls_or_instance : ExtensionArray subclass or instance
obj : arraylike
Values to pass to cls._from_sequence
dtype : ExtensionDtype, optional
Returns
-------
ExtensionArray or obj
"""
try:
result = cls_or_instance._from_sequence(obj, dtype=dtype)
except Exception:
# We can't predict what downstream EA constructors may raise
result = obj
return result | [
"def",
"try_cast_to_ea",
"(",
"cls_or_instance",
",",
"obj",
",",
"dtype",
"=",
"None",
")",
":",
"try",
":",
"result",
"=",
"cls_or_instance",
".",
"_from_sequence",
"(",
"obj",
",",
"dtype",
"=",
"dtype",
")",
"except",
"Exception",
":",
"# We can't predict what downstream EA constructors may raise",
"result",
"=",
"obj",
"return",
"result"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/base.py#L34-L54 | |
arangodb/arangodb | 0d658689c7d1b721b314fa3ca27d38303e1570c8 | 3rdParty/V8/gyp/generator/xcode.py | python | ExpandXcodeVariables | (string, expansions) | return string | Expands Xcode-style $(VARIABLES) in string per the expansions dict.
In some rare cases, it is appropriate to expand Xcode variables when a
project file is generated. For any substring $(VAR) in string, if VAR is a
key in the expansions dict, $(VAR) will be replaced with expansions[VAR].
Any $(VAR) substring in string for which VAR is not a key in the expansions
dict will remain in the returned string. | Expands Xcode-style $(VARIABLES) in string per the expansions dict. | [
"Expands",
"Xcode",
"-",
"style",
"$",
"(",
"VARIABLES",
")",
"in",
"string",
"per",
"the",
"expansions",
"dict",
"."
] | def ExpandXcodeVariables(string, expansions):
"""Expands Xcode-style $(VARIABLES) in string per the expansions dict.
In some rare cases, it is appropriate to expand Xcode variables when a
project file is generated. For any substring $(VAR) in string, if VAR is a
key in the expansions dict, $(VAR) will be replaced with expansions[VAR].
Any $(VAR) substring in string for which VAR is not a key in the expansions
dict will remain in the returned string.
"""
matches = _xcode_variable_re.findall(string)
if matches == None:
return string
matches.reverse()
for match in matches:
(to_replace, variable) = match
if not variable in expansions:
continue
replacement = expansions[variable]
string = re.sub(re.escape(to_replace), replacement, string)
return string | [
"def",
"ExpandXcodeVariables",
"(",
"string",
",",
"expansions",
")",
":",
"matches",
"=",
"_xcode_variable_re",
".",
"findall",
"(",
"string",
")",
"if",
"matches",
"==",
"None",
":",
"return",
"string",
"matches",
".",
"reverse",
"(",
")",
"for",
"match",
"in",
"matches",
":",
"(",
"to_replace",
",",
"variable",
")",
"=",
"match",
"if",
"not",
"variable",
"in",
"expansions",
":",
"continue",
"replacement",
"=",
"expansions",
"[",
"variable",
"]",
"string",
"=",
"re",
".",
"sub",
"(",
"re",
".",
"escape",
"(",
"to_replace",
")",
",",
"replacement",
",",
"string",
")",
"return",
"string"
] | https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/gyp/generator/xcode.py#L533-L556 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/dateutil/tz/win.py | python | tzwinbase.transitions | (self, year) | return dston, dstoff | For a given year, get the DST on and off transition times, expressed
always on the standard time side. For zones with no transitions, this
function returns ``None``.
:param year:
The year whose transitions you would like to query.
:return:
Returns a :class:`tuple` of :class:`datetime.datetime` objects,
``(dston, dstoff)`` for zones with an annual DST transition, or
``None`` for fixed offset zones. | For a given year, get the DST on and off transition times, expressed
always on the standard time side. For zones with no transitions, this
function returns ``None``. | [
"For",
"a",
"given",
"year",
"get",
"the",
"DST",
"on",
"and",
"off",
"transition",
"times",
"expressed",
"always",
"on",
"the",
"standard",
"time",
"side",
".",
"For",
"zones",
"with",
"no",
"transitions",
"this",
"function",
"returns",
"None",
"."
] | def transitions(self, year):
"""
For a given year, get the DST on and off transition times, expressed
always on the standard time side. For zones with no transitions, this
function returns ``None``.
:param year:
The year whose transitions you would like to query.
:return:
Returns a :class:`tuple` of :class:`datetime.datetime` objects,
``(dston, dstoff)`` for zones with an annual DST transition, or
``None`` for fixed offset zones.
"""
if not self.hasdst:
return None
dston = picknthweekday(year, self._dstmonth, self._dstdayofweek,
self._dsthour, self._dstminute,
self._dstweeknumber)
dstoff = picknthweekday(year, self._stdmonth, self._stddayofweek,
self._stdhour, self._stdminute,
self._stdweeknumber)
# Ambiguous dates default to the STD side
dstoff -= self._dst_base_offset
return dston, dstoff | [
"def",
"transitions",
"(",
"self",
",",
"year",
")",
":",
"if",
"not",
"self",
".",
"hasdst",
":",
"return",
"None",
"dston",
"=",
"picknthweekday",
"(",
"year",
",",
"self",
".",
"_dstmonth",
",",
"self",
".",
"_dstdayofweek",
",",
"self",
".",
"_dsthour",
",",
"self",
".",
"_dstminute",
",",
"self",
".",
"_dstweeknumber",
")",
"dstoff",
"=",
"picknthweekday",
"(",
"year",
",",
"self",
".",
"_stdmonth",
",",
"self",
".",
"_stddayofweek",
",",
"self",
".",
"_stdhour",
",",
"self",
".",
"_stdminute",
",",
"self",
".",
"_stdweeknumber",
")",
"# Ambiguous dates default to the STD side",
"dstoff",
"-=",
"self",
".",
"_dst_base_offset",
"return",
"dston",
",",
"dstoff"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/dateutil/tz/win.py#L163-L192 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/fancy_getopt.py | python | translate_longopt | (opt) | return string.translate(opt, longopt_xlate) | Convert a long option name to a valid Python identifier by
changing "-" to "_". | Convert a long option name to a valid Python identifier by
changing "-" to "_". | [
"Convert",
"a",
"long",
"option",
"name",
"to",
"a",
"valid",
"Python",
"identifier",
"by",
"changing",
"-",
"to",
"_",
"."
] | def translate_longopt(opt):
"""Convert a long option name to a valid Python identifier by
changing "-" to "_".
"""
return string.translate(opt, longopt_xlate) | [
"def",
"translate_longopt",
"(",
"opt",
")",
":",
"return",
"string",
".",
"translate",
"(",
"opt",
",",
"longopt_xlate",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/fancy_getopt.py#L469-L473 | |
OAID/Caffe-HRT | aae71e498ab842c6f92bcc23fc668423615a4d65 | examples/pycaffe/layers/pascal_multilabel_datalayers.py | python | check_params | (params) | A utility function to check the parameters for the data layers. | A utility function to check the parameters for the data layers. | [
"A",
"utility",
"function",
"to",
"check",
"the",
"parameters",
"for",
"the",
"data",
"layers",
"."
] | def check_params(params):
"""
A utility function to check the parameters for the data layers.
"""
assert 'split' in params.keys(
), 'Params must include split (train, val, or test).'
required = ['batch_size', 'pascal_root', 'im_shape']
for r in required:
assert r in params.keys(), 'Params must include {}'.format(r) | [
"def",
"check_params",
"(",
"params",
")",
":",
"assert",
"'split'",
"in",
"params",
".",
"keys",
"(",
")",
",",
"'Params must include split (train, val, or test).'",
"required",
"=",
"[",
"'batch_size'",
",",
"'pascal_root'",
",",
"'im_shape'",
"]",
"for",
"r",
"in",
"required",
":",
"assert",
"r",
"in",
"params",
".",
"keys",
"(",
")",
",",
"'Params must include {}'",
".",
"format",
"(",
"r",
")"
] | https://github.com/OAID/Caffe-HRT/blob/aae71e498ab842c6f92bcc23fc668423615a4d65/examples/pycaffe/layers/pascal_multilabel_datalayers.py#L196-L205 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/reduction_gui/widgets/data_table_view.py | python | DataTableModel._isRowEmpty | (self, row) | return all((v is None or not str(v).strip()) for v in self._getRow(row)) | checks if the row is empty
:param row: int of the row to check
:return: true if row is empty | checks if the row is empty
:param row: int of the row to check
:return: true if row is empty | [
"checks",
"if",
"the",
"row",
"is",
"empty",
":",
"param",
"row",
":",
"int",
"of",
"the",
"row",
"to",
"check",
":",
"return",
":",
"true",
"if",
"row",
"is",
"empty"
] | def _isRowEmpty(self, row):
"""
checks if the row is empty
:param row: int of the row to check
:return: true if row is empty
"""
return all((v is None or not str(v).strip()) for v in self._getRow(row)) | [
"def",
"_isRowEmpty",
"(",
"self",
",",
"row",
")",
":",
"return",
"all",
"(",
"(",
"v",
"is",
"None",
"or",
"not",
"str",
"(",
"v",
")",
".",
"strip",
"(",
")",
")",
"for",
"v",
"in",
"self",
".",
"_getRow",
"(",
"row",
")",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/reduction_gui/widgets/data_table_view.py#L47-L53 | |
openthread/openthread | 9fcdbed9c526c70f1556d1ed84099c1535c7cd32 | tools/harness-thci/OpenThread_BR.py | python | OpenThread_BR.ping | (self, strDestination, ilength=0, hop_limit=5, timeout=5) | send ICMPv6 echo request with a given length to a unicast destination
address
Args:
strDestination: the unicast destination address of ICMPv6 echo request
ilength: the size of ICMPv6 echo request payload
hop_limit: the hop limit
timeout: time before ping() stops | send ICMPv6 echo request with a given length to a unicast destination
address | [
"send",
"ICMPv6",
"echo",
"request",
"with",
"a",
"given",
"length",
"to",
"a",
"unicast",
"destination",
"address"
] | def ping(self, strDestination, ilength=0, hop_limit=5, timeout=5):
""" send ICMPv6 echo request with a given length to a unicast destination
address
Args:
strDestination: the unicast destination address of ICMPv6 echo request
ilength: the size of ICMPv6 echo request payload
hop_limit: the hop limit
timeout: time before ping() stops
"""
if hop_limit is None:
hop_limit = 5
if self.IsHost or self.IsBackboneRouter:
ifName = 'eth0'
else:
ifName = 'wpan0'
cmd = 'ping -6 -I %s %s -c 1 -s %d -W %d -t %d' % (
ifName,
strDestination,
int(ilength),
int(timeout),
int(hop_limit),
)
self.bash(cmd)
time.sleep(timeout) | [
"def",
"ping",
"(",
"self",
",",
"strDestination",
",",
"ilength",
"=",
"0",
",",
"hop_limit",
"=",
"5",
",",
"timeout",
"=",
"5",
")",
":",
"if",
"hop_limit",
"is",
"None",
":",
"hop_limit",
"=",
"5",
"if",
"self",
".",
"IsHost",
"or",
"self",
".",
"IsBackboneRouter",
":",
"ifName",
"=",
"'eth0'",
"else",
":",
"ifName",
"=",
"'wpan0'",
"cmd",
"=",
"'ping -6 -I %s %s -c 1 -s %d -W %d -t %d'",
"%",
"(",
"ifName",
",",
"strDestination",
",",
"int",
"(",
"ilength",
")",
",",
"int",
"(",
"timeout",
")",
",",
"int",
"(",
"hop_limit",
")",
",",
")",
"self",
".",
"bash",
"(",
"cmd",
")",
"time",
".",
"sleep",
"(",
"timeout",
")"
] | https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/tools/harness-thci/OpenThread_BR.py#L422-L449 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/npyufunc/deviceufunc.py | python | UFuncMechanism.__init__ | (self, typemap, args) | Never used directly by user. Invoke by UFuncMechanism.call(). | Never used directly by user. Invoke by UFuncMechanism.call(). | [
"Never",
"used",
"directly",
"by",
"user",
".",
"Invoke",
"by",
"UFuncMechanism",
".",
"call",
"()",
"."
] | def __init__(self, typemap, args):
"""Never used directly by user. Invoke by UFuncMechanism.call().
"""
self.typemap = typemap
self.args = args
nargs = len(self.args)
self.argtypes = [None] * nargs
self.scalarpos = []
self.signature = None
self.arrays = [None] * nargs | [
"def",
"__init__",
"(",
"self",
",",
"typemap",
",",
"args",
")",
":",
"self",
".",
"typemap",
"=",
"typemap",
"self",
".",
"args",
"=",
"args",
"nargs",
"=",
"len",
"(",
"self",
".",
"args",
")",
"self",
".",
"argtypes",
"=",
"[",
"None",
"]",
"*",
"nargs",
"self",
".",
"scalarpos",
"=",
"[",
"]",
"self",
".",
"signature",
"=",
"None",
"self",
".",
"arrays",
"=",
"[",
"None",
"]",
"*",
"nargs"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/npyufunc/deviceufunc.py#L81-L90 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/urllib3/util/connection.py | python | is_connection_dropped | (conn) | Returns True if the connection is dropped and should be closed.
:param conn:
:class:`httplib.HTTPConnection` object.
Note: For platforms like AppEngine, this will always return ``False`` to
let the platform handle connection recycling transparently for us. | Returns True if the connection is dropped and should be closed. | [
"Returns",
"True",
"if",
"the",
"connection",
"is",
"dropped",
"and",
"should",
"be",
"closed",
"."
] | def is_connection_dropped(conn): # Platform-specific
"""
Returns True if the connection is dropped and should be closed.
:param conn:
:class:`httplib.HTTPConnection` object.
Note: For platforms like AppEngine, this will always return ``False`` to
let the platform handle connection recycling transparently for us.
"""
sock = getattr(conn, 'sock', False)
if sock is False: # Platform-specific: AppEngine
return False
if sock is None: # Connection already closed (such as by httplib).
return True
if not HAS_SELECT:
return False
try:
return bool(wait_for_read(sock, timeout=0.0))
except SelectorError:
return True | [
"def",
"is_connection_dropped",
"(",
"conn",
")",
":",
"# Platform-specific",
"sock",
"=",
"getattr",
"(",
"conn",
",",
"'sock'",
",",
"False",
")",
"if",
"sock",
"is",
"False",
":",
"# Platform-specific: AppEngine",
"return",
"False",
"if",
"sock",
"is",
"None",
":",
"# Connection already closed (such as by httplib).",
"return",
"True",
"if",
"not",
"HAS_SELECT",
":",
"return",
"False",
"try",
":",
"return",
"bool",
"(",
"wait_for_read",
"(",
"sock",
",",
"timeout",
"=",
"0.0",
")",
")",
"except",
"SelectorError",
":",
"return",
"True"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/urllib3/util/connection.py#L7-L29 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/sparse/coo.py | python | coo_matrix.tocsc | (self, copy=False) | Convert this matrix to Compressed Sparse Column format
Duplicate entries will be summed together.
Examples
--------
>>> from numpy import array
>>> from scipy.sparse import coo_matrix
>>> row = array([0, 0, 1, 3, 1, 0, 0])
>>> col = array([0, 2, 1, 3, 1, 0, 0])
>>> data = array([1, 1, 1, 1, 1, 1, 1])
>>> A = coo_matrix((data, (row, col)), shape=(4, 4)).tocsc()
>>> A.toarray()
array([[3, 0, 1, 0],
[0, 2, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 1]]) | Convert this matrix to Compressed Sparse Column format | [
"Convert",
"this",
"matrix",
"to",
"Compressed",
"Sparse",
"Column",
"format"
] | def tocsc(self, copy=False):
"""Convert this matrix to Compressed Sparse Column format
Duplicate entries will be summed together.
Examples
--------
>>> from numpy import array
>>> from scipy.sparse import coo_matrix
>>> row = array([0, 0, 1, 3, 1, 0, 0])
>>> col = array([0, 2, 1, 3, 1, 0, 0])
>>> data = array([1, 1, 1, 1, 1, 1, 1])
>>> A = coo_matrix((data, (row, col)), shape=(4, 4)).tocsc()
>>> A.toarray()
array([[3, 0, 1, 0],
[0, 2, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 1]])
"""
from .csc import csc_matrix
if self.nnz == 0:
return csc_matrix(self.shape, dtype=self.dtype)
else:
M,N = self.shape
idx_dtype = get_index_dtype((self.col, self.row),
maxval=max(self.nnz, M))
row = self.row.astype(idx_dtype, copy=False)
col = self.col.astype(idx_dtype, copy=False)
indptr = np.empty(N + 1, dtype=idx_dtype)
indices = np.empty_like(row, dtype=idx_dtype)
data = np.empty_like(self.data, dtype=upcast(self.dtype))
coo_tocsr(N, M, self.nnz, col, row, self.data,
indptr, indices, data)
x = csc_matrix((data, indices, indptr), shape=self.shape)
if not self.has_canonical_format:
x.sum_duplicates()
return x | [
"def",
"tocsc",
"(",
"self",
",",
"copy",
"=",
"False",
")",
":",
"from",
".",
"csc",
"import",
"csc_matrix",
"if",
"self",
".",
"nnz",
"==",
"0",
":",
"return",
"csc_matrix",
"(",
"self",
".",
"shape",
",",
"dtype",
"=",
"self",
".",
"dtype",
")",
"else",
":",
"M",
",",
"N",
"=",
"self",
".",
"shape",
"idx_dtype",
"=",
"get_index_dtype",
"(",
"(",
"self",
".",
"col",
",",
"self",
".",
"row",
")",
",",
"maxval",
"=",
"max",
"(",
"self",
".",
"nnz",
",",
"M",
")",
")",
"row",
"=",
"self",
".",
"row",
".",
"astype",
"(",
"idx_dtype",
",",
"copy",
"=",
"False",
")",
"col",
"=",
"self",
".",
"col",
".",
"astype",
"(",
"idx_dtype",
",",
"copy",
"=",
"False",
")",
"indptr",
"=",
"np",
".",
"empty",
"(",
"N",
"+",
"1",
",",
"dtype",
"=",
"idx_dtype",
")",
"indices",
"=",
"np",
".",
"empty_like",
"(",
"row",
",",
"dtype",
"=",
"idx_dtype",
")",
"data",
"=",
"np",
".",
"empty_like",
"(",
"self",
".",
"data",
",",
"dtype",
"=",
"upcast",
"(",
"self",
".",
"dtype",
")",
")",
"coo_tocsr",
"(",
"N",
",",
"M",
",",
"self",
".",
"nnz",
",",
"col",
",",
"row",
",",
"self",
".",
"data",
",",
"indptr",
",",
"indices",
",",
"data",
")",
"x",
"=",
"csc_matrix",
"(",
"(",
"data",
",",
"indices",
",",
"indptr",
")",
",",
"shape",
"=",
"self",
".",
"shape",
")",
"if",
"not",
"self",
".",
"has_canonical_format",
":",
"x",
".",
"sum_duplicates",
"(",
")",
"return",
"x"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/sparse/coo.py#L326-L366 | ||
MegEngine/MegEngine | ce9ad07a27ec909fb8db4dd67943d24ba98fb93a | imperative/python/megengine/core/tensor/dtype.py | python | QuantDtypeMeta.__deepcopy__ | (self, _) | return self | r"""
Ignore deepcopy so that a dtype meta can be treated as singleton, for more
strict check in :meth:`~.FakeQuantize.fake_quant_forward`. | r"""
Ignore deepcopy so that a dtype meta can be treated as singleton, for more
strict check in :meth:`~.FakeQuantize.fake_quant_forward`. | [
"r",
"Ignore",
"deepcopy",
"so",
"that",
"a",
"dtype",
"meta",
"can",
"be",
"treated",
"as",
"singleton",
"for",
"more",
"strict",
"check",
"in",
":",
"meth",
":",
"~",
".",
"FakeQuantize",
".",
"fake_quant_forward",
"."
] | def __deepcopy__(self, _):
r"""
Ignore deepcopy so that a dtype meta can be treated as singleton, for more
strict check in :meth:`~.FakeQuantize.fake_quant_forward`.
"""
return self | [
"def",
"__deepcopy__",
"(",
"self",
",",
"_",
")",
":",
"return",
"self"
] | https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/core/tensor/dtype.py#L79-L84 | |
QMCPACK/qmcpack | d0948ab455e38364458740cc8e2239600a14c5cd | nexus/lib/versions.py | python | Versions.policy_supported_version | (self,name=None) | (`Internal API`) Determine versions of Nexus dependencies that
comply with the age policy relative to today's date. | (`Internal API`) Determine versions of Nexus dependencies that
comply with the age policy relative to today's date. | [
"(",
"Internal",
"API",
")",
"Determine",
"versions",
"of",
"Nexus",
"dependencies",
"that",
"comply",
"with",
"the",
"age",
"policy",
"relative",
"to",
"today",
"s",
"date",
"."
] | def policy_supported_version(self,name=None):
"""
(`Internal API`) Determine versions of Nexus dependencies that
comply with the age policy relative to today's date.
"""
if name is not None:
name = name.lower()
if name not in self.dependencies:
self.error('"{}" is not a dependency of Nexus'.format(name))
#end if
vdata = self.version_data[name]
versions = list(reversed(sorted(vdata.keys())))
sv = None
for version in versions:
vd = vdata[version]
sv = version
if vd['date'] <= support_cutoff_date:
break
#end if
#end for
return sv
else:
supported_versions = dict()
for name in self.dependencies:
sv = self.policy_supported_version(name)
supported_versions[name] = sv
#end for
return supported_versions | [
"def",
"policy_supported_version",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"not",
"None",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"if",
"name",
"not",
"in",
"self",
".",
"dependencies",
":",
"self",
".",
"error",
"(",
"'\"{}\" is not a dependency of Nexus'",
".",
"format",
"(",
"name",
")",
")",
"#end if",
"vdata",
"=",
"self",
".",
"version_data",
"[",
"name",
"]",
"versions",
"=",
"list",
"(",
"reversed",
"(",
"sorted",
"(",
"vdata",
".",
"keys",
"(",
")",
")",
")",
")",
"sv",
"=",
"None",
"for",
"version",
"in",
"versions",
":",
"vd",
"=",
"vdata",
"[",
"version",
"]",
"sv",
"=",
"version",
"if",
"vd",
"[",
"'date'",
"]",
"<=",
"support_cutoff_date",
":",
"break",
"#end if",
"#end for",
"return",
"sv",
"else",
":",
"supported_versions",
"=",
"dict",
"(",
")",
"for",
"name",
"in",
"self",
".",
"dependencies",
":",
"sv",
"=",
"self",
".",
"policy_supported_version",
"(",
"name",
")",
"supported_versions",
"[",
"name",
"]",
"=",
"sv",
"#end for",
"return",
"supported_versions"
] | https://github.com/QMCPACK/qmcpack/blob/d0948ab455e38364458740cc8e2239600a14c5cd/nexus/lib/versions.py#L569-L596 | ||
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/BeautifulSoup.py | python | PageElement.findNextSiblings | (self, name=None, attrs={}, text=None, limit=None,
**kwargs) | return self._findAll(name, attrs, text, limit,
self.nextSiblingGenerator, **kwargs) | Returns the siblings of this Tag that match the given
criteria and appear after this Tag in the document. | Returns the siblings of this Tag that match the given
criteria and appear after this Tag in the document. | [
"Returns",
"the",
"siblings",
"of",
"this",
"Tag",
"that",
"match",
"the",
"given",
"criteria",
"and",
"appear",
"after",
"this",
"Tag",
"in",
"the",
"document",
"."
] | def findNextSiblings(self, name=None, attrs={}, text=None, limit=None,
**kwargs):
"""Returns the siblings of this Tag that match the given
criteria and appear after this Tag in the document."""
return self._findAll(name, attrs, text, limit,
self.nextSiblingGenerator, **kwargs) | [
"def",
"findNextSiblings",
"(",
"self",
",",
"name",
"=",
"None",
",",
"attrs",
"=",
"{",
"}",
",",
"text",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_findAll",
"(",
"name",
",",
"attrs",
",",
"text",
",",
"limit",
",",
"self",
".",
"nextSiblingGenerator",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/BeautifulSoup.py#L270-L275 | |
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | clang/tools/scan-build-py/libscanbuild/arguments.py | python | create_intercept_parser | () | return parser | Creates a parser for command-line arguments to 'intercept'. | Creates a parser for command-line arguments to 'intercept'. | [
"Creates",
"a",
"parser",
"for",
"command",
"-",
"line",
"arguments",
"to",
"intercept",
"."
] | def create_intercept_parser():
""" Creates a parser for command-line arguments to 'intercept'. """
parser = create_default_parser()
parser_add_cdb(parser)
parser_add_prefer_wrapper(parser)
parser_add_compilers(parser)
advanced = parser.add_argument_group('advanced options')
group = advanced.add_mutually_exclusive_group()
group.add_argument(
'--append',
action='store_true',
help="""Extend existing compilation database with new entries.
Duplicate entries are detected and not present in the final output.
The output is not continuously updated, it's done when the build
command finished. """)
parser.add_argument(
dest='build', nargs=argparse.REMAINDER, help="""Command to run.""")
return parser | [
"def",
"create_intercept_parser",
"(",
")",
":",
"parser",
"=",
"create_default_parser",
"(",
")",
"parser_add_cdb",
"(",
"parser",
")",
"parser_add_prefer_wrapper",
"(",
"parser",
")",
"parser_add_compilers",
"(",
"parser",
")",
"advanced",
"=",
"parser",
".",
"add_argument_group",
"(",
"'advanced options'",
")",
"group",
"=",
"advanced",
".",
"add_mutually_exclusive_group",
"(",
")",
"group",
".",
"add_argument",
"(",
"'--append'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"\"\"\"Extend existing compilation database with new entries.\n Duplicate entries are detected and not present in the final output.\n The output is not continuously updated, it's done when the build\n command finished. \"\"\"",
")",
"parser",
".",
"add_argument",
"(",
"dest",
"=",
"'build'",
",",
"nargs",
"=",
"argparse",
".",
"REMAINDER",
",",
"help",
"=",
"\"\"\"Command to run.\"\"\"",
")",
"return",
"parser"
] | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/clang/tools/scan-build-py/libscanbuild/arguments.py#L143-L164 | |
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Script/Main.py | python | _load_all_site_scons_dirs | (topdir, verbose=None) | Load all of the predefined site_scons dir.
Order is significant; we load them in order from most generic
(machine-wide) to most specific (topdir).
The verbose argument is only for testing. | Load all of the predefined site_scons dir.
Order is significant; we load them in order from most generic
(machine-wide) to most specific (topdir).
The verbose argument is only for testing. | [
"Load",
"all",
"of",
"the",
"predefined",
"site_scons",
"dir",
".",
"Order",
"is",
"significant",
";",
"we",
"load",
"them",
"in",
"order",
"from",
"most",
"generic",
"(",
"machine",
"-",
"wide",
")",
"to",
"most",
"specific",
"(",
"topdir",
")",
".",
"The",
"verbose",
"argument",
"is",
"only",
"for",
"testing",
"."
] | def _load_all_site_scons_dirs(topdir, verbose=None):
"""Load all of the predefined site_scons dir.
Order is significant; we load them in order from most generic
(machine-wide) to most specific (topdir).
The verbose argument is only for testing.
"""
platform = SCons.Platform.platform_default()
def homedir(d):
return os.path.expanduser('~/'+d)
if platform == 'win32' or platform == 'cygwin':
# Note we use $ here instead of %...% because older
# pythons (prior to 2.6?) didn't expand %...% on Windows.
# This set of dirs should work on XP, Vista, 7 and later.
sysdirs=[
os.path.expandvars('$ALLUSERSPROFILE\\Application Data\\scons'),
os.path.expandvars('$USERPROFILE\\Local Settings\\Application Data\\scons')]
appdatadir = os.path.expandvars('$APPDATA\\scons')
if appdatadir not in sysdirs:
sysdirs.append(appdatadir)
sysdirs.append(homedir('.scons'))
elif platform == 'darwin': # MacOS X
sysdirs=['/Library/Application Support/SCons',
'/opt/local/share/scons', # (for MacPorts)
'/sw/share/scons', # (for Fink)
homedir('Library/Application Support/SCons'),
homedir('.scons')]
elif platform == 'sunos': # Solaris
sysdirs=['/opt/sfw/scons',
'/usr/share/scons',
homedir('.scons')]
else: # Linux, HPUX, etc.
# assume posix-like, i.e. platform == 'posix'
sysdirs=['/usr/share/scons',
homedir('.scons')]
dirs=sysdirs + [topdir]
for d in dirs:
if verbose: # this is used by unit tests.
print "Loading site dir ", d
_load_site_scons_dir(d) | [
"def",
"_load_all_site_scons_dirs",
"(",
"topdir",
",",
"verbose",
"=",
"None",
")",
":",
"platform",
"=",
"SCons",
".",
"Platform",
".",
"platform_default",
"(",
")",
"def",
"homedir",
"(",
"d",
")",
":",
"return",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~/'",
"+",
"d",
")",
"if",
"platform",
"==",
"'win32'",
"or",
"platform",
"==",
"'cygwin'",
":",
"# Note we use $ here instead of %...% because older",
"# pythons (prior to 2.6?) didn't expand %...% on Windows.",
"# This set of dirs should work on XP, Vista, 7 and later.",
"sysdirs",
"=",
"[",
"os",
".",
"path",
".",
"expandvars",
"(",
"'$ALLUSERSPROFILE\\\\Application Data\\\\scons'",
")",
",",
"os",
".",
"path",
".",
"expandvars",
"(",
"'$USERPROFILE\\\\Local Settings\\\\Application Data\\\\scons'",
")",
"]",
"appdatadir",
"=",
"os",
".",
"path",
".",
"expandvars",
"(",
"'$APPDATA\\\\scons'",
")",
"if",
"appdatadir",
"not",
"in",
"sysdirs",
":",
"sysdirs",
".",
"append",
"(",
"appdatadir",
")",
"sysdirs",
".",
"append",
"(",
"homedir",
"(",
"'.scons'",
")",
")",
"elif",
"platform",
"==",
"'darwin'",
":",
"# MacOS X",
"sysdirs",
"=",
"[",
"'/Library/Application Support/SCons'",
",",
"'/opt/local/share/scons'",
",",
"# (for MacPorts)",
"'/sw/share/scons'",
",",
"# (for Fink)",
"homedir",
"(",
"'Library/Application Support/SCons'",
")",
",",
"homedir",
"(",
"'.scons'",
")",
"]",
"elif",
"platform",
"==",
"'sunos'",
":",
"# Solaris",
"sysdirs",
"=",
"[",
"'/opt/sfw/scons'",
",",
"'/usr/share/scons'",
",",
"homedir",
"(",
"'.scons'",
")",
"]",
"else",
":",
"# Linux, HPUX, etc.",
"# assume posix-like, i.e. platform == 'posix'",
"sysdirs",
"=",
"[",
"'/usr/share/scons'",
",",
"homedir",
"(",
"'.scons'",
")",
"]",
"dirs",
"=",
"sysdirs",
"+",
"[",
"topdir",
"]",
"for",
"d",
"in",
"dirs",
":",
"if",
"verbose",
":",
"# this is used by unit tests.",
"print",
"\"Loading site dir \"",
",",
"d",
"_load_site_scons_dir",
"(",
"d",
")"
] | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Script/Main.py#L754-L796 | ||
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py | python | _MSBuildOnly | (tool, name, setting_type) | Defines a setting that is only found in MSBuild.
Args:
tool: a dictionary that gives the names of the tool for MSVS and MSBuild.
name: the name of the setting.
setting_type: the type of this setting. | Defines a setting that is only found in MSBuild. | [
"Defines",
"a",
"setting",
"that",
"is",
"only",
"found",
"in",
"MSBuild",
"."
] | def _MSBuildOnly(tool, name, setting_type):
"""Defines a setting that is only found in MSBuild.
Args:
tool: a dictionary that gives the names of the tool for MSVS and MSBuild.
name: the name of the setting.
setting_type: the type of this setting.
"""
def _Translate(value, msbuild_settings):
# Let msbuild-only properties get translated as-is from msvs_settings.
tool_settings = msbuild_settings.setdefault(tool.msbuild_name, {})
tool_settings[name] = value
_msbuild_validators[tool.msbuild_name][name] = setting_type.ValidateMSBuild
_msvs_to_msbuild_converters[tool.msvs_name][name] = _Translate | [
"def",
"_MSBuildOnly",
"(",
"tool",
",",
"name",
",",
"setting_type",
")",
":",
"def",
"_Translate",
"(",
"value",
",",
"msbuild_settings",
")",
":",
"# Let msbuild-only properties get translated as-is from msvs_settings.",
"tool_settings",
"=",
"msbuild_settings",
".",
"setdefault",
"(",
"tool",
".",
"msbuild_name",
",",
"{",
"}",
")",
"tool_settings",
"[",
"name",
"]",
"=",
"value",
"_msbuild_validators",
"[",
"tool",
".",
"msbuild_name",
"]",
"[",
"name",
"]",
"=",
"setting_type",
".",
"ValidateMSBuild",
"_msvs_to_msbuild_converters",
"[",
"tool",
".",
"msvs_name",
"]",
"[",
"name",
"]",
"=",
"_Translate"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py#L310-L325 | ||
timi-liuliang/echo | 40a5a24d430eee4118314459ab7e03afcb3b8719 | thirdparty/protobuf/python/google/protobuf/internal/python_message.py | python | _AddPropertiesForField | (field, cls) | Adds a public property for a protocol message field.
Clients can use this property to get and (in the case
of non-repeated scalar fields) directly set the value
of a protocol message field.
Args:
field: A FieldDescriptor for this field.
cls: The class we're constructing. | Adds a public property for a protocol message field.
Clients can use this property to get and (in the case
of non-repeated scalar fields) directly set the value
of a protocol message field. | [
"Adds",
"a",
"public",
"property",
"for",
"a",
"protocol",
"message",
"field",
".",
"Clients",
"can",
"use",
"this",
"property",
"to",
"get",
"and",
"(",
"in",
"the",
"case",
"of",
"non",
"-",
"repeated",
"scalar",
"fields",
")",
"directly",
"set",
"the",
"value",
"of",
"a",
"protocol",
"message",
"field",
"."
] | def _AddPropertiesForField(field, cls):
"""Adds a public property for a protocol message field.
Clients can use this property to get and (in the case
of non-repeated scalar fields) directly set the value
of a protocol message field.
Args:
field: A FieldDescriptor for this field.
cls: The class we're constructing.
"""
# Catch it if we add other types that we should
# handle specially here.
assert _FieldDescriptor.MAX_CPPTYPE == 10
constant_name = field.name.upper() + "_FIELD_NUMBER"
setattr(cls, constant_name, field.number)
if field.label == _FieldDescriptor.LABEL_REPEATED:
_AddPropertiesForRepeatedField(field, cls)
elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
_AddPropertiesForNonRepeatedCompositeField(field, cls)
else:
_AddPropertiesForNonRepeatedScalarField(field, cls) | [
"def",
"_AddPropertiesForField",
"(",
"field",
",",
"cls",
")",
":",
"# Catch it if we add other types that we should",
"# handle specially here.",
"assert",
"_FieldDescriptor",
".",
"MAX_CPPTYPE",
"==",
"10",
"constant_name",
"=",
"field",
".",
"name",
".",
"upper",
"(",
")",
"+",
"\"_FIELD_NUMBER\"",
"setattr",
"(",
"cls",
",",
"constant_name",
",",
"field",
".",
"number",
")",
"if",
"field",
".",
"label",
"==",
"_FieldDescriptor",
".",
"LABEL_REPEATED",
":",
"_AddPropertiesForRepeatedField",
"(",
"field",
",",
"cls",
")",
"elif",
"field",
".",
"cpp_type",
"==",
"_FieldDescriptor",
".",
"CPPTYPE_MESSAGE",
":",
"_AddPropertiesForNonRepeatedCompositeField",
"(",
"field",
",",
"cls",
")",
"else",
":",
"_AddPropertiesForNonRepeatedScalarField",
"(",
"field",
",",
"cls",
")"
] | https://github.com/timi-liuliang/echo/blob/40a5a24d430eee4118314459ab7e03afcb3b8719/thirdparty/protobuf/python/google/protobuf/internal/python_message.py#L377-L399 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/session_ops.py | python | TensorHandle._get_resource_handle | (self) | return self._resource_handle | The ResourceHandle representation of this handle. | The ResourceHandle representation of this handle. | [
"The",
"ResourceHandle",
"representation",
"of",
"this",
"handle",
"."
] | def _get_resource_handle(self):
"""The ResourceHandle representation of this handle."""
if not self._resource_handle:
self._resource_handle = resource_handle_pb2.ResourceHandleProto()
self._resource_handle.device = self._handle.split(";")[-1]
self._resource_handle.container = (
pywrap_tensorflow_internal.TENSOR_HANDLE_KEY)
self._resource_handle.name = self._handle
return self._resource_handle | [
"def",
"_get_resource_handle",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_resource_handle",
":",
"self",
".",
"_resource_handle",
"=",
"resource_handle_pb2",
".",
"ResourceHandleProto",
"(",
")",
"self",
".",
"_resource_handle",
".",
"device",
"=",
"self",
".",
"_handle",
".",
"split",
"(",
"\";\"",
")",
"[",
"-",
"1",
"]",
"self",
".",
"_resource_handle",
".",
"container",
"=",
"(",
"pywrap_tensorflow_internal",
".",
"TENSOR_HANDLE_KEY",
")",
"self",
".",
"_resource_handle",
".",
"name",
"=",
"self",
".",
"_handle",
"return",
"self",
".",
"_resource_handle"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/session_ops.py#L69-L77 | |
zerotier/libzt | 41eb9aebc80a5f1c816fa26a06cefde9de906676 | src/bindings/python/sockets.py | python | socket.setdefaulttimeout | (self, timeout) | libzt does not support this (yet) | libzt does not support this (yet) | [
"libzt",
"does",
"not",
"support",
"this",
"(",
"yet",
")"
] | def setdefaulttimeout(self, timeout):
"""libzt does not support this (yet)"""
raise NotImplementedError("libzt does not support this (yet?)") | [
"def",
"setdefaulttimeout",
"(",
"self",
",",
"timeout",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"libzt does not support this (yet?)\"",
")"
] | https://github.com/zerotier/libzt/blob/41eb9aebc80a5f1c816fa26a06cefde9de906676/src/bindings/python/sockets.py#L199-L201 | ||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/SocketServer.py | python | ForkingMixIn.handle_timeout | (self) | Wait for zombies after self.timeout seconds of inactivity.
May be extended, do not override. | Wait for zombies after self.timeout seconds of inactivity. | [
"Wait",
"for",
"zombies",
"after",
"self",
".",
"timeout",
"seconds",
"of",
"inactivity",
"."
] | def handle_timeout(self):
"""Wait for zombies after self.timeout seconds of inactivity.
May be extended, do not override.
"""
self.collect_children() | [
"def",
"handle_timeout",
"(",
"self",
")",
":",
"self",
".",
"collect_children",
"(",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/SocketServer.py#L513-L518 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.