repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
juju/charm-helpers
charmhelpers/contrib/openstack/utils.py
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L754-L766
def os_requires_version(ostack_release, pkg): """ Decorator for hook to specify minimum supported release """ def wrap(f): @wraps(f) def wrapped_f(*args): if os_release(pkg) < ostack_release: raise Exception("This hook is not supported on releases" ...
[ "def", "os_requires_version", "(", "ostack_release", ",", "pkg", ")", ":", "def", "wrap", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapped_f", "(", "*", "args", ")", ":", "if", "os_release", "(", "pkg", ")", "<", "ostack_release", ":"...
Decorator for hook to specify minimum supported release
[ "Decorator", "for", "hook", "to", "specify", "minimum", "supported", "release" ]
python
train
32.384615
pallets/pallets-sphinx-themes
src/pallets_sphinx_themes/themes/click/domain.py
https://github.com/pallets/pallets-sphinx-themes/blob/1d4517d76dd492017f17acd7f72e82e40a1f1bc6/src/pallets_sphinx_themes/themes/click/domain.py#L62-L84
def patch_modules(): """Patch modules to work better with :meth:`ExampleRunner.invoke`. ``subprocess.call` output is redirected to ``click.echo`` so it shows up in the example output. """ old_call = subprocess.call def dummy_call(*args, **kwargs): with tempfile.TemporaryFile("wb+") as ...
[ "def", "patch_modules", "(", ")", ":", "old_call", "=", "subprocess", ".", "call", "def", "dummy_call", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "tempfile", ".", "TemporaryFile", "(", "\"wb+\"", ")", "as", "f", ":", "kwargs", "[", ...
Patch modules to work better with :meth:`ExampleRunner.invoke`. ``subprocess.call` output is redirected to ``click.echo`` so it shows up in the example output.
[ "Patch", "modules", "to", "work", "better", "with", ":", "meth", ":", "ExampleRunner", ".", "invoke", "." ]
python
train
27.782609
sdispater/eloquent
eloquent/query/grammars/grammar.py
https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/query/grammars/grammar.py#L312-L344
def compile_insert(self, query, values): """ Compile an insert SQL statement :param query: A QueryBuilder instance :type query: QueryBuilder :param values: The values to insert :type values: dict or list :return: The compiled statement :rtype: str ...
[ "def", "compile_insert", "(", "self", ",", "query", ",", "values", ")", ":", "# Essentially we will force every insert to be treated as a batch insert which", "# simply makes creating the SQL easier for us since we can utilize the same", "# basic routine regardless of an amount of records gi...
Compile an insert SQL statement :param query: A QueryBuilder instance :type query: QueryBuilder :param values: The values to insert :type values: dict or list :return: The compiled statement :rtype: str
[ "Compile", "an", "insert", "SQL", "statement" ]
python
train
36.30303
APSL/transmanager
transmanager/utils.py
https://github.com/APSL/transmanager/blob/79157085840008e146b264521681913090197ed1/transmanager/utils.py#L27-L43
def get_model_choices(): """ Get the select options for the model selector :return: """ result = [] for ct in ContentType.objects.order_by('app_label', 'model'): try: if issubclass(ct.model_class(), TranslatableModel): result.append( ('{} ...
[ "def", "get_model_choices", "(", ")", ":", "result", "=", "[", "]", "for", "ct", "in", "ContentType", ".", "objects", ".", "order_by", "(", "'app_label'", ",", "'model'", ")", ":", "try", ":", "if", "issubclass", "(", "ct", ".", "model_class", "(", ")"...
Get the select options for the model selector :return:
[ "Get", "the", "select", "options", "for", "the", "model", "selector" ]
python
train
31.882353
NeuroML/pyNeuroML
pyneuroml/tune/NeuroMLSimulation.py
https://github.com/NeuroML/pyNeuroML/blob/aeba2e3040b360bb26556f643cccbfb3dac3b8fb/pyneuroml/tune/NeuroMLSimulation.py#L58-L77
def show(self): """ Plot the result of the simulation once it's been intialized """ from matplotlib import pyplot as plt if self.already_run: for ref in self.volts.keys(): plt.plot(self.t, self.volts[ref], label=ref) plt...
[ "def", "show", "(", "self", ")", ":", "from", "matplotlib", "import", "pyplot", "as", "plt", "if", "self", ".", "already_run", ":", "for", "ref", "in", "self", ".", "volts", ".", "keys", "(", ")", ":", "plt", ".", "plot", "(", "self", ".", "t", "...
Plot the result of the simulation once it's been intialized
[ "Plot", "the", "result", "of", "the", "simulation", "once", "it", "s", "been", "intialized" ]
python
train
28.25
molpopgen/fwdpy11
fwdpy11/_evolve_genomes.py
https://github.com/molpopgen/fwdpy11/blob/7a5905f0f0a09e24ae5b0f39d22017499e81ea9e/fwdpy11/_evolve_genomes.py#L21-L61
def evolve_genomes(rng, pop, params, recorder=None): """ Evolve a population without tree sequence recordings. In other words, complete genomes must be simulated and tracked. :param rng: random number generator :type rng: :class:`fwdpy11.GSLrng` :param pop: A population :type pop: :class:`...
[ "def", "evolve_genomes", "(", "rng", ",", "pop", ",", "params", ",", "recorder", "=", "None", ")", ":", "import", "warnings", "# Test parameters while suppressing warnings", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "simplefilter",...
Evolve a population without tree sequence recordings. In other words, complete genomes must be simulated and tracked. :param rng: random number generator :type rng: :class:`fwdpy11.GSLrng` :param pop: A population :type pop: :class:`fwdpy11.DiploidPopulation` :param params: simulation paramete...
[ "Evolve", "a", "population", "without", "tree", "sequence", "recordings", ".", "In", "other", "words", "complete", "genomes", "must", "be", "simulated", "and", "tracked", "." ]
python
train
38.536585
se-esss-litterbox/Pynac
Pynac/Elements.py
https://github.com/se-esss-litterbox/Pynac/blob/97e20aa85d20112cd114faa54a8197c5d0f61209/Pynac/Elements.py#L418-L426
def setField(self, new_value): """ Adjust the field of the magnet by the value of ``scalingFactor``. The adjustment is multiplicative, so a value of ``scalingFactor = 1.0`` will result in no change of the field. """ self.field_strength = self.field_strength._replace( ...
[ "def", "setField", "(", "self", ",", "new_value", ")", ":", "self", ".", "field_strength", "=", "self", ".", "field_strength", ".", "_replace", "(", "val", "=", "new_value", ")" ]
Adjust the field of the magnet by the value of ``scalingFactor``. The adjustment is multiplicative, so a value of ``scalingFactor = 1.0`` will result in no change of the field.
[ "Adjust", "the", "field", "of", "the", "magnet", "by", "the", "value", "of", "scalingFactor", ".", "The", "adjustment", "is", "multiplicative", "so", "a", "value", "of", "scalingFactor", "=", "1", ".", "0", "will", "result", "in", "no", "change", "of", "...
python
train
38.222222
OpenKMIP/PyKMIP
kmip/services/server/crypto/engine.py
https://github.com/OpenKMIP/PyKMIP/blob/b51c5b044bd05f8c85a1d65d13a583a4d8fc1b0e/kmip/services/server/crypto/engine.py#L946-L1123
def derive_key(self, derivation_method, derivation_length, derivation_data=None, key_material=None, hash_algorithm=None, salt=None, iteration_count=None, encryption_alg...
[ "def", "derive_key", "(", "self", ",", "derivation_method", ",", "derivation_length", ",", "derivation_data", "=", "None", ",", "key_material", "=", "None", ",", "hash_algorithm", "=", "None", ",", "salt", "=", "None", ",", "iteration_count", "=", "None", ",",...
Derive key data using a variety of key derivation functions. Args: derivation_method (DerivationMethod): An enumeration specifying the key derivation method to use. Required. derivation_length (int): An integer specifying the size of the derived key data ...
[ "Derive", "key", "data", "using", "a", "variety", "of", "key", "derivation", "functions", "." ]
python
test
47
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/tooltip.py
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/tooltip.py#L145-L167
def event(self, event): """Reimplementation of QWidget.event The widget is closed, when the window is deactivated. The widget is closed after the set interval if the mouse leaves the widget. The timer is stops when the mouse enters the widget before the interval ends. On show, t...
[ "def", "event", "(", "self", ",", "event", ")", ":", "if", "event", ".", "type", "(", ")", "==", "QtCore", ".", "QEvent", ".", "WindowDeactivate", ":", "# hide the tooltip", "self", ".", "cyatimer", ".", "stop", "(", ")", "self", ".", "hide", "(", ")...
Reimplementation of QWidget.event The widget is closed, when the window is deactivated. The widget is closed after the set interval if the mouse leaves the widget. The timer is stops when the mouse enters the widget before the interval ends. On show, the added widgets are rendered for t...
[ "Reimplementation", "of", "QWidget", ".", "event" ]
python
train
44.652174
saltstack/salt
salt/modules/dockermod.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dockermod.py#L5922-L6020
def prune(containers=False, networks=False, images=False, build=False, volumes=False, system=None, **filters): ''' .. versionadded:: 2019.2.0 Prune Docker's various subsystems .. note:: This requires docker-py version 2.1.0 or later. containers : False If ``True``, prune...
[ "def", "prune", "(", "containers", "=", "False", ",", "networks", "=", "False", ",", "images", "=", "False", ",", "build", "=", "False", ",", "volumes", "=", "False", ",", "system", "=", "None", ",", "*", "*", "filters", ")", ":", "if", "system", "...
.. versionadded:: 2019.2.0 Prune Docker's various subsystems .. note:: This requires docker-py version 2.1.0 or later. containers : False If ``True``, prunes stopped containers (documentation__) .. __: https://docs.docker.com/engine/reference/commandline/container_prune/#filterin...
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
python
train
34.79798
pulumi/pulumi
sdk/python/lib/pulumi/config.py
https://github.com/pulumi/pulumi/blob/95d51efe6ab9a533838b6d83aa240b5f912e72aa/sdk/python/lib/pulumi/config.py#L79-L95
def get_int(self, key: str) -> Optional[int]: """ Returns an optional configuration value, as an int, by its key, or None if it doesn't exist. If the configuration value isn't a legal int, this function will throw an error. :param str key: The requested configuration key. :retur...
[ "def", "get_int", "(", "self", ",", "key", ":", "str", ")", "->", "Optional", "[", "int", "]", ":", "v", "=", "self", ".", "get", "(", "key", ")", "if", "v", "is", "None", ":", "return", "None", "try", ":", "return", "int", "(", "v", ")", "ex...
Returns an optional configuration value, as an int, by its key, or None if it doesn't exist. If the configuration value isn't a legal int, this function will throw an error. :param str key: The requested configuration key. :return: The configuration key's value, or None if one does not exist. ...
[ "Returns", "an", "optional", "configuration", "value", "as", "an", "int", "by", "its", "key", "or", "None", "if", "it", "doesn", "t", "exist", ".", "If", "the", "configuration", "value", "isn", "t", "a", "legal", "int", "this", "function", "will", "throw...
python
train
41.058824
Contraz/demosys-py
demosys/effects/effect.py
https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/effects/effect.py#L115-L125
def draw(self, time: float, frametime: float, target: moderngl.Framebuffer): """ Draw function called by the system every frame when the effect is active. This method raises ``NotImplementedError`` unless implemented. Args: time (float): The current time in seconds. ...
[ "def", "draw", "(", "self", ",", "time", ":", "float", ",", "frametime", ":", "float", ",", "target", ":", "moderngl", ".", "Framebuffer", ")", ":", "raise", "NotImplementedError", "(", "\"draw() is not implemented\"", ")" ]
Draw function called by the system every frame when the effect is active. This method raises ``NotImplementedError`` unless implemented. Args: time (float): The current time in seconds. frametime (float): The time the previous frame used to render in seconds. target ...
[ "Draw", "function", "called", "by", "the", "system", "every", "frame", "when", "the", "effect", "is", "active", ".", "This", "method", "raises", "NotImplementedError", "unless", "implemented", "." ]
python
valid
49.090909
gabstopper/smc-python
smc/vpn/route.py
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/vpn/route.py#L154-L202
def create_ipsec_tunnel(cls, name, local_endpoint, remote_endpoint, preshared_key=None, monitoring_group=None, vpn_profile=None, mtu=0, pmtu_discovery=True, ttl=0, enabled=True, comment=None): """ The VPN tunnel type neg...
[ "def", "create_ipsec_tunnel", "(", "cls", ",", "name", ",", "local_endpoint", ",", "remote_endpoint", ",", "preshared_key", "=", "None", ",", "monitoring_group", "=", "None", ",", "vpn_profile", "=", "None", ",", "mtu", "=", "0", ",", "pmtu_discovery", "=", ...
The VPN tunnel type negotiates IPsec tunnels in the same way as policy-based VPNs, but traffic is selected to be sent into the tunnel based on routing. :param str name: name of VPN :param TunnelEndpoint local_endpoint: the local side endpoint for this VPN. :p...
[ "The", "VPN", "tunnel", "type", "negotiates", "IPsec", "tunnels", "in", "the", "same", "way", "as", "policy", "-", "based", "VPNs", "but", "traffic", "is", "selected", "to", "be", "sent", "into", "the", "tunnel", "based", "on", "routing", ".", ":", "para...
python
train
44.795918
saltstack/salt
salt/modules/lxd.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxd.py#L1725-L1833
def container_file_get(name, src, dst, overwrite=False, mode=None, uid=None, gid=None, remote_addr=None, cert=None, key=None, verify_cert=True): ''' Get a file from a container name : Name of the container src : The source file or directory...
[ "def", "container_file_get", "(", "name", ",", "src", ",", "dst", ",", "overwrite", "=", "False", ",", "mode", "=", "None", ",", "uid", "=", "None", ",", "gid", "=", "None", ",", "remote_addr", "=", "None", ",", "cert", "=", "None", ",", "key", "="...
Get a file from a container name : Name of the container src : The source file or directory dst : The destination file or directory mode : Set file mode to octal number uid : Set file uid (owner) gid : Set file gid (group) remote_addr : ...
[ "Get", "a", "file", "from", "a", "container" ]
python
train
26.990826
xeroc/stakemachine
stakemachine/basestrategy.py
https://github.com/xeroc/stakemachine/blob/c2d5bcfe7c013a93c8c7293bec44ef5690883b16/stakemachine/basestrategy.py#L160-L166
def execute(self): """ Execute a bundle of operations """ self.bitshares.blocking = "head" r = self.bitshares.txbuffer.broadcast() self.bitshares.blocking = False return r
[ "def", "execute", "(", "self", ")", ":", "self", ".", "bitshares", ".", "blocking", "=", "\"head\"", "r", "=", "self", ".", "bitshares", ".", "txbuffer", ".", "broadcast", "(", ")", "self", ".", "bitshares", ".", "blocking", "=", "False", "return", "r"...
Execute a bundle of operations
[ "Execute", "a", "bundle", "of", "operations" ]
python
train
30.428571
jonathf/chaospy
chaospy/distributions/operators/sinh.py
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/operators/sinh.py#L38-L41
def _pdf(self, x, dist, cache): """Probability density function.""" return evaluation.evaluate_density( dist, numpy.arcsinh(x), cache=cache)/numpy.sqrt(1+x*x)
[ "def", "_pdf", "(", "self", ",", "x", ",", "dist", ",", "cache", ")", ":", "return", "evaluation", ".", "evaluate_density", "(", "dist", ",", "numpy", ".", "arcsinh", "(", "x", ")", ",", "cache", "=", "cache", ")", "/", "numpy", ".", "sqrt", "(", ...
Probability density function.
[ "Probability", "density", "function", "." ]
python
train
45.75
twisted/txaws
txaws/server/resource.py
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/server/resource.py#L216-L249
def _validate(self, request): """Validate an L{HTTPRequest} before executing it. The following conditions are checked: - The request contains all the generic parameters. - The action specified in the request is a supported one. - The signature mechanism is a supported one. ...
[ "def", "_validate", "(", "self", ",", "request", ")", ":", "call_arguments", "=", "self", ".", "get_call_arguments", "(", "request", ")", "args", "=", "call_arguments", "[", "\"transport_args\"", "]", "rest", "=", "call_arguments", "[", "\"handler_args\"", "]", ...
Validate an L{HTTPRequest} before executing it. The following conditions are checked: - The request contains all the generic parameters. - The action specified in the request is a supported one. - The signature mechanism is a supported one. - The provided signature matches the ...
[ "Validate", "an", "L", "{", "HTTPRequest", "}", "before", "executing", "it", "." ]
python
train
40.088235
opencobra/cobrapy
cobra/flux_analysis/reaction.py
https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/reaction.py#L60-L136
def assess_component(model, reaction, side, flux_coefficient_cutoff=0.001, solver=None): """Assesses the ability of the model to provide sufficient precursors, or absorb products, for a reaction operating at, or beyond, the specified cutoff. Parameters ---------- model : co...
[ "def", "assess_component", "(", "model", ",", "reaction", ",", "side", ",", "flux_coefficient_cutoff", "=", "0.001", ",", "solver", "=", "None", ")", ":", "reaction", "=", "model", ".", "reactions", ".", "get_by_any", "(", "reaction", ")", "[", "0", "]", ...
Assesses the ability of the model to provide sufficient precursors, or absorb products, for a reaction operating at, or beyond, the specified cutoff. Parameters ---------- model : cobra.Model The cobra model to assess production capacity for reaction : reaction identifier or cobra.Reac...
[ "Assesses", "the", "ability", "of", "the", "model", "to", "provide", "sufficient", "precursors", "or", "absorb", "products", "for", "a", "reaction", "operating", "at", "or", "beyond", "the", "specified", "cutoff", "." ]
python
valid
41.324675
nickpandolfi/Cyther
cyther/tools.py
https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/tools.py#L103-L115
def read_dict_from_file(file_path): """ Read a dictionary of strings from a file """ with open(file_path) as file: lines = file.read().splitlines() obj = {} for line in lines: key, value = line.split(':', maxsplit=1) obj[key] = eval(value) return obj
[ "def", "read_dict_from_file", "(", "file_path", ")", ":", "with", "open", "(", "file_path", ")", "as", "file", ":", "lines", "=", "file", ".", "read", "(", ")", ".", "splitlines", "(", ")", "obj", "=", "{", "}", "for", "line", "in", "lines", ":", "...
Read a dictionary of strings from a file
[ "Read", "a", "dictionary", "of", "strings", "from", "a", "file" ]
python
train
22.461538
gccxml/pygccxml
pygccxml/declarations/type_traits.py
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L26-L42
def __remove_alias(type_): """ Implementation detail. Args: type_ (type_t): type Returns: type_t: the type associated to the inputted type """ if isinstance(type_, cpptypes.declarated_t) and \ isinstance(type_.declaration, typedef.typedef_t): return __remove...
[ "def", "__remove_alias", "(", "type_", ")", ":", "if", "isinstance", "(", "type_", ",", "cpptypes", ".", "declarated_t", ")", "and", "isinstance", "(", "type_", ".", "declaration", ",", "typedef", ".", "typedef_t", ")", ":", "return", "__remove_alias", "(", ...
Implementation detail. Args: type_ (type_t): type Returns: type_t: the type associated to the inputted type
[ "Implementation", "detail", "." ]
python
train
27.764706
dominicrodger/django-tinycontent
tinycontent/utils/importer.py
https://github.com/dominicrodger/django-tinycontent/blob/2ecfce0bcc2849b97eedb8b21f33bfc8ff7b1659/tinycontent/utils/importer.py#L5-L19
def _imported_symbol(import_path): """Resolve a dotted path into a symbol, and return that. For example... >>> _imported_symbol('django.db.models.Model') <class 'django.db.models.base.Model'> Raise ImportError if there's no such module, AttributeError if no such symbol. """ module_na...
[ "def", "_imported_symbol", "(", "import_path", ")", ":", "module_name", ",", "symbol_name", "=", "import_path", ".", "rsplit", "(", "'.'", ",", "1", ")", "module", "=", "import_module", "(", "module_name", ")", "return", "getattr", "(", "module", ",", "symbo...
Resolve a dotted path into a symbol, and return that. For example... >>> _imported_symbol('django.db.models.Model') <class 'django.db.models.base.Model'> Raise ImportError if there's no such module, AttributeError if no such symbol.
[ "Resolve", "a", "dotted", "path", "into", "a", "symbol", "and", "return", "that", "." ]
python
train
28.666667
mangalam-research/selenic
selenic/builder.py
https://github.com/mangalam-research/selenic/blob/2284c68e15fa3d34b88aa2eec1a2e8ecd37f44ad/selenic/builder.py#L260-L295
def chromedriver_element_center_patch(): """ Patch move_to_element on ActionChains to work around a bug present in Chromedriver 2.14 to 2.20. Calling this function multiple times in the same process will install the patch once, and just once. """ patch_name = "_selenic_chromedriver_element...
[ "def", "chromedriver_element_center_patch", "(", ")", ":", "patch_name", "=", "\"_selenic_chromedriver_element_center_patched\"", "if", "getattr", "(", "ActionChains", ",", "patch_name", ",", "None", ")", ":", "return", "# We've patched ActionChains already!!", "# This is the...
Patch move_to_element on ActionChains to work around a bug present in Chromedriver 2.14 to 2.20. Calling this function multiple times in the same process will install the patch once, and just once.
[ "Patch", "move_to_element", "on", "ActionChains", "to", "work", "around", "a", "bug", "present", "in", "Chromedriver", "2", ".", "14", "to", "2", ".", "20", "." ]
python
train
34.222222
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/bgp.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/bgp.py#L539-L574
def _redistribute_builder(self, afi='ipv4', source=None): """Build BGP redistribute method. Do not use this method directly. You probably want ``redistribute``. Args: source (str): Source for redistributing. (connected) afi (str): Address family to configure. (ipv4, ip...
[ "def", "_redistribute_builder", "(", "self", ",", "afi", "=", "'ipv4'", ",", "source", "=", "None", ")", ":", "if", "source", "==", "'connected'", ":", "return", "getattr", "(", "self", ".", "_rbridge", ",", "'rbridge_id_router_router_bgp_address_family_{0}_'", ...
Build BGP redistribute method. Do not use this method directly. You probably want ``redistribute``. Args: source (str): Source for redistributing. (connected) afi (str): Address family to configure. (ipv4, ipv6) Returns: Method to redistribute desired sour...
[ "Build", "BGP", "redistribute", "method", "." ]
python
train
40.527778
ojengwa/accounting
accounting/accounting.py
https://github.com/ojengwa/accounting/blob/6343cf373a5c57941e407a92c101ac4bc45382e3/accounting/accounting.py#L225-L273
def as_money(self, number, **options): """Format a number into currency. Usage: accounting.formatMoney(number, symbol, precision, thousandsSep, decimalSep, format) defaults: (0, "$", 2, ",", ".", "%s%v") Localise by overriding the symbol, precision,...
[ "def", "as_money", "(", "self", ",", "number", ",", "*", "*", "options", ")", ":", "# Resursively format arrays", "if", "isinstance", "(", "number", ",", "list", ")", ":", "return", "map", "(", "lambda", "val", ":", "self", ".", "as_money", "(", "val", ...
Format a number into currency. Usage: accounting.formatMoney(number, symbol, precision, thousandsSep, decimalSep, format) defaults: (0, "$", 2, ",", ".", "%s%v") Localise by overriding the symbol, precision, thousand / decimal separators and format ...
[ "Format", "a", "number", "into", "currency", "." ]
python
test
37.693878
saltstack/salt
salt/modules/vsphere.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L8127-L8194
def _apply_serial_port(serial_device_spec, key, operation='add'): ''' Returns a vim.vm.device.VirtualSerialPort representing a serial port component serial_device_spec Serial device properties key Unique key of the device operation Add or edit the given device .. ...
[ "def", "_apply_serial_port", "(", "serial_device_spec", ",", "key", ",", "operation", "=", "'add'", ")", ":", "log", ".", "trace", "(", "'Creating serial port adapter=%s type=%s connectable=%s yield=%s'", ",", "serial_device_spec", "[", "'adapter'", "]", ",", "serial_de...
Returns a vim.vm.device.VirtualSerialPort representing a serial port component serial_device_spec Serial device properties key Unique key of the device operation Add or edit the given device .. code-block:: bash serial_ports: adapter: 'Serial port 1' ...
[ "Returns", "a", "vim", ".", "vm", ".", "device", ".", "VirtualSerialPort", "representing", "a", "serial", "port", "component" ]
python
train
41.691176
pjuren/pyokit
src/pyokit/io/repeatmaskerAlignments.py
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/io/repeatmaskerAlignments.py#L102-L137
def _get_repeat_masker_header(pairwise_alignment): """generate header string of repeatmasker formated repr of self.""" res = "" res += str(pairwise_alignment.meta[ALIG_SCORE_KEY]) + " " res += "{:.2f}".format(pairwise_alignment.meta[PCENT_SUBS_KEY]) + " " res += "{:.2f}".format(pairwise_alignment.meta[PCENT_S...
[ "def", "_get_repeat_masker_header", "(", "pairwise_alignment", ")", ":", "res", "=", "\"\"", "res", "+=", "str", "(", "pairwise_alignment", ".", "meta", "[", "ALIG_SCORE_KEY", "]", ")", "+", "\" \"", "res", "+=", "\"{:.2f}\"", ".", "format", "(", "pairwise_ali...
generate header string of repeatmasker formated repr of self.
[ "generate", "header", "string", "of", "repeatmasker", "formated", "repr", "of", "self", "." ]
python
train
54.027778
cokelaer/spectrum
src/spectrum/window.py
https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/window.py#L1304-L1326
def window_cauchy(N, alpha=3): r"""Cauchy tapering window :param int N: window length :param float alpha: parameter of the poisson window .. math:: w(n) = \frac{1}{1+\left(\frac{\alpha*n}{N/2}\right)**2} .. plot:: :width: 80% :include-source: from spectrum import window_v...
[ "def", "window_cauchy", "(", "N", ",", "alpha", "=", "3", ")", ":", "n", "=", "linspace", "(", "-", "N", "/", "2.", ",", "(", "N", ")", "/", "2.", ",", "N", ")", "w", "=", "1.", "/", "(", "1.", "+", "(", "alpha", "*", "n", "/", "(", "N"...
r"""Cauchy tapering window :param int N: window length :param float alpha: parameter of the poisson window .. math:: w(n) = \frac{1}{1+\left(\frac{\alpha*n}{N/2}\right)**2} .. plot:: :width: 80% :include-source: from spectrum import window_visu window_visu(64, 'cauchy...
[ "r", "Cauchy", "tapering", "window" ]
python
valid
25.478261
TylerTemp/docpie
docpie/__init__.py
https://github.com/TylerTemp/docpie/blob/e658454b81b6c79a020d499f12ad73496392c09a/docpie/__init__.py#L34-L133
def docpie(doc, argv=None, help=True, version=None, stdopt=True, attachopt=True, attachvalue=True, helpstyle='python', auto2dashes=True, name=None, case_sensitive=False, optionsfirst=False, appearedonly=False, namedoptions=False, extra=None): """ Parse `arg...
[ "def", "docpie", "(", "doc", ",", "argv", "=", "None", ",", "help", "=", "True", ",", "version", "=", "None", ",", "stdopt", "=", "True", ",", "attachopt", "=", "True", ",", "attachvalue", "=", "True", ",", "helpstyle", "=", "'python'", ",", "auto2da...
Parse `argv` based on command-line interface described in `doc`. `docpie` creates your command-line interface based on its description that you pass as `doc`. Such description can contain --options, <positional-argument>, commands, which could be [optional], (required), (mutually | exclusive) or repeat...
[ "Parse", "argv", "based", "on", "command", "-", "line", "interface", "described", "in", "doc", "." ]
python
train
36.32
scott-griffiths/bitstring
bitstring.py
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2501-L2538
def rfind(self, bs, start=None, end=None, bytealigned=None): """Find final occurrence of substring bs. Returns a single item tuple with the bit position if found, or an empty tuple if not found. The bit position (pos property) will also be set to the start of the substring if it is foun...
[ "def", "rfind", "(", "self", ",", "bs", ",", "start", "=", "None", ",", "end", "=", "None", ",", "bytealigned", "=", "None", ")", ":", "bs", "=", "Bits", "(", "bs", ")", "start", ",", "end", "=", "self", ".", "_validate_slice", "(", "start", ",",...
Find final occurrence of substring bs. Returns a single item tuple with the bit position if found, or an empty tuple if not found. The bit position (pos property) will also be set to the start of the substring if it is found. bs -- The bitstring to find. start -- The bit positi...
[ "Find", "final", "occurrence", "of", "substring", "bs", "." ]
python
train
41.368421
streamlink/streamlink
src/streamlink/plugin/api/validate.py
https://github.com/streamlink/streamlink/blob/c8ed1daff14ac03195870238b9b900c1109dd5c1/src/streamlink/plugin/api/validate.py#L244-L271
def url(**attributes): """Parses an URL and validates its attributes.""" def check_url(value): validate(text, value) parsed = urlparse(value) if not parsed.netloc: raise ValueError("'{0}' is not a valid URL".format(value)) for name, schema in attributes.items(): ...
[ "def", "url", "(", "*", "*", "attributes", ")", ":", "def", "check_url", "(", "value", ")", ":", "validate", "(", "text", ",", "value", ")", "parsed", "=", "urlparse", "(", "value", ")", "if", "not", "parsed", ".", "netloc", ":", "raise", "ValueError...
Parses an URL and validates its attributes.
[ "Parses", "an", "URL", "and", "validates", "its", "attributes", "." ]
python
test
32.607143
Microsoft/nni
examples/trials/weight_sharing/ga_squad/train_model.py
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/train_model.py#L234-L263
def build_char_states(self, char_embed, is_training, reuse, char_ids, char_lengths): """Build char embedding network for the QA model.""" max_char_length = self.cfg.max_char_length inputs = dropout(tf.nn.embedding_lookup(char_embed, char_ids), self.cfg.dropout, is_train...
[ "def", "build_char_states", "(", "self", ",", "char_embed", ",", "is_training", ",", "reuse", ",", "char_ids", ",", "char_lengths", ")", ":", "max_char_length", "=", "self", ".", "cfg", ".", "max_char_length", "inputs", "=", "dropout", "(", "tf", ".", "nn", ...
Build char embedding network for the QA model.
[ "Build", "char", "embedding", "network", "for", "the", "QA", "model", "." ]
python
train
46.766667
alixnovosi/botskeleton
botskeleton/botskeleton.py
https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/botskeleton.py#L510-L554
def _repair(record: Dict[str, Any]) -> Dict[str, Any]: """Repair a corrupted IterationRecord with a specific known issue.""" output_records = record.get("output_records") if record.get("_type", None) == "IterationRecord" and output_records is not None: birdsite_record = output_records.get("birdsite"...
[ "def", "_repair", "(", "record", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "output_records", "=", "record", ".", "get", "(", "\"output_records\"", ")", "if", "record", ".", "get", "(", "\"_type\"",...
Repair a corrupted IterationRecord with a specific known issue.
[ "Repair", "a", "corrupted", "IterationRecord", "with", "a", "specific", "known", "issue", "." ]
python
train
37.488889
pytroll/satpy
satpy/scene.py
https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/scene.py#L889-L958
def load(self, wishlist, calibration=None, resolution=None, polarization=None, level=None, generate=True, unload=True, **kwargs): """Read and generate requested datasets. When the `wishlist` contains `DatasetID` objects they can either be fully-specified `DatasetID` ob...
[ "def", "load", "(", "self", ",", "wishlist", ",", "calibration", "=", "None", ",", "resolution", "=", "None", ",", "polarization", "=", "None", ",", "level", "=", "None", ",", "generate", "=", "True", ",", "unload", "=", "True", ",", "*", "*", "kwarg...
Read and generate requested datasets. When the `wishlist` contains `DatasetID` objects they can either be fully-specified `DatasetID` objects with every parameter specified or they can not provide certain parameters and the "best" parameter will be chosen. For example, if a dataset is a...
[ "Read", "and", "generate", "requested", "datasets", "." ]
python
train
54.771429
tcalmant/ipopo
pelix/ipopo/handlers/requires.py
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requires.py#L90-L120
def get_handlers(self, component_context, instance): """ Sets up service providers for the given component :param component_context: The ComponentContext bean :param instance: The component instance :return: The list of handlers associated to the given component """ ...
[ "def", "get_handlers", "(", "self", ",", "component_context", ",", "instance", ")", ":", "# Extract information from the context", "requirements", "=", "component_context", ".", "get_handler", "(", "ipopo_constants", ".", "HANDLER_REQUIRES", ")", "requires_filters", "=", ...
Sets up service providers for the given component :param component_context: The ComponentContext bean :param instance: The component instance :return: The list of handlers associated to the given component
[ "Sets", "up", "service", "providers", "for", "the", "given", "component" ]
python
train
35.258065
cthoyt/onto2nx
src/onto2nx/ontospy/core/ontospy.py
https://github.com/cthoyt/onto2nx/blob/94c86e5e187cca67534afe0260097177b66e02c8/src/onto2nx/ontospy/core/ontospy.py#L285-L350
def __extractProperties(self): """ 2015-06-04: removed sparql 1.1 queries 2015-06-03: analogous to get classes # instantiate properties making sure duplicates are pruned # but the most specific rdftype is kept # eg OWL:ObjectProperty over RDF:property """ ...
[ "def", "__extractProperties", "(", "self", ")", ":", "self", ".", "properties", "=", "[", "]", "# @todo: keep adding?", "self", ".", "annotationProperties", "=", "[", "]", "self", ".", "objectProperties", "=", "[", "]", "self", ".", "datatypeProperties", "=", ...
2015-06-04: removed sparql 1.1 queries 2015-06-03: analogous to get classes # instantiate properties making sure duplicates are pruned # but the most specific rdftype is kept # eg OWL:ObjectProperty over RDF:property
[ "2015", "-", "06", "-", "04", ":", "removed", "sparql", "1", ".", "1", "queries", "2015", "-", "06", "-", "03", ":", "analogous", "to", "get", "classes" ]
python
train
35.984848
klmitch/turnstile
turnstile/limits.py
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/limits.py#L815-L835
def decode(self, key): """ Given a bucket key, compute the parameters used to compute that key. Note: Deprecated. Use BucketKey.decode() instead. :param key: The bucket key. Note that the UUID must match the UUID of this limit; a ValueError will be raised ...
[ "def", "decode", "(", "self", ",", "key", ")", ":", "# Parse the bucket key", "key", "=", "BucketKey", ".", "decode", "(", "key", ")", "# Make sure the uuids match", "if", "key", ".", "uuid", "!=", "self", ".", "uuid", ":", "raise", "ValueError", "(", "\"%...
Given a bucket key, compute the parameters used to compute that key. Note: Deprecated. Use BucketKey.decode() instead. :param key: The bucket key. Note that the UUID must match the UUID of this limit; a ValueError will be raised if this is not the case...
[ "Given", "a", "bucket", "key", "compute", "the", "parameters", "used", "to", "compute", "that", "key", "." ]
python
train
30.285714
infant-cognition-tampere/saccademodel-py
saccademodel/utils.py
https://github.com/infant-cognition-tampere/saccademodel-py/blob/cb40c0b298fbfa17b3510e3eab78dd7fbb6fff6c/saccademodel/utils.py#L100-L106
def get_minimum(self): ''' Return (t1, t2, value) triple where the value is the minimal one. ''' return (self._min_value_t1, self._min_value_t2, self._min_value, self._min_value_data)
[ "def", "get_minimum", "(", "self", ")", ":", "return", "(", "self", ".", "_min_value_t1", ",", "self", ".", "_min_value_t2", ",", "self", ".", "_min_value", ",", "self", ".", "_min_value_data", ")" ]
Return (t1, t2, value) triple where the value is the minimal one.
[ "Return", "(", "t1", "t2", "value", ")", "triple", "where", "the", "value", "is", "the", "minimal", "one", "." ]
python
train
34.285714
Microsoft/azure-devops-python-api
azure-devops/azure/devops/v5_0/symbol/symbol_client.py
https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_0/symbol/symbol_client.py#L165-L178
def get_requests_request_name(self, request_name): """GetRequestsRequestName. [Preview API] Get a symbol request by request name. :param str request_name: :rtype: :class:`<Request> <azure.devops.v5_0.symbol.models.Request>` """ query_parameters = {} if request_nam...
[ "def", "get_requests_request_name", "(", "self", ",", "request_name", ")", ":", "query_parameters", "=", "{", "}", "if", "request_name", "is", "not", "None", ":", "query_parameters", "[", "'requestName'", "]", "=", "self", ".", "_serialize", ".", "query", "(",...
GetRequestsRequestName. [Preview API] Get a symbol request by request name. :param str request_name: :rtype: :class:`<Request> <azure.devops.v5_0.symbol.models.Request>`
[ "GetRequestsRequestName", ".", "[", "Preview", "API", "]", "Get", "a", "symbol", "request", "by", "request", "name", ".", ":", "param", "str", "request_name", ":", ":", "rtype", ":", ":", "class", ":", "<Request", ">", "<azure", ".", "devops", ".", "v5_0...
python
train
52.214286
dddomodossola/remi
remi/server.py
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/server.py#L551-L590
def do_GET(self): # check here request header to identify the type of req, if http or ws # if this is a ws req, instance a ws handler, add it to App's ws list, return if "Upgrade" in self.headers: if self.headers['Upgrade'] == 'websocket': #passing arguments to websoc...
[ "def", "do_GET", "(", "self", ")", ":", "# check here request header to identify the type of req, if http or ws", "# if this is a ws req, instance a ws handler, add it to App's ws list, return", "if", "\"Upgrade\"", "in", "self", ".", "headers", ":", "if", "self", ".", "headers",...
Handler for the GET requests.
[ "Handler", "for", "the", "GET", "requests", "." ]
python
train
48.45
jleinonen/pytmatrix
pytmatrix/psd.py
https://github.com/jleinonen/pytmatrix/blob/8803507fe5332786feab105fa74acf63e7121718/pytmatrix/psd.py#L310-L334
def get_SZ(self, psd, geometry): """ Compute the scattering matrices for the given PSD and geometries. Returns: The new amplitude (S) and phase (Z) matrices. """ if (self._S_table is None) or (self._Z_table is None): raise AttributeError( ...
[ "def", "get_SZ", "(", "self", ",", "psd", ",", "geometry", ")", ":", "if", "(", "self", ".", "_S_table", "is", "None", ")", "or", "(", "self", ".", "_Z_table", "is", "None", ")", ":", "raise", "AttributeError", "(", "\"Initialize or load the scattering tab...
Compute the scattering matrices for the given PSD and geometries. Returns: The new amplitude (S) and phase (Z) matrices.
[ "Compute", "the", "scattering", "matrices", "for", "the", "given", "PSD", "and", "geometries", "." ]
python
train
34.8
rameshg87/pyremotevbox
pyremotevbox/ZSI/wstools/WSDLTools.py
https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/wstools/WSDLTools.py#L1479-L1483
def setReturnParameter(self, name, type, namespace=None, element_type=0): """Set the return parameter description for the call info.""" parameter = ParameterInfo(name, type, namespace, element_type) self.retval = parameter return parameter
[ "def", "setReturnParameter", "(", "self", ",", "name", ",", "type", ",", "namespace", "=", "None", ",", "element_type", "=", "0", ")", ":", "parameter", "=", "ParameterInfo", "(", "name", ",", "type", ",", "namespace", ",", "element_type", ")", "self", "...
Set the return parameter description for the call info.
[ "Set", "the", "return", "parameter", "description", "for", "the", "call", "info", "." ]
python
train
53.4
delfick/aws_syncr
aws_syncr/formatter.py
https://github.com/delfick/aws_syncr/blob/8cd214b27c1eee98dfba4632cbb8bc0ae36356bd/aws_syncr/formatter.py#L50-L66
def get_string(self, key): """Get a string from all_options""" # Massive hack, lol if key.startswith("lambda."): key = "lambda.items.{0}".format(key[7:]) if key.startswith("apigateway."): key = "apigateway.items.{0}".format(key[11:]) # Make sure key is i...
[ "def", "get_string", "(", "self", ",", "key", ")", ":", "# Massive hack, lol", "if", "key", ".", "startswith", "(", "\"lambda.\"", ")", ":", "key", "=", "\"lambda.items.{0}\"", ".", "format", "(", "key", "[", "7", ":", "]", ")", "if", "key", ".", "star...
Get a string from all_options
[ "Get", "a", "string", "from", "all_options" ]
python
train
39.470588
ajenhl/tacl
tacl/corpus.py
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/corpus.py#L70-L78
def get_works(self): """Returns a list of the names of all works in the corpus. :rtype: `list` of `str` """ return [os.path.split(filepath)[1] for filepath in glob.glob(os.path.join(self._path, '*')) if os.path.isdir(filepath)]
[ "def", "get_works", "(", "self", ")", ":", "return", "[", "os", ".", "path", ".", "split", "(", "filepath", ")", "[", "1", "]", "for", "filepath", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_path", ",", "...
Returns a list of the names of all works in the corpus. :rtype: `list` of `str`
[ "Returns", "a", "list", "of", "the", "names", "of", "all", "works", "in", "the", "corpus", "." ]
python
train
31.666667
BerkeleyAutomation/visualization
visualization/visualizer3d.py
https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer3d.py#L209-L287
def points(points, T_points_world=None, color=np.array([0,1,0]), scale=0.01, n_cuts=20, subsample=None, random=False, name=None): """Scatter a point cloud in pose T_points_world. Parameters ---------- points : autolab_core.BagOfPoints or (n,3) float The point set to visualiz...
[ "def", "points", "(", "points", ",", "T_points_world", "=", "None", ",", "color", "=", "np", ".", "array", "(", "[", "0", ",", "1", ",", "0", "]", ")", ",", "scale", "=", "0.01", ",", "n_cuts", "=", "20", ",", "subsample", "=", "None", ",", "ra...
Scatter a point cloud in pose T_points_world. Parameters ---------- points : autolab_core.BagOfPoints or (n,3) float The point set to visualize. T_points_world : autolab_core.RigidTransform Pose of points, specified as a transformation from point frame to world f...
[ "Scatter", "a", "point", "cloud", "in", "pose", "T_points_world", "." ]
python
train
39.810127
projecthamster/hamster-lib
hamster_lib/helpers/time.py
https://github.com/projecthamster/hamster-lib/blob/bc34c822c239a6fa0cde3a4f90b0d00506fb5a4f/hamster_lib/helpers/time.py#L49-L82
def end_day_to_datetime(end_day, config): """ Convert a given end day to its proper datetime. This is non trivial because of variable ``day_start``. We want to make sure that even if an 'end day' is specified the actual point in time may reach into the following day. Args: end (datetim...
[ "def", "end_day_to_datetime", "(", "end_day", ",", "config", ")", ":", "day_start_time", "=", "config", "[", "'day_start'", "]", "day_end_time", "=", "get_day_end", "(", "config", ")", "if", "day_start_time", "==", "datetime", ".", "time", "(", "0", ",", "0"...
Convert a given end day to its proper datetime. This is non trivial because of variable ``day_start``. We want to make sure that even if an 'end day' is specified the actual point in time may reach into the following day. Args: end (datetime.date): Raw end date that is to be adjusted. ...
[ "Convert", "a", "given", "end", "day", "to", "its", "proper", "datetime", "." ]
python
train
36.176471
PSPC-SPAC-buyandsell/von_anchor
von_anchor/anchor/rrbuilder.py
https://github.com/PSPC-SPAC-buyandsell/von_anchor/blob/78ac1de67be42a676274f4bf71fe12f66e72f309/von_anchor/anchor/rrbuilder.py#L235-L247
def mark_in_progress(self, rr_id: str, rr_size: int) -> None: """ Prepare sentinel directory for revocation registry construction. :param rr_id: revocation registry identifier :rr_size: size of revocation registry to build """ try: makedirs(join(self._dir_tai...
[ "def", "mark_in_progress", "(", "self", ",", "rr_id", ":", "str", ",", "rr_size", ":", "int", ")", "->", "None", ":", "try", ":", "makedirs", "(", "join", "(", "self", ".", "_dir_tails_sentinel", ",", "rr_id", ")", ",", "exist_ok", "=", "False", ")", ...
Prepare sentinel directory for revocation registry construction. :param rr_id: revocation registry identifier :rr_size: size of revocation registry to build
[ "Prepare", "sentinel", "directory", "for", "revocation", "registry", "construction", "." ]
python
train
43.307692
JNPRAutomate/pyJunosManager
pyJunosManager/pyJunosManager.py
https://github.com/JNPRAutomate/pyJunosManager/blob/cfbe87bb55488f44bad0b383771a88be7b2ccf2a/pyJunosManager/pyJunosManager.py#L189-L209
def commit_config(self): """ Commits exiting configuration Example: .. code-block:: python from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper") dev.open() dev.open_config() ...
[ "def", "commit_config", "(", "self", ")", ":", "try", ":", "self", ".", "dev", ".", "rpc", ".", "commit_configuration", "(", ")", "except", "Exception", "as", "err", ":", "print", "err" ]
Commits exiting configuration Example: .. code-block:: python from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper") dev.open() dev.open_config() dev.commit_config() dev.close...
[ "Commits", "exiting", "configuration" ]
python
train
24.095238
pygobject/pgi
pgi/obj.py
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/obj.py#L68-L76
def set_property(self, name, value): """set_property(property_name: str, value: object) Set property *property_name* to *value*. """ if not hasattr(self.props, name): raise TypeError("Unknown property: %r" % name) setattr(self.props, name, value)
[ "def", "set_property", "(", "self", ",", "name", ",", "value", ")", ":", "if", "not", "hasattr", "(", "self", ".", "props", ",", "name", ")", ":", "raise", "TypeError", "(", "\"Unknown property: %r\"", "%", "name", ")", "setattr", "(", "self", ".", "pr...
set_property(property_name: str, value: object) Set property *property_name* to *value*.
[ "set_property", "(", "property_name", ":", "str", "value", ":", "object", ")" ]
python
train
32.444444
mbakker7/timml
timml/equation.py
https://github.com/mbakker7/timml/blob/91e99ad573cb8a9ad8ac1fa041c3ca44520c2390/timml/equation.py#L83-L107
def equation(self): """Mix-in class that returns matrix rows for mscreen condition. Mscreen condition applied at each control point separately (so not like in ditch). Returns matrix part (nunknowns,neq) Returns rhs part (nunknowns) """ mat = np.zeros((self.nunknowns, self...
[ "def", "equation", "(", "self", ")", ":", "mat", "=", "np", ".", "zeros", "(", "(", "self", ".", "nunknowns", ",", "self", ".", "model", ".", "neq", ")", ")", "rhs", "=", "np", ".", "zeros", "(", "self", ".", "nunknowns", ")", "# Needs to be initia...
Mix-in class that returns matrix rows for mscreen condition. Mscreen condition applied at each control point separately (so not like in ditch). Returns matrix part (nunknowns,neq) Returns rhs part (nunknowns)
[ "Mix", "-", "in", "class", "that", "returns", "matrix", "rows", "for", "mscreen", "condition", ".", "Mscreen", "condition", "applied", "at", "each", "control", "point", "separately", "(", "so", "not", "like", "in", "ditch", ")", ".", "Returns", "matrix", "...
python
train
50.12
eventable/vobject
docs/build/lib/vobject/icalendar.py
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/docs/build/lib/vobject/icalendar.py#L1332-L1349
def transformToNative(obj): """ Turn obj.value into a datetime.timedelta. """ if obj.isNative: return obj obj.isNative = True obj.value=obj.value if obj.value == '': return obj else: deltalist=stringToDurations(obj.value...
[ "def", "transformToNative", "(", "obj", ")", ":", "if", "obj", ".", "isNative", ":", "return", "obj", "obj", ".", "isNative", "=", "True", "obj", ".", "value", "=", "obj", ".", "value", "if", "obj", ".", "value", "==", "''", ":", "return", "obj", "...
Turn obj.value into a datetime.timedelta.
[ "Turn", "obj", ".", "value", "into", "a", "datetime", ".", "timedelta", "." ]
python
train
31.888889
rflamary/POT
ot/gpu/utils.py
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/gpu/utils.py#L16-L54
def euclidean_distances(a, b, squared=False, to_numpy=True): """ Compute the pairwise euclidean distance between matrices a and b. If the input matrix are in numpy format, they will be uploaded to the GPU first which can incur significant time overhead. Parameters ---------- a : np.ndarray...
[ "def", "euclidean_distances", "(", "a", ",", "b", ",", "squared", "=", "False", ",", "to_numpy", "=", "True", ")", ":", "a", ",", "b", "=", "to_gpu", "(", "a", ",", "b", ")", "a2", "=", "np", ".", "sum", "(", "np", ".", "square", "(", "a", ")...
Compute the pairwise euclidean distance between matrices a and b. If the input matrix are in numpy format, they will be uploaded to the GPU first which can incur significant time overhead. Parameters ---------- a : np.ndarray (n, f) first matrix b : np.ndarray (m, f) second mat...
[ "Compute", "the", "pairwise", "euclidean", "distance", "between", "matrices", "a", "and", "b", "." ]
python
train
25.25641
foremast/foremast
src/foremast/consts.py
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/consts.py#L77-L91
def extract_formats(config_handle): """Get application formats. See :class:`gogoutils.Formats` for available options. Args: config_handle (configparser.ConfigParser): Instance of configurations. Returns: dict: Formats in ``{$format_type: $format_pattern}``. """ configurations...
[ "def", "extract_formats", "(", "config_handle", ")", ":", "configurations", "=", "dict", "(", "config_handle", ")", "formats", "=", "dict", "(", "configurations", ".", "get", "(", "'formats'", ",", "{", "}", ")", ")", "return", "formats" ]
Get application formats. See :class:`gogoutils.Formats` for available options. Args: config_handle (configparser.ConfigParser): Instance of configurations. Returns: dict: Formats in ``{$format_type: $format_pattern}``.
[ "Get", "application", "formats", "." ]
python
train
26.733333
kgaughan/dbkit
dbkit.py
https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/dbkit.py#L957-L982
def make_placeholders(seq, start=1): """ Generate placeholders for the given sequence. """ if len(seq) == 0: raise ValueError('Sequence must have at least one element.') param_style = Context.current().param_style placeholders = None if isinstance(seq, dict): if param_style i...
[ "def", "make_placeholders", "(", "seq", ",", "start", "=", "1", ")", ":", "if", "len", "(", "seq", ")", "==", "0", ":", "raise", "ValueError", "(", "'Sequence must have at least one element.'", ")", "param_style", "=", "Context", ".", "current", "(", ")", ...
Generate placeholders for the given sequence.
[ "Generate", "placeholders", "for", "the", "given", "sequence", "." ]
python
train
41.615385
saltstack/salt
salt/modules/lxc.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L2607-L2629
def exists(name, path=None): ''' Returns whether the named container exists. path path to the container parent directory (default: /var/lib/lxc) .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' lxc.exists name ''' _exists = name in ls_(path...
[ "def", "exists", "(", "name", ",", "path", "=", "None", ")", ":", "_exists", "=", "name", "in", "ls_", "(", "path", "=", "path", ")", "# container may be just created but we did cached earlier the", "# lxc-ls results", "if", "not", "_exists", ":", "_exists", "="...
Returns whether the named container exists. path path to the container parent directory (default: /var/lib/lxc) .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' lxc.exists name
[ "Returns", "whether", "the", "named", "container", "exists", "." ]
python
train
21.043478
sammchardy/python-kucoin
kucoin/client.py
https://github.com/sammchardy/python-kucoin/blob/a4cacde413804784bd313f27a0ad37234888be29/kucoin/client.py#L592-L621
def get_deposit_address(self, currency): """Get deposit address for a currency https://docs.kucoin.com/#get-deposit-address :param currency: Name of currency :type currency: string .. code:: python address = client.get_deposit_address('NEO') :returns: Api...
[ "def", "get_deposit_address", "(", "self", ",", "currency", ")", ":", "data", "=", "{", "'currency'", ":", "currency", "}", "return", "self", ".", "_get", "(", "'deposit-addresses'", ",", "True", ",", "data", "=", "data", ")" ]
Get deposit address for a currency https://docs.kucoin.com/#get-deposit-address :param currency: Name of currency :type currency: string .. code:: python address = client.get_deposit_address('NEO') :returns: ApiResponse .. code:: python { ...
[ "Get", "deposit", "address", "for", "a", "currency" ]
python
train
22.6
explosion/spaCy
spacy/cli/pretrain.py
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/pretrain.py#L164-L178
def make_update(model, docs, optimizer, drop=0.0, objective="L2"): """Perform an update over a single batch of documents. docs (iterable): A batch of `Doc` objects. drop (float): The droput rate. optimizer (callable): An optimizer. RETURNS loss: A float for the loss. """ predictions, backpr...
[ "def", "make_update", "(", "model", ",", "docs", ",", "optimizer", ",", "drop", "=", "0.0", ",", "objective", "=", "\"L2\"", ")", ":", "predictions", ",", "backprop", "=", "model", ".", "begin_update", "(", "docs", ",", "drop", "=", "drop", ")", "loss"...
Perform an update over a single batch of documents. docs (iterable): A batch of `Doc` objects. drop (float): The droput rate. optimizer (callable): An optimizer. RETURNS loss: A float for the loss.
[ "Perform", "an", "update", "over", "a", "single", "batch", "of", "documents", "." ]
python
train
41.733333
Dallinger/Dallinger
dallinger/experiment_server/experiment_server.py
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/experiment_server.py#L1712-L1729
def worker_failed(): """Fail worker. Used by bots only for now.""" participant_id = request.args.get("participant_id") if not participant_id: return error_response( error_type="bad request", error_text="participantId parameter is required" ) try: _worker_failed(parti...
[ "def", "worker_failed", "(", ")", ":", "participant_id", "=", "request", ".", "args", ".", "get", "(", "\"participant_id\"", ")", "if", "not", "participant_id", ":", "return", "error_response", "(", "error_type", "=", "\"bad request\"", ",", "error_text", "=", ...
Fail worker. Used by bots only for now.
[ "Fail", "worker", ".", "Used", "by", "bots", "only", "for", "now", "." ]
python
train
30.888889
google/identity-toolkit-python-client
identitytoolkit/gitkitclient.py
https://github.com/google/identity-toolkit-python-client/blob/4cfe3013569c21576daa5d22ad21f9f4f8b30c4d/identitytoolkit/gitkitclient.py#L252-L272
def VerifyGitkitToken(self, jwt): """Verifies a Gitkit token string. Args: jwt: string, the token to be checked Returns: GitkitUser, if the token is valid. None otherwise. """ certs = self.rpc_helper.GetPublicCert() crypt.MAX_TOKEN_LIFETIME_SECS = 30 * 86400 # 30 days parsed =...
[ "def", "VerifyGitkitToken", "(", "self", ",", "jwt", ")", ":", "certs", "=", "self", ".", "rpc_helper", ".", "GetPublicCert", "(", ")", "crypt", ".", "MAX_TOKEN_LIFETIME_SECS", "=", "30", "*", "86400", "# 30 days", "parsed", "=", "None", "for", "aud", "in"...
Verifies a Gitkit token string. Args: jwt: string, the token to be checked Returns: GitkitUser, if the token is valid. None otherwise.
[ "Verifies", "a", "Gitkit", "token", "string", "." ]
python
train
31.238095
bwohlberg/sporco
sporco/admm/cbpdn.py
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/cbpdn.py#L1718-L1729
def cnst_A0(self, X, Xf=None): r"""Compute :math:`A_0 \mathbf{x}` component of ADMM problem constraint. """ # This calculation involves non-negligible computational cost # when Xf is None (i.e. the function is not being applied to # self.X). if Xf is None: ...
[ "def", "cnst_A0", "(", "self", ",", "X", ",", "Xf", "=", "None", ")", ":", "# This calculation involves non-negligible computational cost", "# when Xf is None (i.e. the function is not being applied to", "# self.X).", "if", "Xf", "is", "None", ":", "Xf", "=", "sl", ".",...
r"""Compute :math:`A_0 \mathbf{x}` component of ADMM problem constraint.
[ "r", "Compute", ":", "math", ":", "A_0", "\\", "mathbf", "{", "x", "}", "component", "of", "ADMM", "problem", "constraint", "." ]
python
train
39.666667
swift-nav/libsbp
generator/sbpg/targets/haskell.py
https://github.com/swift-nav/libsbp/blob/5a950608506b23e31b73ef7065da905b646055c1/generator/sbpg/targets/haskell.py#L73-L82
def to_global(s): """ Format a global variable name. """ if s.startswith('GPSTime'): s = 'Gps' + s[3:] if '_' in s: s = "".join([i.capitalize() for i in s.split("_")]) return s[0].lower() + s[1:]
[ "def", "to_global", "(", "s", ")", ":", "if", "s", ".", "startswith", "(", "'GPSTime'", ")", ":", "s", "=", "'Gps'", "+", "s", "[", "3", ":", "]", "if", "'_'", "in", "s", ":", "s", "=", "\"\"", ".", "join", "(", "[", "i", ".", "capitalize", ...
Format a global variable name.
[ "Format", "a", "global", "variable", "name", "." ]
python
train
20.7
samuelcolvin/pydantic
pydantic/datetime_parse.py
https://github.com/samuelcolvin/pydantic/blob/bff8a1789dfde2c38928cced6640887b53615aa3/pydantic/datetime_parse.py#L139-L180
def parse_datetime(value: Union[datetime, StrIntFloat]) -> datetime: """ Parse a datetime/int/float/string and return a datetime.datetime. This function supports time zone offsets. When the input contains one, the output uses a timezone with a fixed offset from UTC. Raise ValueError if the input i...
[ "def", "parse_datetime", "(", "value", ":", "Union", "[", "datetime", ",", "StrIntFloat", "]", ")", "->", "datetime", ":", "if", "isinstance", "(", "value", ",", "datetime", ")", ":", "return", "value", "number", "=", "get_numeric", "(", "value", ")", "i...
Parse a datetime/int/float/string and return a datetime.datetime. This function supports time zone offsets. When the input contains one, the output uses a timezone with a fixed offset from UTC. Raise ValueError if the input is well formatted but not a valid datetime. Raise ValueError if the input isn'...
[ "Parse", "a", "datetime", "/", "int", "/", "float", "/", "string", "and", "return", "a", "datetime", ".", "datetime", "." ]
python
train
32.809524
kivy/buildozer
buildozer/__init__.py
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/__init__.py#L398-L437
def check_configuration_tokens(self): '''Ensure the spec file is 'correct'. ''' self.info('Check configuration tokens') self.migrate_configuration_tokens() get = self.config.getdefault errors = [] adderror = errors.append if not get('app', 'title', ''): ...
[ "def", "check_configuration_tokens", "(", "self", ")", ":", "self", ".", "info", "(", "'Check configuration tokens'", ")", "self", ".", "migrate_configuration_tokens", "(", ")", "get", "=", "self", ".", "config", ".", "getdefault", "errors", "=", "[", "]", "ad...
Ensure the spec file is 'correct'.
[ "Ensure", "the", "spec", "file", "is", "correct", "." ]
python
train
41.975
ze-phyr-us/django-libretto
django_libretto/models.py
https://github.com/ze-phyr-us/django-libretto/blob/b19d8aa21b9579ee91e81967a44d1c40f5588b17/django_libretto/models.py#L9-L34
def extendManager(mixinClass): ''' Use as a class decorator to add extra methods to your model manager. Example usage: class Article(django.db.models.Model): published = models.DateTimeField() ... @extendManager class objects(object): def getPublished(self): return self.filter(published__lte...
[ "def", "extendManager", "(", "mixinClass", ")", ":", "class", "MixinManager", "(", "models", ".", "Manager", ",", "mixinClass", ")", ":", "class", "MixinQuerySet", "(", "models", ".", "query", ".", "QuerySet", ",", "mixinClass", ")", ":", "pass", "def", "g...
Use as a class decorator to add extra methods to your model manager. Example usage: class Article(django.db.models.Model): published = models.DateTimeField() ... @extendManager class objects(object): def getPublished(self): return self.filter(published__lte = django.utils.timezone.now()).order...
[ "Use", "as", "a", "class", "decorator", "to", "add", "extra", "methods", "to", "your", "model", "manager", ".", "Example", "usage", ":" ]
python
test
24.615385
jrxFive/python-nomad
nomad/api/deployments.py
https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/deployments.py#L59-L74
def get_deployments(self, prefix=""): """ This endpoint lists all deployments. https://www.nomadproject.io/docs/http/deployments.html optional_arguments: - prefix, (default "") Specifies a string to filter deployments on based on an index prefix. Th...
[ "def", "get_deployments", "(", "self", ",", "prefix", "=", "\"\"", ")", ":", "params", "=", "{", "\"prefix\"", ":", "prefix", "}", "return", "self", ".", "request", "(", "params", "=", "params", ",", "method", "=", "\"get\"", ")", ".", "json", "(", "...
This endpoint lists all deployments. https://www.nomadproject.io/docs/http/deployments.html optional_arguments: - prefix, (default "") Specifies a string to filter deployments on based on an index prefix. This is specified as a querystring parameter. ...
[ "This", "endpoint", "lists", "all", "deployments", "." ]
python
test
39.6875
awacha/sastool
sastool/io/twodim.py
https://github.com/awacha/sastool/blob/deaddfa3002f3f6818697e36139633b7e30427a3/sastool/io/twodim.py#L215-L231
def readbdfv1(filename, bdfext='.bdf', bhfext='.bhf'): """Read bdf file (Bessy Data Format v1) Input ----- filename: string the name of the file Output ------ the BDF structure in a dict Notes ----- This is an adaptation of the bdf_read.m macro of Sylvio Haas. """ ...
[ "def", "readbdfv1", "(", "filename", ",", "bdfext", "=", "'.bdf'", ",", "bhfext", "=", "'.bhf'", ")", ":", "return", "header", ".", "readbhfv1", "(", "filename", ",", "True", ",", "bdfext", ",", "bhfext", ")" ]
Read bdf file (Bessy Data Format v1) Input ----- filename: string the name of the file Output ------ the BDF structure in a dict Notes ----- This is an adaptation of the bdf_read.m macro of Sylvio Haas.
[ "Read", "bdf", "file", "(", "Bessy", "Data", "Format", "v1", ")" ]
python
train
21.352941
galaxyproject/pulsar
pulsar/client/staging/up.py
https://github.com/galaxyproject/pulsar/blob/9ab6683802884324652da0a9f0808c7eb59d3ab4/pulsar/client/staging/up.py#L387-L392
def rewrite_paths(self, local_path, remote_path): """ Rewrite references to `local_path` with `remote_path` in job inputs. """ self.__rewrite_command_line(local_path, remote_path) self.__rewrite_config_files(local_path, remote_path)
[ "def", "rewrite_paths", "(", "self", ",", "local_path", ",", "remote_path", ")", ":", "self", ".", "__rewrite_command_line", "(", "local_path", ",", "remote_path", ")", "self", ".", "__rewrite_config_files", "(", "local_path", ",", "remote_path", ")" ]
Rewrite references to `local_path` with `remote_path` in job inputs.
[ "Rewrite", "references", "to", "local_path", "with", "remote_path", "in", "job", "inputs", "." ]
python
train
44.666667
google/openhtf
openhtf/util/functions.py
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/functions.py#L47-L73
def call_at_most_every(seconds, count=1): """Call the decorated function at most count times every seconds seconds. The decorated function will sleep to ensure that at most count invocations occur within any 'seconds' second window. """ def decorator(func): try: call_history = getattr(func, '_call_...
[ "def", "call_at_most_every", "(", "seconds", ",", "count", "=", "1", ")", ":", "def", "decorator", "(", "func", ")", ":", "try", ":", "call_history", "=", "getattr", "(", "func", ",", "'_call_history'", ")", "except", "AttributeError", ":", "call_history", ...
Call the decorated function at most count times every seconds seconds. The decorated function will sleep to ensure that at most count invocations occur within any 'seconds' second window.
[ "Call", "the", "decorated", "function", "at", "most", "count", "times", "every", "seconds", "seconds", "." ]
python
train
42.333333
craft-ai/craft-ai-client-python
craftai/client.py
https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L205-L223
def delete_agent(self, agent_id): """Delete an agent. :param str agent_id: The id of the agent to delete. It must be an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. :return: agent deleted. :rtype: dict. """ # Raises an error when agent_id is ...
[ "def", "delete_agent", "(", "self", ",", "agent_id", ")", ":", "# Raises an error when agent_id is invalid", "self", ".", "_check_agent_id", "(", "agent_id", ")", "req_url", "=", "\"{}/agents/{}\"", ".", "format", "(", "self", ".", "_base_url", ",", "agent_id", ")...
Delete an agent. :param str agent_id: The id of the agent to delete. It must be an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. :return: agent deleted. :rtype: dict.
[ "Delete", "an", "agent", "." ]
python
train
27.894737
saltstack/salt
salt/modules/junos.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/junos.py#L1115-L1160
def file_copy(src=None, dest=None): ''' Copies the file from the local device to the junos device src The source path where the file is kept. dest The destination path on the where the file will be copied CLI Example: .. code-block:: bash salt 'device_name' junos.fil...
[ "def", "file_copy", "(", "src", "=", "None", ",", "dest", "=", "None", ")", ":", "conn", "=", "__proxy__", "[", "'junos.conn'", "]", "(", ")", "ret", "=", "{", "}", "ret", "[", "'out'", "]", "=", "True", "if", "src", "is", "None", ":", "ret", "...
Copies the file from the local device to the junos device src The source path where the file is kept. dest The destination path on the where the file will be copied CLI Example: .. code-block:: bash salt 'device_name' junos.file_copy /home/m2/info.txt info_copy.txt
[ "Copies", "the", "file", "from", "the", "local", "device", "to", "the", "junos", "device" ]
python
train
26.521739
boriel/zxbasic
zxbpp.py
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L62-L86
def init(): """ Initializes the preprocessor """ global OUTPUT global INCLUDED global CURRENT_DIR global ENABLED global INCLUDEPATH global IFDEFS global ID_TABLE global CURRENT_FILE global_.FILENAME = '(stdin)' OUTPUT = '' INCLUDED = {} CURRENT_DIR = '' pwd =...
[ "def", "init", "(", ")", ":", "global", "OUTPUT", "global", "INCLUDED", "global", "CURRENT_DIR", "global", "ENABLED", "global", "INCLUDEPATH", "global", "IFDEFS", "global", "ID_TABLE", "global", "CURRENT_FILE", "global_", ".", "FILENAME", "=", "'(stdin)'", "OUTPUT...
Initializes the preprocessor
[ "Initializes", "the", "preprocessor" ]
python
train
23.32
funilrys/PyFunceble
PyFunceble/helpers.py
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/helpers.py#L749-L771
def read(self): """ Read a given file path and return its content. :return: The content of the given file path. :rtype: str """ try: with open(self.file, "r", encoding="utf-8") as file: # We open and read a file. # We get the...
[ "def", "read", "(", "self", ")", ":", "try", ":", "with", "open", "(", "self", ".", "file", ",", "\"r\"", ",", "encoding", "=", "\"utf-8\"", ")", "as", "file", ":", "# We open and read a file.", "# We get the file content.", "funilrys", "=", "file", ".", "...
Read a given file path and return its content. :return: The content of the given file path. :rtype: str
[ "Read", "a", "given", "file", "path", "and", "return", "its", "content", "." ]
python
test
27.913043
DataBiosphere/dsub
dsub/lib/dsub_util.py
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/dsub_util.py#L158-L182
def _load_file_from_gcs(gcs_file_path, credentials=None): """Load context from a text file in gcs. Args: gcs_file_path: The target file path; should have the 'gs://' prefix. credentials: Optional credential to be used to load the file from gcs. Returns: The content of the text file as a string. ""...
[ "def", "_load_file_from_gcs", "(", "gcs_file_path", ",", "credentials", "=", "None", ")", ":", "gcs_service", "=", "_get_storage_service", "(", "credentials", ")", "bucket_name", ",", "object_name", "=", "gcs_file_path", "[", "len", "(", "'gs://'", ")", ":", "]"...
Load context from a text file in gcs. Args: gcs_file_path: The target file path; should have the 'gs://' prefix. credentials: Optional credential to be used to load the file from gcs. Returns: The content of the text file as a string.
[ "Load", "context", "from", "a", "text", "file", "in", "gcs", "." ]
python
valid
34.32
jreinhardt/constraining-order
src/constrainingorder/solver.py
https://github.com/jreinhardt/constraining-order/blob/04d00e4cad0fa9bedf15f2e89b8fd667c0495edc/src/constrainingorder/solver.py#L90-L118
def _binary(space,const,name1,name2): """ reduce the domain of variable name1 to be two-consistent (arc-consistent) with this constraint, i.e. remove those values for the variable name1, for which no values for name2 exist such that this pair is consistent with the constraint returns True if th...
[ "def", "_binary", "(", "space", ",", "const", ",", "name1", ",", "name2", ")", ":", "if", "not", "(", "name1", "in", "const", ".", "vnames", "and", "name2", "in", "const", ".", "vnames", ")", ":", "return", "False", "remove", "=", "set", "(", "[", ...
reduce the domain of variable name1 to be two-consistent (arc-consistent) with this constraint, i.e. remove those values for the variable name1, for which no values for name2 exist such that this pair is consistent with the constraint returns True if the domain of name1 was modified
[ "reduce", "the", "domain", "of", "variable", "name1", "to", "be", "two", "-", "consistent", "(", "arc", "-", "consistent", ")", "with", "this", "constraint", "i", ".", "e", ".", "remove", "those", "values", "for", "the", "variable", "name1", "for", "whic...
python
train
33.172414
SheffieldML/GPy
GPy/likelihoods/weibull.py
https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/likelihoods/weibull.py#L313-L322
def samples(self, gp, Y_metadata=None): """ Returns a set of samples of observations conditioned on a given value of latent variable f. :param gp: latent variable """ orig_shape = gp.shape gp = gp.flatten() weibull_samples = np.array([sp.stats.weibull_min.rvs(sel...
[ "def", "samples", "(", "self", ",", "gp", ",", "Y_metadata", "=", "None", ")", ":", "orig_shape", "=", "gp", ".", "shape", "gp", "=", "gp", ".", "flatten", "(", ")", "weibull_samples", "=", "np", ".", "array", "(", "[", "sp", ".", "stats", ".", "...
Returns a set of samples of observations conditioned on a given value of latent variable f. :param gp: latent variable
[ "Returns", "a", "set", "of", "samples", "of", "observations", "conditioned", "on", "a", "given", "value", "of", "latent", "variable", "f", "." ]
python
train
41.7
marten-de-vries/Flask-WebSub
flask_websub/publisher.py
https://github.com/marten-de-vries/Flask-WebSub/blob/422d5b597245554c47e881483f99cae7c57a81ba/flask_websub/publisher.py#L15-L27
def init_publisher(app): """Calling this with your flask app as argument is required for the publisher decorator to work. """ @app.context_processor def inject_links(): return { 'websub_self_url': stack.top.websub_self_url, 'websub_hub_url': stack.top.websub_hub_url,...
[ "def", "init_publisher", "(", "app", ")", ":", "@", "app", ".", "context_processor", "def", "inject_links", "(", ")", ":", "return", "{", "'websub_self_url'", ":", "stack", ".", "top", ".", "websub_self_url", ",", "'websub_hub_url'", ":", "stack", ".", "top"...
Calling this with your flask app as argument is required for the publisher decorator to work.
[ "Calling", "this", "with", "your", "flask", "app", "as", "argument", "is", "required", "for", "the", "publisher", "decorator", "to", "work", "." ]
python
train
33.538462
keleshev/schema
schema.py
https://github.com/keleshev/schema/blob/4a0bf6f509e6b69956a8f2fd4e1c3873fc419be8/schema.py#L197-L211
def validate(self, data): """ Validated data using defined regex. :param data: data to be validated :return: return validated data. """ e = self._error try: if self._pattern.search(data): return data else: r...
[ "def", "validate", "(", "self", ",", "data", ")", ":", "e", "=", "self", ".", "_error", "try", ":", "if", "self", ".", "_pattern", ".", "search", "(", "data", ")", ":", "return", "data", "else", ":", "raise", "SchemaError", "(", "\"%r does not match %r...
Validated data using defined regex. :param data: data to be validated :return: return validated data.
[ "Validated", "data", "using", "defined", "regex", ".", ":", "param", "data", ":", "data", "to", "be", "validated", ":", "return", ":", "return", "validated", "data", "." ]
python
train
30.733333
soimort/you-get
src/you_get/extractors/sina.py
https://github.com/soimort/you-get/blob/b746ac01c9f39de94cac2d56f665285b0523b974/src/you_get/extractors/sina.py#L54-L64
def sina_download_by_vkey(vkey, title=None, output_dir='.', merge=True, info_only=False): """Downloads a Sina video by its unique vkey. http://video.sina.com/ """ url = 'http://video.sina.com/v/flvideo/%s_0.flv' % vkey type, ext, size = url_info(url) print_info(site_info, title, 'flv', size) ...
[ "def", "sina_download_by_vkey", "(", "vkey", ",", "title", "=", "None", ",", "output_dir", "=", "'.'", ",", "merge", "=", "True", ",", "info_only", "=", "False", ")", ":", "url", "=", "'http://video.sina.com/v/flvideo/%s_0.flv'", "%", "vkey", "type", ",", "e...
Downloads a Sina video by its unique vkey. http://video.sina.com/
[ "Downloads", "a", "Sina", "video", "by", "its", "unique", "vkey", ".", "http", ":", "//", "video", ".", "sina", ".", "com", "/" ]
python
test
38.090909
globality-corp/microcosm-flask
microcosm_flask/fields/uri_field.py
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/fields/uri_field.py#L25-L36
def normalize_uri_result(uri): """ Normalize a URI (And return a URIResult) """ ref = uri_reference(uri).normalize() return ref._replace( authority=normalize_uri_authority(ref), query=normalize_uri_query(ref), path=normalize_uri_path(ref), )
[ "def", "normalize_uri_result", "(", "uri", ")", ":", "ref", "=", "uri_reference", "(", "uri", ")", ".", "normalize", "(", ")", "return", "ref", ".", "_replace", "(", "authority", "=", "normalize_uri_authority", "(", "ref", ")", ",", "query", "=", "normaliz...
Normalize a URI (And return a URIResult)
[ "Normalize", "a", "URI", "(", "And", "return", "a", "URIResult", ")" ]
python
train
23.333333
truemped/tornadotools
tornadotools/mongrel2/handler.py
https://github.com/truemped/tornadotools/blob/d22632b83810afc353fa886fbc9e265bee78653f/tornadotools/mongrel2/handler.py#L81-L88
def _recv_callback(self, msg): """ Method is called when there is a message coming from a Mongrel2 server. This message should be a valid Request String. """ m2req = MongrelRequest.parse(msg[0]) MongrelConnection(m2req, self._sending_stream, self.request_callback, ...
[ "def", "_recv_callback", "(", "self", ",", "msg", ")", ":", "m2req", "=", "MongrelRequest", ".", "parse", "(", "msg", "[", "0", "]", ")", "MongrelConnection", "(", "m2req", ",", "self", ".", "_sending_stream", ",", "self", ".", "request_callback", ",", "...
Method is called when there is a message coming from a Mongrel2 server. This message should be a valid Request String.
[ "Method", "is", "called", "when", "there", "is", "a", "message", "coming", "from", "a", "Mongrel2", "server", ".", "This", "message", "should", "be", "a", "valid", "Request", "String", "." ]
python
train
46.875
dwavesystems/dwave-system
dwave/system/cache/database_manager.py
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/system/cache/database_manager.py#L101-L114
def iter_chain(cur): """Iterate over all of the chains in the database. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. Yields: list: The chain. """ select = "SELECT nodes FROM chain" for node...
[ "def", "iter_chain", "(", "cur", ")", ":", "select", "=", "\"SELECT nodes FROM chain\"", "for", "nodes", ",", "in", "cur", ".", "execute", "(", "select", ")", ":", "yield", "json", ".", "loads", "(", "nodes", ")" ]
Iterate over all of the chains in the database. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. Yields: list: The chain.
[ "Iterate", "over", "all", "of", "the", "chains", "in", "the", "database", "." ]
python
train
26.071429
inasafe/inasafe
safe/report/expressions/map_report.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/expressions/map_report.py#L157-L175
def distance_to_nearest_place(feature, parent): """If the impact layer has a distance field, it will return the distance to the nearest place in metres. e.g. distance_to_nearest_place() -> 1234 """ _ = feature, parent # NOQA layer = exposure_summary_layer() if not layer: return No...
[ "def", "distance_to_nearest_place", "(", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "layer", "=", "exposure_summary_layer", "(", ")", "if", "not", "layer", ":", "return", "None", "index", "=", "layer", ".", "fields", ...
If the impact layer has a distance field, it will return the distance to the nearest place in metres. e.g. distance_to_nearest_place() -> 1234
[ "If", "the", "impact", "layer", "has", "a", "distance", "field", "it", "will", "return", "the", "distance", "to", "the", "nearest", "place", "in", "metres", "." ]
python
train
25.684211
sphinx-gallery/sphinx-gallery
sphinx_gallery/scrapers.py
https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/scrapers.py#L29-L50
def _import_matplotlib(): """Import matplotlib safely.""" # make sure that the Agg backend is set before importing any # matplotlib import matplotlib matplotlib.use('agg') matplotlib_backend = matplotlib.get_backend().lower() if matplotlib_backend != 'agg': raise ValueError( ...
[ "def", "_import_matplotlib", "(", ")", ":", "# make sure that the Agg backend is set before importing any", "# matplotlib", "import", "matplotlib", "matplotlib", ".", "use", "(", "'agg'", ")", "matplotlib_backend", "=", "matplotlib", ".", "get_backend", "(", ")", ".", "...
Import matplotlib safely.
[ "Import", "matplotlib", "safely", "." ]
python
train
42.227273
Tinche/cattrs
src/cattr/converters.py
https://github.com/Tinche/cattrs/blob/481bc9bdb69b2190d699b54f331c8c5c075506d5/src/cattr/converters.py#L330-L339
def _structure_set(self, obj, cl): """Convert an iterable into a potentially generic set.""" if is_bare(cl) or cl.__args__[0] is Any: return set(obj) else: elem_type = cl.__args__[0] return { self._structure_func.dispatch(elem_type)(e, elem_typ...
[ "def", "_structure_set", "(", "self", ",", "obj", ",", "cl", ")", ":", "if", "is_bare", "(", "cl", ")", "or", "cl", ".", "__args__", "[", "0", "]", "is", "Any", ":", "return", "set", "(", "obj", ")", "else", ":", "elem_type", "=", "cl", ".", "_...
Convert an iterable into a potentially generic set.
[ "Convert", "an", "iterable", "into", "a", "potentially", "generic", "set", "." ]
python
train
35.6
python-diamond/Diamond
src/diamond/handler/cloudwatch.py
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/cloudwatch.py#L226-L265
def send_metrics_to_cloudwatch(self, rule, metric, dimensions): """ Send metrics to CloudWatch for the given dimensions """ timestamp = datetime.datetime.utcfromtimestamp(metric.timestamp) self.log.debug( "CloudWatch: Attempting to publish metric: %s to %s " ...
[ "def", "send_metrics_to_cloudwatch", "(", "self", ",", "rule", ",", "metric", ",", "dimensions", ")", ":", "timestamp", "=", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "metric", ".", "timestamp", ")", "self", ".", "log", ".", "debug", "(", ...
Send metrics to CloudWatch for the given dimensions
[ "Send", "metrics", "to", "CloudWatch", "for", "the", "given", "dimensions" ]
python
train
34.625
dbcli/athenacli
athenacli/main.py
https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/main.py#L236-L250
def run_query(self, query, new_line=True): """Runs *query*.""" if (self.destructive_warning and confirm_destructive_query(query) is False): message = 'Wise choice. Command execution stopped.' click.echo(message) return results = self.sqlexecut...
[ "def", "run_query", "(", "self", ",", "query", ",", "new_line", "=", "True", ")", ":", "if", "(", "self", ".", "destructive_warning", "and", "confirm_destructive_query", "(", "query", ")", "is", "False", ")", ":", "message", "=", "'Wise choice. Command executi...
Runs *query*.
[ "Runs", "*", "query", "*", "." ]
python
train
38.333333
DataBiosphere/toil
src/toil/provisioners/aws/awsProvisioner.py
https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/provisioners/aws/awsProvisioner.py#L75-L88
def awsRetry(f): """ This decorator retries the wrapped function if aws throws unexpected errors errors. It should wrap any function that makes use of boto """ @wraps(f) def wrapper(*args, **kwargs): for attempt in retry(delays=truncExpBackoff(), timeout=...
[ "def", "awsRetry", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "attempt", "in", "retry", "(", "delays", "=", "truncExpBackoff", "(", ")", ",", "timeout", "=", "300...
This decorator retries the wrapped function if aws throws unexpected errors errors. It should wrap any function that makes use of boto
[ "This", "decorator", "retries", "the", "wrapped", "function", "if", "aws", "throws", "unexpected", "errors", "errors", ".", "It", "should", "wrap", "any", "function", "that", "makes", "use", "of", "boto" ]
python
train
32.642857
rocky/python3-trepan
trepan/interfaces/client.py
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/interfaces/client.py#L56-L64
def read_remote(self): '''Send a message back to the server (in contrast to the local user output channel).''' coded_line = self.inout.read_msg() if isinstance(coded_line, bytes): coded_line = coded_line.decode("utf-8") control = coded_line[0] remote_line = co...
[ "def", "read_remote", "(", "self", ")", ":", "coded_line", "=", "self", ".", "inout", ".", "read_msg", "(", ")", "if", "isinstance", "(", "coded_line", ",", "bytes", ")", ":", "coded_line", "=", "coded_line", ".", "decode", "(", "\"utf-8\"", ")", "contro...
Send a message back to the server (in contrast to the local user output channel).
[ "Send", "a", "message", "back", "to", "the", "server", "(", "in", "contrast", "to", "the", "local", "user", "output", "channel", ")", "." ]
python
test
40.222222
globality-corp/microcosm-flask
microcosm_flask/swagger/parameters/nested.py
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/swagger/parameters/nested.py#L16-L22
def parse_ref(self, field: Field) -> str: """ Parse the reference type for nested fields, if any. """ ref_name = type_name(name_for(field.schema)) return f"#/definitions/{ref_name}"
[ "def", "parse_ref", "(", "self", ",", "field", ":", "Field", ")", "->", "str", ":", "ref_name", "=", "type_name", "(", "name_for", "(", "field", ".", "schema", ")", ")", "return", "f\"#/definitions/{ref_name}\"" ]
Parse the reference type for nested fields, if any.
[ "Parse", "the", "reference", "type", "for", "nested", "fields", "if", "any", "." ]
python
train
30.857143
chriso/timeseries
timeseries/time_series.py
https://github.com/chriso/timeseries/blob/8b81e6cfd955a7cf75a421dfdb71b3f9e53be64d/timeseries/time_series.py#L101-L122
def decompose(self, frequency, window=None, periodic=False): '''Use STL to decompose the time series into seasonal, trend, and residual components.''' R = LazyImport.rpy2() if periodic: window = 'periodic' elif window is None: window = frequency ti...
[ "def", "decompose", "(", "self", ",", "frequency", ",", "window", "=", "None", ",", "periodic", "=", "False", ")", ":", "R", "=", "LazyImport", ".", "rpy2", "(", ")", "if", "periodic", ":", "window", "=", "'periodic'", "elif", "window", "is", "None", ...
Use STL to decompose the time series into seasonal, trend, and residual components.
[ "Use", "STL", "to", "decompose", "the", "time", "series", "into", "seasonal", "trend", "and", "residual", "components", "." ]
python
train
45.590909
apache/airflow
airflow/contrib/hooks/gcp_spanner_hook.py
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_spanner_hook.py#L247-L288
def update_database(self, instance_id, database_id, ddl_statements, project_id=None, operation_id=None): """ Updates DDL of a database in Cloud Spanner. :type project_id: str :param instance_id: The ID of the Cloud Spanner instance. ...
[ "def", "update_database", "(", "self", ",", "instance_id", ",", "database_id", ",", "ddl_statements", ",", "project_id", "=", "None", ",", "operation_id", "=", "None", ")", ":", "instance", "=", "self", ".", "_get_client", "(", "project_id", "=", "project_id",...
Updates DDL of a database in Cloud Spanner. :type project_id: str :param instance_id: The ID of the Cloud Spanner instance. :type instance_id: str :param database_id: The ID of the database in Cloud Spanner. :type database_id: str :param ddl_statements: The string list c...
[ "Updates", "DDL", "of", "a", "database", "in", "Cloud", "Spanner", "." ]
python
test
46.5
ska-sa/montblanc
install/cub.py
https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/install/cub.py#L97-L161
def install_cub(mb_inc_path): """ Downloads and installs cub into mb_inc_path """ cub_url = 'https://github.com/NVlabs/cub/archive/1.6.4.zip' cub_sha_hash = '0d5659200132c2576be0b3959383fa756de6105d' cub_version_str = 'Current release: v1.6.4 (12/06/2016)' cub_zip_file = 'cub.zip' cub_zip_dir = ...
[ "def", "install_cub", "(", "mb_inc_path", ")", ":", "cub_url", "=", "'https://github.com/NVlabs/cub/archive/1.6.4.zip'", "cub_sha_hash", "=", "'0d5659200132c2576be0b3959383fa756de6105d'", "cub_version_str", "=", "'Current release: v1.6.4 (12/06/2016)'", "cub_zip_file", "=", "'cub.z...
Downloads and installs cub into mb_inc_path
[ "Downloads", "and", "installs", "cub", "into", "mb_inc_path" ]
python
train
38.661538
sernst/cauldron
cauldron/session/projects/project.py
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/projects/project.py#L81-L107
def library_directories(self) -> typing.List[str]: """ The list of directories to all of the library locations """ def listify(value): return [value] if isinstance(value, str) else list(value) # If this is a project running remotely remove external library # ...
[ "def", "library_directories", "(", "self", ")", "->", "typing", ".", "List", "[", "str", "]", ":", "def", "listify", "(", "value", ")", ":", "return", "[", "value", "]", "if", "isinstance", "(", "value", ",", "str", ")", "else", "list", "(", "value",...
The list of directories to all of the library locations
[ "The", "list", "of", "directories", "to", "all", "of", "the", "library", "locations" ]
python
train
36.185185
tjcsl/cslbot
cslbot/commands/admins.py
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/admins.py#L23-L36
def cmd(send, _, args): """Returns a list of admins. V = Verified (authed to NickServ), U = Unverified. Syntax: {command} """ adminlist = [] for admin in args['db'].query(Permissions).order_by(Permissions.nick).all(): if admin.registered: adminlist.append("%s (V)" % admin.n...
[ "def", "cmd", "(", "send", ",", "_", ",", "args", ")", ":", "adminlist", "=", "[", "]", "for", "admin", "in", "args", "[", "'db'", "]", ".", "query", "(", "Permissions", ")", ".", "order_by", "(", "Permissions", ".", "nick", ")", ".", "all", "(",...
Returns a list of admins. V = Verified (authed to NickServ), U = Unverified. Syntax: {command}
[ "Returns", "a", "list", "of", "admins", "." ]
python
train
30.642857
ewels/MultiQC
multiqc/modules/deeptools/plotCoverage.py
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/deeptools/plotCoverage.py#L16-L101
def parse_plotCoverage(self): """Find plotCoverage output. Both stdout and --outRawCounts""" self.deeptools_plotCoverageStdout = dict() for f in self.find_log_files('deeptools/plotCoverageStdout'): parsed_data = self.parsePlotCoverageStdout(f) for k, v in parsed_data.item...
[ "def", "parse_plotCoverage", "(", "self", ")", ":", "self", ".", "deeptools_plotCoverageStdout", "=", "dict", "(", ")", "for", "f", "in", "self", ".", "find_log_files", "(", "'deeptools/plotCoverageStdout'", ")", ":", "parsed_data", "=", "self", ".", "parsePlotC...
Find plotCoverage output. Both stdout and --outRawCounts
[ "Find", "plotCoverage", "output", ".", "Both", "stdout", "and", "--", "outRawCounts" ]
python
train
41.453488
mitsei/dlkit
dlkit/json_/resource/sessions.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/resource/sessions.py#L1974-L1997
def unassign_agent_from_resource(self, agent_id, resource_id): """Removes an ``Agent`` from a ``Resource``. arg: agent_id (osid.id.Id): the ``Id`` of the ``Agent`` arg: resource_id (osid.id.Id): the ``Id`` of the ``Resource`` raise: NotFound - ``agent_id`` or ``resource_id`` not ...
[ "def", "unassign_agent_from_resource", "(", "self", ",", "agent_id", ",", "resource_id", ")", ":", "collection", "=", "JSONClientValidated", "(", "'resource'", ",", "collection", "=", "'Resource'", ",", "runtime", "=", "self", ".", "_runtime", ")", "resource", "...
Removes an ``Agent`` from a ``Resource``. arg: agent_id (osid.id.Id): the ``Id`` of the ``Agent`` arg: resource_id (osid.id.Id): the ``Id`` of the ``Resource`` raise: NotFound - ``agent_id`` or ``resource_id`` not found or ``agent_id`` not assigned to ``resource_id`` ...
[ "Removes", "an", "Agent", "from", "a", "Resource", "." ]
python
train
47.416667
vint21h/nagios-notification-google-calendar
notification_google_calendar.py
https://github.com/vint21h/nagios-notification-google-calendar/blob/ef2b58c939d9d55a69a54b4e6a3fd9b61bde50d4/notification_google_calendar.py#L107-L145
def parse_config(options): """ Get settings from config file. """ if os.path.exists(options.config): config = ConfigParser.ConfigParser() try: config.read(options.config) except Exception, err: if not options.quiet: sys.stderr.write("ERROR...
[ "def", "parse_config", "(", "options", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "options", ".", "config", ")", ":", "config", "=", "ConfigParser", ".", "ConfigParser", "(", ")", "try", ":", "config", ".", "read", "(", "options", ".", "c...
Get settings from config file.
[ "Get", "settings", "from", "config", "file", "." ]
python
test
40.666667
fulfilio/python-magento
magento/utils.py
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/utils.py#L29-L32
def camel_2_snake(name): "Converts CamelCase to camel_case" s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
[ "def", "camel_2_snake", "(", "name", ")", ":", "s1", "=", "re", ".", "sub", "(", "'(.)([A-Z][a-z]+)'", ",", "r'\\1_\\2'", ",", "name", ")", "return", "re", ".", "sub", "(", "'([a-z0-9])([A-Z])'", ",", "r'\\1_\\2'", ",", "s1", ")", ".", "lower", "(", ")...
Converts CamelCase to camel_case
[ "Converts", "CamelCase", "to", "camel_case" ]
python
train
43.25
basecrm/basecrm-python
basecrm/services.py
https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L777-L790
def list(self, **params): """ Retrieve all sources Returns all lead sources available to the user according to the parameters provided :calls: ``get /lead_sources`` :param dict params: (optional) Search options. :return: List of dictionaries that support attriubte-style...
[ "def", "list", "(", "self", ",", "*", "*", "params", ")", ":", "_", ",", "_", ",", "lead_sources", "=", "self", ".", "http_client", ".", "get", "(", "\"/lead_sources\"", ",", "params", "=", "params", ")", "return", "lead_sources" ]
Retrieve all sources Returns all lead sources available to the user according to the parameters provided :calls: ``get /lead_sources`` :param dict params: (optional) Search options. :return: List of dictionaries that support attriubte-style access, which represent collection of LeadSou...
[ "Retrieve", "all", "sources" ]
python
train
35.857143
Qiskit/qiskit-terra
qiskit/transpiler/passes/mapping/noise_adaptive_layout.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/noise_adaptive_layout.py#L186-L204
def _select_best_remaining_qubit(self, prog_qubit): """ Select the best remaining hardware qubit for the next program qubit. """ reliab_store = {} for hw_qubit in self.available_hw_qubits: reliab = 1 for n in self.prog_graph.neighbors(prog_qubit): ...
[ "def", "_select_best_remaining_qubit", "(", "self", ",", "prog_qubit", ")", ":", "reliab_store", "=", "{", "}", "for", "hw_qubit", "in", "self", ".", "available_hw_qubits", ":", "reliab", "=", "1", "for", "n", "in", "self", ".", "prog_graph", ".", "neighbors...
Select the best remaining hardware qubit for the next program qubit.
[ "Select", "the", "best", "remaining", "hardware", "qubit", "for", "the", "next", "program", "qubit", "." ]
python
test
40.210526
tBaxter/tango-comments
build/lib/tango_comments/forms.py
https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/forms.py#L73-L84
def initial_security_hash(self, timestamp): """ Generate the initial security hash from self.content_object and a (unix) timestamp. """ initial_security_dict = { 'content_type': str(self.target_object._meta), 'object_pk': str(self.target_object._get_pk_va...
[ "def", "initial_security_hash", "(", "self", ",", "timestamp", ")", ":", "initial_security_dict", "=", "{", "'content_type'", ":", "str", "(", "self", ".", "target_object", ".", "_meta", ")", ",", "'object_pk'", ":", "str", "(", "self", ".", "target_object", ...
Generate the initial security hash from self.content_object and a (unix) timestamp.
[ "Generate", "the", "initial", "security", "hash", "from", "self", ".", "content_object", "and", "a", "(", "unix", ")", "timestamp", "." ]
python
train
36.083333