repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
ff0000/scarlet
scarlet/cms/forms.py
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/forms.py#L38-L59
def get_filter_kwargs(self): """ Translates the cleaned data into a dictionary that can used to generate the filter removing blank values. """ if self.is_valid(): filter_kwargs = {} for field in self.get_filter_fields(): empty_value...
[ "def", "get_filter_kwargs", "(", "self", ")", ":", "if", "self", ".", "is_valid", "(", ")", ":", "filter_kwargs", "=", "{", "}", "for", "field", "in", "self", ".", "get_filter_fields", "(", ")", ":", "empty_values", "=", "EMPTY_VALUES", "if", "hasattr", ...
Translates the cleaned data into a dictionary that can used to generate the filter removing blank values.
[ "Translates", "the", "cleaned", "data", "into", "a", "dictionary", "that", "can", "used", "to", "generate", "the", "filter", "removing", "blank", "values", "." ]
python
train
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_mac_address_table.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_mac_address_table.py#L236-L248
def mac_group_mac_group_entry_entry_address(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") mac_group = ET.SubElement(config, "mac-group", xmlns="urn:brocade.com:mgmt:brocade-mac-address-table") mac_group_id_key = ET.SubElement(mac_group, "mac-group-id")...
[ "def", "mac_group_mac_group_entry_entry_address", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "mac_group", "=", "ET", ".", "SubElement", "(", "config", ",", "\"mac-group\"", ",", "xmlns", "=", ...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
google/grr
grr/core/grr_response_core/lib/parsers/osx_file_parser.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/parsers/osx_file_parser.py#L196-L217
def Parse(self, statentry, file_object, knowledge_base): """Parse the Plist file.""" plist = biplist.readPlist(file_object) if not isinstance(plist, list): raise parser.ParseError( "InstallHistory plist is a '%s', expecting a list" % type(plist)) packages = [] for sw in plist: ...
[ "def", "Parse", "(", "self", ",", "statentry", ",", "file_object", ",", "knowledge_base", ")", ":", "plist", "=", "biplist", ".", "readPlist", "(", "file_object", ")", "if", "not", "isinstance", "(", "plist", ",", "list", ")", ":", "raise", "parser", "."...
Parse the Plist file.
[ "Parse", "the", "Plist", "file", "." ]
python
train
saltstack/salt
salt/modules/ebuildpkg.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ebuildpkg.py#L392-L403
def porttree_matches(name): ''' Returns a list containing the matches for a given package name from the portage tree. Note that the specific version of the package will not be provided for packages that have several versions in the portage tree, but rather the name of the package (i.e. "dev-python/p...
[ "def", "porttree_matches", "(", "name", ")", ":", "matches", "=", "[", "]", "for", "category", "in", "_porttree", "(", ")", ".", "dbapi", ".", "categories", ":", "if", "_porttree", "(", ")", ".", "dbapi", ".", "cp_list", "(", "category", "+", "\"/\"", ...
Returns a list containing the matches for a given package name from the portage tree. Note that the specific version of the package will not be provided for packages that have several versions in the portage tree, but rather the name of the package (i.e. "dev-python/paramiko").
[ "Returns", "a", "list", "containing", "the", "matches", "for", "a", "given", "package", "name", "from", "the", "portage", "tree", ".", "Note", "that", "the", "specific", "version", "of", "the", "package", "will", "not", "be", "provided", "for", "packages", ...
python
train
spyder-ide/spyder
spyder/widgets/fileswitcher.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/fileswitcher.py#L648-L767
def setup_file_list(self, filter_text, current_path): """Setup list widget content for file list display.""" short_paths = shorten_paths(self.paths, self.save_status) paths = self.paths icons = self.icons results = [] trying_for_line_number = ':' in filter_text #...
[ "def", "setup_file_list", "(", "self", ",", "filter_text", ",", "current_path", ")", ":", "short_paths", "=", "shorten_paths", "(", "self", ".", "paths", ",", "self", ".", "save_status", ")", "paths", "=", "self", ".", "paths", "icons", "=", "self", ".", ...
Setup list widget content for file list display.
[ "Setup", "list", "widget", "content", "for", "file", "list", "display", "." ]
python
train
allenai/allennlp
allennlp/common/params.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L35-L72
def infer_and_cast(value: Any): """ In some cases we'll be feeding params dicts to functions we don't own; for example, PyTorch optimizers. In that case we can't use ``pop_int`` or similar to force casts (which means you can't specify ``int`` parameters using environment variables). This function ta...
[ "def", "infer_and_cast", "(", "value", ":", "Any", ")", ":", "# pylint: disable=too-many-return-statements", "if", "isinstance", "(", "value", ",", "(", "int", ",", "float", ",", "bool", ")", ")", ":", "# Already one of our desired types, so leave as is.", "return", ...
In some cases we'll be feeding params dicts to functions we don't own; for example, PyTorch optimizers. In that case we can't use ``pop_int`` or similar to force casts (which means you can't specify ``int`` parameters using environment variables). This function takes something that looks JSON-like and r...
[ "In", "some", "cases", "we", "ll", "be", "feeding", "params", "dicts", "to", "functions", "we", "don", "t", "own", ";", "for", "example", "PyTorch", "optimizers", ".", "In", "that", "case", "we", "can", "t", "use", "pop_int", "or", "similar", "to", "fo...
python
train
aganezov/bg
bg/breakpoint_graph.py
https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/breakpoint_graph.py#L733-L842
def apply_kbreak(self, kbreak, merge=True): """ Check validity of supplied k-break and then applies it to current :class:`BreakpointGraph` Only :class:`bg.kbreak.KBreak` (or its heirs) instances are allowed as ``kbreak`` argument. KBreak must correspond to the valid kbreak and, since some chang...
[ "def", "apply_kbreak", "(", "self", ",", "kbreak", ",", "merge", "=", "True", ")", ":", "############################################################################################################", "#", "# k-break must ba valid to be applied", "#", "################################...
Check validity of supplied k-break and then applies it to current :class:`BreakpointGraph` Only :class:`bg.kbreak.KBreak` (or its heirs) instances are allowed as ``kbreak`` argument. KBreak must correspond to the valid kbreak and, since some changes to its internals might have been done since its creat...
[ "Check", "validity", "of", "supplied", "k", "-", "break", "and", "then", "applies", "it", "to", "current", ":", "class", ":", "BreakpointGraph" ]
python
train
openstack/monasca-common
monasca_common/kafka_lib/consumer/kafka.py
https://github.com/openstack/monasca-common/blob/61e2e00454734e2881611abec8df0d85bf7655ac/monasca_common/kafka_lib/consumer/kafka.py#L521-L586
def commit(self): """Store consumed message offsets (marked via task_done()) to kafka cluster for this consumer_group. Returns: True on success, or False if no offsets were found for commit Note: this functionality requires server version >=0.8.1.1 h...
[ "def", "commit", "(", "self", ")", ":", "if", "not", "self", ".", "_config", "[", "'group_id'", "]", ":", "logger", ".", "warning", "(", "'Cannot commit without a group_id!'", ")", "raise", "KafkaConfigurationError", "(", "'Attempted to commit offsets '", "'without ...
Store consumed message offsets (marked via task_done()) to kafka cluster for this consumer_group. Returns: True on success, or False if no offsets were found for commit Note: this functionality requires server version >=0.8.1.1 https://cwiki.apache.org/confl...
[ "Store", "consumed", "message", "offsets", "(", "marked", "via", "task_done", "()", ")", "to", "kafka", "cluster", "for", "this", "consumer_group", "." ]
python
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/SConscript.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/SConscript.py#L462-L477
def EnsureSConsVersion(self, major, minor, revision=0): """Exit abnormally if the SCons version is not late enough.""" # split string to avoid replacement during build process if SCons.__version__ == '__' + 'VERSION__': SCons.Warnings.warn(SCons.Warnings.DevelopmentVersionWarning, ...
[ "def", "EnsureSConsVersion", "(", "self", ",", "major", ",", "minor", ",", "revision", "=", "0", ")", ":", "# split string to avoid replacement during build process", "if", "SCons", ".", "__version__", "==", "'__'", "+", "'VERSION__'", ":", "SCons", ".", "Warnings...
Exit abnormally if the SCons version is not late enough.
[ "Exit", "abnormally", "if", "the", "SCons", "version", "is", "not", "late", "enough", "." ]
python
train
nwilming/ocupy
ocupy/parallel.py
https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/parallel.py#L228-L245
def partition(self): """Partitions all tasks into groups of tasks. A group is represented by a task_store object that indexes a sub- set of tasks.""" step = int(math.ceil(self.num_tasks / float(self.partitions))) if self.indices == None: slice_ind = list(range(0...
[ "def", "partition", "(", "self", ")", ":", "step", "=", "int", "(", "math", ".", "ceil", "(", "self", ".", "num_tasks", "/", "float", "(", "self", ".", "partitions", ")", ")", ")", "if", "self", ".", "indices", "==", "None", ":", "slice_ind", "=", ...
Partitions all tasks into groups of tasks. A group is represented by a task_store object that indexes a sub- set of tasks.
[ "Partitions", "all", "tasks", "into", "groups", "of", "tasks", ".", "A", "group", "is", "represented", "by", "a", "task_store", "object", "that", "indexes", "a", "sub", "-", "set", "of", "tasks", "." ]
python
train
cloudant/python-cloudant
src/cloudant/feed.py
https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/feed.py#L109-L135
def _validate(self, key, val, arg_types): """ Ensures that the key and the value are valid arguments to be used with the feed. """ if key in arg_types: arg_type = arg_types[key] else: if ANY_ARG not in arg_types: raise CloudantArgum...
[ "def", "_validate", "(", "self", ",", "key", ",", "val", ",", "arg_types", ")", ":", "if", "key", "in", "arg_types", ":", "arg_type", "=", "arg_types", "[", "key", "]", "else", ":", "if", "ANY_ARG", "not", "in", "arg_types", ":", "raise", "CloudantArgu...
Ensures that the key and the value are valid arguments to be used with the feed.
[ "Ensures", "that", "the", "key", "and", "the", "value", "are", "valid", "arguments", "to", "be", "used", "with", "the", "feed", "." ]
python
train
jdoda/sdl2hl
sdl2hl/renderer.py
https://github.com/jdoda/sdl2hl/blob/3b477e1e01cea5d8e15e9e5ef3a302ea460f5946/sdl2hl/renderer.py#L372-L376
def w(self): """int: The width of the texture in pixels.""" w = ffi.new('int *') check_int_err(lib.SDL_QueryTexture(self._ptr, ffi.NULL, ffi.NULL, w, ffi.NULL)) return w[0]
[ "def", "w", "(", "self", ")", ":", "w", "=", "ffi", ".", "new", "(", "'int *'", ")", "check_int_err", "(", "lib", ".", "SDL_QueryTexture", "(", "self", ".", "_ptr", ",", "ffi", ".", "NULL", ",", "ffi", ".", "NULL", ",", "w", ",", "ffi", ".", "N...
int: The width of the texture in pixels.
[ "int", ":", "The", "width", "of", "the", "texture", "in", "pixels", "." ]
python
train
vanheeringen-lab/gimmemotifs
gimmemotifs/denovo.py
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/denovo.py#L185-L273
def create_background(bg_type, fafile, outfile, genome="hg18", width=200, nr_times=10, custom_background=None): """Create background of a specific type. Parameters ---------- bg_type : str Name of background type. fafile : str Name of input FASTA file. outfile : str Na...
[ "def", "create_background", "(", "bg_type", ",", "fafile", ",", "outfile", ",", "genome", "=", "\"hg18\"", ",", "width", "=", "200", ",", "nr_times", "=", "10", ",", "custom_background", "=", "None", ")", ":", "width", "=", "int", "(", "width", ")", "c...
Create background of a specific type. Parameters ---------- bg_type : str Name of background type. fafile : str Name of input FASTA file. outfile : str Name of output FASTA file. genome : str, optional Genome name. width : int, optional Size of re...
[ "Create", "background", "of", "a", "specific", "type", "." ]
python
train
pmorissette/ffn
ffn/core.py
https://github.com/pmorissette/ffn/blob/ef09f28b858b7ffcd2627ce6a4dc618183a6bc8a/ffn/core.py#L1986-L2031
def plot_heatmap(data, title='Heatmap', show_legend=True, show_labels=True, label_fmt='.2f', vmin=None, vmax=None, figsize=None, label_color='w', cmap='RdBu', **kwargs): """ Plot a heatmap using matplotlib's pcolor. Args: * data (D...
[ "def", "plot_heatmap", "(", "data", ",", "title", "=", "'Heatmap'", ",", "show_legend", "=", "True", ",", "show_labels", "=", "True", ",", "label_fmt", "=", "'.2f'", ",", "vmin", "=", "None", ",", "vmax", "=", "None", ",", "figsize", "=", "None", ",", ...
Plot a heatmap using matplotlib's pcolor. Args: * data (DataFrame): DataFrame to plot. Usually small matrix (ex. correlation matrix). * title (string): Plot title * show_legend (bool): Show color legend * show_labels (bool): Show value labels * label_fmt (str): L...
[ "Plot", "a", "heatmap", "using", "matplotlib", "s", "pcolor", "." ]
python
train
GeorgeArgyros/symautomata
symautomata/cfggenerator.py
https://github.com/GeorgeArgyros/symautomata/blob/f5d66533573b27e155bec3f36b8c00b8e3937cb3/symautomata/cfggenerator.py#L175-L187
def generate(self): """ Generates a new random string from the start symbol Args: None Returns: str: The generated string """ result = self._gen(self.optimized, self.splitstring) if self.splitstring and result is not None: resu...
[ "def", "generate", "(", "self", ")", ":", "result", "=", "self", ".", "_gen", "(", "self", ".", "optimized", ",", "self", ".", "splitstring", ")", "if", "self", ".", "splitstring", "and", "result", "is", "not", "None", ":", "result", "=", "result", "...
Generates a new random string from the start symbol Args: None Returns: str: The generated string
[ "Generates", "a", "new", "random", "string", "from", "the", "start", "symbol", "Args", ":", "None", "Returns", ":", "str", ":", "The", "generated", "string" ]
python
train
mitsei/dlkit
dlkit/json_/assessment_authoring/objects.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment_authoring/objects.py#L369-L391
def _init_map(self, record_types=None, **kwargs): """Initialize form map""" osid_objects.OsidContainableForm._init_map(self) osid_objects.OsidOperableForm._init_map(self) osid_objects.OsidObjectForm._init_map(self, record_types=record_types) if 'assessment_part_id' in kwargs: ...
[ "def", "_init_map", "(", "self", ",", "record_types", "=", "None", ",", "*", "*", "kwargs", ")", ":", "osid_objects", ".", "OsidContainableForm", ".", "_init_map", "(", "self", ")", "osid_objects", ".", "OsidOperableForm", ".", "_init_map", "(", "self", ")",...
Initialize form map
[ "Initialize", "form", "map" ]
python
train
twilio/twilio-python
twilio/rest/api/v2010/account/sip/ip_access_control_list/ip_address.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/sip/ip_access_control_list/ip_address.py#L472-L488
def update(self, ip_address=values.unset, friendly_name=values.unset, cidr_prefix_length=values.unset): """ Update the IpAddressInstance :param unicode ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP addres...
[ "def", "update", "(", "self", ",", "ip_address", "=", "values", ".", "unset", ",", "friendly_name", "=", "values", ".", "unset", ",", "cidr_prefix_length", "=", "values", ".", "unset", ")", ":", "return", "self", ".", "_proxy", ".", "update", "(", "ip_ad...
Update the IpAddressInstance :param unicode ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. :param unicode friendly_name: A human readable descriptive text for this re...
[ "Update", "the", "IpAddressInstance" ]
python
train
sunlightlabs/django-locksmith
locksmith/hub/models.py
https://github.com/sunlightlabs/django-locksmith/blob/eef5b7c25404560aaad50b6e622594f89239b74b/locksmith/hub/models.py#L82-L87
def mark_for_update(self): ''' Note that a change has been made so all Statuses need update ''' self.pub_statuses.exclude(status=UNPUBLISHED).update(status=NEEDS_UPDATE) push_key.delay(self)
[ "def", "mark_for_update", "(", "self", ")", ":", "self", ".", "pub_statuses", ".", "exclude", "(", "status", "=", "UNPUBLISHED", ")", ".", "update", "(", "status", "=", "NEEDS_UPDATE", ")", "push_key", ".", "delay", "(", "self", ")" ]
Note that a change has been made so all Statuses need update
[ "Note", "that", "a", "change", "has", "been", "made", "so", "all", "Statuses", "need", "update" ]
python
train
llazzaro/django-scheduler
schedule/views.py
https://github.com/llazzaro/django-scheduler/blob/0530b74a5fc0b1125645002deaa4da2337ed0f17/schedule/views.py#L251-L274
def get_occurrence(event_id, occurrence_id=None, year=None, month=None, day=None, hour=None, minute=None, second=None, tzinfo=None): """ Because occurrences don't have to be persisted, there must be two ways to retrieve them. both need an event, but if its persisted the...
[ "def", "get_occurrence", "(", "event_id", ",", "occurrence_id", "=", "None", ",", "year", "=", "None", ",", "month", "=", "None", ",", "day", "=", "None", ",", "hour", "=", "None", ",", "minute", "=", "None", ",", "second", "=", "None", ",", "tzinfo"...
Because occurrences don't have to be persisted, there must be two ways to retrieve them. both need an event, but if its persisted the occurrence can be retrieved with an id. If it is not persisted it takes a date to retrieve it. This function returns an event and occurrence regardless of which method i...
[ "Because", "occurrences", "don", "t", "have", "to", "be", "persisted", "there", "must", "be", "two", "ways", "to", "retrieve", "them", ".", "both", "need", "an", "event", "but", "if", "its", "persisted", "the", "occurrence", "can", "be", "retrieved", "with...
python
train
mitsei/dlkit
dlkit/json_/assessment/assessment_utilities.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment/assessment_utilities.py#L46-L56
def get_first_part_id_for_assessment(assessment_id, runtime=None, proxy=None, create=False, bank_id=None): """Gets the first part id, which represents the first section, of assessment""" if create and bank_id is None: raise NullArgument('Bank Id must be provided for create option') try: retu...
[ "def", "get_first_part_id_for_assessment", "(", "assessment_id", ",", "runtime", "=", "None", ",", "proxy", "=", "None", ",", "create", "=", "False", ",", "bank_id", "=", "None", ")", ":", "if", "create", "and", "bank_id", "is", "None", ":", "raise", "Null...
Gets the first part id, which represents the first section, of assessment
[ "Gets", "the", "first", "part", "id", "which", "represents", "the", "first", "section", "of", "assessment" ]
python
train
gmdzy2010/dingtalk_sdk_gmdzy2010
dingtalk_sdk_gmdzy2010/user_request.py
https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/user_request.py#L30-L34
def get_userinfo(self): """Method to get current user's name, mobile, email and position.""" wanted_fields = ["name", "mobile", "orgEmail", "position", "avatar"] userinfo = {k: self.json_response.get(k, None) for k in wanted_fields} return userinfo
[ "def", "get_userinfo", "(", "self", ")", ":", "wanted_fields", "=", "[", "\"name\"", ",", "\"mobile\"", ",", "\"orgEmail\"", ",", "\"position\"", ",", "\"avatar\"", "]", "userinfo", "=", "{", "k", ":", "self", ".", "json_response", ".", "get", "(", "k", ...
Method to get current user's name, mobile, email and position.
[ "Method", "to", "get", "current", "user", "s", "name", "mobile", "email", "and", "position", "." ]
python
train
gvanderheide/discreteMarkovChain
discreteMarkovChain/markovChain.py
https://github.com/gvanderheide/discreteMarkovChain/blob/8325ffdb791c109eee600684ee0dc9126ce80700/discreteMarkovChain/markovChain.py#L194-L243
def indirectInitialMatrix(self, initialState): """ Given some initial state, this iteratively determines new states. We repeatedly call the transition function on unvisited states in the frontier set. Each newly visited state is put in a dictionary called 'mapping' and the rates are stor...
[ "def", "indirectInitialMatrix", "(", "self", ",", "initialState", ")", ":", "mapping", "=", "{", "}", "rates", "=", "OrderedDict", "(", ")", "#Check whether the initial state is defined and of the correct type, and convert to a tuple or int. ", "convertedState", "=", "self", ...
Given some initial state, this iteratively determines new states. We repeatedly call the transition function on unvisited states in the frontier set. Each newly visited state is put in a dictionary called 'mapping' and the rates are stored in a dictionary.
[ "Given", "some", "initial", "state", "this", "iteratively", "determines", "new", "states", ".", "We", "repeatedly", "call", "the", "transition", "function", "on", "unvisited", "states", "in", "the", "frontier", "set", ".", "Each", "newly", "visited", "state", ...
python
train
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L2980-L3060
def run(self, indent_size=DEFAULT_INDENT_SIZE): """Fix indentation and return modified line numbers. Line numbers are indexed at 1. """ if indent_size < 1: return self.input_text try: stats = _reindent_stats(tokenize.generate_tokens(self.getline)) ...
[ "def", "run", "(", "self", ",", "indent_size", "=", "DEFAULT_INDENT_SIZE", ")", ":", "if", "indent_size", "<", "1", ":", "return", "self", ".", "input_text", "try", ":", "stats", "=", "_reindent_stats", "(", "tokenize", ".", "generate_tokens", "(", "self", ...
Fix indentation and return modified line numbers. Line numbers are indexed at 1.
[ "Fix", "indentation", "and", "return", "modified", "line", "numbers", "." ]
python
train
DarkEnergySurvey/ugali
ugali/analysis/mcmc.py
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/mcmc.py#L172-L192
def lnprob(self,theta): """ Logarithm of the probability """ global niter params,priors,loglike = self.params,self.priors,self.loglike # Avoid extra likelihood calls with bad priors _lnprior = self.lnprior(theta) if np.isfinite(_lnprior): _lnlike = self.lnlike...
[ "def", "lnprob", "(", "self", ",", "theta", ")", ":", "global", "niter", "params", ",", "priors", ",", "loglike", "=", "self", ".", "params", ",", "self", ".", "priors", ",", "self", ".", "loglike", "# Avoid extra likelihood calls with bad priors", "_lnprior",...
Logarithm of the probability
[ "Logarithm", "of", "the", "probability" ]
python
train
pymupdf/PyMuPDF
fitz/fitz.py
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2341-L2346
def _getTrailerString(self, compressed=1): """_getTrailerString(self, compressed=1) -> PyObject *""" if self.isClosed: raise ValueError("operation illegal for closed doc") return _fitz.Document__getTrailerString(self, compressed)
[ "def", "_getTrailerString", "(", "self", ",", "compressed", "=", "1", ")", ":", "if", "self", ".", "isClosed", ":", "raise", "ValueError", "(", "\"operation illegal for closed doc\"", ")", "return", "_fitz", ".", "Document__getTrailerString", "(", "self", ",", "...
_getTrailerString(self, compressed=1) -> PyObject *
[ "_getTrailerString", "(", "self", "compressed", "=", "1", ")", "-", ">", "PyObject", "*" ]
python
train
bitly/asyncmongo
asyncmongo/cursor.py
https://github.com/bitly/asyncmongo/blob/3da47c96d4592ec9e8b3ef5cf1b7d5b439ab3a5b/asyncmongo/cursor.py#L421-L430
def __query_options(self): """Get the query options string to use for this query.""" options = 0 if self.__tailable: options |= _QUERY_OPTIONS["tailable_cursor"] if self.__slave_okay or self.__pool._slave_okay: options |= _QUERY_OPTIONS["slave_okay"] if no...
[ "def", "__query_options", "(", "self", ")", ":", "options", "=", "0", "if", "self", ".", "__tailable", ":", "options", "|=", "_QUERY_OPTIONS", "[", "\"tailable_cursor\"", "]", "if", "self", ".", "__slave_okay", "or", "self", ".", "__pool", ".", "_slave_okay"...
Get the query options string to use for this query.
[ "Get", "the", "query", "options", "string", "to", "use", "for", "this", "query", "." ]
python
train
1flow/python-ftr
ftr/config.py
https://github.com/1flow/python-ftr/blob/90a2108c5ee005f1bf66dbe8cce68f2b7051b839/ftr/config.py#L492-L507
def load(self, host, exact_host_match=False): """ Load a config for a hostname or url. This method calls :func:`ftr_get_config` and :meth`append` internally. Refer to their docs for details on parameters. """ # Can raise a SiteConfigNotFound, intentionally bubbled. conf...
[ "def", "load", "(", "self", ",", "host", ",", "exact_host_match", "=", "False", ")", ":", "# Can raise a SiteConfigNotFound, intentionally bubbled.", "config_string", ",", "host_string", "=", "ftr_get_config", "(", "host", ",", "exact_host_match", ")", "if", "config_s...
Load a config for a hostname or url. This method calls :func:`ftr_get_config` and :meth`append` internally. Refer to their docs for details on parameters.
[ "Load", "a", "config", "for", "a", "hostname", "or", "url", "." ]
python
train
EelcoHoogendoorn/Numpy_arraysetops_EP
numpy_indexed/grouping.py
https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/grouping.py#L163-L176
def split_array_as_list(self, values): """Group values as a list of arrays, or a jagged-array Parameters ---------- values : ndarray, [keys, ...] Returns ------- list of length self.groups of ndarray, [key_count, ...] """ values = np.asarray(valu...
[ "def", "split_array_as_list", "(", "self", ",", "values", ")", ":", "values", "=", "np", ".", "asarray", "(", "values", ")", "values", "=", "values", "[", "self", ".", "index", ".", "sorter", "]", "return", "np", ".", "split", "(", "values", ",", "se...
Group values as a list of arrays, or a jagged-array Parameters ---------- values : ndarray, [keys, ...] Returns ------- list of length self.groups of ndarray, [key_count, ...]
[ "Group", "values", "as", "a", "list", "of", "arrays", "or", "a", "jagged", "-", "array" ]
python
train
allenai/allennlp
allennlp/tools/wikitables_evaluator.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/tools/wikitables_evaluator.py#L301-L317
def check_denotation(target_values, predicted_values): """Return True if the predicted denotation is correct. Args: target_values (list[Value]) predicted_values (list[Value]) Returns: bool """ # Check size if len(target_values) != len(predicted_values): return Fa...
[ "def", "check_denotation", "(", "target_values", ",", "predicted_values", ")", ":", "# Check size", "if", "len", "(", "target_values", ")", "!=", "len", "(", "predicted_values", ")", ":", "return", "False", "# Check items", "for", "target", "in", "target_values", ...
Return True if the predicted denotation is correct. Args: target_values (list[Value]) predicted_values (list[Value]) Returns: bool
[ "Return", "True", "if", "the", "predicted", "denotation", "is", "correct", "." ]
python
train
saltstack/salt
salt/modules/openvswitch.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/openvswitch.py#L80-L96
def _stdout_list_split(retcode, stdout='', splitstring='\n'): ''' Evaulates Open vSwitch command`s retcode value. Args: retcode: Value of retcode field from response, should be 0, 1 or 2. stdout: Value of stdout filed from response. splitstring: String used to split the stdout defau...
[ "def", "_stdout_list_split", "(", "retcode", ",", "stdout", "=", "''", ",", "splitstring", "=", "'\\n'", ")", ":", "if", "retcode", "==", "0", ":", "ret", "=", "stdout", ".", "split", "(", "splitstring", ")", "return", "ret", "else", ":", "return", "Fa...
Evaulates Open vSwitch command`s retcode value. Args: retcode: Value of retcode field from response, should be 0, 1 or 2. stdout: Value of stdout filed from response. splitstring: String used to split the stdout default new line. Returns: List or False.
[ "Evaulates", "Open", "vSwitch", "command", "s", "retcode", "value", "." ]
python
train
angr/angr
angr/analyses/cfg/cfg_emulated.py
https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/analyses/cfg/cfg_emulated.py#L1823-L1856
def _handle_job_without_successors(self, job, irsb, insn_addrs): """ A block without successors should still be handled so it can be added to the function graph correctly. :param CFGJob job: The current job that do not have any successor. :param IRSB irsb: The related IRSB. :...
[ "def", "_handle_job_without_successors", "(", "self", ",", "job", ",", "irsb", ",", "insn_addrs", ")", ":", "# it's not an empty block", "# handle all conditional exits", "ins_addr", "=", "job", ".", "addr", "for", "stmt_idx", ",", "stmt", "in", "enumerate", "(", ...
A block without successors should still be handled so it can be added to the function graph correctly. :param CFGJob job: The current job that do not have any successor. :param IRSB irsb: The related IRSB. :param insn_addrs: A list of instruction addresses of this IRSB. :return: Non...
[ "A", "block", "without", "successors", "should", "still", "be", "handled", "so", "it", "can", "be", "added", "to", "the", "function", "graph", "correctly", "." ]
python
train
KE-works/pykechain
pykechain/models/scope.py
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/scope.py#L249-L275
def _update_scope_project_team(self, select_action, user, user_type): """ Update the Project Team of the Scope. Updates include addition or removing of managers or members. :param select_action: type of action to be applied :type select_action: basestring :param user: the userna...
[ "def", "_update_scope_project_team", "(", "self", ",", "select_action", ",", "user", ",", "user_type", ")", ":", "if", "isinstance", "(", "user", ",", "str", ")", ":", "users", "=", "self", ".", "_client", ".", "_retrieve_users", "(", ")", "manager_object", ...
Update the Project Team of the Scope. Updates include addition or removing of managers or members. :param select_action: type of action to be applied :type select_action: basestring :param user: the username of the user to which the action applies to :type user: basestring :para...
[ "Update", "the", "Project", "Team", "of", "the", "Scope", ".", "Updates", "include", "addition", "or", "removing", "of", "managers", "or", "members", "." ]
python
train
marshmallow-code/apispec
src/apispec/core.py
https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/core.py#L279-L319
def path( self, path=None, operations=None, summary=None, description=None, **kwargs ): """Add a new path object to the spec. https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#path-item-object :param str|None path: URL path component :param dict|Non...
[ "def", "path", "(", "self", ",", "path", "=", "None", ",", "operations", "=", "None", ",", "summary", "=", "None", ",", "description", "=", "None", ",", "*", "*", "kwargs", ")", ":", "operations", "=", "operations", "or", "OrderedDict", "(", ")", "# ...
Add a new path object to the spec. https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#path-item-object :param str|None path: URL path component :param dict|None operations: describes the http methods and options for `path` :param str summary: short summary relev...
[ "Add", "a", "new", "path", "object", "to", "the", "spec", "." ]
python
train
archman/beamline
beamline/pltutils.py
https://github.com/archman/beamline/blob/417bc5dc13e754bc89d246427984590fced64d07/beamline/pltutils.py#L47-L116
def makeBeamline(beamlinelist, startpoint=(0, 0)): """ function to construct patches for ``plotLattice()``, from different elements like ``rbend``, ``quadrupole``,etc. parsing from lattice file, mad-8. drift sections are calculated from other elements. Input parameters: :param beamlinelist: li...
[ "def", "makeBeamline", "(", "beamlinelist", ",", "startpoint", "=", "(", "0", ",", "0", ")", ")", ":", "latticelist", "=", "[", "]", "anglenow", "=", "0.0", "maxx", ",", "maxy", "=", "startpoint", "minx", ",", "miny", "=", "startpoint", "for", "i", "...
function to construct patches for ``plotLattice()``, from different elements like ``rbend``, ``quadrupole``,etc. parsing from lattice file, mad-8. drift sections are calculated from other elements. Input parameters: :param beamlinelist: list, which elements are dict, each dict is the description for m...
[ "function", "to", "construct", "patches", "for", "plotLattice", "()", "from", "different", "elements", "like", "rbend", "quadrupole", "etc", ".", "parsing", "from", "lattice", "file", "mad", "-", "8", ".", "drift", "sections", "are", "calculated", "from", "oth...
python
train
MatterMiners/cobald
cobald/controller/stepwise.py
https://github.com/MatterMiners/cobald/blob/264138de4382d1c9b53fabcbc6660e10b33a914d/cobald/controller/stepwise.py#L135-L165
def add(self, rule: ControlRule = None, *, supply: float): """ Register a new rule above a given ``supply`` threshold Registration supports a single-argument form for use as a decorator, as well as a two-argument form for direct application. Use the former for ``def`` or ``class...
[ "def", "add", "(", "self", ",", "rule", ":", "ControlRule", "=", "None", ",", "*", ",", "supply", ":", "float", ")", ":", "if", "supply", "in", "self", ".", "_thresholds", ":", "raise", "ValueError", "(", "'rule for threshold %s re-defined'", "%", "supply"...
Register a new rule above a given ``supply`` threshold Registration supports a single-argument form for use as a decorator, as well as a two-argument form for direct application. Use the former for ``def`` or ``class`` definitions, and the later for ``lambda`` functions and existing cal...
[ "Register", "a", "new", "rule", "above", "a", "given", "supply", "threshold" ]
python
train
mcs07/ChemDataExtractor
chemdataextractor/nlp/pos.py
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/pos.py#L82-L195
def _get_features(self, i, context, prev, prev2): """Map tokens into a feature representation.""" w = self.lexicon[context[i]] features = [ 'bias', 'w:shape=%s' % w.shape, 'w:lower=%s' % w.lower, 'p1:tag=%s' % prev, 'p2:tag=%s' % prev2,...
[ "def", "_get_features", "(", "self", ",", "i", ",", "context", ",", "prev", ",", "prev2", ")", ":", "w", "=", "self", ".", "lexicon", "[", "context", "[", "i", "]", "]", "features", "=", "[", "'bias'", ",", "'w:shape=%s'", "%", "w", ".", "shape", ...
Map tokens into a feature representation.
[ "Map", "tokens", "into", "a", "feature", "representation", "." ]
python
train
visualfabriq/bquery
bquery/ctable.py
https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L76-L93
def group_cache_valid(self, col_list): """ Checks whether the column has a factorization that exists and is not older than the source :param col: :return: """ cache_valid = False if self.rootdir: col_values_file_check = os.path.join(self.rootdir, sel...
[ "def", "group_cache_valid", "(", "self", ",", "col_list", ")", ":", "cache_valid", "=", "False", "if", "self", ".", "rootdir", ":", "col_values_file_check", "=", "os", ".", "path", ".", "join", "(", "self", ".", "rootdir", ",", "self", ".", "create_group_b...
Checks whether the column has a factorization that exists and is not older than the source :param col: :return:
[ "Checks", "whether", "the", "column", "has", "a", "factorization", "that", "exists", "and", "is", "not", "older", "than", "the", "source" ]
python
train
jasonbot/arcrest
arcrest/geometry.py
https://github.com/jasonbot/arcrest/blob/b1ba71fd59bb6349415e7879d753d307dbc0da26/arcrest/geometry.py#L391-L423
def contains(self, pt): "Tests if the provided point is in the polygon." if isinstance(pt, Point): ptx, pty = pt.x, pt.y assert (self.spatialReference is None or \ self.spatialReference.wkid is None) or \ (pt.spatialReference is None or \ ...
[ "def", "contains", "(", "self", ",", "pt", ")", ":", "if", "isinstance", "(", "pt", ",", "Point", ")", ":", "ptx", ",", "pty", "=", "pt", ".", "x", ",", "pt", ".", "y", "assert", "(", "self", ".", "spatialReference", "is", "None", "or", "self", ...
Tests if the provided point is in the polygon.
[ "Tests", "if", "the", "provided", "point", "is", "in", "the", "polygon", "." ]
python
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/GettextCommon.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/GettextCommon.py#L114-L116
def Entry(self, name, directory=None, create=1): """ Create `SCons.Node.FS.Entry` """ return self._create_node(name, self.env.fs.Entry, directory, create)
[ "def", "Entry", "(", "self", ",", "name", ",", "directory", "=", "None", ",", "create", "=", "1", ")", ":", "return", "self", ".", "_create_node", "(", "name", ",", "self", ".", "env", ".", "fs", ".", "Entry", ",", "directory", ",", "create", ")" ]
Create `SCons.Node.FS.Entry`
[ "Create", "SCons", ".", "Node", ".", "FS", ".", "Entry" ]
python
train
timothyb0912/pylogit
pylogit/bootstrap_mle.py
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap_mle.py#L103-L133
def get_model_creation_kwargs(model_obj): """ Get a dictionary of the keyword arguments needed to create the passed model object using `pylogit.create_choice_model`. Parameters ---------- model_obj : An MNDC_Model instance. Returns ------- model_kwargs : dict. Contains the ...
[ "def", "get_model_creation_kwargs", "(", "model_obj", ")", ":", "# Extract the model abbreviation for this model", "model_abbrev", "=", "get_model_abbrev", "(", "model_obj", ")", "# Create a dictionary to store the keyword arguments needed to Initialize", "# the new model object.d", "m...
Get a dictionary of the keyword arguments needed to create the passed model object using `pylogit.create_choice_model`. Parameters ---------- model_obj : An MNDC_Model instance. Returns ------- model_kwargs : dict. Contains the keyword arguments and the required values that are nee...
[ "Get", "a", "dictionary", "of", "the", "keyword", "arguments", "needed", "to", "create", "the", "passed", "model", "object", "using", "pylogit", ".", "create_choice_model", "." ]
python
train
dddomodossola/remi
editor/editor.py
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/editor/editor.py#L656-L680
def configure_widget_for_editing(self, widget): """ A widget have to be added to the editor, it is configured here in order to be conformant to the editor """ if not 'editor_varname' in widget.attributes: return widget.onclick.do(self.on_widget_selection...
[ "def", "configure_widget_for_editing", "(", "self", ",", "widget", ")", ":", "if", "not", "'editor_varname'", "in", "widget", ".", "attributes", ":", "return", "widget", ".", "onclick", ".", "do", "(", "self", ".", "on_widget_selection", ")", "#setup of the on_d...
A widget have to be added to the editor, it is configured here in order to be conformant to the editor
[ "A", "widget", "have", "to", "be", "added", "to", "the", "editor", "it", "is", "configured", "here", "in", "order", "to", "be", "conformant", "to", "the", "editor" ]
python
train
RedisJSON/rejson-py
rejson/client.py
https://github.com/RedisJSON/rejson-py/blob/55f0adf3adc40f5a769e28e541dbbf5377b90ec6/rejson/client.py#L78-L87
def setEncoder(self, encoder): """ Sets the client's encoder ``encoder`` should be an instance of a ``json.JSONEncoder`` class """ if not encoder: self._encoder = json.JSONEncoder() else: self._encoder = encoder self._encode = self._encoder...
[ "def", "setEncoder", "(", "self", ",", "encoder", ")", ":", "if", "not", "encoder", ":", "self", ".", "_encoder", "=", "json", ".", "JSONEncoder", "(", ")", "else", ":", "self", ".", "_encoder", "=", "encoder", "self", ".", "_encode", "=", "self", "....
Sets the client's encoder ``encoder`` should be an instance of a ``json.JSONEncoder`` class
[ "Sets", "the", "client", "s", "encoder", "encoder", "should", "be", "an", "instance", "of", "a", "json", ".", "JSONEncoder", "class" ]
python
train
Kortemme-Lab/klab
klab/bio/pdb.py
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/pdb.py#L825-L895
def generate_all_paired_mutations_for_position(self, chain_ids, chain_sequence_mappings = {}, residue_ids_to_ignore = [], typed_residue_ids_to_ignore = [], silent = True): '''Generates a set of mutations for the chains in chain_ids where each set corresponds to the "same" residue (see below) in both ...
[ "def", "generate_all_paired_mutations_for_position", "(", "self", ",", "chain_ids", ",", "chain_sequence_mappings", "=", "{", "}", ",", "residue_ids_to_ignore", "=", "[", "]", ",", "typed_residue_ids_to_ignore", "=", "[", "]", ",", "silent", "=", "True", ")", ":",...
Generates a set of mutations for the chains in chain_ids where each set corresponds to the "same" residue (see below) in both chains and where the wildtype residues match. e.g. if chain A and B both have K19 then the set of mutations K19A, ... K19I, K19L, K19Y will be included in ...
[ "Generates", "a", "set", "of", "mutations", "for", "the", "chains", "in", "chain_ids", "where", "each", "set", "corresponds", "to", "the", "same", "residue", "(", "see", "below", ")", "in", "both", "chains", "and", "where", "the", "wildtype", "residues", "...
python
train
biosustain/optlang
optlang/interface.py
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/interface.py#L1417-L1452
def update(self, callback=int): """Process all pending model modifications.""" # print(self._pending_modifications) add_var = self._pending_modifications.add_var if len(add_var) > 0: self._add_variables(add_var) self._pending_modifications.add_var = [] cal...
[ "def", "update", "(", "self", ",", "callback", "=", "int", ")", ":", "# print(self._pending_modifications)", "add_var", "=", "self", ".", "_pending_modifications", ".", "add_var", "if", "len", "(", "add_var", ")", ">", "0", ":", "self", ".", "_add_variables", ...
Process all pending model modifications.
[ "Process", "all", "pending", "model", "modifications", "." ]
python
train
lrq3000/pyFileFixity
pyFileFixity/lib/aux_funcs.py
https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/aux_funcs.py#L149-L158
def remove_if_exist(path): # pragma: no cover """Delete a file or a directory recursively if it exists, else no exception is raised""" if os.path.exists(path): if os.path.isdir(path): shutil.rmtree(path) return True elif os.path.isfile(path): os.remove(path) ...
[ "def", "remove_if_exist", "(", "path", ")", ":", "# pragma: no cover", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "shutil", ".", "rmtree", "(", "path", ")", "return", ...
Delete a file or a directory recursively if it exists, else no exception is raised
[ "Delete", "a", "file", "or", "a", "directory", "recursively", "if", "it", "exists", "else", "no", "exception", "is", "raised" ]
python
train
saltstack/salt
salt/modules/lxc.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L2109-L2147
def ls_(active=None, cache=True, path=None): ''' Return a list of the containers available on the minion path path to the container parent directory default: /var/lib/lxc (system) .. versionadded:: 2015.8.0 active If ``True``, return only active (i.e. running) containe...
[ "def", "ls_", "(", "active", "=", "None", ",", "cache", "=", "True", ",", "path", "=", "None", ")", ":", "contextvar", "=", "'lxc.ls{0}'", ".", "format", "(", "path", ")", "if", "active", ":", "contextvar", "+=", "'.active'", "if", "cache", "and", "(...
Return a list of the containers available on the minion path path to the container parent directory default: /var/lib/lxc (system) .. versionadded:: 2015.8.0 active If ``True``, return only active (i.e. running) containers .. versionadded:: 2015.5.0 CLI Example: ...
[ "Return", "a", "list", "of", "the", "containers", "available", "on", "the", "minion" ]
python
train
osrg/ryu
ryu/services/protocols/bgp/peer.py
https://github.com/osrg/ryu/blob/6f906e72c92e10bd0264c9b91a2f7bb85b97780c/ryu/services/protocols/bgp/peer.py#L2138-L2150
def _enqueue_init_updates(self): """Enqueues current routes to be shared with this peer.""" assert self.state.bgp_state == const.BGP_FSM_ESTABLISHED if self.is_mbgp_cap_valid(RF_RTC_UC): # Enqueues all best-RTC_NLRIs to be sent as initial update to this # peer. ...
[ "def", "_enqueue_init_updates", "(", "self", ")", ":", "assert", "self", ".", "state", ".", "bgp_state", "==", "const", ".", "BGP_FSM_ESTABLISHED", "if", "self", ".", "is_mbgp_cap_valid", "(", "RF_RTC_UC", ")", ":", "# Enqueues all best-RTC_NLRIs to be sent as initial...
Enqueues current routes to be shared with this peer.
[ "Enqueues", "current", "routes", "to", "be", "shared", "with", "this", "peer", "." ]
python
train
bjoernricks/python-quilt
quilt/push.py
https://github.com/bjoernricks/python-quilt/blob/fae88237f601848cc34d073584d9dcb409f01777/quilt/push.py#L131-L150
def apply_all(self, force=False, quiet=False): """ Apply all patches in series file """ self._check() top = self.db.top_patch() if top: patches = self.series.patches_after(top) else: patches = self.series.patches() if not patches: rais...
[ "def", "apply_all", "(", "self", ",", "force", "=", "False", ",", "quiet", "=", "False", ")", ":", "self", ".", "_check", "(", ")", "top", "=", "self", ".", "db", ".", "top_patch", "(", ")", "if", "top", ":", "patches", "=", "self", ".", "series"...
Apply all patches in series file
[ "Apply", "all", "patches", "in", "series", "file" ]
python
test
cocaine/cocaine-tools
cocaine/tools/dispatch.py
https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L1388-L1400
def group_push(name, app, weight, **kwargs): """ Add application with its weight into the routing group. Warning: application weight must be positive integer. """ ctx = Context(**kwargs) ctx.execute_action('group:app:add', **{ 'storage': ctx.repo.create_secure_service('storage'), ...
[ "def", "group_push", "(", "name", ",", "app", ",", "weight", ",", "*", "*", "kwargs", ")", ":", "ctx", "=", "Context", "(", "*", "*", "kwargs", ")", "ctx", ".", "execute_action", "(", "'group:app:add'", ",", "*", "*", "{", "'storage'", ":", "ctx", ...
Add application with its weight into the routing group. Warning: application weight must be positive integer.
[ "Add", "application", "with", "its", "weight", "into", "the", "routing", "group", "." ]
python
train
ryanjdillon/pyotelem
pyotelem/dynamics.py
https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/dynamics.py#L34-L53
def pitch(ax, ay, az): '''Angle of x-axis relative to ground (theta) Args ---- ax: ndarray x-axis acceleration values ay: ndarray y-axis acceleration values az: ndarray z-axis acceleration values Returns ------- pitch: ndarray Pitch angle in radians ...
[ "def", "pitch", "(", "ax", ",", "ay", ",", "az", ")", ":", "import", "numpy", "# arctan2 not needed here to cover all quadrants, just for consistency", "return", "numpy", ".", "arctan", "(", "ax", ",", "numpy", ".", "sqrt", "(", "ay", "**", "2", "+", "az", "...
Angle of x-axis relative to ground (theta) Args ---- ax: ndarray x-axis acceleration values ay: ndarray y-axis acceleration values az: ndarray z-axis acceleration values Returns ------- pitch: ndarray Pitch angle in radians
[ "Angle", "of", "x", "-", "axis", "relative", "to", "ground", "(", "theta", ")" ]
python
train
arve0/leicascanningtemplate
leicascanningtemplate/template.py
https://github.com/arve0/leicascanningtemplate/blob/053e075d3bed11e335b61ce048c47067b8e9e921/leicascanningtemplate/template.py#L203-L207
def count_of_assigned_jobs(self): "Number of fields that have attrib['JobAssigned'] set to true." assigned = len([x.attrib['JobAssigned'] for x in self.fields if x.attrib['JobAssigned'] == 'true']) return assigned
[ "def", "count_of_assigned_jobs", "(", "self", ")", ":", "assigned", "=", "len", "(", "[", "x", ".", "attrib", "[", "'JobAssigned'", "]", "for", "x", "in", "self", ".", "fields", "if", "x", ".", "attrib", "[", "'JobAssigned'", "]", "==", "'true'", "]", ...
Number of fields that have attrib['JobAssigned'] set to true.
[ "Number", "of", "fields", "that", "have", "attrib", "[", "JobAssigned", "]", "set", "to", "true", "." ]
python
train
benjamin-hodgson/Contexts
src/contexts/tools.py
https://github.com/benjamin-hodgson/Contexts/blob/f5ee6a08aed19ab157158c1fc7752cff18cceb91/src/contexts/tools.py#L6-L22
def catch(func, *args, **kwargs): """ Call the supplied function with the supplied arguments, catching and returning any exception that it throws. Arguments: func: the function to run. *args: positional arguments to pass into the function. **kwargs: keyword arguments to pass int...
[ "def", "catch", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", "as", "e", ":", "return", "e" ]
Call the supplied function with the supplied arguments, catching and returning any exception that it throws. Arguments: func: the function to run. *args: positional arguments to pass into the function. **kwargs: keyword arguments to pass into the function. Returns: If the fu...
[ "Call", "the", "supplied", "function", "with", "the", "supplied", "arguments", "catching", "and", "returning", "any", "exception", "that", "it", "throws", "." ]
python
train
Nagasaki45/bibo
bibo/internals.py
https://github.com/Nagasaki45/bibo/blob/e6afb28711e78eb11475834d3f9455252ac9f347/bibo/internals.py#L111-L119
def editor(*args, **kwargs): ''' Wrapper for `click.edit` that raises an error when None is returned. ''' result = click.edit(*args, **kwargs) if result is None: msg = 'Editor exited without saving, command aborted' raise click.ClickException(msg) return result
[ "def", "editor", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "result", "=", "click", ".", "edit", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "result", "is", "None", ":", "msg", "=", "'Editor exited without saving, command aborted'", ...
Wrapper for `click.edit` that raises an error when None is returned.
[ "Wrapper", "for", "click", ".", "edit", "that", "raises", "an", "error", "when", "None", "is", "returned", "." ]
python
train
tanghaibao/jcvi
jcvi/assembly/hic.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L275-L281
def evaluate_tour_Q(self, tour): """ Use Cythonized version to evaluate the score of a current tour, taking orientation into consideration. This may be the most accurate evaluation under the right condition. """ from .chic import score_evaluate_Q return score_evaluate_Q(t...
[ "def", "evaluate_tour_Q", "(", "self", ",", "tour", ")", ":", "from", ".", "chic", "import", "score_evaluate_Q", "return", "score_evaluate_Q", "(", "tour", ",", "self", ".", "active_sizes", ",", "self", ".", "Q", ")" ]
Use Cythonized version to evaluate the score of a current tour, taking orientation into consideration. This may be the most accurate evaluation under the right condition.
[ "Use", "Cythonized", "version", "to", "evaluate", "the", "score", "of", "a", "current", "tour", "taking", "orientation", "into", "consideration", ".", "This", "may", "be", "the", "most", "accurate", "evaluation", "under", "the", "right", "condition", "." ]
python
train
chrismattmann/tika-python
tika/tika.py
https://github.com/chrismattmann/tika-python/blob/ffd3879ac3eaa9142c0fb6557cc1dc52d458a75a/tika/tika.py#L448-L476
def detectType1(option, urlOrPath, serverEndpoint=ServerEndpoint, verbose=Verbose, tikaServerJar=TikaServerJar, responseMimeType='text/plain', services={'type': '/detect/stream'}, config_path=None): ''' Detect the MIME/media type of the stream and return it in text/plain. :par...
[ "def", "detectType1", "(", "option", ",", "urlOrPath", ",", "serverEndpoint", "=", "ServerEndpoint", ",", "verbose", "=", "Verbose", ",", "tikaServerJar", "=", "TikaServerJar", ",", "responseMimeType", "=", "'text/plain'", ",", "services", "=", "{", "'type'", ":...
Detect the MIME/media type of the stream and return it in text/plain. :param option: :param urlOrPath: :param serverEndpoint: :param verbose: :param tikaServerJar: :param responseMimeType: :param services: :return:
[ "Detect", "the", "MIME", "/", "media", "type", "of", "the", "stream", "and", "return", "it", "in", "text", "/", "plain", ".", ":", "param", "option", ":", ":", "param", "urlOrPath", ":", ":", "param", "serverEndpoint", ":", ":", "param", "verbose", ":"...
python
train
molmod/molmod
molmod/ic.py
https://github.com/molmod/molmod/blob/a7b5b4364ed514ad4c465856c05b5eda1cb561e0/molmod/ic.py#L666-L680
def _dihed_cos_low(a, b, c, deriv): """Similar to dihed_cos, but with relative vectors""" a = Vector3(9, deriv, a, (0, 1, 2)) b = Vector3(9, deriv, b, (3, 4, 5)) c = Vector3(9, deriv, c, (6, 7, 8)) b /= b.norm() tmp = b.copy() tmp *= dot(a, b) a -= tmp tmp = b.copy() tmp *= dot(c...
[ "def", "_dihed_cos_low", "(", "a", ",", "b", ",", "c", ",", "deriv", ")", ":", "a", "=", "Vector3", "(", "9", ",", "deriv", ",", "a", ",", "(", "0", ",", "1", ",", "2", ")", ")", "b", "=", "Vector3", "(", "9", ",", "deriv", ",", "b", ",",...
Similar to dihed_cos, but with relative vectors
[ "Similar", "to", "dihed_cos", "but", "with", "relative", "vectors" ]
python
train
corpusops/pdbclone
lib/pdb_clone/bdb.py
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/bdb.py#L631-L636
def restart(self): """Restart the debugger after source code changes.""" _module_finder.reset() linecache.checkcache() for module_bpts in self.breakpoints.values(): module_bpts.reset()
[ "def", "restart", "(", "self", ")", ":", "_module_finder", ".", "reset", "(", ")", "linecache", ".", "checkcache", "(", ")", "for", "module_bpts", "in", "self", ".", "breakpoints", ".", "values", "(", ")", ":", "module_bpts", ".", "reset", "(", ")" ]
Restart the debugger after source code changes.
[ "Restart", "the", "debugger", "after", "source", "code", "changes", "." ]
python
train
Microsoft/azure-devops-python-api
azure-devops/azure/devops/v5_0/work_item_tracking_process/work_item_tracking_process_client.py
https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_0/work_item_tracking_process/work_item_tracking_process_client.py#L459-L487
def update_group(self, group, process_id, wit_ref_name, page_id, section_id, group_id): """UpdateGroup. [Preview API] Updates a group in the work item form. :param :class:`<Group> <azure.devops.v5_0.work_item_tracking_process.models.Group>` group: The updated group. :param str process_id...
[ "def", "update_group", "(", "self", ",", "group", ",", "process_id", ",", "wit_ref_name", ",", "page_id", ",", "section_id", ",", "group_id", ")", ":", "route_values", "=", "{", "}", "if", "process_id", "is", "not", "None", ":", "route_values", "[", "'proc...
UpdateGroup. [Preview API] Updates a group in the work item form. :param :class:`<Group> <azure.devops.v5_0.work_item_tracking_process.models.Group>` group: The updated group. :param str process_id: The ID of the process. :param str wit_ref_name: The reference name of the work item type....
[ "UpdateGroup", ".", "[", "Preview", "API", "]", "Updates", "a", "group", "in", "the", "work", "item", "form", ".", ":", "param", ":", "class", ":", "<Group", ">", "<azure", ".", "devops", ".", "v5_0", ".", "work_item_tracking_process", ".", "models", "."...
python
train
Vital-Fernandez/dazer
bin/lib/Astro_Libraries/f2n.py
https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Astro_Libraries/f2n.py#L841-L861
def writeinfo(self, linelist, colour = None): """ We add a longer chunk of text on the upper left corner of the image. Provide linelist, a list of strings that will be written one below the other. """ self.checkforpilimage() colour = self.defaultcolour(colour) ...
[ "def", "writeinfo", "(", "self", ",", "linelist", ",", "colour", "=", "None", ")", ":", "self", ".", "checkforpilimage", "(", ")", "colour", "=", "self", ".", "defaultcolour", "(", "colour", ")", "self", ".", "changecolourmode", "(", "colour", ")", "self...
We add a longer chunk of text on the upper left corner of the image. Provide linelist, a list of strings that will be written one below the other.
[ "We", "add", "a", "longer", "chunk", "of", "text", "on", "the", "upper", "left", "corner", "of", "the", "image", ".", "Provide", "linelist", "a", "list", "of", "strings", "that", "will", "be", "written", "one", "below", "the", "other", "." ]
python
train
fastai/fastai
fastai/vision/tta.py
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/tta.py#L32-L43
def _TTA(learn:Learner, beta:float=0.4, scale:float=1.35, ds_type:DatasetType=DatasetType.Valid, with_loss:bool=False) -> Tensors: "Applies TTA to predict on `ds_type` dataset." preds,y = learn.get_preds(ds_type) all_preds = list(learn.tta_only(scale=scale, ds_type=ds_type)) avg_preds = torch.stack(all_...
[ "def", "_TTA", "(", "learn", ":", "Learner", ",", "beta", ":", "float", "=", "0.4", ",", "scale", ":", "float", "=", "1.35", ",", "ds_type", ":", "DatasetType", "=", "DatasetType", ".", "Valid", ",", "with_loss", ":", "bool", "=", "False", ")", "->",...
Applies TTA to predict on `ds_type` dataset.
[ "Applies", "TTA", "to", "predict", "on", "ds_type", "dataset", "." ]
python
train
Autodesk/aomi
aomi/util.py
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/util.py#L12-L35
def update_user_password(client, userpass): """Will update the password for a userpass user""" vault_path = '' user = '' user_path_bits = userpass.split('/') if len(user_path_bits) == 1: user = user_path_bits[0] vault_path = "auth/userpass/users/%s/password" % user LOG.debug(...
[ "def", "update_user_password", "(", "client", ",", "userpass", ")", ":", "vault_path", "=", "''", "user", "=", "''", "user_path_bits", "=", "userpass", ".", "split", "(", "'/'", ")", "if", "len", "(", "user_path_bits", ")", "==", "1", ":", "user", "=", ...
Will update the password for a userpass user
[ "Will", "update", "the", "password", "for", "a", "userpass", "user" ]
python
train
loli/medpy
medpy/metric/binary.py
https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/metric/binary.py#L223-L268
def specificity(result, reference): """ Specificity. Parameters ---------- result : array_like Input data containing objects. Can be any type but will be converted into binary: background where 0, object everywhere else. reference : array_like Input data containing o...
[ "def", "specificity", "(", "result", ",", "reference", ")", ":", "result", "=", "numpy", ".", "atleast_1d", "(", "result", ".", "astype", "(", "numpy", ".", "bool", ")", ")", "reference", "=", "numpy", ".", "atleast_1d", "(", "reference", ".", "astype", ...
Specificity. Parameters ---------- result : array_like Input data containing objects. Can be any type but will be converted into binary: background where 0, object everywhere else. reference : array_like Input data containing objects. Can be any type but will be converted ...
[ "Specificity", ".", "Parameters", "----------", "result", ":", "array_like", "Input", "data", "containing", "objects", ".", "Can", "be", "any", "type", "but", "will", "be", "converted", "into", "binary", ":", "background", "where", "0", "object", "everywhere", ...
python
train
secdev/scapy
scapy/main.py
https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/main.py#L336-L349
def update_session(fname=None): """Update current Scapy session from the file specified in the fname arg. params: - fname: file to load the scapy session from""" if fname is None: fname = conf.session try: s = six.moves.cPickle.load(gzip.open(fname, "rb")) except IOError: ...
[ "def", "update_session", "(", "fname", "=", "None", ")", ":", "if", "fname", "is", "None", ":", "fname", "=", "conf", ".", "session", "try", ":", "s", "=", "six", ".", "moves", ".", "cPickle", ".", "load", "(", "gzip", ".", "open", "(", "fname", ...
Update current Scapy session from the file specified in the fname arg. params: - fname: file to load the scapy session from
[ "Update", "current", "Scapy", "session", "from", "the", "file", "specified", "in", "the", "fname", "arg", "." ]
python
train
gem/oq-engine
openquake/hazardlib/gsim/lin_2009.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/lin_2009.py#L67-L81
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ C = self.COEFFS[imt] mean = ( self._get_magnitude_...
[ "def", "get_mean_and_stddevs", "(", "self", ",", "sites", ",", "rup", ",", "dists", ",", "imt", ",", "stddev_types", ")", ":", "C", "=", "self", ".", "COEFFS", "[", "imt", "]", "mean", "=", "(", "self", ".", "_get_magnitude_term", "(", "C", ",", "rup...
See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.
[ "See", ":", "meth", ":", "superclass", "method", "<", ".", "base", ".", "GroundShakingIntensityModel", ".", "get_mean_and_stddevs", ">", "for", "spec", "of", "input", "and", "result", "values", "." ]
python
train
fuzeman/PyUPnP
pyupnp/logr.py
https://github.com/fuzeman/PyUPnP/blob/6dea64be299952346a14300ab6cc7dac42736433/pyupnp/logr.py#L31-L48
def configure(level=logging.WARNING, handler=None, formatter=None): """Configure Logr @param handler: Logger message handler @type handler: logging.Handler or None @param formatter: Logger message Formatter @type formatter: logging.Formatter or None """ if forma...
[ "def", "configure", "(", "level", "=", "logging", ".", "WARNING", ",", "handler", "=", "None", ",", "formatter", "=", "None", ")", ":", "if", "formatter", "is", "None", ":", "formatter", "=", "LogrFormatter", "(", ")", "if", "handler", "is", "None", ":...
Configure Logr @param handler: Logger message handler @type handler: logging.Handler or None @param formatter: Logger message Formatter @type formatter: logging.Formatter or None
[ "Configure", "Logr" ]
python
train
pydata/xarray
xarray/backends/api.py
https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/backends/api.py#L829-L851
def dump_to_store(dataset, store, writer=None, encoder=None, encoding=None, unlimited_dims=None): """Store dataset contents to a backends.*DataStore object.""" if writer is None: writer = ArrayWriter() if encoding is None: encoding = {} variables, attrs = conventions....
[ "def", "dump_to_store", "(", "dataset", ",", "store", ",", "writer", "=", "None", ",", "encoder", "=", "None", ",", "encoding", "=", "None", ",", "unlimited_dims", "=", "None", ")", ":", "if", "writer", "is", "None", ":", "writer", "=", "ArrayWriter", ...
Store dataset contents to a backends.*DataStore object.
[ "Store", "dataset", "contents", "to", "a", "backends", ".", "*", "DataStore", "object", "." ]
python
train
saltstack/salt
salt/utils/boto3mod.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/boto3mod.py#L231-L237
def get_region(service, region, profile): """ Retrieve the region for a particular AWS service based on configured region and/or profile. """ _, region, _, _ = _get_profile(service, region, None, None, profile) return region
[ "def", "get_region", "(", "service", ",", "region", ",", "profile", ")", ":", "_", ",", "region", ",", "_", ",", "_", "=", "_get_profile", "(", "service", ",", "region", ",", "None", ",", "None", ",", "profile", ")", "return", "region" ]
Retrieve the region for a particular AWS service based on configured region and/or profile.
[ "Retrieve", "the", "region", "for", "a", "particular", "AWS", "service", "based", "on", "configured", "region", "and", "/", "or", "profile", "." ]
python
train
saltstack/salt
salt/modules/solr.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L996-L1022
def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr ini...
[ "def", "signal", "(", "signal", "=", "None", ")", ":", "valid_signals", "=", "(", "'start'", ",", "'stop'", ",", "'restart'", ")", "# Give a friendly error message for invalid signals", "# TODO: Fix this logic to be reusable and used by apache.signal", "if", "signal", "not"...
Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', '...
[ "Signals", "Apache", "Solr", "to", "start", "stop", "or", "restart", ".", "Obviously", "this", "is", "only", "going", "to", "work", "if", "the", "minion", "resides", "on", "the", "solr", "host", ".", "Additionally", "Solr", "doesn", "t", "ship", "with", ...
python
train
SHDShim/pytheos
pytheos/eqn_vinet.py
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_vinet.py#L154-L163
def cal_k_vinet(p, k): """ calculate bulk modulus in GPa :param p: pressure in GPa :param k: [v0, k0, k0p] :return: bulk modulus at high pressure in GPa """ v = cal_v_vinet(p, k) return cal_k_vinet_from_v(v, k[0], k[1], k[2])
[ "def", "cal_k_vinet", "(", "p", ",", "k", ")", ":", "v", "=", "cal_v_vinet", "(", "p", ",", "k", ")", "return", "cal_k_vinet_from_v", "(", "v", ",", "k", "[", "0", "]", ",", "k", "[", "1", "]", ",", "k", "[", "2", "]", ")" ]
calculate bulk modulus in GPa :param p: pressure in GPa :param k: [v0, k0, k0p] :return: bulk modulus at high pressure in GPa
[ "calculate", "bulk", "modulus", "in", "GPa" ]
python
train
lrq3000/pyFileFixity
pyFileFixity/lib/profilers/visual/profilehooks.py
https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/profilehooks.py#L617-L622
def mark(self, lineno, count=1): """Mark a given source line as executed count times. Multiple calls to mark for the same lineno add up. """ self.sourcelines[lineno] = self.sourcelines.get(lineno, 0) + count
[ "def", "mark", "(", "self", ",", "lineno", ",", "count", "=", "1", ")", ":", "self", ".", "sourcelines", "[", "lineno", "]", "=", "self", ".", "sourcelines", ".", "get", "(", "lineno", ",", "0", ")", "+", "count" ]
Mark a given source line as executed count times. Multiple calls to mark for the same lineno add up.
[ "Mark", "a", "given", "source", "line", "as", "executed", "count", "times", "." ]
python
train
jayme-github/steam_idle
steam_idle/idle.py
https://github.com/jayme-github/steam_idle/blob/4f9b887fd6c3aea3baa9087f88ee739efcc150cc/steam_idle/idle.py#L53-L79
def calc_delay(remainingDrops): ''' Calculate the idle delay Minimum play time for cards to drop is ~20min again. Except for accounts that requested a refund? Re-check every 15 mintes if there are more than 1 card drops remaining. If only one drop remains, check every 5 minutes ...
[ "def", "calc_delay", "(", "remainingDrops", ")", ":", "global", "sameDelay", ",", "lastDelay", "# Reset lastDelay for new appids", "if", "remainingDrops", ">", "1", ":", "lastDelay", "=", "5", "sameDelay", "=", "0", "if", "remainingDrops", ">", "2", ":", "return...
Calculate the idle delay Minimum play time for cards to drop is ~20min again. Except for accounts that requested a refund? Re-check every 15 mintes if there are more than 1 card drops remaining. If only one drop remains, check every 5 minutes
[ "Calculate", "the", "idle", "delay", "Minimum", "play", "time", "for", "cards", "to", "drop", "is", "~20min", "again", ".", "Except", "for", "accounts", "that", "requested", "a", "refund?" ]
python
train
Pytwitcher/pytwitcherapi
src/pytwitcherapi/session.py
https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/session.py#L258-L277
def oldapi_request(self, method, endpoint, **kwargs): """Make a request to one of the old api endpoints. The url will be constructed of :data:`TWITCH_APIURL` and the given endpoint. :param method: the request method :type method: :class:`str` :param endpoint: the endpoi...
[ "def", "oldapi_request", "(", "self", ",", "method", ",", "endpoint", ",", "*", "*", "kwargs", ")", ":", "headers", "=", "kwargs", ".", "setdefault", "(", "'headers'", ",", "{", "}", ")", "headers", "[", "'Client-ID'", "]", "=", "CLIENT_ID", "# https://g...
Make a request to one of the old api endpoints. The url will be constructed of :data:`TWITCH_APIURL` and the given endpoint. :param method: the request method :type method: :class:`str` :param endpoint: the endpoint of the old api. The base url is autom...
[ "Make", "a", "request", "to", "one", "of", "the", "old", "api", "endpoints", "." ]
python
train
miso-belica/sumy
sumy/summarizers/edmundson_cue.py
https://github.com/miso-belica/sumy/blob/099ab4938e2c1b6a011297375586bac2953641b9/sumy/summarizers/edmundson_cue.py#L32-L50
def _count_words(self, words): """ Counts number of bonus/stigma words. :param iterable words: Collection of words. :returns pair: Tuple with number of words (bonus words, stigma words). """ bonus_words_count = 0 stigma_words_count = 0 ...
[ "def", "_count_words", "(", "self", ",", "words", ")", ":", "bonus_words_count", "=", "0", "stigma_words_count", "=", "0", "for", "word", "in", "words", ":", "if", "word", "in", "self", ".", "_bonus_words", ":", "bonus_words_count", "+=", "1", "if", "word"...
Counts number of bonus/stigma words. :param iterable words: Collection of words. :returns pair: Tuple with number of words (bonus words, stigma words).
[ "Counts", "number", "of", "bonus", "/", "stigma", "words", "." ]
python
train
google/openhtf
openhtf/util/logs.py
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/logs.py#L294-L315
def format(self, record): """Format the record as tersely as possible but preserve info.""" super(CliFormatter, self).format(record) localized_time = datetime.datetime.fromtimestamp(record.created) terse_time = localized_time.strftime(u'%H:%M:%S') terse_level = record.levelname[0] terse_name = r...
[ "def", "format", "(", "self", ",", "record", ")", ":", "super", "(", "CliFormatter", ",", "self", ")", ".", "format", "(", "record", ")", "localized_time", "=", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "record", ".", "created", ")", "terse...
Format the record as tersely as possible but preserve info.
[ "Format", "the", "record", "as", "tersely", "as", "possible", "but", "preserve", "info", "." ]
python
train
Azure/azure-cli-extensions
src/sqlvm-preview/azext_sqlvm_preview/_format.py
https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/sqlvm-preview/azext_sqlvm_preview/_format.py#L41-L68
def transform_sqlvm_output(result): ''' Transforms the result of SQL virtual machine group to eliminate unnecessary parameters. ''' from collections import OrderedDict from msrestazure.tools import parse_resource_id try: resource_group = getattr(result, 'resource_group', None) or parse_r...
[ "def", "transform_sqlvm_output", "(", "result", ")", ":", "from", "collections", "import", "OrderedDict", "from", "msrestazure", ".", "tools", "import", "parse_resource_id", "try", ":", "resource_group", "=", "getattr", "(", "result", ",", "'resource_group'", ",", ...
Transforms the result of SQL virtual machine group to eliminate unnecessary parameters.
[ "Transforms", "the", "result", "of", "SQL", "virtual", "machine", "group", "to", "eliminate", "unnecessary", "parameters", "." ]
python
train
ChrisCummins/labm8
system.py
https://github.com/ChrisCummins/labm8/blob/dd10d67a757aefb180cb508f86696f99440c94f5/system.py#L205-L214
def sed(match, replacement, path, modifiers=""): """ Perform sed text substitution. """ cmd = "sed -r -i 's/%s/%s/%s' %s" % (match, replacement, modifiers, path) process = Subprocess(cmd, shell=True) ret, out, err = process.run(timeout=60) if ret: raise SubprocessError("Sed command ...
[ "def", "sed", "(", "match", ",", "replacement", ",", "path", ",", "modifiers", "=", "\"\"", ")", ":", "cmd", "=", "\"sed -r -i 's/%s/%s/%s' %s\"", "%", "(", "match", ",", "replacement", ",", "modifiers", ",", "path", ")", "process", "=", "Subprocess", "(",...
Perform sed text substitution.
[ "Perform", "sed", "text", "substitution", "." ]
python
train
kalefranz/auxlib
auxlib/_vendor/boltons/timeutils.py
https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/_vendor/boltons/timeutils.py#L122-L161
def parse_timedelta(text): """Robustly parses a short text description of a time period into a :class:`datetime.timedelta`. Supports weeks, days, hours, minutes, and seconds, with or without decimal points: Args: text (str): Text to parse. Returns: datetime.timedelta Raises: ...
[ "def", "parse_timedelta", "(", "text", ")", ":", "td_kwargs", "=", "{", "}", "for", "match", "in", "_PARSE_TD_RE", ".", "finditer", "(", "text", ")", ":", "value", ",", "unit", "=", "match", ".", "group", "(", "'value'", ")", ",", "match", ".", "grou...
Robustly parses a short text description of a time period into a :class:`datetime.timedelta`. Supports weeks, days, hours, minutes, and seconds, with or without decimal points: Args: text (str): Text to parse. Returns: datetime.timedelta Raises: ValueError: on parse failure....
[ "Robustly", "parses", "a", "short", "text", "description", "of", "a", "time", "period", "into", "a", ":", "class", ":", "datetime", ".", "timedelta", ".", "Supports", "weeks", "days", "hours", "minutes", "and", "seconds", "with", "or", "without", "decimal", ...
python
train
CalebBell/fluids
fluids/geometry.py
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/geometry.py#L693-L782
def V_vertical_torispherical(D, f, k, h): r'''Calculates volume of a vertical tank with a convex torispherical bottom, according to [1]_. No provision for the top of the tank is made here. .. math:: V_f = \frac{\pi h^2}{4}\left(2a_1 + \frac{D_1^2}{2a_1} - \frac{4h}{3}\right),\; 0 \le h \le ...
[ "def", "V_vertical_torispherical", "(", "D", ",", "f", ",", "k", ",", "h", ")", ":", "alpha", "=", "asin", "(", "(", "1", "-", "2", "*", "k", ")", "/", "(", "2", "*", "(", "f", "-", "k", ")", ")", ")", "a1", "=", "f", "*", "D", "*", "("...
r'''Calculates volume of a vertical tank with a convex torispherical bottom, according to [1]_. No provision for the top of the tank is made here. .. math:: V_f = \frac{\pi h^2}{4}\left(2a_1 + \frac{D_1^2}{2a_1} - \frac{4h}{3}\right),\; 0 \le h \le a_1 .. math:: V_f = \frac{\pi}{4}...
[ "r", "Calculates", "volume", "of", "a", "vertical", "tank", "with", "a", "convex", "torispherical", "bottom", "according", "to", "[", "1", "]", "_", ".", "No", "provision", "for", "the", "top", "of", "the", "tank", "is", "made", "here", "." ]
python
train
woolfson-group/isambard
isambard/optimisation/optimizer.py
https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/optimisation/optimizer.py#L89-L103
def comparator_eval(comparator_params): """Gets BUFF score for interaction between two AMPAL objects """ top1, top2, params1, params2, seq1, seq2, movements = comparator_params xrot, yrot, zrot, xtrans, ytrans, ztrans = movements obj1 = top1(*params1) obj2 = top2(*params2) obj2.rotate(xrot, ...
[ "def", "comparator_eval", "(", "comparator_params", ")", ":", "top1", ",", "top2", ",", "params1", ",", "params2", ",", "seq1", ",", "seq2", ",", "movements", "=", "comparator_params", "xrot", ",", "yrot", ",", "zrot", ",", "xtrans", ",", "ytrans", ",", ...
Gets BUFF score for interaction between two AMPAL objects
[ "Gets", "BUFF", "score", "for", "interaction", "between", "two", "AMPAL", "objects" ]
python
train
fermiPy/fermipy
fermipy/hpx_utils.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/hpx_utils.py#L122-L155
def make_hpx_to_wcs_mapping_centers(hpx, wcs): """ Make the mapping data needed to from from HPX pixelization to a WCS-based array Parameters ---------- hpx : `~fermipy.hpx_utils.HPX` The healpix mapping (an HPX object) wcs : `~astropy.wcs.WCS` The wcs mapping (a pywcs.wc...
[ "def", "make_hpx_to_wcs_mapping_centers", "(", "hpx", ",", "wcs", ")", ":", "npix", "=", "(", "int", "(", "wcs", ".", "wcs", ".", "crpix", "[", "0", "]", "*", "2", ")", ",", "int", "(", "wcs", ".", "wcs", ".", "crpix", "[", "1", "]", "*", "2", ...
Make the mapping data needed to from from HPX pixelization to a WCS-based array Parameters ---------- hpx : `~fermipy.hpx_utils.HPX` The healpix mapping (an HPX object) wcs : `~astropy.wcs.WCS` The wcs mapping (a pywcs.wcs object) Returns ------- ipixs : ar...
[ "Make", "the", "mapping", "data", "needed", "to", "from", "from", "HPX", "pixelization", "to", "a", "WCS", "-", "based", "array" ]
python
train
isambard-uob/ampal
src/ampal/naccess.py
https://github.com/isambard-uob/ampal/blob/906e2afacb435ffb129b381f262ff8e7bfb324c5/src/ampal/naccess.py#L8-L19
def naccess_available(): """True if naccess is available on the path.""" available = False try: subprocess.check_output(['naccess'], stderr=subprocess.DEVNULL) except subprocess.CalledProcessError: available = True except FileNotFoundError: print("naccess has not been found o...
[ "def", "naccess_available", "(", ")", ":", "available", "=", "False", "try", ":", "subprocess", ".", "check_output", "(", "[", "'naccess'", "]", ",", "stderr", "=", "subprocess", ".", "DEVNULL", ")", "except", "subprocess", ".", "CalledProcessError", ":", "a...
True if naccess is available on the path.
[ "True", "if", "naccess", "is", "available", "on", "the", "path", "." ]
python
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L427-L449
def runAutomationCommands(self, projectFile, commands, capture=False): ''' Invokes the Automation Test commandlet for the specified project with the supplied automation test commands ''' # IMPORTANT IMPLEMENTATION NOTE: # We need to format the command as a string and execute it using a shell in order to ...
[ "def", "runAutomationCommands", "(", "self", ",", "projectFile", ",", "commands", ",", "capture", "=", "False", ")", ":", "# IMPORTANT IMPLEMENTATION NOTE:", "# We need to format the command as a string and execute it using a shell in order to", "# ensure the \"-ExecCmds\" argument w...
Invokes the Automation Test commandlet for the specified project with the supplied automation test commands
[ "Invokes", "the", "Automation", "Test", "commandlet", "for", "the", "specified", "project", "with", "the", "supplied", "automation", "test", "commands" ]
python
train
twitterdev/search-tweets-python
searchtweets/api_utils.py
https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/api_utils.py#L86-L138
def gen_rule_payload(pt_rule, results_per_call=None, from_date=None, to_date=None, count_bucket=None, tag=None, stringify=True): """ Generates the dict or json payload for a PowerTrack rule. Args: pt_rule (str): The string version of a...
[ "def", "gen_rule_payload", "(", "pt_rule", ",", "results_per_call", "=", "None", ",", "from_date", "=", "None", ",", "to_date", "=", "None", ",", "count_bucket", "=", "None", ",", "tag", "=", "None", ",", "stringify", "=", "True", ")", ":", "pt_rule", "=...
Generates the dict or json payload for a PowerTrack rule. Args: pt_rule (str): The string version of a powertrack rule, e.g., "beyonce has:geo". Accepts multi-line strings for ease of entry. results_per_call (int): number of tweets or counts returned per API call. Th...
[ "Generates", "the", "dict", "or", "json", "payload", "for", "a", "PowerTrack", "rule", "." ]
python
train
bcbio/bcbio-nextgen
bcbio/distributed/objectstore.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/objectstore.py#L164-L170
def _chunk_offsets(self): """Iterator over chunk offests.""" index = 0 blob_size = self.blob_properties.get('content-length') while index < blob_size: yield index index = index + self._chunk_size
[ "def", "_chunk_offsets", "(", "self", ")", ":", "index", "=", "0", "blob_size", "=", "self", ".", "blob_properties", ".", "get", "(", "'content-length'", ")", "while", "index", "<", "blob_size", ":", "yield", "index", "index", "=", "index", "+", "self", ...
Iterator over chunk offests.
[ "Iterator", "over", "chunk", "offests", "." ]
python
train
i3visio/osrframework
osrframework/utils/general.py
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/general.py#L448-L594
def _generateGraphData(data, oldData=nx.Graph()): """ Processing the data from i3visio structures to generate nodes and edges This function uses the networkx graph library. It will create a new node for each and i3visio.<something> entities while it will add properties for all the attribute startin...
[ "def", "_generateGraphData", "(", "data", ",", "oldData", "=", "nx", ".", "Graph", "(", ")", ")", ":", "def", "_addNewNode", "(", "ent", ",", "g", ")", ":", "\"\"\"\n Wraps the creation of a node\n\n Args:\n -----\n ent: The hi3visio-like...
Processing the data from i3visio structures to generate nodes and edges This function uses the networkx graph library. It will create a new node for each and i3visio.<something> entities while it will add properties for all the attribute starting with "@". Args: ----- d: The i3visio struct...
[ "Processing", "the", "data", "from", "i3visio", "structures", "to", "generate", "nodes", "and", "edges" ]
python
train
codenerix/django-codenerix-invoicing
codenerix_invoicing/views_sales.py
https://github.com/codenerix/django-codenerix-invoicing/blob/7db5c62f335f9215a8b308603848625208b48698/codenerix_invoicing/views_sales.py#L2190-L2199
def dispatch(self, *args, **kwargs): self.__line_pk = kwargs.get('pk', None) """ if SalesLineBasketOption.objects.filter(line_budget__pk=self.__line_pk).exists(): self.form_class = LineBasketFormPack self.__is_pack = True else: self.__is_pack = False ...
[ "def", "dispatch", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "__line_pk", "=", "kwargs", ".", "get", "(", "'pk'", ",", "None", ")", "return", "super", "(", "LinesUpdateModalBasket", ",", "self", ")", ".", "dispatc...
if SalesLineBasketOption.objects.filter(line_budget__pk=self.__line_pk).exists(): self.form_class = LineBasketFormPack self.__is_pack = True else: self.__is_pack = False
[ "if", "SalesLineBasketOption", ".", "objects", ".", "filter", "(", "line_budget__pk", "=", "self", ".", "__line_pk", ")", ".", "exists", "()", ":", "self", ".", "form_class", "=", "LineBasketFormPack", "self", ".", "__is_pack", "=", "True", "else", ":", "sel...
python
train
gccxml/pygccxml
pygccxml/declarations/scopedef.py
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/scopedef.py#L351-L357
def __normalize_args(**keywds): """implementation details""" if isinstance(keywds['name'], Callable) and \ None is keywds['function']: keywds['function'] = keywds['name'] keywds['name'] = None return keywds
[ "def", "__normalize_args", "(", "*", "*", "keywds", ")", ":", "if", "isinstance", "(", "keywds", "[", "'name'", "]", ",", "Callable", ")", "and", "None", "is", "keywds", "[", "'function'", "]", ":", "keywds", "[", "'function'", "]", "=", "keywds", "[",...
implementation details
[ "implementation", "details" ]
python
train
thwehner/python-firepit
setup.py
https://github.com/thwehner/python-firepit/blob/68aa3b9c9e034e6a9a3498d997ac8d9a03f8c0f9/setup.py#L12-L20
def get_package_version(): """returns package version without importing it""" base = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(base, "firepit/__init__.py")) as pkg: for line in pkg: m = version.match(line.strip()) if not m: continue ...
[ "def", "get_package_version", "(", ")", ":", "base", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "base", ",", "\"firepit/__init__...
returns package version without importing it
[ "returns", "package", "version", "without", "importing", "it" ]
python
train
vtkiorg/vtki
vtki/renderer.py
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/renderer.py#L499-L503
def camera_position(self): """ Returns camera position of active render window """ return [self.camera.GetPosition(), self.camera.GetFocalPoint(), self.camera.GetViewUp()]
[ "def", "camera_position", "(", "self", ")", ":", "return", "[", "self", ".", "camera", ".", "GetPosition", "(", ")", ",", "self", ".", "camera", ".", "GetFocalPoint", "(", ")", ",", "self", ".", "camera", ".", "GetViewUp", "(", ")", "]" ]
Returns camera position of active render window
[ "Returns", "camera", "position", "of", "active", "render", "window" ]
python
train
kgori/treeCl
treeCl/collection.py
https://github.com/kgori/treeCl/blob/fed624b3db1c19cc07175ca04e3eda6905a8d305/treeCl/collection.py#L361-L391
def calc_distances(self, indices=None, task_interface=None, jobhandler=default_jobhandler, batchsize=1, show_progress=True): """ Calculate fast approximate intra-alignment pairwise distances and variances using ML (requires ML models to have been set up using `calc_trees`)...
[ "def", "calc_distances", "(", "self", ",", "indices", "=", "None", ",", "task_interface", "=", "None", ",", "jobhandler", "=", "default_jobhandler", ",", "batchsize", "=", "1", ",", "show_progress", "=", "True", ")", ":", "if", "indices", "is", "None", ":"...
Calculate fast approximate intra-alignment pairwise distances and variances using ML (requires ML models to have been set up using `calc_trees`). :return: None (all side effects)
[ "Calculate", "fast", "approximate", "intra", "-", "alignment", "pairwise", "distances", "and", "variances", "using", "ML", "(", "requires", "ML", "models", "to", "have", "been", "set", "up", "using", "calc_trees", ")", ".", ":", "return", ":", "None", "(", ...
python
train
rootpy/rootpy
rootpy/extern/pyparsing.py
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/extern/pyparsing.py#L3189-L3213
def matchPreviousExpr(expr): """Helper to define an expression that is indirectly defined from the tokens matched in a previous expression, that is, it looks for a 'repeat' of a previous expression. For example:: first = Word(nums) second = matchPreviousExpr(first) ...
[ "def", "matchPreviousExpr", "(", "expr", ")", ":", "rep", "=", "Forward", "(", ")", "e2", "=", "expr", ".", "copy", "(", ")", "rep", "<<=", "e2", "def", "copyTokenToRepeater", "(", "s", ",", "l", ",", "t", ")", ":", "matchTokens", "=", "_flatten", ...
Helper to define an expression that is indirectly defined from the tokens matched in a previous expression, that is, it looks for a 'repeat' of a previous expression. For example:: first = Word(nums) second = matchPreviousExpr(first) matchExpr = first + ":" + second ...
[ "Helper", "to", "define", "an", "expression", "that", "is", "indirectly", "defined", "from", "the", "tokens", "matched", "in", "a", "previous", "expression", "that", "is", "it", "looks", "for", "a", "repeat", "of", "a", "previous", "expression", ".", "For", ...
python
train
squaresLab/BugZoo
bugzoo/mgr/container.py
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/container.py#L262-L272
def is_alive(self, container: Container) -> bool: """ Determines whether a given container is still alive. Returns: `True` if the underlying Docker container for the given BugZoo container is still alive, otherwise `False`. """ uid = container.uid ...
[ "def", "is_alive", "(", "self", ",", "container", ":", "Container", ")", "->", "bool", ":", "uid", "=", "container", ".", "uid", "return", "uid", "in", "self", ".", "__dockerc", "and", "self", ".", "__dockerc", "[", "uid", "]", ".", "status", "==", "...
Determines whether a given container is still alive. Returns: `True` if the underlying Docker container for the given BugZoo container is still alive, otherwise `False`.
[ "Determines", "whether", "a", "given", "container", "is", "still", "alive", "." ]
python
train
WebarchivCZ/WA-KAT
src/wa_kat/analyzers/keyword_detector.py
https://github.com/WebarchivCZ/WA-KAT/blob/16d064a3a775dc1d2713debda7847ded52dd2a06/src/wa_kat/analyzers/keyword_detector.py#L76-L94
def get_dc_keywords(index_page): """ Return list of `keywords` parsed from Dublin core. Args: index_page (str): Content of the page as UTF-8 string Returns: list: List of :class:`.SourceString` objects. """ keyword_lists = ( keyword_list.split() for keyword_list...
[ "def", "get_dc_keywords", "(", "index_page", ")", ":", "keyword_lists", "=", "(", "keyword_list", ".", "split", "(", ")", "for", "keyword_list", "in", "parse_meta", "(", "index_page", ",", "\"dc.keywords\"", ",", "\"DC\"", ")", ")", "return", "[", "SourceStrin...
Return list of `keywords` parsed from Dublin core. Args: index_page (str): Content of the page as UTF-8 string Returns: list: List of :class:`.SourceString` objects.
[ "Return", "list", "of", "keywords", "parsed", "from", "Dublin", "core", "." ]
python
train
pandas-dev/pandas
pandas/io/excel/_openpyxl.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/excel/_openpyxl.py#L38-L56
def _convert_to_style(cls, style_dict): """ converts a style_dict to an openpyxl style object Parameters ---------- style_dict : style dictionary to convert """ from openpyxl.style import Style xls_style = Style() for key, value in style_dict.item...
[ "def", "_convert_to_style", "(", "cls", ",", "style_dict", ")", ":", "from", "openpyxl", ".", "style", "import", "Style", "xls_style", "=", "Style", "(", ")", "for", "key", ",", "value", "in", "style_dict", ".", "items", "(", ")", ":", "for", "nk", ","...
converts a style_dict to an openpyxl style object Parameters ---------- style_dict : style dictionary to convert
[ "converts", "a", "style_dict", "to", "an", "openpyxl", "style", "object", "Parameters", "----------", "style_dict", ":", "style", "dictionary", "to", "convert" ]
python
train
ui/django-thumbnails
thumbnails/files.py
https://github.com/ui/django-thumbnails/blob/5cef55e7f167060458709ed760dd43981124796a/thumbnails/files.py#L69-L91
def get(self, size, create=True): """ Returns a Thumbnail instance. First check whether thumbnail is already cached. If it doesn't: 1. Try to fetch the thumbnail 2. Create thumbnail if it's not present 3. Cache the thumbnail for future use """ if self._thu...
[ "def", "get", "(", "self", ",", "size", ",", "create", "=", "True", ")", ":", "if", "self", ".", "_thumbnails", "is", "None", ":", "self", ".", "_refresh_cache", "(", ")", "thumbnail", "=", "self", ".", "_thumbnails", ".", "get", "(", "size", ")", ...
Returns a Thumbnail instance. First check whether thumbnail is already cached. If it doesn't: 1. Try to fetch the thumbnail 2. Create thumbnail if it's not present 3. Cache the thumbnail for future use
[ "Returns", "a", "Thumbnail", "instance", ".", "First", "check", "whether", "thumbnail", "is", "already", "cached", ".", "If", "it", "doesn", "t", ":", "1", ".", "Try", "to", "fetch", "the", "thumbnail", "2", ".", "Create", "thumbnail", "if", "it", "s", ...
python
test
projectshift/shift-schema
shiftschema/validators/email.py
https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/validators/email.py#L45-L74
def regex(self): """ RFC822 Email Address Regex Originally written by Cal Henderson c.f. http://iamcal.com/publish/articles/php/parsing_email/ Translated to Python by Tim Fletcher with changes suggested by Dan Kubb http://tfletcher.com/lib/rfc822.py Licensed under...
[ "def", "regex", "(", "self", ")", ":", "qtext", "=", "'[^\\\\x0d\\\\x22\\\\x5c\\\\x80-\\\\xff]'", "dtext", "=", "'[^\\\\x0d\\\\x5b-\\\\x5d\\\\x80-\\\\xff]'", "atom", "=", "'[^\\\\x00-\\\\x20\\\\x22\\\\x28\\\\x29\\\\x2c\\\\x2e\\\\x3a-\\\\x3c\\\\x3e\\\\x40'", "atom", "+=", "'\\\\x5b-...
RFC822 Email Address Regex Originally written by Cal Henderson c.f. http://iamcal.com/publish/articles/php/parsing_email/ Translated to Python by Tim Fletcher with changes suggested by Dan Kubb http://tfletcher.com/lib/rfc822.py Licensed under a Creative Commons Attribution-Share...
[ "RFC822", "Email", "Address", "Regex", "Originally", "written", "by", "Cal", "Henderson", "c", ".", "f", ".", "http", ":", "//", "iamcal", ".", "com", "/", "publish", "/", "articles", "/", "php", "/", "parsing_email", "/", "Translated", "to", "Python", "...
python
train
mixmastamyk/console
console/utils.py
https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/utils.py#L122-L144
def strip_ansi(text, c1=False, osc=False): ''' Strip ANSI escape sequences from a portion of text. https://stackoverflow.com/a/38662876/450917 Arguments: line: str osc: bool - include OSC commands in the strippage. c1: bool - include C1 commands in the strippa...
[ "def", "strip_ansi", "(", "text", ",", "c1", "=", "False", ",", "osc", "=", "False", ")", ":", "text", "=", "ansi_csi0_finder", ".", "sub", "(", "''", ",", "text", ")", "if", "osc", ":", "text", "=", "ansi_osc0_finder", ".", "sub", "(", "''", ",", ...
Strip ANSI escape sequences from a portion of text. https://stackoverflow.com/a/38662876/450917 Arguments: line: str osc: bool - include OSC commands in the strippage. c1: bool - include C1 commands in the strippage. Notes: Enabling c1 and osc...
[ "Strip", "ANSI", "escape", "sequences", "from", "a", "portion", "of", "text", ".", "https", ":", "//", "stackoverflow", ".", "com", "/", "a", "/", "38662876", "/", "450917" ]
python
train
hardbyte/python-can
can/interfaces/socketcan/socketcan.py
https://github.com/hardbyte/python-can/blob/cdc5254d96072df7739263623f3e920628a7d214/can/interfaces/socketcan/socketcan.py#L78-L118
def build_can_frame(msg): """ CAN frame packing/unpacking (see 'struct can_frame' in <linux/can.h>) /** * struct can_frame - basic CAN frame structure * @can_id: the CAN ID of the frame and CAN_*_FLAG flags, see above. * @can_dlc: the data length field of the CAN frame * @data: the CAN f...
[ "def", "build_can_frame", "(", "msg", ")", ":", "can_id", "=", "_add_flags_to_can_id", "(", "msg", ")", "flags", "=", "0", "if", "msg", ".", "bitrate_switch", ":", "flags", "|=", "CANFD_BRS", "if", "msg", ".", "error_state_indicator", ":", "flags", "|=", "...
CAN frame packing/unpacking (see 'struct can_frame' in <linux/can.h>) /** * struct can_frame - basic CAN frame structure * @can_id: the CAN ID of the frame and CAN_*_FLAG flags, see above. * @can_dlc: the data length field of the CAN frame * @data: the CAN frame payload. */ struct c...
[ "CAN", "frame", "packing", "/", "unpacking", "(", "see", "struct", "can_frame", "in", "<linux", "/", "can", ".", "h", ">", ")", "/", "**", "*", "struct", "can_frame", "-", "basic", "CAN", "frame", "structure", "*", "@can_id", ":", "the", "CAN", "ID", ...
python
train
bitlabstudio/django-libs
django_libs/format_utils.py
https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/format_utils.py#L86-L122
def get_format(format_type, lang=None, use_l10n=None): """ For a specific format type, returns the format for the current language (locale), defaults to the format in the settings. format_type is the name of the format, e.g. 'DATE_FORMAT' If use_l10n is provided and is not None, that will force the...
[ "def", "get_format", "(", "format_type", ",", "lang", "=", "None", ",", "use_l10n", "=", "None", ")", ":", "format_type", "=", "str_encode", "(", "format_type", ")", "if", "use_l10n", "or", "(", "use_l10n", "is", "None", "and", "settings", ".", "USE_L10N",...
For a specific format type, returns the format for the current language (locale), defaults to the format in the settings. format_type is the name of the format, e.g. 'DATE_FORMAT' If use_l10n is provided and is not None, that will force the value to be localized (or not), overriding the value of settin...
[ "For", "a", "specific", "format", "type", "returns", "the", "format", "for", "the", "current", "language", "(", "locale", ")", "defaults", "to", "the", "format", "in", "the", "settings", ".", "format_type", "is", "the", "name", "of", "the", "format", "e", ...
python
train
thanethomson/statik
statik/utils.py
https://github.com/thanethomson/statik/blob/56b1b5a2cb05a97afa81f428bfcefc833e935b8d/statik/utils.py#L208-L219
def generate_quickstart(project_path): """Generates all of the basic paths for a Statik project within the given project path. If the project path doesn't exist, it will be created.""" ensure_path_exists(project_path) ensure_file_exists(os.path.join(project_path, "config.yml"), DEFAULT_CONFIG_CONTENT) ...
[ "def", "generate_quickstart", "(", "project_path", ")", ":", "ensure_path_exists", "(", "project_path", ")", "ensure_file_exists", "(", "os", ".", "path", ".", "join", "(", "project_path", ",", "\"config.yml\"", ")", ",", "DEFAULT_CONFIG_CONTENT", ")", "ensure_path_...
Generates all of the basic paths for a Statik project within the given project path. If the project path doesn't exist, it will be created.
[ "Generates", "all", "of", "the", "basic", "paths", "for", "a", "Statik", "project", "within", "the", "given", "project", "path", ".", "If", "the", "project", "path", "doesn", "t", "exist", "it", "will", "be", "created", "." ]
python
train