nwo
stringlengths 5
106
| sha
stringlengths 40
40
| path
stringlengths 4
174
| language
stringclasses 1
value | identifier
stringlengths 1
140
| parameters
stringlengths 0
87.7k
| argument_list
stringclasses 1
value | return_statement
stringlengths 0
426k
| docstring
stringlengths 0
64.3k
| docstring_summary
stringlengths 0
26.3k
| docstring_tokens
list | function
stringlengths 18
4.83M
| function_tokens
list | url
stringlengths 83
304
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
HymanLiuTS/flaskTs
|
286648286976e85d9b9a5873632331efcafe0b21
|
flasky/lib/python2.7/site-packages/sqlalchemy/sql/operators.py
|
python
|
ColumnOperators.any_
|
(self)
|
return self.operate(any_op)
|
Produce a :func:`~.expression.any_` clause against the
parent object.
.. versionadded:: 1.1
|
Produce a :func:`~.expression.any_` clause against the
parent object.
|
[
"Produce",
"a",
":",
"func",
":",
"~",
".",
"expression",
".",
"any_",
"clause",
"against",
"the",
"parent",
"object",
"."
] |
def any_(self):
"""Produce a :func:`~.expression.any_` clause against the
parent object.
.. versionadded:: 1.1
"""
return self.operate(any_op)
|
[
"def",
"any_",
"(",
"self",
")",
":",
"return",
"self",
".",
"operate",
"(",
"any_op",
")"
] |
https://github.com/HymanLiuTS/flaskTs/blob/286648286976e85d9b9a5873632331efcafe0b21/flasky/lib/python2.7/site-packages/sqlalchemy/sql/operators.py#L650-L657
|
|
adamrehn/ue4cli
|
25e3f31830494141bb3bdb11a8d52d5c8d8d64ef
|
ue4cli/UnrealManagerWindows.py
|
python
|
UnrealManagerWindows._detectEngineRoot
|
(self)
|
[] |
def _detectEngineRoot(self):
# Under Windows, the default installation path is `%PROGRAMFILES%\Epic Games`
baseDir = os.environ['PROGRAMFILES'] + '\\Epic Games\\'
prefix = 'UE_4.'
versionDirs = glob.glob(baseDir + prefix + '*')
if len(versionDirs) > 0:
installedVersions = sorted([int(os.path.basename(d).replace(prefix, '')) for d in versionDirs])
newestVersion = max(installedVersions)
return baseDir + prefix + str(newestVersion)
# Could not auto-detect the Unreal Engine location
raise UnrealManagerException('could not detect the location of the latest installed Unreal Engine 4 version')
|
[
"def",
"_detectEngineRoot",
"(",
"self",
")",
":",
"# Under Windows, the default installation path is `%PROGRAMFILES%\\Epic Games`",
"baseDir",
"=",
"os",
".",
"environ",
"[",
"'PROGRAMFILES'",
"]",
"+",
"'\\\\Epic Games\\\\'",
"prefix",
"=",
"'UE_4.'",
"versionDirs",
"=",
"glob",
".",
"glob",
"(",
"baseDir",
"+",
"prefix",
"+",
"'*'",
")",
"if",
"len",
"(",
"versionDirs",
")",
">",
"0",
":",
"installedVersions",
"=",
"sorted",
"(",
"[",
"int",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"d",
")",
".",
"replace",
"(",
"prefix",
",",
"''",
")",
")",
"for",
"d",
"in",
"versionDirs",
"]",
")",
"newestVersion",
"=",
"max",
"(",
"installedVersions",
")",
"return",
"baseDir",
"+",
"prefix",
"+",
"str",
"(",
"newestVersion",
")",
"# Could not auto-detect the Unreal Engine location",
"raise",
"UnrealManagerException",
"(",
"'could not detect the location of the latest installed Unreal Engine 4 version'",
")"
] |
https://github.com/adamrehn/ue4cli/blob/25e3f31830494141bb3bdb11a8d52d5c8d8d64ef/ue4cli/UnrealManagerWindows.py#L61-L73
|
||||
cloudera/hue
|
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
|
desktop/core/ext-py/Django-1.11.29/django/contrib/staticfiles/finders.py
|
python
|
AppDirectoriesFinder.list
|
(self, ignore_patterns)
|
List all files in all app storages.
|
List all files in all app storages.
|
[
"List",
"all",
"files",
"in",
"all",
"app",
"storages",
"."
] |
def list(self, ignore_patterns):
"""
List all files in all app storages.
"""
for storage in six.itervalues(self.storages):
if storage.exists(''): # check if storage location exists
for path in utils.get_files(storage, ignore_patterns):
yield path, storage
|
[
"def",
"list",
"(",
"self",
",",
"ignore_patterns",
")",
":",
"for",
"storage",
"in",
"six",
".",
"itervalues",
"(",
"self",
".",
"storages",
")",
":",
"if",
"storage",
".",
"exists",
"(",
"''",
")",
":",
"# check if storage location exists",
"for",
"path",
"in",
"utils",
".",
"get_files",
"(",
"storage",
",",
"ignore_patterns",
")",
":",
"yield",
"path",
",",
"storage"
] |
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/Django-1.11.29/django/contrib/staticfiles/finders.py#L142-L149
|
||
esrlabs/git-repo
|
09f5180b06edb337b95c03af6a1f770646703a5d
|
manifest_xml.py
|
python
|
XmlManifest._reqatt
|
(self, node, attname)
|
return v
|
reads a required attribute from the node.
|
reads a required attribute from the node.
|
[
"reads",
"a",
"required",
"attribute",
"from",
"the",
"node",
"."
] |
def _reqatt(self, node, attname):
"""
reads a required attribute from the node.
"""
v = node.getAttribute(attname)
if not v:
raise ManifestParseError("no %s in <%s> within %s" %
(attname, node.nodeName, self.manifestFile))
return v
|
[
"def",
"_reqatt",
"(",
"self",
",",
"node",
",",
"attname",
")",
":",
"v",
"=",
"node",
".",
"getAttribute",
"(",
"attname",
")",
"if",
"not",
"v",
":",
"raise",
"ManifestParseError",
"(",
"\"no %s in <%s> within %s\"",
"%",
"(",
"attname",
",",
"node",
".",
"nodeName",
",",
"self",
".",
"manifestFile",
")",
")",
"return",
"v"
] |
https://github.com/esrlabs/git-repo/blob/09f5180b06edb337b95c03af6a1f770646703a5d/manifest_xml.py#L920-L928
|
|
fortharris/Pcode
|
147962d160a834c219e12cb456abc130826468e4
|
Extensions/ViewSwitcher.py
|
python
|
ViewSwitcher.addButton
|
(self, icon, toolTip)
|
[] |
def addButton(self, icon, toolTip):
button = QtGui.QToolButton()
button.setToolTip(toolTip)
button.setCheckable(True)
button.setIcon(icon)
self.buttonGroup.addButton(button)
self.buttonGroup.setId(button, self.lastIndex)
self.mainLayout.addWidget(button)
self.lastIndex += 1
|
[
"def",
"addButton",
"(",
"self",
",",
"icon",
",",
"toolTip",
")",
":",
"button",
"=",
"QtGui",
".",
"QToolButton",
"(",
")",
"button",
".",
"setToolTip",
"(",
"toolTip",
")",
"button",
".",
"setCheckable",
"(",
"True",
")",
"button",
".",
"setIcon",
"(",
"icon",
")",
"self",
".",
"buttonGroup",
".",
"addButton",
"(",
"button",
")",
"self",
".",
"buttonGroup",
".",
"setId",
"(",
"button",
",",
"self",
".",
"lastIndex",
")",
"self",
".",
"mainLayout",
".",
"addWidget",
"(",
"button",
")",
"self",
".",
"lastIndex",
"+=",
"1"
] |
https://github.com/fortharris/Pcode/blob/147962d160a834c219e12cb456abc130826468e4/Extensions/ViewSwitcher.py#L62-L71
|
||||
PyCQA/pylint-django
|
f43c8bd34eec327befa496b8336738cb9baefb42
|
pylint_django/augmentations/__init__.py
|
python
|
is_slugfield_attribute
|
(node)
|
return _attribute_is_magic(node, SLUG_FIELD_ATTRS, parents)
|
Checks that node is attribute of SlugField.
|
Checks that node is attribute of SlugField.
|
[
"Checks",
"that",
"node",
"is",
"attribute",
"of",
"SlugField",
"."
] |
def is_slugfield_attribute(node):
"""Checks that node is attribute of SlugField."""
parents = ("django.db.models.fields.SlugField", ".SlugField")
return _attribute_is_magic(node, SLUG_FIELD_ATTRS, parents)
|
[
"def",
"is_slugfield_attribute",
"(",
"node",
")",
":",
"parents",
"=",
"(",
"\"django.db.models.fields.SlugField\"",
",",
"\".SlugField\"",
")",
"return",
"_attribute_is_magic",
"(",
"node",
",",
"SLUG_FIELD_ATTRS",
",",
"parents",
")"
] |
https://github.com/PyCQA/pylint-django/blob/f43c8bd34eec327befa496b8336738cb9baefb42/pylint_django/augmentations/__init__.py#L610-L613
|
|
aws/sagemaker-python-sdk
|
9d259b316f7f43838c16f35c10e98a110b56735b
|
src/sagemaker/transformer.py
|
python
|
Transformer._retrieve_image_uri
|
(self)
|
Placeholder docstring
|
Placeholder docstring
|
[
"Placeholder",
"docstring"
] |
def _retrieve_image_uri(self):
"""Placeholder docstring"""
try:
model_desc = self.sagemaker_session.sagemaker_client.describe_model(
ModelName=self.model_name
)
primary_container = model_desc.get("PrimaryContainer")
if primary_container:
return primary_container.get("Image")
containers = model_desc.get("Containers")
if containers:
return containers[0].get("Image")
return None
except exceptions.ClientError:
raise ValueError(
"Failed to fetch model information for %s. "
"Please ensure that the model exists. "
"Local instance types require locally created models." % self.model_name
)
|
[
"def",
"_retrieve_image_uri",
"(",
"self",
")",
":",
"try",
":",
"model_desc",
"=",
"self",
".",
"sagemaker_session",
".",
"sagemaker_client",
".",
"describe_model",
"(",
"ModelName",
"=",
"self",
".",
"model_name",
")",
"primary_container",
"=",
"model_desc",
".",
"get",
"(",
"\"PrimaryContainer\"",
")",
"if",
"primary_container",
":",
"return",
"primary_container",
".",
"get",
"(",
"\"Image\"",
")",
"containers",
"=",
"model_desc",
".",
"get",
"(",
"\"Containers\"",
")",
"if",
"containers",
":",
"return",
"containers",
"[",
"0",
"]",
".",
"get",
"(",
"\"Image\"",
")",
"return",
"None",
"except",
"exceptions",
".",
"ClientError",
":",
"raise",
"ValueError",
"(",
"\"Failed to fetch model information for %s. \"",
"\"Please ensure that the model exists. \"",
"\"Local instance types require locally created models.\"",
"%",
"self",
".",
"model_name",
")"
] |
https://github.com/aws/sagemaker-python-sdk/blob/9d259b316f7f43838c16f35c10e98a110b56735b/src/sagemaker/transformer.py#L240-L262
|
||
tp4a/teleport
|
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
|
server/www/packages/packages-darwin/x64/PIL/TiffImagePlugin.py
|
python
|
TiffImageFile._decoder
|
(self, rawmode, layer, tile=None)
|
return args
|
Setup decoder contexts
|
Setup decoder contexts
|
[
"Setup",
"decoder",
"contexts"
] |
def _decoder(self, rawmode, layer, tile=None):
"Setup decoder contexts"
args = None
if rawmode == "RGB" and self._planar_configuration == 2:
rawmode = rawmode[layer]
compression = self._compression
if compression == "raw":
args = (rawmode, 0, 1)
elif compression == "packbits":
args = rawmode
return args
|
[
"def",
"_decoder",
"(",
"self",
",",
"rawmode",
",",
"layer",
",",
"tile",
"=",
"None",
")",
":",
"args",
"=",
"None",
"if",
"rawmode",
"==",
"\"RGB\"",
"and",
"self",
".",
"_planar_configuration",
"==",
"2",
":",
"rawmode",
"=",
"rawmode",
"[",
"layer",
"]",
"compression",
"=",
"self",
".",
"_compression",
"if",
"compression",
"==",
"\"raw\"",
":",
"args",
"=",
"(",
"rawmode",
",",
"0",
",",
"1",
")",
"elif",
"compression",
"==",
"\"packbits\"",
":",
"args",
"=",
"rawmode",
"return",
"args"
] |
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-darwin/x64/PIL/TiffImagePlugin.py#L1045-L1057
|
|
wwqgtxx/wwqLyParse
|
33136508e52821babd9294fdecffbdf02d73a6fc
|
wwqLyParse/lib/python-3.7.2-embed-amd64/Crypto/Util/asn1.py
|
python
|
DerBitString._decodeFromStream
|
(self, s, strict)
|
Decode a complete DER BIT STRING DER from a file.
|
Decode a complete DER BIT STRING DER from a file.
|
[
"Decode",
"a",
"complete",
"DER",
"BIT",
"STRING",
"DER",
"from",
"a",
"file",
"."
] |
def _decodeFromStream(self, s, strict):
"""Decode a complete DER BIT STRING DER from a file."""
# Fill-up self.payload
DerObject._decodeFromStream(self, s, strict)
if self.payload and bord(self.payload[0]) != 0:
raise ValueError("Not a valid BIT STRING")
# Fill-up self.value
self.value = b('')
# Remove padding count byte
if self.payload:
self.value = self.payload[1:]
|
[
"def",
"_decodeFromStream",
"(",
"self",
",",
"s",
",",
"strict",
")",
":",
"# Fill-up self.payload",
"DerObject",
".",
"_decodeFromStream",
"(",
"self",
",",
"s",
",",
"strict",
")",
"if",
"self",
".",
"payload",
"and",
"bord",
"(",
"self",
".",
"payload",
"[",
"0",
"]",
")",
"!=",
"0",
":",
"raise",
"ValueError",
"(",
"\"Not a valid BIT STRING\"",
")",
"# Fill-up self.value",
"self",
".",
"value",
"=",
"b",
"(",
"''",
")",
"# Remove padding count byte",
"if",
"self",
".",
"payload",
":",
"self",
".",
"value",
"=",
"self",
".",
"payload",
"[",
"1",
":",
"]"
] |
https://github.com/wwqgtxx/wwqLyParse/blob/33136508e52821babd9294fdecffbdf02d73a6fc/wwqLyParse/lib/python-3.7.2-embed-amd64/Crypto/Util/asn1.py#L766-L779
|
||
junyanz/BicycleGAN
|
40b9d52c27b9831f56c1c7c7a6ddde8bc9149067
|
models/base_model.py
|
python
|
BaseModel.save_networks
|
(self, epoch)
|
Save all the networks to the disk.
Parameters:
epoch (int) -- current epoch; used in the file name '%s_net_%s.pth' % (epoch, name)
|
Save all the networks to the disk.
|
[
"Save",
"all",
"the",
"networks",
"to",
"the",
"disk",
"."
] |
def save_networks(self, epoch):
"""Save all the networks to the disk.
Parameters:
epoch (int) -- current epoch; used in the file name '%s_net_%s.pth' % (epoch, name)
"""
for name in self.model_names:
if isinstance(name, str):
save_filename = '%s_net_%s.pth' % (epoch, name)
save_path = os.path.join(self.save_dir, save_filename)
net = getattr(self, 'net' + name)
if len(self.gpu_ids) > 0 and torch.cuda.is_available():
torch.save(net.module.cpu().state_dict(), save_path)
net.cuda(self.gpu_ids[0])
else:
torch.save(net.cpu().state_dict(), save_path)
|
[
"def",
"save_networks",
"(",
"self",
",",
"epoch",
")",
":",
"for",
"name",
"in",
"self",
".",
"model_names",
":",
"if",
"isinstance",
"(",
"name",
",",
"str",
")",
":",
"save_filename",
"=",
"'%s_net_%s.pth'",
"%",
"(",
"epoch",
",",
"name",
")",
"save_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"save_dir",
",",
"save_filename",
")",
"net",
"=",
"getattr",
"(",
"self",
",",
"'net'",
"+",
"name",
")",
"if",
"len",
"(",
"self",
".",
"gpu_ids",
")",
">",
"0",
"and",
"torch",
".",
"cuda",
".",
"is_available",
"(",
")",
":",
"torch",
".",
"save",
"(",
"net",
".",
"module",
".",
"cpu",
"(",
")",
".",
"state_dict",
"(",
")",
",",
"save_path",
")",
"net",
".",
"cuda",
"(",
"self",
".",
"gpu_ids",
"[",
"0",
"]",
")",
"else",
":",
"torch",
".",
"save",
"(",
"net",
".",
"cpu",
"(",
")",
".",
"state_dict",
"(",
")",
",",
"save_path",
")"
] |
https://github.com/junyanz/BicycleGAN/blob/40b9d52c27b9831f56c1c7c7a6ddde8bc9149067/models/base_model.py#L141-L157
|
||
JaniceWuo/MovieRecommend
|
4c86db64ca45598917d304f535413df3bc9fea65
|
movierecommend/venv1/Lib/site-packages/django/contrib/admin/filters.py
|
python
|
RelatedOnlyFieldListFilter.field_choices
|
(self, field, request, model_admin)
|
return field.get_choices(include_blank=False, limit_choices_to={'pk__in': pk_qs})
|
[] |
def field_choices(self, field, request, model_admin):
pk_qs = model_admin.get_queryset(request).distinct().values_list('%s__pk' % self.field_path, flat=True)
return field.get_choices(include_blank=False, limit_choices_to={'pk__in': pk_qs})
|
[
"def",
"field_choices",
"(",
"self",
",",
"field",
",",
"request",
",",
"model_admin",
")",
":",
"pk_qs",
"=",
"model_admin",
".",
"get_queryset",
"(",
"request",
")",
".",
"distinct",
"(",
")",
".",
"values_list",
"(",
"'%s__pk'",
"%",
"self",
".",
"field_path",
",",
"flat",
"=",
"True",
")",
"return",
"field",
".",
"get_choices",
"(",
"include_blank",
"=",
"False",
",",
"limit_choices_to",
"=",
"{",
"'pk__in'",
":",
"pk_qs",
"}",
")"
] |
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/django/contrib/admin/filters.py#L448-L450
|
|||
tomplus/kubernetes_asyncio
|
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
|
kubernetes_asyncio/client/models/v1beta1_id_range.py
|
python
|
V1beta1IDRange.__ne__
|
(self, other)
|
return self.to_dict() != other.to_dict()
|
Returns true if both objects are not equal
|
Returns true if both objects are not equal
|
[
"Returns",
"true",
"if",
"both",
"objects",
"are",
"not",
"equal"
] |
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1beta1IDRange):
return True
return self.to_dict() != other.to_dict()
|
[
"def",
"__ne__",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"V1beta1IDRange",
")",
":",
"return",
"True",
"return",
"self",
".",
"to_dict",
"(",
")",
"!=",
"other",
".",
"to_dict",
"(",
")"
] |
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1beta1_id_range.py#L147-L152
|
|
PrefectHQ/prefect
|
67bdc94e2211726d99561f6f52614bec8970e981
|
src/prefect/engine/results/local_result.py
|
python
|
LocalResult.write
|
(self, value_: Any, **kwargs: Any)
|
return new
|
Writes the result to a location in the local file system and returns a new `Result`
object with the result's location.
Args:
- value_ (Any): the value to write; will then be stored as the `value` attribute
of the returned `Result` instance
- **kwargs (optional): if provided, will be used to format the location template
to determine the location to write to
Returns:
- Result: returns a new `Result` with both `value` and `location` attributes
|
Writes the result to a location in the local file system and returns a new `Result`
object with the result's location.
|
[
"Writes",
"the",
"result",
"to",
"a",
"location",
"in",
"the",
"local",
"file",
"system",
"and",
"returns",
"a",
"new",
"Result",
"object",
"with",
"the",
"result",
"s",
"location",
"."
] |
def write(self, value_: Any, **kwargs: Any) -> Result:
"""
Writes the result to a location in the local file system and returns a new `Result`
object with the result's location.
Args:
- value_ (Any): the value to write; will then be stored as the `value` attribute
of the returned `Result` instance
- **kwargs (optional): if provided, will be used to format the location template
to determine the location to write to
Returns:
- Result: returns a new `Result` with both `value` and `location` attributes
"""
new = self.format(**kwargs)
new.value = value_
assert new.location is not None
self.logger.debug("Starting to upload result to {}...".format(new.location))
full_path = os.path.join(self.dir, new.location)
os.makedirs(os.path.dirname(full_path), exist_ok=True)
value = self.serializer.serialize(new.value)
with open(full_path, "wb") as f:
f.write(value)
new.location = full_path
self.logger.debug("Finished uploading result to {}...".format(new.location))
return new
|
[
"def",
"write",
"(",
"self",
",",
"value_",
":",
"Any",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"Result",
":",
"new",
"=",
"self",
".",
"format",
"(",
"*",
"*",
"kwargs",
")",
"new",
".",
"value",
"=",
"value_",
"assert",
"new",
".",
"location",
"is",
"not",
"None",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Starting to upload result to {}...\"",
".",
"format",
"(",
"new",
".",
"location",
")",
")",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"dir",
",",
"new",
".",
"location",
")",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"full_path",
")",
",",
"exist_ok",
"=",
"True",
")",
"value",
"=",
"self",
".",
"serializer",
".",
"serialize",
"(",
"new",
".",
"value",
")",
"with",
"open",
"(",
"full_path",
",",
"\"wb\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"value",
")",
"new",
".",
"location",
"=",
"full_path",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Finished uploading result to {}...\"",
".",
"format",
"(",
"new",
".",
"location",
")",
")",
"return",
"new"
] |
https://github.com/PrefectHQ/prefect/blob/67bdc94e2211726d99561f6f52614bec8970e981/src/prefect/engine/results/local_result.py#L92-L123
|
|
dbr/tvnamer
|
2e1e969542d65c5cac2dad9b3cd20dce4f53b6a8
|
tvnamer/main.py
|
python
|
find_files
|
(paths)
|
return valid_files
|
Takes an array of paths, returns all files found
|
Takes an array of paths, returns all files found
|
[
"Takes",
"an",
"array",
"of",
"paths",
"returns",
"all",
"files",
"found"
] |
def find_files(paths):
# type: (List[str]) -> List[str]
"""Takes an array of paths, returns all files found
"""
valid_files = []
for cfile in paths:
cur = FileFinder(
cfile,
with_extension=Config["valid_extensions"],
filename_blacklist=Config["filename_blacklist"],
recursive=Config["recursive"],
)
try:
valid_files.extend(cur.find_files())
except InvalidPath:
warn("Invalid path: %s" % cfile)
if len(valid_files) == 0:
raise NoValidFilesFoundError()
# Remove duplicate files (all paths from FileFinder are absolute)
valid_files = list(set(valid_files))
return valid_files
|
[
"def",
"find_files",
"(",
"paths",
")",
":",
"# type: (List[str]) -> List[str]",
"valid_files",
"=",
"[",
"]",
"for",
"cfile",
"in",
"paths",
":",
"cur",
"=",
"FileFinder",
"(",
"cfile",
",",
"with_extension",
"=",
"Config",
"[",
"\"valid_extensions\"",
"]",
",",
"filename_blacklist",
"=",
"Config",
"[",
"\"filename_blacklist\"",
"]",
",",
"recursive",
"=",
"Config",
"[",
"\"recursive\"",
"]",
",",
")",
"try",
":",
"valid_files",
".",
"extend",
"(",
"cur",
".",
"find_files",
"(",
")",
")",
"except",
"InvalidPath",
":",
"warn",
"(",
"\"Invalid path: %s\"",
"%",
"cfile",
")",
"if",
"len",
"(",
"valid_files",
")",
"==",
"0",
":",
"raise",
"NoValidFilesFoundError",
"(",
")",
"# Remove duplicate files (all paths from FileFinder are absolute)",
"valid_files",
"=",
"list",
"(",
"set",
"(",
"valid_files",
")",
")",
"return",
"valid_files"
] |
https://github.com/dbr/tvnamer/blob/2e1e969542d65c5cac2dad9b3cd20dce4f53b6a8/tvnamer/main.py#L330-L355
|
|
wzpan/dingdang-robot
|
66d95402232a9102e223a2d8ccefcb83500d2c6a
|
client/tts.py
|
python
|
AbstractMp3TTSEngine.is_available
|
(cls)
|
return (super(AbstractMp3TTSEngine, cls).is_available() and
diagnose.check_python_import('mad'))
|
[] |
def is_available(cls):
return (super(AbstractMp3TTSEngine, cls).is_available() and
diagnose.check_python_import('mad'))
|
[
"def",
"is_available",
"(",
"cls",
")",
":",
"return",
"(",
"super",
"(",
"AbstractMp3TTSEngine",
",",
"cls",
")",
".",
"is_available",
"(",
")",
"and",
"diagnose",
".",
"check_python_import",
"(",
"'mad'",
")",
")"
] |
https://github.com/wzpan/dingdang-robot/blob/66d95402232a9102e223a2d8ccefcb83500d2c6a/client/tts.py#L97-L99
|
|||
lisa-lab/pylearn2
|
af81e5c362f0df4df85c3e54e23b2adeec026055
|
pylearn2/energy_functions/rbm_energy.py
|
python
|
grbm_type_1
|
()
|
return GRBM_Type_1
|
.. todo::
WRITEME
|
.. todo::
|
[
"..",
"todo",
"::"
] |
def grbm_type_1():
"""
.. todo::
WRITEME
"""
return GRBM_Type_1
|
[
"def",
"grbm_type_1",
"(",
")",
":",
"return",
"GRBM_Type_1"
] |
https://github.com/lisa-lab/pylearn2/blob/af81e5c362f0df4df85c3e54e23b2adeec026055/pylearn2/energy_functions/rbm_energy.py#L231-L237
|
|
jgagneastro/coffeegrindsize
|
22661ebd21831dba4cf32bfc6ba59fe3d49f879c
|
App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/scipy/ndimage/measurements.py
|
python
|
sum
|
(input, labels=None, index=None)
|
return sum
|
Calculate the sum of the values of the array.
Parameters
----------
input : array_like
Values of `input` inside the regions defined by `labels`
are summed together.
labels : array_like of ints, optional
Assign labels to the values of the array. Has to have the same shape as
`input`.
index : array_like, optional
A single label number or a sequence of label numbers of
the objects to be measured.
Returns
-------
sum : ndarray or scalar
An array of the sums of values of `input` inside the regions defined
by `labels` with the same shape as `index`. If 'index' is None or scalar,
a scalar is returned.
See also
--------
mean, median
Examples
--------
>>> from scipy import ndimage
>>> input = [0,1,2,3]
>>> labels = [1,1,2,2]
>>> ndimage.sum(input, labels, index=[1,2])
[1.0, 5.0]
>>> ndimage.sum(input, labels, index=1)
1
>>> ndimage.sum(input, labels)
6
|
Calculate the sum of the values of the array.
|
[
"Calculate",
"the",
"sum",
"of",
"the",
"values",
"of",
"the",
"array",
"."
] |
def sum(input, labels=None, index=None):
"""
Calculate the sum of the values of the array.
Parameters
----------
input : array_like
Values of `input` inside the regions defined by `labels`
are summed together.
labels : array_like of ints, optional
Assign labels to the values of the array. Has to have the same shape as
`input`.
index : array_like, optional
A single label number or a sequence of label numbers of
the objects to be measured.
Returns
-------
sum : ndarray or scalar
An array of the sums of values of `input` inside the regions defined
by `labels` with the same shape as `index`. If 'index' is None or scalar,
a scalar is returned.
See also
--------
mean, median
Examples
--------
>>> from scipy import ndimage
>>> input = [0,1,2,3]
>>> labels = [1,1,2,2]
>>> ndimage.sum(input, labels, index=[1,2])
[1.0, 5.0]
>>> ndimage.sum(input, labels, index=1)
1
>>> ndimage.sum(input, labels)
6
"""
count, sum = _stats(input, labels, index)
return sum
|
[
"def",
"sum",
"(",
"input",
",",
"labels",
"=",
"None",
",",
"index",
"=",
"None",
")",
":",
"count",
",",
"sum",
"=",
"_stats",
"(",
"input",
",",
"labels",
",",
"index",
")",
"return",
"sum"
] |
https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/scipy/ndimage/measurements.py#L576-L618
|
|
CalebBell/thermo
|
572a47d1b03d49fe609b8d5f826fa6a7cde00828
|
thermo/vapor_pressure.py
|
python
|
VaporPressure.__init__
|
(self, Tb=None, Tc=None, Pc=None, omega=None, CASRN='',
eos=None, extrapolation='AntoineAB|DIPPR101_ABC', **kwargs)
|
[] |
def __init__(self, Tb=None, Tc=None, Pc=None, omega=None, CASRN='',
eos=None, extrapolation='AntoineAB|DIPPR101_ABC', **kwargs):
self.CASRN = CASRN
self.Tb = Tb
self.Tc = Tc
self.Pc = Pc
self.omega = omega
self.eos = eos
super(VaporPressure, self).__init__(extrapolation, **kwargs)
|
[
"def",
"__init__",
"(",
"self",
",",
"Tb",
"=",
"None",
",",
"Tc",
"=",
"None",
",",
"Pc",
"=",
"None",
",",
"omega",
"=",
"None",
",",
"CASRN",
"=",
"''",
",",
"eos",
"=",
"None",
",",
"extrapolation",
"=",
"'AntoineAB|DIPPR101_ABC'",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"CASRN",
"=",
"CASRN",
"self",
".",
"Tb",
"=",
"Tb",
"self",
".",
"Tc",
"=",
"Tc",
"self",
".",
"Pc",
"=",
"Pc",
"self",
".",
"omega",
"=",
"omega",
"self",
".",
"eos",
"=",
"eos",
"super",
"(",
"VaporPressure",
",",
"self",
")",
".",
"__init__",
"(",
"extrapolation",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/CalebBell/thermo/blob/572a47d1b03d49fe609b8d5f826fa6a7cde00828/thermo/vapor_pressure.py#L260-L268
|
||||
hyperledger/fabric-sdk-py
|
8ee33a8981887e37950dc0f36a7ec63b3a5ba5c3
|
hfc/fabric_network/wallet.py
|
python
|
FileSystenWallet.create_user
|
(self, enrollment_id, org, msp_id, state_store=None)
|
return user
|
Returns an instance of a user whose identity
is stored in the FileSystemWallet
:param enrollment_id: enrollment id
:param org: organization
:param msp_id: MSP id
:param state_store: state store (Default value = None)
:return: a user instance
|
Returns an instance of a user whose identity
is stored in the FileSystemWallet
|
[
"Returns",
"an",
"instance",
"of",
"a",
"user",
"whose",
"identity",
"is",
"stored",
"in",
"the",
"FileSystemWallet"
] |
def create_user(self, enrollment_id, org, msp_id, state_store=None):
"""Returns an instance of a user whose identity
is stored in the FileSystemWallet
:param enrollment_id: enrollment id
:param org: organization
:param msp_id: MSP id
:param state_store: state store (Default value = None)
:return: a user instance
"""
if not self.exists(enrollment_id):
raise AttributeError('"user" does not exist')
state_store = FileKeyValueStore(self._path)
key_path = self._path + '/' + enrollment_id + '/' + 'private_sk'
cert_path = self._path + '/' + enrollment_id + '/' + 'enrollmentCert.pem'
user = create_user(enrollment_id, org, state_store, msp_id, key_path, cert_path)
return user
|
[
"def",
"create_user",
"(",
"self",
",",
"enrollment_id",
",",
"org",
",",
"msp_id",
",",
"state_store",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"exists",
"(",
"enrollment_id",
")",
":",
"raise",
"AttributeError",
"(",
"'\"user\" does not exist'",
")",
"state_store",
"=",
"FileKeyValueStore",
"(",
"self",
".",
"_path",
")",
"key_path",
"=",
"self",
".",
"_path",
"+",
"'/'",
"+",
"enrollment_id",
"+",
"'/'",
"+",
"'private_sk'",
"cert_path",
"=",
"self",
".",
"_path",
"+",
"'/'",
"+",
"enrollment_id",
"+",
"'/'",
"+",
"'enrollmentCert.pem'",
"user",
"=",
"create_user",
"(",
"enrollment_id",
",",
"org",
",",
"state_store",
",",
"msp_id",
",",
"key_path",
",",
"cert_path",
")",
"return",
"user"
] |
https://github.com/hyperledger/fabric-sdk-py/blob/8ee33a8981887e37950dc0f36a7ec63b3a5ba5c3/hfc/fabric_network/wallet.py#L41-L57
|
|
Qiskit/qiskit-terra
|
b66030e3b9192efdd3eb95cf25c6545fe0a13da4
|
qiskit/providers/models/backendconfiguration.py
|
python
|
PulseBackendConfiguration.drive
|
(self, qubit: int)
|
return DriveChannel(qubit)
|
Return the drive channel for the given qubit.
Raises:
BackendConfigurationError: If the qubit is not a part of the system.
Returns:
Qubit drive channel.
|
Return the drive channel for the given qubit.
|
[
"Return",
"the",
"drive",
"channel",
"for",
"the",
"given",
"qubit",
"."
] |
def drive(self, qubit: int) -> DriveChannel:
"""
Return the drive channel for the given qubit.
Raises:
BackendConfigurationError: If the qubit is not a part of the system.
Returns:
Qubit drive channel.
"""
if not 0 <= qubit < self.n_qubits:
raise BackendConfigurationError(f"Invalid index for {qubit}-qubit system.")
return DriveChannel(qubit)
|
[
"def",
"drive",
"(",
"self",
",",
"qubit",
":",
"int",
")",
"->",
"DriveChannel",
":",
"if",
"not",
"0",
"<=",
"qubit",
"<",
"self",
".",
"n_qubits",
":",
"raise",
"BackendConfigurationError",
"(",
"f\"Invalid index for {qubit}-qubit system.\"",
")",
"return",
"DriveChannel",
"(",
"qubit",
")"
] |
https://github.com/Qiskit/qiskit-terra/blob/b66030e3b9192efdd3eb95cf25c6545fe0a13da4/qiskit/providers/models/backendconfiguration.py#L794-L806
|
|
leo-editor/leo-editor
|
383d6776d135ef17d73d935a2f0ecb3ac0e99494
|
leo/plugins/cursesGui2.py
|
python
|
TextMixin.insert
|
(self, i, s)
|
return i
|
TextMixin
|
TextMixin
|
[
"TextMixin"
] |
def insert(self, i, s):
"""TextMixin"""
s2 = self.getAllText()
i = self.toPythonIndex(i)
self.setAllText(s2[:i] + s + s2[i:])
self.setInsertPoint(i + len(s))
return i
|
[
"def",
"insert",
"(",
"self",
",",
"i",
",",
"s",
")",
":",
"s2",
"=",
"self",
".",
"getAllText",
"(",
")",
"i",
"=",
"self",
".",
"toPythonIndex",
"(",
"i",
")",
"self",
".",
"setAllText",
"(",
"s2",
"[",
":",
"i",
"]",
"+",
"s",
"+",
"s2",
"[",
"i",
":",
"]",
")",
"self",
".",
"setInsertPoint",
"(",
"i",
"+",
"len",
"(",
"s",
")",
")",
"return",
"i"
] |
https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/plugins/cursesGui2.py#L4109-L4115
|
|
mrJean1/PyGeodesy
|
7da5ca71aa3edb7bc49e219e0b8190686e1a7965
|
pygeodesy/elliptic.py
|
python
|
Elliptic.eps
|
(self)
|
return self._eps
|
Get epsilon (C{float}).
|
Get epsilon (C{float}).
|
[
"Get",
"epsilon",
"(",
"C",
"{",
"float",
"}",
")",
"."
] |
def eps(self):
'''Get epsilon (C{float}).
'''
return self._eps
|
[
"def",
"eps",
"(",
"self",
")",
":",
"return",
"self",
".",
"_eps"
] |
https://github.com/mrJean1/PyGeodesy/blob/7da5ca71aa3edb7bc49e219e0b8190686e1a7965/pygeodesy/elliptic.py#L320-L323
|
|
tomplus/kubernetes_asyncio
|
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
|
kubernetes_asyncio/client/models/v1beta1_csi_driver_spec.py
|
python
|
V1beta1CSIDriverSpec.fs_group_policy
|
(self, fs_group_policy)
|
Sets the fs_group_policy of this V1beta1CSIDriverSpec.
Defines if the underlying volume supports changing ownership and permission of the volume before being mounted. Refer to the specific FSGroupPolicy values for additional details. This field is alpha-level, and is only honored by servers that enable the CSIVolumeFSGroupPolicy feature gate. # noqa: E501
:param fs_group_policy: The fs_group_policy of this V1beta1CSIDriverSpec. # noqa: E501
:type: str
|
Sets the fs_group_policy of this V1beta1CSIDriverSpec.
|
[
"Sets",
"the",
"fs_group_policy",
"of",
"this",
"V1beta1CSIDriverSpec",
"."
] |
def fs_group_policy(self, fs_group_policy):
"""Sets the fs_group_policy of this V1beta1CSIDriverSpec.
Defines if the underlying volume supports changing ownership and permission of the volume before being mounted. Refer to the specific FSGroupPolicy values for additional details. This field is alpha-level, and is only honored by servers that enable the CSIVolumeFSGroupPolicy feature gate. # noqa: E501
:param fs_group_policy: The fs_group_policy of this V1beta1CSIDriverSpec. # noqa: E501
:type: str
"""
self._fs_group_policy = fs_group_policy
|
[
"def",
"fs_group_policy",
"(",
"self",
",",
"fs_group_policy",
")",
":",
"self",
".",
"_fs_group_policy",
"=",
"fs_group_policy"
] |
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1beta1_csi_driver_spec.py#L110-L119
|
||
kamalgill/flask-appengine-template
|
11760f83faccbb0d0afe416fc58e67ecfb4643c2
|
src/lib/click/utils.py
|
python
|
LazyFile.__exit__
|
(self, exc_type, exc_value, tb)
|
[] |
def __exit__(self, exc_type, exc_value, tb):
self.close_intelligently()
|
[
"def",
"__exit__",
"(",
"self",
",",
"exc_type",
",",
"exc_value",
",",
"tb",
")",
":",
"self",
".",
"close_intelligently",
"(",
")"
] |
https://github.com/kamalgill/flask-appengine-template/blob/11760f83faccbb0d0afe416fc58e67ecfb4643c2/src/lib/click/utils.py#L137-L138
|
||||
getting-things-gnome/gtg
|
4b02c43744b32a00facb98174f04ec5953bd055d
|
GTG/gtk/browser/tag_context_menu.py
|
python
|
TagContextMenu.on_mi_del_activate
|
(self, widget)
|
delete a selected search
|
delete a selected search
|
[
"delete",
"a",
"selected",
"search"
] |
def on_mi_del_activate(self, widget):
""" delete a selected search """
self.req.remove_tag(self.tag.get_name())
|
[
"def",
"on_mi_del_activate",
"(",
"self",
",",
"widget",
")",
":",
"self",
".",
"req",
".",
"remove_tag",
"(",
"self",
".",
"tag",
".",
"get_name",
"(",
")",
")"
] |
https://github.com/getting-things-gnome/gtg/blob/4b02c43744b32a00facb98174f04ec5953bd055d/GTG/gtk/browser/tag_context_menu.py#L97-L99
|
||
cloudera/hue
|
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
|
desktop/core/ext-py/Django-1.11.29/django/db/models/sql/query.py
|
python
|
is_reverse_o2o
|
(field)
|
return field.is_relation and field.one_to_one and not field.concrete
|
A little helper to check if the given field is reverse-o2o. The field is
expected to be some sort of relation field or related object.
|
A little helper to check if the given field is reverse-o2o. The field is
expected to be some sort of relation field or related object.
|
[
"A",
"little",
"helper",
"to",
"check",
"if",
"the",
"given",
"field",
"is",
"reverse",
"-",
"o2o",
".",
"The",
"field",
"is",
"expected",
"to",
"be",
"some",
"sort",
"of",
"relation",
"field",
"or",
"related",
"object",
"."
] |
def is_reverse_o2o(field):
"""
A little helper to check if the given field is reverse-o2o. The field is
expected to be some sort of relation field or related object.
"""
return field.is_relation and field.one_to_one and not field.concrete
|
[
"def",
"is_reverse_o2o",
"(",
"field",
")",
":",
"return",
"field",
".",
"is_relation",
"and",
"field",
".",
"one_to_one",
"and",
"not",
"field",
".",
"concrete"
] |
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/Django-1.11.29/django/db/models/sql/query.py#L2055-L2060
|
|
saltstack/salt
|
fae5bc757ad0f1716483ce7ae180b451545c2058
|
salt/utils/openstack/nova.py
|
python
|
SaltNova.floating_ip_pool_list
|
(self)
|
return response
|
List all floating IP pools
.. versionadded:: 2016.3.0
|
List all floating IP pools
|
[
"List",
"all",
"floating",
"IP",
"pools"
] |
def floating_ip_pool_list(self):
"""
List all floating IP pools
.. versionadded:: 2016.3.0
"""
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
"name": pool.name,
}
return response
|
[
"def",
"floating_ip_pool_list",
"(",
"self",
")",
":",
"nt_ks",
"=",
"self",
".",
"compute_conn",
"pools",
"=",
"nt_ks",
".",
"floating_ip_pools",
".",
"list",
"(",
")",
"response",
"=",
"{",
"}",
"for",
"pool",
"in",
"pools",
":",
"response",
"[",
"pool",
".",
"name",
"]",
"=",
"{",
"\"name\"",
":",
"pool",
".",
"name",
",",
"}",
"return",
"response"
] |
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/utils/openstack/nova.py#L1208-L1221
|
|
Supervisor/supervisor
|
7de6215c9677d1418e7f0a72e7065c1fa69174d4
|
supervisor/rpcinterface.py
|
python
|
SupervisorNamespaceRPCInterface.getAllProcessInfo
|
(self)
|
return output
|
Get info about all processes
@return array result An array of process status results
|
Get info about all processes
|
[
"Get",
"info",
"about",
"all",
"processes"
] |
def getAllProcessInfo(self):
""" Get info about all processes
@return array result An array of process status results
"""
self._update('getAllProcessInfo')
all_processes = self._getAllProcesses(lexical=True)
output = []
for group, process in all_processes:
name = make_namespec(group.config.name, process.config.name)
output.append(self.getProcessInfo(name))
return output
|
[
"def",
"getAllProcessInfo",
"(",
"self",
")",
":",
"self",
".",
"_update",
"(",
"'getAllProcessInfo'",
")",
"all_processes",
"=",
"self",
".",
"_getAllProcesses",
"(",
"lexical",
"=",
"True",
")",
"output",
"=",
"[",
"]",
"for",
"group",
",",
"process",
"in",
"all_processes",
":",
"name",
"=",
"make_namespec",
"(",
"group",
".",
"config",
".",
"name",
",",
"process",
".",
"config",
".",
"name",
")",
"output",
".",
"append",
"(",
"self",
".",
"getProcessInfo",
"(",
"name",
")",
")",
"return",
"output"
] |
https://github.com/Supervisor/supervisor/blob/7de6215c9677d1418e7f0a72e7065c1fa69174d4/supervisor/rpcinterface.py#L685-L698
|
|
Nordeus/pushkin
|
39f7057d3eb82c811c5c6b795d8bc7df9352a217
|
pushkin/database/database.py
|
python
|
upsert_login
|
(login_id, language_id)
|
return login
|
Add or update a login entity. Returns new or updated login.
|
Add or update a login entity. Returns new or updated login.
|
[
"Add",
"or",
"update",
"a",
"login",
"entity",
".",
"Returns",
"new",
"or",
"updated",
"login",
"."
] |
def upsert_login(login_id, language_id):
'''
Add or update a login entity. Returns new or updated login.
'''
with session_scope() as session:
login = session.query(model.Login).filter(model.Login.id == login_id).one_or_none()
if login is not None:
login.language_id = language_id
else:
login = model.Login(id=login_id, language_id=language_id)
session.add(login)
session.commit()
session.refresh(login)
return login
|
[
"def",
"upsert_login",
"(",
"login_id",
",",
"language_id",
")",
":",
"with",
"session_scope",
"(",
")",
"as",
"session",
":",
"login",
"=",
"session",
".",
"query",
"(",
"model",
".",
"Login",
")",
".",
"filter",
"(",
"model",
".",
"Login",
".",
"id",
"==",
"login_id",
")",
".",
"one_or_none",
"(",
")",
"if",
"login",
"is",
"not",
"None",
":",
"login",
".",
"language_id",
"=",
"language_id",
"else",
":",
"login",
"=",
"model",
".",
"Login",
"(",
"id",
"=",
"login_id",
",",
"language_id",
"=",
"language_id",
")",
"session",
".",
"add",
"(",
"login",
")",
"session",
".",
"commit",
"(",
")",
"session",
".",
"refresh",
"(",
"login",
")",
"return",
"login"
] |
https://github.com/Nordeus/pushkin/blob/39f7057d3eb82c811c5c6b795d8bc7df9352a217/pushkin/database/database.py#L235-L248
|
|
pkumza/LibRadar
|
2fa3891123e5fd97d631fbe14bf029714c328ca3
|
LibRadar/dex_parser.py
|
python
|
DexProtoId.__init__
|
(self, )
|
[] |
def __init__(self, ):
super(DexProtoId, self).__init__()
self.shortyIdx = None
self.returnTypeIdx = None
self.parameterOff = None
self.dexTypeList = None
# Address index
self.offset = None
self.length = 0
|
[
"def",
"__init__",
"(",
"self",
",",
")",
":",
"super",
"(",
"DexProtoId",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"shortyIdx",
"=",
"None",
"self",
".",
"returnTypeIdx",
"=",
"None",
"self",
".",
"parameterOff",
"=",
"None",
"self",
".",
"dexTypeList",
"=",
"None",
"# Address index",
"self",
".",
"offset",
"=",
"None",
"self",
".",
"length",
"=",
"0"
] |
https://github.com/pkumza/LibRadar/blob/2fa3891123e5fd97d631fbe14bf029714c328ca3/LibRadar/dex_parser.py#L1943-L1952
|
||||
nilearn/nilearn
|
9edba4471747efacf21260bf470a346307f52706
|
nilearn/datasets/func.py
|
python
|
fetch_localizer_calculation_task
|
(n_subjects=1, data_dir=None, url=None,
verbose=1)
|
return data
|
Fetch calculation task contrast maps from the localizer.
Parameters
----------
n_subjects : int, optional
The number of subjects to load. If None is given,
all 94 subjects are used. Default=1.
%(data_dir)s
%(url)s
%(verbose)s
Returns
-------
data : Bunch
Dictionary-like object, the interest attributes are :
'cmaps': string list, giving paths to nifti contrast maps
Notes
------
This function is only a caller for the fetch_localizer_contrasts in order
to simplify examples reading and understanding.
The 'calculation (auditory and visual cue)' contrast is used.
See Also
---------
nilearn.datasets.fetch_localizer_button_task
nilearn.datasets.fetch_localizer_contrasts
|
Fetch calculation task contrast maps from the localizer.
|
[
"Fetch",
"calculation",
"task",
"contrast",
"maps",
"from",
"the",
"localizer",
"."
] |
def fetch_localizer_calculation_task(n_subjects=1, data_dir=None, url=None,
verbose=1):
"""Fetch calculation task contrast maps from the localizer.
Parameters
----------
n_subjects : int, optional
The number of subjects to load. If None is given,
all 94 subjects are used. Default=1.
%(data_dir)s
%(url)s
%(verbose)s
Returns
-------
data : Bunch
Dictionary-like object, the interest attributes are :
'cmaps': string list, giving paths to nifti contrast maps
Notes
------
This function is only a caller for the fetch_localizer_contrasts in order
to simplify examples reading and understanding.
The 'calculation (auditory and visual cue)' contrast is used.
See Also
---------
nilearn.datasets.fetch_localizer_button_task
nilearn.datasets.fetch_localizer_contrasts
"""
data = fetch_localizer_contrasts(["calculation (auditory and visual cue)"],
n_subjects=n_subjects,
get_tmaps=False, get_masks=False,
get_anats=False, data_dir=data_dir,
url=url, resume=True, verbose=verbose)
return data
|
[
"def",
"fetch_localizer_calculation_task",
"(",
"n_subjects",
"=",
"1",
",",
"data_dir",
"=",
"None",
",",
"url",
"=",
"None",
",",
"verbose",
"=",
"1",
")",
":",
"data",
"=",
"fetch_localizer_contrasts",
"(",
"[",
"\"calculation (auditory and visual cue)\"",
"]",
",",
"n_subjects",
"=",
"n_subjects",
",",
"get_tmaps",
"=",
"False",
",",
"get_masks",
"=",
"False",
",",
"get_anats",
"=",
"False",
",",
"data_dir",
"=",
"data_dir",
",",
"url",
"=",
"url",
",",
"resume",
"=",
"True",
",",
"verbose",
"=",
"verbose",
")",
"return",
"data"
] |
https://github.com/nilearn/nilearn/blob/9edba4471747efacf21260bf470a346307f52706/nilearn/datasets/func.py#L761-L797
|
|
ctxis/canape
|
5f0e03424577296bcc60c2008a60a98ec5307e4b
|
CANAPE.Scripting/Lib/imaplib.py
|
python
|
IMAP4_stream.shutdown
|
(self)
|
Close I/O established in "open".
|
Close I/O established in "open".
|
[
"Close",
"I",
"/",
"O",
"established",
"in",
"open",
"."
] |
def shutdown(self):
"""Close I/O established in "open"."""
self.readfile.close()
self.writefile.close()
self.process.wait()
|
[
"def",
"shutdown",
"(",
"self",
")",
":",
"self",
".",
"readfile",
".",
"close",
"(",
")",
"self",
".",
"writefile",
".",
"close",
"(",
")",
"self",
".",
"process",
".",
"wait",
"(",
")"
] |
https://github.com/ctxis/canape/blob/5f0e03424577296bcc60c2008a60a98ec5307e4b/CANAPE.Scripting/Lib/imaplib.py#L1258-L1262
|
||
lucadelu/pyModis
|
de86ccf28fffcb759d18b4b5b5a601304ec4fd14
|
pymodis/convertmodis.py
|
python
|
processModis.executable
|
(self)
|
Return the executable of resample MRT software
|
Return the executable of resample MRT software
|
[
"Return",
"the",
"executable",
"of",
"resample",
"MRT",
"software"
] |
def executable(self):
"""Return the executable of resample MRT software"""
if sys.platform.count('linux') != -1 or sys.platform.count('darwin') != -1:
if os.path.exists(os.path.join(self.mrtpathbin, 'swath2grid')):
return os.path.join(self.mrtpathbin, 'swath2grid')
elif sys.platform.count('win32') != -1:
if os.path.exists(os.path.join(self.mrtpathbin, 'swath2grid.exe')):
return os.path.join(self.mrtpathbin, 'swath2grid.exe')
|
[
"def",
"executable",
"(",
"self",
")",
":",
"if",
"sys",
".",
"platform",
".",
"count",
"(",
"'linux'",
")",
"!=",
"-",
"1",
"or",
"sys",
".",
"platform",
".",
"count",
"(",
"'darwin'",
")",
"!=",
"-",
"1",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"mrtpathbin",
",",
"'swath2grid'",
")",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"mrtpathbin",
",",
"'swath2grid'",
")",
"elif",
"sys",
".",
"platform",
".",
"count",
"(",
"'win32'",
")",
"!=",
"-",
"1",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"mrtpathbin",
",",
"'swath2grid.exe'",
")",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"mrtpathbin",
",",
"'swath2grid.exe'",
")"
] |
https://github.com/lucadelu/pyModis/blob/de86ccf28fffcb759d18b4b5b5a601304ec4fd14/pymodis/convertmodis.py#L226-L233
|
||
shuup/shuup
|
25f78cfe370109b9885b903e503faac295c7b7f2
|
shuup/notify/runner.py
|
python
|
run_event
|
(event, shop)
|
Run the event.
:param shuup.notify.Event event: the event.
:param shuup.Shop shop: the shop to run the event.
|
Run the event.
:param shuup.notify.Event event: the event.
:param shuup.Shop shop: the shop to run the event.
|
[
"Run",
"the",
"event",
".",
":",
"param",
"shuup",
".",
"notify",
".",
"Event",
"event",
":",
"the",
"event",
".",
":",
"param",
"shuup",
".",
"Shop",
"shop",
":",
"the",
"shop",
"to",
"run",
"the",
"event",
"."
] |
def run_event(event, shop):
"""Run the event.
:param shuup.notify.Event event: the event.
:param shuup.Shop shop: the shop to run the event.
"""
# TODO: Add possible asynchronous implementation.
for script in Script.objects.filter(event_identifier=event.identifier, enabled=True, shop=shop):
try:
script.execute(context=Context.from_event(event, shop))
except Exception: # pragma: no cover
if settings.DEBUG:
raise
LOG.exception("Error! Script %r failed for event %r." % (script, event))
|
[
"def",
"run_event",
"(",
"event",
",",
"shop",
")",
":",
"# TODO: Add possible asynchronous implementation.",
"for",
"script",
"in",
"Script",
".",
"objects",
".",
"filter",
"(",
"event_identifier",
"=",
"event",
".",
"identifier",
",",
"enabled",
"=",
"True",
",",
"shop",
"=",
"shop",
")",
":",
"try",
":",
"script",
".",
"execute",
"(",
"context",
"=",
"Context",
".",
"from_event",
"(",
"event",
",",
"shop",
")",
")",
"except",
"Exception",
":",
"# pragma: no cover",
"if",
"settings",
".",
"DEBUG",
":",
"raise",
"LOG",
".",
"exception",
"(",
"\"Error! Script %r failed for event %r.\"",
"%",
"(",
"script",
",",
"event",
")",
")"
] |
https://github.com/shuup/shuup/blob/25f78cfe370109b9885b903e503faac295c7b7f2/shuup/notify/runner.py#L19-L32
|
||
openedx/ecommerce
|
db6c774e239e5aa65e5a6151995073d364e8c896
|
ecommerce/extensions/refund/models.py
|
python
|
StatusMixin.available_statuses
|
(self)
|
return self.pipeline.get(self.status, ())
|
Returns all possible statuses that this object can move to.
|
Returns all possible statuses that this object can move to.
|
[
"Returns",
"all",
"possible",
"statuses",
"that",
"this",
"object",
"can",
"move",
"to",
"."
] |
def available_statuses(self):
"""Returns all possible statuses that this object can move to."""
return self.pipeline.get(self.status, ())
|
[
"def",
"available_statuses",
"(",
"self",
")",
":",
"return",
"self",
".",
"pipeline",
".",
"get",
"(",
"self",
".",
"status",
",",
"(",
")",
")"
] |
https://github.com/openedx/ecommerce/blob/db6c774e239e5aa65e5a6151995073d364e8c896/ecommerce/extensions/refund/models.py#L37-L39
|
|
DSE-MSU/DeepRobust
|
2bcde200a5969dae32cddece66206a52c87c43e8
|
deeprobust/image/netmodels/resnet.py
|
python
|
BasicBlock.__init__
|
(self, in_planes, planes, stride=1)
|
[] |
def __init__(self, in_planes, planes, stride=1):
super(BasicBlock, self).__init__()
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
self.shortcut = nn.Sequential()
if stride != 1 or in_planes != self.expansion*planes:
self.shortcut = nn.Sequential(
nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(self.expansion*planes)
)
|
[
"def",
"__init__",
"(",
"self",
",",
"in_planes",
",",
"planes",
",",
"stride",
"=",
"1",
")",
":",
"super",
"(",
"BasicBlock",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"conv1",
"=",
"nn",
".",
"Conv2d",
"(",
"in_planes",
",",
"planes",
",",
"kernel_size",
"=",
"3",
",",
"stride",
"=",
"stride",
",",
"padding",
"=",
"1",
",",
"bias",
"=",
"False",
")",
"self",
".",
"bn1",
"=",
"nn",
".",
"BatchNorm2d",
"(",
"planes",
")",
"self",
".",
"conv2",
"=",
"nn",
".",
"Conv2d",
"(",
"planes",
",",
"planes",
",",
"kernel_size",
"=",
"3",
",",
"stride",
"=",
"1",
",",
"padding",
"=",
"1",
",",
"bias",
"=",
"False",
")",
"self",
".",
"bn2",
"=",
"nn",
".",
"BatchNorm2d",
"(",
"planes",
")",
"self",
".",
"shortcut",
"=",
"nn",
".",
"Sequential",
"(",
")",
"if",
"stride",
"!=",
"1",
"or",
"in_planes",
"!=",
"self",
".",
"expansion",
"*",
"planes",
":",
"self",
".",
"shortcut",
"=",
"nn",
".",
"Sequential",
"(",
"nn",
".",
"Conv2d",
"(",
"in_planes",
",",
"self",
".",
"expansion",
"*",
"planes",
",",
"kernel_size",
"=",
"1",
",",
"stride",
"=",
"stride",
",",
"bias",
"=",
"False",
")",
",",
"nn",
".",
"BatchNorm2d",
"(",
"self",
".",
"expansion",
"*",
"planes",
")",
")"
] |
https://github.com/DSE-MSU/DeepRobust/blob/2bcde200a5969dae32cddece66206a52c87c43e8/deeprobust/image/netmodels/resnet.py#L22-L34
|
||||
movidius/ncappzoo
|
5d06afdbfce51b0627fab05d1941a30ecffee172
|
apps/mnist_calc/mnist_calc.py
|
python
|
TouchCalc._do_ncs_infer
|
(self, operand, img_label=None)
|
Detect and classify digits. If you provide an img_label the cropped digit image will be written to file.
|
Detect and classify digits. If you provide an img_label the cropped digit image will be written to file.
|
[
"Detect",
"and",
"classify",
"digits",
".",
"If",
"you",
"provide",
"an",
"img_label",
"the",
"cropped",
"digit",
"image",
"will",
"be",
"written",
"to",
"file",
"."
] |
def _do_ncs_infer(self, operand, img_label=None):
"""Detect and classify digits. If you provide an img_label the cropped digit image will be written to file."""
# Get a list of rectangles for objects detected in this operand's box
op_img = self._canvas[operand.top: operand.bottom, operand.left: operand.right]
gray_img = cv2.cvtColor(op_img, cv2.COLOR_BGR2GRAY)
_, binary_img = cv2.threshold(gray_img, 127, 255, cv2.THRESH_BINARY_INV)
contours, hierarchy = cv2.findContours(binary_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
digits = [cv2.boundingRect(contour) for contour in contours]
if len(digits) > 0:
x, y, w, h = digits[0]
digit_img = self._canvas[operand.top + y: operand.top + y + h,
operand.left + x: operand.left + x + w]
# Write the cropped image to file if a label was provided
if img_label:
cv2.imwrite(img_label + ".png", digit_img)
# Classify the digit and return the most probable result
value, probability = self._net_processor.do_async_inference(digit_img)[0]
print("value: " + str(value) + " probability: " + str(probability))
return value, probability
else:
return None, None
|
[
"def",
"_do_ncs_infer",
"(",
"self",
",",
"operand",
",",
"img_label",
"=",
"None",
")",
":",
"# Get a list of rectangles for objects detected in this operand's box",
"op_img",
"=",
"self",
".",
"_canvas",
"[",
"operand",
".",
"top",
":",
"operand",
".",
"bottom",
",",
"operand",
".",
"left",
":",
"operand",
".",
"right",
"]",
"gray_img",
"=",
"cv2",
".",
"cvtColor",
"(",
"op_img",
",",
"cv2",
".",
"COLOR_BGR2GRAY",
")",
"_",
",",
"binary_img",
"=",
"cv2",
".",
"threshold",
"(",
"gray_img",
",",
"127",
",",
"255",
",",
"cv2",
".",
"THRESH_BINARY_INV",
")",
"contours",
",",
"hierarchy",
"=",
"cv2",
".",
"findContours",
"(",
"binary_img",
",",
"cv2",
".",
"RETR_EXTERNAL",
",",
"cv2",
".",
"CHAIN_APPROX_SIMPLE",
")",
"digits",
"=",
"[",
"cv2",
".",
"boundingRect",
"(",
"contour",
")",
"for",
"contour",
"in",
"contours",
"]",
"if",
"len",
"(",
"digits",
")",
">",
"0",
":",
"x",
",",
"y",
",",
"w",
",",
"h",
"=",
"digits",
"[",
"0",
"]",
"digit_img",
"=",
"self",
".",
"_canvas",
"[",
"operand",
".",
"top",
"+",
"y",
":",
"operand",
".",
"top",
"+",
"y",
"+",
"h",
",",
"operand",
".",
"left",
"+",
"x",
":",
"operand",
".",
"left",
"+",
"x",
"+",
"w",
"]",
"# Write the cropped image to file if a label was provided",
"if",
"img_label",
":",
"cv2",
".",
"imwrite",
"(",
"img_label",
"+",
"\".png\"",
",",
"digit_img",
")",
"# Classify the digit and return the most probable result",
"value",
",",
"probability",
"=",
"self",
".",
"_net_processor",
".",
"do_async_inference",
"(",
"digit_img",
")",
"[",
"0",
"]",
"print",
"(",
"\"value: \"",
"+",
"str",
"(",
"value",
")",
"+",
"\" probability: \"",
"+",
"str",
"(",
"probability",
")",
")",
"return",
"value",
",",
"probability",
"else",
":",
"return",
"None",
",",
"None"
] |
https://github.com/movidius/ncappzoo/blob/5d06afdbfce51b0627fab05d1941a30ecffee172/apps/mnist_calc/mnist_calc.py#L197-L220
|
||
pysmt/pysmt
|
ade4dc2a825727615033a96d31c71e9f53ce4764
|
examples/smtlib.py
|
python
|
TSSmtLibParser._cmd_init
|
(self, current, tokens)
|
return SmtLibCommand(name="init", args=(expr,))
|
[] |
def _cmd_init(self, current, tokens):
# This cmd performs the parsing of:
# <expr> )
# and returns a new SmtLibCommand
expr = self.get_expression(tokens)
self.consume_closing(tokens, current)
return SmtLibCommand(name="init", args=(expr,))
|
[
"def",
"_cmd_init",
"(",
"self",
",",
"current",
",",
"tokens",
")",
":",
"# This cmd performs the parsing of:",
"# <expr> )",
"# and returns a new SmtLibCommand",
"expr",
"=",
"self",
".",
"get_expression",
"(",
"tokens",
")",
"self",
".",
"consume_closing",
"(",
"tokens",
",",
"current",
")",
"return",
"SmtLibCommand",
"(",
"name",
"=",
"\"init\"",
",",
"args",
"=",
"(",
"expr",
",",
")",
")"
] |
https://github.com/pysmt/pysmt/blob/ade4dc2a825727615033a96d31c71e9f53ce4764/examples/smtlib.py#L160-L166
|
|||
httpie/httpie
|
4c56d894ba9e2bb1c097a3a6067006843ac2944d
|
httpie/plugins/base.py
|
python
|
AuthPlugin.get_auth
|
(self, username: str = None, password: str = None)
|
If `auth_parse` is set to `True`, then `username`
and `password` contain the parsed credentials.
Use `self.raw_auth` to access the raw value passed through
`--auth, -a`.
Return a ``requests.auth.AuthBase`` subclass instance.
|
If `auth_parse` is set to `True`, then `username`
and `password` contain the parsed credentials.
|
[
"If",
"auth_parse",
"is",
"set",
"to",
"True",
"then",
"username",
"and",
"password",
"contain",
"the",
"parsed",
"credentials",
"."
] |
def get_auth(self, username: str = None, password: str = None):
"""
If `auth_parse` is set to `True`, then `username`
and `password` contain the parsed credentials.
Use `self.raw_auth` to access the raw value passed through
`--auth, -a`.
Return a ``requests.auth.AuthBase`` subclass instance.
"""
raise NotImplementedError()
|
[
"def",
"get_auth",
"(",
"self",
",",
"username",
":",
"str",
"=",
"None",
",",
"password",
":",
"str",
"=",
"None",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] |
https://github.com/httpie/httpie/blob/4c56d894ba9e2bb1c097a3a6067006843ac2944d/httpie/plugins/base.py#L58-L69
|
||
GoogleCloudPlatform/gsutil
|
5be882803e76608e2fd29cf8c504ccd1fe0a7746
|
gslib/command.py
|
python
|
_NotifyIfDone
|
(caller_id, num_done)
|
Notify any threads waiting for results that something has finished.
Each waiting thread will then need to check the call_completed_map to see if
its work is done.
Note that num_done could be calculated here, but it is passed in as an
optimization so that we have one less call to a globally-locked data
structure.
Args:
caller_id: The caller_id of the function whose progress we're checking.
num_done: The number of tasks currently completed for that caller_id.
|
Notify any threads waiting for results that something has finished.
|
[
"Notify",
"any",
"threads",
"waiting",
"for",
"results",
"that",
"something",
"has",
"finished",
"."
] |
def _NotifyIfDone(caller_id, num_done):
"""Notify any threads waiting for results that something has finished.
Each waiting thread will then need to check the call_completed_map to see if
its work is done.
Note that num_done could be calculated here, but it is passed in as an
optimization so that we have one less call to a globally-locked data
structure.
Args:
caller_id: The caller_id of the function whose progress we're checking.
num_done: The number of tasks currently completed for that caller_id.
"""
num_to_do = total_tasks[caller_id]
if num_to_do == num_done and num_to_do >= 0:
# Notify the Apply call that's sleeping that it's ready to return.
with need_pool_or_done_cond:
call_completed_map[caller_id] = True
need_pool_or_done_cond.notify_all()
|
[
"def",
"_NotifyIfDone",
"(",
"caller_id",
",",
"num_done",
")",
":",
"num_to_do",
"=",
"total_tasks",
"[",
"caller_id",
"]",
"if",
"num_to_do",
"==",
"num_done",
"and",
"num_to_do",
">=",
"0",
":",
"# Notify the Apply call that's sleeping that it's ready to return.",
"with",
"need_pool_or_done_cond",
":",
"call_completed_map",
"[",
"caller_id",
"]",
"=",
"True",
"need_pool_or_done_cond",
".",
"notify_all",
"(",
")"
] |
https://github.com/GoogleCloudPlatform/gsutil/blob/5be882803e76608e2fd29cf8c504ccd1fe0a7746/gslib/command.py#L2497-L2516
|
||
selfteaching/selfteaching-python-camp
|
9982ee964b984595e7d664b07c389cddaf158f1e
|
19100205/Ceasar1978/pip-19.0.3/src/pip/_internal/utils/misc.py
|
python
|
egg_link_path
|
(dist)
|
return None
|
Return the path for the .egg-link file if it exists, otherwise, None.
There's 3 scenarios:
1) not in a virtualenv
try to find in site.USER_SITE, then site_packages
2) in a no-global virtualenv
try to find in site_packages
3) in a yes-global virtualenv
try to find in site_packages, then site.USER_SITE
(don't look in global location)
For #1 and #3, there could be odd cases, where there's an egg-link in 2
locations.
This method will just return the first one found.
|
Return the path for the .egg-link file if it exists, otherwise, None.
|
[
"Return",
"the",
"path",
"for",
"the",
".",
"egg",
"-",
"link",
"file",
"if",
"it",
"exists",
"otherwise",
"None",
"."
] |
def egg_link_path(dist):
# type: (Distribution) -> Optional[str]
"""
Return the path for the .egg-link file if it exists, otherwise, None.
There's 3 scenarios:
1) not in a virtualenv
try to find in site.USER_SITE, then site_packages
2) in a no-global virtualenv
try to find in site_packages
3) in a yes-global virtualenv
try to find in site_packages, then site.USER_SITE
(don't look in global location)
For #1 and #3, there could be odd cases, where there's an egg-link in 2
locations.
This method will just return the first one found.
"""
sites = []
if running_under_virtualenv():
if virtualenv_no_global():
sites.append(site_packages)
else:
sites.append(site_packages)
if user_site:
sites.append(user_site)
else:
if user_site:
sites.append(user_site)
sites.append(site_packages)
for site in sites:
egglink = os.path.join(site, dist.project_name) + '.egg-link'
if os.path.isfile(egglink):
return egglink
return None
|
[
"def",
"egg_link_path",
"(",
"dist",
")",
":",
"# type: (Distribution) -> Optional[str]",
"sites",
"=",
"[",
"]",
"if",
"running_under_virtualenv",
"(",
")",
":",
"if",
"virtualenv_no_global",
"(",
")",
":",
"sites",
".",
"append",
"(",
"site_packages",
")",
"else",
":",
"sites",
".",
"append",
"(",
"site_packages",
")",
"if",
"user_site",
":",
"sites",
".",
"append",
"(",
"user_site",
")",
"else",
":",
"if",
"user_site",
":",
"sites",
".",
"append",
"(",
"user_site",
")",
"sites",
".",
"append",
"(",
"site_packages",
")",
"for",
"site",
"in",
"sites",
":",
"egglink",
"=",
"os",
".",
"path",
".",
"join",
"(",
"site",
",",
"dist",
".",
"project_name",
")",
"+",
"'.egg-link'",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"egglink",
")",
":",
"return",
"egglink",
"return",
"None"
] |
https://github.com/selfteaching/selfteaching-python-camp/blob/9982ee964b984595e7d664b07c389cddaf158f1e/19100205/Ceasar1978/pip-19.0.3/src/pip/_internal/utils/misc.py#L429-L465
|
|
Neuraxio/Neuraxle
|
c5627e663ef6d50736bc6a01110afa626fffec07
|
neuraxle/hyperparams/distributions.py
|
python
|
HyperparameterDistribution.max
|
(self)
|
Abstract method for obtaining maximal value that can sampled in distribution.
:return: maximal value that can be sampled from distribution.
|
Abstract method for obtaining maximal value that can sampled in distribution.
|
[
"Abstract",
"method",
"for",
"obtaining",
"maximal",
"value",
"that",
"can",
"sampled",
"in",
"distribution",
"."
] |
def max(self) -> float:
"""
Abstract method for obtaining maximal value that can sampled in distribution.
:return: maximal value that can be sampled from distribution.
"""
pass
|
[
"def",
"max",
"(",
"self",
")",
"->",
"float",
":",
"pass"
] |
https://github.com/Neuraxio/Neuraxle/blob/c5627e663ef6d50736bc6a01110afa626fffec07/neuraxle/hyperparams/distributions.py#L99-L105
|
||
mattupstate/flask-social
|
36f5790c8fb6d4d9a5120d099419ba30fd73e897
|
flask_social/providers/google.py
|
python
|
get_token_pair_from_response
|
(response)
|
return dict(
access_token = response.get('access_token', None),
secret = None
)
|
[] |
def get_token_pair_from_response(response):
return dict(
access_token = response.get('access_token', None),
secret = None
)
|
[
"def",
"get_token_pair_from_response",
"(",
"response",
")",
":",
"return",
"dict",
"(",
"access_token",
"=",
"response",
".",
"get",
"(",
"'access_token'",
",",
"None",
")",
",",
"secret",
"=",
"None",
")"
] |
https://github.com/mattupstate/flask-social/blob/36f5790c8fb6d4d9a5120d099419ba30fd73e897/flask_social/providers/google.py#L84-L88
|
|||
debian-calibre/calibre
|
020fc81d3936a64b2ac51459ecb796666ab6a051
|
src/odf/odf2xhtml.py
|
python
|
ODF2XHTML.e_text_span
|
(self, tag, attrs)
|
End the <text:span>
|
End the <text:span>
|
[
"End",
"the",
"<text",
":",
"span",
">"
] |
def e_text_span(self, tag, attrs):
""" End the <text:span> """
self.writedata()
c = attrs.get((TEXTNS,'style-name'), None)
# Changed by Kovid to handle inline special styles defined on <text:span> tags.
# Apparently LibreOffice does this.
special = 'span'
if c:
c = c.replace(".","_")
special = special_styles.get("S-"+c)
if special is None:
special = 'span'
self.closetag(special, False)
self.purgedata()
|
[
"def",
"e_text_span",
"(",
"self",
",",
"tag",
",",
"attrs",
")",
":",
"self",
".",
"writedata",
"(",
")",
"c",
"=",
"attrs",
".",
"get",
"(",
"(",
"TEXTNS",
",",
"'style-name'",
")",
",",
"None",
")",
"# Changed by Kovid to handle inline special styles defined on <text:span> tags.",
"# Apparently LibreOffice does this.",
"special",
"=",
"'span'",
"if",
"c",
":",
"c",
"=",
"c",
".",
"replace",
"(",
"\".\"",
",",
"\"_\"",
")",
"special",
"=",
"special_styles",
".",
"get",
"(",
"\"S-\"",
"+",
"c",
")",
"if",
"special",
"is",
"None",
":",
"special",
"=",
"'span'",
"self",
".",
"closetag",
"(",
"special",
",",
"False",
")",
"self",
".",
"purgedata",
"(",
")"
] |
https://github.com/debian-calibre/calibre/blob/020fc81d3936a64b2ac51459ecb796666ab6a051/src/odf/odf2xhtml.py#L1537-L1551
|
||
leo-editor/leo-editor
|
383d6776d135ef17d73d935a2f0ecb3ac0e99494
|
leo/core/leoPrinting.py
|
python
|
PrintingController.preview_expanded_html
|
(self, event=None)
|
Preview all the expanded bodies of the selected node as html. The
expanded text must be valid html, including <html> and <body> elements.
|
Preview all the expanded bodies of the selected node as html. The
expanded text must be valid html, including <html> and <body> elements.
|
[
"Preview",
"all",
"the",
"expanded",
"bodies",
"of",
"the",
"selected",
"node",
"as",
"html",
".",
"The",
"expanded",
"text",
"must",
"be",
"valid",
"html",
"including",
"<html",
">",
"and",
"<body",
">",
"elements",
"."
] |
def preview_expanded_html(self, event=None):
"""
Preview all the expanded bodies of the selected node as html. The
expanded text must be valid html, including <html> and <body> elements.
"""
doc = self.html_document(self.expand(self.c.p))
self.preview_doc(doc)
|
[
"def",
"preview_expanded_html",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"doc",
"=",
"self",
".",
"html_document",
"(",
"self",
".",
"expand",
"(",
"self",
".",
"c",
".",
"p",
")",
")",
"self",
".",
"preview_doc",
"(",
"doc",
")"
] |
https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/core/leoPrinting.py#L126-L132
|
||
cnvogelg/amitools
|
b8aaff735cc64cdb95c4616b0c9a9683e2a0b753
|
amitools/binfmt/hunk/HunkBlockFile.py
|
python
|
HunkBlockFile.read
|
(self, f, isLoadSeg=False, verbose=False)
|
read a hunk file and fill block list
|
read a hunk file and fill block list
|
[
"read",
"a",
"hunk",
"file",
"and",
"fill",
"block",
"list"
] |
def read(self, f, isLoadSeg=False, verbose=False):
"""read a hunk file and fill block list"""
while True:
# first read block id
tag = f.read(4)
# EOF
if len(tag) == 0:
break
elif len(tag) != 4:
raise HunkParseError("Hunk block tag too short!")
blk_id = struct.unpack(">I", tag)[0]
# mask out mem flags
blk_id = blk_id & HUNK_TYPE_MASK
# look up block type
if blk_id in hunk_block_type_map:
# v37 special case: 1015 is 1020 (HUNK_RELOC32SHORT)
# we do this only in LoadSeg() files
if isLoadSeg and blk_id == 1015:
blk_id = 1020
blk_type = hunk_block_type_map[blk_id]
# create block and parse
block = blk_type()
block.blk_id = blk_id
block.parse(f)
self.blocks.append(block)
else:
raise HunkParseError("Unsupported hunk type: %04d" % blk_id)
|
[
"def",
"read",
"(",
"self",
",",
"f",
",",
"isLoadSeg",
"=",
"False",
",",
"verbose",
"=",
"False",
")",
":",
"while",
"True",
":",
"# first read block id",
"tag",
"=",
"f",
".",
"read",
"(",
"4",
")",
"# EOF",
"if",
"len",
"(",
"tag",
")",
"==",
"0",
":",
"break",
"elif",
"len",
"(",
"tag",
")",
"!=",
"4",
":",
"raise",
"HunkParseError",
"(",
"\"Hunk block tag too short!\"",
")",
"blk_id",
"=",
"struct",
".",
"unpack",
"(",
"\">I\"",
",",
"tag",
")",
"[",
"0",
"]",
"# mask out mem flags",
"blk_id",
"=",
"blk_id",
"&",
"HUNK_TYPE_MASK",
"# look up block type",
"if",
"blk_id",
"in",
"hunk_block_type_map",
":",
"# v37 special case: 1015 is 1020 (HUNK_RELOC32SHORT)",
"# we do this only in LoadSeg() files",
"if",
"isLoadSeg",
"and",
"blk_id",
"==",
"1015",
":",
"blk_id",
"=",
"1020",
"blk_type",
"=",
"hunk_block_type_map",
"[",
"blk_id",
"]",
"# create block and parse",
"block",
"=",
"blk_type",
"(",
")",
"block",
".",
"blk_id",
"=",
"blk_id",
"block",
".",
"parse",
"(",
"f",
")",
"self",
".",
"blocks",
".",
"append",
"(",
"block",
")",
"else",
":",
"raise",
"HunkParseError",
"(",
"\"Unsupported hunk type: %04d\"",
"%",
"blk_id",
")"
] |
https://github.com/cnvogelg/amitools/blob/b8aaff735cc64cdb95c4616b0c9a9683e2a0b753/amitools/binfmt/hunk/HunkBlockFile.py#L665-L691
|
||
pwnieexpress/pwn_plug_sources
|
1a23324f5dc2c3de20f9c810269b6a29b2758cad
|
src/wifitap/scapy.py
|
python
|
DNSRRField.i2m
|
(self, pkt, x)
|
return str(x)
|
[] |
def i2m(self, pkt, x):
if x is None:
return ""
return str(x)
|
[
"def",
"i2m",
"(",
"self",
",",
"pkt",
",",
"x",
")",
":",
"if",
"x",
"is",
"None",
":",
"return",
"\"\"",
"return",
"str",
"(",
"x",
")"
] |
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/wifitap/scapy.py#L4685-L4688
|
|||
googleads/google-ads-python
|
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
|
google/ads/googleads/v8/services/services/group_placement_view_service/client.py
|
python
|
GroupPlacementViewServiceClient.common_project_path
|
(project: str,)
|
return "projects/{project}".format(project=project,)
|
Return a fully-qualified project string.
|
Return a fully-qualified project string.
|
[
"Return",
"a",
"fully",
"-",
"qualified",
"project",
"string",
"."
] |
def common_project_path(project: str,) -> str:
"""Return a fully-qualified project string."""
return "projects/{project}".format(project=project,)
|
[
"def",
"common_project_path",
"(",
"project",
":",
"str",
",",
")",
"->",
"str",
":",
"return",
"\"projects/{project}\"",
".",
"format",
"(",
"project",
"=",
"project",
",",
")"
] |
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v8/services/services/group_placement_view_service/client.py#L219-L221
|
|
ChineseGLUE/ChineseGLUE
|
1591b85cf5427c2ff60f718d359ecb71d2b44879
|
baselines/models/bert_wwm_ext/run_classifier.py
|
python
|
InewsProcessor.get_train_examples
|
(self, data_dir)
|
return self._create_examples(
self._read_txt(os.path.join(data_dir, "train.txt")), "train")
|
See base class.
|
See base class.
|
[
"See",
"base",
"class",
"."
] |
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_txt(os.path.join(data_dir, "train.txt")), "train")
|
[
"def",
"get_train_examples",
"(",
"self",
",",
"data_dir",
")",
":",
"return",
"self",
".",
"_create_examples",
"(",
"self",
".",
"_read_txt",
"(",
"os",
".",
"path",
".",
"join",
"(",
"data_dir",
",",
"\"train.txt\"",
")",
")",
",",
"\"train\"",
")"
] |
https://github.com/ChineseGLUE/ChineseGLUE/blob/1591b85cf5427c2ff60f718d359ecb71d2b44879/baselines/models/bert_wwm_ext/run_classifier.py#L305-L308
|
|
igraph/python-igraph
|
e9f83e8af08f24ea025596e745917197d8b44d94
|
src/igraph/remote/gephi.py
|
python
|
GephiConnection.__repr__
|
(self)
|
return "%s(url=%r)" % (self.__class__.__name__, self.url)
|
[] |
def __repr__(self):
return "%s(url=%r)" % (self.__class__.__name__, self.url)
|
[
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"\"%s(url=%r)\"",
"%",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"self",
".",
"url",
")"
] |
https://github.com/igraph/python-igraph/blob/e9f83e8af08f24ea025596e745917197d8b44d94/src/igraph/remote/gephi.py#L78-L79
|
|||
titusjan/argos
|
5a9c31a8a9a2ca825bbf821aa1e685740e3682d7
|
argos/reg/tabview.py
|
python
|
BaseTableView.getCurrentItem
|
(self)
|
return self.model().itemFromIndex(curIdx)
|
Returns the item of the selected row, or None if none is selected
|
Returns the item of the selected row, or None if none is selected
|
[
"Returns",
"the",
"item",
"of",
"the",
"selected",
"row",
"or",
"None",
"if",
"none",
"is",
"selected"
] |
def getCurrentItem(self):
""" Returns the item of the selected row, or None if none is selected
"""
curIdx = self.currentIndex()
return self.model().itemFromIndex(curIdx)
|
[
"def",
"getCurrentItem",
"(",
"self",
")",
":",
"curIdx",
"=",
"self",
".",
"currentIndex",
"(",
")",
"return",
"self",
".",
"model",
"(",
")",
".",
"itemFromIndex",
"(",
"curIdx",
")"
] |
https://github.com/titusjan/argos/blob/5a9c31a8a9a2ca825bbf821aa1e685740e3682d7/argos/reg/tabview.py#L77-L81
|
|
lad1337/XDM
|
0c1b7009fe00f06f102a6f67c793478f515e7efe
|
site-packages/pylint/pyreverse/diadefslib.py
|
python
|
DiaDefGenerator.get_ancestors
|
(self, node, level)
|
return ancestor nodes of a class node
|
return ancestor nodes of a class node
|
[
"return",
"ancestor",
"nodes",
"of",
"a",
"class",
"node"
] |
def get_ancestors(self, node, level):
"""return ancestor nodes of a class node"""
if level == 0:
return
for ancestor in node.ancestors(recurs=False):
if not self.show_node(ancestor):
continue
yield ancestor
|
[
"def",
"get_ancestors",
"(",
"self",
",",
"node",
",",
"level",
")",
":",
"if",
"level",
"==",
"0",
":",
"return",
"for",
"ancestor",
"in",
"node",
".",
"ancestors",
"(",
"recurs",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"show_node",
"(",
"ancestor",
")",
":",
"continue",
"yield",
"ancestor"
] |
https://github.com/lad1337/XDM/blob/0c1b7009fe00f06f102a6f67c793478f515e7efe/site-packages/pylint/pyreverse/diadefslib.py#L87-L94
|
||
loris-imageserver/loris
|
174248d61b7a18f5531005694f057997a2390332
|
loris/parameters.py
|
python
|
RotationParameter.__init__
|
(self, uri_value)
|
Take the uri value, and parse out mirror and rotation values.
Args:
uri_value (str): the rotation slice of the request URI.
Raises:
SyntaxException:
If the argument is not a valid rotation slice.
|
Take the uri value, and parse out mirror and rotation values.
Args:
uri_value (str): the rotation slice of the request URI.
Raises:
SyntaxException:
If the argument is not a valid rotation slice.
|
[
"Take",
"the",
"uri",
"value",
"and",
"parse",
"out",
"mirror",
"and",
"rotation",
"values",
".",
"Args",
":",
"uri_value",
"(",
"str",
")",
":",
"the",
"rotation",
"slice",
"of",
"the",
"request",
"URI",
".",
"Raises",
":",
"SyntaxException",
":",
"If",
"the",
"argument",
"is",
"not",
"a",
"valid",
"rotation",
"slice",
"."
] |
def __init__(self, uri_value):
'''Take the uri value, and parse out mirror and rotation values.
Args:
uri_value (str): the rotation slice of the request URI.
Raises:
SyntaxException:
If the argument is not a valid rotation slice.
'''
match = RotationParameter.ROTATION_REGEX.match(uri_value)
if not match:
raise SyntaxException(
"Rotation parameter %r is not a number" % uri_value
)
self.mirror = bool(match.group('mirror'))
self.rotation = match.group('rotation')
try:
self.canonical_uri_value = '%g' % (float(self.rotation),)
except ValueError:
raise SyntaxException(
"Rotation parameter %r is not a floating point number." %
uri_value
)
if self.mirror:
self.canonical_uri_value = '!%s' % self.canonical_uri_value
if not 0.0 <= float(self.rotation) <= 360.0:
raise SyntaxException(
"Rotation parameter %r is not between 0 and 360." % uri_value
)
logger.debug('Canonical rotation parameter is %s', self.canonical_uri_value)
|
[
"def",
"__init__",
"(",
"self",
",",
"uri_value",
")",
":",
"match",
"=",
"RotationParameter",
".",
"ROTATION_REGEX",
".",
"match",
"(",
"uri_value",
")",
"if",
"not",
"match",
":",
"raise",
"SyntaxException",
"(",
"\"Rotation parameter %r is not a number\"",
"%",
"uri_value",
")",
"self",
".",
"mirror",
"=",
"bool",
"(",
"match",
".",
"group",
"(",
"'mirror'",
")",
")",
"self",
".",
"rotation",
"=",
"match",
".",
"group",
"(",
"'rotation'",
")",
"try",
":",
"self",
".",
"canonical_uri_value",
"=",
"'%g'",
"%",
"(",
"float",
"(",
"self",
".",
"rotation",
")",
",",
")",
"except",
"ValueError",
":",
"raise",
"SyntaxException",
"(",
"\"Rotation parameter %r is not a floating point number.\"",
"%",
"uri_value",
")",
"if",
"self",
".",
"mirror",
":",
"self",
".",
"canonical_uri_value",
"=",
"'!%s'",
"%",
"self",
".",
"canonical_uri_value",
"if",
"not",
"0.0",
"<=",
"float",
"(",
"self",
".",
"rotation",
")",
"<=",
"360.0",
":",
"raise",
"SyntaxException",
"(",
"\"Rotation parameter %r is not between 0 and 360.\"",
"%",
"uri_value",
")",
"logger",
".",
"debug",
"(",
"'Canonical rotation parameter is %s'",
",",
"self",
".",
"canonical_uri_value",
")"
] |
https://github.com/loris-imageserver/loris/blob/174248d61b7a18f5531005694f057997a2390332/loris/parameters.py#L438-L473
|
||
bendmorris/static-python
|
2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473
|
Lib/enum.py
|
python
|
EnumMeta._find_new_
|
(classdict, member_type, first_enum)
|
return __new__, save_new, use_args
|
Returns the __new__ to be used for creating the enum members.
classdict: the class dictionary given to __new__
member_type: the data type whose __new__ will be used by default
first_enum: enumeration to check for an overriding __new__
|
Returns the __new__ to be used for creating the enum members.
|
[
"Returns",
"the",
"__new__",
"to",
"be",
"used",
"for",
"creating",
"the",
"enum",
"members",
"."
] |
def _find_new_(classdict, member_type, first_enum):
"""Returns the __new__ to be used for creating the enum members.
classdict: the class dictionary given to __new__
member_type: the data type whose __new__ will be used by default
first_enum: enumeration to check for an overriding __new__
"""
# now find the correct __new__, checking to see of one was defined
# by the user; also check earlier enum classes in case a __new__ was
# saved as __new_member__
__new__ = classdict.get('__new__', None)
# should __new__ be saved as __new_member__ later?
save_new = __new__ is not None
if __new__ is None:
# check all possibles for __new_member__ before falling back to
# __new__
for method in ('__new_member__', '__new__'):
for possible in (member_type, first_enum):
target = getattr(possible, method, None)
if target not in {
None,
None.__new__,
object.__new__,
Enum.__new__,
}:
__new__ = target
break
if __new__ is not None:
break
else:
__new__ = object.__new__
# if a non-object.__new__ is used then whatever value/tuple was
# assigned to the enum member name will be passed to __new__ and to the
# new enum member's __init__
if __new__ is object.__new__:
use_args = False
else:
use_args = True
return __new__, save_new, use_args
|
[
"def",
"_find_new_",
"(",
"classdict",
",",
"member_type",
",",
"first_enum",
")",
":",
"# now find the correct __new__, checking to see of one was defined",
"# by the user; also check earlier enum classes in case a __new__ was",
"# saved as __new_member__",
"__new__",
"=",
"classdict",
".",
"get",
"(",
"'__new__'",
",",
"None",
")",
"# should __new__ be saved as __new_member__ later?",
"save_new",
"=",
"__new__",
"is",
"not",
"None",
"if",
"__new__",
"is",
"None",
":",
"# check all possibles for __new_member__ before falling back to",
"# __new__",
"for",
"method",
"in",
"(",
"'__new_member__'",
",",
"'__new__'",
")",
":",
"for",
"possible",
"in",
"(",
"member_type",
",",
"first_enum",
")",
":",
"target",
"=",
"getattr",
"(",
"possible",
",",
"method",
",",
"None",
")",
"if",
"target",
"not",
"in",
"{",
"None",
",",
"None",
".",
"__new__",
",",
"object",
".",
"__new__",
",",
"Enum",
".",
"__new__",
",",
"}",
":",
"__new__",
"=",
"target",
"break",
"if",
"__new__",
"is",
"not",
"None",
":",
"break",
"else",
":",
"__new__",
"=",
"object",
".",
"__new__",
"# if a non-object.__new__ is used then whatever value/tuple was",
"# assigned to the enum member name will be passed to __new__ and to the",
"# new enum member's __init__",
"if",
"__new__",
"is",
"object",
".",
"__new__",
":",
"use_args",
"=",
"False",
"else",
":",
"use_args",
"=",
"True",
"return",
"__new__",
",",
"save_new",
",",
"use_args"
] |
https://github.com/bendmorris/static-python/blob/2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473/Lib/enum.py#L367-L410
|
|
andresriancho/w3af
|
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
|
w3af/core/ui/gui/scanrun.py
|
python
|
URLsTree.add_url
|
(self)
|
return True
|
Adds periodically the new URLs to the tree.
:return: True to keep being called by gobject, False when it's done.
|
Adds periodically the new URLs to the tree.
|
[
"Adds",
"periodically",
"the",
"new",
"URLs",
"to",
"the",
"tree",
"."
] |
def add_url(self):
"""Adds periodically the new URLs to the tree.
:return: True to keep being called by gobject, False when it's done.
"""
try:
url = self.urls.get_nowait()
except Queue.Empty:
pass
else:
path = url.get_path()
params = url.get_params_string()
query = str(url.querystring)
fragment = url.get_fragment()
scheme = url.get_protocol()
netloc = url.get_domain()
ini = "%s://%s" % (scheme, netloc)
end = ""
if params:
end += ";" + params
if query:
end += "?" + query
if fragment:
end += "#" + fragment
splittedPath = re.split('(\\\\|/)', path)
nodes = []
for i in splittedPath:
if i not in ['\\', '/']:
nodes.append(i)
nodes.insert(0, ini)
nodes.append(end)
parts = [x for x in nodes if x]
self._insertNodes(None, parts, self.treeholder, 1)
# TODO: Automatically sort after each insertion
# Order the treeview
self.treestore.sort_column_changed()
return True
|
[
"def",
"add_url",
"(",
"self",
")",
":",
"try",
":",
"url",
"=",
"self",
".",
"urls",
".",
"get_nowait",
"(",
")",
"except",
"Queue",
".",
"Empty",
":",
"pass",
"else",
":",
"path",
"=",
"url",
".",
"get_path",
"(",
")",
"params",
"=",
"url",
".",
"get_params_string",
"(",
")",
"query",
"=",
"str",
"(",
"url",
".",
"querystring",
")",
"fragment",
"=",
"url",
".",
"get_fragment",
"(",
")",
"scheme",
"=",
"url",
".",
"get_protocol",
"(",
")",
"netloc",
"=",
"url",
".",
"get_domain",
"(",
")",
"ini",
"=",
"\"%s://%s\"",
"%",
"(",
"scheme",
",",
"netloc",
")",
"end",
"=",
"\"\"",
"if",
"params",
":",
"end",
"+=",
"\";\"",
"+",
"params",
"if",
"query",
":",
"end",
"+=",
"\"?\"",
"+",
"query",
"if",
"fragment",
":",
"end",
"+=",
"\"#\"",
"+",
"fragment",
"splittedPath",
"=",
"re",
".",
"split",
"(",
"'(\\\\\\\\|/)'",
",",
"path",
")",
"nodes",
"=",
"[",
"]",
"for",
"i",
"in",
"splittedPath",
":",
"if",
"i",
"not",
"in",
"[",
"'\\\\'",
",",
"'/'",
"]",
":",
"nodes",
".",
"append",
"(",
"i",
")",
"nodes",
".",
"insert",
"(",
"0",
",",
"ini",
")",
"nodes",
".",
"append",
"(",
"end",
")",
"parts",
"=",
"[",
"x",
"for",
"x",
"in",
"nodes",
"if",
"x",
"]",
"self",
".",
"_insertNodes",
"(",
"None",
",",
"parts",
",",
"self",
".",
"treeholder",
",",
"1",
")",
"# TODO: Automatically sort after each insertion",
"# Order the treeview",
"self",
".",
"treestore",
".",
"sort_column_changed",
"(",
")",
"return",
"True"
] |
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/core/ui/gui/scanrun.py#L527-L569
|
|
holzschu/Carnets
|
44effb10ddfc6aa5c8b0687582a724ba82c6b547
|
Library/lib/python3.7/site-packages/pandas-0.24.2-py3.7-macosx-10.9-x86_64.egg/pandas/core/groupby/generic.py
|
python
|
NDFrameGroupBy._transform_fast
|
(self, result, obj, func_nm)
|
return DataFrame._from_arrays(output, columns=result.columns,
index=obj.index)
|
Fast transform path for aggregations
|
Fast transform path for aggregations
|
[
"Fast",
"transform",
"path",
"for",
"aggregations"
] |
def _transform_fast(self, result, obj, func_nm):
"""
Fast transform path for aggregations
"""
# if there were groups with no observations (Categorical only?)
# try casting data to original dtype
cast = self._transform_should_cast(func_nm)
# for each col, reshape to to size of original frame
# by take operation
ids, _, ngroup = self.grouper.group_info
output = []
for i, _ in enumerate(result.columns):
res = algorithms.take_1d(result.iloc[:, i].values, ids)
if cast:
res = self._try_cast(res, obj.iloc[:, i])
output.append(res)
return DataFrame._from_arrays(output, columns=result.columns,
index=obj.index)
|
[
"def",
"_transform_fast",
"(",
"self",
",",
"result",
",",
"obj",
",",
"func_nm",
")",
":",
"# if there were groups with no observations (Categorical only?)",
"# try casting data to original dtype",
"cast",
"=",
"self",
".",
"_transform_should_cast",
"(",
"func_nm",
")",
"# for each col, reshape to to size of original frame",
"# by take operation",
"ids",
",",
"_",
",",
"ngroup",
"=",
"self",
".",
"grouper",
".",
"group_info",
"output",
"=",
"[",
"]",
"for",
"i",
",",
"_",
"in",
"enumerate",
"(",
"result",
".",
"columns",
")",
":",
"res",
"=",
"algorithms",
".",
"take_1d",
"(",
"result",
".",
"iloc",
"[",
":",
",",
"i",
"]",
".",
"values",
",",
"ids",
")",
"if",
"cast",
":",
"res",
"=",
"self",
".",
"_try_cast",
"(",
"res",
",",
"obj",
".",
"iloc",
"[",
":",
",",
"i",
"]",
")",
"output",
".",
"append",
"(",
"res",
")",
"return",
"DataFrame",
".",
"_from_arrays",
"(",
"output",
",",
"columns",
"=",
"result",
".",
"columns",
",",
"index",
"=",
"obj",
".",
"index",
")"
] |
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/pandas-0.24.2-py3.7-macosx-10.9-x86_64.egg/pandas/core/groupby/generic.py#L550-L569
|
|
frappe/erpnext
|
9d36e30ef7043b391b5ed2523b8288bf46c45d18
|
erpnext/accounts/doctype/pricing_rule/pricing_rule.py
|
python
|
apply_pricing_rule
|
(args, doc=None)
|
return out
|
args = {
"items": [{"doctype": "", "name": "", "item_code": "", "brand": "", "item_group": ""}, ...],
"customer": "something",
"customer_group": "something",
"territory": "something",
"supplier": "something",
"supplier_group": "something",
"currency": "something",
"conversion_rate": "something",
"price_list": "something",
"plc_conversion_rate": "something",
"company": "something",
"transaction_date": "something",
"campaign": "something",
"sales_partner": "something",
"ignore_pricing_rule": "something"
}
|
args = {
"items": [{"doctype": "", "name": "", "item_code": "", "brand": "", "item_group": ""}, ...],
"customer": "something",
"customer_group": "something",
"territory": "something",
"supplier": "something",
"supplier_group": "something",
"currency": "something",
"conversion_rate": "something",
"price_list": "something",
"plc_conversion_rate": "something",
"company": "something",
"transaction_date": "something",
"campaign": "something",
"sales_partner": "something",
"ignore_pricing_rule": "something"
}
|
[
"args",
"=",
"{",
"items",
":",
"[",
"{",
"doctype",
":",
"name",
":",
"item_code",
":",
"brand",
":",
"item_group",
":",
"}",
"...",
"]",
"customer",
":",
"something",
"customer_group",
":",
"something",
"territory",
":",
"something",
"supplier",
":",
"something",
"supplier_group",
":",
"something",
"currency",
":",
"something",
"conversion_rate",
":",
"something",
"price_list",
":",
"something",
"plc_conversion_rate",
":",
"something",
"company",
":",
"something",
"transaction_date",
":",
"something",
"campaign",
":",
"something",
"sales_partner",
":",
"something",
"ignore_pricing_rule",
":",
"something",
"}"
] |
def apply_pricing_rule(args, doc=None):
"""
args = {
"items": [{"doctype": "", "name": "", "item_code": "", "brand": "", "item_group": ""}, ...],
"customer": "something",
"customer_group": "something",
"territory": "something",
"supplier": "something",
"supplier_group": "something",
"currency": "something",
"conversion_rate": "something",
"price_list": "something",
"plc_conversion_rate": "something",
"company": "something",
"transaction_date": "something",
"campaign": "something",
"sales_partner": "something",
"ignore_pricing_rule": "something"
}
"""
if isinstance(args, str):
args = json.loads(args)
args = frappe._dict(args)
if not args.transaction_type:
set_transaction_type(args)
# list of dictionaries
out = []
if args.get("doctype") == "Material Request": return out
item_list = args.get("items")
args.pop("items")
set_serial_nos_based_on_fifo = frappe.db.get_single_value("Stock Settings",
"automatically_set_serial_nos_based_on_fifo")
item_code_list = tuple(item.get('item_code') for item in item_list)
query_items = frappe.get_all('Item', fields=['item_code','has_serial_no'], filters=[['item_code','in',item_code_list]],as_list=1)
serialized_items = dict()
for item_code, val in query_items:
serialized_items.setdefault(item_code, val)
for item in item_list:
args_copy = copy.deepcopy(args)
args_copy.update(item)
data = get_pricing_rule_for_item(args_copy, item.get('price_list_rate'), doc=doc)
out.append(data)
if serialized_items.get(item.get('item_code')) and not item.get("serial_no") and set_serial_nos_based_on_fifo and not args.get('is_return'):
out[0].update(get_serial_no_for_item(args_copy))
return out
|
[
"def",
"apply_pricing_rule",
"(",
"args",
",",
"doc",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"args",
",",
"str",
")",
":",
"args",
"=",
"json",
".",
"loads",
"(",
"args",
")",
"args",
"=",
"frappe",
".",
"_dict",
"(",
"args",
")",
"if",
"not",
"args",
".",
"transaction_type",
":",
"set_transaction_type",
"(",
"args",
")",
"# list of dictionaries",
"out",
"=",
"[",
"]",
"if",
"args",
".",
"get",
"(",
"\"doctype\"",
")",
"==",
"\"Material Request\"",
":",
"return",
"out",
"item_list",
"=",
"args",
".",
"get",
"(",
"\"items\"",
")",
"args",
".",
"pop",
"(",
"\"items\"",
")",
"set_serial_nos_based_on_fifo",
"=",
"frappe",
".",
"db",
".",
"get_single_value",
"(",
"\"Stock Settings\"",
",",
"\"automatically_set_serial_nos_based_on_fifo\"",
")",
"item_code_list",
"=",
"tuple",
"(",
"item",
".",
"get",
"(",
"'item_code'",
")",
"for",
"item",
"in",
"item_list",
")",
"query_items",
"=",
"frappe",
".",
"get_all",
"(",
"'Item'",
",",
"fields",
"=",
"[",
"'item_code'",
",",
"'has_serial_no'",
"]",
",",
"filters",
"=",
"[",
"[",
"'item_code'",
",",
"'in'",
",",
"item_code_list",
"]",
"]",
",",
"as_list",
"=",
"1",
")",
"serialized_items",
"=",
"dict",
"(",
")",
"for",
"item_code",
",",
"val",
"in",
"query_items",
":",
"serialized_items",
".",
"setdefault",
"(",
"item_code",
",",
"val",
")",
"for",
"item",
"in",
"item_list",
":",
"args_copy",
"=",
"copy",
".",
"deepcopy",
"(",
"args",
")",
"args_copy",
".",
"update",
"(",
"item",
")",
"data",
"=",
"get_pricing_rule_for_item",
"(",
"args_copy",
",",
"item",
".",
"get",
"(",
"'price_list_rate'",
")",
",",
"doc",
"=",
"doc",
")",
"out",
".",
"append",
"(",
"data",
")",
"if",
"serialized_items",
".",
"get",
"(",
"item",
".",
"get",
"(",
"'item_code'",
")",
")",
"and",
"not",
"item",
".",
"get",
"(",
"\"serial_no\"",
")",
"and",
"set_serial_nos_based_on_fifo",
"and",
"not",
"args",
".",
"get",
"(",
"'is_return'",
")",
":",
"out",
"[",
"0",
"]",
".",
"update",
"(",
"get_serial_no_for_item",
"(",
"args_copy",
")",
")",
"return",
"out"
] |
https://github.com/frappe/erpnext/blob/9d36e30ef7043b391b5ed2523b8288bf46c45d18/erpnext/accounts/doctype/pricing_rule/pricing_rule.py#L159-L214
|
|
jkkummerfeld/text2sql-data
|
2905ab815b4893d99ea061a20fb55860ecb1f92e
|
systems/sequence-to-sequence/seq2seq/models/model_base.py
|
python
|
ModelBase._build
|
(self, features, labels, params)
|
Subclasses should implement this method. See the `model_fn` documentation
in tf.contrib.learn.Estimator class for a more detailed explanation.
|
Subclasses should implement this method. See the `model_fn` documentation
in tf.contrib.learn.Estimator class for a more detailed explanation.
|
[
"Subclasses",
"should",
"implement",
"this",
"method",
".",
"See",
"the",
"model_fn",
"documentation",
"in",
"tf",
".",
"contrib",
".",
"learn",
".",
"Estimator",
"class",
"for",
"a",
"more",
"detailed",
"explanation",
"."
] |
def _build(self, features, labels, params):
"""Subclasses should implement this method. See the `model_fn` documentation
in tf.contrib.learn.Estimator class for a more detailed explanation.
"""
raise NotImplementedError
|
[
"def",
"_build",
"(",
"self",
",",
"features",
",",
"labels",
",",
"params",
")",
":",
"raise",
"NotImplementedError"
] |
https://github.com/jkkummerfeld/text2sql-data/blob/2905ab815b4893d99ea061a20fb55860ecb1f92e/systems/sequence-to-sequence/seq2seq/models/model_base.py#L148-L152
|
||
MaybeShewill-CV/attentive-gan-derainnet
|
4ec79993cf3d757741c9c88c1036d87bd46e982d
|
data_provider/tf_io_pipline_tools.py
|
python
|
random_horizon_flip_batch_images
|
(rain_image, clean_image, mask_image)
|
return flipped_rain_image, flipped_clean_image, flipped_mask_image
|
Random horizon flip image batch data for training
:param rain_image:
:param clean_image:
:param mask_image:
:return:
|
Random horizon flip image batch data for training
:param rain_image:
:param clean_image:
:param mask_image:
:return:
|
[
"Random",
"horizon",
"flip",
"image",
"batch",
"data",
"for",
"training",
":",
"param",
"rain_image",
":",
":",
"param",
"clean_image",
":",
":",
"param",
"mask_image",
":",
":",
"return",
":"
] |
def random_horizon_flip_batch_images(rain_image, clean_image, mask_image):
"""
Random horizon flip image batch data for training
:param rain_image:
:param clean_image:
:param mask_image:
:return:
"""
concat_images = tf.concat([rain_image, clean_image, mask_image], axis=-1)
[image_height, image_width, _] = rain_image.get_shape().as_list()
concat_flipped_images = tf.image.random_flip_left_right(
image=concat_images,
seed=tf.random.set_random_seed(4321)
)
flipped_rain_image = tf.slice(
concat_flipped_images,
begin=[0, 0, 0],
size=[image_height, image_width, 3]
)
flipped_clean_image = tf.slice(
concat_flipped_images,
begin=[0, 0, 3],
size=[image_height, image_width, 3]
)
flipped_mask_image = tf.slice(
concat_flipped_images,
begin=[0, 0, 6],
size=[image_height, image_width, 1]
)
return flipped_rain_image, flipped_clean_image, flipped_mask_image
|
[
"def",
"random_horizon_flip_batch_images",
"(",
"rain_image",
",",
"clean_image",
",",
"mask_image",
")",
":",
"concat_images",
"=",
"tf",
".",
"concat",
"(",
"[",
"rain_image",
",",
"clean_image",
",",
"mask_image",
"]",
",",
"axis",
"=",
"-",
"1",
")",
"[",
"image_height",
",",
"image_width",
",",
"_",
"]",
"=",
"rain_image",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"concat_flipped_images",
"=",
"tf",
".",
"image",
".",
"random_flip_left_right",
"(",
"image",
"=",
"concat_images",
",",
"seed",
"=",
"tf",
".",
"random",
".",
"set_random_seed",
"(",
"4321",
")",
")",
"flipped_rain_image",
"=",
"tf",
".",
"slice",
"(",
"concat_flipped_images",
",",
"begin",
"=",
"[",
"0",
",",
"0",
",",
"0",
"]",
",",
"size",
"=",
"[",
"image_height",
",",
"image_width",
",",
"3",
"]",
")",
"flipped_clean_image",
"=",
"tf",
".",
"slice",
"(",
"concat_flipped_images",
",",
"begin",
"=",
"[",
"0",
",",
"0",
",",
"3",
"]",
",",
"size",
"=",
"[",
"image_height",
",",
"image_width",
",",
"3",
"]",
")",
"flipped_mask_image",
"=",
"tf",
".",
"slice",
"(",
"concat_flipped_images",
",",
"begin",
"=",
"[",
"0",
",",
"0",
",",
"6",
"]",
",",
"size",
"=",
"[",
"image_height",
",",
"image_width",
",",
"1",
"]",
")",
"return",
"flipped_rain_image",
",",
"flipped_clean_image",
",",
"flipped_mask_image"
] |
https://github.com/MaybeShewill-CV/attentive-gan-derainnet/blob/4ec79993cf3d757741c9c88c1036d87bd46e982d/data_provider/tf_io_pipline_tools.py#L233-L266
|
|
bruderstein/PythonScript
|
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
|
PythonLib/full/pickle.py
|
python
|
_dump
|
(obj, file, protocol=None, *, fix_imports=True, buffer_callback=None)
|
[] |
def _dump(obj, file, protocol=None, *, fix_imports=True, buffer_callback=None):
_Pickler(file, protocol, fix_imports=fix_imports,
buffer_callback=buffer_callback).dump(obj)
|
[
"def",
"_dump",
"(",
"obj",
",",
"file",
",",
"protocol",
"=",
"None",
",",
"*",
",",
"fix_imports",
"=",
"True",
",",
"buffer_callback",
"=",
"None",
")",
":",
"_Pickler",
"(",
"file",
",",
"protocol",
",",
"fix_imports",
"=",
"fix_imports",
",",
"buffer_callback",
"=",
"buffer_callback",
")",
".",
"dump",
"(",
"obj",
")"
] |
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/pickle.py#L1750-L1752
|
||||
larryhastings/gilectomy
|
4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a
|
Lib/logging/config.py
|
python
|
BaseConfigurator.ext_convert
|
(self, value)
|
return self.resolve(value)
|
Default converter for the ext:// protocol.
|
Default converter for the ext:// protocol.
|
[
"Default",
"converter",
"for",
"the",
"ext",
":",
"//",
"protocol",
"."
] |
def ext_convert(self, value):
"""Default converter for the ext:// protocol."""
return self.resolve(value)
|
[
"def",
"ext_convert",
"(",
"self",
",",
"value",
")",
":",
"return",
"self",
".",
"resolve",
"(",
"value",
")"
] |
https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/logging/config.py#L393-L395
|
|
maas/maas
|
db2f89970c640758a51247c59bf1ec6f60cf4ab5
|
src/maascli/api.py
|
python
|
Action.name_value_pair
|
(string)
|
Ensure that `string` is a valid ``name:value`` pair.
When `string` is of the form ``name=value``, this returns a
2-tuple of ``name, value``.
However, when `string` is of the form ``name@=value``, this
returns a ``name, opener`` tuple, where ``opener`` is a function
that will return an open file handle when called. The file will
be opened for reading only, actions will open it as text by default,
but may use binary mode if specified.
|
Ensure that `string` is a valid ``name:value`` pair.
|
[
"Ensure",
"that",
"string",
"is",
"a",
"valid",
"name",
":",
"value",
"pair",
"."
] |
def name_value_pair(string):
"""Ensure that `string` is a valid ``name:value`` pair.
When `string` is of the form ``name=value``, this returns a
2-tuple of ``name, value``.
However, when `string` is of the form ``name@=value``, this
returns a ``name, opener`` tuple, where ``opener`` is a function
that will return an open file handle when called. The file will
be opened for reading only, actions will open it as text by default,
but may use binary mode if specified.
"""
parts = re.split(r"(=|@=)", string, 1)
if len(parts) == 3:
name, what, value = parts
if what == "=":
return name, value
elif what == "@=":
return name, partial(open, value)
else:
raise AssertionError("Unrecognised separator %r" % what)
else:
raise CommandError(
"%r is not a name=value or name@=filename pair" % string
)
|
[
"def",
"name_value_pair",
"(",
"string",
")",
":",
"parts",
"=",
"re",
".",
"split",
"(",
"r\"(=|@=)\"",
",",
"string",
",",
"1",
")",
"if",
"len",
"(",
"parts",
")",
"==",
"3",
":",
"name",
",",
"what",
",",
"value",
"=",
"parts",
"if",
"what",
"==",
"\"=\"",
":",
"return",
"name",
",",
"value",
"elif",
"what",
"==",
"\"@=\"",
":",
"return",
"name",
",",
"partial",
"(",
"open",
",",
"value",
")",
"else",
":",
"raise",
"AssertionError",
"(",
"\"Unrecognised separator %r\"",
"%",
"what",
")",
"else",
":",
"raise",
"CommandError",
"(",
"\"%r is not a name=value or name@=filename pair\"",
"%",
"string",
")"
] |
https://github.com/maas/maas/blob/db2f89970c640758a51247c59bf1ec6f60cf4ab5/src/maascli/api.py#L183-L207
|
||
JaniceWuo/MovieRecommend
|
4c86db64ca45598917d304f535413df3bc9fea65
|
movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/distlib/version.py
|
python
|
NormalizedMatcher._match_le
|
(self, version, constraint, prefix)
|
return version <= constraint
|
[] |
def _match_le(self, version, constraint, prefix):
version, constraint = self._adjust_local(version, constraint, prefix)
return version <= constraint
|
[
"def",
"_match_le",
"(",
"self",
",",
"version",
",",
"constraint",
",",
"prefix",
")",
":",
"version",
",",
"constraint",
"=",
"self",
".",
"_adjust_local",
"(",
"version",
",",
"constraint",
",",
"prefix",
")",
"return",
"version",
"<=",
"constraint"
] |
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/distlib/version.py#L346-L348
|
|||
lindawangg/COVID-Net
|
9eb97f7b8fbbd4b42c67e41a7c92de0d11c966b0
|
data.py
|
python
|
_process_csv_file
|
(file)
|
return files
|
[] |
def _process_csv_file(file):
with open(file, 'r') as fr:
files = fr.readlines()
return files
|
[
"def",
"_process_csv_file",
"(",
"file",
")",
":",
"with",
"open",
"(",
"file",
",",
"'r'",
")",
"as",
"fr",
":",
"files",
"=",
"fr",
".",
"readlines",
"(",
")",
"return",
"files"
] |
https://github.com/lindawangg/COVID-Net/blob/9eb97f7b8fbbd4b42c67e41a7c92de0d11c966b0/data.py#L82-L85
|
|||
TencentCloud/tencentcloud-sdk-python
|
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
|
tencentcloud/mariadb/v20170312/models.py
|
python
|
KillSessionResponse.__init__
|
(self)
|
r"""
:param TaskId: 任务ID
:type TaskId: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
|
r"""
:param TaskId: 任务ID
:type TaskId: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
|
[
"r",
":",
"param",
"TaskId",
":",
"任务ID",
":",
"type",
"TaskId",
":",
"int",
":",
"param",
"RequestId",
":",
"唯一请求",
"ID,每次请求都会返回。定位问题时需要提供该次请求的",
"RequestId。",
":",
"type",
"RequestId",
":",
"str"
] |
def __init__(self):
r"""
:param TaskId: 任务ID
:type TaskId: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TaskId = None
self.RequestId = None
|
[
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"TaskId",
"=",
"None",
"self",
".",
"RequestId",
"=",
"None"
] |
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/mariadb/v20170312/models.py#L3449-L3457
|
||
carla-simulator/scenario_runner
|
f4d00d88eda4212a1e119515c96281a4be5c234e
|
srunner/metrics/tools/metrics_parser.py
|
python
|
parse_velocity
|
(info)
|
return velocity
|
Parses a list into a carla.Vector3D with the velocity
|
Parses a list into a carla.Vector3D with the velocity
|
[
"Parses",
"a",
"list",
"into",
"a",
"carla",
".",
"Vector3D",
"with",
"the",
"velocity"
] |
def parse_velocity(info):
"""Parses a list into a carla.Vector3D with the velocity"""
velocity = carla.Vector3D(
x=float(info[3][1:-1]),
y=float(info[4][:-1]),
z=float(info[5][:-1])
)
return velocity
|
[
"def",
"parse_velocity",
"(",
"info",
")",
":",
"velocity",
"=",
"carla",
".",
"Vector3D",
"(",
"x",
"=",
"float",
"(",
"info",
"[",
"3",
"]",
"[",
"1",
":",
"-",
"1",
"]",
")",
",",
"y",
"=",
"float",
"(",
"info",
"[",
"4",
"]",
"[",
":",
"-",
"1",
"]",
")",
",",
"z",
"=",
"float",
"(",
"info",
"[",
"5",
"]",
"[",
":",
"-",
"1",
"]",
")",
")",
"return",
"velocity"
] |
https://github.com/carla-simulator/scenario_runner/blob/f4d00d88eda4212a1e119515c96281a4be5c234e/srunner/metrics/tools/metrics_parser.py#L97-L104
|
|
merenlab/anvio
|
9b792e2cedc49ecb7c0bed768261595a0d87c012
|
anvio/workflows/metagenomics/__init__.py
|
python
|
MetagenomicsWorkflow.gen_report_with_references_for_removal_info
|
(self, filtered_id_files, output_file_name)
|
If mapping was done to reference for removal then we create a report with the results.
|
If mapping was done to reference for removal then we create a report with the results.
|
[
"If",
"mapping",
"was",
"done",
"to",
"reference",
"for",
"removal",
"then",
"we",
"create",
"a",
"report",
"with",
"the",
"results",
"."
] |
def gen_report_with_references_for_removal_info(self, filtered_id_files, output_file_name):
''' If mapping was done to reference for removal then we create a report with the results.'''
report_dict = {}
for filename in filtered_id_files:
sample = os.path.basename(filename).split("-ids-to-remove.txt")[0]
ids = set(open(filename).read().splitlines())
report_dict[sample] = {}
report_dict[sample]['number_of_filtered_reads'] = len(ids)
u.store_dict_as_TAB_delimited_file(report_dict, output_file_name, headers=["sample", 'number_of_filtered_reads'])
|
[
"def",
"gen_report_with_references_for_removal_info",
"(",
"self",
",",
"filtered_id_files",
",",
"output_file_name",
")",
":",
"report_dict",
"=",
"{",
"}",
"for",
"filename",
"in",
"filtered_id_files",
":",
"sample",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
".",
"split",
"(",
"\"-ids-to-remove.txt\"",
")",
"[",
"0",
"]",
"ids",
"=",
"set",
"(",
"open",
"(",
"filename",
")",
".",
"read",
"(",
")",
".",
"splitlines",
"(",
")",
")",
"report_dict",
"[",
"sample",
"]",
"=",
"{",
"}",
"report_dict",
"[",
"sample",
"]",
"[",
"'number_of_filtered_reads'",
"]",
"=",
"len",
"(",
"ids",
")",
"u",
".",
"store_dict_as_TAB_delimited_file",
"(",
"report_dict",
",",
"output_file_name",
",",
"headers",
"=",
"[",
"\"sample\"",
",",
"'number_of_filtered_reads'",
"]",
")"
] |
https://github.com/merenlab/anvio/blob/9b792e2cedc49ecb7c0bed768261595a0d87c012/anvio/workflows/metagenomics/__init__.py#L530-L538
|
||
Azure/azure-devops-cli-extension
|
11334cd55806bef0b99c3bee5a438eed71e44037
|
azure-devops/azext_devops/devops_sdk/v5_1/feature_management/feature_management_client.py
|
python
|
FeatureManagementClient.get_feature_state_for_scope
|
(self, feature_id, user_scope, scope_name, scope_value)
|
return self._deserialize('ContributedFeatureState', response)
|
GetFeatureStateForScope.
[Preview API] Get the state of the specified feature for the given named scope
:param str feature_id: Contribution id of the feature
:param str user_scope: User-Scope at which to get the value. Should be "me" for the current user or "host" for all users.
:param str scope_name: Scope at which to get the feature setting for (e.g. "project" or "team")
:param str scope_value: Value of the scope (e.g. the project or team id)
:rtype: :class:`<ContributedFeatureState> <azure.devops.v5_1.feature_management.models.ContributedFeatureState>`
|
GetFeatureStateForScope.
[Preview API] Get the state of the specified feature for the given named scope
:param str feature_id: Contribution id of the feature
:param str user_scope: User-Scope at which to get the value. Should be "me" for the current user or "host" for all users.
:param str scope_name: Scope at which to get the feature setting for (e.g. "project" or "team")
:param str scope_value: Value of the scope (e.g. the project or team id)
:rtype: :class:`<ContributedFeatureState> <azure.devops.v5_1.feature_management.models.ContributedFeatureState>`
|
[
"GetFeatureStateForScope",
".",
"[",
"Preview",
"API",
"]",
"Get",
"the",
"state",
"of",
"the",
"specified",
"feature",
"for",
"the",
"given",
"named",
"scope",
":",
"param",
"str",
"feature_id",
":",
"Contribution",
"id",
"of",
"the",
"feature",
":",
"param",
"str",
"user_scope",
":",
"User",
"-",
"Scope",
"at",
"which",
"to",
"get",
"the",
"value",
".",
"Should",
"be",
"me",
"for",
"the",
"current",
"user",
"or",
"host",
"for",
"all",
"users",
".",
":",
"param",
"str",
"scope_name",
":",
"Scope",
"at",
"which",
"to",
"get",
"the",
"feature",
"setting",
"for",
"(",
"e",
".",
"g",
".",
"project",
"or",
"team",
")",
":",
"param",
"str",
"scope_value",
":",
"Value",
"of",
"the",
"scope",
"(",
"e",
".",
"g",
".",
"the",
"project",
"or",
"team",
"id",
")",
":",
"rtype",
":",
":",
"class",
":",
"<ContributedFeatureState",
">",
"<azure",
".",
"devops",
".",
"v5_1",
".",
"feature_management",
".",
"models",
".",
"ContributedFeatureState",
">"
] |
def get_feature_state_for_scope(self, feature_id, user_scope, scope_name, scope_value):
"""GetFeatureStateForScope.
[Preview API] Get the state of the specified feature for the given named scope
:param str feature_id: Contribution id of the feature
:param str user_scope: User-Scope at which to get the value. Should be "me" for the current user or "host" for all users.
:param str scope_name: Scope at which to get the feature setting for (e.g. "project" or "team")
:param str scope_value: Value of the scope (e.g. the project or team id)
:rtype: :class:`<ContributedFeatureState> <azure.devops.v5_1.feature_management.models.ContributedFeatureState>`
"""
route_values = {}
if feature_id is not None:
route_values['featureId'] = self._serialize.url('feature_id', feature_id, 'str')
if user_scope is not None:
route_values['userScope'] = self._serialize.url('user_scope', user_scope, 'str')
if scope_name is not None:
route_values['scopeName'] = self._serialize.url('scope_name', scope_name, 'str')
if scope_value is not None:
route_values['scopeValue'] = self._serialize.url('scope_value', scope_value, 'str')
response = self._send(http_method='GET',
location_id='dd291e43-aa9f-4cee-8465-a93c78e414a4',
version='5.1-preview.1',
route_values=route_values)
return self._deserialize('ContributedFeatureState', response)
|
[
"def",
"get_feature_state_for_scope",
"(",
"self",
",",
"feature_id",
",",
"user_scope",
",",
"scope_name",
",",
"scope_value",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"feature_id",
"is",
"not",
"None",
":",
"route_values",
"[",
"'featureId'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"(",
"'feature_id'",
",",
"feature_id",
",",
"'str'",
")",
"if",
"user_scope",
"is",
"not",
"None",
":",
"route_values",
"[",
"'userScope'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"(",
"'user_scope'",
",",
"user_scope",
",",
"'str'",
")",
"if",
"scope_name",
"is",
"not",
"None",
":",
"route_values",
"[",
"'scopeName'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"(",
"'scope_name'",
",",
"scope_name",
",",
"'str'",
")",
"if",
"scope_value",
"is",
"not",
"None",
":",
"route_values",
"[",
"'scopeValue'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"(",
"'scope_value'",
",",
"scope_value",
",",
"'str'",
")",
"response",
"=",
"self",
".",
"_send",
"(",
"http_method",
"=",
"'GET'",
",",
"location_id",
"=",
"'dd291e43-aa9f-4cee-8465-a93c78e414a4'",
",",
"version",
"=",
"'5.1-preview.1'",
",",
"route_values",
"=",
"route_values",
")",
"return",
"self",
".",
"_deserialize",
"(",
"'ContributedFeatureState'",
",",
"response",
")"
] |
https://github.com/Azure/azure-devops-cli-extension/blob/11334cd55806bef0b99c3bee5a438eed71e44037/azure-devops/azext_devops/devops_sdk/v5_1/feature_management/feature_management_client.py#L105-L127
|
|
shervinea/enzynet
|
7367635ae73595822133577054743a4c4c327cf3
|
enzynet/visualization.py
|
python
|
plot_cube_at
|
(pos: Tuple[float, float, float] = (0, 0, 0),
ax: Optional[plt.gca] = None,
color: Text = 'g')
|
Plots a cube element at position pos.
|
Plots a cube element at position pos.
|
[
"Plots",
"a",
"cube",
"element",
"at",
"position",
"pos",
"."
] |
def plot_cube_at(pos: Tuple[float, float, float] = (0, 0, 0),
ax: Optional[plt.gca] = None,
color: Text = 'g') -> None:
"""Plots a cube element at position pos."""
lightsource = mcolors.LightSource(azdeg=135, altdeg=0)
if ax != None:
X, Y, Z = cuboid_data(pos)
ax.plot_surface(X, Y, Z, color=color, rstride=1, cstride=1, alpha=1,
lightsource=lightsource)
|
[
"def",
"plot_cube_at",
"(",
"pos",
":",
"Tuple",
"[",
"float",
",",
"float",
",",
"float",
"]",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
",",
"ax",
":",
"Optional",
"[",
"plt",
".",
"gca",
"]",
"=",
"None",
",",
"color",
":",
"Text",
"=",
"'g'",
")",
"->",
"None",
":",
"lightsource",
"=",
"mcolors",
".",
"LightSource",
"(",
"azdeg",
"=",
"135",
",",
"altdeg",
"=",
"0",
")",
"if",
"ax",
"!=",
"None",
":",
"X",
",",
"Y",
",",
"Z",
"=",
"cuboid_data",
"(",
"pos",
")",
"ax",
".",
"plot_surface",
"(",
"X",
",",
"Y",
",",
"Z",
",",
"color",
"=",
"color",
",",
"rstride",
"=",
"1",
",",
"cstride",
"=",
"1",
",",
"alpha",
"=",
"1",
",",
"lightsource",
"=",
"lightsource",
")"
] |
https://github.com/shervinea/enzynet/blob/7367635ae73595822133577054743a4c4c327cf3/enzynet/visualization.py#L166-L174
|
||
LGE-ARC-AdvancedAI/auptimizer
|
50f6e3b4e0cb9146ca90fd74b9b24ca97ae22617
|
src/aup/compression/torch/compressor.py
|
python
|
Pruner.calc_mask
|
(self, wrapper, **kwargs)
|
Pruners should overload this method to provide mask for weight tensors.
The mask must have the same shape and type comparing to the weight.
It will be applied with `mul()` operation on the weight.
This method is effectively hooked to `forward()` method of the model.
Parameters
----------
wrapper : Module
calculate mask for `wrapper.module`'s weight
|
Pruners should overload this method to provide mask for weight tensors.
The mask must have the same shape and type comparing to the weight.
It will be applied with `mul()` operation on the weight.
This method is effectively hooked to `forward()` method of the model.
|
[
"Pruners",
"should",
"overload",
"this",
"method",
"to",
"provide",
"mask",
"for",
"weight",
"tensors",
".",
"The",
"mask",
"must",
"have",
"the",
"same",
"shape",
"and",
"type",
"comparing",
"to",
"the",
"weight",
".",
"It",
"will",
"be",
"applied",
"with",
"mul",
"()",
"operation",
"on",
"the",
"weight",
".",
"This",
"method",
"is",
"effectively",
"hooked",
"to",
"forward",
"()",
"method",
"of",
"the",
"model",
"."
] |
def calc_mask(self, wrapper, **kwargs):
"""
Pruners should overload this method to provide mask for weight tensors.
The mask must have the same shape and type comparing to the weight.
It will be applied with `mul()` operation on the weight.
This method is effectively hooked to `forward()` method of the model.
Parameters
----------
wrapper : Module
calculate mask for `wrapper.module`'s weight
"""
raise NotImplementedError("Pruners must overload calc_mask()")
|
[
"def",
"calc_mask",
"(",
"self",
",",
"wrapper",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Pruners must overload calc_mask()\"",
")"
] |
https://github.com/LGE-ARC-AdvancedAI/auptimizer/blob/50f6e3b4e0cb9146ca90fd74b9b24ca97ae22617/src/aup/compression/torch/compressor.py#L338-L350
|
||
jgagneastro/coffeegrindsize
|
22661ebd21831dba4cf32bfc6ba59fe3d49f879c
|
App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/afm.py
|
python
|
_parse_composites
|
(fh)
|
Parse the given filehandle for composites information return them as a
dict.
It is assumed that the file cursor is on the line behind 'StartComposites'.
Returns
-------
composites : dict
A dict mapping composite character names to a parts list. The parts
list is a list of `.CompositePart` entries describing the parts of
the composite.
Example
-------
A composite definition line::
CC Aacute 2 ; PCC A 0 0 ; PCC acute 160 170 ;
will be represented as::
composites['Aacute'] = [CompositePart(name='A', dx=0, dy=0),
CompositePart(name='acute', dx=160, dy=170)]
|
Parse the given filehandle for composites information return them as a
dict.
|
[
"Parse",
"the",
"given",
"filehandle",
"for",
"composites",
"information",
"return",
"them",
"as",
"a",
"dict",
"."
] |
def _parse_composites(fh):
"""
Parse the given filehandle for composites information return them as a
dict.
It is assumed that the file cursor is on the line behind 'StartComposites'.
Returns
-------
composites : dict
A dict mapping composite character names to a parts list. The parts
list is a list of `.CompositePart` entries describing the parts of
the composite.
Example
-------
A composite definition line::
CC Aacute 2 ; PCC A 0 0 ; PCC acute 160 170 ;
will be represented as::
composites['Aacute'] = [CompositePart(name='A', dx=0, dy=0),
CompositePart(name='acute', dx=160, dy=170)]
"""
composites = {}
for line in fh:
line = line.rstrip()
if not line:
continue
if line.startswith(b'EndComposites'):
return composites
vals = line.split(b';')
cc = vals[0].split()
name, numParts = cc[1], _to_int(cc[2])
pccParts = []
for s in vals[1:-1]:
pcc = s.split()
part = CompositePart(pcc[1], _to_float(pcc[2]), _to_float(pcc[3]))
pccParts.append(part)
composites[name] = pccParts
raise RuntimeError('Bad composites parse')
|
[
"def",
"_parse_composites",
"(",
"fh",
")",
":",
"composites",
"=",
"{",
"}",
"for",
"line",
"in",
"fh",
":",
"line",
"=",
"line",
".",
"rstrip",
"(",
")",
"if",
"not",
"line",
":",
"continue",
"if",
"line",
".",
"startswith",
"(",
"b'EndComposites'",
")",
":",
"return",
"composites",
"vals",
"=",
"line",
".",
"split",
"(",
"b';'",
")",
"cc",
"=",
"vals",
"[",
"0",
"]",
".",
"split",
"(",
")",
"name",
",",
"numParts",
"=",
"cc",
"[",
"1",
"]",
",",
"_to_int",
"(",
"cc",
"[",
"2",
"]",
")",
"pccParts",
"=",
"[",
"]",
"for",
"s",
"in",
"vals",
"[",
"1",
":",
"-",
"1",
"]",
":",
"pcc",
"=",
"s",
".",
"split",
"(",
")",
"part",
"=",
"CompositePart",
"(",
"pcc",
"[",
"1",
"]",
",",
"_to_float",
"(",
"pcc",
"[",
"2",
"]",
")",
",",
"_to_float",
"(",
"pcc",
"[",
"3",
"]",
")",
")",
"pccParts",
".",
"append",
"(",
"part",
")",
"composites",
"[",
"name",
"]",
"=",
"pccParts",
"raise",
"RuntimeError",
"(",
"'Bad composites parse'",
")"
] |
https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/afm.py#L282-L325
|
||
quadrismegistus/prosodic
|
2153c3bb3b9e056e03dd885e0c32e6f60cf30ec9
|
prosodic/lib/Text.py
|
python
|
Text.givebirth
|
(self)
|
return stanza
|
Return an empty Stanza.
|
Return an empty Stanza.
|
[
"Return",
"an",
"empty",
"Stanza",
"."
] |
def givebirth(self):
"""Return an empty Stanza."""
stanza=Stanza()
return stanza
|
[
"def",
"givebirth",
"(",
"self",
")",
":",
"stanza",
"=",
"Stanza",
"(",
")",
"return",
"stanza"
] |
https://github.com/quadrismegistus/prosodic/blob/2153c3bb3b9e056e03dd885e0c32e6f60cf30ec9/prosodic/lib/Text.py#L827-L830
|
|
pynamodb/PynamoDB
|
5136edde90dade15f9b376edbfcd9f0ea7498171
|
pynamodb/connection/base.py
|
python
|
Connection.list_tables
|
(
self,
exclusive_start_table_name: Optional[str] = None,
limit: Optional[int] = None,
)
|
Performs the ListTables operation
|
Performs the ListTables operation
|
[
"Performs",
"the",
"ListTables",
"operation"
] |
def list_tables(
self,
exclusive_start_table_name: Optional[str] = None,
limit: Optional[int] = None,
) -> Dict:
"""
Performs the ListTables operation
"""
operation_kwargs: Dict[str, Any] = {}
if exclusive_start_table_name:
operation_kwargs.update({
EXCLUSIVE_START_TABLE_NAME: exclusive_start_table_name
})
if limit is not None:
operation_kwargs.update({
LIMIT: limit
})
try:
return self.dispatch(LIST_TABLES, operation_kwargs)
except BOTOCORE_EXCEPTIONS as e:
raise TableError("Unable to list tables: {}".format(e), e)
|
[
"def",
"list_tables",
"(",
"self",
",",
"exclusive_start_table_name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"limit",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
")",
"->",
"Dict",
":",
"operation_kwargs",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"{",
"}",
"if",
"exclusive_start_table_name",
":",
"operation_kwargs",
".",
"update",
"(",
"{",
"EXCLUSIVE_START_TABLE_NAME",
":",
"exclusive_start_table_name",
"}",
")",
"if",
"limit",
"is",
"not",
"None",
":",
"operation_kwargs",
".",
"update",
"(",
"{",
"LIMIT",
":",
"limit",
"}",
")",
"try",
":",
"return",
"self",
".",
"dispatch",
"(",
"LIST_TABLES",
",",
"operation_kwargs",
")",
"except",
"BOTOCORE_EXCEPTIONS",
"as",
"e",
":",
"raise",
"TableError",
"(",
"\"Unable to list tables: {}\"",
".",
"format",
"(",
"e",
")",
",",
"e",
")"
] |
https://github.com/pynamodb/PynamoDB/blob/5136edde90dade15f9b376edbfcd9f0ea7498171/pynamodb/connection/base.py#L721-L741
|
||
harry159821/XiamiForLinuxProject
|
93d75d7652548d02ba386c961bc8afb5550a530e
|
PIL/Image.py
|
python
|
Image.getpixel
|
(self, xy)
|
return self.im.getpixel(xy)
|
Returns the pixel value at a given position.
:param xy: The coordinate, given as (x, y).
:returns: The pixel value. If the image is a multi-layer image,
this method returns a tuple.
|
Returns the pixel value at a given position.
|
[
"Returns",
"the",
"pixel",
"value",
"at",
"a",
"given",
"position",
"."
] |
def getpixel(self, xy):
"""
Returns the pixel value at a given position.
:param xy: The coordinate, given as (x, y).
:returns: The pixel value. If the image is a multi-layer image,
this method returns a tuple.
"""
self.load()
return self.im.getpixel(xy)
|
[
"def",
"getpixel",
"(",
"self",
",",
"xy",
")",
":",
"self",
".",
"load",
"(",
")",
"return",
"self",
".",
"im",
".",
"getpixel",
"(",
"xy",
")"
] |
https://github.com/harry159821/XiamiForLinuxProject/blob/93d75d7652548d02ba386c961bc8afb5550a530e/PIL/Image.py#L962-L972
|
|
beetbox/beets
|
2fea53c34dd505ba391cb345424e0613901c8025
|
beets/random.py
|
python
|
random_objs
|
(objs, album, number=1, time=None, equal_chance=False,
random_gen=None)
|
Get a random subset of the provided `objs`.
If `number` is provided, produce that many matches. Otherwise, if
`time` is provided, instead select a list whose total time is close
to that number of minutes. If `equal_chance` is true, give each
artist an equal chance of being included so that artists with more
songs are not represented disproportionately.
|
Get a random subset of the provided `objs`.
|
[
"Get",
"a",
"random",
"subset",
"of",
"the",
"provided",
"objs",
"."
] |
def random_objs(objs, album, number=1, time=None, equal_chance=False,
random_gen=None):
"""Get a random subset of the provided `objs`.
If `number` is provided, produce that many matches. Otherwise, if
`time` is provided, instead select a list whose total time is close
to that number of minutes. If `equal_chance` is true, give each
artist an equal chance of being included so that artists with more
songs are not represented disproportionately.
"""
rand = random_gen or random
# Permute the objects either in a straightforward way or an
# artist-balanced way.
if equal_chance:
perm = _equal_chance_permutation(objs)
else:
perm = objs
rand.shuffle(perm) # N.B. This shuffles the original list.
# Select objects by time our count.
if time:
return _take_time(perm, time * 60, album)
else:
return _take(perm, number)
|
[
"def",
"random_objs",
"(",
"objs",
",",
"album",
",",
"number",
"=",
"1",
",",
"time",
"=",
"None",
",",
"equal_chance",
"=",
"False",
",",
"random_gen",
"=",
"None",
")",
":",
"rand",
"=",
"random_gen",
"or",
"random",
"# Permute the objects either in a straightforward way or an",
"# artist-balanced way.",
"if",
"equal_chance",
":",
"perm",
"=",
"_equal_chance_permutation",
"(",
"objs",
")",
"else",
":",
"perm",
"=",
"objs",
"rand",
".",
"shuffle",
"(",
"perm",
")",
"# N.B. This shuffles the original list.",
"# Select objects by time our count.",
"if",
"time",
":",
"return",
"_take_time",
"(",
"perm",
",",
"time",
"*",
"60",
",",
"album",
")",
"else",
":",
"return",
"_take",
"(",
"perm",
",",
"number",
")"
] |
https://github.com/beetbox/beets/blob/2fea53c34dd505ba391cb345424e0613901c8025/beets/random.py#L89-L113
|
||
mathics/Mathics
|
318e06dea8f1c70758a50cb2f95c9900150e3a68
|
mathics/builtin/string/operations.py
|
python
|
StringTrim.apply
|
(self, s, evaluation)
|
return String(s.get_string_value().strip(" \t\n"))
|
StringTrim[s_String]
|
StringTrim[s_String]
|
[
"StringTrim",
"[",
"s_String",
"]"
] |
def apply(self, s, evaluation):
"StringTrim[s_String]"
return String(s.get_string_value().strip(" \t\n"))
|
[
"def",
"apply",
"(",
"self",
",",
"s",
",",
"evaluation",
")",
":",
"return",
"String",
"(",
"s",
".",
"get_string_value",
"(",
")",
".",
"strip",
"(",
"\" \\t\\n\"",
")",
")"
] |
https://github.com/mathics/Mathics/blob/318e06dea8f1c70758a50cb2f95c9900150e3a68/mathics/builtin/string/operations.py#L1028-L1030
|
|
bleachbit/bleachbit
|
88fc4452936d02b56a76f07ce2142306bb47262b
|
windows/setup_py2exe.py
|
python
|
clean_translations
|
()
|
Clean translations (localizations)
|
Clean translations (localizations)
|
[
"Clean",
"translations",
"(",
"localizations",
")"
] |
def clean_translations():
"""Clean translations (localizations)"""
logger.info('Cleaning translations')
if os.path.exists(r'dist\share\locale\locale.alias'):
os.remove(r'dist\share\locale\locale.alias')
else:
logger.warning('locale.alias does not exist')
pygtk_translations = os.listdir('dist/share/locale')
supported_translations = [f[3:-3] for f in glob.glob('po/*.po')]
for pt in pygtk_translations:
if pt not in supported_translations:
path = 'dist/share/locale/' + pt
shutil.rmtree(path)
|
[
"def",
"clean_translations",
"(",
")",
":",
"logger",
".",
"info",
"(",
"'Cleaning translations'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"r'dist\\share\\locale\\locale.alias'",
")",
":",
"os",
".",
"remove",
"(",
"r'dist\\share\\locale\\locale.alias'",
")",
"else",
":",
"logger",
".",
"warning",
"(",
"'locale.alias does not exist'",
")",
"pygtk_translations",
"=",
"os",
".",
"listdir",
"(",
"'dist/share/locale'",
")",
"supported_translations",
"=",
"[",
"f",
"[",
"3",
":",
"-",
"3",
"]",
"for",
"f",
"in",
"glob",
".",
"glob",
"(",
"'po/*.po'",
")",
"]",
"for",
"pt",
"in",
"pygtk_translations",
":",
"if",
"pt",
"not",
"in",
"supported_translations",
":",
"path",
"=",
"'dist/share/locale/'",
"+",
"pt",
"shutil",
".",
"rmtree",
"(",
"path",
")"
] |
https://github.com/bleachbit/bleachbit/blob/88fc4452936d02b56a76f07ce2142306bb47262b/windows/setup_py2exe.py#L373-L385
|
||
GoogleCloudPlatform/PerfKitBenchmarker
|
6e3412d7d5e414b8ca30ed5eaf970cef1d919a67
|
perfkitbenchmarker/providers/ibmcloud/ibmcloud_manager.py
|
python
|
InstanceManager.DeleteVnic
|
(self, instance, vnicid)
|
return self._g.Request('DELETE', inst_uri)
|
Send a vm vnic delete request.
|
Send a vm vnic delete request.
|
[
"Send",
"a",
"vm",
"vnic",
"delete",
"request",
"."
] |
def DeleteVnic(self, instance, vnicid):
"""Send a vm vnic delete request."""
inst_uri = self.GetUri(instance) + '/network_interfaces/' + vnicid
return self._g.Request('DELETE', inst_uri)
|
[
"def",
"DeleteVnic",
"(",
"self",
",",
"instance",
",",
"vnicid",
")",
":",
"inst_uri",
"=",
"self",
".",
"GetUri",
"(",
"instance",
")",
"+",
"'/network_interfaces/'",
"+",
"vnicid",
"return",
"self",
".",
"_g",
".",
"Request",
"(",
"'DELETE'",
",",
"inst_uri",
")"
] |
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/6e3412d7d5e414b8ca30ed5eaf970cef1d919a67/perfkitbenchmarker/providers/ibmcloud/ibmcloud_manager.py#L504-L507
|
|
yuxiaokui/Intranet-Penetration
|
f57678a204840c83cbf3308e3470ae56c5ff514b
|
proxy/XX-Net/code/default/gae_proxy/server/lib/antlr3/recognizers.py
|
python
|
TokenSource.__iter__
|
(self)
|
return self
|
The TokenSource is an interator.
The iteration will not include the final EOF token, see also the note
for the next() method.
|
The TokenSource is an interator.
|
[
"The",
"TokenSource",
"is",
"an",
"interator",
"."
] |
def __iter__(self):
"""The TokenSource is an interator.
The iteration will not include the final EOF token, see also the note
for the next() method.
"""
return self
|
[
"def",
"__iter__",
"(",
"self",
")",
":",
"return",
"self"
] |
https://github.com/yuxiaokui/Intranet-Penetration/blob/f57678a204840c83cbf3308e3470ae56c5ff514b/proxy/XX-Net/code/default/gae_proxy/server/lib/antlr3/recognizers.py#L1060-L1068
|
|
automl/ConfigSpace
|
4d69931de5540fc6be4230731ddebf6a25d2e1a8
|
ConfigSpace/read_and_write/json.py
|
python
|
_build_greater_than_condition
|
(condition: GreaterThanCondition)
|
return {
'child': child,
'parent': parent,
'type': 'GT',
'value': value,
}
|
[] |
def _build_greater_than_condition(condition: GreaterThanCondition) -> Dict:
child = condition.child.name
parent = condition.parent.name
value = condition.value
return {
'child': child,
'parent': parent,
'type': 'GT',
'value': value,
}
|
[
"def",
"_build_greater_than_condition",
"(",
"condition",
":",
"GreaterThanCondition",
")",
"->",
"Dict",
":",
"child",
"=",
"condition",
".",
"child",
".",
"name",
"parent",
"=",
"condition",
".",
"parent",
".",
"name",
"value",
"=",
"condition",
".",
"value",
"return",
"{",
"'child'",
":",
"child",
",",
"'parent'",
":",
"parent",
",",
"'type'",
":",
"'GT'",
",",
"'value'",
":",
"value",
",",
"}"
] |
https://github.com/automl/ConfigSpace/blob/4d69931de5540fc6be4230731ddebf6a25d2e1a8/ConfigSpace/read_and_write/json.py#L203-L212
|
|||
araffin/robotics-rl-srl
|
eae7c1ab310c79662f6e68c0d255e08641037ffa
|
real_robots/omnirobot_utils/utils.py
|
python
|
PosTransformer.phyPosCam2PhyPosGround
|
(self, pos_coord_cam)
|
return (np.matmul(self.camera_2_ground_trans, homo_pos))[0:3, :]
|
Transform physical position in camera coordinate to physical position in ground coordinate
|
Transform physical position in camera coordinate to physical position in ground coordinate
|
[
"Transform",
"physical",
"position",
"in",
"camera",
"coordinate",
"to",
"physical",
"position",
"in",
"ground",
"coordinate"
] |
def phyPosCam2PhyPosGround(self, pos_coord_cam):
"""
Transform physical position in camera coordinate to physical position in ground coordinate
"""
assert pos_coord_cam.shape == (3, 1)
homo_pos = np.ones((4, 1), np.float32)
homo_pos[0:3, :] = pos_coord_cam
return (np.matmul(self.camera_2_ground_trans, homo_pos))[0:3, :]
|
[
"def",
"phyPosCam2PhyPosGround",
"(",
"self",
",",
"pos_coord_cam",
")",
":",
"assert",
"pos_coord_cam",
".",
"shape",
"==",
"(",
"3",
",",
"1",
")",
"homo_pos",
"=",
"np",
".",
"ones",
"(",
"(",
"4",
",",
"1",
")",
",",
"np",
".",
"float32",
")",
"homo_pos",
"[",
"0",
":",
"3",
",",
":",
"]",
"=",
"pos_coord_cam",
"return",
"(",
"np",
".",
"matmul",
"(",
"self",
".",
"camera_2_ground_trans",
",",
"homo_pos",
")",
")",
"[",
"0",
":",
"3",
",",
":",
"]"
] |
https://github.com/araffin/robotics-rl-srl/blob/eae7c1ab310c79662f6e68c0d255e08641037ffa/real_robots/omnirobot_utils/utils.py#L28-L35
|
|
sagemath/sagenb
|
67a73cbade02639bc08265f28f3165442113ad4d
|
sagenb/notebook/worksheet.py
|
python
|
split_search_string_into_keywords
|
(s)
|
return ans
|
r"""
The point of this function is to allow for searches like this::
"ws 7" foo bar Modular '"the" end'
i.e., where search terms can be in quotes and the different quote
types can be mixed.
INPUT:
- ``s`` - a string
OUTPUT:
- ``list`` - a list of strings
|
r"""
The point of this function is to allow for searches like this::
|
[
"r",
"The",
"point",
"of",
"this",
"function",
"is",
"to",
"allow",
"for",
"searches",
"like",
"this",
"::"
] |
def split_search_string_into_keywords(s):
r"""
The point of this function is to allow for searches like this::
"ws 7" foo bar Modular '"the" end'
i.e., where search terms can be in quotes and the different quote
types can be mixed.
INPUT:
- ``s`` - a string
OUTPUT:
- ``list`` - a list of strings
"""
ans = []
while len(s) > 0:
word, i = _get_next(s, '"')
if i != -1:
ans.append(word)
s = s[i:]
word, j = _get_next(s, "'")
if j != -1:
ans.append(word)
s = s[j:]
if i == -1 and j == -1:
break
ans.extend(s.split())
return ans
|
[
"def",
"split_search_string_into_keywords",
"(",
"s",
")",
":",
"ans",
"=",
"[",
"]",
"while",
"len",
"(",
"s",
")",
">",
"0",
":",
"word",
",",
"i",
"=",
"_get_next",
"(",
"s",
",",
"'\"'",
")",
"if",
"i",
"!=",
"-",
"1",
":",
"ans",
".",
"append",
"(",
"word",
")",
"s",
"=",
"s",
"[",
"i",
":",
"]",
"word",
",",
"j",
"=",
"_get_next",
"(",
"s",
",",
"\"'\"",
")",
"if",
"j",
"!=",
"-",
"1",
":",
"ans",
".",
"append",
"(",
"word",
")",
"s",
"=",
"s",
"[",
"j",
":",
"]",
"if",
"i",
"==",
"-",
"1",
"and",
"j",
"==",
"-",
"1",
":",
"break",
"ans",
".",
"extend",
"(",
"s",
".",
"split",
"(",
")",
")",
"return",
"ans"
] |
https://github.com/sagemath/sagenb/blob/67a73cbade02639bc08265f28f3165442113ad4d/sagenb/notebook/worksheet.py#L4551-L4581
|
|
pymedusa/Medusa
|
1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38
|
ext/boto/s3/bucketlistresultset.py
|
python
|
versioned_bucket_lister
|
(bucket, prefix='', delimiter='',
key_marker='', version_id_marker='', headers=None,
encoding_type=None)
|
A generator function for listing versions in a bucket.
|
A generator function for listing versions in a bucket.
|
[
"A",
"generator",
"function",
"for",
"listing",
"versions",
"in",
"a",
"bucket",
"."
] |
def versioned_bucket_lister(bucket, prefix='', delimiter='',
key_marker='', version_id_marker='', headers=None,
encoding_type=None):
"""
A generator function for listing versions in a bucket.
"""
more_results = True
k = None
while more_results:
rs = bucket.get_all_versions(prefix=prefix, key_marker=key_marker,
version_id_marker=version_id_marker,
delimiter=delimiter, headers=headers,
max_keys=999, encoding_type=encoding_type)
for k in rs:
yield k
key_marker = rs.next_key_marker
if key_marker and encoding_type == "url":
key_marker = unquote_str(key_marker)
version_id_marker = rs.next_version_id_marker
more_results= rs.is_truncated
|
[
"def",
"versioned_bucket_lister",
"(",
"bucket",
",",
"prefix",
"=",
"''",
",",
"delimiter",
"=",
"''",
",",
"key_marker",
"=",
"''",
",",
"version_id_marker",
"=",
"''",
",",
"headers",
"=",
"None",
",",
"encoding_type",
"=",
"None",
")",
":",
"more_results",
"=",
"True",
"k",
"=",
"None",
"while",
"more_results",
":",
"rs",
"=",
"bucket",
".",
"get_all_versions",
"(",
"prefix",
"=",
"prefix",
",",
"key_marker",
"=",
"key_marker",
",",
"version_id_marker",
"=",
"version_id_marker",
",",
"delimiter",
"=",
"delimiter",
",",
"headers",
"=",
"headers",
",",
"max_keys",
"=",
"999",
",",
"encoding_type",
"=",
"encoding_type",
")",
"for",
"k",
"in",
"rs",
":",
"yield",
"k",
"key_marker",
"=",
"rs",
".",
"next_key_marker",
"if",
"key_marker",
"and",
"encoding_type",
"==",
"\"url\"",
":",
"key_marker",
"=",
"unquote_str",
"(",
"key_marker",
")",
"version_id_marker",
"=",
"rs",
".",
"next_version_id_marker",
"more_results",
"=",
"rs",
".",
"is_truncated"
] |
https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/boto/s3/bucketlistresultset.py#L67-L86
|
||
pymedusa/Medusa
|
1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38
|
ext/github/Reaction.py
|
python
|
Reaction.content
|
(self)
|
return self._content.value
|
:type: string
|
:type: string
|
[
":",
"type",
":",
"string"
] |
def content(self):
"""
:type: string
"""
self._completeIfNotSet(self._content)
return self._content.value
|
[
"def",
"content",
"(",
"self",
")",
":",
"self",
".",
"_completeIfNotSet",
"(",
"self",
".",
"_content",
")",
"return",
"self",
".",
"_content",
".",
"value"
] |
https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/github/Reaction.py#L44-L49
|
|
MichaelGrupp/evo
|
c65af3b69188aaadbbd7b5f99ac7973d74343d65
|
evo/core/filters.py
|
python
|
filter_pairs_by_path
|
(poses: typing.Sequence[np.ndarray], delta: float,
tol: float = 0.0, all_pairs: bool = False)
|
return id_pairs
|
filters pairs in a list of SE(3) poses by their path distance in meters
- the accumulated, traveled path distance between the two pair points
is considered
:param poses: list of SE(3) poses
:param delta: the path distance in meters used for filtering
:param tol: absolute path tolerance to accept or reject pairs
in all_pairs mode
:param all_pairs: use all pairs instead of consecutive pairs
:return: list of index tuples of the filtered pairs
|
filters pairs in a list of SE(3) poses by their path distance in meters
- the accumulated, traveled path distance between the two pair points
is considered
:param poses: list of SE(3) poses
:param delta: the path distance in meters used for filtering
:param tol: absolute path tolerance to accept or reject pairs
in all_pairs mode
:param all_pairs: use all pairs instead of consecutive pairs
:return: list of index tuples of the filtered pairs
|
[
"filters",
"pairs",
"in",
"a",
"list",
"of",
"SE",
"(",
"3",
")",
"poses",
"by",
"their",
"path",
"distance",
"in",
"meters",
"-",
"the",
"accumulated",
"traveled",
"path",
"distance",
"between",
"the",
"two",
"pair",
"points",
"is",
"considered",
":",
"param",
"poses",
":",
"list",
"of",
"SE",
"(",
"3",
")",
"poses",
":",
"param",
"delta",
":",
"the",
"path",
"distance",
"in",
"meters",
"used",
"for",
"filtering",
":",
"param",
"tol",
":",
"absolute",
"path",
"tolerance",
"to",
"accept",
"or",
"reject",
"pairs",
"in",
"all_pairs",
"mode",
":",
"param",
"all_pairs",
":",
"use",
"all",
"pairs",
"instead",
"of",
"consecutive",
"pairs",
":",
"return",
":",
"list",
"of",
"index",
"tuples",
"of",
"the",
"filtered",
"pairs"
] |
def filter_pairs_by_path(poses: typing.Sequence[np.ndarray], delta: float,
tol: float = 0.0, all_pairs: bool = False) -> IdPairs:
"""
filters pairs in a list of SE(3) poses by their path distance in meters
- the accumulated, traveled path distance between the two pair points
is considered
:param poses: list of SE(3) poses
:param delta: the path distance in meters used for filtering
:param tol: absolute path tolerance to accept or reject pairs
in all_pairs mode
:param all_pairs: use all pairs instead of consecutive pairs
:return: list of index tuples of the filtered pairs
"""
id_pairs = []
if all_pairs:
positions = np.array([pose[:3, 3] for pose in poses])
distances = geometry.accumulated_distances(positions)
for i in range(distances.size - 1):
offset = i + 1
distances_from_here = distances[offset:] - distances[i]
candidate_index = int(
np.argmin(np.abs(distances_from_here - delta)))
if (np.abs(distances_from_here[candidate_index] - delta) > tol):
continue
id_pairs.append((i, candidate_index + offset))
else:
ids = []
previous_pose = poses[0]
current_path = 0.0
for i, current_pose in enumerate(poses):
current_path += float(
np.linalg.norm(current_pose[:3, 3] - previous_pose[:3, 3]))
previous_pose = current_pose
if current_path >= delta:
ids.append(i)
current_path = 0.0
id_pairs = [(i, j) for i, j in zip(ids, ids[1:])]
return id_pairs
|
[
"def",
"filter_pairs_by_path",
"(",
"poses",
":",
"typing",
".",
"Sequence",
"[",
"np",
".",
"ndarray",
"]",
",",
"delta",
":",
"float",
",",
"tol",
":",
"float",
"=",
"0.0",
",",
"all_pairs",
":",
"bool",
"=",
"False",
")",
"->",
"IdPairs",
":",
"id_pairs",
"=",
"[",
"]",
"if",
"all_pairs",
":",
"positions",
"=",
"np",
".",
"array",
"(",
"[",
"pose",
"[",
":",
"3",
",",
"3",
"]",
"for",
"pose",
"in",
"poses",
"]",
")",
"distances",
"=",
"geometry",
".",
"accumulated_distances",
"(",
"positions",
")",
"for",
"i",
"in",
"range",
"(",
"distances",
".",
"size",
"-",
"1",
")",
":",
"offset",
"=",
"i",
"+",
"1",
"distances_from_here",
"=",
"distances",
"[",
"offset",
":",
"]",
"-",
"distances",
"[",
"i",
"]",
"candidate_index",
"=",
"int",
"(",
"np",
".",
"argmin",
"(",
"np",
".",
"abs",
"(",
"distances_from_here",
"-",
"delta",
")",
")",
")",
"if",
"(",
"np",
".",
"abs",
"(",
"distances_from_here",
"[",
"candidate_index",
"]",
"-",
"delta",
")",
">",
"tol",
")",
":",
"continue",
"id_pairs",
".",
"append",
"(",
"(",
"i",
",",
"candidate_index",
"+",
"offset",
")",
")",
"else",
":",
"ids",
"=",
"[",
"]",
"previous_pose",
"=",
"poses",
"[",
"0",
"]",
"current_path",
"=",
"0.0",
"for",
"i",
",",
"current_pose",
"in",
"enumerate",
"(",
"poses",
")",
":",
"current_path",
"+=",
"float",
"(",
"np",
".",
"linalg",
".",
"norm",
"(",
"current_pose",
"[",
":",
"3",
",",
"3",
"]",
"-",
"previous_pose",
"[",
":",
"3",
",",
"3",
"]",
")",
")",
"previous_pose",
"=",
"current_pose",
"if",
"current_path",
">=",
"delta",
":",
"ids",
".",
"append",
"(",
"i",
")",
"current_path",
"=",
"0.0",
"id_pairs",
"=",
"[",
"(",
"i",
",",
"j",
")",
"for",
"i",
",",
"j",
"in",
"zip",
"(",
"ids",
",",
"ids",
"[",
"1",
":",
"]",
")",
"]",
"return",
"id_pairs"
] |
https://github.com/MichaelGrupp/evo/blob/c65af3b69188aaadbbd7b5f99ac7973d74343d65/evo/core/filters.py#L58-L95
|
|
apple/ccs-calendarserver
|
13c706b985fb728b9aab42dc0fef85aae21921c3
|
contrib/performance/benchmarks/event_change_summary.py
|
python
|
measure
|
(host, port, dtrace, attendeeCount, samples)
|
return _measure(
host, port, dtrace, attendeeCount, samples, "change-summary",
replaceSummary)
|
[] |
def measure(host, port, dtrace, attendeeCount, samples):
return _measure(
host, port, dtrace, attendeeCount, samples, "change-summary",
replaceSummary)
|
[
"def",
"measure",
"(",
"host",
",",
"port",
",",
"dtrace",
",",
"attendeeCount",
",",
"samples",
")",
":",
"return",
"_measure",
"(",
"host",
",",
"port",
",",
"dtrace",
",",
"attendeeCount",
",",
"samples",
",",
"\"change-summary\"",
",",
"replaceSummary",
")"
] |
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/contrib/performance/benchmarks/event_change_summary.py#L25-L28
|
|||
slhck/ffmpeg-normalize
|
654e2f030706f972eea2c57ffc49db419761f360
|
ffmpeg_normalize/_cmd_utils.py
|
python
|
ffmpeg_has_loudnorm
|
()
|
Run feature detection on ffmpeg, returns True if ffmpeg supports
the loudnorm filter
|
Run feature detection on ffmpeg, returns True if ffmpeg supports
the loudnorm filter
|
[
"Run",
"feature",
"detection",
"on",
"ffmpeg",
"returns",
"True",
"if",
"ffmpeg",
"supports",
"the",
"loudnorm",
"filter"
] |
def ffmpeg_has_loudnorm():
"""
Run feature detection on ffmpeg, returns True if ffmpeg supports
the loudnorm filter
"""
cmd_runner = CommandRunner([get_ffmpeg_exe(), "-filters"])
cmd_runner.run_command()
output = cmd_runner.get_output()
if "loudnorm" in output:
return True
else:
logger.error(
"Your ffmpeg version does not support the 'loudnorm' filter. "
"Please make sure you are running ffmpeg v3.1 or above."
)
return False
|
[
"def",
"ffmpeg_has_loudnorm",
"(",
")",
":",
"cmd_runner",
"=",
"CommandRunner",
"(",
"[",
"get_ffmpeg_exe",
"(",
")",
",",
"\"-filters\"",
"]",
")",
"cmd_runner",
".",
"run_command",
"(",
")",
"output",
"=",
"cmd_runner",
".",
"get_output",
"(",
")",
"if",
"\"loudnorm\"",
"in",
"output",
":",
"return",
"True",
"else",
":",
"logger",
".",
"error",
"(",
"\"Your ffmpeg version does not support the 'loudnorm' filter. \"",
"\"Please make sure you are running ffmpeg v3.1 or above.\"",
")",
"return",
"False"
] |
https://github.com/slhck/ffmpeg-normalize/blob/654e2f030706f972eea2c57ffc49db419761f360/ffmpeg_normalize/_cmd_utils.py#L161-L176
|
||
kamalgill/flask-appengine-template
|
11760f83faccbb0d0afe416fc58e67ecfb4643c2
|
src/lib/werkzeug/wrappers.py
|
python
|
ResponseStream.encoding
|
(self)
|
return self.response.charset
|
[] |
def encoding(self):
return self.response.charset
|
[
"def",
"encoding",
"(",
"self",
")",
":",
"return",
"self",
".",
"response",
".",
"charset"
] |
https://github.com/kamalgill/flask-appengine-template/blob/11760f83faccbb0d0afe416fc58e67ecfb4643c2/src/lib/werkzeug/wrappers.py#L1668-L1669
|
|||
istresearch/scrapy-cluster
|
01861c2dca1563aab740417d315cc4ebf9b73f72
|
rest/rest_service.py
|
python
|
RestService._create_consumer
|
(self)
|
Tries to establing the Kafka consumer connection
|
Tries to establing the Kafka consumer connection
|
[
"Tries",
"to",
"establing",
"the",
"Kafka",
"consumer",
"connection"
] |
def _create_consumer(self):
"""Tries to establing the Kafka consumer connection"""
if not self.closed:
try:
self.logger.debug("Creating new kafka consumer using brokers: " +
str(self.settings['KAFKA_HOSTS']) + ' and topic ' +
self.settings['KAFKA_TOPIC_PREFIX'] +
".outbound_firehose")
return KafkaConsumer(
self.settings['KAFKA_TOPIC_PREFIX'] + ".outbound_firehose",
group_id=None,
bootstrap_servers=self.settings['KAFKA_HOSTS'],
consumer_timeout_ms=self.settings['KAFKA_CONSUMER_TIMEOUT'],
auto_offset_reset=self.settings['KAFKA_CONSUMER_AUTO_OFFSET_RESET'],
auto_commit_interval_ms=self.settings['KAFKA_CONSUMER_COMMIT_INTERVAL_MS'],
enable_auto_commit=self.settings['KAFKA_CONSUMER_AUTO_COMMIT_ENABLE'],
max_partition_fetch_bytes=self.settings['KAFKA_CONSUMER_FETCH_MESSAGE_MAX_BYTES'])
except KeyError as e:
self.logger.error('Missing setting named ' + str(e),
{'ex': traceback.format_exc()})
except:
self.logger.error("Couldn't initialize kafka consumer for topic",
{'ex': traceback.format_exc()})
raise
|
[
"def",
"_create_consumer",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"closed",
":",
"try",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Creating new kafka consumer using brokers: \"",
"+",
"str",
"(",
"self",
".",
"settings",
"[",
"'KAFKA_HOSTS'",
"]",
")",
"+",
"' and topic '",
"+",
"self",
".",
"settings",
"[",
"'KAFKA_TOPIC_PREFIX'",
"]",
"+",
"\".outbound_firehose\"",
")",
"return",
"KafkaConsumer",
"(",
"self",
".",
"settings",
"[",
"'KAFKA_TOPIC_PREFIX'",
"]",
"+",
"\".outbound_firehose\"",
",",
"group_id",
"=",
"None",
",",
"bootstrap_servers",
"=",
"self",
".",
"settings",
"[",
"'KAFKA_HOSTS'",
"]",
",",
"consumer_timeout_ms",
"=",
"self",
".",
"settings",
"[",
"'KAFKA_CONSUMER_TIMEOUT'",
"]",
",",
"auto_offset_reset",
"=",
"self",
".",
"settings",
"[",
"'KAFKA_CONSUMER_AUTO_OFFSET_RESET'",
"]",
",",
"auto_commit_interval_ms",
"=",
"self",
".",
"settings",
"[",
"'KAFKA_CONSUMER_COMMIT_INTERVAL_MS'",
"]",
",",
"enable_auto_commit",
"=",
"self",
".",
"settings",
"[",
"'KAFKA_CONSUMER_AUTO_COMMIT_ENABLE'",
"]",
",",
"max_partition_fetch_bytes",
"=",
"self",
".",
"settings",
"[",
"'KAFKA_CONSUMER_FETCH_MESSAGE_MAX_BYTES'",
"]",
")",
"except",
"KeyError",
"as",
"e",
":",
"self",
".",
"logger",
".",
"error",
"(",
"'Missing setting named '",
"+",
"str",
"(",
"e",
")",
",",
"{",
"'ex'",
":",
"traceback",
".",
"format_exc",
"(",
")",
"}",
")",
"except",
":",
"self",
".",
"logger",
".",
"error",
"(",
"\"Couldn't initialize kafka consumer for topic\"",
",",
"{",
"'ex'",
":",
"traceback",
".",
"format_exc",
"(",
")",
"}",
")",
"raise"
] |
https://github.com/istresearch/scrapy-cluster/blob/01861c2dca1563aab740417d315cc4ebf9b73f72/rest/rest_service.py#L402-L426
|
||
taomujian/linbing
|
fe772a58f41e3b046b51a866bdb7e4655abaf51a
|
python/app/thirdparty/dirsearch/thirdparty/jinja2/visitor.py
|
python
|
NodeVisitor.visit
|
(self, node: Node, *args: t.Any, **kwargs: t.Any)
|
return self.generic_visit(node, *args, **kwargs)
|
Visit a node.
|
Visit a node.
|
[
"Visit",
"a",
"node",
"."
] |
def visit(self, node: Node, *args: t.Any, **kwargs: t.Any) -> t.Any:
"""Visit a node."""
f = self.get_visitor(node)
if f is not None:
return f(node, *args, **kwargs)
return self.generic_visit(node, *args, **kwargs)
|
[
"def",
"visit",
"(",
"self",
",",
"node",
":",
"Node",
",",
"*",
"args",
":",
"t",
".",
"Any",
",",
"*",
"*",
"kwargs",
":",
"t",
".",
"Any",
")",
"->",
"t",
".",
"Any",
":",
"f",
"=",
"self",
".",
"get_visitor",
"(",
"node",
")",
"if",
"f",
"is",
"not",
"None",
":",
"return",
"f",
"(",
"node",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"generic_visit",
"(",
"node",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/taomujian/linbing/blob/fe772a58f41e3b046b51a866bdb7e4655abaf51a/python/app/thirdparty/dirsearch/thirdparty/jinja2/visitor.py#L35-L42
|
|
dimagi/commcare-hq
|
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
|
corehq/elastic.py
|
python
|
get_es_export
|
()
|
return es
|
Get a handle to the configured elastic search DB with settings geared towards exports.
Returns an elasticsearch.Elasticsearch instance.
|
Get a handle to the configured elastic search DB with settings geared towards exports.
Returns an elasticsearch.Elasticsearch instance.
|
[
"Get",
"a",
"handle",
"to",
"the",
"configured",
"elastic",
"search",
"DB",
"with",
"settings",
"geared",
"towards",
"exports",
".",
"Returns",
"an",
"elasticsearch",
".",
"Elasticsearch",
"instance",
"."
] |
def get_es_export():
"""
Get a handle to the configured elastic search DB with settings geared towards exports.
Returns an elasticsearch.Elasticsearch instance.
"""
hosts = _es_hosts()
es = Elasticsearch(
hosts,
retry_on_timeout=True,
max_retries=3,
# Timeout in seconds for an elasticsearch query
timeout=300,
serializer=ESJSONSerializer(),
)
return es
|
[
"def",
"get_es_export",
"(",
")",
":",
"hosts",
"=",
"_es_hosts",
"(",
")",
"es",
"=",
"Elasticsearch",
"(",
"hosts",
",",
"retry_on_timeout",
"=",
"True",
",",
"max_retries",
"=",
"3",
",",
"# Timeout in seconds for an elasticsearch query",
"timeout",
"=",
"300",
",",
"serializer",
"=",
"ESJSONSerializer",
"(",
")",
",",
")",
"return",
"es"
] |
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/elastic.py#L72-L86
|
|
tobegit3hub/deep_image_model
|
8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e
|
java_predict_client/src/main/proto/tensorflow/examples/tutorials/mnist/fully_connected_feed.py
|
python
|
do_eval
|
(sess,
eval_correct,
images_placeholder,
labels_placeholder,
data_set)
|
Runs one evaluation against the full epoch of data.
Args:
sess: The session in which the model has been trained.
eval_correct: The Tensor that returns the number of correct predictions.
images_placeholder: The images placeholder.
labels_placeholder: The labels placeholder.
data_set: The set of images and labels to evaluate, from
input_data.read_data_sets().
|
Runs one evaluation against the full epoch of data.
|
[
"Runs",
"one",
"evaluation",
"against",
"the",
"full",
"epoch",
"of",
"data",
"."
] |
def do_eval(sess,
eval_correct,
images_placeholder,
labels_placeholder,
data_set):
"""Runs one evaluation against the full epoch of data.
Args:
sess: The session in which the model has been trained.
eval_correct: The Tensor that returns the number of correct predictions.
images_placeholder: The images placeholder.
labels_placeholder: The labels placeholder.
data_set: The set of images and labels to evaluate, from
input_data.read_data_sets().
"""
# And run one epoch of eval.
true_count = 0 # Counts the number of correct predictions.
steps_per_epoch = data_set.num_examples // FLAGS.batch_size
num_examples = steps_per_epoch * FLAGS.batch_size
for step in xrange(steps_per_epoch):
feed_dict = fill_feed_dict(data_set,
images_placeholder,
labels_placeholder)
true_count += sess.run(eval_correct, feed_dict=feed_dict)
precision = true_count / num_examples
print(' Num examples: %d Num correct: %d Precision @ 1: %0.04f' %
(num_examples, true_count, precision))
|
[
"def",
"do_eval",
"(",
"sess",
",",
"eval_correct",
",",
"images_placeholder",
",",
"labels_placeholder",
",",
"data_set",
")",
":",
"# And run one epoch of eval.",
"true_count",
"=",
"0",
"# Counts the number of correct predictions.",
"steps_per_epoch",
"=",
"data_set",
".",
"num_examples",
"//",
"FLAGS",
".",
"batch_size",
"num_examples",
"=",
"steps_per_epoch",
"*",
"FLAGS",
".",
"batch_size",
"for",
"step",
"in",
"xrange",
"(",
"steps_per_epoch",
")",
":",
"feed_dict",
"=",
"fill_feed_dict",
"(",
"data_set",
",",
"images_placeholder",
",",
"labels_placeholder",
")",
"true_count",
"+=",
"sess",
".",
"run",
"(",
"eval_correct",
",",
"feed_dict",
"=",
"feed_dict",
")",
"precision",
"=",
"true_count",
"/",
"num_examples",
"print",
"(",
"' Num examples: %d Num correct: %d Precision @ 1: %0.04f'",
"%",
"(",
"num_examples",
",",
"true_count",
",",
"precision",
")",
")"
] |
https://github.com/tobegit3hub/deep_image_model/blob/8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e/java_predict_client/src/main/proto/tensorflow/examples/tutorials/mnist/fully_connected_feed.py#L87-L113
|
||
idanr1986/cuckoo-droid
|
1350274639473d3d2b0ac740cae133ca53ab7444
|
analyzer/android/lib/api/androguard/dvm.py
|
python
|
FieldIdItem.get_class_name
|
(self)
|
return self.class_idx_value
|
Return the class name of the field
:rtype: string
|
Return the class name of the field
|
[
"Return",
"the",
"class",
"name",
"of",
"the",
"field"
] |
def get_class_name(self) :
"""
Return the class name of the field
:rtype: string
"""
return self.class_idx_value
|
[
"def",
"get_class_name",
"(",
"self",
")",
":",
"return",
"self",
".",
"class_idx_value"
] |
https://github.com/idanr1986/cuckoo-droid/blob/1350274639473d3d2b0ac740cae133ca53ab7444/analyzer/android/lib/api/androguard/dvm.py#L2155-L2161
|
|
FSecureLABS/drozer
|
df11e6e63fbaefa9b58ed1e42533ddf76241d7e1
|
src/drozer/repoman/installer.py
|
python
|
ModuleInstaller.__read_local_module
|
(self, module)
|
return fs.read(module)
|
Read a module file from the local filesystem, and return the source.
|
Read a module file from the local filesystem, and return the source.
|
[
"Read",
"a",
"module",
"file",
"from",
"the",
"local",
"filesystem",
"and",
"return",
"the",
"source",
"."
] |
def __read_local_module(self, module):
"""
Read a module file from the local filesystem, and return the source.
"""
return fs.read(module)
|
[
"def",
"__read_local_module",
"(",
"self",
",",
"module",
")",
":",
"return",
"fs",
".",
"read",
"(",
"module",
")"
] |
https://github.com/FSecureLABS/drozer/blob/df11e6e63fbaefa9b58ed1e42533ddf76241d7e1/src/drozer/repoman/installer.py#L168-L173
|
|
F8LEFT/DecLLVM
|
d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c
|
python/idaapi.py
|
python
|
idainfo.get_proc_name
|
(self, *args)
|
return _idaapi.idainfo_get_proc_name(self, *args)
|
get_proc_name(self) -> char *
|
get_proc_name(self) -> char *
|
[
"get_proc_name",
"(",
"self",
")",
"-",
">",
"char",
"*"
] |
def get_proc_name(self, *args):
"""
get_proc_name(self) -> char *
"""
return _idaapi.idainfo_get_proc_name(self, *args)
|
[
"def",
"get_proc_name",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_idaapi",
".",
"idainfo_get_proc_name",
"(",
"self",
",",
"*",
"args",
")"
] |
https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idaapi.py#L2676-L2680
|
|
LabPy/lantz
|
3e878e3f765a4295b0089d04e241d4beb7b8a65b
|
lantz/drivers/legacy/andor/ccd.py
|
python
|
CCD.readout_mode
|
(self)
|
return self.readout_mode_mode
|
This function will set the readout mode to be used on the subsequent
acquisitions.
|
This function will set the readout mode to be used on the subsequent
acquisitions.
|
[
"This",
"function",
"will",
"set",
"the",
"readout",
"mode",
"to",
"be",
"used",
"on",
"the",
"subsequent",
"acquisitions",
"."
] |
def readout_mode(self):
""" This function will set the readout mode to be used on the subsequent
acquisitions.
"""
return self.readout_mode_mode
|
[
"def",
"readout_mode",
"(",
"self",
")",
":",
"return",
"self",
".",
"readout_mode_mode"
] |
https://github.com/LabPy/lantz/blob/3e878e3f765a4295b0089d04e241d4beb7b8a65b/lantz/drivers/legacy/andor/ccd.py#L892-L896
|
|
wmayner/pyphi
|
299fccd4a8152dcfa4bb989d7d739e245343b0a5
|
pyphi/network.py
|
python
|
Network._build_cm
|
(self, cm)
|
return (cm, utils.np_hash(cm))
|
Convert the passed CM to the proper format, or construct the
unitary CM if none was provided.
|
Convert the passed CM to the proper format, or construct the
unitary CM if none was provided.
|
[
"Convert",
"the",
"passed",
"CM",
"to",
"the",
"proper",
"format",
"or",
"construct",
"the",
"unitary",
"CM",
"if",
"none",
"was",
"provided",
"."
] |
def _build_cm(self, cm):
"""Convert the passed CM to the proper format, or construct the
unitary CM if none was provided.
"""
if cm is None:
# Assume all are connected.
cm = np.ones((self.size, self.size))
else:
cm = np.array(cm)
utils.np_immutable(cm)
return (cm, utils.np_hash(cm))
|
[
"def",
"_build_cm",
"(",
"self",
",",
"cm",
")",
":",
"if",
"cm",
"is",
"None",
":",
"# Assume all are connected.",
"cm",
"=",
"np",
".",
"ones",
"(",
"(",
"self",
".",
"size",
",",
"self",
".",
"size",
")",
")",
"else",
":",
"cm",
"=",
"np",
".",
"array",
"(",
"cm",
")",
"utils",
".",
"np_immutable",
"(",
"cm",
")",
"return",
"(",
"cm",
",",
"utils",
".",
"np_hash",
"(",
"cm",
")",
")"
] |
https://github.com/wmayner/pyphi/blob/299fccd4a8152dcfa4bb989d7d739e245343b0a5/pyphi/network.py#L104-L116
|
|
openhatch/oh-mainline
|
ce29352a034e1223141dcc2f317030bbc3359a51
|
vendor/packages/twisted/twisted/internet/endpoints.py
|
python
|
_WrappingFactory.buildProtocol
|
(self, addr)
|
Proxy C{buildProtocol} to our C{self._wrappedFactory} or errback
the C{self._onConnection} L{Deferred}.
@return: An instance of L{_WrappingProtocol} or C{None}
|
Proxy C{buildProtocol} to our C{self._wrappedFactory} or errback
the C{self._onConnection} L{Deferred}.
|
[
"Proxy",
"C",
"{",
"buildProtocol",
"}",
"to",
"our",
"C",
"{",
"self",
".",
"_wrappedFactory",
"}",
"or",
"errback",
"the",
"C",
"{",
"self",
".",
"_onConnection",
"}",
"L",
"{",
"Deferred",
"}",
"."
] |
def buildProtocol(self, addr):
"""
Proxy C{buildProtocol} to our C{self._wrappedFactory} or errback
the C{self._onConnection} L{Deferred}.
@return: An instance of L{_WrappingProtocol} or C{None}
"""
try:
proto = self._wrappedFactory.buildProtocol(addr)
except:
self._onConnection.errback()
else:
return self.protocol(self._onConnection, proto)
|
[
"def",
"buildProtocol",
"(",
"self",
",",
"addr",
")",
":",
"try",
":",
"proto",
"=",
"self",
".",
"_wrappedFactory",
".",
"buildProtocol",
"(",
"addr",
")",
"except",
":",
"self",
".",
"_onConnection",
".",
"errback",
"(",
")",
"else",
":",
"return",
"self",
".",
"protocol",
"(",
"self",
".",
"_onConnection",
",",
"proto",
")"
] |
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/twisted/twisted/internet/endpoints.py#L124-L136
|
||
dbt-labs/dbt-core
|
e943b9fc842535e958ef4fd0b8703adc91556bc6
|
core/dbt/deps/git.py
|
python
|
GitPackageMixin.name
|
(self)
|
return self.git
|
[] |
def name(self):
return self.git
|
[
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"git"
] |
https://github.com/dbt-labs/dbt-core/blob/e943b9fc842535e958ef4fd0b8703adc91556bc6/core/dbt/deps/git.py#L32-L33
|
|||
ctxis/canape
|
5f0e03424577296bcc60c2008a60a98ec5307e4b
|
CANAPE.Scripting/Lib/mailbox.py
|
python
|
_singlefileMailbox.add
|
(self, message)
|
return self._next_key - 1
|
Add message and return assigned key.
|
Add message and return assigned key.
|
[
"Add",
"message",
"and",
"return",
"assigned",
"key",
"."
] |
def add(self, message):
"""Add message and return assigned key."""
self._lookup()
self._toc[self._next_key] = self._append_message(message)
self._next_key += 1
self._pending = True
return self._next_key - 1
|
[
"def",
"add",
"(",
"self",
",",
"message",
")",
":",
"self",
".",
"_lookup",
"(",
")",
"self",
".",
"_toc",
"[",
"self",
".",
"_next_key",
"]",
"=",
"self",
".",
"_append_message",
"(",
"message",
")",
"self",
".",
"_next_key",
"+=",
"1",
"self",
".",
"_pending",
"=",
"True",
"return",
"self",
".",
"_next_key",
"-",
"1"
] |
https://github.com/ctxis/canape/blob/5f0e03424577296bcc60c2008a60a98ec5307e4b/CANAPE.Scripting/Lib/mailbox.py#L570-L576
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.