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 |
|---|---|---|---|---|---|---|---|---|
jazzband/django-push-notifications | push_notifications/apns.py | https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/apns.py#L97-L120 | def apns_send_message(registration_id, alert, application_id=None, certfile=None, **kwargs):
"""
Sends an APNS notification to a single registration_id.
This will send the notification as form data.
If sending multiple notifications, it is more efficient to use
apns_send_bulk_message()
Note that if set alert sho... | [
"def",
"apns_send_message",
"(",
"registration_id",
",",
"alert",
",",
"application_id",
"=",
"None",
",",
"certfile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"_apns_send",
"(",
"registration_id",
",",
"alert",
",",
"application_id",
"=",... | Sends an APNS notification to a single registration_id.
This will send the notification as form data.
If sending multiple notifications, it is more efficient to use
apns_send_bulk_message()
Note that if set alert should always be a string. If it is not set,
it won"t be included in the notification. You will need ... | [
"Sends",
"an",
"APNS",
"notification",
"to",
"a",
"single",
"registration_id",
".",
"This",
"will",
"send",
"the",
"notification",
"as",
"form",
"data",
".",
"If",
"sending",
"multiple",
"notifications",
"it",
"is",
"more",
"efficient",
"to",
"use",
"apns_send... | python | train |
keras-rl/keras-rl | rl/policy.py | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L62-L75 | def get_current_value(self):
"""Return current annealing value
# Returns
Value to use in annealing
"""
if self.agent.training:
# Linear annealed: f(x) = ax + b.
a = -float(self.value_max - self.value_min) / float(self.nb_steps)
b = float(s... | [
"def",
"get_current_value",
"(",
"self",
")",
":",
"if",
"self",
".",
"agent",
".",
"training",
":",
"# Linear annealed: f(x) = ax + b.",
"a",
"=",
"-",
"float",
"(",
"self",
".",
"value_max",
"-",
"self",
".",
"value_min",
")",
"/",
"float",
"(",
"self",
... | Return current annealing value
# Returns
Value to use in annealing | [
"Return",
"current",
"annealing",
"value"
] | python | train |
python-diamond/Diamond | src/diamond/collector.py | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/collector.py#L495-L528 | def find_binary(self, binary):
"""
Scan and return the first path to a binary that we can find
"""
if os.path.exists(binary):
return binary
# Extract out the filename if we were given a full path
binary_name = os.path.basename(binary)
# Gather $PATH
... | [
"def",
"find_binary",
"(",
"self",
",",
"binary",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"binary",
")",
":",
"return",
"binary",
"# Extract out the filename if we were given a full path",
"binary_name",
"=",
"os",
".",
"path",
".",
"basename",
... | Scan and return the first path to a binary that we can find | [
"Scan",
"and",
"return",
"the",
"first",
"path",
"to",
"a",
"binary",
"that",
"we",
"can",
"find"
] | python | train |
TAPPGuild/bitjws | bitjws/jws.py | https://github.com/TAPPGuild/bitjws/blob/bcf943e0c60985da11fb7895a416525e63728c35/bitjws/jws.py#L70-L81 | def _jws_header(keyid, algorithm):
"""Produce a base64-encoded JWS header."""
data = {
'typ': 'JWT',
'alg': algorithm.name,
# 'kid' is used to indicate the public part of the key
# used during signing.
'kid': keyid
}
datajson = json.dumps(data, sort_keys=True).en... | [
"def",
"_jws_header",
"(",
"keyid",
",",
"algorithm",
")",
":",
"data",
"=",
"{",
"'typ'",
":",
"'JWT'",
",",
"'alg'",
":",
"algorithm",
".",
"name",
",",
"# 'kid' is used to indicate the public part of the key",
"# used during signing.",
"'kid'",
":",
"keyid",
"}... | Produce a base64-encoded JWS header. | [
"Produce",
"a",
"base64",
"-",
"encoded",
"JWS",
"header",
"."
] | python | train |
datadesk/django-bakery | bakery/management/commands/publish.py | https://github.com/datadesk/django-bakery/blob/e2feb13a66552a388fbcfaaacdd504bba08d3c69/bakery/management/commands/publish.py#L284-L311 | def sync_with_s3(self):
"""
Walk through our self.local_files list, and match them with the list
of keys in the S3 bucket.
"""
# Create a list to put all the files we're going to update
self.update_list = []
# Figure out which files need to be updated and upload ... | [
"def",
"sync_with_s3",
"(",
"self",
")",
":",
"# Create a list to put all the files we're going to update",
"self",
".",
"update_list",
"=",
"[",
"]",
"# Figure out which files need to be updated and upload all these files",
"logger",
".",
"debug",
"(",
"\"Comparing {} local file... | Walk through our self.local_files list, and match them with the list
of keys in the S3 bucket. | [
"Walk",
"through",
"our",
"self",
".",
"local_files",
"list",
"and",
"match",
"them",
"with",
"the",
"list",
"of",
"keys",
"in",
"the",
"S3",
"bucket",
"."
] | python | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConf.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConf.py#L631-L647 | def TryRun(self, text, extension ):
"""Compiles and runs the program given in text, using extension
as file extension (e.g. '.c'). Returns (1, outputStr) on success,
(0, '') otherwise. The target (a file containing the program's stdout)
is saved in self.lastTarget (for further processing... | [
"def",
"TryRun",
"(",
"self",
",",
"text",
",",
"extension",
")",
":",
"ok",
"=",
"self",
".",
"TryLink",
"(",
"text",
",",
"extension",
")",
"if",
"(",
"ok",
")",
":",
"prog",
"=",
"self",
".",
"lastTarget",
"pname",
"=",
"prog",
".",
"get_interna... | Compiles and runs the program given in text, using extension
as file extension (e.g. '.c'). Returns (1, outputStr) on success,
(0, '') otherwise. The target (a file containing the program's stdout)
is saved in self.lastTarget (for further processing). | [
"Compiles",
"and",
"runs",
"the",
"program",
"given",
"in",
"text",
"using",
"extension",
"as",
"file",
"extension",
"(",
"e",
".",
"g",
".",
".",
"c",
")",
".",
"Returns",
"(",
"1",
"outputStr",
")",
"on",
"success",
"(",
"0",
")",
"otherwise",
".",... | python | train |
aeguana/PyFileMaker | PyFileMaker/xml2obj.py | https://github.com/aeguana/PyFileMaker/blob/ef269b52a97e329d91da3c4851ddac800d7fd7e6/PyFileMaker/xml2obj.py#L35-L46 | def getElements(self,name=''):
'Get a list of child elements'
#If no tag name is specified, return the all children
if not name:
return self.children
else:
# else return only those children with a matching tag name
elements = []
for element in self.children:
if element.name == name:
element... | [
"def",
"getElements",
"(",
"self",
",",
"name",
"=",
"''",
")",
":",
"#If no tag name is specified, return the all children",
"if",
"not",
"name",
":",
"return",
"self",
".",
"children",
"else",
":",
"# else return only those children with a matching tag name",
"elements"... | Get a list of child elements | [
"Get",
"a",
"list",
"of",
"child",
"elements"
] | python | train |
genialis/resolwe | resolwe/flow/managers/listener.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/managers/listener.py#L611-L671 | async def run(self):
"""Run the main listener run loop.
Doesn't return until :meth:`terminate` is called.
"""
logger.info(__(
"Starting Resolwe listener on channel '{}'.",
state.MANAGER_EXECUTOR_CHANNELS.queue
))
while not self._should_stop:
... | [
"async",
"def",
"run",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"__",
"(",
"\"Starting Resolwe listener on channel '{}'.\"",
",",
"state",
".",
"MANAGER_EXECUTOR_CHANNELS",
".",
"queue",
")",
")",
"while",
"not",
"self",
".",
"_should_stop",
":",
"aw... | Run the main listener run loop.
Doesn't return until :meth:`terminate` is called. | [
"Run",
"the",
"main",
"listener",
"run",
"loop",
"."
] | python | train |
quantmind/pulsar | pulsar/async/mixins.py | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/mixins.py#L60-L77 | def resume_writing(self, exc=None):
'''Resume writing.
Successive calls to this method will fails unless
:meth:`pause_writing` is called first.
'''
assert self._paused
self._paused = False
waiter = self._waiter
if waiter is not None:
self._wai... | [
"def",
"resume_writing",
"(",
"self",
",",
"exc",
"=",
"None",
")",
":",
"assert",
"self",
".",
"_paused",
"self",
".",
"_paused",
"=",
"False",
"waiter",
"=",
"self",
".",
"_waiter",
"if",
"waiter",
"is",
"not",
"None",
":",
"self",
".",
"_waiter",
... | Resume writing.
Successive calls to this method will fails unless
:meth:`pause_writing` is called first. | [
"Resume",
"writing",
"."
] | python | train |
saltstack/salt | salt/states/file.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/file.py#L7049-L7426 | def serialize(name,
dataset=None,
dataset_pillar=None,
user=None,
group=None,
mode=None,
backup='',
makedirs=False,
show_changes=True,
create=True,
merge_if_exists=False,
... | [
"def",
"serialize",
"(",
"name",
",",
"dataset",
"=",
"None",
",",
"dataset_pillar",
"=",
"None",
",",
"user",
"=",
"None",
",",
"group",
"=",
"None",
",",
"mode",
"=",
"None",
",",
"backup",
"=",
"''",
",",
"makedirs",
"=",
"False",
",",
"show_chang... | Serializes dataset and store it into managed file. Useful for sharing
simple configuration files.
name
The location of the file to create
dataset
The dataset that will be serialized
dataset_pillar
Operates like ``dataset``, but draws from a value stored in pillar,
usin... | [
"Serializes",
"dataset",
"and",
"store",
"it",
"into",
"managed",
"file",
".",
"Useful",
"for",
"sharing",
"simple",
"configuration",
"files",
"."
] | python | train |
fboender/ansible-cmdb | lib/mako/_ast_util.py | https://github.com/fboender/ansible-cmdb/blob/ebd960ac10684e8c9ec2b12751bba2c4c9504ab7/lib/mako/_ast_util.py#L235-L245 | def walk(node):
"""
Iterate over all nodes. This is useful if you only want to modify nodes in
place and don't care about the context or the order the nodes are returned.
"""
from collections import deque
todo = deque([node])
while todo:
node = todo.popleft()
todo.extend(ite... | [
"def",
"walk",
"(",
"node",
")",
":",
"from",
"collections",
"import",
"deque",
"todo",
"=",
"deque",
"(",
"[",
"node",
"]",
")",
"while",
"todo",
":",
"node",
"=",
"todo",
".",
"popleft",
"(",
")",
"todo",
".",
"extend",
"(",
"iter_child_nodes",
"("... | Iterate over all nodes. This is useful if you only want to modify nodes in
place and don't care about the context or the order the nodes are returned. | [
"Iterate",
"over",
"all",
"nodes",
".",
"This",
"is",
"useful",
"if",
"you",
"only",
"want",
"to",
"modify",
"nodes",
"in",
"place",
"and",
"don",
"t",
"care",
"about",
"the",
"context",
"or",
"the",
"order",
"the",
"nodes",
"are",
"returned",
"."
] | python | train |
carawarner/pantheon | pantheon/gods.py | https://github.com/carawarner/pantheon/blob/7e8718f4397eaa389fb3d5dc04fa01c7cb556512/pantheon/gods.py#L49-L57 | def set_chromosomes(self, chromosomes=None):
"""This model uses the XY sex-determination system. Sex != gender.
Assign either XX or XY randomly with a 50/50 chance of each, unless
<chromosomes> are passed as an argument.
"""
if chromosomes and chromosomes in valid_chromosomes:
... | [
"def",
"set_chromosomes",
"(",
"self",
",",
"chromosomes",
"=",
"None",
")",
":",
"if",
"chromosomes",
"and",
"chromosomes",
"in",
"valid_chromosomes",
":",
"self",
".",
"chromosomes",
"=",
"chromosomes",
"else",
":",
"self",
".",
"chromosomes",
"=",
"random",... | This model uses the XY sex-determination system. Sex != gender.
Assign either XX or XY randomly with a 50/50 chance of each, unless
<chromosomes> are passed as an argument. | [
"This",
"model",
"uses",
"the",
"XY",
"sex",
"-",
"determination",
"system",
".",
"Sex",
"!",
"=",
"gender",
".",
"Assign",
"either",
"XX",
"or",
"XY",
"randomly",
"with",
"a",
"50",
"/",
"50",
"chance",
"of",
"each",
"unless",
"<chromosomes",
">",
"ar... | python | valid |
mitsei/dlkit | dlkit/services/assessment.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/services/assessment.py#L2818-L2826 | def use_comparative_assessment_view(self):
"""Pass through to provider AssessmentLookupSession.use_comparative_assessment_view"""
self._object_views['assessment'] = COMPARATIVE
# self._get_provider_session('assessment_lookup_session') # To make sure the session is tracked
for session in ... | [
"def",
"use_comparative_assessment_view",
"(",
"self",
")",
":",
"self",
".",
"_object_views",
"[",
"'assessment'",
"]",
"=",
"COMPARATIVE",
"# self._get_provider_session('assessment_lookup_session') # To make sure the session is tracked",
"for",
"session",
"in",
"self",
".",
... | Pass through to provider AssessmentLookupSession.use_comparative_assessment_view | [
"Pass",
"through",
"to",
"provider",
"AssessmentLookupSession",
".",
"use_comparative_assessment_view"
] | python | train |
ensime/ensime-vim | ensime_shared/ensime.py | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/ensime.py#L97-L108 | def client_for(self, config_path, quiet=False, bootstrap_server=False,
create_client=False):
"""Get a cached client for a project, otherwise create one."""
client = None
abs_path = os.path.abspath(config_path)
if abs_path in self.clients:
client = self.clie... | [
"def",
"client_for",
"(",
"self",
",",
"config_path",
",",
"quiet",
"=",
"False",
",",
"bootstrap_server",
"=",
"False",
",",
"create_client",
"=",
"False",
")",
":",
"client",
"=",
"None",
"abs_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"config... | Get a cached client for a project, otherwise create one. | [
"Get",
"a",
"cached",
"client",
"for",
"a",
"project",
"otherwise",
"create",
"one",
"."
] | python | train |
titusjan/argos | argos/utils/masks.py | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/masks.py#L114-L130 | def createFromMaskedArray(cls, masked_arr):
""" Creates an ArrayWithMak
:param masked_arr: a numpy MaskedArray or numpy array
:return: ArrayWithMask
"""
if isinstance(masked_arr, ArrayWithMask):
return masked_arr
check_class(masked_arr, (np.ndarray, ... | [
"def",
"createFromMaskedArray",
"(",
"cls",
",",
"masked_arr",
")",
":",
"if",
"isinstance",
"(",
"masked_arr",
",",
"ArrayWithMask",
")",
":",
"return",
"masked_arr",
"check_class",
"(",
"masked_arr",
",",
"(",
"np",
".",
"ndarray",
",",
"ma",
".",
"MaskedA... | Creates an ArrayWithMak
:param masked_arr: a numpy MaskedArray or numpy array
:return: ArrayWithMask | [
"Creates",
"an",
"ArrayWithMak"
] | python | train |
Azure/azure-cosmos-table-python | azure-cosmosdb-table/azure/cosmosdb/table/tableservice.py | https://github.com/Azure/azure-cosmos-table-python/blob/a7b618f6bddc465c9fdf899ea2971dfe4d04fcf0/azure-cosmosdb-table/azure/cosmosdb/table/tableservice.py#L848-L859 | def batch(self, table_name, timeout=None):
'''
Creates a batch object which can be used as a context manager. Commits the batch on exit.
:param str table_name:
The name of the table to commit the batch to.
:param int timeout:
The server timeout, expressed in seco... | [
"def",
"batch",
"(",
"self",
",",
"table_name",
",",
"timeout",
"=",
"None",
")",
":",
"batch",
"=",
"TableBatch",
"(",
"self",
".",
"require_encryption",
",",
"self",
".",
"key_encryption_key",
",",
"self",
".",
"encryption_resolver_function",
")",
"yield",
... | Creates a batch object which can be used as a context manager. Commits the batch on exit.
:param str table_name:
The name of the table to commit the batch to.
:param int timeout:
The server timeout, expressed in seconds. | [
"Creates",
"a",
"batch",
"object",
"which",
"can",
"be",
"used",
"as",
"a",
"context",
"manager",
".",
"Commits",
"the",
"batch",
"on",
"exit",
"."
] | python | train |
aholkner/bacon | bacon/graphics.py | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/bacon/graphics.py#L181-L195 | def draw_image(image, x1, y1, x2 = None, y2 = None):
'''Draw an image.
The image's top-left corner is drawn at ``(x1, y1)``, and its lower-left at ``(x2, y2)``. If ``x2`` and ``y2`` are omitted, they
are calculated to render the image at its native resoultion.
Note that images can be flipped and scal... | [
"def",
"draw_image",
"(",
"image",
",",
"x1",
",",
"y1",
",",
"x2",
"=",
"None",
",",
"y2",
"=",
"None",
")",
":",
"if",
"x2",
"is",
"None",
":",
"x2",
"=",
"x1",
"+",
"image",
".",
"width",
"if",
"y2",
"is",
"None",
":",
"y2",
"=",
"y1",
"... | Draw an image.
The image's top-left corner is drawn at ``(x1, y1)``, and its lower-left at ``(x2, y2)``. If ``x2`` and ``y2`` are omitted, they
are calculated to render the image at its native resoultion.
Note that images can be flipped and scaled by providing alternative values for ``x2`` and ``y2``.
... | [
"Draw",
"an",
"image",
"."
] | python | test |
nevimov/django-easycart | easycart/cart.py | https://github.com/nevimov/django-easycart/blob/81b7d7d4b197e34d21dcd8cb9eb9104b565041a9/easycart/cart.py#L232-L257 | def change_quantity(self, pk, quantity):
"""Change the quantity of an item.
Parameters
----------
pk : str or int
The primary key of the item.
quantity : int-convertible
A new quantity.
Raises
------
ItemNotInCart
Negative... | [
"def",
"change_quantity",
"(",
"self",
",",
"pk",
",",
"quantity",
")",
":",
"pk",
"=",
"str",
"(",
"pk",
")",
"try",
":",
"item",
"=",
"self",
".",
"items",
"[",
"pk",
"]",
"except",
"KeyError",
":",
"raise",
"ItemNotInCart",
"(",
"pk",
"=",
"pk",... | Change the quantity of an item.
Parameters
----------
pk : str or int
The primary key of the item.
quantity : int-convertible
A new quantity.
Raises
------
ItemNotInCart
NegativeItemQuantity
NonConvertibleItemQuantity
... | [
"Change",
"the",
"quantity",
"of",
"an",
"item",
"."
] | python | train |
nerdvegas/rez | src/rez/vendor/pygraph/algorithms/minmax.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/minmax.py#L243-L310 | def heuristic_search(graph, start, goal, heuristic):
"""
A* search algorithm.
A set of heuristics is available under C{graph.algorithms.heuristics}. User-created heuristics
are allowed too.
@type graph: graph, digraph
@param graph: Graph
@type start: node
@param start: Sta... | [
"def",
"heuristic_search",
"(",
"graph",
",",
"start",
",",
"goal",
",",
"heuristic",
")",
":",
"# The queue stores priority, node, cost to reach, and parent.",
"queue",
"=",
"[",
"(",
"0",
",",
"start",
",",
"0",
",",
"None",
")",
"]",
"# This dictionary maps que... | A* search algorithm.
A set of heuristics is available under C{graph.algorithms.heuristics}. User-created heuristics
are allowed too.
@type graph: graph, digraph
@param graph: Graph
@type start: node
@param start: Start node
@type goal: node
@param goal: Goal node
... | [
"A",
"*",
"search",
"algorithm",
".",
"A",
"set",
"of",
"heuristics",
"is",
"available",
"under",
"C",
"{",
"graph",
".",
"algorithms",
".",
"heuristics",
"}",
".",
"User",
"-",
"created",
"heuristics",
"are",
"allowed",
"too",
"."
] | python | train |
cslarsen/crianza | crianza/compiler.py | https://github.com/cslarsen/crianza/blob/fa044f9d491f37cc06892bad14b2c80b8ac5a7cd/crianza/compiler.py#L68-L186 | def compile(code, silent=True, ignore_errors=False, optimize=True):
"""Compiles subroutine-forms into a complete working code.
A program such as:
: sub1 <sub1 code ...> ;
: sub2 <sub2 code ...> ;
sub1 foo sub2 bar
is compiled into:
<sub1 address> call
foo
... | [
"def",
"compile",
"(",
"code",
",",
"silent",
"=",
"True",
",",
"ignore_errors",
"=",
"False",
",",
"optimize",
"=",
"True",
")",
":",
"assert",
"(",
"isinstance",
"(",
"code",
",",
"list",
")",
")",
"output",
"=",
"[",
"]",
"subroutine",
"=",
"{",
... | Compiles subroutine-forms into a complete working code.
A program such as:
: sub1 <sub1 code ...> ;
: sub2 <sub2 code ...> ;
sub1 foo sub2 bar
is compiled into:
<sub1 address> call
foo
<sub2 address> call
exit
<sub1 code ...> return
<su... | [
"Compiles",
"subroutine",
"-",
"forms",
"into",
"a",
"complete",
"working",
"code",
"."
] | python | train |
jahuth/litus | spikes.py | https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/spikes.py#L1432-L1436 | def linspace_bins(self,dim,*args,**kwargs):
"""
Like linspace, but shifts the space to create edges for histograms.
"""
return self.spike_times.get_label(dim).linspace_bins(*args,**kwargs) | [
"def",
"linspace_bins",
"(",
"self",
",",
"dim",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"spike_times",
".",
"get_label",
"(",
"dim",
")",
".",
"linspace_bins",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Like linspace, but shifts the space to create edges for histograms. | [
"Like",
"linspace",
"but",
"shifts",
"the",
"space",
"to",
"create",
"edges",
"for",
"histograms",
"."
] | python | train |
ntucllab/libact | libact/base/dataset.py | https://github.com/ntucllab/libact/blob/e37e9ed6c36febe701d84b2d495c958ab02f0bc8/libact/base/dataset.py#L82-L102 | def append(self, feature, label=None):
"""
Add a (feature, label) entry into the dataset.
A None label indicates an unlabeled entry.
Parameters
----------
feature : {array-like}, shape = (n_features)
Feature of the sample to append to dataset.
label ... | [
"def",
"append",
"(",
"self",
",",
"feature",
",",
"label",
"=",
"None",
")",
":",
"self",
".",
"data",
".",
"append",
"(",
"(",
"feature",
",",
"label",
")",
")",
"self",
".",
"modified",
"=",
"True",
"return",
"len",
"(",
"self",
".",
"data",
"... | Add a (feature, label) entry into the dataset.
A None label indicates an unlabeled entry.
Parameters
----------
feature : {array-like}, shape = (n_features)
Feature of the sample to append to dataset.
label : {int, None}
Label of the sample to append to ... | [
"Add",
"a",
"(",
"feature",
"label",
")",
"entry",
"into",
"the",
"dataset",
".",
"A",
"None",
"label",
"indicates",
"an",
"unlabeled",
"entry",
"."
] | python | train |
7sDream/zhihu-py3 | zhihu/author.py | https://github.com/7sDream/zhihu-py3/blob/bcb4aa8325f8b54d3b44bd0bdc959edd9761fcfc/zhihu/author.py#L174-L186 | def follower_num(self):
"""获取追随者数量,就是关注此人的人数.
:return: 追随者数量
:rtype: int
"""
if self.url is None:
return 0
else:
number = int(self.soup.find(
'div', class_='zm-profile-side-following zg-clear').find_all(
'a')[1].str... | [
"def",
"follower_num",
"(",
"self",
")",
":",
"if",
"self",
".",
"url",
"is",
"None",
":",
"return",
"0",
"else",
":",
"number",
"=",
"int",
"(",
"self",
".",
"soup",
".",
"find",
"(",
"'div'",
",",
"class_",
"=",
"'zm-profile-side-following zg-clear'",
... | 获取追随者数量,就是关注此人的人数.
:return: 追随者数量
:rtype: int | [
"获取追随者数量,就是关注此人的人数",
"."
] | python | train |
Shopify/shopify_python_api | scripts/shopify_api.py | https://github.com/Shopify/shopify_python_api/blob/88d3ba332fb2cd331f87517a16f2c2d4296cee90/scripts/shopify_api.py#L62-L86 | def help(cls, task=None):
"""Describe available tasks or one specific task"""
if task is None:
usage_list = []
for task in iter(cls._tasks):
task_func = getattr(cls, task)
usage_string = " %s %s" % (cls._prog, task_func.usage)
desc... | [
"def",
"help",
"(",
"cls",
",",
"task",
"=",
"None",
")",
":",
"if",
"task",
"is",
"None",
":",
"usage_list",
"=",
"[",
"]",
"for",
"task",
"in",
"iter",
"(",
"cls",
".",
"_tasks",
")",
":",
"task_func",
"=",
"getattr",
"(",
"cls",
",",
"task",
... | Describe available tasks or one specific task | [
"Describe",
"available",
"tasks",
"or",
"one",
"specific",
"task"
] | python | train |
TkTech/PyNBT | pynbt/nbt.py | https://github.com/TkTech/PyNBT/blob/060fb0a2b58fc464a637fc108f05bd7274da8e5f/pynbt/nbt.py#L345-L356 | def save(self, io, little_endian=False):
"""
Saves the `NBTFile()` to `io`, which can be any file-like object
providing `write()`.
"""
if little_endian:
write = lambda fmt, *args: io.write(pack('<' + fmt, *args))
else:
write = lambda fmt, *args: io... | [
"def",
"save",
"(",
"self",
",",
"io",
",",
"little_endian",
"=",
"False",
")",
":",
"if",
"little_endian",
":",
"write",
"=",
"lambda",
"fmt",
",",
"*",
"args",
":",
"io",
".",
"write",
"(",
"pack",
"(",
"'<'",
"+",
"fmt",
",",
"*",
"args",
")",... | Saves the `NBTFile()` to `io`, which can be any file-like object
providing `write()`. | [
"Saves",
"the",
"NBTFile",
"()",
"to",
"io",
"which",
"can",
"be",
"any",
"file",
"-",
"like",
"object",
"providing",
"write",
"()",
"."
] | python | train |
libyal/dtfabric | dtfabric/data_types.py | https://github.com/libyal/dtfabric/blob/0d2b5719fa257f6e5c661a406737ebcf8c8db266/dtfabric/data_types.py#L562-L578 | def GetByteSize(self):
"""Retrieves the byte size of the data type definition.
Returns:
int: data type size in bytes or None if size cannot be determined.
"""
if self._byte_size is None and self.members:
self._byte_size = 0
for member_definition in self.members:
byte_size = me... | [
"def",
"GetByteSize",
"(",
"self",
")",
":",
"if",
"self",
".",
"_byte_size",
"is",
"None",
"and",
"self",
".",
"members",
":",
"self",
".",
"_byte_size",
"=",
"0",
"for",
"member_definition",
"in",
"self",
".",
"members",
":",
"byte_size",
"=",
"member_... | Retrieves the byte size of the data type definition.
Returns:
int: data type size in bytes or None if size cannot be determined. | [
"Retrieves",
"the",
"byte",
"size",
"of",
"the",
"data",
"type",
"definition",
"."
] | python | train |
serge-sans-paille/pythran | pythran/spec.py | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/spec.py#L394-L403 | def p_term(self, p):
'''term : STR
| NONE
| dtype'''
if p[1] == 'str':
p[0] = str
elif p[1] == 'None':
p[0] = type(None)
else:
p[0] = p[1][0] | [
"def",
"p_term",
"(",
"self",
",",
"p",
")",
":",
"if",
"p",
"[",
"1",
"]",
"==",
"'str'",
":",
"p",
"[",
"0",
"]",
"=",
"str",
"elif",
"p",
"[",
"1",
"]",
"==",
"'None'",
":",
"p",
"[",
"0",
"]",
"=",
"type",
"(",
"None",
")",
"else",
... | term : STR
| NONE
| dtype | [
"term",
":",
"STR",
"|",
"NONE",
"|",
"dtype"
] | python | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/collectionseditor.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1028-L1044 | def remove_item(self):
"""Remove item"""
indexes = self.selectedIndexes()
if not indexes:
return
for index in indexes:
if not index.isValid():
return
one = _("Do you want to remove the selected item?")
more = _("Do you want... | [
"def",
"remove_item",
"(",
"self",
")",
":",
"indexes",
"=",
"self",
".",
"selectedIndexes",
"(",
")",
"if",
"not",
"indexes",
":",
"return",
"for",
"index",
"in",
"indexes",
":",
"if",
"not",
"index",
".",
"isValid",
"(",
")",
":",
"return",
"one",
... | Remove item | [
"Remove",
"item"
] | python | train |
bspaans/python-mingus | mingus/midi/sequencer.py | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L190-L217 | def play_Bar(self, bar, channel=1, bpm=120):
"""Play a Bar object.
Return a dictionary with the bpm lemma set on success, an empty dict
on some kind of failure.
The tempo can be changed by setting the bpm attribute on a
NoteContainer.
"""
self.notify_listeners(s... | [
"def",
"play_Bar",
"(",
"self",
",",
"bar",
",",
"channel",
"=",
"1",
",",
"bpm",
"=",
"120",
")",
":",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_PLAY_BAR",
",",
"{",
"'bar'",
":",
"bar",
",",
"'channel'",
":",
"channel",
",",
"'bpm'",
... | Play a Bar object.
Return a dictionary with the bpm lemma set on success, an empty dict
on some kind of failure.
The tempo can be changed by setting the bpm attribute on a
NoteContainer. | [
"Play",
"a",
"Bar",
"object",
"."
] | python | train |
linuxsoftware/ls.joyous | ls/joyous/models/events.py | https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L198-L214 | def getAllEvents(request, *, home=None):
"""
Return all the events (under home if given).
:param request: Django request object
:param home: only include events that are under this page (if given)
:rtype: list of event pages
"""
qrys = [SimpleEventPage.events(request).all(),
Mul... | [
"def",
"getAllEvents",
"(",
"request",
",",
"*",
",",
"home",
"=",
"None",
")",
":",
"qrys",
"=",
"[",
"SimpleEventPage",
".",
"events",
"(",
"request",
")",
".",
"all",
"(",
")",
",",
"MultidayEventPage",
".",
"events",
"(",
"request",
")",
".",
"al... | Return all the events (under home if given).
:param request: Django request object
:param home: only include events that are under this page (if given)
:rtype: list of event pages | [
"Return",
"all",
"the",
"events",
"(",
"under",
"home",
"if",
"given",
")",
"."
] | python | train |
ciena/afkak | afkak/producer.py | https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/producer.py#L268-L277 | def _send_timer_stopped(self, lCall):
"""
We're shutting down, clean up our looping call...
"""
if self._sendLooper is not lCall:
log.warning('commitTimerStopped with wrong timer:%s not:%s',
lCall, self._sendLooper)
else:
self._send... | [
"def",
"_send_timer_stopped",
"(",
"self",
",",
"lCall",
")",
":",
"if",
"self",
".",
"_sendLooper",
"is",
"not",
"lCall",
":",
"log",
".",
"warning",
"(",
"'commitTimerStopped with wrong timer:%s not:%s'",
",",
"lCall",
",",
"self",
".",
"_sendLooper",
")",
"... | We're shutting down, clean up our looping call... | [
"We",
"re",
"shutting",
"down",
"clean",
"up",
"our",
"looping",
"call",
"..."
] | python | train |
secdev/scapy | scapy/contrib/http2.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/contrib/http2.py#L1834-L1855 | def get_hdrs_len(self):
# type: () -> int
""" get_hdrs_len computes the length of the hdrs field
To do this computation, the length of the padlen field, reserved,
stream_id and the actual padding is subtracted to the string that was
provided to the pre_dissect fun of the pkt par... | [
"def",
"get_hdrs_len",
"(",
"self",
")",
":",
"# type: () -> int",
"fld",
",",
"padding_len",
"=",
"self",
".",
"getfield_and_val",
"(",
"'padlen'",
")",
"padding_len_len",
"=",
"fld",
".",
"i2len",
"(",
"self",
",",
"padding_len",
")",
"bit_len",
"=",
"self... | get_hdrs_len computes the length of the hdrs field
To do this computation, the length of the padlen field, reserved,
stream_id and the actual padding is subtracted to the string that was
provided to the pre_dissect fun of the pkt parameter.
@return int: the length of the hdrs field
... | [
"get_hdrs_len",
"computes",
"the",
"length",
"of",
"the",
"hdrs",
"field"
] | python | train |
thunder-project/thunder | thunder/base.py | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/base.py#L159-L166 | def npartitions(self):
"""
Get number of partitions (Spark only).
"""
if self.mode == 'spark':
return self.tordd().getNumPartitions()
else:
notsupported(self.mode) | [
"def",
"npartitions",
"(",
"self",
")",
":",
"if",
"self",
".",
"mode",
"==",
"'spark'",
":",
"return",
"self",
".",
"tordd",
"(",
")",
".",
"getNumPartitions",
"(",
")",
"else",
":",
"notsupported",
"(",
"self",
".",
"mode",
")"
] | Get number of partitions (Spark only). | [
"Get",
"number",
"of",
"partitions",
"(",
"Spark",
"only",
")",
"."
] | python | train |
HewlettPackard/python-hpOneView | hpOneView/resources/networking/sas_logical_interconnects.py | https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/networking/sas_logical_interconnects.py#L100-L108 | def get_firmware(self):
"""
Gets baseline firmware information for a SAS Logical Interconnect.
Returns:
dict: SAS Logical Interconnect Firmware.
"""
firmware_uri = "{}/firmware".format(self.data["uri"])
return self._helper.do_get(firmware_uri) | [
"def",
"get_firmware",
"(",
"self",
")",
":",
"firmware_uri",
"=",
"\"{}/firmware\"",
".",
"format",
"(",
"self",
".",
"data",
"[",
"\"uri\"",
"]",
")",
"return",
"self",
".",
"_helper",
".",
"do_get",
"(",
"firmware_uri",
")"
] | Gets baseline firmware information for a SAS Logical Interconnect.
Returns:
dict: SAS Logical Interconnect Firmware. | [
"Gets",
"baseline",
"firmware",
"information",
"for",
"a",
"SAS",
"Logical",
"Interconnect",
"."
] | python | train |
elyase/masstable | masstable/masstable.py | https://github.com/elyase/masstable/blob/3eb72b22cd3337bc5c6bb95bb7bb73fdbe6ae9e2/masstable/masstable.py#L500-L507 | def ds2p(self):
"""Calculates the derivative of the neutron separation energies:
ds2n(Z,A) = s2n(Z,A) - s2n(Z,A+2)
"""
idx = [(x[0] + 2, x[1]) for x in self.df.index]
values = self.s2p.values - self.s2p.loc[idx].values
return Table(df=pd.Series(values, index=self.df.inde... | [
"def",
"ds2p",
"(",
"self",
")",
":",
"idx",
"=",
"[",
"(",
"x",
"[",
"0",
"]",
"+",
"2",
",",
"x",
"[",
"1",
"]",
")",
"for",
"x",
"in",
"self",
".",
"df",
".",
"index",
"]",
"values",
"=",
"self",
".",
"s2p",
".",
"values",
"-",
"self",... | Calculates the derivative of the neutron separation energies:
ds2n(Z,A) = s2n(Z,A) - s2n(Z,A+2) | [
"Calculates",
"the",
"derivative",
"of",
"the",
"neutron",
"separation",
"energies",
":"
] | python | test |
wright-group/WrightTools | WrightTools/data/_data.py | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_data.py#L1547-L1613 | def smooth(self, factors, channel=None, verbose=True) -> "Data":
"""Smooth a channel using an n-dimenional kaiser window.
Note, all arrays are loaded into memory.
For more info see `Kaiser_window`__ wikipedia entry.
__ https://en.wikipedia.org/wiki/Kaiser_window
Parameters
... | [
"def",
"smooth",
"(",
"self",
",",
"factors",
",",
"channel",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
"->",
"\"Data\"",
":",
"warnings",
".",
"warn",
"(",
"\"smooth\"",
",",
"category",
"=",
"wt_exceptions",
".",
"EntireDatasetInMemoryWarning",
")",
... | Smooth a channel using an n-dimenional kaiser window.
Note, all arrays are loaded into memory.
For more info see `Kaiser_window`__ wikipedia entry.
__ https://en.wikipedia.org/wiki/Kaiser_window
Parameters
----------
factors : int or list of int
The smooth... | [
"Smooth",
"a",
"channel",
"using",
"an",
"n",
"-",
"dimenional",
"kaiser",
"window",
"."
] | python | train |
inveniosoftware/invenio-jsonschemas | invenio_jsonschemas/ext.py | https://github.com/inveniosoftware/invenio-jsonschemas/blob/93019b8fe3bf549335e94c84198c9c0b76d8fde2/invenio_jsonschemas/ext.py#L71-L77 | def register_schema(self, directory, path):
"""Register a json-schema.
:param directory: root directory path.
:param path: schema path, relative to the root directory.
"""
self.schemas[path] = os.path.abspath(directory) | [
"def",
"register_schema",
"(",
"self",
",",
"directory",
",",
"path",
")",
":",
"self",
".",
"schemas",
"[",
"path",
"]",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"directory",
")"
] | Register a json-schema.
:param directory: root directory path.
:param path: schema path, relative to the root directory. | [
"Register",
"a",
"json",
"-",
"schema",
"."
] | python | train |
chaoss/grimoirelab-elk | grimoire_elk/enriched/bugzillarest.py | https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/bugzillarest.py#L49-L54 | def get_identities(self, item):
""" Return the identities from an item """
for rol in self.roles:
if rol in item['data']:
yield self.get_sh_identity(item["data"][rol]) | [
"def",
"get_identities",
"(",
"self",
",",
"item",
")",
":",
"for",
"rol",
"in",
"self",
".",
"roles",
":",
"if",
"rol",
"in",
"item",
"[",
"'data'",
"]",
":",
"yield",
"self",
".",
"get_sh_identity",
"(",
"item",
"[",
"\"data\"",
"]",
"[",
"rol",
... | Return the identities from an item | [
"Return",
"the",
"identities",
"from",
"an",
"item"
] | python | train |
farzadghanei/distutilazy | distutilazy/clean.py | https://github.com/farzadghanei/distutilazy/blob/c3c7d062f7cb79abb7677cac57dd752127ff78e7/distutilazy/clean.py#L100-L111 | def find_compiled_files(self):
"""Find compiled Python files recursively in the root path
:return: list of absolute file paths
"""
files = self._find_files()
self.announce(
"found '{}' compiled python files in '{}'".format(
len(files), self.root
... | [
"def",
"find_compiled_files",
"(",
"self",
")",
":",
"files",
"=",
"self",
".",
"_find_files",
"(",
")",
"self",
".",
"announce",
"(",
"\"found '{}' compiled python files in '{}'\"",
".",
"format",
"(",
"len",
"(",
"files",
")",
",",
"self",
".",
"root",
")"... | Find compiled Python files recursively in the root path
:return: list of absolute file paths | [
"Find",
"compiled",
"Python",
"files",
"recursively",
"in",
"the",
"root",
"path"
] | python | train |
onicagroup/runway | runway/module/terraform.py | https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/module/terraform.py#L180-L217 | def run_terraform_init(tf_bin, # pylint: disable=too-many-arguments
module_path, backend_options, env_name, env_region,
env_vars):
"""Run Terraform init."""
init_cmd = [tf_bin, 'init']
cmd_opts = {'env_vars': env_vars, 'exit_on_error': False}
if backend_op... | [
"def",
"run_terraform_init",
"(",
"tf_bin",
",",
"# pylint: disable=too-many-arguments",
"module_path",
",",
"backend_options",
",",
"env_name",
",",
"env_region",
",",
"env_vars",
")",
":",
"init_cmd",
"=",
"[",
"tf_bin",
",",
"'init'",
"]",
"cmd_opts",
"=",
"{",... | Run Terraform init. | [
"Run",
"Terraform",
"init",
"."
] | python | train |
intiocean/pyinter | pyinter/interval.py | https://github.com/intiocean/pyinter/blob/fb6e904307477fa43123cc9ab326680aa1a8cd62/pyinter/interval.py#L264-L291 | def difference(self, other):
"""Returns a new Interval or an :class:`~pyinter.IntervalSet` representing the subtraction of this
:class:`~pyinter.Interval` with the other :class:`~pyinter.Interval`.
The result will contain everything that is contained by the left interval but not contained
... | [
"def",
"difference",
"(",
"self",
",",
"other",
")",
":",
"if",
"other",
".",
"empty",
"(",
")",
":",
"return",
"self",
"if",
"self",
"in",
"other",
":",
"return",
"open",
"(",
"self",
".",
"_lower_value",
",",
"self",
".",
"_lower_value",
")",
"if",... | Returns a new Interval or an :class:`~pyinter.IntervalSet` representing the subtraction of this
:class:`~pyinter.Interval` with the other :class:`~pyinter.Interval`.
The result will contain everything that is contained by the left interval but not contained
by the second interval.
If t... | [
"Returns",
"a",
"new",
"Interval",
"or",
"an",
":",
"class",
":",
"~pyinter",
".",
"IntervalSet",
"representing",
"the",
"subtraction",
"of",
"this",
":",
"class",
":",
"~pyinter",
".",
"Interval",
"with",
"the",
"other",
":",
"class",
":",
"~pyinter",
"."... | python | train |
SeleniumHQ/selenium | py/selenium/webdriver/common/action_chains.py | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/action_chains.py#L280-L299 | def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""
Move the mouse by an offset of the specified element.
Offsets are relative to the top-left corner of the element.
:Args:
- to_element: The WebElement to move to.
- xoffset: X offset to move to.... | [
"def",
"move_to_element_with_offset",
"(",
"self",
",",
"to_element",
",",
"xoffset",
",",
"yoffset",
")",
":",
"if",
"self",
".",
"_driver",
".",
"w3c",
":",
"self",
".",
"w3c_actions",
".",
"pointer_action",
".",
"move_to",
"(",
"to_element",
",",
"xoffset... | Move the mouse by an offset of the specified element.
Offsets are relative to the top-left corner of the element.
:Args:
- to_element: The WebElement to move to.
- xoffset: X offset to move to.
- yoffset: Y offset to move to. | [
"Move",
"the",
"mouse",
"by",
"an",
"offset",
"of",
"the",
"specified",
"element",
".",
"Offsets",
"are",
"relative",
"to",
"the",
"top",
"-",
"left",
"corner",
"of",
"the",
"element",
"."
] | python | train |
SeabornGames/RequestClient | example_bindings/echo.py | https://github.com/SeabornGames/RequestClient/blob/21aeb951ddfdb6ee453ad0edc896ff224e06425d/example_bindings/echo.py#L121-L128 | def post(self, key='hello', value='world'):
"""
This takes two parameters a key and a value and temporarily stores them on the server
:param key: str of key to store the value under
:param value: str of the value to store
:return: Echo dict of the key value store... | [
"def",
"post",
"(",
"self",
",",
"key",
"=",
"'hello'",
",",
"value",
"=",
"'world'",
")",
":",
"return",
"self",
".",
"connection",
".",
"post",
"(",
"'echo/key'",
",",
"data",
"=",
"dict",
"(",
"key",
"=",
"key",
",",
"value",
"=",
"value",
")",
... | This takes two parameters a key and a value and temporarily stores them on the server
:param key: str of key to store the value under
:param value: str of the value to store
:return: Echo dict of the key value stored | [
"This",
"takes",
"two",
"parameters",
"a",
"key",
"and",
"a",
"value",
"and",
"temporarily",
"stores",
"them",
"on",
"the",
"server",
":",
"param",
"key",
":",
"str",
"of",
"key",
"to",
"store",
"the",
"value",
"under",
":",
"param",
"value",
":",
"str... | python | train |
Dallinger/Dallinger | dallinger/data.py | https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/data.py#L332-L347 | def _get_or_create_s3_bucket(s3, name):
"""Get an S3 bucket resource after making sure it exists"""
exists = True
try:
s3.meta.client.head_bucket(Bucket=name)
except botocore.exceptions.ClientError as e:
error_code = int(e.response["Error"]["Code"])
if error_code == 404:
... | [
"def",
"_get_or_create_s3_bucket",
"(",
"s3",
",",
"name",
")",
":",
"exists",
"=",
"True",
"try",
":",
"s3",
".",
"meta",
".",
"client",
".",
"head_bucket",
"(",
"Bucket",
"=",
"name",
")",
"except",
"botocore",
".",
"exceptions",
".",
"ClientError",
"a... | Get an S3 bucket resource after making sure it exists | [
"Get",
"an",
"S3",
"bucket",
"resource",
"after",
"making",
"sure",
"it",
"exists"
] | python | train |
Azure/blobxfer | blobxfer/operations/download.py | https://github.com/Azure/blobxfer/blob/3eccbe7530cc6a20ab2d30f9e034b6f021817f34/blobxfer/operations/download.py#L515-L590 | def _process_download_descriptor(self, dd):
# type: (Downloader, blobxfer.models.download.Descriptor) -> None
"""Process download descriptor
:param Downloader self: this
:param blobxfer.models.download.Descriptor dd: download descriptor
"""
# update progress bar
s... | [
"def",
"_process_download_descriptor",
"(",
"self",
",",
"dd",
")",
":",
"# type: (Downloader, blobxfer.models.download.Descriptor) -> None",
"# update progress bar",
"self",
".",
"_update_progress_bar",
"(",
")",
"# get download offsets",
"offsets",
",",
"resume_bytes",
"=",
... | Process download descriptor
:param Downloader self: this
:param blobxfer.models.download.Descriptor dd: download descriptor | [
"Process",
"download",
"descriptor",
":",
"param",
"Downloader",
"self",
":",
"this",
":",
"param",
"blobxfer",
".",
"models",
".",
"download",
".",
"Descriptor",
"dd",
":",
"download",
"descriptor"
] | python | train |
PredixDev/predixpy | predix/admin/app.py | https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/app.py#L179-L190 | def create_logstash(self, **kwargs):
"""
Creates an instance of the Logging Service.
"""
logstash = predix.admin.logstash.Logging(**kwargs)
logstash.create()
logstash.add_to_manifest(self)
logging.info('Install Kibana-Me-Logs application by following GitHub instr... | [
"def",
"create_logstash",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"logstash",
"=",
"predix",
".",
"admin",
".",
"logstash",
".",
"Logging",
"(",
"*",
"*",
"kwargs",
")",
"logstash",
".",
"create",
"(",
")",
"logstash",
".",
"add_to_manifest",
"... | Creates an instance of the Logging Service. | [
"Creates",
"an",
"instance",
"of",
"the",
"Logging",
"Service",
"."
] | python | train |
pyroscope/pyrobase | src/pyrobase/io/http.py | https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/src/pyrobase/io/http.py#L99-L134 | def _encode_multipart_formdata(self):
""" Encode POST body.
Return (content_type, body) ready for httplib.HTTP instance
"""
def get_content_type(filename):
"Helper to get MIME type."
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
... | [
"def",
"_encode_multipart_formdata",
"(",
"self",
")",
":",
"def",
"get_content_type",
"(",
"filename",
")",
":",
"\"Helper to get MIME type.\"",
"return",
"mimetypes",
".",
"guess_type",
"(",
"filename",
")",
"[",
"0",
"]",
"or",
"'application/octet-stream'",
"boun... | Encode POST body.
Return (content_type, body) ready for httplib.HTTP instance | [
"Encode",
"POST",
"body",
".",
"Return",
"(",
"content_type",
"body",
")",
"ready",
"for",
"httplib",
".",
"HTTP",
"instance"
] | python | train |
rootpy/rootpy | rootpy/extern/byteplay2/__init__.py | https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/extern/byteplay2/__init__.py#L887-L899 | def recompile_all(path):
"""recursively recompile all .py files in the directory"""
import os
if os.path.isdir(path):
for root, dirs, files in os.walk(path):
for name in files:
if name.endswith('.py'):
filename = os.path.abspath(os.path.join(root, name... | [
"def",
"recompile_all",
"(",
"path",
")",
":",
"import",
"os",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"for",
"name",
"in",
"files",
... | recursively recompile all .py files in the directory | [
"recursively",
"recompile",
"all",
".",
"py",
"files",
"in",
"the",
"directory"
] | python | train |
projectshift/shift-schema | shiftschema/schema.py | https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/schema.py#L149-L166 | def set(self, model, property_name, value):
"""
Set model property to value. Use setter if possible.
:param model: model object or dict
:param property_name: str, name on the model
:param value: mixed, a value to set
:return: None
"""
if type(model) is dic... | [
"def",
"set",
"(",
"self",
",",
"model",
",",
"property_name",
",",
"value",
")",
":",
"if",
"type",
"(",
"model",
")",
"is",
"dict",
":",
"model",
"[",
"property_name",
"]",
"=",
"value",
"elif",
"hasattr",
"(",
"model",
",",
"'set_'",
"+",
"propert... | Set model property to value. Use setter if possible.
:param model: model object or dict
:param property_name: str, name on the model
:param value: mixed, a value to set
:return: None | [
"Set",
"model",
"property",
"to",
"value",
".",
"Use",
"setter",
"if",
"possible",
".",
":",
"param",
"model",
":",
"model",
"object",
"or",
"dict",
":",
"param",
"property_name",
":",
"str",
"name",
"on",
"the",
"model",
":",
"param",
"value",
":",
"m... | python | train |
smarie/python-parsyfiles | parsyfiles/plugins_base/support_for_objects.py | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/plugins_base/support_for_objects.py#L336-L363 | def dict_to_object(desired_type: Type[T], contents_dict: Dict[str, Any], logger: Logger,
options: Dict[str, Dict[str, Any]], conversion_finder: ConversionFinder = None,
is_dict_of_dicts: bool = False) -> T:
"""
Utility method to create an object from a dictionary of constru... | [
"def",
"dict_to_object",
"(",
"desired_type",
":",
"Type",
"[",
"T",
"]",
",",
"contents_dict",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"logger",
":",
"Logger",
",",
"options",
":",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"Any",
"]... | Utility method to create an object from a dictionary of constructor arguments. Constructor arguments that dont have
the correct type are intelligently converted if possible
:param desired_type:
:param contents_dict:
:param logger:
:param options:
:param conversion_finder:
:param is_dict_of_... | [
"Utility",
"method",
"to",
"create",
"an",
"object",
"from",
"a",
"dictionary",
"of",
"constructor",
"arguments",
".",
"Constructor",
"arguments",
"that",
"dont",
"have",
"the",
"correct",
"type",
"are",
"intelligently",
"converted",
"if",
"possible"
] | python | train |
kwikteam/phy | phy/io/datasets.py | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/io/datasets.py#L103-L138 | def download_file(url, output_path):
"""Download a binary file from an URL.
The checksum will be downloaded from `URL + .md5`. If this download
succeeds, the file's MD5 will be compared to the expected checksum.
Parameters
----------
url : str
The file's URL.
output_path : str
... | [
"def",
"download_file",
"(",
"url",
",",
"output_path",
")",
":",
"output_path",
"=",
"op",
".",
"realpath",
"(",
"output_path",
")",
"assert",
"output_path",
"is",
"not",
"None",
"if",
"op",
".",
"exists",
"(",
"output_path",
")",
":",
"checked",
"=",
"... | Download a binary file from an URL.
The checksum will be downloaded from `URL + .md5`. If this download
succeeds, the file's MD5 will be compared to the expected checksum.
Parameters
----------
url : str
The file's URL.
output_path : str
The path where the file is to be saved. | [
"Download",
"a",
"binary",
"file",
"from",
"an",
"URL",
"."
] | python | train |
dwhswenson/autorelease | autorelease/git_repo_checks.py | https://github.com/dwhswenson/autorelease/blob/339c32c3934e4751857f35aaa2bfffaaaf3b39c4/autorelease/git_repo_checks.py#L50-L96 | def reasonable_desired_version(self, desired_version, allow_equal=False,
allow_patch_skip=False):
"""
Determine whether the desired version is a reasonable next version.
Parameters
----------
desired_version: str
the proposed next ve... | [
"def",
"reasonable_desired_version",
"(",
"self",
",",
"desired_version",
",",
"allow_equal",
"=",
"False",
",",
"allow_patch_skip",
"=",
"False",
")",
":",
"try",
":",
"desired_version",
"=",
"desired_version",
".",
"base_version",
"except",
":",
"pass",
"(",
"... | Determine whether the desired version is a reasonable next version.
Parameters
----------
desired_version: str
the proposed next version name | [
"Determine",
"whether",
"the",
"desired",
"version",
"is",
"a",
"reasonable",
"next",
"version",
"."
] | python | test |
JoelBender/bacpypes | py34/bacpypes/service/object.py | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py34/bacpypes/service/object.py#L193-L223 | def read_property_to_result_element(obj, propertyIdentifier, propertyArrayIndex=None):
"""Read the specified property of the object, with the optional array index,
and cast the result into an Any object."""
if _debug: read_property_to_result_element._debug("read_property_to_result_element %s %r %r", obj, pr... | [
"def",
"read_property_to_result_element",
"(",
"obj",
",",
"propertyIdentifier",
",",
"propertyArrayIndex",
"=",
"None",
")",
":",
"if",
"_debug",
":",
"read_property_to_result_element",
".",
"_debug",
"(",
"\"read_property_to_result_element %s %r %r\"",
",",
"obj",
",",
... | Read the specified property of the object, with the optional array index,
and cast the result into an Any object. | [
"Read",
"the",
"specified",
"property",
"of",
"the",
"object",
"with",
"the",
"optional",
"array",
"index",
"and",
"cast",
"the",
"result",
"into",
"an",
"Any",
"object",
"."
] | python | train |
Miserlou/Zappa | zappa/letsencrypt.py | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/letsencrypt.py#L212-L226 | def register_account():
"""
Agree to LE TOS
"""
LOGGER.info("Registering account...")
code, result = _send_signed_request(DEFAULT_CA + "/acme/new-reg", {
"resource": "new-reg",
"agreement": "https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf",
})
if code == 201... | [
"def",
"register_account",
"(",
")",
":",
"LOGGER",
".",
"info",
"(",
"\"Registering account...\"",
")",
"code",
",",
"result",
"=",
"_send_signed_request",
"(",
"DEFAULT_CA",
"+",
"\"/acme/new-reg\"",
",",
"{",
"\"resource\"",
":",
"\"new-reg\"",
",",
"\"agreemen... | Agree to LE TOS | [
"Agree",
"to",
"LE",
"TOS"
] | python | train |
onicagroup/runway | runway/util.py | https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/util.py#L64-L78 | def merge_dicts(dict1, dict2, deep_merge=True):
"""Merge dict2 into dict1."""
if deep_merge:
if isinstance(dict1, list) and isinstance(dict2, list):
return dict1 + dict2
if not isinstance(dict1, dict) or not isinstance(dict2, dict):
return dict2
for key in dict2... | [
"def",
"merge_dicts",
"(",
"dict1",
",",
"dict2",
",",
"deep_merge",
"=",
"True",
")",
":",
"if",
"deep_merge",
":",
"if",
"isinstance",
"(",
"dict1",
",",
"list",
")",
"and",
"isinstance",
"(",
"dict2",
",",
"list",
")",
":",
"return",
"dict1",
"+",
... | Merge dict2 into dict1. | [
"Merge",
"dict2",
"into",
"dict1",
"."
] | python | train |
clalancette/pycdlib | pycdlib/path_table_record.py | https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/path_table_record.py#L191-L204 | def update_parent_directory_number(self, parent_dir_num):
# type: (int) -> None
'''
A method to update the parent directory number for this Path Table
Record from the directory record.
Parameters:
parent_dir_num - The new parent directory number to assign to this PTR.
... | [
"def",
"update_parent_directory_number",
"(",
"self",
",",
"parent_dir_num",
")",
":",
"# type: (int) -> None",
"if",
"not",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'Path Table Record not yet initialized'",
")",
"s... | A method to update the parent directory number for this Path Table
Record from the directory record.
Parameters:
parent_dir_num - The new parent directory number to assign to this PTR.
Returns:
Nothing. | [
"A",
"method",
"to",
"update",
"the",
"parent",
"directory",
"number",
"for",
"this",
"Path",
"Table",
"Record",
"from",
"the",
"directory",
"record",
"."
] | python | train |
log2timeline/plaso | plaso/storage/fake/writer.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/storage/fake/writer.py#L112-L137 | def AddEvent(self, event):
"""Adds an event.
Args:
event (EventObject): event.
Raises:
IOError: when the storage writer is closed or
if the event data identifier type is not supported.
OSError: when the storage writer is closed or
if the event data identifier type is ... | [
"def",
"AddEvent",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"_RaiseIfNotWritable",
"(",
")",
"# TODO: change to no longer allow event_data_identifier is None",
"# after refactoring every parser to generate event data.",
"event_data_identifier",
"=",
"event",
".",
"GetE... | Adds an event.
Args:
event (EventObject): event.
Raises:
IOError: when the storage writer is closed or
if the event data identifier type is not supported.
OSError: when the storage writer is closed or
if the event data identifier type is not supported. | [
"Adds",
"an",
"event",
"."
] | python | train |
Kane610/axis | axis/rtsp.py | https://github.com/Kane610/axis/blob/b2b44ce595c7b722b5e13eabcab7b91f048e1808/axis/rtsp.py#L112-L119 | def time_out(self):
"""If we don't get a response within time the RTSP request time out.
This usually happens if device isn't available on specified IP.
"""
_LOGGER.warning('Response timed out %s', self.session.host)
self.stop()
self.callback(SIGNAL_FAILED) | [
"def",
"time_out",
"(",
"self",
")",
":",
"_LOGGER",
".",
"warning",
"(",
"'Response timed out %s'",
",",
"self",
".",
"session",
".",
"host",
")",
"self",
".",
"stop",
"(",
")",
"self",
".",
"callback",
"(",
"SIGNAL_FAILED",
")"
] | If we don't get a response within time the RTSP request time out.
This usually happens if device isn't available on specified IP. | [
"If",
"we",
"don",
"t",
"get",
"a",
"response",
"within",
"time",
"the",
"RTSP",
"request",
"time",
"out",
"."
] | python | train |
DeV1doR/aioethereum | aioethereum/management/eth.py | https://github.com/DeV1doR/aioethereum/blob/85eb46550d862b3ccc309914ea871ca1c7b42157/aioethereum/management/eth.py#L152-L163 | def eth_getBlockTransactionCountByNumber(self, block=BLOCK_TAG_LATEST):
"""https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getblocktransactioncountbynumber
:param block: Block tag or number (optional)
:type block: int or BLOCK_TAGS
:return: count
:rtype: int
"""
... | [
"def",
"eth_getBlockTransactionCountByNumber",
"(",
"self",
",",
"block",
"=",
"BLOCK_TAG_LATEST",
")",
":",
"block",
"=",
"validate_block",
"(",
"block",
")",
"return",
"hex_to_dec",
"(",
"(",
"yield",
"from",
"self",
".",
"rpc_call",
"(",
"'eth_getBlockTransacti... | https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getblocktransactioncountbynumber
:param block: Block tag or number (optional)
:type block: int or BLOCK_TAGS
:return: count
:rtype: int | [
"https",
":",
"//",
"github",
".",
"com",
"/",
"ethereum",
"/",
"wiki",
"/",
"wiki",
"/",
"JSON",
"-",
"RPC#eth_getblocktransactioncountbynumber"
] | python | train |
aio-libs/aioftp | aioftp/common.py | https://github.com/aio-libs/aioftp/blob/b45395b1aba41301b898040acade7010e6878a08/aioftp/common.py#L398-L405 | def clone(self):
"""
Clone throttles without memory
"""
return StreamThrottle(
read=self.read.clone(),
write=self.write.clone()
) | [
"def",
"clone",
"(",
"self",
")",
":",
"return",
"StreamThrottle",
"(",
"read",
"=",
"self",
".",
"read",
".",
"clone",
"(",
")",
",",
"write",
"=",
"self",
".",
"write",
".",
"clone",
"(",
")",
")"
] | Clone throttles without memory | [
"Clone",
"throttles",
"without",
"memory"
] | python | valid |
psd-tools/psd-tools | src/psd_tools/utils.py | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/utils.py#L84-L103 | def write_length_block(fp, writer, fmt='I', padding=1, **kwargs):
"""
Writes a block of data with a length marker at the beginning.
Example::
with io.BytesIO() as fp:
write_length_block(fp, lambda f: f.write(b'\x00\x00'))
:param fp: file-like
:param writer: function object tha... | [
"def",
"write_length_block",
"(",
"fp",
",",
"writer",
",",
"fmt",
"=",
"'I'",
",",
"padding",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"length_position",
"=",
"reserve_position",
"(",
"fp",
",",
"fmt",
")",
"written",
"=",
"writer",
"(",
"fp",
"... | Writes a block of data with a length marker at the beginning.
Example::
with io.BytesIO() as fp:
write_length_block(fp, lambda f: f.write(b'\x00\x00'))
:param fp: file-like
:param writer: function object that takes file-like object as an argument
:param fmt: format of the length m... | [
"Writes",
"a",
"block",
"of",
"data",
"with",
"a",
"length",
"marker",
"at",
"the",
"beginning",
"."
] | python | train |
Kortemme-Lab/klab | klab/bio/pdb.py | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/pdb.py#L639-L666 | def _update_structure_lines(self):
'''ATOM and HETATM lines may be altered by function calls. When this happens, this function should be called to keep self.structure_lines up to date.'''
structure_lines = []
atom_chain_order = []
chain_atoms = {}
for line in self.lines:
... | [
"def",
"_update_structure_lines",
"(",
"self",
")",
":",
"structure_lines",
"=",
"[",
"]",
"atom_chain_order",
"=",
"[",
"]",
"chain_atoms",
"=",
"{",
"}",
"for",
"line",
"in",
"self",
".",
"lines",
":",
"linetype",
"=",
"line",
"[",
"0",
":",
"6",
"]"... | ATOM and HETATM lines may be altered by function calls. When this happens, this function should be called to keep self.structure_lines up to date. | [
"ATOM",
"and",
"HETATM",
"lines",
"may",
"be",
"altered",
"by",
"function",
"calls",
".",
"When",
"this",
"happens",
"this",
"function",
"should",
"be",
"called",
"to",
"keep",
"self",
".",
"structure_lines",
"up",
"to",
"date",
"."
] | python | train |
contentful/contentful-management.py | contentful_management/client_proxy.py | https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/client_proxy.py#L33-L43 | def all(self, query=None):
"""
Gets resource collection for _resource_class.
"""
if query is None:
query = {}
return self.client._get(
self._url(),
query
) | [
"def",
"all",
"(",
"self",
",",
"query",
"=",
"None",
")",
":",
"if",
"query",
"is",
"None",
":",
"query",
"=",
"{",
"}",
"return",
"self",
".",
"client",
".",
"_get",
"(",
"self",
".",
"_url",
"(",
")",
",",
"query",
")"
] | Gets resource collection for _resource_class. | [
"Gets",
"resource",
"collection",
"for",
"_resource_class",
"."
] | python | train |
20c/xbahn | xbahn/connection/tcp.py | https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/connection/tcp.py#L98-L105 | def respond(self, data):
"""
Respond to the connection accepted in this object
"""
self.push("%s%s" % (data, TERMINATOR))
if self.temporary:
self.close_when_done() | [
"def",
"respond",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"push",
"(",
"\"%s%s\"",
"%",
"(",
"data",
",",
"TERMINATOR",
")",
")",
"if",
"self",
".",
"temporary",
":",
"self",
".",
"close_when_done",
"(",
")"
] | Respond to the connection accepted in this object | [
"Respond",
"to",
"the",
"connection",
"accepted",
"in",
"this",
"object"
] | python | train |
python-visualization/folium | folium/features.py | https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/features.py#L608-L611 | def _to_key(d):
"""Convert dict to str and enable Jinja2 template syntax."""
as_str = json.dumps(d, sort_keys=True)
return as_str.replace('"{{', '{{').replace('}}"', '}}') | [
"def",
"_to_key",
"(",
"d",
")",
":",
"as_str",
"=",
"json",
".",
"dumps",
"(",
"d",
",",
"sort_keys",
"=",
"True",
")",
"return",
"as_str",
".",
"replace",
"(",
"'\"{{'",
",",
"'{{'",
")",
".",
"replace",
"(",
"'}}\"'",
",",
"'}}'",
")"
] | Convert dict to str and enable Jinja2 template syntax. | [
"Convert",
"dict",
"to",
"str",
"and",
"enable",
"Jinja2",
"template",
"syntax",
"."
] | python | train |
neithere/argh | argh/helpers.py | https://github.com/neithere/argh/blob/dcd3253f2994400a6a58a700c118c53765bc50a4/argh/helpers.py#L57-L64 | def parse_args(self, args=None, namespace=None):
"""
Wrapper for :meth:`argparse.ArgumentParser.parse_args`. If `namespace`
is not defined, :class:`argh.dispatching.ArghNamespace` is used.
This is required for functions to be properly used as commands.
"""
namespace = na... | [
"def",
"parse_args",
"(",
"self",
",",
"args",
"=",
"None",
",",
"namespace",
"=",
"None",
")",
":",
"namespace",
"=",
"namespace",
"or",
"ArghNamespace",
"(",
")",
"return",
"super",
"(",
"ArghParser",
",",
"self",
")",
".",
"parse_args",
"(",
"args",
... | Wrapper for :meth:`argparse.ArgumentParser.parse_args`. If `namespace`
is not defined, :class:`argh.dispatching.ArghNamespace` is used.
This is required for functions to be properly used as commands. | [
"Wrapper",
"for",
":",
"meth",
":",
"argparse",
".",
"ArgumentParser",
".",
"parse_args",
".",
"If",
"namespace",
"is",
"not",
"defined",
":",
"class",
":",
"argh",
".",
"dispatching",
".",
"ArghNamespace",
"is",
"used",
".",
"This",
"is",
"required",
"for... | python | test |
berkerpeksag/astor | astor/file_util.py | https://github.com/berkerpeksag/astor/blob/d9e893eb49d9eb2e30779680f90cd632c30e0ba1/astor/file_util.py#L55-L74 | def parse_file(fname):
"""Parse a python file into an AST.
This is a very thin wrapper around ast.parse
TODO: Handle encodings other than the default for Python 2
(issue #26)
"""
try:
with fopen(fname) as f:
fstr = f.read(... | [
"def",
"parse_file",
"(",
"fname",
")",
":",
"try",
":",
"with",
"fopen",
"(",
"fname",
")",
"as",
"f",
":",
"fstr",
"=",
"f",
".",
"read",
"(",
")",
"except",
"IOError",
":",
"if",
"fname",
"!=",
"'stdin'",
":",
"raise",
"sys",
".",
"stdout",
".... | Parse a python file into an AST.
This is a very thin wrapper around ast.parse
TODO: Handle encodings other than the default for Python 2
(issue #26) | [
"Parse",
"a",
"python",
"file",
"into",
"an",
"AST",
"."
] | python | train |
numenta/nupic.core | bindings/py/setup.py | https://github.com/numenta/nupic.core/blob/333290c32403ce11e7117f826a6348c3a8e6c125/bindings/py/setup.py#L91-L102 | def findRequirements(platform):
"""
Read the requirements.txt file and parse into requirements for setup's
install_requirements option.
"""
includePycapnp = platform not in WINDOWS_PLATFORMS
requirementsPath = fixPath(os.path.join(PY_BINDINGS, "requirements.txt"))
return [
line.strip()
for line in... | [
"def",
"findRequirements",
"(",
"platform",
")",
":",
"includePycapnp",
"=",
"platform",
"not",
"in",
"WINDOWS_PLATFORMS",
"requirementsPath",
"=",
"fixPath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"PY_BINDINGS",
",",
"\"requirements.txt\"",
")",
")",
"return... | Read the requirements.txt file and parse into requirements for setup's
install_requirements option. | [
"Read",
"the",
"requirements",
".",
"txt",
"file",
"and",
"parse",
"into",
"requirements",
"for",
"setup",
"s",
"install_requirements",
"option",
"."
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py#L1227-L1243 | def start(self, n):
"""Start n copies of the process using LSF batch system.
This cant inherit from the base class because bsub expects
to be piped a shell script in order to honor the #BSUB directives :
bsub < script
"""
# Here we save profile_dir in the context so they
... | [
"def",
"start",
"(",
"self",
",",
"n",
")",
":",
"# Here we save profile_dir in the context so they",
"# can be used in the batch script template as {profile_dir}",
"self",
".",
"write_batch_script",
"(",
"n",
")",
"#output = check_output(self.args, env=os.environ)",
"piped_cmd",
... | Start n copies of the process using LSF batch system.
This cant inherit from the base class because bsub expects
to be piped a shell script in order to honor the #BSUB directives :
bsub < script | [
"Start",
"n",
"copies",
"of",
"the",
"process",
"using",
"LSF",
"batch",
"system",
".",
"This",
"cant",
"inherit",
"from",
"the",
"base",
"class",
"because",
"bsub",
"expects",
"to",
"be",
"piped",
"a",
"shell",
"script",
"in",
"order",
"to",
"honor",
"t... | python | test |
iotile/coretools | iotilebuild/iotile/build/build/build.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/build/build.py#L26-L47 | def build(args):
"""
Invoke the scons build system from the current directory, exactly as if
the scons tool had been invoked.
"""
# Do some sleuthing work to find scons if it's not installed into an importable
# place, as it is usually not.
scons_path = "Error"
try:
scons_path =... | [
"def",
"build",
"(",
"args",
")",
":",
"# Do some sleuthing work to find scons if it's not installed into an importable",
"# place, as it is usually not.",
"scons_path",
"=",
"\"Error\"",
"try",
":",
"scons_path",
"=",
"resource_path",
"(",
"'scons-local-{}'",
".",
"format",
... | Invoke the scons build system from the current directory, exactly as if
the scons tool had been invoked. | [
"Invoke",
"the",
"scons",
"build",
"system",
"from",
"the",
"current",
"directory",
"exactly",
"as",
"if",
"the",
"scons",
"tool",
"had",
"been",
"invoked",
"."
] | python | train |
Qiskit/qiskit-terra | qiskit/transpiler/passes/mapping/stochastic_swap.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/stochastic_swap.py#L512-L532 | def regtuple_to_numeric(items, qregs):
"""Takes (QuantumRegister, int) tuples and converts
them into an integer array.
Args:
items (list): List of tuples of (QuantumRegister, int)
to convert.
qregs (dict): List of )QuantumRegister, int) tuples.
Returns:
nda... | [
"def",
"regtuple_to_numeric",
"(",
"items",
",",
"qregs",
")",
":",
"sizes",
"=",
"[",
"qr",
".",
"size",
"for",
"qr",
"in",
"qregs",
".",
"values",
"(",
")",
"]",
"reg_idx",
"=",
"np",
".",
"cumsum",
"(",
"[",
"0",
"]",
"+",
"sizes",
")",
"regin... | Takes (QuantumRegister, int) tuples and converts
them into an integer array.
Args:
items (list): List of tuples of (QuantumRegister, int)
to convert.
qregs (dict): List of )QuantumRegister, int) tuples.
Returns:
ndarray: Array of integers. | [
"Takes",
"(",
"QuantumRegister",
"int",
")",
"tuples",
"and",
"converts",
"them",
"into",
"an",
"integer",
"array",
"."
] | python | test |
msmbuilder/msmbuilder | msmbuilder/tpt/path.py | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/tpt/path.py#L161-L173 | def _remove_bottleneck(net_flux, path):
"""
Internal function for modifying the net flux matrix by removing
a particular edge, corresponding to the bottleneck of a particular
path.
"""
net_flux = copy.copy(net_flux)
bottleneck_ind = net_flux[path[:-1], path[1:]].argmin()
net_flux[path[... | [
"def",
"_remove_bottleneck",
"(",
"net_flux",
",",
"path",
")",
":",
"net_flux",
"=",
"copy",
".",
"copy",
"(",
"net_flux",
")",
"bottleneck_ind",
"=",
"net_flux",
"[",
"path",
"[",
":",
"-",
"1",
"]",
",",
"path",
"[",
"1",
":",
"]",
"]",
".",
"ar... | Internal function for modifying the net flux matrix by removing
a particular edge, corresponding to the bottleneck of a particular
path. | [
"Internal",
"function",
"for",
"modifying",
"the",
"net",
"flux",
"matrix",
"by",
"removing",
"a",
"particular",
"edge",
"corresponding",
"to",
"the",
"bottleneck",
"of",
"a",
"particular",
"path",
"."
] | python | train |
pydsigner/taskit | taskit/frontend.py | https://github.com/pydsigner/taskit/blob/3b228e2dbac16b3b84b2581f5b46e027d1d8fa7f/taskit/frontend.py#L131-L150 | def _package(self, task, *args, **kw):
"""
Used internally. Simply wraps the arguments up in a list and encodes
the list.
"""
# Implementation note: it is faster to use a tuple than a list here,
# because json does the list-like check like so (json/encoder.py:424):
... | [
"def",
"_package",
"(",
"self",
",",
"task",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"# Implementation note: it is faster to use a tuple than a list here, ",
"# because json does the list-like check like so (json/encoder.py:424):",
"# isinstance(o, (list, tuple))",
"# ... | Used internally. Simply wraps the arguments up in a list and encodes
the list. | [
"Used",
"internally",
".",
"Simply",
"wraps",
"the",
"arguments",
"up",
"in",
"a",
"list",
"and",
"encodes",
"the",
"list",
"."
] | python | train |
NiklasRosenstein-Python/nr-deprecated | nr/archive.py | https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/archive.py#L145-L219 | def extract(archive, directory, suffix=None, unpack_single_dir=False,
check_extract_file=None, progress_callback=None, default_mode='755'):
"""
Extract the contents of *archive* to the specified *directory*. This
function ensures that no file is extracted outside of the target directory
(which can theoretic... | [
"def",
"extract",
"(",
"archive",
",",
"directory",
",",
"suffix",
"=",
"None",
",",
"unpack_single_dir",
"=",
"False",
",",
"check_extract_file",
"=",
"None",
",",
"progress_callback",
"=",
"None",
",",
"default_mode",
"=",
"'755'",
")",
":",
"if",
"isinsta... | Extract the contents of *archive* to the specified *directory*. This
function ensures that no file is extracted outside of the target directory
(which can theoretically happen if the arcname is not relative or points
to a parent directory).
# Parameters
archive (str, archive-like): The filename of an archive... | [
"Extract",
"the",
"contents",
"of",
"*",
"archive",
"*",
"to",
"the",
"specified",
"*",
"directory",
"*",
".",
"This",
"function",
"ensures",
"that",
"no",
"file",
"is",
"extracted",
"outside",
"of",
"the",
"target",
"directory",
"(",
"which",
"can",
"theo... | python | train |
hannes-brt/hebel | hebel/pycuda_ops/cublas.py | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L4010-L4025 | def cublasZgemm(handle, transa, transb, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc):
"""
Matrix-matrix product for complex general matrix.
"""
status = _libcublas.cublasZgemm_v2(handle,
_CUBLAS_OP[transa],
_CUBLAS_OP[trans... | [
"def",
"cublasZgemm",
"(",
"handle",
",",
"transa",
",",
"transb",
",",
"m",
",",
"n",
",",
"k",
",",
"alpha",
",",
"A",
",",
"lda",
",",
"B",
",",
"ldb",
",",
"beta",
",",
"C",
",",
"ldc",
")",
":",
"status",
"=",
"_libcublas",
".",
"cublasZge... | Matrix-matrix product for complex general matrix. | [
"Matrix",
"-",
"matrix",
"product",
"for",
"complex",
"general",
"matrix",
"."
] | python | train |
aiogram/aiogram | aiogram/utils/callback_data.py | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/callback_data.py#L100-L110 | def filter(self, **config) -> CallbackDataFilter:
"""
Generate filter
:param config:
:return:
"""
for key in config.keys():
if key not in self._part_names:
raise ValueError(f"Invalid field name '{key}'")
return CallbackDataFilter(self,... | [
"def",
"filter",
"(",
"self",
",",
"*",
"*",
"config",
")",
"->",
"CallbackDataFilter",
":",
"for",
"key",
"in",
"config",
".",
"keys",
"(",
")",
":",
"if",
"key",
"not",
"in",
"self",
".",
"_part_names",
":",
"raise",
"ValueError",
"(",
"f\"Invalid fi... | Generate filter
:param config:
:return: | [
"Generate",
"filter"
] | python | train |
yamins81/tabular | tabular/tab.py | https://github.com/yamins81/tabular/blob/1caf091c8c395960a9ad7078f95158b533cc52dd/tabular/tab.py#L785-L802 | def aggregate_in(self, On=None, AggFuncDict=None, AggFunc=None,
AggList=None, interspersed=True):
"""
Aggregate a tabarray and include original data in the result.
See the :func:`aggregate` method.
Method wraps::
tabular.summarize.aggregate_in(self, On... | [
"def",
"aggregate_in",
"(",
"self",
",",
"On",
"=",
"None",
",",
"AggFuncDict",
"=",
"None",
",",
"AggFunc",
"=",
"None",
",",
"AggList",
"=",
"None",
",",
"interspersed",
"=",
"True",
")",
":",
"data",
"=",
"spreadsheet",
".",
"aggregate_in",
"(",
"Da... | Aggregate a tabarray and include original data in the result.
See the :func:`aggregate` method.
Method wraps::
tabular.summarize.aggregate_in(self, On, AggFuncDict, AggFunc, interspersed) | [
"Aggregate",
"a",
"tabarray",
"and",
"include",
"original",
"data",
"in",
"the",
"result",
"."
] | python | train |
pycontribs/jira | jira/client.py | https://github.com/pycontribs/jira/blob/397db5d78441ed6a680a9b7db4c62030ade1fd8a/jira/client.py#L3733-L3736 | def incompletedIssuesEstimateSum(self, board_id, sprint_id):
"""Return the total incompleted points this sprint."""
return self._get_json('rapid/charts/sprintreport?rapidViewId=%s&sprintId=%s' % (board_id, sprint_id),
base=self.AGILE_BASE_URL)['contents']['incompletedIssues... | [
"def",
"incompletedIssuesEstimateSum",
"(",
"self",
",",
"board_id",
",",
"sprint_id",
")",
":",
"return",
"self",
".",
"_get_json",
"(",
"'rapid/charts/sprintreport?rapidViewId=%s&sprintId=%s'",
"%",
"(",
"board_id",
",",
"sprint_id",
")",
",",
"base",
"=",
"self",... | Return the total incompleted points this sprint. | [
"Return",
"the",
"total",
"incompleted",
"points",
"this",
"sprint",
"."
] | python | train |
scanny/python-pptx | pptx/shapes/freeform.py | https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/shapes/freeform.py#L300-L308 | def apply_operation_to(self, path):
"""Add `a:lnTo` element to *path* for this line segment.
Returns the `a:lnTo` element newly added to the path.
"""
return path.add_lnTo(
self._x - self._freeform_builder.shape_offset_x,
self._y - self._freeform_builder.shape_of... | [
"def",
"apply_operation_to",
"(",
"self",
",",
"path",
")",
":",
"return",
"path",
".",
"add_lnTo",
"(",
"self",
".",
"_x",
"-",
"self",
".",
"_freeform_builder",
".",
"shape_offset_x",
",",
"self",
".",
"_y",
"-",
"self",
".",
"_freeform_builder",
".",
... | Add `a:lnTo` element to *path* for this line segment.
Returns the `a:lnTo` element newly added to the path. | [
"Add",
"a",
":",
"lnTo",
"element",
"to",
"*",
"path",
"*",
"for",
"this",
"line",
"segment",
"."
] | python | train |
tgbugs/pyontutils | pyontutils/sheets.py | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/sheets.py#L134-L144 | def fetch(self, fetch_notes=None):
""" update remote values (called automatically at __init__) """
if fetch_notes is None:
fetch_notes = self.fetch_notes
values, notes_index = get_sheet_values(self.name, self.sheet_name,
spreadsheet_serv... | [
"def",
"fetch",
"(",
"self",
",",
"fetch_notes",
"=",
"None",
")",
":",
"if",
"fetch_notes",
"is",
"None",
":",
"fetch_notes",
"=",
"self",
".",
"fetch_notes",
"values",
",",
"notes_index",
"=",
"get_sheet_values",
"(",
"self",
".",
"name",
",",
"self",
... | update remote values (called automatically at __init__) | [
"update",
"remote",
"values",
"(",
"called",
"automatically",
"at",
"__init__",
")"
] | python | train |
nicolargo/glances | glances/autodiscover.py | https://github.com/nicolargo/glances/blob/5bd4d587a736e0d2b03170b56926841d2a3eb7ee/glances/autodiscover.py#L112-L114 | def set_server(self, server_pos, key, value):
"""Set the key to the value for the server_pos (position in the list)."""
self.servers.set_server(server_pos, key, value) | [
"def",
"set_server",
"(",
"self",
",",
"server_pos",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"servers",
".",
"set_server",
"(",
"server_pos",
",",
"key",
",",
"value",
")"
] | Set the key to the value for the server_pos (position in the list). | [
"Set",
"the",
"key",
"to",
"the",
"value",
"for",
"the",
"server_pos",
"(",
"position",
"in",
"the",
"list",
")",
"."
] | python | train |
geophysics-ubonn/crtomo_tools | src/td_plot.py | https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/src/td_plot.py#L719-L836 | def create_singleplots(plotman, cov, mag, pha, pha_fpi, alpha, options):
'''Plot the data of the tomodir in individual plots.
'''
magunit = 'log_rho'
if not pha == []:
[real, imag] = calc_complex(mag, pha)
if not pha_fpi == []:
[real_fpi, imag_fpi] = calc_complex(mag, pha_fpi... | [
"def",
"create_singleplots",
"(",
"plotman",
",",
"cov",
",",
"mag",
",",
"pha",
",",
"pha_fpi",
",",
"alpha",
",",
"options",
")",
":",
"magunit",
"=",
"'log_rho'",
"if",
"not",
"pha",
"==",
"[",
"]",
":",
"[",
"real",
",",
"imag",
"]",
"=",
"calc... | Plot the data of the tomodir in individual plots. | [
"Plot",
"the",
"data",
"of",
"the",
"tomodir",
"in",
"individual",
"plots",
"."
] | python | train |
aliyun/aliyun-odps-python-sdk | odps/df/expr/collections.py | https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/df/expr/collections.py#L1044-L1153 | def pivot_table(expr, values=None, rows=None, columns=None, aggfunc='mean',
fill_value=None):
"""
Create a spreadsheet-style pivot table as a DataFrame.
:param expr: collection
:param values (optional): column to aggregate
:param rows: rows to group
:param columns: keys to group... | [
"def",
"pivot_table",
"(",
"expr",
",",
"values",
"=",
"None",
",",
"rows",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"aggfunc",
"=",
"'mean'",
",",
"fill_value",
"=",
"None",
")",
":",
"def",
"get_names",
"(",
"iters",
")",
":",
"return",
"[",
... | Create a spreadsheet-style pivot table as a DataFrame.
:param expr: collection
:param values (optional): column to aggregate
:param rows: rows to group
:param columns: keys to group by on the pivot table column
:param aggfunc: aggregate function or functions
:param fill_value (optional): value ... | [
"Create",
"a",
"spreadsheet",
"-",
"style",
"pivot",
"table",
"as",
"a",
"DataFrame",
"."
] | python | train |
ninjaaron/libaaron | libaaron/libaaron.py | https://github.com/ninjaaron/libaaron/blob/a2ee417b784ca72c89c05bddb2e3e815a6b95154/libaaron/libaaron.py#L236-L239 | def printtsv(table, sep="\t", file=sys.stdout):
"""stupidly print an iterable of iterables in TSV format"""
for record in table:
print(*record, sep=sep, file=file) | [
"def",
"printtsv",
"(",
"table",
",",
"sep",
"=",
"\"\\t\"",
",",
"file",
"=",
"sys",
".",
"stdout",
")",
":",
"for",
"record",
"in",
"table",
":",
"print",
"(",
"*",
"record",
",",
"sep",
"=",
"sep",
",",
"file",
"=",
"file",
")"
] | stupidly print an iterable of iterables in TSV format | [
"stupidly",
"print",
"an",
"iterable",
"of",
"iterables",
"in",
"TSV",
"format"
] | python | test |
ff0000/scarlet | scarlet/assets/models.py | https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/assets/models.py#L85-L98 | def reset_crops(self):
"""
Reset all known crops to the default crop.
If settings.ASSET_CELERY is specified then
the task will be run async
"""
if self._can_crop():
if settings.CELERY or settings.USE_CELERY_DECORATOR:
# this means that we are... | [
"def",
"reset_crops",
"(",
"self",
")",
":",
"if",
"self",
".",
"_can_crop",
"(",
")",
":",
"if",
"settings",
".",
"CELERY",
"or",
"settings",
".",
"USE_CELERY_DECORATOR",
":",
"# this means that we are using celery",
"tasks",
".",
"reset_crops",
".",
"apply_asy... | Reset all known crops to the default crop.
If settings.ASSET_CELERY is specified then
the task will be run async | [
"Reset",
"all",
"known",
"crops",
"to",
"the",
"default",
"crop",
"."
] | python | train |
biolink/ontobio | ontobio/io/entityparser.py | https://github.com/biolink/ontobio/blob/4e512a7831cfe6bc1b32f2c3be2ba41bc5cf7345/ontobio/io/entityparser.py#L9-L60 | def parse(self, file, outfile=None):
"""Parse a line-oriented entity file into a list of entity dict objects
Note the returned list is of dict objects. TODO: These will
later be specified using marshmallow and it should be possible
to generate objects
Arguments
--------... | [
"def",
"parse",
"(",
"self",
",",
"file",
",",
"outfile",
"=",
"None",
")",
":",
"file",
"=",
"self",
".",
"_ensure_file",
"(",
"file",
")",
"ents",
"=",
"[",
"]",
"skipped",
"=",
"[",
"]",
"n_lines",
"=",
"0",
"for",
"line",
"in",
"file",
":",
... | Parse a line-oriented entity file into a list of entity dict objects
Note the returned list is of dict objects. TODO: These will
later be specified using marshmallow and it should be possible
to generate objects
Arguments
---------
file : file or string
The ... | [
"Parse",
"a",
"line",
"-",
"oriented",
"entity",
"file",
"into",
"a",
"list",
"of",
"entity",
"dict",
"objects"
] | python | train |
jedie/django-cms-tools | django_cms_tools/fixture_helper/pages.py | https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L129-L140 | def get_home_page(self):
"""
Return the published home page.
Used for 'parent' in cms.api.create_page()
"""
try:
home_page_draft = Page.objects.get(
is_home=True, publisher_is_draft=True)
except Page.DoesNotExist:
log.error('ERROR: ... | [
"def",
"get_home_page",
"(",
"self",
")",
":",
"try",
":",
"home_page_draft",
"=",
"Page",
".",
"objects",
".",
"get",
"(",
"is_home",
"=",
"True",
",",
"publisher_is_draft",
"=",
"True",
")",
"except",
"Page",
".",
"DoesNotExist",
":",
"log",
".",
"erro... | Return the published home page.
Used for 'parent' in cms.api.create_page() | [
"Return",
"the",
"published",
"home",
"page",
".",
"Used",
"for",
"parent",
"in",
"cms",
".",
"api",
".",
"create_page",
"()"
] | python | train |
quiltdata/quilt | compiler/quilt/tools/util.py | https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/util.py#L138-L146 | def sub_dirs(path, invisible=False):
"""
Child directories (non-recursive)
"""
dirs = [x for x in os.listdir(path) if os.path.isdir(os.path.join(path, x))]
if not invisible:
dirs = [x for x in dirs if not x.startswith('.')]
return dirs | [
"def",
"sub_dirs",
"(",
"path",
",",
"invisible",
"=",
"False",
")",
":",
"dirs",
"=",
"[",
"x",
"for",
"x",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
... | Child directories (non-recursive) | [
"Child",
"directories",
"(",
"non",
"-",
"recursive",
")"
] | python | train |
woolfson-group/isambard | isambard/tools/file_parsing.py | https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/tools/file_parsing.py#L158-L277 | def get_protein_dict(cif_data):
""" Parse cif_data dict for a subset of its data.
Notes
-----
cif_data dict contains all the data from the .cif file, with values as strings.
This function returns a more 'human readable' dictionary of key-value pairs.
The keys have simpler (and still often more ... | [
"def",
"get_protein_dict",
"(",
"cif_data",
")",
":",
"# Dictionary relating the keys of protein_dict (column names in Protein model) to the keys of cif_data.",
"mmcif_data_names",
"=",
"{",
"'keywords'",
":",
"'_struct_keywords.text'",
",",
"'header'",
":",
"'_struct_keywords.pdbx_k... | Parse cif_data dict for a subset of its data.
Notes
-----
cif_data dict contains all the data from the .cif file, with values as strings.
This function returns a more 'human readable' dictionary of key-value pairs.
The keys have simpler (and still often more descriptive!) names, and the values are ... | [
"Parse",
"cif_data",
"dict",
"for",
"a",
"subset",
"of",
"its",
"data",
"."
] | python | train |
erdc/RAPIDpy | RAPIDpy/gis/workflow.py | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/gis/workflow.py#L22-L148 | def CreateAllStaticRAPIDFiles(in_drainage_line,
river_id,
length_id,
slope_id,
next_down_id,
rapid_output_folder,
kfac_celerity=1000.0/3600.... | [
"def",
"CreateAllStaticRAPIDFiles",
"(",
"in_drainage_line",
",",
"river_id",
",",
"length_id",
",",
"slope_id",
",",
"next_down_id",
",",
"rapid_output_folder",
",",
"kfac_celerity",
"=",
"1000.0",
"/",
"3600.0",
",",
"kfac_formula_type",
"=",
"3",
",",
"kfac_lengt... | To generate the static RAPID files (rapid_connect.csv, riv_bas_id.csv,
kfac.csv, k.csv, x.csv, comid_lat_lon_z.csv) with default values.
Parameters
----------
in_drainage_line: str
Path to the stream network (i.e. Drainage Line) shapefile.
river_id: str
The name of the field with th... | [
"To",
"generate",
"the",
"static",
"RAPID",
"files",
"(",
"rapid_connect",
".",
"csv",
"riv_bas_id",
".",
"csv",
"kfac",
".",
"csv",
"k",
".",
"csv",
"x",
".",
"csv",
"comid_lat_lon_z",
".",
"csv",
")",
"with",
"default",
"values",
"."
] | python | train |
doraemonext/wechat-python-sdk | wechat_sdk/core/conf.py | https://github.com/doraemonext/wechat-python-sdk/blob/bf6f6f3d4a5440feb73a51937059d7feddc335a0/wechat_sdk/core/conf.py#L160-L173 | def jsapi_ticket(self):
""" 获取当前 jsapi ticket 值, 本方法会自行维护 jsapi ticket 有效性 """
self._check_appid_appsecret()
if callable(self.__jsapi_ticket_getfunc):
self.__jsapi_ticket, self.__jsapi_ticket_expires_at = self.__jsapi_ticket_getfunc()
if self.__jsapi_ticket:
now... | [
"def",
"jsapi_ticket",
"(",
"self",
")",
":",
"self",
".",
"_check_appid_appsecret",
"(",
")",
"if",
"callable",
"(",
"self",
".",
"__jsapi_ticket_getfunc",
")",
":",
"self",
".",
"__jsapi_ticket",
",",
"self",
".",
"__jsapi_ticket_expires_at",
"=",
"self",
".... | 获取当前 jsapi ticket 值, 本方法会自行维护 jsapi ticket 有效性 | [
"获取当前",
"jsapi",
"ticket",
"值",
"本方法会自行维护",
"jsapi",
"ticket",
"有效性"
] | python | valid |
CalebBell/thermo | thermo/critical.py | https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/critical.py#L849-L938 | def Mersmann_Kind_predictor(atoms, coeff=3.645, power=0.5,
covalent_radii=rcovs_Mersmann_Kind):
r'''Predicts the critical molar volume of a chemical based only on its
atomic composition according to [1]_ and [2]_. This is a crude approach,
but provides very reasonable
estima... | [
"def",
"Mersmann_Kind_predictor",
"(",
"atoms",
",",
"coeff",
"=",
"3.645",
",",
"power",
"=",
"0.5",
",",
"covalent_radii",
"=",
"rcovs_Mersmann_Kind",
")",
":",
"H_RADIUS_COV",
"=",
"covalent_radii",
"[",
"'H'",
"]",
"tot",
"=",
"0",
"atom_count",
"=",
"0"... | r'''Predicts the critical molar volume of a chemical based only on its
atomic composition according to [1]_ and [2]_. This is a crude approach,
but provides very reasonable
estimates in practice. Optionally, the `coeff` used and the `power` in the
fraction as well as the atomic contributions can be adju... | [
"r",
"Predicts",
"the",
"critical",
"molar",
"volume",
"of",
"a",
"chemical",
"based",
"only",
"on",
"its",
"atomic",
"composition",
"according",
"to",
"[",
"1",
"]",
"_",
"and",
"[",
"2",
"]",
"_",
".",
"This",
"is",
"a",
"crude",
"approach",
"but",
... | python | valid |
Cornices/cornice.ext.swagger | cornice_swagger/swagger.py | https://github.com/Cornices/cornice.ext.swagger/blob/c31a5cc8d5dd112b11dc41ccb6d09b423b537abc/cornice_swagger/swagger.py#L687-L705 | def _extract_transform_colander_schema(self, args):
"""
Extract schema from view args and transform it using
the pipeline of schema transformers
:param args:
Arguments from the view decorator.
:rtype: colander.MappingSchema()
:returns: View schema cloned and... | [
"def",
"_extract_transform_colander_schema",
"(",
"self",
",",
"args",
")",
":",
"schema",
"=",
"args",
".",
"get",
"(",
"'schema'",
",",
"colander",
".",
"MappingSchema",
"(",
")",
")",
"if",
"not",
"isinstance",
"(",
"schema",
",",
"colander",
".",
"Sche... | Extract schema from view args and transform it using
the pipeline of schema transformers
:param args:
Arguments from the view decorator.
:rtype: colander.MappingSchema()
:returns: View schema cloned and transformed | [
"Extract",
"schema",
"from",
"view",
"args",
"and",
"transform",
"it",
"using",
"the",
"pipeline",
"of",
"schema",
"transformers"
] | python | valid |
tryolabs/requestium | requestium/requestium.py | https://github.com/tryolabs/requestium/blob/9533932ae688da26f3fb78b97b3c0b05c6f24934/requestium/requestium.py#L246-L258 | def is_cookie_in_driver(self, cookie):
"""We check that the cookie is correctly added to the driver
We only compare name, value and domain, as the rest can produce false negatives.
We are a bit lenient when comparing domains.
"""
for driver_cookie in self.get_cookies():
... | [
"def",
"is_cookie_in_driver",
"(",
"self",
",",
"cookie",
")",
":",
"for",
"driver_cookie",
"in",
"self",
".",
"get_cookies",
"(",
")",
":",
"if",
"(",
"cookie",
"[",
"'name'",
"]",
"==",
"driver_cookie",
"[",
"'name'",
"]",
"and",
"cookie",
"[",
"'value... | We check that the cookie is correctly added to the driver
We only compare name, value and domain, as the rest can produce false negatives.
We are a bit lenient when comparing domains. | [
"We",
"check",
"that",
"the",
"cookie",
"is",
"correctly",
"added",
"to",
"the",
"driver"
] | python | train |
libyal/dtfabric | dtfabric/runtime/data_maps.py | https://github.com/libyal/dtfabric/blob/0d2b5719fa257f6e5c661a406737ebcf8c8db266/dtfabric/runtime/data_maps.py#L253-L274 | def FoldByteStream(self, mapped_value, **unused_kwargs):
"""Folds the data type into a byte stream.
Args:
mapped_value (object): mapped value.
Returns:
bytes: byte stream.
Raises:
FoldingError: if the data type definition cannot be folded into
the byte stream.
"""
... | [
"def",
"FoldByteStream",
"(",
"self",
",",
"mapped_value",
",",
"*",
"*",
"unused_kwargs",
")",
":",
"try",
":",
"value",
"=",
"self",
".",
"FoldValue",
"(",
"mapped_value",
")",
"return",
"self",
".",
"_operation",
".",
"WriteTo",
"(",
"tuple",
"(",
"["... | Folds the data type into a byte stream.
Args:
mapped_value (object): mapped value.
Returns:
bytes: byte stream.
Raises:
FoldingError: if the data type definition cannot be folded into
the byte stream. | [
"Folds",
"the",
"data",
"type",
"into",
"a",
"byte",
"stream",
"."
] | python | train |
tensorflow/hub | tensorflow_hub/tensor_info.py | https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/tensor_info.py#L133-L151 | def convert_dict_to_compatible_tensor(values, targets):
"""Converts dict `values` in tensors that are compatible with `targets`.
Args:
values: A dict to objects to convert with same keys as `targets`.
targets: A dict returned by `parse_tensor_info_map`.
Returns:
A map with the same keys as `values` ... | [
"def",
"convert_dict_to_compatible_tensor",
"(",
"values",
",",
"targets",
")",
":",
"result",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"sorted",
"(",
"values",
".",
"items",
"(",
")",
")",
":",
"result",
"[",
"key",
"]",
"=",
"_convert_to_compat... | Converts dict `values` in tensors that are compatible with `targets`.
Args:
values: A dict to objects to convert with same keys as `targets`.
targets: A dict returned by `parse_tensor_info_map`.
Returns:
A map with the same keys as `values` but values converted into
Tensor/SparseTensors that can b... | [
"Converts",
"dict",
"values",
"in",
"tensors",
"that",
"are",
"compatible",
"with",
"targets",
"."
] | python | train |
saltstack/salt | salt/scripts.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/scripts.py#L527-L535 | def salt_spm():
'''
The main function for spm, the Salt Package Manager
.. versionadded:: 2015.8.0
'''
import salt.cli.spm
spm = salt.cli.spm.SPM() # pylint: disable=E1120
spm.run() | [
"def",
"salt_spm",
"(",
")",
":",
"import",
"salt",
".",
"cli",
".",
"spm",
"spm",
"=",
"salt",
".",
"cli",
".",
"spm",
".",
"SPM",
"(",
")",
"# pylint: disable=E1120",
"spm",
".",
"run",
"(",
")"
] | The main function for spm, the Salt Package Manager
.. versionadded:: 2015.8.0 | [
"The",
"main",
"function",
"for",
"spm",
"the",
"Salt",
"Package",
"Manager"
] | python | train |
HiPERCAM/hcam_widgets | hcam_widgets/misc.py | https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/misc.py#L195-L227 | def saveJSON(g, data, backup=False):
"""
Saves the current setup to disk.
g : hcam_drivers.globals.Container
Container with globals
data : dict
The current setup in JSON compatible dictionary format.
backup : bool
If we are saving a backup on close, don't prompt for filename
"""
... | [
"def",
"saveJSON",
"(",
"g",
",",
"data",
",",
"backup",
"=",
"False",
")",
":",
"if",
"not",
"backup",
":",
"fname",
"=",
"filedialog",
".",
"asksaveasfilename",
"(",
"defaultextension",
"=",
"'.json'",
",",
"filetypes",
"=",
"[",
"(",
"'json files'",
"... | Saves the current setup to disk.
g : hcam_drivers.globals.Container
Container with globals
data : dict
The current setup in JSON compatible dictionary format.
backup : bool
If we are saving a backup on close, don't prompt for filename | [
"Saves",
"the",
"current",
"setup",
"to",
"disk",
"."
] | python | train |
mwickert/scikit-dsp-comm | sk_dsp_comm/sigsys.py | https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/sigsys.py#L61-L92 | def CIC(M, K):
"""
A functional form implementation of a cascade of integrator comb (CIC) filters.
Parameters
----------
M : Effective number of taps per section (typically the decimation factor).
K : The number of CIC sections cascaded (larger K gives the filter a wider image rejection bandwid... | [
"def",
"CIC",
"(",
"M",
",",
"K",
")",
":",
"if",
"K",
"==",
"1",
":",
"b",
"=",
"np",
".",
"ones",
"(",
"M",
")",
"else",
":",
"h",
"=",
"np",
".",
"ones",
"(",
"M",
")",
"b",
"=",
"h",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"K",
... | A functional form implementation of a cascade of integrator comb (CIC) filters.
Parameters
----------
M : Effective number of taps per section (typically the decimation factor).
K : The number of CIC sections cascaded (larger K gives the filter a wider image rejection bandwidth).
Returns
-----... | [
"A",
"functional",
"form",
"implementation",
"of",
"a",
"cascade",
"of",
"integrator",
"comb",
"(",
"CIC",
")",
"filters",
"."
] | python | valid |
wheerd/multiset | multiset.py | https://github.com/wheerd/multiset/blob/1f002397096edae3da32d004e3159345a476999c/multiset.py#L719-L750 | def union_update(self, *others):
r"""Update the multiset, adding elements from all others using the maximum multiplicity.
>>> ms = Multiset('aab')
>>> ms.union_update('bc')
>>> sorted(ms)
['a', 'a', 'b', 'c']
You can also use the ``|=`` operator for the same effect. How... | [
"def",
"union_update",
"(",
"self",
",",
"*",
"others",
")",
":",
"_elements",
"=",
"self",
".",
"_elements",
"_total",
"=",
"self",
".",
"_total",
"for",
"other",
"in",
"map",
"(",
"self",
".",
"_as_mapping",
",",
"others",
")",
":",
"for",
"element",... | r"""Update the multiset, adding elements from all others using the maximum multiplicity.
>>> ms = Multiset('aab')
>>> ms.union_update('bc')
>>> sorted(ms)
['a', 'a', 'b', 'c']
You can also use the ``|=`` operator for the same effect. However, the operator version
will o... | [
"r",
"Update",
"the",
"multiset",
"adding",
"elements",
"from",
"all",
"others",
"using",
"the",
"maximum",
"multiplicity",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.