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
tensorflow/cleverhans
cleverhans/utils_keras.py
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_keras.py#L129-L140
def _get_abstract_layer_name(self): """ Looks for the name of abstracted layer. Usually these layers appears when model is stacked. :return: List of abstracted layers """ abstract_layers = [] for layer in self.model.layers: if 'layers' in layer.get_config(): abstract_layers.app...
[ "def", "_get_abstract_layer_name", "(", "self", ")", ":", "abstract_layers", "=", "[", "]", "for", "layer", "in", "self", ".", "model", ".", "layers", ":", "if", "'layers'", "in", "layer", ".", "get_config", "(", ")", ":", "abstract_layers", ".", "append",...
Looks for the name of abstracted layer. Usually these layers appears when model is stacked. :return: List of abstracted layers
[ "Looks", "for", "the", "name", "of", "abstracted", "layer", ".", "Usually", "these", "layers", "appears", "when", "model", "is", "stacked", ".", ":", "return", ":", "List", "of", "abstracted", "layers" ]
python
train
29.333333
bunq/sdk_python
bunq/sdk/model/generated/endpoint.py
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L4825-L4851
def is_all_field_none(self): """ :rtype: bool """ if self._id_ is not None: return False if self._created is not None: return False if self._updated is not None: return False if self._type_ is not None: return Fa...
[ "def", "is_all_field_none", "(", "self", ")", ":", "if", "self", ".", "_id_", "is", "not", "None", ":", "return", "False", "if", "self", ".", "_created", "is", "not", "None", ":", "return", "False", "if", "self", ".", "_updated", "is", "not", "None", ...
:rtype: bool
[ ":", "rtype", ":", "bool" ]
python
train
18.888889
hobson/pug
pca_so.py
https://github.com/hobson/pug/blob/f183e2b29e0b3efa425a9b75cfe001b28a279acc/pca_so.py#L81-L84
def pc( self ): """ e.g. 1000 x 2 U[:, :npc] * d[:npc], to plot etc. """ n = self.npc return self.U[:, :n] * self.d[:n]
[ "def", "pc", "(", "self", ")", ":", "n", "=", "self", ".", "npc", "return", "self", ".", "U", "[", ":", ",", ":", "n", "]", "*", "self", ".", "d", "[", ":", "n", "]" ]
e.g. 1000 x 2 U[:, :npc] * d[:npc], to plot etc.
[ "e", ".", "g", ".", "1000", "x", "2", "U", "[", ":", ":", "npc", "]", "*", "d", "[", ":", "npc", "]", "to", "plot", "etc", "." ]
python
valid
35
tamland/python-actors
actors/ref.py
https://github.com/tamland/python-actors/blob/9f826ab2947c665d61363a6ebc401e9e42cc6238/actors/ref.py#L26-L39
def tell(self, message, sender=no_sender): """ Send a message to this actor. Asynchronous fire-and-forget. :param message: The message to send. :type message: Any :param sender: The sender of the message. If provided it will be made available to the receiving actor via the ...
[ "def", "tell", "(", "self", ",", "message", ",", "sender", "=", "no_sender", ")", ":", "if", "sender", "is", "not", "no_sender", "and", "not", "isinstance", "(", "sender", ",", "ActorRef", ")", ":", "raise", "ValueError", "(", "\"Sender must be actor referen...
Send a message to this actor. Asynchronous fire-and-forget. :param message: The message to send. :type message: Any :param sender: The sender of the message. If provided it will be made available to the receiving actor via the :attr:`Actor.sender` attribute. :type sender: :...
[ "Send", "a", "message", "to", "this", "actor", ".", "Asynchronous", "fire", "-", "and", "-", "forget", "." ]
python
valid
40.928571
quantopian/zipline
zipline/assets/assets.py
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L216-L223
def _convert_asset_timestamp_fields(dict_): """ Takes in a dict of Asset init args and converts dates to pd.Timestamps """ for key in _asset_timestamp_fields & viewkeys(dict_): value = pd.Timestamp(dict_[key], tz='UTC') dict_[key] = None if isnull(value) else value return dict_
[ "def", "_convert_asset_timestamp_fields", "(", "dict_", ")", ":", "for", "key", "in", "_asset_timestamp_fields", "&", "viewkeys", "(", "dict_", ")", ":", "value", "=", "pd", ".", "Timestamp", "(", "dict_", "[", "key", "]", ",", "tz", "=", "'UTC'", ")", "...
Takes in a dict of Asset init args and converts dates to pd.Timestamps
[ "Takes", "in", "a", "dict", "of", "Asset", "init", "args", "and", "converts", "dates", "to", "pd", ".", "Timestamps" ]
python
train
38.375
iotile/coretools
iotilebuild/iotile/build/config/site_scons/release.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/release.py#L99-L125
def copy_extra_files(tile): """Copy all files listed in a copy_files and copy_products section. Files listed in copy_files will be copied from the specified location in the current component to the specified path under the output folder. Files listed in copy_products will be looked up with a Produ...
[ "def", "copy_extra_files", "(", "tile", ")", ":", "env", "=", "Environment", "(", "tools", "=", "[", "]", ")", "outputbase", "=", "os", ".", "path", ".", "join", "(", "'build'", ",", "'output'", ")", "for", "src", ",", "dest", "in", "tile", ".", "s...
Copy all files listed in a copy_files and copy_products section. Files listed in copy_files will be copied from the specified location in the current component to the specified path under the output folder. Files listed in copy_products will be looked up with a ProductResolver and copied copied to...
[ "Copy", "all", "files", "listed", "in", "a", "copy_files", "and", "copy_products", "section", "." ]
python
train
42.148148
mathandy/svgpathtools
svgpathtools/path.py
https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L1474-L1594
def point_to_t(self, point): """If the point lies on the Arc, returns its `t` parameter. If the point does not lie on the Arc, returns None. This function only works on Arcs with rotation == 0.0""" def in_range(min, max, val): return (min <= val) and (max >= val) # ...
[ "def", "point_to_t", "(", "self", ",", "point", ")", ":", "def", "in_range", "(", "min", ",", "max", ",", "val", ")", ":", "return", "(", "min", "<=", "val", ")", "and", "(", "max", ">=", "val", ")", "# Single-precision floats have only 7 significant figur...
If the point lies on the Arc, returns its `t` parameter. If the point does not lie on the Arc, returns None. This function only works on Arcs with rotation == 0.0
[ "If", "the", "point", "lies", "on", "the", "Arc", "returns", "its", "t", "parameter", ".", "If", "the", "point", "does", "not", "lie", "on", "the", "Arc", "returns", "None", ".", "This", "function", "only", "works", "on", "Arcs", "with", "rotation", "=...
python
train
33.975207
kata198/AdvancedHTMLParser
AdvancedHTMLParser/Parser.py
https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Parser.py#L839-L847
def _reset(self): ''' _reset - reset this object. Assigned to .reset after __init__ call. ''' HTMLParser.reset(self) self.root = None self.doctype = None self._inTag = []
[ "def", "_reset", "(", "self", ")", ":", "HTMLParser", ".", "reset", "(", "self", ")", "self", ".", "root", "=", "None", "self", ".", "doctype", "=", "None", "self", ".", "_inTag", "=", "[", "]" ]
_reset - reset this object. Assigned to .reset after __init__ call.
[ "_reset", "-", "reset", "this", "object", ".", "Assigned", "to", ".", "reset", "after", "__init__", "call", "." ]
python
train
24.777778
denisenkom/pytds
src/pytds/tds.py
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L467-L484
def raise_db_exception(self): """ Raises exception from last server message This function will skip messages: The statement has been terminated """ if not self.messages: raise tds_base.Error("Request failed, server didn't send error message") msg = None while...
[ "def", "raise_db_exception", "(", "self", ")", ":", "if", "not", "self", ".", "messages", ":", "raise", "tds_base", ".", "Error", "(", "\"Request failed, server didn't send error message\"", ")", "msg", "=", "None", "while", "True", ":", "msg", "=", "self", "....
Raises exception from last server message This function will skip messages: The statement has been terminated
[ "Raises", "exception", "from", "last", "server", "message" ]
python
train
36.222222
piotr-rusin/spam-lists
spam_lists/host_collections.py
https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/host_collections.py#L140-L160
def _add_new(self, host_object): """Add a new host to the collection. Before a new hostname can be added, all its subdomains already present in the collection must be removed. Since the collection is sorted, we can limit our search for them to a slice of the collection starting ...
[ "def", "_add_new", "(", "self", ",", "host_object", ")", ":", "i", "=", "self", ".", "_get_insertion_point", "(", "host_object", ")", "for", "listed", "in", "self", "[", "i", ":", "]", ":", "if", "not", "listed", ".", "is_subdomain", "(", "host_object", ...
Add a new host to the collection. Before a new hostname can be added, all its subdomains already present in the collection must be removed. Since the collection is sorted, we can limit our search for them to a slice of the collection starting from insertion point and ending with ...
[ "Add", "a", "new", "host", "to", "the", "collection", "." ]
python
train
38.761905
androguard/androguard
androguard/core/bytecodes/apk.py
https://github.com/androguard/androguard/blob/984c0d981be2950cf0451e484f7b0d4d53bc4911/androguard/core/bytecodes/apk.py#L625-L670
def _get_file_magic_name(self, buffer): """ Return the filetype guessed for a buffer :param buffer: bytes :returns: str of filetype """ default = "Unknown" # Faster way, test once, return default. if self.__no_magic: return default tr...
[ "def", "_get_file_magic_name", "(", "self", ",", "buffer", ")", ":", "default", "=", "\"Unknown\"", "# Faster way, test once, return default.", "if", "self", ".", "__no_magic", ":", "return", "default", "try", ":", "# Magic is optional", "import", "magic", "except", ...
Return the filetype guessed for a buffer :param buffer: bytes :returns: str of filetype
[ "Return", "the", "filetype", "guessed", "for", "a", "buffer", ":", "param", "buffer", ":", "bytes", ":", "returns", ":", "str", "of", "filetype" ]
python
train
35.673913
eternnoir/pyTelegramBotAPI
telebot/__init__.py
https://github.com/eternnoir/pyTelegramBotAPI/blob/47b53b88123097f1b9562a6cd5d4e080b86185d1/telebot/__init__.py#L786-L797
def stop_message_live_location(self, chat_id=None, message_id=None, inline_message_id=None, reply_markup=None): """ Use this method to stop updating a live location message sent by the bot or via the bot (for inline bots) before live_period expires :param chat_id: :param message_...
[ "def", "stop_message_live_location", "(", "self", ",", "chat_id", "=", "None", ",", "message_id", "=", "None", ",", "inline_message_id", "=", "None", ",", "reply_markup", "=", "None", ")", ":", "return", "types", ".", "Message", ".", "de_json", "(", "apihelp...
Use this method to stop updating a live location message sent by the bot or via the bot (for inline bots) before live_period expires :param chat_id: :param message_id: :param inline_message_id: :param reply_markup: :return:
[ "Use", "this", "method", "to", "stop", "updating", "a", "live", "location", "message", "sent", "by", "the", "bot", "or", "via", "the", "bot", "(", "for", "inline", "bots", ")", "before", "live_period", "expires", ":", "param", "chat_id", ":", ":", "param...
python
train
46.5
markovmodel/msmtools
msmtools/analysis/dense/pcca.py
https://github.com/markovmodel/msmtools/blob/54dc76dd2113a0e8f3d15d5316abab41402941be/msmtools/analysis/dense/pcca.py#L194-L219
def _fill_matrix(rot_crop_matrix, eigvectors): """ Helper function for opt_soft """ (x, y) = rot_crop_matrix.shape row_sums = np.sum(rot_crop_matrix, axis=1) row_sums = np.reshape(row_sums, (x, 1)) # add -row_sums as leftmost column to rot_crop_matrix rot_crop_matrix = np.concatenate...
[ "def", "_fill_matrix", "(", "rot_crop_matrix", ",", "eigvectors", ")", ":", "(", "x", ",", "y", ")", "=", "rot_crop_matrix", ".", "shape", "row_sums", "=", "np", ".", "sum", "(", "rot_crop_matrix", ",", "axis", "=", "1", ")", "row_sums", "=", "np", "."...
Helper function for opt_soft
[ "Helper", "function", "for", "opt_soft" ]
python
train
27.538462
RedHatInsights/insights-core
insights/client/mount.py
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/mount.py#L150-L157
def unmount_path(path, force=False): """ Unmounts the directory specified by path. """ r = util.subp(['umount', path]) if not force: if r.return_code != 0: raise ValueError(r.stderr)
[ "def", "unmount_path", "(", "path", ",", "force", "=", "False", ")", ":", "r", "=", "util", ".", "subp", "(", "[", "'umount'", ",", "path", "]", ")", "if", "not", "force", ":", "if", "r", ".", "return_code", "!=", "0", ":", "raise", "ValueError", ...
Unmounts the directory specified by path.
[ "Unmounts", "the", "directory", "specified", "by", "path", "." ]
python
train
30.375
jason-weirather/py-seq-tools
seqtools/format/sam/__init__.py
https://github.com/jason-weirather/py-seq-tools/blob/f642c2c73ffef2acc83656a78059a476fc734ca1/seqtools/format/sam/__init__.py#L511-L518
def is_header(line): """true if we are in a header""" if re.match('^@',line): f = line.rstrip().split("\t") if(len(f) > 9): return False return True return False
[ "def", "is_header", "(", "line", ")", ":", "if", "re", ".", "match", "(", "'^@'", ",", "line", ")", ":", "f", "=", "line", ".", "rstrip", "(", ")", ".", "split", "(", "\"\\t\"", ")", "if", "(", "len", "(", "f", ")", ">", "9", ")", ":", "ret...
true if we are in a header
[ "true", "if", "we", "are", "in", "a", "header" ]
python
train
22.25
yvesalexandre/bandicoot
bandicoot/recharge.py
https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/recharge.py#L74-L91
def average_balance_recharges(user, **kwargs): """ Return the average daily balance estimated from all recharges. We assume a linear usage between two recharges, and an empty balance before a recharge. The average balance can be seen as the area under the curve delimited by all recharges. """ ...
[ "def", "average_balance_recharges", "(", "user", ",", "*", "*", "kwargs", ")", ":", "balance", "=", "0", "for", "r1", ",", "r2", "in", "pairwise", "(", "user", ".", "recharges", ")", ":", "# If the range is less than 1 day, cap at 1", "balance", "+=", "r1", ...
Return the average daily balance estimated from all recharges. We assume a linear usage between two recharges, and an empty balance before a recharge. The average balance can be seen as the area under the curve delimited by all recharges.
[ "Return", "the", "average", "daily", "balance", "estimated", "from", "all", "recharges", ".", "We", "assume", "a", "linear", "usage", "between", "two", "recharges", "and", "an", "empty", "balance", "before", "a", "recharge", "." ]
python
train
37.666667
tmontaigu/pylas
pylas/vlrs/geotiff.py
https://github.com/tmontaigu/pylas/blob/8335a1a7d7677f0e4bc391bb6fa3c75b42ed5b06/pylas/vlrs/geotiff.py#L52-L81
def parse_geo_tiff( key_dir_vlr: GeoKeyDirectoryVlr, double_vlr: GeoDoubleParamsVlr, ascii_vlr: GeoAsciiParamsVlr, ) -> List[GeoTiffKey]: """ Parses the GeoTiff VLRs information into nicer structs """ geotiff_keys = [] for k in key_dir_vlr.geo_keys: if k.tiff_tag_location == 0: ...
[ "def", "parse_geo_tiff", "(", "key_dir_vlr", ":", "GeoKeyDirectoryVlr", ",", "double_vlr", ":", "GeoDoubleParamsVlr", ",", "ascii_vlr", ":", "GeoAsciiParamsVlr", ",", ")", "->", "List", "[", "GeoTiffKey", "]", ":", "geotiff_keys", "=", "[", "]", "for", "k", "i...
Parses the GeoTiff VLRs information into nicer structs
[ "Parses", "the", "GeoTiff", "VLRs", "information", "into", "nicer", "structs" ]
python
test
34.4
cackharot/suds-py3
suds/sax/element.py
https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/sax/element.py#L237-L249
def setText(self, value): """ Set the element's L{Text} content. @param value: The element's text value. @type value: basestring @return: self @rtype: I{Element} """ if isinstance(value, Text): self.text = value else: self.t...
[ "def", "setText", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "Text", ")", ":", "self", ".", "text", "=", "value", "else", ":", "self", ".", "text", "=", "Text", "(", "value", ")", "return", "self" ]
Set the element's L{Text} content. @param value: The element's text value. @type value: basestring @return: self @rtype: I{Element}
[ "Set", "the", "element", "s", "L", "{", "Text", "}", "content", "." ]
python
train
26.538462
Grunny/zap-cli
zapcli/commands/scanners.py
https://github.com/Grunny/zap-cli/blob/d58d4850ecfc5467badfac5e5bcc841d064bd419/zapcli/commands/scanners.py#L104-L107
def _get_all_scanner_ids(zap_helper): """Get all scanner IDs.""" scanners = zap_helper.zap.ascan.scanners() return [s['id'] for s in scanners]
[ "def", "_get_all_scanner_ids", "(", "zap_helper", ")", ":", "scanners", "=", "zap_helper", ".", "zap", ".", "ascan", ".", "scanners", "(", ")", "return", "[", "s", "[", "'id'", "]", "for", "s", "in", "scanners", "]" ]
Get all scanner IDs.
[ "Get", "all", "scanner", "IDs", "." ]
python
train
37.75
gwastro/pycbc-glue
pycbc_glue/segments.py
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/segments.py#L1234-L1245
def intersection(self, keys): """ Return the intersection of the segmentlists associated with the keys in keys. """ keys = set(keys) if not keys: return segmentlist() seglist = _shallowcopy(self[keys.pop()]) for key in keys: seglist &= self[key] return seglist
[ "def", "intersection", "(", "self", ",", "keys", ")", ":", "keys", "=", "set", "(", "keys", ")", "if", "not", "keys", ":", "return", "segmentlist", "(", ")", "seglist", "=", "_shallowcopy", "(", "self", "[", "keys", ".", "pop", "(", ")", "]", ")", ...
Return the intersection of the segmentlists associated with the keys in keys.
[ "Return", "the", "intersection", "of", "the", "segmentlists", "associated", "with", "the", "keys", "in", "keys", "." ]
python
train
22.75
jmgilman/Neolib
neolib/pyamf/remoting/amf3.py
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/remoting/amf3.py#L53-L93
def generate_error(request, cls, e, tb, include_traceback=False): """ Builds an L{ErrorMessage<pyamf.flex.messaging.ErrorMessage>} based on the last traceback and the request that was sent. """ import traceback if hasattr(cls, '_amf_code'): code = cls._amf_code else: code = ...
[ "def", "generate_error", "(", "request", ",", "cls", ",", "e", ",", "tb", ",", "include_traceback", "=", "False", ")", ":", "import", "traceback", "if", "hasattr", "(", "cls", ",", "'_amf_code'", ")", ":", "code", "=", "cls", ".", "_amf_code", "else", ...
Builds an L{ErrorMessage<pyamf.flex.messaging.ErrorMessage>} based on the last traceback and the request that was sent.
[ "Builds", "an", "L", "{", "ErrorMessage<pyamf", ".", "flex", ".", "messaging", ".", "ErrorMessage", ">", "}", "based", "on", "the", "last", "traceback", "and", "the", "request", "that", "was", "sent", "." ]
python
train
27.121951
caseyjlaw/rtpipe
rtpipe/FDMT.py
https://github.com/caseyjlaw/rtpipe/blob/ac33e4332cf215091a63afbb3137850876d73ec0/rtpipe/FDMT.py#L97-L125
def FDMT_initialization(datain, f_min, f_max, maxDT, dataType): """ Input: datain - visibilities of (nint, nbl, nchan, npol) f_min,f_max - are the base-band begin and end frequencies. The frequencies can be entered in both MHz and GHz, units are factored out in all uses. maxDT - the ...
[ "def", "FDMT_initialization", "(", "datain", ",", "f_min", ",", "f_max", ",", "maxDT", ",", "dataType", ")", ":", "# Data initialization is done prior to the first FDMT iteration", "# See Equations 17 and 19 in Zackay & Ofek (2014)", "[", "nint", ",", "nbl", ",", "nchan", ...
Input: datain - visibilities of (nint, nbl, nchan, npol) f_min,f_max - are the base-band begin and end frequencies. The frequencies can be entered in both MHz and GHz, units are factored out in all uses. maxDT - the maximal delay (in time bins) of the maximal dispersion. Appears ...
[ "Input", ":", "datain", "-", "visibilities", "of", "(", "nint", "nbl", "nchan", "npol", ")", "f_min", "f_max", "-", "are", "the", "base", "-", "band", "begin", "and", "end", "frequencies", ".", "The", "frequencies", "can", "be", "entered", "in", "both", ...
python
train
48.103448
jsvine/spectra
spectra/grapefruit.py
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1177-L1201
def NewFromRgb(r, g, b, alpha=1.0, wref=_DEFAULT_WREF): '''Create a new instance based on the specifed RGB values. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] :alpha: The color...
[ "def", "NewFromRgb", "(", "r", ",", "g", ",", "b", ",", "alpha", "=", "1.0", ",", "wref", "=", "_DEFAULT_WREF", ")", ":", "return", "Color", "(", "(", "r", ",", "g", ",", "b", ")", ",", "'rgb'", ",", "alpha", ",", "wref", ")" ]
Create a new instance based on the specifed RGB values. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: T...
[ "Create", "a", "new", "instance", "based", "on", "the", "specifed", "RGB", "values", "." ]
python
train
25.76
gmr/queries
queries/pool.py
https://github.com/gmr/queries/blob/a68855013dc6aaf9ed7b6909a4701f8da8796a0a/queries/pool.py#L653-L657
def shutdown(cls): """Close all connections on in all pools""" for pid in list(cls._pools.keys()): cls._pools[pid].shutdown() LOGGER.info('Shutdown complete, all pooled connections closed')
[ "def", "shutdown", "(", "cls", ")", ":", "for", "pid", "in", "list", "(", "cls", ".", "_pools", ".", "keys", "(", ")", ")", ":", "cls", ".", "_pools", "[", "pid", "]", ".", "shutdown", "(", ")", "LOGGER", ".", "info", "(", "'Shutdown complete, all ...
Close all connections on in all pools
[ "Close", "all", "connections", "on", "in", "all", "pools" ]
python
train
44.2
andersinno/python-database-sanitizer
database_sanitizer/dump/postgres.py
https://github.com/andersinno/python-database-sanitizer/blob/742bc1f43526b60f322a48f18c900f94fd446ed4/database_sanitizer/dump/postgres.py#L18-L85
def sanitize(url, config): """ Obtains dump of an Postgres database by executing `pg_dump` command and sanitizes it's output. :param url: URL to the database which is going to be sanitized, parsed by Python's URL parser. :type url: six.moves.urllib.parse.ParseResult :param conf...
[ "def", "sanitize", "(", "url", ",", "config", ")", ":", "if", "url", ".", "scheme", "not", "in", "(", "\"postgres\"", ",", "\"postgresql\"", ",", "\"postgis\"", ")", ":", "raise", "ValueError", "(", "\"Unsupported database type: '%s'\"", "%", "(", "url", "."...
Obtains dump of an Postgres database by executing `pg_dump` command and sanitizes it's output. :param url: URL to the database which is going to be sanitized, parsed by Python's URL parser. :type url: six.moves.urllib.parse.ParseResult :param config: Optional sanitizer configuration to...
[ "Obtains", "dump", "of", "an", "Postgres", "database", "by", "executing", "pg_dump", "command", "and", "sanitizes", "it", "s", "output", "." ]
python
train
33.308824
uw-it-aca/uw-restclients-pws
uw_pws/__init__.py
https://github.com/uw-it-aca/uw-restclients-pws/blob/758d94b42a01762738140c5f984d05f389325b7a/uw_pws/__init__.py#L120-L141
def get_person_by_prox_rfid(self, prox_rfid): """ Returns a restclients.Person object for the given rfid. If the rfid isn't found, or if there is an error communicating with the IdCard WS, a DataFailureException will be thrown. """ if not self.valid_prox_rfid(prox_rfid):...
[ "def", "get_person_by_prox_rfid", "(", "self", ",", "prox_rfid", ")", ":", "if", "not", "self", ".", "valid_prox_rfid", "(", "prox_rfid", ")", ":", "raise", "InvalidProxRFID", "(", "prox_rfid", ")", "url", "=", "\"{}.json?{}\"", ".", "format", "(", "CARD_PREFI...
Returns a restclients.Person object for the given rfid. If the rfid isn't found, or if there is an error communicating with the IdCard WS, a DataFailureException will be thrown.
[ "Returns", "a", "restclients", ".", "Person", "object", "for", "the", "given", "rfid", ".", "If", "the", "rfid", "isn", "t", "found", "or", "if", "there", "is", "an", "error", "communicating", "with", "the", "IdCard", "WS", "a", "DataFailureException", "wi...
python
train
38.818182
lmacken/tbgrep
tbgrep/__init__.py
https://github.com/lmacken/tbgrep/blob/3bc0030906d9bb82aebace585576c495111ba40c/tbgrep/__init__.py#L82-L98
def tracebacks_from_file(fileobj, reverse=False): """Generator that yields tracebacks found in a file object With reverse=True, searches backwards from the end of the file. """ if reverse: lines = deque() for line in BackwardsReader(fileobj): lines.appendleft(line) ...
[ "def", "tracebacks_from_file", "(", "fileobj", ",", "reverse", "=", "False", ")", ":", "if", "reverse", ":", "lines", "=", "deque", "(", ")", "for", "line", "in", "BackwardsReader", "(", "fileobj", ")", ":", "lines", ".", "appendleft", "(", "line", ")", ...
Generator that yields tracebacks found in a file object With reverse=True, searches backwards from the end of the file.
[ "Generator", "that", "yields", "tracebacks", "found", "in", "a", "file", "object" ]
python
train
30
qubole/qds-sdk-py
qds_sdk/cluster.py
https://github.com/qubole/qds-sdk-py/blob/77210fb64e5a7d567aedeea3b742a1d872fd0e5e/qds_sdk/cluster.py#L743-L750
def update_node(cls, cluster_id_label, command, private_dns, parameters=None): """ Add a node to an existing cluster """ conn = Qubole.agent(version=Cluster.api_version) parameters = {} if not parameters else parameters data = {"command" : command, "private_dns" : private...
[ "def", "update_node", "(", "cls", ",", "cluster_id_label", ",", "command", ",", "private_dns", ",", "parameters", "=", "None", ")", ":", "conn", "=", "Qubole", ".", "agent", "(", "version", "=", "Cluster", ".", "api_version", ")", "parameters", "=", "{", ...
Add a node to an existing cluster
[ "Add", "a", "node", "to", "an", "existing", "cluster" ]
python
train
52.75
twisted/txaws
txaws/s3/client.py
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/s3/client.py#L344-L358
def get_bucket_notification_config(self, bucket): """ Get the notification configuration of a bucket. @param bucket: The name of the bucket. @return: A C{Deferred} that will request the bucket's notification configuration. """ details = self._details( ...
[ "def", "get_bucket_notification_config", "(", "self", ",", "bucket", ")", ":", "details", "=", "self", ".", "_details", "(", "method", "=", "b\"GET\"", ",", "url_context", "=", "self", ".", "_url_context", "(", "bucket", "=", "bucket", ",", "object_name", "=...
Get the notification configuration of a bucket. @param bucket: The name of the bucket. @return: A C{Deferred} that will request the bucket's notification configuration.
[ "Get", "the", "notification", "configuration", "of", "a", "bucket", "." ]
python
train
36.333333
ptrus/suffix-trees
suffix_trees/STree.py
https://github.com/ptrus/suffix-trees/blob/e7439c93a7b895523fad36c8c65a781710320b57/suffix_trees/STree.py#L181-L208
def find(self, y): """Returns starting position of the substring y in the string used for building the Suffix tree. :param y: String :return: Index of the starting position of string y in the string used for building the Suffix tree -1 if y is not a substring. "...
[ "def", "find", "(", "self", ",", "y", ")", ":", "node", "=", "self", ".", "root", "while", "True", ":", "edge", "=", "self", ".", "_edgeLabel", "(", "node", ",", "node", ".", "parent", ")", "if", "edge", ".", "startswith", "(", "y", ")", ":", "...
Returns starting position of the substring y in the string used for building the Suffix tree. :param y: String :return: Index of the starting position of string y in the string used for building the Suffix tree -1 if y is not a substring.
[ "Returns", "starting", "position", "of", "the", "substring", "y", "in", "the", "string", "used", "for", "building", "the", "Suffix", "tree", "." ]
python
valid
31.071429
alex-kostirin/pyatomac
atomac/ldtpd/core.py
https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/core.py#L424-L456
def launchapp(self, cmd, args=[], delay=0, env=1, lang="C"): """ Launch application. @param cmd: Command line string to execute. @type cmd: string @param args: Arguments to the application @type args: list @param delay: Delay after the application is launched ...
[ "def", "launchapp", "(", "self", ",", "cmd", ",", "args", "=", "[", "]", ",", "delay", "=", "0", ",", "env", "=", "1", ",", "lang", "=", "\"C\"", ")", ":", "try", ":", "atomac", ".", "NativeUIElement", ".", "launchAppByBundleId", "(", "cmd", ")", ...
Launch application. @param cmd: Command line string to execute. @type cmd: string @param args: Arguments to the application @type args: list @param delay: Delay after the application is launched @type delay: int @param env: GNOME accessibility environment to be s...
[ "Launch", "application", "." ]
python
valid
33.757576
keon/algorithms
algorithms/calculator/math_parser.py
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/calculator/math_parser.py#L77-L99
def parse(expression): """ Return array of parsed tokens in the expression expression String: Math expression to parse in infix notation """ result = [] current = "" for i in expression: if i.isdigit() or i == '.': current += i else: if le...
[ "def", "parse", "(", "expression", ")", ":", "result", "=", "[", "]", "current", "=", "\"\"", "for", "i", "in", "expression", ":", "if", "i", ".", "isdigit", "(", ")", "or", "i", "==", "'.'", ":", "current", "+=", "i", "else", ":", "if", "len", ...
Return array of parsed tokens in the expression expression String: Math expression to parse in infix notation
[ "Return", "array", "of", "parsed", "tokens", "in", "the", "expression", "expression", "String", ":", "Math", "expression", "to", "parse", "in", "infix", "notation" ]
python
train
27.434783
google/grr
grr/server/grr_response_server/databases/mysql_paths.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_paths.py#L26-L113
def ReadPathInfo(self, client_id, path_type, components, timestamp=None, cursor=None): """Retrieves a path info record for a given path.""" if timestamp is None: path_infos = self.ReadPathInfos(client_id, path_t...
[ "def", "ReadPathInfo", "(", "self", ",", "client_id", ",", "path_type", ",", "components", ",", "timestamp", "=", "None", ",", "cursor", "=", "None", ")", ":", "if", "timestamp", "is", "None", ":", "path_infos", "=", "self", ".", "ReadPathInfos", "(", "c...
Retrieves a path info record for a given path.
[ "Retrieves", "a", "path", "info", "record", "for", "a", "given", "path", "." ]
python
train
35.170455
google/neuroglancer
python/neuroglancer/futures.py
https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/futures.py#L23-L41
def future_then_immediate(future, func): """Returns a future that maps the result of `future` by `func`. If `future` succeeds, sets the result of the returned future to `func(future.result())`. If `future` fails or `func` raises an exception, the exception is stored in the returned future. If `future...
[ "def", "future_then_immediate", "(", "future", ",", "func", ")", ":", "result", "=", "concurrent", ".", "futures", ".", "Future", "(", ")", "def", "on_done", "(", "f", ")", ":", "try", ":", "result", ".", "set_result", "(", "func", "(", "f", ".", "re...
Returns a future that maps the result of `future` by `func`. If `future` succeeds, sets the result of the returned future to `func(future.result())`. If `future` fails or `func` raises an exception, the exception is stored in the returned future. If `future` has not yet finished, `func` is invoked by the...
[ "Returns", "a", "future", "that", "maps", "the", "result", "of", "future", "by", "func", "." ]
python
train
38.473684
google/apitools
apitools/base/py/credentials_lib.py
https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/credentials_lib.py#L132-L156
def GetCredentials(package_name, scopes, client_id, client_secret, user_agent, credentials_filename=None, api_key=None, # pylint: disable=unused-argument client=None, # pylint: disable=unused-argument oauth2client_args=None, ...
[ "def", "GetCredentials", "(", "package_name", ",", "scopes", ",", "client_id", ",", "client_secret", ",", "user_agent", ",", "credentials_filename", "=", "None", ",", "api_key", "=", "None", ",", "# pylint: disable=unused-argument", "client", "=", "None", ",", "# ...
Attempt to get credentials, using an oauth dance as the last resort.
[ "Attempt", "to", "get", "credentials", "using", "an", "oauth", "dance", "as", "the", "last", "resort", "." ]
python
train
47.16
cltk/cltk
cltk/phonology/syllabify.py
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/phonology/syllabify.py#L330-L379
def legal_onsets(self, syllables): """ Filters syllable respecting the legality principle :param syllables: str list Example: The method scans for invalid syllable onsets: >>> s = Syllabifier(["i", "u", "y"], ["o", "ø", "e"], ["a"], ["r"], ["l"], ["m", "n"], ["f...
[ "def", "legal_onsets", "(", "self", ",", "syllables", ")", ":", "vowels", "=", "self", ".", "vowels", "for", "i", "in", "range", "(", "1", ",", "len", "(", "syllables", ")", ")", ":", "onset", "=", "\"\"", "for", "letter", "in", "syllables", "[", "...
Filters syllable respecting the legality principle :param syllables: str list Example: The method scans for invalid syllable onsets: >>> s = Syllabifier(["i", "u", "y"], ["o", "ø", "e"], ["a"], ["r"], ["l"], ["m", "n"], ["f", "v", "s", "h"], ["k", "g", "b", "p", "t", "d"]) ...
[ "Filters", "syllable", "respecting", "the", "legality", "principle", ":", "param", "syllables", ":", "str", "list" ]
python
train
27.86
gagneurlab/concise
concise/metrics.py
https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/metrics.py#L126-L134
def cat_acc(y, z): """Classification accuracy for multi-categorical case """ weights = _cat_sample_weights(y) _acc = K.cast(K.equal(K.argmax(y, axis=-1), K.argmax(z, axis=-1)), K.floatx()) _acc = K.sum(_acc * weights) / K.sum(weights) return _acc
[ "def", "cat_acc", "(", "y", ",", "z", ")", ":", "weights", "=", "_cat_sample_weights", "(", "y", ")", "_acc", "=", "K", ".", "cast", "(", "K", ".", "equal", "(", "K", ".", "argmax", "(", "y", ",", "axis", "=", "-", "1", ")", ",", "K", ".", ...
Classification accuracy for multi-categorical case
[ "Classification", "accuracy", "for", "multi", "-", "categorical", "case" ]
python
train
34
syndbg/demonoid-api
demonoid/urls.py
https://github.com/syndbg/demonoid-api/blob/518aa389ac91b5243b92fc19923103f31041a61e/demonoid/urls.py#L100-L110
def update_DOM(self): """ Makes a request and updates `self._DOM`. Worth using only if you manually change `self.base_url` or `self.path`. :return: self :rtype: Url """ response = self.fetch() self._DOM = html.fromstring(response.text) return self
[ "def", "update_DOM", "(", "self", ")", ":", "response", "=", "self", ".", "fetch", "(", ")", "self", ".", "_DOM", "=", "html", ".", "fromstring", "(", "response", ".", "text", ")", "return", "self" ]
Makes a request and updates `self._DOM`. Worth using only if you manually change `self.base_url` or `self.path`. :return: self :rtype: Url
[ "Makes", "a", "request", "and", "updates", "self", ".", "_DOM", ".", "Worth", "using", "only", "if", "you", "manually", "change", "self", ".", "base_url", "or", "self", ".", "path", "." ]
python
train
28.181818
coded-by-hand/mass
env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/index.py
https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/index.py#L59-L87
def _sort_locations(locations): """ Sort locations into "files" (archives) and "urls", and return a pair of lists (files,urls) """ files = [] urls = [] # puts the url for the given file path into the appropriate # list def sort_path(path): ...
[ "def", "_sort_locations", "(", "locations", ")", ":", "files", "=", "[", "]", "urls", "=", "[", "]", "# puts the url for the given file path into the appropriate", "# list", "def", "sort_path", "(", "path", ")", ":", "url", "=", "path_to_url2", "(", "path", ")",...
Sort locations into "files" (archives) and "urls", and return a pair of lists (files,urls)
[ "Sort", "locations", "into", "files", "(", "archives", ")", "and", "urls", "and", "return", "a", "pair", "of", "lists", "(", "files", "urls", ")" ]
python
train
32.689655
Koed00/django-q
django_q/tasks.py
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L469-L479
def run(self): """ Start queueing the tasks to the worker cluster :return: the task id """ self.kwargs['cached'] = self.cached self.kwargs['sync'] = self.sync self.kwargs['broker'] = self.broker self.id = async_iter(self.func, self.args, **self.kwargs) ...
[ "def", "run", "(", "self", ")", ":", "self", ".", "kwargs", "[", "'cached'", "]", "=", "self", ".", "cached", "self", ".", "kwargs", "[", "'sync'", "]", "=", "self", ".", "sync", "self", ".", "kwargs", "[", "'broker'", "]", "=", "self", ".", "bro...
Start queueing the tasks to the worker cluster :return: the task id
[ "Start", "queueing", "the", "tasks", "to", "the", "worker", "cluster", ":", "return", ":", "the", "task", "id" ]
python
train
32.454545
ciena/afkak
afkak/brokerclient.py
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/brokerclient.py#L130-L147
def updateMetadata(self, new): """ Update the metadata stored for this broker. Future connections made to the broker will use the host and port defined in the new metadata. Any existing connection is not dropped, however. :param new: :clas:`afkak.common.Brok...
[ "def", "updateMetadata", "(", "self", ",", "new", ")", ":", "if", "self", ".", "node_id", "!=", "new", ".", "node_id", ":", "raise", "ValueError", "(", "\"Broker metadata {!r} doesn't match node_id={}\"", ".", "format", "(", "new", ",", "self", ".", "node_id",...
Update the metadata stored for this broker. Future connections made to the broker will use the host and port defined in the new metadata. Any existing connection is not dropped, however. :param new: :clas:`afkak.common.BrokerMetadata` with the same node ID as the ...
[ "Update", "the", "metadata", "stored", "for", "this", "broker", "." ]
python
train
34.611111
biolink/ontobio
ontobio/io/gafgpibridge.py
https://github.com/biolink/ontobio/blob/4e512a7831cfe6bc1b32f2c3be2ba41bc5cf7345/ontobio/io/gafgpibridge.py#L21-L43
def convert_association(self, association: Association) -> Entity: """ 'id' is already `join`ed in both the Association and the Entity, so we don't have to worry about what that looks like. We assume it's correct. """ if "header" not in association or association["header"...
[ "def", "convert_association", "(", "self", ",", "association", ":", "Association", ")", "->", "Entity", ":", "if", "\"header\"", "not", "in", "association", "or", "association", "[", "\"header\"", "]", "==", "False", ":", "# print(json.dumps(association, indent=4))"...
'id' is already `join`ed in both the Association and the Entity, so we don't have to worry about what that looks like. We assume it's correct.
[ "id", "is", "already", "join", "ed", "in", "both", "the", "Association", "and", "the", "Entity", "so", "we", "don", "t", "have", "to", "worry", "about", "what", "that", "looks", "like", ".", "We", "assume", "it", "s", "correct", "." ]
python
train
47.521739
lrq3000/pyFileFixity
pyFileFixity/lib/profilers/visual/pympler/tracker.py
https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/pympler/tracker.py#L215-L228
def get_diff(self, ignore=[]): """Get the diff to the last time the state of objects was measured. keyword arguments ignore -- list of objects to ignore """ # ignore this and the caller frame ignore.append(inspect.currentframe()) #PYCHOK change ignore self.o1 = ...
[ "def", "get_diff", "(", "self", ",", "ignore", "=", "[", "]", ")", ":", "# ignore this and the caller frame", "ignore", ".", "append", "(", "inspect", ".", "currentframe", "(", ")", ")", "#PYCHOK change ignore", "self", ".", "o1", "=", "self", ".", "_get_obj...
Get the diff to the last time the state of objects was measured. keyword arguments ignore -- list of objects to ignore
[ "Get", "the", "diff", "to", "the", "last", "time", "the", "state", "of", "objects", "was", "measured", "." ]
python
train
36.714286
Microsoft/nni
tools/nni_cmd/rest_utils.py
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/rest_utils.py#L60-L68
def rest_delete(url, timeout, show_error=False): '''Call rest delete method''' try: response = requests.delete(url, timeout=timeout) return response except Exception as exception: if show_error: print_error(exception) return None
[ "def", "rest_delete", "(", "url", ",", "timeout", ",", "show_error", "=", "False", ")", ":", "try", ":", "response", "=", "requests", ".", "delete", "(", "url", ",", "timeout", "=", "timeout", ")", "return", "response", "except", "Exception", "as", "exce...
Call rest delete method
[ "Call", "rest", "delete", "method" ]
python
train
30.777778
mdsol/rwslib
rwslib/builders/common.py
https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/builders/common.py#L141-L147
def transaction_type(self, value): """Set the TransactionType (with Input Validation)""" if value is not None: if value not in self.ALLOWED_TRANSACTION_TYPES: raise AttributeError('%s transaction_type element must be one of %s not %s' % ( self.__class__.__...
[ "def", "transaction_type", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", ":", "if", "value", "not", "in", "self", ".", "ALLOWED_TRANSACTION_TYPES", ":", "raise", "AttributeError", "(", "'%s transaction_type element must be one of %s not %s...
Set the TransactionType (with Input Validation)
[ "Set", "the", "TransactionType", "(", "with", "Input", "Validation", ")" ]
python
train
58.714286
PyCQA/astroid
astroid/as_string.py
https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/as_string.py#L93-L97
def visit_assert(self, node): """return an astroid.Assert node as string""" if node.fail: return "assert %s, %s" % (node.test.accept(self), node.fail.accept(self)) return "assert %s" % node.test.accept(self)
[ "def", "visit_assert", "(", "self", ",", "node", ")", ":", "if", "node", ".", "fail", ":", "return", "\"assert %s, %s\"", "%", "(", "node", ".", "test", ".", "accept", "(", "self", ")", ",", "node", ".", "fail", ".", "accept", "(", "self", ")", ")"...
return an astroid.Assert node as string
[ "return", "an", "astroid", ".", "Assert", "node", "as", "string" ]
python
train
47.8
marshmallow-code/marshmallow
src/marshmallow/decorators.py
https://github.com/marshmallow-code/marshmallow/blob/a6b6c4151f1fbf16f3774d4052ca2bddf6903750/src/marshmallow/decorators.py#L137-L148
def post_load(fn=None, pass_many=False, pass_original=False): """Register a method to invoke after deserializing an object. The method receives the deserialized data and returns the processed data. By default, receives a single datum at a time, transparently handling the ``many`` argument passed to the...
[ "def", "post_load", "(", "fn", "=", "None", ",", "pass_many", "=", "False", ",", "pass_original", "=", "False", ")", ":", "return", "set_hook", "(", "fn", ",", "(", "POST_LOAD", ",", "pass_many", ")", ",", "pass_original", "=", "pass_original", ")" ]
Register a method to invoke after deserializing an object. The method receives the deserialized data and returns the processed data. By default, receives a single datum at a time, transparently handling the ``many`` argument passed to the Schema. If ``pass_many=True``, the raw data (which may be a coll...
[ "Register", "a", "method", "to", "invoke", "after", "deserializing", "an", "object", ".", "The", "method", "receives", "the", "deserialized", "data", "and", "returns", "the", "processed", "data", "." ]
python
train
53.416667
orbingol/NURBS-Python
geomdl/helpers.py
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/helpers.py#L140-L170
def basis_function(degree, knot_vector, span, knot): """ Computes the non-vanishing basis functions for a single parameter. Implementation of Algorithm A2.2 from The NURBS Book by Piegl & Tiller. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :typ...
[ "def", "basis_function", "(", "degree", ",", "knot_vector", ",", "span", ",", "knot", ")", ":", "left", "=", "[", "0.0", "for", "_", "in", "range", "(", "degree", "+", "1", ")", "]", "right", "=", "[", "0.0", "for", "_", "in", "range", "(", "degr...
Computes the non-vanishing basis functions for a single parameter. Implementation of Algorithm A2.2 from The NURBS Book by Piegl & Tiller. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :param span: knot span, :math:...
[ "Computes", "the", "non", "-", "vanishing", "basis", "functions", "for", "a", "single", "parameter", "." ]
python
train
32.741935
rosenbrockc/fortpy
fortpy/isense/evaluator.py
https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/isense/evaluator.py#L404-L419
def _complete_word(self, symbol, attribute): """Suggests context completions based exclusively on the word preceding the cursor.""" #The cursor is after a %(,\s and the user is looking for a list #of possibilities that is a bit smarter that regular AC. if self.context.el_call in ...
[ "def", "_complete_word", "(", "self", ",", "symbol", ",", "attribute", ")", ":", "#The cursor is after a %(,\\s and the user is looking for a list", "#of possibilities that is a bit smarter that regular AC.", "if", "self", ".", "context", ".", "el_call", "in", "[", "\"sub\"",...
Suggests context completions based exclusively on the word preceding the cursor.
[ "Suggests", "context", "completions", "based", "exclusively", "on", "the", "word", "preceding", "the", "cursor", "." ]
python
train
53.1875
dmlc/gluon-nlp
scripts/bert/bert_qa_dataset.py
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/bert_qa_dataset.py#L56-L86
def preprocess_dataset(dataset, transform, num_workers=8): """Use multiprocessing to perform transform for dataset. Parameters ---------- dataset: dataset-like object Source dataset. transform: callable Transformer function. num_workers: int, default 8 The number of mult...
[ "def", "preprocess_dataset", "(", "dataset", ",", "transform", ",", "num_workers", "=", "8", ")", ":", "worker_fn", "=", "partial", "(", "_worker_fn", ",", "transform", "=", "transform", ")", "start", "=", "time", ".", "time", "(", ")", "pool", "=", "mp"...
Use multiprocessing to perform transform for dataset. Parameters ---------- dataset: dataset-like object Source dataset. transform: callable Transformer function. num_workers: int, default 8 The number of multiprocessing workers to use for data preprocessing.
[ "Use", "multiprocessing", "to", "perform", "transform", "for", "dataset", "." ]
python
train
31
jim-easterbrook/pywws
src/pywws/process.py
https://github.com/jim-easterbrook/pywws/blob/4e4d74cee5a3ac5bf42286feaa251cd2ffcaf02c/src/pywws/process.py#L625-L671
def generate_daily(day_end_hour, use_dst, calib_data, hourly_data, daily_data, process_from): """Generate daily summaries from calibrated and hourly data.""" start = daily_data.before(datetime.max) if start is None: start = datetime.min start = calib_data.after(start + SECOND)...
[ "def", "generate_daily", "(", "day_end_hour", ",", "use_dst", ",", "calib_data", ",", "hourly_data", ",", "daily_data", ",", "process_from", ")", ":", "start", "=", "daily_data", ".", "before", "(", "datetime", ".", "max", ")", "if", "start", "is", "None", ...
Generate daily summaries from calibrated and hourly data.
[ "Generate", "daily", "summaries", "from", "calibrated", "and", "hourly", "data", "." ]
python
train
36.617021
datascopeanalytics/scrubadub
scrubadub/import_magic.py
https://github.com/datascopeanalytics/scrubadub/blob/914bda49a16130b44af43df6a2f84755477c407c/scrubadub/import_magic.py#L16-L23
def _iter_module_subclasses(package, module_name, base_cls): """inspect all modules in this directory for subclasses of inherit from ``base_cls``. inpiration from http://stackoverflow.com/q/1796180/564709 """ module = importlib.import_module('.' + module_name, package) for name, obj in inspect.getme...
[ "def", "_iter_module_subclasses", "(", "package", ",", "module_name", ",", "base_cls", ")", ":", "module", "=", "importlib", ".", "import_module", "(", "'.'", "+", "module_name", ",", "package", ")", "for", "name", ",", "obj", "in", "inspect", ".", "getmembe...
inspect all modules in this directory for subclasses of inherit from ``base_cls``. inpiration from http://stackoverflow.com/q/1796180/564709
[ "inspect", "all", "modules", "in", "this", "directory", "for", "subclasses", "of", "inherit", "from", "base_cls", ".", "inpiration", "from", "http", ":", "//", "stackoverflow", ".", "com", "/", "q", "/", "1796180", "/", "564709" ]
python
train
51.5
opengridcc/opengrid
opengrid/library/regression.py
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/regression.py#L459-L473
def _modeldesc_to_dict(self, md): """Return a string representation of a patsy ModelDesc object""" d = {'lhs_termlist': [md.lhs_termlist[0].factors[0].name()]} rhs_termlist = [] # add other terms, if any for term in md.rhs_termlist[:]: if len(term.factors) == 0: ...
[ "def", "_modeldesc_to_dict", "(", "self", ",", "md", ")", ":", "d", "=", "{", "'lhs_termlist'", ":", "[", "md", ".", "lhs_termlist", "[", "0", "]", ".", "factors", "[", "0", "]", ".", "name", "(", ")", "]", "}", "rhs_termlist", "=", "[", "]", "# ...
Return a string representation of a patsy ModelDesc object
[ "Return", "a", "string", "representation", "of", "a", "patsy", "ModelDesc", "object" ]
python
train
35.533333
Jasily/jasily-python
jasily/format/utils.py
https://github.com/Jasily/jasily-python/blob/1c821a120ebbbbc3c5761f5f1e8a73588059242a/jasily/format/utils.py#L9-L29
def object_to_primitive(obj): ''' convert object to primitive type so we can serialize it to data format like python. all primitive types: dict, list, int, float, bool, str, None ''' if obj is None: return obj if isinstance(obj, (int, float, bool, str)): return obj if isin...
[ "def", "object_to_primitive", "(", "obj", ")", ":", "if", "obj", "is", "None", ":", "return", "obj", "if", "isinstance", "(", "obj", ",", "(", "int", ",", "float", ",", "bool", ",", "str", ")", ")", ":", "return", "obj", "if", "isinstance", "(", "o...
convert object to primitive type so we can serialize it to data format like python. all primitive types: dict, list, int, float, bool, str, None
[ "convert", "object", "to", "primitive", "type", "so", "we", "can", "serialize", "it", "to", "data", "format", "like", "python", "." ]
python
test
29
jameslyons/pycipher
pycipher/util.py
https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/util.py#L7-L14
def ic(ctext): ''' takes ciphertext, calculates index of coincidence.''' counts = ngram_count(ctext,N=1) icval = 0 for k in counts.keys(): icval += counts[k]*(counts[k]-1) icval /= (len(ctext)*(len(ctext)-1)) return icval
[ "def", "ic", "(", "ctext", ")", ":", "counts", "=", "ngram_count", "(", "ctext", ",", "N", "=", "1", ")", "icval", "=", "0", "for", "k", "in", "counts", ".", "keys", "(", ")", ":", "icval", "+=", "counts", "[", "k", "]", "*", "(", "counts", "...
takes ciphertext, calculates index of coincidence.
[ "takes", "ciphertext", "calculates", "index", "of", "coincidence", "." ]
python
train
30.75
SheffieldML/GPy
GPy/models/input_warped_gp.py
https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/models/input_warped_gp.py#L126-L144
def predict(self, Xnew): """Prediction on the new data Parameters ---------- Xnew : array_like, shape = (n_samples, n_features) The test data. Returns ------- mean : array_like, shape = (n_samples, output.dim) Posterior mean at the locati...
[ "def", "predict", "(", "self", ",", "Xnew", ")", ":", "Xnew_warped", "=", "self", ".", "transform_data", "(", "Xnew", ",", "test_data", "=", "True", ")", "mean", ",", "var", "=", "super", "(", "InputWarpedGP", ",", "self", ")", ".", "predict", "(", "...
Prediction on the new data Parameters ---------- Xnew : array_like, shape = (n_samples, n_features) The test data. Returns ------- mean : array_like, shape = (n_samples, output.dim) Posterior mean at the location of Xnew var : array_like...
[ "Prediction", "on", "the", "new", "data" ]
python
train
32.631579
MKLab-ITI/reveal-graph-embedding
reveal_graph_embedding/eps_randomwalk/transition.py
https://github.com/MKLab-ITI/reveal-graph-embedding/blob/eda862687aa5a64b79c6b12de1b4dca6ce986dc8/reveal_graph_embedding/eps_randomwalk/transition.py#L43-L99
def get_natural_random_walk_matrix(adjacency_matrix, make_shared=False): """ Returns the natural random walk transition probability matrix given the adjacency matrix. Input: - A: A sparse matrix that contains the adjacency matrix of the graph. Output: - W: A sparse matrix that contains the natural ra...
[ "def", "get_natural_random_walk_matrix", "(", "adjacency_matrix", ",", "make_shared", "=", "False", ")", ":", "# Turn to sparse.csr_matrix format for faster row access.", "rw_transition", "=", "sparse", ".", "csr_matrix", "(", "adjacency_matrix", ",", "dtype", "=", "np", ...
Returns the natural random walk transition probability matrix given the adjacency matrix. Input: - A: A sparse matrix that contains the adjacency matrix of the graph. Output: - W: A sparse matrix that contains the natural random walk transition probability matrix.
[ "Returns", "the", "natural", "random", "walk", "transition", "probability", "matrix", "given", "the", "adjacency", "matrix", "." ]
python
train
46
flowersteam/explauto
explauto/sensorimotor_model/inverse/inverse.py
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/inverse.py#L53-L73
def _guess_x(self, y_desired, **kwargs): """Choose the relevant neighborhood to feed the inverse model, based on the minimum spread of the corresponding neighborhood in S. for each (x, y) with y neighbor of y_desired, 1. find the neighborhood of x, (xi, yi)_k. 2. compute ...
[ "def", "_guess_x", "(", "self", ",", "y_desired", ",", "*", "*", "kwargs", ")", ":", "k", "=", "kwargs", ".", "get", "(", "'k'", ",", "self", ".", "k", ")", "_", ",", "indexes", "=", "self", ".", "fmodel", ".", "dataset", ".", "nn_y", "(", "y_d...
Choose the relevant neighborhood to feed the inverse model, based on the minimum spread of the corresponding neighborhood in S. for each (x, y) with y neighbor of y_desired, 1. find the neighborhood of x, (xi, yi)_k. 2. compute the standart deviation of the error between yi and y...
[ "Choose", "the", "relevant", "neighborhood", "to", "feed", "the", "inverse", "model", "based", "on", "the", "minimum", "spread", "of", "the", "corresponding", "neighborhood", "in", "S", ".", "for", "each", "(", "x", "y", ")", "with", "y", "neighbor", "of",...
python
train
49
cloud-custodian/cloud-custodian
c7n/mu.py
https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/mu.py#L168-L182
def add_py_file(self, src, dest=None): """This is a special case of :py:meth:`add_file` that helps for adding a ``py`` when a ``pyc`` may be present as well. So for example, if ``__file__`` is ``foo.pyc`` and you do: .. code-block:: python archive.add_py_file(__file__) ...
[ "def", "add_py_file", "(", "self", ",", "src", ",", "dest", "=", "None", ")", ":", "src", "=", "src", "[", ":", "-", "1", "]", "if", "src", ".", "endswith", "(", "'.pyc'", ")", "else", "src", "self", ".", "add_file", "(", "src", ",", "dest", ")...
This is a special case of :py:meth:`add_file` that helps for adding a ``py`` when a ``pyc`` may be present as well. So for example, if ``__file__`` is ``foo.pyc`` and you do: .. code-block:: python archive.add_py_file(__file__) then this method will add ``foo.py`` instead if...
[ "This", "is", "a", "special", "case", "of", ":", "py", ":", "meth", ":", "add_file", "that", "helps", "for", "adding", "a", "py", "when", "a", "pyc", "may", "be", "present", "as", "well", ".", "So", "for", "example", "if", "__file__", "is", "foo", ...
python
train
34.266667
python-openxml/python-docx
docx/parts/document.py
https://github.com/python-openxml/python-docx/blob/6756f6cd145511d3eb6d1d188beea391b1ddfd53/docx/parts/document.py#L27-L31
def add_footer_part(self): """Return (footer_part, rId) pair for newly-created footer part.""" footer_part = FooterPart.new(self.package) rId = self.relate_to(footer_part, RT.FOOTER) return footer_part, rId
[ "def", "add_footer_part", "(", "self", ")", ":", "footer_part", "=", "FooterPart", ".", "new", "(", "self", ".", "package", ")", "rId", "=", "self", ".", "relate_to", "(", "footer_part", ",", "RT", ".", "FOOTER", ")", "return", "footer_part", ",", "rId" ...
Return (footer_part, rId) pair for newly-created footer part.
[ "Return", "(", "footer_part", "rId", ")", "pair", "for", "newly", "-", "created", "footer", "part", "." ]
python
train
46.8
crunchyroll/ef-open
efopen/ef_aws_resolver.py
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_aws_resolver.py#L483-L500
def ec2_route_table_main_route_table_id(self, lookup, default=None): """ Args: lookup: the friendly name of the VPC whose main route table we are looking up default: the optional value to return if lookup failed; returns None if not set Returns: the ID of the main route table of the named ...
[ "def", "ec2_route_table_main_route_table_id", "(", "self", ",", "lookup", ",", "default", "=", "None", ")", ":", "vpc_id", "=", "self", ".", "ec2_vpc_vpc_id", "(", "lookup", ")", "if", "vpc_id", "is", "None", ":", "return", "default", "route_table", "=", "EF...
Args: lookup: the friendly name of the VPC whose main route table we are looking up default: the optional value to return if lookup failed; returns None if not set Returns: the ID of the main route table of the named VPC, or default if no match/multiple matches found
[ "Args", ":", "lookup", ":", "the", "friendly", "name", "of", "the", "VPC", "whose", "main", "route", "table", "we", "are", "looking", "up", "default", ":", "the", "optional", "value", "to", "return", "if", "lookup", "failed", ";", "returns", "None", "if"...
python
train
42.333333
not-na/peng3d
peng3d/actor/player.py
https://github.com/not-na/peng3d/blob/1151be665b26cc8a479f6307086ba919e4d32d85/peng3d/actor/player.py#L51-L65
def registerEventHandlers(self): """ Registers needed keybinds and schedules the :py:meth:`update` Method. You can control what keybinds are used via the :confval:`controls.controls.forward` etc. Configuration Values. """ # Forward self.peng.keybinds.add(self.pen...
[ "def", "registerEventHandlers", "(", "self", ")", ":", "# Forward", "self", ".", "peng", ".", "keybinds", ".", "add", "(", "self", ".", "peng", ".", "cfg", "[", "\"controls.controls.forward\"", "]", ",", "\"peng3d:actor.%s.player.controls.forward\"", "%", "self", ...
Registers needed keybinds and schedules the :py:meth:`update` Method. You can control what keybinds are used via the :confval:`controls.controls.forward` etc. Configuration Values.
[ "Registers", "needed", "keybinds", "and", "schedules", "the", ":", "py", ":", "meth", ":", "update", "Method", ".", "You", "can", "control", "what", "keybinds", "are", "used", "via", "the", ":", "confval", ":", "controls", ".", "controls", ".", "forward", ...
python
test
68.8
libtcod/python-tcod
tcod/libtcodpy.py
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L2263-L2285
def heightmap_set_value(hm: np.ndarray, x: int, y: int, value: float) -> None: """Set the value of a point on a heightmap. .. deprecated:: 2.0 `hm` is a NumPy array, so values should be assigned to it directly. """ if hm.flags["C_CONTIGUOUS"]: warnings.warn( "Assign to this ...
[ "def", "heightmap_set_value", "(", "hm", ":", "np", ".", "ndarray", ",", "x", ":", "int", ",", "y", ":", "int", ",", "value", ":", "float", ")", "->", "None", ":", "if", "hm", ".", "flags", "[", "\"C_CONTIGUOUS\"", "]", ":", "warnings", ".", "warn"...
Set the value of a point on a heightmap. .. deprecated:: 2.0 `hm` is a NumPy array, so values should be assigned to it directly.
[ "Set", "the", "value", "of", "a", "point", "on", "a", "heightmap", "." ]
python
train
32.347826
Groundworkstech/pybfd
setup.py
https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/setup.py#L267-L273
def _darwin_current_arch(self): """Add Mac OS X support.""" if sys.platform == "darwin": if sys.maxsize > 2 ** 32: # 64bits. return platform.mac_ver()[2] # Both Darwin and Python are 64bits. else: # Python 32 bits return platform.processor()
[ "def", "_darwin_current_arch", "(", "self", ")", ":", "if", "sys", ".", "platform", "==", "\"darwin\"", ":", "if", "sys", ".", "maxsize", ">", "2", "**", "32", ":", "# 64bits.", "return", "platform", ".", "mac_ver", "(", ")", "[", "2", "]", "# Both Dar...
Add Mac OS X support.
[ "Add", "Mac", "OS", "X", "support", "." ]
python
train
43.857143
Devoxin/Lavalink.py
lavalink/WebSocket.py
https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/lavalink/WebSocket.py#L75-L91
async def _attempt_reconnect(self): """ Attempts to reconnect to the Lavalink server. Returns ------- bool ``True`` if the reconnection attempt was successful. """ log.info('Connection closed; attempting to reconnect in 30 seconds') fo...
[ "async", "def", "_attempt_reconnect", "(", "self", ")", ":", "log", ".", "info", "(", "'Connection closed; attempting to reconnect in 30 seconds'", ")", "for", "a", "in", "range", "(", "0", ",", "self", ".", "_ws_retry", ")", ":", "await", "asyncio", ".", "sle...
Attempts to reconnect to the Lavalink server. Returns ------- bool ``True`` if the reconnection attempt was successful.
[ "Attempts", "to", "reconnect", "to", "the", "Lavalink", "server", ".", "Returns", "-------", "bool", "True", "if", "the", "reconnection", "attempt", "was", "successful", "." ]
python
valid
32.882353
daknuett/py_register_machine2
core/parts.py
https://github.com/daknuett/py_register_machine2/blob/599c53cd7576297d0d7a53344ed5d9aa98acc751/core/parts.py#L193-L207
def getuvalue(self): """ .. _getuvalue: Get the unsigned value of the Integer, truncate it and handle Overflows. """ bitset = [0] * self.width zero = [1] * self.width for shift in range(self.width): bitset[shift] = (self._value & (1 << shift)) >> shift if(self._sign): bitset = bitsetxor(zero, bit...
[ "def", "getuvalue", "(", "self", ")", ":", "bitset", "=", "[", "0", "]", "*", "self", ".", "width", "zero", "=", "[", "1", "]", "*", "self", ".", "width", "for", "shift", "in", "range", "(", "self", ".", "width", ")", ":", "bitset", "[", "shift...
.. _getuvalue: Get the unsigned value of the Integer, truncate it and handle Overflows.
[ "..", "_getuvalue", ":" ]
python
train
26.533333
ilblackdragon/django-misc
misc/admin.py
https://github.com/ilblackdragon/django-misc/blob/0accd2dc97de656a1c9e275be81e817f78a2eb9d/misc/admin.py#L26-L52
def foreign_field_func(field_name, short_description=None, admin_order_field=None): """ Allow to use ForeignKey field attributes at list_display in a simple way. Example: from misc.admin import foreign_field_func as ff class SongAdmin(admin.ModelAdmin): ...
[ "def", "foreign_field_func", "(", "field_name", ",", "short_description", "=", "None", ",", "admin_order_field", "=", "None", ")", ":", "def", "accessor", "(", "obj", ")", ":", "val", "=", "obj", "for", "part", "in", "field_name", ".", "split", "(", "'__'"...
Allow to use ForeignKey field attributes at list_display in a simple way. Example: from misc.admin import foreign_field_func as ff class SongAdmin(admin.ModelAdmin): ...
[ "Allow", "to", "use", "ForeignKey", "field", "attributes", "at", "list_display", "in", "a", "simple", "way", "." ]
python
train
36.222222
woolfson-group/isambard
isambard/optimisation/base_evo_opt.py
https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/optimisation/base_evo_opt.py#L384-L405
def best_model(self): """Rebuilds the top scoring model from an optimisation. Returns ------- model: AMPAL Returns an AMPAL model of the top scoring parameters. Raises ------ AttributeError Raises a name error if the optimiser has not bee...
[ "def", "best_model", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'halloffame'", ")", ":", "raise", "AttributeError", "(", "'No best model found, have you ran the optimiser?'", ")", "model", "=", "self", ".", "build_fn", "(", "(", "self", ...
Rebuilds the top scoring model from an optimisation. Returns ------- model: AMPAL Returns an AMPAL model of the top scoring parameters. Raises ------ AttributeError Raises a name error if the optimiser has not been run.
[ "Rebuilds", "the", "top", "scoring", "model", "from", "an", "optimisation", "." ]
python
train
29.409091
rwl/pylon
pylon/generator.py
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/generator.py#L278-L308
def poly_to_pwl(self, n_points=4): """ Sets the piece-wise linear cost attribute, converting the polynomial cost variable by evaluating at zero and then at n_points evenly spaced points between p_min and p_max. """ assert self.pcost_model == POLYNOMIAL p_min = self.p_min ...
[ "def", "poly_to_pwl", "(", "self", ",", "n_points", "=", "4", ")", ":", "assert", "self", ".", "pcost_model", "==", "POLYNOMIAL", "p_min", "=", "self", ".", "p_min", "p_max", "=", "self", ".", "p_max", "p_cost", "=", "[", "]", "if", "p_min", ">", "0....
Sets the piece-wise linear cost attribute, converting the polynomial cost variable by evaluating at zero and then at n_points evenly spaced points between p_min and p_max.
[ "Sets", "the", "piece", "-", "wise", "linear", "cost", "attribute", "converting", "the", "polynomial", "cost", "variable", "by", "evaluating", "at", "zero", "and", "then", "at", "n_points", "evenly", "spaced", "points", "between", "p_min", "and", "p_max", "." ...
python
train
30.225806
apple/turicreate
deps/src/libxml2-2.9.1/python/libxml2.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L7733-L7744
def xpathNextPrecedingSibling(self, cur): """Traversal function for the "preceding-sibling" direction The preceding-sibling axis contains the preceding siblings of the context node in reverse document order; the first preceding sibling is first on the axis; the sibling p...
[ "def", "xpathNextPrecedingSibling", "(", "self", ",", "cur", ")", ":", "if", "cur", "is", "None", ":", "cur__o", "=", "None", "else", ":", "cur__o", "=", "cur", ".", "_o", "ret", "=", "libxml2mod", ".", "xmlXPathNextPrecedingSibling", "(", "self", ".", "...
Traversal function for the "preceding-sibling" direction The preceding-sibling axis contains the preceding siblings of the context node in reverse document order; the first preceding sibling is first on the axis; the sibling preceding that node is the second on the axis and so o...
[ "Traversal", "function", "for", "the", "preceding", "-", "sibling", "direction", "The", "preceding", "-", "sibling", "axis", "contains", "the", "preceding", "siblings", "of", "the", "context", "node", "in", "reverse", "document", "order", ";", "the", "first", ...
python
train
53.583333
kylef/maintain
maintain/release/aggregate.py
https://github.com/kylef/maintain/blob/4b60e6c52accb4a7faf0d7255a7079087d3ecee0/maintain/release/aggregate.py#L38-L61
def detected_releasers(cls, config): """ Returns all of the releasers that are compatible with the project. """ def get_config(releaser): if config: return config.get(releaser.config_name(), {}) return {} releasers = [] for rele...
[ "def", "detected_releasers", "(", "cls", ",", "config", ")", ":", "def", "get_config", "(", "releaser", ")", ":", "if", "config", ":", "return", "config", ".", "get", "(", "releaser", ".", "config_name", "(", ")", ",", "{", "}", ")", "return", "{", "...
Returns all of the releasers that are compatible with the project.
[ "Returns", "all", "of", "the", "releasers", "that", "are", "compatible", "with", "the", "project", "." ]
python
train
27.833333
pip-services3-python/pip-services3-components-python
pip_services3_components/count/CompositeCounters.py
https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/count/CompositeCounters.py#L123-L132
def timestamp(self, name, value): """ Records the given timestamp. :param name: a counter name of Timestamp type. :param value: a timestamp to record. """ for counter in self._counters: counter.timestamp(name, value)
[ "def", "timestamp", "(", "self", ",", "name", ",", "value", ")", ":", "for", "counter", "in", "self", ".", "_counters", ":", "counter", ".", "timestamp", "(", "name", ",", "value", ")" ]
Records the given timestamp. :param name: a counter name of Timestamp type. :param value: a timestamp to record.
[ "Records", "the", "given", "timestamp", "." ]
python
train
26.9
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_misc.py
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_misc.py#L242-L260
def cmd_oreoled(self, args): '''send LED pattern as override, using OreoLED conventions''' if len(args) < 4: print("Usage: oreoled LEDNUM RED GREEN BLUE <RATE>") return lednum = int(args[0]) pattern = [0] * 24 pattern[0] = ord('R') pattern[1] = ord...
[ "def", "cmd_oreoled", "(", "self", ",", "args", ")", ":", "if", "len", "(", "args", ")", "<", "4", ":", "print", "(", "\"Usage: oreoled LEDNUM RED GREEN BLUE <RATE>\"", ")", "return", "lednum", "=", "int", "(", "args", "[", "0", "]", ")", "pattern", "=",...
send LED pattern as override, using OreoLED conventions
[ "send", "LED", "pattern", "as", "override", "using", "OreoLED", "conventions" ]
python
train
37.368421
django-extensions/django-extensions
django_extensions/management/commands/pipchecker.py
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/pipchecker.py#L166-L295
def check_github(self): """ If the requirement is frozen to a github url, check for new commits. API Tokens ---------- For more than 50 github api calls per hour, pipchecker requires authentication with the github api by settings the environemnt variable ``GITHUB...
[ "def", "check_github", "(", "self", ")", ":", "for", "name", ",", "req", "in", "list", "(", "self", ".", "reqs", ".", "items", "(", ")", ")", ":", "req_url", "=", "req", "[", "\"url\"", "]", "if", "not", "req_url", ":", "continue", "req_url", "=", ...
If the requirement is frozen to a github url, check for new commits. API Tokens ---------- For more than 50 github api calls per hour, pipchecker requires authentication with the github api by settings the environemnt variable ``GITHUB_API_TOKEN`` or setting the command flag ...
[ "If", "the", "requirement", "is", "frozen", "to", "a", "github", "url", "check", "for", "new", "commits", "." ]
python
train
47.1
Jajcus/pyxmpp2
pyxmpp2/streamsasl.py
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/streamsasl.py#L112-L137
def handle_stream_features(self, stream, features): """Process incoming <stream:features/> element. [initiating entity only] """ element = features.find(MECHANISMS_TAG) self.peer_sasl_mechanisms = [] if element is None: return None for sub in element:...
[ "def", "handle_stream_features", "(", "self", ",", "stream", ",", "features", ")", ":", "element", "=", "features", ".", "find", "(", "MECHANISMS_TAG", ")", "self", ".", "peer_sasl_mechanisms", "=", "[", "]", "if", "element", "is", "None", ":", "return", "...
Process incoming <stream:features/> element. [initiating entity only]
[ "Process", "incoming", "<stream", ":", "features", "/", ">", "element", "." ]
python
valid
35.923077
nugget/python-insteonplm
insteonplm/states/onOff.py
https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/states/onOff.py#L85-L177
def _register_messages(self): """Register messages to listen for.""" template_on_group = StandardReceive.template( commandtuple=COMMAND_LIGHT_ON_0X11_NONE, address=self._address, target=bytearray([0x00, 0x00, self._group]), flags=MessageFlags.template(MESS...
[ "def", "_register_messages", "(", "self", ")", ":", "template_on_group", "=", "StandardReceive", ".", "template", "(", "commandtuple", "=", "COMMAND_LIGHT_ON_0X11_NONE", ",", "address", "=", "self", ".", "_address", ",", "target", "=", "bytearray", "(", "[", "0x...
Register messages to listen for.
[ "Register", "messages", "to", "listen", "for", "." ]
python
train
52.763441
reorx/torext
torext/app.py
https://github.com/reorx/torext/blob/84c4300ebc7fab0dbd11cf8b020bc7d4d1570171/torext/app.py#L266-L325
def command_line_config(self): """ settings.py is the basis if wants to change them by command line arguments, the existing option will be transformed to the value type in settings.py the unexisting option will be treated as string by default, and transform to certain ty...
[ "def", "command_line_config", "(", "self", ")", ":", "args", "=", "sys", ".", "argv", "[", "1", ":", "]", "args_dict", "=", "{", "}", "existed_keys", "=", "[", "]", "new_keys", "=", "[", "]", "for", "t", "in", "args", ":", "if", "not", "t", ".", ...
settings.py is the basis if wants to change them by command line arguments, the existing option will be transformed to the value type in settings.py the unexisting option will be treated as string by default, and transform to certain type if `!<type>` was added after the value. ...
[ "settings", ".", "py", "is", "the", "basis" ]
python
train
33.95
CalebBell/ht
ht/hx.py
https://github.com/CalebBell/ht/blob/3097ef9524c4cf0068ad453c17b10ec9ce551eee/ht/hx.py#L5661-L5877
def Ntubes_Phadkeb(DBundle, Do, pitch, Ntp, angle=30): r'''Using tabulated values and correction factors for number of passes, the highly accurate method of [1]_ is used to obtain the tube count of a given tube bundle outer diameter for a given tube size and pitch. Parameters ---------- DBundle...
[ "def", "Ntubes_Phadkeb", "(", "DBundle", ",", "Do", ",", "pitch", ",", "Ntp", ",", "angle", "=", "30", ")", ":", "if", "DBundle", "<=", "Do", "*", "Ntp", ":", "return", "0", "if", "Ntp", "==", "6", ":", "e", "=", "0.265", "elif", "Ntp", "==", "...
r'''Using tabulated values and correction factors for number of passes, the highly accurate method of [1]_ is used to obtain the tube count of a given tube bundle outer diameter for a given tube size and pitch. Parameters ---------- DBundle : float Outer diameter of tube bundle, [m] Do ...
[ "r", "Using", "tabulated", "values", "and", "correction", "factors", "for", "number", "of", "passes", "the", "highly", "accurate", "method", "of", "[", "1", "]", "_", "is", "used", "to", "obtain", "the", "tube", "count", "of", "a", "given", "tube", "bund...
python
train
30.889401
tensorflow/tensor2tensor
tensor2tensor/trax/layers/core.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/core.py#L415-L429
def Dropout(x, params, rate=0.0, mode='train', rng=None, **kwargs): """Layer construction function for a dropout layer with given rate.""" del params, kwargs if rng is None: msg = ('Dropout layer requires apply_fun to be called with a rng keyword ' 'argument. That is, instead of `Dropout(params, in...
[ "def", "Dropout", "(", "x", ",", "params", ",", "rate", "=", "0.0", ",", "mode", "=", "'train'", ",", "rng", "=", "None", ",", "*", "*", "kwargs", ")", ":", "del", "params", ",", "kwargs", "if", "rng", "is", "None", ":", "msg", "=", "(", "'Drop...
Layer construction function for a dropout layer with given rate.
[ "Layer", "construction", "function", "for", "a", "dropout", "layer", "with", "given", "rate", "." ]
python
train
44
agile-geoscience/striplog
striplog/striplog.py
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/striplog.py#L1845-L1867
def intersect(self, other): """ Makes a striplog of all intersections. Args: Striplog. The striplog instance to intersect with. Returns: Striplog. The result of the intersection. """ if not isinstance(other, self.__class__): m = "You ...
[ "def", "intersect", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "self", ".", "__class__", ")", ":", "m", "=", "\"You can only intersect striplogs with each other.\"", "raise", "StriplogError", "(", "m", ")", "result", "="...
Makes a striplog of all intersections. Args: Striplog. The striplog instance to intersect with. Returns: Striplog. The result of the intersection.
[ "Makes", "a", "striplog", "of", "all", "intersections", "." ]
python
test
29.173913
ryanjdillon/pyotelem
pyotelem/utils.py
https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/utils.py#L73-L106
def rm_regions(a, b, a_start_ind, a_stop_ind): '''Remove contiguous regions in `a` before region `b` Boolean arrays `a` and `b` should have alternating occuances of regions of `True` values. This routine removes additional contiguous regions in `a` that occur before a complimentary region in `b` has oc...
[ "def", "rm_regions", "(", "a", ",", "b", ",", "a_start_ind", ",", "a_stop_ind", ")", ":", "import", "numpy", "for", "i", "in", "range", "(", "len", "(", "a_stop_ind", ")", ")", ":", "next_a_start", "=", "numpy", ".", "argmax", "(", "a", "[", "a_stop_...
Remove contiguous regions in `a` before region `b` Boolean arrays `a` and `b` should have alternating occuances of regions of `True` values. This routine removes additional contiguous regions in `a` that occur before a complimentary region in `b` has occured Args ---- a: ndarray Boolea...
[ "Remove", "contiguous", "regions", "in", "a", "before", "region", "b" ]
python
train
30.264706
mcs07/ChemDataExtractor
chemdataextractor/parse/actions.py
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/parse/actions.py#L33-L41
def join(tokens, start, result): """Join tokens into a single string with spaces between.""" texts = [] if len(result) > 0: for e in result: for child in e.iter(): if child.text is not None: texts.append(child.text) return [E(result[0].tag, ' '...
[ "def", "join", "(", "tokens", ",", "start", ",", "result", ")", ":", "texts", "=", "[", "]", "if", "len", "(", "result", ")", ">", "0", ":", "for", "e", "in", "result", ":", "for", "child", "in", "e", ".", "iter", "(", ")", ":", "if", "child"...
Join tokens into a single string with spaces between.
[ "Join", "tokens", "into", "a", "single", "string", "with", "spaces", "between", "." ]
python
train
36.222222
The-Politico/politico-civic-election
election/models/election.py
https://github.com/The-Politico/politico-civic-election/blob/44c6872c419909df616e997e1990c4d295b25eda/election/models/election.py#L128-L138
def get_electoral_votes(self): """ Get all electoral votes for all candidates in this election. """ candidate_elections = CandidateElection.objects.filter(election=self) electoral_votes = None for ce in candidate_elections: electoral_votes = electoral_votes |...
[ "def", "get_electoral_votes", "(", "self", ")", ":", "candidate_elections", "=", "CandidateElection", ".", "objects", ".", "filter", "(", "election", "=", "self", ")", "electoral_votes", "=", "None", "for", "ce", "in", "candidate_elections", ":", "electoral_votes"...
Get all electoral votes for all candidates in this election.
[ "Get", "all", "electoral", "votes", "for", "all", "candidates", "in", "this", "election", "." ]
python
train
33.363636
openid/JWTConnect-Python-OidcService
src/oidcservice/oauth2/provider_info_discovery.py
https://github.com/openid/JWTConnect-Python-OidcService/blob/759ab7adef30a7e3b9d75475e2971433b9613788/src/oidcservice/oauth2/provider_info_discovery.py#L54-L129
def _update_service_context(self, resp, **kwargs): """ Deal with Provider Config Response. Based on the provider info response a set of parameters in different places needs to be set. :param resp: The provider info response :param service_context: Information collected/used by s...
[ "def", "_update_service_context", "(", "self", ",", "resp", ",", "*", "*", "kwargs", ")", ":", "issuer", "=", "self", ".", "service_context", ".", "issuer", "# Verify that the issuer value received is the same as the", "# url that was used as service endpoint (without the .we...
Deal with Provider Config Response. Based on the provider info response a set of parameters in different places needs to be set. :param resp: The provider info response :param service_context: Information collected/used by services
[ "Deal", "with", "Provider", "Config", "Response", ".", "Based", "on", "the", "provider", "info", "response", "a", "set", "of", "parameters", "in", "different", "places", "needs", "to", "be", "set", "." ]
python
train
40.684211
Nic30/hwt
hwt/hdl/types/bitValFunctions.py
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/hdl/types/bitValFunctions.py#L91-L144
def bitsCmp(self, other, op, evalFn=None): """ :attention: If other is Bool signal convert this to bool (not ideal, due VHDL event operator) """ other = toHVal(other) t = self._dtype ot = other._dtype iamVal = isinstance(self, Value) otherIsVal = isinstance(other, Value) if...
[ "def", "bitsCmp", "(", "self", ",", "other", ",", "op", ",", "evalFn", "=", "None", ")", ":", "other", "=", "toHVal", "(", "other", ")", "t", "=", "self", ".", "_dtype", "ot", "=", "other", ".", "_dtype", "iamVal", "=", "isinstance", "(", "self", ...
:attention: If other is Bool signal convert this to bool (not ideal, due VHDL event operator)
[ ":", "attention", ":", "If", "other", "is", "Bool", "signal", "convert", "this", "to", "bool", "(", "not", "ideal", "due", "VHDL", "event", "operator", ")" ]
python
test
29.092593
idlesign/torrentool
torrentool/torrent.py
https://github.com/idlesign/torrentool/blob/78c474c2ecddbad2e3287b390ac8a043957f3563/torrentool/torrent.py#L428-L436
def from_file(cls, filepath): """Alternative constructor to get Torrent object from file. :param str filepath: :rtype: Torrent """ torrent = cls(Bencode.read_file(filepath)) torrent._filepath = filepath return torrent
[ "def", "from_file", "(", "cls", ",", "filepath", ")", ":", "torrent", "=", "cls", "(", "Bencode", ".", "read_file", "(", "filepath", ")", ")", "torrent", ".", "_filepath", "=", "filepath", "return", "torrent" ]
Alternative constructor to get Torrent object from file. :param str filepath: :rtype: Torrent
[ "Alternative", "constructor", "to", "get", "Torrent", "object", "from", "file", "." ]
python
train
29.555556
kyuupichan/aiorpcX
aiorpcx/session.py
https://github.com/kyuupichan/aiorpcX/blob/707c989ed1c67ac9a40cd20b0161b1ce1f4d7db0/aiorpcx/session.py#L555-L591
async def _throttled_request(self, request): '''Process a single request, respecting the concurrency limit.''' disconnect = False try: timeout = self.processing_timeout async with timeout_after(timeout): async with self._incoming_concurrency: ...
[ "async", "def", "_throttled_request", "(", "self", ",", "request", ")", ":", "disconnect", "=", "False", "try", ":", "timeout", "=", "self", ".", "processing_timeout", "async", "with", "timeout_after", "(", "timeout", ")", ":", "async", "with", "self", ".", ...
Process a single request, respecting the concurrency limit.
[ "Process", "a", "single", "request", "respecting", "the", "concurrency", "limit", "." ]
python
train
42.864865
szastupov/aiotg
aiotg/bot.py
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L198-L222
def run_webhook(self, webhook_url, **options): """ Convenience method for running bots in webhook mode :Example: >>> if __name__ == '__main__': >>> bot.run_webhook(webhook_url="https://yourserver.com/webhooktoken") Additional documentation on https://core.telegram....
[ "def", "run_webhook", "(", "self", ",", "webhook_url", ",", "*", "*", "options", ")", ":", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "loop", ".", "run_until_complete", "(", "self", ".", "set_webhook", "(", "webhook_url", ",", "*", "*", "op...
Convenience method for running bots in webhook mode :Example: >>> if __name__ == '__main__': >>> bot.run_webhook(webhook_url="https://yourserver.com/webhooktoken") Additional documentation on https://core.telegram.org/bots/api#setwebhook
[ "Convenience", "method", "for", "running", "bots", "in", "webhook", "mode" ]
python
train
36.16
wummel/linkchecker
third_party/dnspython/dns/renderer.py
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/third_party/dnspython/dns/renderer.py#L159-L178
def add_rrset(self, section, rrset, **kw): """Add the rrset to the specified section. Any keyword arguments are passed on to the rdataset's to_wire() routine. @param section: the section @type section: int @param rrset: the rrset @type rrset: dns.rrset.RRset obj...
[ "def", "add_rrset", "(", "self", ",", "section", ",", "rrset", ",", "*", "*", "kw", ")", ":", "self", ".", "_set_section", "(", "section", ")", "before", "=", "self", ".", "output", ".", "tell", "(", ")", "n", "=", "rrset", ".", "to_wire", "(", "...
Add the rrset to the specified section. Any keyword arguments are passed on to the rdataset's to_wire() routine. @param section: the section @type section: int @param rrset: the rrset @type rrset: dns.rrset.RRset object
[ "Add", "the", "rrset", "to", "the", "specified", "section", "." ]
python
train
31.95
google/grr
grr/client_builder/grr_response_client_builder/builders/windows.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client_builder/grr_response_client_builder/builders/windows.py#L39-L82
def EnumMissingModules(): """Enumerate all modules which match the patterns MODULE_PATTERNS. PyInstaller often fails to locate all dlls which are required at runtime. We import all the client modules here, we simply introspect all the modules we have loaded in our current running process, and all the ones ma...
[ "def", "EnumMissingModules", "(", ")", ":", "module_handle", "=", "ctypes", ".", "c_ulong", "(", ")", "count", "=", "ctypes", ".", "c_ulong", "(", ")", "process_handle", "=", "ctypes", ".", "windll", ".", "kernel32", ".", "OpenProcess", "(", "PROCESS_QUERY_I...
Enumerate all modules which match the patterns MODULE_PATTERNS. PyInstaller often fails to locate all dlls which are required at runtime. We import all the client modules here, we simply introspect all the modules we have loaded in our current running process, and all the ones matching the patterns are copied ...
[ "Enumerate", "all", "modules", "which", "match", "the", "patterns", "MODULE_PATTERNS", "." ]
python
train
38.409091
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/crash.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/crash.py#L878-L898
def __is_block_data_move(self): """ Private method to tell if the instruction pointed to by the program counter is a block data move instruction. Currently only works for x86 and amd64 architectures. """ block_data_move_instructions = ('movs', 'stos', 'lods') isB...
[ "def", "__is_block_data_move", "(", "self", ")", ":", "block_data_move_instructions", "=", "(", "'movs'", ",", "'stos'", ",", "'lods'", ")", "isBlockDataMove", "=", "False", "instruction", "=", "None", "if", "self", ".", "pc", "is", "not", "None", "and", "se...
Private method to tell if the instruction pointed to by the program counter is a block data move instruction. Currently only works for x86 and amd64 architectures.
[ "Private", "method", "to", "tell", "if", "the", "instruction", "pointed", "to", "by", "the", "program", "counter", "is", "a", "block", "data", "move", "instruction", "." ]
python
train
37.285714
saltstack/salt
salt/states/linux_acl.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/linux_acl.py#L222-L307
def absent(name, acl_type, acl_name='', perms='', recurse=False): ''' Ensure a Linux ACL does not exist name The acl path acl_type The type of the acl is used for, it can be 'user' or 'group' acl_names The user or group perms Remove the permissions eg.: rwx ...
[ "def", "absent", "(", "name", ",", "acl_type", ",", "acl_name", "=", "''", ",", "perms", "=", "''", ",", "recurse", "=", "False", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'changes'", ":", "{", "}", ","...
Ensure a Linux ACL does not exist name The acl path acl_type The type of the acl is used for, it can be 'user' or 'group' acl_names The user or group perms Remove the permissions eg.: rwx recurse Set the permissions recursive in the path
[ "Ensure", "a", "Linux", "ACL", "does", "not", "exist" ]
python
train
30.023256
ebroecker/canmatrix
src/canmatrix/formats/arxml.py
https://github.com/ebroecker/canmatrix/blob/d6150b7a648350f051a11c431e9628308c8d5593/src/canmatrix/formats/arxml.py#L834-L846
def get_cached_element_by_path(data_tree, path): # type: (ArTree, str) -> typing.Optional[_Element] """Get element from ArTree by path.""" if not isinstance(data_tree, ArTree): logger.warning("%s not called with ArTree, return None", get_cached_element_by_path.__name__) return None ptr =...
[ "def", "get_cached_element_by_path", "(", "data_tree", ",", "path", ")", ":", "# type: (ArTree, str) -> typing.Optional[_Element]", "if", "not", "isinstance", "(", "data_tree", ",", "ArTree", ")", ":", "logger", ".", "warning", "(", "\"%s not called with ArTree, return No...
Get element from ArTree by path.
[ "Get", "element", "from", "ArTree", "by", "path", "." ]
python
train
38.923077
gem/oq-engine
openquake/hmtk/seismicity/catalogue.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/catalogue.py#L499-L529
def get_magnitude_time_distribution(self, magnitude_bins, time_bins, normalisation=False, bootstrap=None): ''' Returns a 2-D histogram indicating the number of earthquakes in a set of time-magnitude bins. Time is in decimal years! :param numpy.nda...
[ "def", "get_magnitude_time_distribution", "(", "self", ",", "magnitude_bins", ",", "time_bins", ",", "normalisation", "=", "False", ",", "bootstrap", "=", "None", ")", ":", "return", "bootstrap_histogram_2D", "(", "self", ".", "get_decimal_time", "(", ")", ",", ...
Returns a 2-D histogram indicating the number of earthquakes in a set of time-magnitude bins. Time is in decimal years! :param numpy.ndarray magnitude_bins: Bin edges for the magnitudes :param numpy.ndarray time_bins: Bin edges for the times :param bool normal...
[ "Returns", "a", "2", "-", "D", "histogram", "indicating", "the", "number", "of", "earthquakes", "in", "a", "set", "of", "time", "-", "magnitude", "bins", ".", "Time", "is", "in", "decimal", "years!" ]
python
train
35.354839
gccxml/pygccxml
pygccxml/parser/__init__.py
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/__init__.py#L29-L53
def parse( files, config=None, compilation_mode=COMPILATION_MODE.FILE_BY_FILE, cache=None): """ Parse header files. :param files: The header files that should be parsed :type files: list of str :param config: Configuration object or None :type config: :class:`par...
[ "def", "parse", "(", "files", ",", "config", "=", "None", ",", "compilation_mode", "=", "COMPILATION_MODE", ".", "FILE_BY_FILE", ",", "cache", "=", "None", ")", ":", "if", "not", "config", ":", "config", "=", "xml_generator_configuration_t", "(", ")", "parse...
Parse header files. :param files: The header files that should be parsed :type files: list of str :param config: Configuration object or None :type config: :class:`parser.xml_generator_configuration_t` :param compilation_mode: Determines whether the files are parsed ind...
[ "Parse", "header", "files", "." ]
python
train
39.28
skioo/django-customer-billing
billing/psp.py
https://github.com/skioo/django-customer-billing/blob/6ac1ed9ef9d1d7eee0379de7f0c4b76919ae1f2d/billing/psp.py#L16-L28
def charge_credit_card(credit_card_psp_object: Model, amount: Money, client_ref: str) -> Tuple[bool, Model]: """ :param credit_card_psp_object: an instance representing the credit card in the psp :param amount: the amount to charge :param client_ref: a reference that will appear on the customer's credit...
[ "def", "charge_credit_card", "(", "credit_card_psp_object", ":", "Model", ",", "amount", ":", "Money", ",", "client_ref", ":", "str", ")", "->", "Tuple", "[", "bool", ",", "Model", "]", ":", "logger", ".", "debug", "(", "'charge-credit-card'", ",", "credit_c...
:param credit_card_psp_object: an instance representing the credit card in the psp :param amount: the amount to charge :param client_ref: a reference that will appear on the customer's credit card report :return: a tuple (success, payment_psp_object)
[ ":", "param", "credit_card_psp_object", ":", "an", "instance", "representing", "the", "credit", "card", "in", "the", "psp", ":", "param", "amount", ":", "the", "amount", "to", "charge", ":", "param", "client_ref", ":", "a", "reference", "that", "will", "appe...
python
train
57.692308
ramses-tech/ramses
ramses/views.py
https://github.com/ramses-tech/ramses/blob/ea2e1e896325b7256cdf5902309e05fd98e0c14c/ramses/views.py#L359-L361
def _get_context_key(self, **kwargs): """ Get value of `self._resource.parent.id_name` from :kwargs: """ return str(kwargs.get(self._resource.parent.id_name))
[ "def", "_get_context_key", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "str", "(", "kwargs", ".", "get", "(", "self", ".", "_resource", ".", "parent", ".", "id_name", ")", ")" ]
Get value of `self._resource.parent.id_name` from :kwargs:
[ "Get", "value", "of", "self", ".", "_resource", ".", "parent", ".", "id_name", "from", ":", "kwargs", ":" ]
python
train
57.333333
cltk/cltk
cltk/corpus/utils/formatter.py
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/utils/formatter.py#L126-L162
def phi5_plaintext_cleanup(text, rm_punctuation=False, rm_periods=False): """Remove and substitute post-processing for Greek PHI5 text. TODO: Surely more junk to pull out. Please submit bugs! TODO: This is a rather slow now, help in speeding up welcome. """ # This works OK, doesn't get some # No...
[ "def", "phi5_plaintext_cleanup", "(", "text", ",", "rm_punctuation", "=", "False", ",", "rm_periods", "=", "False", ")", ":", "# This works OK, doesn't get some", "# Note: rming all characters between {} and ()", "remove_comp", "=", "regex", ".", "compile", "(", "r'-\\n|«...
Remove and substitute post-processing for Greek PHI5 text. TODO: Surely more junk to pull out. Please submit bugs! TODO: This is a rather slow now, help in speeding up welcome.
[ "Remove", "and", "substitute", "post", "-", "processing", "for", "Greek", "PHI5", "text", ".", "TODO", ":", "Surely", "more", "junk", "to", "pull", "out", ".", "Please", "submit", "bugs!", "TODO", ":", "This", "is", "a", "rather", "slow", "now", "help", ...
python
train
37.351351
gem/oq-engine
openquake/hazardlib/geo/surface/complex_fault.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/complex_fault.py#L96-L111
def get_dip(self): """ Return the fault dip as the average dip over the mesh. The average dip is defined as the weighted mean inclination of all the mesh cells. See :meth:`openquake.hazardlib.geo.mesh.RectangularMesh.get_mean_inclination_and_azimuth` :returns: ...
[ "def", "get_dip", "(", "self", ")", ":", "# uses the same approach as in simple fault surface", "if", "self", ".", "dip", "is", "None", ":", "mesh", "=", "self", ".", "mesh", "self", ".", "dip", ",", "self", ".", "strike", "=", "mesh", ".", "get_mean_inclina...
Return the fault dip as the average dip over the mesh. The average dip is defined as the weighted mean inclination of all the mesh cells. See :meth:`openquake.hazardlib.geo.mesh.RectangularMesh.get_mean_inclination_and_azimuth` :returns: The average dip, in decimal degrees.
[ "Return", "the", "fault", "dip", "as", "the", "average", "dip", "over", "the", "mesh", "." ]
python
train
35.875
makearl/tornado-profile
tornado_profile.py
https://github.com/makearl/tornado-profile/blob/1b721480d7edc6229f991469e88b9f7a8bb914f3/tornado_profile.py#L273-L280
def main(port=8888): """Run as sample test server.""" import tornado.ioloop routes = [] + TornadoProfiler().get_routes() app = tornado.web.Application(routes) app.listen(port) tornado.ioloop.IOLoop.current().start()
[ "def", "main", "(", "port", "=", "8888", ")", ":", "import", "tornado", ".", "ioloop", "routes", "=", "[", "]", "+", "TornadoProfiler", "(", ")", ".", "get_routes", "(", ")", "app", "=", "tornado", ".", "web", ".", "Application", "(", "routes", ")", ...
Run as sample test server.
[ "Run", "as", "sample", "test", "server", "." ]
python
test
29.125