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
doakey3/DashTable
dashtable/data2rst/cell/center_cell_text.py
https://github.com/doakey3/DashTable/blob/744cfb6a717fa75a8092c83ebcd49b2668023681/dashtable/data2rst/cell/center_cell_text.py#L4-L50
def center_cell_text(cell): """ Horizontally center the text within a cell's grid Like this:: +---------+ +---------+ | foo | --> | foo | +---------+ +---------+ Parameters ---------- cell : dashtable.data2rst.Cell Returns ------- cell : da...
[ "def", "center_cell_text", "(", "cell", ")", ":", "lines", "=", "cell", ".", "text", ".", "split", "(", "'\\n'", ")", "cell_width", "=", "len", "(", "lines", "[", "0", "]", ")", "-", "2", "truncated_lines", "=", "[", "''", "]", "for", "i", "in", ...
Horizontally center the text within a cell's grid Like this:: +---------+ +---------+ | foo | --> | foo | +---------+ +---------+ Parameters ---------- cell : dashtable.data2rst.Cell Returns ------- cell : dashtable.data2rst.Cell
[ "Horizontally", "center", "the", "text", "within", "a", "cell", "s", "grid" ]
python
train
twilio/twilio-python
twilio/jwt/client/__init__.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/jwt/client/__init__.py#L44-L55
def allow_client_outgoing(self, application_sid, **kwargs): """ Allow the user of this token to make outgoing connections. Keyword arguments are passed to the application. :param str application_sid: Application to contact """ scope = ScopeURI('client', 'outgoing', {'app...
[ "def", "allow_client_outgoing", "(", "self", ",", "application_sid", ",", "*", "*", "kwargs", ")", ":", "scope", "=", "ScopeURI", "(", "'client'", ",", "'outgoing'", ",", "{", "'appSid'", ":", "application_sid", "}", ")", "if", "kwargs", ":", "scope", ".",...
Allow the user of this token to make outgoing connections. Keyword arguments are passed to the application. :param str application_sid: Application to contact
[ "Allow", "the", "user", "of", "this", "token", "to", "make", "outgoing", "connections", ".", "Keyword", "arguments", "are", "passed", "to", "the", "application", "." ]
python
train
Xython/Linq.py
linq/standard/general.py
https://github.com/Xython/Linq.py/blob/ffb65f92f1df0d8161d5f835f5947554f6f33d72/linq/standard/general.py#L88-L102
def ChunkBy(self, f=None): """ [ { 'self': [1, 1, 3, 3, 1, 1], 'f': lambda x: x%2, 'assert': lambda ret: ret == [[1, 1], [3, 3], [1, 1]] } ] """ if f is None: return _chunk(self) if is_to_destruct(f): f = destruct_func(f) r...
[ "def", "ChunkBy", "(", "self", ",", "f", "=", "None", ")", ":", "if", "f", "is", "None", ":", "return", "_chunk", "(", "self", ")", "if", "is_to_destruct", "(", "f", ")", ":", "f", "=", "destruct_func", "(", "f", ")", "return", "_chunk", "(", "se...
[ { 'self': [1, 1, 3, 3, 1, 1], 'f': lambda x: x%2, 'assert': lambda ret: ret == [[1, 1], [3, 3], [1, 1]] } ]
[ "[", "{", "self", ":", "[", "1", "1", "3", "3", "1", "1", "]", "f", ":", "lambda", "x", ":", "x%2", "assert", ":", "lambda", "ret", ":", "ret", "==", "[[", "1", "1", "]", "[", "3", "3", "]", "[", "1", "1", "]]", "}", "]" ]
python
train
tanghaibao/jcvi
jcvi/assembly/kmer.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/kmer.py#L76-L210
def analyze(self, ploidy=2, K=23, covmax=1000000): """ Analyze Kmer spectrum, calculations derived from allpathslg/src/kmers/KmerSpectra.cc """ from math import sqrt data = self.data kf_ceil = max(K for (K, c) in data) if kf_ceil > covmax: exc...
[ "def", "analyze", "(", "self", ",", "ploidy", "=", "2", ",", "K", "=", "23", ",", "covmax", "=", "1000000", ")", ":", "from", "math", "import", "sqrt", "data", "=", "self", ".", "data", "kf_ceil", "=", "max", "(", "K", "for", "(", "K", ",", "c"...
Analyze Kmer spectrum, calculations derived from allpathslg/src/kmers/KmerSpectra.cc
[ "Analyze", "Kmer", "spectrum", "calculations", "derived", "from", "allpathslg", "/", "src", "/", "kmers", "/", "KmerSpectra", ".", "cc" ]
python
train
rkargon/pixelsorter
pixelsorter/sort.py
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/sort.py#L109-L240
def sort_image(image, size, vertical=False, path=None, path_kwargs=None, max_interval=0, progressive_amount=0, randomize=False, edge_threshold=0, edge_data=None, image_threshold=None, image_mask=None, key=None, discretize=0, reverse=False, mirror=False, splice...
[ "def", "sort_image", "(", "image", ",", "size", ",", "vertical", "=", "False", ",", "path", "=", "None", ",", "path_kwargs", "=", "None", ",", "max_interval", "=", "0", ",", "progressive_amount", "=", "0", ",", "randomize", "=", "False", ",", "edge_thres...
Applies pixel sorting to an image. This is done by first creating a sort mask that describes the sorting intervals, and then calling apply_sort_mask to the image using the generated mask. :param discretize: Amount by which to "discretize" pixel values. This is done by dividing each pixel's value (after appl...
[ "Applies", "pixel", "sorting", "to", "an", "image", ".", "This", "is", "done", "by", "first", "creating", "a", "sort", "mask", "that", "describes", "the", "sorting", "intervals", "and", "then", "calling", "apply_sort_mask", "to", "the", "image", "using", "th...
python
train
UCL-INGI/INGInious
inginious/frontend/plugins/scoreboard/__init__.py
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/plugins/scoreboard/__init__.py#L198-L223
def init(plugin_manager, _, _2, _3): """ Init the plugin. Available configuration in configuration.yaml: :: - plugin_module: "inginious.frontend.plugins.scoreboard" Available configuration in course.yaml: :: - scoreboard: #you can define multiple sc...
[ "def", "init", "(", "plugin_manager", ",", "_", ",", "_2", ",", "_3", ")", ":", "page_pattern_course", "=", "r'/scoreboard/([a-z0-9A-Z\\-_]+)'", "page_pattern_scoreboard", "=", "r'/scoreboard/([a-z0-9A-Z\\-_]+)/([0-9]+)'", "plugin_manager", ".", "add_page", "(", "page_pat...
Init the plugin. Available configuration in configuration.yaml: :: - plugin_module: "inginious.frontend.plugins.scoreboard" Available configuration in course.yaml: :: - scoreboard: #you can define multiple scoreboards - content: "taskid1" #creat...
[ "Init", "the", "plugin", ".", "Available", "configuration", "in", "configuration", ".", "yaml", ":", "::" ]
python
train
Rapptz/discord.py
discord/ext/commands/core.py
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L705-L715
def reset_cooldown(self, ctx): """Resets the cooldown on this command. Parameters ----------- ctx: :class:`.Context` The invocation context to reset the cooldown under. """ if self._buckets.valid: bucket = self._buckets.get_bucket(ctx.message) ...
[ "def", "reset_cooldown", "(", "self", ",", "ctx", ")", ":", "if", "self", ".", "_buckets", ".", "valid", ":", "bucket", "=", "self", ".", "_buckets", ".", "get_bucket", "(", "ctx", ".", "message", ")", "bucket", ".", "reset", "(", ")" ]
Resets the cooldown on this command. Parameters ----------- ctx: :class:`.Context` The invocation context to reset the cooldown under.
[ "Resets", "the", "cooldown", "on", "this", "command", "." ]
python
train
buildbot/buildbot
master/buildbot/reporters/message.py
https://github.com/buildbot/buildbot/blob/5df3cfae6d760557d99156633c32b1822a1e130c/master/buildbot/reporters/message.py#L187-L213
def formatMessageForBuildResults(self, mode, buildername, buildset, build, master, previous_results, blamelist): """Generate a buildbot mail message and return a dictionary containing the message body, type and subject.""" ss_list = buildset['sourcestamps'] results = build['results'] ...
[ "def", "formatMessageForBuildResults", "(", "self", ",", "mode", ",", "buildername", ",", "buildset", ",", "build", ",", "master", ",", "previous_results", ",", "blamelist", ")", ":", "ss_list", "=", "buildset", "[", "'sourcestamps'", "]", "results", "=", "bui...
Generate a buildbot mail message and return a dictionary containing the message body, type and subject.
[ "Generate", "a", "buildbot", "mail", "message", "and", "return", "a", "dictionary", "containing", "the", "message", "body", "type", "and", "subject", "." ]
python
train
lehins/python-wepay
wepay/calls/subscription_plan.py
https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/subscription_plan.py#L57-L84
def __create(self, account_id, name, short_description, amount, period, **kwargs): """Call documentation: `/subscription_plan/create <https://www.wepay.com/developer/reference/subscription_plan#create>`_, plus extra keyword parameters: :keyword str access_token:...
[ "def", "__create", "(", "self", ",", "account_id", ",", "name", ",", "short_description", ",", "amount", ",", "period", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "'account_id'", ":", "account_id", ",", "'name'", ":", "name", ",", "'short_des...
Call documentation: `/subscription_plan/create <https://www.wepay.com/developer/reference/subscription_plan#create>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``, with ``batch_mode=True`` will set `authorizati...
[ "Call", "documentation", ":", "/", "subscription_plan", "/", "create", "<https", ":", "//", "www", ".", "wepay", ".", "com", "/", "developer", "/", "reference", "/", "subscription_plan#create", ">", "_", "plus", "extra", "keyword", "parameters", ":", ":", "k...
python
train
gem/oq-engine
openquake/hazardlib/contexts.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/contexts.py#L432-L448
def roundup(self, minimum_distance): """ If the minimum_distance is nonzero, returns a copy of the DistancesContext with updated distances, i.e. the ones below minimum_distance are rounded up to the minimum_distance. Otherwise, returns the original DistancesContext unchanged. ...
[ "def", "roundup", "(", "self", ",", "minimum_distance", ")", ":", "if", "not", "minimum_distance", ":", "return", "self", "ctx", "=", "DistancesContext", "(", ")", "for", "dist", ",", "array", "in", "vars", "(", "self", ")", ".", "items", "(", ")", ":"...
If the minimum_distance is nonzero, returns a copy of the DistancesContext with updated distances, i.e. the ones below minimum_distance are rounded up to the minimum_distance. Otherwise, returns the original DistancesContext unchanged.
[ "If", "the", "minimum_distance", "is", "nonzero", "returns", "a", "copy", "of", "the", "DistancesContext", "with", "updated", "distances", "i", ".", "e", ".", "the", "ones", "below", "minimum_distance", "are", "rounded", "up", "to", "the", "minimum_distance", ...
python
train
pythongssapi/python-gssapi
gssapi/creds.py
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/creds.py#L70-L73
def name(self): """Get the name associated with these credentials""" return self.inquire(name=True, lifetime=False, usage=False, mechs=False).name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "inquire", "(", "name", "=", "True", ",", "lifetime", "=", "False", ",", "usage", "=", "False", ",", "mechs", "=", "False", ")", ".", "name" ]
Get the name associated with these credentials
[ "Get", "the", "name", "associated", "with", "these", "credentials" ]
python
train
WhyNotHugo/django-afip
django_afip/models.py
https://github.com/WhyNotHugo/django-afip/blob/5fb73213f1fe86ca52b501ffd0737911ef26ddb3/django_afip/models.py#L704-L726
def _assign_numbers(self): """ Assign numbers in preparation for validating these receipts. WARNING: Don't call the method manually unless you know what you're doing! """ first = self.select_related('point_of_sales', 'receipt_type').first() next_num = Receipt.ob...
[ "def", "_assign_numbers", "(", "self", ")", ":", "first", "=", "self", ".", "select_related", "(", "'point_of_sales'", ",", "'receipt_type'", ")", ".", "first", "(", ")", "next_num", "=", "Receipt", ".", "objects", ".", "fetch_last_receipt_number", "(", "first...
Assign numbers in preparation for validating these receipts. WARNING: Don't call the method manually unless you know what you're doing!
[ "Assign", "numbers", "in", "preparation", "for", "validating", "these", "receipts", "." ]
python
train
NYUCCL/psiTurk
psiturk/amt_services.py
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/amt_services.py#L641-L650
def get_hit(self, hitid): ''' Get HIT ''' if not self.connect_to_turk(): return False try: hitdata = self.mtc.get_hit(HITId=hitid) except Exception as e: print e return False return hitdata['HIT']
[ "def", "get_hit", "(", "self", ",", "hitid", ")", ":", "if", "not", "self", ".", "connect_to_turk", "(", ")", ":", "return", "False", "try", ":", "hitdata", "=", "self", ".", "mtc", ".", "get_hit", "(", "HITId", "=", "hitid", ")", "except", "Exceptio...
Get HIT
[ "Get", "HIT" ]
python
train
alorence/django-modern-rpc
modernrpc/core.py
https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/core.py#L380-L382
def get_all_method_names(entry_point=ALL, protocol=ALL, sort_methods=False): """For backward compatibility. Use registry.get_all_method_names() instead (with same arguments)""" return registry.get_all_method_names(entry_point=entry_point, protocol=protocol, sort_methods=sort_methods)
[ "def", "get_all_method_names", "(", "entry_point", "=", "ALL", ",", "protocol", "=", "ALL", ",", "sort_methods", "=", "False", ")", ":", "return", "registry", ".", "get_all_method_names", "(", "entry_point", "=", "entry_point", ",", "protocol", "=", "protocol", ...
For backward compatibility. Use registry.get_all_method_names() instead (with same arguments)
[ "For", "backward", "compatibility", ".", "Use", "registry", ".", "get_all_method_names", "()", "instead", "(", "with", "same", "arguments", ")" ]
python
train
sdispater/orator
orator/query/builder.py
https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/query/builder.py#L1161-L1183
def lists(self, column, key=None): """ Get a list with the values of a given column :param column: The column to get the values for :type column: str :param key: The key :type key: str :return: The list of values :rtype: Collection or dict """ ...
[ "def", "lists", "(", "self", ",", "column", ",", "key", "=", "None", ")", ":", "columns", "=", "self", ".", "_get_list_select", "(", "column", ",", "key", ")", "if", "key", "is", "not", "None", ":", "results", "=", "{", "}", "for", "result", "in", ...
Get a list with the values of a given column :param column: The column to get the values for :type column: str :param key: The key :type key: str :return: The list of values :rtype: Collection or dict
[ "Get", "a", "list", "with", "the", "values", "of", "a", "given", "column" ]
python
train
oscarlazoarjona/fast
fast/atomic_structure.py
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/atomic_structure.py#L1894-L2127
def calculate_r_matrices(fine_states, reduced_matrix_elements, q=None, numeric=True, convention=1): ur"""Calculate the matrix elements of the electric dipole (in the helicity basis). We calculate all matrix elements for the D2 line in Rb 87. >>> from sympy import symbols, ppri...
[ "def", "calculate_r_matrices", "(", "fine_states", ",", "reduced_matrix_elements", ",", "q", "=", "None", ",", "numeric", "=", "True", ",", "convention", "=", "1", ")", ":", "magnetic_states", "=", "make_list_of_states", "(", "fine_states", ",", "'magnetic'", ",...
ur"""Calculate the matrix elements of the electric dipole (in the helicity basis). We calculate all matrix elements for the D2 line in Rb 87. >>> from sympy import symbols, pprint >>> red = symbols("r", positive=True) >>> reduced_matrix_elements = [[0, -red], [red, 0]] >>> g = State("Rb", 87, ...
[ "ur", "Calculate", "the", "matrix", "elements", "of", "the", "electric", "dipole", "(", "in", "the", "helicity", "basis", ")", "." ]
python
train
mickybart/python-atlasapi
atlasapi/specs.py
https://github.com/mickybart/python-atlasapi/blob/2962c37740998694cb55f82b375b81cc604b953e/atlasapi/specs.py#L55-L68
def getSpecs(self): """Get specs Returns: dict: Representation of the object """ content = { "databaseName" : self.databaseName, "roles" : self.roles, "username" : self.username, "password" : self.password } ...
[ "def", "getSpecs", "(", "self", ")", ":", "content", "=", "{", "\"databaseName\"", ":", "self", ".", "databaseName", ",", "\"roles\"", ":", "self", ".", "roles", ",", "\"username\"", ":", "self", ".", "username", ",", "\"password\"", ":", "self", ".", "p...
Get specs Returns: dict: Representation of the object
[ "Get", "specs", "Returns", ":", "dict", ":", "Representation", "of", "the", "object" ]
python
train
gwastro/pycbc
pycbc/filter/matchedfilter.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/filter/matchedfilter.py#L1366-L1393
def overlap(vec1, vec2, psd=None, low_frequency_cutoff=None, high_frequency_cutoff=None, normalized=True): """ Return the overlap between the two TimeSeries or FrequencySeries. Parameters ---------- vec1 : TimeSeries or FrequencySeries The input vector containing a waveform. vec2 ...
[ "def", "overlap", "(", "vec1", ",", "vec2", ",", "psd", "=", "None", ",", "low_frequency_cutoff", "=", "None", ",", "high_frequency_cutoff", "=", "None", ",", "normalized", "=", "True", ")", ":", "return", "overlap_cplx", "(", "vec1", ",", "vec2", ",", "...
Return the overlap between the two TimeSeries or FrequencySeries. Parameters ---------- vec1 : TimeSeries or FrequencySeries The input vector containing a waveform. vec2 : TimeSeries or FrequencySeries The input vector containing a waveform. psd : Frequency Series A power sp...
[ "Return", "the", "overlap", "between", "the", "two", "TimeSeries", "or", "FrequencySeries", "." ]
python
train
ethereum/py-evm
eth/tools/builder/chain/builders.py
https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/builder/chain/builders.py#L309-L335
def disable_pow_check(chain_class: Type[BaseChain]) -> Type[BaseChain]: """ Disable the proof of work validation check for each of the chain's vms. This allows for block mining without generation of the proof of work seal. .. note:: blocks mined this way will not be importable on any chain tha...
[ "def", "disable_pow_check", "(", "chain_class", ":", "Type", "[", "BaseChain", "]", ")", "->", "Type", "[", "BaseChain", "]", ":", "if", "not", "chain_class", ".", "vm_configuration", ":", "raise", "ValidationError", "(", "\"Chain class has no vm_configuration\"", ...
Disable the proof of work validation check for each of the chain's vms. This allows for block mining without generation of the proof of work seal. .. note:: blocks mined this way will not be importable on any chain that does not have proof of work disabled.
[ "Disable", "the", "proof", "of", "work", "validation", "check", "for", "each", "of", "the", "chain", "s", "vms", ".", "This", "allows", "for", "block", "mining", "without", "generation", "of", "the", "proof", "of", "work", "seal", "." ]
python
train
rdo-management/python-rdomanager-oscplugin
rdomanager_oscplugin/v1/baremetal.py
https://github.com/rdo-management/python-rdomanager-oscplugin/blob/165a166fb2e5a2598380779b35812b8b8478c4fb/rdomanager_oscplugin/v1/baremetal.py#L35-L58
def _csv_to_nodes_dict(nodes_csv): """Convert CSV to a list of dicts formatted for os_cloud_config Given a CSV file in the format below, convert it into the structure expected by os_could_config JSON files. pm_type, pm_addr, pm_user, pm_password, mac """ data = [] for row in csv.reader(n...
[ "def", "_csv_to_nodes_dict", "(", "nodes_csv", ")", ":", "data", "=", "[", "]", "for", "row", "in", "csv", ".", "reader", "(", "nodes_csv", ")", ":", "node", "=", "{", "\"pm_user\"", ":", "row", "[", "2", "]", ",", "\"pm_addr\"", ":", "row", "[", "...
Convert CSV to a list of dicts formatted for os_cloud_config Given a CSV file in the format below, convert it into the structure expected by os_could_config JSON files. pm_type, pm_addr, pm_user, pm_password, mac
[ "Convert", "CSV", "to", "a", "list", "of", "dicts", "formatted", "for", "os_cloud_config" ]
python
train
mardix/Mocha
mocha/render.py
https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/render.py#L138-L153
def jsonp(func): """Wraps JSONified output for JSONP requests. http://flask.pocoo.org/snippets/79/ """ @functools.wraps(func) def decorated_view(*args, **kwargs): callback = request.args.get('callback', None) if callback: data = str(func(*args, **kwargs)) con...
[ "def", "jsonp", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "decorated_view", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "callback", "=", "request", ".", "args", ".", "get", "(", "'callback'", ",", "Non...
Wraps JSONified output for JSONP requests. http://flask.pocoo.org/snippets/79/
[ "Wraps", "JSONified", "output", "for", "JSONP", "requests", ".", "http", ":", "//", "flask", ".", "pocoo", ".", "org", "/", "snippets", "/", "79", "/" ]
python
train
volafiled/python-volapi
volapi/user.py
https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/user.py#L93-L101
def __verify_username(self, username): """Raises an exception if the given username is not valid.""" if len(username) > self.__max_length or len(username) < 3: raise ValueError( f"Username must be between 3 and {self.__max_length} characters." ) if any(c ...
[ "def", "__verify_username", "(", "self", ",", "username", ")", ":", "if", "len", "(", "username", ")", ">", "self", ".", "__max_length", "or", "len", "(", "username", ")", "<", "3", ":", "raise", "ValueError", "(", "f\"Username must be between 3 and {self.__ma...
Raises an exception if the given username is not valid.
[ "Raises", "an", "exception", "if", "the", "given", "username", "is", "not", "valid", "." ]
python
train
archman/beamline
beamline/ui/myappframe.py
https://github.com/archman/beamline/blob/417bc5dc13e754bc89d246427984590fced64d07/beamline/ui/myappframe.py#L600-L619
def lte2json(self, filename): """ convert lte to json return tuple of json, lte file content """ lpins = lattice.LteParser(filename) data_json = lpins.file2json() latins = lattice.Lattice(lpins.file2json()) self.lattice_instance = latins self.all_bea...
[ "def", "lte2json", "(", "self", ",", "filename", ")", ":", "lpins", "=", "lattice", ".", "LteParser", "(", "filename", ")", "data_json", "=", "lpins", ".", "file2json", "(", ")", "latins", "=", "lattice", ".", "Lattice", "(", "lpins", ".", "file2json", ...
convert lte to json return tuple of json, lte file content
[ "convert", "lte", "to", "json" ]
python
train
cltk/cltk
cltk/phonology/old_english/phonology.py
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/phonology/old_english/phonology.py#L157-L188
def transliterate(self, text, mode='Latin'): """ Transliterates Anglo-Saxon runes into latin and vice versa. Sources: http://www.arild-hauge.com/eanglor.htm https://en.wikipedia.org/wiki/Anglo-Saxon_runes :param text: str: The text to be transcribed :par...
[ "def", "transliterate", "(", "self", ",", "text", ",", "mode", "=", "'Latin'", ")", ":", "if", "mode", "==", "'Latin'", ":", "return", "Transliterate", ".", "__transliterate_helper", "(", "text", ",", "L_Transliteration", ")", "elif", "mode", "in", "[", "'...
Transliterates Anglo-Saxon runes into latin and vice versa. Sources: http://www.arild-hauge.com/eanglor.htm https://en.wikipedia.org/wiki/Anglo-Saxon_runes :param text: str: The text to be transcribed :param mode: Specifies transliteration mode, options: La...
[ "Transliterates", "Anglo", "-", "Saxon", "runes", "into", "latin", "and", "vice", "versa", "." ]
python
train
oseledets/ttpy
tt/riemannian/riemannian.py
https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/riemannian/riemannian.py#L359-L432
def projector_splitting_add(Y, delta, debug=False): """Compute Y + delta via the projector splitting scheme. This function implements the projector splitting scheme (section 4.2 of [1]). The result is a TT-tensor with the TT-ranks equal to the TT-ranks of Y.""" # Get rid of redundant ranks (they cause...
[ "def", "projector_splitting_add", "(", "Y", ",", "delta", ",", "debug", "=", "False", ")", ":", "# Get rid of redundant ranks (they cause technical difficulties).", "delta", "=", "delta", ".", "round", "(", "eps", "=", "0", ")", "numDims", "=", "delta", ".", "d"...
Compute Y + delta via the projector splitting scheme. This function implements the projector splitting scheme (section 4.2 of [1]). The result is a TT-tensor with the TT-ranks equal to the TT-ranks of Y.
[ "Compute", "Y", "+", "delta", "via", "the", "projector", "splitting", "scheme", "." ]
python
train
wummel/linkchecker
linkcheck/memoryutil.py
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/memoryutil.py#L31-L46
def write_memory_dump(): """Dump memory to a temporary filename with the meliae package. @return: JSON filename where memory dump has been written to @rtype: string """ # first do a full garbage collection run gc.collect() if gc.garbage: log.warn(LOG_CHECK, "Unreachabe objects: %s", ...
[ "def", "write_memory_dump", "(", ")", ":", "# first do a full garbage collection run", "gc", ".", "collect", "(", ")", "if", "gc", ".", "garbage", ":", "log", ".", "warn", "(", "LOG_CHECK", ",", "\"Unreachabe objects: %s\"", ",", "pprint", ".", "pformat", "(", ...
Dump memory to a temporary filename with the meliae package. @return: JSON filename where memory dump has been written to @rtype: string
[ "Dump", "memory", "to", "a", "temporary", "filename", "with", "the", "meliae", "package", "." ]
python
train
apache/airflow
airflow/jobs.py
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/jobs.py#L139-L189
def heartbeat(self): """ Heartbeats update the job's entry in the database with a timestamp for the latest_heartbeat and allows for the job to be killed externally. This allows at the system level to monitor what is actually active. For instance, an old heartbeat for Sch...
[ "def", "heartbeat", "(", "self", ")", ":", "try", ":", "with", "create_session", "(", ")", "as", "session", ":", "job", "=", "session", ".", "query", "(", "BaseJob", ")", ".", "filter_by", "(", "id", "=", "self", ".", "id", ")", ".", "one", "(", ...
Heartbeats update the job's entry in the database with a timestamp for the latest_heartbeat and allows for the job to be killed externally. This allows at the system level to monitor what is actually active. For instance, an old heartbeat for SchedulerJob would mean something is...
[ "Heartbeats", "update", "the", "job", "s", "entry", "in", "the", "database", "with", "a", "timestamp", "for", "the", "latest_heartbeat", "and", "allows", "for", "the", "job", "to", "be", "killed", "externally", ".", "This", "allows", "at", "the", "system", ...
python
test
apple/turicreate
src/unity/python/turicreate/toolkits/_feature_engineering/_transformer_chain.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_feature_engineering/_transformer_chain.py#L192-L203
def _preprocess(self, data): """ Internal function to perform fit_transform() on all but last step. """ transformed_data = _copy(data) for name, step in self._transformers[:-1]: transformed_data = step.fit_transform(transformed_data) if type(transformed_da...
[ "def", "_preprocess", "(", "self", ",", "data", ")", ":", "transformed_data", "=", "_copy", "(", "data", ")", "for", "name", ",", "step", "in", "self", ".", "_transformers", "[", ":", "-", "1", "]", ":", "transformed_data", "=", "step", ".", "fit_trans...
Internal function to perform fit_transform() on all but last step.
[ "Internal", "function", "to", "perform", "fit_transform", "()", "on", "all", "but", "last", "step", "." ]
python
train
pjmark/NIMPA
niftypet/nimpa/prc/prc.py
https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/prc.py#L693-L716
def centre_mass_img(imdct): ''' Calculate the centre of mass of an image along each axes (x,y,z), separately. Arguments: imdct - the image dictionary with the image and header data. Output the list of the centre of mass for each axis. ''' #> initialise centre of mass arr...
[ "def", "centre_mass_img", "(", "imdct", ")", ":", "#> initialise centre of mass array", "com", "=", "np", ".", "zeros", "(", "3", ",", "dtype", "=", "np", ".", "float32", ")", "#> total image sum", "imsum", "=", "np", ".", "sum", "(", "imdct", "[", "'im'",...
Calculate the centre of mass of an image along each axes (x,y,z), separately. Arguments: imdct - the image dictionary with the image and header data. Output the list of the centre of mass for each axis.
[ "Calculate", "the", "centre", "of", "mass", "of", "an", "image", "along", "each", "axes", "(", "x", "y", "z", ")", "separately", ".", "Arguments", ":", "imdct", "-", "the", "image", "dictionary", "with", "the", "image", "and", "header", "data", ".", "O...
python
train
geronimp/graftM
graftm/search_table.py
https://github.com/geronimp/graftM/blob/c82576517290167f605fd0bc4facd009cee29f48/graftm/search_table.py#L88-L124
def _write_results(self, db_count, output_path): '''Write the table to the output_path directory db_count: dict Contains samples as entries. The value for each sample is another dictionary with HMM as the key, and number of hits as values: {"sample_1":{H...
[ "def", "_write_results", "(", "self", ",", "db_count", ",", "output_path", ")", ":", "logging", ".", "debug", "(", "\"Writing search otu table to file: %s\"", "%", "output_path", ")", "output_dict", "=", "{", "}", "for", "idx", ",", "value_dict", "in", "enumerat...
Write the table to the output_path directory db_count: dict Contains samples as entries. The value for each sample is another dictionary with HMM as the key, and number of hits as values: {"sample_1":{HMM_1: 12 HMM_2: 35 ...
[ "Write", "the", "table", "to", "the", "output_path", "directory", "db_count", ":", "dict", "Contains", "samples", "as", "entries", ".", "The", "value", "for", "each", "sample", "is", "another", "dictionary", "with", "HMM", "as", "the", "key", "and", "number"...
python
train
bcbio/bcbio-nextgen
bcbio/variation/qsnp.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/qsnp.py#L193-L202
def _set_reject(line): """Set REJECT in VCF line, or add it if there is something else.""" if line.startswith("#"): return line parts = line.split("\t") if parts[6] == "PASS": parts[6] = "REJECT" else: parts[6] += ";REJECT" return "\t".join(parts)
[ "def", "_set_reject", "(", "line", ")", ":", "if", "line", ".", "startswith", "(", "\"#\"", ")", ":", "return", "line", "parts", "=", "line", ".", "split", "(", "\"\\t\"", ")", "if", "parts", "[", "6", "]", "==", "\"PASS\"", ":", "parts", "[", "6",...
Set REJECT in VCF line, or add it if there is something else.
[ "Set", "REJECT", "in", "VCF", "line", "or", "add", "it", "if", "there", "is", "something", "else", "." ]
python
train
Opentrons/opentrons
api/src/opentrons/protocol_api/contexts.py
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/contexts.py#L878-L965
def pick_up_tip(self, location: Union[types.Location, Well] = None, presses: int = 3, increment: float = 1.0) -> 'InstrumentContext': """ Pick up a tip for the pipette to run liquid-handling commands with If no location is passed, the Pipette will pick up...
[ "def", "pick_up_tip", "(", "self", ",", "location", ":", "Union", "[", "types", ".", "Location", ",", "Well", "]", "=", "None", ",", "presses", ":", "int", "=", "3", ",", "increment", ":", "float", "=", "1.0", ")", "->", "'InstrumentContext'", ":", "...
Pick up a tip for the pipette to run liquid-handling commands with If no location is passed, the Pipette will pick up the next available tip in its :py:attr:`InstrumentContext.tip_racks` list. The tip to pick up can be manually specified with the `location` argument. The `location` arg...
[ "Pick", "up", "a", "tip", "for", "the", "pipette", "to", "run", "liquid", "-", "handling", "commands", "with" ]
python
train
moonlitesolutions/SolrClient
SolrClient/helpers/reindexer.py
https://github.com/moonlitesolutions/SolrClient/blob/19c5280c9f8e97ee104d22ae883c4ccfd7c4f43b/SolrClient/helpers/reindexer.py#L87-L96
def reindex(self, fq= [], **kwargs): ''' Starts Reindexing Process. All parameter arguments will be passed down to the getter function. :param string fq: FilterQuery to pass to source Solr to retrieve items. This can be used to limit the results. ''' for items in self._gette...
[ "def", "reindex", "(", "self", ",", "fq", "=", "[", "]", ",", "*", "*", "kwargs", ")", ":", "for", "items", "in", "self", ".", "_getter", "(", "fq", "=", "fq", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_putter", "(", "items", ")", "if"...
Starts Reindexing Process. All parameter arguments will be passed down to the getter function. :param string fq: FilterQuery to pass to source Solr to retrieve items. This can be used to limit the results.
[ "Starts", "Reindexing", "Process", ".", "All", "parameter", "arguments", "will", "be", "passed", "down", "to", "the", "getter", "function", ".", ":", "param", "string", "fq", ":", "FilterQuery", "to", "pass", "to", "source", "Solr", "to", "retrieve", "items"...
python
train
bioasp/caspo
caspo/core/mapping.py
https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/core/mapping.py#L100-L111
def iteritems(self): """ Iterates over all mappings Yields ------ (int,Mapping) The next pair (index, mapping) """ for m in self.mappings: yield self.indexes[m.clause][m.target], m
[ "def", "iteritems", "(", "self", ")", ":", "for", "m", "in", "self", ".", "mappings", ":", "yield", "self", ".", "indexes", "[", "m", ".", "clause", "]", "[", "m", ".", "target", "]", ",", "m" ]
Iterates over all mappings Yields ------ (int,Mapping) The next pair (index, mapping)
[ "Iterates", "over", "all", "mappings" ]
python
train
fhcrc/seqmagick
seqmagick/subcommands/primer_trim.py
https://github.com/fhcrc/seqmagick/blob/1642bb87ba5c171fbd307f9da0f8a0ee1d69d5ed/seqmagick/subcommands/primer_trim.py#L220-L272
def locate_primers(sequences, forward_primer, reverse_primer, reverse_complement, max_hamming_distance): """ Find forward and reverse primers in a set of sequences, return two tuples: (forward_start, forward_end), (reverse_start, reverse_end) """ forward_loc = None reverse_loc...
[ "def", "locate_primers", "(", "sequences", ",", "forward_primer", ",", "reverse_primer", ",", "reverse_complement", ",", "max_hamming_distance", ")", ":", "forward_loc", "=", "None", "reverse_loc", "=", "None", "seq_length", "=", "None", "# Reverse complement the revers...
Find forward and reverse primers in a set of sequences, return two tuples: (forward_start, forward_end), (reverse_start, reverse_end)
[ "Find", "forward", "and", "reverse", "primers", "in", "a", "set", "of", "sequences", "return", "two", "tuples", ":", "(", "forward_start", "forward_end", ")", "(", "reverse_start", "reverse_end", ")" ]
python
train
ray-project/ray
python/ray/experimental/streaming/batched_queue.py
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/streaming/batched_queue.py#L136-L141
def enable_writes(self): """Restores the state of the batched queue for writing.""" self.write_buffer = [] self.flush_lock = threading.RLock() self.flush_thread = FlushThread(self.max_batch_time, self._flush_writes)
[ "def", "enable_writes", "(", "self", ")", ":", "self", ".", "write_buffer", "=", "[", "]", "self", ".", "flush_lock", "=", "threading", ".", "RLock", "(", ")", "self", ".", "flush_thread", "=", "FlushThread", "(", "self", ".", "max_batch_time", ",", "sel...
Restores the state of the batched queue for writing.
[ "Restores", "the", "state", "of", "the", "batched", "queue", "for", "writing", "." ]
python
train
gmr/tredis
tredis/strings.py
https://github.com/gmr/tredis/blob/2e91c6a58a35460be0525c51ac6a98fde3b506ad/tredis/strings.py#L269-L288
def getbit(self, key, offset): """Returns the bit value at offset in the string value stored at key. When offset is beyond the string length, the string is assumed to be a contiguous space with 0 bits. When key does not exist it is assumed to be an empty string, so offset is always out ...
[ "def", "getbit", "(", "self", ",", "key", ",", "offset", ")", ":", "return", "self", ".", "_execute", "(", "[", "b'GETBIT'", ",", "key", ",", "ascii", "(", "offset", ")", "]", ")" ]
Returns the bit value at offset in the string value stored at key. When offset is beyond the string length, the string is assumed to be a contiguous space with 0 bits. When key does not exist it is assumed to be an empty string, so offset is always out of range and the value is also ass...
[ "Returns", "the", "bit", "value", "at", "offset", "in", "the", "string", "value", "stored", "at", "key", "." ]
python
train
senaite/senaite.core
bika/lims/utils/__init__.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/utils/__init__.py#L502-L512
def dicts_to_dict(dictionaries, key_subfieldname): """Convert a list of dictionaries into a dictionary of dictionaries. key_subfieldname must exist in each Record's subfields and have a value, which will be used as the key for the new dictionary. If a key is duplicated, the earlier value will be overwr...
[ "def", "dicts_to_dict", "(", "dictionaries", ",", "key_subfieldname", ")", ":", "result", "=", "{", "}", "for", "d", "in", "dictionaries", ":", "result", "[", "d", "[", "key_subfieldname", "]", "]", "=", "d", "return", "result" ]
Convert a list of dictionaries into a dictionary of dictionaries. key_subfieldname must exist in each Record's subfields and have a value, which will be used as the key for the new dictionary. If a key is duplicated, the earlier value will be overwritten.
[ "Convert", "a", "list", "of", "dictionaries", "into", "a", "dictionary", "of", "dictionaries", "." ]
python
train
RealTimeWeb/datasets
preprocess/earthquakes/earthquakes.py
https://github.com/RealTimeWeb/datasets/blob/2fe5befd251c783744d000bd4763e277616a152f/preprocess/earthquakes/earthquakes.py#L148-L169
def disconnect(filename=None): """ Connect to the local cache, so no internet connection is required. :returns: void """ global _CONNECTED if filename is not None: try: with open(filename, 'r') as f: _load_from_string(f.read()) except FileNotFoundError...
[ "def", "disconnect", "(", "filename", "=", "None", ")", ":", "global", "_CONNECTED", "if", "filename", "is", "not", "None", ":", "try", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "f", ":", "_load_from_string", "(", "f", ".", "read", ...
Connect to the local cache, so no internet connection is required. :returns: void
[ "Connect", "to", "the", "local", "cache", "so", "no", "internet", "connection", "is", "required", ".", ":", "returns", ":", "void" ]
python
train
csurfer/pyheat
pyheat/pyheat.py
https://github.com/csurfer/pyheat/blob/cc0ee3721aea70a1da4918957500131aa7077afe/pyheat/pyheat.py#L83-L88
def __profile_file(self): """Method used to profile the given file line by line.""" self.line_profiler = pprofile.Profile() self.line_profiler.runfile( open(self.pyfile.path, "r"), {}, self.pyfile.path )
[ "def", "__profile_file", "(", "self", ")", ":", "self", ".", "line_profiler", "=", "pprofile", ".", "Profile", "(", ")", "self", ".", "line_profiler", ".", "runfile", "(", "open", "(", "self", ".", "pyfile", ".", "path", ",", "\"r\"", ")", ",", "{", ...
Method used to profile the given file line by line.
[ "Method", "used", "to", "profile", "the", "given", "file", "line", "by", "line", "." ]
python
train
sveetch/djangocodemirror
djangocodemirror/helper.py
https://github.com/sveetch/djangocodemirror/blob/7d556eec59861b2f619398e837bdd089b3a8a7d7/djangocodemirror/helper.py#L52-L88
def codemirror_settings_update(configs, parameters, on=None, names=None): """ Return a new dictionnary of configs updated with given parameters. You may use ``on`` and ``names`` arguments to select config or filter out some configs from returned dict. Arguments: configs (dict): Dictionnary...
[ "def", "codemirror_settings_update", "(", "configs", ",", "parameters", ",", "on", "=", "None", ",", "names", "=", "None", ")", ":", "# Deep copy of given config", "output", "=", "copy", ".", "deepcopy", "(", "configs", ")", "# Optionnaly filtering config from given...
Return a new dictionnary of configs updated with given parameters. You may use ``on`` and ``names`` arguments to select config or filter out some configs from returned dict. Arguments: configs (dict): Dictionnary of configurations to update. parameters (dict): Dictionnary of parameters to ...
[ "Return", "a", "new", "dictionnary", "of", "configs", "updated", "with", "given", "parameters", "." ]
python
train
CTPUG/wafer
wafer/pages/management/commands/load_pages.py
https://github.com/CTPUG/wafer/blob/a20af3c399267f76373dc342f4d542a9bc457c35/wafer/pages/management/commands/load_pages.py#L24-L38
def get_parent(self, directory): """ Given a directory name, return the Page representing it in the menu heirarchy. """ assert settings.PAGE_DIR.startswith('/') assert settings.PAGE_DIR.endswith('/') parents = directory[len(settings.PAGE_DIR):] page = No...
[ "def", "get_parent", "(", "self", ",", "directory", ")", ":", "assert", "settings", ".", "PAGE_DIR", ".", "startswith", "(", "'/'", ")", "assert", "settings", ".", "PAGE_DIR", ".", "endswith", "(", "'/'", ")", "parents", "=", "directory", "[", "len", "("...
Given a directory name, return the Page representing it in the menu heirarchy.
[ "Given", "a", "directory", "name", "return", "the", "Page", "representing", "it", "in", "the", "menu", "heirarchy", "." ]
python
train
ToucanToco/toucan-data-sdk
toucan_data_sdk/utils/postprocess/add_aggregation_columns.py
https://github.com/ToucanToco/toucan-data-sdk/blob/c3ca874e1b64f4bdcc2edda750a72d45d1561d8a/toucan_data_sdk/utils/postprocess/add_aggregation_columns.py#L6-L74
def add_aggregation_columns( df, *, group_cols: Union[str, List[str]], aggregations: Dict[str, Agg] ): """ Add new columns containing aggregations values on existing columns --- ### Parameters *mandatory :* - `group_cols` (*str* or *list*): columns used to aggregate th...
[ "def", "add_aggregation_columns", "(", "df", ",", "*", ",", "group_cols", ":", "Union", "[", "str", ",", "List", "[", "str", "]", "]", ",", "aggregations", ":", "Dict", "[", "str", ",", "Agg", "]", ")", ":", "group", "=", "df", ".", "groupby", "(",...
Add new columns containing aggregations values on existing columns --- ### Parameters *mandatory :* - `group_cols` (*str* or *list*): columns used to aggregate the data - `aggregations` (*dict*): keys are name of new columns and values are aggregation functions Examples of aggregation func...
[ "Add", "new", "columns", "containing", "aggregations", "values", "on", "existing", "columns" ]
python
test
CalebBell/fluids
fluids/friction.py
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/friction.py#L2317-L2369
def helical_turbulent_fd_Mori_Nakayama(Re, Di, Dc): r'''Calculates Darcy friction factor for a fluid flowing inside a curved pipe such as a helical coil under turbulent conditions, using the method of Mori and Nakayama [1]_, also shown in [2]_ and [3]_. .. math:: f_{curv} = 0.3\left(\...
[ "def", "helical_turbulent_fd_Mori_Nakayama", "(", "Re", ",", "Di", ",", "Dc", ")", ":", "term", "=", "(", "Re", "*", "(", "Di", "/", "Dc", ")", "**", "2", ")", "**", "-", "0.2", "return", "0.3", "*", "(", "Dc", "/", "Di", ")", "**", "-", "0.5",...
r'''Calculates Darcy friction factor for a fluid flowing inside a curved pipe such as a helical coil under turbulent conditions, using the method of Mori and Nakayama [1]_, also shown in [2]_ and [3]_. .. math:: f_{curv} = 0.3\left(\frac{D_i}{D_c}\right)^{0.5} \left[Re\left(\frac{...
[ "r", "Calculates", "Darcy", "friction", "factor", "for", "a", "fluid", "flowing", "inside", "a", "curved", "pipe", "such", "as", "a", "helical", "coil", "under", "turbulent", "conditions", "using", "the", "method", "of", "Mori", "and", "Nakayama", "[", "1", ...
python
train
senaite/senaite.core
bika/lims/browser/attachment.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/attachment.py#L430-L438
def get_attachment_types(self): """Returns a list of available attachment types """ bika_setup_catalog = api.get_tool("bika_setup_catalog") attachment_types = bika_setup_catalog(portal_type='AttachmentType', is_active=True, ...
[ "def", "get_attachment_types", "(", "self", ")", ":", "bika_setup_catalog", "=", "api", ".", "get_tool", "(", "\"bika_setup_catalog\"", ")", "attachment_types", "=", "bika_setup_catalog", "(", "portal_type", "=", "'AttachmentType'", ",", "is_active", "=", "True", ",...
Returns a list of available attachment types
[ "Returns", "a", "list", "of", "available", "attachment", "types" ]
python
train
beetbox/audioread
audioread/gstdec.py
https://github.com/beetbox/audioread/blob/c8bedf7880f13a7b7488b108aaf245d648674818/audioread/gstdec.py#L262-L283
def _notify_caps(self, pad, args): """The callback for the sinkpad's "notify::caps" signal. """ # The sink has started to receive data, so the stream is ready. # This also is our opportunity to read information about the # stream. self.got_caps = True info = pad.g...
[ "def", "_notify_caps", "(", "self", ",", "pad", ",", "args", ")", ":", "# The sink has started to receive data, so the stream is ready.", "# This also is our opportunity to read information about the", "# stream.", "self", ".", "got_caps", "=", "True", "info", "=", "pad", "...
The callback for the sinkpad's "notify::caps" signal.
[ "The", "callback", "for", "the", "sinkpad", "s", "notify", "::", "caps", "signal", "." ]
python
train
Saledddar/pyunet
pyunet/util.py
https://github.com/Saledddar/pyunet/blob/ca5ccc32588fae8da43f968e7747d3f3da509507/pyunet/util.py#L123-L166
def get_decorated_names(path,decorator_module, decorator_name): ''' Get the name of fumctions or methods decorated with the specified decorator. If a method, the name will be as class_name.method_name. Args : path : The path to the module. decorator_mod...
[ "def", "get_decorated_names", "(", "path", ",", "decorator_module", ",", "decorator_name", ")", ":", "#Read the source", "with", "open", "(", "path", ")", "as", "f", ":", "module_source", "=", "f", ".", "read", "(", ")", "expression", "=", "'\\s*@(?:{}\\.)?{}[...
Get the name of fumctions or methods decorated with the specified decorator. If a method, the name will be as class_name.method_name. Args : path : The path to the module. decorator_module : The name of the module defining the decorator. decorator_na...
[ "Get", "the", "name", "of", "fumctions", "or", "methods", "decorated", "with", "the", "specified", "decorator", ".", "If", "a", "method", "the", "name", "will", "be", "as", "class_name", ".", "method_name", ".", "Args", ":", "path", ":", "The", "path", "...
python
train
oasiswork/zimsoap
zimsoap/zobjects.py
https://github.com/oasiswork/zimsoap/blob/d1ea2eb4d50f263c9a16e5549af03f1eff3e295e/zimsoap/zobjects.py#L471-L530
def to_creator(self, for_modify=False): """ Returns a dict object suitable for a 'CreateSignature'. A signature object for creation is like : <signature name="unittest"> <content type="text/plain">My signature content</content> </signature> which is : ...
[ "def", "to_creator", "(", "self", ",", "for_modify", "=", "False", ")", ":", "signature", "=", "{", "}", "if", "for_modify", ":", "try", ":", "# we should have an ID", "signature", "[", "'id'", "]", "=", "self", ".", "id", "except", "AttributeError", ":", ...
Returns a dict object suitable for a 'CreateSignature'. A signature object for creation is like : <signature name="unittest"> <content type="text/plain">My signature content</content> </signature> which is : { 'name' : 'unittest', ...
[ "Returns", "a", "dict", "object", "suitable", "for", "a", "CreateSignature", "." ]
python
train
twilio/twilio-python
twilio/rest/preview/deployed_devices/fleet/device.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/preview/deployed_devices/fleet/device.py#L211-L220
def get_instance(self, payload): """ Build an instance of DeviceInstance :param dict payload: Payload response from the API :returns: twilio.rest.preview.deployed_devices.fleet.device.DeviceInstance :rtype: twilio.rest.preview.deployed_devices.fleet.device.DeviceInstance ...
[ "def", "get_instance", "(", "self", ",", "payload", ")", ":", "return", "DeviceInstance", "(", "self", ".", "_version", ",", "payload", ",", "fleet_sid", "=", "self", ".", "_solution", "[", "'fleet_sid'", "]", ",", ")" ]
Build an instance of DeviceInstance :param dict payload: Payload response from the API :returns: twilio.rest.preview.deployed_devices.fleet.device.DeviceInstance :rtype: twilio.rest.preview.deployed_devices.fleet.device.DeviceInstance
[ "Build", "an", "instance", "of", "DeviceInstance" ]
python
train
CygnusNetworks/pypureomapi
pypureomapi.py
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L131-L146
def add(self, data): """ >>> ob = OutBuffer().add(OutBuffer.sizelimit * b"x") >>> ob.add(b"y") # doctest: +ELLIPSIS Traceback (most recent call last): ... OmapiSizeLimitError: ... @type data: bytes @returns: self @raises OmapiSizeLimitError: """ if len(self) + len(data) > self.sizelimit: raise...
[ "def", "add", "(", "self", ",", "data", ")", ":", "if", "len", "(", "self", ")", "+", "len", "(", "data", ")", ">", "self", ".", "sizelimit", ":", "raise", "OmapiSizeLimitError", "(", ")", "self", ".", "buff", ".", "write", "(", "data", ")", "ret...
>>> ob = OutBuffer().add(OutBuffer.sizelimit * b"x") >>> ob.add(b"y") # doctest: +ELLIPSIS Traceback (most recent call last): ... OmapiSizeLimitError: ... @type data: bytes @returns: self @raises OmapiSizeLimitError:
[ ">>>", "ob", "=", "OutBuffer", "()", ".", "add", "(", "OutBuffer", ".", "sizelimit", "*", "b", "x", ")", ">>>", "ob", ".", "add", "(", "b", "y", ")", "#", "doctest", ":", "+", "ELLIPSIS", "Traceback", "(", "most", "recent", "call", "last", ")", "...
python
train
bcbio/bcbio-nextgen
bcbio/chipseq/peaks.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/chipseq/peaks.py#L45-L59
def calling(data): """Main function to parallelize peak calling.""" chip_bam = data.get("work_bam") input_bam = data.get("work_bam_input", None) caller_fn = get_callers()[data["peak_fn"]] name = dd.get_sample_name(data) out_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), data["peak_...
[ "def", "calling", "(", "data", ")", ":", "chip_bam", "=", "data", ".", "get", "(", "\"work_bam\"", ")", "input_bam", "=", "data", ".", "get", "(", "\"work_bam_input\"", ",", "None", ")", "caller_fn", "=", "get_callers", "(", ")", "[", "data", "[", "\"p...
Main function to parallelize peak calling.
[ "Main", "function", "to", "parallelize", "peak", "calling", "." ]
python
train
Nic30/hwt
hwt/hdl/types/boolVal.py
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/hdl/types/boolVal.py#L70-L89
def fromPy(cls, val, typeObj, vldMask=None): """ :param val: value of python type bool or None :param typeObj: instance of HdlType :param vldMask: None vldMask is resolved from val, if is 0 value is invalidated if is 1 value has to be valid """ vld...
[ "def", "fromPy", "(", "cls", ",", "val", ",", "typeObj", ",", "vldMask", "=", "None", ")", ":", "vld", "=", "int", "(", "val", "is", "not", "None", ")", "if", "not", "vld", ":", "assert", "vldMask", "is", "None", "or", "vldMask", "==", "0", "val"...
:param val: value of python type bool or None :param typeObj: instance of HdlType :param vldMask: None vldMask is resolved from val, if is 0 value is invalidated if is 1 value has to be valid
[ ":", "param", "val", ":", "value", "of", "python", "type", "bool", "or", "None", ":", "param", "typeObj", ":", "instance", "of", "HdlType", ":", "param", "vldMask", ":", "None", "vldMask", "is", "resolved", "from", "val", "if", "is", "0", "value", "is"...
python
test
openstack/pyghmi
pyghmi/ipmi/command.py
https://github.com/openstack/pyghmi/blob/f710b1d30a8eed19a9e86f01f9351c737666f3e5/pyghmi/ipmi/command.py#L295-L352
def set_power(self, powerstate, wait=False): """Request power state change (helper) :param powerstate: * on -- Request system turn on * off -- Request system turn off without waiting for OS to shutdown ...
[ "def", "set_power", "(", "self", ",", "powerstate", ",", "wait", "=", "False", ")", ":", "if", "powerstate", "not", "in", "power_states", ":", "raise", "exc", ".", "InvalidParameterValue", "(", "\"Unknown power state %s requested\"", "%", "powerstate", ")", "new...
Request power state change (helper) :param powerstate: * on -- Request system turn on * off -- Request system turn off without waiting for OS to shutdown * shutdown -- Have system request OS...
[ "Request", "power", "state", "change", "(", "helper", ")" ]
python
train
oscarlazoarjona/fast
fast/electric_field.py
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/electric_field.py#L318-L338
def electric_field_amplitude_gaussian(P, sigmax, sigmay=None, Omega=1.0e6, units="ad-hoc"): """Return the amplitude of the electric field for a Gaussian beam. This the amplitude at the center of a laser beam of power P (in Watts) and\ a Gaussian intensity distributio...
[ "def", "electric_field_amplitude_gaussian", "(", "P", ",", "sigmax", ",", "sigmay", "=", "None", ",", "Omega", "=", "1.0e6", ",", "units", "=", "\"ad-hoc\"", ")", ":", "e0", "=", "hbar", "*", "Omega", "/", "(", "e", "*", "a0", ")", "# This is the electri...
Return the amplitude of the electric field for a Gaussian beam. This the amplitude at the center of a laser beam of power P (in Watts) and\ a Gaussian intensity distribution of standard deviations sigmax, sigmay\ (in meters). The value of E0 is given in rescaled units according to the\ frequency scale Ome...
[ "Return", "the", "amplitude", "of", "the", "electric", "field", "for", "a", "Gaussian", "beam", ".", "This", "the", "amplitude", "at", "the", "center", "of", "a", "laser", "beam", "of", "power", "P", "(", "in", "Watts", ")", "and", "\\", "a", "Gaussian...
python
train
DLR-RM/RAFCON
source/rafcon/core/states/library_state.py
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/library_state.py#L259-L270
def remove_outcome(self, outcome_id, force=False, destroy=True): """Overwrites the remove_outcome method of the State class. Prevents user from removing a outcome from the library state. For further documentation, look at the State class. :raises exceptions.NotImplementedError: in any ...
[ "def", "remove_outcome", "(", "self", ",", "outcome_id", ",", "force", "=", "False", ",", "destroy", "=", "True", ")", ":", "if", "force", ":", "return", "State", ".", "remove_outcome", "(", "self", ",", "outcome_id", ",", "force", ",", "destroy", ")", ...
Overwrites the remove_outcome method of the State class. Prevents user from removing a outcome from the library state. For further documentation, look at the State class. :raises exceptions.NotImplementedError: in any case
[ "Overwrites", "the", "remove_outcome", "method", "of", "the", "State", "class", ".", "Prevents", "user", "from", "removing", "a", "outcome", "from", "the", "library", "state", "." ]
python
train
senseobservationsystems/commonsense-python-lib
senseapi.py
https://github.com/senseobservationsystems/commonsense-python-lib/blob/aac59a1751ef79eb830b3ca1fab6ef2c83931f87/senseapi.py#L592-L606
def SensorsPost(self, parameters): """ Create a sensor in CommonSense. If SensorsPost is successful, the sensor details, including its sensor_id, can be obtained by a call to getResponse(), and should be a json string. @param parameters (dictonary) - Diction...
[ "def", "SensorsPost", "(", "self", ",", "parameters", ")", ":", "if", "self", ".", "__SenseApiCall__", "(", "'/sensors.json'", ",", "'POST'", ",", "parameters", "=", "parameters", ")", ":", "return", "True", "else", ":", "self", ".", "__error__", "=", "\"a...
Create a sensor in CommonSense. If SensorsPost is successful, the sensor details, including its sensor_id, can be obtained by a call to getResponse(), and should be a json string. @param parameters (dictonary) - Dictionary containing the details of the sensor to be created. ...
[ "Create", "a", "sensor", "in", "CommonSense", ".", "If", "SensorsPost", "is", "successful", "the", "sensor", "details", "including", "its", "sensor_id", "can", "be", "obtained", "by", "a", "call", "to", "getResponse", "()", "and", "should", "be", "a", "json"...
python
train
bakwc/JamSpell
evaluate/context_spell_prototype.py
https://github.com/bakwc/JamSpell/blob/bfdfd889436df4dbcd9ec86b20d2baeb815068bd/evaluate/context_spell_prototype.py#L33-L43
def correction(sentence, pos): "Most probable spelling correction for word." word = sentence[pos] cands = candidates(word) if not cands: cands = candidates(word, False) if not cands: return word cands = sorted(cands, key=lambda w: P(w, sentence, pos), reverse=True) cands = [c...
[ "def", "correction", "(", "sentence", ",", "pos", ")", ":", "word", "=", "sentence", "[", "pos", "]", "cands", "=", "candidates", "(", "word", ")", "if", "not", "cands", ":", "cands", "=", "candidates", "(", "word", ",", "False", ")", "if", "not", ...
Most probable spelling correction for word.
[ "Most", "probable", "spelling", "correction", "for", "word", "." ]
python
train
computational-metabolomics/msp2db
msp2db/re.py
https://github.com/computational-metabolomics/msp2db/blob/f86f01efca26fd2745547c9993f97337c6bef123/msp2db/re.py#L60-L91
def get_compound_regex(schema='mona'): """ Create a dictionary of regex for extracting the compound information for the spectra """ # NOTE: will just ignore cases in the regex, to avoid repetition here meta_parse = collections.OrderedDict() if schema == 'mona': meta_parse['name'] = ['^Name...
[ "def", "get_compound_regex", "(", "schema", "=", "'mona'", ")", ":", "# NOTE: will just ignore cases in the regex, to avoid repetition here", "meta_parse", "=", "collections", ".", "OrderedDict", "(", ")", "if", "schema", "==", "'mona'", ":", "meta_parse", "[", "'name'"...
Create a dictionary of regex for extracting the compound information for the spectra
[ "Create", "a", "dictionary", "of", "regex", "for", "extracting", "the", "compound", "information", "for", "the", "spectra" ]
python
train
tensorflow/tensor2tensor
tensor2tensor/layers/discretization.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L1374-L1390
def tanh_discrete_bottleneck(x, bottleneck_bits, bottleneck_noise, discretize_warmup_steps, mode): """Simple discretization through tanh, flip bottleneck_noise many bits.""" x = tf.layers.dense(x, bottleneck_bits, name="tanh_discrete_bottleneck") d0 = tf.stop_gradient(2.0 * tf.to_floa...
[ "def", "tanh_discrete_bottleneck", "(", "x", ",", "bottleneck_bits", ",", "bottleneck_noise", ",", "discretize_warmup_steps", ",", "mode", ")", ":", "x", "=", "tf", ".", "layers", ".", "dense", "(", "x", ",", "bottleneck_bits", ",", "name", "=", "\"tanh_discre...
Simple discretization through tanh, flip bottleneck_noise many bits.
[ "Simple", "discretization", "through", "tanh", "flip", "bottleneck_noise", "many", "bits", "." ]
python
train
gboeing/osmnx
osmnx/plot.py
https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/plot.py#L148-L180
def get_node_colors_by_attr(G, attr, num_bins=None, cmap='viridis', start=0, stop=1, na_color='none'): """ Get a list of node colors by binning some continuous-variable attribute into quantiles. Parameters ---------- G : networkx multidigraph attr : string the name of the attribute ...
[ "def", "get_node_colors_by_attr", "(", "G", ",", "attr", ",", "num_bins", "=", "None", ",", "cmap", "=", "'viridis'", ",", "start", "=", "0", ",", "stop", "=", "1", ",", "na_color", "=", "'none'", ")", ":", "if", "num_bins", "is", "None", ":", "num_b...
Get a list of node colors by binning some continuous-variable attribute into quantiles. Parameters ---------- G : networkx multidigraph attr : string the name of the attribute num_bins : int how many quantiles (default None assigns each node to its own bin) cmap : string ...
[ "Get", "a", "list", "of", "node", "colors", "by", "binning", "some", "continuous", "-", "variable", "attribute", "into", "quantiles", "." ]
python
train
thebigmunch/gmusicapi-wrapper
gmusicapi_wrapper/mobileclient.py
https://github.com/thebigmunch/gmusicapi-wrapper/blob/8708683cd33955def1378fc28319ef37805b851d/gmusicapi_wrapper/mobileclient.py#L146-L191
def get_google_playlist_songs(self, playlist, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False): """Create song list from a user-generated Google Music playlist. Parameters: playlist (str): Name or ID of Google Music playlist. Names are case-sensitive. Google allows multipl...
[ "def", "get_google_playlist_songs", "(", "self", ",", "playlist", ",", "include_filters", "=", "None", ",", "exclude_filters", "=", "None", ",", "all_includes", "=", "False", ",", "all_excludes", "=", "False", ")", ":", "logger", ".", "info", "(", "\"Loading G...
Create song list from a user-generated Google Music playlist. Parameters: playlist (str): Name or ID of Google Music playlist. Names are case-sensitive. Google allows multiple playlists with the same name. If multiple playlists have the same name, the first one encountered is used. include_filters (li...
[ "Create", "song", "list", "from", "a", "user", "-", "generated", "Google", "Music", "playlist", "." ]
python
valid
saltstack/salt
salt/modules/influxdb08mod.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L584-L628
def query(database, query, time_precision='s', chunked=False, user=None, password=None, host=None, port=None): ''' Querying data database The database to query query Query to be executed time_precision T...
[ "def", "query", "(", "database", ",", "query", ",", "time_precision", "=", "'s'", ",", "chunked", "=", "False", ",", "user", "=", "None", ",", "password", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ")", ":", "client", "=", "_c...
Querying data database The database to query query Query to be executed time_precision Time precision to use ('s', 'm', or 'u') chunked Whether is chunked or not user The user to connect as password The password of the user host ...
[ "Querying", "data" ]
python
train
amol-/dukpy
dukpy/tsc.py
https://github.com/amol-/dukpy/blob/69f56f375a217c9f907499c28dbc964af76feae6/dukpy/tsc.py#L8-L15
def typescript_compile(source): """Compiles the given ``source`` from TypeScript to ES5 using TypescriptServices.js""" with open(TS_COMPILER, 'r') as tsservices_js: return evaljs( (tsservices_js.read(), 'ts.transpile(dukpy.tscode, {options});'.format(options=TSC_OPTIONS)), ...
[ "def", "typescript_compile", "(", "source", ")", ":", "with", "open", "(", "TS_COMPILER", ",", "'r'", ")", "as", "tsservices_js", ":", "return", "evaljs", "(", "(", "tsservices_js", ".", "read", "(", ")", ",", "'ts.transpile(dukpy.tscode, {options});'", ".", "...
Compiles the given ``source`` from TypeScript to ES5 using TypescriptServices.js
[ "Compiles", "the", "given", "source", "from", "TypeScript", "to", "ES5", "using", "TypescriptServices", ".", "js" ]
python
train
django-extensions/django-extensions
django_extensions/templatetags/indent_text.py
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/templatetags/indent_text.py#L33-L55
def indentby(parser, token): """ Add indentation to text between the tags by the given indentation level. {% indentby <indent_level> [if <statement>] %} ... {% endindentby %} Arguments: indent_level - Number of spaces to indent text with. statement - Only apply indent_level if the ...
[ "def", "indentby", "(", "parser", ",", "token", ")", ":", "args", "=", "token", ".", "split_contents", "(", ")", "largs", "=", "len", "(", "args", ")", "if", "largs", "not", "in", "(", "2", ",", "4", ")", ":", "raise", "template", ".", "TemplateSyn...
Add indentation to text between the tags by the given indentation level. {% indentby <indent_level> [if <statement>] %} ... {% endindentby %} Arguments: indent_level - Number of spaces to indent text with. statement - Only apply indent_level if the boolean statement evalutates to True.
[ "Add", "indentation", "to", "text", "between", "the", "tags", "by", "the", "given", "indentation", "level", "." ]
python
train
slundberg/shap
shap/benchmark/metrics.py
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/metrics.py#L207-L214
def keep_negative_resample(X, y, model_generator, method_name, num_fcounts=11): """ Keep Negative (resample) xlabel = "Max fraction of features kept" ylabel = "Negative mean model output" transform = "negate" sort_order = 11 """ return __run_measure(measures.keep_resample, X, y, model_genera...
[ "def", "keep_negative_resample", "(", "X", ",", "y", ",", "model_generator", ",", "method_name", ",", "num_fcounts", "=", "11", ")", ":", "return", "__run_measure", "(", "measures", ".", "keep_resample", ",", "X", ",", "y", ",", "model_generator", ",", "meth...
Keep Negative (resample) xlabel = "Max fraction of features kept" ylabel = "Negative mean model output" transform = "negate" sort_order = 11
[ "Keep", "Negative", "(", "resample", ")", "xlabel", "=", "Max", "fraction", "of", "features", "kept", "ylabel", "=", "Negative", "mean", "model", "output", "transform", "=", "negate", "sort_order", "=", "11" ]
python
train
TheHive-Project/TheHive4py
thehive4py/api.py
https://github.com/TheHive-Project/TheHive4py/blob/35762bbd50d8376943268464326b59c752d6241b/thehive4py/api.py#L126-L143
def create_case_task(self, case_id, case_task): """ :param case_id: Case identifier :param case_task: TheHive task :type case_task: CaseTask defined in models.py :return: TheHive task :rtype: json """ req = self.url + "/api/case/{}/task".format(case_id)...
[ "def", "create_case_task", "(", "self", ",", "case_id", ",", "case_task", ")", ":", "req", "=", "self", ".", "url", "+", "\"/api/case/{}/task\"", ".", "format", "(", "case_id", ")", "data", "=", "case_task", ".", "jsonify", "(", ")", "try", ":", "return"...
:param case_id: Case identifier :param case_task: TheHive task :type case_task: CaseTask defined in models.py :return: TheHive task :rtype: json
[ ":", "param", "case_id", ":", "Case", "identifier", ":", "param", "case_task", ":", "TheHive", "task", ":", "type", "case_task", ":", "CaseTask", "defined", "in", "models", ".", "py", ":", "return", ":", "TheHive", "task", ":", "rtype", ":", "json" ]
python
train
ace0/pyrelic
pyrelic/vpop.py
https://github.com/ace0/pyrelic/blob/f23d4e6586674675f72304d5938548267d6413bf/pyrelic/vpop.py#L10-L30
def eval(w,t,x,msk,s): """ Pythia server-side computation of intermediate PRF output. @w: ensemble key selector (e.g. webserver ID) @t: tweak (e.g. user ID) @x: blinded message (element of G1) @msk: Pythia server's master secret key @s: state value from Pythia server's key table @returns...
[ "def", "eval", "(", "w", ",", "t", ",", "x", ",", "msk", ",", "s", ")", ":", "# Construct the key", "kw", "=", "genKw", "(", "w", ",", "msk", ",", "s", ")", "# Multiply x by kw (it's fastest this way), hash the tweak, and compute", "# the pairing.", "tTilde", ...
Pythia server-side computation of intermediate PRF output. @w: ensemble key selector (e.g. webserver ID) @t: tweak (e.g. user ID) @x: blinded message (element of G1) @msk: Pythia server's master secret key @s: state value from Pythia server's key table @returns: (y, kw, tTile) where: y: int...
[ "Pythia", "server", "-", "side", "computation", "of", "intermediate", "PRF", "output", "." ]
python
train
thebigmunch/google-music
src/google_music/clients/base.py
https://github.com/thebigmunch/google-music/blob/d8a94dab462a1f063fbc1152187a73dc2f0e2a85/src/google_music/clients/base.py#L107-L124
def login(self, username, *, token=None): """Log in to Google Music. Parameters: username (str, Optional): Your Google Music username. Used for keeping stored OAuth tokens for multiple accounts separate. device_id (str, Optional): A mobile device ID or music manager uploader ID. Default: MAC address ...
[ "def", "login", "(", "self", ",", "username", ",", "*", ",", "token", "=", "None", ")", ":", "self", ".", "_username", "=", "username", "self", ".", "_oauth", "(", "username", ",", "token", "=", "token", ")", "return", "self", ".", "is_authenticated" ]
Log in to Google Music. Parameters: username (str, Optional): Your Google Music username. Used for keeping stored OAuth tokens for multiple accounts separate. device_id (str, Optional): A mobile device ID or music manager uploader ID. Default: MAC address is used. token (dict, Optional): An OAuth to...
[ "Log", "in", "to", "Google", "Music", "." ]
python
train
darothen/xbpch
xbpch/common.py
https://github.com/darothen/xbpch/blob/31972dd6fd5f3f7cecc3a46080ce4f43ca23fbe5/xbpch/common.py#L23-L49
def get_timestamp(time=True, date=True, fmt=None): """ Return the current timestamp in machine local time. Parameters: ----------- time, date : Boolean Flag to include the time or date components, respectively, in the output. fmt : str, optional If passed, will override the ...
[ "def", "get_timestamp", "(", "time", "=", "True", ",", "date", "=", "True", ",", "fmt", "=", "None", ")", ":", "time_format", "=", "\"%H:%M:%S\"", "date_format", "=", "\"%m-%d-%Y\"", "if", "fmt", "is", "None", ":", "if", "time", "and", "date", ":", "fm...
Return the current timestamp in machine local time. Parameters: ----------- time, date : Boolean Flag to include the time or date components, respectively, in the output. fmt : str, optional If passed, will override the time/date choice and use as the format string passe...
[ "Return", "the", "current", "timestamp", "in", "machine", "local", "time", "." ]
python
train
wangsix/vmo
vmo/analysis/analysis.py
https://github.com/wangsix/vmo/blob/bb1cc4cf1f33f0bb49e38c91126c1be1a0cdd09d/vmo/analysis/analysis.py#L469-L503
def _query_k(k, i, P, oracle, query, trn, state_cache, dist_cache, smooth=False, D=None, weight=0.5): """A helper function for query-matching function`s iteration over observations. Args: k - index of the candidate path i - index of the frames of the observations P - the path matrix...
[ "def", "_query_k", "(", "k", ",", "i", ",", "P", ",", "oracle", ",", "query", ",", "trn", ",", "state_cache", ",", "dist_cache", ",", "smooth", "=", "False", ",", "D", "=", "None", ",", "weight", "=", "0.5", ")", ":", "_trn", "=", "trn", "(", "...
A helper function for query-matching function`s iteration over observations. Args: k - index of the candidate path i - index of the frames of the observations P - the path matrix of size K x N, K the number for paths initiated, N the frame number of observations ora...
[ "A", "helper", "function", "for", "query", "-", "matching", "function", "s", "iteration", "over", "observations", ".", "Args", ":", "k", "-", "index", "of", "the", "candidate", "path", "i", "-", "index", "of", "the", "frames", "of", "the", "observations", ...
python
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology2.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology2.py#L498-L524
def defuse_activation(self): """ Defuse the fused activation layers in the network. """ idx, nb_layers = 0, len(self.layer_list) while idx < nb_layers: layer = self.layer_list[idx] k_layer = self.keras_layer_map[layer] if (isinstance(k_layer, _keras.la...
[ "def", "defuse_activation", "(", "self", ")", ":", "idx", ",", "nb_layers", "=", "0", ",", "len", "(", "self", ".", "layer_list", ")", "while", "idx", "<", "nb_layers", ":", "layer", "=", "self", ".", "layer_list", "[", "idx", "]", "k_layer", "=", "s...
Defuse the fused activation layers in the network.
[ "Defuse", "the", "fused", "activation", "layers", "in", "the", "network", "." ]
python
train
dshean/demcoreg
demcoreg/dem_mask.py
https://github.com/dshean/demcoreg/blob/abd6be75d326b35f52826ee30dff01f9e86b4b52/demcoreg/dem_mask.py#L230-L249
def get_modis_tile_list(ds): """Helper function to identify MODIS tiles that intersect input geometry modis_gird.py contains dictionary of tile boundaries (tile name and WKT polygon ring from bbox) See: https://modis-land.gsfc.nasa.gov/MODLAND_grid.html """ from demcoreg import modis_grid modi...
[ "def", "get_modis_tile_list", "(", "ds", ")", ":", "from", "demcoreg", "import", "modis_grid", "modis_dict", "=", "{", "}", "for", "key", "in", "modis_grid", ".", "modis_dict", ":", "modis_dict", "[", "key", "]", "=", "ogr", ".", "CreateGeometryFromWkt", "("...
Helper function to identify MODIS tiles that intersect input geometry modis_gird.py contains dictionary of tile boundaries (tile name and WKT polygon ring from bbox) See: https://modis-land.gsfc.nasa.gov/MODLAND_grid.html
[ "Helper", "function", "to", "identify", "MODIS", "tiles", "that", "intersect", "input", "geometry" ]
python
train
benley/butcher
butcher/cache.py
https://github.com/benley/butcher/blob/8b18828ea040af56b7835beab5fd03eab23cc9ee/butcher/cache.py#L115-L126
def in_cache(self, objpath, metahash): """Returns true if object is cached. Args: objpath: Filename relative to buildroot. metahash: hash object """ try: self.path_in_cache(objpath, metahash) return True except CacheMiss: r...
[ "def", "in_cache", "(", "self", ",", "objpath", ",", "metahash", ")", ":", "try", ":", "self", ".", "path_in_cache", "(", "objpath", ",", "metahash", ")", "return", "True", "except", "CacheMiss", ":", "return", "False" ]
Returns true if object is cached. Args: objpath: Filename relative to buildroot. metahash: hash object
[ "Returns", "true", "if", "object", "is", "cached", "." ]
python
train
slackapi/python-slackclient
slack/rtm/client.py
https://github.com/slackapi/python-slackclient/blob/901341c0284fd81e6d2719d6a0502308760d83e4/slack/rtm/client.py#L176-L202
def start(self) -> asyncio.Future: """Starts an RTM Session with Slack. Makes an authenticated call to Slack's RTM API to retrieve a websocket URL and then connects to the message server. As events stream-in we run any associated callbacks stored on the client. If 'auto...
[ "def", "start", "(", "self", ")", "->", "asyncio", ".", "Future", ":", "# TODO: Add Windows support for graceful shutdowns.", "if", "os", ".", "name", "!=", "\"nt\"", ":", "signals", "=", "(", "signal", ".", "SIGHUP", ",", "signal", ".", "SIGTERM", ",", "sig...
Starts an RTM Session with Slack. Makes an authenticated call to Slack's RTM API to retrieve a websocket URL and then connects to the message server. As events stream-in we run any associated callbacks stored on the client. If 'auto_reconnect' is specified we retrieve a...
[ "Starts", "an", "RTM", "Session", "with", "Slack", "." ]
python
train
romana/vpc-router
vpcrouter/vpc/__init__.py
https://github.com/romana/vpc-router/blob/d696c2e023f1111ceb61f9c6fbabfafed8e14040/vpcrouter/vpc/__init__.py#L367-L433
def _get_host_for_route(vpc_info, route, route_table, dcidr): """ Given a specific route, return information about the instance to which it points. Returns 3-tuple: instance-id, ipaddr, eni-id Need to take care of scenarios where the instance isn't set anymore in the route (the instance may ha...
[ "def", "_get_host_for_route", "(", "vpc_info", ",", "route", ",", "route_table", ",", "dcidr", ")", ":", "class", "_CouldNotIdentifyHost", "(", "Exception", ")", ":", "# If we can't find both the instance as well as an eni for the route,", "# we will raise this exception. In th...
Given a specific route, return information about the instance to which it points. Returns 3-tuple: instance-id, ipaddr, eni-id Need to take care of scenarios where the instance isn't set anymore in the route (the instance may have disappeared).
[ "Given", "a", "specific", "route", "return", "information", "about", "the", "instance", "to", "which", "it", "points", "." ]
python
train
not-na/peng3d
peng3d/resource.py
https://github.com/not-na/peng3d/blob/1151be665b26cc8a479f6307086ba919e4d32d85/peng3d/resource.py#L229-L238
def loadModel(self,name): """ Loads the model of the given name. The model will also be inserted into the cache. """ m = model.Model(self.peng,self,name) self.modelobjcache[name]=m self.peng.sendEvent("peng3d:rsrc.model.load",{"peng":self.peng,"name":name...
[ "def", "loadModel", "(", "self", ",", "name", ")", ":", "m", "=", "model", ".", "Model", "(", "self", ".", "peng", ",", "self", ",", "name", ")", "self", ".", "modelobjcache", "[", "name", "]", "=", "m", "self", ".", "peng", ".", "sendEvent", "("...
Loads the model of the given name. The model will also be inserted into the cache.
[ "Loads", "the", "model", "of", "the", "given", "name", ".", "The", "model", "will", "also", "be", "inserted", "into", "the", "cache", "." ]
python
test
istresearch/scrapy-cluster
kafka-monitor/plugins/scraper_handler.py
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/kafka-monitor/plugins/scraper_handler.py#L31-L60
def handle(self, dict): ''' Processes a vaild crawl request @param dict: a valid dictionary object ''' # format key ex_res = self.extract(dict['url']) key = "{sid}:{dom}.{suf}:queue".format( sid=dict['spiderid'], dom=ex_res.domain, ...
[ "def", "handle", "(", "self", ",", "dict", ")", ":", "# format key", "ex_res", "=", "self", ".", "extract", "(", "dict", "[", "'url'", "]", ")", "key", "=", "\"{sid}:{dom}.{suf}:queue\"", ".", "format", "(", "sid", "=", "dict", "[", "'spiderid'", "]", ...
Processes a vaild crawl request @param dict: a valid dictionary object
[ "Processes", "a", "vaild", "crawl", "request" ]
python
train
Sean1708/HipPy
hippy/__init__.py
https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/__init__.py#L21-L24
def write(file_name, data): """Encode and write a Hip file.""" with open(file_name, 'w') as f: f.write(encode(data))
[ "def", "write", "(", "file_name", ",", "data", ")", ":", "with", "open", "(", "file_name", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "encode", "(", "data", ")", ")" ]
Encode and write a Hip file.
[ "Encode", "and", "write", "a", "Hip", "file", "." ]
python
train
twisted/txacme
src/txacme/client.py
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/client.py#L292-L300
def _expect_response(cls, response, code): """ Ensure we got the expected response code. """ if response.code != code: raise errors.ClientError( 'Expected {!r} response but got {!r}'.format( code, response.code)) return response
[ "def", "_expect_response", "(", "cls", ",", "response", ",", "code", ")", ":", "if", "response", ".", "code", "!=", "code", ":", "raise", "errors", ".", "ClientError", "(", "'Expected {!r} response but got {!r}'", ".", "format", "(", "code", ",", "response", ...
Ensure we got the expected response code.
[ "Ensure", "we", "got", "the", "expected", "response", "code", "." ]
python
train
kevinconway/iface
iface/decorators.py
https://github.com/kevinconway/iface/blob/2687f7965eed155b9594a298ffa260a2f9f821f9/iface/decorators.py#L59-L67
def classmethod(func): """Wrap a function as a classmethod. This applies the classmethod decorator. """ attr = abc.abstractmethod(func) attr.__iclassmethod__ = True attr = _classmethod(attr) return attr
[ "def", "classmethod", "(", "func", ")", ":", "attr", "=", "abc", ".", "abstractmethod", "(", "func", ")", "attr", ".", "__iclassmethod__", "=", "True", "attr", "=", "_classmethod", "(", "attr", ")", "return", "attr" ]
Wrap a function as a classmethod. This applies the classmethod decorator.
[ "Wrap", "a", "function", "as", "a", "classmethod", "." ]
python
train
googlefonts/ufo2ft
Lib/ufo2ft/postProcessor.py
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/postProcessor.py#L73-L93
def _rename_glyphs_from_ufo(self): """Rename glyphs using ufo.lib.public.postscriptNames in UFO.""" rename_map = self._build_production_names() otf = self.otf otf.setGlyphOrder([rename_map.get(n, n) for n in otf.getGlyphOrder()]) # we need to compile format 2 'post' table so th...
[ "def", "_rename_glyphs_from_ufo", "(", "self", ")", ":", "rename_map", "=", "self", ".", "_build_production_names", "(", ")", "otf", "=", "self", ".", "otf", "otf", ".", "setGlyphOrder", "(", "[", "rename_map", ".", "get", "(", "n", ",", "n", ")", "for",...
Rename glyphs using ufo.lib.public.postscriptNames in UFO.
[ "Rename", "glyphs", "using", "ufo", ".", "lib", ".", "public", ".", "postscriptNames", "in", "UFO", "." ]
python
train
knipknap/exscript
Exscript/protocols/protocol.py
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/protocols/protocol.py#L1036-L1061
def expect(self, prompt): """ Like waitfor(), but also removes the matched string from the buffer containing the incoming data. In other words, the following may not alway complete:: conn.expect('myprompt>') conn.expect('myprompt>') # timeout Returns the...
[ "def", "expect", "(", "self", ",", "prompt", ")", ":", "while", "True", ":", "try", ":", "result", "=", "self", ".", "_expect", "(", "prompt", ")", "except", "DriverReplacedException", ":", "continue", "# retry", "return", "result" ]
Like waitfor(), but also removes the matched string from the buffer containing the incoming data. In other words, the following may not alway complete:: conn.expect('myprompt>') conn.expect('myprompt>') # timeout Returns the index of the regular expression that matched....
[ "Like", "waitfor", "()", "but", "also", "removes", "the", "matched", "string", "from", "the", "buffer", "containing", "the", "incoming", "data", ".", "In", "other", "words", "the", "following", "may", "not", "alway", "complete", "::" ]
python
train
tBaxter/tango-shared-core
build/lib/tango_shared/utils/sanetize.py
https://github.com/tBaxter/tango-shared-core/blob/35fc10aef1ceedcdb4d6d866d44a22efff718812/build/lib/tango_shared/utils/sanetize.py#L257-L278
def format_text(value): """ Takes cleaned text and creates HTML-formatted, web-friendly version. - converts links to images and video to actual media objects. - Make raw links clickable (and truncated, if necessary). - Converts smilies and markdown to valid HTML. _ Bleaches output (again) to cat...
[ "def", "format_text", "(", "value", ")", ":", "# convert media links", "value", "=", "convert_links", "(", "value", ")", "value", "=", "urlizetrunc", "(", "value", ",", "30", ")", "for", "x", "in", "EMOTICON_REPLACEMENTS", ":", "value", "=", "value", ".", ...
Takes cleaned text and creates HTML-formatted, web-friendly version. - converts links to images and video to actual media objects. - Make raw links clickable (and truncated, if necessary). - Converts smilies and markdown to valid HTML. _ Bleaches output (again) to catch any stray HTML inserted by markdo...
[ "Takes", "cleaned", "text", "and", "creates", "HTML", "-", "formatted", "web", "-", "friendly", "version", ".", "-", "converts", "links", "to", "images", "and", "video", "to", "actual", "media", "objects", ".", "-", "Make", "raw", "links", "clickable", "("...
python
train
alejandroautalan/pygubu
pygubu/builder/__init__.py
https://github.com/alejandroautalan/pygubu/blob/41c8fb37ef973736ec5d68cbe1cd4ecb78712e40/pygubu/builder/__init__.py#L195-L211
def get_image(self, path): """Return tk image corresponding to name which is taken form path.""" image = '' name = os.path.basename(path) if not StockImage.is_registered(name): ipath = self.__find_image(path) if ipath is not None: StockImage.regist...
[ "def", "get_image", "(", "self", ",", "path", ")", ":", "image", "=", "''", "name", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "if", "not", "StockImage", ".", "is_registered", "(", "name", ")", ":", "ipath", "=", "self", ".", "__fin...
Return tk image corresponding to name which is taken form path.
[ "Return", "tk", "image", "corresponding", "to", "name", "which", "is", "taken", "form", "path", "." ]
python
train
Erotemic/utool
utool/util_iter.py
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_iter.py#L146-L229
def itertwo(iterable, wrap=False): r""" equivalent to iter_window(iterable, 2, 1, wrap) Args: iterable (iter): an iterable sequence wrap (bool): if True, returns with wraparound Returns: iter: returns edges in a sequence CommandLine: python -m utool.util_iter --tes...
[ "def", "itertwo", "(", "iterable", ",", "wrap", "=", "False", ")", ":", "# it.tee may be slow, but works on all iterables", "iter1", ",", "iter2", "=", "it", ".", "tee", "(", "iterable", ",", "2", ")", "if", "wrap", ":", "iter2", "=", "it", ".", "cycle", ...
r""" equivalent to iter_window(iterable, 2, 1, wrap) Args: iterable (iter): an iterable sequence wrap (bool): if True, returns with wraparound Returns: iter: returns edges in a sequence CommandLine: python -m utool.util_iter --test-itertwo Example0: >>> # ...
[ "r", "equivalent", "to", "iter_window", "(", "iterable", "2", "1", "wrap", ")" ]
python
train
tdryer/hangups
hangups/conversation.py
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L209-L216
def last_modified(self): """When conversation was last modified (:class:`datetime.datetime`).""" timestamp = self._conversation.self_conversation_state.sort_timestamp # timestamp can be None for some reason when there is an ongoing video # hangout if timestamp is None: ...
[ "def", "last_modified", "(", "self", ")", ":", "timestamp", "=", "self", ".", "_conversation", ".", "self_conversation_state", ".", "sort_timestamp", "# timestamp can be None for some reason when there is an ongoing video", "# hangout", "if", "timestamp", "is", "None", ":",...
When conversation was last modified (:class:`datetime.datetime`).
[ "When", "conversation", "was", "last", "modified", "(", ":", "class", ":", "datetime", ".", "datetime", ")", "." ]
python
valid
remcohaszing/pywakeonlan
wakeonlan.py
https://github.com/remcohaszing/pywakeonlan/blob/d30b66172c483c4baadb426f493c3de30fecc19b/wakeonlan.py#L50-L82
def send_magic_packet(*macs, **kwargs): """ Wake up computers having any of the given mac addresses. Wake on lan must be enabled on the host device. Args: macs (str): One or more macaddresses of machines to wake. Keyword Args: ip_address (str): the ip address of the host to send t...
[ "def", "send_magic_packet", "(", "*", "macs", ",", "*", "*", "kwargs", ")", ":", "packets", "=", "[", "]", "ip", "=", "kwargs", ".", "pop", "(", "'ip_address'", ",", "BROADCAST_IP", ")", "port", "=", "kwargs", ".", "pop", "(", "'port'", ",", "DEFAULT...
Wake up computers having any of the given mac addresses. Wake on lan must be enabled on the host device. Args: macs (str): One or more macaddresses of machines to wake. Keyword Args: ip_address (str): the ip address of the host to send the magic packet to (default "25...
[ "Wake", "up", "computers", "having", "any", "of", "the", "given", "mac", "addresses", "." ]
python
train
wakatime/wakatime
wakatime/packages/ntlm_auth/ntlm.py
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/ntlm_auth/ntlm.py#L101-L108
def parse_challenge_message(self, msg2): """ Parse the NTLM CHALLENGE_MESSAGE from the server and add it to the Ntlm context fields :param msg2: A base64 encoded string of the CHALLENGE_MESSAGE """ msg2 = base64.b64decode(msg2) self.challenge_message = ChallengeMessage(m...
[ "def", "parse_challenge_message", "(", "self", ",", "msg2", ")", ":", "msg2", "=", "base64", ".", "b64decode", "(", "msg2", ")", "self", ".", "challenge_message", "=", "ChallengeMessage", "(", "msg2", ")" ]
Parse the NTLM CHALLENGE_MESSAGE from the server and add it to the Ntlm context fields :param msg2: A base64 encoded string of the CHALLENGE_MESSAGE
[ "Parse", "the", "NTLM", "CHALLENGE_MESSAGE", "from", "the", "server", "and", "add", "it", "to", "the", "Ntlm", "context", "fields" ]
python
train
h2oai/h2o-3
h2o-docs/src/product/sphinxext/apigen.py
https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-docs/src/product/sphinxext/apigen.py#L394-L427
def write_index(self, outdir, froot='gen', relative_to=None): """Make a reST API index file from written files Parameters ---------- path : string Filename to write index to outdir : string Directory to which to write generated index file froot : ...
[ "def", "write_index", "(", "self", ",", "outdir", ",", "froot", "=", "'gen'", ",", "relative_to", "=", "None", ")", ":", "if", "self", ".", "written_modules", "is", "None", ":", "raise", "ValueError", "(", "'No modules written'", ")", "# Get full filename path...
Make a reST API index file from written files Parameters ---------- path : string Filename to write index to outdir : string Directory to which to write generated index file froot : string, optional root (filename without extension) of filenam...
[ "Make", "a", "reST", "API", "index", "file", "from", "written", "files" ]
python
test
mikedh/trimesh
trimesh/primitives.py
https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/primitives.py#L509-L545
def sample_grid(self, count=None, step=None): """ Return a 3D grid which is contained by the box. Samples are either 'step' distance apart, or there are 'count' samples per box side. Parameters ----------- count : int or (3,) int If specified samples ar...
[ "def", "sample_grid", "(", "self", ",", "count", "=", "None", ",", "step", "=", "None", ")", ":", "if", "(", "count", "is", "not", "None", "and", "step", "is", "not", "None", ")", ":", "raise", "ValueError", "(", "'only step OR count can be specified!'", ...
Return a 3D grid which is contained by the box. Samples are either 'step' distance apart, or there are 'count' samples per box side. Parameters ----------- count : int or (3,) int If specified samples are spaced with np.linspace step : float or (3,) float ...
[ "Return", "a", "3D", "grid", "which", "is", "contained", "by", "the", "box", ".", "Samples", "are", "either", "step", "distance", "apart", "or", "there", "are", "count", "samples", "per", "box", "side", "." ]
python
train
log2timeline/plaso
plaso/parsers/winreg_plugins/sam_users.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/winreg_plugins/sam_users.py#L117-L216
def ExtractEvents(self, parser_mediator, registry_key, **kwargs): """Extracts events from a Windows Registry key. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows ...
[ "def", "ExtractEvents", "(", "self", ",", "parser_mediator", ",", "registry_key", ",", "*", "*", "kwargs", ")", ":", "names_key", "=", "registry_key", ".", "GetSubkeyByName", "(", "'Names'", ")", "if", "not", "names_key", ":", "parser_mediator", ".", "ProduceE...
Extracts events from a Windows Registry key. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
[ "Extracts", "events", "from", "a", "Windows", "Registry", "key", "." ]
python
train
modlinltd/django-advanced-filters
advanced_filters/forms.py
https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/forms.py#L245-L267
def get_fields_from_model(self, model, fields): """ Iterate over given <field> names (in "orm query" notation) and find the actual field given the initial <model>. If <field> is a tuple of the format ('field_name', 'Verbose name'), overwrite the field's verbose name with the giv...
[ "def", "get_fields_from_model", "(", "self", ",", "model", ",", "fields", ")", ":", "model_fields", "=", "{", "}", "for", "field", "in", "fields", ":", "if", "isinstance", "(", "field", ",", "tuple", ")", "and", "len", "(", "field", ")", "==", "2", "...
Iterate over given <field> names (in "orm query" notation) and find the actual field given the initial <model>. If <field> is a tuple of the format ('field_name', 'Verbose name'), overwrite the field's verbose name with the given name for display purposes.
[ "Iterate", "over", "given", "<field", ">", "names", "(", "in", "orm", "query", "notation", ")", "and", "find", "the", "actual", "field", "given", "the", "initial", "<model", ">", "." ]
python
train
noahbenson/neuropythy
neuropythy/geometry/util.py
https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/geometry/util.py#L329-L338
def triangle_area(a,b,c): ''' triangle_area(a, b, c) yields the area of the triangle whose vertices are given by the points a, b, and c. ''' (a,b,c) = [np.asarray(x) for x in (a,b,c)] sides = np.sqrt(np.sum([(p1 - p2)**2 for (p1,p2) in zip([b,c,a],[c,a,b])], axis=1)) s = 0.5 * np.sum(sides, ...
[ "def", "triangle_area", "(", "a", ",", "b", ",", "c", ")", ":", "(", "a", ",", "b", ",", "c", ")", "=", "[", "np", ".", "asarray", "(", "x", ")", "for", "x", "in", "(", "a", ",", "b", ",", "c", ")", "]", "sides", "=", "np", ".", "sqrt",...
triangle_area(a, b, c) yields the area of the triangle whose vertices are given by the points a, b, and c.
[ "triangle_area", "(", "a", "b", "c", ")", "yields", "the", "area", "of", "the", "triangle", "whose", "vertices", "are", "given", "by", "the", "points", "a", "b", "and", "c", "." ]
python
train
jaegertracing/jaeger-client-python
jaeger_client/reporter.py
https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/reporter.py#L218-L226
def close(self): """ Ensure that all spans from the queue are submitted. Returns Future that will be completed once the queue is empty. """ with self.stop_lock: self.stopped = True return ioloop_util.submit(self._flush, io_loop=self.io_loop)
[ "def", "close", "(", "self", ")", ":", "with", "self", ".", "stop_lock", ":", "self", ".", "stopped", "=", "True", "return", "ioloop_util", ".", "submit", "(", "self", ".", "_flush", ",", "io_loop", "=", "self", ".", "io_loop", ")" ]
Ensure that all spans from the queue are submitted. Returns Future that will be completed once the queue is empty.
[ "Ensure", "that", "all", "spans", "from", "the", "queue", "are", "submitted", ".", "Returns", "Future", "that", "will", "be", "completed", "once", "the", "queue", "is", "empty", "." ]
python
train
brocade/pynos
pynos/versions/ver_7/ver_7_1_0/yang/brocade_isns.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_isns.py#L24-L37
def isns_isns_vrf_isns_ipaddress_ip(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") isns = ET.SubElement(config, "isns", xmlns="urn:brocade.com:mgmt:brocade-isns") isns_vrf = ET.SubElement(isns, "isns-vrf") isns_vrf_instance_key = ET.SubElement(i...
[ "def", "isns_isns_vrf_isns_ipaddress_ip", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "isns", "=", "ET", ".", "SubElement", "(", "config", ",", "\"isns\"", ",", "xmlns", "=", "\"urn:brocade.c...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
Iotic-Labs/py-IoticAgent
src/IoticAgent/IOT/Client.py
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/Client.py#L285-L311
def register_catchall_controlreq(self, callback, callback_parsed=None): """ Registers a callback that is called for all control requests received by your Thing `Example` #!python def controlreq_callback(data): print(data) ... clie...
[ "def", "register_catchall_controlreq", "(", "self", ",", "callback", ",", "callback_parsed", "=", "None", ")", ":", "if", "callback_parsed", ":", "callback", "=", "self", ".", "_get_parsed_control_callback", "(", "callback_parsed", ",", "callback", ")", "return", ...
Registers a callback that is called for all control requests received by your Thing `Example` #!python def controlreq_callback(data): print(data) ... client.register_catchall_controlreq(controlreq_callback) `callback` (required) the func...
[ "Registers", "a", "callback", "that", "is", "called", "for", "all", "control", "requests", "received", "by", "your", "Thing" ]
python
train
bwohlberg/sporco
sporco/dictlrn/prlcnscdl.py
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/dictlrn/prlcnscdl.py#L161-L167
def cbpdn_relax(k): """Do relaxation for the cbpdn stage. The only parameter is the slice index `k` and there are no return values; all inputs and outputs are from and to global variables. """ mp_Z_X[k] = mp_xrlx * mp_Z_X[k] + (1 - mp_xrlx) * mp_Z_Y[k]
[ "def", "cbpdn_relax", "(", "k", ")", ":", "mp_Z_X", "[", "k", "]", "=", "mp_xrlx", "*", "mp_Z_X", "[", "k", "]", "+", "(", "1", "-", "mp_xrlx", ")", "*", "mp_Z_Y", "[", "k", "]" ]
Do relaxation for the cbpdn stage. The only parameter is the slice index `k` and there are no return values; all inputs and outputs are from and to global variables.
[ "Do", "relaxation", "for", "the", "cbpdn", "stage", ".", "The", "only", "parameter", "is", "the", "slice", "index", "k", "and", "there", "are", "no", "return", "values", ";", "all", "inputs", "and", "outputs", "are", "from", "and", "to", "global", "varia...
python
train
cds-astro/mocpy
mocpy/utils.py
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/utils.py#L27-L61
def log2_lut(v): """ See `this algo <https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogLookup>`__ for computing the log2 of a 32 bit integer using a look up table Parameters ---------- v : int 32 bit integer Returns ------- """ res = np.zeros(v.shape, dtyp...
[ "def", "log2_lut", "(", "v", ")", ":", "res", "=", "np", ".", "zeros", "(", "v", ".", "shape", ",", "dtype", "=", "np", ".", "int32", ")", "tt", "=", "v", ">>", "16", "tt_zero", "=", "(", "tt", "==", "0", ")", "tt_not_zero", "=", "~", "tt_zer...
See `this algo <https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogLookup>`__ for computing the log2 of a 32 bit integer using a look up table Parameters ---------- v : int 32 bit integer Returns -------
[ "See", "this", "algo", "<https", ":", "//", "graphics", ".", "stanford", ".", "edu", "/", "~seander", "/", "bithacks", ".", "html#IntegerLogLookup", ">", "__", "for", "computing", "the", "log2", "of", "a", "32", "bit", "integer", "using", "a", "look", "u...
python
train
ff0000/scarlet
scarlet/versioning/models.py
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/versioning/models.py#L492-L503
def add_to_class(cls, name, value): """ Django 1.10 doesn't allow us to modify `_base_manager` attr: https://docs.djangoproject.com/en/1.10/topics/db/managers/#django.db.models.Model._base_manager """ if name == '_base_manager': if not value.name: valu...
[ "def", "add_to_class", "(", "cls", ",", "name", ",", "value", ")", ":", "if", "name", "==", "'_base_manager'", ":", "if", "not", "value", ".", "name", ":", "value", ".", "name", "=", "name", "value", ".", "model", "=", "cls", "setattr", "(", "cls", ...
Django 1.10 doesn't allow us to modify `_base_manager` attr: https://docs.djangoproject.com/en/1.10/topics/db/managers/#django.db.models.Model._base_manager
[ "Django", "1", ".", "10", "doesn", "t", "allow", "us", "to", "modify", "_base_manager", "attr", ":", "https", ":", "//", "docs", ".", "djangoproject", ".", "com", "/", "en", "/", "1", ".", "10", "/", "topics", "/", "db", "/", "managers", "/", "#dja...
python
train
RI-imaging/nrefocus
nrefocus/_autofocus.py
https://github.com/RI-imaging/nrefocus/blob/ad09aeecace609ab8f9effcb662d2b7d50826080/nrefocus/_autofocus.py#L86-L175
def autofocus_stack(fieldstack, nm, res, ival, roi=None, metric="average gradient", padding=True, same_dist=False, ret_ds=False, ret_grads=False, num_cpus=_cpu_count, copy=True): """Numerical autofocusing of a stack using the Helmholtz equation. Para...
[ "def", "autofocus_stack", "(", "fieldstack", ",", "nm", ",", "res", ",", "ival", ",", "roi", "=", "None", ",", "metric", "=", "\"average gradient\"", ",", "padding", "=", "True", ",", "same_dist", "=", "False", ",", "ret_ds", "=", "False", ",", "ret_grad...
Numerical autofocusing of a stack using the Helmholtz equation. Parameters ---------- fieldstack : 2d or 3d ndarray Electric field is BG-Corrected, i.e. Field = EX/BEx nm : float Refractive index of medium. res : float Size of wavelength in pixels. ival : tuple of float...
[ "Numerical", "autofocusing", "of", "a", "stack", "using", "the", "Helmholtz", "equation", "." ]
python
train