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
aio-libs/aiomysql
aiomysql/sa/result.py
https://github.com/aio-libs/aiomysql/blob/131fb9f914739ff01a24b402d29bfd719f2d1a8b/aiomysql/sa/result.py#L427-L437
async def first(self): """Fetch the first row and then close the result set unconditionally. Returns None if no row is present. """ if self._metadata is None: self._non_result() try: return (await self.fetchone()) finally: await self.c...
[ "async", "def", "first", "(", "self", ")", ":", "if", "self", ".", "_metadata", "is", "None", ":", "self", ".", "_non_result", "(", ")", "try", ":", "return", "(", "await", "self", ".", "fetchone", "(", ")", ")", "finally", ":", "await", "self", "....
Fetch the first row and then close the result set unconditionally. Returns None if no row is present.
[ "Fetch", "the", "first", "row", "and", "then", "close", "the", "result", "set", "unconditionally", "." ]
python
train
28.727273
mosesschwartz/scrypture
scrypture/demo_scripts/Utils/json_to_csv.py
https://github.com/mosesschwartz/scrypture/blob/d51eb0c9835a5122a655078268185ce8ab9ec86a/scrypture/demo_scripts/Utils/json_to_csv.py#L28-L47
def json_to_csv(json_input): ''' Convert simple JSON to CSV Accepts a JSON string or JSON object ''' try: json_input = json.loads(json_input) except: pass # If loads fails, it's probably already parsed headers = set() for json_row in json_input: headers.update(jso...
[ "def", "json_to_csv", "(", "json_input", ")", ":", "try", ":", "json_input", "=", "json", ".", "loads", "(", "json_input", ")", "except", ":", "pass", "# If loads fails, it's probably already parsed", "headers", "=", "set", "(", ")", "for", "json_row", "in", "...
Convert simple JSON to CSV Accepts a JSON string or JSON object
[ "Convert", "simple", "JSON", "to", "CSV", "Accepts", "a", "JSON", "string", "or", "JSON", "object" ]
python
train
26.5
samluescher/django-media-tree
media_tree/admin/actions/forms.py
https://github.com/samluescher/django-media-tree/blob/3eb6345faaf57e2fbe35ca431d4d133f950f2b5f/media_tree/admin/actions/forms.py#L204-L215
def save(self): """ Deletes the selected files from storage """ storage = get_media_storage() for storage_name in self.cleaned_data['selected_files']: full_path = storage.path(storage_name) try: storage.delete(storage_name) ...
[ "def", "save", "(", "self", ")", ":", "storage", "=", "get_media_storage", "(", ")", "for", "storage_name", "in", "self", ".", "cleaned_data", "[", "'selected_files'", "]", ":", "full_path", "=", "storage", ".", "path", "(", "storage_name", ")", "try", ":"...
Deletes the selected files from storage
[ "Deletes", "the", "selected", "files", "from", "storage" ]
python
train
35.333333
Grunny/zap-cli
zapcli/commands/scripts.py
https://github.com/Grunny/zap-cli/blob/d58d4850ecfc5467badfac5e5bcc841d064bd419/zapcli/commands/scripts.py#L68-L77
def disable_script(zap_helper, script_name): """Disable a script.""" with zap_error_handler(): console.debug('Disabling script "{0}"'.format(script_name)) result = zap_helper.zap.script.disable(script_name) if result != 'OK': raise ZAPError('Error disabling script: {0}'.form...
[ "def", "disable_script", "(", "zap_helper", ",", "script_name", ")", ":", "with", "zap_error_handler", "(", ")", ":", "console", ".", "debug", "(", "'Disabling script \"{0}\"'", ".", "format", "(", "script_name", ")", ")", "result", "=", "zap_helper", ".", "za...
Disable a script.
[ "Disable", "a", "script", "." ]
python
train
38.5
lindsaymarkward/python-yeelight-sunflower
yeelightsunflower/main.py
https://github.com/lindsaymarkward/python-yeelight-sunflower/blob/4ec72d005ce307f832429620ba0bcbf6b236eead/yeelightsunflower/main.py#L215-L220
def turn_on(self): """Turn bulb on (full brightness).""" command = "C {},,,,100,\r\n".format(self._zid) response = self._hub.send_command(command) _LOGGER.debug("Turn on %s: %s", repr(command), response) return response
[ "def", "turn_on", "(", "self", ")", ":", "command", "=", "\"C {},,,,100,\\r\\n\"", ".", "format", "(", "self", ".", "_zid", ")", "response", "=", "self", ".", "_hub", ".", "send_command", "(", "command", ")", "_LOGGER", ".", "debug", "(", "\"Turn on %s: %s...
Turn bulb on (full brightness).
[ "Turn", "bulb", "on", "(", "full", "brightness", ")", "." ]
python
valid
42.333333
pvlib/pvlib-python
pvlib/pvsystem.py
https://github.com/pvlib/pvlib-python/blob/2e844a595b820b43d1170269781fa66bd0ccc8a3/pvlib/pvsystem.py#L276-L296
def ashraeiam(self, aoi): """ Determine the incidence angle modifier using ``self.module_parameters['b']``, ``aoi``, and the :py:func:`ashraeiam` function. Uses default arguments if keys not in module_parameters. Parameters ---------- aoi : numeric ...
[ "def", "ashraeiam", "(", "self", ",", "aoi", ")", ":", "kwargs", "=", "_build_kwargs", "(", "[", "'b'", "]", ",", "self", ".", "module_parameters", ")", "return", "ashraeiam", "(", "aoi", ",", "*", "*", "kwargs", ")" ]
Determine the incidence angle modifier using ``self.module_parameters['b']``, ``aoi``, and the :py:func:`ashraeiam` function. Uses default arguments if keys not in module_parameters. Parameters ---------- aoi : numeric The angle of incidence in degrees. ...
[ "Determine", "the", "incidence", "angle", "modifier", "using", "self", ".", "module_parameters", "[", "b", "]", "aoi", "and", "the", ":", "py", ":", "func", ":", "ashraeiam", "function", "." ]
python
train
26
petl-developers/petl
petl/io/text.py
https://github.com/petl-developers/petl/blob/1d33ca055f7e04e0d28a772041c9fd30c8d415d6/petl/io/text.py#L212-L221
def teetext(table, source=None, encoding=None, errors='strict', template=None, prologue=None, epilogue=None): """ Return a table that writes rows to a text file as they are iterated over. """ assert template is not None, 'template is required' return TeeTextView(table, source=source, e...
[ "def", "teetext", "(", "table", ",", "source", "=", "None", ",", "encoding", "=", "None", ",", "errors", "=", "'strict'", ",", "template", "=", "None", ",", "prologue", "=", "None", ",", "epilogue", "=", "None", ")", ":", "assert", "template", "is", ...
Return a table that writes rows to a text file as they are iterated over.
[ "Return", "a", "table", "that", "writes", "rows", "to", "a", "text", "file", "as", "they", "are", "iterated", "over", "." ]
python
train
42.3
waqasbhatti/astrobase
astrobase/plotbase.py
https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/plotbase.py#L1294-L1414
def plot_periodbase_lsp(lspinfo, outfile=None, plotdpi=100): '''Makes a plot of periodograms obtained from `periodbase` functions. This takes the output dict produced by any `astrobase.periodbase` period-finder function or a pickle filename containing such a dict and makes a periodogram plot. Par...
[ "def", "plot_periodbase_lsp", "(", "lspinfo", ",", "outfile", "=", "None", ",", "plotdpi", "=", "100", ")", ":", "# get the lspinfo from a pickle file transparently", "if", "isinstance", "(", "lspinfo", ",", "str", ")", "and", "os", ".", "path", ".", "exists", ...
Makes a plot of periodograms obtained from `periodbase` functions. This takes the output dict produced by any `astrobase.periodbase` period-finder function or a pickle filename containing such a dict and makes a periodogram plot. Parameters ---------- lspinfo : dict or str If lspinfo ...
[ "Makes", "a", "plot", "of", "periodograms", "obtained", "from", "periodbase", "functions", "." ]
python
valid
36.735537
geertj/gruvi
lib/gruvi/ssl.py
https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/ssl.py#L125-L133
def feed_eof(self): """Send a potentially "ragged" EOF. This method will raise an SSL_ERROR_EOF exception if the EOF is unexpected. """ self._incoming.write_eof() ssldata, appdata = self.feed_ssldata(b'') assert appdata == [] or appdata == [b'']
[ "def", "feed_eof", "(", "self", ")", ":", "self", ".", "_incoming", ".", "write_eof", "(", ")", "ssldata", ",", "appdata", "=", "self", ".", "feed_ssldata", "(", "b''", ")", "assert", "appdata", "==", "[", "]", "or", "appdata", "==", "[", "b''", "]" ...
Send a potentially "ragged" EOF. This method will raise an SSL_ERROR_EOF exception if the EOF is unexpected.
[ "Send", "a", "potentially", "ragged", "EOF", "." ]
python
train
32.666667
JustinLovinger/optimal
optimal/algorithms/gaoperators.py
https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/gaoperators.py#L230-L248
def uniform_crossover(parents): """Perform uniform crossover on two parent chromosomes. Randomly take genes from one parent or the other. Ex. p1 = xxxxx, p2 = yyyyy, child = xyxxy """ chromosome_length = len(parents[0]) children = [[], []] for i in range(chromosome_length): select...
[ "def", "uniform_crossover", "(", "parents", ")", ":", "chromosome_length", "=", "len", "(", "parents", "[", "0", "]", ")", "children", "=", "[", "[", "]", ",", "[", "]", "]", "for", "i", "in", "range", "(", "chromosome_length", ")", ":", "selected_pare...
Perform uniform crossover on two parent chromosomes. Randomly take genes from one parent or the other. Ex. p1 = xxxxx, p2 = yyyyy, child = xyxxy
[ "Perform", "uniform", "crossover", "on", "two", "parent", "chromosomes", "." ]
python
train
31.315789
pazz/alot
alot/db/manager.py
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/db/manager.py#L314-L381
def async_(self, cbl, fun): """ return a pair (pipe, process) so that the process writes `fun(a)` to the pipe for each element `a` in the iterable returned by the callable `cbl`. :param cbl: a function returning something iterable :type cbl: callable :param fun: ...
[ "def", "async_", "(", "self", ",", "cbl", ",", "fun", ")", ":", "# create two unix pipes to redirect the workers stdout and", "# stderr", "stdout", "=", "os", ".", "pipe", "(", ")", "stderr", "=", "os", ".", "pipe", "(", ")", "# create a multiprocessing pipe for t...
return a pair (pipe, process) so that the process writes `fun(a)` to the pipe for each element `a` in the iterable returned by the callable `cbl`. :param cbl: a function returning something iterable :type cbl: callable :param fun: an unary translation function :type fun:...
[ "return", "a", "pair", "(", "pipe", "process", ")", "so", "that", "the", "process", "writes", "fun", "(", "a", ")", "to", "the", "pipe", "for", "each", "element", "a", "in", "the", "iterable", "returned", "by", "the", "callable", "cbl", "." ]
python
train
39.147059
thiagopbueno/rddl2tf
rddl2tf/fluent.py
https://github.com/thiagopbueno/rddl2tf/blob/f7c03d3a74d2663807c1e23e04eeed2e85166b71/rddl2tf/fluent.py#L406-L415
def round(cls, x: 'TensorFluent') -> 'TensorFluent': '''Returns a TensorFluent for the round function. Args: x: The input fluent. Returns: A TensorFluent wrapping the round function. ''' return cls._unary_op(x, tf.round, tf.float32)
[ "def", "round", "(", "cls", ",", "x", ":", "'TensorFluent'", ")", "->", "'TensorFluent'", ":", "return", "cls", ".", "_unary_op", "(", "x", ",", "tf", ".", "round", ",", "tf", ".", "float32", ")" ]
Returns a TensorFluent for the round function. Args: x: The input fluent. Returns: A TensorFluent wrapping the round function.
[ "Returns", "a", "TensorFluent", "for", "the", "round", "function", "." ]
python
train
28.9
senaite/senaite.core
bika/lims/browser/dashboard/dashboard.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/dashboard/dashboard.py#L265-L324
def get_date_range(self, periodicity=PERIODICITY_WEEKLY): """Returns a date range (date from, date to) that suits with the passed in periodicity. :param periodicity: string that represents the periodicity :type periodicity: str :return: A date range :rtype: [(DateTime, D...
[ "def", "get_date_range", "(", "self", ",", "periodicity", "=", "PERIODICITY_WEEKLY", ")", ":", "today", "=", "datetime", ".", "date", ".", "today", "(", ")", "if", "periodicity", "==", "PERIODICITY_DAILY", ":", "# Daily, load last 30 days", "date_from", "=", "Da...
Returns a date range (date from, date to) that suits with the passed in periodicity. :param periodicity: string that represents the periodicity :type periodicity: str :return: A date range :rtype: [(DateTime, DateTime)]
[ "Returns", "a", "date", "range", "(", "date", "from", "date", "to", ")", "that", "suits", "with", "the", "passed", "in", "periodicity", "." ]
python
train
44.816667
jorgenschaefer/elpy
elpy/refactor.py
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L222-L226
def refactor_froms_to_imports(self, offset): """Converting imports of the form "from ..." to "import ...".""" refactor = ImportOrganizer(self.project) changes = refactor.froms_to_imports(self.resource, offset) return translate_changes(changes)
[ "def", "refactor_froms_to_imports", "(", "self", ",", "offset", ")", ":", "refactor", "=", "ImportOrganizer", "(", "self", ".", "project", ")", "changes", "=", "refactor", ".", "froms_to_imports", "(", "self", ".", "resource", ",", "offset", ")", "return", "...
Converting imports of the form "from ..." to "import ...".
[ "Converting", "imports", "of", "the", "form", "from", "...", "to", "import", "...", "." ]
python
train
54.2
raiden-network/raiden
raiden/network/transport/udp/udp_transport.py
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/udp/udp_transport.py#L240-L250
def _run(self): # pylint: disable=method-hidden """ Runnable main method, perform wait on long-running subtasks """ try: self.event_stop.wait() except gevent.GreenletExit: # killed without exception self.event_stop.set() gevent.killall(self.greenlets) # kil...
[ "def", "_run", "(", "self", ")", ":", "# pylint: disable=method-hidden", "try", ":", "self", ".", "event_stop", ".", "wait", "(", ")", "except", "gevent", ".", "GreenletExit", ":", "# killed without exception", "self", ".", "event_stop", ".", "set", "(", ")", ...
Runnable main method, perform wait on long-running subtasks
[ "Runnable", "main", "method", "perform", "wait", "on", "long", "-", "running", "subtasks" ]
python
train
43.545455
ThreatConnect-Inc/tcex
tcex/tcex_request.py
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_request.py#L136-L139
def set_basic_auth(self, username, password): """Manually set basic auth in the header when normal method does not work.""" credentials = str(b64encode('{}:{}'.format(username, password).encode('utf-8')), 'utf-8') self.authorization = 'Basic {}'.format(credentials)
[ "def", "set_basic_auth", "(", "self", ",", "username", ",", "password", ")", ":", "credentials", "=", "str", "(", "b64encode", "(", "'{}:{}'", ".", "format", "(", "username", ",", "password", ")", ".", "encode", "(", "'utf-8'", ")", ")", ",", "'utf-8'", ...
Manually set basic auth in the header when normal method does not work.
[ "Manually", "set", "basic", "auth", "in", "the", "header", "when", "normal", "method", "does", "not", "work", "." ]
python
train
71.5
MillionIntegrals/vel
vel/commands/train_command.py
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/commands/train_command.py#L27-L63
def run(self): """ Run the command with supplied configuration """ device = self.model_config.torch_device() learner = api.Learner(device, self.model_factory.instantiate(), self.max_grad_norm) optimizer = self.optimizer_factory.instantiate(learner.model) # All callbacks used fo...
[ "def", "run", "(", "self", ")", ":", "device", "=", "self", ".", "model_config", ".", "torch_device", "(", ")", "learner", "=", "api", ".", "Learner", "(", "device", ",", "self", ".", "model_factory", ".", "instantiate", "(", ")", ",", "self", ".", "...
Run the command with supplied configuration
[ "Run", "the", "command", "with", "supplied", "configuration" ]
python
train
36.216216
vpelletier/python-libusb1
usb1/__init__.py
https://github.com/vpelletier/python-libusb1/blob/740c9778e28523e4ec3543415d95f5400ae0fa24/usb1/__init__.py#L2267-L2285
def close(self): """ Close (destroy) this USB context, and all related instances. When this method has been called, methods on its instance will become mosty no-ops, returning None until explicitly re-opened (by calling open() or __enter__()). Note: "exit" is a deprecat...
[ "def", "close", "(", "self", ")", ":", "self", ".", "__auto_open", "=", "False", "self", ".", "__context_cond", ".", "acquire", "(", ")", "try", ":", "while", "self", ".", "__context_refcount", "and", "self", ".", "__context_p", ":", "self", ".", "__cont...
Close (destroy) this USB context, and all related instances. When this method has been called, methods on its instance will become mosty no-ops, returning None until explicitly re-opened (by calling open() or __enter__()). Note: "exit" is a deprecated alias of "close".
[ "Close", "(", "destroy", ")", "this", "USB", "context", "and", "all", "related", "instances", "." ]
python
train
34.368421
tensorflow/tensorboard
tensorboard/compat/tensorflow_stub/dtypes.py
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/compat/tensorflow_stub/dtypes.py#L152-L156
def is_floating(self): """Returns whether this is a (non-quantized, real) floating point type.""" return ( self.is_numpy_compatible and np.issubdtype(self.as_numpy_dtype, np.floating) ) or self.base_dtype == bfloat16
[ "def", "is_floating", "(", "self", ")", ":", "return", "(", "self", ".", "is_numpy_compatible", "and", "np", ".", "issubdtype", "(", "self", ".", "as_numpy_dtype", ",", "np", ".", "floating", ")", ")", "or", "self", ".", "base_dtype", "==", "bfloat16" ]
Returns whether this is a (non-quantized, real) floating point type.
[ "Returns", "whether", "this", "is", "a", "(", "non", "-", "quantized", "real", ")", "floating", "point", "type", "." ]
python
train
49.6
emin63/eyap
eyap/core/comments.py
https://github.com/emin63/eyap/blob/a610761973b478ca0e864e970be05ce29d5994a5/eyap/core/comments.py#L438-L456
def add_comment(self, body, allow_create=False, allow_hashes=False, summary=None): "Implement as required by parent to store comment in CSV file." if allow_hashes: raise ValueError('allow_hashes not implemented for %s yet' % ( self.__class__.__name__)) ...
[ "def", "add_comment", "(", "self", ",", "body", ",", "allow_create", "=", "False", ",", "allow_hashes", "=", "False", ",", "summary", "=", "None", ")", ":", "if", "allow_hashes", ":", "raise", "ValueError", "(", "'allow_hashes not implemented for %s yet'", "%", ...
Implement as required by parent to store comment in CSV file.
[ "Implement", "as", "required", "by", "parent", "to", "store", "comment", "in", "CSV", "file", "." ]
python
train
44.684211
tensorflow/tensor2tensor
tensor2tensor/models/transformer.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/transformer.py#L1568-L1633
def transformer_base_v1(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.norm_type = "layer" hparams.hidden_size = 512 hparams.batch_size = 4096 hparams.max_length = 256 hparams.clip_grad_norm = 0. # i.e. no gradient clipping hparams.optimizer_adam_epsilon = 1e-9 hpar...
[ "def", "transformer_base_v1", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "norm_type", "=", "\"layer\"", "hparams", ".", "hidden_size", "=", "512", "hparams", ".", "batch_size", "=", "4096", "hparams", ".", ...
Set of hyperparameters.
[ "Set", "of", "hyperparameters", "." ]
python
train
43.242424
ace0/pyrelic
pyrelic/ec.py
https://github.com/ace0/pyrelic/blob/f23d4e6586674675f72304d5938548267d6413bf/pyrelic/ec.py#L263-L267
def deserializeEc(x, compress=True): """ Deserialize binary string @x into an EC element. """ return _deserialize(x, ec1Element, compress, librelic.ec_read_bin_abi)
[ "def", "deserializeEc", "(", "x", ",", "compress", "=", "True", ")", ":", "return", "_deserialize", "(", "x", ",", "ec1Element", ",", "compress", ",", "librelic", ".", "ec_read_bin_abi", ")" ]
Deserialize binary string @x into an EC element.
[ "Deserialize", "binary", "string" ]
python
train
35.2
ratcave/ratcave
ratcave/coordinates.py
https://github.com/ratcave/ratcave/blob/e3862cdaba100ac2c6c78c08c4b09638e0c88fd4/ratcave/coordinates.py#L22-L42
def _init_coord_properties(self): """ Generates combinations of named coordinate values, mapping them to the internal array. For Example: x, xy, xyz, y, yy, zyx, etc """ def gen_getter_setter_funs(*args): indices = [self.coords[coord] for coord in args] d...
[ "def", "_init_coord_properties", "(", "self", ")", ":", "def", "gen_getter_setter_funs", "(", "*", "args", ")", ":", "indices", "=", "[", "self", ".", "coords", "[", "coord", "]", "for", "coord", "in", "args", "]", "def", "getter", "(", "self", ")", ":...
Generates combinations of named coordinate values, mapping them to the internal array. For Example: x, xy, xyz, y, yy, zyx, etc
[ "Generates", "combinations", "of", "named", "coordinate", "values", "mapping", "them", "to", "the", "internal", "array", ".", "For", "Example", ":", "x", "xy", "xyz", "y", "yy", "zyx", "etc" ]
python
train
41.428571
rigetti/pyquil
pyquil/quil.py
https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/quil.py#L213-L231
def defgate(self, name, matrix, parameters=None): """ Define a new static gate. .. note:: The matrix elements along each axis are ordered by bitstring. For two qubits the order is ``00, 01, 10, 11``, where the the bits **are ordered in reverse** by the qubit index, ...
[ "def", "defgate", "(", "self", ",", "name", ",", "matrix", ",", "parameters", "=", "None", ")", ":", "return", "self", ".", "inst", "(", "DefGate", "(", "name", ",", "matrix", ",", "parameters", ")", ")" ]
Define a new static gate. .. note:: The matrix elements along each axis are ordered by bitstring. For two qubits the order is ``00, 01, 10, 11``, where the the bits **are ordered in reverse** by the qubit index, i.e., for qubits 0 and 1 the bitstring ``01`` indicates that q...
[ "Define", "a", "new", "static", "gate", "." ]
python
train
43.631579
hollenstein/maspy
maspy/core.py
https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/core.py#L1590-L1629
def addSiInfo(self, msrunContainer, specfiles=None, attributes=['obsMz', 'rt', 'charge']): """Transfer attributes to :class:`Sii` elements from the corresponding :class`Si` in :class:`MsrunContainer.sic <MsrunContainer>`. If an attribute is not present in the ``Si`` the attribu...
[ "def", "addSiInfo", "(", "self", ",", "msrunContainer", ",", "specfiles", "=", "None", ",", "attributes", "=", "[", "'obsMz'", ",", "'rt'", ",", "'charge'", "]", ")", ":", "if", "specfiles", "is", "None", ":", "specfiles", "=", "[", "_", "for", "_", ...
Transfer attributes to :class:`Sii` elements from the corresponding :class`Si` in :class:`MsrunContainer.sic <MsrunContainer>`. If an attribute is not present in the ``Si`` the attribute value in the ``Sii``is set to ``None``. Attribute examples: 'obsMz', 'rt', 'charge', 'tic', 'iit', '...
[ "Transfer", "attributes", "to", ":", "class", ":", "Sii", "elements", "from", "the", "corresponding", ":", "class", "Si", "in", ":", "class", ":", "MsrunContainer", ".", "sic", "<MsrunContainer", ">", ".", "If", "an", "attribute", "is", "not", "present", "...
python
train
48.425
twilio/twilio-python
twilio/rest/flex_api/v1/configuration.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/flex_api/v1/configuration.py#L500-L509
def fetch(self, ui_version=values.unset): """ Fetch a ConfigurationInstance :param unicode ui_version: Pinned UI version :returns: Fetched ConfigurationInstance :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationInstance """ return self._proxy.fetch(ui_v...
[ "def", "fetch", "(", "self", ",", "ui_version", "=", "values", ".", "unset", ")", ":", "return", "self", ".", "_proxy", ".", "fetch", "(", "ui_version", "=", "ui_version", ",", ")" ]
Fetch a ConfigurationInstance :param unicode ui_version: Pinned UI version :returns: Fetched ConfigurationInstance :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationInstance
[ "Fetch", "a", "ConfigurationInstance" ]
python
train
33.1
seperman/deepdiff
deepdiff/diff.py
https://github.com/seperman/deepdiff/blob/a66879190fadc671632f154c1fcb82f5c3cef800/deepdiff/diff.py#L322-L344
def __diff_set(self, level): """Difference of sets""" t1_hashtable = self.__create_hashtable(level.t1, level) t2_hashtable = self.__create_hashtable(level.t2, level) t1_hashes = set(t1_hashtable.keys()) t2_hashes = set(t2_hashtable.keys()) hashes_added = t2_hashes - t1_...
[ "def", "__diff_set", "(", "self", ",", "level", ")", ":", "t1_hashtable", "=", "self", ".", "__create_hashtable", "(", "level", ".", "t1", ",", "level", ")", "t2_hashtable", "=", "self", ".", "__create_hashtable", "(", "level", ".", "t2", ",", "level", "...
Difference of sets
[ "Difference", "of", "sets" ]
python
train
40.869565
wal-e/wal-e
wal_e/worker/pg/wal_transfer.py
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/pg/wal_transfer.py#L130-L144
def join(self): """Wait for transfer to exit, raising errors as necessary.""" self.closed = True while self.expect > 0: val = self.wait_change.get() self.expect -= 1 if val is not None: # Wait a while for all running greenlets to exit, and ...
[ "def", "join", "(", "self", ")", ":", "self", ".", "closed", "=", "True", "while", "self", ".", "expect", ">", "0", ":", "val", "=", "self", ".", "wait_change", ".", "get", "(", ")", "self", ".", "expect", "-=", "1", "if", "val", "is", "not", "...
Wait for transfer to exit, raising errors as necessary.
[ "Wait", "for", "transfer", "to", "exit", "raising", "errors", "as", "necessary", "." ]
python
train
39.666667
gem/oq-engine
openquake/hazardlib/gsim/nga_east.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/nga_east.py#L174-L189
def cena_tau(imt, mag, params): """ Returns the inter-event standard deviation, tau, for the CENA case """ if imt.name == "PGV": C = params["PGV"] else: C = params["SA"] if mag > 6.5: return C["tau3"] elif (mag > 5.5) and (mag <= 6.5): return ITPL(mag, C["tau3...
[ "def", "cena_tau", "(", "imt", ",", "mag", ",", "params", ")", ":", "if", "imt", ".", "name", "==", "\"PGV\"", ":", "C", "=", "params", "[", "\"PGV\"", "]", "else", ":", "C", "=", "params", "[", "\"SA\"", "]", "if", "mag", ">", "6.5", ":", "ret...
Returns the inter-event standard deviation, tau, for the CENA case
[ "Returns", "the", "inter", "-", "event", "standard", "deviation", "tau", "for", "the", "CENA", "case" ]
python
train
28.75
michaelliao/sinaweibopy
snspy.py
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/snspy.py#L336-L341
def _parse_access_token(self, resp_text): ' parse access token from urlencoded str like access_token=abcxyz&expires_in=123000&other=true ' r = self._qs2dict(resp_text) access_token = r.pop('access_token') expires = time.time() + float(r.pop('expires_in')) return JsonDict(access_t...
[ "def", "_parse_access_token", "(", "self", ",", "resp_text", ")", ":", "r", "=", "self", ".", "_qs2dict", "(", "resp_text", ")", "access_token", "=", "r", ".", "pop", "(", "'access_token'", ")", "expires", "=", "time", ".", "time", "(", ")", "+", "floa...
parse access token from urlencoded str like access_token=abcxyz&expires_in=123000&other=true
[ "parse", "access", "token", "from", "urlencoded", "str", "like", "access_token", "=", "abcxyz&expires_in", "=", "123000&other", "=", "true" ]
python
train
59.166667
blockstack/pybitcoin
pybitcoin/transactions/serialize.py
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/serialize.py#L84-L130
def deserialize_transaction(tx_hex): """ Given a serialized transaction, return its inputs, outputs, locktime, and version Each input will have: * transaction_hash: string * output_index: int * [optional] sequence: int * [optional] script_sig: string ...
[ "def", "deserialize_transaction", "(", "tx_hex", ")", ":", "tx", "=", "bitcoin", ".", "deserialize", "(", "str", "(", "tx_hex", ")", ")", "inputs", "=", "tx", "[", "\"ins\"", "]", "outputs", "=", "tx", "[", "\"outs\"", "]", "ret_inputs", "=", "[", "]",...
Given a serialized transaction, return its inputs, outputs, locktime, and version Each input will have: * transaction_hash: string * output_index: int * [optional] sequence: int * [optional] script_sig: string Each output will have: * value: int ...
[ "Given", "a", "serialized", "transaction", "return", "its", "inputs", "outputs", "locktime", "and", "version" ]
python
train
23.276596
apache/spark
python/pyspark/mllib/feature.py
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/mllib/feature.py#L635-L642
def load(cls, sc, path): """ Load a model from the given path. """ jmodel = sc._jvm.org.apache.spark.mllib.feature \ .Word2VecModel.load(sc._jsc.sc(), path) model = sc._jvm.org.apache.spark.mllib.api.python.Word2VecModelWrapper(jmodel) return Word2VecModel(mod...
[ "def", "load", "(", "cls", ",", "sc", ",", "path", ")", ":", "jmodel", "=", "sc", ".", "_jvm", ".", "org", ".", "apache", ".", "spark", ".", "mllib", ".", "feature", ".", "Word2VecModel", ".", "load", "(", "sc", ".", "_jsc", ".", "sc", "(", ")"...
Load a model from the given path.
[ "Load", "a", "model", "from", "the", "given", "path", "." ]
python
train
39.5
BlueBrain/NeuroM
neurom/morphmath.py
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/morphmath.py#L244-L250
def path_distance(points): """ Compute the path distance from given set of points """ vecs = np.diff(points, axis=0)[:, :3] d2 = [np.dot(p, p) for p in vecs] return np.sum(np.sqrt(d2))
[ "def", "path_distance", "(", "points", ")", ":", "vecs", "=", "np", ".", "diff", "(", "points", ",", "axis", "=", "0", ")", "[", ":", ",", ":", "3", "]", "d2", "=", "[", "np", ".", "dot", "(", "p", ",", "p", ")", "for", "p", "in", "vecs", ...
Compute the path distance from given set of points
[ "Compute", "the", "path", "distance", "from", "given", "set", "of", "points" ]
python
train
28.857143
ssalentin/plip
plip/modules/plipxml.py
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/plipxml.py#L303-L306
def load_data(self, pdbid): """Loads and parses an XML resource and saves it as a tree if successful""" f = urlopen("http://projects.biotec.tu-dresden.de/plip-rest/pdb/%s?format=xml" % pdbid.lower()) self.doc = etree.parse(f)
[ "def", "load_data", "(", "self", ",", "pdbid", ")", ":", "f", "=", "urlopen", "(", "\"http://projects.biotec.tu-dresden.de/plip-rest/pdb/%s?format=xml\"", "%", "pdbid", ".", "lower", "(", ")", ")", "self", ".", "doc", "=", "etree", ".", "parse", "(", "f", ")...
Loads and parses an XML resource and saves it as a tree if successful
[ "Loads", "and", "parses", "an", "XML", "resource", "and", "saves", "it", "as", "a", "tree", "if", "successful" ]
python
train
61.5
gem/oq-engine
openquake/hmtk/seismicity/utils.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/utils.py#L333-L363
def sample_truncated_gaussian_vector(data, uncertainties, bounds=None): ''' Samples a Gaussian distribution subject to boundaries on the data :param numpy.ndarray data: Vector of N data values :param numpy.ndarray uncertainties: Vector of N data uncertainties :param int number_boots...
[ "def", "sample_truncated_gaussian_vector", "(", "data", ",", "uncertainties", ",", "bounds", "=", "None", ")", ":", "nvals", "=", "len", "(", "data", ")", "if", "bounds", ":", "# if bounds[0] or (fabs(bounds[0]) < PRECISION):", "if", "bounds", "[", "0", "]", "is...
Samples a Gaussian distribution subject to boundaries on the data :param numpy.ndarray data: Vector of N data values :param numpy.ndarray uncertainties: Vector of N data uncertainties :param int number_bootstraps: Number of bootstrap samples :param tuple bounds: (Lower, ...
[ "Samples", "a", "Gaussian", "distribution", "subject", "to", "boundaries", "on", "the", "data" ]
python
train
34.258065
uw-it-aca/uw-restclients-gws
uw_gws/__init__.py
https://github.com/uw-it-aca/uw-restclients-gws/blob/2aa6038d5f83027bae680e52fc38c2ec0cd192c5/uw_gws/__init__.py#L182-L195
def get_effective_member_count(self, group_id): """ Returns a count of effective members for the group identified by the passed group ID. """ self._valid_group_id(group_id) url = "{}/group/{}/effective_member?view=count".format(self.API, ...
[ "def", "get_effective_member_count", "(", "self", ",", "group_id", ")", ":", "self", ".", "_valid_group_id", "(", "group_id", ")", "url", "=", "\"{}/group/{}/effective_member?view=count\"", ".", "format", "(", "self", ".", "API", ",", "group_id", ")", "data", "=...
Returns a count of effective members for the group identified by the passed group ID.
[ "Returns", "a", "count", "of", "effective", "members", "for", "the", "group", "identified", "by", "the", "passed", "group", "ID", "." ]
python
test
32.785714
voidpp/python-tools
voidpp_tools/config_loader.py
https://github.com/voidpp/python-tools/blob/0fc7460c827b02d8914411cedddadc23ccb3cc73/voidpp_tools/config_loader.py#L108-L128
def save(self, data): """Save the config data Args: data: any serializable config data Raises: ConfigLoaderException: if the ConfigLoader.load not called, so there is no config file name, or the data is not serializable or the loader i...
[ "def", "save", "(", "self", ",", "data", ")", ":", "if", "self", ".", "__nested", ":", "raise", "ConfigLoaderException", "(", "\"Cannot save the config if the 'nested' paramter is True!\"", ")", "if", "self", ".", "__loaded_config_file", "is", "None", ":", "raise", ...
Save the config data Args: data: any serializable config data Raises: ConfigLoaderException: if the ConfigLoader.load not called, so there is no config file name, or the data is not serializable or the loader is nested
[ "Save", "the", "config", "data" ]
python
train
38.095238
frascoweb/frasco
frasco/views.py
https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/views.py#L159-L184
def as_view(url=None, methods=None, view_class=ActionsView, name=None, url_rules=None, **kwargs): """Decorator to transform a function into a view class. Be warned that this will replace the function with the view class. """ def decorator(f): if url is not None: f = expose(url, metho...
[ "def", "as_view", "(", "url", "=", "None", ",", "methods", "=", "None", ",", "view_class", "=", "ActionsView", ",", "name", "=", "None", ",", "url_rules", "=", "None", ",", "*", "*", "kwargs", ")", ":", "def", "decorator", "(", "f", ")", ":", "if",...
Decorator to transform a function into a view class. Be warned that this will replace the function with the view class.
[ "Decorator", "to", "transform", "a", "function", "into", "a", "view", "class", ".", "Be", "warned", "that", "this", "will", "replace", "the", "function", "with", "the", "view", "class", "." ]
python
train
36.807692
Infinidat/infi.clickhouse_orm
src/infi/clickhouse_orm/query.py
https://github.com/Infinidat/infi.clickhouse_orm/blob/595f2023e334e3925a5c3fbfdd6083a5992a7169/src/infi/clickhouse_orm/query.py#L554-L565
def group_by(self, *args): """ This method lets you specify the grouping fields explicitly. The `args` must be names of grouping fields or calculated fields that this queryset was created with. """ for name in args: assert name in self._fields or name in self....
[ "def", "group_by", "(", "self", ",", "*", "args", ")", ":", "for", "name", "in", "args", ":", "assert", "name", "in", "self", ".", "_fields", "or", "name", "in", "self", ".", "_calculated_fields", ",", "'Cannot group by `%s` since it is not included in the query...
This method lets you specify the grouping fields explicitly. The `args` must be names of grouping fields or calculated fields that this queryset was created with.
[ "This", "method", "lets", "you", "specify", "the", "grouping", "fields", "explicitly", ".", "The", "args", "must", "be", "names", "of", "grouping", "fields", "or", "calculated", "fields", "that", "this", "queryset", "was", "created", "with", "." ]
python
train
41.166667
roclark/sportsreference
sportsreference/ncaaf/conferences.py
https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaaf/conferences.py#L49-L71
def _get_team_abbreviation(self, team): """ Retrieve team's abbreviation. The team's abbreviation is embedded within the 'school_name' tag and requires special parsing as it is located in the middle of a URI. The abbreviation is returned for the requested school. Parame...
[ "def", "_get_team_abbreviation", "(", "self", ",", "team", ")", ":", "name_tag", "=", "team", "(", "'th[data-stat=\"school_name\"] a'", ")", "team_abbreviation", "=", "re", ".", "sub", "(", "r'.*/cfb/schools/'", ",", "''", ",", "str", "(", "name_tag", ")", ")"...
Retrieve team's abbreviation. The team's abbreviation is embedded within the 'school_name' tag and requires special parsing as it is located in the middle of a URI. The abbreviation is returned for the requested school. Parameters ---------- team : PyQuery object ...
[ "Retrieve", "team", "s", "abbreviation", "." ]
python
train
35.565217
mohamedattahri/PyXMLi
pyxmli/__init__.py
https://github.com/mohamedattahri/PyXMLi/blob/a81a245be822d62f1a20c734ca14b42c786ae81e/pyxmli/__init__.py#L969-L987
def to_xml(self): ''' Returns a DOM representation of the deliveries method @returns: Element ''' for n, v in { "method": self.method, "status": self.status, "date":self.date}.items(): if is_empty_or_none(v): raise DeliveryMethodEr...
[ "def", "to_xml", "(", "self", ")", ":", "for", "n", ",", "v", "in", "{", "\"method\"", ":", "self", ".", "method", ",", "\"status\"", ":", "self", ".", "status", ",", "\"date\"", ":", "self", ".", "date", "}", ".", "items", "(", ")", ":", "if", ...
Returns a DOM representation of the deliveries method @returns: Element
[ "Returns", "a", "DOM", "representation", "of", "the", "deliveries", "method" ]
python
train
40.947368
odlgroup/odl
odl/operator/oputils.py
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/oputils.py#L24-L121
def matrix_representation(op): """Return a matrix representation of a linear operator. Parameters ---------- op : `Operator` The linear operator of which one wants a matrix representation. If the domain or range is a `ProductSpace`, it must be a power-space. Returns ------- ...
[ "def", "matrix_representation", "(", "op", ")", ":", "if", "not", "op", ".", "is_linear", ":", "raise", "ValueError", "(", "'the operator is not linear'", ")", "if", "not", "(", "isinstance", "(", "op", ".", "domain", ",", "TensorSpace", ")", "or", "(", "i...
Return a matrix representation of a linear operator. Parameters ---------- op : `Operator` The linear operator of which one wants a matrix representation. If the domain or range is a `ProductSpace`, it must be a power-space. Returns ------- matrix : `numpy.ndarray` The ...
[ "Return", "a", "matrix", "representation", "of", "a", "linear", "operator", "." ]
python
train
33.530612
Brobin/django-seed
django_seed/toposort.py
https://github.com/Brobin/django-seed/blob/eb4c60a62d8c42dc52e2c48e7fd88a349770cfee/django_seed/toposort.py#L61-L72
def toposort_flatten(data, sort=True): """Returns a single list of dependencies. For any set returned by toposort(), those items are sorted and appended to the result (just to make the results deterministic).""" result = [] for d in toposort(data): try: result.extend((sorted if sort els...
[ "def", "toposort_flatten", "(", "data", ",", "sort", "=", "True", ")", ":", "result", "=", "[", "]", "for", "d", "in", "toposort", "(", "data", ")", ":", "try", ":", "result", ".", "extend", "(", "(", "sorted", "if", "sort", "else", "list", ")", ...
Returns a single list of dependencies. For any set returned by toposort(), those items are sorted and appended to the result (just to make the results deterministic).
[ "Returns", "a", "single", "list", "of", "dependencies", ".", "For", "any", "set", "returned", "by", "toposort", "()", "those", "items", "are", "sorted", "and", "appended", "to", "the", "result", "(", "just", "to", "make", "the", "results", "deterministic", ...
python
valid
33.666667
librosa/librosa
librosa/core/spectrum.py
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/core/spectrum.py#L1055-L1123
def perceptual_weighting(S, frequencies, **kwargs): '''Perceptual weighting of a power spectrogram: `S_p[f] = A_weighting(f) + 10*log(S[f] / ref)` Parameters ---------- S : np.ndarray [shape=(d, t)] Power spectrogram frequencies : np.ndarray [shape=(d,)] Center frequency for e...
[ "def", "perceptual_weighting", "(", "S", ",", "frequencies", ",", "*", "*", "kwargs", ")", ":", "offset", "=", "time_frequency", ".", "A_weighting", "(", "frequencies", ")", ".", "reshape", "(", "(", "-", "1", ",", "1", ")", ")", "return", "offset", "+...
Perceptual weighting of a power spectrogram: `S_p[f] = A_weighting(f) + 10*log(S[f] / ref)` Parameters ---------- S : np.ndarray [shape=(d, t)] Power spectrogram frequencies : np.ndarray [shape=(d,)] Center frequency for each row of `S` kwargs : additional keyword arguments ...
[ "Perceptual", "weighting", "of", "a", "power", "spectrogram", ":" ]
python
test
32.57971
chriso/gauged
gauged/drivers/mysql.py
https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/drivers/mysql.py#L95-L113
def replace_blocks(self, blocks): """Replace multiple blocks. blocks must be a list of tuples where each tuple consists of (namespace, offset, key, data)""" start = 0 bulk_insert = self.bulk_insert blocks_len = len(blocks) row = '(%s,%s,%s,%s,%s)' query = 'REPLACE...
[ "def", "replace_blocks", "(", "self", ",", "blocks", ")", ":", "start", "=", "0", "bulk_insert", "=", "self", ".", "bulk_insert", "blocks_len", "=", "len", "(", "blocks", ")", "row", "=", "'(%s,%s,%s,%s,%s)'", "query", "=", "'REPLACE INTO gauged_data (namespace,...
Replace multiple blocks. blocks must be a list of tuples where each tuple consists of (namespace, offset, key, data)
[ "Replace", "multiple", "blocks", ".", "blocks", "must", "be", "a", "list", "of", "tuples", "where", "each", "tuple", "consists", "of", "(", "namespace", "offset", "key", "data", ")" ]
python
train
44.315789
jordanh/neurio-python
neurio/__init__.py
https://github.com/jordanh/neurio-python/blob/3a1bcadadb3bb3ad48f2df41c039d8b828ffd9c8/neurio/__init__.py#L332-L387
def get_appliance_stats_by_location(self, location_id, start, end, granularity=None, per_page=None, page=None, min_power=None): """Get appliance usage data for a given location within a given time range. Stats are generated by fetching appliance events that match the suppli...
[ "def", "get_appliance_stats_by_location", "(", "self", ",", "location_id", ",", "start", ",", "end", ",", "granularity", "=", "None", ",", "per_page", "=", "None", ",", "page", "=", "None", ",", "min_power", "=", "None", ")", ":", "url", "=", "\"https://ap...
Get appliance usage data for a given location within a given time range. Stats are generated by fetching appliance events that match the supplied criteria and then aggregating them together based on the granularity specified with the request. Note: This endpoint uses the location's time zone when...
[ "Get", "appliance", "usage", "data", "for", "a", "given", "location", "within", "a", "given", "time", "range", ".", "Stats", "are", "generated", "by", "fetching", "appliance", "events", "that", "match", "the", "supplied", "criteria", "and", "then", "aggregatin...
python
train
40.517857
empymod/empymod
empymod/transform.py
https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/transform.py#L47-L107
def fht(zsrc, zrec, lsrc, lrec, off, factAng, depth, ab, etaH, etaV, zetaH, zetaV, xdirect, fhtarg, use_ne_eval, msrc, mrec): r"""Hankel Transform using the Digital Linear Filter method. The *Digital Linear Filter* method was introduced to geophysics by [Ghos70]_, and made popular and wide-spread b...
[ "def", "fht", "(", "zsrc", ",", "zrec", ",", "lsrc", ",", "lrec", ",", "off", ",", "factAng", ",", "depth", ",", "ab", ",", "etaH", ",", "etaV", ",", "zetaH", ",", "zetaV", ",", "xdirect", ",", "fhtarg", ",", "use_ne_eval", ",", "msrc", ",", "mre...
r"""Hankel Transform using the Digital Linear Filter method. The *Digital Linear Filter* method was introduced to geophysics by [Ghos70]_, and made popular and wide-spread by [Ande75]_, [Ande79]_, [Ande82]_. The DLF is sometimes referred to as the *Fast Hankel Transform* FHT, from which this routine ha...
[ "r", "Hankel", "Transform", "using", "the", "Digital", "Linear", "Filter", "method", "." ]
python
train
32.885246
openthread/openthread
tools/harness-automation/autothreadharness/open_thread_controller.py
https://github.com/openthread/openthread/blob/0208d10563aa21c518092985c78ecf9cd223ab74/tools/harness-automation/autothreadharness/open_thread_controller.py#L149-L170
def _readline(self): """Read exactly one line from the device, nonblocking. Returns: None on no data """ if len(self.lines) > 1: return self.lines.pop(0) tail = '' if len(self.lines): tail = self.lines.pop() try: ...
[ "def", "_readline", "(", "self", ")", ":", "if", "len", "(", "self", ".", "lines", ")", ">", "1", ":", "return", "self", ".", "lines", ".", "pop", "(", "0", ")", "tail", "=", "''", "if", "len", "(", "self", ".", "lines", ")", ":", "tail", "="...
Read exactly one line from the device, nonblocking. Returns: None on no data
[ "Read", "exactly", "one", "line", "from", "the", "device", "nonblocking", "." ]
python
train
24.272727
unfoldingWord-dev/tx-shared-tools
general_tools/file_utils.py
https://github.com/unfoldingWord-dev/tx-shared-tools/blob/6ff5cd024e1ab54c53dd1bc788bbc78e2358772e/general_tools/file_utils.py#L80-L98
def load_json_object(file_name, default=None): """ Deserialized <file_name> into a Python object :param str|unicode file_name: The name of the file to read :param default: The value to return if the file is not found """ if not os.path.isfile(file_name): return default # use utf-8-s...
[ "def", "load_json_object", "(", "file_name", ",", "default", "=", "None", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "file_name", ")", ":", "return", "default", "# use utf-8-sig in case the file has a Byte Order Mark", "with", "codecs", ".", "...
Deserialized <file_name> into a Python object :param str|unicode file_name: The name of the file to read :param default: The value to return if the file is not found
[ "Deserialized", "<file_name", ">", "into", "a", "Python", "object", ":", "param", "str|unicode", "file_name", ":", "The", "name", "of", "the", "file", "to", "read", ":", "param", "default", ":", "The", "value", "to", "return", "if", "the", "file", "is", ...
python
train
33.947368
rcsb/mmtf-python
mmtf/converters/numpy_converters.py
https://github.com/rcsb/mmtf-python/blob/899bb877ca1b32a9396803d38c5bf38a2520754e/mmtf/converters/numpy_converters.py#L17-L23
def decode_chain_list(in_bytes): """Convert a list of bytes to a list of strings. Each string is of length mmtf.CHAIN_LEN :param in_bytes: the input bytes :return the decoded list of strings""" bstrings = numpy.frombuffer(in_bytes, numpy.dtype('S' + str(mmtf.utils.constants.CHAIN_LEN))) return [s.d...
[ "def", "decode_chain_list", "(", "in_bytes", ")", ":", "bstrings", "=", "numpy", ".", "frombuffer", "(", "in_bytes", ",", "numpy", ".", "dtype", "(", "'S'", "+", "str", "(", "mmtf", ".", "utils", ".", "constants", ".", "CHAIN_LEN", ")", ")", ")", "retu...
Convert a list of bytes to a list of strings. Each string is of length mmtf.CHAIN_LEN :param in_bytes: the input bytes :return the decoded list of strings
[ "Convert", "a", "list", "of", "bytes", "to", "a", "list", "of", "strings", ".", "Each", "string", "is", "of", "length", "mmtf", ".", "CHAIN_LEN" ]
python
train
55
matrix-org/matrix-python-sdk
matrix_client/room.py
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L454-L470
def update_aliases(self): """Get aliases information from room state. Returns: boolean: True if the aliases changed, False if not """ try: response = self.client.api.get_room_state(self.room_id) for chunk in response: if "content" in c...
[ "def", "update_aliases", "(", "self", ")", ":", "try", ":", "response", "=", "self", ".", "client", ".", "api", ".", "get_room_state", "(", "self", ".", "room_id", ")", "for", "chunk", "in", "response", ":", "if", "\"content\"", "in", "chunk", "and", "...
Get aliases information from room state. Returns: boolean: True if the aliases changed, False if not
[ "Get", "aliases", "information", "from", "room", "state", "." ]
python
train
37.470588
thombashi/SimpleSQLite
simplesqlite/core.py
https://github.com/thombashi/SimpleSQLite/blob/b16f212132b9b98773e68bf7395abc2f60f56fe5/simplesqlite/core.py#L503-L519
def insert(self, table_name, record, attr_names=None): """ Send an INSERT query to the database. :param str table_name: Table name of executing the query. :param record: Record to be inserted. :type record: |dict|/|namedtuple|/|list|/|tuple| :raises IOError: |raises_writ...
[ "def", "insert", "(", "self", ",", "table_name", ",", "record", ",", "attr_names", "=", "None", ")", ":", "self", ".", "insert_many", "(", "table_name", ",", "records", "=", "[", "record", "]", ",", "attr_names", "=", "attr_names", ")" ]
Send an INSERT query to the database. :param str table_name: Table name of executing the query. :param record: Record to be inserted. :type record: |dict|/|namedtuple|/|list|/|tuple| :raises IOError: |raises_write_permission| :raises simplesqlite.NullDatabaseConnectionError: ...
[ "Send", "an", "INSERT", "query", "to", "the", "database", "." ]
python
train
37.588235
Esri/ArcREST
src/arcrest/ags/_geocodeservice.py
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/ags/_geocodeservice.py#L160-L261
def find(self, text, magicKey=None, sourceCountry=None, bbox=None, location=None, distance=3218.69, outSR=102100, category=None, outFields="*", maxLocations=20, forStorage=False...
[ "def", "find", "(", "self", ",", "text", ",", "magicKey", "=", "None", ",", "sourceCountry", "=", "None", ",", "bbox", "=", "None", ",", "location", "=", "None", ",", "distance", "=", "3218.69", ",", "outSR", "=", "102100", ",", "category", "=", "Non...
The find operation geocodes one location per request; the input address is specified in a single parameter. Inputs: text - Specifies the location to be geocoded. This can be a street address, place name, postal code, or POI. magicKey - The find operation retrieves resu...
[ "The", "find", "operation", "geocodes", "one", "location", "per", "request", ";", "the", "input", "address", "is", "specified", "in", "a", "single", "parameter", "." ]
python
train
50.578431
OCA/openupgradelib
openupgradelib/openupgrade.py
https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L1737-L1749
def savepoint(cr): """return a context manager wrapping postgres savepoints""" if hasattr(cr, 'savepoint'): with cr.savepoint(): yield else: name = uuid.uuid1().hex cr.execute('SAVEPOINT "%s"' % name) try: yield cr.execute('RELEASE SAVEPOIN...
[ "def", "savepoint", "(", "cr", ")", ":", "if", "hasattr", "(", "cr", ",", "'savepoint'", ")", ":", "with", "cr", ".", "savepoint", "(", ")", ":", "yield", "else", ":", "name", "=", "uuid", ".", "uuid1", "(", ")", ".", "hex", "cr", ".", "execute",...
return a context manager wrapping postgres savepoints
[ "return", "a", "context", "manager", "wrapping", "postgres", "savepoints" ]
python
train
30.692308
yamcs/yamcs-python
yamcs-client/yamcs/archive/client.py
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/archive/client.py#L96-L123
def list_processed_parameter_group_histogram(self, group=None, start=None, stop=None, merge_time=20): """ Reads index records related to processed parameter groups between the specified start and stop time. Each iteration returns a chunk of chronologically-sorted records. :para...
[ "def", "list_processed_parameter_group_histogram", "(", "self", ",", "group", "=", "None", ",", "start", "=", "None", ",", "stop", "=", "None", ",", "merge_time", "=", "20", ")", ":", "params", "=", "{", "}", "if", "group", "is", "not", "None", ":", "p...
Reads index records related to processed parameter groups between the specified start and stop time. Each iteration returns a chunk of chronologically-sorted records. :param float merge_time: Maximum gap in seconds before two consecutive index records are merged together. :rtype: ~coll...
[ "Reads", "index", "records", "related", "to", "processed", "parameter", "groups", "between", "the", "specified", "start", "and", "stop", "time", "." ]
python
train
38.928571
fastai/fastai
fastai/callbacks/hooks.py
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/hooks.py#L18-L23
def hook_fn(self, module:nn.Module, input:Tensors, output:Tensors): "Applies `hook_func` to `module`, `input`, `output`." if self.detach: input = (o.detach() for o in input ) if is_listy(input ) else input.detach() output = (o.detach() for o in output) if is_listy(output) else o...
[ "def", "hook_fn", "(", "self", ",", "module", ":", "nn", ".", "Module", ",", "input", ":", "Tensors", ",", "output", ":", "Tensors", ")", ":", "if", "self", ".", "detach", ":", "input", "=", "(", "o", ".", "detach", "(", ")", "for", "o", "in", ...
Applies `hook_func` to `module`, `input`, `output`.
[ "Applies", "hook_func", "to", "module", "input", "output", "." ]
python
train
64.833333
dwavesystems/dwave_networkx
dwave_networkx/algorithms/matching.py
https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/matching.py#L259-L309
def is_maximal_matching(G, matching): """Determines whether the given set of edges is a maximal matching. A matching is a subset of edges in which no node occurs more than once. The cardinality of a matching is the number of matched edges. A maximal matching is one where one cannot add any more edges ...
[ "def", "is_maximal_matching", "(", "G", ",", "matching", ")", ":", "touched_nodes", "=", "set", "(", ")", ".", "union", "(", "*", "matching", ")", "# first check if a matching", "if", "len", "(", "touched_nodes", ")", "!=", "len", "(", "matching", ")", "*"...
Determines whether the given set of edges is a maximal matching. A matching is a subset of edges in which no node occurs more than once. The cardinality of a matching is the number of matched edges. A maximal matching is one where one cannot add any more edges without violating the matching rule. ...
[ "Determines", "whether", "the", "given", "set", "of", "edges", "is", "a", "maximal", "matching", "." ]
python
train
29.117647
StackStorm/pybind
pybind/slxos/v17r_1_01a/mpls_config/router/mpls/mpls_cmds_holder/policy/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17r_1_01a/mpls_config/router/mpls/mpls_cmds_holder/policy/__init__.py#L613-L634
def _set_implicit_commit(self, v, load=False): """ Setter method for implicit_commit, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/policy/implicit_commit (container) If this variable is read-only (config: false) in the source YANG file, then _set_implicit_commit is considered as a...
[ "def", "_set_implicit_commit", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", ...
Setter method for implicit_commit, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/policy/implicit_commit (container) If this variable is read-only (config: false) in the source YANG file, then _set_implicit_commit is considered as a private method. Backends looking to populate this vari...
[ "Setter", "method", "for", "implicit_commit", "mapped", "from", "YANG", "variable", "/", "mpls_config", "/", "router", "/", "mpls", "/", "mpls_cmds_holder", "/", "policy", "/", "implicit_commit", "(", "container", ")", "If", "this", "variable", "is", "read", "...
python
train
78.318182
raghakot/keras-vis
vis/utils/utils.py
https://github.com/raghakot/keras-vis/blob/668b0e11dab93f3487f23c17e07f40554a8939e9/vis/utils/utils.py#L181-L213
def stitch_images(images, margin=5, cols=5): """Utility function to stitch images together with a `margin`. Args: images: The array of 2D images to stitch. margin: The black border margin size between images (Default value = 5) cols: Max number of image cols. New row is created when num...
[ "def", "stitch_images", "(", "images", ",", "margin", "=", "5", ",", "cols", "=", "5", ")", ":", "if", "len", "(", "images", ")", "==", "0", ":", "return", "None", "h", ",", "w", ",", "c", "=", "images", "[", "0", "]", ".", "shape", "n_rows", ...
Utility function to stitch images together with a `margin`. Args: images: The array of 2D images to stitch. margin: The black border margin size between images (Default value = 5) cols: Max number of image cols. New row is created when number of images exceed the column size. (D...
[ "Utility", "function", "to", "stitch", "images", "together", "with", "a", "margin", "." ]
python
train
34.212121
cackharot/suds-py3
suds/properties.py
https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/properties.py#L520-L530
def link(self, other): """ Link (associate) this object with anI{other} properties object to create a network of properties. Links are bidirectional. @param other: The object to link. @type other: L{Properties} @return: self @rtype: L{Properties} """ ...
[ "def", "link", "(", "self", ",", "other", ")", ":", "p", "=", "other", ".", "__pts__", "return", "self", ".", "properties", ".", "link", "(", "p", ")" ]
Link (associate) this object with anI{other} properties object to create a network of properties. Links are bidirectional. @param other: The object to link. @type other: L{Properties} @return: self @rtype: L{Properties}
[ "Link", "(", "associate", ")", "this", "object", "with", "anI", "{", "other", "}", "properties", "object", "to", "create", "a", "network", "of", "properties", ".", "Links", "are", "bidirectional", "." ]
python
train
33.636364
openstack/networking-cisco
networking_cisco/ml2_drivers/nexus/nexus_db_v2.py
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_db_v2.py#L609-L638
def _lookup_vpc_count_min_max(session=None, **bfilter): """Look up count/min/max Nexus VPC Allocs for given switch. :param session: db session :param bfilter: filter for mappings query :returns: number of VPCs and min value if query gave a result, else raise NexusVPCAllocNotFound. """ ...
[ "def", "_lookup_vpc_count_min_max", "(", "session", "=", "None", ",", "*", "*", "bfilter", ")", ":", "if", "session", "is", "None", ":", "session", "=", "bc", ".", "get_reader_session", "(", ")", "try", ":", "res", "=", "session", ".", "query", "(", "f...
Look up count/min/max Nexus VPC Allocs for given switch. :param session: db session :param bfilter: filter for mappings query :returns: number of VPCs and min value if query gave a result, else raise NexusVPCAllocNotFound.
[ "Look", "up", "count", "/", "min", "/", "max", "Nexus", "VPC", "Allocs", "for", "given", "switch", "." ]
python
train
29.666667
mitsei/dlkit
dlkit/json_/authorization/managers.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/authorization/managers.py#L447-L462
def get_authorization_lookup_session(self): """Gets the ``OsidSession`` associated with the authorization lookup service. return: (osid.authorization.AuthorizationLookupSession) - an ``AuthorizationLookupSession`` raise: OperationFailed - unable to complete request rais...
[ "def", "get_authorization_lookup_session", "(", "self", ")", ":", "if", "not", "self", ".", "supports_authorization_lookup", "(", ")", ":", "raise", "errors", ".", "Unimplemented", "(", ")", "# pylint: disable=no-member", "return", "sessions", ".", "AuthorizationLooku...
Gets the ``OsidSession`` associated with the authorization lookup service. return: (osid.authorization.AuthorizationLookupSession) - an ``AuthorizationLookupSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_authorization_lookup()``...
[ "Gets", "the", "OsidSession", "associated", "with", "the", "authorization", "lookup", "service", "." ]
python
train
45.75
hubo1016/vlcp
vlcp/event/runnable.py
https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/event/runnable.py#L636-L645
async def wait_for_all_empty(self, *queues): """ Wait for multiple queues to be empty at the same time. Require delegate when calling from coroutines running in other containers """ matchers = [m for m in (q.waitForEmpty() for q in queues) if m is not None] while matcher...
[ "async", "def", "wait_for_all_empty", "(", "self", ",", "*", "queues", ")", ":", "matchers", "=", "[", "m", "for", "m", "in", "(", "q", ".", "waitForEmpty", "(", ")", "for", "q", "in", "queues", ")", "if", "m", "is", "not", "None", "]", "while", ...
Wait for multiple queues to be empty at the same time. Require delegate when calling from coroutines running in other containers
[ "Wait", "for", "multiple", "queues", "to", "be", "empty", "at", "the", "same", "time", "." ]
python
train
44.8
ska-sa/katcp-python
katcp/resource_client.py
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource_client.py#L371-L382
def until_state(self, state, timeout=None): """Future that resolves when a certain client state is attained Parameters ---------- state : str Desired state, one of ("disconnected", "syncing", "synced") timeout: float Timeout for operation in seconds. ...
[ "def", "until_state", "(", "self", ",", "state", ",", "timeout", "=", "None", ")", ":", "return", "self", ".", "_state", ".", "until_state", "(", "state", ",", "timeout", "=", "timeout", ")" ]
Future that resolves when a certain client state is attained Parameters ---------- state : str Desired state, one of ("disconnected", "syncing", "synced") timeout: float Timeout for operation in seconds.
[ "Future", "that", "resolves", "when", "a", "certain", "client", "state", "is", "attained" ]
python
train
31.666667
bennylope/smartystreets.py
smartystreets/async.py
https://github.com/bennylope/smartystreets.py/blob/f45e37dd52ea7cec8ed43ce2b64724beb6dbbb69/smartystreets/async.py#L24-L29
def chunker(l, n): """ Generates n-sized chunks from the list l """ for i in ranger(0, len(l), n): yield l[i:i + n]
[ "def", "chunker", "(", "l", ",", "n", ")", ":", "for", "i", "in", "ranger", "(", "0", ",", "len", "(", "l", ")", ",", "n", ")", ":", "yield", "l", "[", "i", ":", "i", "+", "n", "]" ]
Generates n-sized chunks from the list l
[ "Generates", "n", "-", "sized", "chunks", "from", "the", "list", "l" ]
python
train
22.333333
KelSolaar/Foundations
foundations/guerilla.py
https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/guerilla.py#L57-L77
def base_warfare(name, bases, attributes): """ Adds any number of attributes to an existing class. :param name: Name. :type name: unicode :param bases: Bases. :type bases: list :param attributes: Attributes. :type attributes: dict :return: Base. :rtype: object """ asser...
[ "def", "base_warfare", "(", "name", ",", "bases", ",", "attributes", ")", ":", "assert", "len", "(", "bases", ")", "==", "1", ",", "\"{0} | '{1}' object has multiple bases!\"", ".", "format", "(", "__name__", ",", "name", ")", "base", "=", "foundations", "."...
Adds any number of attributes to an existing class. :param name: Name. :type name: unicode :param bases: Bases. :type bases: list :param attributes: Attributes. :type attributes: dict :return: Base. :rtype: object
[ "Adds", "any", "number", "of", "attributes", "to", "an", "existing", "class", "." ]
python
train
27.285714
TeamHG-Memex/eli5
eli5/lime/lime.py
https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/lime/lime.py#L293-L302
def show_weights(self, **kwargs): """ Call :func:`eli5.show_weights` for the locally-fit classification pipeline. Keyword arguments are passed to :func:`eli5.show_weights`. :func:`fit` must be called before using this method. """ self._fix_target_names(kwargs) ...
[ "def", "show_weights", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_fix_target_names", "(", "kwargs", ")", "return", "eli5", ".", "show_weights", "(", "self", ".", "clf_", ",", "vec", "=", "self", ".", "vec_", ",", "*", "*", "kwargs...
Call :func:`eli5.show_weights` for the locally-fit classification pipeline. Keyword arguments are passed to :func:`eli5.show_weights`. :func:`fit` must be called before using this method.
[ "Call", ":", "func", ":", "eli5", ".", "show_weights", "for", "the", "locally", "-", "fit", "classification", "pipeline", ".", "Keyword", "arguments", "are", "passed", "to", ":", "func", ":", "eli5", ".", "show_weights", "." ]
python
train
37.7
bokeh/bokeh
bokeh/command/util.py
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/command/util.py#L141-L177
def build_single_handler_applications(paths, argvs=None): ''' Return a dictionary mapping routes to Bokeh applications built using single handlers, for specified files or directories. This function iterates over ``paths`` and ``argvs`` and calls :func:`~bokeh.command.util.build_single_handler_applicati...
[ "def", "build_single_handler_applications", "(", "paths", ",", "argvs", "=", "None", ")", ":", "applications", "=", "{", "}", "argvs", "=", "{", "}", "or", "argvs", "for", "path", "in", "paths", ":", "application", "=", "build_single_handler_application", "(",...
Return a dictionary mapping routes to Bokeh applications built using single handlers, for specified files or directories. This function iterates over ``paths`` and ``argvs`` and calls :func:`~bokeh.command.util.build_single_handler_application` on each to generate the mapping. Args: path (...
[ "Return", "a", "dictionary", "mapping", "routes", "to", "Bokeh", "applications", "built", "using", "single", "handlers", "for", "specified", "files", "or", "directories", "." ]
python
train
29.864865
transceptor-technology/pyleri
pyleri/grammar.py
https://github.com/transceptor-technology/pyleri/blob/af754300d42a5a79bcdfc7852ee4cc75ce245f39/pyleri/grammar.py#L632-L678
def parse(self, string): '''Parse some string to the Grammar. Returns a nodeResult with the following attributes: - is_valid: True when the string is successfully parsed by the Grammar. - pos: position in the string where parsing ended. (this is th...
[ "def", "parse", "(", "self", ",", "string", ")", ":", "self", ".", "_string", "=", "string", "self", ".", "_expecting", "=", "Expecting", "(", ")", "self", ".", "_cached_kw_match", ".", "clear", "(", ")", "self", ".", "_len_string", "=", "len", "(", ...
Parse some string to the Grammar. Returns a nodeResult with the following attributes: - is_valid: True when the string is successfully parsed by the Grammar. - pos: position in the string where parsing ended. (this is the end of the string when is_valid is...
[ "Parse", "some", "string", "to", "the", "Grammar", "." ]
python
train
35.595745
chimera0/accel-brain-code
Reinforcement-Learning/pyqlearning/q_learning.py
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/q_learning.py#L244-L251
def set_t(self, value): ''' setter Time. ''' if isinstance(value, int) is False: raise TypeError("The type of __t must be int.") self.__t = value
[ "def", "set_t", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "int", ")", "is", "False", ":", "raise", "TypeError", "(", "\"The type of __t must be int.\"", ")", "self", ".", "__t", "=", "value" ]
setter Time.
[ "setter", "Time", "." ]
python
train
24.75
rosenbrockc/acorn
acorn/acrn.py
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/acrn.py#L51-L86
def _conf_packages(args): """Runs custom configuration steps for the packages that ship with support in acorn. """ from acorn.config import config_dir from os import path from acorn.base import testmode target = config_dir(True) alternate = path.join(path.abspath(path.expanduser("~")), "...
[ "def", "_conf_packages", "(", "args", ")", ":", "from", "acorn", ".", "config", "import", "config_dir", "from", "os", "import", "path", "from", "acorn", ".", "base", "import", "testmode", "target", "=", "config_dir", "(", "True", ")", "alternate", "=", "pa...
Runs custom configuration steps for the packages that ship with support in acorn.
[ "Runs", "custom", "configuration", "steps", "for", "the", "packages", "that", "ship", "with", "support", "in", "acorn", "." ]
python
train
32.388889
pandas-dev/pandas
pandas/core/strings.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/strings.py#L1532-L1593
def str_wrap(arr, width, **kwargs): r""" Wrap long strings in the Series/Index to be formatted in paragraphs with length less than a given width. This method has the same keyword parameters and defaults as :class:`textwrap.TextWrapper`. Parameters ---------- width : int Maximum...
[ "def", "str_wrap", "(", "arr", ",", "width", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'width'", "]", "=", "width", "tw", "=", "textwrap", ".", "TextWrapper", "(", "*", "*", "kwargs", ")", "return", "_na_map", "(", "lambda", "s", ":", "'\\...
r""" Wrap long strings in the Series/Index to be formatted in paragraphs with length less than a given width. This method has the same keyword parameters and defaults as :class:`textwrap.TextWrapper`. Parameters ---------- width : int Maximum line width. expand_tabs : bool, opt...
[ "r", "Wrap", "long", "strings", "in", "the", "Series", "/", "Index", "to", "be", "formatted", "in", "paragraphs", "with", "length", "less", "than", "a", "given", "width", "." ]
python
train
35.516129
PyMySQL/PyMySQL
pymysql/_auth.py
https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/_auth.py#L34-L45
def scramble_native_password(password, message): """Scramble used for mysql_native_password""" if not password: return b'' stage1 = sha1_new(password).digest() stage2 = sha1_new(stage1).digest() s = sha1_new() s.update(message[:SCRAMBLE_LENGTH]) s.update(stage2) result = s.diges...
[ "def", "scramble_native_password", "(", "password", ",", "message", ")", ":", "if", "not", "password", ":", "return", "b''", "stage1", "=", "sha1_new", "(", "password", ")", ".", "digest", "(", ")", "stage2", "=", "sha1_new", "(", "stage1", ")", ".", "di...
Scramble used for mysql_native_password
[ "Scramble", "used", "for", "mysql_native_password" ]
python
train
29.083333
tensorflow/tensor2tensor
tensor2tensor/envs/env_problem.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L199-L235
def _verify_same_spaces(self): """Verifies that all the envs have the same observation and action space.""" # Pre-conditions: self._envs is initialized. if self._envs is None: raise ValueError("Environments not initialized.") if not isinstance(self._envs, list): tf.logging.warning("Not ch...
[ "def", "_verify_same_spaces", "(", "self", ")", ":", "# Pre-conditions: self._envs is initialized.", "if", "self", ".", "_envs", "is", "None", ":", "raise", "ValueError", "(", "\"Environments not initialized.\"", ")", "if", "not", "isinstance", "(", "self", ".", "_e...
Verifies that all the envs have the same observation and action space.
[ "Verifies", "that", "all", "the", "envs", "have", "the", "same", "observation", "and", "action", "space", "." ]
python
train
39.810811
scikit-tda/kepler-mapper
kmapper/plotlyviz.py
https://github.com/scikit-tda/kepler-mapper/blob/d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d/kmapper/plotlyviz.py#L488-L540
def node_hist_fig( node_color_distribution, title="Graph Node Distribution", width=400, height=300, top=60, left=25, bottom=60, right=25, bgcolor="rgb(240,240,240)", y_gridcolor="white", ): """Define the plotly plot representing the node histogram Param...
[ "def", "node_hist_fig", "(", "node_color_distribution", ",", "title", "=", "\"Graph Node Distribution\"", ",", "width", "=", "400", ",", "height", "=", "300", ",", "top", "=", "60", ",", "left", "=", "25", ",", "bottom", "=", "60", ",", "right", "=", "25...
Define the plotly plot representing the node histogram Parameters ---------- node_color_distribution: list of dicts describing the build_histogram width, height: integers - width and height of the histogram FigureWidget left, top, right, bottom: ints; number of pixels around the FigureWi...
[ "Define", "the", "plotly", "plot", "representing", "the", "node", "histogram", "Parameters", "----------", "node_color_distribution", ":", "list", "of", "dicts", "describing", "the", "build_histogram", "width", "height", ":", "integers", "-", "width", "and", "height...
python
train
30.358491
glitchassassin/lackey
lackey/RegionMatching.py
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L88-L93
def targetOffset(self, dx, dy): """ Returns a new Pattern with the given target offset """ pattern = Pattern(self.path) pattern.similarity = self.similarity pattern.offset = Location(dx, dy) return pattern
[ "def", "targetOffset", "(", "self", ",", "dx", ",", "dy", ")", ":", "pattern", "=", "Pattern", "(", "self", ".", "path", ")", "pattern", ".", "similarity", "=", "self", ".", "similarity", "pattern", ".", "offset", "=", "Location", "(", "dx", ",", "dy...
Returns a new Pattern with the given target offset
[ "Returns", "a", "new", "Pattern", "with", "the", "given", "target", "offset" ]
python
train
40
pilosus/ForgeryPy3
forgery_py/forgery/lorem_ipsum.py
https://github.com/pilosus/ForgeryPy3/blob/e15f2e59538deb4cbfceaac314f5ea897f2d5450/forgery_py/forgery/lorem_ipsum.py#L88-L93
def paragraph(separator='\n\n', wrap_start='', wrap_end='', html=False, sentences_quantity=3): """Return a random paragraph.""" return paragraphs(quantity=1, separator=separator, wrap_start=wrap_start, wrap_end=wrap_end, html=html, sentences_quantity=sen...
[ "def", "paragraph", "(", "separator", "=", "'\\n\\n'", ",", "wrap_start", "=", "''", ",", "wrap_end", "=", "''", ",", "html", "=", "False", ",", "sentences_quantity", "=", "3", ")", ":", "return", "paragraphs", "(", "quantity", "=", "1", ",", "separator"...
Return a random paragraph.
[ "Return", "a", "random", "paragraph", "." ]
python
valid
55.166667
manns/pyspread
pyspread/src/gui/_grid.py
https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/_grid.py#L585-L593
def OnPasteFormat(self, event): """Paste format event handler""" with undo.group(_("Paste format")): self.grid.actions.paste_format() self.grid.ForceRefresh() self.grid.update_attribute_toolbar() self.grid.actions.zoom()
[ "def", "OnPasteFormat", "(", "self", ",", "event", ")", ":", "with", "undo", ".", "group", "(", "_", "(", "\"Paste format\"", ")", ")", ":", "self", ".", "grid", ".", "actions", ".", "paste_format", "(", ")", "self", ".", "grid", ".", "ForceRefresh", ...
Paste format event handler
[ "Paste", "format", "event", "handler" ]
python
train
29.555556
henzk/ape
ape/container_mode/tasks.py
https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/container_mode/tasks.py#L127-L163
def switch(poi): """ Zaps into a specific product specified by switch context to the product of interest(poi) A poi is: sdox:dev - for product "dev" located in container "sdox" If poi does not contain a ":" it is interpreted as product name implying that a product within this container is a...
[ "def", "switch", "(", "poi", ")", ":", "parts", "=", "poi", ".", "split", "(", "':'", ")", "if", "len", "(", "parts", ")", "==", "2", ":", "container_name", ",", "product_name", "=", "parts", "elif", "len", "(", "parts", ")", "==", "1", "and", "o...
Zaps into a specific product specified by switch context to the product of interest(poi) A poi is: sdox:dev - for product "dev" located in container "sdox" If poi does not contain a ":" it is interpreted as product name implying that a product within this container is already active. So if this tas...
[ "Zaps", "into", "a", "specific", "product", "specified", "by", "switch", "context", "to", "the", "product", "of", "interest", "(", "poi", ")", "A", "poi", "is", ":", "sdox", ":", "dev", "-", "for", "product", "dev", "located", "in", "container", "sdox" ]
python
train
42.972973
wilzbach/smarkov
examples/text.py
https://github.com/wilzbach/smarkov/blob/c98c08cc432e18c5c87fb9a6e013b1b8eaa54d37/examples/text.py#L15-L34
def join_tokens_to_sentences(tokens): """ Correctly joins tokens to multiple sentences Instead of always placing white-space between the tokens, it will distinguish between the next symbol and *not* insert whitespace if it is a sentence symbol (e.g. '.', or '?') Args: tokens: array of stri...
[ "def", "join_tokens_to_sentences", "(", "tokens", ")", ":", "text", "=", "\"\"", "for", "(", "entry", ",", "next_entry", ")", "in", "zip", "(", "tokens", ",", "tokens", "[", "1", ":", "]", ")", ":", "text", "+=", "entry", "if", "next_entry", "not", "...
Correctly joins tokens to multiple sentences Instead of always placing white-space between the tokens, it will distinguish between the next symbol and *not* insert whitespace if it is a sentence symbol (e.g. '.', or '?') Args: tokens: array of string tokens Returns: Joint sentences...
[ "Correctly", "joins", "tokens", "to", "multiple", "sentences" ]
python
train
28.5
nwilming/ocupy
ocupy/spline_base.py
https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/spline_base.py#L105-L137
def fit1d(samples, e, remove_zeros = False, **kw): """Fits a 1D distribution with splines. Input: samples: Array Array of samples from a probability distribution e: Array Edges that define the events in the probability distribution. For example, e[0] < x <= ...
[ "def", "fit1d", "(", "samples", ",", "e", ",", "remove_zeros", "=", "False", ",", "*", "*", "kw", ")", ":", "samples", "=", "samples", "[", "~", "np", ".", "isnan", "(", "samples", ")", "]", "length", "=", "len", "(", "e", ")", "-", "1", "hist"...
Fits a 1D distribution with splines. Input: samples: Array Array of samples from a probability distribution e: Array Edges that define the events in the probability distribution. For example, e[0] < x <= e[1] is the range of values that are associate...
[ "Fits", "a", "1D", "distribution", "with", "splines", "." ]
python
train
35.515152
mongolab/mongoctl
mongoctl/objects/server.py
https://github.com/mongolab/mongoctl/blob/fab15216127ad4bf8ea9aa8a95d75504c0ef01a2/mongoctl/objects/server.py#L258-L273
def get_mongo_version(self): """ Gets mongo version of the server if it is running. Otherwise return version configured in mongoVersion property """ if self._mongo_version: return self._mongo_version mongo_version = self.read_current_mongo_version() ...
[ "def", "get_mongo_version", "(", "self", ")", ":", "if", "self", ".", "_mongo_version", ":", "return", "self", ".", "_mongo_version", "mongo_version", "=", "self", ".", "read_current_mongo_version", "(", ")", "if", "not", "mongo_version", ":", "mongo_version", "...
Gets mongo version of the server if it is running. Otherwise return version configured in mongoVersion property
[ "Gets", "mongo", "version", "of", "the", "server", "if", "it", "is", "running", ".", "Otherwise", "return", "version", "configured", "in", "mongoVersion", "property" ]
python
train
29.5
airspeed-velocity/asv
asv/extern/asizeof.py
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L1703-L1713
def exclude_types(self, *objs): '''Exclude the specified object instances and types from sizing. All instances and types of the given objects are excluded, even objects specified as positional arguments in subsequent calls to methods **asizeof** and **asizesof**. ''' ...
[ "def", "exclude_types", "(", "self", ",", "*", "objs", ")", ":", "for", "o", "in", "objs", ":", "for", "t", "in", "_keytuple", "(", "o", ")", ":", "if", "t", "and", "t", "not", "in", "self", ".", "_excl_d", ":", "self", ".", "_excl_d", "[", "t"...
Exclude the specified object instances and types from sizing. All instances and types of the given objects are excluded, even objects specified as positional arguments in subsequent calls to methods **asizeof** and **asizesof**.
[ "Exclude", "the", "specified", "object", "instances", "and", "types", "from", "sizing", "." ]
python
train
41.181818
fastai/fastai
fastai/vision/image.py
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L558-L567
def _affine_inv_mult(c, m): "Applies the inverse affine transform described in `m` to `c`." size = c.flow.size() h,w = c.size m[0,1] *= h/w m[1,0] *= w/h c.flow = c.flow.view(-1,2) a = torch.inverse(m[:2,:2].t()) c.flow = torch.mm(c.flow - m[:2,2], a).view(size) return c
[ "def", "_affine_inv_mult", "(", "c", ",", "m", ")", ":", "size", "=", "c", ".", "flow", ".", "size", "(", ")", "h", ",", "w", "=", "c", ".", "size", "m", "[", "0", ",", "1", "]", "*=", "h", "/", "w", "m", "[", "1", ",", "0", "]", "*=", ...
Applies the inverse affine transform described in `m` to `c`.
[ "Applies", "the", "inverse", "affine", "transform", "described", "in", "m", "to", "c", "." ]
python
train
29.8
allenai/allennlp
allennlp/data/dataset_readers/dataset_utils/ontonotes.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/ontonotes.py#L362-L408
def _process_coref_span_annotations_for_word(label: str, word_index: int, clusters: DefaultDict[int, List[Tuple[int, int]]], coref_stacks: DefaultDict[int, List[int]]) -> No...
[ "def", "_process_coref_span_annotations_for_word", "(", "label", ":", "str", ",", "word_index", ":", "int", ",", "clusters", ":", "DefaultDict", "[", "int", ",", "List", "[", "Tuple", "[", "int", ",", "int", "]", "]", "]", ",", "coref_stacks", ":", "Defaul...
For a given coref label, add it to a currently open span(s), complete a span(s) or ignore it, if it is outside of all spans. This method mutates the clusters and coref_stacks dictionaries. Parameters ---------- label : ``str`` The coref label for this word. w...
[ "For", "a", "given", "coref", "label", "add", "it", "to", "a", "currently", "open", "span", "(", "s", ")", "complete", "a", "span", "(", "s", ")", "or", "ignore", "it", "if", "it", "is", "outside", "of", "all", "spans", ".", "This", "method", "muta...
python
train
53.851064
oscarbranson/latools
latools/latools.py
https://github.com/oscarbranson/latools/blob/cd25a650cfee318152f234d992708511f7047fbe/latools/latools.py#L2214-L2252
def apply_classifier(self, name, samples=None, subset=None): """ Apply a clustering classifier based on all samples, or a subset. Parameters ---------- name : str The name of the classifier to apply. subset : str The subset of samples to apply the...
[ "def", "apply_classifier", "(", "self", ",", "name", ",", "samples", "=", "None", ",", "subset", "=", "None", ")", ":", "if", "samples", "is", "not", "None", ":", "subset", "=", "self", ".", "make_subset", "(", "samples", ")", "samples", "=", "self", ...
Apply a clustering classifier based on all samples, or a subset. Parameters ---------- name : str The name of the classifier to apply. subset : str The subset of samples to apply the classifier to. Returns ------- name : str
[ "Apply", "a", "clustering", "classifier", "based", "on", "all", "samples", "or", "a", "subset", "." ]
python
test
32.410256
PyFilesystem/pyfilesystem2
fs/walk.py
https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/walk.py#L599-L639
def files(self, path="/", **kwargs): # type: (Text, **Any) -> Iterator[Text] """Walk a filesystem, yielding absolute paths to files. Arguments: path (str): A path to a directory. Keyword Arguments: ignore_errors (bool): If `True`, any errors reading a ...
[ "def", "files", "(", "self", ",", "path", "=", "\"/\"", ",", "*", "*", "kwargs", ")", ":", "# type: (Text, **Any) -> Iterator[Text]", "walker", "=", "self", ".", "_make_walker", "(", "*", "*", "kwargs", ")", "return", "walker", ".", "files", "(", "self", ...
Walk a filesystem, yielding absolute paths to files. Arguments: path (str): A path to a directory. Keyword Arguments: ignore_errors (bool): If `True`, any errors reading a directory will be ignored, otherwise exceptions will be raised. ...
[ "Walk", "a", "filesystem", "yielding", "absolute", "paths", "to", "files", "." ]
python
train
49
kensho-technologies/graphql-compiler
graphql_compiler/compiler/ir_lowering_gremlin/ir_lowering.py
https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/compiler/ir_lowering_gremlin/ir_lowering.py#L68-L81
def lower_coerce_type_blocks(ir_blocks): """Lower CoerceType blocks into Filter blocks with a type-check predicate.""" new_ir_blocks = [] for block in ir_blocks: new_block = block if isinstance(block, CoerceType): predicate = BinaryComposition( u'contains', Liter...
[ "def", "lower_coerce_type_blocks", "(", "ir_blocks", ")", ":", "new_ir_blocks", "=", "[", "]", "for", "block", "in", "ir_blocks", ":", "new_block", "=", "block", "if", "isinstance", "(", "block", ",", "CoerceType", ")", ":", "predicate", "=", "BinaryCompositio...
Lower CoerceType blocks into Filter blocks with a type-check predicate.
[ "Lower", "CoerceType", "blocks", "into", "Filter", "blocks", "with", "a", "type", "-", "check", "predicate", "." ]
python
train
33.357143
flo-compbio/genometools
genometools/expression/filter.py
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/filter.py#L32-L71
def filter_variance(matrix, top): """Filter genes in an expression matrix by variance. Parameters ---------- matrix: ExpMatrix The expression matrix. top: int The number of genes to retain. Returns ------- ExpMatrix The filtered expression matrix. """ as...
[ "def", "filter_variance", "(", "matrix", ",", "top", ")", ":", "assert", "isinstance", "(", "matrix", ",", "ExpMatrix", ")", "assert", "isinstance", "(", "top", ",", "(", "int", ",", "np", ".", "integer", ")", ")", "if", "top", ">=", "matrix", ".", "...
Filter genes in an expression matrix by variance. Parameters ---------- matrix: ExpMatrix The expression matrix. top: int The number of genes to retain. Returns ------- ExpMatrix The filtered expression matrix.
[ "Filter", "genes", "in", "an", "expression", "matrix", "by", "variance", "." ]
python
train
28.15
arne-cl/discoursegraphs
src/discoursegraphs/readwrite/exportxml.py
https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/readwrite/exportxml.py#L247-L250
def parse_descedant_elements(self, element): '''parses all descendants of an etree element''' for descendant in element.iterdescendants(): self.parsers[descendant.tag](descendant)
[ "def", "parse_descedant_elements", "(", "self", ",", "element", ")", ":", "for", "descendant", "in", "element", ".", "iterdescendants", "(", ")", ":", "self", ".", "parsers", "[", "descendant", ".", "tag", "]", "(", "descendant", ")" ]
parses all descendants of an etree element
[ "parses", "all", "descendants", "of", "an", "etree", "element" ]
python
train
51
rbarrois/xworkflows
src/xworkflows/utils.py
https://github.com/rbarrois/xworkflows/blob/4a94b04ba83cb43f61d4b0f7db6964a667c86b5b/src/xworkflows/utils.py#L9-L21
def iterclass(cls): """Iterates over (valid) attributes of a class. Args: cls (object): the class to iterate over Yields: (str, obj) tuples: the class-level attributes. """ for field in dir(cls): if hasattr(cls, field): value = getattr(cls, field) yi...
[ "def", "iterclass", "(", "cls", ")", ":", "for", "field", "in", "dir", "(", "cls", ")", ":", "if", "hasattr", "(", "cls", ",", "field", ")", ":", "value", "=", "getattr", "(", "cls", ",", "field", ")", "yield", "field", ",", "value" ]
Iterates over (valid) attributes of a class. Args: cls (object): the class to iterate over Yields: (str, obj) tuples: the class-level attributes.
[ "Iterates", "over", "(", "valid", ")", "attributes", "of", "a", "class", "." ]
python
train
24.923077
PaulHancock/Aegean
AegeanTools/BANE.py
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/BANE.py#L127-L267
def sigma_filter(filename, region, step_size, box_size, shape, domask, sid): """ Calculate the background and rms for a sub region of an image. The results are written to shared memory - irms and ibkg. Parameters ---------- filename : string Fits file to open region : list ...
[ "def", "sigma_filter", "(", "filename", ",", "region", ",", "step_size", ",", "box_size", ",", "shape", ",", "domask", ",", "sid", ")", ":", "ymin", ",", "ymax", "=", "region", "logging", ".", "debug", "(", "'rows {0}-{1} starting at {2}'", ".", "format", ...
Calculate the background and rms for a sub region of an image. The results are written to shared memory - irms and ibkg. Parameters ---------- filename : string Fits file to open region : list Region within the fits file that is to be processed. (row_min, row_max). step_size :...
[ "Calculate", "the", "background", "and", "rms", "for", "a", "sub", "region", "of", "an", "image", ".", "The", "results", "are", "written", "to", "shared", "memory", "-", "irms", "and", "ibkg", "." ]
python
train
35.042553
prompt-toolkit/pymux
pymux/arrangement.py
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/arrangement.py#L543-L546
def get_pane_index(self, pane): " Return the index of the given pane. ValueError if not found. " assert isinstance(pane, Pane) return self.panes.index(pane)
[ "def", "get_pane_index", "(", "self", ",", "pane", ")", ":", "assert", "isinstance", "(", "pane", ",", "Pane", ")", "return", "self", ".", "panes", ".", "index", "(", "pane", ")" ]
Return the index of the given pane. ValueError if not found.
[ "Return", "the", "index", "of", "the", "given", "pane", ".", "ValueError", "if", "not", "found", "." ]
python
train
44.25
dmlc/gluon-nlp
src/gluonnlp/model/block.py
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/block.py#L48-L69
def forward(self, inputs, states=None): # pylint: disable=arguments-differ """Defines the forward computation. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`.""" batch_size = inputs.shape[self._batch_axis] skip_states = states is None if skip_states: ...
[ "def", "forward", "(", "self", ",", "inputs", ",", "states", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "batch_size", "=", "inputs", ".", "shape", "[", "self", ".", "_batch_axis", "]", "skip_states", "=", "states", "is", "None", "if", "skip...
Defines the forward computation. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`.
[ "Defines", "the", "forward", "computation", ".", "Arguments", "can", "be", "either", ":", "py", ":", "class", ":", "NDArray", "or", ":", "py", ":", "class", ":", "Symbol", "." ]
python
train
46.954545
samghelms/mathviz
mathviz_hopper/src/bottle.py
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/bottle.py#L2523-L2525
def meta_set(self, key, metafield, value): """ Set the meta field for a key to a new value. """ self._meta.setdefault(key, {})[metafield] = value
[ "def", "meta_set", "(", "self", ",", "key", ",", "metafield", ",", "value", ")", ":", "self", ".", "_meta", ".", "setdefault", "(", "key", ",", "{", "}", ")", "[", "metafield", "]", "=", "value" ]
Set the meta field for a key to a new value.
[ "Set", "the", "meta", "field", "for", "a", "key", "to", "a", "new", "value", "." ]
python
train
53
svinota/mdns
mdns/zeroconf.py
https://github.com/svinota/mdns/blob/295f6407132616a0ff7401124b9057d89555f91d/mdns/zeroconf.py#L435-L439
def to_string(self, other): """String representation with addtional information""" arg = "%s/%s,%s" % ( self.ttl, self.get_remaining_ttl(current_time_millis()), other) return DNSEntry.to_string(self, "record", arg)
[ "def", "to_string", "(", "self", ",", "other", ")", ":", "arg", "=", "\"%s/%s,%s\"", "%", "(", "self", ".", "ttl", ",", "self", ".", "get_remaining_ttl", "(", "current_time_millis", "(", ")", ")", ",", "other", ")", "return", "DNSEntry", ".", "to_string"...
String representation with addtional information
[ "String", "representation", "with", "addtional", "information" ]
python
train
50
BernardFW/bernard
src/bernard/i18n/translator.py
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/translator.py#L192-L207
def append(self, item: TransItem): """ Append an item to the list. If there is not enough sentences in the list, then the list is extended as needed. There is no control made to make sure that the key is consistent. """ if not (1 <= item.index <= settings.I18N_MAX_SENTE...
[ "def", "append", "(", "self", ",", "item", ":", "TransItem", ")", ":", "if", "not", "(", "1", "<=", "item", ".", "index", "<=", "settings", ".", "I18N_MAX_SENTENCES_PER_GROUP", ")", ":", "return", "if", "len", "(", "self", ".", "sentences", ")", "<", ...
Append an item to the list. If there is not enough sentences in the list, then the list is extended as needed. There is no control made to make sure that the key is consistent.
[ "Append", "an", "item", "to", "the", "list", ".", "If", "there", "is", "not", "enough", "sentences", "in", "the", "list", "then", "the", "list", "is", "extended", "as", "needed", "." ]
python
train
34.375
cjdrake/pyeda
pyeda/boolalg/bfarray.py
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L640-L646
def compose(self, mapping): """Apply the ``compose`` method to all functions. Returns a new farray. """ items = [f.compose(mapping) for f in self._items] return self.__class__(items, self.shape, self.ftype)
[ "def", "compose", "(", "self", ",", "mapping", ")", ":", "items", "=", "[", "f", ".", "compose", "(", "mapping", ")", "for", "f", "in", "self", ".", "_items", "]", "return", "self", ".", "__class__", "(", "items", ",", "self", ".", "shape", ",", ...
Apply the ``compose`` method to all functions. Returns a new farray.
[ "Apply", "the", "compose", "method", "to", "all", "functions", "." ]
python
train
34.428571
ubernostrum/django-flashpolicies
flashpolicies/policies.py
https://github.com/ubernostrum/django-flashpolicies/blob/fb04693504186dde859cce97bad6e83d2b380dc6/flashpolicies/policies.py#L109-L138
def metapolicy(self, permitted): """ Sets metapolicy to ``permitted``. (only applicable to master policy files). Acceptable values correspond to those listed in Section 3(b)(i) of the crossdomain.xml specification, and are also available as a set of constants defined in this modu...
[ "def", "metapolicy", "(", "self", ",", "permitted", ")", ":", "if", "permitted", "not", "in", "VALID_SITE_CONTROL", ":", "raise", "TypeError", "(", "SITE_CONTROL_ERROR", ".", "format", "(", "permitted", ")", ")", "if", "permitted", "==", "SITE_CONTROL_NONE", "...
Sets metapolicy to ``permitted``. (only applicable to master policy files). Acceptable values correspond to those listed in Section 3(b)(i) of the crossdomain.xml specification, and are also available as a set of constants defined in this module. By default, Flash assumes a value of ``m...
[ "Sets", "metapolicy", "to", "permitted", ".", "(", "only", "applicable", "to", "master", "policy", "files", ")", ".", "Acceptable", "values", "correspond", "to", "those", "listed", "in", "Section", "3", "(", "b", ")", "(", "i", ")", "of", "the", "crossdo...
python
train
48.533333
rosshamish/catanlog
catanlog.py
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L208-L235
def log_player_trades_with_port(self, player, to_port, port, to_player): """ :param player: catan.game.Player :param to_port: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param port: catan.board.Port :param to_player: list of tuples, [(int, game.board.T...
[ "def", "log_player_trades_with_port", "(", "self", ",", "player", ",", "to_port", ",", "port", ",", "to_player", ")", ":", "self", ".", "_log", "(", "'{0} trades '", ".", "format", "(", "player", ".", "color", ")", ")", "# to_port items", "self", ".", "_lo...
:param player: catan.game.Player :param to_port: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param port: catan.board.Port :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)]
[ ":", "param", "player", ":", "catan", ".", "game", ".", "Player", ":", "param", "to_port", ":", "list", "of", "tuples", "[", "(", "int", "game", ".", "board", ".", "Terrain", ")", "(", "int", "game", ".", "board", ".", "Terrain", ")", "]", ":", "...
python
train
33.821429