repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
pmacosta/ptrie | ptrie/ptrie.py | https://github.com/pmacosta/ptrie/blob/c176d3ee810b7b5243c7ff2bbf2f1af0b0fff2a8/ptrie/ptrie.py#L937-L975 | def get_subtree(self, name): # noqa: D302
r"""
Get all node names in a sub-tree.
:param name: Sub-tree root node name
:type name: :ref:`NodeName`
:rtype: list of :ref:`NodeName`
:raises:
* RuntimeError (Argument \`name\` is not valid)
* RuntimeError (Node *[name]* not in tree)
Using the same example tree created in
:py:meth:`ptrie.Trie.add_nodes`::
>>> from __future__ import print_function
>>> import docs.support.ptrie_example, pprint
>>> tobj = docs.support.ptrie_example.create_tree()
>>> print(tobj)
root
├branch1 (*)
│├leaf1
││└subleaf1 (*)
│└leaf2 (*)
│ └subleaf2
└branch2
>>> pprint.pprint(tobj.get_subtree('root.branch1'))
['root.branch1',
'root.branch1.leaf1',
'root.branch1.leaf1.subleaf1',
'root.branch1.leaf2',
'root.branch1.leaf2.subleaf2']
"""
if self._validate_node_name(name):
raise RuntimeError("Argument `name` is not valid")
self._node_in_tree(name)
return self._get_subtree(name) | [
"def",
"get_subtree",
"(",
"self",
",",
"name",
")",
":",
"# noqa: D302",
"if",
"self",
".",
"_validate_node_name",
"(",
"name",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Argument `name` is not valid\"",
")",
"self",
".",
"_node_in_tree",
"(",
"name",
")",
"r... | r"""
Get all node names in a sub-tree.
:param name: Sub-tree root node name
:type name: :ref:`NodeName`
:rtype: list of :ref:`NodeName`
:raises:
* RuntimeError (Argument \`name\` is not valid)
* RuntimeError (Node *[name]* not in tree)
Using the same example tree created in
:py:meth:`ptrie.Trie.add_nodes`::
>>> from __future__ import print_function
>>> import docs.support.ptrie_example, pprint
>>> tobj = docs.support.ptrie_example.create_tree()
>>> print(tobj)
root
├branch1 (*)
│├leaf1
││└subleaf1 (*)
│└leaf2 (*)
│ └subleaf2
└branch2
>>> pprint.pprint(tobj.get_subtree('root.branch1'))
['root.branch1',
'root.branch1.leaf1',
'root.branch1.leaf1.subleaf1',
'root.branch1.leaf2',
'root.branch1.leaf2.subleaf2'] | [
"r",
"Get",
"all",
"node",
"names",
"in",
"a",
"sub",
"-",
"tree",
"."
] | python | train |
saltstack/salt | salt/modules/btrfs.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L195-L212 | def _usage_overall(raw):
'''
Parse usage/overall.
'''
data = {}
for line in raw.split("\n")[1:]:
keyset = [item.strip() for item in re.sub(r"\s+", " ", line).split(":", 1) if item.strip()]
if len(keyset) == 2:
key = re.sub(r"[()]", "", keyset[0]).replace(" ", "_").lower()
if key in ['free_estimated', 'global_reserve']: # An extra field
subk = keyset[1].split("(")
data[key] = subk[0].strip()
subk = subk[1].replace(")", "").split(": ")
data["{0}_{1}".format(key, subk[0])] = subk[1]
else:
data[key] = keyset[1]
return data | [
"def",
"_usage_overall",
"(",
"raw",
")",
":",
"data",
"=",
"{",
"}",
"for",
"line",
"in",
"raw",
".",
"split",
"(",
"\"\\n\"",
")",
"[",
"1",
":",
"]",
":",
"keyset",
"=",
"[",
"item",
".",
"strip",
"(",
")",
"for",
"item",
"in",
"re",
".",
... | Parse usage/overall. | [
"Parse",
"usage",
"/",
"overall",
"."
] | python | train |
dustinmm80/healthy | package_utils.py | https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/package_utils.py#L14-L24 | def create_sandbox(name='healthybox'):
"""
Create a temporary sandbox directory
:param name: name of the directory to create
:return: The directory created
"""
sandbox = tempfile.mkdtemp(prefix=name)
if not os.path.isdir(sandbox):
os.mkdir(sandbox)
return sandbox | [
"def",
"create_sandbox",
"(",
"name",
"=",
"'healthybox'",
")",
":",
"sandbox",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"prefix",
"=",
"name",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"sandbox",
")",
":",
"os",
".",
"mkdir",
"(",
"sandbo... | Create a temporary sandbox directory
:param name: name of the directory to create
:return: The directory created | [
"Create",
"a",
"temporary",
"sandbox",
"directory",
":",
"param",
"name",
":",
"name",
"of",
"the",
"directory",
"to",
"create",
":",
"return",
":",
"The",
"directory",
"created"
] | python | train |
cloudendpoints/endpoints-management-python | endpoints_management/control/distribution.py | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/distribution.py#L99-L118 | def create_explicit(bounds):
"""Creates a new instance of distribution with explicit buckets.
bounds is an iterable of ordered floats that define the explicit buckets
Args:
bounds (iterable[float]): initializes the bounds
Return:
:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`
Raises:
ValueError: if the args are invalid for creating an instance
"""
safe_bounds = sorted(float(x) for x in bounds)
if len(safe_bounds) != len(set(safe_bounds)):
raise ValueError(u'Detected two elements of bounds that are the same')
return sc_messages.Distribution(
bucketCounts=[0] * (len(safe_bounds) + 1),
explicitBuckets=sc_messages.ExplicitBuckets(bounds=safe_bounds)) | [
"def",
"create_explicit",
"(",
"bounds",
")",
":",
"safe_bounds",
"=",
"sorted",
"(",
"float",
"(",
"x",
")",
"for",
"x",
"in",
"bounds",
")",
"if",
"len",
"(",
"safe_bounds",
")",
"!=",
"len",
"(",
"set",
"(",
"safe_bounds",
")",
")",
":",
"raise",
... | Creates a new instance of distribution with explicit buckets.
bounds is an iterable of ordered floats that define the explicit buckets
Args:
bounds (iterable[float]): initializes the bounds
Return:
:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`
Raises:
ValueError: if the args are invalid for creating an instance | [
"Creates",
"a",
"new",
"instance",
"of",
"distribution",
"with",
"explicit",
"buckets",
"."
] | python | train |
aliyun/aliyun-odps-python-sdk | odps/df/expr/strings.py | https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/df/expr/strings.py#L671-L684 | def _strptime(expr, date_format):
"""
Return datetimes specified by date_format,
which supports the same string format as the python standard library.
Details of the string format can be found in python string format doc
:param expr:
:param date_format: date format string (e.g. “%Y-%m-%d”)
:type date_format: str
:return:
"""
return _string_op(expr, Strptime, _date_format=date_format,
output_type=types.datetime) | [
"def",
"_strptime",
"(",
"expr",
",",
"date_format",
")",
":",
"return",
"_string_op",
"(",
"expr",
",",
"Strptime",
",",
"_date_format",
"=",
"date_format",
",",
"output_type",
"=",
"types",
".",
"datetime",
")"
] | Return datetimes specified by date_format,
which supports the same string format as the python standard library.
Details of the string format can be found in python string format doc
:param expr:
:param date_format: date format string (e.g. “%Y-%m-%d”)
:type date_format: str
:return: | [
"Return",
"datetimes",
"specified",
"by",
"date_format",
"which",
"supports",
"the",
"same",
"string",
"format",
"as",
"the",
"python",
"standard",
"library",
".",
"Details",
"of",
"the",
"string",
"format",
"can",
"be",
"found",
"in",
"python",
"string",
"for... | python | train |
dodger487/dplython | dplython/dplython.py | https://github.com/dodger487/dplython/blob/09c2a5f4ca67221b2a59928366ca8274357f7234/dplython/dplython.py#L203-L232 | def select(*args):
"""Select specific columns from DataFrame.
Output will be DplyFrame type. Order of columns will be the same as input into
select.
>>> diamonds >> select(X.color, X.carat) >> head(3)
Out:
color carat
0 E 0.23
1 E 0.21
2 E 0.23
Grouping variables are implied in selection.
>>> df >> group_by(X.a, X.b) >> select(X.c)
returns a dataframe like `df[[X.a, X.b, X.c]]` with the variables appearing in
grouped order before the selected column(s), unless a grouped variable is
explicitly selected
>>> df >> group_by(X.a, X.b) >> select(X.c, X.b)
returns a dataframe like `df[[X.a, X.c, X.b]]`
"""
def select_columns(df, args):
columns = [column._name for column in args]
if df._grouped_on:
for col in df._grouped_on[::-1]:
if col not in columns:
columns.insert(0, col)
return columns
return lambda df: df[select_columns(df, args)] | [
"def",
"select",
"(",
"*",
"args",
")",
":",
"def",
"select_columns",
"(",
"df",
",",
"args",
")",
":",
"columns",
"=",
"[",
"column",
".",
"_name",
"for",
"column",
"in",
"args",
"]",
"if",
"df",
".",
"_grouped_on",
":",
"for",
"col",
"in",
"df",
... | Select specific columns from DataFrame.
Output will be DplyFrame type. Order of columns will be the same as input into
select.
>>> diamonds >> select(X.color, X.carat) >> head(3)
Out:
color carat
0 E 0.23
1 E 0.21
2 E 0.23
Grouping variables are implied in selection.
>>> df >> group_by(X.a, X.b) >> select(X.c)
returns a dataframe like `df[[X.a, X.b, X.c]]` with the variables appearing in
grouped order before the selected column(s), unless a grouped variable is
explicitly selected
>>> df >> group_by(X.a, X.b) >> select(X.c, X.b)
returns a dataframe like `df[[X.a, X.c, X.b]]` | [
"Select",
"specific",
"columns",
"from",
"DataFrame",
"."
] | python | train |
RPi-Distro/python-gpiozero | gpiozero/boards.py | https://github.com/RPi-Distro/python-gpiozero/blob/7b67374fd0c8c4fde5586d9bad9531f076db9c0c/gpiozero/boards.py#L1601-L1633 | def forward(self, speed=1, **kwargs):
"""
Drive the robot forward by running both motors forward.
:param float speed:
Speed at which to drive the motors, as a value between 0 (stopped)
and 1 (full speed). The default is 1.
:param float curve_left:
The amount to curve left while moving forwards, by driving the
left motor at a slower speed. Maximum *curve_left* is 1, the
default is 0 (no curve). This parameter can only be specified as a
keyword parameter, and is mutually exclusive with *curve_right*.
:param float curve_right:
The amount to curve right while moving forwards, by driving the
right motor at a slower speed. Maximum *curve_right* is 1, the
default is 0 (no curve). This parameter can only be specified as a
keyword parameter, and is mutually exclusive with *curve_left*.
"""
curve_left = kwargs.pop('curve_left', 0)
curve_right = kwargs.pop('curve_right', 0)
if kwargs:
raise TypeError('unexpected argument %s' % kwargs.popitem()[0])
if not 0 <= curve_left <= 1:
raise ValueError('curve_left must be between 0 and 1')
if not 0 <= curve_right <= 1:
raise ValueError('curve_right must be between 0 and 1')
if curve_left != 0 and curve_right != 0:
raise ValueError("curve_left and curve_right can't be used at "
"the same time")
self.left_motor.forward(speed * (1 - curve_left))
self.right_motor.forward(speed * (1 - curve_right)) | [
"def",
"forward",
"(",
"self",
",",
"speed",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"curve_left",
"=",
"kwargs",
".",
"pop",
"(",
"'curve_left'",
",",
"0",
")",
"curve_right",
"=",
"kwargs",
".",
"pop",
"(",
"'curve_right'",
",",
"0",
")",
"i... | Drive the robot forward by running both motors forward.
:param float speed:
Speed at which to drive the motors, as a value between 0 (stopped)
and 1 (full speed). The default is 1.
:param float curve_left:
The amount to curve left while moving forwards, by driving the
left motor at a slower speed. Maximum *curve_left* is 1, the
default is 0 (no curve). This parameter can only be specified as a
keyword parameter, and is mutually exclusive with *curve_right*.
:param float curve_right:
The amount to curve right while moving forwards, by driving the
right motor at a slower speed. Maximum *curve_right* is 1, the
default is 0 (no curve). This parameter can only be specified as a
keyword parameter, and is mutually exclusive with *curve_left*. | [
"Drive",
"the",
"robot",
"forward",
"by",
"running",
"both",
"motors",
"forward",
"."
] | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/subproc.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/subproc.py#L301-L454 | def mimic_user_input(
args: List[str],
source_challenge_response: List[Tuple[SubprocSource,
str,
Union[str, SubprocCommand]]],
line_terminators: List[str] = None,
print_stdout: bool = False,
print_stderr: bool = False,
print_stdin: bool = False,
stdin_encoding: str = None,
stdout_encoding: str = None,
suppress_decoding_errors: bool = True,
sleep_time_s: float = 0.1) -> None:
r"""
Run an external command. Pretend to be a human by sending text to the
subcommand (responses) when the external command sends us triggers
(challenges).
This is a bit nasty.
Args:
args: command-line arguments
source_challenge_response: list of tuples of the format ``(challsrc,
challenge, response)``; see below
line_terminators: valid line terminators
print_stdout:
print_stderr:
print_stdin:
stdin_encoding:
stdout_encoding:
suppress_decoding_errors: trap any ``UnicodeDecodeError``?
sleep_time_s:
The ``(challsrc, challenge, response)`` tuples have this meaning:
- ``challsrc``: where is the challenge coming from? Must be one of the
objects :data:`SOURCE_STDOUT` or :data:`SOURCE_STDERR`;
- ``challenge``: text of challenge
- ``response``: text of response (send to the subcommand's ``stdin``).
Example (modified from :class:`CorruptedZipReader`):
.. code-block:: python
from cardinal_pythonlib.subproc import *
SOURCE_FILENAME = "corrupt.zip"
TMP_DIR = "/tmp"
OUTPUT_FILENAME = "rescued.zip"
cmdargs = [
"zip", # Linux zip tool
"-FF", # or "--fixfix": "fix very broken things"
SOURCE_FILENAME, # input file
"--temp-path", TMP_DIR, # temporary storage path
"--out", OUTPUT_FILENAME # output file
]
# We would like to be able to say "y" automatically to
# "Is this a single-disk archive? (y/n):"
# The source code (api.c, zip.c, zipfile.c), from
# ftp://ftp.info-zip.org/pub/infozip/src/ , suggests that "-q"
# should do this (internally "-q" sets "noisy = 0") - but in
# practice it doesn't work. This is a critical switch.
# Therefore we will do something very ugly, and send raw text via
# stdin.
ZIP_PROMPTS_RESPONSES = [
(SOURCE_STDOUT, "Is this a single-disk archive? (y/n): ", "y\n"),
(SOURCE_STDOUT, " or ENTER (try reading this split again): ", "q\n"),
(SOURCE_STDERR,
"zip: malloc.c:2394: sysmalloc: Assertion `(old_top == initial_top (av) "
"&& old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && "
"prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) "
"== 0)' failed.", TERMINATE_SUBPROCESS),
]
ZIP_STDOUT_TERMINATORS = ["\n", "): "]
mimic_user_input(cmdargs,
source_challenge_response=ZIP_PROMPTS_RESPONSES,
line_terminators=ZIP_STDOUT_TERMINATORS,
print_stdout=show_zip_output,
print_stdin=show_zip_output)
""" # noqa
line_terminators = line_terminators or ["\n"] # type: List[str]
stdin_encoding = stdin_encoding or sys.getdefaultencoding()
stdout_encoding = stdout_encoding or sys.getdefaultencoding()
# Launch the command
p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE, bufsize=0)
# Launch the asynchronous readers of stdout and stderr
stdout_queue = Queue()
# noinspection PyTypeChecker
stdout_reader = AsynchronousFileReader(
fd=p.stdout,
queue=stdout_queue,
encoding=stdout_encoding,
line_terminators=line_terminators,
cmdargs=args,
suppress_decoding_errors=suppress_decoding_errors
)
stdout_reader.start()
stderr_queue = Queue()
# noinspection PyTypeChecker
stderr_reader = AsynchronousFileReader(
fd=p.stderr,
queue=stderr_queue,
encoding=stdout_encoding, # same as stdout
line_terminators=line_terminators,
cmdargs=args,
suppress_decoding_errors=suppress_decoding_errors
)
stderr_reader.start()
while not stdout_reader.eof() or not stderr_reader.eof():
lines_with_source = [] # type: List[Tuple[SubprocSource, str]]
while not stdout_queue.empty():
lines_with_source.append((SOURCE_STDOUT, stdout_queue.get()))
while not stderr_queue.empty():
lines_with_source.append((SOURCE_STDERR, stderr_queue.get()))
for src, line in lines_with_source:
if src is SOURCE_STDOUT and print_stdout:
print(line, end="") # terminator already in line
if src is SOURCE_STDERR and print_stderr:
print(line, end="") # terminator already in line
for challsrc, challenge, response in source_challenge_response:
# log.critical("challsrc={!r}", challsrc)
# log.critical("challenge={!r}", challenge)
# log.critical("line={!r}", line)
# log.critical("response={!r}", response)
if challsrc != src:
continue
if challenge in line:
if response is TERMINATE_SUBPROCESS:
log.warning("Terminating subprocess {!r} because input "
"{!r} received", args, challenge)
p.kill()
return
else:
p.stdin.write(response.encode(stdin_encoding))
p.stdin.flush()
if print_stdin:
print(response, end="")
# Sleep a bit before asking the readers again.
sleep(sleep_time_s)
stdout_reader.join()
stderr_reader.join()
p.stdout.close()
p.stderr.close() | [
"def",
"mimic_user_input",
"(",
"args",
":",
"List",
"[",
"str",
"]",
",",
"source_challenge_response",
":",
"List",
"[",
"Tuple",
"[",
"SubprocSource",
",",
"str",
",",
"Union",
"[",
"str",
",",
"SubprocCommand",
"]",
"]",
"]",
",",
"line_terminators",
":... | r"""
Run an external command. Pretend to be a human by sending text to the
subcommand (responses) when the external command sends us triggers
(challenges).
This is a bit nasty.
Args:
args: command-line arguments
source_challenge_response: list of tuples of the format ``(challsrc,
challenge, response)``; see below
line_terminators: valid line terminators
print_stdout:
print_stderr:
print_stdin:
stdin_encoding:
stdout_encoding:
suppress_decoding_errors: trap any ``UnicodeDecodeError``?
sleep_time_s:
The ``(challsrc, challenge, response)`` tuples have this meaning:
- ``challsrc``: where is the challenge coming from? Must be one of the
objects :data:`SOURCE_STDOUT` or :data:`SOURCE_STDERR`;
- ``challenge``: text of challenge
- ``response``: text of response (send to the subcommand's ``stdin``).
Example (modified from :class:`CorruptedZipReader`):
.. code-block:: python
from cardinal_pythonlib.subproc import *
SOURCE_FILENAME = "corrupt.zip"
TMP_DIR = "/tmp"
OUTPUT_FILENAME = "rescued.zip"
cmdargs = [
"zip", # Linux zip tool
"-FF", # or "--fixfix": "fix very broken things"
SOURCE_FILENAME, # input file
"--temp-path", TMP_DIR, # temporary storage path
"--out", OUTPUT_FILENAME # output file
]
# We would like to be able to say "y" automatically to
# "Is this a single-disk archive? (y/n):"
# The source code (api.c, zip.c, zipfile.c), from
# ftp://ftp.info-zip.org/pub/infozip/src/ , suggests that "-q"
# should do this (internally "-q" sets "noisy = 0") - but in
# practice it doesn't work. This is a critical switch.
# Therefore we will do something very ugly, and send raw text via
# stdin.
ZIP_PROMPTS_RESPONSES = [
(SOURCE_STDOUT, "Is this a single-disk archive? (y/n): ", "y\n"),
(SOURCE_STDOUT, " or ENTER (try reading this split again): ", "q\n"),
(SOURCE_STDERR,
"zip: malloc.c:2394: sysmalloc: Assertion `(old_top == initial_top (av) "
"&& old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && "
"prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) "
"== 0)' failed.", TERMINATE_SUBPROCESS),
]
ZIP_STDOUT_TERMINATORS = ["\n", "): "]
mimic_user_input(cmdargs,
source_challenge_response=ZIP_PROMPTS_RESPONSES,
line_terminators=ZIP_STDOUT_TERMINATORS,
print_stdout=show_zip_output,
print_stdin=show_zip_output) | [
"r",
"Run",
"an",
"external",
"command",
".",
"Pretend",
"to",
"be",
"a",
"human",
"by",
"sending",
"text",
"to",
"the",
"subcommand",
"(",
"responses",
")",
"when",
"the",
"external",
"command",
"sends",
"us",
"triggers",
"(",
"challenges",
")",
".",
"T... | python | train |
python-xlib/python-xlib | Xlib/display.py | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/display.py#L490-L495 | def get_atom_name(self, atom):
"""Look up the name of atom, returning it as a string. Will raise
BadAtom if atom does not exist."""
r = request.GetAtomName(display = self.display,
atom = atom)
return r.name | [
"def",
"get_atom_name",
"(",
"self",
",",
"atom",
")",
":",
"r",
"=",
"request",
".",
"GetAtomName",
"(",
"display",
"=",
"self",
".",
"display",
",",
"atom",
"=",
"atom",
")",
"return",
"r",
".",
"name"
] | Look up the name of atom, returning it as a string. Will raise
BadAtom if atom does not exist. | [
"Look",
"up",
"the",
"name",
"of",
"atom",
"returning",
"it",
"as",
"a",
"string",
".",
"Will",
"raise",
"BadAtom",
"if",
"atom",
"does",
"not",
"exist",
"."
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/models/image_transformer.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/image_transformer.py#L1147-L1157 | def imagetransformer_b10l_4h_big_uncond_dr01_tpu():
"""big 1d model for conditional image generation."""
hparams = imagetransformer_b12l_4h_big_uncond_dr03_tpu()
# num_hidden_layers
hparams.num_decoder_layers = 10
hparams.num_heads = 4
hparams.hidden_size = 1024
hparams.filter_size = 4096
hparams.batch_size = 1
hparams.layer_prepostprocess_dropout = 0.1
return hparams | [
"def",
"imagetransformer_b10l_4h_big_uncond_dr01_tpu",
"(",
")",
":",
"hparams",
"=",
"imagetransformer_b12l_4h_big_uncond_dr03_tpu",
"(",
")",
"# num_hidden_layers",
"hparams",
".",
"num_decoder_layers",
"=",
"10",
"hparams",
".",
"num_heads",
"=",
"4",
"hparams",
".",
... | big 1d model for conditional image generation. | [
"big",
"1d",
"model",
"for",
"conditional",
"image",
"generation",
"."
] | python | train |
mozilla/amo-validator | validator/submain.py | https://github.com/mozilla/amo-validator/blob/0251bfbd7d93106e01ecdb6de5fcd1dc1a180664/validator/submain.py#L279-L354 | def populate_chrome_manifest(err, xpi_package):
"Loads the chrome.manifest if it's present"
if 'chrome.manifest' in xpi_package:
chrome_data = xpi_package.read('chrome.manifest')
chrome = ChromeManifest(chrome_data, 'chrome.manifest')
chrome_recursion_buster = set()
# Handle the case of manifests linked from the manifest.
def get_linked_manifest(path, from_path, from_chrome, from_triple):
if path in chrome_recursion_buster:
err.warning(
err_id=('submain', 'populate_chrome_manifest',
'recursion'),
warning='Linked manifest recursion detected.',
description='A chrome registration file links back to '
'itself. This can cause a multitude of '
'issues.',
filename=path)
return
# Make sure the manifest is properly linked
if path not in xpi_package:
err.notice(
err_id=('submain', 'populate_chrome_manifest', 'linkerr'),
notice='Linked manifest could not be found.',
description=('A linked manifest file could not be found '
'in the package.',
'Path: %s' % path),
filename=from_path,
line=from_triple['line'],
context=from_chrome.context)
return
chrome_recursion_buster.add(path)
manifest = ChromeManifest(xpi_package.read(path), path)
for triple in manifest.triples:
yield triple
if triple['subject'] == 'manifest':
subpath = triple['predicate']
# If the path is relative, make it relative to the current
# file.
if not subpath.startswith('/'):
subpath = '%s/%s' % (
'/'.join(path.split('/')[:-1]), subpath)
subpath = subpath.lstrip('/')
for subtriple in get_linked_manifest(
subpath, path, manifest, triple):
yield subtriple
chrome_recursion_buster.discard(path)
chrome_recursion_buster.add('chrome.manifest')
# Search for linked manifests in the base manifest.
for extra_manifest in chrome.get_triples(subject='manifest'):
# When one is found, add its triples to our own.
for triple in get_linked_manifest(extra_manifest['predicate'],
'chrome.manifest', chrome,
extra_manifest):
chrome.triples.append(triple)
chrome_recursion_buster.discard('chrome.manifest')
# Create a reference so we can get the chrome manifest later, but make
# it pushable so we don't run chrome manifests in JAR files.
err.save_resource('chrome.manifest', chrome, pushable=True)
# Create a non-pushable reference for tests that need to access the
# chrome manifest from within JAR files.
err.save_resource('chrome.manifest_nopush', chrome, pushable=False) | [
"def",
"populate_chrome_manifest",
"(",
"err",
",",
"xpi_package",
")",
":",
"if",
"'chrome.manifest'",
"in",
"xpi_package",
":",
"chrome_data",
"=",
"xpi_package",
".",
"read",
"(",
"'chrome.manifest'",
")",
"chrome",
"=",
"ChromeManifest",
"(",
"chrome_data",
",... | Loads the chrome.manifest if it's present | [
"Loads",
"the",
"chrome",
".",
"manifest",
"if",
"it",
"s",
"present"
] | python | train |
onnx/onnxmltools | onnxmltools/convert/coreml/shape_calculators/neural_network/Upsample.py | https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxmltools/convert/coreml/shape_calculators/neural_network/Upsample.py#L13-L27 | def calculate_upsample_output_shapes(operator):
'''
Allowed input/output patterns are
1. [N, C, H, W] ---> [N, C, H', W']
'''
check_input_and_output_numbers(operator, input_count_range=1, output_count_range=1)
check_input_and_output_types(operator, good_input_types=[FloatTensorType])
scales = operator.raw_operator.upsample.scalingFactor
output_shape = copy.deepcopy(operator.inputs[0].type.shape)
output_shape[2] *= scales[0]
output_shape[3] *= scales[1]
operator.outputs[0].type = FloatTensorType(output_shape, doc_string=operator.outputs[0].type.doc_string) | [
"def",
"calculate_upsample_output_shapes",
"(",
"operator",
")",
":",
"check_input_and_output_numbers",
"(",
"operator",
",",
"input_count_range",
"=",
"1",
",",
"output_count_range",
"=",
"1",
")",
"check_input_and_output_types",
"(",
"operator",
",",
"good_input_types",... | Allowed input/output patterns are
1. [N, C, H, W] ---> [N, C, H', W'] | [
"Allowed",
"input",
"/",
"output",
"patterns",
"are",
"1",
".",
"[",
"N",
"C",
"H",
"W",
"]",
"---",
">",
"[",
"N",
"C",
"H",
"W",
"]"
] | python | train |
codelv/enaml-native | src/enamlnative/android/android_date_picker.py | https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_date_picker.py#L46-L52 | def create_widget(self):
""" Create the underlying widget.
"""
d = self.declaration
self.widget = DatePicker(self.get_context(), None,
d.style or "@attr/datePickerStyle") | [
"def",
"create_widget",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"declaration",
"self",
".",
"widget",
"=",
"DatePicker",
"(",
"self",
".",
"get_context",
"(",
")",
",",
"None",
",",
"d",
".",
"style",
"or",
"\"@attr/datePickerStyle\"",
")"
] | Create the underlying widget. | [
"Create",
"the",
"underlying",
"widget",
"."
] | python | train |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L9321-L9341 | def rc_channels_raw_encode(self, time_boot_ms, port, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, rssi):
'''
The RAW values of the RC channels received. The standard PPM
modulation is as follows: 1000 microseconds: 0%, 2000
microseconds: 100%. Individual receivers/transmitters
might violate this specification.
time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t)
port : Servo output port (set of 8 outputs = 1 port). Most MAVs will just use one, but this allows for more than 8 servos. (uint8_t)
chan1_raw : RC channel 1 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t)
chan2_raw : RC channel 2 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t)
chan3_raw : RC channel 3 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t)
chan4_raw : RC channel 4 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t)
chan5_raw : RC channel 5 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t)
chan6_raw : RC channel 6 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t)
chan7_raw : RC channel 7 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t)
chan8_raw : RC channel 8 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t)
rssi : Receive signal strength indicator, 0: 0%, 100: 100%, 255: invalid/unknown. (uint8_t)
'''
return MAVLink_rc_channels_raw_message(time_boot_ms, port, chan1_raw, chan2_raw, chan3_raw, chan4_raw, chan5_raw, chan6_raw, chan7_raw, chan8_raw, rssi) | [
"def",
"rc_channels_raw_encode",
"(",
"self",
",",
"time_boot_ms",
",",
"port",
",",
"chan1_raw",
",",
"chan2_raw",
",",
"chan3_raw",
",",
"chan4_raw",
",",
"chan5_raw",
",",
"chan6_raw",
",",
"chan7_raw",
",",
"chan8_raw",
",",
"rssi",
")",
":",
"return",
"... | The RAW values of the RC channels received. The standard PPM
modulation is as follows: 1000 microseconds: 0%, 2000
microseconds: 100%. Individual receivers/transmitters
might violate this specification.
time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t)
port : Servo output port (set of 8 outputs = 1 port). Most MAVs will just use one, but this allows for more than 8 servos. (uint8_t)
chan1_raw : RC channel 1 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t)
chan2_raw : RC channel 2 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t)
chan3_raw : RC channel 3 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t)
chan4_raw : RC channel 4 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t)
chan5_raw : RC channel 5 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t)
chan6_raw : RC channel 6 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t)
chan7_raw : RC channel 7 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t)
chan8_raw : RC channel 8 value, in microseconds. A value of UINT16_MAX implies the channel is unused. (uint16_t)
rssi : Receive signal strength indicator, 0: 0%, 100: 100%, 255: invalid/unknown. (uint8_t) | [
"The",
"RAW",
"values",
"of",
"the",
"RC",
"channels",
"received",
".",
"The",
"standard",
"PPM",
"modulation",
"is",
"as",
"follows",
":",
"1000",
"microseconds",
":",
"0%",
"2000",
"microseconds",
":",
"100%",
".",
"Individual",
"receivers",
"/",
"transmit... | python | train |
sebp/scikit-survival | sksurv/svm/survival_svm.py | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/svm/survival_svm.py#L702-L717 | def _argsort_and_resolve_ties(time, random_state):
"""Like numpy.argsort, but resolves ties uniformly at random"""
n_samples = len(time)
order = numpy.argsort(time, kind="mergesort")
i = 0
while i < n_samples - 1:
inext = i + 1
while inext < n_samples and time[order[i]] == time[order[inext]]:
inext += 1
if i + 1 != inext:
# resolve ties randomly
random_state.shuffle(order[i:inext])
i = inext
return order | [
"def",
"_argsort_and_resolve_ties",
"(",
"time",
",",
"random_state",
")",
":",
"n_samples",
"=",
"len",
"(",
"time",
")",
"order",
"=",
"numpy",
".",
"argsort",
"(",
"time",
",",
"kind",
"=",
"\"mergesort\"",
")",
"i",
"=",
"0",
"while",
"i",
"<",
"n_... | Like numpy.argsort, but resolves ties uniformly at random | [
"Like",
"numpy",
".",
"argsort",
"but",
"resolves",
"ties",
"uniformly",
"at",
"random"
] | python | train |
lreis2415/PyGeoC | pygeoc/utils.py | https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L494-L527 | def extract_numeric_values_from_string(str_contains_values):
# type: (AnyStr) -> Optional[List[Union[int, float]]]
"""
Find numeric values from string, e.g., 1, .7, 1.2, 4e2, 3e-3, -9, etc.
Reference: `how-to-extract-a-floating-number-from-a-string-in-python`_
Examples:
>>> input_str = '.1 .12 9.1 98.1 1. 12. 1 12'
>>> StringClass.extract_numeric_values_from_string(input_str)
[0.1, 0.12, 9.1, 98.1, 1, 12, 1, 12]
>>> input_str = '-1 +1 2e9 +2E+09 -2e-9'
>>> StringClass.extract_numeric_values_from_string(input_str)
[-1, 1, 2000000000, 2000000000, -2e-09]
>>> input_str = 'current level: -2.03e+2db'
>>> StringClass.extract_numeric_values_from_string(input_str)
[-203]
Args:
str_contains_values: string which may contains numeric values
Returns:
list of numeric values
.. _how-to-extract-a-floating-number-from-a-string-in-python:
https://stackoverflow.com/questions/4703390/how-to-extract-a-floating-number-from-a-string-in-python/4703508#4703508
"""
numeric_const_pattern = r'[-+]?(?:(?:\d*\.\d+)|(?:\d+\.?))(?:[Ee][+-]?\d+)?'
rx = re.compile(numeric_const_pattern, re.VERBOSE)
value_strs = rx.findall(str_contains_values)
if len(value_strs) == 0:
return None
else:
return [int(float(v)) if float(v) % 1. == 0 else float(v) for v in value_strs] | [
"def",
"extract_numeric_values_from_string",
"(",
"str_contains_values",
")",
":",
"# type: (AnyStr) -> Optional[List[Union[int, float]]]",
"numeric_const_pattern",
"=",
"r'[-+]?(?:(?:\\d*\\.\\d+)|(?:\\d+\\.?))(?:[Ee][+-]?\\d+)?'",
"rx",
"=",
"re",
".",
"compile",
"(",
"numeric_const... | Find numeric values from string, e.g., 1, .7, 1.2, 4e2, 3e-3, -9, etc.
Reference: `how-to-extract-a-floating-number-from-a-string-in-python`_
Examples:
>>> input_str = '.1 .12 9.1 98.1 1. 12. 1 12'
>>> StringClass.extract_numeric_values_from_string(input_str)
[0.1, 0.12, 9.1, 98.1, 1, 12, 1, 12]
>>> input_str = '-1 +1 2e9 +2E+09 -2e-9'
>>> StringClass.extract_numeric_values_from_string(input_str)
[-1, 1, 2000000000, 2000000000, -2e-09]
>>> input_str = 'current level: -2.03e+2db'
>>> StringClass.extract_numeric_values_from_string(input_str)
[-203]
Args:
str_contains_values: string which may contains numeric values
Returns:
list of numeric values
.. _how-to-extract-a-floating-number-from-a-string-in-python:
https://stackoverflow.com/questions/4703390/how-to-extract-a-floating-number-from-a-string-in-python/4703508#4703508 | [
"Find",
"numeric",
"values",
"from",
"string",
"e",
".",
"g",
".",
"1",
".",
"7",
"1",
".",
"2",
"4e2",
"3e",
"-",
"3",
"-",
"9",
"etc",
".",
"Reference",
":",
"how",
"-",
"to",
"-",
"extract",
"-",
"a",
"-",
"floating",
"-",
"number",
"-",
"... | python | train |
quasipedia/swaggery | examples/async/async.py | https://github.com/quasipedia/swaggery/blob/89a2e1b2bebbc511c781c9e63972f65aef73cc2f/examples/async/async.py#L187-L195 | def form_echo(cls, request,
foo: (Ptypes.form, String('A form parameter'))) -> [
(200, 'Ok', String)]:
'''Echo the form parameter.'''
log.info('Echoing form param, value is: {}'.format(foo))
for i in range(randint(0, MAX_LOOP_DURATION)):
yield
msg = 'The value sent was: {}'.format(foo)
Respond(200, msg) | [
"def",
"form_echo",
"(",
"cls",
",",
"request",
",",
"foo",
":",
"(",
"Ptypes",
".",
"form",
",",
"String",
"(",
"'A form parameter'",
")",
")",
")",
"->",
"[",
"(",
"200",
",",
"'Ok'",
",",
"String",
")",
"]",
":",
"log",
".",
"info",
"(",
"'Ech... | Echo the form parameter. | [
"Echo",
"the",
"form",
"parameter",
"."
] | python | train |
saltstack/salt | salt/modules/boto_route53.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_route53.py#L285-L337 | def create_zone(zone, private=False, vpc_id=None, vpc_region=None, region=None,
key=None, keyid=None, profile=None):
'''
Create a Route53 hosted zone.
.. versionadded:: 2015.8.0
zone
DNS zone to create
private
True/False if the zone will be a private zone
vpc_id
VPC ID to associate the zone to (required if private is True)
vpc_region
VPC Region (required if private is True)
region
region endpoint to connect to
key
AWS key
keyid
AWS keyid
profile
AWS pillar profile
CLI Example::
salt myminion boto_route53.create_zone example.org
'''
if region is None:
region = 'universal'
if private:
if not vpc_id or not vpc_region:
msg = 'vpc_id and vpc_region must be specified for a private zone'
raise SaltInvocationError(msg)
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
_zone = conn.get_zone(zone)
if _zone:
return False
conn.create_zone(zone, private_zone=private, vpc_id=vpc_id,
vpc_region=vpc_region)
return True | [
"def",
"create_zone",
"(",
"zone",
",",
"private",
"=",
"False",
",",
"vpc_id",
"=",
"None",
",",
"vpc_region",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"if"... | Create a Route53 hosted zone.
.. versionadded:: 2015.8.0
zone
DNS zone to create
private
True/False if the zone will be a private zone
vpc_id
VPC ID to associate the zone to (required if private is True)
vpc_region
VPC Region (required if private is True)
region
region endpoint to connect to
key
AWS key
keyid
AWS keyid
profile
AWS pillar profile
CLI Example::
salt myminion boto_route53.create_zone example.org | [
"Create",
"a",
"Route53",
"hosted",
"zone",
"."
] | python | train |
sosreport/sos | sos/plugins/__init__.py | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L754-L827 | def add_copy_spec(self, copyspecs, sizelimit=None, tailit=True, pred=None):
"""Add a file or glob but limit it to sizelimit megabytes. If fname is
a single file the file will be tailed to meet sizelimit. If the first
file in a glob is too large it will be tailed to meet the sizelimit.
"""
if not self.test_predicate(pred=pred):
self._log_info("skipped copy spec '%s' due to predicate (%s)" %
(copyspecs, self.get_predicate(pred=pred)))
return
if sizelimit is None:
sizelimit = self.get_option("log_size")
if self.get_option('all_logs'):
sizelimit = None
if sizelimit:
sizelimit *= 1024 * 1024 # in MB
if not copyspecs:
return False
if isinstance(copyspecs, six.string_types):
copyspecs = [copyspecs]
for copyspec in copyspecs:
if not (copyspec and len(copyspec)):
return False
if self.use_sysroot():
copyspec = self.join_sysroot(copyspec)
files = self._expand_copy_spec(copyspec)
if len(files) == 0:
continue
# Files hould be sorted in most-recently-modified order, so that
# we collect the newest data first before reaching the limit.
def getmtime(path):
try:
return os.path.getmtime(path)
except OSError:
return 0
files.sort(key=getmtime, reverse=True)
current_size = 0
limit_reached = False
_file = None
for _file in files:
if self._is_forbidden_path(_file):
self._log_debug("skipping forbidden path '%s'" % _file)
continue
try:
current_size += os.stat(_file)[stat.ST_SIZE]
except OSError:
self._log_info("failed to stat '%s'" % _file)
if sizelimit and current_size > sizelimit:
limit_reached = True
break
self._add_copy_paths([_file])
if limit_reached and tailit and not _file_is_compressed(_file):
file_name = _file
if file_name[0] == os.sep:
file_name = file_name.lstrip(os.sep)
strfile = file_name.replace(os.path.sep, ".") + ".tailed"
self.add_string_as_file(tail(_file, sizelimit), strfile)
rel_path = os.path.relpath('/', os.path.dirname(_file))
link_path = os.path.join(rel_path, 'sos_strings',
self.name(), strfile)
self.archive.add_link(link_path, _file) | [
"def",
"add_copy_spec",
"(",
"self",
",",
"copyspecs",
",",
"sizelimit",
"=",
"None",
",",
"tailit",
"=",
"True",
",",
"pred",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"test_predicate",
"(",
"pred",
"=",
"pred",
")",
":",
"self",
".",
"_log_i... | Add a file or glob but limit it to sizelimit megabytes. If fname is
a single file the file will be tailed to meet sizelimit. If the first
file in a glob is too large it will be tailed to meet the sizelimit. | [
"Add",
"a",
"file",
"or",
"glob",
"but",
"limit",
"it",
"to",
"sizelimit",
"megabytes",
".",
"If",
"fname",
"is",
"a",
"single",
"file",
"the",
"file",
"will",
"be",
"tailed",
"to",
"meet",
"sizelimit",
".",
"If",
"the",
"first",
"file",
"in",
"a",
"... | python | train |
ewels/MultiQC | multiqc/modules/fastqc/fastqc.py | https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/fastqc/fastqc.py#L117-L188 | def parse_fastqc_report(self, file_contents, s_name=None, f=None):
""" Takes contents from a fastq_data.txt file and parses out required
statistics and data. Returns a dict with keys 'stats' and 'data'.
Data is for plotting graphs, stats are for top table. """
# Make the sample name from the input filename if we find it
fn_search = re.search(r"Filename\s+(.+)", file_contents)
if fn_search:
s_name = self.clean_s_name(fn_search.group(1) , f['root'])
if s_name in self.fastqc_data.keys():
log.debug("Duplicate sample name found! Overwriting: {}".format(s_name))
self.add_data_source(f, s_name)
self.fastqc_data[s_name] = { 'statuses': dict() }
# Parse the report
section = None
s_headers = None
self.dup_keys = []
for l in file_contents.splitlines():
if l == '>>END_MODULE':
section = None
s_headers = None
elif l.startswith('>>'):
(section, status) = l[2:].split("\t", 1)
section = section.lower().replace(' ', '_')
self.fastqc_data[s_name]['statuses'][section] = status
elif section is not None:
if l.startswith('#'):
s_headers = l[1:].split("\t")
# Special case: Total Deduplicated Percentage header line
if s_headers[0] == 'Total Deduplicated Percentage':
self.fastqc_data[s_name]['basic_statistics'].append({
'measure': 'total_deduplicated_percentage',
'value': float(s_headers[1])
})
else:
# Special case: Rename dedup header in old versions of FastQC (v10)
if s_headers[1] == 'Relative count':
s_headers[1] = 'Percentage of total'
s_headers = [s.lower().replace(' ', '_') for s in s_headers]
self.fastqc_data[s_name][section] = list()
elif s_headers is not None:
s = l.split("\t")
row = dict()
for (i, v) in enumerate(s):
v.replace('NaN','0')
try:
v = float(v)
except ValueError:
pass
row[s_headers[i]] = v
self.fastqc_data[s_name][section].append(row)
# Special case - need to remember order of duplication keys
if section == 'sequence_duplication_levels':
try:
self.dup_keys.append(float(s[0]))
except ValueError:
self.dup_keys.append(s[0])
# Tidy up the Basic Stats
self.fastqc_data[s_name]['basic_statistics'] = {d['measure']: d['value'] for d in self.fastqc_data[s_name]['basic_statistics']}
# Calculate the average sequence length (Basic Statistics gives a range)
length_bp = 0
total_count = 0
for d in self.fastqc_data[s_name].get('sequence_length_distribution', {}):
length_bp += d['count'] * self.avg_bp_from_range(d['length'])
total_count += d['count']
if total_count > 0:
self.fastqc_data[s_name]['basic_statistics']['avg_sequence_length'] = length_bp / total_count | [
"def",
"parse_fastqc_report",
"(",
"self",
",",
"file_contents",
",",
"s_name",
"=",
"None",
",",
"f",
"=",
"None",
")",
":",
"# Make the sample name from the input filename if we find it",
"fn_search",
"=",
"re",
".",
"search",
"(",
"r\"Filename\\s+(.+)\"",
",",
"f... | Takes contents from a fastq_data.txt file and parses out required
statistics and data. Returns a dict with keys 'stats' and 'data'.
Data is for plotting graphs, stats are for top table. | [
"Takes",
"contents",
"from",
"a",
"fastq_data",
".",
"txt",
"file",
"and",
"parses",
"out",
"required",
"statistics",
"and",
"data",
".",
"Returns",
"a",
"dict",
"with",
"keys",
"stats",
"and",
"data",
".",
"Data",
"is",
"for",
"plotting",
"graphs",
"stats... | python | train |
belbio/bel | bel/utils.py | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/utils.py#L27-L56 | def get_url(url: str, params: dict = {}, timeout: float = 5.0, cache: bool = True):
"""Wrapper for requests.get(url)
Args:
url: url to retrieve
params: query string parameters
timeout: allow this much time for the request and time it out if over
cache: Cache for up to a day unless this is false
Returns:
Requests Result obj or None if timed out
"""
try:
if not cache:
with requests_cache.disabled():
r = requests.get(url, params=params, timeout=timeout)
else:
r = requests.get(url, params=params, timeout=timeout)
log.debug(f"Response headers {r.headers} From cache {r.from_cache}")
return r
except requests.exceptions.Timeout:
log.warn(f"Timed out getting url in get_url: {url}")
return None
except Exception as e:
log.warn(f"Error getting url: {url} error: {e}")
return None | [
"def",
"get_url",
"(",
"url",
":",
"str",
",",
"params",
":",
"dict",
"=",
"{",
"}",
",",
"timeout",
":",
"float",
"=",
"5.0",
",",
"cache",
":",
"bool",
"=",
"True",
")",
":",
"try",
":",
"if",
"not",
"cache",
":",
"with",
"requests_cache",
".",... | Wrapper for requests.get(url)
Args:
url: url to retrieve
params: query string parameters
timeout: allow this much time for the request and time it out if over
cache: Cache for up to a day unless this is false
Returns:
Requests Result obj or None if timed out | [
"Wrapper",
"for",
"requests",
".",
"get",
"(",
"url",
")"
] | python | train |
marcomusy/vtkplotter | vtkplotter/plotter.py | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/plotter.py#L661-L696 | def moveCamera(self, camstart, camstop, fraction):
"""
Takes as input two ``vtkCamera`` objects and returns a
new ``vtkCamera`` that is at an intermediate position:
fraction=0 -> camstart, fraction=1 -> camstop.
Press ``shift-C`` key in interactive mode to dump a python snipplet
of parameters for the current camera view.
"""
if isinstance(fraction, int):
colors.printc("~lightning Warning in moveCamera(): fraction should not be an integer", c=1)
if fraction > 1:
colors.printc("~lightning Warning in moveCamera(): fraction is > 1", c=1)
cam = vtk.vtkCamera()
cam.DeepCopy(camstart)
p1 = numpy.array(camstart.GetPosition())
f1 = numpy.array(camstart.GetFocalPoint())
v1 = numpy.array(camstart.GetViewUp())
c1 = numpy.array(camstart.GetClippingRange())
s1 = camstart.GetDistance()
p2 = numpy.array(camstop.GetPosition())
f2 = numpy.array(camstop.GetFocalPoint())
v2 = numpy.array(camstop.GetViewUp())
c2 = numpy.array(camstop.GetClippingRange())
s2 = camstop.GetDistance()
cam.SetPosition(p2 * fraction + p1 * (1 - fraction))
cam.SetFocalPoint(f2 * fraction + f1 * (1 - fraction))
cam.SetViewUp(v2 * fraction + v1 * (1 - fraction))
cam.SetDistance(s2 * fraction + s1 * (1 - fraction))
cam.SetClippingRange(c2 * fraction + c1 * (1 - fraction))
self.camera = cam
save_int = self.interactive
self.show(resetcam=0, interactive=0)
self.interactive = save_int | [
"def",
"moveCamera",
"(",
"self",
",",
"camstart",
",",
"camstop",
",",
"fraction",
")",
":",
"if",
"isinstance",
"(",
"fraction",
",",
"int",
")",
":",
"colors",
".",
"printc",
"(",
"\"~lightning Warning in moveCamera(): fraction should not be an integer\"",
",",
... | Takes as input two ``vtkCamera`` objects and returns a
new ``vtkCamera`` that is at an intermediate position:
fraction=0 -> camstart, fraction=1 -> camstop.
Press ``shift-C`` key in interactive mode to dump a python snipplet
of parameters for the current camera view. | [
"Takes",
"as",
"input",
"two",
"vtkCamera",
"objects",
"and",
"returns",
"a",
"new",
"vtkCamera",
"that",
"is",
"at",
"an",
"intermediate",
"position",
":"
] | python | train |
jaraco/irc | irc/server.py | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/server.py#L346-L355 | def _send_to_others(self, message, channel):
"""
Send the message to all clients in the specified channel except for
self.
"""
other_clients = [
client for client in channel.clients
if not client == self]
for client in other_clients:
client.send_queue.append(message) | [
"def",
"_send_to_others",
"(",
"self",
",",
"message",
",",
"channel",
")",
":",
"other_clients",
"=",
"[",
"client",
"for",
"client",
"in",
"channel",
".",
"clients",
"if",
"not",
"client",
"==",
"self",
"]",
"for",
"client",
"in",
"other_clients",
":",
... | Send the message to all clients in the specified channel except for
self. | [
"Send",
"the",
"message",
"to",
"all",
"clients",
"in",
"the",
"specified",
"channel",
"except",
"for",
"self",
"."
] | python | train |
datajoint/datajoint-python | datajoint/table.py | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/table.py#L58-L74 | def declare(self, context=None):
"""
Use self.definition to declare the table in the schema.
"""
try:
sql, uses_external = declare(self.full_table_name, self.definition, context)
if uses_external:
sql = sql.format(external_table=self.external_table.full_table_name)
self.connection.query(sql)
except pymysql.OperationalError as error:
# skip if no create privilege
if error.args[0] == server_error_codes['command denied']:
logger.warning(error.args[1])
else:
raise
else:
self._log('Declared ' + self.full_table_name) | [
"def",
"declare",
"(",
"self",
",",
"context",
"=",
"None",
")",
":",
"try",
":",
"sql",
",",
"uses_external",
"=",
"declare",
"(",
"self",
".",
"full_table_name",
",",
"self",
".",
"definition",
",",
"context",
")",
"if",
"uses_external",
":",
"sql",
... | Use self.definition to declare the table in the schema. | [
"Use",
"self",
".",
"definition",
"to",
"declare",
"the",
"table",
"in",
"the",
"schema",
"."
] | python | train |
ronaldguillen/wave | wave/views.py | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/views.py#L343-L351 | def determine_version(self, request, *args, **kwargs):
"""
If versioning is being used, then determine any API version for the
incoming request. Returns a two-tuple of (version, versioning_scheme)
"""
if self.versioning_class is None:
return (None, None)
scheme = self.versioning_class()
return (scheme.determine_version(request, *args, **kwargs), scheme) | [
"def",
"determine_version",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"versioning_class",
"is",
"None",
":",
"return",
"(",
"None",
",",
"None",
")",
"scheme",
"=",
"self",
".",
"versioning_cla... | If versioning is being used, then determine any API version for the
incoming request. Returns a two-tuple of (version, versioning_scheme) | [
"If",
"versioning",
"is",
"being",
"used",
"then",
"determine",
"any",
"API",
"version",
"for",
"the",
"incoming",
"request",
".",
"Returns",
"a",
"two",
"-",
"tuple",
"of",
"(",
"version",
"versioning_scheme",
")"
] | python | train |
ishepard/pydriller | pydriller/git_repository.py | https://github.com/ishepard/pydriller/blob/71facb32afa085d5ddf0081beba34d00d57b8080/pydriller/git_repository.py#L144-L156 | def files(self) -> List[str]:
"""
Obtain the list of the files (excluding .git directory).
:return: List[str], the list of the files
"""
_all = []
for path, _, files in os.walk(str(self.path)):
if '.git' in path:
continue
for name in files:
_all.append(os.path.join(path, name))
return _all | [
"def",
"files",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"_all",
"=",
"[",
"]",
"for",
"path",
",",
"_",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"str",
"(",
"self",
".",
"path",
")",
")",
":",
"if",
"'.git'",
"in",
"path",
... | Obtain the list of the files (excluding .git directory).
:return: List[str], the list of the files | [
"Obtain",
"the",
"list",
"of",
"the",
"files",
"(",
"excluding",
".",
"git",
"directory",
")",
"."
] | python | train |
apache/airflow | airflow/hooks/mysql_hook.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/mysql_hook.py#L62-L105 | def get_conn(self):
"""
Returns a mysql connection object
"""
conn = self.get_connection(self.mysql_conn_id)
conn_config = {
"user": conn.login,
"passwd": conn.password or '',
"host": conn.host or 'localhost',
"db": self.schema or conn.schema or ''
}
if not conn.port:
conn_config["port"] = 3306
else:
conn_config["port"] = int(conn.port)
if conn.extra_dejson.get('charset', False):
conn_config["charset"] = conn.extra_dejson["charset"]
if (conn_config["charset"]).lower() == 'utf8' or\
(conn_config["charset"]).lower() == 'utf-8':
conn_config["use_unicode"] = True
if conn.extra_dejson.get('cursor', False):
if (conn.extra_dejson["cursor"]).lower() == 'sscursor':
conn_config["cursorclass"] = MySQLdb.cursors.SSCursor
elif (conn.extra_dejson["cursor"]).lower() == 'dictcursor':
conn_config["cursorclass"] = MySQLdb.cursors.DictCursor
elif (conn.extra_dejson["cursor"]).lower() == 'ssdictcursor':
conn_config["cursorclass"] = MySQLdb.cursors.SSDictCursor
local_infile = conn.extra_dejson.get('local_infile', False)
if conn.extra_dejson.get('ssl', False):
# SSL parameter for MySQL has to be a dictionary and in case
# of extra/dejson we can get string if extra is passed via
# URL parameters
dejson_ssl = conn.extra_dejson['ssl']
if isinstance(dejson_ssl, six.string_types):
dejson_ssl = json.loads(dejson_ssl)
conn_config['ssl'] = dejson_ssl
if conn.extra_dejson.get('unix_socket'):
conn_config['unix_socket'] = conn.extra_dejson['unix_socket']
if local_infile:
conn_config["local_infile"] = 1
conn = MySQLdb.connect(**conn_config)
return conn | [
"def",
"get_conn",
"(",
"self",
")",
":",
"conn",
"=",
"self",
".",
"get_connection",
"(",
"self",
".",
"mysql_conn_id",
")",
"conn_config",
"=",
"{",
"\"user\"",
":",
"conn",
".",
"login",
",",
"\"passwd\"",
":",
"conn",
".",
"password",
"or",
"''",
"... | Returns a mysql connection object | [
"Returns",
"a",
"mysql",
"connection",
"object"
] | python | test |
GoogleCloudPlatform/cloud-debug-python | src/googleclouddebugger/gcp_hub_client.py | https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/gcp_hub_client.py#L303-L340 | def _RegisterDebuggee(self, service):
"""Single attempt to register the debuggee.
If the registration succeeds, sets self._debuggee_id to the registered
debuggee ID.
Args:
service: client to use for API calls
Returns:
(registration_required, delay) tuple
"""
try:
request = {'debuggee': self._GetDebuggee()}
try:
response = service.debuggees().register(body=request).execute()
# self._project_number will refer to the project id on initialization if
# the project number is not available. The project field in the debuggee
# will always refer to the project number. Update so the server will not
# have to do id->number translations in the future.
project_number = response['debuggee'].get('project')
self._project_number = project_number or self._project_number
self._debuggee_id = response['debuggee']['id']
native.LogInfo('Debuggee registered successfully, ID: %s' % (
self._debuggee_id))
self.register_backoff.Succeeded()
return (False, 0) # Proceed immediately to list active breakpoints.
except BaseException:
native.LogInfo('Failed to register debuggee: %s, %s' %
(request, traceback.format_exc()))
except BaseException:
native.LogWarning('Debuggee information not available: ' +
traceback.format_exc())
return (True, self.register_backoff.Failed()) | [
"def",
"_RegisterDebuggee",
"(",
"self",
",",
"service",
")",
":",
"try",
":",
"request",
"=",
"{",
"'debuggee'",
":",
"self",
".",
"_GetDebuggee",
"(",
")",
"}",
"try",
":",
"response",
"=",
"service",
".",
"debuggees",
"(",
")",
".",
"register",
"(",... | Single attempt to register the debuggee.
If the registration succeeds, sets self._debuggee_id to the registered
debuggee ID.
Args:
service: client to use for API calls
Returns:
(registration_required, delay) tuple | [
"Single",
"attempt",
"to",
"register",
"the",
"debuggee",
"."
] | python | train |
ttinies/sc2common | sc2common/containers.py | https://github.com/ttinies/sc2common/blob/469623c319c7ab7af799551055839ea3b3f87d54/sc2common/containers.py#L270-L274 | def magnitude(self, allow3d=True):
"""determine the magnitude of this location from the origin (presume values represent a Vector)"""
ret = self.x**2 + self.y**2
if allow3d: ret += self.z**2
return ret**0.5 # square root | [
"def",
"magnitude",
"(",
"self",
",",
"allow3d",
"=",
"True",
")",
":",
"ret",
"=",
"self",
".",
"x",
"**",
"2",
"+",
"self",
".",
"y",
"**",
"2",
"if",
"allow3d",
":",
"ret",
"+=",
"self",
".",
"z",
"**",
"2",
"return",
"ret",
"**",
"0.5",
"... | determine the magnitude of this location from the origin (presume values represent a Vector) | [
"determine",
"the",
"magnitude",
"of",
"this",
"location",
"from",
"the",
"origin",
"(",
"presume",
"values",
"represent",
"a",
"Vector",
")"
] | python | train |
djordon/queueing-tool | queueing_tool/graph/graph_wrapper.py | https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/graph/graph_wrapper.py#L73-L181 | def adjacency2graph(adjacency, edge_type=None, adjust=1, **kwargs):
"""Takes an adjacency list, dict, or matrix and returns a graph.
The purpose of this function is take an adjacency list (or matrix)
and return a :class:`.QueueNetworkDiGraph` that can be used with a
:class:`.QueueNetwork` instance. The Graph returned has the
``edge_type`` edge property set for each edge. Note that the graph may
be altered.
Parameters
----------
adjacency : dict or :class:`~numpy.ndarray`
An adjacency list as either a dict, or an adjacency matrix.
adjust : int ``{1, 2}`` (optional, default: 1)
Specifies what to do when the graph has terminal vertices
(nodes with no out-edges). Note that if ``adjust`` is not 2
then it is assumed to be 1. There are two choices:
* ``adjust = 1``: A loop is added to each terminal node in the
graph, and their ``edge_type`` of that loop is set to 0.
* ``adjust = 2``: All edges leading to terminal nodes have
their ``edge_type`` set to 0.
**kwargs :
Unused.
Returns
-------
out : :any:`networkx.DiGraph`
A directed graph with the ``edge_type`` edge property.
Raises
------
TypeError
Is raised if ``adjacency`` is not a dict or
:class:`~numpy.ndarray`.
Examples
--------
If terminal nodes are such that all in-edges have edge type ``0``
then nothing is changed. However, if a node is a terminal node then
a loop is added with edge type 0.
>>> import queueing_tool as qt
>>> adj = {
... 0: {1: {}},
... 1: {2: {},
... 3: {}},
... 3: {0: {}}}
>>> eTy = {0: {1: 1}, 1: {2: 2, 3: 4}, 3: {0: 1}}
>>> # A loop will be added to vertex 2
>>> g = qt.adjacency2graph(adj, edge_type=eTy)
>>> ans = qt.graph2dict(g)
>>> sorted(ans.items()) # doctest: +NORMALIZE_WHITESPACE
[(0, {1: {'edge_type': 1}}),
(1, {2: {'edge_type': 2}, 3: {'edge_type': 4}}),
(2, {2: {'edge_type': 0}}),
(3, {0: {'edge_type': 1}})]
You can use a dict of lists to represent the adjacency list.
>>> adj = {0 : [1], 1: [2, 3], 3: [0]}
>>> g = qt.adjacency2graph(adj, edge_type=eTy)
>>> ans = qt.graph2dict(g)
>>> sorted(ans.items()) # doctest: +NORMALIZE_WHITESPACE
[(0, {1: {'edge_type': 1}}),
(1, {2: {'edge_type': 2}, 3: {'edge_type': 4}}),
(2, {2: {'edge_type': 0}}),
(3, {0: {'edge_type': 1}})]
Alternatively, you could have this function adjust the edges that
lead to terminal vertices by changing their edge type to 0:
>>> # The graph is unaltered
>>> g = qt.adjacency2graph(adj, edge_type=eTy, adjust=2)
>>> ans = qt.graph2dict(g)
>>> sorted(ans.items()) # doctest: +NORMALIZE_WHITESPACE
[(0, {1: {'edge_type': 1}}),
(1, {2: {'edge_type': 0}, 3: {'edge_type': 4}}),
(2, {}),
(3, {0: {'edge_type': 1}})]
"""
if isinstance(adjacency, np.ndarray):
adjacency = _matrix2dict(adjacency)
elif isinstance(adjacency, dict):
adjacency = _dict2dict(adjacency)
else:
msg = ("If the adjacency parameter is supplied it must be a "
"dict, or a numpy.ndarray.")
raise TypeError(msg)
if edge_type is None:
edge_type = {}
else:
if isinstance(edge_type, np.ndarray):
edge_type = _matrix2dict(edge_type, etype=True)
elif isinstance(edge_type, dict):
edge_type = _dict2dict(edge_type)
for u, ty in edge_type.items():
for v, et in ty.items():
adjacency[u][v]['edge_type'] = et
g = nx.from_dict_of_dicts(adjacency, create_using=nx.DiGraph())
adjacency = nx.to_dict_of_dicts(g)
adjacency = _adjacency_adjust(adjacency, adjust, True)
return nx.from_dict_of_dicts(adjacency, create_using=nx.DiGraph()) | [
"def",
"adjacency2graph",
"(",
"adjacency",
",",
"edge_type",
"=",
"None",
",",
"adjust",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"adjacency",
",",
"np",
".",
"ndarray",
")",
":",
"adjacency",
"=",
"_matrix2dict",
"(",
"ad... | Takes an adjacency list, dict, or matrix and returns a graph.
The purpose of this function is take an adjacency list (or matrix)
and return a :class:`.QueueNetworkDiGraph` that can be used with a
:class:`.QueueNetwork` instance. The Graph returned has the
``edge_type`` edge property set for each edge. Note that the graph may
be altered.
Parameters
----------
adjacency : dict or :class:`~numpy.ndarray`
An adjacency list as either a dict, or an adjacency matrix.
adjust : int ``{1, 2}`` (optional, default: 1)
Specifies what to do when the graph has terminal vertices
(nodes with no out-edges). Note that if ``adjust`` is not 2
then it is assumed to be 1. There are two choices:
* ``adjust = 1``: A loop is added to each terminal node in the
graph, and their ``edge_type`` of that loop is set to 0.
* ``adjust = 2``: All edges leading to terminal nodes have
their ``edge_type`` set to 0.
**kwargs :
Unused.
Returns
-------
out : :any:`networkx.DiGraph`
A directed graph with the ``edge_type`` edge property.
Raises
------
TypeError
Is raised if ``adjacency`` is not a dict or
:class:`~numpy.ndarray`.
Examples
--------
If terminal nodes are such that all in-edges have edge type ``0``
then nothing is changed. However, if a node is a terminal node then
a loop is added with edge type 0.
>>> import queueing_tool as qt
>>> adj = {
... 0: {1: {}},
... 1: {2: {},
... 3: {}},
... 3: {0: {}}}
>>> eTy = {0: {1: 1}, 1: {2: 2, 3: 4}, 3: {0: 1}}
>>> # A loop will be added to vertex 2
>>> g = qt.adjacency2graph(adj, edge_type=eTy)
>>> ans = qt.graph2dict(g)
>>> sorted(ans.items()) # doctest: +NORMALIZE_WHITESPACE
[(0, {1: {'edge_type': 1}}),
(1, {2: {'edge_type': 2}, 3: {'edge_type': 4}}),
(2, {2: {'edge_type': 0}}),
(3, {0: {'edge_type': 1}})]
You can use a dict of lists to represent the adjacency list.
>>> adj = {0 : [1], 1: [2, 3], 3: [0]}
>>> g = qt.adjacency2graph(adj, edge_type=eTy)
>>> ans = qt.graph2dict(g)
>>> sorted(ans.items()) # doctest: +NORMALIZE_WHITESPACE
[(0, {1: {'edge_type': 1}}),
(1, {2: {'edge_type': 2}, 3: {'edge_type': 4}}),
(2, {2: {'edge_type': 0}}),
(3, {0: {'edge_type': 1}})]
Alternatively, you could have this function adjust the edges that
lead to terminal vertices by changing their edge type to 0:
>>> # The graph is unaltered
>>> g = qt.adjacency2graph(adj, edge_type=eTy, adjust=2)
>>> ans = qt.graph2dict(g)
>>> sorted(ans.items()) # doctest: +NORMALIZE_WHITESPACE
[(0, {1: {'edge_type': 1}}),
(1, {2: {'edge_type': 0}, 3: {'edge_type': 4}}),
(2, {}),
(3, {0: {'edge_type': 1}})] | [
"Takes",
"an",
"adjacency",
"list",
"dict",
"or",
"matrix",
"and",
"returns",
"a",
"graph",
"."
] | python | valid |
EventTeam/beliefs | src/beliefs/cells/lists.py | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/lists.py#L304-L323 | def merge(self, other):
"""
Merges two prefixes
"""
other = PrefixCell.coerce(other)
if self.is_equal(other):
# pick among dependencies
return self
elif other.is_entailed_by(self):
return self
elif self.is_entailed_by(other):
self.value = other.value
elif self.is_contradictory(other):
raise Contradiction("Cannot merge prefix '%s' with '%s'" % \
(self, other))
else:
if len(self.value) > len(other.value):
self.value = other.value[:]
# otherwise, return self
return self | [
"def",
"merge",
"(",
"self",
",",
"other",
")",
":",
"other",
"=",
"PrefixCell",
".",
"coerce",
"(",
"other",
")",
"if",
"self",
".",
"is_equal",
"(",
"other",
")",
":",
"# pick among dependencies",
"return",
"self",
"elif",
"other",
".",
"is_entailed_by",... | Merges two prefixes | [
"Merges",
"two",
"prefixes"
] | python | train |
StackStorm/pybind | pybind/slxos/v17r_1_01a/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17r_1_01a/__init__.py#L13373-L13396 | def _set_loam_state(self, v, load=False):
"""
Setter method for loam_state, mapped from YANG variable /loam_state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_loam_state is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_loam_state() directly.
YANG Description: LINK-OAM Operational Information
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=loam_state.loam_state, is_container='container', presence=False, yang_name="loam-state", rest_name="loam-state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'callpoint': u'dot1ag-loam', u'cli-suppress-show-path': None}}, namespace='urn:brocade.com:mgmt:brocade-dot1ag-operational', defining_module='brocade-dot1ag-operational', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """loam_state must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=loam_state.loam_state, is_container='container', presence=False, yang_name="loam-state", rest_name="loam-state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'callpoint': u'dot1ag-loam', u'cli-suppress-show-path': None}}, namespace='urn:brocade.com:mgmt:brocade-dot1ag-operational', defining_module='brocade-dot1ag-operational', yang_type='container', is_config=True)""",
})
self.__loam_state = t
if hasattr(self, '_set'):
self._set() | [
"def",
"_set_loam_state",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"bas... | Setter method for loam_state, mapped from YANG variable /loam_state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_loam_state is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_loam_state() directly.
YANG Description: LINK-OAM Operational Information | [
"Setter",
"method",
"for",
"loam_state",
"mapped",
"from",
"YANG",
"variable",
"/",
"loam_state",
"(",
"container",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
"source",
"YANG",
"file",
"then",
... | python | train |
d0c-s4vage/pfp | pfp/interp.py | https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L951-L972 | def _handle_file_ast(self, node, scope, ctxt, stream):
"""TODO: Docstring for _handle_file_ast.
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO
"""
self._root = ctxt = fields.Dom(stream)
ctxt._pfp__scope = scope
self._root._pfp__name = "__root"
self._root._pfp__interp = self
self._dlog("handling file AST with {} children".format(len(node.children())))
for child in node.children():
self._handle_node(child, scope, ctxt, stream)
ctxt._pfp__process_fields_metadata()
return ctxt | [
"def",
"_handle_file_ast",
"(",
"self",
",",
"node",
",",
"scope",
",",
"ctxt",
",",
"stream",
")",
":",
"self",
".",
"_root",
"=",
"ctxt",
"=",
"fields",
".",
"Dom",
"(",
"stream",
")",
"ctxt",
".",
"_pfp__scope",
"=",
"scope",
"self",
".",
"_root",... | TODO: Docstring for _handle_file_ast.
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO | [
"TODO",
":",
"Docstring",
"for",
"_handle_file_ast",
"."
] | python | train |
ewiger/mlab | src/mlab/awmstools.py | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L655-L669 | def unweave(iterable, n=2):
r"""Divide `iterable` in `n` lists, so that every `n`th element belongs to
list `n`.
Example:
>>> unweave((1,2,3,4,5), 3)
[[1, 4], [2, 5], [3]]
"""
res = [[] for i in range(n)]
i = 0
for x in iterable:
res[i % n].append(x)
i += 1
return res | [
"def",
"unweave",
"(",
"iterable",
",",
"n",
"=",
"2",
")",
":",
"res",
"=",
"[",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"n",
")",
"]",
"i",
"=",
"0",
"for",
"x",
"in",
"iterable",
":",
"res",
"[",
"i",
"%",
"n",
"]",
".",
"append",
"(... | r"""Divide `iterable` in `n` lists, so that every `n`th element belongs to
list `n`.
Example:
>>> unweave((1,2,3,4,5), 3)
[[1, 4], [2, 5], [3]] | [
"r",
"Divide",
"iterable",
"in",
"n",
"lists",
"so",
"that",
"every",
"n",
"th",
"element",
"belongs",
"to",
"list",
"n",
"."
] | python | train |
blackecho/Deep-Learning-TensorFlow | yadlt/utils/tf_utils.py | https://github.com/blackecho/Deep-Learning-TensorFlow/blob/ddeb1f2848da7b7bee166ad2152b4afc46bb2086/yadlt/utils/tf_utils.py#L53-L93 | def run_summaries(
sess, merged_summaries, summary_writer, epoch, feed, tens):
"""Run the summaries and error computation on the validation set.
Parameters
----------
sess : tf.Session
Tensorflow session object.
merged_summaries : tf obj
Tensorflow merged summaries obj.
summary_writer : tf.summary.FileWriter
Tensorflow summary writer obj.
epoch : int
Current training epoch.
feed : dict
Validation feed dict.
tens : tf.Tensor
Tensor to display and evaluate during training.
Can be self.accuracy for SupervisedModel or self.cost for
UnsupervisedModel.
Returns
-------
err : float, mean error over the validation set.
"""
try:
result = sess.run([merged_summaries, tens], feed_dict=feed)
summary_str = result[0]
out = result[1]
summary_writer.add_summary(summary_str, epoch)
except tf.errors.InvalidArgumentError:
out = sess.run(tens, feed_dict=feed)
return out | [
"def",
"run_summaries",
"(",
"sess",
",",
"merged_summaries",
",",
"summary_writer",
",",
"epoch",
",",
"feed",
",",
"tens",
")",
":",
"try",
":",
"result",
"=",
"sess",
".",
"run",
"(",
"[",
"merged_summaries",
",",
"tens",
"]",
",",
"feed_dict",
"=",
... | Run the summaries and error computation on the validation set.
Parameters
----------
sess : tf.Session
Tensorflow session object.
merged_summaries : tf obj
Tensorflow merged summaries obj.
summary_writer : tf.summary.FileWriter
Tensorflow summary writer obj.
epoch : int
Current training epoch.
feed : dict
Validation feed dict.
tens : tf.Tensor
Tensor to display and evaluate during training.
Can be self.accuracy for SupervisedModel or self.cost for
UnsupervisedModel.
Returns
-------
err : float, mean error over the validation set. | [
"Run",
"the",
"summaries",
"and",
"error",
"computation",
"on",
"the",
"validation",
"set",
"."
] | python | train |
mrstephenneal/mysql-toolkit | mysql/toolkit/components/structure/__init__.py | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/structure/__init__.py#L55-L58 | def get_duplicate_vals(self, table, column):
"""Retrieve duplicate values in a column of a table."""
query = 'SELECT {0} FROM {1} GROUP BY {0} HAVING COUNT(*) > 1'.format(join_cols(column), wrap(table))
return self.fetch(query) | [
"def",
"get_duplicate_vals",
"(",
"self",
",",
"table",
",",
"column",
")",
":",
"query",
"=",
"'SELECT {0} FROM {1} GROUP BY {0} HAVING COUNT(*) > 1'",
".",
"format",
"(",
"join_cols",
"(",
"column",
")",
",",
"wrap",
"(",
"table",
")",
")",
"return",
"self",
... | Retrieve duplicate values in a column of a table. | [
"Retrieve",
"duplicate",
"values",
"in",
"a",
"column",
"of",
"a",
"table",
"."
] | python | train |
PmagPy/PmagPy | SPD/lib/lib_ptrm_statistics.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/SPD/lib/lib_ptrm_statistics.py#L198-L212 | def get_b_star(x_star, y_err, y_mean, y_segment):
"""
input: x_star, y_err, y_mean, y_segment
output: b_star (corrected slope for delta_pal statistic)
"""
#print "x_star, should be same as Xcorr / NRM"
#print x_star
x_star_mean = numpy.mean(x_star)
x_err = x_star - x_star_mean
b_star = -1* numpy.sqrt( old_div(sum(numpy.array(y_err)**2), sum(numpy.array(x_err)**2)) ) # averaged slope
#print "y_segment", y_segment
b_star = numpy.sign(sum(x_err * y_err)) * numpy.std(y_segment, ddof=1) / numpy.std(x_star, ddof=1)
#print "b_star (should be same as corr_slope)"
#print b_star
return b_star | [
"def",
"get_b_star",
"(",
"x_star",
",",
"y_err",
",",
"y_mean",
",",
"y_segment",
")",
":",
"#print \"x_star, should be same as Xcorr / NRM\"",
"#print x_star",
"x_star_mean",
"=",
"numpy",
".",
"mean",
"(",
"x_star",
")",
"x_err",
"=",
"x_star",
"-",
"x_star_mea... | input: x_star, y_err, y_mean, y_segment
output: b_star (corrected slope for delta_pal statistic) | [
"input",
":",
"x_star",
"y_err",
"y_mean",
"y_segment",
"output",
":",
"b_star",
"(",
"corrected",
"slope",
"for",
"delta_pal",
"statistic",
")"
] | python | train |
DataBiosphere/toil | src/toil/__init__.py | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/__init__.py#L384-L410 | def requestCheckDockerIo(origAppliance, imageName, tag):
"""
Checks docker.io to see if an image exists using the requests library.
URL is based on the docker v2 schema. Requires that an access token be fetched first.
:param str origAppliance: The full url of the docker image originally
specified by the user (or the default). e.g. "ubuntu:latest"
:param str imageName: The image, including path and excluding the tag. e.g. "ubuntu"
:param str tag: The tag used at that docker image's registry. e.g. "latest"
:return: Return True if match found. Raise otherwise.
"""
# only official images like 'busybox' or 'ubuntu'
if '/' not in imageName:
imageName = 'library/' + imageName
token_url = 'https://auth.docker.io/token?service=registry.docker.io&scope=repository:{repo}:pull'.format(repo=imageName)
requests_url = 'https://registry-1.docker.io/v2/{repo}/manifests/{tag}'.format(repo=imageName, tag=tag)
token = requests.get(token_url)
jsonToken = token.json()
bearer = jsonToken["token"]
response = requests.head(requests_url, headers={'Authorization': 'Bearer {}'.format(bearer)})
if not response.ok:
raise ApplianceImageNotFound(origAppliance, requests_url, response.status_code)
else:
return origAppliance | [
"def",
"requestCheckDockerIo",
"(",
"origAppliance",
",",
"imageName",
",",
"tag",
")",
":",
"# only official images like 'busybox' or 'ubuntu'",
"if",
"'/'",
"not",
"in",
"imageName",
":",
"imageName",
"=",
"'library/'",
"+",
"imageName",
"token_url",
"=",
"'https://... | Checks docker.io to see if an image exists using the requests library.
URL is based on the docker v2 schema. Requires that an access token be fetched first.
:param str origAppliance: The full url of the docker image originally
specified by the user (or the default). e.g. "ubuntu:latest"
:param str imageName: The image, including path and excluding the tag. e.g. "ubuntu"
:param str tag: The tag used at that docker image's registry. e.g. "latest"
:return: Return True if match found. Raise otherwise. | [
"Checks",
"docker",
".",
"io",
"to",
"see",
"if",
"an",
"image",
"exists",
"using",
"the",
"requests",
"library",
"."
] | python | train |
Karaage-Cluster/karaage | karaage/datastores/slurm.py | https://github.com/Karaage-Cluster/karaage/blob/2f4c8b4e2d728b3fcbb151160c49000f1c04f5c9/karaage/datastores/slurm.py#L401-L411 | def delete_project(self, project):
""" Called when project is deleted. """
pid = project.pid
# project deleted
ds_project = self.get_project(pid)
if ds_project is not None:
self._call(["delete", "account", "name=%s" % pid])
return | [
"def",
"delete_project",
"(",
"self",
",",
"project",
")",
":",
"pid",
"=",
"project",
".",
"pid",
"# project deleted",
"ds_project",
"=",
"self",
".",
"get_project",
"(",
"pid",
")",
"if",
"ds_project",
"is",
"not",
"None",
":",
"self",
".",
"_call",
"(... | Called when project is deleted. | [
"Called",
"when",
"project",
"is",
"deleted",
"."
] | python | train |
GNS3/gns3-server | gns3server/controller/udp_link.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/udp_link.py#L165-L172 | def stop_capture(self):
"""
Stop capture on a link
"""
if self._capture_node:
yield from self._capture_node["node"].post("/adapters/{adapter_number}/ports/{port_number}/stop_capture".format(adapter_number=self._capture_node["adapter_number"], port_number=self._capture_node["port_number"]))
self._capture_node = None
yield from super().stop_capture() | [
"def",
"stop_capture",
"(",
"self",
")",
":",
"if",
"self",
".",
"_capture_node",
":",
"yield",
"from",
"self",
".",
"_capture_node",
"[",
"\"node\"",
"]",
".",
"post",
"(",
"\"/adapters/{adapter_number}/ports/{port_number}/stop_capture\"",
".",
"format",
"(",
"ad... | Stop capture on a link | [
"Stop",
"capture",
"on",
"a",
"link"
] | python | train |
seleniumbase/SeleniumBase | seleniumbase/fixtures/page_utils.py | https://github.com/seleniumbase/SeleniumBase/blob/62e5b43ee1f90a9ed923841bdd53b1b38358f43a/seleniumbase/fixtures/page_utils.py#L132-L145 | def _get_link_status_code(link, allow_redirects=False, timeout=5):
""" Get the status code of a link.
If the timeout is exceeded, will return a 404.
For a list of available status codes, see:
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
"""
status_code = None
try:
response = requests.get(
link, allow_redirects=allow_redirects, timeout=timeout)
status_code = response.status_code
except Exception:
status_code = 404
return status_code | [
"def",
"_get_link_status_code",
"(",
"link",
",",
"allow_redirects",
"=",
"False",
",",
"timeout",
"=",
"5",
")",
":",
"status_code",
"=",
"None",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"link",
",",
"allow_redirects",
"=",
"allow_redirects... | Get the status code of a link.
If the timeout is exceeded, will return a 404.
For a list of available status codes, see:
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes | [
"Get",
"the",
"status",
"code",
"of",
"a",
"link",
".",
"If",
"the",
"timeout",
"is",
"exceeded",
"will",
"return",
"a",
"404",
".",
"For",
"a",
"list",
"of",
"available",
"status",
"codes",
"see",
":",
"https",
":",
"//",
"en",
".",
"wikipedia",
"."... | python | train |
pantsbuild/pants | src/python/pants/backend/jvm/tasks/jar_task.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/jar_task.py#L160-L181 | def write(self, src, dest=None):
"""Schedules a write of the file at ``src`` to the ``dest`` path in this jar.
If the ``src`` is a file, then ``dest`` must be specified.
If the ``src`` is a directory then by default all descendant files will be added to the jar as
entries carrying their relative path. If ``dest`` is specified it will be prefixed to each
descendant's relative path to form its jar entry path.
:param string src: the path to the pre-existing source file or directory
:param string dest: the path the source file or directory should have in this jar
"""
if not src or not isinstance(src, string_types):
raise ValueError('The src path must be a non-empty string, got {} of type {}.'.format(
src, type(src)))
if dest and not isinstance(dest, string_types):
raise ValueError('The dest entry path must be a non-empty string, got {} of type {}.'.format(
dest, type(dest)))
if not os.path.isdir(src) and not dest:
raise self.Error('Source file {} must have a jar destination specified'.format(src))
self._add_entry(self.FileSystemEntry(src, dest)) | [
"def",
"write",
"(",
"self",
",",
"src",
",",
"dest",
"=",
"None",
")",
":",
"if",
"not",
"src",
"or",
"not",
"isinstance",
"(",
"src",
",",
"string_types",
")",
":",
"raise",
"ValueError",
"(",
"'The src path must be a non-empty string, got {} of type {}.'",
... | Schedules a write of the file at ``src`` to the ``dest`` path in this jar.
If the ``src`` is a file, then ``dest`` must be specified.
If the ``src`` is a directory then by default all descendant files will be added to the jar as
entries carrying their relative path. If ``dest`` is specified it will be prefixed to each
descendant's relative path to form its jar entry path.
:param string src: the path to the pre-existing source file or directory
:param string dest: the path the source file or directory should have in this jar | [
"Schedules",
"a",
"write",
"of",
"the",
"file",
"at",
"src",
"to",
"the",
"dest",
"path",
"in",
"this",
"jar",
"."
] | python | train |
welbornprod/colr | colr/colr.py | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/colr.py#L1605-L1664 | def gradient_black(
self, text=None, fore=None, back=None, style=None,
start=None, step=1, reverse=False,
linemode=True, movefactor=2, rgb_mode=False):
""" Return a black and white gradient.
Arguments:
text : String to colorize.
This will always be greater than 0.
fore : Foreground color, background will be gradient.
back : Background color, foreground will be gradient.
style : Name of style to use for the gradient.
start : Starting 256-color number.
The `start` will be adjusted if it is not within
bounds.
This will always be > 15.
This will be adjusted to fit within a 6-length
gradient, or the 24-length black/white gradient.
step : Number of characters to colorize per color.
This allows a "wider" gradient.
linemode : Colorize each line in the input.
Default: True
movefactor : Factor for offset increase on each line when
using linemode.
Minimum value: 0
Default: 2
rgb_mode : Use true color (rgb) method and codes.
"""
gradargs = {
'step': step,
'fore': fore,
'back': back,
'style': style,
'reverse': reverse,
'rgb_mode': rgb_mode,
}
if linemode:
gradargs['movefactor'] = 2 if movefactor is None else movefactor
method = self._gradient_black_lines
else:
method = self._gradient_black_line
if text:
return self.__class__(
''.join((
self.data or '',
method(
text,
start or (255 if reverse else 232),
**gradargs)
))
)
# Operating on self.data.
return self.__class__(
method(
self.stripped(),
start or (255 if reverse else 232),
**gradargs)
) | [
"def",
"gradient_black",
"(",
"self",
",",
"text",
"=",
"None",
",",
"fore",
"=",
"None",
",",
"back",
"=",
"None",
",",
"style",
"=",
"None",
",",
"start",
"=",
"None",
",",
"step",
"=",
"1",
",",
"reverse",
"=",
"False",
",",
"linemode",
"=",
"... | Return a black and white gradient.
Arguments:
text : String to colorize.
This will always be greater than 0.
fore : Foreground color, background will be gradient.
back : Background color, foreground will be gradient.
style : Name of style to use for the gradient.
start : Starting 256-color number.
The `start` will be adjusted if it is not within
bounds.
This will always be > 15.
This will be adjusted to fit within a 6-length
gradient, or the 24-length black/white gradient.
step : Number of characters to colorize per color.
This allows a "wider" gradient.
linemode : Colorize each line in the input.
Default: True
movefactor : Factor for offset increase on each line when
using linemode.
Minimum value: 0
Default: 2
rgb_mode : Use true color (rgb) method and codes. | [
"Return",
"a",
"black",
"and",
"white",
"gradient",
".",
"Arguments",
":",
"text",
":",
"String",
"to",
"colorize",
".",
"This",
"will",
"always",
"be",
"greater",
"than",
"0",
".",
"fore",
":",
"Foreground",
"color",
"background",
"will",
"be",
"gradient"... | python | train |
sdispater/orator | orator/orm/relations/has_one_or_many.py | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/has_one_or_many.py#L297-L312 | def update(self, _attributes=None, **attributes):
"""
Perform an update on all the related models.
:param attributes: The attributes
:type attributes: dict
:rtype: int
"""
if _attributes is not None:
attributes.update(_attributes)
if self._related.uses_timestamps():
attributes[self.get_related_updated_at()] = self._related.fresh_timestamp()
return self._query.update(attributes) | [
"def",
"update",
"(",
"self",
",",
"_attributes",
"=",
"None",
",",
"*",
"*",
"attributes",
")",
":",
"if",
"_attributes",
"is",
"not",
"None",
":",
"attributes",
".",
"update",
"(",
"_attributes",
")",
"if",
"self",
".",
"_related",
".",
"uses_timestamp... | Perform an update on all the related models.
:param attributes: The attributes
:type attributes: dict
:rtype: int | [
"Perform",
"an",
"update",
"on",
"all",
"the",
"related",
"models",
"."
] | python | train |
quantopian/zipline | zipline/data/loader.py | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/loader.py#L78-L87 | def has_data_for_dates(series_or_df, first_date, last_date):
"""
Does `series_or_df` have data on or before first_date and on or after
last_date?
"""
dts = series_or_df.index
if not isinstance(dts, pd.DatetimeIndex):
raise TypeError("Expected a DatetimeIndex, but got %s." % type(dts))
first, last = dts[[0, -1]]
return (first <= first_date) and (last >= last_date) | [
"def",
"has_data_for_dates",
"(",
"series_or_df",
",",
"first_date",
",",
"last_date",
")",
":",
"dts",
"=",
"series_or_df",
".",
"index",
"if",
"not",
"isinstance",
"(",
"dts",
",",
"pd",
".",
"DatetimeIndex",
")",
":",
"raise",
"TypeError",
"(",
"\"Expecte... | Does `series_or_df` have data on or before first_date and on or after
last_date? | [
"Does",
"series_or_df",
"have",
"data",
"on",
"or",
"before",
"first_date",
"and",
"on",
"or",
"after",
"last_date?"
] | python | train |
pystorm/pystorm | pystorm/spout.py | https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/spout.py#L183-L206 | def emit(
self, tup, tup_id=None, stream=None, direct_task=None, need_task_ids=False
):
"""Emit a spout Tuple & add metadata about it to `unacked_tuples`.
In order for this to work, `tup_id` is a required parameter.
See :meth:`Bolt.emit`.
"""
if tup_id is None:
raise ValueError(
"You must provide a tuple ID when emitting with a "
"ReliableSpout in order for the tuple to be "
"tracked."
)
args = (tup, stream, direct_task, need_task_ids)
self.unacked_tuples[tup_id] = args
return super(ReliableSpout, self).emit(
tup,
tup_id=tup_id,
stream=stream,
direct_task=direct_task,
need_task_ids=need_task_ids,
) | [
"def",
"emit",
"(",
"self",
",",
"tup",
",",
"tup_id",
"=",
"None",
",",
"stream",
"=",
"None",
",",
"direct_task",
"=",
"None",
",",
"need_task_ids",
"=",
"False",
")",
":",
"if",
"tup_id",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"You must pr... | Emit a spout Tuple & add metadata about it to `unacked_tuples`.
In order for this to work, `tup_id` is a required parameter.
See :meth:`Bolt.emit`. | [
"Emit",
"a",
"spout",
"Tuple",
"&",
"add",
"metadata",
"about",
"it",
"to",
"unacked_tuples",
"."
] | python | train |
jcrist/skein | skein/objects.py | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/objects.py#L247-L250 | def to_yaml(self, skip_nulls=True):
"""Convert object to a yaml string"""
return yaml.safe_dump(self.to_dict(skip_nulls=skip_nulls),
default_flow_style=False) | [
"def",
"to_yaml",
"(",
"self",
",",
"skip_nulls",
"=",
"True",
")",
":",
"return",
"yaml",
".",
"safe_dump",
"(",
"self",
".",
"to_dict",
"(",
"skip_nulls",
"=",
"skip_nulls",
")",
",",
"default_flow_style",
"=",
"False",
")"
] | Convert object to a yaml string | [
"Convert",
"object",
"to",
"a",
"yaml",
"string"
] | python | train |
ejeschke/ginga | ginga/gtkw/ImageViewGtk.py | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/gtkw/ImageViewGtk.py#L83-L91 | def save_plain_image_as_file(self, filepath, format='png', quality=90):
"""Used for generating thumbnails. Does not include overlaid
graphics.
"""
pixbuf = self.get_plain_image_as_pixbuf()
options = {}
if format == 'jpeg':
options['quality'] = str(quality)
pixbuf.save(filepath, format, options) | [
"def",
"save_plain_image_as_file",
"(",
"self",
",",
"filepath",
",",
"format",
"=",
"'png'",
",",
"quality",
"=",
"90",
")",
":",
"pixbuf",
"=",
"self",
".",
"get_plain_image_as_pixbuf",
"(",
")",
"options",
"=",
"{",
"}",
"if",
"format",
"==",
"'jpeg'",
... | Used for generating thumbnails. Does not include overlaid
graphics. | [
"Used",
"for",
"generating",
"thumbnails",
".",
"Does",
"not",
"include",
"overlaid",
"graphics",
"."
] | python | train |
iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/sensor_log.py#L104-L119 | def clear_to_reset(self, config_vars):
"""Clear all volatile information across a reset."""
self._logger.info("Config vars in sensor log reset: %s", config_vars)
super(SensorLogSubsystem, self).clear_to_reset(config_vars)
self.storage.destroy_all_walkers()
self.dump_walker = None
if config_vars.get('storage_fillstop', False):
self._logger.debug("Marking storage log fill/stop")
self.storage.set_rollover('storage', False)
if config_vars.get('streaming_fillstop', False):
self._logger.debug("Marking streaming log fill/stop")
self.storage.set_rollover('streaming', False) | [
"def",
"clear_to_reset",
"(",
"self",
",",
"config_vars",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"\"Config vars in sensor log reset: %s\"",
",",
"config_vars",
")",
"super",
"(",
"SensorLogSubsystem",
",",
"self",
")",
".",
"clear_to_reset",
"(",
"c... | Clear all volatile information across a reset. | [
"Clear",
"all",
"volatile",
"information",
"across",
"a",
"reset",
"."
] | python | train |
nlppln/nlppln | nlppln/commands/frog_to_saf.py | https://github.com/nlppln/nlppln/blob/1155191921289a65ba2becd2bf8dfabb48eaf1f1/nlppln/commands/frog_to_saf.py#L53-L59 | def _add_pos1(token):
"""
Adds a 'pos1' element to a frog token.
"""
result = token.copy()
result['pos1'] = _POSMAP[token['pos'].split("(")[0]]
return result | [
"def",
"_add_pos1",
"(",
"token",
")",
":",
"result",
"=",
"token",
".",
"copy",
"(",
")",
"result",
"[",
"'pos1'",
"]",
"=",
"_POSMAP",
"[",
"token",
"[",
"'pos'",
"]",
".",
"split",
"(",
"\"(\"",
")",
"[",
"0",
"]",
"]",
"return",
"result"
] | Adds a 'pos1' element to a frog token. | [
"Adds",
"a",
"pos1",
"element",
"to",
"a",
"frog",
"token",
"."
] | python | train |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cluster_info/display.py | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/display.py#L190-L254 | def display_leader_imbalance(cluster_topologies):
"""Display leader count and weight imbalance statistics.
:param cluster_topologies: A dictionary mapping a string name to a
ClusterTopology object.
"""
broker_ids = list(next(six.itervalues(cluster_topologies)).brokers.keys())
assert all(
set(broker_ids) == set(cluster_topology.brokers.keys())
for cluster_topology in six.itervalues(cluster_topologies)
)
broker_leader_counts = [
stats.get_broker_leader_counts(
cluster_topology.brokers[broker_id]
for broker_id in broker_ids
)
for cluster_topology in six.itervalues(cluster_topologies)
]
broker_leader_weights = [
stats.get_broker_leader_weights(
cluster_topology.brokers[broker_id]
for broker_id in broker_ids
)
for cluster_topology in six.itervalues(cluster_topologies)
]
_display_table_title_multicolumn(
'Leader Count',
'Brokers',
broker_ids,
list(cluster_topologies.keys()),
broker_leader_counts,
)
print('')
_display_table_title_multicolumn(
'Leader weight',
'Brokers',
broker_ids,
list(cluster_topologies.keys()),
broker_leader_weights,
)
for name, blc, blw in zip(
list(cluster_topologies.keys()),
broker_leader_counts,
broker_leader_weights
):
print(
'\n'
'{name}'
'Leader count imbalance: {net_imbalance}\n'
'Broker leader weight mean: {weight_mean}\n'
'Broker leader weight stdev: {weight_stdev}\n'
'Broker leader weight cv: {weight_cv}'
.format(
name='' if len(cluster_topologies) == 1 else name + '\n',
net_imbalance=stats.get_net_imbalance(blc),
weight_mean=stats.mean(blw),
weight_stdev=stats.stdevp(blw),
weight_cv=stats.coefficient_of_variation(blw),
)
) | [
"def",
"display_leader_imbalance",
"(",
"cluster_topologies",
")",
":",
"broker_ids",
"=",
"list",
"(",
"next",
"(",
"six",
".",
"itervalues",
"(",
"cluster_topologies",
")",
")",
".",
"brokers",
".",
"keys",
"(",
")",
")",
"assert",
"all",
"(",
"set",
"("... | Display leader count and weight imbalance statistics.
:param cluster_topologies: A dictionary mapping a string name to a
ClusterTopology object. | [
"Display",
"leader",
"count",
"and",
"weight",
"imbalance",
"statistics",
"."
] | python | train |
PyCQA/pylint | pylint/lint.py | https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/lint.py#L898-L905 | def get_checkers(self):
"""return all available checkers as a list"""
return [self] + [
c
for _checkers in self._checkers.values()
for c in _checkers
if c is not self
] | [
"def",
"get_checkers",
"(",
"self",
")",
":",
"return",
"[",
"self",
"]",
"+",
"[",
"c",
"for",
"_checkers",
"in",
"self",
".",
"_checkers",
".",
"values",
"(",
")",
"for",
"c",
"in",
"_checkers",
"if",
"c",
"is",
"not",
"self",
"]"
] | return all available checkers as a list | [
"return",
"all",
"available",
"checkers",
"as",
"a",
"list"
] | python | test |
DarkEnergySurvey/ugali | ugali/isochrone/model.py | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/model.py#L1158-L1203 | def download(self,age=None,metallicity=None,outdir=None,force=False):
"""
Check valid parameter range and download isochrones from:
http://stev.oapd.inaf.it/cgi-bin/cmd
"""
try:
from urllib.error import URLError
except ImportError:
from urllib2 import URLError
if age is None: age = float(self.age)
if metallicity is None: metallicity = float(self.metallicity)
if outdir is None: outdir = './'
basename = self.params2filename(age,metallicity)
outfile = os.path.join(outdir,basename)
if os.path.exists(outfile) and not force:
try:
self.verify(outfile,self.survey,age,metallicity)
logger.info("Found %s; skipping..."%(outfile))
return
except Exception as e:
msg = "Overwriting corrupted %s..."%(outfile)
logger.warn(msg)
os.remove(outfile)
mkdir(outdir)
self.print_info(age,metallicity)
self.query_server(outfile,age,metallicity)
if not os.path.exists(outfile):
raise RuntimeError('Download failed')
try:
self.verify(outfile,self.survey,age,metallicity)
except Exception as e:
msg = "Output file is corrupted."
logger.error(msg)
msg = "Removing %s."%outfile
logger.info(msg)
os.remove(outfile)
raise(e)
return outfile | [
"def",
"download",
"(",
"self",
",",
"age",
"=",
"None",
",",
"metallicity",
"=",
"None",
",",
"outdir",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"try",
":",
"from",
"urllib",
".",
"error",
"import",
"URLError",
"except",
"ImportError",
":",
... | Check valid parameter range and download isochrones from:
http://stev.oapd.inaf.it/cgi-bin/cmd | [
"Check",
"valid",
"parameter",
"range",
"and",
"download",
"isochrones",
"from",
":",
"http",
":",
"//",
"stev",
".",
"oapd",
".",
"inaf",
".",
"it",
"/",
"cgi",
"-",
"bin",
"/",
"cmd"
] | python | train |
awslabs/serverless-application-model | samtranslator/translator/translator.py | https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/translator/translator.py#L34-L122 | def translate(self, sam_template, parameter_values):
"""Loads the SAM resources from the given SAM manifest, replaces them with their corresponding
CloudFormation resources, and returns the resulting CloudFormation template.
:param dict sam_template: the SAM manifest, as loaded by json.load() or yaml.load(), or as provided by \
CloudFormation transforms.
:param dict parameter_values: Map of template parameter names to their values. It is a required parameter that
should at least be an empty map. By providing an empty map, the caller explicitly opts-into the idea
that some functionality that relies on resolving parameter references might not work as expected
(ex: auto-creating new Lambda Version when CodeUri contains reference to template parameter). This is
why this parameter is required
:returns: a copy of the template with SAM resources replaced with the corresponding CloudFormation, which may \
be dumped into a valid CloudFormation JSON or YAML template
"""
sam_parameter_values = SamParameterValues(parameter_values)
sam_parameter_values.add_default_parameter_values(sam_template)
sam_parameter_values.add_pseudo_parameter_values()
parameter_values = sam_parameter_values.parameter_values
# Create & Install plugins
sam_plugins = prepare_plugins(self.plugins, parameter_values)
self.sam_parser.parse(
sam_template=sam_template,
parameter_values=parameter_values,
sam_plugins=sam_plugins
)
template = copy.deepcopy(sam_template)
macro_resolver = ResourceTypeResolver(sam_resources)
intrinsics_resolver = IntrinsicsResolver(parameter_values)
deployment_preference_collection = DeploymentPreferenceCollection()
supported_resource_refs = SupportedResourceReferences()
document_errors = []
changed_logical_ids = {}
for logical_id, resource_dict in self._get_resources_to_iterate(sam_template, macro_resolver):
try:
macro = macro_resolver\
.resolve_resource_type(resource_dict)\
.from_dict(logical_id, resource_dict, sam_plugins=sam_plugins)
kwargs = macro.resources_to_link(sam_template['Resources'])
kwargs['managed_policy_map'] = self.managed_policy_map
kwargs['intrinsics_resolver'] = intrinsics_resolver
kwargs['deployment_preference_collection'] = deployment_preference_collection
translated = macro.to_cloudformation(**kwargs)
supported_resource_refs = macro.get_resource_references(translated, supported_resource_refs)
# Some resources mutate their logical ids. Track those to change all references to them:
if logical_id != macro.logical_id:
changed_logical_ids[logical_id] = macro.logical_id
del template['Resources'][logical_id]
for resource in translated:
if verify_unique_logical_id(resource, sam_template['Resources']):
template['Resources'].update(resource.to_dict())
else:
document_errors.append(DuplicateLogicalIdException(
logical_id, resource.logical_id, resource.resource_type))
except (InvalidResourceException, InvalidEventException) as e:
document_errors.append(e)
if deployment_preference_collection.any_enabled():
template['Resources'].update(deployment_preference_collection.codedeploy_application.to_dict())
if not deployment_preference_collection.can_skip_service_role():
template['Resources'].update(deployment_preference_collection.codedeploy_iam_role.to_dict())
for logical_id in deployment_preference_collection.enabled_logical_ids():
template['Resources'].update(deployment_preference_collection.deployment_group(logical_id).to_dict())
# Run the after-transform plugin target
try:
sam_plugins.act(LifeCycleEvents.after_transform_template, template)
except (InvalidDocumentException, InvalidResourceException) as e:
document_errors.append(e)
# Cleanup
if 'Transform' in template:
del template['Transform']
if len(document_errors) == 0:
template = intrinsics_resolver.resolve_sam_resource_id_refs(template, changed_logical_ids)
template = intrinsics_resolver.resolve_sam_resource_refs(template, supported_resource_refs)
return template
else:
raise InvalidDocumentException(document_errors) | [
"def",
"translate",
"(",
"self",
",",
"sam_template",
",",
"parameter_values",
")",
":",
"sam_parameter_values",
"=",
"SamParameterValues",
"(",
"parameter_values",
")",
"sam_parameter_values",
".",
"add_default_parameter_values",
"(",
"sam_template",
")",
"sam_parameter_... | Loads the SAM resources from the given SAM manifest, replaces them with their corresponding
CloudFormation resources, and returns the resulting CloudFormation template.
:param dict sam_template: the SAM manifest, as loaded by json.load() or yaml.load(), or as provided by \
CloudFormation transforms.
:param dict parameter_values: Map of template parameter names to their values. It is a required parameter that
should at least be an empty map. By providing an empty map, the caller explicitly opts-into the idea
that some functionality that relies on resolving parameter references might not work as expected
(ex: auto-creating new Lambda Version when CodeUri contains reference to template parameter). This is
why this parameter is required
:returns: a copy of the template with SAM resources replaced with the corresponding CloudFormation, which may \
be dumped into a valid CloudFormation JSON or YAML template | [
"Loads",
"the",
"SAM",
"resources",
"from",
"the",
"given",
"SAM",
"manifest",
"replaces",
"them",
"with",
"their",
"corresponding",
"CloudFormation",
"resources",
"and",
"returns",
"the",
"resulting",
"CloudFormation",
"template",
"."
] | python | train |
idlesign/django-siteprefs | siteprefs/toolbox.py | https://github.com/idlesign/django-siteprefs/blob/3d6bf5e64220fe921468a36fce68e15d7947cf92/siteprefs/toolbox.py#L249-L279 | def register_prefs(*args, **kwargs):
"""Registers preferences that should be handled by siteprefs.
Expects preferences as *args.
Use keyword arguments to batch apply params supported by
``PrefProxy`` to all preferences not constructed by ``pref`` and ``pref_group``.
Batch kwargs:
:param str|unicode help_text: Field help text.
:param bool static: Leave this preference static (do not store in DB).
:param bool readonly: Make this field read only.
:param bool swap_settings_module: Whether to automatically replace settings module
with a special ``ProxyModule`` object to access dynamic values of settings
transparently (so not to bother with calling ``.value`` of ``PrefProxy`` object).
"""
swap_settings_module = bool(kwargs.get('swap_settings_module', True))
if __PATCHED_LOCALS_SENTINEL not in get_frame_locals(2):
raise SitePrefsException('Please call `patch_locals()` right before the `register_prefs()`.')
bind_proxy(args, **kwargs)
unpatch_locals()
swap_settings_module and proxy_settings_module() | [
"def",
"register_prefs",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"swap_settings_module",
"=",
"bool",
"(",
"kwargs",
".",
"get",
"(",
"'swap_settings_module'",
",",
"True",
")",
")",
"if",
"__PATCHED_LOCALS_SENTINEL",
"not",
"in",
"get_frame_local... | Registers preferences that should be handled by siteprefs.
Expects preferences as *args.
Use keyword arguments to batch apply params supported by
``PrefProxy`` to all preferences not constructed by ``pref`` and ``pref_group``.
Batch kwargs:
:param str|unicode help_text: Field help text.
:param bool static: Leave this preference static (do not store in DB).
:param bool readonly: Make this field read only.
:param bool swap_settings_module: Whether to automatically replace settings module
with a special ``ProxyModule`` object to access dynamic values of settings
transparently (so not to bother with calling ``.value`` of ``PrefProxy`` object). | [
"Registers",
"preferences",
"that",
"should",
"be",
"handled",
"by",
"siteprefs",
"."
] | python | valid |
boriel/zxbasic | zxbasmpplex.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbasmpplex.py#L295-L298 | def put_current_line(self, prefix=''):
""" Returns line and file for include / end of include sequences.
"""
return '%s#line %i "%s"\n' % (prefix, self.lex.lineno, os.path.basename(self.filestack[-1][0])) | [
"def",
"put_current_line",
"(",
"self",
",",
"prefix",
"=",
"''",
")",
":",
"return",
"'%s#line %i \"%s\"\\n'",
"%",
"(",
"prefix",
",",
"self",
".",
"lex",
".",
"lineno",
",",
"os",
".",
"path",
".",
"basename",
"(",
"self",
".",
"filestack",
"[",
"-"... | Returns line and file for include / end of include sequences. | [
"Returns",
"line",
"and",
"file",
"for",
"include",
"/",
"end",
"of",
"include",
"sequences",
"."
] | python | train |
evandempsey/fp-growth | pyfpgrowth/pyfpgrowth.py | https://github.com/evandempsey/fp-growth/blob/6bf4503024e86c5bbea8a05560594f2f7f061c15/pyfpgrowth/pyfpgrowth.py#L135-L146 | def tree_has_single_path(self, node):
"""
If there is a single path in the tree,
return True, else return False.
"""
num_children = len(node.children)
if num_children > 1:
return False
elif num_children == 0:
return True
else:
return True and self.tree_has_single_path(node.children[0]) | [
"def",
"tree_has_single_path",
"(",
"self",
",",
"node",
")",
":",
"num_children",
"=",
"len",
"(",
"node",
".",
"children",
")",
"if",
"num_children",
">",
"1",
":",
"return",
"False",
"elif",
"num_children",
"==",
"0",
":",
"return",
"True",
"else",
":... | If there is a single path in the tree,
return True, else return False. | [
"If",
"there",
"is",
"a",
"single",
"path",
"in",
"the",
"tree",
"return",
"True",
"else",
"return",
"False",
"."
] | python | train |
pandas-dev/pandas | pandas/core/groupby/groupby.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/groupby.py#L1474-L1505 | def _fill(self, direction, limit=None):
"""
Shared function for `pad` and `backfill` to call Cython method.
Parameters
----------
direction : {'ffill', 'bfill'}
Direction passed to underlying Cython function. `bfill` will cause
values to be filled backwards. `ffill` and any other values will
default to a forward fill
limit : int, default None
Maximum number of consecutive values to fill. If `None`, this
method will convert to -1 prior to passing to Cython
Returns
-------
`Series` or `DataFrame` with filled values
See Also
--------
pad
backfill
"""
# Need int value for Cython
if limit is None:
limit = -1
return self._get_cythonized_result('group_fillna_indexer',
self.grouper, needs_mask=True,
cython_dtype=np.int64,
result_is_index=True,
direction=direction, limit=limit) | [
"def",
"_fill",
"(",
"self",
",",
"direction",
",",
"limit",
"=",
"None",
")",
":",
"# Need int value for Cython",
"if",
"limit",
"is",
"None",
":",
"limit",
"=",
"-",
"1",
"return",
"self",
".",
"_get_cythonized_result",
"(",
"'group_fillna_indexer'",
",",
... | Shared function for `pad` and `backfill` to call Cython method.
Parameters
----------
direction : {'ffill', 'bfill'}
Direction passed to underlying Cython function. `bfill` will cause
values to be filled backwards. `ffill` and any other values will
default to a forward fill
limit : int, default None
Maximum number of consecutive values to fill. If `None`, this
method will convert to -1 prior to passing to Cython
Returns
-------
`Series` or `DataFrame` with filled values
See Also
--------
pad
backfill | [
"Shared",
"function",
"for",
"pad",
"and",
"backfill",
"to",
"call",
"Cython",
"method",
"."
] | python | train |
saltstack/salt | salt/modules/jenkinsmod.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jenkinsmod.py#L222-L251 | def build_job(name=None, parameters=None):
'''
Initiate a build for the provided job.
:param name: The name of the job is check if it exists.
:param parameters: Parameters to send to the job.
:return: True is successful, otherwise raise an exception.
CLI Example:
.. code-block:: bash
salt '*' jenkins.build_job jobname
'''
if not name:
raise SaltInvocationError('Required parameter \'name\' is missing')
server = _connect()
if not job_exists(name):
raise CommandExecutionError('Job \'{0}\' does not exist.'.format(name))
try:
server.build_job(name, parameters)
except jenkins.JenkinsException as err:
raise CommandExecutionError(
'Encountered error building job \'{0}\': {1}'.format(name, err)
)
return True | [
"def",
"build_job",
"(",
"name",
"=",
"None",
",",
"parameters",
"=",
"None",
")",
":",
"if",
"not",
"name",
":",
"raise",
"SaltInvocationError",
"(",
"'Required parameter \\'name\\' is missing'",
")",
"server",
"=",
"_connect",
"(",
")",
"if",
"not",
"job_exi... | Initiate a build for the provided job.
:param name: The name of the job is check if it exists.
:param parameters: Parameters to send to the job.
:return: True is successful, otherwise raise an exception.
CLI Example:
.. code-block:: bash
salt '*' jenkins.build_job jobname | [
"Initiate",
"a",
"build",
"for",
"the",
"provided",
"job",
"."
] | python | train |
pybel/pybel | src/pybel/manager/models.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/models.py#L166-L184 | def to_json(self, include_id: bool = False) -> Mapping[str, str]:
"""Describe the namespaceEntry as dictionary of Namespace-Keyword and Name.
:param include_id: If true, includes the model identifier
"""
result = {
NAMESPACE: self.namespace.keyword,
}
if self.name:
result[NAME] = self.name
if self.identifier:
result[IDENTIFIER] = self.identifier
if include_id:
result['id'] = self.id
return result | [
"def",
"to_json",
"(",
"self",
",",
"include_id",
":",
"bool",
"=",
"False",
")",
"->",
"Mapping",
"[",
"str",
",",
"str",
"]",
":",
"result",
"=",
"{",
"NAMESPACE",
":",
"self",
".",
"namespace",
".",
"keyword",
",",
"}",
"if",
"self",
".",
"name"... | Describe the namespaceEntry as dictionary of Namespace-Keyword and Name.
:param include_id: If true, includes the model identifier | [
"Describe",
"the",
"namespaceEntry",
"as",
"dictionary",
"of",
"Namespace",
"-",
"Keyword",
"and",
"Name",
".",
":",
"param",
"include_id",
":",
"If",
"true",
"includes",
"the",
"model",
"identifier"
] | python | train |
manns/pyspread | pyspread/src/lib/vlc.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/lib/vlc.py#L2727-L2740 | def set_mrl(self, mrl, *options):
"""Set the MRL to play.
Warning: most audio and video options, such as text renderer,
have no effects on an individual media. These options must be
set at the vlc.Instance or vlc.MediaPlayer instanciation.
@param mrl: The MRL
@param options: optional media option=value strings
@return: the Media object
"""
m = self.get_instance().media_new(mrl, *options)
self.set_media(m)
return m | [
"def",
"set_mrl",
"(",
"self",
",",
"mrl",
",",
"*",
"options",
")",
":",
"m",
"=",
"self",
".",
"get_instance",
"(",
")",
".",
"media_new",
"(",
"mrl",
",",
"*",
"options",
")",
"self",
".",
"set_media",
"(",
"m",
")",
"return",
"m"
] | Set the MRL to play.
Warning: most audio and video options, such as text renderer,
have no effects on an individual media. These options must be
set at the vlc.Instance or vlc.MediaPlayer instanciation.
@param mrl: The MRL
@param options: optional media option=value strings
@return: the Media object | [
"Set",
"the",
"MRL",
"to",
"play",
"."
] | python | train |
ArangoDB-Community/pyArango | pyArango/document.py | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/document.py#L214-L224 | def setPrivates(self, fieldDict) :
"""will set self._id, self._rev and self._key field."""
for priv in self.privates :
if priv in fieldDict :
setattr(self, priv, fieldDict[priv])
else :
setattr(self, priv, None)
if self._id is not None :
self.URL = "%s/%s" % (self.documentsURL, self._id) | [
"def",
"setPrivates",
"(",
"self",
",",
"fieldDict",
")",
":",
"for",
"priv",
"in",
"self",
".",
"privates",
":",
"if",
"priv",
"in",
"fieldDict",
":",
"setattr",
"(",
"self",
",",
"priv",
",",
"fieldDict",
"[",
"priv",
"]",
")",
"else",
":",
"setatt... | will set self._id, self._rev and self._key field. | [
"will",
"set",
"self",
".",
"_id",
"self",
".",
"_rev",
"and",
"self",
".",
"_key",
"field",
"."
] | python | train |
eqcorrscan/EQcorrscan | eqcorrscan/utils/catalog_utils.py | https://github.com/eqcorrscan/EQcorrscan/blob/3121b4aca801ee5d38f56ca297ce1c0f9515d9ff/eqcorrscan/utils/catalog_utils.py#L166-L209 | def spatial_clip(catalog, corners, mindepth=None, maxdepth=None):
"""
Clip the catalog to a spatial box, can be irregular.
Can only be irregular in 2D, depth must be between bounds.
:type catalog: :class:`obspy.core.catalog.Catalog`
:param catalog: Catalog to clip.
:type corners: :class:`matplotlib.path.Path`
:param corners: Corners to clip the catalog to
:type mindepth: float
:param mindepth: Minimum depth for earthquakes in km.
:type maxdepth: float
:param maxdepth: Maximum depth for earthquakes in km.
.. Note::
Corners is expected to be a :class:`matplotlib.path.Path` in the form
of tuples of (lat, lon) in decimal degrees.
"""
cat_out = catalog.copy()
if mindepth is not None:
for event in cat_out:
try:
origin = _get_origin(event)
except IOError:
continue
if origin.depth < mindepth * 1000:
cat_out.events.remove(event)
if maxdepth is not None:
for event in cat_out:
try:
origin = _get_origin(event)
except IOError:
continue
if origin.depth > maxdepth * 1000:
cat_out.events.remove(event)
for event in cat_out:
try:
origin = _get_origin(event)
except IOError:
continue
if not corners.contains_point((origin.latitude, origin.longitude)):
cat_out.events.remove(event)
return cat_out | [
"def",
"spatial_clip",
"(",
"catalog",
",",
"corners",
",",
"mindepth",
"=",
"None",
",",
"maxdepth",
"=",
"None",
")",
":",
"cat_out",
"=",
"catalog",
".",
"copy",
"(",
")",
"if",
"mindepth",
"is",
"not",
"None",
":",
"for",
"event",
"in",
"cat_out",
... | Clip the catalog to a spatial box, can be irregular.
Can only be irregular in 2D, depth must be between bounds.
:type catalog: :class:`obspy.core.catalog.Catalog`
:param catalog: Catalog to clip.
:type corners: :class:`matplotlib.path.Path`
:param corners: Corners to clip the catalog to
:type mindepth: float
:param mindepth: Minimum depth for earthquakes in km.
:type maxdepth: float
:param maxdepth: Maximum depth for earthquakes in km.
.. Note::
Corners is expected to be a :class:`matplotlib.path.Path` in the form
of tuples of (lat, lon) in decimal degrees. | [
"Clip",
"the",
"catalog",
"to",
"a",
"spatial",
"box",
"can",
"be",
"irregular",
"."
] | python | train |
trevisanj/a99 | a99/config.py | https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/config.py#L87-L94 | def get_config_obj(filename):
"""Reads/creates filename at user **home** folder and returns a AAConfigObj object"""
if not filename.startswith("."):
a99.get_python_logger().warning("Configuration filename '{}' does not start with a '.'".format(filename))
path_ = os.path.join(os.path.expanduser("~"), filename)
return AAConfigObj(path_, encoding="UTF8") | [
"def",
"get_config_obj",
"(",
"filename",
")",
":",
"if",
"not",
"filename",
".",
"startswith",
"(",
"\".\"",
")",
":",
"a99",
".",
"get_python_logger",
"(",
")",
".",
"warning",
"(",
"\"Configuration filename '{}' does not start with a '.'\"",
".",
"format",
"(",... | Reads/creates filename at user **home** folder and returns a AAConfigObj object | [
"Reads",
"/",
"creates",
"filename",
"at",
"user",
"**",
"home",
"**",
"folder",
"and",
"returns",
"a",
"AAConfigObj",
"object"
] | python | train |
biocore/burrito-fillings | bfillings/usearch.py | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/usearch.py#L991-L1036 | def get_fasta_from_uc_file(fasta_filepath,
uc_filepath,
hit_type="H",
output_fna_filepath=None,
label_prefix="",
output_dir=None):
""" writes fasta of sequences from uc file of type hit_type
fasta_filepath: Filepath of original query fasta file
uc_filepath: Filepath of .uc file created by usearch post error filtering
hit_type: type to read from first field of .uc file, "H" for hits, "N" for
no hits.
output_fna_filepath = fasta output filepath
label_prefix = Added before each fasta label, important when doing ref
based OTU picking plus de novo clustering to preserve label matching.
output_dir: output directory
"""
hit_type_index = 0
seq_label_index = 8
target_label_index = 9
labels_hits = {}
labels_to_keep = []
for line in open(uc_filepath, "U"):
if line.startswith("#") or len(line.strip()) == 0:
continue
curr_line = line.split('\t')
if curr_line[0] == hit_type:
labels_hits[curr_line[seq_label_index]] =\
curr_line[target_label_index].strip()
labels_to_keep.append(curr_line[seq_label_index])
labels_to_keep = set(labels_to_keep)
out_fna = open(output_fna_filepath, "w")
for label, seq in parse_fasta(open(fasta_filepath, "U")):
if label in labels_to_keep:
if hit_type == "H":
out_fna.write(">" + labels_hits[label] + "\n%s\n" % seq)
if hit_type == "N":
out_fna.write(">" + label + "\n%s\n" % seq)
return output_fna_filepath, labels_hits | [
"def",
"get_fasta_from_uc_file",
"(",
"fasta_filepath",
",",
"uc_filepath",
",",
"hit_type",
"=",
"\"H\"",
",",
"output_fna_filepath",
"=",
"None",
",",
"label_prefix",
"=",
"\"\"",
",",
"output_dir",
"=",
"None",
")",
":",
"hit_type_index",
"=",
"0",
"seq_label... | writes fasta of sequences from uc file of type hit_type
fasta_filepath: Filepath of original query fasta file
uc_filepath: Filepath of .uc file created by usearch post error filtering
hit_type: type to read from first field of .uc file, "H" for hits, "N" for
no hits.
output_fna_filepath = fasta output filepath
label_prefix = Added before each fasta label, important when doing ref
based OTU picking plus de novo clustering to preserve label matching.
output_dir: output directory | [
"writes",
"fasta",
"of",
"sequences",
"from",
"uc",
"file",
"of",
"type",
"hit_type"
] | python | train |
zhanglab/psamm | psamm/lpsolver/lp.py | https://github.com/zhanglab/psamm/blob/dc427848c4f9d109ca590f0afa024c63b685b3f4/psamm/lpsolver/lp.py#L605-L612 | def set(self, names):
"""Return a variable set of the given names in the namespace.
>>> v = prob.namespace(name='v')
>>> v.define([1, 2, 5], lower=0, upper=10)
>>> prob.add_linear_constraints(v.set([1, 2]) >= 4)
"""
return self._problem.set((self, name) for name in names) | [
"def",
"set",
"(",
"self",
",",
"names",
")",
":",
"return",
"self",
".",
"_problem",
".",
"set",
"(",
"(",
"self",
",",
"name",
")",
"for",
"name",
"in",
"names",
")"
] | Return a variable set of the given names in the namespace.
>>> v = prob.namespace(name='v')
>>> v.define([1, 2, 5], lower=0, upper=10)
>>> prob.add_linear_constraints(v.set([1, 2]) >= 4) | [
"Return",
"a",
"variable",
"set",
"of",
"the",
"given",
"names",
"in",
"the",
"namespace",
"."
] | python | train |
gwastro/pycbc | pycbc/waveform/ringdown.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/ringdown.py#L96-L116 | def lm_freqs_taus(**kwargs):
""" Take input_params and return dictionaries with frequencies and damping
times of each overtone of a specific lm mode, checking that all of them
are given.
"""
lmns = kwargs['lmns']
freqs, taus = {}, {}
for lmn in lmns:
l, m, nmodes = int(lmn[0]), int(lmn[1]), int(lmn[2])
for n in range(nmodes):
try:
freqs['%d%d%d' %(l,m,n)] = kwargs['f_%d%d%d' %(l,m,n)]
except KeyError:
raise ValueError('f_%d%d%d is required' %(l,m,n))
try:
taus['%d%d%d' %(l,m,n)] = kwargs['tau_%d%d%d' %(l,m,n)]
except KeyError:
raise ValueError('tau_%d%d%d is required' %(l,m,n))
return freqs, taus | [
"def",
"lm_freqs_taus",
"(",
"*",
"*",
"kwargs",
")",
":",
"lmns",
"=",
"kwargs",
"[",
"'lmns'",
"]",
"freqs",
",",
"taus",
"=",
"{",
"}",
",",
"{",
"}",
"for",
"lmn",
"in",
"lmns",
":",
"l",
",",
"m",
",",
"nmodes",
"=",
"int",
"(",
"lmn",
"... | Take input_params and return dictionaries with frequencies and damping
times of each overtone of a specific lm mode, checking that all of them
are given. | [
"Take",
"input_params",
"and",
"return",
"dictionaries",
"with",
"frequencies",
"and",
"damping",
"times",
"of",
"each",
"overtone",
"of",
"a",
"specific",
"lm",
"mode",
"checking",
"that",
"all",
"of",
"them",
"are",
"given",
"."
] | python | train |
pvlib/pvlib-python | pvlib/iotools/tmy.py | https://github.com/pvlib/pvlib-python/blob/2e844a595b820b43d1170269781fa66bd0ccc8a3/pvlib/iotools/tmy.py#L273-L420 | def read_tmy2(filename):
'''
Read a TMY2 file in to a DataFrame.
Note that values contained in the DataFrame are unchanged from the
TMY2 file (i.e. units are retained). Time/Date and location data
imported from the TMY2 file have been modified to a "friendlier"
form conforming to modern conventions (e.g. N latitude is postive, E
longitude is positive, the "24th" hour of any day is technically the
"0th" hour of the next day). In the case of any discrepencies
between this documentation and the TMY2 User's Manual [1], the TMY2
User's Manual takes precedence.
Parameters
----------
filename : None or string
If None, attempts to use a Tkinter file browser. A string can be
a relative file path, absolute file path, or url.
Returns
-------
Tuple of the form (data, metadata).
data : DataFrame
A dataframe with the columns described in the table below. For a
more detailed descriptions of each component, please consult the
TMY2 User's Manual ([1]), especially tables 3-1 through 3-6, and
Appendix B.
metadata : dict
The site metadata available in the file.
Notes
-----
The returned structures have the following fields.
============= ==================================
key description
============= ==================================
WBAN Site identifier code (WBAN number)
City Station name
State Station state 2 letter designator
TZ Hours from Greenwich
latitude Latitude in decimal degrees
longitude Longitude in decimal degrees
altitude Site elevation in meters
============= ==================================
============================ ==========================================================================================================================================================================
TMYData field description
============================ ==========================================================================================================================================================================
index Pandas timeseries object containing timestamps
year
month
day
hour
ETR Extraterrestrial horizontal radiation recv'd during 60 minutes prior to timestamp, Wh/m^2
ETRN Extraterrestrial normal radiation recv'd during 60 minutes prior to timestamp, Wh/m^2
GHI Direct and diffuse horizontal radiation recv'd during 60 minutes prior to timestamp, Wh/m^2
GHISource See [1], Table 3-3
GHIUncertainty See [1], Table 3-4
DNI Amount of direct normal radiation (modeled) recv'd during 60 mintues prior to timestamp, Wh/m^2
DNISource See [1], Table 3-3
DNIUncertainty See [1], Table 3-4
DHI Amount of diffuse horizontal radiation recv'd during 60 minutes prior to timestamp, Wh/m^2
DHISource See [1], Table 3-3
DHIUncertainty See [1], Table 3-4
GHillum Avg. total horizontal illuminance recv'd during the 60 minutes prior to timestamp, units of 100 lux (e.g. value of 50 = 5000 lux)
GHillumSource See [1], Table 3-3
GHillumUncertainty See [1], Table 3-4
DNillum Avg. direct normal illuminance recv'd during the 60 minutes prior to timestamp, units of 100 lux
DNillumSource See [1], Table 3-3
DNillumUncertainty See [1], Table 3-4
DHillum Avg. horizontal diffuse illuminance recv'd during the 60 minutes prior to timestamp, units of 100 lux
DHillumSource See [1], Table 3-3
DHillumUncertainty See [1], Table 3-4
Zenithlum Avg. luminance at the sky's zenith during the 60 minutes prior to timestamp, units of 10 Cd/m^2 (e.g. value of 700 = 7,000 Cd/m^2)
ZenithlumSource See [1], Table 3-3
ZenithlumUncertainty See [1], Table 3-4
TotCld Amount of sky dome covered by clouds or obscuring phenonema at time stamp, tenths of sky
TotCldSource See [1], Table 3-5, 8760x1 cell array of strings
TotCldUnertainty See [1], Table 3-6
OpqCld Amount of sky dome covered by clouds or obscuring phenonema that prevent observing the sky at time stamp, tenths of sky
OpqCldSource See [1], Table 3-5, 8760x1 cell array of strings
OpqCldUncertainty See [1], Table 3-6
DryBulb Dry bulb temperature at the time indicated, in tenths of degree C (e.g. 352 = 35.2 C).
DryBulbSource See [1], Table 3-5, 8760x1 cell array of strings
DryBulbUncertainty See [1], Table 3-6
DewPoint Dew-point temperature at the time indicated, in tenths of degree C (e.g. 76 = 7.6 C).
DewPointSource See [1], Table 3-5, 8760x1 cell array of strings
DewPointUncertainty See [1], Table 3-6
RHum Relative humidity at the time indicated, percent
RHumSource See [1], Table 3-5, 8760x1 cell array of strings
RHumUncertainty See [1], Table 3-6
Pressure Station pressure at the time indicated, 1 mbar
PressureSource See [1], Table 3-5, 8760x1 cell array of strings
PressureUncertainty See [1], Table 3-6
Wdir Wind direction at time indicated, degrees from east of north (360 = 0 = north; 90 = East; 0 = undefined,calm)
WdirSource See [1], Table 3-5, 8760x1 cell array of strings
WdirUncertainty See [1], Table 3-6
Wspd Wind speed at the time indicated, in tenths of meters/second (e.g. 212 = 21.2 m/s)
WspdSource See [1], Table 3-5, 8760x1 cell array of strings
WspdUncertainty See [1], Table 3-6
Hvis Distance to discernable remote objects at time indicated (7777=unlimited, 9999=missing data), in tenths of kilometers (e.g. 341 = 34.1 km).
HvisSource See [1], Table 3-5, 8760x1 cell array of strings
HvisUncertainty See [1], Table 3-6
CeilHgt Height of cloud base above local terrain (7777=unlimited, 88888=cirroform, 99999=missing data), in meters
CeilHgtSource See [1], Table 3-5, 8760x1 cell array of strings
CeilHgtUncertainty See [1], Table 3-6
Pwat Total precipitable water contained in a column of unit cross section from Earth to top of atmosphere, in millimeters
PwatSource See [1], Table 3-5, 8760x1 cell array of strings
PwatUncertainty See [1], Table 3-6
AOD The broadband aerosol optical depth (broadband turbidity) in thousandths on the day indicated (e.g. 114 = 0.114)
AODSource See [1], Table 3-5, 8760x1 cell array of strings
AODUncertainty See [1], Table 3-6
SnowDepth Snow depth in centimeters on the day indicated, (999 = missing data).
SnowDepthSource See [1], Table 3-5, 8760x1 cell array of strings
SnowDepthUncertainty See [1], Table 3-6
LastSnowfall Number of days since last snowfall (maximum value of 88, where 88 = 88 or greater days; 99 = missing data)
LastSnowfallSource See [1], Table 3-5, 8760x1 cell array of strings
LastSnowfallUncertainty See [1], Table 3-6
PresentWeather See [1], Appendix B, an 8760x1 cell array of strings. Each string contains 10 numeric values. The string can be parsed to determine each of 10 observed weather metrics.
============================ ==========================================================================================================================================================================
References
----------
[1] Marion, W and Urban, K. "Wilcox, S and Marion, W. "User's Manual
for TMY2s". NREL 1995.
'''
if filename is None:
try:
filename = _interactive_load()
except ImportError:
raise ImportError('Interactive load failed. Tkinter not supported '
'on this system. Try installing X-Quartz and '
'reloading')
# paste in the column info as one long line
string = '%2d%2d%2d%2d%4d%4d%4d%1s%1d%4d%1s%1d%4d%1s%1d%4d%1s%1d%4d%1s%1d%4d%1s%1d%4d%1s%1d%2d%1s%1d%2d%1s%1d%4d%1s%1d%4d%1s%1d%3d%1s%1d%4d%1s%1d%3d%1s%1d%3d%1s%1d%4d%1s%1d%5d%1s%1d%10d%3d%1s%1d%3d%1s%1d%3d%1s%1d%2d%1s%1d' # noqa: E501
columns = 'year,month,day,hour,ETR,ETRN,GHI,GHISource,GHIUncertainty,DNI,DNISource,DNIUncertainty,DHI,DHISource,DHIUncertainty,GHillum,GHillumSource,GHillumUncertainty,DNillum,DNillumSource,DNillumUncertainty,DHillum,DHillumSource,DHillumUncertainty,Zenithlum,ZenithlumSource,ZenithlumUncertainty,TotCld,TotCldSource,TotCldUnertainty,OpqCld,OpqCldSource,OpqCldUncertainty,DryBulb,DryBulbSource,DryBulbUncertainty,DewPoint,DewPointSource,DewPointUncertainty,RHum,RHumSource,RHumUncertainty,Pressure,PressureSource,PressureUncertainty,Wdir,WdirSource,WdirUncertainty,Wspd,WspdSource,WspdUncertainty,Hvis,HvisSource,HvisUncertainty,CeilHgt,CeilHgtSource,CeilHgtUncertainty,PresentWeather,Pwat,PwatSource,PwatUncertainty,AOD,AODSource,AODUncertainty,SnowDepth,SnowDepthSource,SnowDepthUncertainty,LastSnowfall,LastSnowfallSource,LastSnowfallUncertaint' # noqa: E501
hdr_columns = 'WBAN,City,State,TZ,latitude,longitude,altitude'
tmy2, tmy2_meta = _read_tmy2(string, columns, hdr_columns, filename)
return tmy2, tmy2_meta | [
"def",
"read_tmy2",
"(",
"filename",
")",
":",
"if",
"filename",
"is",
"None",
":",
"try",
":",
"filename",
"=",
"_interactive_load",
"(",
")",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"'Interactive load failed. Tkinter not supported '",
"'on this ... | Read a TMY2 file in to a DataFrame.
Note that values contained in the DataFrame are unchanged from the
TMY2 file (i.e. units are retained). Time/Date and location data
imported from the TMY2 file have been modified to a "friendlier"
form conforming to modern conventions (e.g. N latitude is postive, E
longitude is positive, the "24th" hour of any day is technically the
"0th" hour of the next day). In the case of any discrepencies
between this documentation and the TMY2 User's Manual [1], the TMY2
User's Manual takes precedence.
Parameters
----------
filename : None or string
If None, attempts to use a Tkinter file browser. A string can be
a relative file path, absolute file path, or url.
Returns
-------
Tuple of the form (data, metadata).
data : DataFrame
A dataframe with the columns described in the table below. For a
more detailed descriptions of each component, please consult the
TMY2 User's Manual ([1]), especially tables 3-1 through 3-6, and
Appendix B.
metadata : dict
The site metadata available in the file.
Notes
-----
The returned structures have the following fields.
============= ==================================
key description
============= ==================================
WBAN Site identifier code (WBAN number)
City Station name
State Station state 2 letter designator
TZ Hours from Greenwich
latitude Latitude in decimal degrees
longitude Longitude in decimal degrees
altitude Site elevation in meters
============= ==================================
============================ ==========================================================================================================================================================================
TMYData field description
============================ ==========================================================================================================================================================================
index Pandas timeseries object containing timestamps
year
month
day
hour
ETR Extraterrestrial horizontal radiation recv'd during 60 minutes prior to timestamp, Wh/m^2
ETRN Extraterrestrial normal radiation recv'd during 60 minutes prior to timestamp, Wh/m^2
GHI Direct and diffuse horizontal radiation recv'd during 60 minutes prior to timestamp, Wh/m^2
GHISource See [1], Table 3-3
GHIUncertainty See [1], Table 3-4
DNI Amount of direct normal radiation (modeled) recv'd during 60 mintues prior to timestamp, Wh/m^2
DNISource See [1], Table 3-3
DNIUncertainty See [1], Table 3-4
DHI Amount of diffuse horizontal radiation recv'd during 60 minutes prior to timestamp, Wh/m^2
DHISource See [1], Table 3-3
DHIUncertainty See [1], Table 3-4
GHillum Avg. total horizontal illuminance recv'd during the 60 minutes prior to timestamp, units of 100 lux (e.g. value of 50 = 5000 lux)
GHillumSource See [1], Table 3-3
GHillumUncertainty See [1], Table 3-4
DNillum Avg. direct normal illuminance recv'd during the 60 minutes prior to timestamp, units of 100 lux
DNillumSource See [1], Table 3-3
DNillumUncertainty See [1], Table 3-4
DHillum Avg. horizontal diffuse illuminance recv'd during the 60 minutes prior to timestamp, units of 100 lux
DHillumSource See [1], Table 3-3
DHillumUncertainty See [1], Table 3-4
Zenithlum Avg. luminance at the sky's zenith during the 60 minutes prior to timestamp, units of 10 Cd/m^2 (e.g. value of 700 = 7,000 Cd/m^2)
ZenithlumSource See [1], Table 3-3
ZenithlumUncertainty See [1], Table 3-4
TotCld Amount of sky dome covered by clouds or obscuring phenonema at time stamp, tenths of sky
TotCldSource See [1], Table 3-5, 8760x1 cell array of strings
TotCldUnertainty See [1], Table 3-6
OpqCld Amount of sky dome covered by clouds or obscuring phenonema that prevent observing the sky at time stamp, tenths of sky
OpqCldSource See [1], Table 3-5, 8760x1 cell array of strings
OpqCldUncertainty See [1], Table 3-6
DryBulb Dry bulb temperature at the time indicated, in tenths of degree C (e.g. 352 = 35.2 C).
DryBulbSource See [1], Table 3-5, 8760x1 cell array of strings
DryBulbUncertainty See [1], Table 3-6
DewPoint Dew-point temperature at the time indicated, in tenths of degree C (e.g. 76 = 7.6 C).
DewPointSource See [1], Table 3-5, 8760x1 cell array of strings
DewPointUncertainty See [1], Table 3-6
RHum Relative humidity at the time indicated, percent
RHumSource See [1], Table 3-5, 8760x1 cell array of strings
RHumUncertainty See [1], Table 3-6
Pressure Station pressure at the time indicated, 1 mbar
PressureSource See [1], Table 3-5, 8760x1 cell array of strings
PressureUncertainty See [1], Table 3-6
Wdir Wind direction at time indicated, degrees from east of north (360 = 0 = north; 90 = East; 0 = undefined,calm)
WdirSource See [1], Table 3-5, 8760x1 cell array of strings
WdirUncertainty See [1], Table 3-6
Wspd Wind speed at the time indicated, in tenths of meters/second (e.g. 212 = 21.2 m/s)
WspdSource See [1], Table 3-5, 8760x1 cell array of strings
WspdUncertainty See [1], Table 3-6
Hvis Distance to discernable remote objects at time indicated (7777=unlimited, 9999=missing data), in tenths of kilometers (e.g. 341 = 34.1 km).
HvisSource See [1], Table 3-5, 8760x1 cell array of strings
HvisUncertainty See [1], Table 3-6
CeilHgt Height of cloud base above local terrain (7777=unlimited, 88888=cirroform, 99999=missing data), in meters
CeilHgtSource See [1], Table 3-5, 8760x1 cell array of strings
CeilHgtUncertainty See [1], Table 3-6
Pwat Total precipitable water contained in a column of unit cross section from Earth to top of atmosphere, in millimeters
PwatSource See [1], Table 3-5, 8760x1 cell array of strings
PwatUncertainty See [1], Table 3-6
AOD The broadband aerosol optical depth (broadband turbidity) in thousandths on the day indicated (e.g. 114 = 0.114)
AODSource See [1], Table 3-5, 8760x1 cell array of strings
AODUncertainty See [1], Table 3-6
SnowDepth Snow depth in centimeters on the day indicated, (999 = missing data).
SnowDepthSource See [1], Table 3-5, 8760x1 cell array of strings
SnowDepthUncertainty See [1], Table 3-6
LastSnowfall Number of days since last snowfall (maximum value of 88, where 88 = 88 or greater days; 99 = missing data)
LastSnowfallSource See [1], Table 3-5, 8760x1 cell array of strings
LastSnowfallUncertainty See [1], Table 3-6
PresentWeather See [1], Appendix B, an 8760x1 cell array of strings. Each string contains 10 numeric values. The string can be parsed to determine each of 10 observed weather metrics.
============================ ==========================================================================================================================================================================
References
----------
[1] Marion, W and Urban, K. "Wilcox, S and Marion, W. "User's Manual
for TMY2s". NREL 1995. | [
"Read",
"a",
"TMY2",
"file",
"in",
"to",
"a",
"DataFrame",
"."
] | python | train |
PyCQA/astroid | astroid/node_classes.py | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L2966-L2979 | def catch(self, exceptions): # pylint: disable=redefined-outer-name
"""Check if this node handles any of the given exceptions.
If ``exceptions`` is empty, this will default to ``True``.
:param exceptions: The name of the exceptions to check for.
:type exceptions: list(str)
"""
if self.type is None or exceptions is None:
return True
for node in self.type._get_name_nodes():
if node.name in exceptions:
return True
return False | [
"def",
"catch",
"(",
"self",
",",
"exceptions",
")",
":",
"# pylint: disable=redefined-outer-name",
"if",
"self",
".",
"type",
"is",
"None",
"or",
"exceptions",
"is",
"None",
":",
"return",
"True",
"for",
"node",
"in",
"self",
".",
"type",
".",
"_get_name_no... | Check if this node handles any of the given exceptions.
If ``exceptions`` is empty, this will default to ``True``.
:param exceptions: The name of the exceptions to check for.
:type exceptions: list(str) | [
"Check",
"if",
"this",
"node",
"handles",
"any",
"of",
"the",
"given",
"exceptions",
"."
] | python | train |
dw/mitogen | ansible_mitogen/services.py | https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/ansible_mitogen/services.py#L343-L403 | def _connect(self, key, spec, via=None):
"""
Actual connect implementation. Arranges for the Mitogen connection to
be created and enqueues an asynchronous call to start the forked task
parent in the remote context.
:param key:
Deduplication key representing the connection configuration.
:param spec:
Connection specification.
:returns:
Dict like::
{
'context': mitogen.core.Context or None,
'via': mitogen.core.Context or None,
'init_child_result': {
'fork_context': mitogen.core.Context,
'home_dir': str or None,
},
'msg': str or None
}
Where `context` is a reference to the newly constructed context,
`init_child_result` is the result of executing
:func:`ansible_mitogen.target.init_child` in that context, `msg` is
an error message and the remaining fields are :data:`None`, or
`msg` is :data:`None` and the remaining fields are set.
"""
try:
method = getattr(self.router, spec['method'])
except AttributeError:
raise Error('unsupported method: %(transport)s' % spec)
context = method(via=via, unidirectional=True, **spec['kwargs'])
if via and spec.get('enable_lru'):
self._update_lru(context, spec, via)
# Forget the context when its disconnect event fires.
mitogen.core.listen(context, 'disconnect',
lambda: self._on_context_disconnect(context))
self._send_module_forwards(context)
init_child_result = context.call(
ansible_mitogen.target.init_child,
log_level=LOG.getEffectiveLevel(),
candidate_temp_dirs=self._get_candidate_temp_dirs(),
)
if os.environ.get('MITOGEN_DUMP_THREAD_STACKS'):
from mitogen import debug
context.call(debug.dump_to_logger)
self._key_by_context[context] = key
self._refs_by_context[context] = 0
return {
'context': context,
'via': via,
'init_child_result': init_child_result,
'msg': None,
} | [
"def",
"_connect",
"(",
"self",
",",
"key",
",",
"spec",
",",
"via",
"=",
"None",
")",
":",
"try",
":",
"method",
"=",
"getattr",
"(",
"self",
".",
"router",
",",
"spec",
"[",
"'method'",
"]",
")",
"except",
"AttributeError",
":",
"raise",
"Error",
... | Actual connect implementation. Arranges for the Mitogen connection to
be created and enqueues an asynchronous call to start the forked task
parent in the remote context.
:param key:
Deduplication key representing the connection configuration.
:param spec:
Connection specification.
:returns:
Dict like::
{
'context': mitogen.core.Context or None,
'via': mitogen.core.Context or None,
'init_child_result': {
'fork_context': mitogen.core.Context,
'home_dir': str or None,
},
'msg': str or None
}
Where `context` is a reference to the newly constructed context,
`init_child_result` is the result of executing
:func:`ansible_mitogen.target.init_child` in that context, `msg` is
an error message and the remaining fields are :data:`None`, or
`msg` is :data:`None` and the remaining fields are set. | [
"Actual",
"connect",
"implementation",
".",
"Arranges",
"for",
"the",
"Mitogen",
"connection",
"to",
"be",
"created",
"and",
"enqueues",
"an",
"asynchronous",
"call",
"to",
"start",
"the",
"forked",
"task",
"parent",
"in",
"the",
"remote",
"context",
"."
] | python | train |
fermiPy/fermipy | fermipy/jobs/link.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/link.py#L850-L860 | def missing_input_files(self):
"""Make and return a dictionary of the missing input files.
This returns a dictionary mapping
filepath to list of `Link` that use the file as input.
"""
missing = self.check_input_files(return_found=False)
ret_dict = {}
for miss_file in missing:
ret_dict[miss_file] = [self.linkname]
return ret_dict | [
"def",
"missing_input_files",
"(",
"self",
")",
":",
"missing",
"=",
"self",
".",
"check_input_files",
"(",
"return_found",
"=",
"False",
")",
"ret_dict",
"=",
"{",
"}",
"for",
"miss_file",
"in",
"missing",
":",
"ret_dict",
"[",
"miss_file",
"]",
"=",
"[",... | Make and return a dictionary of the missing input files.
This returns a dictionary mapping
filepath to list of `Link` that use the file as input. | [
"Make",
"and",
"return",
"a",
"dictionary",
"of",
"the",
"missing",
"input",
"files",
"."
] | python | train |
druids/django-chamber | chamber/utils/decorators.py | https://github.com/druids/django-chamber/blob/eef4169923557e96877a664fa254e8c0814f3f23/chamber/utils/decorators.py#L26-L44 | def translation_activate_block(function=None, language=None):
"""
Activate language only for one method or function
"""
def _translation_activate_block(function):
def _decorator(*args, **kwargs):
tmp_language = translation.get_language()
try:
translation.activate(language or settings.LANGUAGE_CODE)
return function(*args, **kwargs)
finally:
translation.activate(tmp_language)
return wraps(function)(_decorator)
if function:
return _translation_activate_block(function)
else:
return _translation_activate_block | [
"def",
"translation_activate_block",
"(",
"function",
"=",
"None",
",",
"language",
"=",
"None",
")",
":",
"def",
"_translation_activate_block",
"(",
"function",
")",
":",
"def",
"_decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"tmp_languag... | Activate language only for one method or function | [
"Activate",
"language",
"only",
"for",
"one",
"method",
"or",
"function"
] | python | train |
RedFantom/ttkwidgets | ttkwidgets/color/colorpicker.py | https://github.com/RedFantom/ttkwidgets/blob/02150322060f867b6e59a175522ef84b09168019/ttkwidgets/color/colorpicker.py#L332-L340 | def _update_preview(self):
"""Update color preview."""
color = self.hexa.get()
if self.alpha_channel:
prev = overlay(self._transparent_bg, hexa_to_rgb(color))
self._im_color = ImageTk.PhotoImage(prev, master=self)
self.color_preview.configure(image=self._im_color)
else:
self.color_preview.configure(background=color) | [
"def",
"_update_preview",
"(",
"self",
")",
":",
"color",
"=",
"self",
".",
"hexa",
".",
"get",
"(",
")",
"if",
"self",
".",
"alpha_channel",
":",
"prev",
"=",
"overlay",
"(",
"self",
".",
"_transparent_bg",
",",
"hexa_to_rgb",
"(",
"color",
")",
")",
... | Update color preview. | [
"Update",
"color",
"preview",
"."
] | python | train |
saltstack/salt | salt/runners/cache.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/cache.py#L388-L405 | def store(bank, key, data, cachedir=None):
'''
Lists entries stored in the specified bank.
CLI Example:
.. code-block:: bash
salt-run cache.store mycache mykey 'The time has come the walrus said'
'''
if cachedir is None:
cachedir = __opts__['cachedir']
try:
cache = salt.cache.Cache(__opts__, cachedir=cachedir)
except TypeError:
cache = salt.cache.Cache(__opts__)
return cache.store(bank, key, data) | [
"def",
"store",
"(",
"bank",
",",
"key",
",",
"data",
",",
"cachedir",
"=",
"None",
")",
":",
"if",
"cachedir",
"is",
"None",
":",
"cachedir",
"=",
"__opts__",
"[",
"'cachedir'",
"]",
"try",
":",
"cache",
"=",
"salt",
".",
"cache",
".",
"Cache",
"(... | Lists entries stored in the specified bank.
CLI Example:
.. code-block:: bash
salt-run cache.store mycache mykey 'The time has come the walrus said' | [
"Lists",
"entries",
"stored",
"in",
"the",
"specified",
"bank",
"."
] | python | train |
saltstack/salt | salt/modules/portage_config.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/portage_config.py#L68-L93 | def _get_config_file(conf, atom):
'''
Parse the given atom, allowing access to its parts
Success does not mean that the atom exists, just that it
is in the correct format.
Returns none if the atom is invalid.
'''
if '*' in atom:
parts = portage.dep.Atom(atom, allow_wildcard=True)
if not parts:
return
if parts.cp == '*/*':
# parts.repo will be empty if there is no repo part
relative_path = parts.repo or "gentoo"
elif six.text_type(parts.cp).endswith('/*'):
relative_path = six.text_type(parts.cp).split("/")[0] + "_"
else:
relative_path = os.path.join(*[x for x in os.path.split(parts.cp) if x != '*'])
else:
relative_path = _p_to_cp(atom)
if not relative_path:
return
complete_file_path = BASE_PATH.format(conf) + '/' + relative_path
return complete_file_path | [
"def",
"_get_config_file",
"(",
"conf",
",",
"atom",
")",
":",
"if",
"'*'",
"in",
"atom",
":",
"parts",
"=",
"portage",
".",
"dep",
".",
"Atom",
"(",
"atom",
",",
"allow_wildcard",
"=",
"True",
")",
"if",
"not",
"parts",
":",
"return",
"if",
"parts",... | Parse the given atom, allowing access to its parts
Success does not mean that the atom exists, just that it
is in the correct format.
Returns none if the atom is invalid. | [
"Parse",
"the",
"given",
"atom",
"allowing",
"access",
"to",
"its",
"parts",
"Success",
"does",
"not",
"mean",
"that",
"the",
"atom",
"exists",
"just",
"that",
"it",
"is",
"in",
"the",
"correct",
"format",
".",
"Returns",
"none",
"if",
"the",
"atom",
"is... | python | train |
ronhanson/python-tbx | tbx/code.py | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/code.py#L313-L327 | def sort_dictionary_list(dict_list, sort_key):
"""
sorts a list of dictionaries based on the value of the sort_key
dict_list - a list of dictionaries
sort_key - a string that identifies the key to sort the dictionaries with.
Test sorting a list of dictionaries:
>>> sort_dictionary_list([{'b' : 1, 'value' : 2}, {'c' : 2, 'value' : 3}, {'a' : 3, 'value' : 1}], 'value')
[{'a': 3, 'value': 1}, {'b': 1, 'value': 2}, {'c': 2, 'value': 3}]
"""
if not dict_list or len(dict_list) == 0:
return dict_list
dict_list.sort(key=itemgetter(sort_key))
return dict_list | [
"def",
"sort_dictionary_list",
"(",
"dict_list",
",",
"sort_key",
")",
":",
"if",
"not",
"dict_list",
"or",
"len",
"(",
"dict_list",
")",
"==",
"0",
":",
"return",
"dict_list",
"dict_list",
".",
"sort",
"(",
"key",
"=",
"itemgetter",
"(",
"sort_key",
")",
... | sorts a list of dictionaries based on the value of the sort_key
dict_list - a list of dictionaries
sort_key - a string that identifies the key to sort the dictionaries with.
Test sorting a list of dictionaries:
>>> sort_dictionary_list([{'b' : 1, 'value' : 2}, {'c' : 2, 'value' : 3}, {'a' : 3, 'value' : 1}], 'value')
[{'a': 3, 'value': 1}, {'b': 1, 'value': 2}, {'c': 2, 'value': 3}] | [
"sorts",
"a",
"list",
"of",
"dictionaries",
"based",
"on",
"the",
"value",
"of",
"the",
"sort_key"
] | python | train |
timkpaine/pyEX | pyEX/stocks.py | https://github.com/timkpaine/pyEX/blob/91cf751dafdb208a0c8b5377945e5808b99f94ba/pyEX/stocks.py#L12-L28 | def balanceSheet(symbol, token='', version=''):
'''Pulls balance sheet data. Available quarterly (4 quarters) and annually (4 years)
https://iexcloud.io/docs/api/#balance-sheet
Updates at 8am, 9am UTC daily
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
dict: result
'''
_raiseIfNotStr(symbol)
return _getJson('stock/' + symbol + '/balance-sheet', token, version) | [
"def",
"balanceSheet",
"(",
"symbol",
",",
"token",
"=",
"''",
",",
"version",
"=",
"''",
")",
":",
"_raiseIfNotStr",
"(",
"symbol",
")",
"return",
"_getJson",
"(",
"'stock/'",
"+",
"symbol",
"+",
"'/balance-sheet'",
",",
"token",
",",
"version",
")"
] | Pulls balance sheet data. Available quarterly (4 quarters) and annually (4 years)
https://iexcloud.io/docs/api/#balance-sheet
Updates at 8am, 9am UTC daily
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
dict: result | [
"Pulls",
"balance",
"sheet",
"data",
".",
"Available",
"quarterly",
"(",
"4",
"quarters",
")",
"and",
"annually",
"(",
"4",
"years",
")"
] | python | valid |
senaite/senaite.core | bika/lims/browser/reports/selection_macros/__init__.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/reports/selection_macros/__init__.py#L167-L172 | def _cache_key_select_sample_type(method, self, allow_blank=True, multiselect=False, style=None):
"""
This function returns the key used to decide if method select_sample_type has to be recomputed
"""
key = update_timer(), allow_blank, multiselect, style
return key | [
"def",
"_cache_key_select_sample_type",
"(",
"method",
",",
"self",
",",
"allow_blank",
"=",
"True",
",",
"multiselect",
"=",
"False",
",",
"style",
"=",
"None",
")",
":",
"key",
"=",
"update_timer",
"(",
")",
",",
"allow_blank",
",",
"multiselect",
",",
"... | This function returns the key used to decide if method select_sample_type has to be recomputed | [
"This",
"function",
"returns",
"the",
"key",
"used",
"to",
"decide",
"if",
"method",
"select_sample_type",
"has",
"to",
"be",
"recomputed"
] | python | train |
saltstack/salt | salt/states/ssh_auth.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ssh_auth.py#L512-L605 | def manage(
name,
ssh_keys,
user,
enc='ssh-rsa',
comment='',
source='',
options=None,
config='.ssh/authorized_keys',
fingerprint_hash_type=None,
**kwargs):
'''
.. versionadded:: Neon
Ensures that only the specified ssh_keys are present for the specified user
ssh_keys
The SSH key to manage
user
The user who owns the SSH authorized keys file to modify
enc
Defines what type of key is being used; can be ed25519, ecdsa, ssh-rsa
or ssh-dss
comment
The comment to be placed with the SSH public key
source
The source file for the key(s). Can contain any number of public keys,
in standard "authorized_keys" format. If this is set, comment and enc
will be ignored.
.. note::
The source file must contain keys in the format ``<enc> <key>
<comment>``. If you have generated a keypair using PuTTYgen, then you
will need to do the following to retrieve an OpenSSH-compatible public
key.
1. In PuTTYgen, click ``Load``, and select the *private* key file (not
the public key), and click ``Open``.
2. Copy the public key from the box labeled ``Public key for pasting
into OpenSSH authorized_keys file``.
3. Paste it into a new file.
options
The options passed to the keys, pass a list object
config
The location of the authorized keys file relative to the user's home
directory, defaults to ".ssh/authorized_keys". Token expansion %u and
%h for username and home path supported.
fingerprint_hash_type
The public key fingerprint hash type that the public key fingerprint
was originally hashed with. This defaults to ``sha256`` if not specified.
'''
ret = {'name': '',
'changes': {},
'result': True,
'comment': ''}
all_potential_keys = []
for ssh_key in ssh_keys:
# gather list potential ssh keys for removal comparison
# options, enc, and comments could be in the mix
all_potential_keys.extend(ssh_key.split(' '))
existing_keys = __salt__['ssh.auth_keys'](user=user).keys()
remove_keys = set(existing_keys).difference(all_potential_keys)
for remove_key in remove_keys:
if __opts__['test']:
remove_comment = '{0} Key set for removal'.format(remove_key)
ret['comment'] = remove_comment
ret['result'] = None
else:
remove_comment = absent(remove_key, user)['comment']
ret['changes'][remove_key] = remove_comment
for ssh_key in ssh_keys:
run_return = present(ssh_key, user, enc, comment, source,
options, config, fingerprint_hash_type, **kwargs)
if run_return['changes']:
ret['changes'].update(run_return['changes'])
else:
ret['comment'] += '\n' + run_return['comment']
ret['comment'].strip()
if run_return['result'] is None:
ret['result'] = None
elif not run_return['result']:
ret['result'] = False
return ret | [
"def",
"manage",
"(",
"name",
",",
"ssh_keys",
",",
"user",
",",
"enc",
"=",
"'ssh-rsa'",
",",
"comment",
"=",
"''",
",",
"source",
"=",
"''",
",",
"options",
"=",
"None",
",",
"config",
"=",
"'.ssh/authorized_keys'",
",",
"fingerprint_hash_type",
"=",
"... | .. versionadded:: Neon
Ensures that only the specified ssh_keys are present for the specified user
ssh_keys
The SSH key to manage
user
The user who owns the SSH authorized keys file to modify
enc
Defines what type of key is being used; can be ed25519, ecdsa, ssh-rsa
or ssh-dss
comment
The comment to be placed with the SSH public key
source
The source file for the key(s). Can contain any number of public keys,
in standard "authorized_keys" format. If this is set, comment and enc
will be ignored.
.. note::
The source file must contain keys in the format ``<enc> <key>
<comment>``. If you have generated a keypair using PuTTYgen, then you
will need to do the following to retrieve an OpenSSH-compatible public
key.
1. In PuTTYgen, click ``Load``, and select the *private* key file (not
the public key), and click ``Open``.
2. Copy the public key from the box labeled ``Public key for pasting
into OpenSSH authorized_keys file``.
3. Paste it into a new file.
options
The options passed to the keys, pass a list object
config
The location of the authorized keys file relative to the user's home
directory, defaults to ".ssh/authorized_keys". Token expansion %u and
%h for username and home path supported.
fingerprint_hash_type
The public key fingerprint hash type that the public key fingerprint
was originally hashed with. This defaults to ``sha256`` if not specified. | [
"..",
"versionadded",
"::",
"Neon"
] | python | train |
b3j0f/annotation | b3j0f/annotation/oop.py | https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/oop.py#L151-L194 | def mixin_function_or_method(target, routine, name=None, isbound=False):
"""Mixin a routine into the target.
:param routine: routine to mix in target.
:param str name: mixin name. Routine name by default.
:param bool isbound: If True (False by default), the mixin result is a
bound method to target.
"""
function = None
if isfunction(routine):
function = routine
elif ismethod(routine):
function = get_method_function(routine)
else:
raise Mixin.MixInError(
"{0} must be a function or a method.".format(routine))
if name is None:
name = routine.__name__
if not isclass(target) or isbound:
_type = type(target)
method_args = [function, target]
if PY2:
method_args += _type
result = MethodType(*method_args)
else:
if PY2:
result = MethodType(function, None, target)
else:
result = function
Mixin.set_mixin(target, result, name)
return result | [
"def",
"mixin_function_or_method",
"(",
"target",
",",
"routine",
",",
"name",
"=",
"None",
",",
"isbound",
"=",
"False",
")",
":",
"function",
"=",
"None",
"if",
"isfunction",
"(",
"routine",
")",
":",
"function",
"=",
"routine",
"elif",
"ismethod",
"(",
... | Mixin a routine into the target.
:param routine: routine to mix in target.
:param str name: mixin name. Routine name by default.
:param bool isbound: If True (False by default), the mixin result is a
bound method to target. | [
"Mixin",
"a",
"routine",
"into",
"the",
"target",
"."
] | python | train |
Qiskit/qiskit-terra | qiskit/pulse/pulse_lib/discrete.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/pulse_lib/discrete.py#L227-L251 | def drag(duration: int, amp: complex, sigma: float, beta: float, name: str = None) -> SamplePulse:
r"""Generates Y-only correction DRAG `SamplePulse` for standard nonlinear oscillator (SNO) [1].
Centered at `duration/2` and zeroed at `t=-1` to prevent large initial discontinuity.
Applies `left` sampling strategy to generate discrete pulse from continuous function.
[1] Gambetta, J. M., Motzoi, F., Merkel, S. T. & Wilhelm, F. K.
Analytic control methods for high-fidelity unitary operations
in a weakly nonlinear oscillator. Phys. Rev. A 83, 012308 (2011).
Args:
duration: Duration of pulse. Must be greater than zero.
amp: Pulse amplitude at `center`.
sigma: Width (standard deviation) of pulse.
beta: Y correction amplitude. For the SNO this is $\beta=-\frac{\lambda_1^2}{4\Delta_2}$.
Where $\lambds_1$ is the relative coupling strength between the first excited and second
excited states and $\Delta_2$ is the detuning between the resepective excited states.
name: Name of pulse.
"""
center = duration/2
zeroed_width = duration + 2
return _sampled_drag_pulse(duration, amp, center, sigma, beta,
zeroed_width=zeroed_width, rescale_amp=True, name=name) | [
"def",
"drag",
"(",
"duration",
":",
"int",
",",
"amp",
":",
"complex",
",",
"sigma",
":",
"float",
",",
"beta",
":",
"float",
",",
"name",
":",
"str",
"=",
"None",
")",
"->",
"SamplePulse",
":",
"center",
"=",
"duration",
"/",
"2",
"zeroed_width",
... | r"""Generates Y-only correction DRAG `SamplePulse` for standard nonlinear oscillator (SNO) [1].
Centered at `duration/2` and zeroed at `t=-1` to prevent large initial discontinuity.
Applies `left` sampling strategy to generate discrete pulse from continuous function.
[1] Gambetta, J. M., Motzoi, F., Merkel, S. T. & Wilhelm, F. K.
Analytic control methods for high-fidelity unitary operations
in a weakly nonlinear oscillator. Phys. Rev. A 83, 012308 (2011).
Args:
duration: Duration of pulse. Must be greater than zero.
amp: Pulse amplitude at `center`.
sigma: Width (standard deviation) of pulse.
beta: Y correction amplitude. For the SNO this is $\beta=-\frac{\lambda_1^2}{4\Delta_2}$.
Where $\lambds_1$ is the relative coupling strength between the first excited and second
excited states and $\Delta_2$ is the detuning between the resepective excited states.
name: Name of pulse. | [
"r",
"Generates",
"Y",
"-",
"only",
"correction",
"DRAG",
"SamplePulse",
"for",
"standard",
"nonlinear",
"oscillator",
"(",
"SNO",
")",
"[",
"1",
"]",
"."
] | python | test |
jkitzes/macroeco | macroeco/misc/misc.py | https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/misc/misc.py#L36-L57 | def inherit_docstring_from(cls):
"""
This decorator modifies the decorated function's docstring by
replacing occurrences of '%(super)s' with the docstring of the
method of the same name from the class `cls`.
If the decorated method has no docstring, it is simply given the
docstring of cls method.
Extracted from scipy.misc.doccer.
"""
def _doc(func):
cls_docstring = getattr(cls, func.__name__).__doc__
func_docstring = func.__doc__
if func_docstring is None:
func.__doc__ = cls_docstring
else:
new_docstring = func_docstring % dict(super=cls_docstring)
func.__doc__ = new_docstring
return func
return _doc | [
"def",
"inherit_docstring_from",
"(",
"cls",
")",
":",
"def",
"_doc",
"(",
"func",
")",
":",
"cls_docstring",
"=",
"getattr",
"(",
"cls",
",",
"func",
".",
"__name__",
")",
".",
"__doc__",
"func_docstring",
"=",
"func",
".",
"__doc__",
"if",
"func_docstrin... | This decorator modifies the decorated function's docstring by
replacing occurrences of '%(super)s' with the docstring of the
method of the same name from the class `cls`.
If the decorated method has no docstring, it is simply given the
docstring of cls method.
Extracted from scipy.misc.doccer. | [
"This",
"decorator",
"modifies",
"the",
"decorated",
"function",
"s",
"docstring",
"by",
"replacing",
"occurrences",
"of",
"%",
"(",
"super",
")",
"s",
"with",
"the",
"docstring",
"of",
"the",
"method",
"of",
"the",
"same",
"name",
"from",
"the",
"class",
... | python | train |
chaoss/grimoirelab-perceval | perceval/backends/core/gitlab.py | https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/gitlab.py#L533-L552 | def fetch(self, url, payload=None, headers=None, method=HttpClient.GET, stream=False):
"""Fetch the data from a given URL.
:param url: link to the resource
:param payload: payload of the request
:param headers: headers of the request
:param method: type of request call (GET or POST)
:param stream: defer downloading the response body until the response content is available
:returns a response object
"""
if not self.from_archive:
self.sleep_for_rate_limit()
response = super().fetch(url, payload, headers, method, stream)
if not self.from_archive:
self.update_rate_limit(response)
return response | [
"def",
"fetch",
"(",
"self",
",",
"url",
",",
"payload",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"method",
"=",
"HttpClient",
".",
"GET",
",",
"stream",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"from_archive",
":",
"self",
".",
"sle... | Fetch the data from a given URL.
:param url: link to the resource
:param payload: payload of the request
:param headers: headers of the request
:param method: type of request call (GET or POST)
:param stream: defer downloading the response body until the response content is available
:returns a response object | [
"Fetch",
"the",
"data",
"from",
"a",
"given",
"URL",
"."
] | python | test |
ejeschke/ginga | experimental/plugins/IRAF.py | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/experimental/plugins/IRAF.py#L389-L410 | def init_frame(self, n):
"""
NOTE: this is called from the IIS_RequestHandler
"""
self.logger.debug("initializing frame %d" % (n))
# create the frame, if needed
try:
fb = self.get_frame(n)
except KeyError:
fb = iis.framebuffer()
self.fb[n] = fb
fb.width = None
fb.height = None
fb.wcs = ''
fb.image = None
fb.bitmap = None
fb.zoom = 1.0
fb.buffer = array.array('B')
fb.ct = iis.coord_tran()
#fb.chname = None
return fb | [
"def",
"init_frame",
"(",
"self",
",",
"n",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"initializing frame %d\"",
"%",
"(",
"n",
")",
")",
"# create the frame, if needed",
"try",
":",
"fb",
"=",
"self",
".",
"get_frame",
"(",
"n",
")",
"except... | NOTE: this is called from the IIS_RequestHandler | [
"NOTE",
":",
"this",
"is",
"called",
"from",
"the",
"IIS_RequestHandler"
] | python | train |
jason-weirather/py-seq-tools | seqtools/errors.py | https://github.com/jason-weirather/py-seq-tools/blob/f642c2c73ffef2acc83656a78059a476fc734ca1/seqtools/errors.py#L425-L458 | def get_string(self):
""" Get a string representation of this single base error.
:returns: report
:rtype: string
"""
ostr = ''
ostr += 'BaseError for ['+self._type+'] base: '+self.get_base()+"\n"
if self._observable.get_error_probability() > 0:
ostr += ' Homopolymer set:'+"\n"
ostr += ' '+str(self.get_homopolymer())+"\n"
ostr += ' Observable:'+"\n"
ostr += ' type is: '+str(self.get_observable_type())+"\n"
ostr += ' P(error): '+str(self._observable.get_error_probability())+"\n"
ostr += ' Elength: '+str(self._observable.get_attributable_length())+"\n"
before = self._unobservable.get_before_type()
after = self._unobservable.get_after_type()
if before or after:
ostr += ' Unobservable '
if self._type == 'query': ostr += 'deletion:'+"\n"
else: ostr += 'insertion:'+"\n"
ostr += ' P(error): '+str(self._unobservable.get_error_probability())+"\n"
ostr += ' Elength: '+str(self._unobservable.get_attributable_length())+"\n"
if before:
ostr += ' before: '+"\n"
ostr += ' P(error): '+str(self._unobservable.get_before_probability())+"\n"
ostr += ' '+str(before)+"\n"
if after:
ostr += ' after:'+"\n"
ostr += ' P(error): '+str(self._unobservable.get_after_probability())+"\n"
ostr += ' '+str(after)+"\n"
return ostr | [
"def",
"get_string",
"(",
"self",
")",
":",
"ostr",
"=",
"''",
"ostr",
"+=",
"'BaseError for ['",
"+",
"self",
".",
"_type",
"+",
"'] base: '",
"+",
"self",
".",
"get_base",
"(",
")",
"+",
"\"\\n\"",
"if",
"self",
".",
"_observable",
".",
"get_error_prob... | Get a string representation of this single base error.
:returns: report
:rtype: string | [
"Get",
"a",
"string",
"representation",
"of",
"this",
"single",
"base",
"error",
"."
] | python | train |
twilio/twilio-python | twilio/rest/taskrouter/v1/workspace/worker/__init__.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/taskrouter/v1/workspace/worker/__init__.py#L213-L225 | def statistics(self):
"""
Access the statistics
:returns: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsList
:rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsList
"""
if self._statistics is None:
self._statistics = WorkersStatisticsList(
self._version,
workspace_sid=self._solution['workspace_sid'],
)
return self._statistics | [
"def",
"statistics",
"(",
"self",
")",
":",
"if",
"self",
".",
"_statistics",
"is",
"None",
":",
"self",
".",
"_statistics",
"=",
"WorkersStatisticsList",
"(",
"self",
".",
"_version",
",",
"workspace_sid",
"=",
"self",
".",
"_solution",
"[",
"'workspace_sid... | Access the statistics
:returns: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsList
:rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_statistics.WorkersStatisticsList | [
"Access",
"the",
"statistics"
] | python | train |
SUSE-Enceladus/ipa | ipa/ipa_gce.py | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_gce.py#L274-L286 | def _set_instance_ip(self):
"""Retrieve and set the instance ip address."""
instance = self._get_instance()
if instance.public_ips:
self.instance_ip = instance.public_ips[0]
elif instance.private_ips:
self.instance_ip = instance.private_ips[0]
else:
raise GCECloudException(
'IP address for instance: %s cannot be found.'
% self.running_instance_id
) | [
"def",
"_set_instance_ip",
"(",
"self",
")",
":",
"instance",
"=",
"self",
".",
"_get_instance",
"(",
")",
"if",
"instance",
".",
"public_ips",
":",
"self",
".",
"instance_ip",
"=",
"instance",
".",
"public_ips",
"[",
"0",
"]",
"elif",
"instance",
".",
"... | Retrieve and set the instance ip address. | [
"Retrieve",
"and",
"set",
"the",
"instance",
"ip",
"address",
"."
] | python | train |
saltstack/salt | salt/modules/parallels.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parallels.py#L688-L742 | def delete_snapshot(name, snap_name, runas=None, all=False):
'''
Delete a snapshot
.. note::
Deleting a snapshot from which other snapshots are dervied will not
delete the derived snapshots
:param str name:
Name/ID of VM whose snapshot will be deleted
:param str snap_name:
Name/ID of snapshot to delete
:param str runas:
The user that the prlctl command will be run as
:param bool all:
Delete all snapshots having the name given
.. versionadded:: 2016.11.0
Example:
.. code-block:: bash
salt '*' parallels.delete_snapshot macvm 'unneeded snapshot' runas=macdev
salt '*' parallels.delete_snapshot macvm 'Snapshot for linked clone' all=True runas=macdev
'''
# strict means raise an error if multiple snapshot IDs found for the name given
strict = not all
# Validate VM and snapshot names
name = salt.utils.data.decode(name)
snap_ids = _validate_snap_name(name, snap_name, strict=strict, runas=runas)
if isinstance(snap_ids, six.string_types):
snap_ids = [snap_ids]
# Delete snapshot(s)
ret = {}
for snap_id in snap_ids:
snap_id = snap_id.strip('{}')
# Construct argument list
args = [name, '--id', snap_id]
# Execute command
ret[snap_id] = prlctl('snapshot-delete', args, runas=runas)
# Return results
ret_keys = list(ret.keys())
if len(ret_keys) == 1:
return ret[ret_keys[0]]
else:
return ret | [
"def",
"delete_snapshot",
"(",
"name",
",",
"snap_name",
",",
"runas",
"=",
"None",
",",
"all",
"=",
"False",
")",
":",
"# strict means raise an error if multiple snapshot IDs found for the name given",
"strict",
"=",
"not",
"all",
"# Validate VM and snapshot names",
"nam... | Delete a snapshot
.. note::
Deleting a snapshot from which other snapshots are dervied will not
delete the derived snapshots
:param str name:
Name/ID of VM whose snapshot will be deleted
:param str snap_name:
Name/ID of snapshot to delete
:param str runas:
The user that the prlctl command will be run as
:param bool all:
Delete all snapshots having the name given
.. versionadded:: 2016.11.0
Example:
.. code-block:: bash
salt '*' parallels.delete_snapshot macvm 'unneeded snapshot' runas=macdev
salt '*' parallels.delete_snapshot macvm 'Snapshot for linked clone' all=True runas=macdev | [
"Delete",
"a",
"snapshot"
] | python | train |
SergeySatskiy/cdm-pythonparser | cdmpyparser.py | https://github.com/SergeySatskiy/cdm-pythonparser/blob/7e933aca899b1853d744082313ffc3a8b1154505/cdmpyparser.py#L562-L569 | def _onDecorator(self, name, line, pos, absPosition):
"""Memorizes a function or a class decorator"""
# A class or a function must be on the top of the stack
d = Decorator(name, line, pos, absPosition)
if self.__lastDecorators is None:
self.__lastDecorators = [d]
else:
self.__lastDecorators.append(d) | [
"def",
"_onDecorator",
"(",
"self",
",",
"name",
",",
"line",
",",
"pos",
",",
"absPosition",
")",
":",
"# A class or a function must be on the top of the stack",
"d",
"=",
"Decorator",
"(",
"name",
",",
"line",
",",
"pos",
",",
"absPosition",
")",
"if",
"self... | Memorizes a function or a class decorator | [
"Memorizes",
"a",
"function",
"or",
"a",
"class",
"decorator"
] | python | train |
log2timeline/plaso | plaso/parsers/manager.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/manager.py#L283-L301 | def GetParserPluginsInformation(cls, parser_filter_expression=None):
"""Retrieves the parser plugins information.
Args:
parser_filter_expression (Optional[str]): parser filter expression,
where None represents all parsers and plugins.
Returns:
list[tuple[str, str]]: pairs of parser plugin names and descriptions.
"""
parser_plugins_information = []
for _, parser_class in cls.GetParsers(
parser_filter_expression=parser_filter_expression):
if parser_class.SupportsPlugins():
for plugin_name, plugin_class in parser_class.GetPlugins():
description = getattr(plugin_class, 'DESCRIPTION', '')
parser_plugins_information.append((plugin_name, description))
return parser_plugins_information | [
"def",
"GetParserPluginsInformation",
"(",
"cls",
",",
"parser_filter_expression",
"=",
"None",
")",
":",
"parser_plugins_information",
"=",
"[",
"]",
"for",
"_",
",",
"parser_class",
"in",
"cls",
".",
"GetParsers",
"(",
"parser_filter_expression",
"=",
"parser_filt... | Retrieves the parser plugins information.
Args:
parser_filter_expression (Optional[str]): parser filter expression,
where None represents all parsers and plugins.
Returns:
list[tuple[str, str]]: pairs of parser plugin names and descriptions. | [
"Retrieves",
"the",
"parser",
"plugins",
"information",
"."
] | python | train |
barryp/py-amqplib | amqplib/client_0_8/transport.py | https://github.com/barryp/py-amqplib/blob/2b3a47de34b4712c111d0a55d7ff109dffc2a7b2/amqplib/client_0_8/transport.py#L245-L252 | def _setup_transport(self):
"""
Setup to _write() directly to the socket, and
do our own buffered reads.
"""
self._write = self.sock.sendall
self._read_buffer = bytes() | [
"def",
"_setup_transport",
"(",
"self",
")",
":",
"self",
".",
"_write",
"=",
"self",
".",
"sock",
".",
"sendall",
"self",
".",
"_read_buffer",
"=",
"bytes",
"(",
")"
] | Setup to _write() directly to the socket, and
do our own buffered reads. | [
"Setup",
"to",
"_write",
"()",
"directly",
"to",
"the",
"socket",
"and",
"do",
"our",
"own",
"buffered",
"reads",
"."
] | python | train |
kensho-technologies/graphql-compiler | graphql_compiler/compiler/ir_lowering_gremlin/ir_lowering.py | https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/compiler/ir_lowering_gremlin/ir_lowering.py#L319-L355 | def lower_folded_outputs(ir_blocks):
"""Lower standard folded output fields into GremlinFoldedContextField objects."""
folds, remaining_ir_blocks = extract_folds_from_ir_blocks(ir_blocks)
if not remaining_ir_blocks:
raise AssertionError(u'Expected at least one non-folded block to remain: {} {} '
u'{}'.format(folds, remaining_ir_blocks, ir_blocks))
output_block = remaining_ir_blocks[-1]
if not isinstance(output_block, ConstructResult):
raise AssertionError(u'Expected the last non-folded block to be ConstructResult, '
u'but instead was: {} {} '
u'{}'.format(type(output_block), output_block, ir_blocks))
# Turn folded Filter blocks into GremlinFoldedFilter blocks.
converted_folds = {
base_fold_location.get_location_name()[0]: _convert_folded_blocks(folded_ir_blocks)
for base_fold_location, folded_ir_blocks in six.iteritems(folds)
}
new_output_fields = dict()
for output_name, output_expression in six.iteritems(output_block.fields):
new_output_expression = output_expression
# Turn FoldedContextField expressions into GremlinFoldedContextField ones.
if isinstance(output_expression, FoldedContextField):
# Get the matching folded IR blocks and put them in the new context field.
base_fold_location_name = output_expression.fold_scope_location.get_location_name()[0]
folded_ir_blocks = converted_folds[base_fold_location_name]
new_output_expression = GremlinFoldedContextField(
output_expression.fold_scope_location, folded_ir_blocks,
output_expression.field_type)
new_output_fields[output_name] = new_output_expression
new_ir_blocks = remaining_ir_blocks[:-1]
new_ir_blocks.append(ConstructResult(new_output_fields))
return new_ir_blocks | [
"def",
"lower_folded_outputs",
"(",
"ir_blocks",
")",
":",
"folds",
",",
"remaining_ir_blocks",
"=",
"extract_folds_from_ir_blocks",
"(",
"ir_blocks",
")",
"if",
"not",
"remaining_ir_blocks",
":",
"raise",
"AssertionError",
"(",
"u'Expected at least one non-folded block to ... | Lower standard folded output fields into GremlinFoldedContextField objects. | [
"Lower",
"standard",
"folded",
"output",
"fields",
"into",
"GremlinFoldedContextField",
"objects",
"."
] | python | train |
swharden/SWHLab | doc/oldcode/swhlab/core/ap.py | https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/ap.py#L323-L332 | def stats_first(abf):
"""provide all stats on the first AP."""
msg=""
for sweep in range(abf.sweeps):
for AP in abf.APs[sweep]:
for key in sorted(AP.keys()):
if key[-1] is "I" or key[-2:] in ["I1","I2"]:
continue
msg+="%s = %s\n"%(key,AP[key])
return msg | [
"def",
"stats_first",
"(",
"abf",
")",
":",
"msg",
"=",
"\"\"",
"for",
"sweep",
"in",
"range",
"(",
"abf",
".",
"sweeps",
")",
":",
"for",
"AP",
"in",
"abf",
".",
"APs",
"[",
"sweep",
"]",
":",
"for",
"key",
"in",
"sorted",
"(",
"AP",
".",
"key... | provide all stats on the first AP. | [
"provide",
"all",
"stats",
"on",
"the",
"first",
"AP",
"."
] | python | valid |
mlperf/training | reinforcement/tensorflow/minigo/bigtable_input.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/bigtable_input.py#L331-L363 | def trim_games_since(self, t, max_games=500000):
"""Trim off the games since the given time.
Search back no more than max_games for this time point, locate
the game there, and remove all games since that game,
resetting the latest game counter.
If `t` is a `datetime.timedelta`, then the target time will be
found by subtracting that delta from the time of the last
game. Otherwise, it will be the target time.
"""
latest = self.latest_game_number
earliest = int(latest - max_games)
gbt = self.games_by_time(earliest, latest)
if not gbt:
utils.dbg('No games between %d and %d' % (earliest, latest))
return
most_recent = gbt[-1]
if isinstance(t, datetime.timedelta):
target = most_recent[0] - t
else:
target = t
i = bisect.bisect_right(gbt, (target,))
if i >= len(gbt):
utils.dbg('Last game is already at %s' % gbt[-1][0])
return
when, which = gbt[i]
utils.dbg('Most recent: %s %s' % most_recent)
utils.dbg(' Target: %s %s' % (when, which))
which = int(which)
self.delete_row_range(ROW_PREFIX, which, latest)
self.delete_row_range(ROWCOUNT_PREFIX, which, latest)
self.latest_game_number = which | [
"def",
"trim_games_since",
"(",
"self",
",",
"t",
",",
"max_games",
"=",
"500000",
")",
":",
"latest",
"=",
"self",
".",
"latest_game_number",
"earliest",
"=",
"int",
"(",
"latest",
"-",
"max_games",
")",
"gbt",
"=",
"self",
".",
"games_by_time",
"(",
"e... | Trim off the games since the given time.
Search back no more than max_games for this time point, locate
the game there, and remove all games since that game,
resetting the latest game counter.
If `t` is a `datetime.timedelta`, then the target time will be
found by subtracting that delta from the time of the last
game. Otherwise, it will be the target time. | [
"Trim",
"off",
"the",
"games",
"since",
"the",
"given",
"time",
"."
] | python | train |
cloud9ers/gurumate | environment/share/doc/ipython/examples/parallel/rmt/rmtkernel.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/share/doc/ipython/examples/parallel/rmt/rmtkernel.py#L24-L30 | def ensemble_diffs(num, N):
"""Return num eigenvalue diffs for the NxN GOE ensemble."""
diffs = np.empty(num)
for i in xrange(num):
mat = GOE(N)
diffs[i] = center_eigenvalue_diff(mat)
return diffs | [
"def",
"ensemble_diffs",
"(",
"num",
",",
"N",
")",
":",
"diffs",
"=",
"np",
".",
"empty",
"(",
"num",
")",
"for",
"i",
"in",
"xrange",
"(",
"num",
")",
":",
"mat",
"=",
"GOE",
"(",
"N",
")",
"diffs",
"[",
"i",
"]",
"=",
"center_eigenvalue_diff",... | Return num eigenvalue diffs for the NxN GOE ensemble. | [
"Return",
"num",
"eigenvalue",
"diffs",
"for",
"the",
"NxN",
"GOE",
"ensemble",
"."
] | python | test |
carpedm20/fbchat | fbchat/_client.py | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1949-L1964 | def changeThreadColor(self, color, thread_id=None):
"""
Changes thread color
:param color: New thread color
:param thread_id: User/Group ID to change color of. See :ref:`intro_threads`
:type color: models.ThreadColor
:raises: FBchatException if request failed
"""
thread_id, thread_type = self._getThread(thread_id, None)
data = {
"color_choice": color.value if color != ThreadColor.MESSENGER_BLUE else "",
"thread_or_other_fbid": thread_id,
}
j = self._post(self.req_url.THREAD_COLOR, data, fix_request=True, as_json=True) | [
"def",
"changeThreadColor",
"(",
"self",
",",
"color",
",",
"thread_id",
"=",
"None",
")",
":",
"thread_id",
",",
"thread_type",
"=",
"self",
".",
"_getThread",
"(",
"thread_id",
",",
"None",
")",
"data",
"=",
"{",
"\"color_choice\"",
":",
"color",
".",
... | Changes thread color
:param color: New thread color
:param thread_id: User/Group ID to change color of. See :ref:`intro_threads`
:type color: models.ThreadColor
:raises: FBchatException if request failed | [
"Changes",
"thread",
"color"
] | python | train |
DLR-RM/RAFCON | share/examples/plugins/templates/gtkmvc_template_observer.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/share/examples/plugins/templates/gtkmvc_template_observer.py#L36-L46 | def relieve_state_machines(self, model, prop_name, info):
""" The method relieves observed models before those get removed from the list of state_machines hold by
observed StateMachineMangerModel. The method register as observer of observable
StateMachineMangerModel.state_machines."""
if info['method_name'] == '__setitem__':
pass
elif info['method_name'] == '__delitem__':
self.relieve_model(self.state_machine_manager_model.state_machines[info['args'][0]])
self.logger.info(NotificationOverview(info))
else:
self.logger.warning(NotificationOverview(info)) | [
"def",
"relieve_state_machines",
"(",
"self",
",",
"model",
",",
"prop_name",
",",
"info",
")",
":",
"if",
"info",
"[",
"'method_name'",
"]",
"==",
"'__setitem__'",
":",
"pass",
"elif",
"info",
"[",
"'method_name'",
"]",
"==",
"'__delitem__'",
":",
"self",
... | The method relieves observed models before those get removed from the list of state_machines hold by
observed StateMachineMangerModel. The method register as observer of observable
StateMachineMangerModel.state_machines. | [
"The",
"method",
"relieves",
"observed",
"models",
"before",
"those",
"get",
"removed",
"from",
"the",
"list",
"of",
"state_machines",
"hold",
"by",
"observed",
"StateMachineMangerModel",
".",
"The",
"method",
"register",
"as",
"observer",
"of",
"observable",
"Sta... | python | train |
csparpa/pyowm | pyowm/weatherapi25/owm25.py | https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/weatherapi25/owm25.py#L1090-L1111 | def uvindex_around_coords(self, lat, lon):
"""
Queries the OWM Weather API for Ultra Violet value sampled in the
surroundings of the provided geocoordinates and in the specified time
interval. A *UVIndex* object instance is returned, encapsulating a
*Location* object and the UV intensity value.
:param lat: the location's latitude, must be between -90.0 and 90.0
:type lat: int/float
:param lon: the location's longitude, must be between -180.0 and 180.0
:type lon: int/float
:return: a *UVIndex* instance or ``None`` if data is not available
:raises: *ParseResponseException* when OWM Weather API responses' data
cannot be parsed, *APICallException* when OWM Weather API can not be
reached, *ValueError* for wrong input values
"""
geo.assert_is_lon(lon)
geo.assert_is_lat(lat)
params = {'lon': lon, 'lat': lat}
json_data = self._uvapi.get_uvi(params)
uvindex = self._parsers['uvindex'].parse_JSON(json_data)
return uvindex | [
"def",
"uvindex_around_coords",
"(",
"self",
",",
"lat",
",",
"lon",
")",
":",
"geo",
".",
"assert_is_lon",
"(",
"lon",
")",
"geo",
".",
"assert_is_lat",
"(",
"lat",
")",
"params",
"=",
"{",
"'lon'",
":",
"lon",
",",
"'lat'",
":",
"lat",
"}",
"json_d... | Queries the OWM Weather API for Ultra Violet value sampled in the
surroundings of the provided geocoordinates and in the specified time
interval. A *UVIndex* object instance is returned, encapsulating a
*Location* object and the UV intensity value.
:param lat: the location's latitude, must be between -90.0 and 90.0
:type lat: int/float
:param lon: the location's longitude, must be between -180.0 and 180.0
:type lon: int/float
:return: a *UVIndex* instance or ``None`` if data is not available
:raises: *ParseResponseException* when OWM Weather API responses' data
cannot be parsed, *APICallException* when OWM Weather API can not be
reached, *ValueError* for wrong input values | [
"Queries",
"the",
"OWM",
"Weather",
"API",
"for",
"Ultra",
"Violet",
"value",
"sampled",
"in",
"the",
"surroundings",
"of",
"the",
"provided",
"geocoordinates",
"and",
"in",
"the",
"specified",
"time",
"interval",
".",
"A",
"*",
"UVIndex",
"*",
"object",
"in... | python | train |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/loader/archive.py | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/loader/archive.py#L177-L206 | def build(self, path, lTOC):
"""
Create an archive file of name 'path'.
lTOC is a 'logical TOC' - a list of (name, path, ...)
where name is the internal name, eg 'a'
and path is a file to get the object from, eg './a.pyc'.
"""
self.path = path
self.lib = open(path, 'wb')
#reserve space for the header
if self.HDRLEN:
self.lib.write('\0' * self.HDRLEN)
#create an empty toc
if type(self.TOCTMPLT) == type({}):
self.toc = {}
else: # assume callable
self.toc = self.TOCTMPLT()
for tocentry in lTOC:
self.add(tocentry) # the guts of the archive
tocpos = self.lib.tell()
self.save_toc(tocpos)
if self.TRLLEN:
self.save_trailer(tocpos)
if self.HDRLEN:
self.update_headers(tocpos)
self.lib.close() | [
"def",
"build",
"(",
"self",
",",
"path",
",",
"lTOC",
")",
":",
"self",
".",
"path",
"=",
"path",
"self",
".",
"lib",
"=",
"open",
"(",
"path",
",",
"'wb'",
")",
"#reserve space for the header",
"if",
"self",
".",
"HDRLEN",
":",
"self",
".",
"lib",
... | Create an archive file of name 'path'.
lTOC is a 'logical TOC' - a list of (name, path, ...)
where name is the internal name, eg 'a'
and path is a file to get the object from, eg './a.pyc'. | [
"Create",
"an",
"archive",
"file",
"of",
"name",
"path",
".",
"lTOC",
"is",
"a",
"logical",
"TOC",
"-",
"a",
"list",
"of",
"(",
"name",
"path",
"...",
")",
"where",
"name",
"is",
"the",
"internal",
"name",
"eg",
"a",
"and",
"path",
"is",
"a",
"file... | python | train |
atlassian-api/atlassian-python-api | atlassian/jira.py | https://github.com/atlassian-api/atlassian-python-api/blob/540d269905c3e7547b666fe30c647b2d512cf358/atlassian/jira.py#L1131-L1138 | def get_agile_board(self, board_id):
"""
Get agile board info by id
:param board_id:
:return:
"""
url = 'rest/agile/1.0/board/{}'.format(str(board_id))
return self.get(url) | [
"def",
"get_agile_board",
"(",
"self",
",",
"board_id",
")",
":",
"url",
"=",
"'rest/agile/1.0/board/{}'",
".",
"format",
"(",
"str",
"(",
"board_id",
")",
")",
"return",
"self",
".",
"get",
"(",
"url",
")"
] | Get agile board info by id
:param board_id:
:return: | [
"Get",
"agile",
"board",
"info",
"by",
"id",
":",
"param",
"board_id",
":",
":",
"return",
":"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.