repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
psss/did | did/plugins/wiki.py | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/wiki.py#L46-L53 | def header(self):
""" Show summary header. """
# Different header for wiki: Updates on xxx: x changes of y pages
item(
"{0}: {1} change{2} of {3} page{4}".format(
self.name, self.changes, "" if self.changes == 1 else "s",
len(self.stats), "" if len(sel... | [
"def",
"header",
"(",
"self",
")",
":",
"# Different header for wiki: Updates on xxx: x changes of y pages",
"item",
"(",
"\"{0}: {1} change{2} of {3} page{4}\"",
".",
"format",
"(",
"self",
".",
"name",
",",
"self",
".",
"changes",
",",
"\"\"",
"if",
"self",
".",
"... | Show summary header. | [
"Show",
"summary",
"header",
"."
] | python | train |
jtmoulia/switchboard-python | switchboard/__init__.py | https://github.com/jtmoulia/switchboard-python/blob/c9b0cb74cb12a64385465091be633e78d39f08b1/switchboard/__init__.py#L154-L163 | def _get_cmds_id(*cmds):
"""
Returns an identifier for a group of partially tagged commands.
If there are no tagged commands, returns None.
"""
tags = [cmd[2] if len(cmd) == 3 else None for cmd in cmds]
if [tag for tag in tags if tag != None]:
return tuple(tags)
else:
return ... | [
"def",
"_get_cmds_id",
"(",
"*",
"cmds",
")",
":",
"tags",
"=",
"[",
"cmd",
"[",
"2",
"]",
"if",
"len",
"(",
"cmd",
")",
"==",
"3",
"else",
"None",
"for",
"cmd",
"in",
"cmds",
"]",
"if",
"[",
"tag",
"for",
"tag",
"in",
"tags",
"if",
"tag",
"!... | Returns an identifier for a group of partially tagged commands.
If there are no tagged commands, returns None. | [
"Returns",
"an",
"identifier",
"for",
"a",
"group",
"of",
"partially",
"tagged",
"commands",
".",
"If",
"there",
"are",
"no",
"tagged",
"commands",
"returns",
"None",
"."
] | python | train |
pmacosta/ptrie | ptrie/ptrie.py | https://github.com/pmacosta/ptrie/blob/c176d3ee810b7b5243c7ff2bbf2f1af0b0fff2a8/ptrie/ptrie.py#L190-L213 | def _delete_subtree(self, nodes):
"""
Delete subtree private method.
No argument validation and usage of getter/setter private methods is
used for speed
"""
nodes = nodes if isinstance(nodes, list) else [nodes]
iobj = [
(self._db[node]["parent"], node... | [
"def",
"_delete_subtree",
"(",
"self",
",",
"nodes",
")",
":",
"nodes",
"=",
"nodes",
"if",
"isinstance",
"(",
"nodes",
",",
"list",
")",
"else",
"[",
"nodes",
"]",
"iobj",
"=",
"[",
"(",
"self",
".",
"_db",
"[",
"node",
"]",
"[",
"\"parent\"",
"]"... | Delete subtree private method.
No argument validation and usage of getter/setter private methods is
used for speed | [
"Delete",
"subtree",
"private",
"method",
"."
] | python | train |
Nekmo/amazon-dash | amazon_dash/config.py | https://github.com/Nekmo/amazon-dash/blob/0e2bdc24ff8ea32cecb2f5f54f5cc1c0f99c197b/amazon_dash/config.py#L159-L172 | def bitperm(s, perm, pos):
"""Returns zero if there are no permissions for a bit of the perm. of a file. Otherwise it returns a positive value
:param os.stat_result s: os.stat(file) object
:param str perm: R (Read) or W (Write) or X (eXecute)
:param str pos: USR (USeR) or GRP (GRouP) or OTH (OTHer)
... | [
"def",
"bitperm",
"(",
"s",
",",
"perm",
",",
"pos",
")",
":",
"perm",
"=",
"perm",
".",
"upper",
"(",
")",
"pos",
"=",
"pos",
".",
"upper",
"(",
")",
"assert",
"perm",
"in",
"[",
"'R'",
",",
"'W'",
",",
"'X'",
"]",
"assert",
"pos",
"in",
"["... | Returns zero if there are no permissions for a bit of the perm. of a file. Otherwise it returns a positive value
:param os.stat_result s: os.stat(file) object
:param str perm: R (Read) or W (Write) or X (eXecute)
:param str pos: USR (USeR) or GRP (GRouP) or OTH (OTHer)
:return: mask value
:rtype: i... | [
"Returns",
"zero",
"if",
"there",
"are",
"no",
"permissions",
"for",
"a",
"bit",
"of",
"the",
"perm",
".",
"of",
"a",
"file",
".",
"Otherwise",
"it",
"returns",
"a",
"positive",
"value"
] | python | test |
zetaops/zengine | zengine/lib/utils.py | https://github.com/zetaops/zengine/blob/b5bc32d3b37bca799f8985be916f04528ac79e4a/zengine/lib/utils.py#L34-L43 | def to_safe_str(s):
"""
converts some (tr) non-ascii chars to ascii counterparts,
then return the result as lowercase
"""
# TODO: This is insufficient as it doesn't do anything for other non-ascii chars
return re.sub(r'[^0-9a-zA-Z]+', '_', s.strip().replace(u'ğ', 'g').replace(u'ö', 'o').replace(... | [
"def",
"to_safe_str",
"(",
"s",
")",
":",
"# TODO: This is insufficient as it doesn't do anything for other non-ascii chars",
"return",
"re",
".",
"sub",
"(",
"r'[^0-9a-zA-Z]+'",
",",
"'_'",
",",
"s",
".",
"strip",
"(",
")",
".",
"replace",
"(",
"u'ğ',",
" ",
"g')... | converts some (tr) non-ascii chars to ascii counterparts,
then return the result as lowercase | [
"converts",
"some",
"(",
"tr",
")",
"non",
"-",
"ascii",
"chars",
"to",
"ascii",
"counterparts",
"then",
"return",
"the",
"result",
"as",
"lowercase"
] | python | train |
pkgw/pwkit | pwkit/io.py | https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/io.py#L125-L131 | def make_path_func (*baseparts):
"""Return a function that joins paths onto some base directory."""
from os.path import join
base = join (*baseparts)
def path_func (*args):
return join (base, *args)
return path_func | [
"def",
"make_path_func",
"(",
"*",
"baseparts",
")",
":",
"from",
"os",
".",
"path",
"import",
"join",
"base",
"=",
"join",
"(",
"*",
"baseparts",
")",
"def",
"path_func",
"(",
"*",
"args",
")",
":",
"return",
"join",
"(",
"base",
",",
"*",
"args",
... | Return a function that joins paths onto some base directory. | [
"Return",
"a",
"function",
"that",
"joins",
"paths",
"onto",
"some",
"base",
"directory",
"."
] | python | train |
joke2k/django-environ | environ/environ.py | https://github.com/joke2k/django-environ/blob/c2620021614557abe197578f99deeef42af3e082/environ/environ.py#L157-L161 | def int(self, var, default=NOTSET):
"""
:rtype: int
"""
return self.get_value(var, cast=int, default=default) | [
"def",
"int",
"(",
"self",
",",
"var",
",",
"default",
"=",
"NOTSET",
")",
":",
"return",
"self",
".",
"get_value",
"(",
"var",
",",
"cast",
"=",
"int",
",",
"default",
"=",
"default",
")"
] | :rtype: int | [
":",
"rtype",
":",
"int"
] | python | train |
Azure/azure-cosmos-python | azure/cosmos/routing/collection_routing_map.py | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/routing/collection_routing_map.py#L74-L94 | def get_range_by_effective_partition_key(self, effective_partition_key_value):
"""Gets the range containing the given partition key
:param str effective_partition_key_value:
The partition key value.
:return:
The partition key range.
:rtype: dict
"""
... | [
"def",
"get_range_by_effective_partition_key",
"(",
"self",
",",
"effective_partition_key_value",
")",
":",
"if",
"_CollectionRoutingMap",
".",
"MinimumInclusiveEffectivePartitionKey",
"==",
"effective_partition_key_value",
":",
"return",
"self",
".",
"_orderedPartitionKeyRanges"... | Gets the range containing the given partition key
:param str effective_partition_key_value:
The partition key value.
:return:
The partition key range.
:rtype: dict | [
"Gets",
"the",
"range",
"containing",
"the",
"given",
"partition",
"key"
] | python | train |
waqasbhatti/astrobase | astrobase/lcproc/checkplotgen.py | https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/checkplotgen.py#L1239-L1483 | def parallel_cp_pfdir(pfpickledir,
outdir,
lcbasedir,
pfpickleglob='periodfinding-*.pkl*',
lclistpkl=None,
cprenorm=False,
nbrradiusarcsec=60.0,
maxnumneighbors=5,
... | [
"def",
"parallel_cp_pfdir",
"(",
"pfpickledir",
",",
"outdir",
",",
"lcbasedir",
",",
"pfpickleglob",
"=",
"'periodfinding-*.pkl*'",
",",
"lclistpkl",
"=",
"None",
",",
"cprenorm",
"=",
"False",
",",
"nbrradiusarcsec",
"=",
"60.0",
",",
"maxnumneighbors",
"=",
"... | This drives the parallel execution of `runcp` for a directory of
periodfinding pickles.
Parameters
----------
pfpickledir : str
This is the directory containing all of the period-finding pickles to
process.
outdir : str
The directory the checkplot pickles will be written t... | [
"This",
"drives",
"the",
"parallel",
"execution",
"of",
"runcp",
"for",
"a",
"directory",
"of",
"periodfinding",
"pickles",
"."
] | python | valid |
CiscoDevNet/webexteamssdk | webexteamssdk/utils.py | https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/utils.py#L100-L110 | def is_web_url(string):
"""Check to see if string is an validly-formatted web url."""
assert isinstance(string, basestring)
parsed_url = urllib.parse.urlparse(string)
return (
(
parsed_url.scheme.lower() == 'http'
or parsed_url.scheme.lower() == 'https'
)
... | [
"def",
"is_web_url",
"(",
"string",
")",
":",
"assert",
"isinstance",
"(",
"string",
",",
"basestring",
")",
"parsed_url",
"=",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"string",
")",
"return",
"(",
"(",
"parsed_url",
".",
"scheme",
".",
"lower",
"(... | Check to see if string is an validly-formatted web url. | [
"Check",
"to",
"see",
"if",
"string",
"is",
"an",
"validly",
"-",
"formatted",
"web",
"url",
"."
] | python | test |
matrix-org/matrix-python-sdk | matrix_client/room.py | https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L614-L622 | def set_guest_access(self, allow_guests):
"""Set whether guests can join the room and return True if successful."""
guest_access = "can_join" if allow_guests else "forbidden"
try:
self.client.api.set_guest_access(self.room_id, guest_access)
self.guest_access = allow_guest... | [
"def",
"set_guest_access",
"(",
"self",
",",
"allow_guests",
")",
":",
"guest_access",
"=",
"\"can_join\"",
"if",
"allow_guests",
"else",
"\"forbidden\"",
"try",
":",
"self",
".",
"client",
".",
"api",
".",
"set_guest_access",
"(",
"self",
".",
"room_id",
",",... | Set whether guests can join the room and return True if successful. | [
"Set",
"whether",
"guests",
"can",
"join",
"the",
"room",
"and",
"return",
"True",
"if",
"successful",
"."
] | python | train |
tarbell-project/tarbell | tarbell/app.py | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/app.py#L487-L511 | def get_context_from_csv(self):
"""
Open CONTEXT_SOURCE_FILE, parse and return a context
"""
if re.search('^(http|https)://', self.project.CONTEXT_SOURCE_FILE):
data = requests.get(self.project.CONTEXT_SOURCE_FILE)
reader = csv.reader(
data.iter_li... | [
"def",
"get_context_from_csv",
"(",
"self",
")",
":",
"if",
"re",
".",
"search",
"(",
"'^(http|https)://'",
",",
"self",
".",
"project",
".",
"CONTEXT_SOURCE_FILE",
")",
":",
"data",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"project",
".",
"CONTEXT_S... | Open CONTEXT_SOURCE_FILE, parse and return a context | [
"Open",
"CONTEXT_SOURCE_FILE",
"parse",
"and",
"return",
"a",
"context"
] | python | train |
kipe/enocean | enocean/protocol/eep.py | https://github.com/kipe/enocean/blob/99fa03f47004eef74c7987545c33ecd01af0de07/enocean/protocol/eep.py#L70-L89 | def _get_value(self, source, bitarray):
''' Get value, based on the data in XML '''
raw_value = self._get_raw(source, bitarray)
rng = source.find('range')
rng_min = float(rng.find('min').text)
rng_max = float(rng.find('max').text)
scl = source.find('scale')
scl_... | [
"def",
"_get_value",
"(",
"self",
",",
"source",
",",
"bitarray",
")",
":",
"raw_value",
"=",
"self",
".",
"_get_raw",
"(",
"source",
",",
"bitarray",
")",
"rng",
"=",
"source",
".",
"find",
"(",
"'range'",
")",
"rng_min",
"=",
"float",
"(",
"rng",
"... | Get value, based on the data in XML | [
"Get",
"value",
"based",
"on",
"the",
"data",
"in",
"XML"
] | python | train |
SheffieldML/GPy | GPy/models/state_space_main.py | https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/models/state_space_main.py#L244-L275 | def R_isrk(self, k):
"""
Function returns the inverse square root of R matrix on step k.
"""
ind = int(self.index[self.R_time_var_index, k])
R = self.R[:, :, ind]
if (R.shape[0] == 1): # 1-D case handle simplier. No storage
# of the result, just compute it e... | [
"def",
"R_isrk",
"(",
"self",
",",
"k",
")",
":",
"ind",
"=",
"int",
"(",
"self",
".",
"index",
"[",
"self",
".",
"R_time_var_index",
",",
"k",
"]",
")",
"R",
"=",
"self",
".",
"R",
"[",
":",
",",
":",
",",
"ind",
"]",
"if",
"(",
"R",
".",
... | Function returns the inverse square root of R matrix on step k. | [
"Function",
"returns",
"the",
"inverse",
"square",
"root",
"of",
"R",
"matrix",
"on",
"step",
"k",
"."
] | python | train |
seyriz/taiga-contrib-google-auth | back/taiga_contrib_google_auth/services.py | https://github.com/seyriz/taiga-contrib-google-auth/blob/e9fb5d062027a055e09f7614aa2e48eab7a8604b/back/taiga_contrib_google_auth/services.py#L36-L72 | def google_register(username:str, email:str, full_name:str, google_id:int, bio:str, token:str=None):
"""
Register a new user from google.
This can raise `exc.IntegrityError` exceptions in
case of conflics found.
:returns: User
"""
auth_data_model = apps.get_model("users", "AuthData")
use... | [
"def",
"google_register",
"(",
"username",
":",
"str",
",",
"email",
":",
"str",
",",
"full_name",
":",
"str",
",",
"google_id",
":",
"int",
",",
"bio",
":",
"str",
",",
"token",
":",
"str",
"=",
"None",
")",
":",
"auth_data_model",
"=",
"apps",
".",... | Register a new user from google.
This can raise `exc.IntegrityError` exceptions in
case of conflics found.
:returns: User | [
"Register",
"a",
"new",
"user",
"from",
"google",
".",
"This",
"can",
"raise",
"exc",
".",
"IntegrityError",
"exceptions",
"in",
"case",
"of",
"conflics",
"found",
".",
":",
"returns",
":",
"User"
] | python | train |
bcbio/bcbio-nextgen | bcbio/broad/metrics.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/broad/metrics.py#L50-L72 | def extract_metrics(self, metrics_files):
"""Return summary information for a lane of metrics files.
"""
extension_maps = dict(
align_metrics=(self._parse_align_metrics, "AL"),
dup_metrics=(self._parse_dup_metrics, "DUP"),
hs_metrics=(self._parse_hybrid_metric... | [
"def",
"extract_metrics",
"(",
"self",
",",
"metrics_files",
")",
":",
"extension_maps",
"=",
"dict",
"(",
"align_metrics",
"=",
"(",
"self",
".",
"_parse_align_metrics",
",",
"\"AL\"",
")",
",",
"dup_metrics",
"=",
"(",
"self",
".",
"_parse_dup_metrics",
",",... | Return summary information for a lane of metrics files. | [
"Return",
"summary",
"information",
"for",
"a",
"lane",
"of",
"metrics",
"files",
"."
] | python | train |
ciena/afkak | afkak/producer.py | https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/producer.py#L451-L481 | def _cancel_send_messages(self, d):
"""Cancel a `send_messages` request
First check if the request is in a waiting batch, of so, great, remove
it from the batch. If it's not found, we errback() the deferred and
the downstream processing steps take care of aborting further
process... | [
"def",
"_cancel_send_messages",
"(",
"self",
",",
"d",
")",
":",
"# Is the request in question in an unsent batch?",
"for",
"req",
"in",
"self",
".",
"_batch_reqs",
":",
"if",
"req",
".",
"deferred",
"==",
"d",
":",
"# Found the request, remove it and return.",
"msgs"... | Cancel a `send_messages` request
First check if the request is in a waiting batch, of so, great, remove
it from the batch. If it's not found, we errback() the deferred and
the downstream processing steps take care of aborting further
processing.
We check if there's a current _bat... | [
"Cancel",
"a",
"send_messages",
"request",
"First",
"check",
"if",
"the",
"request",
"is",
"in",
"a",
"waiting",
"batch",
"of",
"so",
"great",
"remove",
"it",
"from",
"the",
"batch",
".",
"If",
"it",
"s",
"not",
"found",
"we",
"errback",
"()",
"the",
"... | python | train |
ForensicArtifacts/artifacts | tools/stats.py | https://github.com/ForensicArtifacts/artifacts/blob/044a63bfb4448af33d085c69066c80f9505ae7ca/tools/stats.py#L114-L120 | def PrintStats(self):
"""Build stats and print in MarkDown format."""
self.BuildStats()
self.PrintSummaryTable()
self.PrintSourceTypeTable()
self.PrintOSTable()
self.PrintLabelTable() | [
"def",
"PrintStats",
"(",
"self",
")",
":",
"self",
".",
"BuildStats",
"(",
")",
"self",
".",
"PrintSummaryTable",
"(",
")",
"self",
".",
"PrintSourceTypeTable",
"(",
")",
"self",
".",
"PrintOSTable",
"(",
")",
"self",
".",
"PrintLabelTable",
"(",
")"
] | Build stats and print in MarkDown format. | [
"Build",
"stats",
"and",
"print",
"in",
"MarkDown",
"format",
"."
] | python | train |
spacetelescope/stsci.tools | lib/stsci/tools/wcsutil.py | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/wcsutil.py#L824-L864 | def archive(self,prepend=None,overwrite=no,quiet=yes):
""" Create backup copies of the WCS keywords with the given prepended
string.
If backup keywords are already present, only update them if
'overwrite' is set to 'yes', otherwise, do warn the user and do nothing.
... | [
"def",
"archive",
"(",
"self",
",",
"prepend",
"=",
"None",
",",
"overwrite",
"=",
"no",
",",
"quiet",
"=",
"yes",
")",
":",
"# Verify that existing backup values are not overwritten accidentally.",
"if",
"len",
"(",
"list",
"(",
"self",
".",
"backup",
".",
"k... | Create backup copies of the WCS keywords with the given prepended
string.
If backup keywords are already present, only update them if
'overwrite' is set to 'yes', otherwise, do warn the user and do nothing.
Set the WCSDATE at this time as well. | [
"Create",
"backup",
"copies",
"of",
"the",
"WCS",
"keywords",
"with",
"the",
"given",
"prepended",
"string",
".",
"If",
"backup",
"keywords",
"are",
"already",
"present",
"only",
"update",
"them",
"if",
"overwrite",
"is",
"set",
"to",
"yes",
"otherwise",
"do... | python | train |
theislab/scanpy | scanpy/readwrite.py | https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/readwrite.py#L93-L135 | def read_10x_h5(filename, genome=None, gex_only=True) -> AnnData:
"""Read 10x-Genomics-formatted hdf5 file.
Parameters
----------
filename : `str` | :class:`~pathlib.Path`
Filename.
genome : `str`, optional (default: ``None``)
Filter expression to this genes within this genome. For ... | [
"def",
"read_10x_h5",
"(",
"filename",
",",
"genome",
"=",
"None",
",",
"gex_only",
"=",
"True",
")",
"->",
"AnnData",
":",
"logg",
".",
"info",
"(",
"'reading'",
",",
"filename",
",",
"r",
"=",
"True",
",",
"end",
"=",
"' '",
")",
"with",
"tables",
... | Read 10x-Genomics-formatted hdf5 file.
Parameters
----------
filename : `str` | :class:`~pathlib.Path`
Filename.
genome : `str`, optional (default: ``None``)
Filter expression to this genes within this genome. For legacy 10x h5
files, this must be provided if the data contains m... | [
"Read",
"10x",
"-",
"Genomics",
"-",
"formatted",
"hdf5",
"file",
"."
] | python | train |
GetmeUK/MongoFrames | mongoframes/frames.py | https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/frames.py#L95-L103 | def _path_to_keys(cls, path):
"""Return a list of keys for a given path"""
# Paths are cached for performance
keys = _BaseFrame._path_to_keys_cache.get(path)
if keys is None:
keys = _BaseFrame._path_to_keys_cache[path] = path.split('.')
return keys | [
"def",
"_path_to_keys",
"(",
"cls",
",",
"path",
")",
":",
"# Paths are cached for performance",
"keys",
"=",
"_BaseFrame",
".",
"_path_to_keys_cache",
".",
"get",
"(",
"path",
")",
"if",
"keys",
"is",
"None",
":",
"keys",
"=",
"_BaseFrame",
".",
"_path_to_key... | Return a list of keys for a given path | [
"Return",
"a",
"list",
"of",
"keys",
"for",
"a",
"given",
"path"
] | python | train |
awesto/djangoshop-paypal | shop_paypal/payment.py | https://github.com/awesto/djangoshop-paypal/blob/d1db892304869fc9b182404db1d6ef214fafe2a7/shop_paypal/payment.py#L48-L95 | def get_payment_request(self, cart, request):
"""
From the given request, redirect onto the checkout view, hosted by PayPal.
"""
shop_ns = resolve(request.path).namespace
return_url = reverse('{}:{}:return'.format(shop_ns, self.namespace))
cancel_url = reverse('{}:{}:canc... | [
"def",
"get_payment_request",
"(",
"self",
",",
"cart",
",",
"request",
")",
":",
"shop_ns",
"=",
"resolve",
"(",
"request",
".",
"path",
")",
".",
"namespace",
"return_url",
"=",
"reverse",
"(",
"'{}:{}:return'",
".",
"format",
"(",
"shop_ns",
",",
"self"... | From the given request, redirect onto the checkout view, hosted by PayPal. | [
"From",
"the",
"given",
"request",
"redirect",
"onto",
"the",
"checkout",
"view",
"hosted",
"by",
"PayPal",
"."
] | python | train |
kylef/maintain | maintain/release/aggregate.py | https://github.com/kylef/maintain/blob/4b60e6c52accb4a7faf0d7255a7079087d3ecee0/maintain/release/aggregate.py#L20-L35 | def releasers(cls):
"""
Returns all of the supported releasers.
"""
return [
HookReleaser,
VersionFileReleaser,
PythonReleaser,
CocoaPodsReleaser,
NPMReleaser,
CReleaser,
ChangelogReleaser,
G... | [
"def",
"releasers",
"(",
"cls",
")",
":",
"return",
"[",
"HookReleaser",
",",
"VersionFileReleaser",
",",
"PythonReleaser",
",",
"CocoaPodsReleaser",
",",
"NPMReleaser",
",",
"CReleaser",
",",
"ChangelogReleaser",
",",
"GitHubReleaser",
",",
"GitReleaser",
",",
"]... | Returns all of the supported releasers. | [
"Returns",
"all",
"of",
"the",
"supported",
"releasers",
"."
] | python | train |
EpistasisLab/scikit-rebate | skrebate/scoring_utils.py | https://github.com/EpistasisLab/scikit-rebate/blob/67dab51a7525fa5d076b059f1e6f8cff7481c1ef/skrebate/scoring_utils.py#L352-L358 | def ReliefF_compute_scores(inst, attr, nan_entries, num_attributes, mcmap, NN, headers, class_type, X, y, labels_std, data_type):
""" Unique scoring procedure for ReliefF algorithm. Scoring based on k nearest hits and misses of current target instance. """
scores = np.zeros(num_attributes)
for feature_nu... | [
"def",
"ReliefF_compute_scores",
"(",
"inst",
",",
"attr",
",",
"nan_entries",
",",
"num_attributes",
",",
"mcmap",
",",
"NN",
",",
"headers",
",",
"class_type",
",",
"X",
",",
"y",
",",
"labels_std",
",",
"data_type",
")",
":",
"scores",
"=",
"np",
".",... | Unique scoring procedure for ReliefF algorithm. Scoring based on k nearest hits and misses of current target instance. | [
"Unique",
"scoring",
"procedure",
"for",
"ReliefF",
"algorithm",
".",
"Scoring",
"based",
"on",
"k",
"nearest",
"hits",
"and",
"misses",
"of",
"current",
"target",
"instance",
"."
] | python | train |
ViiSiX/FlaskRedislite | flask_redislite.py | https://github.com/ViiSiX/FlaskRedislite/blob/01bc9fbbeb415aac621c7a9cc091a666e728e651/flask_redislite.py#L150-L158 | def collection(self):
"""Return the redis-collection instance."""
if not self.include_collections:
return None
ctx = stack.top
if ctx is not None:
if not hasattr(ctx, 'redislite_collection'):
ctx.redislite_collection = Collection(redis=self.connect... | [
"def",
"collection",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"include_collections",
":",
"return",
"None",
"ctx",
"=",
"stack",
".",
"top",
"if",
"ctx",
"is",
"not",
"None",
":",
"if",
"not",
"hasattr",
"(",
"ctx",
",",
"'redislite_collection'",... | Return the redis-collection instance. | [
"Return",
"the",
"redis",
"-",
"collection",
"instance",
"."
] | python | train |
rameshg87/pyremotevbox | pyremotevbox/ZSI/writer.py | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/writer.py#L154-L161 | def Known(self, obj):
'''Seen this object (known by its id()? Return 1 if so,
otherwise add it to our memory and return 0.
'''
obj = _get_idstr(obj)
if obj in self.memo: return 1
self.memo.append(obj)
return 0 | [
"def",
"Known",
"(",
"self",
",",
"obj",
")",
":",
"obj",
"=",
"_get_idstr",
"(",
"obj",
")",
"if",
"obj",
"in",
"self",
".",
"memo",
":",
"return",
"1",
"self",
".",
"memo",
".",
"append",
"(",
"obj",
")",
"return",
"0"
] | Seen this object (known by its id()? Return 1 if so,
otherwise add it to our memory and return 0. | [
"Seen",
"this",
"object",
"(",
"known",
"by",
"its",
"id",
"()",
"?",
"Return",
"1",
"if",
"so",
"otherwise",
"add",
"it",
"to",
"our",
"memory",
"and",
"return",
"0",
"."
] | python | train |
HttpRunner/har2case | har2case/cli.py | https://github.com/HttpRunner/har2case/blob/369e576b24b3521832c35344b104828e30742170/har2case/cli.py#L20-L61 | def main():
""" HAR converter: parse command line options and run commands.
"""
parser = argparse.ArgumentParser(description=__description__)
parser.add_argument(
'-V', '--version', dest='version', action='store_true',
help="show version")
parser.add_argument(
'--log-level', ... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"__description__",
")",
"parser",
".",
"add_argument",
"(",
"'-V'",
",",
"'--version'",
",",
"dest",
"=",
"'version'",
",",
"action",
"=",
"'store_true'"... | HAR converter: parse command line options and run commands. | [
"HAR",
"converter",
":",
"parse",
"command",
"line",
"options",
"and",
"run",
"commands",
"."
] | python | train |
AltSchool/dynamic-rest | dynamic_rest/routers.py | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/routers.py#L249-L276 | def get_canonical_serializer(
resource_key,
model=None,
instance=None,
resource_name=None
):
"""
Return canonical serializer for a given resource name.
Arguments:
resource_key - Resource key, usually DB table for model-based
... | [
"def",
"get_canonical_serializer",
"(",
"resource_key",
",",
"model",
"=",
"None",
",",
"instance",
"=",
"None",
",",
"resource_name",
"=",
"None",
")",
":",
"if",
"model",
":",
"resource_key",
"=",
"get_model_table",
"(",
"model",
")",
"elif",
"instance",
"... | Return canonical serializer for a given resource name.
Arguments:
resource_key - Resource key, usually DB table for model-based
resources, otherwise the plural name.
model - (Optional) Model class to look up by.
instance - (Optional) Model object i... | [
"Return",
"canonical",
"serializer",
"for",
"a",
"given",
"resource",
"name",
"."
] | python | train |
edeposit/edeposit.amqp.ltp | src/edeposit/amqp/ltp/ltp.py | https://github.com/edeposit/edeposit.amqp.ltp/blob/df9ac7ec6cbdbeaaeed438ca66df75ea967b6d8e/src/edeposit/amqp/ltp/ltp.py#L22-L37 | def _get_package_name(prefix=settings.TEMP_DIR, book_id=None):
"""
Return package path. Use uuid to generate package's directory name.
Args:
book_id (str, default None): UUID of the book.
prefix (str, default settings.TEMP_DIR): Where the package will be
stored. Default :attr... | [
"def",
"_get_package_name",
"(",
"prefix",
"=",
"settings",
".",
"TEMP_DIR",
",",
"book_id",
"=",
"None",
")",
":",
"if",
"book_id",
"is",
"None",
":",
"book_id",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"return",
"os",
".",
"path",
".",... | Return package path. Use uuid to generate package's directory name.
Args:
book_id (str, default None): UUID of the book.
prefix (str, default settings.TEMP_DIR): Where the package will be
stored. Default :attr:`settings.TEMP_DIR`.
Returns:
str: Path to the root directory... | [
"Return",
"package",
"path",
".",
"Use",
"uuid",
"to",
"generate",
"package",
"s",
"directory",
"name",
"."
] | python | train |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/scrappers/ben_cz.py | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/ben_cz.py#L111-L140 | def _parse_authors(details):
"""
Parse authors of the book.
Args:
details (obj): HTMLElement containing slice of the page with details.
Returns:
list: List of :class:`structures.Author` objects. Blank if no author \
found.
"""
authors = details.find(
"tr",... | [
"def",
"_parse_authors",
"(",
"details",
")",
":",
"authors",
"=",
"details",
".",
"find",
"(",
"\"tr\"",
",",
"{",
"\"id\"",
":",
"\"ctl00_ContentPlaceHolder1_tblRowAutor\"",
"}",
")",
"if",
"not",
"authors",
":",
"return",
"[",
"]",
"# book with unspecified au... | Parse authors of the book.
Args:
details (obj): HTMLElement containing slice of the page with details.
Returns:
list: List of :class:`structures.Author` objects. Blank if no author \
found. | [
"Parse",
"authors",
"of",
"the",
"book",
"."
] | python | train |
adamrothman/ftl | ftl/utils.py | https://github.com/adamrothman/ftl/blob/a88f3df1ecbdfba45035b65f833b8ffffc49b399/ftl/utils.py#L6-L39 | def default_ssl_context() -> ssl.SSLContext:
"""Creates an SSL context suitable for use with HTTP/2. See
https://tools.ietf.org/html/rfc7540#section-9.2 for what this entails.
Specifically, we are interested in these points:
§ 9.2: Implementations of HTTP/2 MUST use TLS version 1.2 or higher.
... | [
"def",
"default_ssl_context",
"(",
")",
"->",
"ssl",
".",
"SSLContext",
":",
"ctx",
"=",
"ssl",
".",
"create_default_context",
"(",
"purpose",
"=",
"ssl",
".",
"Purpose",
".",
"SERVER_AUTH",
")",
"# OP_NO_SSLv2, OP_NO_SSLv3, and OP_NO_COMPRESSION are already set by defa... | Creates an SSL context suitable for use with HTTP/2. See
https://tools.ietf.org/html/rfc7540#section-9.2 for what this entails.
Specifically, we are interested in these points:
§ 9.2: Implementations of HTTP/2 MUST use TLS version 1.2 or higher.
§ 9.2.1: A deployment of HTTP/2 over TLS 1.2 MUST... | [
"Creates",
"an",
"SSL",
"context",
"suitable",
"for",
"use",
"with",
"HTTP",
"/",
"2",
".",
"See",
"https",
":",
"//",
"tools",
".",
"ietf",
".",
"org",
"/",
"html",
"/",
"rfc7540#section",
"-",
"9",
".",
"2",
"for",
"what",
"this",
"entails",
".",
... | python | train |
sanger-pathogens/ariba | ariba/assembly_compare.py | https://github.com/sanger-pathogens/ariba/blob/16a0b1916ce0e886bd22550ba2d648542977001b/ariba/assembly_compare.py#L181-L214 | def _get_assembled_reference_sequences(nucmer_hits, ref_sequence, assembly):
'''nucmer_hits = hits made by self._parse_nucmer_coords_file.
ref_gene = reference sequence (pyfastaq.sequences.Fasta object)
assembly = dictionary of contig name -> contig.
Makes a set of Fasta object... | [
"def",
"_get_assembled_reference_sequences",
"(",
"nucmer_hits",
",",
"ref_sequence",
",",
"assembly",
")",
":",
"sequences",
"=",
"{",
"}",
"for",
"contig",
"in",
"sorted",
"(",
"nucmer_hits",
")",
":",
"for",
"hit",
"in",
"nucmer_hits",
"[",
"contig",
"]",
... | nucmer_hits = hits made by self._parse_nucmer_coords_file.
ref_gene = reference sequence (pyfastaq.sequences.Fasta object)
assembly = dictionary of contig name -> contig.
Makes a set of Fasta objects of each piece of assembly that
corresponds to the reference sequeunce. | [
"nucmer_hits",
"=",
"hits",
"made",
"by",
"self",
".",
"_parse_nucmer_coords_file",
".",
"ref_gene",
"=",
"reference",
"sequence",
"(",
"pyfastaq",
".",
"sequences",
".",
"Fasta",
"object",
")",
"assembly",
"=",
"dictionary",
"of",
"contig",
"name",
"-",
">",
... | python | train |
ihmeuw/vivarium | src/vivarium/framework/values.py | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/values.py#L54-L79 | def joint_value_post_processor(a, _):
"""The final step in calculating joint values like disability weights.
If the combiner is list_combiner then the effective formula is:
.. math::
value(args) = 1 - \prod_{i=1}^{mutator count} 1-mutator_{i}(args)
Parameters
----------
a : List[pd.S... | [
"def",
"joint_value_post_processor",
"(",
"a",
",",
"_",
")",
":",
"# if there is only one value, return the value",
"if",
"len",
"(",
"a",
")",
"==",
"1",
":",
"return",
"a",
"[",
"0",
"]",
"# if there are multiple values, calculate the joint value",
"product",
"=",
... | The final step in calculating joint values like disability weights.
If the combiner is list_combiner then the effective formula is:
.. math::
value(args) = 1 - \prod_{i=1}^{mutator count} 1-mutator_{i}(args)
Parameters
----------
a : List[pd.Series]
a is a list of series, indexed... | [
"The",
"final",
"step",
"in",
"calculating",
"joint",
"values",
"like",
"disability",
"weights",
".",
"If",
"the",
"combiner",
"is",
"list_combiner",
"then",
"the",
"effective",
"formula",
"is",
":"
] | python | train |
PyCQA/pylint | pylint/lint.py | https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/lint.py#L1284-L1290 | def report_total_messages_stats(sect, stats, previous_stats):
"""make total errors / warnings report"""
lines = ["type", "number", "previous", "difference"]
lines += checkers.table_lines_from_stats(
stats, previous_stats, ("convention", "refactor", "warning", "error")
)
sect.append(report_no... | [
"def",
"report_total_messages_stats",
"(",
"sect",
",",
"stats",
",",
"previous_stats",
")",
":",
"lines",
"=",
"[",
"\"type\"",
",",
"\"number\"",
",",
"\"previous\"",
",",
"\"difference\"",
"]",
"lines",
"+=",
"checkers",
".",
"table_lines_from_stats",
"(",
"s... | make total errors / warnings report | [
"make",
"total",
"errors",
"/",
"warnings",
"report"
] | python | test |
tensorflow/tensor2tensor | tensor2tensor/models/slicenet.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/slicenet.py#L33-L81 | def attention(targets_shifted, inputs_encoded, norm_fn, hparams, bias=None):
"""Complete attention layer with preprocessing."""
separabilities = [hparams.separability, hparams.separability]
if hparams.separability < 0:
separabilities = [hparams.separability - 1, hparams.separability]
targets_timed = common_... | [
"def",
"attention",
"(",
"targets_shifted",
",",
"inputs_encoded",
",",
"norm_fn",
",",
"hparams",
",",
"bias",
"=",
"None",
")",
":",
"separabilities",
"=",
"[",
"hparams",
".",
"separability",
",",
"hparams",
".",
"separability",
"]",
"if",
"hparams",
".",... | Complete attention layer with preprocessing. | [
"Complete",
"attention",
"layer",
"with",
"preprocessing",
"."
] | python | train |
BD2KGenomics/protect | src/protect/common.py | https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/src/protect/common.py#L451-L464 | def delete_fastqs(job, patient_dict):
"""
Delete the fastqs from the job Store once their purpose has been achieved (i.e. after all
mapping steps)
:param dict patient_dict: Dict of list of input fastqs
"""
for key in patient_dict.keys():
if 'fastq' not in key:
continue
... | [
"def",
"delete_fastqs",
"(",
"job",
",",
"patient_dict",
")",
":",
"for",
"key",
"in",
"patient_dict",
".",
"keys",
"(",
")",
":",
"if",
"'fastq'",
"not",
"in",
"key",
":",
"continue",
"job",
".",
"fileStore",
".",
"logToMaster",
"(",
"'Deleting \"%s:%s\" ... | Delete the fastqs from the job Store once their purpose has been achieved (i.e. after all
mapping steps)
:param dict patient_dict: Dict of list of input fastqs | [
"Delete",
"the",
"fastqs",
"from",
"the",
"job",
"Store",
"once",
"their",
"purpose",
"has",
"been",
"achieved",
"(",
"i",
".",
"e",
".",
"after",
"all",
"mapping",
"steps",
")"
] | python | train |
fedora-infra/fmn.rules | fmn/rules/utils.py | https://github.com/fedora-infra/fmn.rules/blob/f9ec790619fcc8b41803077c4dec094e5127fc24/fmn/rules/utils.py#L40-L66 | def get_fas(config):
""" Return a fedora.client.fas2.AccountSystem object if the provided
configuration contains a FAS username and password.
"""
global _FAS
if _FAS is not None:
return _FAS
# In some development environments, having fas_credentials around is a
# pain.. so, let thin... | [
"def",
"get_fas",
"(",
"config",
")",
":",
"global",
"_FAS",
"if",
"_FAS",
"is",
"not",
"None",
":",
"return",
"_FAS",
"# In some development environments, having fas_credentials around is a",
"# pain.. so, let things proceed here, but emit a warning.",
"try",
":",
"creds",
... | Return a fedora.client.fas2.AccountSystem object if the provided
configuration contains a FAS username and password. | [
"Return",
"a",
"fedora",
".",
"client",
".",
"fas2",
".",
"AccountSystem",
"object",
"if",
"the",
"provided",
"configuration",
"contains",
"a",
"FAS",
"username",
"and",
"password",
"."
] | python | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xviewpanel.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanel.py#L407-L418 | def clear(self):
"""
Clears out all the items from this tab bar.
"""
self.blockSignals(True)
items = list(self.items())
for item in items:
item.close()
self.blockSignals(False)
self._currentIndex = -1
self.currentIndexChanged.emit(self... | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"blockSignals",
"(",
"True",
")",
"items",
"=",
"list",
"(",
"self",
".",
"items",
"(",
")",
")",
"for",
"item",
"in",
"items",
":",
"item",
".",
"close",
"(",
")",
"self",
".",
"blockSignals",
... | Clears out all the items from this tab bar. | [
"Clears",
"out",
"all",
"the",
"items",
"from",
"this",
"tab",
"bar",
"."
] | python | train |
Yelp/threat_intel | threat_intel/util/http.py | https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/util/http.py#L79-L91 | def make_calls(self, num_calls=1):
"""Adds appropriate sleep to avoid making too many calls.
Args:
num_calls: int the number of calls which will be made
"""
self._cull()
while self._outstanding_calls + num_calls > self._max_calls_per_second:
time.sleep(0)... | [
"def",
"make_calls",
"(",
"self",
",",
"num_calls",
"=",
"1",
")",
":",
"self",
".",
"_cull",
"(",
")",
"while",
"self",
".",
"_outstanding_calls",
"+",
"num_calls",
">",
"self",
".",
"_max_calls_per_second",
":",
"time",
".",
"sleep",
"(",
"0",
")",
"... | Adds appropriate sleep to avoid making too many calls.
Args:
num_calls: int the number of calls which will be made | [
"Adds",
"appropriate",
"sleep",
"to",
"avoid",
"making",
"too",
"many",
"calls",
"."
] | python | train |
Azure/azure-uamqp-python | uamqp/address.py | https://github.com/Azure/azure-uamqp-python/blob/b67e4fcaf2e8a337636947523570239c10a58ae2/uamqp/address.py#L189-L212 | def set_filter(self, value, name=constants.STRING_FILTER, descriptor=constants.STRING_FILTER):
"""Set a filter on the endpoint. Only one filter
can be applied to an endpoint.
:param value: The filter to apply to the endpoint. Set to None for a NULL filter.
:type value: bytes or str or N... | [
"def",
"set_filter",
"(",
"self",
",",
"value",
",",
"name",
"=",
"constants",
".",
"STRING_FILTER",
",",
"descriptor",
"=",
"constants",
".",
"STRING_FILTER",
")",
":",
"value",
"=",
"value",
".",
"encode",
"(",
"self",
".",
"_encoding",
")",
"if",
"isi... | Set a filter on the endpoint. Only one filter
can be applied to an endpoint.
:param value: The filter to apply to the endpoint. Set to None for a NULL filter.
:type value: bytes or str or None
:param name: The name of the filter. This will be encoded as
an AMQP Symbol. By defau... | [
"Set",
"a",
"filter",
"on",
"the",
"endpoint",
".",
"Only",
"one",
"filter",
"can",
"be",
"applied",
"to",
"an",
"endpoint",
"."
] | python | train |
sorgerlab/indra | indra/tools/assemble_corpus.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L566-L581 | def _remove_bound_conditions(agent, keep_criterion):
"""Removes bound conditions of agent such that keep_criterion is False.
Parameters
----------
agent: Agent
The agent whose bound conditions we evaluate
keep_criterion: function
Evaluates removal_criterion(a) for each agent a in a ... | [
"def",
"_remove_bound_conditions",
"(",
"agent",
",",
"keep_criterion",
")",
":",
"new_bc",
"=",
"[",
"]",
"for",
"ind",
"in",
"range",
"(",
"len",
"(",
"agent",
".",
"bound_conditions",
")",
")",
":",
"if",
"keep_criterion",
"(",
"agent",
".",
"bound_cond... | Removes bound conditions of agent such that keep_criterion is False.
Parameters
----------
agent: Agent
The agent whose bound conditions we evaluate
keep_criterion: function
Evaluates removal_criterion(a) for each agent a in a bound condition
and if it evaluates to False, remove... | [
"Removes",
"bound",
"conditions",
"of",
"agent",
"such",
"that",
"keep_criterion",
"is",
"False",
"."
] | python | train |
equinor/segyviewer | src/segyviewlib/sliceview.py | https://github.com/equinor/segyviewer/blob/994d402a8326f30608d98103f8831dee9e3c5850/src/segyviewlib/sliceview.py#L39-L70 | def create_slice(self, context):
""" :type context: dict """
model = self._model
axes = self._image.axes
""" :type: matplotlib.axes.Axes """
axes.set_title(model.title, fontsize=12)
axes.tick_params(axis='both')
axes.set_ylabel(model.y_axis_name, fontsize=9)
... | [
"def",
"create_slice",
"(",
"self",
",",
"context",
")",
":",
"model",
"=",
"self",
".",
"_model",
"axes",
"=",
"self",
".",
"_image",
".",
"axes",
"\"\"\" :type: matplotlib.axes.Axes \"\"\"",
"axes",
".",
"set_title",
"(",
"model",
".",
"title",
",",
"fonts... | :type context: dict | [
":",
"type",
"context",
":",
"dict"
] | python | train |
uw-it-aca/django-saferecipient-email-backend | saferecipient/__init__.py | https://github.com/uw-it-aca/django-saferecipient-email-backend/blob/8af20dece5a668d6bcad5dea75cc60871a4bd9fa/saferecipient/__init__.py#L44-L54 | def _only_safe_emails(self, emails):
""""Given a list of emails, checks whether they are all in the white
list."""
email_modified = False
if any(not self._is_whitelisted(email) for email in emails):
email_modified = True
emails = [email for email in emails if sel... | [
"def",
"_only_safe_emails",
"(",
"self",
",",
"emails",
")",
":",
"email_modified",
"=",
"False",
"if",
"any",
"(",
"not",
"self",
".",
"_is_whitelisted",
"(",
"email",
")",
"for",
"email",
"in",
"emails",
")",
":",
"email_modified",
"=",
"True",
"emails",... | Given a list of emails, checks whether they are all in the white
list. | [
"Given",
"a",
"list",
"of",
"emails",
"checks",
"whether",
"they",
"are",
"all",
"in",
"the",
"white",
"list",
"."
] | python | train |
Esri/ArcREST | src/arcrest/common/symbology.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/common/symbology.py#L136-L140 | def outlineWidth(self, value):
"""gets/sets the outlineWidth"""
if isinstance(value, (int, float, long)) and \
not self._outline is None:
self._outline['width'] = value | [
"def",
"outlineWidth",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"int",
",",
"float",
",",
"long",
")",
")",
"and",
"not",
"self",
".",
"_outline",
"is",
"None",
":",
"self",
".",
"_outline",
"[",
"'width'",
"... | gets/sets the outlineWidth | [
"gets",
"/",
"sets",
"the",
"outlineWidth"
] | python | train |
vtemian/buffpy | buffpy/response.py | https://github.com/vtemian/buffpy/blob/6c9236fd3b6a8f9e2d70dbf1bc01529242b73075/buffpy/response.py#L20-L29 | def _check_for_inception(self, root_dict):
'''
Used to check if there is a dict in a dict
'''
for key in root_dict:
if isinstance(root_dict[key], dict):
root_dict[key] = ResponseObject(root_dict[key])
return root_dict | [
"def",
"_check_for_inception",
"(",
"self",
",",
"root_dict",
")",
":",
"for",
"key",
"in",
"root_dict",
":",
"if",
"isinstance",
"(",
"root_dict",
"[",
"key",
"]",
",",
"dict",
")",
":",
"root_dict",
"[",
"key",
"]",
"=",
"ResponseObject",
"(",
"root_di... | Used to check if there is a dict in a dict | [
"Used",
"to",
"check",
"if",
"there",
"is",
"a",
"dict",
"in",
"a",
"dict"
] | python | valid |
iotile/coretools | iotilesensorgraph/iotile/sg/sim/simulator.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sim/simulator.py#L95-L109 | def step(self, input_stream, value):
"""Step the sensor graph through one since input.
The internal tick count is not advanced so this function may
be called as many times as desired to input specific conditions
without simulation time passing.
Args:
input_stream (D... | [
"def",
"step",
"(",
"self",
",",
"input_stream",
",",
"value",
")",
":",
"reading",
"=",
"IOTileReading",
"(",
"input_stream",
".",
"encode",
"(",
")",
",",
"self",
".",
"tick_count",
",",
"value",
")",
"self",
".",
"sensor_graph",
".",
"process_input",
... | Step the sensor graph through one since input.
The internal tick count is not advanced so this function may
be called as many times as desired to input specific conditions
without simulation time passing.
Args:
input_stream (DataStream): The input stream to push the
... | [
"Step",
"the",
"sensor",
"graph",
"through",
"one",
"since",
"input",
"."
] | python | train |
DataDog/integrations-core | datadog_checks_base/datadog_checks/base/log.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/datadog_checks_base/datadog_checks/base/log.py#L62-L77 | def init_logging():
"""
Initialize logging (set up forwarding to Go backend and sane defaults)
"""
# Forward to Go backend
logging.addLevelName(TRACE_LEVEL, 'TRACE')
logging.setLoggerClass(AgentLogger)
rootLogger = logging.getLogger()
rootLogger.addHandler(AgentLogHandler())
rootLogg... | [
"def",
"init_logging",
"(",
")",
":",
"# Forward to Go backend",
"logging",
".",
"addLevelName",
"(",
"TRACE_LEVEL",
",",
"'TRACE'",
")",
"logging",
".",
"setLoggerClass",
"(",
"AgentLogger",
")",
"rootLogger",
"=",
"logging",
".",
"getLogger",
"(",
")",
"rootLo... | Initialize logging (set up forwarding to Go backend and sane defaults) | [
"Initialize",
"logging",
"(",
"set",
"up",
"forwarding",
"to",
"Go",
"backend",
"and",
"sane",
"defaults",
")"
] | python | train |
saltstack/salt | salt/modules/apache.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apache.py#L403-L449 | def _parse_config(conf, slot=None):
'''
Recursively goes through config structure and builds final Apache configuration
:param conf: defined config structure
:param slot: name of section container if needed
'''
ret = cStringIO()
if isinstance(conf, six.string_types):
if slot:
... | [
"def",
"_parse_config",
"(",
"conf",
",",
"slot",
"=",
"None",
")",
":",
"ret",
"=",
"cStringIO",
"(",
")",
"if",
"isinstance",
"(",
"conf",
",",
"six",
".",
"string_types",
")",
":",
"if",
"slot",
":",
"print",
"(",
"'{0} {1}'",
".",
"format",
"(",
... | Recursively goes through config structure and builds final Apache configuration
:param conf: defined config structure
:param slot: name of section container if needed | [
"Recursively",
"goes",
"through",
"config",
"structure",
"and",
"builds",
"final",
"Apache",
"configuration"
] | python | train |
icometrix/dicom2nifti | dicom2nifti/convert_ge.py | https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_ge.py#L139-L165 | def _get_full_block(grouped_dicoms):
"""
Generate a full datablock containing all timepoints
"""
# For each slice / mosaic create a data volume block
data_blocks = []
for index in range(0, len(grouped_dicoms)):
logger.info('Creating block %s of %s' % (index + 1, len(grouped_dicoms)))
... | [
"def",
"_get_full_block",
"(",
"grouped_dicoms",
")",
":",
"# For each slice / mosaic create a data volume block",
"data_blocks",
"=",
"[",
"]",
"for",
"index",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"grouped_dicoms",
")",
")",
":",
"logger",
".",
"info",
"("... | Generate a full datablock containing all timepoints | [
"Generate",
"a",
"full",
"datablock",
"containing",
"all",
"timepoints"
] | python | train |
saltstack/salt | salt/utils/gitfs.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/gitfs.py#L2988-L3006 | def symlink_list(self, load):
'''
Return a dict of all symlinks based on a given path in the repo
'''
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
if not salt.utils.stringutils.is_hex(load['saltenv']) \
and lo... | [
"def",
"symlink_list",
"(",
"self",
",",
"load",
")",
":",
"if",
"'env'",
"in",
"load",
":",
"# \"env\" is not supported; Use \"saltenv\".",
"load",
".",
"pop",
"(",
"'env'",
")",
"if",
"not",
"salt",
".",
"utils",
".",
"stringutils",
".",
"is_hex",
"(",
"... | Return a dict of all symlinks based on a given path in the repo | [
"Return",
"a",
"dict",
"of",
"all",
"symlinks",
"based",
"on",
"a",
"given",
"path",
"in",
"the",
"repo"
] | python | train |
jmbhughes/suvi-trainer | suvitrainer/fileio.py | https://github.com/jmbhughes/suvi-trainer/blob/3d89894a4a037286221974c7eb5634d229b4f5d4/suvitrainer/fileio.py#L414-L560 | def align_solar_fov(header, data, cdelt_min, naxis_min,
translate_origin=True, rotate=True, scale=True):
"""
taken from suvi code by vhsu
Apply field of view image corrections
:param header: FITS header
:param data: Image data
:param cdelt_min: Mi... | [
"def",
"align_solar_fov",
"(",
"header",
",",
"data",
",",
"cdelt_min",
",",
"naxis_min",
",",
"translate_origin",
"=",
"True",
",",
"rotate",
"=",
"True",
",",
"scale",
"=",
"True",
")",
":",
"from",
"skimage",
".",
"transform",
"import",
"ProjectiveTransfo... | taken from suvi code by vhsu
Apply field of view image corrections
:param header: FITS header
:param data: Image data
:param cdelt_min: Minimum plate scale for images (static run config param)
:param naxis_min: Minimum axis dimension for images (static run config param)
... | [
"taken",
"from",
"suvi",
"code",
"by",
"vhsu",
"Apply",
"field",
"of",
"view",
"image",
"corrections"
] | python | train |
sparklingpandas/sparklingpandas | sparklingpandas/groupby.py | https://github.com/sparklingpandas/sparklingpandas/blob/7d549df4348c979042b683c355aa778fc6d3a768/sparklingpandas/groupby.py#L366-L375 | def nth(self, n, *args, **kwargs):
"""Take the nth element of each grouby."""
# TODO: Stop collecting the entire frame for each key.
self._prep_pandas_groupby()
myargs = self._myargs
mykwargs = self._mykwargs
nthRDD = self._regroup_mergedRDD().mapValues(
lambd... | [
"def",
"nth",
"(",
"self",
",",
"n",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: Stop collecting the entire frame for each key.",
"self",
".",
"_prep_pandas_groupby",
"(",
")",
"myargs",
"=",
"self",
".",
"_myargs",
"mykwargs",
"=",
"self",
... | Take the nth element of each grouby. | [
"Take",
"the",
"nth",
"element",
"of",
"each",
"grouby",
"."
] | python | train |
Esri/ArcREST | src/arcrest/manageags/_services.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageags/_services.py#L87-L106 | def folderName(self, folder):
"""gets/set the current folder"""
if folder == "" or\
folder == "/":
self._currentURL = self._url
self._services = None
self._description = None
self._folderName = None
self._webEncrypted = None
... | [
"def",
"folderName",
"(",
"self",
",",
"folder",
")",
":",
"if",
"folder",
"==",
"\"\"",
"or",
"folder",
"==",
"\"/\"",
":",
"self",
".",
"_currentURL",
"=",
"self",
".",
"_url",
"self",
".",
"_services",
"=",
"None",
"self",
".",
"_description",
"=",
... | gets/set the current folder | [
"gets",
"/",
"set",
"the",
"current",
"folder"
] | python | train |
thespacedoctor/rockAtlas | rockAtlas/positions/orbfitPositions.py | https://github.com/thespacedoctor/rockAtlas/blob/062ecaa95ab547efda535aa33165944f13c621de/rockAtlas/positions/orbfitPositions.py#L84-L119 | def get(self,
singleExposure=False):
"""
*get the orbfitPositions object*
**Key Arguments:**
- ``singleExposure`` -- only execute fot a single exposure (useful for debugging)
**Return:**
- None
**Usage:**
See class docstring
... | [
"def",
"get",
"(",
"self",
",",
"singleExposure",
"=",
"False",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``get`` method'",
")",
"if",
"singleExposure",
":",
"batchSize",
"=",
"1",
"else",
":",
"batchSize",
"=",
"int",
"(",
"self",
"... | *get the orbfitPositions object*
**Key Arguments:**
- ``singleExposure`` -- only execute fot a single exposure (useful for debugging)
**Return:**
- None
**Usage:**
See class docstring | [
"*",
"get",
"the",
"orbfitPositions",
"object",
"*"
] | python | train |
czielinski/portfolioopt | portfolioopt/portfolioopt.py | https://github.com/czielinski/portfolioopt/blob/96ac25daab0c0dbc8933330a92ff31fb898112f2/portfolioopt/portfolioopt.py#L45-L122 | def markowitz_portfolio(cov_mat, exp_rets, target_ret,
allow_short=False, market_neutral=False):
"""
Computes a Markowitz portfolio.
Parameters
----------
cov_mat: pandas.DataFrame
Covariance matrix of asset returns.
exp_rets: pandas.Series
Expected asset... | [
"def",
"markowitz_portfolio",
"(",
"cov_mat",
",",
"exp_rets",
",",
"target_ret",
",",
"allow_short",
"=",
"False",
",",
"market_neutral",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"cov_mat",
",",
"pd",
".",
"DataFrame",
")",
":",
"raise",
"V... | Computes a Markowitz portfolio.
Parameters
----------
cov_mat: pandas.DataFrame
Covariance matrix of asset returns.
exp_rets: pandas.Series
Expected asset returns (often historical returns).
target_ret: float
Target return of portfolio.
allow_short: bool, optional
... | [
"Computes",
"a",
"Markowitz",
"portfolio",
"."
] | python | train |
danilobellini/audiolazy | math/lowpass_highpass_digital.py | https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/math/lowpass_highpass_digital.py#L46-L125 | def design_z_filter_single_pole(filt_str, max_gain_freq):
"""
Finds the coefficients for a simple lowpass/highpass filter.
This function just prints the coefficient values, besides the given
filter equation and its power gain. There's 3 constraints used to find the
coefficients:
1. The G value is defined ... | [
"def",
"design_z_filter_single_pole",
"(",
"filt_str",
",",
"max_gain_freq",
")",
":",
"print",
"(",
"\"H(z) = \"",
"+",
"filt_str",
")",
"# Avoids printing as \"1/z\"",
"filt",
"=",
"sympify",
"(",
"filt_str",
",",
"dict",
"(",
"G",
"=",
"G",
",",
"R",
"=",
... | Finds the coefficients for a simple lowpass/highpass filter.
This function just prints the coefficient values, besides the given
filter equation and its power gain. There's 3 constraints used to find the
coefficients:
1. The G value is defined by the max gain of 1 (0 dB) imposed at a
specific frequency
... | [
"Finds",
"the",
"coefficients",
"for",
"a",
"simple",
"lowpass",
"/",
"highpass",
"filter",
"."
] | python | train |
serge-sans-paille/pythran | pythran/backend.py | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/backend.py#L1275-L1289 | def visit_Module(self, node):
""" Build a compilation unit. """
# build all types
deps = sorted(self.dependencies)
headers = [Include(os.path.join("pythonic", "include", *t) + ".hpp")
for t in deps]
headers += [Include(os.path.join("pythonic", *t) + ".hpp")
... | [
"def",
"visit_Module",
"(",
"self",
",",
"node",
")",
":",
"# build all types",
"deps",
"=",
"sorted",
"(",
"self",
".",
"dependencies",
")",
"headers",
"=",
"[",
"Include",
"(",
"os",
".",
"path",
".",
"join",
"(",
"\"pythonic\"",
",",
"\"include\"",
",... | Build a compilation unit. | [
"Build",
"a",
"compilation",
"unit",
"."
] | python | train |
bitcraft/pyscroll | pyscroll/isometric.py | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/isometric.py#L86-L127 | def center(self, coords):
""" center the map on a "map pixel"
"""
x, y = [round(i, 0) for i in coords]
self.view_rect.center = x, y
tw, th = self.data.tile_size
left, ox = divmod(x, tw)
top, oy = divmod(y, th)
vec = int(ox / 2), int(oy)
iso = v... | [
"def",
"center",
"(",
"self",
",",
"coords",
")",
":",
"x",
",",
"y",
"=",
"[",
"round",
"(",
"i",
",",
"0",
")",
"for",
"i",
"in",
"coords",
"]",
"self",
".",
"view_rect",
".",
"center",
"=",
"x",
",",
"y",
"tw",
",",
"th",
"=",
"self",
".... | center the map on a "map pixel" | [
"center",
"the",
"map",
"on",
"a",
"map",
"pixel"
] | python | train |
FulcrumTechnologies/pyconfluence | pyconfluence/api.py | https://github.com/FulcrumTechnologies/pyconfluence/blob/a999726dbc1cbdd3d9062234698eeae799ce84ce/pyconfluence/api.py#L67-L84 | def _api_action(url, req, data=None):
"""Take action based on what kind of request is needed."""
requisite_headers = {'Accept': 'application/json',
'Content-Type': 'application/json'}
auth = (user, token)
if req == "GET":
response = requests.get(url, headers=requisite_h... | [
"def",
"_api_action",
"(",
"url",
",",
"req",
",",
"data",
"=",
"None",
")",
":",
"requisite_headers",
"=",
"{",
"'Accept'",
":",
"'application/json'",
",",
"'Content-Type'",
":",
"'application/json'",
"}",
"auth",
"=",
"(",
"user",
",",
"token",
")",
"if"... | Take action based on what kind of request is needed. | [
"Take",
"action",
"based",
"on",
"what",
"kind",
"of",
"request",
"is",
"needed",
"."
] | python | train |
bear/ninka | ninka/micropub.py | https://github.com/bear/ninka/blob/4d13a48d2b8857496f7fc470b0c379486351c89b/ninka/micropub.py#L91-L104 | def discoverMicropubEndpoints(domain, content=None, look_in={'name': 'link'}, test_urls=True, validateCerts=True):
"""Find the micropub for the given domain.
Only scan html element matching all criteria in look_in.
optionally the content to be scanned can be given as an argument.
:param domain: the UR... | [
"def",
"discoverMicropubEndpoints",
"(",
"domain",
",",
"content",
"=",
"None",
",",
"look_in",
"=",
"{",
"'name'",
":",
"'link'",
"}",
",",
"test_urls",
"=",
"True",
",",
"validateCerts",
"=",
"True",
")",
":",
"return",
"discoverEndpoint",
"(",
"domain",
... | Find the micropub for the given domain.
Only scan html element matching all criteria in look_in.
optionally the content to be scanned can be given as an argument.
:param domain: the URL of the domain to handle
:param content: the content to be scanned for the endpoint
:param look_in: dictionary wi... | [
"Find",
"the",
"micropub",
"for",
"the",
"given",
"domain",
".",
"Only",
"scan",
"html",
"element",
"matching",
"all",
"criteria",
"in",
"look_in",
"."
] | python | train |
pysathq/pysat | pysat/solvers.py | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/solvers.py#L2742-L2748 | def prop_budget(self, budget):
"""
Set limit on the number of propagations.
"""
if self.minicard:
pysolvers.minicard_pbudget(self.minicard, budget) | [
"def",
"prop_budget",
"(",
"self",
",",
"budget",
")",
":",
"if",
"self",
".",
"minicard",
":",
"pysolvers",
".",
"minicard_pbudget",
"(",
"self",
".",
"minicard",
",",
"budget",
")"
] | Set limit on the number of propagations. | [
"Set",
"limit",
"on",
"the",
"number",
"of",
"propagations",
"."
] | python | train |
Knio/dominate | dominate/util.py | https://github.com/Knio/dominate/blob/1eb88f9fd797658eef83568a548e2ef9b546807d/dominate/util.py#L54-L68 | def escape(data, quote=True): # stoled from std lib cgi
'''
Escapes special characters into their html entities
Replace special characters "&", "<" and ">" to HTML-safe sequences.
If the optional flag quote is true, the quotation mark character (")
is also translated.
This is used to escape content that a... | [
"def",
"escape",
"(",
"data",
",",
"quote",
"=",
"True",
")",
":",
"# stoled from std lib cgi",
"data",
"=",
"data",
".",
"replace",
"(",
"\"&\"",
",",
"\"&\"",
")",
"# Must be done first!",
"data",
"=",
"data",
".",
"replace",
"(",
"\"<\"",
",",
"\"&l... | Escapes special characters into their html entities
Replace special characters "&", "<" and ">" to HTML-safe sequences.
If the optional flag quote is true, the quotation mark character (")
is also translated.
This is used to escape content that appears in the body of an HTML cocument | [
"Escapes",
"special",
"characters",
"into",
"their",
"html",
"entities",
"Replace",
"special",
"characters",
"&",
"<",
"and",
">",
"to",
"HTML",
"-",
"safe",
"sequences",
".",
"If",
"the",
"optional",
"flag",
"quote",
"is",
"true",
"the",
"quotation",
"mark"... | python | valid |
konture/CloeePy | cloeepy/logger.py | https://github.com/konture/CloeePy/blob/dcb21284d2df405d92ac6868ea7215792c9323b9/cloeepy/logger.py#L49-L57 | def _set_formatter(self):
"""
Inspects config and sets the name of the formatter to either "json" or "text"
as instance attr. If not present in config, default is "text"
"""
if hasattr(self._config, "formatter") and self._config.formatter == "json":
self._formatter = ... | [
"def",
"_set_formatter",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"_config",
",",
"\"formatter\"",
")",
"and",
"self",
".",
"_config",
".",
"formatter",
"==",
"\"json\"",
":",
"self",
".",
"_formatter",
"=",
"\"json\"",
"else",
":",
"sel... | Inspects config and sets the name of the formatter to either "json" or "text"
as instance attr. If not present in config, default is "text" | [
"Inspects",
"config",
"and",
"sets",
"the",
"name",
"of",
"the",
"formatter",
"to",
"either",
"json",
"or",
"text",
"as",
"instance",
"attr",
".",
"If",
"not",
"present",
"in",
"config",
"default",
"is",
"text"
] | python | train |
nitipit/appkit | appkit/app.py | https://github.com/nitipit/appkit/blob/08eeaf45a9ca884bf5fe105d47a81269d44b1412/appkit/app.py#L40-L68 | def do_startup(self):
"""Gtk.Application.run() will call this function()"""
Gtk.Application.do_startup(self)
gtk_window = Gtk.ApplicationWindow(application=self)
gtk_window.set_title('AppKit')
webkit_web_view = WebKit.WebView()
webkit_web_view.load_uri('http://localhost:... | [
"def",
"do_startup",
"(",
"self",
")",
":",
"Gtk",
".",
"Application",
".",
"do_startup",
"(",
"self",
")",
"gtk_window",
"=",
"Gtk",
".",
"ApplicationWindow",
"(",
"application",
"=",
"self",
")",
"gtk_window",
".",
"set_title",
"(",
"'AppKit'",
")",
"web... | Gtk.Application.run() will call this function() | [
"Gtk",
".",
"Application",
".",
"run",
"()",
"will",
"call",
"this",
"function",
"()"
] | python | train |
wandb/client | wandb/vendor/prompt_toolkit/contrib/telnet/protocol.py | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/contrib/telnet/protocol.py#L175-L181 | def feed(self, data):
"""
Feed data to the parser.
"""
assert isinstance(data, binary_type)
for b in iterbytes(data):
self._parser.send(int2byte(b)) | [
"def",
"feed",
"(",
"self",
",",
"data",
")",
":",
"assert",
"isinstance",
"(",
"data",
",",
"binary_type",
")",
"for",
"b",
"in",
"iterbytes",
"(",
"data",
")",
":",
"self",
".",
"_parser",
".",
"send",
"(",
"int2byte",
"(",
"b",
")",
")"
] | Feed data to the parser. | [
"Feed",
"data",
"to",
"the",
"parser",
"."
] | python | train |
droope/droopescan | dscan/common/functions.py | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/common/functions.py#L246-L275 | def tail(f, window=20):
"""
Returns the last `window` lines of file `f` as a list.
@param window: the number of lines.
"""
if window == 0:
return []
BUFSIZ = 1024
f.seek(0, 2)
bytes = f.tell()
size = window + 1
block = -1
data = []
while size > 0 and bytes > 0:
... | [
"def",
"tail",
"(",
"f",
",",
"window",
"=",
"20",
")",
":",
"if",
"window",
"==",
"0",
":",
"return",
"[",
"]",
"BUFSIZ",
"=",
"1024",
"f",
".",
"seek",
"(",
"0",
",",
"2",
")",
"bytes",
"=",
"f",
".",
"tell",
"(",
")",
"size",
"=",
"windo... | Returns the last `window` lines of file `f` as a list.
@param window: the number of lines. | [
"Returns",
"the",
"last",
"window",
"lines",
"of",
"file",
"f",
"as",
"a",
"list",
"."
] | python | train |
ardydedase/pycouchbase | pycouchbase/viewsync.py | https://github.com/ardydedase/pycouchbase/blob/6f010b4d2ef41aead2366878d0cf0b1284c0db0e/pycouchbase/viewsync.py#L117-L176 | def upload(cls):
"""Uploads all the local views from :attr:`VIEW_PATHS` directory
to CouchBase server
This method **over-writes** all the server-side views with the same
named ones coming from :attr:`VIEW_PATHS` folder.
"""
cls._check_folder()
os.chdir(cls.VIEWS_... | [
"def",
"upload",
"(",
"cls",
")",
":",
"cls",
".",
"_check_folder",
"(",
")",
"os",
".",
"chdir",
"(",
"cls",
".",
"VIEWS_PATH",
")",
"buckets",
"=",
"dict",
"(",
")",
"# iterate local folders",
"for",
"bucket_name",
"in",
"os",
".",
"listdir",
"(",
"c... | Uploads all the local views from :attr:`VIEW_PATHS` directory
to CouchBase server
This method **over-writes** all the server-side views with the same
named ones coming from :attr:`VIEW_PATHS` folder. | [
"Uploads",
"all",
"the",
"local",
"views",
"from",
":",
"attr",
":",
"VIEW_PATHS",
"directory",
"to",
"CouchBase",
"server"
] | python | train |
ergoithz/browsepy | browsepy/compat.py | https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/compat.py#L236-L259 | def pathconf(path,
os_name=os.name,
isdir_fnc=os.path.isdir,
pathconf_fnc=getattr(os, 'pathconf', None),
pathconf_names=getattr(os, 'pathconf_names', ())):
'''
Get all pathconf variables for given path.
:param path: absolute fs path
:type path: str
... | [
"def",
"pathconf",
"(",
"path",
",",
"os_name",
"=",
"os",
".",
"name",
",",
"isdir_fnc",
"=",
"os",
".",
"path",
".",
"isdir",
",",
"pathconf_fnc",
"=",
"getattr",
"(",
"os",
",",
"'pathconf'",
",",
"None",
")",
",",
"pathconf_names",
"=",
"getattr",
... | Get all pathconf variables for given path.
:param path: absolute fs path
:type path: str
:returns: dictionary containing pathconf keys and their values (both str)
:rtype: dict | [
"Get",
"all",
"pathconf",
"variables",
"for",
"given",
"path",
"."
] | python | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/utils.py | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L125-L145 | def get_ip_prefixes_from_config(config, services, ip_version):
"""Build a set of IP prefixes found in service configuration files.
Arguments:
config (obg): A configparser object which holds our configuration.
services (list): A list of section names which are the name of the
service che... | [
"def",
"get_ip_prefixes_from_config",
"(",
"config",
",",
"services",
",",
"ip_version",
")",
":",
"ip_prefixes",
"=",
"set",
"(",
")",
"for",
"service",
"in",
"services",
":",
"ip_prefix",
"=",
"ipaddress",
".",
"ip_network",
"(",
"config",
".",
"get",
"(",... | Build a set of IP prefixes found in service configuration files.
Arguments:
config (obg): A configparser object which holds our configuration.
services (list): A list of section names which are the name of the
service checks.
ip_version (int): IP protocol version
Returns:
... | [
"Build",
"a",
"set",
"of",
"IP",
"prefixes",
"found",
"in",
"service",
"configuration",
"files",
"."
] | python | train |
kontron/python-aardvark | pyaardvark/aardvark.py | https://github.com/kontron/python-aardvark/blob/9827f669fbdc5bceb98e7d08a294b4e4e455d0d5/pyaardvark/aardvark.py#L326-L336 | def i2c_bitrate(self):
"""I2C bitrate in kHz. Not every bitrate is supported by the host
adapter. Therefore, the actual bitrate may be less than the value which
is set.
The power-on default value is 100 kHz.
"""
ret = api.py_aa_i2c_bitrate(self.handle, 0)
_raise... | [
"def",
"i2c_bitrate",
"(",
"self",
")",
":",
"ret",
"=",
"api",
".",
"py_aa_i2c_bitrate",
"(",
"self",
".",
"handle",
",",
"0",
")",
"_raise_error_if_negative",
"(",
"ret",
")",
"return",
"ret"
] | I2C bitrate in kHz. Not every bitrate is supported by the host
adapter. Therefore, the actual bitrate may be less than the value which
is set.
The power-on default value is 100 kHz. | [
"I2C",
"bitrate",
"in",
"kHz",
".",
"Not",
"every",
"bitrate",
"is",
"supported",
"by",
"the",
"host",
"adapter",
".",
"Therefore",
"the",
"actual",
"bitrate",
"may",
"be",
"less",
"than",
"the",
"value",
"which",
"is",
"set",
"."
] | python | train |
aaugustin/django-sequences | sequences/__init__.py | https://github.com/aaugustin/django-sequences/blob/0228ae003540ccb63be4a456fb8f63a2f4038de6/sequences/__init__.py#L13-L59 | def get_next_value(
sequence_name='default', initial_value=1, reset_value=None,
*, nowait=False, using=None):
"""
Return the next value for a given sequence.
"""
# Inner import because models cannot be imported before their application.
from .models import Sequence
if reset_val... | [
"def",
"get_next_value",
"(",
"sequence_name",
"=",
"'default'",
",",
"initial_value",
"=",
"1",
",",
"reset_value",
"=",
"None",
",",
"*",
",",
"nowait",
"=",
"False",
",",
"using",
"=",
"None",
")",
":",
"# Inner import because models cannot be imported before t... | Return the next value for a given sequence. | [
"Return",
"the",
"next",
"value",
"for",
"a",
"given",
"sequence",
"."
] | python | train |
google/grr | grr/core/grr_response_core/lib/parsers/linux_pam_parser.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/parsers/linux_pam_parser.py#L47-L84 | def EnumerateAllConfigs(self, stats, file_objects):
"""Generate RDFs for the fully expanded configs.
Args:
stats: A list of RDF StatEntries corresponding to the file_objects.
file_objects: A list of file handles.
Returns:
A tuple of a list of RDFValue PamConfigEntries found & a list of s... | [
"def",
"EnumerateAllConfigs",
"(",
"self",
",",
"stats",
",",
"file_objects",
")",
":",
"# Convert the stats & file_objects into a cache of a",
"# simple path keyed dict of file contents.",
"cache",
"=",
"{",
"}",
"for",
"stat_obj",
",",
"file_obj",
"in",
"zip",
"(",
"s... | Generate RDFs for the fully expanded configs.
Args:
stats: A list of RDF StatEntries corresponding to the file_objects.
file_objects: A list of file handles.
Returns:
A tuple of a list of RDFValue PamConfigEntries found & a list of strings
which are the external config references found... | [
"Generate",
"RDFs",
"for",
"the",
"fully",
"expanded",
"configs",
"."
] | python | train |
fp12/achallonge | challonge/user.py | https://github.com/fp12/achallonge/blob/25780b3c48b66400a50ff9f884e4287afd4c89e4/challonge/user.py#L58-L95 | async def get_tournament(self, t_id: int = None, url: str = None, subdomain: str = None, force_update=False) -> Tournament:
""" gets a tournament with its id or url or url+subdomain
Note: from the API, it can't be known if the retrieved tournament was made from this user.
Thus, any tournament i... | [
"async",
"def",
"get_tournament",
"(",
"self",
",",
"t_id",
":",
"int",
"=",
"None",
",",
"url",
":",
"str",
"=",
"None",
",",
"subdomain",
":",
"str",
"=",
"None",
",",
"force_update",
"=",
"False",
")",
"->",
"Tournament",
":",
"assert_or_raise",
"("... | gets a tournament with its id or url or url+subdomain
Note: from the API, it can't be known if the retrieved tournament was made from this user.
Thus, any tournament is added to the local list of tournaments, but some functions (updates/destroy...) cannot be used for tournaments not owned by this user.... | [
"gets",
"a",
"tournament",
"with",
"its",
"id",
"or",
"url",
"or",
"url",
"+",
"subdomain",
"Note",
":",
"from",
"the",
"API",
"it",
"can",
"t",
"be",
"known",
"if",
"the",
"retrieved",
"tournament",
"was",
"made",
"from",
"this",
"user",
".",
"Thus",
... | python | train |
dj-stripe/dj-stripe | djstripe/management/commands/djstripe_sync_customers.py | https://github.com/dj-stripe/dj-stripe/blob/a5308a3808cd6e2baba49482f7a699f3a8992518/djstripe/management/commands/djstripe_sync_customers.py#L15-L28 | def handle(self, *args, **options):
"""Call sync_subscriber on Subscribers without customers associated to them."""
qs = get_subscriber_model().objects.filter(djstripe_customers__isnull=True)
count = 0
total = qs.count()
for subscriber in qs:
count += 1
perc = int(round(100 * (float(count) / float(total... | [
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"qs",
"=",
"get_subscriber_model",
"(",
")",
".",
"objects",
".",
"filter",
"(",
"djstripe_customers__isnull",
"=",
"True",
")",
"count",
"=",
"0",
"total",
"=",
"qs",
... | Call sync_subscriber on Subscribers without customers associated to them. | [
"Call",
"sync_subscriber",
"on",
"Subscribers",
"without",
"customers",
"associated",
"to",
"them",
"."
] | python | train |
CalebBell/ht | ht/insulation.py | https://github.com/CalebBell/ht/blob/3097ef9524c4cf0068ad453c17b10ec9ce551eee/ht/insulation.py#L496-L535 | def refractory_VDI_k(ID, T=None):
r'''Returns thermal conductivity of a refractory material from a table in
[1]_. Here, thermal conductivity is a function of temperature between
673.15 K and 1473.15 K according to linear interpolation among 5
equally-spaced points. Here, thermal conductivity is not a fu... | [
"def",
"refractory_VDI_k",
"(",
"ID",
",",
"T",
"=",
"None",
")",
":",
"if",
"T",
"is",
"None",
":",
"return",
"float",
"(",
"refractories",
"[",
"ID",
"]",
"[",
"1",
"]",
"[",
"0",
"]",
")",
"else",
":",
"ks",
"=",
"refractories",
"[",
"ID",
"... | r'''Returns thermal conductivity of a refractory material from a table in
[1]_. Here, thermal conductivity is a function of temperature between
673.15 K and 1473.15 K according to linear interpolation among 5
equally-spaced points. Here, thermal conductivity is not a function of
porosity, which can affe... | [
"r",
"Returns",
"thermal",
"conductivity",
"of",
"a",
"refractory",
"material",
"from",
"a",
"table",
"in",
"[",
"1",
"]",
"_",
".",
"Here",
"thermal",
"conductivity",
"is",
"a",
"function",
"of",
"temperature",
"between",
"673",
".",
"15",
"K",
"and",
"... | python | train |
scivision/sciencedates | sciencedates/__init__.py | https://github.com/scivision/sciencedates/blob/a713389e027b42d26875cf227450a5d7c6696000/sciencedates/__init__.py#L40-L72 | def yeardoy2datetime(yeardate: int,
utsec: Union[float, int] = None) -> datetime.datetime:
"""
Inputs:
yd: yyyyddd four digit year, 3 digit day of year (INTEGER 7 digits)
outputs:
t: datetime
http://stackoverflow.com/questions/2427555/python-question-year-and-day-of-year-t... | [
"def",
"yeardoy2datetime",
"(",
"yeardate",
":",
"int",
",",
"utsec",
":",
"Union",
"[",
"float",
",",
"int",
"]",
"=",
"None",
")",
"->",
"datetime",
".",
"datetime",
":",
"if",
"isinstance",
"(",
"yeardate",
",",
"(",
"tuple",
",",
"list",
",",
"np... | Inputs:
yd: yyyyddd four digit year, 3 digit day of year (INTEGER 7 digits)
outputs:
t: datetime
http://stackoverflow.com/questions/2427555/python-question-year-and-day-of-year-to-date | [
"Inputs",
":",
"yd",
":",
"yyyyddd",
"four",
"digit",
"year",
"3",
"digit",
"day",
"of",
"year",
"(",
"INTEGER",
"7",
"digits",
")"
] | python | train |
log2timeline/plaso | plaso/parsers/msiecf.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/msiecf.py#L193-L214 | def _ParseRedirected(
self, parser_mediator, msiecf_item, recovered=False):
"""Extract data from a MSIE Cache Files (MSIECF) redirected item.
Every item is stored as an event object, one for each timestamp.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
... | [
"def",
"_ParseRedirected",
"(",
"self",
",",
"parser_mediator",
",",
"msiecf_item",
",",
"recovered",
"=",
"False",
")",
":",
"date_time",
"=",
"dfdatetime_semantic_time",
".",
"SemanticTime",
"(",
"'Not set'",
")",
"event_data",
"=",
"MSIECFRedirectedEventData",
"(... | Extract data from a MSIE Cache Files (MSIECF) redirected item.
Every item is stored as an event object, one for each timestamp.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
msiecf_item (pymsiecf.redirected)... | [
"Extract",
"data",
"from",
"a",
"MSIE",
"Cache",
"Files",
"(",
"MSIECF",
")",
"redirected",
"item",
"."
] | python | train |
rconradharris/envparse | envparse.py | https://github.com/rconradharris/envparse/blob/e67e70307af19d925e194b2a163e0608dae7eb55/envparse.py#L167-L214 | def read_envfile(path=None, **overrides):
"""
Read a .env file (line delimited KEY=VALUE) into os.environ.
If not given a path to the file, recurses up the directory tree until
found.
Uses code from Honcho (github.com/nickstenning/honcho) for parsing the
file.
"... | [
"def",
"read_envfile",
"(",
"path",
"=",
"None",
",",
"*",
"*",
"overrides",
")",
":",
"if",
"path",
"is",
"None",
":",
"frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
".",
"f_back",
"caller_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
... | Read a .env file (line delimited KEY=VALUE) into os.environ.
If not given a path to the file, recurses up the directory tree until
found.
Uses code from Honcho (github.com/nickstenning/honcho) for parsing the
file. | [
"Read",
"a",
".",
"env",
"file",
"(",
"line",
"delimited",
"KEY",
"=",
"VALUE",
")",
"into",
"os",
".",
"environ",
"."
] | python | train |
mkouhei/tonicdnscli | src/tonicdnscli/command.py | https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/command.py#L401-L413 | def delete_zone(args):
"""Delete zone.
Argument:
args: arguments object
"""
if args.__dict__.get('domain'):
domain = args.domain
password = get_password(args)
token = connect.get_token(args.username, password, args.server)
processing.delete_zone(args.server, token, domain) | [
"def",
"delete_zone",
"(",
"args",
")",
":",
"if",
"args",
".",
"__dict__",
".",
"get",
"(",
"'domain'",
")",
":",
"domain",
"=",
"args",
".",
"domain",
"password",
"=",
"get_password",
"(",
"args",
")",
"token",
"=",
"connect",
".",
"get_token",
"(",
... | Delete zone.
Argument:
args: arguments object | [
"Delete",
"zone",
"."
] | python | train |
tensorflow/probability | tensorflow_probability/python/stats/quantiles.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/stats/quantiles.py#L726-L787 | def _get_static_ndims(x,
expect_static=False,
expect_ndims=None,
expect_ndims_no_more_than=None,
expect_ndims_at_least=None):
"""Get static number of dimensions and assert that some expectations are met.
This function returns t... | [
"def",
"_get_static_ndims",
"(",
"x",
",",
"expect_static",
"=",
"False",
",",
"expect_ndims",
"=",
"None",
",",
"expect_ndims_no_more_than",
"=",
"None",
",",
"expect_ndims_at_least",
"=",
"None",
")",
":",
"ndims",
"=",
"x",
".",
"shape",
".",
"ndims",
"if... | Get static number of dimensions and assert that some expectations are met.
This function returns the number of dimensions 'ndims' of x, as a Python int.
The optional expect arguments are used to check the ndims of x, but this is
only done if the static ndims of x is not None.
Args:
x: A Tensor.
expe... | [
"Get",
"static",
"number",
"of",
"dimensions",
"and",
"assert",
"that",
"some",
"expectations",
"are",
"met",
"."
] | python | test |
KelSolaar/Umbra | umbra/ui/models.py | https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/ui/models.py#L430-L449 | def index(self, row, column=0, parent=QModelIndex()):
"""
Reimplements the :meth:`QAbstractItemModel.index` method.
:param row: Row.
:type row: int
:param column: Column.
:type column: int
:param parent: Parent.
:type parent: QModelIndex
:return: ... | [
"def",
"index",
"(",
"self",
",",
"row",
",",
"column",
"=",
"0",
",",
"parent",
"=",
"QModelIndex",
"(",
")",
")",
":",
"parent_node",
"=",
"self",
".",
"get_node",
"(",
"parent",
")",
"child",
"=",
"parent_node",
".",
"child",
"(",
"row",
")",
"i... | Reimplements the :meth:`QAbstractItemModel.index` method.
:param row: Row.
:type row: int
:param column: Column.
:type column: int
:param parent: Parent.
:type parent: QModelIndex
:return: Index.
:rtype: QModelIndex | [
"Reimplements",
"the",
":",
"meth",
":",
"QAbstractItemModel",
".",
"index",
"method",
"."
] | python | train |
learningequality/ricecooker | ricecooker/classes/files.py | https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/classes/files.py#L561-L573 | def is_youtube_subtitle_file_supported_language(language):
"""
Check if the language code `language` (string) is a valid language code in the
internal language id format `{primary_code}` or `{primary_code}-{subcode}`
ot alternatively if it s YouTube language code that can be mapped to one of
the lan... | [
"def",
"is_youtube_subtitle_file_supported_language",
"(",
"language",
")",
":",
"language_obj",
"=",
"_get_language_with_alpha2_fallback",
"(",
"language",
")",
"if",
"language_obj",
"is",
"None",
":",
"config",
".",
"LOGGER",
".",
"warning",
"(",
"\"Found unsupported ... | Check if the language code `language` (string) is a valid language code in the
internal language id format `{primary_code}` or `{primary_code}-{subcode}`
ot alternatively if it s YouTube language code that can be mapped to one of
the languages in the internal represention. | [
"Check",
"if",
"the",
"language",
"code",
"language",
"(",
"string",
")",
"is",
"a",
"valid",
"language",
"code",
"in",
"the",
"internal",
"language",
"id",
"format",
"{",
"primary_code",
"}",
"or",
"{",
"primary_code",
"}",
"-",
"{",
"subcode",
"}",
"ot... | python | train |
mikhaildubov/AST-text-analysis | east/asts/easa.py | https://github.com/mikhaildubov/AST-text-analysis/blob/055ad8d2492c100bbbaa25309ec1074bdf1dfaa5/east/asts/easa.py#L247-L266 | def _compute_lcptab(self, string, suftab):
"""Computes the LCP array in O(n) based on the input string & its suffix array.
Kasai et al. (2001).
"""
n = len(suftab)
rank = [0] * n
for i in xrange(n):
rank[suftab[i]] = i
lcptab = np.zeros(n, dtype=np.in... | [
"def",
"_compute_lcptab",
"(",
"self",
",",
"string",
",",
"suftab",
")",
":",
"n",
"=",
"len",
"(",
"suftab",
")",
"rank",
"=",
"[",
"0",
"]",
"*",
"n",
"for",
"i",
"in",
"xrange",
"(",
"n",
")",
":",
"rank",
"[",
"suftab",
"[",
"i",
"]",
"]... | Computes the LCP array in O(n) based on the input string & its suffix array.
Kasai et al. (2001). | [
"Computes",
"the",
"LCP",
"array",
"in",
"O",
"(",
"n",
")",
"based",
"on",
"the",
"input",
"string",
"&",
"its",
"suffix",
"array",
"."
] | python | train |
ivelum/graphql-py | graphql/parser.py | https://github.com/ivelum/graphql-py/blob/72baf16d838e82349ee5e8d8f8971ce11cfcedf9/graphql/parser.py#L213-L217 | def p_field_optional1_2(self, p):
"""
field : alias name directives selection_set
"""
p[0] = Field(name=p[2], alias=p[1], directives=p[3], selections=p[5]) | [
"def",
"p_field_optional1_2",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Field",
"(",
"name",
"=",
"p",
"[",
"2",
"]",
",",
"alias",
"=",
"p",
"[",
"1",
"]",
",",
"directives",
"=",
"p",
"[",
"3",
"]",
",",
"selections",
"=",
... | field : alias name directives selection_set | [
"field",
":",
"alias",
"name",
"directives",
"selection_set"
] | python | train |
splunk/splunk-sdk-python | examples/analytics/bottle.py | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L1076-L1108 | def set_cookie(self, key, value, secret=None, **kargs):
''' Add a cookie or overwrite an old one. If the `secret` parameter is
set, create a `Signed Cookie` (described below).
:param key: the name of the cookie.
:param value: the value of the cookie.
:param secre... | [
"def",
"set_cookie",
"(",
"self",
",",
"key",
",",
"value",
",",
"secret",
"=",
"None",
",",
"*",
"*",
"kargs",
")",
":",
"if",
"secret",
":",
"value",
"=",
"touni",
"(",
"cookie_encode",
"(",
"(",
"key",
",",
"value",
")",
",",
"secret",
")",
")... | Add a cookie or overwrite an old one. If the `secret` parameter is
set, create a `Signed Cookie` (described below).
:param key: the name of the cookie.
:param value: the value of the cookie.
:param secret: required for signed cookies. (default: None)
:param m... | [
"Add",
"a",
"cookie",
"or",
"overwrite",
"an",
"old",
"one",
".",
"If",
"the",
"secret",
"parameter",
"is",
"set",
"create",
"a",
"Signed",
"Cookie",
"(",
"described",
"below",
")",
"."
] | python | train |
GoogleCloudPlatform/google-cloud-datastore | python/googledatastore/connection.py | https://github.com/GoogleCloudPlatform/google-cloud-datastore/blob/a23940d0634d7f537faf01ad9e60598046bcb40a/python/googledatastore/connection.py#L174-L204 | def _call_method(self, method, req, resp_class):
"""_call_method call the given RPC method over HTTP.
It uses the given protobuf message request as the payload and
returns the deserialized protobuf message response.
Args:
method: RPC method name to be called.
req: protobuf message for the ... | [
"def",
"_call_method",
"(",
"self",
",",
"method",
",",
"req",
",",
"resp_class",
")",
":",
"payload",
"=",
"req",
".",
"SerializeToString",
"(",
")",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/x-protobuf'",
",",
"'Content-Length'",
":",
"str",
... | _call_method call the given RPC method over HTTP.
It uses the given protobuf message request as the payload and
returns the deserialized protobuf message response.
Args:
method: RPC method name to be called.
req: protobuf message for the RPC request.
resp_class: protobuf message class fo... | [
"_call_method",
"call",
"the",
"given",
"RPC",
"method",
"over",
"HTTP",
"."
] | python | train |
kubernetes-client/python | kubernetes/client/apis/rbac_authorization_v1_api.py | https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/rbac_authorization_v1_api.py#L1349-L1375 | def delete_namespaced_role_binding(self, name, namespace, **kwargs):
"""
delete a RoleBinding
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_namespaced_role_binding(name, namespace,... | [
"def",
"delete_namespaced_role_binding",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
... | delete a RoleBinding
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_namespaced_role_binding(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
... | [
"delete",
"a",
"RoleBinding",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"pass",
"async_req",
"=",
"True",
">>>",
"thread",
"=",
"api",
".",
"delete... | python | train |
molmod/molmod | molmod/randomize.py | https://github.com/molmod/molmod/blob/a7b5b4364ed514ad4c465856c05b5eda1cb561e0/molmod/randomize.py#L402-L468 | def random_dimer(molecule0, molecule1, thresholds, shoot_max):
"""Create a random dimer.
molecule0 and molecule1 are placed in one reference frame at random
relative positions. Interatomic distances are above the thresholds.
Initially a dimer is created where one interatomic distance approxima... | [
"def",
"random_dimer",
"(",
"molecule0",
",",
"molecule1",
",",
"thresholds",
",",
"shoot_max",
")",
":",
"# apply a random rotation to molecule1",
"center",
"=",
"np",
".",
"zeros",
"(",
"3",
",",
"float",
")",
"angle",
"=",
"np",
".",
"random",
".",
"unifo... | Create a random dimer.
molecule0 and molecule1 are placed in one reference frame at random
relative positions. Interatomic distances are above the thresholds.
Initially a dimer is created where one interatomic distance approximates
the threshold value. Then the molecules are given an additi... | [
"Create",
"a",
"random",
"dimer",
"."
] | python | train |
bxlab/bx-python | lib/bx_extras/stats.py | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1685-L1696 | def lsumdiffsquared(x,y):
"""
Takes pairwise differences of the values in lists x and y, squares
these differences, and returns the sum of these squares.
Usage: lsumdiffsquared(x,y)
Returns: sum[(x[i]-y[i])**2]
"""
sds = 0
for i in range(len(x)):
sds = sds + (x[i]-y[i])**2
return sds | [
"def",
"lsumdiffsquared",
"(",
"x",
",",
"y",
")",
":",
"sds",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"x",
")",
")",
":",
"sds",
"=",
"sds",
"+",
"(",
"x",
"[",
"i",
"]",
"-",
"y",
"[",
"i",
"]",
")",
"**",
"2",
"return",
... | Takes pairwise differences of the values in lists x and y, squares
these differences, and returns the sum of these squares.
Usage: lsumdiffsquared(x,y)
Returns: sum[(x[i]-y[i])**2] | [
"Takes",
"pairwise",
"differences",
"of",
"the",
"values",
"in",
"lists",
"x",
"and",
"y",
"squares",
"these",
"differences",
"and",
"returns",
"the",
"sum",
"of",
"these",
"squares",
"."
] | python | train |
doanguyen/lasotuvi | lasotuvi/AmDuong.py | https://github.com/doanguyen/lasotuvi/blob/98383a3056f0a0633d6937d364c37eb788661c0d/lasotuvi/AmDuong.py#L452-L475 | def timTuVi(cuc, ngaySinhAmLich):
"""Tìm vị trí của sao Tử vi
Args:
cuc (TYPE): Description
ngaySinhAmLich (TYPE): Description
Returns:
TYPE: Description
Raises:
Exception: Description
"""
cungDan = 3 # Vị trí cung Dần ban đầu là 3
cucBanDau = cuc
if c... | [
"def",
"timTuVi",
"(",
"cuc",
",",
"ngaySinhAmLich",
")",
":",
"cungDan",
"=",
"3",
"# Vị trí cung Dần ban đầu là 3",
"cucBanDau",
"=",
"cuc",
"if",
"cuc",
"not",
"in",
"[",
"2",
",",
"3",
",",
"4",
",",
"5",
",",
"6",
"]",
":",
"# Tránh trường hợp infin... | Tìm vị trí của sao Tử vi
Args:
cuc (TYPE): Description
ngaySinhAmLich (TYPE): Description
Returns:
TYPE: Description
Raises:
Exception: Description | [
"Tìm",
"vị",
"trí",
"của",
"sao",
"Tử",
"vi"
] | python | train |
meng89/ipodshuffle | ipodshuffle/db/itunessd.py | https://github.com/meng89/ipodshuffle/blob/c9093dbb5cdac609376ebd3b4ef1b0fc58107d96/ipodshuffle/db/itunessd.py#L418-L516 | def dics_to_itunessd(header_dic, tracks_dics, playlists_dics_and_indexes):
"""
:param header_dic: dic of header_table
:param tracks_dics: list of all track_table's dics
:param playlists_dics_and_indexes: list of all playlists and all their track's indexes
:return: the whole iTunesSD bytes data
"... | [
"def",
"dics_to_itunessd",
"(",
"header_dic",
",",
"tracks_dics",
",",
"playlists_dics_and_indexes",
")",
":",
"############################################",
"# header",
"######",
"header_dic",
"[",
"'length'",
"]",
"=",
"get_table_size",
"(",
"header_table",
")",
"heade... | :param header_dic: dic of header_table
:param tracks_dics: list of all track_table's dics
:param playlists_dics_and_indexes: list of all playlists and all their track's indexes
:return: the whole iTunesSD bytes data | [
":",
"param",
"header_dic",
":",
"dic",
"of",
"header_table",
":",
"param",
"tracks_dics",
":",
"list",
"of",
"all",
"track_table",
"s",
"dics",
":",
"param",
"playlists_dics_and_indexes",
":",
"list",
"of",
"all",
"playlists",
"and",
"all",
"their",
"track",
... | python | train |
fprimex/zdesk | zdesk/zdesk_api.py | https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L1447-L1454 | def help_center_article_comment_votes(self, article_id, comment_id, locale=None, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/votes#list-votes"
api_path = "/api/v2/help_center/articles/{article_id}/comments/{comment_id}/votes.json"
api_path = api_path.format(article_id=art... | [
"def",
"help_center_article_comment_votes",
"(",
"self",
",",
"article_id",
",",
"comment_id",
",",
"locale",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/help_center/articles/{article_id}/comments/{comment_id}/votes.json\"",
"api_path",
"="... | https://developer.zendesk.com/rest_api/docs/help_center/votes#list-votes | [
"https",
":",
"//",
"developer",
".",
"zendesk",
".",
"com",
"/",
"rest_api",
"/",
"docs",
"/",
"help_center",
"/",
"votes#list",
"-",
"votes"
] | python | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/targets.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/targets.py#L169-L188 | def main_target_usage_requirements (self, specification, project):
""" Returns the use requirement to use when declaraing a main target,
which are obtained by
- translating all specified property paths, and
- adding project's usage requirements
specification: Use... | [
"def",
"main_target_usage_requirements",
"(",
"self",
",",
"specification",
",",
"project",
")",
":",
"assert",
"is_iterable_typed",
"(",
"specification",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"project",
",",
"ProjectTarget",
")",
"project_usage_require... | Returns the use requirement to use when declaraing a main target,
which are obtained by
- translating all specified property paths, and
- adding project's usage requirements
specification: Use-properties explicitly specified for a main target
project: ... | [
"Returns",
"the",
"use",
"requirement",
"to",
"use",
"when",
"declaraing",
"a",
"main",
"target",
"which",
"are",
"obtained",
"by",
"-",
"translating",
"all",
"specified",
"property",
"paths",
"and",
"-",
"adding",
"project",
"s",
"usage",
"requirements",
"spe... | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/fileops.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L270-L276 | def rmglob(pattern: str) -> None:
"""
Deletes all files whose filename matches the glob ``pattern`` (via
:func:`glob.glob`).
"""
for f in glob.glob(pattern):
os.remove(f) | [
"def",
"rmglob",
"(",
"pattern",
":",
"str",
")",
"->",
"None",
":",
"for",
"f",
"in",
"glob",
".",
"glob",
"(",
"pattern",
")",
":",
"os",
".",
"remove",
"(",
"f",
")"
] | Deletes all files whose filename matches the glob ``pattern`` (via
:func:`glob.glob`). | [
"Deletes",
"all",
"files",
"whose",
"filename",
"matches",
"the",
"glob",
"pattern",
"(",
"via",
":",
"func",
":",
"glob",
".",
"glob",
")",
"."
] | python | train |
ScienceLogic/amiuploader | amiimporter/AWSUtilities.py | https://github.com/ScienceLogic/amiuploader/blob/c36c247b2226107b38571cbc6119118b1fe07182/amiimporter/AWSUtilities.py#L319-L337 | def import_vmdk(self):
"""
All actions necessary to import vmdk (calls s3 upload, and import to aws ec2)
:param vmdk_location: location of vmdk to import. Can be provided as a string, or the result output of fabric
execution
:return:
"""
# Set the inital upload to... | [
"def",
"import_vmdk",
"(",
"self",
")",
":",
"# Set the inital upload to be the first region in the list",
"first_upload_region",
"=",
"self",
".",
"aws_regions",
"[",
"0",
"]",
"print",
"\"Initial AMI will be created in: {}\"",
".",
"format",
"(",
"first_upload_region",
")... | All actions necessary to import vmdk (calls s3 upload, and import to aws ec2)
:param vmdk_location: location of vmdk to import. Can be provided as a string, or the result output of fabric
execution
:return: | [
"All",
"actions",
"necessary",
"to",
"import",
"vmdk",
"(",
"calls",
"s3",
"upload",
"and",
"import",
"to",
"aws",
"ec2",
")",
":",
"param",
"vmdk_location",
":",
"location",
"of",
"vmdk",
"to",
"import",
".",
"Can",
"be",
"provided",
"as",
"a",
"string"... | python | train |
esterhui/pypu | pypu/service_facebook.py | https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/service_facebook.py#L93-L101 | def Upload(self,directory,filename):
"""Uploads/Updates/Replaces files"""
if self._isMediaFile(filename):
return self._upload_media(directory,filename)
elif self._isConfigFile(filename):
return self._update_config(directory,filename)
print "Not handled!"
... | [
"def",
"Upload",
"(",
"self",
",",
"directory",
",",
"filename",
")",
":",
"if",
"self",
".",
"_isMediaFile",
"(",
"filename",
")",
":",
"return",
"self",
".",
"_upload_media",
"(",
"directory",
",",
"filename",
")",
"elif",
"self",
".",
"_isConfigFile",
... | Uploads/Updates/Replaces files | [
"Uploads",
"/",
"Updates",
"/",
"Replaces",
"files"
] | python | train |
data61/clkhash | clkhash/cli.py | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/cli.py#L56-L92 | def hash(pii_csv, keys, schema, clk_json, quiet, no_header, check_header, validate):
"""Process data to create CLKs
Given a file containing CSV data as PII_CSV, and a JSON
document defining the expected schema, verify the schema, then
hash the data to create CLKs writing them as JSON to CLK_JSON. Note ... | [
"def",
"hash",
"(",
"pii_csv",
",",
"keys",
",",
"schema",
",",
"clk_json",
",",
"quiet",
",",
"no_header",
",",
"check_header",
",",
"validate",
")",
":",
"schema_object",
"=",
"clkhash",
".",
"schema",
".",
"from_json_file",
"(",
"schema_file",
"=",
"sch... | Process data to create CLKs
Given a file containing CSV data as PII_CSV, and a JSON
document defining the expected schema, verify the schema, then
hash the data to create CLKs writing them as JSON to CLK_JSON. Note the CSV
file should contain a header row - however this row is not used
by this tool... | [
"Process",
"data",
"to",
"create",
"CLKs"
] | python | train |
jbeluch/xbmcswift2 | xbmcswift2/cli/console.py | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/cli/console.py#L73-L91 | def get_user_choice(items):
'''Returns the selected item from provided items or None if 'q' was
entered for quit.
'''
choice = raw_input('Choose an item or "q" to quit: ')
while choice != 'q':
try:
item = items[int(choice)]
print # Blank line for readability between ... | [
"def",
"get_user_choice",
"(",
"items",
")",
":",
"choice",
"=",
"raw_input",
"(",
"'Choose an item or \"q\" to quit: '",
")",
"while",
"choice",
"!=",
"'q'",
":",
"try",
":",
"item",
"=",
"items",
"[",
"int",
"(",
"choice",
")",
"]",
"print",
"# Blank line ... | Returns the selected item from provided items or None if 'q' was
entered for quit. | [
"Returns",
"the",
"selected",
"item",
"from",
"provided",
"items",
"or",
"None",
"if",
"q",
"was",
"entered",
"for",
"quit",
"."
] | python | train |
RI-imaging/qpformat | qpformat/file_formats/series_zip_tif_phasics.py | https://github.com/RI-imaging/qpformat/blob/364e29d7d9e8b9f1d7a4a25c753d1baf9d73d5eb/qpformat/file_formats/series_zip_tif_phasics.py#L55-L59 | def files(self):
"""List of Phasics tif file names in the input zip file"""
if self._files is None:
self._files = SeriesZipTifPhasics._index_files(self.path)
return self._files | [
"def",
"files",
"(",
"self",
")",
":",
"if",
"self",
".",
"_files",
"is",
"None",
":",
"self",
".",
"_files",
"=",
"SeriesZipTifPhasics",
".",
"_index_files",
"(",
"self",
".",
"path",
")",
"return",
"self",
".",
"_files"
] | List of Phasics tif file names in the input zip file | [
"List",
"of",
"Phasics",
"tif",
"file",
"names",
"in",
"the",
"input",
"zip",
"file"
] | python | train |
indranilsinharoy/pyzos | pyzos/zos.py | https://github.com/indranilsinharoy/pyzos/blob/da6bf3296b0154ccee44ad9a4286055ae031ecc7/pyzos/zos.py#L53-L65 | def _delete_file(fileName, n=10):
"""Cleanly deletes a file in `n` attempts (if necessary)"""
status = False
count = 0
while not status and count < n:
try:
_os.remove(fileName)
except OSError:
count += 1
_time.sleep(0.2)
else:
statu... | [
"def",
"_delete_file",
"(",
"fileName",
",",
"n",
"=",
"10",
")",
":",
"status",
"=",
"False",
"count",
"=",
"0",
"while",
"not",
"status",
"and",
"count",
"<",
"n",
":",
"try",
":",
"_os",
".",
"remove",
"(",
"fileName",
")",
"except",
"OSError",
... | Cleanly deletes a file in `n` attempts (if necessary) | [
"Cleanly",
"deletes",
"a",
"file",
"in",
"n",
"attempts",
"(",
"if",
"necessary",
")"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.