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
nyaruka/smartmin
smartmin/templatetags/smartmin.py
https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/templatetags/smartmin.py#L84-L89
def get_class(context, field, obj=None): """ Looks up the class for this field """ view = context['view'] return view.lookup_field_class(field, obj, "field_" + field)
[ "def", "get_class", "(", "context", ",", "field", ",", "obj", "=", "None", ")", ":", "view", "=", "context", "[", "'view'", "]", "return", "view", ".", "lookup_field_class", "(", "field", ",", "obj", ",", "\"field_\"", "+", "field", ")" ]
Looks up the class for this field
[ "Looks", "up", "the", "class", "for", "this", "field" ]
python
train
30.166667
OpenTreeOfLife/peyotl
peyotl/nexson_syntax/direct2badgerfish_nexson.py
https://github.com/OpenTreeOfLife/peyotl/blob/5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0/peyotl/nexson_syntax/direct2badgerfish_nexson.py#L72-L94
def convert(self, obj): """Takes a dict corresponding to the honeybadgerfish JSON blob of the 1.0.* type and converts it to BY_ID_HONEY_BADGERFISH version. The object is modified in place and returned. """ if self.pristine_if_invalid: raise NotImplementedError('pristi...
[ "def", "convert", "(", "self", ",", "obj", ")", ":", "if", "self", ".", "pristine_if_invalid", ":", "raise", "NotImplementedError", "(", "'pristine_if_invalid option is not supported yet'", ")", "nex", "=", "get_nexml_el", "(", "obj", ")", "assert", "nex", "self",...
Takes a dict corresponding to the honeybadgerfish JSON blob of the 1.0.* type and converts it to BY_ID_HONEY_BADGERFISH version. The object is modified in place and returned.
[ "Takes", "a", "dict", "corresponding", "to", "the", "honeybadgerfish", "JSON", "blob", "of", "the", "1", ".", "0", ".", "*", "type", "and", "converts", "it", "to", "BY_ID_HONEY_BADGERFISH", "version", ".", "The", "object", "is", "modified", "in", "place", ...
python
train
45.913043
ozak/georasters
georasters/georasters.py
https://github.com/ozak/georasters/blob/0612bd91bb2a2cb2f1d59ba89c1ff131dae27d70/georasters/georasters.py#L778-L790
def gini(self): """ geo.gini() Return computed Gini coefficient. """ if self.count()>1: xsort = sorted(self.raster.data[self.raster.mask == False].flatten()) # increasing order y = np.cumsum(xsort) B = sum(y) / (y[-1] * len(xsort)) ...
[ "def", "gini", "(", "self", ")", ":", "if", "self", ".", "count", "(", ")", ">", "1", ":", "xsort", "=", "sorted", "(", "self", ".", "raster", ".", "data", "[", "self", ".", "raster", ".", "mask", "==", "False", "]", ".", "flatten", "(", ")", ...
geo.gini() Return computed Gini coefficient.
[ "geo", ".", "gini", "()" ]
python
train
28.769231
theislab/scanpy
scanpy/plotting/_utils.py
https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/plotting/_utils.py#L749-L764
def axis_to_data(ax, width): """For a width in axis coordinates, return the corresponding in data coordinates. Parameters ---------- ax : matplotlib.axis Axis object from matplotlib. width : float Width in xaxis coordinates. """ xlim = ax.get_xlim() widthx = width*(x...
[ "def", "axis_to_data", "(", "ax", ",", "width", ")", ":", "xlim", "=", "ax", ".", "get_xlim", "(", ")", "widthx", "=", "width", "*", "(", "xlim", "[", "1", "]", "-", "xlim", "[", "0", "]", ")", "ylim", "=", "ax", ".", "get_ylim", "(", ")", "w...
For a width in axis coordinates, return the corresponding in data coordinates. Parameters ---------- ax : matplotlib.axis Axis object from matplotlib. width : float Width in xaxis coordinates.
[ "For", "a", "width", "in", "axis", "coordinates", "return", "the", "corresponding", "in", "data", "coordinates", "." ]
python
train
26.1875
cs01/gdbgui
gdbgui/backend.py
https://github.com/cs01/gdbgui/blob/5367f87554f8f7c671d1f4596c133bf1303154f0/gdbgui/backend.py#L136-L152
def is_cross_origin(request): """Compare headers HOST and ORIGIN. Remove protocol prefix from ORIGIN, then compare. Return true if they are not equal example HTTP_HOST: '127.0.0.1:5000' example HTTP_ORIGIN: 'http://127.0.0.1:5000' """ origin = request.environ.get("HTTP_ORIGIN") host = reques...
[ "def", "is_cross_origin", "(", "request", ")", ":", "origin", "=", "request", ".", "environ", ".", "get", "(", "\"HTTP_ORIGIN\"", ")", "host", "=", "request", ".", "environ", ".", "get", "(", "\"HTTP_HOST\"", ")", "if", "origin", "is", "None", ":", "# or...
Compare headers HOST and ORIGIN. Remove protocol prefix from ORIGIN, then compare. Return true if they are not equal example HTTP_HOST: '127.0.0.1:5000' example HTTP_ORIGIN: 'http://127.0.0.1:5000'
[ "Compare", "headers", "HOST", "and", "ORIGIN", ".", "Remove", "protocol", "prefix", "from", "ORIGIN", "then", "compare", ".", "Return", "true", "if", "they", "are", "not", "equal", "example", "HTTP_HOST", ":", "127", ".", "0", ".", "0", ".", "1", ":", ...
python
train
38.647059
BerkeleyAutomation/perception
perception/image.py
https://github.com/BerkeleyAutomation/perception/blob/03d9b37dd6b66896cdfe173905c9413c8c3c5df6/perception/image.py#L332-L362
def align(self, scale, center, angle, height, width): """ Create a thumbnail from the original image that is scaled by the given factor, centered on the center pixel, oriented along the grasp angle, and cropped to the desired height and width. Parameters ---------- scale : float...
[ "def", "align", "(", "self", ",", "scale", ",", "center", ",", "angle", ",", "height", ",", "width", ")", ":", "# rescale", "scaled_im", "=", "self", ".", "resize", "(", "scale", ")", "# transform", "cx", "=", "scaled_im", ".", "center", "[", "1", "]...
Create a thumbnail from the original image that is scaled by the given factor, centered on the center pixel, oriented along the grasp angle, and cropped to the desired height and width. Parameters ---------- scale : float scale factor to apply center : 2D array ...
[ "Create", "a", "thumbnail", "from", "the", "original", "image", "that", "is", "scaled", "by", "the", "given", "factor", "centered", "on", "the", "center", "pixel", "oriented", "along", "the", "grasp", "angle", "and", "cropped", "to", "the", "desired", "heigh...
python
train
32.967742
earlzo/hfut
hfut/util.py
https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/util.py#L71-L95
def cal_gpa(grades): """ 根据成绩数组计算课程平均绩点和 gpa, 算法不一定与学校一致, 结果仅供参考 :param grades: :meth:`models.StudentSession.get_my_achievements` 返回的成绩数组 :return: 包含了课程平均绩点和 gpa 的元组 """ # 课程总数 courses_sum = len(grades) # 课程绩点和 points_sum = 0 # 学分和 credit_sum = 0 # 课程学分 x 课程绩点之和 gpa_...
[ "def", "cal_gpa", "(", "grades", ")", ":", "# 课程总数", "courses_sum", "=", "len", "(", "grades", ")", "# 课程绩点和", "points_sum", "=", "0", "# 学分和", "credit_sum", "=", "0", "# 课程学分 x 课程绩点之和", "gpa_points_sum", "=", "0", "for", "grade", "in", "grades", ":", "poi...
根据成绩数组计算课程平均绩点和 gpa, 算法不一定与学校一致, 结果仅供参考 :param grades: :meth:`models.StudentSession.get_my_achievements` 返回的成绩数组 :return: 包含了课程平均绩点和 gpa 的元组
[ "根据成绩数组计算课程平均绩点和", "gpa", "算法不一定与学校一致", "结果仅供参考" ]
python
train
26.2
The-Politico/politico-civic-election-night
electionnight/serializers/votes.py
https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/votes.py#L69-L75
def get_statepostal(self, obj): """State postal abbreviation if county or state else ``None``.""" if obj.division.level.name == DivisionLevel.STATE: return us.states.lookup(obj.division.code).abbr elif obj.division.level.name == DivisionLevel.COUNTY: return us.states.look...
[ "def", "get_statepostal", "(", "self", ",", "obj", ")", ":", "if", "obj", ".", "division", ".", "level", ".", "name", "==", "DivisionLevel", ".", "STATE", ":", "return", "us", ".", "states", ".", "lookup", "(", "obj", ".", "division", ".", "code", ")...
State postal abbreviation if county or state else ``None``.
[ "State", "postal", "abbreviation", "if", "county", "or", "state", "else", "None", "." ]
python
train
52.428571
mvantellingen/localshop
src/localshop/utils.py
https://github.com/mvantellingen/localshop/blob/32310dc454720aefdea5bf4cea7f78a38c183954/src/localshop/utils.py#L25-L38
def no_duplicates(function, *args, **kwargs): """ Makes sure that no duplicated tasks are enqueued. """ @wraps(function) def wrapper(self, *args, **kwargs): key = generate_key(function, *args, **kwargs) try: function(self, *args, **kwargs) finally: log...
[ "def", "no_duplicates", "(", "function", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "@", "wraps", "(", "function", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "key", "=", "generate_key", "(", ...
Makes sure that no duplicated tasks are enqueued.
[ "Makes", "sure", "that", "no", "duplicated", "tasks", "are", "enqueued", "." ]
python
train
27.857143
IBM-Cloud/gp-python-client
gpclient/gpclient.py
https://github.com/IBM-Cloud/gp-python-client/blob/082c6cdc250fb61bea99cba8ac3ee855ee77a410/gpclient/gpclient.py#L101-L145
def __get_language_match(self, languageCode, languageIds): """Compares ``languageCode`` to the provided ``languageIds`` to find the closest match and returns it, if a match is not found returns ``None``. e.g. if ``languageCode`` is ``en_CA`` and ``languageIds`` contains ``...
[ "def", "__get_language_match", "(", "self", ",", "languageCode", ",", "languageIds", ")", ":", "# special case\r", "if", "languageCode", "==", "'zh'", ":", "return", "'zh-Hans'", "# this will take care of cases such as mapping en_CA to en\r", "if", "'-'", "in", "languageC...
Compares ``languageCode`` to the provided ``languageIds`` to find the closest match and returns it, if a match is not found returns ``None``. e.g. if ``languageCode`` is ``en_CA`` and ``languageIds`` contains ``en``, the return value will be ``en``
[ "Compares", "languageCode", "to", "the", "provided", "languageIds", "to", "find", "the", "closest", "match", "and", "returns", "it", "if", "a", "match", "is", "not", "found", "returns", "None", ".", "e", ".", "g", ".", "if", "languageCode", "is", "en_CA", ...
python
train
37.444444
gwastro/pycbc
pycbc/filter/qtransform.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/filter/qtransform.py#L183-L231
def qseries(fseries, Q, f0, return_complex=False): """Calculate the energy 'TimeSeries' for the given fseries Parameters ---------- fseries: 'pycbc FrequencySeries' frequency-series data set Q: q value f0: central frequency return_complex: {False, bool} Retur...
[ "def", "qseries", "(", "fseries", ",", "Q", ",", "f0", ",", "return_complex", "=", "False", ")", ":", "# normalize and generate bi-square window", "qprime", "=", "Q", "/", "11", "**", "(", "1", "/", "2.", ")", "norm", "=", "numpy", ".", "sqrt", "(", "3...
Calculate the energy 'TimeSeries' for the given fseries Parameters ---------- fseries: 'pycbc FrequencySeries' frequency-series data set Q: q value f0: central frequency return_complex: {False, bool} Return the raw complex series instead of the normalized power. ...
[ "Calculate", "the", "energy", "TimeSeries", "for", "the", "given", "fseries" ]
python
train
31.55102
calmjs/calmjs.parse
src/calmjs/parse/parsers/es5.py
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1091-L1101
def p_variable_declaration_list_noin(self, p): """ variable_declaration_list_noin \ : variable_declaration_noin | variable_declaration_list_noin COMMA variable_declaration_noin """ if len(p) == 2: p[0] = [p[1]] else: p[1].append(p[3...
[ "def", "p_variable_declaration_list_noin", "(", "self", ",", "p", ")", ":", "if", "len", "(", "p", ")", "==", "2", ":", "p", "[", "0", "]", "=", "[", "p", "[", "1", "]", "]", "else", ":", "p", "[", "1", "]", ".", "append", "(", "p", "[", "3...
variable_declaration_list_noin \ : variable_declaration_noin | variable_declaration_list_noin COMMA variable_declaration_noin
[ "variable_declaration_list_noin", "\\", ":", "variable_declaration_noin", "|", "variable_declaration_list_noin", "COMMA", "variable_declaration_noin" ]
python
train
30.545455
astropy/photutils
photutils/datasets/make.py
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/datasets/make.py#L812-L855
def make_imagehdu(data, wcs=None): """ Create a FITS `~astropy.io.fits.ImageHDU` containing the input 2D image. Parameters ---------- data : 2D array-like The input 2D data. wcs : `~astropy.wcs.WCS`, optional The world coordinate system (WCS) transformation to include in ...
[ "def", "make_imagehdu", "(", "data", ",", "wcs", "=", "None", ")", ":", "data", "=", "np", ".", "asanyarray", "(", "data", ")", "if", "data", ".", "ndim", "!=", "2", ":", "raise", "ValueError", "(", "'data must be a 2D array'", ")", "if", "wcs", "is", ...
Create a FITS `~astropy.io.fits.ImageHDU` containing the input 2D image. Parameters ---------- data : 2D array-like The input 2D data. wcs : `~astropy.wcs.WCS`, optional The world coordinate system (WCS) transformation to include in the output FITS header. Returns ...
[ "Create", "a", "FITS", "~astropy", ".", "io", ".", "fits", ".", "ImageHDU", "containing", "the", "input", "2D", "image", "." ]
python
train
22.227273
sassoftware/saspy
saspy/sasdata.py
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L287-L308
def obs(self): """ return the number of observations for your SASdata object """ code = "proc sql;select count(*) format best32. into :lastobs from " + self.libref + '.' + self.table + self._dsopts() + ";%put lastobs=&lastobs tom;quit;" if self.sas.nosub: print(code)...
[ "def", "obs", "(", "self", ")", ":", "code", "=", "\"proc sql;select count(*) format best32. into :lastobs from \"", "+", "self", ".", "libref", "+", "'.'", "+", "self", ".", "table", "+", "self", ".", "_dsopts", "(", ")", "+", "\";%put lastobs=&lastobs tom;quit;\...
return the number of observations for your SASdata object
[ "return", "the", "number", "of", "observations", "for", "your", "SASdata", "object" ]
python
train
33.5
xtrementl/focus
focus/common.py
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/common.py#L75-L101
def which(name): """ Returns the full path to executable in path matching provided name. `name` String value. Returns string or ``None``. """ # we were given a filename, return it if it's executable if os.path.dirname(name) != '': if not os.path.isdir(name) and...
[ "def", "which", "(", "name", ")", ":", "# we were given a filename, return it if it's executable", "if", "os", ".", "path", ".", "dirname", "(", "name", ")", "!=", "''", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "name", ")", "and", "os", "....
Returns the full path to executable in path matching provided name. `name` String value. Returns string or ``None``.
[ "Returns", "the", "full", "path", "to", "executable", "in", "path", "matching", "provided", "name", "." ]
python
train
25.703704
the01/python-paps
examples/gpio_detector.py
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/examples/gpio_detector.py#L100-L133
def start(self, blocking=False): """ Start the interface :param blocking: Should the call block until stop() is called (default: False) :type blocking: bool :rtype: None """ self.debug("()") # Init GPIO # Enable warnings GPIO.s...
[ "def", "start", "(", "self", ",", "blocking", "=", "False", ")", ":", "self", ".", "debug", "(", "\"()\"", ")", "# Init GPIO", "# Enable warnings", "GPIO", ".", "setwarnings", "(", "True", ")", "# Careful - numbering between different pi version might differ", "if",...
Start the interface :param blocking: Should the call block until stop() is called (default: False) :type blocking: bool :rtype: None
[ "Start", "the", "interface" ]
python
train
31.088235
markovmodel/msmtools
msmtools/analysis/sparse/fingerprints.py
https://github.com/markovmodel/msmtools/blob/54dc76dd2113a0e8f3d15d5316abab41402941be/msmtools/analysis/sparse/fingerprints.py#L242-L293
def correlation_matvec(P, obs1, obs2=None, times=[1]): r"""Time-correlation for equilibrium experiment - via matrix vector products. Parameters ---------- P : (M, M) ndarray Transition matrix obs1 : (M,) ndarray Observable, represented as vector on state space obs2 : (M,) ndarra...
[ "def", "correlation_matvec", "(", "P", ",", "obs1", ",", "obs2", "=", "None", ",", "times", "=", "[", "1", "]", ")", ":", "if", "obs2", "is", "None", ":", "obs2", "=", "obs1", "\"\"\"Compute stationary vector\"\"\"", "mu", "=", "statdist", "(", "P", ")...
r"""Time-correlation for equilibrium experiment - via matrix vector products. Parameters ---------- P : (M, M) ndarray Transition matrix obs1 : (M,) ndarray Observable, represented as vector on state space obs2 : (M,) ndarray (optional) Second observable, for cross-correlati...
[ "r", "Time", "-", "correlation", "for", "equilibrium", "experiment", "-", "via", "matrix", "vector", "products", "." ]
python
train
25.596154
gbiggs/rtctree
rtctree/manager.py
https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/manager.py#L198-L213
def delete_component(self, instance_name): '''Delete a component. Deletes the component specified by @ref instance_name from the manager. This will invalidate any objects that are children of this node. @param instance_name The instance name of the component to delete. @raises ...
[ "def", "delete_component", "(", "self", ",", "instance_name", ")", ":", "with", "self", ".", "_mutex", ":", "if", "self", ".", "_obj", ".", "delete_component", "(", "instance_name", ")", "!=", "RTC", ".", "RTC_OK", ":", "raise", "exceptions", ".", "FailedT...
Delete a component. Deletes the component specified by @ref instance_name from the manager. This will invalidate any objects that are children of this node. @param instance_name The instance name of the component to delete. @raises FailedToDeleteComponentError
[ "Delete", "a", "component", "." ]
python
train
41.875
DeepHorizons/iarm
iarm/arm_instructions/data_movement.py
https://github.com/DeepHorizons/iarm/blob/b913c9fd577b793a6bbced78b78a5d8d7cd88de4/iarm/arm_instructions/data_movement.py#L175-L191
def SXTB(self, params): """ STXB Ra, Rb Sign extend the byte in Rb and store the result in Ra """ Ra, Rb = self.get_two_parameters(r'\s*([^\s,]*),\s*([^\s,]*)(,\s*[^\s,]*)*\s*', params) self.check_arguments(low_registers=(Ra, Rb)) def SXTB_func(): i...
[ "def", "SXTB", "(", "self", ",", "params", ")", ":", "Ra", ",", "Rb", "=", "self", ".", "get_two_parameters", "(", "r'\\s*([^\\s,]*),\\s*([^\\s,]*)(,\\s*[^\\s,]*)*\\s*'", ",", "params", ")", "self", ".", "check_arguments", "(", "low_registers", "=", "(", "Ra", ...
STXB Ra, Rb Sign extend the byte in Rb and store the result in Ra
[ "STXB", "Ra", "Rb" ]
python
train
30.470588
ynop/audiomate
audiomate/corpus/io/tatoeba.py
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/io/tatoeba.py#L123-L134
def _download_audio_files(self, records, target_path): """ Download all audio files based on the given records. """ for record in records: audio_folder = os.path.join(target_path, 'audio', record[2]) audio_file = os.path.join(audio_folder, '{}.mp3'.format(record[...
[ "def", "_download_audio_files", "(", "self", ",", "records", ",", "target_path", ")", ":", "for", "record", "in", "records", ":", "audio_folder", "=", "os", ".", "path", ".", "join", "(", "target_path", ",", "'audio'", ",", "record", "[", "2", "]", ")", ...
Download all audio files based on the given records.
[ "Download", "all", "audio", "files", "based", "on", "the", "given", "records", "." ]
python
train
44.333333
coremke/django-quill
quill/fields.py
https://github.com/coremke/django-quill/blob/6c5ace1a96e291f0a8e401f6d61d634dd0cb7c9f/quill/fields.py#L20-L27
def formfield(self, **kwargs): """Get the form for field.""" defaults = { 'form_class': RichTextFormField, 'config': self.config, } defaults.update(kwargs) return super(RichTextField, self).formfield(**defaults)
[ "def", "formfield", "(", "self", ",", "*", "*", "kwargs", ")", ":", "defaults", "=", "{", "'form_class'", ":", "RichTextFormField", ",", "'config'", ":", "self", ".", "config", ",", "}", "defaults", ".", "update", "(", "kwargs", ")", "return", "super", ...
Get the form for field.
[ "Get", "the", "form", "for", "field", "." ]
python
valid
33.5
ggaughan/pipe2py
pipe2py/modules/pipereverse.py
https://github.com/ggaughan/pipe2py/blob/4767d6d1fd354d2a35e6528594b8deb8a033eed4/pipe2py/modules/pipereverse.py#L11-L26
def pipe_reverse(context=None, _INPUT=None, conf=None, **kwargs): """An operator that reverses the order of source items. Not loopable. Not lazy. Parameters ---------- context : pipe2py.Context object _INPUT : pipe2py.modules pipe like object (iterable of items) conf : unused Yields ...
[ "def", "pipe_reverse", "(", "context", "=", "None", ",", "_INPUT", "=", "None", ",", "conf", "=", "None", ",", "*", "*", "kwargs", ")", ":", "for", "item", "in", "reversed", "(", "list", "(", "_INPUT", ")", ")", ":", "yield", "item" ]
An operator that reverses the order of source items. Not loopable. Not lazy. Parameters ---------- context : pipe2py.Context object _INPUT : pipe2py.modules pipe like object (iterable of items) conf : unused Yields ------ _OUTPUT : items
[ "An", "operator", "that", "reverses", "the", "order", "of", "source", "items", ".", "Not", "loopable", ".", "Not", "lazy", "." ]
python
train
25
wakatime/wakatime
wakatime/project.py
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/project.py#L39-L100
def get_project_info(configs, heartbeat, data): """Find the current project and branch. First looks for a .wakatime-project file. Second, uses the --project arg. Third, uses the folder name from a revision control repository. Last, uses the --alternate-project arg. Returns a project, branch tuple....
[ "def", "get_project_info", "(", "configs", ",", "heartbeat", ",", "data", ")", ":", "project_name", ",", "branch_name", "=", "heartbeat", ".", "project", ",", "heartbeat", ".", "branch", "if", "heartbeat", ".", "type", "!=", "'file'", ":", "project_name", "=...
Find the current project and branch. First looks for a .wakatime-project file. Second, uses the --project arg. Third, uses the folder name from a revision control repository. Last, uses the --alternate-project arg. Returns a project, branch tuple.
[ "Find", "the", "current", "project", "and", "branch", "." ]
python
train
37.306452
waqasbhatti/astrobase
astrobase/lcproc/epd.py
https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/epd.py#L344-L510
def parallel_epd_lclist(lclist, externalparams, timecols=None, magcols=None, errcols=None, lcformat='hat-sql', lcformatdir=None, epdsmooth_sigclip=3.0, ...
[ "def", "parallel_epd_lclist", "(", "lclist", ",", "externalparams", ",", "timecols", "=", "None", ",", "magcols", "=", "None", ",", "errcols", "=", "None", ",", "lcformat", "=", "'hat-sql'", ",", "lcformatdir", "=", "None", ",", "epdsmooth_sigclip", "=", "3....
This applies EPD in parallel to all LCs in the input list. Parameters ---------- lclist : list of str This is the list of light curve files to run EPD on. externalparams : dict or None This is a dict that indicates which keys in the lcdict obtained from the lcfile correspond t...
[ "This", "applies", "EPD", "in", "parallel", "to", "all", "LCs", "in", "the", "input", "list", "." ]
python
valid
41.047904
ph4r05/monero-serialize
monero_serialize/xmrboost.py
https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/xmrboost.py#L572-L598
async def variant(self, elem=None, elem_type=None, params=None): """ Loads/dumps variant type :param elem: :param elem_type: :param params: :return: """ elem_type = elem_type if elem_type else elem.__class__ version = await self.version(elem_type, ...
[ "async", "def", "variant", "(", "self", ",", "elem", "=", "None", ",", "elem_type", "=", "None", ",", "params", "=", "None", ")", ":", "elem_type", "=", "elem_type", "if", "elem_type", "else", "elem", ".", "__class__", "version", "=", "await", "self", ...
Loads/dumps variant type :param elem: :param elem_type: :param params: :return:
[ "Loads", "/", "dumps", "variant", "type", ":", "param", "elem", ":", ":", "param", "elem_type", ":", ":", "param", "params", ":", ":", "return", ":" ]
python
train
39.703704
objectrocket/python-client
objectrocket/acls.py
https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/acls.py#L28-L38
def all(self, instance): """Get all ACLs associated with the instance specified by name. :param str instance: The name of the instance from which to fetch ACLs. :returns: A list of :py:class:`Acl` objects associated with the specified instance. :rtype: list """ url = sel...
[ "def", "all", "(", "self", ",", "instance", ")", ":", "url", "=", "self", ".", "_url", ".", "format", "(", "instance", "=", "instance", ")", "response", "=", "requests", ".", "get", "(", "url", ",", "*", "*", "self", ".", "_default_request_kwargs", "...
Get all ACLs associated with the instance specified by name. :param str instance: The name of the instance from which to fetch ACLs. :returns: A list of :py:class:`Acl` objects associated with the specified instance. :rtype: list
[ "Get", "all", "ACLs", "associated", "with", "the", "instance", "specified", "by", "name", "." ]
python
train
45.909091
saltstack/salt
salt/runners/digicertapi.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/digicertapi.py#L692-L707
def show_rsa(minion_id, dns_name): ''' Show a private RSA key CLI Example: .. code-block:: bash salt-run digicert.show_rsa myminion domain.example.com ''' cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR) bank = 'digicert/domains' data = cache.fetch( bank, dns_nam...
[ "def", "show_rsa", "(", "minion_id", ",", "dns_name", ")", ":", "cache", "=", "salt", ".", "cache", ".", "Cache", "(", "__opts__", ",", "syspaths", ".", "CACHE_DIR", ")", "bank", "=", "'digicert/domains'", "data", "=", "cache", ".", "fetch", "(", "bank",...
Show a private RSA key CLI Example: .. code-block:: bash salt-run digicert.show_rsa myminion domain.example.com
[ "Show", "a", "private", "RSA", "key" ]
python
train
21.4375
hydraplatform/hydra-base
hydra_base/lib/users.py
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/users.py#L327-L369
def get_all_users(**kwargs): """ Get the username & ID of all users. Use the the filter if it has been provided The filter has to be a list of values """ users_qry = db.DBSession.query(User) filter_type = kwargs.get('filter_type') filter_value = kwargs.get('filter_value') ...
[ "def", "get_all_users", "(", "*", "*", "kwargs", ")", ":", "users_qry", "=", "db", ".", "DBSession", ".", "query", "(", "User", ")", "filter_type", "=", "kwargs", ".", "get", "(", "'filter_type'", ")", "filter_value", "=", "kwargs", ".", "get", "(", "'...
Get the username & ID of all users. Use the the filter if it has been provided The filter has to be a list of values
[ "Get", "the", "username", "&", "ID", "of", "all", "users", ".", "Use", "the", "the", "filter", "if", "it", "has", "been", "provided", "The", "filter", "has", "to", "be", "a", "list", "of", "values" ]
python
train
39.930233
Metatab/metapack
metapack/package/core.py
https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/package/core.py#L298-L323
def add_resource(self, ref, **properties): """Add one or more resources entities, from a url and property values, possibly adding multiple entries for an excel spreadsheet or ZIP file""" raise NotImplementedError("Still uses decompose_url") du = Bunch(decompose_url(ref)) added...
[ "def", "add_resource", "(", "self", ",", "ref", ",", "*", "*", "properties", ")", ":", "raise", "NotImplementedError", "(", "\"Still uses decompose_url\"", ")", "du", "=", "Bunch", "(", "decompose_url", "(", "ref", ")", ")", "added", "=", "[", "]", "if", ...
Add one or more resources entities, from a url and property values, possibly adding multiple entries for an excel spreadsheet or ZIP file
[ "Add", "one", "or", "more", "resources", "entities", "from", "a", "url", "and", "property", "values", "possibly", "adding", "multiple", "entries", "for", "an", "excel", "spreadsheet", "or", "ZIP", "file" ]
python
train
36.615385
ic-labs/django-icekit
icekit/workflow/admin.py
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/workflow/admin.py#L126-L132
def workflow_states_column(self, obj): """ Return text description of workflow states assigned to object """ workflow_states = models.WorkflowState.objects.filter( content_type=self._get_obj_ct(obj), object_id=obj.pk, ) return ', '.join([unicode(wfs) for wfs in wo...
[ "def", "workflow_states_column", "(", "self", ",", "obj", ")", ":", "workflow_states", "=", "models", ".", "WorkflowState", ".", "objects", ".", "filter", "(", "content_type", "=", "self", ".", "_get_obj_ct", "(", "obj", ")", ",", "object_id", "=", "obj", ...
Return text description of workflow states assigned to object
[ "Return", "text", "description", "of", "workflow", "states", "assigned", "to", "object" ]
python
train
47
saltstack/salt
salt/states/kmod.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/kmod.py#L43-L52
def _append_comment(ret, comment): ''' append ``comment`` to ``ret['comment']`` ''' if ret['comment']: ret['comment'] = ret['comment'].rstrip() + '\n' + comment else: ret['comment'] = comment return ret
[ "def", "_append_comment", "(", "ret", ",", "comment", ")", ":", "if", "ret", "[", "'comment'", "]", ":", "ret", "[", "'comment'", "]", "=", "ret", "[", "'comment'", "]", ".", "rstrip", "(", ")", "+", "'\\n'", "+", "comment", "else", ":", "ret", "["...
append ``comment`` to ``ret['comment']``
[ "append", "comment", "to", "ret", "[", "comment", "]" ]
python
train
23.4
watson-developer-cloud/python-sdk
ibm_watson/speech_to_text_v1.py
https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/speech_to_text_v1.py#L5100-L5113
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'results') and self.results is not None: _dict['results'] = [x._to_dict() for x in self.results] if hasattr(self, 'result_index') and self.result_index is not None: ...
[ "def", "_to_dict", "(", "self", ")", ":", "_dict", "=", "{", "}", "if", "hasattr", "(", "self", ",", "'results'", ")", "and", "self", ".", "results", "is", "not", "None", ":", "_dict", "[", "'results'", "]", "=", "[", "x", ".", "_to_dict", "(", "...
Return a json dictionary representing this model.
[ "Return", "a", "json", "dictionary", "representing", "this", "model", "." ]
python
train
48.571429
proteanhq/protean
src/protean/core/field/basic.py
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/field/basic.py#L73-L78
def _cast_to_type(self, value): """ Convert the value to an int and raise error on failures""" try: return int(value) except (ValueError, TypeError): self.fail('invalid', value=value)
[ "def", "_cast_to_type", "(", "self", ",", "value", ")", ":", "try", ":", "return", "int", "(", "value", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "self", ".", "fail", "(", "'invalid'", ",", "value", "=", "value", ")" ]
Convert the value to an int and raise error on failures
[ "Convert", "the", "value", "to", "an", "int", "and", "raise", "error", "on", "failures" ]
python
train
37.666667
marrow/schema
marrow/schema/transform/container.py
https://github.com/marrow/schema/blob/0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152/marrow/schema/transform/container.py#L21-L32
def _clean(self, value): """Perform a standardized pipline of operations across an iterable.""" value = (str(v) for v in value) if self.strip: value = (v.strip() for v in value) if not self.empty: value = (v for v in value if v) return value
[ "def", "_clean", "(", "self", ",", "value", ")", ":", "value", "=", "(", "str", "(", "v", ")", "for", "v", "in", "value", ")", "if", "self", ".", "strip", ":", "value", "=", "(", "v", ".", "strip", "(", ")", "for", "v", "in", "value", ")", ...
Perform a standardized pipline of operations across an iterable.
[ "Perform", "a", "standardized", "pipline", "of", "operations", "across", "an", "iterable", "." ]
python
train
21.5
devassistant/devassistant
devassistant/lang.py
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/lang.py#L286-L313
def get_for_control_var_and_eval_expr(comm_type, kwargs): """Returns tuple that consists of control variable name and iterable that is result of evaluated expression of given for loop. For example: - given 'for $i in $(echo "foo bar")' it returns (['i'], ['foo', 'bar']) - given 'for $i, $j in $foo'...
[ "def", "get_for_control_var_and_eval_expr", "(", "comm_type", ",", "kwargs", ")", ":", "# let possible exceptions bubble up", "control_vars", ",", "iter_type", ",", "expression", "=", "parse_for", "(", "comm_type", ")", "eval_expression", "=", "evaluate_expression", "(", ...
Returns tuple that consists of control variable name and iterable that is result of evaluated expression of given for loop. For example: - given 'for $i in $(echo "foo bar")' it returns (['i'], ['foo', 'bar']) - given 'for $i, $j in $foo' it returns (['i', 'j'], [('foo', 'bar')])
[ "Returns", "tuple", "that", "consists", "of", "control", "variable", "name", "and", "iterable", "that", "is", "result", "of", "evaluated", "expression", "of", "given", "for", "loop", "." ]
python
train
39.75
h2oai/datatable
ci/make_fast.py
https://github.com/h2oai/datatable/blob/dd5fba74d2ca85b66f82ae3c1e0b6ea2fd792564/ci/make_fast.py#L81-L90
def build_sourcemap(sources): """ Similar to build_headermap(), but builds a dictionary of includes from the "source" files (i.e. ".c/.cc" files). """ sourcemap = {} for sfile in sources: inc = find_includes(sfile) sourcemap[sfile] = set(inc) return sourcemap
[ "def", "build_sourcemap", "(", "sources", ")", ":", "sourcemap", "=", "{", "}", "for", "sfile", "in", "sources", ":", "inc", "=", "find_includes", "(", "sfile", ")", "sourcemap", "[", "sfile", "]", "=", "set", "(", "inc", ")", "return", "sourcemap" ]
Similar to build_headermap(), but builds a dictionary of includes from the "source" files (i.e. ".c/.cc" files).
[ "Similar", "to", "build_headermap", "()", "but", "builds", "a", "dictionary", "of", "includes", "from", "the", "source", "files", "(", "i", ".", "e", ".", ".", "c", "/", ".", "cc", "files", ")", "." ]
python
train
29.4
econ-ark/HARK
HARK/ConsumptionSaving/ConsMarkovModel.py
https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsMarkovModel.py#L313-L344
def makeEndOfPrdvPfuncCond(self): ''' Construct the end-of-period marginal value function conditional on next period's state. Parameters ---------- None Returns ------- EndofPrdvPfunc_cond : MargValueFunc The end-of-period marginal va...
[ "def", "makeEndOfPrdvPfuncCond", "(", "self", ")", ":", "# Get data to construct the end-of-period marginal value function (conditional on next state)", "self", ".", "aNrm_cond", "=", "self", ".", "prepareToCalcEndOfPrdvP", "(", ")", "self", ".", "EndOfPrdvP_cond", "=", "self...
Construct the end-of-period marginal value function conditional on next period's state. Parameters ---------- None Returns ------- EndofPrdvPfunc_cond : MargValueFunc The end-of-period marginal value function conditional on a particular s...
[ "Construct", "the", "end", "-", "of", "-", "period", "marginal", "value", "function", "conditional", "on", "next", "period", "s", "state", "." ]
python
train
48.21875
saltstack/salt
salt/modules/win_powercfg.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_powercfg.py#L156-L195
def set_disk_timeout(timeout, power='ac', scheme=None): ''' Set the disk timeout in minutes for the given power scheme Args: timeout (int): The amount of time in minutes before the disk will timeout power (str): Set the value for AC or DC power. Default is ``ac``. V...
[ "def", "set_disk_timeout", "(", "timeout", ",", "power", "=", "'ac'", ",", "scheme", "=", "None", ")", ":", "return", "_set_powercfg_value", "(", "scheme", "=", "scheme", ",", "sub_group", "=", "'SUB_DISK'", ",", "setting_guid", "=", "'DISKIDLE'", ",", "powe...
Set the disk timeout in minutes for the given power scheme Args: timeout (int): The amount of time in minutes before the disk will timeout power (str): Set the value for AC or DC power. Default is ``ac``. Valid options are: - ``ac`` (AC Power) ...
[ "Set", "the", "disk", "timeout", "in", "minutes", "for", "the", "given", "power", "scheme" ]
python
train
28.4
boriel/zxbasic
arch/zx48k/backend/__parray.py
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__parray.py#L62-L71
def _paload8(ins): ''' Loads an 8 bit value from a memory address If 2nd arg. start with '*', it is always treated as an indirect value. ''' output = _paddr(ins.quad[2]) output.append('ld a, (hl)') output.append('push af') return output
[ "def", "_paload8", "(", "ins", ")", ":", "output", "=", "_paddr", "(", "ins", ".", "quad", "[", "2", "]", ")", "output", ".", "append", "(", "'ld a, (hl)'", ")", "output", ".", "append", "(", "'push af'", ")", "return", "output" ]
Loads an 8 bit value from a memory address If 2nd arg. start with '*', it is always treated as an indirect value.
[ "Loads", "an", "8", "bit", "value", "from", "a", "memory", "address", "If", "2nd", "arg", ".", "start", "with", "*", "it", "is", "always", "treated", "as", "an", "indirect", "value", "." ]
python
train
26
akissa/spamc
spamc/client.py
https://github.com/akissa/spamc/blob/da50732e276f7ed3d67cb75c31cb017d6a62f066/spamc/client.py#L40-L47
def _check_action(action): """check for invalid actions""" if isinstance(action, types.StringTypes): action = action.lower() if action not in ['learn', 'forget', 'report', 'revoke']: raise SpamCError('The action option is invalid') return action
[ "def", "_check_action", "(", "action", ")", ":", "if", "isinstance", "(", "action", ",", "types", ".", "StringTypes", ")", ":", "action", "=", "action", ".", "lower", "(", ")", "if", "action", "not", "in", "[", "'learn'", ",", "'forget'", ",", "'report...
check for invalid actions
[ "check", "for", "invalid", "actions" ]
python
train
33.875
minhhoit/yacms
yacms/twitter/templatetags/twitter_tags.py
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/twitter/templatetags/twitter_tags.py#L64-L74
def tweets_default(*args): """ Tweets for the default settings. """ query_type = settings.TWITTER_DEFAULT_QUERY_TYPE args = (settings.TWITTER_DEFAULT_QUERY, settings.TWITTER_DEFAULT_NUM_TWEETS) per_user = None if query_type == QUERY_TYPE_LIST: per_user = 1 return twee...
[ "def", "tweets_default", "(", "*", "args", ")", ":", "query_type", "=", "settings", ".", "TWITTER_DEFAULT_QUERY_TYPE", "args", "=", "(", "settings", ".", "TWITTER_DEFAULT_QUERY", ",", "settings", ".", "TWITTER_DEFAULT_NUM_TWEETS", ")", "per_user", "=", "None", "if...
Tweets for the default settings.
[ "Tweets", "for", "the", "default", "settings", "." ]
python
train
32.090909
fboender/ansible-cmdb
lib/mako/codegen.py
https://github.com/fboender/ansible-cmdb/blob/ebd960ac10684e8c9ec2b12751bba2c4c9504ab7/lib/mako/codegen.py#L613-L665
def write_def_finish(self, node, buffered, filtered, cached, callstack=True): """write the end section of a rendering function, either outermost or inline. this takes into account if the rendering function was filtered, buffered, etc. and closes the corresponding try: block...
[ "def", "write_def_finish", "(", "self", ",", "node", ",", "buffered", ",", "filtered", ",", "cached", ",", "callstack", "=", "True", ")", ":", "if", "not", "buffered", "and", "not", "cached", "and", "not", "filtered", ":", "self", ".", "printer", ".", ...
write the end section of a rendering function, either outermost or inline. this takes into account if the rendering function was filtered, buffered, etc. and closes the corresponding try: block if any, and writes code to retrieve captured content, apply filters, send proper ret...
[ "write", "the", "end", "section", "of", "a", "rendering", "function", "either", "outermost", "or", "inline", "." ]
python
train
39.471698
limix/limix-core
limix_core/covar/freeform.py
https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/covar/freeform.py#L123-L127
def setCovariance(self,cov): """ set hyperparameters from given covariance """ chol = LA.cholesky(cov,lower=True) params = chol[sp.tril_indices(self.dim)] self.setParams(params)
[ "def", "setCovariance", "(", "self", ",", "cov", ")", ":", "chol", "=", "LA", ".", "cholesky", "(", "cov", ",", "lower", "=", "True", ")", "params", "=", "chol", "[", "sp", ".", "tril_indices", "(", "self", ".", "dim", ")", "]", "self", ".", "set...
set hyperparameters from given covariance
[ "set", "hyperparameters", "from", "given", "covariance" ]
python
train
41
onicagroup/runway
runway/commands/runway/gen_sample.py
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/commands/runway/gen_sample.py#L279-L296
def execute(self): """Run selected module generator.""" if self._cli_arguments['cfn']: generate_sample_cfn_module(self.env_root) elif self._cli_arguments['sls']: generate_sample_sls_module(self.env_root) elif self._cli_arguments['sls-tsc']: generate_sa...
[ "def", "execute", "(", "self", ")", ":", "if", "self", ".", "_cli_arguments", "[", "'cfn'", "]", ":", "generate_sample_cfn_module", "(", "self", ".", "env_root", ")", "elif", "self", ".", "_cli_arguments", "[", "'sls'", "]", ":", "generate_sample_sls_module", ...
Run selected module generator.
[ "Run", "selected", "module", "generator", "." ]
python
train
46.777778
ska-sa/montblanc
montblanc/src_types.py
https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/montblanc/src_types.py#L188-L197
def source_range_slices(start, end, nr_var_dict): """ Given a range of source numbers, as well as a dictionary containing the numbers of each source, returns a dictionary containing slices for each source variable type. """ return OrderedDict((k, slice(s,e,1)) for k, (s, e) in s...
[ "def", "source_range_slices", "(", "start", ",", "end", ",", "nr_var_dict", ")", ":", "return", "OrderedDict", "(", "(", "k", ",", "slice", "(", "s", ",", "e", ",", "1", ")", ")", "for", "k", ",", "(", "s", ",", "e", ")", "in", "source_range_tuple"...
Given a range of source numbers, as well as a dictionary containing the numbers of each source, returns a dictionary containing slices for each source variable type.
[ "Given", "a", "range", "of", "source", "numbers", "as", "well", "as", "a", "dictionary", "containing", "the", "numbers", "of", "each", "source", "returns", "a", "dictionary", "containing", "slices", "for", "each", "source", "variable", "type", "." ]
python
train
36.6
pmacosta/peng
peng/functions.py
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/functions.py#L176-L203
def _parse_expr(text, ldelim="(", rdelim=")"): """Parse mathematical expression using PyParsing.""" var = pyparsing.Word(pyparsing.alphas + "_", pyparsing.alphanums + "_") point = pyparsing.Literal(".") exp = pyparsing.CaselessLiteral("E") number = pyparsing.Combine( pyparsing.Word("+-" + py...
[ "def", "_parse_expr", "(", "text", ",", "ldelim", "=", "\"(\"", ",", "rdelim", "=", "\")\"", ")", ":", "var", "=", "pyparsing", ".", "Word", "(", "pyparsing", ".", "alphas", "+", "\"_\"", ",", "pyparsing", ".", "alphanums", "+", "\"_\"", ")", "point", ...
Parse mathematical expression using PyParsing.
[ "Parse", "mathematical", "expression", "using", "PyParsing", "." ]
python
test
45
BreakingBytes/simkit
simkit/core/data_readers.py
https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/simkit/core/data_readers.py#L698-L708
def apply_units_to_cache(self, data): """ Apply units to :class:`ParameterizedXLS` data reader. """ # parameter parameter_name = self.parameters['parameter']['name'] parameter_units = str(self.parameters['parameter']['units']) data[parameter_name] *= UREG(paramete...
[ "def", "apply_units_to_cache", "(", "self", ",", "data", ")", ":", "# parameter", "parameter_name", "=", "self", ".", "parameters", "[", "'parameter'", "]", "[", "'name'", "]", "parameter_units", "=", "str", "(", "self", ".", "parameters", "[", "'parameter'", ...
Apply units to :class:`ParameterizedXLS` data reader.
[ "Apply", "units", "to", ":", "class", ":", "ParameterizedXLS", "data", "reader", "." ]
python
train
40.545455
googleapis/google-cloud-python
bigquery/google/cloud/bigquery/client.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L869-L891
def job_from_resource(self, resource): """Detect correct job type from resource and instantiate. :type resource: dict :param resource: one job resource from API response :rtype: One of: :class:`google.cloud.bigquery.job.LoadJob`, :class:`google.cloud.big...
[ "def", "job_from_resource", "(", "self", ",", "resource", ")", ":", "config", "=", "resource", ".", "get", "(", "\"configuration\"", ",", "{", "}", ")", "if", "\"load\"", "in", "config", ":", "return", "job", ".", "LoadJob", ".", "from_api_repr", "(", "r...
Detect correct job type from resource and instantiate. :type resource: dict :param resource: one job resource from API response :rtype: One of: :class:`google.cloud.bigquery.job.LoadJob`, :class:`google.cloud.bigquery.job.CopyJob`, :class:`google...
[ "Detect", "correct", "job", "type", "from", "resource", "and", "instantiate", "." ]
python
train
43.695652
hasgeek/coaster
coaster/sqlalchemy/mixins.py
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/mixins.py#L386-L394
def upsert(cls, name, **fields): """Insert or update an instance""" instance = cls.get(name) if instance: instance._set_fields(fields) else: instance = cls(name=name, **fields) instance = failsafe_add(cls.query.session, instance, name=name) ret...
[ "def", "upsert", "(", "cls", ",", "name", ",", "*", "*", "fields", ")", ":", "instance", "=", "cls", ".", "get", "(", "name", ")", "if", "instance", ":", "instance", ".", "_set_fields", "(", "fields", ")", "else", ":", "instance", "=", "cls", "(", ...
Insert or update an instance
[ "Insert", "or", "update", "an", "instance" ]
python
train
36
spookylukey/django-paypal
paypal/standard/models.py
https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/standard/models.py#L385-L393
def initialize(self, request): """Store the data we'll need to make the postback from the request object.""" if request.method == 'GET': # PDT only - this data is currently unused self.query = request.META.get('QUERY_STRING', '') elif request.method == 'POST': ...
[ "def", "initialize", "(", "self", ",", "request", ")", ":", "if", "request", ".", "method", "==", "'GET'", ":", "# PDT only - this data is currently unused", "self", ".", "query", "=", "request", ".", "META", ".", "get", "(", "'QUERY_STRING'", ",", "''", ")"...
Store the data we'll need to make the postback from the request object.
[ "Store", "the", "data", "we", "ll", "need", "to", "make", "the", "postback", "from", "the", "request", "object", "." ]
python
train
55.666667
DataONEorg/d1_python
lib_common/src/d1_common/checksum.py
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/checksum.py#L168-L189
def calculate_checksum_on_bytes( b, algorithm=d1_common.const.DEFAULT_CHECKSUM_ALGORITHM ): """Calculate the checksum of ``bytes``. Warning: This method requires the entire object to be buffered in (virtual) memory, which should normally be avoided in production code. Args: b: bytes ...
[ "def", "calculate_checksum_on_bytes", "(", "b", ",", "algorithm", "=", "d1_common", ".", "const", ".", "DEFAULT_CHECKSUM_ALGORITHM", ")", ":", "checksum_calc", "=", "get_checksum_calculator_by_dataone_designator", "(", "algorithm", ")", "checksum_calc", ".", "update", "...
Calculate the checksum of ``bytes``. Warning: This method requires the entire object to be buffered in (virtual) memory, which should normally be avoided in production code. Args: b: bytes Raw bytes algorithm: str Checksum algorithm, ``MD5`` or ``SHA1`` / ``SHA-1``. Retur...
[ "Calculate", "the", "checksum", "of", "bytes", "." ]
python
train
29.090909
pypa/pipenv
pipenv/patched/notpip/_internal/req/req_uninstall.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/req_uninstall.py#L241-L258
def stash(self, path): """Stashes the directory or file and returns its new location. """ if os.path.isdir(path): new_path = self._get_directory_stash(path) else: new_path = self._get_file_stash(path) self._moves.append((path, new_path)) if os.pat...
[ "def", "stash", "(", "self", ",", "path", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "new_path", "=", "self", ".", "_get_directory_stash", "(", "path", ")", "else", ":", "new_path", "=", "self", ".", "_get_file_stash", "(...
Stashes the directory or file and returns its new location.
[ "Stashes", "the", "directory", "or", "file", "and", "returns", "its", "new", "location", "." ]
python
train
38.388889
xeroc/python-graphenelib
graphenebase/operationids.py
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/operationids.py#L14-L21
def getOperationNameForId(i: int): """ Convert an operation id into the corresponding string """ assert isinstance(i, (int)), "This method expects an integer argument" for key in operations: if int(operations[key]) is int(i): return key raise ValueError("Unknown Operation ID %d" ...
[ "def", "getOperationNameForId", "(", "i", ":", "int", ")", ":", "assert", "isinstance", "(", "i", ",", "(", "int", ")", ")", ",", "\"This method expects an integer argument\"", "for", "key", "in", "operations", ":", "if", "int", "(", "operations", "[", "key"...
Convert an operation id into the corresponding string
[ "Convert", "an", "operation", "id", "into", "the", "corresponding", "string" ]
python
valid
39.625
ethereum/pyethereum
ethereum/experimental/pruning_trie.py
https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/experimental/pruning_trie.py#L154-L168
def unpack_to_nibbles(bindata): """unpack packed binary data to nibbles :param bindata: binary packed from nibbles :return: nibbles sequence, may have a terminator """ o = bin_to_nibbles(bindata) flags = o[0] if flags & 2: o.append(NIBBLE_TERMINATOR) if flags & 1 == 1: o...
[ "def", "unpack_to_nibbles", "(", "bindata", ")", ":", "o", "=", "bin_to_nibbles", "(", "bindata", ")", "flags", "=", "o", "[", "0", "]", "if", "flags", "&", "2", ":", "o", ".", "append", "(", "NIBBLE_TERMINATOR", ")", "if", "flags", "&", "1", "==", ...
unpack packed binary data to nibbles :param bindata: binary packed from nibbles :return: nibbles sequence, may have a terminator
[ "unpack", "packed", "binary", "data", "to", "nibbles" ]
python
train
23.666667
studionow/pybrightcove
pybrightcove/http_core.py
https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/http_core.py#L138-L145
def _copy(self): """Creates a deep copy of this request.""" copied_uri = Uri(self.uri.scheme, self.uri.host, self.uri.port, self.uri.path, self.uri.query.copy()) new_request = HttpRequest(uri=copied_uri, method=self.method, headers=self.headers.copy()) ...
[ "def", "_copy", "(", "self", ")", ":", "copied_uri", "=", "Uri", "(", "self", ".", "uri", ".", "scheme", ",", "self", ".", "uri", ".", "host", ",", "self", ".", "uri", ".", "port", ",", "self", ".", "uri", ".", "path", ",", "self", ".", "uri", ...
Creates a deep copy of this request.
[ "Creates", "a", "deep", "copy", "of", "this", "request", "." ]
python
train
47.625
rootpy/rootpy
rootpy/plotting/base.py
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/base.py#L484-L519
def Draw(self, *args, **kwargs): """ Parameters ---------- args : positional arguments Positional arguments are passed directly to ROOT's Draw kwargs : keyword arguments If keyword arguments are present, then a clone is drawn instead with DrawC...
[ "def", "Draw", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ":", "return", "self", ".", "DrawCopy", "(", "*", "args", ",", "*", "*", "kwargs", ")", "pad", "=", "ROOT", ".", "gPad", "own_pad", "=", "False", "...
Parameters ---------- args : positional arguments Positional arguments are passed directly to ROOT's Draw kwargs : keyword arguments If keyword arguments are present, then a clone is drawn instead with DrawCopy, where the name, title, and style attributes are ...
[ "Parameters", "----------", "args", ":", "positional", "arguments", "Positional", "arguments", "are", "passed", "directly", "to", "ROOT", "s", "Draw", "kwargs", ":", "keyword", "arguments", "If", "keyword", "arguments", "are", "present", "then", "a", "clone", "i...
python
train
33.5
shaldengeki/python-mal
myanimelist/media.py
https://github.com/shaldengeki/python-mal/blob/2c3356411a74d88ba13f6b970388040d696f8392/myanimelist/media.py#L470-L479
def load_characters(self): """Fetches the MAL media characters page and sets the current media's character attributes. :rtype: :class:`.Media` :return: current media object. """ characters_page = self.session.session.get(u'http://myanimelist.net/' + self.__class__.__name__.lower() + u'/' + str(sel...
[ "def", "load_characters", "(", "self", ")", ":", "characters_page", "=", "self", ".", "session", ".", "session", ".", "get", "(", "u'http://myanimelist.net/'", "+", "self", ".", "__class__", ".", "__name__", ".", "lower", "(", ")", "+", "u'/'", "+", "str",...
Fetches the MAL media characters page and sets the current media's character attributes. :rtype: :class:`.Media` :return: current media object.
[ "Fetches", "the", "MAL", "media", "characters", "page", "and", "sets", "the", "current", "media", "s", "character", "attributes", "." ]
python
train
47.4
spyder-ide/spyder
spyder/plugins/console/widgets/shell.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/shell.py#L530-L545
def write(self, text, flush=False, error=False, prompt=False): """Simulate stdout and stderr""" if prompt: self.flush() if not is_string(text): # This test is useful to discriminate QStrings from decoded str text = to_text_string(text) self.__bu...
[ "def", "write", "(", "self", ",", "text", ",", "flush", "=", "False", ",", "error", "=", "False", ",", "prompt", "=", "False", ")", ":", "if", "prompt", ":", "self", ".", "flush", "(", ")", "if", "not", "is_string", "(", "text", ")", ":", "# This...
Simulate stdout and stderr
[ "Simulate", "stdout", "and", "stderr" ]
python
train
41.6875
saltstack/salt
salt/runners/manage.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/manage.py#L182-L205
def up(tgt='*', tgt_type='glob', timeout=None, gather_job_timeout=None): # pylint: disable=C0103 ''' .. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Print a list of all of the minions that are up CLI Ex...
[ "def", "up", "(", "tgt", "=", "'*'", ",", "tgt_type", "=", "'glob'", ",", "timeout", "=", "None", ",", "gather_job_timeout", "=", "None", ")", ":", "# pylint: disable=C0103", "ret", "=", "status", "(", "output", "=", "False", ",", "tgt", "=", "tgt", ",...
.. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Print a list of all of the minions that are up CLI Example: .. code-block:: bash salt-run manage.up salt-run manage.up tgt="webservers" tgt_t...
[ "..", "versionchanged", "::", "2017", ".", "7", ".", "0", "The", "expr_form", "argument", "has", "been", "renamed", "to", "tgt_type", "earlier", "releases", "must", "use", "expr_form", "." ]
python
train
28.291667
Pythonity/icon-font-to-png
icon_font_to_png/command_line.py
https://github.com/Pythonity/icon-font-to-png/blob/4851fe15c077402749f843d43fbc10d28f6c655d/icon_font_to_png/command_line.py#L168-L177
def download_icon_font(icon_font, directory): """Download given (implemented) icon font into passed directory""" try: downloader = AVAILABLE_ICON_FONTS[icon_font]['downloader'](directory) downloader.download_files() return downloader except KeyError: # pragma: no cover raise...
[ "def", "download_icon_font", "(", "icon_font", ",", "directory", ")", ":", "try", ":", "downloader", "=", "AVAILABLE_ICON_FONTS", "[", "icon_font", "]", "[", "'downloader'", "]", "(", "directory", ")", "downloader", ".", "download_files", "(", ")", "return", "...
Download given (implemented) icon font into passed directory
[ "Download", "given", "(", "implemented", ")", "icon", "font", "into", "passed", "directory" ]
python
train
41.2
davisd50/sparc.cache
sparc/cache/splunk/area.py
https://github.com/davisd50/sparc.cache/blob/f2378aad48c368a53820e97b093ace790d4d4121/sparc/cache/splunk/area.py#L51-L53
def current_kv_names(self): """Return set of string names of current available Splunk KV collections""" return current_kv_names(self.sci, self.username, self.appname, request=self._request)
[ "def", "current_kv_names", "(", "self", ")", ":", "return", "current_kv_names", "(", "self", ".", "sci", ",", "self", ".", "username", ",", "self", ".", "appname", ",", "request", "=", "self", ".", "_request", ")" ]
Return set of string names of current available Splunk KV collections
[ "Return", "set", "of", "string", "names", "of", "current", "available", "Splunk", "KV", "collections" ]
python
train
67.666667
DeV1doR/aioethereum
aioethereum/management/personal.py
https://github.com/DeV1doR/aioethereum/blob/85eb46550d862b3ccc309914ea871ca1c7b42157/aioethereum/management/personal.py#L57-L72
def personal_unlockAccount(self, address, passphrase=None, duration=None): """https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_unlockaccount :param address: Account address :type address: str :param passphrase: Passphrase of account (optional) :type passphr...
[ "def", "personal_unlockAccount", "(", "self", ",", "address", ",", "passphrase", "=", "None", ",", "duration", "=", "None", ")", ":", "return", "(", "yield", "from", "self", ".", "rpc_call", "(", "'personal_unlockAccount'", ",", "[", "address", ",", "passphr...
https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_unlockaccount :param address: Account address :type address: str :param passphrase: Passphrase of account (optional) :type passphrase: str :param duration: Duration to be unlocked (optional) :type du...
[ "https", ":", "//", "github", ".", "com", "/", "ethereum", "/", "go", "-", "ethereum", "/", "wiki", "/", "Management", "-", "APIs#personal_unlockaccount" ]
python
train
36.125
pmichali/whodunit
whodunit/__init__.py
https://github.com/pmichali/whodunit/blob/eed9107533766d716469e35fbb647a39dfa07035/whodunit/__init__.py#L467-L477
def sort_by_name(names): """Sort by last name, uniquely.""" def last_name_key(full_name): parts = full_name.split(' ') if len(parts) == 1: return full_name.upper() last_first = parts[-1] + ' ' + ' '.join(parts[:-1]) return last_first.upper() return sorted(set(na...
[ "def", "sort_by_name", "(", "names", ")", ":", "def", "last_name_key", "(", "full_name", ")", ":", "parts", "=", "full_name", ".", "split", "(", "' '", ")", "if", "len", "(", "parts", ")", "==", "1", ":", "return", "full_name", ".", "upper", "(", ")"...
Sort by last name, uniquely.
[ "Sort", "by", "last", "name", "uniquely", "." ]
python
train
30.363636
moderngl/moderngl
moderngl/framebuffer.py
https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/framebuffer.py#L38-L43
def viewport(self) -> Tuple[int, int, int, int]: ''' tuple: The viewport of the framebuffer. ''' return self.mglo.viewport
[ "def", "viewport", "(", "self", ")", "->", "Tuple", "[", "int", ",", "int", ",", "int", ",", "int", "]", ":", "return", "self", ".", "mglo", ".", "viewport" ]
tuple: The viewport of the framebuffer.
[ "tuple", ":", "The", "viewport", "of", "the", "framebuffer", "." ]
python
train
25.666667
moliware/dicts
dicts/dict.py
https://github.com/moliware/dicts/blob/0e8258cc3dc00fe929685cae9cda062222722715/dicts/dict.py#L30-L33
def map(self, callable): """ Apply 'callable' function over all values. """ for k,v in self.iteritems(): self[k] = callable(v)
[ "def", "map", "(", "self", ",", "callable", ")", ":", "for", "k", ",", "v", "in", "self", ".", "iteritems", "(", ")", ":", "self", "[", "k", "]", "=", "callable", "(", "v", ")" ]
Apply 'callable' function over all values.
[ "Apply", "callable", "function", "over", "all", "values", "." ]
python
train
37.75
mitsei/dlkit
dlkit/json_/assessment/mixins.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment/mixins.py#L712-L718
def get_correctness(self, question_id): """get measure of correctness for the question""" response = self.get_response(question_id) if response.is_answered(): item = self._get_item(response.get_item_id()) return item.get_correctness_for_response(response) raise er...
[ "def", "get_correctness", "(", "self", ",", "question_id", ")", ":", "response", "=", "self", ".", "get_response", "(", "question_id", ")", "if", "response", ".", "is_answered", "(", ")", ":", "item", "=", "self", ".", "_get_item", "(", "response", ".", ...
get measure of correctness for the question
[ "get", "measure", "of", "correctness", "for", "the", "question" ]
python
train
47.571429
tokibito/django-ftpserver
django_ftpserver/filesystems.py
https://github.com/tokibito/django-ftpserver/blob/18cf9f6645df9c2d9c5188bf21e74c188d55de47/django_ftpserver/filesystems.py#L68-L73
def _exists(self, path): """S3 directory is not S3Ojbect. """ if path.endswith('/'): return True return self.storage.exists(path)
[ "def", "_exists", "(", "self", ",", "path", ")", ":", "if", "path", ".", "endswith", "(", "'/'", ")", ":", "return", "True", "return", "self", ".", "storage", ".", "exists", "(", "path", ")" ]
S3 directory is not S3Ojbect.
[ "S3", "directory", "is", "not", "S3Ojbect", "." ]
python
train
28
dslackw/slpkg
slpkg/tracking.py
https://github.com/dslackw/slpkg/blob/dd2e08a80e944d337d157b992167ba631a4343de/slpkg/tracking.py#L125-L142
def repositories(self): """Get dependencies by repositories """ if self.repo == "sbo": self.sbo_case_insensitive() self.find_pkg = sbo_search_pkg(self.name) if self.find_pkg: self.dependencies_list = Requires(self.flag).sbo(self.name) e...
[ "def", "repositories", "(", "self", ")", ":", "if", "self", ".", "repo", "==", "\"sbo\"", ":", "self", ".", "sbo_case_insensitive", "(", ")", "self", ".", "find_pkg", "=", "sbo_search_pkg", "(", "self", ".", "name", ")", "if", "self", ".", "find_pkg", ...
Get dependencies by repositories
[ "Get", "dependencies", "by", "repositories" ]
python
train
45.777778
Tanganelli/CoAPthon3
coapthon/forward_proxy/coap.py
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/forward_proxy/coap.py#L153-L162
def close(self): """ Stop the server. """ logger.info("Stop server") self.stopped.set() for event in self.to_be_stopped: event.set() self._socket.close()
[ "def", "close", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Stop server\"", ")", "self", ".", "stopped", ".", "set", "(", ")", "for", "event", "in", "self", ".", "to_be_stopped", ":", "event", ".", "set", "(", ")", "self", ".", "_socket", ...
Stop the server.
[ "Stop", "the", "server", "." ]
python
train
21.3
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L339-L362
def prefilter_lines(self, lines, continue_prompt=False): """Prefilter multiple input lines of text. This is the main entry point for prefiltering multiple lines of input. This simply calls :meth:`prefilter_line` for each line of input. This covers cases where there are multipl...
[ "def", "prefilter_lines", "(", "self", ",", "lines", ",", "continue_prompt", "=", "False", ")", ":", "llines", "=", "lines", ".", "rstrip", "(", "'\\n'", ")", ".", "split", "(", "'\\n'", ")", "# We can get multiple lines in one shot, where multiline input 'blends'",...
Prefilter multiple input lines of text. This is the main entry point for prefiltering multiple lines of input. This simply calls :meth:`prefilter_line` for each line of input. This covers cases where there are multiple lines in the user entry, which is the case when the user g...
[ "Prefilter", "multiple", "input", "lines", "of", "text", "." ]
python
test
44.666667
softlayer/softlayer-python
SoftLayer/managers/block.py
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/block.py#L306-L333
def order_modified_volume(self, volume_id, new_size=None, new_iops=None, new_tier_level=None): """Places an order for modifying an existing block volume. :param volume_id: The ID of the volume to be modified :param new_size: The new size/capacity for the volume :param new_iops: The new ...
[ "def", "order_modified_volume", "(", "self", ",", "volume_id", ",", "new_size", "=", "None", ",", "new_iops", "=", "None", ",", "new_tier_level", "=", "None", ")", ":", "mask_items", "=", "[", "'id'", ",", "'billingItem'", ",", "'storageType[keyName]'", ",", ...
Places an order for modifying an existing block volume. :param volume_id: The ID of the volume to be modified :param new_size: The new size/capacity for the volume :param new_iops: The new IOPS for the volume :param new_tier_level: The new tier level for the volume :return: Retu...
[ "Places", "an", "order", "for", "modifying", "an", "existing", "block", "volume", "." ]
python
train
37.285714
KrzyHonk/bpmn-python
bpmn_python/bpmn_diagram_export.py
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_export.py#L158-L171
def export_throw_event_info(node_params, output_element): """ Adds EndEvent or IntermediateThrowingEvent attributes to exported XML element :param node_params: dictionary with given intermediate throw event parameters, :param output_element: object representing BPMN XML 'intermediateThr...
[ "def", "export_throw_event_info", "(", "node_params", ",", "output_element", ")", ":", "definitions", "=", "node_params", "[", "consts", ".", "Consts", ".", "event_definitions", "]", "for", "definition", "in", "definitions", ":", "definition_id", "=", "definition", ...
Adds EndEvent or IntermediateThrowingEvent attributes to exported XML element :param node_params: dictionary with given intermediate throw event parameters, :param output_element: object representing BPMN XML 'intermediateThrowEvent' element.
[ "Adds", "EndEvent", "or", "IntermediateThrowingEvent", "attributes", "to", "exported", "XML", "element" ]
python
train
54.285714
hobson/pug-invest
pug/invest/util.py
https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L910-L1004
def estimate_shift(x, y, smoother=None, w=None, index_and_value=False, ignore_edge=1/3., method='valid'): """Estimate the time shift between two signals based on their cross correlation Arguements: smoother: Smoothing function applied to correlation values before finding peak w:...
[ "def", "estimate_shift", "(", "x", ",", "y", ",", "smoother", "=", "None", ",", "w", "=", "None", ",", "index_and_value", "=", "False", ",", "ignore_edge", "=", "1", "/", "3.", ",", "method", "=", "'valid'", ")", ":", "return", "NotImplementedError", "...
Estimate the time shift between two signals based on their cross correlation Arguements: smoother: Smoothing function applied to correlation values before finding peak w: Window. Sequence of values between 0 and 1 for wind centered on 0-shift to weight correlation by before fi...
[ "Estimate", "the", "time", "shift", "between", "two", "signals", "based", "on", "their", "cross", "correlation" ]
python
train
28.978947
DAI-Lab/Copulas
copulas/bivariate/base.py
https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/bivariate/base.py#L191-L207
def sample(self, n_samples): """Generate specified `n_samples` of new data from model. `v~U[0,1],v~C^-1(u|v)` Args: n_samples: `int`, amount of samples to create. Returns: np.ndarray: Array of length `n_samples` with generated data from the model. """ if...
[ "def", "sample", "(", "self", ",", "n_samples", ")", ":", "if", "self", ".", "tau", ">", "1", "or", "self", ".", "tau", "<", "-", "1", ":", "raise", "ValueError", "(", "\"The range for correlation measure is [-1,1].\"", ")", "v", "=", "np", ".", "random"...
Generate specified `n_samples` of new data from model. `v~U[0,1],v~C^-1(u|v)` Args: n_samples: `int`, amount of samples to create. Returns: np.ndarray: Array of length `n_samples` with generated data from the model.
[ "Generate", "specified", "n_samples", "of", "new", "data", "from", "model", ".", "v~U", "[", "0", "1", "]", "v~C^", "-", "1", "(", "u|v", ")" ]
python
train
34.352941
buildbot/buildbot
master/buildbot/reporters/gitlab.py
https://github.com/buildbot/buildbot/blob/5df3cfae6d760557d99156633c32b1822a1e130c/master/buildbot/reporters/gitlab.py#L63-L91
def createStatus(self, project_id, branch, sha, state, target_url=None, description=None, context=None): """ :param project_id: Project ID from GitLab :param branch: Branch name to create the status for. :param sha: Full sha to create the status ...
[ "def", "createStatus", "(", "self", ",", "project_id", ",", "branch", ",", "sha", ",", "state", ",", "target_url", "=", "None", ",", "description", "=", "None", ",", "context", "=", "None", ")", ":", "payload", "=", "{", "'state'", ":", "state", ",", ...
:param project_id: Project ID from GitLab :param branch: Branch name to create the status for. :param sha: Full sha to create the status for. :param state: one of the following 'pending', 'success', 'failed' or 'cancelled'. :param target_url: Target url to associate...
[ ":", "param", "project_id", ":", "Project", "ID", "from", "GitLab", ":", "param", "branch", ":", "Branch", "name", "to", "create", "the", "status", "for", ".", ":", "param", "sha", ":", "Full", "sha", "to", "create", "the", "status", "for", ".", ":", ...
python
train
36.896552
nerdvegas/rez
src/rez/config.py
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/config.py#L524-L529
def nonlocal_packages_path(self): """Returns package search paths with local path removed.""" paths = self.packages_path[:] if self.local_packages_path in paths: paths.remove(self.local_packages_path) return paths
[ "def", "nonlocal_packages_path", "(", "self", ")", ":", "paths", "=", "self", ".", "packages_path", "[", ":", "]", "if", "self", ".", "local_packages_path", "in", "paths", ":", "paths", ".", "remove", "(", "self", ".", "local_packages_path", ")", "return", ...
Returns package search paths with local path removed.
[ "Returns", "package", "search", "paths", "with", "local", "path", "removed", "." ]
python
train
42
savoirfairelinux/num2words
num2words/base.py
https://github.com/savoirfairelinux/num2words/blob/f4b2bac098ae8e4850cf2f185f6ff52a5979641f/num2words/base.py#L266-L303
def to_currency(self, val, currency='EUR', cents=True, separator=',', adjective=False): """ Args: val: Numeric value currency (str): Currency code cents (bool): Verbose cents separator (str): Cent separator adjective (bool):...
[ "def", "to_currency", "(", "self", ",", "val", ",", "currency", "=", "'EUR'", ",", "cents", "=", "True", ",", "separator", "=", "','", ",", "adjective", "=", "False", ")", ":", "left", ",", "right", ",", "is_negative", "=", "parse_currency_parts", "(", ...
Args: val: Numeric value currency (str): Currency code cents (bool): Verbose cents separator (str): Cent separator adjective (bool): Prefix currency name with adjective Returns: str: Formatted string
[ "Args", ":", "val", ":", "Numeric", "value", "currency", "(", "str", ")", ":", "Currency", "code", "cents", "(", "bool", ")", ":", "Verbose", "cents", "separator", "(", "str", ")", ":", "Cent", "separator", "adjective", "(", "bool", ")", ":", "Prefix",...
python
test
32.868421
nuclio/nuclio-sdk-py
nuclio_sdk/event.py
https://github.com/nuclio/nuclio-sdk-py/blob/5af9ffc19a0d96255ff430bc358be9cd7a57f424/nuclio_sdk/event.py#L102-L119
def decode_body(body, content_type): """Decode event body""" if isinstance(body, dict): return body else: try: decoded_body = base64.b64decode(body) except: return body if content_type == 'application/json': ...
[ "def", "decode_body", "(", "body", ",", "content_type", ")", ":", "if", "isinstance", "(", "body", ",", "dict", ")", ":", "return", "body", "else", ":", "try", ":", "decoded_body", "=", "base64", ".", "b64decode", "(", "body", ")", "except", ":", "retu...
Decode event body
[ "Decode", "event", "body" ]
python
train
25.055556
deontologician/restnavigator
restnavigator/utils.py
https://github.com/deontologician/restnavigator/blob/453b9de4e70e602009d3e3ffafcf77d23c8b07c5/restnavigator/utils.py#L226-L229
def named(self, name): '''Returns .get_by('name', name)''' name = self.serialize(name) return self.get_by('name', name)
[ "def", "named", "(", "self", ",", "name", ")", ":", "name", "=", "self", ".", "serialize", "(", "name", ")", "return", "self", ".", "get_by", "(", "'name'", ",", "name", ")" ]
Returns .get_by('name', name)
[ "Returns", ".", "get_by", "(", "name", "name", ")" ]
python
train
35
PythonCharmers/python-future
src/future/standard_library/__init__.py
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/standard_library/__init__.py#L600-L615
def cache_py2_modules(): """ Currently this function is unneeded, as we are not attempting to provide import hooks for modules with ambiguous names: email, urllib, pickle. """ if len(sys.py2_modules) != 0: return assert not detect_hooks() import urllib sys.py2_modules['urllib'] =...
[ "def", "cache_py2_modules", "(", ")", ":", "if", "len", "(", "sys", ".", "py2_modules", ")", "!=", "0", ":", "return", "assert", "not", "detect_hooks", "(", ")", "import", "urllib", "sys", ".", "py2_modules", "[", "'urllib'", "]", "=", "urllib", "import"...
Currently this function is unneeded, as we are not attempting to provide import hooks for modules with ambiguous names: email, urllib, pickle.
[ "Currently", "this", "function", "is", "unneeded", "as", "we", "are", "not", "attempting", "to", "provide", "import", "hooks", "for", "modules", "with", "ambiguous", "names", ":", "email", "urllib", "pickle", "." ]
python
train
26.5625
IRC-SPHERE/HyperStream
hyperstream/plate/plate_manager.py
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/plate/plate_manager.py#L71-L98
def delete_plate(self, plate_id, delete_meta_data=False): """ Delete a plate from the database :param plate_id: The plate id :param delete_meta_data: Optionally delete all meta data associated with this plate as well :return: None """ if plate_id not in ...
[ "def", "delete_plate", "(", "self", ",", "plate_id", ",", "delete_meta_data", "=", "False", ")", ":", "if", "plate_id", "not", "in", "self", ".", "plates", ":", "logging", ".", "info", "(", "\"Plate {} not found for deletion\"", ".", "format", "(", "plate_id",...
Delete a plate from the database :param plate_id: The plate id :param delete_meta_data: Optionally delete all meta data associated with this plate as well :return: None
[ "Delete", "a", "plate", "from", "the", "database", ":", "param", "plate_id", ":", "The", "plate", "id", ":", "param", "delete_meta_data", ":", "Optionally", "delete", "all", "meta", "data", "associated", "with", "this", "plate", "as", "well", ":", "return", ...
python
train
35.464286
annoviko/pyclustering
pyclustering/utils/__init__.py
https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/utils/__init__.py#L1230-L1241
def list_math_addition(a, b): """! @brief Addition of two lists. @details Each element from list 'a' is added to element from list 'b' accordingly. @param[in] a (list): List of elements that supports mathematic addition.. @param[in] b (list): List of elements that supports mathematic addi...
[ "def", "list_math_addition", "(", "a", ",", "b", ")", ":", "return", "[", "a", "[", "i", "]", "+", "b", "[", "i", "]", "for", "i", "in", "range", "(", "len", "(", "a", ")", ")", "]" ]
! @brief Addition of two lists. @details Each element from list 'a' is added to element from list 'b' accordingly. @param[in] a (list): List of elements that supports mathematic addition.. @param[in] b (list): List of elements that supports mathematic addition.. @return (list) Resul...
[ "!" ]
python
valid
36.916667
ARMmbed/autoversion
src/auto_version/auto_version_tool.py
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/auto_version_tool.py#L98-L108
def detect_file_triggers(trigger_patterns): """The existence of files matching configured globs will trigger a version bump""" triggers = set() for trigger, pattern in trigger_patterns.items(): matches = glob.glob(pattern) if matches: _LOG.debug("trigger: %s bump from %r\n\t%s", ...
[ "def", "detect_file_triggers", "(", "trigger_patterns", ")", ":", "triggers", "=", "set", "(", ")", "for", "trigger", ",", "pattern", "in", "trigger_patterns", ".", "items", "(", ")", ":", "matches", "=", "glob", ".", "glob", "(", "pattern", ")", "if", "...
The existence of files matching configured globs will trigger a version bump
[ "The", "existence", "of", "files", "matching", "configured", "globs", "will", "trigger", "a", "version", "bump" ]
python
train
42.090909
saltstack/salt
salt/modules/neutronng.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutronng.py#L463-L484
def security_group_get(auth=None, **kwargs): ''' Get a single security group. This will create a default security group if one does not exist yet for a particular project id. filters A Python dictionary of filter conditions to push down CLI Example: .. code-block:: bash salt ...
[ "def", "security_group_get", "(", "auth", "=", "None", ",", "*", "*", "kwargs", ")", ":", "cloud", "=", "get_operator_cloud", "(", "auth", ")", "kwargs", "=", "_clean_kwargs", "(", "*", "*", "kwargs", ")", "return", "cloud", ".", "get_security_group", "(",...
Get a single security group. This will create a default security group if one does not exist yet for a particular project id. filters A Python dictionary of filter conditions to push down CLI Example: .. code-block:: bash salt '*' neutronng.security_group_get \ name=1dcac31...
[ "Get", "a", "single", "security", "group", ".", "This", "will", "create", "a", "default", "security", "group", "if", "one", "does", "not", "exist", "yet", "for", "a", "particular", "project", "id", "." ]
python
train
29.590909
swisscom/cleanerversion
versions/util/postgresql.py
https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/util/postgresql.py#L22-L48
def remove_uuid_id_like_indexes(app_name, database=None): """ Remove all of varchar_pattern_ops indexes that django created for uuid columns. A search is never done with a filter of the style (uuid__like='1ae3c%'), so all such indexes can be removed from Versionable models. This will only try to...
[ "def", "remove_uuid_id_like_indexes", "(", "app_name", ",", "database", "=", "None", ")", ":", "removed_indexes", "=", "0", "with", "database_connection", "(", "database", ")", ".", "cursor", "(", ")", "as", "cursor", ":", "for", "model", "in", "versionable_mo...
Remove all of varchar_pattern_ops indexes that django created for uuid columns. A search is never done with a filter of the style (uuid__like='1ae3c%'), so all such indexes can be removed from Versionable models. This will only try to remove indexes if they exist in the database, so it should be saf...
[ "Remove", "all", "of", "varchar_pattern_ops", "indexes", "that", "django", "created", "for", "uuid", "columns", ".", "A", "search", "is", "never", "done", "with", "a", "filter", "of", "the", "style", "(", "uuid__like", "=", "1ae3c%", ")", "so", "all", "suc...
python
train
44.888889
dsoprea/PySchedules
pyschedules/xml_callbacks.py
https://github.com/dsoprea/PySchedules/blob/e5aae988fad90217f72db45f93bf69839f4d75e7/pyschedules/xml_callbacks.py#L178-L195
def _startProgramsNode(self, name, attrs): """Process the start of a node under xtvd/programs""" if name == 'program': self._programId = attrs.get('id') self._series = None self._title = None self._subtitle = None self._description = None ...
[ "def", "_startProgramsNode", "(", "self", ",", "name", ",", "attrs", ")", ":", "if", "name", "==", "'program'", ":", "self", ".", "_programId", "=", "attrs", ".", "get", "(", "'id'", ")", "self", ".", "_series", "=", "None", "self", ".", "_title", "=...
Process the start of a node under xtvd/programs
[ "Process", "the", "start", "of", "a", "node", "under", "xtvd", "/", "programs" ]
python
train
34.777778
twisted/txaws
txaws/wsdl.py
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/wsdl.py#L243-L245
def _create_child(self, tag): """Create a new child element with the given tag.""" return etree.SubElement(self._root, self._get_namespace_tag(tag))
[ "def", "_create_child", "(", "self", ",", "tag", ")", ":", "return", "etree", ".", "SubElement", "(", "self", ".", "_root", ",", "self", ".", "_get_namespace_tag", "(", "tag", ")", ")" ]
Create a new child element with the given tag.
[ "Create", "a", "new", "child", "element", "with", "the", "given", "tag", "." ]
python
train
54
LuminosoInsight/langcodes
langcodes/__init__.py
https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/__init__.py#L845-L859
def to_dict(self): """ Get a dictionary of the attributes of this Language object, which can be useful for constructing a similar object. """ if self._dict is not None: return self._dict result = {} for key in self.ATTRIBUTES: value = geta...
[ "def", "to_dict", "(", "self", ")", ":", "if", "self", ".", "_dict", "is", "not", "None", ":", "return", "self", ".", "_dict", "result", "=", "{", "}", "for", "key", "in", "self", ".", "ATTRIBUTES", ":", "value", "=", "getattr", "(", "self", ",", ...
Get a dictionary of the attributes of this Language object, which can be useful for constructing a similar object.
[ "Get", "a", "dictionary", "of", "the", "attributes", "of", "this", "Language", "object", "which", "can", "be", "useful", "for", "constructing", "a", "similar", "object", "." ]
python
train
28.533333
mixmastamyk/fr
fr/ansi.py
https://github.com/mixmastamyk/fr/blob/f96df8ed7210a033b9e711bbed768d4116213bfb/fr/ansi.py#L108-L117
def colorstart(fgcolor, bgcolor, weight): ''' Begin a text style. ''' if weight: weight = bold else: weight = norm if bgcolor: out('\x1b[%s;%s;%sm' % (weight, fgcolor, bgcolor)) else: out('\x1b[%s;%sm' % (weight, fgcolor))
[ "def", "colorstart", "(", "fgcolor", ",", "bgcolor", ",", "weight", ")", ":", "if", "weight", ":", "weight", "=", "bold", "else", ":", "weight", "=", "norm", "if", "bgcolor", ":", "out", "(", "'\\x1b[%s;%s;%sm'", "%", "(", "weight", ",", "fgcolor", ","...
Begin a text style.
[ "Begin", "a", "text", "style", "." ]
python
train
26.5
Robpol86/sphinxcontrib-disqus
sphinxcontrib/disqus.py
https://github.com/Robpol86/sphinxcontrib-disqus/blob/1da36bcb83b82b6493a33481c03a0956a557bd5c/sphinxcontrib/disqus.py#L77-L89
def get_identifier(self): """Validate and returns disqus_identifier option value. :returns: disqus_identifier config value. :rtype: str """ if 'disqus_identifier' in self.options: return self.options['disqus_identifier'] title_nodes = self.state.document.tra...
[ "def", "get_identifier", "(", "self", ")", ":", "if", "'disqus_identifier'", "in", "self", ".", "options", ":", "return", "self", ".", "options", "[", "'disqus_identifier'", "]", "title_nodes", "=", "self", ".", "state", ".", "document", ".", "traverse", "("...
Validate and returns disqus_identifier option value. :returns: disqus_identifier config value. :rtype: str
[ "Validate", "and", "returns", "disqus_identifier", "option", "value", "." ]
python
train
38.923077
pandas-dev/pandas
pandas/core/sparse/series.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/sparse/series.py#L342-L364
def get_value(self, label, takeable=False): """ Retrieve single value at passed index label .. deprecated:: 0.21.0 Please use .at[] or .iat[] accessors. Parameters ---------- index : label takeable : interpret the index as indexers, default False ...
[ "def", "get_value", "(", "self", ",", "label", ",", "takeable", "=", "False", ")", ":", "warnings", ".", "warn", "(", "\"get_value is deprecated and will be removed \"", "\"in a future release. Please use \"", "\".at[] or .iat[] accessors instead\"", ",", "FutureWarning", "...
Retrieve single value at passed index label .. deprecated:: 0.21.0 Please use .at[] or .iat[] accessors. Parameters ---------- index : label takeable : interpret the index as indexers, default False Returns ------- value : scalar value
[ "Retrieve", "single", "value", "at", "passed", "index", "label" ]
python
train
28.652174
MacHu-GWU/angora-project
angora/dtypes/dicttree.py
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/dicttree.py#L287-L302
def k_depth(d, depth, _counter=1): """Iterate keys on specific depth. depth has to be greater equal than 0. Usage reference see :meth:`DictTree.kv_depth()<DictTree.kv_depth>` """ if depth == 0: yield d[_meta]["_rootname"] else: if _counter == dept...
[ "def", "k_depth", "(", "d", ",", "depth", ",", "_counter", "=", "1", ")", ":", "if", "depth", "==", "0", ":", "yield", "d", "[", "_meta", "]", "[", "\"_rootname\"", "]", "else", ":", "if", "_counter", "==", "depth", ":", "for", "key", "in", "Dict...
Iterate keys on specific depth. depth has to be greater equal than 0. Usage reference see :meth:`DictTree.kv_depth()<DictTree.kv_depth>`
[ "Iterate", "keys", "on", "specific", "depth", ".", "depth", "has", "to", "be", "greater", "equal", "than", "0", ".", "Usage", "reference", "see", ":", "meth", ":", "DictTree", ".", "kv_depth", "()", "<DictTree", ".", "kv_depth", ">" ]
python
train
36
quantopian/zipline
zipline/assets/assets.py
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/assets.py#L1416-L1456
def _compute_asset_lifetimes(self, country_codes): """ Compute and cache a recarray of asset lifetimes. """ equities_cols = self.equities.c if country_codes: buf = np.array( tuple( sa.select(( equities_cols.s...
[ "def", "_compute_asset_lifetimes", "(", "self", ",", "country_codes", ")", ":", "equities_cols", "=", "self", ".", "equities", ".", "c", "if", "country_codes", ":", "buf", "=", "np", ".", "array", "(", "tuple", "(", "sa", ".", "select", "(", "(", "equiti...
Compute and cache a recarray of asset lifetimes.
[ "Compute", "and", "cache", "a", "recarray", "of", "asset", "lifetimes", "." ]
python
train
32.95122
jrief/django-websocket-redis
ws4redis/uwsgi_runserver.py
https://github.com/jrief/django-websocket-redis/blob/abcddaad2f579d71dbf375e5e34bc35eef795a81/ws4redis/uwsgi_runserver.py#L12-L18
def get_file_descriptor(self): """Return the file descriptor for the given websocket""" try: return uwsgi.connection_fd() except IOError as e: self.close() raise WebSocketError(e)
[ "def", "get_file_descriptor", "(", "self", ")", ":", "try", ":", "return", "uwsgi", ".", "connection_fd", "(", ")", "except", "IOError", "as", "e", ":", "self", ".", "close", "(", ")", "raise", "WebSocketError", "(", "e", ")" ]
Return the file descriptor for the given websocket
[ "Return", "the", "file", "descriptor", "for", "the", "given", "websocket" ]
python
train
33.285714
10gen/mongo-orchestration
mongo_orchestration/apps/__init__.py
https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/apps/__init__.py#L39-L44
def setup_versioned_routes(routes, version=None): """Set up routes with a version prefix.""" prefix = '/' + version if version else "" for r in routes: path, method = r route(prefix + path, method, routes[r])
[ "def", "setup_versioned_routes", "(", "routes", ",", "version", "=", "None", ")", ":", "prefix", "=", "'/'", "+", "version", "if", "version", "else", "\"\"", "for", "r", "in", "routes", ":", "path", ",", "method", "=", "r", "route", "(", "prefix", "+",...
Set up routes with a version prefix.
[ "Set", "up", "routes", "with", "a", "version", "prefix", "." ]
python
train
38.5
tanghaibao/goatools
setup_helper.py
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/setup_helper.py#L58-L69
def install_requirements(self, requires): """ Install the listed requirements """ # Temporarily install dependencies required by setup.py before trying to import them. sys.path[0:0] = ['setup-requires'] pkg_resources.working_set.add_entry('setup-requires') to_install = l...
[ "def", "install_requirements", "(", "self", ",", "requires", ")", ":", "# Temporarily install dependencies required by setup.py before trying to import them.", "sys", ".", "path", "[", "0", ":", "0", "]", "=", "[", "'setup-requires'", "]", "pkg_resources", ".", "working...
Install the listed requirements
[ "Install", "the", "listed", "requirements" ]
python
train
43.083333
moralrecordings/mrcrowbar
mrcrowbar/utils.py
https://github.com/moralrecordings/mrcrowbar/blob/b1ed882c4555552e7656b2d84aca543184577fa3/mrcrowbar/utils.py#L15-L28
def enable_logging( level='WARNING' ): """Enable sending logs to stderr. Useful for shell sessions. level Logging threshold, as defined in the logging module of the Python standard library. Defaults to 'WARNING'. """ log = logging.getLogger( 'mrcrowbar' ) log.setLevel( level ) o...
[ "def", "enable_logging", "(", "level", "=", "'WARNING'", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "'mrcrowbar'", ")", "log", ".", "setLevel", "(", "level", ")", "out", "=", "logging", ".", "StreamHandler", "(", ")", "out", ".", "setLevel",...
Enable sending logs to stderr. Useful for shell sessions. level Logging threshold, as defined in the logging module of the Python standard library. Defaults to 'WARNING'.
[ "Enable", "sending", "logs", "to", "stderr", ".", "Useful", "for", "shell", "sessions", "." ]
python
train
34.928571
gem/oq-engine
openquake/hmtk/plotting/beachball.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/beachball.py#L852-L879
def MT2Axes(mt): """ Calculates the principal axes of a given moment tensor. :param mt: :class:`~MomentTensor` :return: tuple of :class:`~PrincipalAxis` T, N and P Adapted from ps_tensor / utilmeca.c / `Generic Mapping Tools (GMT) <http://gmt.soest.hawaii.edu>`_. """ (D, V) = np.linalg...
[ "def", "MT2Axes", "(", "mt", ")", ":", "(", "D", ",", "V", ")", "=", "np", ".", "linalg", ".", "eigh", "(", "mt", ".", "mt", ")", "pl", "=", "np", ".", "arcsin", "(", "-", "V", "[", "0", "]", ")", "az", "=", "np", ".", "arctan2", "(", "...
Calculates the principal axes of a given moment tensor. :param mt: :class:`~MomentTensor` :return: tuple of :class:`~PrincipalAxis` T, N and P Adapted from ps_tensor / utilmeca.c / `Generic Mapping Tools (GMT) <http://gmt.soest.hawaii.edu>`_.
[ "Calculates", "the", "principal", "axes", "of", "a", "given", "moment", "tensor", "." ]
python
train
27.035714
alexhayes/django-toolkit
django_toolkit/templatetags/sliced_pagination.py
https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/templatetags/sliced_pagination.py#L29-L61
def _build_full_list(self): """Build a full list of pages. Examples: >>> _SlicedPaginator(1, 7, 5)._build_full_list() [1, 2, 3, 4, 5] >>> _SlicedPaginator(6, 7, 5)._build_full_list() [3, 4, 5, 6, 7] >>> _SlicedPaginator(6, 7, 5)._build_full_list() ...
[ "def", "_build_full_list", "(", "self", ")", ":", "if", "self", ".", "npages", "<=", "self", ".", "maxpages_items", ":", "return", "range", "(", "1", ",", "self", ".", "npages", "+", "1", ")", "else", ":", "l", "=", "range", "(", "self", ".", "curp...
Build a full list of pages. Examples: >>> _SlicedPaginator(1, 7, 5)._build_full_list() [1, 2, 3, 4, 5] >>> _SlicedPaginator(6, 7, 5)._build_full_list() [3, 4, 5, 6, 7] >>> _SlicedPaginator(6, 7, 5)._build_full_list() [3, 4, 5, 6, 7] >>> import ite...
[ "Build", "a", "full", "list", "of", "pages", ".", "Examples", ":", ">>>", "_SlicedPaginator", "(", "1", "7", "5", ")", ".", "_build_full_list", "()", "[", "1", "2", "3", "4", "5", "]", ">>>", "_SlicedPaginator", "(", "6", "7", "5", ")", ".", "_buil...
python
train
37.545455
jpscaletti/pyceo
pyceo/command.py
https://github.com/jpscaletti/pyceo/blob/7f37eaf8e557d25f8e54634176139e0aad84b8df/pyceo/command.py#L9-L29
def get_doc(func): """Extract and dedent the __doc__ of a function. Unlike `textwrap.dedent()` it also works when the first line is not indented. """ doc = func.__doc__ if not doc: return "" # doc has only one line if "\n" not in doc: return doc # Only Python core ...
[ "def", "get_doc", "(", "func", ")", ":", "doc", "=", "func", ".", "__doc__", "if", "not", "doc", ":", "return", "\"\"", "# doc has only one line", "if", "\"\\n\"", "not", "in", "doc", ":", "return", "doc", "# Only Python core devs write __doc__ like this", "if",...
Extract and dedent the __doc__ of a function. Unlike `textwrap.dedent()` it also works when the first line is not indented.
[ "Extract", "and", "dedent", "the", "__doc__", "of", "a", "function", "." ]
python
train
24.857143