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 |
|---|---|---|---|---|---|---|---|---|
uw-it-aca/uw-restclients-sws | uw_sws/section_status.py | https://github.com/uw-it-aca/uw-restclients-sws/blob/4d36776dcca36855fc15c1b8fe7650ae045194cf/uw_sws/section_status.py#L21-L52 | def _json_to_sectionstatus(section_data):
"""
Returns a uw_sws.models.SectionStatus object
created from the passed json.
"""
section_status = SectionStatus()
if section_data["AddCodeRequired"] == 'true':
section_status.add_code_required = True
else:
section_status.add_code_re... | [
"def",
"_json_to_sectionstatus",
"(",
"section_data",
")",
":",
"section_status",
"=",
"SectionStatus",
"(",
")",
"if",
"section_data",
"[",
"\"AddCodeRequired\"",
"]",
"==",
"'true'",
":",
"section_status",
".",
"add_code_required",
"=",
"True",
"else",
":",
"sec... | Returns a uw_sws.models.SectionStatus object
created from the passed json. | [
"Returns",
"a",
"uw_sws",
".",
"models",
".",
"SectionStatus",
"object",
"created",
"from",
"the",
"passed",
"json",
"."
] | python | train |
tensorflow/cleverhans | cleverhans_tutorials/tutorial_models_tfe.py | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/tutorial_models_tfe.py#L98-L111 | def get_params(self):
"""
Provides access to the model's parameters.
Works arounds the non-availability of graph collections in
eager mode.
:return: A list of all Variables defining the model parameters.
"""
assert tf.executing_eagerly()
out = []
# Collecting params ... | [
"def",
"get_params",
"(",
"self",
")",
":",
"assert",
"tf",
".",
"executing_eagerly",
"(",
")",
"out",
"=",
"[",
"]",
"# Collecting params from each layer.",
"for",
"layer_name",
"in",
"self",
".",
"layers",
":",
"out",
"+=",
"self",
".",
"get_layer_params",
... | Provides access to the model's parameters.
Works arounds the non-availability of graph collections in
eager mode.
:return: A list of all Variables defining the model parameters. | [
"Provides",
"access",
"to",
"the",
"model",
"s",
"parameters",
".",
"Works",
"arounds",
"the",
"non",
"-",
"availability",
"of",
"graph",
"collections",
"in",
"eager",
"mode",
".",
":",
"return",
":",
"A",
"list",
"of",
"all",
"Variables",
"defining",
"the... | python | train |
ethereum/py-evm | eth/db/journal.py | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/journal.py#L354-L361 | def _validate_changeset(self, changeset_id: uuid.UUID) -> None:
"""
Checks to be sure the changeset is known by the journal
"""
if not self.journal.has_changeset(changeset_id):
raise ValidationError("Changeset not found in journal: {0}".format(
str(changeset_i... | [
"def",
"_validate_changeset",
"(",
"self",
",",
"changeset_id",
":",
"uuid",
".",
"UUID",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"journal",
".",
"has_changeset",
"(",
"changeset_id",
")",
":",
"raise",
"ValidationError",
"(",
"\"Changeset not found ... | Checks to be sure the changeset is known by the journal | [
"Checks",
"to",
"be",
"sure",
"the",
"changeset",
"is",
"known",
"by",
"the",
"journal"
] | python | train |
Phyks/libbmc | libbmc/bibtex.py | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/bibtex.py#L156-L200 | def get_entry_by_filter(filename, filter_function, ignore_fields=None):
"""
Get an entry from a BibTeX file.
.. note ::
Returns the first matching entry.
:param filename: The name of the BibTeX file.
:param filter_function: A function returning ``True`` or ``False`` \
whether ... | [
"def",
"get_entry_by_filter",
"(",
"filename",
",",
"filter_function",
",",
"ignore_fields",
"=",
"None",
")",
":",
"# Handle default argument",
"if",
"ignore_fields",
"is",
"None",
":",
"ignore_fields",
"=",
"[",
"]",
"# Open bibtex file",
"with",
"open",
"(",
"f... | Get an entry from a BibTeX file.
.. note ::
Returns the first matching entry.
:param filename: The name of the BibTeX file.
:param filter_function: A function returning ``True`` or ``False`` \
whether the entry should be included or not.
:param ignore_fields: An optional list of f... | [
"Get",
"an",
"entry",
"from",
"a",
"BibTeX",
"file",
"."
] | python | train |
coursera-dl/coursera-dl | coursera/formatting.py | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/formatting.py#L25-L76 | def get_lecture_filename(combined_section_lectures_nums,
section_dir,
secnum,
lecnum,
lecname,
title,
fmt):
"""
Prepare a destination lecture filename.
@para... | [
"def",
"get_lecture_filename",
"(",
"combined_section_lectures_nums",
",",
"section_dir",
",",
"secnum",
",",
"lecnum",
",",
"lecname",
",",
"title",
",",
"fmt",
")",
":",
"# FIXME: this is a quick and dirty solution to Filename too long",
"# problem. We need to think of a more... | Prepare a destination lecture filename.
@param combined_section_lectures_nums: Flag that indicates whether
section lectures should have combined numbering.
@type combined_section_lectures_nums: bool
@param section_dir: Path to current section directory.
@type section_dir: str
@param secnu... | [
"Prepare",
"a",
"destination",
"lecture",
"filename",
"."
] | python | train |
apache/incubator-mxnet | python/mxnet/image/detection.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L113-L115 | def dumps(self):
"""Override default."""
return [self.__class__.__name__.lower(), [x.dumps() for x in self.aug_list]] | [
"def",
"dumps",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"__class__",
".",
"__name__",
".",
"lower",
"(",
")",
",",
"[",
"x",
".",
"dumps",
"(",
")",
"for",
"x",
"in",
"self",
".",
"aug_list",
"]",
"]"
] | Override default. | [
"Override",
"default",
"."
] | python | train |
mitsei/dlkit | dlkit/records/assessment/edx/drag_and_drop_records.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/records/assessment/edx/drag_and_drop_records.py#L74-L79 | def _init_map(self):
"""stub"""
super(EdXDragAndDropQuestionFormRecord, self)._init_map()
QuestionTextFormRecord._init_map(self)
QuestionFilesFormRecord._init_map(self)
self.my_osid_object_form._my_map['text']['text'] = '' | [
"def",
"_init_map",
"(",
"self",
")",
":",
"super",
"(",
"EdXDragAndDropQuestionFormRecord",
",",
"self",
")",
".",
"_init_map",
"(",
")",
"QuestionTextFormRecord",
".",
"_init_map",
"(",
"self",
")",
"QuestionFilesFormRecord",
".",
"_init_map",
"(",
"self",
")"... | stub | [
"stub"
] | python | train |
GearPlug/payu-python | payu/tokenization.py | https://github.com/GearPlug/payu-python/blob/47ec5c9fc89f1f89a53ec0a68c84f358bbe3394e/payu/tokenization.py#L12-L44 | def create_single_token(self, *, payer_id, name, identification_number, payment_method, number, expiration_date):
"""
Using this feature you can register a customer’s credit card data and get a token sequential number.
Args:
payer_id:
name:
identification_num... | [
"def",
"create_single_token",
"(",
"self",
",",
"*",
",",
"payer_id",
",",
"name",
",",
"identification_number",
",",
"payment_method",
",",
"number",
",",
"expiration_date",
")",
":",
"payload",
"=",
"{",
"\"language\"",
":",
"self",
".",
"client",
".",
"la... | Using this feature you can register a customer’s credit card data and get a token sequential number.
Args:
payer_id:
name:
identification_number:
payment_method:
number:
expiration_date:
Returns: | [
"Using",
"this",
"feature",
"you",
"can",
"register",
"a",
"customer’s",
"credit",
"card",
"data",
"and",
"get",
"a",
"token",
"sequential",
"number",
"."
] | python | train |
petebachant/PXL | pxl/timeseries.py | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/timeseries.py#L146-L153 | def integral_scale(u, t, tau1=0.0, tau2=1.0):
"""Calculate the integral scale of a time series by integrating up to
the first zero crossing.
"""
tau, rho = autocorr_coeff(u, t, tau1, tau2)
zero_cross_ind = np.where(np.diff(np.sign(rho)))[0][0]
int_scale = np.trapz(rho[:zero_cross_ind], tau... | [
"def",
"integral_scale",
"(",
"u",
",",
"t",
",",
"tau1",
"=",
"0.0",
",",
"tau2",
"=",
"1.0",
")",
":",
"tau",
",",
"rho",
"=",
"autocorr_coeff",
"(",
"u",
",",
"t",
",",
"tau1",
",",
"tau2",
")",
"zero_cross_ind",
"=",
"np",
".",
"where",
"(",
... | Calculate the integral scale of a time series by integrating up to
the first zero crossing. | [
"Calculate",
"the",
"integral",
"scale",
"of",
"a",
"time",
"series",
"by",
"integrating",
"up",
"to",
"the",
"first",
"zero",
"crossing",
"."
] | python | train |
numan/py-analytics | analytics/__init__.py | https://github.com/numan/py-analytics/blob/abbc814925c6cc200b3329c7de9f1868e1cb8c01/analytics/__init__.py#L27-L55 | def create_analytic_backend(settings):
"""
Creates a new Analytics backend from the settings
:param settings: Dictionary of settings for the analytics backend
:returns: A backend object implementing the analytics api
>>>
>>> analytics = create_analytic({
>>> 'backend': 'analytics.backe... | [
"def",
"create_analytic_backend",
"(",
"settings",
")",
":",
"backend",
"=",
"settings",
".",
"get",
"(",
"'backend'",
")",
"if",
"isinstance",
"(",
"backend",
",",
"basestring",
")",
":",
"backend",
"=",
"import_string",
"(",
"backend",
")",
"elif",
"backen... | Creates a new Analytics backend from the settings
:param settings: Dictionary of settings for the analytics backend
:returns: A backend object implementing the analytics api
>>>
>>> analytics = create_analytic({
>>> 'backend': 'analytics.backends.redis.Redis',
>>> 'settings': {
>>>... | [
"Creates",
"a",
"new",
"Analytics",
"backend",
"from",
"the",
"settings"
] | python | train |
wright-group/WrightTools | WrightTools/artists/_quick.py | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_quick.py#L163-L377 | def quick2D(
data,
xaxis=0,
yaxis=1,
at={},
channel=0,
*,
contours=0,
pixelated=True,
dynamic_range=False,
local=False,
contours_local=True,
autosave=False,
save_directory=None,
fname=None,
verbose=True
):
"""Quickly plot 2D slice(s) of data.
Paramete... | [
"def",
"quick2D",
"(",
"data",
",",
"xaxis",
"=",
"0",
",",
"yaxis",
"=",
"1",
",",
"at",
"=",
"{",
"}",
",",
"channel",
"=",
"0",
",",
"*",
",",
"contours",
"=",
"0",
",",
"pixelated",
"=",
"True",
",",
"dynamic_range",
"=",
"False",
",",
"loc... | Quickly plot 2D slice(s) of data.
Parameters
----------
data : WrightTools.Data object.
Data to plot.
xaxis : string or integer (optional)
Expression or index of horizontal axis. Default is 0.
yaxis : string or integer (optional)
Expression or index of vertical axis. Default... | [
"Quickly",
"plot",
"2D",
"slice",
"(",
"s",
")",
"of",
"data",
"."
] | python | train |
cokelaer/spectrum | doc/sphinxext/sphinx_gallery/gen_rst.py | https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/doc/sphinxext/sphinx_gallery/gen_rst.py#L335-L377 | def scale_image(in_fname, out_fname, max_width, max_height):
"""Scales an image with the same aspect ratio centered in an
image with a given max_width and max_height
if in_fname == out_fname the image can only be scaled down
"""
# local import to avoid testing dependency on PIL:
try:
... | [
"def",
"scale_image",
"(",
"in_fname",
",",
"out_fname",
",",
"max_width",
",",
"max_height",
")",
":",
"# local import to avoid testing dependency on PIL:",
"try",
":",
"from",
"PIL",
"import",
"Image",
"except",
"ImportError",
":",
"import",
"Image",
"img",
"=",
... | Scales an image with the same aspect ratio centered in an
image with a given max_width and max_height
if in_fname == out_fname the image can only be scaled down | [
"Scales",
"an",
"image",
"with",
"the",
"same",
"aspect",
"ratio",
"centered",
"in",
"an",
"image",
"with",
"a",
"given",
"max_width",
"and",
"max_height",
"if",
"in_fname",
"==",
"out_fname",
"the",
"image",
"can",
"only",
"be",
"scaled",
"down"
] | python | valid |
dw/mitogen | ansible_mitogen/strategy.py | https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/ansible_mitogen/strategy.py#L43-L66 | def _patch_awx_callback():
"""
issue #400: AWX loads a display callback that suffers from thread-safety
issues. Detect the presence of older AWX versions and patch the bug.
"""
# AWX uses sitecustomize.py to force-load this package. If it exists, we're
# running under AWX.
try:
from ... | [
"def",
"_patch_awx_callback",
"(",
")",
":",
"# AWX uses sitecustomize.py to force-load this package. If it exists, we're",
"# running under AWX.",
"try",
":",
"from",
"awx_display_callback",
".",
"events",
"import",
"EventContext",
"from",
"awx_display_callback",
".",
"events",
... | issue #400: AWX loads a display callback that suffers from thread-safety
issues. Detect the presence of older AWX versions and patch the bug. | [
"issue",
"#400",
":",
"AWX",
"loads",
"a",
"display",
"callback",
"that",
"suffers",
"from",
"thread",
"-",
"safety",
"issues",
".",
"Detect",
"the",
"presence",
"of",
"older",
"AWX",
"versions",
"and",
"patch",
"the",
"bug",
"."
] | python | train |
saltstack/salt | salt/utils/event.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/event.py#L1327-L1356 | def fire_master(self, data, tag, preload=None):
'''
Fire an event off on the master server
CLI Example:
.. code-block:: bash
salt '*' event.fire_master 'stuff to be in the event' 'tag'
'''
load = {}
if preload:
load.update(preload)
... | [
"def",
"fire_master",
"(",
"self",
",",
"data",
",",
"tag",
",",
"preload",
"=",
"None",
")",
":",
"load",
"=",
"{",
"}",
"if",
"preload",
":",
"load",
".",
"update",
"(",
"preload",
")",
"load",
".",
"update",
"(",
"{",
"'id'",
":",
"self",
".",... | Fire an event off on the master server
CLI Example:
.. code-block:: bash
salt '*' event.fire_master 'stuff to be in the event' 'tag' | [
"Fire",
"an",
"event",
"off",
"on",
"the",
"master",
"server"
] | python | train |
tanghaibao/jcvi | jcvi/compara/catalog.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/compara/catalog.py#L354-L373 | def omgparse(args):
"""
%prog omgparse work
Parse the OMG outputs to get gene lists.
"""
p = OptionParser(omgparse.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
work, = args
omgfiles = glob(op.join(work, "gf*.out"))
for omgfil... | [
"def",
"omgparse",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"omgparse",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"sys",
".",
"exit",
"(",
... | %prog omgparse work
Parse the OMG outputs to get gene lists. | [
"%prog",
"omgparse",
"work"
] | python | train |
saltstack/salt | salt/modules/redismod.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L132-L143 | def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize() | [
"def",
"dbsize",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
"return",
"server",
".",
"d... | Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize | [
"Return",
"the",
"number",
"of",
"keys",
"in",
"the",
"selected",
"database"
] | python | train |
google/dotty | efilter/dispatch.py | https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/dispatch.py#L254-L335 | def _find_and_cache_best_function(self, dispatch_type):
"""Finds the best implementation of this function given a type.
This function caches the result, and uses locking for thread safety.
Returns:
Implementing function, in below order of preference:
1. Explicitly regis... | [
"def",
"_find_and_cache_best_function",
"(",
"self",
",",
"dispatch_type",
")",
":",
"result",
"=",
"self",
".",
"_dispatch_table",
".",
"get",
"(",
"dispatch_type",
")",
"if",
"result",
":",
"return",
"result",
"# The outer try ensures the lock is always released.",
... | Finds the best implementation of this function given a type.
This function caches the result, and uses locking for thread safety.
Returns:
Implementing function, in below order of preference:
1. Explicitly registered implementations (through
multimethod.implement... | [
"Finds",
"the",
"best",
"implementation",
"of",
"this",
"function",
"given",
"a",
"type",
"."
] | python | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/install.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/install.py#L55-L100 | def scons_copytree(src, dst, symlinks=False):
"""Recursively copy a directory tree using copy2().
The destination directory must not already exist.
If exception(s) occur, an CopytreeError is raised with a list of reasons.
If the optional symlinks flag is true, symbolic links in the
source tree res... | [
"def",
"scons_copytree",
"(",
"src",
",",
"dst",
",",
"symlinks",
"=",
"False",
")",
":",
"names",
"=",
"os",
".",
"listdir",
"(",
"src",
")",
"# garyo@genarts.com fix: check for dir before making dirs.",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"... | Recursively copy a directory tree using copy2().
The destination directory must not already exist.
If exception(s) occur, an CopytreeError is raised with a list of reasons.
If the optional symlinks flag is true, symbolic links in the
source tree result in symbolic links in the destination tree; if
... | [
"Recursively",
"copy",
"a",
"directory",
"tree",
"using",
"copy2",
"()",
"."
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/zmq/zmqshell.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/zmqshell.py#L494-L509 | def init_environment(self):
"""Configure the user's environment.
"""
env = os.environ
# These two ensure 'ls' produces nice coloring on BSD-derived systems
env['TERM'] = 'xterm-color'
env['CLICOLOR'] = '1'
# Since normal pagers don't work at all (over pexpect we ... | [
"def",
"init_environment",
"(",
"self",
")",
":",
"env",
"=",
"os",
".",
"environ",
"# These two ensure 'ls' produces nice coloring on BSD-derived systems",
"env",
"[",
"'TERM'",
"]",
"=",
"'xterm-color'",
"env",
"[",
"'CLICOLOR'",
"]",
"=",
"'1'",
"# Since normal pag... | Configure the user's environment. | [
"Configure",
"the",
"user",
"s",
"environment",
"."
] | python | test |
Dentosal/python-sc2 | sc2/client.py | https://github.com/Dentosal/python-sc2/blob/608bd25f04e89d39cef68b40101d8e9a8a7f1634/sc2/client.py#L350-L380 | async def debug_text(self, texts: Union[str, list], positions: Union[list, set], color=(0, 255, 0), size_px=16):
""" Deprecated, may be removed soon """
if isinstance(positions, (set, list)):
if not positions:
return
if isinstance(texts, str):
tex... | [
"async",
"def",
"debug_text",
"(",
"self",
",",
"texts",
":",
"Union",
"[",
"str",
",",
"list",
"]",
",",
"positions",
":",
"Union",
"[",
"list",
",",
"set",
"]",
",",
"color",
"=",
"(",
"0",
",",
"255",
",",
"0",
")",
",",
"size_px",
"=",
"16"... | Deprecated, may be removed soon | [
"Deprecated",
"may",
"be",
"removed",
"soon"
] | python | train |
squaresLab/BugZoo | bugzoo/client/container.py | https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/client/container.py#L295-L342 | def exec(self,
container: Container,
command: str,
context: Optional[str] = None,
stdout: bool = True,
stderr: bool = False,
time_limit: Optional[int] = None
) -> ExecResponse:
"""
Executes a given command inside ... | [
"def",
"exec",
"(",
"self",
",",
"container",
":",
"Container",
",",
"command",
":",
"str",
",",
"context",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"stdout",
":",
"bool",
"=",
"True",
",",
"stderr",
":",
"bool",
"=",
"False",
",",
"time... | Executes a given command inside a provided container.
Parameters:
container: the container to which the command should be issued.
command: the command that should be executed.
context: the working directory that should be used to perform the
execution. If no ... | [
"Executes",
"a",
"given",
"command",
"inside",
"a",
"provided",
"container",
"."
] | python | train |
openpermissions/perch | perch/migrate.py | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/migrate.py#L153-L173 | def run_migrations(migrations):
"""
Run migrations for a resource type
:param: a dicitionary of migrations
"""
for resource, resource_migrations in migrations.items():
for version in resource_migrations:
to_migrate = yield resource_version.get(
key=[resource.reso... | [
"def",
"run_migrations",
"(",
"migrations",
")",
":",
"for",
"resource",
",",
"resource_migrations",
"in",
"migrations",
".",
"items",
"(",
")",
":",
"for",
"version",
"in",
"resource_migrations",
":",
"to_migrate",
"=",
"yield",
"resource_version",
".",
"get",
... | Run migrations for a resource type
:param: a dicitionary of migrations | [
"Run",
"migrations",
"for",
"a",
"resource",
"type"
] | python | train |
crytic/slither | slither/printers/summary/data_depenency.py | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/printers/summary/data_depenency.py#L21-L46 | def output(self, _filename):
"""
_filename is not used
Args:
_filename(string)
"""
txt = ''
for c in self.contracts:
txt += "\nContract %s\n"%c.name
table = PrettyTable(['Variable', 'Dependencies'])
for v in c.s... | [
"def",
"output",
"(",
"self",
",",
"_filename",
")",
":",
"txt",
"=",
"''",
"for",
"c",
"in",
"self",
".",
"contracts",
":",
"txt",
"+=",
"\"\\nContract %s\\n\"",
"%",
"c",
".",
"name",
"table",
"=",
"PrettyTable",
"(",
"[",
"'Variable'",
",",
"'Depend... | _filename is not used
Args:
_filename(string) | [
"_filename",
"is",
"not",
"used",
"Args",
":",
"_filename",
"(",
"string",
")"
] | python | train |
osrg/ryu | ryu/services/protocols/bgp/api/rtconf.py | https://github.com/osrg/ryu/blob/6f906e72c92e10bd0264c9b91a2f7bb85b97780c/ryu/services/protocols/bgp/api/rtconf.py#L198-L211 | def get_neighbor_attribute_map(neigh_ip_address, route_dist=None,
route_family=VRF_RF_IPV4):
"""Returns a neighbor attribute_map for given ip address if exists."""
core = CORE_MANAGER.get_core_service()
peer = core.peer_manager.get_by_addr(neigh_ip_address)
at_maps_key = c... | [
"def",
"get_neighbor_attribute_map",
"(",
"neigh_ip_address",
",",
"route_dist",
"=",
"None",
",",
"route_family",
"=",
"VRF_RF_IPV4",
")",
":",
"core",
"=",
"CORE_MANAGER",
".",
"get_core_service",
"(",
")",
"peer",
"=",
"core",
".",
"peer_manager",
".",
"get_b... | Returns a neighbor attribute_map for given ip address if exists. | [
"Returns",
"a",
"neighbor",
"attribute_map",
"for",
"given",
"ip",
"address",
"if",
"exists",
"."
] | python | train |
kensho-technologies/graphql-compiler | graphql_compiler/query_formatting/gremlin_formatting.py | https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/query_formatting/gremlin_formatting.py#L81-L92 | def _safe_gremlin_list(inner_type, argument_value):
"""Represent the list of "inner_type" objects in Gremlin form."""
if not isinstance(argument_value, list):
raise GraphQLInvalidArgumentError(u'Attempting to represent a non-list as a list: '
u'{}'.format(argume... | [
"def",
"_safe_gremlin_list",
"(",
"inner_type",
",",
"argument_value",
")",
":",
"if",
"not",
"isinstance",
"(",
"argument_value",
",",
"list",
")",
":",
"raise",
"GraphQLInvalidArgumentError",
"(",
"u'Attempting to represent a non-list as a list: '",
"u'{}'",
".",
"for... | Represent the list of "inner_type" objects in Gremlin form. | [
"Represent",
"the",
"list",
"of",
"inner_type",
"objects",
"in",
"Gremlin",
"form",
"."
] | python | train |
mitsei/dlkit | dlkit/services/assessment.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/services/assessment.py#L891-L899 | def use_plenary_bank_view(self):
"""Pass through to provider ItemBankSession.use_plenary_bank_view"""
self._bank_view = PLENARY
# self._get_provider_session('item_bank_session') # To make sure the session is tracked
for session in self._get_provider_sessions():
try:
... | [
"def",
"use_plenary_bank_view",
"(",
"self",
")",
":",
"self",
".",
"_bank_view",
"=",
"PLENARY",
"# self._get_provider_session('item_bank_session') # To make sure the session is tracked",
"for",
"session",
"in",
"self",
".",
"_get_provider_sessions",
"(",
")",
":",
"try",
... | Pass through to provider ItemBankSession.use_plenary_bank_view | [
"Pass",
"through",
"to",
"provider",
"ItemBankSession",
".",
"use_plenary_bank_view"
] | python | train |
lowandrew/OLCTools | spadespipeline/GeneSeekr.py | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/spadespipeline/GeneSeekr.py#L151-L171 | def makeblastdb(self):
"""Makes blast database files from targets as necessary"""
while True: # while daemon
fastapath = self.dqueue.get() # grabs fastapath from dqueue
# remove the path and the file extension for easier future globbing
db = os.path.splitext(fastapa... | [
"def",
"makeblastdb",
"(",
"self",
")",
":",
"while",
"True",
":",
"# while daemon",
"fastapath",
"=",
"self",
".",
"dqueue",
".",
"get",
"(",
")",
"# grabs fastapath from dqueue",
"# remove the path and the file extension for easier future globbing",
"db",
"=",
"os",
... | Makes blast database files from targets as necessary | [
"Makes",
"blast",
"database",
"files",
"from",
"targets",
"as",
"necessary"
] | python | train |
mikeboers/PyAV | setup.py | https://github.com/mikeboers/PyAV/blob/9414187088b9b8dbaa180cfe1db6ceba243184ea/setup.py#L76-L97 | def get_library_config(name):
"""Get distutils-compatible extension extras for the given library.
This requires ``pkg-config``.
"""
try:
proc = Popen(['pkg-config', '--cflags', '--libs', name], stdout=PIPE, stderr=PIPE)
except OSError:
print('pkg-config is required for building PyA... | [
"def",
"get_library_config",
"(",
"name",
")",
":",
"try",
":",
"proc",
"=",
"Popen",
"(",
"[",
"'pkg-config'",
",",
"'--cflags'",
",",
"'--libs'",
",",
"name",
"]",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"PIPE",
")",
"except",
"OSError",
":",... | Get distutils-compatible extension extras for the given library.
This requires ``pkg-config``. | [
"Get",
"distutils",
"-",
"compatible",
"extension",
"extras",
"for",
"the",
"given",
"library",
"."
] | python | valid |
fastai/fastai | docs_src/nbval/plugin.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/plugin.py#L135-L160 | def find_comment_markers(cellsource):
"""Look through the cell source for comments which affect nbval's behaviour
Yield an iterable of ``(MARKER_TYPE, True)``.
"""
found = {}
for line in cellsource.splitlines():
line = line.strip()
if line.startswith('#'):
# print("Found... | [
"def",
"find_comment_markers",
"(",
"cellsource",
")",
":",
"found",
"=",
"{",
"}",
"for",
"line",
"in",
"cellsource",
".",
"splitlines",
"(",
")",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
".",
"startswith",
"(",
"'#'",
")",
":... | Look through the cell source for comments which affect nbval's behaviour
Yield an iterable of ``(MARKER_TYPE, True)``. | [
"Look",
"through",
"the",
"cell",
"source",
"for",
"comments",
"which",
"affect",
"nbval",
"s",
"behaviour"
] | python | train |
nirum/descent | descent/objectives.py | https://github.com/nirum/descent/blob/074c8452f15a0da638668a4fe139fde06ccfae7f/descent/objectives.py#L44-L51 | def doublewell(theta):
"""Pointwise minimum of two quadratic bowls"""
k0, k1, depth = 0.01, 100, 0.5
shallow = 0.5 * k0 * theta ** 2 + depth
deep = 0.5 * k1 * theta ** 2
obj = float(np.minimum(shallow, deep))
grad = np.where(deep < shallow, k1 * theta, k0 * theta)
return obj, grad | [
"def",
"doublewell",
"(",
"theta",
")",
":",
"k0",
",",
"k1",
",",
"depth",
"=",
"0.01",
",",
"100",
",",
"0.5",
"shallow",
"=",
"0.5",
"*",
"k0",
"*",
"theta",
"**",
"2",
"+",
"depth",
"deep",
"=",
"0.5",
"*",
"k1",
"*",
"theta",
"**",
"2",
... | Pointwise minimum of two quadratic bowls | [
"Pointwise",
"minimum",
"of",
"two",
"quadratic",
"bowls"
] | python | valid |
libyal/dtfabric | dtfabric/reader.py | https://github.com/libyal/dtfabric/blob/0d2b5719fa257f6e5c661a406737ebcf8c8db266/dtfabric/reader.py#L1078-L1100 | def _ReadUnionDataTypeDefinition(
self, definitions_registry, definition_values, definition_name,
is_member=False):
"""Reads an union data type definition.
Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
registry.
definition_values (dict[str, ob... | [
"def",
"_ReadUnionDataTypeDefinition",
"(",
"self",
",",
"definitions_registry",
",",
"definition_values",
",",
"definition_name",
",",
"is_member",
"=",
"False",
")",
":",
"return",
"self",
".",
"_ReadDataTypeDefinitionWithMembers",
"(",
"definitions_registry",
",",
"d... | Reads an union data type definition.
Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
registry.
definition_values (dict[str, object]): definition values.
definition_name (str): name of the definition.
is_member (Optional[bool]): True if the data type... | [
"Reads",
"an",
"union",
"data",
"type",
"definition",
"."
] | python | train |
revelc/pyaccumulo | pyaccumulo/proxy/AccumuloProxy.py | https://github.com/revelc/pyaccumulo/blob/8adcf535bb82ba69c749efce785c9efc487e85de/pyaccumulo/proxy/AccumuloProxy.py#L1765-L1773 | def removeTableProperty(self, login, tableName, property):
"""
Parameters:
- login
- tableName
- property
"""
self.send_removeTableProperty(login, tableName, property)
self.recv_removeTableProperty() | [
"def",
"removeTableProperty",
"(",
"self",
",",
"login",
",",
"tableName",
",",
"property",
")",
":",
"self",
".",
"send_removeTableProperty",
"(",
"login",
",",
"tableName",
",",
"property",
")",
"self",
".",
"recv_removeTableProperty",
"(",
")"
] | Parameters:
- login
- tableName
- property | [
"Parameters",
":",
"-",
"login",
"-",
"tableName",
"-",
"property"
] | python | train |
utek/pyseaweed | pyseaweed/utils.py | https://github.com/utek/pyseaweed/blob/218049329885425a2b8370157fa44952e64516be/pyseaweed/utils.py#L41-L48 | def head(self, url, *args, **kwargs):
"""Returns response to http HEAD
on provided url
"""
res = self._conn.head(url, headers=self._prepare_headers(**kwargs))
if res.status_code == 200:
return res
return None | [
"def",
"head",
"(",
"self",
",",
"url",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"res",
"=",
"self",
".",
"_conn",
".",
"head",
"(",
"url",
",",
"headers",
"=",
"self",
".",
"_prepare_headers",
"(",
"*",
"*",
"kwargs",
")",
")",
"if... | Returns response to http HEAD
on provided url | [
"Returns",
"response",
"to",
"http",
"HEAD",
"on",
"provided",
"url"
] | python | train |
phaethon/kamene | kamene/crypto/cert.py | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/crypto/cert.py#L605-L661 | def _rsaes_pkcs1_v1_5_decrypt(self, C):
"""
Implements RSAES-PKCS1-V1_5-DECRYPT() function described in section
7.2.2 of RFC 3447.
Input:
C: ciphertext to be decrypted, an octet string of length k, where
k is the length in octets of the RSA modulus n.
O... | [
"def",
"_rsaes_pkcs1_v1_5_decrypt",
"(",
"self",
",",
"C",
")",
":",
"# 1) Length checking",
"cLen",
"=",
"len",
"(",
"C",
")",
"k",
"=",
"self",
".",
"modulusLen",
"/",
"8",
"if",
"cLen",
"!=",
"k",
"or",
"k",
"<",
"11",
":",
"warning",
"(",
"\"Key.... | Implements RSAES-PKCS1-V1_5-DECRYPT() function described in section
7.2.2 of RFC 3447.
Input:
C: ciphertext to be decrypted, an octet string of length k, where
k is the length in octets of the RSA modulus n.
Output:
an octet string of length k at most k - 11... | [
"Implements",
"RSAES",
"-",
"PKCS1",
"-",
"V1_5",
"-",
"DECRYPT",
"()",
"function",
"described",
"in",
"section",
"7",
".",
"2",
".",
"2",
"of",
"RFC",
"3447",
"."
] | python | train |
SteveMcGrath/pySecurityCenter | securitycenter/base.py | https://github.com/SteveMcGrath/pySecurityCenter/blob/f0b10b1bcd4fd23a8d4d09ca6774cdf5e1cfd880/securitycenter/base.py#L90-L96 | def post(self, path, **kwargs):
'''Calls the specified path with the POST method'''
resp = self._session.post(self._url(path), **self._builder(**kwargs))
if 'stream' in kwargs:
return resp
else:
return self._resp_error_check(resp) | [
"def",
"post",
"(",
"self",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"resp",
"=",
"self",
".",
"_session",
".",
"post",
"(",
"self",
".",
"_url",
"(",
"path",
")",
",",
"*",
"*",
"self",
".",
"_builder",
"(",
"*",
"*",
"kwargs",
")",
"... | Calls the specified path with the POST method | [
"Calls",
"the",
"specified",
"path",
"with",
"the",
"POST",
"method"
] | python | train |
BernardFW/bernard | src/bernard/i18n/_formatter.py | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/_formatter.py#L80-L85 | def format_date(self, value, format_):
"""
Format the date using Babel
"""
date_ = make_date(value)
return dates.format_date(date_, format_, locale=self.lang) | [
"def",
"format_date",
"(",
"self",
",",
"value",
",",
"format_",
")",
":",
"date_",
"=",
"make_date",
"(",
"value",
")",
"return",
"dates",
".",
"format_date",
"(",
"date_",
",",
"format_",
",",
"locale",
"=",
"self",
".",
"lang",
")"
] | Format the date using Babel | [
"Format",
"the",
"date",
"using",
"Babel"
] | python | train |
tomnor/channelpack | channelpack/pack.py | https://github.com/tomnor/channelpack/blob/9ad3cd11c698aed4c0fc178385b2ba38a7d0efae/channelpack/pack.py#L344-L402 | def rebase(self, key, start=None, decimals=5):
"""Rebase a channel (key) on start.
The step (between elements) need to be constant all through,
else ValueError is raised. The exception to this is the border
step between data loaded from two different files.
key: int or str
... | [
"def",
"rebase",
"(",
"self",
",",
"key",
",",
"start",
"=",
"None",
",",
"decimals",
"=",
"5",
")",
":",
"diffs",
"=",
"[",
"]",
"def",
"diffsappend",
"(",
"d",
",",
"sc",
")",
":",
"diff",
"=",
"np",
".",
"around",
"(",
"np",
".",
"diff",
"... | Rebase a channel (key) on start.
The step (between elements) need to be constant all through,
else ValueError is raised. The exception to this is the border
step between data loaded from two different files.
key: int or str
The key for the channel to rebase.
start:... | [
"Rebase",
"a",
"channel",
"(",
"key",
")",
"on",
"start",
"."
] | python | train |
LEMS/pylems | lems/parser/LEMS.py | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/parser/LEMS.py#L655-L680 | def parse_event_writer(self, node):
"""
Parses <EventWriter>
@param node: Node containing the <EventWriter> element
@type node: xml.etree.Element
"""
if 'path' in node.lattrib:
path = node.lattrib['path']
else:
self.raise_error('<EventWri... | [
"def",
"parse_event_writer",
"(",
"self",
",",
"node",
")",
":",
"if",
"'path'",
"in",
"node",
".",
"lattrib",
":",
"path",
"=",
"node",
".",
"lattrib",
"[",
"'path'",
"]",
"else",
":",
"self",
".",
"raise_error",
"(",
"'<EventWriter> must specify a path.'",... | Parses <EventWriter>
@param node: Node containing the <EventWriter> element
@type node: xml.etree.Element | [
"Parses",
"<EventWriter",
">"
] | python | train |
tkem/uritools | uritools/split.py | https://github.com/tkem/uritools/blob/e77ba4acd937b68da9850138563debd4c925ef9f/uritools/split.py#L173-L176 | def getpath(self, encoding='utf-8', errors='strict'):
"""Return the normalized decoded URI path."""
path = self.__remove_dot_segments(self.path)
return uridecode(path, encoding, errors) | [
"def",
"getpath",
"(",
"self",
",",
"encoding",
"=",
"'utf-8'",
",",
"errors",
"=",
"'strict'",
")",
":",
"path",
"=",
"self",
".",
"__remove_dot_segments",
"(",
"self",
".",
"path",
")",
"return",
"uridecode",
"(",
"path",
",",
"encoding",
",",
"errors"... | Return the normalized decoded URI path. | [
"Return",
"the",
"normalized",
"decoded",
"URI",
"path",
"."
] | python | train |
OpenKMIP/PyKMIP | kmip/core/messages/payloads/get.py | https://github.com/OpenKMIP/PyKMIP/blob/b51c5b044bd05f8c85a1d65d13a583a4d8fc1b0e/kmip/core/messages/payloads/get.py#L414-L470 | def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the data encoding the Get response payload and decode it
into its constituent parts.
Args:
input_stream (stream): A data stream containing encoded object
data, supporting a read m... | [
"def",
"read",
"(",
"self",
",",
"input_stream",
",",
"kmip_version",
"=",
"enums",
".",
"KMIPVersion",
".",
"KMIP_1_0",
")",
":",
"super",
"(",
"GetResponsePayload",
",",
"self",
")",
".",
"read",
"(",
"input_stream",
",",
"kmip_version",
"=",
"kmip_version... | Read the data encoding the Get response payload and decode it
into its constituent parts.
Args:
input_stream (stream): A data stream containing encoded object
data, supporting a read method; usually a BytearrayStream
object.
kmip_version (KMIPVers... | [
"Read",
"the",
"data",
"encoding",
"the",
"Get",
"response",
"payload",
"and",
"decode",
"it",
"into",
"its",
"constituent",
"parts",
"."
] | python | test |
robertmartin8/PyPortfolioOpt | pypfopt/efficient_frontier.py | https://github.com/robertmartin8/PyPortfolioOpt/blob/dfad1256cb6995c7fbd7a025eedb54b1ca04b2fc/pypfopt/efficient_frontier.py#L257-L276 | def portfolio_performance(self, verbose=False, risk_free_rate=0.02):
"""
After optimising, calculate (and optionally print) the performance of the optimal
portfolio. Currently calculates expected return, volatility, and the Sharpe ratio.
:param verbose: whether performance should be pri... | [
"def",
"portfolio_performance",
"(",
"self",
",",
"verbose",
"=",
"False",
",",
"risk_free_rate",
"=",
"0.02",
")",
":",
"return",
"base_optimizer",
".",
"portfolio_performance",
"(",
"self",
".",
"expected_returns",
",",
"self",
".",
"cov_matrix",
",",
"self",
... | After optimising, calculate (and optionally print) the performance of the optimal
portfolio. Currently calculates expected return, volatility, and the Sharpe ratio.
:param verbose: whether performance should be printed, defaults to False
:type verbose: bool, optional
:param risk_free_ra... | [
"After",
"optimising",
"calculate",
"(",
"and",
"optionally",
"print",
")",
"the",
"performance",
"of",
"the",
"optimal",
"portfolio",
".",
"Currently",
"calculates",
"expected",
"return",
"volatility",
"and",
"the",
"Sharpe",
"ratio",
"."
] | python | train |
PedalPi/Raspberry-Physical | physical/liquidcristal/liquid_crystal.py | https://github.com/PedalPi/Raspberry-Physical/blob/3dc71b6997ef36d0de256c5db7a1b38178937fd5/physical/liquidcristal/liquid_crystal.py#L149-L155 | def home(self):
"""Return to initial position (row=0, column=0)"""
self.row = 0
self.column = 0
self.command(Command.RETURN_HOME)
msleep(2) | [
"def",
"home",
"(",
"self",
")",
":",
"self",
".",
"row",
"=",
"0",
"self",
".",
"column",
"=",
"0",
"self",
".",
"command",
"(",
"Command",
".",
"RETURN_HOME",
")",
"msleep",
"(",
"2",
")"
] | Return to initial position (row=0, column=0) | [
"Return",
"to",
"initial",
"position",
"(",
"row",
"=",
"0",
"column",
"=",
"0",
")"
] | python | train |
CI-WATER/gsshapy | gsshapy/util/context.py | https://github.com/CI-WATER/gsshapy/blob/00fd4af0fd65f1614d75a52fe950a04fb0867f4c/gsshapy/util/context.py#L13-L20 | def tmp_chdir(new_path):
"""Change directory temporarily and return when done."""
prev_cwd = os.getcwd()
os.chdir(new_path)
try:
yield
finally:
os.chdir(prev_cwd) | [
"def",
"tmp_chdir",
"(",
"new_path",
")",
":",
"prev_cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"os",
".",
"chdir",
"(",
"new_path",
")",
"try",
":",
"yield",
"finally",
":",
"os",
".",
"chdir",
"(",
"prev_cwd",
")"
] | Change directory temporarily and return when done. | [
"Change",
"directory",
"temporarily",
"and",
"return",
"when",
"done",
"."
] | python | train |
PmagPy/PmagPy | programs/magic_gui.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/magic_gui.py#L557-L563 | def on_close_grid(self, event):
"""
If there is an open grid, save its data and close it.
"""
if self.parent.grid_frame:
self.parent.grid_frame.onSave(None)
self.parent.grid_frame.Destroy() | [
"def",
"on_close_grid",
"(",
"self",
",",
"event",
")",
":",
"if",
"self",
".",
"parent",
".",
"grid_frame",
":",
"self",
".",
"parent",
".",
"grid_frame",
".",
"onSave",
"(",
"None",
")",
"self",
".",
"parent",
".",
"grid_frame",
".",
"Destroy",
"(",
... | If there is an open grid, save its data and close it. | [
"If",
"there",
"is",
"an",
"open",
"grid",
"save",
"its",
"data",
"and",
"close",
"it",
"."
] | python | train |
log2timeline/dfvfs | dfvfs/helpers/command_line.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/command_line.py#L213-L237 | def _WriteRow(self, output_writer, values, in_bold=False):
"""Writes a row of values aligned with the width to the output writer.
Args:
output_writer (CLIOutputWriter): output writer.
values (list[object]): values.
in_bold (Optional[bool]): True if the row should be written in bold.
"""
... | [
"def",
"_WriteRow",
"(",
"self",
",",
"output_writer",
",",
"values",
",",
"in_bold",
"=",
"False",
")",
":",
"row_strings",
"=",
"[",
"]",
"for",
"value_index",
",",
"value_string",
"in",
"enumerate",
"(",
"values",
")",
":",
"padding_size",
"=",
"self",
... | Writes a row of values aligned with the width to the output writer.
Args:
output_writer (CLIOutputWriter): output writer.
values (list[object]): values.
in_bold (Optional[bool]): True if the row should be written in bold. | [
"Writes",
"a",
"row",
"of",
"values",
"aligned",
"with",
"the",
"width",
"to",
"the",
"output",
"writer",
"."
] | python | train |
frasertweedale/ledgertools | ltlib/xn.py | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/xn.py#L168-L308 | def apply_outcomes(self, outcomes, uio, dropped=False, prevxn=None):
"""Apply the given outcomes to this rule.
If user intervention is required, outcomes are not applied
unless a ui.UI is supplied.
"""
if self.dropped and not dropped:
# do nothing for dropped xn, unl... | [
"def",
"apply_outcomes",
"(",
"self",
",",
"outcomes",
",",
"uio",
",",
"dropped",
"=",
"False",
",",
"prevxn",
"=",
"None",
")",
":",
"if",
"self",
".",
"dropped",
"and",
"not",
"dropped",
":",
"# do nothing for dropped xn, unless specifically told to",
"return... | Apply the given outcomes to this rule.
If user intervention is required, outcomes are not applied
unless a ui.UI is supplied. | [
"Apply",
"the",
"given",
"outcomes",
"to",
"this",
"rule",
"."
] | python | train |
sorgerlab/indra | indra/sources/reach/reader.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/reach/reader.py#L55-L69 | def get_api_ruler(self):
"""Return the existing reader if it exists or launch a new one.
Returns
-------
api_ruler : org.clulab.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object).
"""
if self.api_ruler is None:
try:
... | [
"def",
"get_api_ruler",
"(",
"self",
")",
":",
"if",
"self",
".",
"api_ruler",
"is",
"None",
":",
"try",
":",
"self",
".",
"api_ruler",
"=",
"autoclass",
"(",
"'org.clulab.reach.export.apis.ApiRuler'",
")",
"except",
"JavaException",
"as",
"e",
":",
"raise",
... | Return the existing reader if it exists or launch a new one.
Returns
-------
api_ruler : org.clulab.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object). | [
"Return",
"the",
"existing",
"reader",
"if",
"it",
"exists",
"or",
"launch",
"a",
"new",
"one",
"."
] | python | train |
Alveo/pyalveo | pyalveo/pyalveo.py | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L572-L619 | def api_request(self, url, data=None, method='GET', raw=False, file=None):
""" Perform an API request to the given URL, optionally
including the specified data
:type url: String
:param url: the URL to which to make the request
:type data: String
:param data: the data to ... | [
"def",
"api_request",
"(",
"self",
",",
"url",
",",
"data",
"=",
"None",
",",
"method",
"=",
"'GET'",
",",
"raw",
"=",
"False",
",",
"file",
"=",
"None",
")",
":",
"if",
"method",
"is",
"'GET'",
":",
"response",
"=",
"self",
".",
"oauth",
".",
"g... | Perform an API request to the given URL, optionally
including the specified data
:type url: String
:param url: the URL to which to make the request
:type data: String
:param data: the data to send with the request, if any
:type method: String
:param method: the H... | [
"Perform",
"an",
"API",
"request",
"to",
"the",
"given",
"URL",
"optionally",
"including",
"the",
"specified",
"data"
] | python | train |
zaturox/glin | glin/zmq/messages.py | https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/zmq/messages.py#L93-L99 | def uint64(self, val):
"""append a frame containing a uint64"""
try:
self.msg += [pack("!Q", val)]
except struct.error:
raise ValueError("Expected uint64")
return self | [
"def",
"uint64",
"(",
"self",
",",
"val",
")",
":",
"try",
":",
"self",
".",
"msg",
"+=",
"[",
"pack",
"(",
"\"!Q\"",
",",
"val",
")",
"]",
"except",
"struct",
".",
"error",
":",
"raise",
"ValueError",
"(",
"\"Expected uint64\"",
")",
"return",
"self... | append a frame containing a uint64 | [
"append",
"a",
"frame",
"containing",
"a",
"uint64"
] | python | train |
allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L362-L373 | def select_number(self, rows: List[Row], column: NumberColumn) -> Number:
"""
Select function takes a row (as a list) and a column name and returns the number in that
column. If multiple rows are given, will return the first number that is not None.
"""
numbers: List[float] = []
... | [
"def",
"select_number",
"(",
"self",
",",
"rows",
":",
"List",
"[",
"Row",
"]",
",",
"column",
":",
"NumberColumn",
")",
"->",
"Number",
":",
"numbers",
":",
"List",
"[",
"float",
"]",
"=",
"[",
"]",
"for",
"row",
"in",
"rows",
":",
"cell_value",
"... | Select function takes a row (as a list) and a column name and returns the number in that
column. If multiple rows are given, will return the first number that is not None. | [
"Select",
"function",
"takes",
"a",
"row",
"(",
"as",
"a",
"list",
")",
"and",
"a",
"column",
"name",
"and",
"returns",
"the",
"number",
"in",
"that",
"column",
".",
"If",
"multiple",
"rows",
"are",
"given",
"will",
"return",
"the",
"first",
"number",
... | python | train |
edx/i18n-tools | i18n/validate.py | https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/validate.py#L86-L105 | def tags_in_string(msg):
"""
Return the set of tags in a message string.
Tags includes HTML tags, data placeholders, etc.
Skips tags that might change due to translations: HTML entities, <abbr>,
and so on.
"""
def is_linguistic_tag(tag):
"""Is this tag one that can change with the... | [
"def",
"tags_in_string",
"(",
"msg",
")",
":",
"def",
"is_linguistic_tag",
"(",
"tag",
")",
":",
"\"\"\"Is this tag one that can change with the language?\"\"\"",
"if",
"tag",
".",
"startswith",
"(",
"\"&\"",
")",
":",
"return",
"True",
"if",
"any",
"(",
"x",
"i... | Return the set of tags in a message string.
Tags includes HTML tags, data placeholders, etc.
Skips tags that might change due to translations: HTML entities, <abbr>,
and so on. | [
"Return",
"the",
"set",
"of",
"tags",
"in",
"a",
"message",
"string",
"."
] | python | train |
hydraplatform/hydra-base | hydra_base/lib/sharing.py | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/sharing.py#L57-L93 | def share_network(network_id, usernames, read_only, share,**kwargs):
"""
Share a network with a list of users, identified by their usernames.
The read_only flag ('Y' or 'N') must be set
to 'Y' to allow write access or sharing.
The share flat ('Y' or 'N') must be set to 'Y' to allow... | [
"def",
"share_network",
"(",
"network_id",
",",
"usernames",
",",
"read_only",
",",
"share",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"net_i",
"=",
"_get_network",
"(",
"network_id",
")",
"net_i",
".... | Share a network with a list of users, identified by their usernames.
The read_only flag ('Y' or 'N') must be set
to 'Y' to allow write access or sharing.
The share flat ('Y' or 'N') must be set to 'Y' to allow the
project to be shared with other users | [
"Share",
"a",
"network",
"with",
"a",
"list",
"of",
"users",
"identified",
"by",
"their",
"usernames",
"."
] | python | train |
spulec/moto | moto/batch/models.py | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/batch/models.py#L310-L405 | def run(self):
"""
Run the container.
Logic is as follows:
Generate container info (eventually from task definition)
Start container
Loop whilst not asked to stop and the container is running.
Get all logs from container between the last time I checked and now.... | [
"def",
"run",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"job_state",
"=",
"'PENDING'",
"time",
".",
"sleep",
"(",
"1",
")",
"image",
"=",
"'alpine:latest'",
"cmd",
"=",
"'/bin/sh -c \"for a in `seq 1 10`; do echo Hello World; sleep 1; done\"'",
"name",
"=",
... | Run the container.
Logic is as follows:
Generate container info (eventually from task definition)
Start container
Loop whilst not asked to stop and the container is running.
Get all logs from container between the last time I checked and now.
Convert logs into cloudwat... | [
"Run",
"the",
"container",
"."
] | python | train |
log2timeline/dfvfs | dfvfs/file_io/encoded_stream_io.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/file_io/encoded_stream_io.py#L288-L327 | def seek(self, offset, whence=os.SEEK_SET):
"""Seeks to an offset within the file-like object.
Args:
offset (int): offset to seek to.
whence (Optional(int)): value that indicates whether offset is an absolute
or relative position within the file.
Raises:
IOError: if the seek fa... | [
"def",
"seek",
"(",
"self",
",",
"offset",
",",
"whence",
"=",
"os",
".",
"SEEK_SET",
")",
":",
"if",
"not",
"self",
".",
"_is_open",
":",
"raise",
"IOError",
"(",
"'Not opened.'",
")",
"if",
"self",
".",
"_current_offset",
"<",
"0",
":",
"raise",
"I... | Seeks to an offset within the file-like object.
Args:
offset (int): offset to seek to.
whence (Optional(int)): value that indicates whether offset is an absolute
or relative position within the file.
Raises:
IOError: if the seek failed.
OSError: if the seek failed. | [
"Seeks",
"to",
"an",
"offset",
"within",
"the",
"file",
"-",
"like",
"object",
"."
] | python | train |
inveniosoftware/invenio-oauthclient | invenio_oauthclient/handlers.py | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/handlers.py#L469-L474 | def oauth_logout_handler(sender_app, user=None):
"""Remove all access tokens from session on logout."""
oauth = current_app.extensions['oauthlib.client']
for remote in oauth.remote_apps.values():
token_delete(remote)
db.session.commit() | [
"def",
"oauth_logout_handler",
"(",
"sender_app",
",",
"user",
"=",
"None",
")",
":",
"oauth",
"=",
"current_app",
".",
"extensions",
"[",
"'oauthlib.client'",
"]",
"for",
"remote",
"in",
"oauth",
".",
"remote_apps",
".",
"values",
"(",
")",
":",
"token_dele... | Remove all access tokens from session on logout. | [
"Remove",
"all",
"access",
"tokens",
"from",
"session",
"on",
"logout",
"."
] | python | train |
ARMmbed/mbed-cloud-sdk-python | src/mbed_cloud/_backends/iam/apis/aggregator_account_admin_api.py | https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/iam/apis/aggregator_account_admin_api.py#L4274-L4296 | def update_account_certificate(self, account_id, cert_id, body, **kwargs): # noqa: E501
"""Update trusted certificate. # noqa: E501
An endpoint for updating existing trusted certificates. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HT... | [
"def",
"update_account_certificate",
"(",
"self",
",",
"account_id",
",",
"cert_id",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",... | Update trusted certificate. # noqa: E501
An endpoint for updating existing trusted certificates. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.update_account_certificate(accoun... | [
"Update",
"trusted",
"certificate",
".",
"#",
"noqa",
":",
"E501"
] | python | train |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/event.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/event.py#L1627-L1647 | def event(self, event):
"""
Forwards events to the corresponding instance of your event handler
for this process.
If you subclass L{EventSift} and reimplement this method, no event
will be forwarded at all unless you call the superclass implementation.
If your filtering... | [
"def",
"event",
"(",
"self",
",",
"event",
")",
":",
"eventCode",
"=",
"event",
".",
"get_event_code",
"(",
")",
"pid",
"=",
"event",
".",
"get_pid",
"(",
")",
"handler",
"=",
"self",
".",
"forward",
".",
"get",
"(",
"pid",
",",
"None",
")",
"if",
... | Forwards events to the corresponding instance of your event handler
for this process.
If you subclass L{EventSift} and reimplement this method, no event
will be forwarded at all unless you call the superclass implementation.
If your filtering is based on the event type, there's a much ... | [
"Forwards",
"events",
"to",
"the",
"corresponding",
"instance",
"of",
"your",
"event",
"handler",
"for",
"this",
"process",
"."
] | python | train |
freelancer/freelancer-sdk-python | freelancersdk/resources/projects/projects.py | https://github.com/freelancer/freelancer-sdk-python/blob/e09034936d6f13b3909a9464ee329c81c1834941/freelancersdk/resources/projects/projects.py#L701-L714 | def post_review(session, review):
"""
Post a review
"""
# POST /api/projects/0.1/reviews/
response = make_post_request(session, 'reviews', json_data=review)
json_data = response.json()
if response.status_code == 200:
return json_data['status']
else:
raise ReviewNotPostedE... | [
"def",
"post_review",
"(",
"session",
",",
"review",
")",
":",
"# POST /api/projects/0.1/reviews/",
"response",
"=",
"make_post_request",
"(",
"session",
",",
"'reviews'",
",",
"json_data",
"=",
"review",
")",
"json_data",
"=",
"response",
".",
"json",
"(",
")",... | Post a review | [
"Post",
"a",
"review"
] | python | valid |
saltstack/salt | salt/states/boto_apigateway.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L524-L532 | def _log_error_and_abort(ret, obj):
'''
helper function to update errors in the return structure
'''
ret['result'] = False
ret['abort'] = True
if 'error' in obj:
ret['comment'] = '{0}'.format(obj.get('error'))
return ret | [
"def",
"_log_error_and_abort",
"(",
"ret",
",",
"obj",
")",
":",
"ret",
"[",
"'result'",
"]",
"=",
"False",
"ret",
"[",
"'abort'",
"]",
"=",
"True",
"if",
"'error'",
"in",
"obj",
":",
"ret",
"[",
"'comment'",
"]",
"=",
"'{0}'",
".",
"format",
"(",
... | helper function to update errors in the return structure | [
"helper",
"function",
"to",
"update",
"errors",
"in",
"the",
"return",
"structure"
] | python | train |
ethan92429/onshapepy | onshapepy/part.py | https://github.com/ethan92429/onshapepy/blob/61dc7ccbdc6095fa6cc3b4a414e2f72d03d1c9df/onshapepy/part.py#L96-L100 | def get_params(self):
"""Manually pull params defined in config from OnShape and return a python representation of the params.
Quantities are converted to pint quantities, Bools are converted to python bools and Enums are converted
to strings. Note that Enum names are autogenerated by OnShape an... | [
"def",
"get_params",
"(",
"self",
")",
":",
"self",
".",
"res",
"=",
"c",
".",
"get_configuration",
"(",
"self",
".",
"parent",
".",
"uri",
".",
"as_dict",
"(",
")",
")"
] | Manually pull params defined in config from OnShape and return a python representation of the params.
Quantities are converted to pint quantities, Bools are converted to python bools and Enums are converted
to strings. Note that Enum names are autogenerated by OnShape and do not match the name on the On... | [
"Manually",
"pull",
"params",
"defined",
"in",
"config",
"from",
"OnShape",
"and",
"return",
"a",
"python",
"representation",
"of",
"the",
"params",
".",
"Quantities",
"are",
"converted",
"to",
"pint",
"quantities",
"Bools",
"are",
"converted",
"to",
"python",
... | python | train |
pgxcentre/geneparse | geneparse/readers/bgen.py | https://github.com/pgxcentre/geneparse/blob/f698f9708af4c7962d384a70a5a14006b1cb7108/geneparse/readers/bgen.py#L190-L220 | def get_variant_by_name(self, name):
"""Get the genotype of a marker using it's name.
Args:
name (str): The name of the marker.
Returns:
list: A list of Genotypes.
"""
results = []
try:
for info, dosage in self._bgen.get_variant(nam... | [
"def",
"get_variant_by_name",
"(",
"self",
",",
"name",
")",
":",
"results",
"=",
"[",
"]",
"try",
":",
"for",
"info",
",",
"dosage",
"in",
"self",
".",
"_bgen",
".",
"get_variant",
"(",
"name",
")",
":",
"results",
".",
"append",
"(",
"Genotypes",
"... | Get the genotype of a marker using it's name.
Args:
name (str): The name of the marker.
Returns:
list: A list of Genotypes. | [
"Get",
"the",
"genotype",
"of",
"a",
"marker",
"using",
"it",
"s",
"name",
"."
] | python | train |
PaulHancock/Aegean | AegeanTools/MIMAS.py | https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/MIMAS.py#L95-L139 | def mask_plane(data, wcs, region, negate=False):
"""
Mask a 2d image (data) such that pixels within 'region' are set to nan.
Parameters
----------
data : 2d-array
Image array.
wcs : astropy.wcs.WCS
WCS for the image in question.
region : :class:`AegeanTools.regions.Region`... | [
"def",
"mask_plane",
"(",
"data",
",",
"wcs",
",",
"region",
",",
"negate",
"=",
"False",
")",
":",
"# create an array but don't set the values (they are random)",
"indexes",
"=",
"np",
".",
"empty",
"(",
"(",
"data",
".",
"shape",
"[",
"0",
"]",
"*",
"data"... | Mask a 2d image (data) such that pixels within 'region' are set to nan.
Parameters
----------
data : 2d-array
Image array.
wcs : astropy.wcs.WCS
WCS for the image in question.
region : :class:`AegeanTools.regions.Region`
A region within which the image pixels will be maske... | [
"Mask",
"a",
"2d",
"image",
"(",
"data",
")",
"such",
"that",
"pixels",
"within",
"region",
"are",
"set",
"to",
"nan",
"."
] | python | train |
jmgilman/Neolib | neolib/pyamf/util/__init__.py | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/__init__.py#L28-L43 | def get_timestamp(d):
"""
Returns a UTC timestamp for a C{datetime.datetime} object.
@type d: C{datetime.datetime}
@return: UTC timestamp.
@rtype: C{float}
@see: Inspiration taken from the U{Intertwingly blog
<http://intertwingly.net/blog/2007/09/02/Dealing-With-Dates>}.
"""
if ... | [
"def",
"get_timestamp",
"(",
"d",
")",
":",
"if",
"isinstance",
"(",
"d",
",",
"datetime",
".",
"date",
")",
"and",
"not",
"isinstance",
"(",
"d",
",",
"datetime",
".",
"datetime",
")",
":",
"d",
"=",
"datetime",
".",
"datetime",
".",
"combine",
"(",... | Returns a UTC timestamp for a C{datetime.datetime} object.
@type d: C{datetime.datetime}
@return: UTC timestamp.
@rtype: C{float}
@see: Inspiration taken from the U{Intertwingly blog
<http://intertwingly.net/blog/2007/09/02/Dealing-With-Dates>}. | [
"Returns",
"a",
"UTC",
"timestamp",
"for",
"a",
"C",
"{",
"datetime",
".",
"datetime",
"}",
"object",
"."
] | python | train |
sphinx-contrib/paverutils | sphinxcontrib/paverutils.py | https://github.com/sphinx-contrib/paverutils/blob/6268e5952fa564cefac05c06823b929a60522613/sphinxcontrib/paverutils.py#L312-L487 | def run_script(input_file, script_name,
interpreter='python',
include_prefix=True,
ignore_error=False,
trailing_newlines=True,
break_lines_at=0,
line_break_mode='break',
adjust_python_for_version=True,
... | [
"def",
"run_script",
"(",
"input_file",
",",
"script_name",
",",
"interpreter",
"=",
"'python'",
",",
"include_prefix",
"=",
"True",
",",
"ignore_error",
"=",
"False",
",",
"trailing_newlines",
"=",
"True",
",",
"break_lines_at",
"=",
"0",
",",
"line_break_mode"... | Run a script in the context of the input_file's directory,
return the text output formatted to be included as an rst
literal text block.
Arguments:
input_file
The name of the file being processed by cog. Usually passed as
cog.inFile.
script_name
The name of the Python script... | [
"Run",
"a",
"script",
"in",
"the",
"context",
"of",
"the",
"input_file",
"s",
"directory",
"return",
"the",
"text",
"output",
"formatted",
"to",
"be",
"included",
"as",
"an",
"rst",
"literal",
"text",
"block",
"."
] | python | train |
olitheolix/qtmacs | qtmacs/extensions/qtmacstextedit_widget.py | https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacstextedit_widget.py#L125-L132 | def reverseCommit(self):
"""
Reverse the document to the original state.
"""
print(self.after == self.before)
pos = self.qteWidget.textCursor().position()
self.qteWidget.setHtml(self.before)
self.placeCursor(pos) | [
"def",
"reverseCommit",
"(",
"self",
")",
":",
"print",
"(",
"self",
".",
"after",
"==",
"self",
".",
"before",
")",
"pos",
"=",
"self",
".",
"qteWidget",
".",
"textCursor",
"(",
")",
".",
"position",
"(",
")",
"self",
".",
"qteWidget",
".",
"setHtml... | Reverse the document to the original state. | [
"Reverse",
"the",
"document",
"to",
"the",
"original",
"state",
"."
] | python | train |
ConsenSys/mythril-classic | mythril/ethereum/interface/leveldb/client.py | https://github.com/ConsenSys/mythril-classic/blob/27af71c34b2ce94f4fae5613ec457f93df1a8f56/mythril/ethereum/interface/leveldb/client.py#L117-L128 | def _get_block_header(self, block_hash, num):
"""Get block header by block header hash & number.
:param block_hash:
:param num:
:return:
"""
header_key = header_prefix + num + block_hash
block_header_data = self.db.get(header_key)
header = rlp.decode(blo... | [
"def",
"_get_block_header",
"(",
"self",
",",
"block_hash",
",",
"num",
")",
":",
"header_key",
"=",
"header_prefix",
"+",
"num",
"+",
"block_hash",
"block_header_data",
"=",
"self",
".",
"db",
".",
"get",
"(",
"header_key",
")",
"header",
"=",
"rlp",
".",... | Get block header by block header hash & number.
:param block_hash:
:param num:
:return: | [
"Get",
"block",
"header",
"by",
"block",
"header",
"hash",
"&",
"number",
"."
] | python | train |
Karaage-Cluster/karaage | karaage/plugins/kgapplications/views/aed.py | https://github.com/Karaage-Cluster/karaage/blob/2f4c8b4e2d728b3fcbb151160c49000f1c04f5c9/karaage/plugins/kgapplications/views/aed.py#L431-L511 | def get_next_action(self, request, application, label, roles):
""" Process the get_next_action request at the current step. """
# if user is logged and and not applicant, steal the
# application
if 'is_applicant' in roles:
# if we got this far, then we either we are logged i... | [
"def",
"get_next_action",
"(",
"self",
",",
"request",
",",
"application",
",",
"label",
",",
"roles",
")",
":",
"# if user is logged and and not applicant, steal the",
"# application",
"if",
"'is_applicant'",
"in",
"roles",
":",
"# if we got this far, then we either we are... | Process the get_next_action request at the current step. | [
"Process",
"the",
"get_next_action",
"request",
"at",
"the",
"current",
"step",
"."
] | python | train |
wbond/certvalidator | certvalidator/registry.py | https://github.com/wbond/certvalidator/blob/c62233a713bcc36963e9d82323ec8d84f8e01485/certvalidator/registry.py#L276-L323 | def build_paths(self, end_entity_cert):
"""
Builds a list of ValidationPath objects from a certificate in the
operating system trust store to the end-entity certificate
:param end_entity_cert:
A byte string of a DER or PEM-encoded X.509 certificate, or an
instanc... | [
"def",
"build_paths",
"(",
"self",
",",
"end_entity_cert",
")",
":",
"if",
"not",
"isinstance",
"(",
"end_entity_cert",
",",
"byte_cls",
")",
"and",
"not",
"isinstance",
"(",
"end_entity_cert",
",",
"x509",
".",
"Certificate",
")",
":",
"raise",
"TypeError",
... | Builds a list of ValidationPath objects from a certificate in the
operating system trust store to the end-entity certificate
:param end_entity_cert:
A byte string of a DER or PEM-encoded X.509 certificate, or an
instance of asn1crypto.x509.Certificate
:return:
... | [
"Builds",
"a",
"list",
"of",
"ValidationPath",
"objects",
"from",
"a",
"certificate",
"in",
"the",
"operating",
"system",
"trust",
"store",
"to",
"the",
"end",
"-",
"entity",
"certificate"
] | python | train |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1445-L1449 | def weighted_n(self):
"""float count of returned rows adjusted for weighting."""
if not self.is_weighted:
return float(self.unweighted_n)
return float(sum(self._cube_dict["result"]["measures"]["count"]["data"])) | [
"def",
"weighted_n",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_weighted",
":",
"return",
"float",
"(",
"self",
".",
"unweighted_n",
")",
"return",
"float",
"(",
"sum",
"(",
"self",
".",
"_cube_dict",
"[",
"\"result\"",
"]",
"[",
"\"measures\""... | float count of returned rows adjusted for weighting. | [
"float",
"count",
"of",
"returned",
"rows",
"adjusted",
"for",
"weighting",
"."
] | python | train |
google/grr | grr/core/grr_response_core/lib/utils.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/utils.py#L828-L877 | def _GenerateZipInfo(self, arcname=None, compress_type=None, st=None):
"""Generate ZipInfo instance for the given name, compression and stat.
Args:
arcname: The name in the archive this should take.
compress_type: Compression type (zipfile.ZIP_DEFLATED, or ZIP_STORED)
st: An optional stat obj... | [
"def",
"_GenerateZipInfo",
"(",
"self",
",",
"arcname",
"=",
"None",
",",
"compress_type",
"=",
"None",
",",
"st",
"=",
"None",
")",
":",
"# Fake stat response.",
"if",
"st",
"is",
"None",
":",
"# TODO(user):pytype: stat_result typing is not correct.",
"# pytype: di... | Generate ZipInfo instance for the given name, compression and stat.
Args:
arcname: The name in the archive this should take.
compress_type: Compression type (zipfile.ZIP_DEFLATED, or ZIP_STORED)
st: An optional stat object to be used for setting headers.
Returns:
ZipInfo instance.
... | [
"Generate",
"ZipInfo",
"instance",
"for",
"the",
"given",
"name",
"compression",
"and",
"stat",
"."
] | python | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py#L757-L790 | def DocbookSlidesHtml(env, target, source=None, *args, **kw):
"""
A pseudo-Builder, providing a Docbook toolchain for HTML slides output.
"""
# Init list of targets/sources
if not SCons.Util.is_List(target):
target = [target]
if not source:
source = target
target = ['inde... | [
"def",
"DocbookSlidesHtml",
"(",
"env",
",",
"target",
",",
"source",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"# Init list of targets/sources",
"if",
"not",
"SCons",
".",
"Util",
".",
"is_List",
"(",
"target",
")",
":",
"target",
... | A pseudo-Builder, providing a Docbook toolchain for HTML slides output. | [
"A",
"pseudo",
"-",
"Builder",
"providing",
"a",
"Docbook",
"toolchain",
"for",
"HTML",
"slides",
"output",
"."
] | python | train |
saltstack/salt | salt/modules/boto_secgroup.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_secgroup.py#L239-L298 | def get_all_security_groups(groupnames=None, group_ids=None, filters=None,
region=None, key=None, keyid=None, profile=None):
'''
Return a list of all Security Groups matching the given criteria and filters.
Note that the 'groupnames' argument only functions correctly for EC2 Cla... | [
"def",
"get_all_security_groups",
"(",
"groupnames",
"=",
"None",
",",
"group_ids",
"=",
"None",
",",
"filters",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",... | Return a list of all Security Groups matching the given criteria and filters.
Note that the 'groupnames' argument only functions correctly for EC2 Classic
and default VPC Security Groups. To find groups by name in other VPCs you'll
want to use the 'group-name' filter instead.
Valid keys for the filte... | [
"Return",
"a",
"list",
"of",
"all",
"Security",
"Groups",
"matching",
"the",
"given",
"criteria",
"and",
"filters",
"."
] | python | train |
neo4j-drivers/neobolt | neobolt/impl/python/direct.py | https://github.com/neo4j-drivers/neobolt/blob/724569d76e85777c4f5e30e8d0a18116bda4d8cd/neobolt/impl/python/direct.py#L288-L298 | def _append(self, signature, fields=(), response=None):
""" Add a message to the outgoing queue.
:arg signature: the signature of the message
:arg fields: the fields of the message as a tuple
:arg response: a response object to handle callbacks
"""
self.packer.pack_struc... | [
"def",
"_append",
"(",
"self",
",",
"signature",
",",
"fields",
"=",
"(",
")",
",",
"response",
"=",
"None",
")",
":",
"self",
".",
"packer",
".",
"pack_struct",
"(",
"signature",
",",
"fields",
")",
"self",
".",
"output_buffer",
".",
"chunk",
"(",
"... | Add a message to the outgoing queue.
:arg signature: the signature of the message
:arg fields: the fields of the message as a tuple
:arg response: a response object to handle callbacks | [
"Add",
"a",
"message",
"to",
"the",
"outgoing",
"queue",
"."
] | python | train |
twilio/twilio-python | twilio/rest/api/v2010/account/usage/trigger.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/usage/trigger.py#L296-L325 | def update(self, callback_method=values.unset, callback_url=values.unset,
friendly_name=values.unset):
"""
Update the TriggerInstance
:param unicode callback_method: The HTTP method to use to call callback_url
:param unicode callback_url: The URL we call when the trigger ... | [
"def",
"update",
"(",
"self",
",",
"callback_method",
"=",
"values",
".",
"unset",
",",
"callback_url",
"=",
"values",
".",
"unset",
",",
"friendly_name",
"=",
"values",
".",
"unset",
")",
":",
"data",
"=",
"values",
".",
"of",
"(",
"{",
"'CallbackMethod... | Update the TriggerInstance
:param unicode callback_method: The HTTP method to use to call callback_url
:param unicode callback_url: The URL we call when the trigger fires
:param unicode friendly_name: A string to describe the resource
:returns: Updated TriggerInstance
:rtype: t... | [
"Update",
"the",
"TriggerInstance"
] | python | train |
Rockhopper-Technologies/pluginlib | pluginlib/_loader.py | https://github.com/Rockhopper-Technologies/pluginlib/blob/8beb78984dd9c97c493642df9da9f1b5a1c5e2b2/pluginlib/_loader.py#L371-L395 | def get_plugin(self, plugin_type, name, version=None):
"""
Args:
plugin_type(str): Parent type
name(str): Plugin name
version(str): Plugin version
Returns:
:py:class:`Plugin`: Plugin, or :py:data:`None` if plugin can't be found
Retrieve a... | [
"def",
"get_plugin",
"(",
"self",
",",
"plugin_type",
",",
"name",
",",
"version",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"loaded",
":",
"self",
".",
"load_modules",
"(",
")",
"# pylint: disable=protected-access",
"return",
"get_plugins",
"(",
")",... | Args:
plugin_type(str): Parent type
name(str): Plugin name
version(str): Plugin version
Returns:
:py:class:`Plugin`: Plugin, or :py:data:`None` if plugin can't be found
Retrieve a specific plugin. ``blacklist`` and ``type_filter`` still apply.
I... | [
"Args",
":",
"plugin_type",
"(",
"str",
")",
":",
"Parent",
"type",
"name",
"(",
"str",
")",
":",
"Plugin",
"name",
"version",
"(",
"str",
")",
":",
"Plugin",
"version"
] | python | train |
ubc/ubcpi | ubcpi/answer_pool.py | https://github.com/ubc/ubcpi/blob/7b6de03f93f3a4a8af4b92dfde7c69eeaf21f46e/ubcpi/answer_pool.py#L277-L323 | def get_other_answers_random(pool, seeded_answers, get_student_item_dict, num_responses):
"""
Get answers from others with random algorithm, which randomly select answer from the pool.
Student may get three answers for option 1 or one answer for option 1 and two answers for option 2.
Args:
see... | [
"def",
"get_other_answers_random",
"(",
"pool",
",",
"seeded_answers",
",",
"get_student_item_dict",
",",
"num_responses",
")",
":",
"ret",
"=",
"[",
"]",
"# clean up answers so that all keys are int",
"pool",
"=",
"{",
"int",
"(",
"k",
")",
":",
"v",
"for",
"k"... | Get answers from others with random algorithm, which randomly select answer from the pool.
Student may get three answers for option 1 or one answer for option 1 and two answers for option 2.
Args:
see `get_other_answers`
num_responses (int): the number of responses to be returned. This value m... | [
"Get",
"answers",
"from",
"others",
"with",
"random",
"algorithm",
"which",
"randomly",
"select",
"answer",
"from",
"the",
"pool",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/analysis/gb/grain.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/gb/grain.py#L1376-L1517 | def enum_sigma_rho(cutoff, r_axis, ratio_alpha):
"""
Find all possible sigma values and corresponding rotation angles
within a sigma value cutoff with known rotation axis in rhombohedral system.
The algorithm for this code is from reference, Acta Cryst, A45,505(1989).
Args:
... | [
"def",
"enum_sigma_rho",
"(",
"cutoff",
",",
"r_axis",
",",
"ratio_alpha",
")",
":",
"sigmas",
"=",
"{",
"}",
"# transform four index notation to three index notation",
"if",
"len",
"(",
"r_axis",
")",
"==",
"4",
":",
"u1",
"=",
"r_axis",
"[",
"0",
"]",
"v1"... | Find all possible sigma values and corresponding rotation angles
within a sigma value cutoff with known rotation axis in rhombohedral system.
The algorithm for this code is from reference, Acta Cryst, A45,505(1989).
Args:
cutoff (integer): the cutoff of sigma values.
r_a... | [
"Find",
"all",
"possible",
"sigma",
"values",
"and",
"corresponding",
"rotation",
"angles",
"within",
"a",
"sigma",
"value",
"cutoff",
"with",
"known",
"rotation",
"axis",
"in",
"rhombohedral",
"system",
".",
"The",
"algorithm",
"for",
"this",
"code",
"is",
"f... | python | train |
WoLpH/python-progressbar | progressbar/bar.py | https://github.com/WoLpH/python-progressbar/blob/963617a1bb9d81624ecf31f3457185992cd97bfa/progressbar/bar.py#L527-L550 | def _needs_update(self):
'Returns whether the ProgressBar should redraw the line.'
if self.poll_interval:
delta = timeit.default_timer() - self._last_update_timer
poll_status = delta > self.poll_interval.total_seconds()
else:
delta = 0
poll_status... | [
"def",
"_needs_update",
"(",
"self",
")",
":",
"if",
"self",
".",
"poll_interval",
":",
"delta",
"=",
"timeit",
".",
"default_timer",
"(",
")",
"-",
"self",
".",
"_last_update_timer",
"poll_status",
"=",
"delta",
">",
"self",
".",
"poll_interval",
".",
"to... | Returns whether the ProgressBar should redraw the line. | [
"Returns",
"whether",
"the",
"ProgressBar",
"should",
"redraw",
"the",
"line",
"."
] | python | train |
google/openhtf | openhtf/plugs/usb/adb_device.py | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_device.py#L153-L172 | def pull(self, device_filename, dest_file=None, timeout_ms=None):
"""Pull file from device.
Arguments:
device_filename: The filename on the device to pull.
dest_file: If set, a filename or writable file-like object.
timeout_ms: Expected timeout for the pull.
Returns:
The file data ... | [
"def",
"pull",
"(",
"self",
",",
"device_filename",
",",
"dest_file",
"=",
"None",
",",
"timeout_ms",
"=",
"None",
")",
":",
"should_return_data",
"=",
"dest_file",
"is",
"None",
"if",
"isinstance",
"(",
"dest_file",
",",
"six",
".",
"string_types",
")",
"... | Pull file from device.
Arguments:
device_filename: The filename on the device to pull.
dest_file: If set, a filename or writable file-like object.
timeout_ms: Expected timeout for the pull.
Returns:
The file data if dest_file is not set, None otherwise. | [
"Pull",
"file",
"from",
"device",
"."
] | python | train |
google/openhtf | openhtf/plugs/usb/filesync_service.py | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/filesync_service.py#L415-L461 | def read_message(self, timeout=None):
"""Read a message from this transport and return it.
Reads a message of RECV_MSG_TYPE and returns it. Note that this method
abstracts the data length and data read so that the caller simply gets the
data along with the header in the returned message.
Args:
... | [
"def",
"read_message",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"raw_data",
"=",
"self",
".",
"stream",
".",
"read",
"(",
"struct",
".",
"calcsize",
"(",
"self",
".",
"RECV_MSG_TYPE",
".",
"struct_format",
")",
",",
"timeout",
")",
"try",
":... | Read a message from this transport and return it.
Reads a message of RECV_MSG_TYPE and returns it. Note that this method
abstracts the data length and data read so that the caller simply gets the
data along with the header in the returned message.
Args:
timeout: timeouts.PolledTimeout to use fo... | [
"Read",
"a",
"message",
"from",
"this",
"transport",
"and",
"return",
"it",
"."
] | python | train |
ereOn/azmq | azmq/common.py | https://github.com/ereOn/azmq/blob/9f40d6d721eea7f7659ec6cc668811976db59854/azmq/common.py#L156-L168 | def close(self):
"""
Close the instance.
"""
if not self.closed and not self.closing:
logger.debug(
"%s[%s] closing...",
self.__class__.__name__,
id(self),
)
self._closing.set()
future = async... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"closed",
"and",
"not",
"self",
".",
"closing",
":",
"logger",
".",
"debug",
"(",
"\"%s[%s] closing...\"",
",",
"self",
".",
"__class__",
".",
"__name__",
",",
"id",
"(",
"self",
")",
"... | Close the instance. | [
"Close",
"the",
"instance",
"."
] | python | train |
dstufft/crust | crust/query.py | https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L80-L99 | def set_limits(self, low=None, high=None):
"""
Adjusts the limits on the rows retrieved. We use low/high to set these,
as it makes it more Pythonic to read and write. When the API query is
created, they are converted to the appropriate offset and limit values.
Any limits passed ... | [
"def",
"set_limits",
"(",
"self",
",",
"low",
"=",
"None",
",",
"high",
"=",
"None",
")",
":",
"if",
"high",
"is",
"not",
"None",
":",
"if",
"self",
".",
"high_mark",
"is",
"not",
"None",
":",
"self",
".",
"high_mark",
"=",
"min",
"(",
"self",
".... | Adjusts the limits on the rows retrieved. We use low/high to set these,
as it makes it more Pythonic to read and write. When the API query is
created, they are converted to the appropriate offset and limit values.
Any limits passed in here are applied relative to the existing
constraint... | [
"Adjusts",
"the",
"limits",
"on",
"the",
"rows",
"retrieved",
".",
"We",
"use",
"low",
"/",
"high",
"to",
"set",
"these",
"as",
"it",
"makes",
"it",
"more",
"Pythonic",
"to",
"read",
"and",
"write",
".",
"When",
"the",
"API",
"query",
"is",
"created",
... | python | train |
edx/edx-enterprise | enterprise/api/pagination.py | https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/pagination.py#L13-L47 | def get_paginated_response(data, request):
"""
Update pagination links in course catalog data and return DRF Response.
Arguments:
data (dict): Dictionary containing catalog courses.
request (HttpRequest): Current request object.
Returns:
(Response): DRF response object containi... | [
"def",
"get_paginated_response",
"(",
"data",
",",
"request",
")",
":",
"url",
"=",
"urlparse",
"(",
"request",
".",
"build_absolute_uri",
"(",
")",
")",
".",
"_replace",
"(",
"query",
"=",
"None",
")",
".",
"geturl",
"(",
")",
"next_page",
"=",
"None",
... | Update pagination links in course catalog data and return DRF Response.
Arguments:
data (dict): Dictionary containing catalog courses.
request (HttpRequest): Current request object.
Returns:
(Response): DRF response object containing pagination links. | [
"Update",
"pagination",
"links",
"in",
"course",
"catalog",
"data",
"and",
"return",
"DRF",
"Response",
"."
] | python | valid |
Fuyukai/ConfigMaster | configmaster/ConfigKey.py | https://github.com/Fuyukai/ConfigMaster/blob/8018aa415da55c84edaa8a49664f674758a14edd/configmaster/ConfigKey.py#L37-L52 | def dump(self) -> dict:
"""
Dumps data from the ConfigKey into a dict.
:return: The keys and values from the ConfigKey encapsulated in a dict.
"""
d = {}
for item in self.__dict__:
if item in ['parsed', 'dump', 'parse_data', 'iter_list', 'safe_load']:
... | [
"def",
"dump",
"(",
"self",
")",
"->",
"dict",
":",
"d",
"=",
"{",
"}",
"for",
"item",
"in",
"self",
".",
"__dict__",
":",
"if",
"item",
"in",
"[",
"'parsed'",
",",
"'dump'",
",",
"'parse_data'",
",",
"'iter_list'",
",",
"'safe_load'",
"]",
":",
"c... | Dumps data from the ConfigKey into a dict.
:return: The keys and values from the ConfigKey encapsulated in a dict. | [
"Dumps",
"data",
"from",
"the",
"ConfigKey",
"into",
"a",
"dict",
".",
":",
"return",
":",
"The",
"keys",
"and",
"values",
"from",
"the",
"ConfigKey",
"encapsulated",
"in",
"a",
"dict",
"."
] | python | train |
gwastro/pycbc | pycbc/frame/frame.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/frame/frame.py#L295-L328 | def frame_paths(frame_type, start_time, end_time, server=None, url_type='file'):
"""Return the paths to a span of frame files
Parameters
----------
frame_type : string
The string representation of the frame type (ex. 'H1_ER_C00_L1')
start_time : int
The start time that we need the f... | [
"def",
"frame_paths",
"(",
"frame_type",
",",
"start_time",
",",
"end_time",
",",
"server",
"=",
"None",
",",
"url_type",
"=",
"'file'",
")",
":",
"site",
"=",
"frame_type",
"[",
"0",
"]",
"connection",
"=",
"datafind_connection",
"(",
"server",
")",
"conn... | Return the paths to a span of frame files
Parameters
----------
frame_type : string
The string representation of the frame type (ex. 'H1_ER_C00_L1')
start_time : int
The start time that we need the frames to span.
end_time : int
The end time that we need the frames to span.
... | [
"Return",
"the",
"paths",
"to",
"a",
"span",
"of",
"frame",
"files"
] | python | train |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L376-L412 | def convert_surfaces(self, surface_nodes):
"""
Utility to convert a list of surface nodes into a single hazardlib
surface. There are four possibilities:
1. there is a single simpleFaultGeometry node; returns a
:class:`openquake.hazardlib.geo.simpleFaultSurface` instance
... | [
"def",
"convert_surfaces",
"(",
"self",
",",
"surface_nodes",
")",
":",
"surface_node",
"=",
"surface_nodes",
"[",
"0",
"]",
"if",
"surface_node",
".",
"tag",
".",
"endswith",
"(",
"'simpleFaultGeometry'",
")",
":",
"surface",
"=",
"geo",
".",
"SimpleFaultSurf... | Utility to convert a list of surface nodes into a single hazardlib
surface. There are four possibilities:
1. there is a single simpleFaultGeometry node; returns a
:class:`openquake.hazardlib.geo.simpleFaultSurface` instance
2. there is a single complexFaultGeometry node; returns a
... | [
"Utility",
"to",
"convert",
"a",
"list",
"of",
"surface",
"nodes",
"into",
"a",
"single",
"hazardlib",
"surface",
".",
"There",
"are",
"four",
"possibilities",
":"
] | python | train |
zhanglab/psamm | psamm/datasource/native.py | https://github.com/zhanglab/psamm/blob/dc427848c4f9d109ca590f0afa024c63b685b3f4/psamm/datasource/native.py#L244-L287 | def parse_compartments(self):
"""Parse compartment information from model.
Return tuple of: 1) iterator of
:class:`psamm.datasource.entry.CompartmentEntry`; 2) Set of pairs
defining the compartment boundaries of the model.
"""
compartments = OrderedDict()
bounda... | [
"def",
"parse_compartments",
"(",
"self",
")",
":",
"compartments",
"=",
"OrderedDict",
"(",
")",
"boundaries",
"=",
"set",
"(",
")",
"if",
"'compartments'",
"in",
"self",
".",
"_model",
":",
"boundary_map",
"=",
"{",
"}",
"for",
"compartment_def",
"in",
"... | Parse compartment information from model.
Return tuple of: 1) iterator of
:class:`psamm.datasource.entry.CompartmentEntry`; 2) Set of pairs
defining the compartment boundaries of the model. | [
"Parse",
"compartment",
"information",
"from",
"model",
"."
] | python | train |
Qiskit/qiskit-terra | qiskit/dagcircuit/dagcircuit.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/dagcircuit/dagcircuit.py#L1205-L1217 | def remove_nonancestors_of(self, node):
"""Remove all of the non-ancestors operation nodes of node."""
if isinstance(node, int):
warnings.warn('Calling remove_nonancestors_of() with a node id is deprecated,'
' use a DAGNode instead',
Deprec... | [
"def",
"remove_nonancestors_of",
"(",
"self",
",",
"node",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"int",
")",
":",
"warnings",
".",
"warn",
"(",
"'Calling remove_nonancestors_of() with a node id is deprecated,'",
"' use a DAGNode instead'",
",",
"DeprecationWar... | Remove all of the non-ancestors operation nodes of node. | [
"Remove",
"all",
"of",
"the",
"non",
"-",
"ancestors",
"operation",
"nodes",
"of",
"node",
"."
] | python | test |
pyviz/holoviews | holoviews/plotting/plotly/element.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/plotting/plotly/element.py#L103-L110 | def initialize_plot(self, ranges=None):
"""
Initializes a new plot object with the last available frame.
"""
# Get element key and ranges for frame
fig = self.generate_plot(self.keys[-1], ranges)
self.drawn = True
return fig | [
"def",
"initialize_plot",
"(",
"self",
",",
"ranges",
"=",
"None",
")",
":",
"# Get element key and ranges for frame",
"fig",
"=",
"self",
".",
"generate_plot",
"(",
"self",
".",
"keys",
"[",
"-",
"1",
"]",
",",
"ranges",
")",
"self",
".",
"drawn",
"=",
... | Initializes a new plot object with the last available frame. | [
"Initializes",
"a",
"new",
"plot",
"object",
"with",
"the",
"last",
"available",
"frame",
"."
] | python | train |
gabrielelanaro/chemview | chemview/viewer.py | https://github.com/gabrielelanaro/chemview/blob/2c9768dd23db99e59e27adff2a953bb8ee795fa3/chemview/viewer.py#L86-L148 | def toggle_axes(self, parameters = None):
'''Toggle axes [x,y,z] on and off for the current representation
Parameters: dictionary of parameters to control axes:
position/p: origin of axes
length/l: length of axis
offset/o: offset to place axis labels
... | [
"def",
"toggle_axes",
"(",
"self",
",",
"parameters",
"=",
"None",
")",
":",
"if",
"len",
"(",
"self",
".",
"_axes_reps",
")",
">",
"0",
":",
"for",
"rep_id",
"in",
"self",
".",
"_axes_reps",
":",
"self",
".",
"remove_representation",
"(",
"rep_id",
")... | Toggle axes [x,y,z] on and off for the current representation
Parameters: dictionary of parameters to control axes:
position/p: origin of axes
length/l: length of axis
offset/o: offset to place axis labels
axis_colors/ac: axis colors
te... | [
"Toggle",
"axes",
"[",
"x",
"y",
"z",
"]",
"on",
"and",
"off",
"for",
"the",
"current",
"representation",
"Parameters",
":",
"dictionary",
"of",
"parameters",
"to",
"control",
"axes",
":",
"position",
"/",
"p",
":",
"origin",
"of",
"axes",
"length",
"/",... | python | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L1523-L1547 | def copy(cell):
"""
Copy the contents of a SpiceCell of any data type to another
cell of the same type.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/copy_c.html
:param cell: Cell to be copied.
:type cell: spiceypy.utils.support_types.SpiceCell
:return: New cell
:rtype: spice... | [
"def",
"copy",
"(",
"cell",
")",
":",
"assert",
"isinstance",
"(",
"cell",
",",
"stypes",
".",
"SpiceCell",
")",
"# Next line was redundant with [raise NotImpImplementedError] below",
"# assert cell.dtype == 0 or cell.dtype == 1 or cell.dtype == 2",
"if",
"cell",
".",
"dtype"... | Copy the contents of a SpiceCell of any data type to another
cell of the same type.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/copy_c.html
:param cell: Cell to be copied.
:type cell: spiceypy.utils.support_types.SpiceCell
:return: New cell
:rtype: spiceypy.utils.support_types.Spic... | [
"Copy",
"the",
"contents",
"of",
"a",
"SpiceCell",
"of",
"any",
"data",
"type",
"to",
"another",
"cell",
"of",
"the",
"same",
"type",
"."
] | python | train |
HazyResearch/metal | metal/label_model/baselines.py | https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/label_model/baselines.py#L35-L41 | def train_model(self, balance, *args, **kwargs):
"""
Args:
balance: A 1d arraylike that sums to 1, corresponding to the
(possibly estimated) class balance.
"""
self.balance = np.array(balance) | [
"def",
"train_model",
"(",
"self",
",",
"balance",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"balance",
"=",
"np",
".",
"array",
"(",
"balance",
")"
] | Args:
balance: A 1d arraylike that sums to 1, corresponding to the
(possibly estimated) class balance. | [
"Args",
":",
"balance",
":",
"A",
"1d",
"arraylike",
"that",
"sums",
"to",
"1",
"corresponding",
"to",
"the",
"(",
"possibly",
"estimated",
")",
"class",
"balance",
"."
] | python | train |
fictorial/pygameui | pygameui/view.py | https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/view.py#L209-L227 | def stylize(self):
"""Apply theme style attributes to this instance and its children.
This also causes a relayout to occur so that any changes in padding
or other stylistic attributes may be handled.
"""
# do children first in case parent needs to override their style
fo... | [
"def",
"stylize",
"(",
"self",
")",
":",
"# do children first in case parent needs to override their style",
"for",
"child",
"in",
"self",
".",
"children",
":",
"child",
".",
"stylize",
"(",
")",
"style",
"=",
"theme",
".",
"current",
".",
"get_dict",
"(",
"self... | Apply theme style attributes to this instance and its children.
This also causes a relayout to occur so that any changes in padding
or other stylistic attributes may be handled. | [
"Apply",
"theme",
"style",
"attributes",
"to",
"this",
"instance",
"and",
"its",
"children",
"."
] | python | train |
sibirrer/lenstronomy | lenstronomy/Util/param_util.py | https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/Util/param_util.py#L50-L58 | def ellipticity2phi_gamma(e1, e2):
"""
:param e1: ellipticity component
:param e2: ellipticity component
:return: angle and abs value of ellipticity
"""
phi = np.arctan2(e2, e1)/2
gamma = np.sqrt(e1**2+e2**2)
return phi, gamma | [
"def",
"ellipticity2phi_gamma",
"(",
"e1",
",",
"e2",
")",
":",
"phi",
"=",
"np",
".",
"arctan2",
"(",
"e2",
",",
"e1",
")",
"/",
"2",
"gamma",
"=",
"np",
".",
"sqrt",
"(",
"e1",
"**",
"2",
"+",
"e2",
"**",
"2",
")",
"return",
"phi",
",",
"ga... | :param e1: ellipticity component
:param e2: ellipticity component
:return: angle and abs value of ellipticity | [
":",
"param",
"e1",
":",
"ellipticity",
"component",
":",
"param",
"e2",
":",
"ellipticity",
"component",
":",
"return",
":",
"angle",
"and",
"abs",
"value",
"of",
"ellipticity"
] | python | train |
timothydmorton/simpledist | simpledist/distributions.py | https://github.com/timothydmorton/simpledist/blob/d9807c90a935bd125213445ffed6255af558f1ca/simpledist/distributions.py#L615-L664 | def double_lorgauss(x,p):
"""Evaluates a normalized distribution that is a mixture of a double-sided Gaussian and Double-sided Lorentzian.
Parameters
----------
x : float or array-like
Value(s) at which to evaluate distribution
p : array-like
Input parameters: mu (mode of distribut... | [
"def",
"double_lorgauss",
"(",
"x",
",",
"p",
")",
":",
"mu",
",",
"sig1",
",",
"sig2",
",",
"gam1",
",",
"gam2",
",",
"G1",
",",
"G2",
"=",
"p",
"gam1",
"=",
"float",
"(",
"gam1",
")",
"gam2",
"=",
"float",
"(",
"gam2",
")",
"G1",
"=",
"abs"... | Evaluates a normalized distribution that is a mixture of a double-sided Gaussian and Double-sided Lorentzian.
Parameters
----------
x : float or array-like
Value(s) at which to evaluate distribution
p : array-like
Input parameters: mu (mode of distribution),
s... | [
"Evaluates",
"a",
"normalized",
"distribution",
"that",
"is",
"a",
"mixture",
"of",
"a",
"double",
"-",
"sided",
"Gaussian",
"and",
"Double",
"-",
"sided",
"Lorentzian",
"."
] | python | train |
pypa/pipenv | pipenv/vendor/ptyprocess/ptyprocess.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/ptyprocess/ptyprocess.py#L557-L562 | def write(self, s, flush=True):
"""Write bytes to the pseudoterminal.
Returns the number of bytes written.
"""
return self._writeb(s, flush=flush) | [
"def",
"write",
"(",
"self",
",",
"s",
",",
"flush",
"=",
"True",
")",
":",
"return",
"self",
".",
"_writeb",
"(",
"s",
",",
"flush",
"=",
"flush",
")"
] | Write bytes to the pseudoterminal.
Returns the number of bytes written. | [
"Write",
"bytes",
"to",
"the",
"pseudoterminal",
".",
"Returns",
"the",
"number",
"of",
"bytes",
"written",
"."
] | python | train |
gabstopper/smc-python | smc/administration/user_auth/servers.py | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/administration/user_auth/servers.py#L136-L214 | def create(cls, name, address, base_dn, bind_user_id=None, bind_password=None,
port=389, protocol='ldap', tls_profile=None, tls_identity=None,
domain_controller=None, supported_method=None, timeout=10, max_search_result=0,
page_size=0, internet_auth_service_enabled=False, **kwargs):
"""
... | [
"def",
"create",
"(",
"cls",
",",
"name",
",",
"address",
",",
"base_dn",
",",
"bind_user_id",
"=",
"None",
",",
"bind_password",
"=",
"None",
",",
"port",
"=",
"389",
",",
"protocol",
"=",
"'ldap'",
",",
"tls_profile",
"=",
"None",
",",
"tls_identity",
... | Create an AD server element using basic settings. You can also provide additional
kwargs documented in the class description::
ActiveDirectoryServer.create(name='somedirectory',
address='10.10.10.10',
base_dn='dc=domain,dc=net',
bind_user_id='... | [
"Create",
"an",
"AD",
"server",
"element",
"using",
"basic",
"settings",
".",
"You",
"can",
"also",
"provide",
"additional",
"kwargs",
"documented",
"in",
"the",
"class",
"description",
"::",
"ActiveDirectoryServer",
".",
"create",
"(",
"name",
"=",
"somedirecto... | python | train |
apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L4803-L4811 | def validateRoot(self, ctxt):
"""Try to validate a the root element basically it does the
following check as described by the XML-1.0 recommendation:
- [ VC: Root Element Type ] it doesn't try to recurse or
apply other check to the element """
if ctxt is None: ctxt__o = No... | [
"def",
"validateRoot",
"(",
"self",
",",
"ctxt",
")",
":",
"if",
"ctxt",
"is",
"None",
":",
"ctxt__o",
"=",
"None",
"else",
":",
"ctxt__o",
"=",
"ctxt",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlValidateRoot",
"(",
"ctxt__o",
",",
"self",
".",
"_... | Try to validate a the root element basically it does the
following check as described by the XML-1.0 recommendation:
- [ VC: Root Element Type ] it doesn't try to recurse or
apply other check to the element | [
"Try",
"to",
"validate",
"a",
"the",
"root",
"element",
"basically",
"it",
"does",
"the",
"following",
"check",
"as",
"described",
"by",
"the",
"XML",
"-",
"1",
".",
"0",
"recommendation",
":",
"-",
"[",
"VC",
":",
"Root",
"Element",
"Type",
"]",
"it",... | python | train |
numenta/htmresearch | htmresearch/data/sm_sequences.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/data/sm_sequences.py#L391-L399 | def printSensoryCodingScheme(self):
"""
Print sensory inputs along with their encoded versions.
"""
print "\nsensory coding scheme: "
for loc in self.spatialConfig:
sensoryElement = self.spatialMap[tuple(loc)]
print sensoryElement, "%s : " % loc,
printSequence(self.encodeSensoryInp... | [
"def",
"printSensoryCodingScheme",
"(",
"self",
")",
":",
"print",
"\"\\nsensory coding scheme: \"",
"for",
"loc",
"in",
"self",
".",
"spatialConfig",
":",
"sensoryElement",
"=",
"self",
".",
"spatialMap",
"[",
"tuple",
"(",
"loc",
")",
"]",
"print",
"sensoryEle... | Print sensory inputs along with their encoded versions. | [
"Print",
"sensory",
"inputs",
"along",
"with",
"their",
"encoded",
"versions",
"."
] | python | train |
heroku/heroku.py | heroku/models.py | https://github.com/heroku/heroku.py/blob/cadc0a074896cf29c65a457c5c5bdb2069470af0/heroku/models.py#L300-L308 | def maintenance(self, on=True):
"""Toggles maintenance mode."""
r = self._h._http_resource(
method='POST',
resource=('apps', self.name, 'server', 'maintenance'),
data={'maintenance_mode': int(on)}
)
return r.ok | [
"def",
"maintenance",
"(",
"self",
",",
"on",
"=",
"True",
")",
":",
"r",
"=",
"self",
".",
"_h",
".",
"_http_resource",
"(",
"method",
"=",
"'POST'",
",",
"resource",
"=",
"(",
"'apps'",
",",
"self",
".",
"name",
",",
"'server'",
",",
"'maintenance'... | Toggles maintenance mode. | [
"Toggles",
"maintenance",
"mode",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.