repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
jantman/webhook2lambda2sqs | webhook2lambda2sqs/aws.py | AWSInfo._all_queue_names | def _all_queue_names(self):
"""
Return a list of all unique queue names in our config.
:return: list of all queue names (str)
:rtype: :std:term:`list`
"""
queues = set()
endpoints = self.config.get('endpoints')
for e in endpoints:
for q in end... | python | def _all_queue_names(self):
"""
Return a list of all unique queue names in our config.
:return: list of all queue names (str)
:rtype: :std:term:`list`
"""
queues = set()
endpoints = self.config.get('endpoints')
for e in endpoints:
for q in end... | [
"def",
"_all_queue_names",
"(",
"self",
")",
":",
"queues",
"=",
"set",
"(",
")",
"endpoints",
"=",
"self",
".",
"config",
".",
"get",
"(",
"'endpoints'",
")",
"for",
"e",
"in",
"endpoints",
":",
"for",
"q",
"in",
"endpoints",
"[",
"e",
"]",
"[",
"... | Return a list of all unique queue names in our config.
:return: list of all queue names (str)
:rtype: :std:term:`list` | [
"Return",
"a",
"list",
"of",
"all",
"unique",
"queue",
"names",
"in",
"our",
"config",
"."
] | train | https://github.com/jantman/webhook2lambda2sqs/blob/c80c18d5a908ba8b8ee624dc3a977c633fba2b7c/webhook2lambda2sqs/aws.py#L231-L243 |
jantman/webhook2lambda2sqs | webhook2lambda2sqs/aws.py | AWSInfo.show_queue | def show_queue(self, name=None, count=10, delete=False):
"""
Show up to ``count`` messages from the queue named ``name``. If ``name``
is None, show for each queue in our config. If ``delete`` is True,
delete the messages after showing them.
:param name: queue name, or None for a... | python | def show_queue(self, name=None, count=10, delete=False):
"""
Show up to ``count`` messages from the queue named ``name``. If ``name``
is None, show for each queue in our config. If ``delete`` is True,
delete the messages after showing them.
:param name: queue name, or None for a... | [
"def",
"show_queue",
"(",
"self",
",",
"name",
"=",
"None",
",",
"count",
"=",
"10",
",",
"delete",
"=",
"False",
")",
":",
"logger",
".",
"debug",
"(",
"'Connecting to SQS API'",
")",
"conn",
"=",
"client",
"(",
"'sqs'",
")",
"if",
"name",
"is",
"no... | Show up to ``count`` messages from the queue named ``name``. If ``name``
is None, show for each queue in our config. If ``delete`` is True,
delete the messages after showing them.
:param name: queue name, or None for all queues in config.
:type name: str
:param count: maximum nu... | [
"Show",
"up",
"to",
"count",
"messages",
"from",
"the",
"queue",
"named",
"name",
".",
"If",
"name",
"is",
"None",
"show",
"for",
"each",
"queue",
"in",
"our",
"config",
".",
"If",
"delete",
"is",
"True",
"delete",
"the",
"messages",
"after",
"showing",
... | train | https://github.com/jantman/webhook2lambda2sqs/blob/c80c18d5a908ba8b8ee624dc3a977c633fba2b7c/webhook2lambda2sqs/aws.py#L245-L268 |
jantman/webhook2lambda2sqs | webhook2lambda2sqs/aws.py | AWSInfo.get_api_id | def get_api_id(self):
"""
Return the API ID.
:return: API ID
:rtype: str
"""
logger.debug('Connecting to AWS apigateway API')
conn = client('apigateway')
apis = conn.get_rest_apis()
api_id = None
for api in apis['items']:
if ap... | python | def get_api_id(self):
"""
Return the API ID.
:return: API ID
:rtype: str
"""
logger.debug('Connecting to AWS apigateway API')
conn = client('apigateway')
apis = conn.get_rest_apis()
api_id = None
for api in apis['items']:
if ap... | [
"def",
"get_api_id",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Connecting to AWS apigateway API'",
")",
"conn",
"=",
"client",
"(",
"'apigateway'",
")",
"apis",
"=",
"conn",
".",
"get_rest_apis",
"(",
")",
"api_id",
"=",
"None",
"for",
"api",
"... | Return the API ID.
:return: API ID
:rtype: str | [
"Return",
"the",
"API",
"ID",
"."
] | train | https://github.com/jantman/webhook2lambda2sqs/blob/c80c18d5a908ba8b8ee624dc3a977c633fba2b7c/webhook2lambda2sqs/aws.py#L277-L296 |
jantman/webhook2lambda2sqs | webhook2lambda2sqs/aws.py | AWSInfo.set_method_settings | def set_method_settings(self):
"""
Set the Method settings <https://docs.aws.amazon.com/apigateway/api-\
reference/resource/stage/#methodSettings> on our Deployment Stage.
This is currently not supported by Terraform; see <https://github.com/\
jantman/webhook2lambda2sqs/issues/7> and <https://gi... | python | def set_method_settings(self):
"""
Set the Method settings <https://docs.aws.amazon.com/apigateway/api-\
reference/resource/stage/#methodSettings> on our Deployment Stage.
This is currently not supported by Terraform; see <https://github.com/\
jantman/webhook2lambda2sqs/issues/7> and <https://gi... | [
"def",
"set_method_settings",
"(",
"self",
")",
":",
"settings",
"=",
"self",
".",
"config",
".",
"get",
"(",
"'api_gateway_method_settings'",
")",
"if",
"settings",
"is",
"None",
":",
"logger",
".",
"debug",
"(",
"'api_gateway_method_settings not set in config'",
... | Set the Method settings <https://docs.aws.amazon.com/apigateway/api-\
reference/resource/stage/#methodSettings> on our Deployment Stage.
This is currently not supported by Terraform; see <https://github.com/\
jantman/webhook2lambda2sqs/issues/7> and <https://github.com/hashicorp\
/terraform/issues/6612>.
... | [
"Set",
"the",
"Method",
"settings",
"<https",
":",
"//",
"docs",
".",
"aws",
".",
"amazon",
".",
"com",
"/",
"apigateway",
"/",
"api",
"-",
"\\",
"reference",
"/",
"resource",
"/",
"stage",
"/",
"#methodSettings",
">",
"on",
"our",
"Deployment",
"Stage",... | train | https://github.com/jantman/webhook2lambda2sqs/blob/c80c18d5a908ba8b8ee624dc3a977c633fba2b7c/webhook2lambda2sqs/aws.py#L298-L341 |
jantman/webhook2lambda2sqs | webhook2lambda2sqs/aws.py | AWSInfo._add_method_setting | def _add_method_setting(self, conn, api_id, stage_name, path, key, value,
op):
"""
Update a single method setting on the specified stage. This uses the
'add' operation to PATCH the resource.
:param conn: APIGateway API connection
:type conn: :py:class... | python | def _add_method_setting(self, conn, api_id, stage_name, path, key, value,
op):
"""
Update a single method setting on the specified stage. This uses the
'add' operation to PATCH the resource.
:param conn: APIGateway API connection
:type conn: :py:class... | [
"def",
"_add_method_setting",
"(",
"self",
",",
"conn",
",",
"api_id",
",",
"stage_name",
",",
"path",
",",
"key",
",",
"value",
",",
"op",
")",
":",
"logger",
".",
"debug",
"(",
"'update_stage PATCH %s on %s; value=%s'",
",",
"op",
",",
"path",
",",
"str"... | Update a single method setting on the specified stage. This uses the
'add' operation to PATCH the resource.
:param conn: APIGateway API connection
:type conn: :py:class:`botocore:APIGateway.Client`
:param api_id: ReST API ID
:type api_id: str
:param stage_name: stage nam... | [
"Update",
"a",
"single",
"method",
"setting",
"on",
"the",
"specified",
"stage",
".",
"This",
"uses",
"the",
"add",
"operation",
"to",
"PATCH",
"the",
"resource",
"."
] | train | https://github.com/jantman/webhook2lambda2sqs/blob/c80c18d5a908ba8b8ee624dc3a977c633fba2b7c/webhook2lambda2sqs/aws.py#L343-L383 |
abingham/spor | src/spor/repository/repository.py | initialize_repository | def initialize_repository(path, spor_dir='.spor'):
"""Initialize a spor repository in `path` if one doesn't already exist.
Args:
path: Path to any file or directory within the repository.
spor_dir: The name of the directory containing spor data.
Returns: A `Repository` instance.
Raise... | python | def initialize_repository(path, spor_dir='.spor'):
"""Initialize a spor repository in `path` if one doesn't already exist.
Args:
path: Path to any file or directory within the repository.
spor_dir: The name of the directory containing spor data.
Returns: A `Repository` instance.
Raise... | [
"def",
"initialize_repository",
"(",
"path",
",",
"spor_dir",
"=",
"'.spor'",
")",
":",
"path",
"=",
"pathlib",
".",
"Path",
"(",
"path",
")",
"spor_path",
"=",
"path",
"/",
"spor_dir",
"if",
"spor_path",
".",
"exists",
"(",
")",
":",
"raise",
"ValueErro... | Initialize a spor repository in `path` if one doesn't already exist.
Args:
path: Path to any file or directory within the repository.
spor_dir: The name of the directory containing spor data.
Returns: A `Repository` instance.
Raises:
ValueError: A repository already exists at `pat... | [
"Initialize",
"a",
"spor",
"repository",
"in",
"path",
"if",
"one",
"doesn",
"t",
"already",
"exist",
"."
] | train | https://github.com/abingham/spor/blob/673c8c36c99a4b9ea882f002bfb529f1eca89126/src/spor/repository/repository.py#L8-L26 |
abingham/spor | src/spor/repository/repository.py | open_repository | def open_repository(path, spor_dir='.spor'):
"""Open an existing repository.
Args:
path: Path to any file or directory within the repository.
spor_dir: The name of the directory containing spor data.
Returns: A `Repository` instance.
Raises:
ValueError: No repository is found.... | python | def open_repository(path, spor_dir='.spor'):
"""Open an existing repository.
Args:
path: Path to any file or directory within the repository.
spor_dir: The name of the directory containing spor data.
Returns: A `Repository` instance.
Raises:
ValueError: No repository is found.... | [
"def",
"open_repository",
"(",
"path",
",",
"spor_dir",
"=",
"'.spor'",
")",
":",
"root",
"=",
"_find_root_dir",
"(",
"path",
",",
"spor_dir",
")",
"return",
"Repository",
"(",
"root",
",",
"spor_dir",
")"
] | Open an existing repository.
Args:
path: Path to any file or directory within the repository.
spor_dir: The name of the directory containing spor data.
Returns: A `Repository` instance.
Raises:
ValueError: No repository is found. | [
"Open",
"an",
"existing",
"repository",
"."
] | train | https://github.com/abingham/spor/blob/673c8c36c99a4b9ea882f002bfb529f1eca89126/src/spor/repository/repository.py#L29-L42 |
abingham/spor | src/spor/repository/repository.py | _find_root_dir | def _find_root_dir(path, spor_dir):
"""Search for a spor repo containing `path`.
This searches for `spor_dir` in directories dominating `path`. If a
directory containing `spor_dir` is found, then that directory is returned
as a `pathlib.Path`.
Returns: The dominating directory containing `spor_dir... | python | def _find_root_dir(path, spor_dir):
"""Search for a spor repo containing `path`.
This searches for `spor_dir` in directories dominating `path`. If a
directory containing `spor_dir` is found, then that directory is returned
as a `pathlib.Path`.
Returns: The dominating directory containing `spor_dir... | [
"def",
"_find_root_dir",
"(",
"path",
",",
"spor_dir",
")",
":",
"start_path",
"=",
"pathlib",
".",
"Path",
"(",
"os",
".",
"getcwd",
"(",
")",
"if",
"path",
"is",
"None",
"else",
"path",
")",
"paths",
"=",
"[",
"start_path",
"]",
"+",
"list",
"(",
... | Search for a spor repo containing `path`.
This searches for `spor_dir` in directories dominating `path`. If a
directory containing `spor_dir` is found, then that directory is returned
as a `pathlib.Path`.
Returns: The dominating directory containing `spor_dir` as a
`pathlib.Path`.
Raises:
... | [
"Search",
"for",
"a",
"spor",
"repo",
"containing",
"path",
"."
] | train | https://github.com/abingham/spor/blob/673c8c36c99a4b9ea882f002bfb529f1eca89126/src/spor/repository/repository.py#L148-L171 |
abingham/spor | src/spor/repository/repository.py | Repository.add | def add(self, anchor):
"""Add a new anchor to the repository.
This will create a new ID for the anchor and provision new storage for
it.
Returns: The storage ID for the Anchor which can be used to retrieve
the anchor later.
"""
anchor_id = uuid.uuid4().hex
... | python | def add(self, anchor):
"""Add a new anchor to the repository.
This will create a new ID for the anchor and provision new storage for
it.
Returns: The storage ID for the Anchor which can be used to retrieve
the anchor later.
"""
anchor_id = uuid.uuid4().hex
... | [
"def",
"add",
"(",
"self",
",",
"anchor",
")",
":",
"anchor_id",
"=",
"uuid",
".",
"uuid4",
"(",
")",
".",
"hex",
"anchor_path",
"=",
"self",
".",
"_anchor_path",
"(",
"anchor_id",
")",
"with",
"anchor_path",
".",
"open",
"(",
"mode",
"=",
"'wt'",
")... | Add a new anchor to the repository.
This will create a new ID for the anchor and provision new storage for
it.
Returns: The storage ID for the Anchor which can be used to retrieve
the anchor later. | [
"Add",
"a",
"new",
"anchor",
"to",
"the",
"repository",
"."
] | train | https://github.com/abingham/spor/blob/673c8c36c99a4b9ea882f002bfb529f1eca89126/src/spor/repository/repository.py#L61-L76 |
abingham/spor | src/spor/repository/repository.py | Repository.items | def items(self):
"""An iterable of all (anchor-id, Anchor) mappings in the repository.
"""
for anchor_id in self:
try:
anchor = self[anchor_id]
except KeyError:
assert False, 'Trying to load from missing file or something'
yiel... | python | def items(self):
"""An iterable of all (anchor-id, Anchor) mappings in the repository.
"""
for anchor_id in self:
try:
anchor = self[anchor_id]
except KeyError:
assert False, 'Trying to load from missing file or something'
yiel... | [
"def",
"items",
"(",
"self",
")",
":",
"for",
"anchor_id",
"in",
"self",
":",
"try",
":",
"anchor",
"=",
"self",
"[",
"anchor_id",
"]",
"except",
"KeyError",
":",
"assert",
"False",
",",
"'Trying to load from missing file or something'",
"yield",
"(",
"anchor_... | An iterable of all (anchor-id, Anchor) mappings in the repository. | [
"An",
"iterable",
"of",
"all",
"(",
"anchor",
"-",
"id",
"Anchor",
")",
"mappings",
"in",
"the",
"repository",
"."
] | train | https://github.com/abingham/spor/blob/673c8c36c99a4b9ea882f002bfb529f1eca89126/src/spor/repository/repository.py#L130-L139 |
abingham/spor | src/spor/repository/repository.py | Repository._anchor_path | def _anchor_path(self, anchor_id):
"Absolute path to the data file for `anchor_id`."
file_name = '{}.yml'.format(anchor_id)
file_path = self._spor_dir / file_name
return file_path | python | def _anchor_path(self, anchor_id):
"Absolute path to the data file for `anchor_id`."
file_name = '{}.yml'.format(anchor_id)
file_path = self._spor_dir / file_name
return file_path | [
"def",
"_anchor_path",
"(",
"self",
",",
"anchor_id",
")",
":",
"file_name",
"=",
"'{}.yml'",
".",
"format",
"(",
"anchor_id",
")",
"file_path",
"=",
"self",
".",
"_spor_dir",
"/",
"file_name",
"return",
"file_path"
] | Absolute path to the data file for `anchor_id`. | [
"Absolute",
"path",
"to",
"the",
"data",
"file",
"for",
"anchor_id",
"."
] | train | https://github.com/abingham/spor/blob/673c8c36c99a4b9ea882f002bfb529f1eca89126/src/spor/repository/repository.py#L141-L145 |
Robin8Put/pmes | history/MongoDB/views.py | log | def log(**data):
"""RPC method for logging events
Makes entry with new account creating
Return None
"""
# Get data from request body
entry = {
"module": data["params"]["module"],
"event": data["params"]["event"],
"timestamp": data["params"]["timestamp"],
"arguments": data["params"]["arguments"]
}
# Call... | python | def log(**data):
"""RPC method for logging events
Makes entry with new account creating
Return None
"""
# Get data from request body
entry = {
"module": data["params"]["module"],
"event": data["params"]["event"],
"timestamp": data["params"]["timestamp"],
"arguments": data["params"]["arguments"]
}
# Call... | [
"def",
"log",
"(",
"*",
"*",
"data",
")",
":",
"# Get data from request body",
"entry",
"=",
"{",
"\"module\"",
":",
"data",
"[",
"\"params\"",
"]",
"[",
"\"module\"",
"]",
",",
"\"event\"",
":",
"data",
"[",
"\"params\"",
"]",
"[",
"\"event\"",
"]",
","... | RPC method for logging events
Makes entry with new account creating
Return None | [
"RPC",
"method",
"for",
"logging",
"events",
"Makes",
"entry",
"with",
"new",
"account",
"creating",
"Return",
"None"
] | train | https://github.com/Robin8Put/pmes/blob/338bec94162098f05b75bad035417317e1252fd2/history/MongoDB/views.py#L14-L27 |
Robin8Put/pmes | history/MongoDB/views.py | HistoryHandler.post | def post(self):
"""Accepts jsorpc post request.
Retrieves data from request body.
Calls log method for writung data to database
"""
data = json.loads(self.request.body.decode())
response = dispatch([log],{'jsonrpc': '2.0',
'method': 'log', 'params': data, 'id': 1}) | python | def post(self):
"""Accepts jsorpc post request.
Retrieves data from request body.
Calls log method for writung data to database
"""
data = json.loads(self.request.body.decode())
response = dispatch([log],{'jsonrpc': '2.0',
'method': 'log', 'params': data, 'id': 1}) | [
"def",
"post",
"(",
"self",
")",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"request",
".",
"body",
".",
"decode",
"(",
")",
")",
"response",
"=",
"dispatch",
"(",
"[",
"log",
"]",
",",
"{",
"'jsonrpc'",
":",
"'2.0'",
",",
"'method... | Accepts jsorpc post request.
Retrieves data from request body.
Calls log method for writung data to database | [
"Accepts",
"jsorpc",
"post",
"request",
".",
"Retrieves",
"data",
"from",
"request",
"body",
".",
"Calls",
"log",
"method",
"for",
"writung",
"data",
"to",
"database"
] | train | https://github.com/Robin8Put/pmes/blob/338bec94162098f05b75bad035417317e1252fd2/history/MongoDB/views.py#L37-L44 |
isambard-uob/ampal | src/ampal/align.py | MMCAlign.start_optimisation | def start_optimisation(self, rounds: int, max_angle: float,
max_distance: float, temp: float=298.15,
stop_when=None, verbose=None):
"""Starts the loop fitting protocol.
Parameters
----------
rounds : int
The number of Mon... | python | def start_optimisation(self, rounds: int, max_angle: float,
max_distance: float, temp: float=298.15,
stop_when=None, verbose=None):
"""Starts the loop fitting protocol.
Parameters
----------
rounds : int
The number of Mon... | [
"def",
"start_optimisation",
"(",
"self",
",",
"rounds",
":",
"int",
",",
"max_angle",
":",
"float",
",",
"max_distance",
":",
"float",
",",
"temp",
":",
"float",
"=",
"298.15",
",",
"stop_when",
"=",
"None",
",",
"verbose",
"=",
"None",
")",
":",
"sel... | Starts the loop fitting protocol.
Parameters
----------
rounds : int
The number of Monte Carlo moves to be evaluated.
max_angle : float
The maximum variation in rotation that can moved per
step.
max_distance : float
The maximum dis... | [
"Starts",
"the",
"loop",
"fitting",
"protocol",
"."
] | train | https://github.com/isambard-uob/ampal/blob/906e2afacb435ffb129b381f262ff8e7bfb324c5/src/ampal/align.py#L62-L84 |
isambard-uob/ampal | src/ampal/align.py | MMCAlign._generate_initial_score | def _generate_initial_score(self):
"""Runs the evaluation function for the initial pose."""
self.current_energy = self.eval_fn(self.polypeptide, *self.eval_args)
self.best_energy = copy.deepcopy(self.current_energy)
self.best_model = copy.deepcopy(self.polypeptide)
return | python | def _generate_initial_score(self):
"""Runs the evaluation function for the initial pose."""
self.current_energy = self.eval_fn(self.polypeptide, *self.eval_args)
self.best_energy = copy.deepcopy(self.current_energy)
self.best_model = copy.deepcopy(self.polypeptide)
return | [
"def",
"_generate_initial_score",
"(",
"self",
")",
":",
"self",
".",
"current_energy",
"=",
"self",
".",
"eval_fn",
"(",
"self",
".",
"polypeptide",
",",
"*",
"self",
".",
"eval_args",
")",
"self",
".",
"best_energy",
"=",
"copy",
".",
"deepcopy",
"(",
... | Runs the evaluation function for the initial pose. | [
"Runs",
"the",
"evaluation",
"function",
"for",
"the",
"initial",
"pose",
"."
] | train | https://github.com/isambard-uob/ampal/blob/906e2afacb435ffb129b381f262ff8e7bfb324c5/src/ampal/align.py#L86-L91 |
isambard-uob/ampal | src/ampal/align.py | MMCAlign._mmc_loop | def _mmc_loop(self, rounds, max_angle, max_distance,
temp=298.15, stop_when=None, verbose=True):
"""The main Metropolis Monte Carlo loop."""
current_round = 0
while current_round < rounds:
working_model = copy.deepcopy(self.polypeptide)
random_vector = u... | python | def _mmc_loop(self, rounds, max_angle, max_distance,
temp=298.15, stop_when=None, verbose=True):
"""The main Metropolis Monte Carlo loop."""
current_round = 0
while current_round < rounds:
working_model = copy.deepcopy(self.polypeptide)
random_vector = u... | [
"def",
"_mmc_loop",
"(",
"self",
",",
"rounds",
",",
"max_angle",
",",
"max_distance",
",",
"temp",
"=",
"298.15",
",",
"stop_when",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"current_round",
"=",
"0",
"while",
"current_round",
"<",
"rounds",
"... | The main Metropolis Monte Carlo loop. | [
"The",
"main",
"Metropolis",
"Monte",
"Carlo",
"loop",
"."
] | train | https://github.com/isambard-uob/ampal/blob/906e2afacb435ffb129b381f262ff8e7bfb324c5/src/ampal/align.py#L93-L132 |
isambard-uob/ampal | src/ampal/align.py | MMCAlign.check_move | def check_move(new, old, t):
"""Determines if a model will be accepted."""
if (t <= 0) or numpy.isclose(t, 0.0):
return False
K_BOLTZ = 1.9872041E-003 # kcal/mol.K
if new < old:
return True
else:
move_prob = math.exp(-(new - old) / (K_BOLTZ * ... | python | def check_move(new, old, t):
"""Determines if a model will be accepted."""
if (t <= 0) or numpy.isclose(t, 0.0):
return False
K_BOLTZ = 1.9872041E-003 # kcal/mol.K
if new < old:
return True
else:
move_prob = math.exp(-(new - old) / (K_BOLTZ * ... | [
"def",
"check_move",
"(",
"new",
",",
"old",
",",
"t",
")",
":",
"if",
"(",
"t",
"<=",
"0",
")",
"or",
"numpy",
".",
"isclose",
"(",
"t",
",",
"0.0",
")",
":",
"return",
"False",
"K_BOLTZ",
"=",
"1.9872041E-003",
"# kcal/mol.K",
"if",
"new",
"<",
... | Determines if a model will be accepted. | [
"Determines",
"if",
"a",
"model",
"will",
"be",
"accepted",
"."
] | train | https://github.com/isambard-uob/ampal/blob/906e2afacb435ffb129b381f262ff8e7bfb324c5/src/ampal/align.py#L140-L151 |
sveetch/boussole | boussole/conf/discovery.py | Discover.scan_backends | def scan_backends(self, backends):
"""
From given backends create and return engine, filename and extension
indexes.
Arguments:
backends (list): List of backend engines to scan. Order does matter
since resulted indexes are stored in an ``OrderedDict``. So
... | python | def scan_backends(self, backends):
"""
From given backends create and return engine, filename and extension
indexes.
Arguments:
backends (list): List of backend engines to scan. Order does matter
since resulted indexes are stored in an ``OrderedDict``. So
... | [
"def",
"scan_backends",
"(",
"self",
",",
"backends",
")",
":",
"engines",
"=",
"OrderedDict",
"(",
")",
"filenames",
"=",
"OrderedDict",
"(",
")",
"extensions",
"=",
"OrderedDict",
"(",
")",
"for",
"item",
"in",
"backends",
":",
"engines",
"[",
"item",
... | From given backends create and return engine, filename and extension
indexes.
Arguments:
backends (list): List of backend engines to scan. Order does matter
since resulted indexes are stored in an ``OrderedDict``. So
discovering will stop its job if it meets ... | [
"From",
"given",
"backends",
"create",
"and",
"return",
"engine",
"filename",
"and",
"extension",
"indexes",
"."
] | train | https://github.com/sveetch/boussole/blob/22cc644e9d633f41ebfc167d427a71c1726cee21/boussole/conf/discovery.py#L38-L67 |
sveetch/boussole | boussole/conf/discovery.py | Discover.get_engine | def get_engine(self, filepath, kind=None):
"""
From given filepath try to discover which backend format to use.
Discovering is pretty naive as it find format from file extension.
Args:
filepath (str): Settings filepath or filename.
Keyword Arguments:
ki... | python | def get_engine(self, filepath, kind=None):
"""
From given filepath try to discover which backend format to use.
Discovering is pretty naive as it find format from file extension.
Args:
filepath (str): Settings filepath or filename.
Keyword Arguments:
ki... | [
"def",
"get_engine",
"(",
"self",
",",
"filepath",
",",
"kind",
"=",
"None",
")",
":",
"if",
"not",
"kind",
":",
"extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filepath",
")",
"[",
"1",
"]",
"if",
"not",
"extension",
":",
"msg",
"=",
... | From given filepath try to discover which backend format to use.
Discovering is pretty naive as it find format from file extension.
Args:
filepath (str): Settings filepath or filename.
Keyword Arguments:
kind (str): A format name to enforce a specific backend. Can be a... | [
"From",
"given",
"filepath",
"try",
"to",
"discover",
"which",
"backend",
"format",
"to",
"use",
"."
] | train | https://github.com/sveetch/boussole/blob/22cc644e9d633f41ebfc167d427a71c1726cee21/boussole/conf/discovery.py#L69-L106 |
sveetch/boussole | boussole/conf/discovery.py | Discover.guess_filename | def guess_filename(self, basedir, kind=None):
"""
Try to find existing settings filename from base directory using
default filename from available engines.
First finded filename from available engines win. So registred engines
order matter.
Arguments:
basedi... | python | def guess_filename(self, basedir, kind=None):
"""
Try to find existing settings filename from base directory using
default filename from available engines.
First finded filename from available engines win. So registred engines
order matter.
Arguments:
basedi... | [
"def",
"guess_filename",
"(",
"self",
",",
"basedir",
",",
"kind",
"=",
"None",
")",
":",
"if",
"kind",
":",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"basedir",
",",
"self",
".",
"engines",
"[",
"kind",
"]",
".",
"_default_filename",
")"... | Try to find existing settings filename from base directory using
default filename from available engines.
First finded filename from available engines win. So registred engines
order matter.
Arguments:
basedir (string): Directory path where to search for.
Keyword A... | [
"Try",
"to",
"find",
"existing",
"settings",
"filename",
"from",
"base",
"directory",
"using",
"default",
"filename",
"from",
"available",
"engines",
"."
] | train | https://github.com/sveetch/boussole/blob/22cc644e9d633f41ebfc167d427a71c1726cee21/boussole/conf/discovery.py#L108-L139 |
sveetch/boussole | boussole/conf/discovery.py | Discover.search | def search(self, filepath=None, basedir=None, kind=None):
"""
Search for a settings file.
Keyword Arguments:
filepath (string): Path to a config file, either absolute or
relative. If absolute set its directory as basedir (omitting
given basedir argume... | python | def search(self, filepath=None, basedir=None, kind=None):
"""
Search for a settings file.
Keyword Arguments:
filepath (string): Path to a config file, either absolute or
relative. If absolute set its directory as basedir (omitting
given basedir argume... | [
"def",
"search",
"(",
"self",
",",
"filepath",
"=",
"None",
",",
"basedir",
"=",
"None",
",",
"kind",
"=",
"None",
")",
":",
"# None values would cause trouble with path joining",
"if",
"filepath",
"is",
"None",
":",
"filepath",
"=",
"''",
"if",
"basedir",
"... | Search for a settings file.
Keyword Arguments:
filepath (string): Path to a config file, either absolute or
relative. If absolute set its directory as basedir (omitting
given basedir argument). If relative join it to basedir.
basedir (string): Directory p... | [
"Search",
"for",
"a",
"settings",
"file",
"."
] | train | https://github.com/sveetch/boussole/blob/22cc644e9d633f41ebfc167d427a71c1726cee21/boussole/conf/discovery.py#L141-L191 |
sarugaku/virtenv | virtenv.py | create | def create(python, env_dir, system, prompt, bare, virtualenv_py=None):
"""Main entry point to use this as a module.
"""
if not python or python == sys.executable:
_create_with_this(
env_dir=env_dir, system=system, prompt=prompt,
bare=bare, virtualenv_py=virtualenv_py,
... | python | def create(python, env_dir, system, prompt, bare, virtualenv_py=None):
"""Main entry point to use this as a module.
"""
if not python or python == sys.executable:
_create_with_this(
env_dir=env_dir, system=system, prompt=prompt,
bare=bare, virtualenv_py=virtualenv_py,
... | [
"def",
"create",
"(",
"python",
",",
"env_dir",
",",
"system",
",",
"prompt",
",",
"bare",
",",
"virtualenv_py",
"=",
"None",
")",
":",
"if",
"not",
"python",
"or",
"python",
"==",
"sys",
".",
"executable",
":",
"_create_with_this",
"(",
"env_dir",
"=",
... | Main entry point to use this as a module. | [
"Main",
"entry",
"point",
"to",
"use",
"this",
"as",
"a",
"module",
"."
] | train | https://github.com/sarugaku/virtenv/blob/fc42a9d8dc9f1821d3893899df78e08a081f6ca3/virtenv.py#L150-L163 |
diefans/docker-events | src/docker_events/__init__.py | event.matches | def matches(self, client, event_data):
"""True if all filters are matching."""
for f in self.filters:
if not f(client, event_data):
return False
return True | python | def matches(self, client, event_data):
"""True if all filters are matching."""
for f in self.filters:
if not f(client, event_data):
return False
return True | [
"def",
"matches",
"(",
"self",
",",
"client",
",",
"event_data",
")",
":",
"for",
"f",
"in",
"self",
".",
"filters",
":",
"if",
"not",
"f",
"(",
"client",
",",
"event_data",
")",
":",
"return",
"False",
"return",
"True"
] | True if all filters are matching. | [
"True",
"if",
"all",
"filters",
"are",
"matching",
"."
] | train | https://github.com/diefans/docker-events/blob/cc07591d908fefcc265285ba7fc0047632e06dea/src/docker_events/__init__.py#L40-L47 |
diefans/docker-events | src/docker_events/__init__.py | event.filter_events | def filter_events(cls, client, event_data):
"""Filter registered events and yield them."""
for event in cls.events:
# try event filters
if event.matches(client, event_data):
yield event | python | def filter_events(cls, client, event_data):
"""Filter registered events and yield them."""
for event in cls.events:
# try event filters
if event.matches(client, event_data):
yield event | [
"def",
"filter_events",
"(",
"cls",
",",
"client",
",",
"event_data",
")",
":",
"for",
"event",
"in",
"cls",
".",
"events",
":",
"# try event filters",
"if",
"event",
".",
"matches",
"(",
"client",
",",
"event_data",
")",
":",
"yield",
"event"
] | Filter registered events and yield them. | [
"Filter",
"registered",
"events",
"and",
"yield",
"them",
"."
] | train | https://github.com/diefans/docker-events/blob/cc07591d908fefcc265285ba7fc0047632e06dea/src/docker_events/__init__.py#L50-L56 |
diefans/docker-events | src/docker_events/__init__.py | event.filter_callbacks | def filter_callbacks(cls, client, event_data):
"""Filter registered events and yield all of their callbacks."""
for event in cls.filter_events(client, event_data):
for cb in event.callbacks:
yield cb | python | def filter_callbacks(cls, client, event_data):
"""Filter registered events and yield all of their callbacks."""
for event in cls.filter_events(client, event_data):
for cb in event.callbacks:
yield cb | [
"def",
"filter_callbacks",
"(",
"cls",
",",
"client",
",",
"event_data",
")",
":",
"for",
"event",
"in",
"cls",
".",
"filter_events",
"(",
"client",
",",
"event_data",
")",
":",
"for",
"cb",
"in",
"event",
".",
"callbacks",
":",
"yield",
"cb"
] | Filter registered events and yield all of their callbacks. | [
"Filter",
"registered",
"events",
"and",
"yield",
"all",
"of",
"their",
"callbacks",
"."
] | train | https://github.com/diefans/docker-events/blob/cc07591d908fefcc265285ba7fc0047632e06dea/src/docker_events/__init__.py#L59-L64 |
jelmer/python-fastimport | fastimport/processor.py | ImportProcessor.validate_parameters | def validate_parameters(self):
"""Validate that the parameters are correctly specified."""
for p in self.params:
if p not in self.known_params:
raise errors.UnknownParameter(p, self.known_params) | python | def validate_parameters(self):
"""Validate that the parameters are correctly specified."""
for p in self.params:
if p not in self.known_params:
raise errors.UnknownParameter(p, self.known_params) | [
"def",
"validate_parameters",
"(",
"self",
")",
":",
"for",
"p",
"in",
"self",
".",
"params",
":",
"if",
"p",
"not",
"in",
"self",
".",
"known_params",
":",
"raise",
"errors",
".",
"UnknownParameter",
"(",
"p",
",",
"self",
".",
"known_params",
")"
] | Validate that the parameters are correctly specified. | [
"Validate",
"that",
"the",
"parameters",
"are",
"correctly",
"specified",
"."
] | train | https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/processor.py#L64-L68 |
jantman/webhook2lambda2sqs | webhook2lambda2sqs/runner.py | parse_args | def parse_args(argv):
"""
Use Argparse to parse command-line arguments.
:param argv: list of arguments to parse (``sys.argv[1:]``)
:type argv: :std:term:`list`
:return: parsed arguments
:rtype: :py:class:`argparse.Namespace`
"""
p = argparse.ArgumentParser(
description='webhook2... | python | def parse_args(argv):
"""
Use Argparse to parse command-line arguments.
:param argv: list of arguments to parse (``sys.argv[1:]``)
:type argv: :std:term:`list`
:return: parsed arguments
:rtype: :py:class:`argparse.Namespace`
"""
p = argparse.ArgumentParser(
description='webhook2... | [
"def",
"parse_args",
"(",
"argv",
")",
":",
"p",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'webhook2lambda2sqs - Generate code and manage '",
"'infrastructure for receiving webhooks with AWS API '",
"'Gateway and pushing to SQS via Lambda - <%s>'",
"%",
"P... | Use Argparse to parse command-line arguments.
:param argv: list of arguments to parse (``sys.argv[1:]``)
:type argv: :std:term:`list`
:return: parsed arguments
:rtype: :py:class:`argparse.Namespace` | [
"Use",
"Argparse",
"to",
"parse",
"command",
"-",
"line",
"arguments",
"."
] | train | https://github.com/jantman/webhook2lambda2sqs/blob/c80c18d5a908ba8b8ee624dc3a977c633fba2b7c/webhook2lambda2sqs/runner.py#L75-L170 |
jantman/webhook2lambda2sqs | webhook2lambda2sqs/runner.py | get_base_url | def get_base_url(config, args):
"""
Get the API base url. Try Terraform state first, then
:py:class:`~.AWSInfo`.
:param config: configuration
:type config: :py:class:`~.Config`
:param args: command line arguments
:type args: :py:class:`argparse.Namespace`
:return: API base URL
:rtyp... | python | def get_base_url(config, args):
"""
Get the API base url. Try Terraform state first, then
:py:class:`~.AWSInfo`.
:param config: configuration
:type config: :py:class:`~.Config`
:param args: command line arguments
:type args: :py:class:`argparse.Namespace`
:return: API base URL
:rtyp... | [
"def",
"get_base_url",
"(",
"config",
",",
"args",
")",
":",
"try",
":",
"logger",
".",
"debug",
"(",
"'Trying to get Terraform base_url output'",
")",
"runner",
"=",
"TerraformRunner",
"(",
"config",
",",
"args",
".",
"tf_path",
")",
"outputs",
"=",
"runner",... | Get the API base url. Try Terraform state first, then
:py:class:`~.AWSInfo`.
:param config: configuration
:type config: :py:class:`~.Config`
:param args: command line arguments
:type args: :py:class:`argparse.Namespace`
:return: API base URL
:rtype: str | [
"Get",
"the",
"API",
"base",
"url",
".",
"Try",
"Terraform",
"state",
"first",
"then",
":",
"py",
":",
"class",
":",
"~",
".",
"AWSInfo",
"."
] | train | https://github.com/jantman/webhook2lambda2sqs/blob/c80c18d5a908ba8b8ee624dc3a977c633fba2b7c/webhook2lambda2sqs/runner.py#L202-L228 |
jantman/webhook2lambda2sqs | webhook2lambda2sqs/runner.py | get_api_id | def get_api_id(config, args):
"""
Get the API ID from Terraform, or from AWS if that fails.
:param config: configuration
:type config: :py:class:`~.Config`
:param args: command line arguments
:type args: :py:class:`argparse.Namespace`
:return: API Gateway ID
:rtype: str
"""
try:... | python | def get_api_id(config, args):
"""
Get the API ID from Terraform, or from AWS if that fails.
:param config: configuration
:type config: :py:class:`~.Config`
:param args: command line arguments
:type args: :py:class:`argparse.Namespace`
:return: API Gateway ID
:rtype: str
"""
try:... | [
"def",
"get_api_id",
"(",
"config",
",",
"args",
")",
":",
"try",
":",
"logger",
".",
"debug",
"(",
"'Trying to get Terraform rest_api_id output'",
")",
"runner",
"=",
"TerraformRunner",
"(",
"config",
",",
"args",
".",
"tf_path",
")",
"outputs",
"=",
"runner"... | Get the API ID from Terraform, or from AWS if that fails.
:param config: configuration
:type config: :py:class:`~.Config`
:param args: command line arguments
:type args: :py:class:`argparse.Namespace`
:return: API Gateway ID
:rtype: str | [
"Get",
"the",
"API",
"ID",
"from",
"Terraform",
"or",
"from",
"AWS",
"if",
"that",
"fails",
"."
] | train | https://github.com/jantman/webhook2lambda2sqs/blob/c80c18d5a908ba8b8ee624dc3a977c633fba2b7c/webhook2lambda2sqs/runner.py#L231-L254 |
jantman/webhook2lambda2sqs | webhook2lambda2sqs/runner.py | main | def main(args=None):
"""
Main entry point
"""
# parse args
if args is None:
args = parse_args(sys.argv[1:])
# dump example config if that action
if args.action == 'example-config':
conf, doc = Config.example_config()
print(conf)
sys.stderr.write(doc + "\n")
... | python | def main(args=None):
"""
Main entry point
"""
# parse args
if args is None:
args = parse_args(sys.argv[1:])
# dump example config if that action
if args.action == 'example-config':
conf, doc = Config.example_config()
print(conf)
sys.stderr.write(doc + "\n")
... | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"# parse args",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"parse_args",
"(",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
"# dump example config if that action",
"if",
"args",
".",
"action",
"==",
... | Main entry point | [
"Main",
"entry",
"point"
] | train | https://github.com/jantman/webhook2lambda2sqs/blob/c80c18d5a908ba8b8ee624dc3a977c633fba2b7c/webhook2lambda2sqs/runner.py#L298-L378 |
Fantomas42/mots-vides | mots_vides/scripts/merger.py | cmdline | def cmdline(argv=sys.argv[1:]):
"""
Script for merging different collections of stop words.
"""
parser = ArgumentParser(
description='Create and merge collections of stop words')
parser.add_argument(
'language', help='The language used in the collection')
parser.add_argument('sou... | python | def cmdline(argv=sys.argv[1:]):
"""
Script for merging different collections of stop words.
"""
parser = ArgumentParser(
description='Create and merge collections of stop words')
parser.add_argument(
'language', help='The language used in the collection')
parser.add_argument('sou... | [
"def",
"cmdline",
"(",
"argv",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"'Create and merge collections of stop words'",
")",
"parser",
".",
"add_argument",
"(",
"'language'",
",",
"help",
... | Script for merging different collections of stop words. | [
"Script",
"for",
"merging",
"different",
"collections",
"of",
"stop",
"words",
"."
] | train | https://github.com/Fantomas42/mots-vides/blob/eaeccf73bdb415d0c5559ccd74de360b37a2bbac/mots_vides/scripts/merger.py#L11-L31 |
squidsoup/muddle.py | muddle/core.py | authenticate | def authenticate(api_key, api_url, **kwargs):
"""Returns a muddle instance, with API key and url set for requests."""
muddle = Muddle(**kwargs)
# Login.
muddle.authenticate(api_key, api_url)
return muddle | python | def authenticate(api_key, api_url, **kwargs):
"""Returns a muddle instance, with API key and url set for requests."""
muddle = Muddle(**kwargs)
# Login.
muddle.authenticate(api_key, api_url)
return muddle | [
"def",
"authenticate",
"(",
"api_key",
",",
"api_url",
",",
"*",
"*",
"kwargs",
")",
":",
"muddle",
"=",
"Muddle",
"(",
"*",
"*",
"kwargs",
")",
"# Login.",
"muddle",
".",
"authenticate",
"(",
"api_key",
",",
"api_url",
")",
"return",
"muddle"
] | Returns a muddle instance, with API key and url set for requests. | [
"Returns",
"a",
"muddle",
"instance",
"with",
"API",
"key",
"and",
"url",
"set",
"for",
"requests",
"."
] | train | https://github.com/squidsoup/muddle.py/blob/f58c62e7d92b9ac24a16de007c0fbd6607b15687/muddle/core.py#L13-L20 |
galaxyproject/gravity | gravity/config_manager.py | ConfigManager.get_job_config | def get_job_config(conf):
""" Extract handler names from job_conf.xml
"""
rval = []
root = elementtree.parse(conf).getroot()
for handler in root.find('handlers'):
rval.append({'service_name' : handler.attrib['id']})
return rval | python | def get_job_config(conf):
""" Extract handler names from job_conf.xml
"""
rval = []
root = elementtree.parse(conf).getroot()
for handler in root.find('handlers'):
rval.append({'service_name' : handler.attrib['id']})
return rval | [
"def",
"get_job_config",
"(",
"conf",
")",
":",
"rval",
"=",
"[",
"]",
"root",
"=",
"elementtree",
".",
"parse",
"(",
"conf",
")",
".",
"getroot",
"(",
")",
"for",
"handler",
"in",
"root",
".",
"find",
"(",
"'handlers'",
")",
":",
"rval",
".",
"app... | Extract handler names from job_conf.xml | [
"Extract",
"handler",
"names",
"from",
"job_conf",
".",
"xml"
] | train | https://github.com/galaxyproject/gravity/blob/2f792497fc60874f881c9ef74a5905a286a9ce3e/gravity/config_manager.py#L153-L160 |
galaxyproject/gravity | gravity/config_manager.py | ConfigManager.__load_state | def __load_state(self):
""" Read persisted state from the JSON statefile
"""
try:
return ConfigState(json.load(open(self.config_state_path)))
except (OSError, IOError) as exc:
if exc.errno == errno.ENOENT:
self.__dump_state({})
retu... | python | def __load_state(self):
""" Read persisted state from the JSON statefile
"""
try:
return ConfigState(json.load(open(self.config_state_path)))
except (OSError, IOError) as exc:
if exc.errno == errno.ENOENT:
self.__dump_state({})
retu... | [
"def",
"__load_state",
"(",
"self",
")",
":",
"try",
":",
"return",
"ConfigState",
"(",
"json",
".",
"load",
"(",
"open",
"(",
"self",
".",
"config_state_path",
")",
")",
")",
"except",
"(",
"OSError",
",",
"IOError",
")",
"as",
"exc",
":",
"if",
"ex... | Read persisted state from the JSON statefile | [
"Read",
"persisted",
"state",
"from",
"the",
"JSON",
"statefile"
] | train | https://github.com/galaxyproject/gravity/blob/2f792497fc60874f881c9ef74a5905a286a9ce3e/gravity/config_manager.py#L174-L183 |
galaxyproject/gravity | gravity/config_manager.py | ConfigManager._register_config_file | def _register_config_file(self, key, val):
""" Persist a newly added config file, or update (overwrite) the value
of a previously persisted config.
"""
state = self.__load_state()
if 'config_files' not in state:
state['config_files'] = {}
state['config_files']... | python | def _register_config_file(self, key, val):
""" Persist a newly added config file, or update (overwrite) the value
of a previously persisted config.
"""
state = self.__load_state()
if 'config_files' not in state:
state['config_files'] = {}
state['config_files']... | [
"def",
"_register_config_file",
"(",
"self",
",",
"key",
",",
"val",
")",
":",
"state",
"=",
"self",
".",
"__load_state",
"(",
")",
"if",
"'config_files'",
"not",
"in",
"state",
":",
"state",
"[",
"'config_files'",
"]",
"=",
"{",
"}",
"state",
"[",
"'c... | Persist a newly added config file, or update (overwrite) the value
of a previously persisted config. | [
"Persist",
"a",
"newly",
"added",
"config",
"file",
"or",
"update",
"(",
"overwrite",
")",
"the",
"value",
"of",
"a",
"previously",
"persisted",
"config",
"."
] | train | https://github.com/galaxyproject/gravity/blob/2f792497fc60874f881c9ef74a5905a286a9ce3e/gravity/config_manager.py#L190-L198 |
galaxyproject/gravity | gravity/config_manager.py | ConfigManager._deregister_config_file | def _deregister_config_file(self, key):
""" Deregister a previously registered config file. The caller should
ensure that it was previously registered.
"""
state = self.__load_state()
if 'remove_configs' not in state:
state['remove_configs'] = {}
state['remov... | python | def _deregister_config_file(self, key):
""" Deregister a previously registered config file. The caller should
ensure that it was previously registered.
"""
state = self.__load_state()
if 'remove_configs' not in state:
state['remove_configs'] = {}
state['remov... | [
"def",
"_deregister_config_file",
"(",
"self",
",",
"key",
")",
":",
"state",
"=",
"self",
".",
"__load_state",
"(",
")",
"if",
"'remove_configs'",
"not",
"in",
"state",
":",
"state",
"[",
"'remove_configs'",
"]",
"=",
"{",
"}",
"state",
"[",
"'remove_conf... | Deregister a previously registered config file. The caller should
ensure that it was previously registered. | [
"Deregister",
"a",
"previously",
"registered",
"config",
"file",
".",
"The",
"caller",
"should",
"ensure",
"that",
"it",
"was",
"previously",
"registered",
"."
] | train | https://github.com/galaxyproject/gravity/blob/2f792497fc60874f881c9ef74a5905a286a9ce3e/gravity/config_manager.py#L200-L208 |
galaxyproject/gravity | gravity/config_manager.py | ConfigManager._purge_config_file | def _purge_config_file(self, key):
""" Forget a previously deregister config file. The caller should
ensure that it was previously deregistered.
"""
state = self.__load_state()
del state['remove_configs'][key]
self.__dump_state(state) | python | def _purge_config_file(self, key):
""" Forget a previously deregister config file. The caller should
ensure that it was previously deregistered.
"""
state = self.__load_state()
del state['remove_configs'][key]
self.__dump_state(state) | [
"def",
"_purge_config_file",
"(",
"self",
",",
"key",
")",
":",
"state",
"=",
"self",
".",
"__load_state",
"(",
")",
"del",
"state",
"[",
"'remove_configs'",
"]",
"[",
"key",
"]",
"self",
".",
"__dump_state",
"(",
"state",
")"
] | Forget a previously deregister config file. The caller should
ensure that it was previously deregistered. | [
"Forget",
"a",
"previously",
"deregister",
"config",
"file",
".",
"The",
"caller",
"should",
"ensure",
"that",
"it",
"was",
"previously",
"deregistered",
"."
] | train | https://github.com/galaxyproject/gravity/blob/2f792497fc60874f881c9ef74a5905a286a9ce3e/gravity/config_manager.py#L210-L216 |
galaxyproject/gravity | gravity/config_manager.py | ConfigManager.determine_config_changes | def determine_config_changes(self):
""" The magic: Determine what has changed since the last time.
Caller should pass the returned config to register_config_changes to persist.
"""
# 'update' here is synonymous with 'add or update'
instances = set()
new_configs = {}
... | python | def determine_config_changes(self):
""" The magic: Determine what has changed since the last time.
Caller should pass the returned config to register_config_changes to persist.
"""
# 'update' here is synonymous with 'add or update'
instances = set()
new_configs = {}
... | [
"def",
"determine_config_changes",
"(",
"self",
")",
":",
"# 'update' here is synonymous with 'add or update'",
"instances",
"=",
"set",
"(",
")",
"new_configs",
"=",
"{",
"}",
"meta_changes",
"=",
"{",
"'changed_instances'",
":",
"set",
"(",
")",
",",
"'remove_inst... | The magic: Determine what has changed since the last time.
Caller should pass the returned config to register_config_changes to persist. | [
"The",
"magic",
":",
"Determine",
"what",
"has",
"changed",
"since",
"the",
"last",
"time",
"."
] | train | https://github.com/galaxyproject/gravity/blob/2f792497fc60874f881c9ef74a5905a286a9ce3e/gravity/config_manager.py#L218-L281 |
galaxyproject/gravity | gravity/config_manager.py | ConfigManager.register_config_changes | def register_config_changes(self, configs, meta_changes):
""" Persist config changes to the JSON state file. When a config
changes, a process manager may perform certain actions based on these
changes. This method can be called once the actions are complete.
"""
for config_file i... | python | def register_config_changes(self, configs, meta_changes):
""" Persist config changes to the JSON state file. When a config
changes, a process manager may perform certain actions based on these
changes. This method can be called once the actions are complete.
"""
for config_file i... | [
"def",
"register_config_changes",
"(",
"self",
",",
"configs",
",",
"meta_changes",
")",
":",
"for",
"config_file",
"in",
"meta_changes",
"[",
"'remove_configs'",
"]",
".",
"keys",
"(",
")",
":",
"self",
".",
"_purge_config_file",
"(",
"config_file",
")",
"for... | Persist config changes to the JSON state file. When a config
changes, a process manager may perform certain actions based on these
changes. This method can be called once the actions are complete. | [
"Persist",
"config",
"changes",
"to",
"the",
"JSON",
"state",
"file",
".",
"When",
"a",
"config",
"changes",
"a",
"process",
"manager",
"may",
"perform",
"certain",
"actions",
"based",
"on",
"these",
"changes",
".",
"This",
"method",
"can",
"be",
"called",
... | train | https://github.com/galaxyproject/gravity/blob/2f792497fc60874f881c9ef74a5905a286a9ce3e/gravity/config_manager.py#L283-L303 |
galaxyproject/gravity | gravity/config_manager.py | ConfigManager.get_registered_configs | def get_registered_configs(self, instances=None):
""" Return the persisted values of all config files registered with the config manager.
"""
configs = self.state.get('config_files', {})
if instances is not None:
for config_file, config in configs.items():
if ... | python | def get_registered_configs(self, instances=None):
""" Return the persisted values of all config files registered with the config manager.
"""
configs = self.state.get('config_files', {})
if instances is not None:
for config_file, config in configs.items():
if ... | [
"def",
"get_registered_configs",
"(",
"self",
",",
"instances",
"=",
"None",
")",
":",
"configs",
"=",
"self",
".",
"state",
".",
"get",
"(",
"'config_files'",
",",
"{",
"}",
")",
"if",
"instances",
"is",
"not",
"None",
":",
"for",
"config_file",
",",
... | Return the persisted values of all config files registered with the config manager. | [
"Return",
"the",
"persisted",
"values",
"of",
"all",
"config",
"files",
"registered",
"with",
"the",
"config",
"manager",
"."
] | train | https://github.com/galaxyproject/gravity/blob/2f792497fc60874f881c9ef74a5905a286a9ce3e/gravity/config_manager.py#L311-L319 |
galaxyproject/gravity | gravity/config_manager.py | ConfigManager.get_registered_instances | def get_registered_instances(self, include_removed=False):
""" Return the persisted names of all instances across all registered configs.
"""
rval = []
configs = self.state.get('config_files', {}).values()
if include_removed:
configs.extend(self.state.get('remove_conf... | python | def get_registered_instances(self, include_removed=False):
""" Return the persisted names of all instances across all registered configs.
"""
rval = []
configs = self.state.get('config_files', {}).values()
if include_removed:
configs.extend(self.state.get('remove_conf... | [
"def",
"get_registered_instances",
"(",
"self",
",",
"include_removed",
"=",
"False",
")",
":",
"rval",
"=",
"[",
"]",
"configs",
"=",
"self",
".",
"state",
".",
"get",
"(",
"'config_files'",
",",
"{",
"}",
")",
".",
"values",
"(",
")",
"if",
"include_... | Return the persisted names of all instances across all registered configs. | [
"Return",
"the",
"persisted",
"names",
"of",
"all",
"instances",
"across",
"all",
"registered",
"configs",
"."
] | train | https://github.com/galaxyproject/gravity/blob/2f792497fc60874f881c9ef74a5905a286a9ce3e/gravity/config_manager.py#L331-L341 |
galaxyproject/gravity | gravity/config_manager.py | ConfigManager.add | def add(self, config_files, galaxy_root=None):
""" Public method to add (register) config file(s).
"""
for config_file in config_files:
config_file = abspath(expanduser(config_file))
if self.is_registered(config_file):
log.warning('%s is already registered... | python | def add(self, config_files, galaxy_root=None):
""" Public method to add (register) config file(s).
"""
for config_file in config_files:
config_file = abspath(expanduser(config_file))
if self.is_registered(config_file):
log.warning('%s is already registered... | [
"def",
"add",
"(",
"self",
",",
"config_files",
",",
"galaxy_root",
"=",
"None",
")",
":",
"for",
"config_file",
"in",
"config_files",
":",
"config_file",
"=",
"abspath",
"(",
"expanduser",
"(",
"config_file",
")",
")",
"if",
"self",
".",
"is_registered",
... | Public method to add (register) config file(s). | [
"Public",
"method",
"to",
"add",
"(",
"register",
")",
"config",
"file",
"(",
"s",
")",
"."
] | train | https://github.com/galaxyproject/gravity/blob/2f792497fc60874f881c9ef74a5905a286a9ce3e/gravity/config_manager.py#L362-L387 |
welchbj/sublemon | demos/from_the_readme.py | main | async def main():
"""`sublemon` library example!"""
for c in (1, 2, 4,):
async with Sublemon(max_concurrency=c) as s:
start = time.perf_counter()
await asyncio.gather(one(s), two(s))
end = time.perf_counter()
print('Limiting to', c, 'concurrent subprocess(... | python | async def main():
"""`sublemon` library example!"""
for c in (1, 2, 4,):
async with Sublemon(max_concurrency=c) as s:
start = time.perf_counter()
await asyncio.gather(one(s), two(s))
end = time.perf_counter()
print('Limiting to', c, 'concurrent subprocess(... | [
"async",
"def",
"main",
"(",
")",
":",
"for",
"c",
"in",
"(",
"1",
",",
"2",
",",
"4",
",",
")",
":",
"async",
"with",
"Sublemon",
"(",
"max_concurrency",
"=",
"c",
")",
"as",
"s",
":",
"start",
"=",
"time",
".",
"perf_counter",
"(",
")",
"awai... | `sublemon` library example! | [
"sublemon",
"library",
"example!"
] | train | https://github.com/welchbj/sublemon/blob/edbfd1ca2a0ce3de9470dfc88f8db1cadf4b6326/demos/from_the_readme.py#L12-L20 |
welchbj/sublemon | demos/from_the_readme.py | one | async def one(s: Sublemon):
"""Spin up some subprocesses, sleep, and echo a message for this coro."""
shell_cmds = [
'sleep 1 && echo subprocess 1 in coroutine one',
'sleep 1 && echo subprocess 2 in coroutine one']
async for line in s.iter_lines(*shell_cmds):
print(line) | python | async def one(s: Sublemon):
"""Spin up some subprocesses, sleep, and echo a message for this coro."""
shell_cmds = [
'sleep 1 && echo subprocess 1 in coroutine one',
'sleep 1 && echo subprocess 2 in coroutine one']
async for line in s.iter_lines(*shell_cmds):
print(line) | [
"async",
"def",
"one",
"(",
"s",
":",
"Sublemon",
")",
":",
"shell_cmds",
"=",
"[",
"'sleep 1 && echo subprocess 1 in coroutine one'",
",",
"'sleep 1 && echo subprocess 2 in coroutine one'",
"]",
"async",
"for",
"line",
"in",
"s",
".",
"iter_lines",
"(",
"*",
"shell... | Spin up some subprocesses, sleep, and echo a message for this coro. | [
"Spin",
"up",
"some",
"subprocesses",
"sleep",
"and",
"echo",
"a",
"message",
"for",
"this",
"coro",
"."
] | train | https://github.com/welchbj/sublemon/blob/edbfd1ca2a0ce3de9470dfc88f8db1cadf4b6326/demos/from_the_readme.py#L23-L29 |
welchbj/sublemon | demos/from_the_readme.py | two | async def two(s: Sublemon):
"""Spin up some subprocesses, sleep, and echo a message for this coro."""
subprocess_1, subprocess_2 = s.spawn(
'sleep 1 && echo subprocess 1 in coroutine two',
'sleep 1 && echo subprocess 2 in coroutine two')
async for line in amerge(subprocess_1.stdout, subproce... | python | async def two(s: Sublemon):
"""Spin up some subprocesses, sleep, and echo a message for this coro."""
subprocess_1, subprocess_2 = s.spawn(
'sleep 1 && echo subprocess 1 in coroutine two',
'sleep 1 && echo subprocess 2 in coroutine two')
async for line in amerge(subprocess_1.stdout, subproce... | [
"async",
"def",
"two",
"(",
"s",
":",
"Sublemon",
")",
":",
"subprocess_1",
",",
"subprocess_2",
"=",
"s",
".",
"spawn",
"(",
"'sleep 1 && echo subprocess 1 in coroutine two'",
",",
"'sleep 1 && echo subprocess 2 in coroutine two'",
")",
"async",
"for",
"line",
"in",
... | Spin up some subprocesses, sleep, and echo a message for this coro. | [
"Spin",
"up",
"some",
"subprocesses",
"sleep",
"and",
"echo",
"a",
"message",
"for",
"this",
"coro",
"."
] | train | https://github.com/welchbj/sublemon/blob/edbfd1ca2a0ce3de9470dfc88f8db1cadf4b6326/demos/from_the_readme.py#L32-L38 |
disqus/nose-performance | src/noseperf/stacks.py | get_lines_from_file | def get_lines_from_file(filename, lineno, context_lines, loader=None, module_name=None):
"""
Returns context_lines before and after lineno from file.
Returns (pre_context_lineno, pre_context, context_line, post_context).
"""
source = None
if loader is not None and hasattr(loader, "get_source"):
... | python | def get_lines_from_file(filename, lineno, context_lines, loader=None, module_name=None):
"""
Returns context_lines before and after lineno from file.
Returns (pre_context_lineno, pre_context, context_line, post_context).
"""
source = None
if loader is not None and hasattr(loader, "get_source"):
... | [
"def",
"get_lines_from_file",
"(",
"filename",
",",
"lineno",
",",
"context_lines",
",",
"loader",
"=",
"None",
",",
"module_name",
"=",
"None",
")",
":",
"source",
"=",
"None",
"if",
"loader",
"is",
"not",
"None",
"and",
"hasattr",
"(",
"loader",
",",
"... | Returns context_lines before and after lineno from file.
Returns (pre_context_lineno, pre_context, context_line, post_context). | [
"Returns",
"context_lines",
"before",
"and",
"after",
"lineno",
"from",
"file",
".",
"Returns",
"(",
"pre_context_lineno",
"pre_context",
"context_line",
"post_context",
")",
"."
] | train | https://github.com/disqus/nose-performance/blob/916c8bd7fe7f30e4b7cba24a79a4157fd7889ec2/src/noseperf/stacks.py#L39-L97 |
disqus/nose-performance | src/noseperf/stacks.py | get_stack_info | def get_stack_info(frames):
"""
Given a list of frames, returns a list of stack information
dictionary objects that are JSON-ready.
We have to be careful here as certain implementations of the
_Frame class do not contain the nescesary data to lookup all
of the information we want.
"""
_... | python | def get_stack_info(frames):
"""
Given a list of frames, returns a list of stack information
dictionary objects that are JSON-ready.
We have to be careful here as certain implementations of the
_Frame class do not contain the nescesary data to lookup all
of the information we want.
"""
_... | [
"def",
"get_stack_info",
"(",
"frames",
")",
":",
"__traceback_hide__",
"=",
"True",
"# NOQA",
"results",
"=",
"[",
"]",
"for",
"frame_info",
"in",
"frames",
":",
"# Old, terrible API",
"if",
"isinstance",
"(",
"frame_info",
",",
"(",
"list",
",",
"tuple",
"... | Given a list of frames, returns a list of stack information
dictionary objects that are JSON-ready.
We have to be careful here as certain implementations of the
_Frame class do not contain the nescesary data to lookup all
of the information we want. | [
"Given",
"a",
"list",
"of",
"frames",
"returns",
"a",
"list",
"of",
"stack",
"information",
"dictionary",
"objects",
"that",
"are",
"JSON",
"-",
"ready",
"."
] | train | https://github.com/disqus/nose-performance/blob/916c8bd7fe7f30e4b7cba24a79a4157fd7889ec2/src/noseperf/stacks.py#L127-L193 |
grahambell/pymoc | lib/pymoc/util/catalog.py | catalog_to_moc | def catalog_to_moc(catalog, radius, order, **kwargs):
"""
Convert a catalog to a MOC.
The catalog is given as an Astropy SkyCoord object containing
multiple coordinates. The radius of catalog entries can be
given as an Astropy Quantity (with units), otherwise it is assumed
to be in arcseconds.... | python | def catalog_to_moc(catalog, radius, order, **kwargs):
"""
Convert a catalog to a MOC.
The catalog is given as an Astropy SkyCoord object containing
multiple coordinates. The radius of catalog entries can be
given as an Astropy Quantity (with units), otherwise it is assumed
to be in arcseconds.... | [
"def",
"catalog_to_moc",
"(",
"catalog",
",",
"radius",
",",
"order",
",",
"*",
"*",
"kwargs",
")",
":",
"# Generate list of MOC cells.",
"cells",
"=",
"catalog_to_cells",
"(",
"catalog",
",",
"radius",
",",
"order",
",",
"*",
"*",
"kwargs",
")",
"# Create n... | Convert a catalog to a MOC.
The catalog is given as an Astropy SkyCoord object containing
multiple coordinates. The radius of catalog entries can be
given as an Astropy Quantity (with units), otherwise it is assumed
to be in arcseconds.
Any additional keyword arguments are passed on to `catalog_t... | [
"Convert",
"a",
"catalog",
"to",
"a",
"MOC",
"."
] | train | https://github.com/grahambell/pymoc/blob/0e2e57ce07ff3de6ac024627c1fb6ad30c2fde48/lib/pymoc/util/catalog.py#L32-L50 |
grahambell/pymoc | lib/pymoc/util/catalog.py | _catalog_to_cells_neighbor | def _catalog_to_cells_neighbor(catalog, radius, order):
"""
Convert a catalog to a list of cells.
This is the original implementation of the `catalog_to_cells`
function which does not make use of the Healpy `query_disc` routine.
Note: this function uses a simple flood-filling approach and is
v... | python | def _catalog_to_cells_neighbor(catalog, radius, order):
"""
Convert a catalog to a list of cells.
This is the original implementation of the `catalog_to_cells`
function which does not make use of the Healpy `query_disc` routine.
Note: this function uses a simple flood-filling approach and is
v... | [
"def",
"_catalog_to_cells_neighbor",
"(",
"catalog",
",",
"radius",
",",
"order",
")",
":",
"if",
"not",
"isinstance",
"(",
"radius",
",",
"Quantity",
")",
":",
"radius",
"=",
"radius",
"*",
"arcsecond",
"nside",
"=",
"2",
"**",
"order",
"# Ensure catalog is... | Convert a catalog to a list of cells.
This is the original implementation of the `catalog_to_cells`
function which does not make use of the Healpy `query_disc` routine.
Note: this function uses a simple flood-filling approach and is
very slow, especially when used with a large radius for catalog objec... | [
"Convert",
"a",
"catalog",
"to",
"a",
"list",
"of",
"cells",
"."
] | train | https://github.com/grahambell/pymoc/blob/0e2e57ce07ff3de6ac024627c1fb6ad30c2fde48/lib/pymoc/util/catalog.py#L53-L113 |
grahambell/pymoc | lib/pymoc/util/catalog.py | catalog_to_cells | def catalog_to_cells(catalog, radius, order, include_fallback=True, **kwargs):
"""
Convert a catalog to a set of cells.
This function is intended to be used via `catalog_to_moc` but
is available for separate usage. It takes the same arguments
as that function.
This function uses the Healpy `q... | python | def catalog_to_cells(catalog, radius, order, include_fallback=True, **kwargs):
"""
Convert a catalog to a set of cells.
This function is intended to be used via `catalog_to_moc` but
is available for separate usage. It takes the same arguments
as that function.
This function uses the Healpy `q... | [
"def",
"catalog_to_cells",
"(",
"catalog",
",",
"radius",
",",
"order",
",",
"include_fallback",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"nside",
"=",
"2",
"**",
"order",
"# Ensure catalog is in ICRS coordinates.",
"catalog",
"=",
"catalog",
".",
"icrs... | Convert a catalog to a set of cells.
This function is intended to be used via `catalog_to_moc` but
is available for separate usage. It takes the same arguments
as that function.
This function uses the Healpy `query_disc` function to get a list
of cells for each item in the catalog in turn. Addit... | [
"Convert",
"a",
"catalog",
"to",
"a",
"set",
"of",
"cells",
"."
] | train | https://github.com/grahambell/pymoc/blob/0e2e57ce07ff3de6ac024627c1fb6ad30c2fde48/lib/pymoc/util/catalog.py#L116-L180 |
grahambell/pymoc | lib/pymoc/util/catalog.py | read_ascii_catalog | def read_ascii_catalog(filename, format_, unit=None):
"""
Read an ASCII catalog file using Astropy.
This routine is used by pymoctool to load coordinates from a
catalog file in order to generate a MOC representation.
"""
catalog = ascii.read(filename, format=format_)
columns = catalog.colu... | python | def read_ascii_catalog(filename, format_, unit=None):
"""
Read an ASCII catalog file using Astropy.
This routine is used by pymoctool to load coordinates from a
catalog file in order to generate a MOC representation.
"""
catalog = ascii.read(filename, format=format_)
columns = catalog.colu... | [
"def",
"read_ascii_catalog",
"(",
"filename",
",",
"format_",
",",
"unit",
"=",
"None",
")",
":",
"catalog",
"=",
"ascii",
".",
"read",
"(",
"filename",
",",
"format",
"=",
"format_",
")",
"columns",
"=",
"catalog",
".",
"columns",
"if",
"'RA'",
"in",
... | Read an ASCII catalog file using Astropy.
This routine is used by pymoctool to load coordinates from a
catalog file in order to generate a MOC representation. | [
"Read",
"an",
"ASCII",
"catalog",
"file",
"using",
"Astropy",
"."
] | train | https://github.com/grahambell/pymoc/blob/0e2e57ce07ff3de6ac024627c1fb6ad30c2fde48/lib/pymoc/util/catalog.py#L183-L215 |
aparsons/threadfix_api | threadfix_api/threadfix.py | ThreadFixAPI.create_application | def create_application(self, team_id, name, url=None):
"""
Creates an application under a given team.
:param team_id: Team identifier.
:param name: The name of the new application being created.
:param url: The url of where the application is located.
"""
params =... | python | def create_application(self, team_id, name, url=None):
"""
Creates an application under a given team.
:param team_id: Team identifier.
:param name: The name of the new application being created.
:param url: The url of where the application is located.
"""
params =... | [
"def",
"create_application",
"(",
"self",
",",
"team_id",
",",
"name",
",",
"url",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'name'",
":",
"name",
"}",
"if",
"url",
":",
"params",
"[",
"'url'",
"]",
"=",
"url",
"return",
"self",
".",
"_request",
... | Creates an application under a given team.
:param team_id: Team identifier.
:param name: The name of the new application being created.
:param url: The url of where the application is located. | [
"Creates",
"an",
"application",
"under",
"a",
"given",
"team",
".",
":",
"param",
"team_id",
":",
"Team",
"identifier",
".",
":",
"param",
"name",
":",
"The",
"name",
"of",
"the",
"new",
"application",
"being",
"created",
".",
":",
"param",
"url",
":",
... | train | https://github.com/aparsons/threadfix_api/blob/76fd1bd26e9ac863636112cd30d733543807ff7d/threadfix_api/threadfix.py#L70-L80 |
aparsons/threadfix_api | threadfix_api/threadfix.py | ThreadFixAPI.get_application_by_name | def get_application_by_name(self, team_name, application_name):
"""
Retrieves an application using the given team name and application name.
:param team_name: The name of the team of the application to be retrieved.
:param application_name: The name of the application to be retrieved.
... | python | def get_application_by_name(self, team_name, application_name):
"""
Retrieves an application using the given team name and application name.
:param team_name: The name of the team of the application to be retrieved.
:param application_name: The name of the application to be retrieved.
... | [
"def",
"get_application_by_name",
"(",
"self",
",",
"team_name",
",",
"application_name",
")",
":",
"return",
"self",
".",
"_request",
"(",
"'GET'",
",",
"'rest/applications/'",
"+",
"str",
"(",
"team_name",
")",
"+",
"'/lookup?name='",
"+",
"str",
"(",
"appli... | Retrieves an application using the given team name and application name.
:param team_name: The name of the team of the application to be retrieved.
:param application_name: The name of the application to be retrieved. | [
"Retrieves",
"an",
"application",
"using",
"the",
"given",
"team",
"name",
"and",
"application",
"name",
".",
":",
"param",
"team_name",
":",
"The",
"name",
"of",
"the",
"team",
"of",
"the",
"application",
"to",
"be",
"retrieved",
".",
":",
"param",
"appli... | train | https://github.com/aparsons/threadfix_api/blob/76fd1bd26e9ac863636112cd30d733543807ff7d/threadfix_api/threadfix.py#L89-L95 |
aparsons/threadfix_api | threadfix_api/threadfix.py | ThreadFixAPI.set_application_parameters | def set_application_parameters(self, application_id, framework_type, repository_url):
"""
Sets parameters for the Hybrid Analysis Mapping ThreadFix functionality.
:param application_id: Application identifier.
:param framework_type: The web framework the app was built on. ('None', 'DETEC... | python | def set_application_parameters(self, application_id, framework_type, repository_url):
"""
Sets parameters for the Hybrid Analysis Mapping ThreadFix functionality.
:param application_id: Application identifier.
:param framework_type: The web framework the app was built on. ('None', 'DETEC... | [
"def",
"set_application_parameters",
"(",
"self",
",",
"application_id",
",",
"framework_type",
",",
"repository_url",
")",
":",
"params",
"=",
"{",
"'frameworkType'",
":",
"framework_type",
",",
"'repositoryUrl'",
":",
"repository_url",
"}",
"return",
"self",
".",
... | Sets parameters for the Hybrid Analysis Mapping ThreadFix functionality.
:param application_id: Application identifier.
:param framework_type: The web framework the app was built on. ('None', 'DETECT', 'JSP', 'SPRING_MVC')
:param repository_url: The git repository where the source code for the a... | [
"Sets",
"parameters",
"for",
"the",
"Hybrid",
"Analysis",
"Mapping",
"ThreadFix",
"functionality",
".",
":",
"param",
"application_id",
":",
"Application",
"identifier",
".",
":",
"param",
"framework_type",
":",
"The",
"web",
"framework",
"the",
"app",
"was",
"b... | train | https://github.com/aparsons/threadfix_api/blob/76fd1bd26e9ac863636112cd30d733543807ff7d/threadfix_api/threadfix.py#L97-L108 |
aparsons/threadfix_api | threadfix_api/threadfix.py | ThreadFixAPI.create_manual_finding | def create_manual_finding(self, application_id, vulnerability_type, description, severity, full_url=None,
native_id=None, path=None):
"""
Creates a manual finding with given properties.
:param application_id: Application identification.
:param vulnerability_... | python | def create_manual_finding(self, application_id, vulnerability_type, description, severity, full_url=None,
native_id=None, path=None):
"""
Creates a manual finding with given properties.
:param application_id: Application identification.
:param vulnerability_... | [
"def",
"create_manual_finding",
"(",
"self",
",",
"application_id",
",",
"vulnerability_type",
",",
"description",
",",
"severity",
",",
"full_url",
"=",
"None",
",",
"native_id",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'isStati... | Creates a manual finding with given properties.
:param application_id: Application identification.
:param vulnerability_type: Name of CWE vulnerability.
:param description: General description of the issue.
:param severity: Severity level from 0-8.
:param full_url: Absolute URL t... | [
"Creates",
"a",
"manual",
"finding",
"with",
"given",
"properties",
".",
":",
"param",
"application_id",
":",
"Application",
"identification",
".",
":",
"param",
"vulnerability_type",
":",
"Name",
"of",
"CWE",
"vulnerability",
".",
":",
"param",
"description",
"... | train | https://github.com/aparsons/threadfix_api/blob/76fd1bd26e9ac863636112cd30d733543807ff7d/threadfix_api/threadfix.py#L128-L155 |
aparsons/threadfix_api | threadfix_api/threadfix.py | ThreadFixAPI.create_static_finding | def create_static_finding(self, application_id, vulnerability_type, description, severity, parameter=None,
file_path=None, native_id=None, column=None, line_text=None, line_number=None):
"""
Creates a static finding with given properties.
:param application_id: Appl... | python | def create_static_finding(self, application_id, vulnerability_type, description, severity, parameter=None,
file_path=None, native_id=None, column=None, line_text=None, line_number=None):
"""
Creates a static finding with given properties.
:param application_id: Appl... | [
"def",
"create_static_finding",
"(",
"self",
",",
"application_id",
",",
"vulnerability_type",
",",
"description",
",",
"severity",
",",
"parameter",
"=",
"None",
",",
"file_path",
"=",
"None",
",",
"native_id",
"=",
"None",
",",
"column",
"=",
"None",
",",
... | Creates a static finding with given properties.
:param application_id: Application identifier number.
:param vulnerability_type: Name of CWE vulnerability.
:param description: General description of the issue.
:param severity: Severity level from 0-8.
:param parameter: Request pa... | [
"Creates",
"a",
"static",
"finding",
"with",
"given",
"properties",
".",
":",
"param",
"application_id",
":",
"Application",
"identifier",
"number",
".",
":",
"param",
"vulnerability_type",
":",
"Name",
"of",
"CWE",
"vulnerability",
".",
":",
"param",
"descripti... | train | https://github.com/aparsons/threadfix_api/blob/76fd1bd26e9ac863636112cd30d733543807ff7d/threadfix_api/threadfix.py#L157-L192 |
aparsons/threadfix_api | threadfix_api/threadfix.py | ThreadFixAPI.upload_scan | def upload_scan(self, application_id, file_path):
"""
Uploads and processes a scan file.
:param application_id: Application identifier.
:param file_path: Path to the scan file to be uploaded.
"""
return self._request(
'POST', 'rest/applications/' + str(applica... | python | def upload_scan(self, application_id, file_path):
"""
Uploads and processes a scan file.
:param application_id: Application identifier.
:param file_path: Path to the scan file to be uploaded.
"""
return self._request(
'POST', 'rest/applications/' + str(applica... | [
"def",
"upload_scan",
"(",
"self",
",",
"application_id",
",",
"file_path",
")",
":",
"return",
"self",
".",
"_request",
"(",
"'POST'",
",",
"'rest/applications/'",
"+",
"str",
"(",
"application_id",
")",
"+",
"'/upload'",
",",
"files",
"=",
"{",
"'file'",
... | Uploads and processes a scan file.
:param application_id: Application identifier.
:param file_path: Path to the scan file to be uploaded. | [
"Uploads",
"and",
"processes",
"a",
"scan",
"file",
".",
":",
"param",
"application_id",
":",
"Application",
"identifier",
".",
":",
"param",
"file_path",
":",
"Path",
"to",
"the",
"scan",
"file",
"to",
"be",
"uploaded",
"."
] | train | https://github.com/aparsons/threadfix_api/blob/76fd1bd26e9ac863636112cd30d733543807ff7d/threadfix_api/threadfix.py#L194-L203 |
aparsons/threadfix_api | threadfix_api/threadfix.py | ThreadFixAPI.create_waf | def create_waf(self, name, waf_type):
"""
Creates a WAF with the given type.
:param name: Name of the WAF.
:param waf_type: WAF type. ('mod_security', 'Snort', 'Imperva SecureSphere', 'F5 BigIP ASM', 'DenyAll rWeb')
"""
params = {
'name': name,
'ty... | python | def create_waf(self, name, waf_type):
"""
Creates a WAF with the given type.
:param name: Name of the WAF.
:param waf_type: WAF type. ('mod_security', 'Snort', 'Imperva SecureSphere', 'F5 BigIP ASM', 'DenyAll rWeb')
"""
params = {
'name': name,
'ty... | [
"def",
"create_waf",
"(",
"self",
",",
"name",
",",
"waf_type",
")",
":",
"params",
"=",
"{",
"'name'",
":",
"name",
",",
"'type'",
":",
"waf_type",
"}",
"return",
"self",
".",
"_request",
"(",
"'POST'",
",",
"'rest/wafs/new'",
",",
"params",
")"
] | Creates a WAF with the given type.
:param name: Name of the WAF.
:param waf_type: WAF type. ('mod_security', 'Snort', 'Imperva SecureSphere', 'F5 BigIP ASM', 'DenyAll rWeb') | [
"Creates",
"a",
"WAF",
"with",
"the",
"given",
"type",
".",
":",
"param",
"name",
":",
"Name",
"of",
"the",
"WAF",
".",
":",
"param",
"waf_type",
":",
"WAF",
"type",
".",
"(",
"mod_security",
"Snort",
"Imperva",
"SecureSphere",
"F5",
"BigIP",
"ASM",
"D... | train | https://github.com/aparsons/threadfix_api/blob/76fd1bd26e9ac863636112cd30d733543807ff7d/threadfix_api/threadfix.py#L211-L221 |
aparsons/threadfix_api | threadfix_api/threadfix.py | ThreadFixAPI.get_waf_rules_by_application | def get_waf_rules_by_application(self, waf_id, application_id):
"""
Returns the WAF rule text for one or all of the applications in a WAF. If the application id is -1, it will get
rules for all apps. If the application is a valid application id, rules will be generated for that application.
... | python | def get_waf_rules_by_application(self, waf_id, application_id):
"""
Returns the WAF rule text for one or all of the applications in a WAF. If the application id is -1, it will get
rules for all apps. If the application is a valid application id, rules will be generated for that application.
... | [
"def",
"get_waf_rules_by_application",
"(",
"self",
",",
"waf_id",
",",
"application_id",
")",
":",
"return",
"self",
".",
"_request",
"(",
"'GET'",
",",
"'rest/wafs/'",
"+",
"str",
"(",
"waf_id",
")",
"+",
"'/rules/app/'",
"+",
"str",
"(",
"application_id",
... | Returns the WAF rule text for one or all of the applications in a WAF. If the application id is -1, it will get
rules for all apps. If the application is a valid application id, rules will be generated for that application.
:param waf_id: WAF identifier.
:param application_id: Application identi... | [
"Returns",
"the",
"WAF",
"rule",
"text",
"for",
"one",
"or",
"all",
"of",
"the",
"applications",
"in",
"a",
"WAF",
".",
"If",
"the",
"application",
"id",
"is",
"-",
"1",
"it",
"will",
"get",
"rules",
"for",
"all",
"apps",
".",
"If",
"the",
"applicati... | train | https://github.com/aparsons/threadfix_api/blob/76fd1bd26e9ac863636112cd30d733543807ff7d/threadfix_api/threadfix.py#L244-L251 |
aparsons/threadfix_api | threadfix_api/threadfix.py | ThreadFixAPI.upload_waf_log | def upload_waf_log(self, waf_id, file_path):
"""
Uploads and processes a WAF log.
:param waf_id: WAF identifier.
:param file_path: Path to the WAF log file to be uploaded.
"""
return self._request('POST', 'rest/wafs/' + str(waf_id) + '/uploadLog', files={'file': open(file... | python | def upload_waf_log(self, waf_id, file_path):
"""
Uploads and processes a WAF log.
:param waf_id: WAF identifier.
:param file_path: Path to the WAF log file to be uploaded.
"""
return self._request('POST', 'rest/wafs/' + str(waf_id) + '/uploadLog', files={'file': open(file... | [
"def",
"upload_waf_log",
"(",
"self",
",",
"waf_id",
",",
"file_path",
")",
":",
"return",
"self",
".",
"_request",
"(",
"'POST'",
",",
"'rest/wafs/'",
"+",
"str",
"(",
"waf_id",
")",
"+",
"'/uploadLog'",
",",
"files",
"=",
"{",
"'file'",
":",
"open",
... | Uploads and processes a WAF log.
:param waf_id: WAF identifier.
:param file_path: Path to the WAF log file to be uploaded. | [
"Uploads",
"and",
"processes",
"a",
"WAF",
"log",
".",
":",
"param",
"waf_id",
":",
"WAF",
"identifier",
".",
":",
"param",
"file_path",
":",
"Path",
"to",
"the",
"WAF",
"log",
"file",
"to",
"be",
"uploaded",
"."
] | train | https://github.com/aparsons/threadfix_api/blob/76fd1bd26e9ac863636112cd30d733543807ff7d/threadfix_api/threadfix.py#L253-L259 |
aparsons/threadfix_api | threadfix_api/threadfix.py | ThreadFixAPI.get_vulnerabilities | def get_vulnerabilities(self, teams=None, applications=None, channel_types=None, start_date=None, end_date=None,
generic_severities=None, generic_vulnerabilities=None, number_merged=None,
number_vulnerabilities=None, parameter=None, path=None, show_open=None, show... | python | def get_vulnerabilities(self, teams=None, applications=None, channel_types=None, start_date=None, end_date=None,
generic_severities=None, generic_vulnerabilities=None, number_merged=None,
number_vulnerabilities=None, parameter=None, path=None, show_open=None, show... | [
"def",
"get_vulnerabilities",
"(",
"self",
",",
"teams",
"=",
"None",
",",
"applications",
"=",
"None",
",",
"channel_types",
"=",
"None",
",",
"start_date",
"=",
"None",
",",
"end_date",
"=",
"None",
",",
"generic_severities",
"=",
"None",
",",
"generic_vul... | Returns filtered list of vulnerabilities.
:param teams: List of team ids.
:param applications: List of application ids.
:param channel_types: List of scanner names.
:param start_date: Lower bound on scan dates.
:param end_date: Upper bound on scan dates.
:param generic_se... | [
"Returns",
"filtered",
"list",
"of",
"vulnerabilities",
".",
":",
"param",
"teams",
":",
"List",
"of",
"team",
"ids",
".",
":",
"param",
"applications",
":",
"List",
"of",
"application",
"ids",
".",
":",
"param",
"channel_types",
":",
"List",
"of",
"scanne... | train | https://github.com/aparsons/threadfix_api/blob/76fd1bd26e9ac863636112cd30d733543807ff7d/threadfix_api/threadfix.py#L263-L332 |
aparsons/threadfix_api | threadfix_api/threadfix.py | ThreadFixAPI._build_list_params | def _build_list_params(param_name, key, values):
"""Builds a list of POST parameters from a list or single value."""
params = {}
if hasattr(values, '__iter__'):
index = 0
for value in values:
params[str(param_name) + '[' + str(index) + '].' + str(key)] = s... | python | def _build_list_params(param_name, key, values):
"""Builds a list of POST parameters from a list or single value."""
params = {}
if hasattr(values, '__iter__'):
index = 0
for value in values:
params[str(param_name) + '[' + str(index) + '].' + str(key)] = s... | [
"def",
"_build_list_params",
"(",
"param_name",
",",
"key",
",",
"values",
")",
":",
"params",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"values",
",",
"'__iter__'",
")",
":",
"index",
"=",
"0",
"for",
"value",
"in",
"values",
":",
"params",
"[",
"str",
"... | Builds a list of POST parameters from a list or single value. | [
"Builds",
"a",
"list",
"of",
"POST",
"parameters",
"from",
"a",
"list",
"or",
"single",
"value",
"."
] | train | https://github.com/aparsons/threadfix_api/blob/76fd1bd26e9ac863636112cd30d733543807ff7d/threadfix_api/threadfix.py#L337-L347 |
aparsons/threadfix_api | threadfix_api/threadfix.py | ThreadFixAPI._request | def _request(self, method, url, params=None, files=None):
"""Common handler for all HTTP requests."""
if not params:
params = {}
params['apiKey'] = self.api_key
headers = {
'User-Agent': self.user_agent,
'Accept': 'application/json'
}
... | python | def _request(self, method, url, params=None, files=None):
"""Common handler for all HTTP requests."""
if not params:
params = {}
params['apiKey'] = self.api_key
headers = {
'User-Agent': self.user_agent,
'Accept': 'application/json'
}
... | [
"def",
"_request",
"(",
"self",
",",
"method",
",",
"url",
",",
"params",
"=",
"None",
",",
"files",
"=",
"None",
")",
":",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"}",
"params",
"[",
"'apiKey'",
"]",
"=",
"self",
".",
"api_key",
"headers",... | Common handler for all HTTP requests. | [
"Common",
"handler",
"for",
"all",
"HTTP",
"requests",
"."
] | train | https://github.com/aparsons/threadfix_api/blob/76fd1bd26e9ac863636112cd30d733543807ff7d/threadfix_api/threadfix.py#L349-L391 |
aparsons/threadfix_api | threadfix_api/threadfix.py | ThreadFixResponse.data_json | def data_json(self, pretty=False):
"""Returns the data as a valid JSON string."""
if pretty:
return json.dumps(self.data, sort_keys=True, indent=4, separators=(',', ': '))
else:
return json.dumps(self.data) | python | def data_json(self, pretty=False):
"""Returns the data as a valid JSON string."""
if pretty:
return json.dumps(self.data, sort_keys=True, indent=4, separators=(',', ': '))
else:
return json.dumps(self.data) | [
"def",
"data_json",
"(",
"self",
",",
"pretty",
"=",
"False",
")",
":",
"if",
"pretty",
":",
"return",
"json",
".",
"dumps",
"(",
"self",
".",
"data",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"4",
",",
"separators",
"=",
"(",
"','",
",",
... | Returns the data as a valid JSON string. | [
"Returns",
"the",
"data",
"as",
"a",
"valid",
"JSON",
"string",
"."
] | train | https://github.com/aparsons/threadfix_api/blob/76fd1bd26e9ac863636112cd30d733543807ff7d/threadfix_api/threadfix.py#L409-L414 |
abingham/spor | src/spor/diff.py | get_anchor_diff | def get_anchor_diff(anchor):
"""Get the get_anchor_diff between an anchor and the current state of its source.
Returns: A tuple of get_anchor_diff lines. If there is not different, then this
returns an empty tuple.
"""
new_anchor = make_anchor(
file_path=anchor.file_path,
offset... | python | def get_anchor_diff(anchor):
"""Get the get_anchor_diff between an anchor and the current state of its source.
Returns: A tuple of get_anchor_diff lines. If there is not different, then this
returns an empty tuple.
"""
new_anchor = make_anchor(
file_path=anchor.file_path,
offset... | [
"def",
"get_anchor_diff",
"(",
"anchor",
")",
":",
"new_anchor",
"=",
"make_anchor",
"(",
"file_path",
"=",
"anchor",
".",
"file_path",
",",
"offset",
"=",
"anchor",
".",
"context",
".",
"offset",
",",
"width",
"=",
"len",
"(",
"anchor",
".",
"context",
... | Get the get_anchor_diff between an anchor and the current state of its source.
Returns: A tuple of get_anchor_diff lines. If there is not different, then this
returns an empty tuple. | [
"Get",
"the",
"get_anchor_diff",
"between",
"an",
"anchor",
"and",
"the",
"current",
"state",
"of",
"its",
"source",
"."
] | train | https://github.com/abingham/spor/blob/673c8c36c99a4b9ea882f002bfb529f1eca89126/src/spor/diff.py#L23-L45 |
abingham/spor | src/spor/anchor.py | make_anchor | def make_anchor(file_path: pathlib.Path,
offset: int,
width: int,
context_width: int,
metadata,
encoding: str = 'utf-8',
handle=None):
"""Construct a new `Anchor`.
Args:
file_path: The absolute path to the t... | python | def make_anchor(file_path: pathlib.Path,
offset: int,
width: int,
context_width: int,
metadata,
encoding: str = 'utf-8',
handle=None):
"""Construct a new `Anchor`.
Args:
file_path: The absolute path to the t... | [
"def",
"make_anchor",
"(",
"file_path",
":",
"pathlib",
".",
"Path",
",",
"offset",
":",
"int",
",",
"width",
":",
"int",
",",
"context_width",
":",
"int",
",",
"metadata",
",",
"encoding",
":",
"str",
"=",
"'utf-8'",
",",
"handle",
"=",
"None",
")",
... | Construct a new `Anchor`.
Args:
file_path: The absolute path to the target file for the anchor.
offset: The offset of the anchored text in codepoints in `file_path`'s
contents.
width: The width in codepoints of the anchored text.
context_width: The width in codepoints of... | [
"Construct",
"a",
"new",
"Anchor",
"."
] | train | https://github.com/abingham/spor/blob/673c8c36c99a4b9ea882f002bfb529f1eca89126/src/spor/anchor.py#L172-L215 |
openmicroscopy/omero-marshal | omero_marshal/encode/__init__.py | Encoder.rgba_to_int | def rgba_to_int(cls, red, green, blue, alpha):
"""
Encodes the color as an Integer in RGBA encoding
Returns None if any of red, green or blue are None.
If alpha is None we use 255 by default.
:return: Integer
:rtype: int
"""
red = unwrap(red)
... | python | def rgba_to_int(cls, red, green, blue, alpha):
"""
Encodes the color as an Integer in RGBA encoding
Returns None if any of red, green or blue are None.
If alpha is None we use 255 by default.
:return: Integer
:rtype: int
"""
red = unwrap(red)
... | [
"def",
"rgba_to_int",
"(",
"cls",
",",
"red",
",",
"green",
",",
"blue",
",",
"alpha",
")",
":",
"red",
"=",
"unwrap",
"(",
"red",
")",
"green",
"=",
"unwrap",
"(",
"green",
")",
"blue",
"=",
"unwrap",
"(",
"blue",
")",
"alpha",
"=",
"unwrap",
"(... | Encodes the color as an Integer in RGBA encoding
Returns None if any of red, green or blue are None.
If alpha is None we use 255 by default.
:return: Integer
:rtype: int | [
"Encodes",
"the",
"color",
"as",
"an",
"Integer",
"in",
"RGBA",
"encoding"
] | train | https://github.com/openmicroscopy/omero-marshal/blob/0f427927b471a19f14b434452de88e16d621c487/omero_marshal/encode/__init__.py#L55-L80 |
welchbj/sublemon | sublemon/utils.py | amerge | async def amerge(*agens) -> AsyncGenerator[Any, None]:
"""Thin wrapper around aiostream.stream.merge."""
xs = stream.merge(*agens)
async with xs.stream() as streamer:
async for x in streamer:
yield x | python | async def amerge(*agens) -> AsyncGenerator[Any, None]:
"""Thin wrapper around aiostream.stream.merge."""
xs = stream.merge(*agens)
async with xs.stream() as streamer:
async for x in streamer:
yield x | [
"async",
"def",
"amerge",
"(",
"*",
"agens",
")",
"->",
"AsyncGenerator",
"[",
"Any",
",",
"None",
"]",
":",
"xs",
"=",
"stream",
".",
"merge",
"(",
"*",
"agens",
")",
"async",
"with",
"xs",
".",
"stream",
"(",
")",
"as",
"streamer",
":",
"async",
... | Thin wrapper around aiostream.stream.merge. | [
"Thin",
"wrapper",
"around",
"aiostream",
".",
"stream",
".",
"merge",
"."
] | train | https://github.com/welchbj/sublemon/blob/edbfd1ca2a0ce3de9470dfc88f8db1cadf4b6326/sublemon/utils.py#L14-L19 |
welchbj/sublemon | sublemon/utils.py | crossplat_loop_run | def crossplat_loop_run(coro) -> Any:
"""Cross-platform method for running a subprocess-spawning coroutine."""
if sys.platform == 'win32':
signal.signal(signal.SIGINT, signal.SIG_DFL)
loop = asyncio.ProactorEventLoop()
else:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(... | python | def crossplat_loop_run(coro) -> Any:
"""Cross-platform method for running a subprocess-spawning coroutine."""
if sys.platform == 'win32':
signal.signal(signal.SIGINT, signal.SIG_DFL)
loop = asyncio.ProactorEventLoop()
else:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(... | [
"def",
"crossplat_loop_run",
"(",
"coro",
")",
"->",
"Any",
":",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"signal",
".",
"SIG_DFL",
")",
"loop",
"=",
"asyncio",
".",
"ProactorEventLoo... | Cross-platform method for running a subprocess-spawning coroutine. | [
"Cross",
"-",
"platform",
"method",
"for",
"running",
"a",
"subprocess",
"-",
"spawning",
"coroutine",
"."
] | train | https://github.com/welchbj/sublemon/blob/edbfd1ca2a0ce3de9470dfc88f8db1cadf4b6326/sublemon/utils.py#L22-L32 |
chbrown/viz | viz/format.py | quantiles | def quantiles(xs, qs=None, step=25, width=None, cellspacing=3):
'''
Use stats.quantiles to get quantile-value pairs, and then print them to fit.
>>> import numpy as np
>>> quantiles(np.random.normal(size=10000), qs=[0, 5, 50, 95, 100])
0% < -3.670 5% < -1.675 50% < -0.002 95% < 1.6500 100%... | python | def quantiles(xs, qs=None, step=25, width=None, cellspacing=3):
'''
Use stats.quantiles to get quantile-value pairs, and then print them to fit.
>>> import numpy as np
>>> quantiles(np.random.normal(size=10000), qs=[0, 5, 50, 95, 100])
0% < -3.670 5% < -1.675 50% < -0.002 95% < 1.6500 100%... | [
"def",
"quantiles",
"(",
"xs",
",",
"qs",
"=",
"None",
",",
"step",
"=",
"25",
",",
"width",
"=",
"None",
",",
"cellspacing",
"=",
"3",
")",
":",
"if",
"width",
"is",
"None",
":",
"width",
"=",
"terminal",
".",
"width",
"(",
")",
"qs_values",
"="... | Use stats.quantiles to get quantile-value pairs, and then print them to fit.
>>> import numpy as np
>>> quantiles(np.random.normal(size=10000), qs=[0, 5, 50, 95, 100])
0% < -3.670 5% < -1.675 50% < -0.002 95% < 1.6500 100% < 3.4697
(Or something like that) | [
"Use",
"stats",
".",
"quantiles",
"to",
"get",
"quantile",
"-",
"value",
"pairs",
"and",
"then",
"print",
"them",
"to",
"fit",
".",
">>>",
"import",
"numpy",
"as",
"np",
">>>",
"quantiles",
"(",
"np",
".",
"random",
".",
"normal",
"(",
"size",
"=",
"... | train | https://github.com/chbrown/viz/blob/683a8f91630582d74250690a0e8ea7743ab94058/viz/format.py#L5-L25 |
SiLab-Bonn/online_monitor | online_monitor/utils/utils.py | parse_args | def parse_args(args):
''' Parse an argument string
http://stackoverflow.com/questions/18160078/
how-do-you-write-tests-for-the-argparse-portion-of-a-python-module
'''
parser = argparse.ArgumentParser()
parser.add_argument('config_file', nargs='?',
help='Configura... | python | def parse_args(args):
''' Parse an argument string
http://stackoverflow.com/questions/18160078/
how-do-you-write-tests-for-the-argparse-portion-of-a-python-module
'''
parser = argparse.ArgumentParser()
parser.add_argument('config_file', nargs='?',
help='Configura... | [
"def",
"parse_args",
"(",
"args",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'config_file'",
",",
"nargs",
"=",
"'?'",
",",
"help",
"=",
"'Configuration yaml file'",
",",
"default",
"=",
"None",... | Parse an argument string
http://stackoverflow.com/questions/18160078/
how-do-you-write-tests-for-the-argparse-portion-of-a-python-module | [
"Parse",
"an",
"argument",
"string"
] | train | https://github.com/SiLab-Bonn/online_monitor/blob/113c7d33e9ea4bc18520cefa329462faa406cc08/online_monitor/utils/utils.py#L38-L55 |
SiLab-Bonn/online_monitor | online_monitor/utils/utils.py | _factory | def _factory(importname, base_class_type, path=None, *args, **kargs):
''' Load a module of a given base class type
Parameter
--------
importname: string
Name of the module, etc. converter
base_class_type: class type
E.g converter
path: Absoulte path o... | python | def _factory(importname, base_class_type, path=None, *args, **kargs):
''' Load a module of a given base class type
Parameter
--------
importname: string
Name of the module, etc. converter
base_class_type: class type
E.g converter
path: Absoulte path o... | [
"def",
"_factory",
"(",
"importname",
",",
"base_class_type",
",",
"path",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
":",
"def",
"is_base_class",
"(",
"item",
")",
":",
"return",
"isclass",
"(",
"item",
")",
"and",
"item",
".",
"__m... | Load a module of a given base class type
Parameter
--------
importname: string
Name of the module, etc. converter
base_class_type: class type
E.g converter
path: Absoulte path of the module
Neede for extensions. If not given module is in onlin... | [
"Load",
"a",
"module",
"of",
"a",
"given",
"base",
"class",
"type"
] | train | https://github.com/SiLab-Bonn/online_monitor/blob/113c7d33e9ea4bc18520cefa329462faa406cc08/online_monitor/utils/utils.py#L78-L117 |
SiLab-Bonn/online_monitor | online_monitor/utils/utils.py | json_numpy_obj_hook | def json_numpy_obj_hook(dct):
"""Decodes a previously encoded numpy ndarray with proper shape and dtype.
And decompresses the data with blosc
:param dct: (dict) json encoded ndarray
:return: (ndarray) if input was an encoded ndarray
"""
if isinstance(dct, dict) and '__ndarray__' in dct:
... | python | def json_numpy_obj_hook(dct):
"""Decodes a previously encoded numpy ndarray with proper shape and dtype.
And decompresses the data with blosc
:param dct: (dict) json encoded ndarray
:return: (ndarray) if input was an encoded ndarray
"""
if isinstance(dct, dict) and '__ndarray__' in dct:
... | [
"def",
"json_numpy_obj_hook",
"(",
"dct",
")",
":",
"if",
"isinstance",
"(",
"dct",
",",
"dict",
")",
"and",
"'__ndarray__'",
"in",
"dct",
":",
"array",
"=",
"dct",
"[",
"'__ndarray__'",
"]",
"# http://stackoverflow.com/questions/24369666/typeerror-b1-is-not-json-seri... | Decodes a previously encoded numpy ndarray with proper shape and dtype.
And decompresses the data with blosc
:param dct: (dict) json encoded ndarray
:return: (ndarray) if input was an encoded ndarray | [
"Decodes",
"a",
"previously",
"encoded",
"numpy",
"ndarray",
"with",
"proper",
"shape",
"and",
"dtype",
".",
"And",
"decompresses",
"the",
"data",
"with",
"blosc"
] | train | https://github.com/SiLab-Bonn/online_monitor/blob/113c7d33e9ea4bc18520cefa329462faa406cc08/online_monitor/utils/utils.py#L201-L224 |
SiLab-Bonn/online_monitor | online_monitor/utils/utils.py | NumpyEncoder.default | def default(self, obj):
"""If input object is an ndarray it will be converted into a dict
holding dtype, shape and the data, base64 encoded and blosc compressed.
"""
if isinstance(obj, np.ndarray):
if obj.flags['C_CONTIGUOUS']:
obj_data = obj.data
... | python | def default(self, obj):
"""If input object is an ndarray it will be converted into a dict
holding dtype, shape and the data, base64 encoded and blosc compressed.
"""
if isinstance(obj, np.ndarray):
if obj.flags['C_CONTIGUOUS']:
obj_data = obj.data
... | [
"def",
"default",
"(",
"self",
",",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"np",
".",
"ndarray",
")",
":",
"if",
"obj",
".",
"flags",
"[",
"'C_CONTIGUOUS'",
"]",
":",
"obj_data",
"=",
"obj",
".",
"data",
"else",
":",
"cont_obj",
"=",... | If input object is an ndarray it will be converted into a dict
holding dtype, shape and the data, base64 encoded and blosc compressed. | [
"If",
"input",
"object",
"is",
"an",
"ndarray",
"it",
"will",
"be",
"converted",
"into",
"a",
"dict",
"holding",
"dtype",
"shape",
"and",
"the",
"data",
"base64",
"encoded",
"and",
"blosc",
"compressed",
"."
] | train | https://github.com/SiLab-Bonn/online_monitor/blob/113c7d33e9ea4bc18520cefa329462faa406cc08/online_monitor/utils/utils.py#L178-L198 |
isambard-uob/ampal | src/ampal/dssp.py | run_dssp | def run_dssp(pdb, path=True):
"""Uses DSSP to find helices and extracts helices from a pdb file or string.
Parameters
----------
pdb : str
Path to pdb file or string.
path : bool, optional
Indicates if pdb is a path or a string.
Returns
-------
dssp_out : str
Std... | python | def run_dssp(pdb, path=True):
"""Uses DSSP to find helices and extracts helices from a pdb file or string.
Parameters
----------
pdb : str
Path to pdb file or string.
path : bool, optional
Indicates if pdb is a path or a string.
Returns
-------
dssp_out : str
Std... | [
"def",
"run_dssp",
"(",
"pdb",
",",
"path",
"=",
"True",
")",
":",
"if",
"not",
"path",
":",
"if",
"isinstance",
"(",
"pdb",
",",
"str",
")",
":",
"pdb",
"=",
"pdb",
".",
"encode",
"(",
")",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
")",
... | Uses DSSP to find helices and extracts helices from a pdb file or string.
Parameters
----------
pdb : str
Path to pdb file or string.
path : bool, optional
Indicates if pdb is a path or a string.
Returns
-------
dssp_out : str
Std out from DSSP. | [
"Uses",
"DSSP",
"to",
"find",
"helices",
"and",
"extracts",
"helices",
"from",
"a",
"pdb",
"file",
"or",
"string",
".",
"Parameters",
"----------",
"pdb",
":",
"str",
"Path",
"to",
"pdb",
"file",
"or",
"string",
".",
"path",
":",
"bool",
"optional",
"Ind... | train | https://github.com/isambard-uob/ampal/blob/906e2afacb435ffb129b381f262ff8e7bfb324c5/src/ampal/dssp.py#L32-L58 |
isambard-uob/ampal | src/ampal/dssp.py | extract_all_ss_dssp | def extract_all_ss_dssp(in_dssp, path=True):
"""Uses DSSP to extract secondary structure information on every residue.
Parameters
----------
in_dssp : str
Path to DSSP file.
path : bool, optional
Indicates if pdb is a path or a string.
Returns
-------
dssp_residues : [t... | python | def extract_all_ss_dssp(in_dssp, path=True):
"""Uses DSSP to extract secondary structure information on every residue.
Parameters
----------
in_dssp : str
Path to DSSP file.
path : bool, optional
Indicates if pdb is a path or a string.
Returns
-------
dssp_residues : [t... | [
"def",
"extract_all_ss_dssp",
"(",
"in_dssp",
",",
"path",
"=",
"True",
")",
":",
"if",
"path",
":",
"with",
"open",
"(",
"in_dssp",
",",
"'r'",
")",
"as",
"inf",
":",
"dssp_out",
"=",
"inf",
".",
"read",
"(",
")",
"else",
":",
"dssp_out",
"=",
"in... | Uses DSSP to extract secondary structure information on every residue.
Parameters
----------
in_dssp : str
Path to DSSP file.
path : bool, optional
Indicates if pdb is a path or a string.
Returns
-------
dssp_residues : [tuple]
Each internal list contains:
... | [
"Uses",
"DSSP",
"to",
"extract",
"secondary",
"structure",
"information",
"on",
"every",
"residue",
"."
] | train | https://github.com/isambard-uob/ampal/blob/906e2afacb435ffb129b381f262ff8e7bfb324c5/src/ampal/dssp.py#L61-L108 |
isambard-uob/ampal | src/ampal/dssp.py | find_ss_regions | def find_ss_regions(dssp_residues, loop_assignments=(' ', 'B', 'S', 'T')):
"""Separates parsed DSSP data into groups of secondary structure.
Notes
-----
Example: all residues in a single helix/loop/strand will be gathered
into a list, then the next secondary structure element will be
gathered i... | python | def find_ss_regions(dssp_residues, loop_assignments=(' ', 'B', 'S', 'T')):
"""Separates parsed DSSP data into groups of secondary structure.
Notes
-----
Example: all residues in a single helix/loop/strand will be gathered
into a list, then the next secondary structure element will be
gathered i... | [
"def",
"find_ss_regions",
"(",
"dssp_residues",
",",
"loop_assignments",
"=",
"(",
"' '",
",",
"'B'",
",",
"'S'",
",",
"'T'",
")",
")",
":",
"loops",
"=",
"loop_assignments",
"previous_ele",
"=",
"None",
"fragment",
"=",
"[",
"]",
"fragments",
"=",
"[",
... | Separates parsed DSSP data into groups of secondary structure.
Notes
-----
Example: all residues in a single helix/loop/strand will be gathered
into a list, then the next secondary structure element will be
gathered into a separate list, and so on.
Parameters
----------
dssp_residues :... | [
"Separates",
"parsed",
"DSSP",
"data",
"into",
"groups",
"of",
"secondary",
"structure",
"."
] | train | https://github.com/isambard-uob/ampal/blob/906e2afacb435ffb129b381f262ff8e7bfb324c5/src/ampal/dssp.py#L111-L163 |
isambard-uob/ampal | src/ampal/dssp.py | tag_dssp_data | def tag_dssp_data(assembly, loop_assignments=(' ', 'B', 'S', 'T')):
"""Adds output data from DSSP to an Assembly.
A dictionary will be added to the `tags` dictionary of each
residue called `dssp_data`, which contains the secondary
structure definition, solvent accessibility phi and psi values
from ... | python | def tag_dssp_data(assembly, loop_assignments=(' ', 'B', 'S', 'T')):
"""Adds output data from DSSP to an Assembly.
A dictionary will be added to the `tags` dictionary of each
residue called `dssp_data`, which contains the secondary
structure definition, solvent accessibility phi and psi values
from ... | [
"def",
"tag_dssp_data",
"(",
"assembly",
",",
"loop_assignments",
"=",
"(",
"' '",
",",
"'B'",
",",
"'S'",
",",
"'T'",
")",
")",
":",
"dssp_out",
"=",
"run_dssp",
"(",
"assembly",
".",
"pdb",
",",
"path",
"=",
"False",
")",
"dssp_data",
"=",
"extract_a... | Adds output data from DSSP to an Assembly.
A dictionary will be added to the `tags` dictionary of each
residue called `dssp_data`, which contains the secondary
structure definition, solvent accessibility phi and psi values
from DSSP. A list of regions of continuous secondary assignments
will also b... | [
"Adds",
"output",
"data",
"from",
"DSSP",
"to",
"an",
"Assembly",
"."
] | train | https://github.com/isambard-uob/ampal/blob/906e2afacb435ffb129b381f262ff8e7bfb324c5/src/ampal/dssp.py#L166-L206 |
isambard-uob/ampal | src/ampal/dssp.py | get_ss_regions | def get_ss_regions(assembly, ss_types):
"""Returns an Assembly containing Polymers for each region of structure.
Parameters
----------
assembly : ampal.Assembly
`Assembly` object to be searched secondary structure regions.
ss_types : list
List of secondary structure tags to be separ... | python | def get_ss_regions(assembly, ss_types):
"""Returns an Assembly containing Polymers for each region of structure.
Parameters
----------
assembly : ampal.Assembly
`Assembly` object to be searched secondary structure regions.
ss_types : list
List of secondary structure tags to be separ... | [
"def",
"get_ss_regions",
"(",
"assembly",
",",
"ss_types",
")",
":",
"if",
"not",
"any",
"(",
"map",
"(",
"lambda",
"x",
":",
"'ss_regions'",
"in",
"x",
".",
"tags",
",",
"assembly",
")",
")",
":",
"raise",
"ValueError",
"(",
"'This assembly does not have ... | Returns an Assembly containing Polymers for each region of structure.
Parameters
----------
assembly : ampal.Assembly
`Assembly` object to be searched secondary structure regions.
ss_types : list
List of secondary structure tags to be separate i.e. ['H']
would return helices, ['... | [
"Returns",
"an",
"Assembly",
"containing",
"Polymers",
"for",
"each",
"region",
"of",
"structure",
"."
] | train | https://github.com/isambard-uob/ampal/blob/906e2afacb435ffb129b381f262ff8e7bfb324c5/src/ampal/dssp.py#L209-L242 |
adammck/djtables | lib/djtables/urls.py | extract | def extract(query_dict, prefix=""):
"""
Extract the *order_by*, *per_page*, and *page* parameters from
`query_dict` (a Django QueryDict), and return a dict suitable for
instantiating a preconfigured Table object.
"""
strs = ['order_by']
ints = ['per_page', 'page']
extracted = { }
... | python | def extract(query_dict, prefix=""):
"""
Extract the *order_by*, *per_page*, and *page* parameters from
`query_dict` (a Django QueryDict), and return a dict suitable for
instantiating a preconfigured Table object.
"""
strs = ['order_by']
ints = ['per_page', 'page']
extracted = { }
... | [
"def",
"extract",
"(",
"query_dict",
",",
"prefix",
"=",
"\"\"",
")",
":",
"strs",
"=",
"[",
"'order_by'",
"]",
"ints",
"=",
"[",
"'per_page'",
",",
"'page'",
"]",
"extracted",
"=",
"{",
"}",
"for",
"key",
"in",
"(",
"strs",
"+",
"ints",
")",
":",
... | Extract the *order_by*, *per_page*, and *page* parameters from
`query_dict` (a Django QueryDict), and return a dict suitable for
instantiating a preconfigured Table object. | [
"Extract",
"the",
"*",
"order_by",
"*",
"*",
"per_page",
"*",
"and",
"*",
"page",
"*",
"parameters",
"from",
"query_dict",
"(",
"a",
"Django",
"QueryDict",
")",
"and",
"return",
"a",
"dict",
"suitable",
"for",
"instantiating",
"a",
"preconfigured",
"Table",
... | train | https://github.com/adammck/djtables/blob/8fa279e7088123f00cca9c838fe028ebf327325e/lib/djtables/urls.py#L8-L28 |
adammck/djtables | lib/djtables/urls.py | _copy | def _copy(query_dict):
"""
Return a mutable copy of `query_dict`. This is a workaround to
Django bug #13572, which prevents QueryDict.copy from working.
"""
memo = { }
result = query_dict.__class__('',
encoding=query_dict.encoding,
mutable=True)
memo[id(query_dict)] = resu... | python | def _copy(query_dict):
"""
Return a mutable copy of `query_dict`. This is a workaround to
Django bug #13572, which prevents QueryDict.copy from working.
"""
memo = { }
result = query_dict.__class__('',
encoding=query_dict.encoding,
mutable=True)
memo[id(query_dict)] = resu... | [
"def",
"_copy",
"(",
"query_dict",
")",
":",
"memo",
"=",
"{",
"}",
"result",
"=",
"query_dict",
".",
"__class__",
"(",
"''",
",",
"encoding",
"=",
"query_dict",
".",
"encoding",
",",
"mutable",
"=",
"True",
")",
"memo",
"[",
"id",
"(",
"query_dict",
... | Return a mutable copy of `query_dict`. This is a workaround to
Django bug #13572, which prevents QueryDict.copy from working. | [
"Return",
"a",
"mutable",
"copy",
"of",
"query_dict",
".",
"This",
"is",
"a",
"workaround",
"to",
"Django",
"bug",
"#13572",
"which",
"prevents",
"QueryDict",
".",
"copy",
"from",
"working",
"."
] | train | https://github.com/adammck/djtables/blob/8fa279e7088123f00cca9c838fe028ebf327325e/lib/djtables/urls.py#L45-L64 |
komissarex/snaql-migration | snaql_migration/snaql_migration.py | snaql_migration | def snaql_migration(ctx, db_uri, migrations, app, config):
"""
Lightweight SQL Schema migration tool based on Snaql queries
"""
if config:
migrations_config = _parse_config(config)
else:
if db_uri and migrations and app:
migrations_config = _generate_config(db_uri, migra... | python | def snaql_migration(ctx, db_uri, migrations, app, config):
"""
Lightweight SQL Schema migration tool based on Snaql queries
"""
if config:
migrations_config = _parse_config(config)
else:
if db_uri and migrations and app:
migrations_config = _generate_config(db_uri, migra... | [
"def",
"snaql_migration",
"(",
"ctx",
",",
"db_uri",
",",
"migrations",
",",
"app",
",",
"config",
")",
":",
"if",
"config",
":",
"migrations_config",
"=",
"_parse_config",
"(",
"config",
")",
"else",
":",
"if",
"db_uri",
"and",
"migrations",
"and",
"app",... | Lightweight SQL Schema migration tool based on Snaql queries | [
"Lightweight",
"SQL",
"Schema",
"migration",
"tool",
"based",
"on",
"Snaql",
"queries"
] | train | https://github.com/komissarex/snaql-migration/blob/b4cafab126a162a5fc8866618b2f1cb6c453bde1/snaql_migration/snaql_migration.py#L39-L59 |
komissarex/snaql-migration | snaql_migration/snaql_migration.py | show | def show(ctx):
"""
Show migrations list
"""
for app_name, app in ctx.obj['config']['apps'].items():
click.echo(click.style(app_name, fg='green', bold=True))
for migration in app['migrations']:
applied = ctx.obj['db'].is_migration_applied(app_name, migration)
clic... | python | def show(ctx):
"""
Show migrations list
"""
for app_name, app in ctx.obj['config']['apps'].items():
click.echo(click.style(app_name, fg='green', bold=True))
for migration in app['migrations']:
applied = ctx.obj['db'].is_migration_applied(app_name, migration)
clic... | [
"def",
"show",
"(",
"ctx",
")",
":",
"for",
"app_name",
",",
"app",
"in",
"ctx",
".",
"obj",
"[",
"'config'",
"]",
"[",
"'apps'",
"]",
".",
"items",
"(",
")",
":",
"click",
".",
"echo",
"(",
"click",
".",
"style",
"(",
"app_name",
",",
"fg",
"=... | Show migrations list | [
"Show",
"migrations",
"list"
] | train | https://github.com/komissarex/snaql-migration/blob/b4cafab126a162a5fc8866618b2f1cb6c453bde1/snaql_migration/snaql_migration.py#L64-L73 |
komissarex/snaql-migration | snaql_migration/snaql_migration.py | apply | def apply(ctx, name, verbose):
"""
Apply migration
"""
if name != 'all': # specific migration
try:
app_name, target_migration = name.split('/', 2)
except ValueError:
raise click.ClickException("NAME format is <app>/<migration> or 'all'")
apps = ctx.obj[... | python | def apply(ctx, name, verbose):
"""
Apply migration
"""
if name != 'all': # specific migration
try:
app_name, target_migration = name.split('/', 2)
except ValueError:
raise click.ClickException("NAME format is <app>/<migration> or 'all'")
apps = ctx.obj[... | [
"def",
"apply",
"(",
"ctx",
",",
"name",
",",
"verbose",
")",
":",
"if",
"name",
"!=",
"'all'",
":",
"# specific migration",
"try",
":",
"app_name",
",",
"target_migration",
"=",
"name",
".",
"split",
"(",
"'/'",
",",
"2",
")",
"except",
"ValueError",
... | Apply migration | [
"Apply",
"migration"
] | train | https://github.com/komissarex/snaql-migration/blob/b4cafab126a162a5fc8866618b2f1cb6c453bde1/snaql_migration/snaql_migration.py#L80-L159 |
komissarex/snaql-migration | snaql_migration/snaql_migration.py | revert | def revert(ctx, name, verbose):
"""
Revert migration
"""
try:
app_name, target_migration = name.split('/', 2)
except ValueError:
raise click.ClickException('NAME format is <app>/<migration>')
apps = ctx.obj['config']['apps']
if app_name not in apps.keys():
raise cli... | python | def revert(ctx, name, verbose):
"""
Revert migration
"""
try:
app_name, target_migration = name.split('/', 2)
except ValueError:
raise click.ClickException('NAME format is <app>/<migration>')
apps = ctx.obj['config']['apps']
if app_name not in apps.keys():
raise cli... | [
"def",
"revert",
"(",
"ctx",
",",
"name",
",",
"verbose",
")",
":",
"try",
":",
"app_name",
",",
"target_migration",
"=",
"name",
".",
"split",
"(",
"'/'",
",",
"2",
")",
"except",
"ValueError",
":",
"raise",
"click",
".",
"ClickException",
"(",
"'NAME... | Revert migration | [
"Revert",
"migration"
] | train | https://github.com/komissarex/snaql-migration/blob/b4cafab126a162a5fc8866618b2f1cb6c453bde1/snaql_migration/snaql_migration.py#L166-L216 |
Clinical-Genomics/housekeeper | housekeeper/store/api.py | BaseHandler.bundle | def bundle(self, name: str) -> models.Bundle:
"""Fetch a bundle from the store."""
return self.Bundle.filter_by(name=name).first() | python | def bundle(self, name: str) -> models.Bundle:
"""Fetch a bundle from the store."""
return self.Bundle.filter_by(name=name).first() | [
"def",
"bundle",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"models",
".",
"Bundle",
":",
"return",
"self",
".",
"Bundle",
".",
"filter_by",
"(",
"name",
"=",
"name",
")",
".",
"first",
"(",
")"
] | Fetch a bundle from the store. | [
"Fetch",
"a",
"bundle",
"from",
"the",
"store",
"."
] | train | https://github.com/Clinical-Genomics/housekeeper/blob/a7d10d327dc9f06274bdef5504ed1b9413f2c8c1/housekeeper/store/api.py#L28-L30 |
Clinical-Genomics/housekeeper | housekeeper/store/api.py | BaseHandler.version | def version(self, bundle: str, date: dt.datetime) -> models.Version:
"""Fetch a version from the store."""
return (self.Version.query
.join(models.Version.bundle)
.filter(models.Bundle.name == bundle,
models.Vers... | python | def version(self, bundle: str, date: dt.datetime) -> models.Version:
"""Fetch a version from the store."""
return (self.Version.query
.join(models.Version.bundle)
.filter(models.Bundle.name == bundle,
models.Vers... | [
"def",
"version",
"(",
"self",
",",
"bundle",
":",
"str",
",",
"date",
":",
"dt",
".",
"datetime",
")",
"->",
"models",
".",
"Version",
":",
"return",
"(",
"self",
".",
"Version",
".",
"query",
".",
"join",
"(",
"models",
".",
"Version",
".",
"bund... | Fetch a version from the store. | [
"Fetch",
"a",
"version",
"from",
"the",
"store",
"."
] | train | https://github.com/Clinical-Genomics/housekeeper/blob/a7d10d327dc9f06274bdef5504ed1b9413f2c8c1/housekeeper/store/api.py#L32-L38 |
Clinical-Genomics/housekeeper | housekeeper/store/api.py | BaseHandler.tag | def tag(self, name: str) -> models.Tag:
"""Fetch a tag from the database."""
return self.Tag.filter_by(name=name).first() | python | def tag(self, name: str) -> models.Tag:
"""Fetch a tag from the database."""
return self.Tag.filter_by(name=name).first() | [
"def",
"tag",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"models",
".",
"Tag",
":",
"return",
"self",
".",
"Tag",
".",
"filter_by",
"(",
"name",
"=",
"name",
")",
".",
"first",
"(",
")"
] | Fetch a tag from the database. | [
"Fetch",
"a",
"tag",
"from",
"the",
"database",
"."
] | train | https://github.com/Clinical-Genomics/housekeeper/blob/a7d10d327dc9f06274bdef5504ed1b9413f2c8c1/housekeeper/store/api.py#L40-L42 |
Clinical-Genomics/housekeeper | housekeeper/store/api.py | BaseHandler.new_bundle | def new_bundle(self, name: str, created_at: dt.datetime=None) -> models.Bundle:
"""Create a new file bundle."""
new_bundle = self.Bundle(name=name, created_at=created_at)
return new_bundle | python | def new_bundle(self, name: str, created_at: dt.datetime=None) -> models.Bundle:
"""Create a new file bundle."""
new_bundle = self.Bundle(name=name, created_at=created_at)
return new_bundle | [
"def",
"new_bundle",
"(",
"self",
",",
"name",
":",
"str",
",",
"created_at",
":",
"dt",
".",
"datetime",
"=",
"None",
")",
"->",
"models",
".",
"Bundle",
":",
"new_bundle",
"=",
"self",
".",
"Bundle",
"(",
"name",
"=",
"name",
",",
"created_at",
"="... | Create a new file bundle. | [
"Create",
"a",
"new",
"file",
"bundle",
"."
] | train | https://github.com/Clinical-Genomics/housekeeper/blob/a7d10d327dc9f06274bdef5504ed1b9413f2c8c1/housekeeper/store/api.py#L44-L47 |
Clinical-Genomics/housekeeper | housekeeper/store/api.py | BaseHandler.new_version | def new_version(self, created_at: dt.datetime, expires_at: dt.datetime=None) -> models.Version:
"""Create a new bundle version."""
new_version = self.Version(created_at=created_at, expires_at=expires_at)
return new_version | python | def new_version(self, created_at: dt.datetime, expires_at: dt.datetime=None) -> models.Version:
"""Create a new bundle version."""
new_version = self.Version(created_at=created_at, expires_at=expires_at)
return new_version | [
"def",
"new_version",
"(",
"self",
",",
"created_at",
":",
"dt",
".",
"datetime",
",",
"expires_at",
":",
"dt",
".",
"datetime",
"=",
"None",
")",
"->",
"models",
".",
"Version",
":",
"new_version",
"=",
"self",
".",
"Version",
"(",
"created_at",
"=",
... | Create a new bundle version. | [
"Create",
"a",
"new",
"bundle",
"version",
"."
] | train | https://github.com/Clinical-Genomics/housekeeper/blob/a7d10d327dc9f06274bdef5504ed1b9413f2c8c1/housekeeper/store/api.py#L49-L52 |
Clinical-Genomics/housekeeper | housekeeper/store/api.py | BaseHandler.new_file | def new_file(self, path: str, checksum: str=None, to_archive: bool=False,
tags: List[models.Tag]=None) -> models.File:
"""Create a new file."""
new_file = self.File(path=path, checksum=checksum, to_archive=to_archive, tags=tags)
return new_file | python | def new_file(self, path: str, checksum: str=None, to_archive: bool=False,
tags: List[models.Tag]=None) -> models.File:
"""Create a new file."""
new_file = self.File(path=path, checksum=checksum, to_archive=to_archive, tags=tags)
return new_file | [
"def",
"new_file",
"(",
"self",
",",
"path",
":",
"str",
",",
"checksum",
":",
"str",
"=",
"None",
",",
"to_archive",
":",
"bool",
"=",
"False",
",",
"tags",
":",
"List",
"[",
"models",
".",
"Tag",
"]",
"=",
"None",
")",
"->",
"models",
".",
"Fil... | Create a new file. | [
"Create",
"a",
"new",
"file",
"."
] | train | https://github.com/Clinical-Genomics/housekeeper/blob/a7d10d327dc9f06274bdef5504ed1b9413f2c8c1/housekeeper/store/api.py#L54-L58 |
Clinical-Genomics/housekeeper | housekeeper/store/api.py | BaseHandler.new_tag | def new_tag(self, name: str, category: str=None) -> models.Tag:
"""Create a new tag."""
new_tag = self.Tag(name=name, category=category)
return new_tag | python | def new_tag(self, name: str, category: str=None) -> models.Tag:
"""Create a new tag."""
new_tag = self.Tag(name=name, category=category)
return new_tag | [
"def",
"new_tag",
"(",
"self",
",",
"name",
":",
"str",
",",
"category",
":",
"str",
"=",
"None",
")",
"->",
"models",
".",
"Tag",
":",
"new_tag",
"=",
"self",
".",
"Tag",
"(",
"name",
"=",
"name",
",",
"category",
"=",
"category",
")",
"return",
... | Create a new tag. | [
"Create",
"a",
"new",
"tag",
"."
] | train | https://github.com/Clinical-Genomics/housekeeper/blob/a7d10d327dc9f06274bdef5504ed1b9413f2c8c1/housekeeper/store/api.py#L60-L63 |
Clinical-Genomics/housekeeper | housekeeper/store/api.py | BaseHandler.files | def files(self, *, bundle: str=None, tags: List[str]=None, version: int=None,
path: str=None) -> models.File:
"""Fetch files from the store."""
query = self.File.query
if bundle:
query = (query.join(self.File.version, self.Version.bundle)
.filt... | python | def files(self, *, bundle: str=None, tags: List[str]=None, version: int=None,
path: str=None) -> models.File:
"""Fetch files from the store."""
query = self.File.query
if bundle:
query = (query.join(self.File.version, self.Version.bundle)
.filt... | [
"def",
"files",
"(",
"self",
",",
"*",
",",
"bundle",
":",
"str",
"=",
"None",
",",
"tags",
":",
"List",
"[",
"str",
"]",
"=",
"None",
",",
"version",
":",
"int",
"=",
"None",
",",
"path",
":",
"str",
"=",
"None",
")",
"->",
"models",
".",
"F... | Fetch files from the store. | [
"Fetch",
"files",
"from",
"the",
"store",
"."
] | train | https://github.com/Clinical-Genomics/housekeeper/blob/a7d10d327dc9f06274bdef5504ed1b9413f2c8c1/housekeeper/store/api.py#L69-L92 |
Clinical-Genomics/housekeeper | housekeeper/store/api.py | BaseHandler.files_before | def files_before(self, *, bundle: str=None, tags: List[str]=None, before:
str=None) -> models.File:
"""Fetch files before date from store"""
query = self.files(tags=tags, bundle=bundle)
if before:
before_dt = parse_date(before)
query = query.join(mode... | python | def files_before(self, *, bundle: str=None, tags: List[str]=None, before:
str=None) -> models.File:
"""Fetch files before date from store"""
query = self.files(tags=tags, bundle=bundle)
if before:
before_dt = parse_date(before)
query = query.join(mode... | [
"def",
"files_before",
"(",
"self",
",",
"*",
",",
"bundle",
":",
"str",
"=",
"None",
",",
"tags",
":",
"List",
"[",
"str",
"]",
"=",
"None",
",",
"before",
":",
"str",
"=",
"None",
")",
"->",
"models",
".",
"File",
":",
"query",
"=",
"self",
"... | Fetch files before date from store | [
"Fetch",
"files",
"before",
"date",
"from",
"store"
] | train | https://github.com/Clinical-Genomics/housekeeper/blob/a7d10d327dc9f06274bdef5504ed1b9413f2c8c1/housekeeper/store/api.py#L95-L103 |
Clinical-Genomics/housekeeper | housekeeper/store/api.py | BaseHandler.files_ondisk | def files_ondisk(self, file_objs: models.File) -> set:
"""Returns a list of files that are not on disk."""
return set([ file_obj for file_obj in file_objs if Path(file_obj.full_path).is_file() ]) | python | def files_ondisk(self, file_objs: models.File) -> set:
"""Returns a list of files that are not on disk."""
return set([ file_obj for file_obj in file_objs if Path(file_obj.full_path).is_file() ]) | [
"def",
"files_ondisk",
"(",
"self",
",",
"file_objs",
":",
"models",
".",
"File",
")",
"->",
"set",
":",
"return",
"set",
"(",
"[",
"file_obj",
"for",
"file_obj",
"in",
"file_objs",
"if",
"Path",
"(",
"file_obj",
".",
"full_path",
")",
".",
"is_file",
... | Returns a list of files that are not on disk. | [
"Returns",
"a",
"list",
"of",
"files",
"that",
"are",
"not",
"on",
"disk",
"."
] | train | https://github.com/Clinical-Genomics/housekeeper/blob/a7d10d327dc9f06274bdef5504ed1b9413f2c8c1/housekeeper/store/api.py#L106-L109 |
jelmer/python-fastimport | fastimport/parser.py | _unquote_c_string | def _unquote_c_string(s):
"""replace C-style escape sequences (\n, \", etc.) with real chars."""
# doing a s.encode('utf-8').decode('unicode_escape') can return an
# incorrect output with unicode string (both in py2 and py3) the safest way
# is to match the escape sequences and decoding them alone.... | python | def _unquote_c_string(s):
"""replace C-style escape sequences (\n, \", etc.) with real chars."""
# doing a s.encode('utf-8').decode('unicode_escape') can return an
# incorrect output with unicode string (both in py2 and py3) the safest way
# is to match the escape sequences and decoding them alone.... | [
"def",
"_unquote_c_string",
"(",
"s",
")",
":",
"# doing a s.encode('utf-8').decode('unicode_escape') can return an",
"# incorrect output with unicode string (both in py2 and py3) the safest way",
"# is to match the escape sequences and decoding them alone.",
"def",
"decode_match",
"(",
"mat... | replace C-style escape sequences (\n, \", etc.) with real chars. | [
"replace",
"C",
"-",
"style",
"escape",
"sequences",
"(",
"\\",
"n",
"\\",
"etc",
".",
")",
"with",
"real",
"chars",
"."
] | train | https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/parser.py#L642-L656 |
jelmer/python-fastimport | fastimport/parser.py | LineBasedParser.readline | def readline(self):
"""Get the next line including the newline or '' on EOF."""
self.lineno += 1
if self._buffer:
return self._buffer.pop()
else:
return self.input.readline() | python | def readline(self):
"""Get the next line including the newline or '' on EOF."""
self.lineno += 1
if self._buffer:
return self._buffer.pop()
else:
return self.input.readline() | [
"def",
"readline",
"(",
"self",
")",
":",
"self",
".",
"lineno",
"+=",
"1",
"if",
"self",
".",
"_buffer",
":",
"return",
"self",
".",
"_buffer",
".",
"pop",
"(",
")",
"else",
":",
"return",
"self",
".",
"input",
".",
"readline",
"(",
")"
] | Get the next line including the newline or '' on EOF. | [
"Get",
"the",
"next",
"line",
"including",
"the",
"newline",
"or",
"on",
"EOF",
"."
] | train | https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/parser.py#L196-L202 |
jelmer/python-fastimport | fastimport/parser.py | LineBasedParser.push_line | def push_line(self, line):
"""Push line back onto the line buffer.
:param line: the line with no trailing newline
"""
self.lineno -= 1
self._buffer.append(line + b'\n') | python | def push_line(self, line):
"""Push line back onto the line buffer.
:param line: the line with no trailing newline
"""
self.lineno -= 1
self._buffer.append(line + b'\n') | [
"def",
"push_line",
"(",
"self",
",",
"line",
")",
":",
"self",
".",
"lineno",
"-=",
"1",
"self",
".",
"_buffer",
".",
"append",
"(",
"line",
"+",
"b'\\n'",
")"
] | Push line back onto the line buffer.
:param line: the line with no trailing newline | [
"Push",
"line",
"back",
"onto",
"the",
"line",
"buffer",
"."
] | train | https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/parser.py#L212-L218 |
jelmer/python-fastimport | fastimport/parser.py | LineBasedParser.read_bytes | def read_bytes(self, count):
"""Read a given number of bytes from the input stream.
Throws MissingBytes if the bytes are not found.
Note: This method does not read from the line buffer.
:return: a string
"""
result = self.input.read(count)
found = len(result)
... | python | def read_bytes(self, count):
"""Read a given number of bytes from the input stream.
Throws MissingBytes if the bytes are not found.
Note: This method does not read from the line buffer.
:return: a string
"""
result = self.input.read(count)
found = len(result)
... | [
"def",
"read_bytes",
"(",
"self",
",",
"count",
")",
":",
"result",
"=",
"self",
".",
"input",
".",
"read",
"(",
"count",
")",
"found",
"=",
"len",
"(",
"result",
")",
"self",
".",
"lineno",
"+=",
"result",
".",
"count",
"(",
"b'\\n'",
")",
"if",
... | Read a given number of bytes from the input stream.
Throws MissingBytes if the bytes are not found.
Note: This method does not read from the line buffer.
:return: a string | [
"Read",
"a",
"given",
"number",
"of",
"bytes",
"from",
"the",
"input",
"stream",
"."
] | train | https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/parser.py#L220-L234 |
jelmer/python-fastimport | fastimport/parser.py | LineBasedParser.read_until | def read_until(self, terminator):
"""Read the input stream until the terminator is found.
Throws MissingTerminator if the terminator is not found.
Note: This method does not read from the line buffer.
:return: the bytes read up to but excluding the terminator.
"""
lin... | python | def read_until(self, terminator):
"""Read the input stream until the terminator is found.
Throws MissingTerminator if the terminator is not found.
Note: This method does not read from the line buffer.
:return: the bytes read up to but excluding the terminator.
"""
lin... | [
"def",
"read_until",
"(",
"self",
",",
"terminator",
")",
":",
"lines",
"=",
"[",
"]",
"term",
"=",
"terminator",
"+",
"b'\\n'",
"while",
"True",
":",
"line",
"=",
"self",
".",
"input",
".",
"readline",
"(",
")",
"if",
"line",
"==",
"term",
":",
"b... | Read the input stream until the terminator is found.
Throws MissingTerminator if the terminator is not found.
Note: This method does not read from the line buffer.
:return: the bytes read up to but excluding the terminator. | [
"Read",
"the",
"input",
"stream",
"until",
"the",
"terminator",
"is",
"found",
"."
] | train | https://github.com/jelmer/python-fastimport/blob/5cef9e037b7d7b37f58f522ac9ea4e343e6a1dff/fastimport/parser.py#L236-L254 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.