repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
EpistasisLab/tpot
tpot/base.py
https://github.com/EpistasisLab/tpot/blob/b626271e6b5896a73fb9d7d29bebc7aa9100772e/tpot/base.py#L1208-L1223
def _compile_to_sklearn(self, expr): """Compile a DEAP pipeline into a sklearn pipeline. Parameters ---------- expr: DEAP individual The DEAP pipeline to be compiled Returns ------- sklearn_pipeline: sklearn.pipeline.Pipeline """ skle...
[ "def", "_compile_to_sklearn", "(", "self", ",", "expr", ")", ":", "sklearn_pipeline_str", "=", "generate_pipeline_code", "(", "expr_to_tree", "(", "expr", ",", "self", ".", "_pset", ")", ",", "self", ".", "operators", ")", "sklearn_pipeline", "=", "eval", "(",...
Compile a DEAP pipeline into a sklearn pipeline. Parameters ---------- expr: DEAP individual The DEAP pipeline to be compiled Returns ------- sklearn_pipeline: sklearn.pipeline.Pipeline
[ "Compile", "a", "DEAP", "pipeline", "into", "a", "sklearn", "pipeline", "." ]
python
train
34.4375
acutesoftware/AIKIF
aikif/web_app/web_aikif.py
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/web_app/web_aikif.py#L183-L208
def aikif_web_menu(cur=''): """ returns the web page header containing standard AIKIF top level web menu """ pgeHdg = '' pgeBlurb = '' if cur == '': cur = 'Home' txt = get_header(cur) #"<div id=top_menu>" txt += '<div id = "container">\n' txt += ' <div id = "header">\n' txt +=...
[ "def", "aikif_web_menu", "(", "cur", "=", "''", ")", ":", "pgeHdg", "=", "''", "pgeBlurb", "=", "''", "if", "cur", "==", "''", ":", "cur", "=", "'Home'", "txt", "=", "get_header", "(", "cur", ")", "#\"<div id=top_menu>\"", "txt", "+=", "'<div id = \"cont...
returns the web page header containing standard AIKIF top level web menu
[ "returns", "the", "web", "page", "header", "containing", "standard", "AIKIF", "top", "level", "web", "menu" ]
python
train
37.423077
spyder-ide/spyder
spyder/plugins/editor/widgets/editor.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/editor.py#L93-L112
def close_threads(self, parent): """Close threads associated to parent_id""" logger.debug("Call ThreadManager's 'close_threads'") if parent is None: # Closing all threads self.pending_threads = [] threadlist = [] for threads in list(self.sta...
[ "def", "close_threads", "(", "self", ",", "parent", ")", ":", "logger", ".", "debug", "(", "\"Call ThreadManager's 'close_threads'\"", ")", "if", "parent", "is", "None", ":", "# Closing all threads\r", "self", ".", "pending_threads", "=", "[", "]", "threadlist", ...
Close threads associated to parent_id
[ "Close", "threads", "associated", "to", "parent_id" ]
python
train
46.3
pantsbuild/pants
src/python/pants/engine/legacy/graph.py
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/legacy/graph.py#L455-L477
def transitive_hydrated_targets(build_file_addresses): """Given BuildFileAddresses, kicks off recursion on expansion of TransitiveHydratedTargets. The TransitiveHydratedTarget struct represents a structure-shared graph, which we walk and flatten here. The engine memoizes the computation of TransitiveHydratedTarg...
[ "def", "transitive_hydrated_targets", "(", "build_file_addresses", ")", ":", "transitive_hydrated_targets", "=", "yield", "[", "Get", "(", "TransitiveHydratedTarget", ",", "Address", ",", "a", ")", "for", "a", "in", "build_file_addresses", ".", "addresses", "]", "cl...
Given BuildFileAddresses, kicks off recursion on expansion of TransitiveHydratedTargets. The TransitiveHydratedTarget struct represents a structure-shared graph, which we walk and flatten here. The engine memoizes the computation of TransitiveHydratedTarget, so when multiple TransitiveHydratedTargets objects are...
[ "Given", "BuildFileAddresses", "kicks", "off", "recursion", "on", "expansion", "of", "TransitiveHydratedTargets", "." ]
python
train
40.304348
gunthercox/ChatterBot
chatterbot/trainers.py
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/trainers.py#L213-L221
def is_extracted(self, file_path): """ Check if the data file is already extracted. """ if os.path.isdir(file_path): self.chatbot.logger.info('File is already extracted') return True return False
[ "def", "is_extracted", "(", "self", ",", "file_path", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "file_path", ")", ":", "self", ".", "chatbot", ".", "logger", ".", "info", "(", "'File is already extracted'", ")", "return", "True", "return", "F...
Check if the data file is already extracted.
[ "Check", "if", "the", "data", "file", "is", "already", "extracted", "." ]
python
train
28
tensorflow/tensor2tensor
tensor2tensor/layers/discretization.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L1492-L1528
def iaf_hparams(hidden_size=512, filter_size=4096): """Create hyperpameters for inverse autoregressive flows. Args: hidden_size: Width of attention layers and neural network output layer. filter_size: Hidden layer width for neural network. Returns: hparams: Hyperpameters with basic presets for inver...
[ "def", "iaf_hparams", "(", "hidden_size", "=", "512", ",", "filter_size", "=", "4096", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "# Attention hyperparameters.", "hparams", ".", "hidden_size", "=", "hidden_size", "hparams", ".", ...
Create hyperpameters for inverse autoregressive flows. Args: hidden_size: Width of attention layers and neural network output layer. filter_size: Hidden layer width for neural network. Returns: hparams: Hyperpameters with basic presets for inverse autoregressive flows.
[ "Create", "hyperpameters", "for", "inverse", "autoregressive", "flows", "." ]
python
train
36.189189
tgbugs/pyontutils
ilxutils/ilxutils/ontopandas.py
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/ontopandas.py#L75-L117
def Graph2Pandas_converter(self): '''Updates self.g or self.path bc you could only choose 1''' if isinstance(self.path, str) or isinstance(self.path, p): self.path = str(self.path) filetype = p(self.path).suffix if filetype == '.pickle': self.g = pick...
[ "def", "Graph2Pandas_converter", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "path", ",", "str", ")", "or", "isinstance", "(", "self", ".", "path", ",", "p", ")", ":", "self", ".", "path", "=", "str", "(", "self", ".", "path", ")",...
Updates self.g or self.path bc you could only choose 1
[ "Updates", "self", ".", "g", "or", "self", ".", "path", "bc", "you", "could", "only", "choose", "1" ]
python
train
43.069767
dnanexus/dx-toolkit
src/python/dxpy/utils/describe.py
https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/utils/describe.py#L939-L960
def print_desc(desc, verbose=False): ''' :param desc: The describe hash of a DNAnexus entity :type desc: dict Depending on the class of the entity, this method will print a formatted and human-readable string containing the data in *desc*. ''' if desc['class'] in ['project', 'workspace', 'c...
[ "def", "print_desc", "(", "desc", ",", "verbose", "=", "False", ")", ":", "if", "desc", "[", "'class'", "]", "in", "[", "'project'", ",", "'workspace'", ",", "'container'", "]", ":", "print_project_desc", "(", "desc", ",", "verbose", "=", "verbose", ")",...
:param desc: The describe hash of a DNAnexus entity :type desc: dict Depending on the class of the entity, this method will print a formatted and human-readable string containing the data in *desc*.
[ ":", "param", "desc", ":", "The", "describe", "hash", "of", "a", "DNAnexus", "entity", ":", "type", "desc", ":", "dict" ]
python
train
37.409091
rstoneback/pysat
pysat/instruments/pysat_sgp4.py
https://github.com/rstoneback/pysat/blob/4ae1afd80e15e4449397d39dce8c3e969c32c422/pysat/instruments/pysat_sgp4.py#L768-L843
def add_msis(inst, glat_label='glat', glong_label='glong', alt_label='alt'): """ Uses MSIS model to obtain thermospheric values. Uses pyglow module to run MSIS. Configured to use actual solar parameters to run model. Example ------- # f...
[ "def", "add_msis", "(", "inst", ",", "glat_label", "=", "'glat'", ",", "glong_label", "=", "'glong'", ",", "alt_label", "=", "'alt'", ")", ":", "import", "pyglow", "from", "pyglow", ".", "pyglow", "import", "Point", "msis_params", "=", "[", "]", "# print '...
Uses MSIS model to obtain thermospheric values. Uses pyglow module to run MSIS. Configured to use actual solar parameters to run model. Example ------- # function added velow modifies the inst object upon every inst.load call inst.custom.add(add_msis, 'modify', glat_label='cus...
[ "Uses", "MSIS", "model", "to", "obtain", "thermospheric", "values", ".", "Uses", "pyglow", "module", "to", "run", "MSIS", ".", "Configured", "to", "use", "actual", "solar", "parameters", "to", "run", "model", ".", "Example", "-------", "#", "function", "adde...
python
train
36.263158
tbielawa/bitmath
bitmath/__init__.py
https://github.com/tbielawa/bitmath/blob/58ad3ac5f076cc6e53f36a91af055c6028c850a5/bitmath/__init__.py#L1437-L1559
def parse_string_unsafe(s, system=SI): """Attempt to parse a string with ambiguous units and try to make a bitmath object out of it. This may produce inaccurate results if parsing shell output. For example `ls` may say a 2730 Byte file is '2.7K'. 2730 Bytes == 2.73 kB ~= 2.666 KiB. See the documentation for all of...
[ "def", "parse_string_unsafe", "(", "s", ",", "system", "=", "SI", ")", ":", "if", "not", "isinstance", "(", "s", ",", "(", "str", ",", "unicode", ")", ")", "and", "not", "isinstance", "(", "s", ",", "numbers", ".", "Number", ")", ":", "raise", "Val...
Attempt to parse a string with ambiguous units and try to make a bitmath object out of it. This may produce inaccurate results if parsing shell output. For example `ls` may say a 2730 Byte file is '2.7K'. 2730 Bytes == 2.73 kB ~= 2.666 KiB. See the documentation for all of the important details. Note the following ca...
[ "Attempt", "to", "parse", "a", "string", "with", "ambiguous", "units", "and", "try", "to", "make", "a", "bitmath", "object", "out", "of", "it", "." ]
python
train
34.780488
chrisdev/django-pandas
django_pandas/managers.py
https://github.com/chrisdev/django-pandas/blob/8276d699f25dca7da58e6c3fcebbd46e1c3e35e9/django_pandas/managers.py#L135-L238
def to_timeseries(self, fieldnames=(), verbose=True, index=None, storage='wide', values=None, pivot_columns=None, freq=None, coerce_float=True, rs_kwargs=None): """ A convenience method for creating a time series DataFrame i.e the ...
[ "def", "to_timeseries", "(", "self", ",", "fieldnames", "=", "(", ")", ",", "verbose", "=", "True", ",", "index", "=", "None", ",", "storage", "=", "'wide'", ",", "values", "=", "None", ",", "pivot_columns", "=", "None", ",", "freq", "=", "None", ","...
A convenience method for creating a time series DataFrame i.e the DataFrame index will be an instance of DateTime or PeriodIndex Parameters ---------- fieldnames: The model field names(columns) to utilise in creating the DataFrame. You can span a relationships in...
[ "A", "convenience", "method", "for", "creating", "a", "time", "series", "DataFrame", "i", ".", "e", "the", "DataFrame", "index", "will", "be", "an", "instance", "of", "DateTime", "or", "PeriodIndex" ]
python
train
43.115385
KE-works/pykechain
pykechain/client.py
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L992-L1041
def _create_activity2(self, parent, name, activity_type=ActivityType.TASK): """Create a new activity. .. important:: This function creates activities for KE-chain versions later than 2.9.0-135 In effect where the module 'wim' has version '>=2.0.0'. The version of 'wi...
[ "def", "_create_activity2", "(", "self", ",", "parent", ",", "name", ",", "activity_type", "=", "ActivityType", ".", "TASK", ")", ":", "# WIM1: activity_class, WIM2: activity_type", "if", "self", ".", "match_app_version", "(", "label", "=", "'wim'", ",", "version"...
Create a new activity. .. important:: This function creates activities for KE-chain versions later than 2.9.0-135 In effect where the module 'wim' has version '>=2.0.0'. The version of 'wim' in KE-chain can be found in the property :attr:`Client.app_versions` In WIM...
[ "Create", "a", "new", "activity", "." ]
python
train
46.32
PrefPy/prefpy
prefpy/mechanism.py
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/mechanism.py#L513-L550
def computePairwisePreferences(self, profile): """ Returns a two-dimensional dictionary that associates every pair of candidates, cand1 and cand2, with number of voters who prefer cand1 to cand2. :ivar Profile profile: A Profile object that represents an election profile. """ ...
[ "def", "computePairwisePreferences", "(", "self", ",", "profile", ")", ":", "cands", "=", "profile", ".", "candMap", ".", "keys", "(", ")", "# Initialize the two-dimensional dictionary that will hold our pairwise preferences.", "pairwisePreferences", "=", "dict", "(", ")"...
Returns a two-dimensional dictionary that associates every pair of candidates, cand1 and cand2, with number of voters who prefer cand1 to cand2. :ivar Profile profile: A Profile object that represents an election profile.
[ "Returns", "a", "two", "-", "dimensional", "dictionary", "that", "associates", "every", "pair", "of", "candidates", "cand1", "and", "cand2", "with", "number", "of", "voters", "who", "prefer", "cand1", "to", "cand2", "." ]
python
train
42.394737
log2timeline/dfvfs
dfvfs/vfs/tsk_partition_file_entry.py
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/tsk_partition_file_entry.py#L104-L112
def _GetDirectory(self): """Retrieves a directory. Returns: TSKPartitionDirectory: a directory or None if not available. """ if self.entry_type != definitions.FILE_ENTRY_TYPE_DIRECTORY: return None return TSKPartitionDirectory(self._file_system, self.path_spec)
[ "def", "_GetDirectory", "(", "self", ")", ":", "if", "self", ".", "entry_type", "!=", "definitions", ".", "FILE_ENTRY_TYPE_DIRECTORY", ":", "return", "None", "return", "TSKPartitionDirectory", "(", "self", ".", "_file_system", ",", "self", ".", "path_spec", ")" ...
Retrieves a directory. Returns: TSKPartitionDirectory: a directory or None if not available.
[ "Retrieves", "a", "directory", "." ]
python
train
31.777778
NoviceLive/intellicoder
intellicoder/utils.py
https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/utils.py#L196-L205
def write_file(filename, text): """Write text to a file.""" logging.debug(_('Writing file: %s'), filename) try: with open(filename, 'w') as writable: writable.write(text) except (PermissionError, NotADirectoryError): logging.error(_('Error writing file: %s'), filename) ...
[ "def", "write_file", "(", "filename", ",", "text", ")", ":", "logging", ".", "debug", "(", "_", "(", "'Writing file: %s'", ")", ",", "filename", ")", "try", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "writable", ":", "writable", ".", ...
Write text to a file.
[ "Write", "text", "to", "a", "file", "." ]
python
train
34.1
scott-griffiths/bitstring
bitstring.py
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1748-L1760
def _getuie(self): """Return data as unsigned interleaved exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code. """ try: value, newpos = self._readuie(0) if value is None or newpos != self.len: raise...
[ "def", "_getuie", "(", "self", ")", ":", "try", ":", "value", ",", "newpos", "=", "self", ".", "_readuie", "(", "0", ")", "if", "value", "is", "None", "or", "newpos", "!=", "self", ".", "len", ":", "raise", "ReadError", "except", "ReadError", ":", ...
Return data as unsigned interleaved exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code.
[ "Return", "data", "as", "unsigned", "interleaved", "exponential", "-", "Golomb", "code", "." ]
python
train
35.692308
siemens/django-dingos
dingos/core/datastructures.py
https://github.com/siemens/django-dingos/blob/7154f75b06d2538568e2f2455a76f3d0db0b7d70/dingos/core/datastructures.py#L113-L127
def chained_get(self, *keys): """ This function allows traversals over several keys to be performed by passing a list of keys:: d.chained_get(key1,key2,key3) = d[key1][key2][key3] """ existing = self for i in range(0, len(keys)): if keys[i] in ex...
[ "def", "chained_get", "(", "self", ",", "*", "keys", ")", ":", "existing", "=", "self", "for", "i", "in", "range", "(", "0", ",", "len", "(", "keys", ")", ")", ":", "if", "keys", "[", "i", "]", "in", "existing", ":", "existing", "=", "existing", ...
This function allows traversals over several keys to be performed by passing a list of keys:: d.chained_get(key1,key2,key3) = d[key1][key2][key3]
[ "This", "function", "allows", "traversals", "over", "several", "keys", "to", "be", "performed", "by", "passing", "a", "list", "of", "keys", "::" ]
python
train
28.533333
facebook/watchman
python/pywatchman_aio/__init__.py
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman_aio/__init__.py#L191-L198
def _loads(self, response): """ Parse the BSER packet """ return bser.loads( response, True, value_encoding=encoding.get_local_encoding(), value_errors=encoding.default_local_errors, )
[ "def", "_loads", "(", "self", ",", "response", ")", ":", "return", "bser", ".", "loads", "(", "response", ",", "True", ",", "value_encoding", "=", "encoding", ".", "get_local_encoding", "(", ")", ",", "value_errors", "=", "encoding", ".", "default_local_erro...
Parse the BSER packet
[ "Parse", "the", "BSER", "packet" ]
python
train
31.125
twilio/twilio-python
twilio/rest/api/v2010/account/conference/participant.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/conference/participant.py#L510-L525
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: ParticipantContext for this ParticipantInstance :rtype: twilio.rest.api.v2010.account.conference....
[ "def", "_proxy", "(", "self", ")", ":", "if", "self", ".", "_context", "is", "None", ":", "self", ".", "_context", "=", "ParticipantContext", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]", ",",...
Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: ParticipantContext for this ParticipantInstance :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantContext
[ "Generate", "an", "instance", "context", "for", "the", "instance", "the", "context", "is", "capable", "of", "performing", "various", "actions", ".", "All", "instance", "actions", "are", "proxied", "to", "the", "context" ]
python
train
42.5
CTPUG/wafer
wafer/registration/views.py
https://github.com/CTPUG/wafer/blob/a20af3c399267f76373dc342f4d542a9bc457c35/wafer/registration/views.py#L12-L20
def redirect_profile(request): ''' The default destination from logging in, redirect to the actual profile URL ''' if request.user.is_authenticated: return HttpResponseRedirect(reverse('wafer_user_profile', args=(request.user.username,))) else: ...
[ "def", "redirect_profile", "(", "request", ")", ":", "if", "request", ".", "user", ".", "is_authenticated", ":", "return", "HttpResponseRedirect", "(", "reverse", "(", "'wafer_user_profile'", ",", "args", "=", "(", "request", ".", "user", ".", "username", ",",...
The default destination from logging in, redirect to the actual profile URL
[ "The", "default", "destination", "from", "logging", "in", "redirect", "to", "the", "actual", "profile", "URL" ]
python
train
41.444444
jdoda/sdl2hl
sdl2hl/renderer.py
https://github.com/jdoda/sdl2hl/blob/3b477e1e01cea5d8e15e9e5ef3a302ea460f5946/sdl2hl/renderer.py#L127-L133
def render_target(self): """Texture: The current render target, or None if using the default render target.""" render_target = lib.SDL_GetRenderTarget(self._ptr) if render_target == ffi.NULL: return None else: return Texture._from_ptr(render_target)
[ "def", "render_target", "(", "self", ")", ":", "render_target", "=", "lib", ".", "SDL_GetRenderTarget", "(", "self", ".", "_ptr", ")", "if", "render_target", "==", "ffi", ".", "NULL", ":", "return", "None", "else", ":", "return", "Texture", ".", "_from_ptr...
Texture: The current render target, or None if using the default render target.
[ "Texture", ":", "The", "current", "render", "target", "or", "None", "if", "using", "the", "default", "render", "target", "." ]
python
train
42.714286
dshean/pygeotools
pygeotools/lib/timelib.py
https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/timelib.py#L519-L525
def gps2dt(gps_week, gps_ms): """Convert GPS week and ms to a datetime """ gps_epoch = datetime(1980,1,6,0,0,0) gps_week_s = timedelta(seconds=gps_week*7*24*60*60) gps_ms_s = timedelta(milliseconds=gps_ms) return gps_epoch + gps_week_s + gps_ms_s
[ "def", "gps2dt", "(", "gps_week", ",", "gps_ms", ")", ":", "gps_epoch", "=", "datetime", "(", "1980", ",", "1", ",", "6", ",", "0", ",", "0", ",", "0", ")", "gps_week_s", "=", "timedelta", "(", "seconds", "=", "gps_week", "*", "7", "*", "24", "*"...
Convert GPS week and ms to a datetime
[ "Convert", "GPS", "week", "and", "ms", "to", "a", "datetime" ]
python
train
37.857143
joeferraro/mm
mm/commands/debug.py
https://github.com/joeferraro/mm/blob/43dce48a2249faab4d872c228ada9fbdbeec147b/mm/commands/debug.py#L162-L214
def execute(self): """ params = { "ApexCode" : "None", "ApexProfiling" : "01pd0000001yXtYAAU", "Callout" : True, "Database" : 1, "ExpirationDate" : 3, "ScopeId" ...
[ "def", "execute", "(", "self", ")", ":", "if", "'type'", "not", "in", "self", ".", "params", ":", "raise", "MMException", "(", "\"Please include the type of log, 'user' or 'apex'\"", ")", "if", "'debug_categories'", "not", "in", "self", ".", "params", ":", "rais...
params = { "ApexCode" : "None", "ApexProfiling" : "01pd0000001yXtYAAU", "Callout" : True, "Database" : 1, "ExpirationDate" : 3, "ScopeId" : "", "System" ...
[ "params", "=", "{", "ApexCode", ":", "None", "ApexProfiling", ":", "01pd0000001yXtYAAU", "Callout", ":", "True", "Database", ":", "1", "ExpirationDate", ":", "3", "ScopeId", ":", "System", ":", "TracedEntityId", ":", "Validation", ":", "Visualforce", ":", "Wor...
python
train
40.320755
Microsoft/azure-devops-python-api
azure-devops/azure/devops/v5_0/work_item_tracking/work_item_tracking_client.py
https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_0/work_item_tracking/work_item_tracking_client.py#L223-L245
def delete_classification_node(self, project, structure_group, path=None, reclassify_id=None): """DeleteClassificationNode. Delete an existing classification node. :param str project: Project ID or project name :param TreeStructureGroup structure_group: Structure group of the classificat...
[ "def", "delete_classification_node", "(", "self", ",", "project", ",", "structure_group", ",", "path", "=", "None", ",", "reclassify_id", "=", "None", ")", ":", "route_values", "=", "{", "}", "if", "project", "is", "not", "None", ":", "route_values", "[", ...
DeleteClassificationNode. Delete an existing classification node. :param str project: Project ID or project name :param TreeStructureGroup structure_group: Structure group of the classification node, area or iteration. :param str path: Path of the classification node. :param int ...
[ "DeleteClassificationNode", ".", "Delete", "an", "existing", "classification", "node", ".", ":", "param", "str", "project", ":", "Project", "ID", "or", "project", "name", ":", "param", "TreeStructureGroup", "structure_group", ":", "Structure", "group", "of", "the"...
python
train
57.521739
hyperledger/sawtooth-core
validator/sawtooth_validator/gossip/permission_verifier.py
https://github.com/hyperledger/sawtooth-core/blob/8cf473bc2207e51f02bd182d825158a57d72b098/validator/sawtooth_validator/gossip/permission_verifier.py#L106-L176
def is_transaction_signer_authorized(self, transactions, state_root, from_state): """ Check the transaction signing key against the allowed transactor permissions. The roles being checked are the following, from first to last: "tra...
[ "def", "is_transaction_signer_authorized", "(", "self", ",", "transactions", ",", "state_root", ",", "from_state", ")", ":", "role", "=", "None", "if", "role", "is", "None", ":", "role", "=", "self", ".", "_cache", ".", "get_role", "(", "\"transactor.transacti...
Check the transaction signing key against the allowed transactor permissions. The roles being checked are the following, from first to last: "transactor.transaction_signer.<TP_Name>" "transactor.transaction_signer" "transactor" "def...
[ "Check", "the", "transaction", "signing", "key", "against", "the", "allowed", "transactor", "permissions", ".", "The", "roles", "being", "checked", "are", "the", "following", "from", "first", "to", "last", ":", "transactor", ".", "transaction_signer", ".", "<TP_...
python
train
43.408451
scivision/gridaurora
gridaurora/calcemissions.py
https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/calcemissions.py#L151-L166
def doBandTrapz(Aein, lambnew, fc, kin, lamb, ver, z, br): """ ver dimensions: wavelength, altitude, time A and lambda dimensions: axis 0 is upper state vib. level (nu') axis 1 is bottom state vib level (nu'') there is a Franck-Condon parameter (variable fc) for each upper state nu' """ ...
[ "def", "doBandTrapz", "(", "Aein", ",", "lambnew", ",", "fc", ",", "kin", ",", "lamb", ",", "ver", ",", "z", ",", "br", ")", ":", "tau", "=", "1", "/", "np", ".", "nansum", "(", "Aein", ",", "axis", "=", "1", ")", "scalevec", "=", "(", "Aein"...
ver dimensions: wavelength, altitude, time A and lambda dimensions: axis 0 is upper state vib. level (nu') axis 1 is bottom state vib level (nu'') there is a Franck-Condon parameter (variable fc) for each upper state nu'
[ "ver", "dimensions", ":", "wavelength", "altitude", "time" ]
python
train
32.25
vtkiorg/vtki
vtki/renderer.py
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/renderer.py#L506-L537
def camera_position(self, camera_location): """ Set camera position of all active render windows """ if camera_location is None: return if isinstance(camera_location, str): camera_location = camera_location.lower() if camera_location == 'xy': ...
[ "def", "camera_position", "(", "self", ",", "camera_location", ")", ":", "if", "camera_location", "is", "None", ":", "return", "if", "isinstance", "(", "camera_location", ",", "str", ")", ":", "camera_location", "=", "camera_location", ".", "lower", "(", ")", ...
Set camera position of all active render windows
[ "Set", "camera", "position", "of", "all", "active", "render", "windows" ]
python
train
34.65625
rigetti/pyquil
pyquil/operator_estimation.py
https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/operator_estimation.py#L229-L243
def _abbrev_program(program: Program, max_len=10): """Create an abbreviated string representation of a Program. This will join all instructions onto a single line joined by '; '. If the number of instructions exceeds ``max_len``, some will be excluded from the string representation. """ program_lin...
[ "def", "_abbrev_program", "(", "program", ":", "Program", ",", "max_len", "=", "10", ")", ":", "program_lines", "=", "program", ".", "out", "(", ")", ".", "splitlines", "(", ")", "if", "max_len", "is", "not", "None", "and", "len", "(", "program_lines", ...
Create an abbreviated string representation of a Program. This will join all instructions onto a single line joined by '; '. If the number of instructions exceeds ``max_len``, some will be excluded from the string representation.
[ "Create", "an", "abbreviated", "string", "representation", "of", "a", "Program", "." ]
python
train
46.2
Nic30/hwt
hwt/synthesizer/rtlLevel/netlist.py
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/synthesizer/rtlLevel/netlist.py#L240-L284
def sig(self, name, dtype=BIT, clk=None, syncRst=None, defVal=None): """ Create new signal in this context :param clk: clk signal, if specified signal is synthesized as SyncSignal :param syncRst: synchronous reset signal """ if isinstance(defVal, RtlSignal): ...
[ "def", "sig", "(", "self", ",", "name", ",", "dtype", "=", "BIT", ",", "clk", "=", "None", ",", "syncRst", "=", "None", ",", "defVal", "=", "None", ")", ":", "if", "isinstance", "(", "defVal", ",", "RtlSignal", ")", ":", "assert", "defVal", ".", ...
Create new signal in this context :param clk: clk signal, if specified signal is synthesized as SyncSignal :param syncRst: synchronous reset signal
[ "Create", "new", "signal", "in", "this", "context" ]
python
test
33.866667
Pytwitcher/pytwitcherapi
src/pytwitcherapi/session.py
https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/session.py#L215-L237
def kraken_request(self, method, endpoint, **kwargs): """Make a request to one of the kraken api endpoints. Headers are automatically set to accept :data:`TWITCH_HEADER_ACCEPT`. Also the client id from :data:`CLIENT_ID` will be set. The url will be constructed of :data:`TWITCH_KRAKENURL...
[ "def", "kraken_request", "(", "self", ",", "method", ",", "endpoint", ",", "*", "*", "kwargs", ")", ":", "url", "=", "TWITCH_KRAKENURL", "+", "endpoint", "headers", "=", "kwargs", ".", "setdefault", "(", "'headers'", ",", "{", "}", ")", "headers", "[", ...
Make a request to one of the kraken api endpoints. Headers are automatically set to accept :data:`TWITCH_HEADER_ACCEPT`. Also the client id from :data:`CLIENT_ID` will be set. The url will be constructed of :data:`TWITCH_KRAKENURL` and the given endpoint. :param method: the req...
[ "Make", "a", "request", "to", "one", "of", "the", "kraken", "api", "endpoints", "." ]
python
train
46.434783
obriencj/python-javatools
javatools/jarutil.py
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/jarutil.py#L177-L218
def sign(jar_file, cert_file, key_file, key_alias, extra_certs=None, digest="SHA-256", output=None): """ Signs the jar (almost) identically to jarsigner. :exception ManifestNotFoundError, CannotFindKeyTypeError :return None """ mf = Manifest() mf.load_from_jar(jar_file) mf.add_...
[ "def", "sign", "(", "jar_file", ",", "cert_file", ",", "key_file", ",", "key_alias", ",", "extra_certs", "=", "None", ",", "digest", "=", "\"SHA-256\"", ",", "output", "=", "None", ")", ":", "mf", "=", "Manifest", "(", ")", "mf", ".", "load_from_jar", ...
Signs the jar (almost) identically to jarsigner. :exception ManifestNotFoundError, CannotFindKeyTypeError :return None
[ "Signs", "the", "jar", "(", "almost", ")", "identically", "to", "jarsigner", ".", ":", "exception", "ManifestNotFoundError", "CannotFindKeyTypeError", ":", "return", "None" ]
python
train
40.833333
shichao-an/115wangpan
u115/api.py
https://github.com/shichao-an/115wangpan/blob/e7cc935313f675e886bceca831fcffcdedf1e880/u115/api.py#L830-L840
def _req_files_edit(self, fid, file_name=None, is_mark=0): """Edit a file or directory""" url = self.web_api_url + '/edit' data = locals() del data['self'] req = Request(method='POST', url=url, data=data) res = self.http.send(req) if res.state: return ...
[ "def", "_req_files_edit", "(", "self", ",", "fid", ",", "file_name", "=", "None", ",", "is_mark", "=", "0", ")", ":", "url", "=", "self", ".", "web_api_url", "+", "'/edit'", "data", "=", "locals", "(", ")", "del", "data", "[", "'self'", "]", "req", ...
Edit a file or directory
[ "Edit", "a", "file", "or", "directory" ]
python
train
35.636364
pybel/pybel
src/pybel/struct/filters/node_predicates.py
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/filters/node_predicates.py#L260-L269
def is_isolated_list_abundance(graph: BELGraph, node: BaseEntity, cls: Type[ListAbundance] = ListAbundance) -> bool: """Return if the node is a list abundance but has no qualified edges.""" return ( isinstance(node, cls) and 0 == graph.in_degree(node) and all( data[RELATION] ...
[ "def", "is_isolated_list_abundance", "(", "graph", ":", "BELGraph", ",", "node", ":", "BaseEntity", ",", "cls", ":", "Type", "[", "ListAbundance", "]", "=", "ListAbundance", ")", "->", "bool", ":", "return", "(", "isinstance", "(", "node", ",", "cls", ")",...
Return if the node is a list abundance but has no qualified edges.
[ "Return", "if", "the", "node", "is", "a", "list", "abundance", "but", "has", "no", "qualified", "edges", "." ]
python
train
40.7
deschler/django-modeltranslation
modeltranslation/translator.py
https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/translator.py#L223-L237
def patch_constructor(model): """ Monkey patches the original model to rewrite fields names in __init__ """ old_init = model.__init__ def new_init(self, *args, **kwargs): self._mt_init = True populate_translation_fields(self.__class__, kwargs) for key, val in list(kwargs.ite...
[ "def", "patch_constructor", "(", "model", ")", ":", "old_init", "=", "model", ".", "__init__", "def", "new_init", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_mt_init", "=", "True", "populate_translation_fields", "(", ...
Monkey patches the original model to rewrite fields names in __init__
[ "Monkey", "patches", "the", "original", "model", "to", "rewrite", "fields", "names", "in", "__init__" ]
python
train
37.466667
biolink/ontobio
ontobio/golr/golr_query.py
https://github.com/biolink/ontobio/blob/4e512a7831cfe6bc1b32f2c3be2ba41bc5cf7345/ontobio/golr/golr_query.py#L485-L493
def search(self): """ Execute solr search query """ params = self.solr_params() logging.info("PARAMS=" + str(params)) results = self.solr.search(**params) logging.info("Docs found: {}".format(results.hits)) return self._process_search_results(results)
[ "def", "search", "(", "self", ")", ":", "params", "=", "self", ".", "solr_params", "(", ")", "logging", ".", "info", "(", "\"PARAMS=\"", "+", "str", "(", "params", ")", ")", "results", "=", "self", ".", "solr", ".", "search", "(", "*", "*", "params...
Execute solr search query
[ "Execute", "solr", "search", "query" ]
python
train
34.111111
paulovn/sparql-kernel
sparqlkernel/install.py
https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/install.py#L50-L57
def copyresource( resource, filename, destdir ): """ Copy a resource file to a destination """ data = pkgutil.get_data(resource, os.path.join('resources',filename) ) #log.info( "Installing %s", os.path.join(destdir,filename) ) with open( os.path.join(destdir,filename), 'wb' ) as fp: fp.w...
[ "def", "copyresource", "(", "resource", ",", "filename", ",", "destdir", ")", ":", "data", "=", "pkgutil", ".", "get_data", "(", "resource", ",", "os", ".", "path", ".", "join", "(", "'resources'", ",", "filename", ")", ")", "#log.info( \"Installing %s\", os...
Copy a resource file to a destination
[ "Copy", "a", "resource", "file", "to", "a", "destination" ]
python
train
40.375
perimosocordiae/viztricks
viztricks/convenience.py
https://github.com/perimosocordiae/viztricks/blob/bae2f8a9ce9278ce0197f8efc34cc4fef1dfe1eb/viztricks/convenience.py#L72-L78
def imagesc(data, title=None, fig='current', ax=None): '''Simple alias for a Matlab-like imshow function.''' ax = _get_axis(fig, ax, False) ax.imshow(data, interpolation='nearest', aspect='auto') if title: ax.set_title(title) return plt.show
[ "def", "imagesc", "(", "data", ",", "title", "=", "None", ",", "fig", "=", "'current'", ",", "ax", "=", "None", ")", ":", "ax", "=", "_get_axis", "(", "fig", ",", "ax", ",", "False", ")", "ax", ".", "imshow", "(", "data", ",", "interpolation", "=...
Simple alias for a Matlab-like imshow function.
[ "Simple", "alias", "for", "a", "Matlab", "-", "like", "imshow", "function", "." ]
python
train
35.571429
coldfix/udiskie
udiskie/dbus.py
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/dbus.py#L176-L179
def connect(self, interface, event, handler): """Connect to a DBus signal. Returns subscription id (int).""" object_path = self.object_path return self.bus.connect(interface, event, object_path, handler)
[ "def", "connect", "(", "self", ",", "interface", ",", "event", ",", "handler", ")", ":", "object_path", "=", "self", ".", "object_path", "return", "self", ".", "bus", ".", "connect", "(", "interface", ",", "event", ",", "object_path", ",", "handler", ")"...
Connect to a DBus signal. Returns subscription id (int).
[ "Connect", "to", "a", "DBus", "signal", ".", "Returns", "subscription", "id", "(", "int", ")", "." ]
python
train
56
RaRe-Technologies/smart_open
smart_open/bytebuffer.py
https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/bytebuffer.py#L110-L155
def fill(self, source, size=-1): """Fill the buffer with bytes from source until one of these conditions is met: * size bytes have been read from source (if size >= 0); * chunk_size bytes have been read from source; * no more bytes can be read from source; Ret...
[ "def", "fill", "(", "self", ",", "source", ",", "size", "=", "-", "1", ")", ":", "size", "=", "size", "if", "size", ">=", "0", "else", "self", ".", "_chunk_size", "size", "=", "min", "(", "size", ",", "self", ".", "_chunk_size", ")", "if", "self"...
Fill the buffer with bytes from source until one of these conditions is met: * size bytes have been read from source (if size >= 0); * chunk_size bytes have been read from source; * no more bytes can be read from source; Returns the number of new bytes added to the bu...
[ "Fill", "the", "buffer", "with", "bytes", "from", "source", "until", "one", "of", "these", "conditions", "is", "met", ":", "*", "size", "bytes", "have", "been", "read", "from", "source", "(", "if", "size", ">", "=", "0", ")", ";", "*", "chunk_size", ...
python
train
40.804348
gwastro/pycbc-glue
pycbc_glue/pipeline.py
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L501-L508
def add_input_file(self, filename): """ Add filename as a necessary input file for this DAG node. @param filename: input filename to add """ if filename not in self.__input_files: self.__input_files.append(filename)
[ "def", "add_input_file", "(", "self", ",", "filename", ")", ":", "if", "filename", "not", "in", "self", ".", "__input_files", ":", "self", ".", "__input_files", ".", "append", "(", "filename", ")" ]
Add filename as a necessary input file for this DAG node. @param filename: input filename to add
[ "Add", "filename", "as", "a", "necessary", "input", "file", "for", "this", "DAG", "node", "." ]
python
train
29.375
ArduPilot/MAVProxy
MAVProxy/modules/lib/optparse_gui/__init__.py
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/optparse_gui/__init__.py#L182-L189
def getOptionsAndArgs( self ): '''Returns the tuple ( options, args ) options - a dictionary of option names and values args - a sequence of args''' option_values = self._getOptions() args = self._getArgs() return option_values, args
[ "def", "getOptionsAndArgs", "(", "self", ")", ":", "option_values", "=", "self", ".", "_getOptions", "(", ")", "args", "=", "self", ".", "_getArgs", "(", ")", "return", "option_values", ",", "args" ]
Returns the tuple ( options, args ) options - a dictionary of option names and values args - a sequence of args
[ "Returns", "the", "tuple", "(", "options", "args", ")", "options", "-", "a", "dictionary", "of", "option", "names", "and", "values", "args", "-", "a", "sequence", "of", "args" ]
python
train
34.5
vertica/vertica-python
vertica_python/datatypes.py
https://github.com/vertica/vertica-python/blob/5619c1b2b2eb5ea751c684b28648fc376b5be29c/vertica_python/datatypes.py#L284-L310
def getPrecision(data_type_oid, type_modifier): """ Returns the precision for the given Vertica type with consideration of the type modifier. For numerics, precision is the total number of digits (in base 10) that can fit in the type. For intervals, time and timestamps, precision is the number...
[ "def", "getPrecision", "(", "data_type_oid", ",", "type_modifier", ")", ":", "if", "data_type_oid", "==", "VerticaType", ".", "NUMERIC", ":", "if", "type_modifier", "==", "-", "1", ":", "return", "1024", "return", "(", "(", "type_modifier", "-", "4", ")", ...
Returns the precision for the given Vertica type with consideration of the type modifier. For numerics, precision is the total number of digits (in base 10) that can fit in the type. For intervals, time and timestamps, precision is the number of digits to the right of the decimal point in the seco...
[ "Returns", "the", "precision", "for", "the", "given", "Vertica", "type", "with", "consideration", "of", "the", "type", "modifier", "." ]
python
train
37.074074
astropy/astropy-helpers
astropy_helpers/version_helpers.py
https://github.com/astropy/astropy-helpers/blob/f5a27d3f84a98ea0eebb85e0cf3e7214c6bc0d09/astropy_helpers/version_helpers.py#L352-L367
def get_pkg_version_module(packagename, fromlist=None): """Returns the package's .version module generated by `astropy_helpers.version_helpers.generate_version_py`. Raises an ImportError if the version module is not found. If ``fromlist`` is an iterable, return a tuple of the members of the versio...
[ "def", "get_pkg_version_module", "(", "packagename", ",", "fromlist", "=", "None", ")", ":", "version", "=", "import_file", "(", "os", ".", "path", ".", "join", "(", "packagename", ",", "'version.py'", ")", ",", "name", "=", "'version'", ")", "if", "fromli...
Returns the package's .version module generated by `astropy_helpers.version_helpers.generate_version_py`. Raises an ImportError if the version module is not found. If ``fromlist`` is an iterable, return a tuple of the members of the version module corresponding to the member names given in ``fromlist`...
[ "Returns", "the", "package", "s", ".", "version", "module", "generated", "by", "astropy_helpers", ".", "version_helpers", ".", "generate_version_py", ".", "Raises", "an", "ImportError", "if", "the", "version", "module", "is", "not", "found", "." ]
python
train
41.25
gem/oq-engine
openquake/commonlib/util.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/util.py#L25-L40
def read(calc_id, username=None): """ :param calc_id: a calculation ID :param username: if given, restrict the search to the user's calculations :returns: the associated DataStore instance """ if isinstance(calc_id, str) or calc_id < 0 and not username: # get the last calculation in the ...
[ "def", "read", "(", "calc_id", ",", "username", "=", "None", ")", ":", "if", "isinstance", "(", "calc_id", ",", "str", ")", "or", "calc_id", "<", "0", "and", "not", "username", ":", "# get the last calculation in the datastore of the current user", "return", "da...
:param calc_id: a calculation ID :param username: if given, restrict the search to the user's calculations :returns: the associated DataStore instance
[ ":", "param", "calc_id", ":", "a", "calculation", "ID", ":", "param", "username", ":", "if", "given", "restrict", "the", "search", "to", "the", "user", "s", "calculations", ":", "returns", ":", "the", "associated", "DataStore", "instance" ]
python
train
42.5625
inasafe/inasafe
safe/gui/tools/extent_selector_dialog.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/extent_selector_dialog.py#L219-L224
def clear(self): """Clear the currently set extent.""" self.tool.reset() self._populate_coordinates() # Revert to using hazard, exposure and view as basis for analysis self.hazard_exposure_view_extent.setChecked(True)
[ "def", "clear", "(", "self", ")", ":", "self", ".", "tool", ".", "reset", "(", ")", "self", ".", "_populate_coordinates", "(", ")", "# Revert to using hazard, exposure and view as basis for analysis", "self", ".", "hazard_exposure_view_extent", ".", "setChecked", "(",...
Clear the currently set extent.
[ "Clear", "the", "currently", "set", "extent", "." ]
python
train
42
mitsei/dlkit
dlkit/handcar/repository/managers.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/handcar/repository/managers.py#L2503-L2534
def get_asset_spatial_assignment_session_for_repository(self, repository_id, proxy): """Gets the session for assigning spatial coverage of an asset for the given repository. arg: repository_id (osid.id.Id): the Id of the repository arg proxy (osid.proxy.Proxy): a proxy re...
[ "def", "get_asset_spatial_assignment_session_for_repository", "(", "self", ",", "repository_id", ",", "proxy", ")", ":", "if", "not", "repository_id", ":", "raise", "NullArgument", "(", ")", "if", "not", "self", ".", "supports_asset_spatial_assignment", "(", ")", "o...
Gets the session for assigning spatial coverage of an asset for the given repository. arg: repository_id (osid.id.Id): the Id of the repository arg proxy (osid.proxy.Proxy): a proxy return: (osid.repository.AssetSpatialAssignmentSession) - an AssetSpatialAssignmen...
[ "Gets", "the", "session", "for", "assigning", "spatial", "coverage", "of", "an", "asset", "for", "the", "given", "repository", "." ]
python
train
46.0625
HttpRunner/HttpRunner
httprunner/loader.py
https://github.com/HttpRunner/HttpRunner/blob/f259551bf9c8ba905eae5c1afcf2efea20ae0871/httprunner/loader.py#L34-L40
def load_yaml_file(yaml_file): """ load yaml file and check file content format """ with io.open(yaml_file, 'r', encoding='utf-8') as stream: yaml_content = yaml.load(stream) _check_format(yaml_file, yaml_content) return yaml_content
[ "def", "load_yaml_file", "(", "yaml_file", ")", ":", "with", "io", ".", "open", "(", "yaml_file", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "as", "stream", ":", "yaml_content", "=", "yaml", ".", "load", "(", "stream", ")", "_check_format", "(", ...
load yaml file and check file content format
[ "load", "yaml", "file", "and", "check", "file", "content", "format" ]
python
train
37.571429
tilezen/tilequeue
tilequeue/rawr.py
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/rawr.py#L230-L233
def unconvert_coord_object(tile): """Convert rawr_tiles.tile.Tile -> ModestMaps.Core.Coordinate""" assert isinstance(tile, Tile) return Coordinate(zoom=tile.z, column=tile.x, row=tile.y)
[ "def", "unconvert_coord_object", "(", "tile", ")", ":", "assert", "isinstance", "(", "tile", ",", "Tile", ")", "return", "Coordinate", "(", "zoom", "=", "tile", ".", "z", ",", "column", "=", "tile", ".", "x", ",", "row", "=", "tile", ".", "y", ")" ]
Convert rawr_tiles.tile.Tile -> ModestMaps.Core.Coordinate
[ "Convert", "rawr_tiles", ".", "tile", ".", "Tile", "-", ">", "ModestMaps", ".", "Core", ".", "Coordinate" ]
python
train
48.75
nerdvegas/rez
src/rez/utils/scope.py
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/scope.py#L238-L260
def scoped_format(txt, **objects): """Format a string with respect to a set of objects' attributes. Example: >>> Class Foo(object): >>> def __init__(self): >>> self.name = "Dave" >>> print scoped_format("hello {foo.name}", foo=Foo()) hello Dave Args: ...
[ "def", "scoped_format", "(", "txt", ",", "*", "*", "objects", ")", ":", "pretty", "=", "objects", ".", "pop", "(", "\"pretty\"", ",", "RecursiveAttribute", ".", "format_pretty", ")", "expand", "=", "objects", ".", "pop", "(", "\"expand\"", ",", "RecursiveA...
Format a string with respect to a set of objects' attributes. Example: >>> Class Foo(object): >>> def __init__(self): >>> self.name = "Dave" >>> print scoped_format("hello {foo.name}", foo=Foo()) hello Dave Args: objects (dict): Dict of objects to f...
[ "Format", "a", "string", "with", "respect", "to", "a", "set", "of", "objects", "attributes", "." ]
python
train
38.521739
openego/ding0
ding0/tools/pypsa_io.py
https://github.com/openego/ding0/blob/e2d6528f96255e4bb22ba15514a4f1883564ed5d/ding0/tools/pypsa_io.py#L60-L295
def nodes_to_dict_of_dataframes(grid, nodes, lv_transformer=True): """ Creates dictionary of dataframes containing grid Parameters ---------- grid: ding0.Network nodes: list of ding0 grid components objects Nodes of the grid graph lv_transformer: bool, True Toggle transforme...
[ "def", "nodes_to_dict_of_dataframes", "(", "grid", ",", "nodes", ",", "lv_transformer", "=", "True", ")", ":", "generator_instances", "=", "[", "MVStationDing0", ",", "GeneratorDing0", "]", "# TODO: MVStationDing0 has a slack generator", "cos_phi_load", "=", "cfg_ding0", ...
Creates dictionary of dataframes containing grid Parameters ---------- grid: ding0.Network nodes: list of ding0 grid components objects Nodes of the grid graph lv_transformer: bool, True Toggle transformer representation in power flow analysis Returns: components: dict of p...
[ "Creates", "dictionary", "of", "dataframes", "containing", "grid" ]
python
train
48.423729
angr/angr
angr/simos/linux.py
https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/simos/linux.py#L359-L378
def initialize_gdt_x86(self,state,concrete_target): """ Create a GDT in the state memory and populate the segment registers. Rehook the vsyscall address using the real value in the concrete process memory :param state: state which will be modified :param concrete_t...
[ "def", "initialize_gdt_x86", "(", "self", ",", "state", ",", "concrete_target", ")", ":", "_l", ".", "debug", "(", "\"Creating fake Global Descriptor Table and synchronizing gs segment register\"", ")", "gs", "=", "self", ".", "_read_gs_register_x86", "(", "concrete_targe...
Create a GDT in the state memory and populate the segment registers. Rehook the vsyscall address using the real value in the concrete process memory :param state: state which will be modified :param concrete_target: concrete target that will be used to read the fs register ...
[ "Create", "a", "GDT", "in", "the", "state", "memory", "and", "populate", "the", "segment", "registers", ".", "Rehook", "the", "vsyscall", "address", "using", "the", "real", "value", "in", "the", "concrete", "process", "memory" ]
python
train
50.35
base4sistemas/pyescpos
escpos/conn/network.py
https://github.com/base4sistemas/pyescpos/blob/621bd00f1499aff700f37d8d36d04e0d761708f1/escpos/conn/network.py#L51-L56
def create(cls, setting, **kwargs): """Instantiate a :class:`NetworkConnection` (or subclass) object based on a given host name and port number (eg. ``192.168.0.205:9100``). """ host, port = setting.rsplit(':', 1) return cls(host, int(port), **kwargs)
[ "def", "create", "(", "cls", ",", "setting", ",", "*", "*", "kwargs", ")", ":", "host", ",", "port", "=", "setting", ".", "rsplit", "(", "':'", ",", "1", ")", "return", "cls", "(", "host", ",", "int", "(", "port", ")", ",", "*", "*", "kwargs", ...
Instantiate a :class:`NetworkConnection` (or subclass) object based on a given host name and port number (eg. ``192.168.0.205:9100``).
[ "Instantiate", "a", ":", "class", ":", "NetworkConnection", "(", "or", "subclass", ")", "object", "based", "on", "a", "given", "host", "name", "and", "port", "number", "(", "eg", ".", "192", ".", "168", ".", "0", ".", "205", ":", "9100", ")", "." ]
python
train
47.666667
proofit404/service-factory
service_factory/validation.py
https://github.com/proofit404/service-factory/blob/a09d4e097e5599244564a2a7f0611e58efb4156a/service_factory/validation.py#L43-L52
def validate_id(request): """Validate request id.""" if 'id' in request: correct_id = isinstance( request['id'], (string_types, int, None), ) error = 'Incorrect identifier' assert correct_id, error
[ "def", "validate_id", "(", "request", ")", ":", "if", "'id'", "in", "request", ":", "correct_id", "=", "isinstance", "(", "request", "[", "'id'", "]", ",", "(", "string_types", ",", "int", ",", "None", ")", ",", ")", "error", "=", "'Incorrect identifier'...
Validate request id.
[ "Validate", "request", "id", "." ]
python
test
25.3
saltstack/salt
salt/modules/namecheap_domains_ns.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/namecheap_domains_ns.py#L164-L199
def create(sld, tld, nameserver, ip): ''' Creates a new nameserver. Returns ``True`` if the nameserver was created successfully. sld SLD of the domain name tld TLD of the domain name nameserver Nameserver to create ip Nameserver IP address CLI Example...
[ "def", "create", "(", "sld", ",", "tld", ",", "nameserver", ",", "ip", ")", ":", "opts", "=", "salt", ".", "utils", ".", "namecheap", ".", "get_opts", "(", "'namecheap.domains.ns.create'", ")", "opts", "[", "'SLD'", "]", "=", "sld", "opts", "[", "'TLD'...
Creates a new nameserver. Returns ``True`` if the nameserver was created successfully. sld SLD of the domain name tld TLD of the domain name nameserver Nameserver to create ip Nameserver IP address CLI Example: .. code-block:: bash salt '*' name...
[ "Creates", "a", "new", "nameserver", ".", "Returns", "True", "if", "the", "nameserver", "was", "created", "successfully", "." ]
python
train
23.777778
clinicedc/edc-auth
edc_auth/import_users.py
https://github.com/clinicedc/edc-auth/blob/e633a5461139d3799f389f7bed0e02c9d2c1e103/edc_auth/import_users.py#L27-L91
def import_users( path, resource_name=None, send_email_to_user=None, alternate_email=None, verbose=None, export_to_file=None, **kwargs, ): """Import users from a CSV file with columns: username first_name last_name email sites: a comma-separated li...
[ "def", "import_users", "(", "path", ",", "resource_name", "=", "None", ",", "send_email_to_user", "=", "None", ",", "alternate_email", "=", "None", ",", "verbose", "=", "None", ",", "export_to_file", "=", "None", ",", "*", "*", "kwargs", ",", ")", ":", "...
Import users from a CSV file with columns: username first_name last_name email sites: a comma-separated list of sites groups: a comma-separated list of groups job_title
[ "Import", "users", "from", "a", "CSV", "file", "with", "columns", ":", "username", "first_name", "last_name", "email", "sites", ":", "a", "comma", "-", "separated", "list", "of", "sites", "groups", ":", "a", "comma", "-", "separated", "list", "of", "groups...
python
train
31.169231
Workiva/furious
furious/context/context.py
https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/context/context.py#L368-L416
def _insert_tasks(tasks, queue, transactional=False, retry_transient_errors=True, retry_delay=RETRY_SLEEP_SECS): """Insert a batch of tasks into the specified queue. If an error occurs during insertion, split the batch and retry until they are successfully inserted. Retur...
[ "def", "_insert_tasks", "(", "tasks", ",", "queue", ",", "transactional", "=", "False", ",", "retry_transient_errors", "=", "True", ",", "retry_delay", "=", "RETRY_SLEEP_SECS", ")", ":", "from", "google", ".", "appengine", ".", "api", "import", "taskqueue", "i...
Insert a batch of tasks into the specified queue. If an error occurs during insertion, split the batch and retry until they are successfully inserted. Return the number of successfully inserted tasks.
[ "Insert", "a", "batch", "of", "tasks", "into", "the", "specified", "queue", ".", "If", "an", "error", "occurs", "during", "insertion", "split", "the", "batch", "and", "retry", "until", "they", "are", "successfully", "inserted", ".", "Return", "the", "number"...
python
train
41.244898
jedie/DragonPy
bootstrap/source_after_install.py
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/bootstrap/source_after_install.py#L14-L37
def after_install(options, home_dir): # --- CUT here --- """ called after virtualenv was created and pip/setuptools installed. Now we installed requirement libs/packages. """ if options.install_type==INST_PYPI: requirements=NORMAL_INSTALLATION elif options.install_type==INST_GIT: ...
[ "def", "after_install", "(", "options", ",", "home_dir", ")", ":", "# --- CUT here ---", "if", "options", ".", "install_type", "==", "INST_PYPI", ":", "requirements", "=", "NORMAL_INSTALLATION", "elif", "options", ".", "install_type", "==", "INST_GIT", ":", "requi...
called after virtualenv was created and pip/setuptools installed. Now we installed requirement libs/packages.
[ "called", "after", "virtualenv", "was", "created", "and", "pip", "/", "setuptools", "installed", ".", "Now", "we", "installed", "requirement", "libs", "/", "packages", "." ]
python
train
38.291667
pypa/pipenv
pipenv/patched/notpip/_internal/commands/__init__.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/commands/__init__.py#L45-L54
def get_summaries(ordered=True): """Yields sorted (command name, command summary) tuples.""" if ordered: cmditems = _sort_commands(commands_dict, commands_order) else: cmditems = commands_dict.items() for name, command_class in cmditems: yield (name, command_class.summary)
[ "def", "get_summaries", "(", "ordered", "=", "True", ")", ":", "if", "ordered", ":", "cmditems", "=", "_sort_commands", "(", "commands_dict", ",", "commands_order", ")", "else", ":", "cmditems", "=", "commands_dict", ".", "items", "(", ")", "for", "name", ...
Yields sorted (command name, command summary) tuples.
[ "Yields", "sorted", "(", "command", "name", "command", "summary", ")", "tuples", "." ]
python
train
30.6
pgmpy/pgmpy
pgmpy/factors/FactorSet.py
https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/factors/FactorSet.py#L220-L265
def marginalize(self, variables, inplace=True): """ Marginalizes the factors present in the factor sets with respect to the given variables. Parameters ---------- variables: list, array-like List of the variables to be marginalized. inplace: boolean (Default...
[ "def", "marginalize", "(", "self", ",", "variables", ",", "inplace", "=", "True", ")", ":", "if", "isinstance", "(", "variables", ",", "six", ".", "string_types", ")", ":", "raise", "TypeError", "(", "'Expected list or array-like type got type str'", ")", "facto...
Marginalizes the factors present in the factor sets with respect to the given variables. Parameters ---------- variables: list, array-like List of the variables to be marginalized. inplace: boolean (Default value True) If inplace=True it will modify the factor s...
[ "Marginalizes", "the", "factors", "present", "in", "the", "factor", "sets", "with", "respect", "to", "the", "given", "variables", "." ]
python
train
41.413043
Asana/python-asana
asana/resources/gen/tasks.py
https://github.com/Asana/python-asana/blob/6deb7a34495db23f44858e53b6bb2c9eccff7872/asana/resources/gen/tasks.py#L116-L125
def find_by_section(self, section, params={}, **options): """<b>Board view only:</b> Returns the compact section records for all tasks within the given section. Parameters ---------- section : {Id} The section in which to search for tasks. [params] : {Object} Parameters for the...
[ "def", "find_by_section", "(", "self", ",", "section", ",", "params", "=", "{", "}", ",", "*", "*", "options", ")", ":", "path", "=", "\"/sections/%s/tasks\"", "%", "(", "section", ")", "return", "self", ".", "client", ".", "get_collection", "(", "path",...
<b>Board view only:</b> Returns the compact section records for all tasks within the given section. Parameters ---------- section : {Id} The section in which to search for tasks. [params] : {Object} Parameters for the request
[ "<b", ">", "Board", "view", "only", ":", "<", "/", "b", ">", "Returns", "the", "compact", "section", "records", "for", "all", "tasks", "within", "the", "given", "section", "." ]
python
train
44.6
robotframework/Rammbock
src/Rammbock/rammbock.py
https://github.com/robotframework/Rammbock/blob/c906058d055a6f7c68fe1a6096d78c2e3f642b1c/src/Rammbock/rammbock.py#L92-L96
def u40(self, name, value=None, align=None): """Add an unsigned 5 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.""" self.uint(5, name, value, align)
[ "def", "u40", "(", "self", ",", "name", ",", "value", "=", "None", ",", "align", "=", "None", ")", ":", "self", ".", "uint", "(", "5", ",", "name", ",", "value", ",", "align", ")" ]
Add an unsigned 5 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.
[ "Add", "an", "unsigned", "5", "byte", "integer", "field", "to", "template", "." ]
python
train
48.2
JarryShaw/PyPCAPKit
src/protocols/internet/hip.py
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/hip.py#L683-L719
def _read_para_dh_group_list(self, code, cbit, clen, *, desc, length, version): """Read HIP DH_GROUP_LIST parameter. Structure of HIP DH_GROUP_LIST parameter [RFC 7401]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2...
[ "def", "_read_para_dh_group_list", "(", "self", ",", "code", ",", "cbit", ",", "clen", ",", "*", ",", "desc", ",", "length", ",", "version", ")", ":", "_dhid", "=", "list", "(", ")", "for", "_", "in", "range", "(", "clen", ")", ":", "_dhid", ".", ...
Read HIP DH_GROUP_LIST parameter. Structure of HIP DH_GROUP_LIST parameter [RFC 7401]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-...
[ "Read", "HIP", "DH_GROUP_LIST", "parameter", "." ]
python
train
43.432432
rosenbrockc/acorn
acorn/logging/decoration.py
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L1170-L1272
def decorate_obj(parent, n, o, otype, recurse=True, redecorate=False): """Adds the decoration for automated logging to the specified object, if it hasn't already been done. Args: parent: object that `o` belongs to. n (str): name in the parent's dictionary. o (type): instance of the ...
[ "def", "decorate_obj", "(", "parent", ",", "n", ",", "o", ",", "otype", ",", "recurse", "=", "True", ",", "redecorate", "=", "False", ")", ":", "global", "_decor_count", ",", "_decorated_o", "from", "inspect", "import", "isclass", ",", "isfunction", ",", ...
Adds the decoration for automated logging to the specified object, if it hasn't already been done. Args: parent: object that `o` belongs to. n (str): name in the parent's dictionary. o (type): instance of the object's type. otype (str): one of ['classes', 'functions', 'methods',...
[ "Adds", "the", "decoration", "for", "automated", "logging", "to", "the", "specified", "object", "if", "it", "hasn", "t", "already", "been", "done", "." ]
python
train
41.737864
Azure/blobxfer
blobxfer/models/download.py
https://github.com/Azure/blobxfer/blob/3eccbe7530cc6a20ab2d30f9e034b6f021817f34/blobxfer/models/download.py#L657-L696
def perform_chunked_integrity_check(self): # type: (Descriptor) -> None """Hash data against stored hasher safely :param Descriptor self: this """ hasher = self.hmac or self.md5 # iterate from next chunk to be checked while True: ucc = None ...
[ "def", "perform_chunked_integrity_check", "(", "self", ")", ":", "# type: (Descriptor) -> None", "hasher", "=", "self", ".", "hmac", "or", "self", ".", "md5", "# iterate from next chunk to be checked", "while", "True", ":", "ucc", "=", "None", "with", "self", ".", ...
Hash data against stored hasher safely :param Descriptor self: this
[ "Hash", "data", "against", "stored", "hasher", "safely", ":", "param", "Descriptor", "self", ":", "this" ]
python
train
42.975
steinitzu/giveme
giveme/core.py
https://github.com/steinitzu/giveme/blob/b250995c59eb7e141d2cd8260e292c417785bbd1/giveme/core.py#L45-L63
def get_value(self, name): """ Get return value of a dependency factory or a live singleton instance. """ factory = self._registered.get(name) if not factory: raise KeyError('Name not registered') if factory._giveme_singleton: if name in se...
[ "def", "get_value", "(", "self", ",", "name", ")", ":", "factory", "=", "self", ".", "_registered", ".", "get", "(", "name", ")", "if", "not", "factory", ":", "raise", "KeyError", "(", "'Name not registered'", ")", "if", "factory", ".", "_giveme_singleton"...
Get return value of a dependency factory or a live singleton instance.
[ "Get", "return", "value", "of", "a", "dependency", "factory", "or", "a", "live", "singleton", "instance", "." ]
python
train
38.736842
tensorpack/tensorpack
examples/FasterRCNN/dataset.py
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L112-L170
def _add_detection_gt(self, img, add_mask): """ Add 'boxes', 'class', 'is_crowd' of this image to the dict, used by detection. If add_mask is True, also add 'segmentation' in coco poly format. """ # ann_ids = self.coco.getAnnIds(imgIds=img['image_id']) # objs = self.coco....
[ "def", "_add_detection_gt", "(", "self", ",", "img", ",", "add_mask", ")", ":", "# ann_ids = self.coco.getAnnIds(imgIds=img['image_id'])", "# objs = self.coco.loadAnns(ann_ids)", "objs", "=", "self", ".", "coco", ".", "imgToAnns", "[", "img", "[", "'image_id'", "]", "...
Add 'boxes', 'class', 'is_crowd' of this image to the dict, used by detection. If add_mask is True, also add 'segmentation' in coco poly format.
[ "Add", "boxes", "class", "is_crowd", "of", "this", "image", "to", "the", "dict", "used", "by", "detection", ".", "If", "add_mask", "is", "True", "also", "add", "segmentation", "in", "coco", "poly", "format", "." ]
python
train
47.542373
pyviz/holoviews
holoviews/core/dimension.py
https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/dimension.py#L1345-L1355
def _process_items(cls, vals): "Processes list of items assigning unique paths to each." if type(vals) is cls: return vals.data elif not isinstance(vals, (list, tuple)): vals = [vals] items = [] counts = defaultdict(lambda: 1) cls._unpack_paths(val...
[ "def", "_process_items", "(", "cls", ",", "vals", ")", ":", "if", "type", "(", "vals", ")", "is", "cls", ":", "return", "vals", ".", "data", "elif", "not", "isinstance", "(", "vals", ",", "(", "list", ",", "tuple", ")", ")", ":", "vals", "=", "["...
Processes list of items assigning unique paths to each.
[ "Processes", "list", "of", "items", "assigning", "unique", "paths", "to", "each", "." ]
python
train
35.818182
quantumlib/Cirq
dev_tools/shell_tools.py
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/shell_tools.py#L45-L59
def highlight(text: str, color_code: int, bold: bool=False) -> str: """Wraps the given string with terminal color codes. Args: text: The content to highlight. color_code: The color to highlight with, e.g. 'shelltools.RED'. bold: Whether to bold the content in addition to coloring. ...
[ "def", "highlight", "(", "text", ":", "str", ",", "color_code", ":", "int", ",", "bold", ":", "bool", "=", "False", ")", "->", "str", ":", "return", "'{}\\033[{}m{}\\033[0m'", ".", "format", "(", "'\\033[1m'", "if", "bold", "else", "''", ",", "color_code...
Wraps the given string with terminal color codes. Args: text: The content to highlight. color_code: The color to highlight with, e.g. 'shelltools.RED'. bold: Whether to bold the content in addition to coloring. Returns: The highlighted string.
[ "Wraps", "the", "given", "string", "with", "terminal", "color", "codes", "." ]
python
train
31
pypa/pipenv
pipenv/cli/command.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/cli/command.py#L431-L450
def check( state, unused=False, style=False, ignore=None, args=None, **kwargs ): """Checks for security vulnerabilities and against PEP 508 markers provided in Pipfile.""" from ..core import do_check do_check( three=state.three, python=state.python, system=st...
[ "def", "check", "(", "state", ",", "unused", "=", "False", ",", "style", "=", "False", ",", "ignore", "=", "None", ",", "args", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", ".", ".", "core", "import", "do_check", "do_check", "(", "three"...
Checks for security vulnerabilities and against PEP 508 markers provided in Pipfile.
[ "Checks", "for", "security", "vulnerabilities", "and", "against", "PEP", "508", "markers", "provided", "in", "Pipfile", "." ]
python
train
21.1
DinoTools/python-ssdeep
src/ssdeep/__init__.py
https://github.com/DinoTools/python-ssdeep/blob/c17b3dc0f53514afff59eca67717291ccd206b7c/src/ssdeep/__init__.py#L74-L97
def digest(self, elimseq=False, notrunc=False): """ Obtain the fuzzy hash. This operation does not change the state at all. It reports the hash for the concatenation of the data previously fed using update(). :return: The fuzzy hash :rtype: String :raises Intern...
[ "def", "digest", "(", "self", ",", "elimseq", "=", "False", ",", "notrunc", "=", "False", ")", ":", "if", "self", ".", "_state", "==", "ffi", ".", "NULL", ":", "raise", "InternalError", "(", "\"State object is NULL\"", ")", "flags", "=", "(", "binding", ...
Obtain the fuzzy hash. This operation does not change the state at all. It reports the hash for the concatenation of the data previously fed using update(). :return: The fuzzy hash :rtype: String :raises InternalError: If lib returns an internal error
[ "Obtain", "the", "fuzzy", "hash", "." ]
python
train
35.333333
aleju/imgaug
imgaug/augmenters/arithmetic.py
https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmenters/arithmetic.py#L977-L1059
def Dropout(p=0, per_channel=False, name=None, deterministic=False, random_state=None): """ Augmenter that sets a certain fraction of pixels in images to zero. dtype support:: See ``imgaug.augmenters.arithmetic.MultiplyElementwise``. Parameters ---------- p : float or tuple of float o...
[ "def", "Dropout", "(", "p", "=", "0", ",", "per_channel", "=", "False", ",", "name", "=", "None", ",", "deterministic", "=", "False", ",", "random_state", "=", "None", ")", ":", "if", "ia", ".", "is_single_number", "(", "p", ")", ":", "p2", "=", "i...
Augmenter that sets a certain fraction of pixels in images to zero. dtype support:: See ``imgaug.augmenters.arithmetic.MultiplyElementwise``. Parameters ---------- p : float or tuple of float or imgaug.parameters.StochasticParameter, optional The probability of any pixel being dropped...
[ "Augmenter", "that", "sets", "a", "certain", "fraction", "of", "pixels", "in", "images", "to", "zero", "." ]
python
valid
39.204819
bslatkin/dpxdt
dpxdt/server/auth.py
https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/auth.py#L524-L558
def revoke_admin(): """Form submission handler for revoking admin access to a build.""" build = g.build form = forms.RemoveAdminForm() if form.validate_on_submit(): user = models.User.query.get(form.user_id.data) if not user: logging.debug('User being revoked admin access doe...
[ "def", "revoke_admin", "(", ")", ":", "build", "=", "g", ".", "build", "form", "=", "forms", ".", "RemoveAdminForm", "(", ")", "if", "form", ".", "validate_on_submit", "(", ")", ":", "user", "=", "models", ".", "User", ".", "query", ".", "get", "(", ...
Form submission handler for revoking admin access to a build.
[ "Form", "submission", "handler", "for", "revoking", "admin", "access", "to", "a", "build", "." ]
python
train
36.371429
jesford/cluster-lensing
clusterlensing/utils.py
https://github.com/jesford/cluster-lensing/blob/2815c1bb07d904ca91a80dae3f52090016768072/clusterlensing/utils.py#L58-L75
def check_array_or_list(input): """Return 1D ndarray, if input can be converted and elements are non-negative.""" if type(input) != np.ndarray: if type(input) == list: output = np.array(input) else: raise TypeError('Expecting input type as ndarray or list.') else:...
[ "def", "check_array_or_list", "(", "input", ")", ":", "if", "type", "(", "input", ")", "!=", "np", ".", "ndarray", ":", "if", "type", "(", "input", ")", "==", "list", ":", "output", "=", "np", ".", "array", "(", "input", ")", "else", ":", "raise", ...
Return 1D ndarray, if input can be converted and elements are non-negative.
[ "Return", "1D", "ndarray", "if", "input", "can", "be", "converted", "and", "elements", "are", "non", "-", "negative", "." ]
python
train
29.888889
ff0000/scarlet
scarlet/versioning/models.py
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/versioning/models.py#L111-L131
def _clone_reverses(self, old_reverses): """ Clones all the objects that were previously gathered. """ for ctype, reverses in old_reverses.items(): for parts in reverses.values(): sub_objs = parts[1] field_name = parts[0] attr...
[ "def", "_clone_reverses", "(", "self", ",", "old_reverses", ")", ":", "for", "ctype", ",", "reverses", "in", "old_reverses", ".", "items", "(", ")", ":", "for", "parts", "in", "reverses", ".", "values", "(", ")", ":", "sub_objs", "=", "parts", "[", "1"...
Clones all the objects that were previously gathered.
[ "Clones", "all", "the", "objects", "that", "were", "previously", "gathered", "." ]
python
train
35.333333
cggh/scikit-allel
allel/util.py
https://github.com/cggh/scikit-allel/blob/3c979a57a100240ba959dd13f98839349530f215/allel/util.py#L32-L61
def asarray_ndim(a, *ndims, **kwargs): """Ensure numpy array. Parameters ---------- a : array_like *ndims : int, optional Allowed values for number of dimensions. **kwargs Passed through to :func:`numpy.array`. Returns ------- a : numpy.ndarray """ allow_no...
[ "def", "asarray_ndim", "(", "a", ",", "*", "ndims", ",", "*", "*", "kwargs", ")", ":", "allow_none", "=", "kwargs", ".", "pop", "(", "'allow_none'", ",", "False", ")", "kwargs", ".", "setdefault", "(", "'copy'", ",", "False", ")", "if", "a", "is", ...
Ensure numpy array. Parameters ---------- a : array_like *ndims : int, optional Allowed values for number of dimensions. **kwargs Passed through to :func:`numpy.array`. Returns ------- a : numpy.ndarray
[ "Ensure", "numpy", "array", "." ]
python
train
26.4
fchorney/rpI2C
rpI2C.py
https://github.com/fchorney/rpI2C/blob/7c60f82fa8c91496a74182373da0b95a13919d6e/rpI2C.py#L181-L213
def __connect_to_bus(self, bus): """ Attempt to connect to an I2C bus """ def connect(bus_num): try: self.log.debug("Attempting to connect to bus %s..." % bus_num) self.bus = smbus.SMBus(bus_num) self.log.debug("Success") ...
[ "def", "__connect_to_bus", "(", "self", ",", "bus", ")", ":", "def", "connect", "(", "bus_num", ")", ":", "try", ":", "self", ".", "log", ".", "debug", "(", "\"Attempting to connect to bus %s...\"", "%", "bus_num", ")", "self", ".", "bus", "=", "smbus", ...
Attempt to connect to an I2C bus
[ "Attempt", "to", "connect", "to", "an", "I2C", "bus" ]
python
train
25.939394
ArduPilot/MAVProxy
MAVProxy/modules/lib/wxhorizon_ui.py
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/wxhorizon_ui.py#L162-L172
def checkReszie(self): '''Checks if the window was resized.''' if not self.resized: oldypx = self.ypx oldxpx = self.xpx self.ypx = self.figure.get_size_inches()[1]*self.figure.dpi self.xpx = self.figure.get_size_inches()[0]*self.figure.dpi if (...
[ "def", "checkReszie", "(", "self", ")", ":", "if", "not", "self", ".", "resized", ":", "oldypx", "=", "self", ".", "ypx", "oldxpx", "=", "self", ".", "xpx", "self", ".", "ypx", "=", "self", ".", "figure", ".", "get_size_inches", "(", ")", "[", "1",...
Checks if the window was resized.
[ "Checks", "if", "the", "window", "was", "resized", "." ]
python
train
40.454545
KelSolaar/Umbra
umbra/ui/completers.py
https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/ui/completers.py#L91-L102
def language(self, value): """ Setter for **self.__language** attribute. :param value: Attribute value. :type value: unicode """ if value is not None: assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format( "lan...
[ "def", "language", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", ":", "assert", "type", "(", "value", ")", "is", "unicode", ",", "\"'{0}' attribute: '{1}' type is not 'unicode'!\"", ".", "format", "(", "\"language\"", ",", "value", ...
Setter for **self.__language** attribute. :param value: Attribute value. :type value: unicode
[ "Setter", "for", "**", "self", ".", "__language", "**", "attribute", "." ]
python
train
29.583333
pennlabs/penncoursereview-sdk-python
penncoursereview/penncoursereview.py
https://github.com/pennlabs/penncoursereview-sdk-python/blob/f9f2f1bfcadf0aff50133e35d761f6d1cf85b564/penncoursereview/penncoursereview.py#L14-L18
def fetch_pcr(*args, **kwargs): """Wrapper for fetch to automatically parse results from the PCR API.""" # Load user's token from `PCR_AUTH_TOKEN`, use public token as default if missing kwargs['token'] = os.getenv("PCR_AUTH_TOKEN", "public") return fetch(DOMAIN, *args, **kwargs)['result']
[ "def", "fetch_pcr", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Load user's token from `PCR_AUTH_TOKEN`, use public token as default if missing", "kwargs", "[", "'token'", "]", "=", "os", ".", "getenv", "(", "\"PCR_AUTH_TOKEN\"", ",", "\"public\"", ")", ...
Wrapper for fetch to automatically parse results from the PCR API.
[ "Wrapper", "for", "fetch", "to", "automatically", "parse", "results", "from", "the", "PCR", "API", "." ]
python
train
60.4
ungarj/s2reader
s2reader/cli/transform.py
https://github.com/ungarj/s2reader/blob/376fd7ee1d15cce0849709c149d694663a7bc0ef/s2reader/cli/transform.py#L348-L415
def main(args=sys.argv[1:]): """Generate EO O&M XML metadata.""" parser = argparse.ArgumentParser() parser.add_argument("filename", nargs=1) parser.add_argument("--granule-id", dest="granule_id", help=( "Optional. Specify a granule to export metadata from." ) ) parser...
[ "def", "main", "(", "args", "=", "sys", ".", "argv", "[", "1", ":", "]", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "\"filename\"", ",", "nargs", "=", "1", ")", "parser", ".", "add_argume...
Generate EO O&M XML metadata.
[ "Generate", "EO", "O&M", "XML", "metadata", "." ]
python
train
31.647059
rodynnz/xccdf
src/xccdf/models/rule.py
https://github.com/rodynnz/xccdf/blob/1b9dc2f06b5cce8db2a54c5f95a8f6bcf5cb6981/src/xccdf/models/rule.py#L74-L121
def load_children(self): """ Load the subelements from the xml_element in its correspondent classes. :returns: List of child objects. :rtype: list :raises CardinalityException: If there is more than one Version child. """ # Containers children = list() ...
[ "def", "load_children", "(", "self", ")", ":", "# Containers", "children", "=", "list", "(", ")", "statuses", "=", "list", "(", ")", "version", "=", "None", "titles", "=", "list", "(", ")", "descriptions", "=", "list", "(", ")", "platforms", "=", "list...
Load the subelements from the xml_element in its correspondent classes. :returns: List of child objects. :rtype: list :raises CardinalityException: If there is more than one Version child.
[ "Load", "the", "subelements", "from", "the", "xml_element", "in", "its", "correspondent", "classes", "." ]
python
train
32.145833
datamachine/twx.botapi
twx/botapi/botapi.py
https://github.com/datamachine/twx.botapi/blob/c85184da738169e8f9d6d8e62970540f427c486e/twx/botapi/botapi.py#L4358-L4360
def get_chat_member(self, *args, **kwargs): """See :func:`get_chat_member`""" return get_chat_member(*args, **self._merge_overrides(**kwargs)).run()
[ "def", "get_chat_member", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "get_chat_member", "(", "*", "args", ",", "*", "*", "self", ".", "_merge_overrides", "(", "*", "*", "kwargs", ")", ")", ".", "run", "(", ")" ]
See :func:`get_chat_member`
[ "See", ":", "func", ":", "get_chat_member" ]
python
train
54
ZELLMECHANIK-DRESDEN/dclab
dclab/kde_contours.py
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/kde_contours.py#L12-L67
def find_contours_level(density, x, y, level, closed=False): """Find iso-valued density contours for a given level value Parameters ---------- density: 2d ndarray of shape (M, N) Kernel density estimate for which to compute the contours x: 2d ndarray of shape (M, N) or 1d ndarray of size M ...
[ "def", "find_contours_level", "(", "density", ",", "x", ",", "y", ",", "level", ",", "closed", "=", "False", ")", ":", "if", "level", ">=", "1", "or", "level", "<=", "0", ":", "raise", "ValueError", "(", "\"`level` must be in (0,1), got '{}'!\"", ".", "for...
Find iso-valued density contours for a given level value Parameters ---------- density: 2d ndarray of shape (M, N) Kernel density estimate for which to compute the contours x: 2d ndarray of shape (M, N) or 1d ndarray of size M X-values corresponding to `kde` y: 2d ndarray of shape (...
[ "Find", "iso", "-", "valued", "density", "contours", "for", "a", "given", "level", "value" ]
python
train
30.642857
astropy/photutils
photutils/psf/models.py
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/psf/models.py#L386-L451
def compute_interpolator(self, ikwargs={}): """ Compute/define the interpolating spline. This function can be overriden in a subclass to define custom interpolators. Parameters ---------- ikwargs : dict, optional Additional optional keyword arguments. Possib...
[ "def", "compute_interpolator", "(", "self", ",", "ikwargs", "=", "{", "}", ")", ":", "from", "scipy", ".", "interpolate", "import", "RectBivariateSpline", "if", "'degree'", "in", "ikwargs", ":", "degree", "=", "ikwargs", "[", "'degree'", "]", "if", "hasattr"...
Compute/define the interpolating spline. This function can be overriden in a subclass to define custom interpolators. Parameters ---------- ikwargs : dict, optional Additional optional keyword arguments. Possible values are: - **degree** : int, tuple, optional ...
[ "Compute", "/", "define", "the", "interpolating", "spline", ".", "This", "function", "can", "be", "overriden", "in", "a", "subclass", "to", "define", "custom", "interpolators", "." ]
python
train
37.393939
quantopian/zipline
zipline/pipeline/loaders/earnings_estimates.py
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/earnings_estimates.py#L1407-L1534
def collect_split_adjustments(self, adjustments_for_sid, requested_qtr_data, dates, sid, sid_idx, sid_estimates, ...
[ "def", "collect_split_adjustments", "(", "self", ",", "adjustments_for_sid", ",", "requested_qtr_data", ",", "dates", ",", "sid", ",", "sid_idx", ",", "sid_estimates", ",", "split_adjusted_asof_idx", ",", "pre_adjustments", ",", "post_adjustments", ",", "requested_split...
Collect split adjustments for future quarters. Re-apply adjustments that would be overwritten by overwrites. Merge split adjustments with overwrites into the given dictionary of splits for the given sid. Parameters ---------- adjustments_for_sid : dict[str -> dict[int -> list]] ...
[ "Collect", "split", "adjustments", "for", "future", "quarters", ".", "Re", "-", "apply", "adjustments", "that", "would", "be", "overwritten", "by", "overwrites", ".", "Merge", "split", "adjustments", "with", "overwrites", "into", "the", "given", "dictionary", "o...
python
train
48.398438
econ-ark/HARK
HARK/FashionVictim/FashionVictimModel.py
https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/FashionVictim/FashionVictimModel.py#L384-L409
def calcFashionEvoFunc(pNow): ''' Calculates a new approximate dynamic rule for the evolution of the proportion of punks as a linear function and a "shock width". Parameters ---------- pNow : [float] List describing the history of the proportion of punks in the population. Returns ...
[ "def", "calcFashionEvoFunc", "(", "pNow", ")", ":", "pNowX", "=", "np", ".", "array", "(", "pNow", ")", "T", "=", "pNowX", ".", "size", "p_t", "=", "pNowX", "[", "100", ":", "(", "T", "-", "1", ")", "]", "p_tp1", "=", "pNowX", "[", "101", ":", ...
Calculates a new approximate dynamic rule for the evolution of the proportion of punks as a linear function and a "shock width". Parameters ---------- pNow : [float] List describing the history of the proportion of punks in the population. Returns ------- (unnamed) : FashionEvoFunc...
[ "Calculates", "a", "new", "approximate", "dynamic", "rule", "for", "the", "evolution", "of", "the", "proportion", "of", "punks", "as", "a", "linear", "function", "and", "a", "shock", "width", "." ]
python
train
35.230769
juju/charm-helpers
charmhelpers/cli/__init__.py
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/cli/__init__.py#L148-L165
def run(self): "Run cli, processing arguments and executing subcommands." arguments = self.argument_parser.parse_args() argspec = inspect.getargspec(arguments.func) vargs = [] for arg in argspec.args: vargs.append(getattr(arguments, arg)) if argspec.varargs: ...
[ "def", "run", "(", "self", ")", ":", "arguments", "=", "self", ".", "argument_parser", ".", "parse_args", "(", ")", "argspec", "=", "inspect", ".", "getargspec", "(", "arguments", ".", "func", ")", "vargs", "=", "[", "]", "for", "arg", "in", "argspec",...
Run cli, processing arguments and executing subcommands.
[ "Run", "cli", "processing", "arguments", "and", "executing", "subcommands", "." ]
python
train
43.388889
softlayer/softlayer-python
SoftLayer/CLI/user/detail.py
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/user/detail.py#L138-L143
def print_logins(logins): """Prints out the login history for a user""" table = formatting.Table(['Date', 'IP Address', 'Successufl Login?']) for login in logins: table.add_row([login.get('createDate'), login.get('ipAddress'), login.get('successFlag')]) return table
[ "def", "print_logins", "(", "logins", ")", ":", "table", "=", "formatting", ".", "Table", "(", "[", "'Date'", ",", "'IP Address'", ",", "'Successufl Login?'", "]", ")", "for", "login", "in", "logins", ":", "table", ".", "add_row", "(", "[", "login", ".",...
Prints out the login history for a user
[ "Prints", "out", "the", "login", "history", "for", "a", "user" ]
python
train
47.5
fbcotter/py3nvml
py3nvml/py3nvml.py
https://github.com/fbcotter/py3nvml/blob/47f0f2c0eee56dec4e4beebec26b734e01d357b7/py3nvml/py3nvml.py#L4722-L4758
def nvmlDeviceGetIndex(handle): r""" /** * Retrieves the NVML index of this device. * * For all products. * * Valid indices are derived from the \a accessibleDevices count returned by * \ref nvmlDeviceGetCount(). For example, if \a accessibleDevices is 2 the valid indices * ...
[ "def", "nvmlDeviceGetIndex", "(", "handle", ")", ":", "fn", "=", "_nvmlGetFunctionPointer", "(", "\"nvmlDeviceGetIndex\"", ")", "c_index", "=", "c_uint", "(", ")", "ret", "=", "fn", "(", "handle", ",", "byref", "(", "c_index", ")", ")", "_nvmlCheckReturn", "...
r""" /** * Retrieves the NVML index of this device. * * For all products. * * Valid indices are derived from the \a accessibleDevices count returned by * \ref nvmlDeviceGetCount(). For example, if \a accessibleDevices is 2 the valid indices * are 0 and 1, corresponding to GPU ...
[ "r", "/", "**", "*", "Retrieves", "the", "NVML", "index", "of", "this", "device", ".", "*", "*", "For", "all", "products", ".", "*", "*", "Valid", "indices", "are", "derived", "from", "the", "\\", "a", "accessibleDevices", "count", "returned", "by", "*...
python
train
47.162162
aiogram/aiogram
aiogram/utils/executor.py
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/executor.py#L25-L41
def start_polling(dispatcher, *, loop=None, skip_updates=False, reset_webhook=True, on_startup=None, on_shutdown=None, timeout=20, fast=True): """ Start bot in long-polling mode :param dispatcher: :param loop: :param skip_updates: :param reset_webhook: :param on_startup: ...
[ "def", "start_polling", "(", "dispatcher", ",", "*", ",", "loop", "=", "None", ",", "skip_updates", "=", "False", ",", "reset_webhook", "=", "True", ",", "on_startup", "=", "None", ",", "on_shutdown", "=", "None", ",", "timeout", "=", "20", ",", "fast", ...
Start bot in long-polling mode :param dispatcher: :param loop: :param skip_updates: :param reset_webhook: :param on_startup: :param on_shutdown: :param timeout:
[ "Start", "bot", "in", "long", "-", "polling", "mode" ]
python
train
33.470588
apache/spark
python/pyspark/rdd.py
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1974-L1986
def mapValues(self, f): """ Pass each value in the key-value pair RDD through a map function without changing the keys; this also retains the original RDD's partitioning. >>> x = sc.parallelize([("a", ["apple", "banana", "lemon"]), ("b", ["grapes"])]) >>> def f(x): retur...
[ "def", "mapValues", "(", "self", ",", "f", ")", ":", "map_values_fn", "=", "lambda", "kv", ":", "(", "kv", "[", "0", "]", ",", "f", "(", "kv", "[", "1", "]", ")", ")", "return", "self", ".", "map", "(", "map_values_fn", ",", "preservesPartitioning"...
Pass each value in the key-value pair RDD through a map function without changing the keys; this also retains the original RDD's partitioning. >>> x = sc.parallelize([("a", ["apple", "banana", "lemon"]), ("b", ["grapes"])]) >>> def f(x): return len(x) >>> x.mapValues(f).collect(...
[ "Pass", "each", "value", "in", "the", "key", "-", "value", "pair", "RDD", "through", "a", "map", "function", "without", "changing", "the", "keys", ";", "this", "also", "retains", "the", "original", "RDD", "s", "partitioning", "." ]
python
train
39.538462
inasafe/inasafe
safe/impact_function/impact_function.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/impact_function.py#L2310-L2400
def intersect_exposure_and_aggregate_hazard(self): """This function intersects the exposure with the aggregate hazard. If the the exposure is a continuous raster exposure, this function will set the aggregate hazard layer. However, this function will set the impact layer. ""...
[ "def", "intersect_exposure_and_aggregate_hazard", "(", "self", ")", ":", "LOGGER", ".", "info", "(", "'ANALYSIS : Intersect Exposure and Aggregate Hazard'", ")", "if", "is_raster_layer", "(", "self", ".", "exposure", ")", ":", "self", ".", "set_state_process", "(", "'...
This function intersects the exposure with the aggregate hazard. If the the exposure is a continuous raster exposure, this function will set the aggregate hazard layer. However, this function will set the impact layer.
[ "This", "function", "intersects", "the", "exposure", "with", "the", "aggregate", "hazard", "." ]
python
train
46.208791
jason-weirather/py-seq-tools
seqtools/range/__init__.py
https://github.com/jason-weirather/py-seq-tools/blob/f642c2c73ffef2acc83656a78059a476fc734ca1/seqtools/range/__init__.py#L366-L379
def distance(self,rng): """The distance between two ranges. :param rng: another range :type rng: GenomicRange :returns: bases separting, 0 if overlapped or adjacent, -1 if on different chromsomes :rtype: int """ if self.chr != rng.chr: return -1 c = self.cmp(rng) if c == 0: return 0...
[ "def", "distance", "(", "self", ",", "rng", ")", ":", "if", "self", ".", "chr", "!=", "rng", ".", "chr", ":", "return", "-", "1", "c", "=", "self", ".", "cmp", "(", "rng", ")", "if", "c", "==", "0", ":", "return", "0", "if", "c", "<", "0", ...
The distance between two ranges. :param rng: another range :type rng: GenomicRange :returns: bases separting, 0 if overlapped or adjacent, -1 if on different chromsomes :rtype: int
[ "The", "distance", "between", "two", "ranges", "." ]
python
train
27.928571
MaxHalford/starboost
starboost/boosting.py
https://github.com/MaxHalford/starboost/blob/59d96dcc983404cbc326878facd8171fd2655ce1/starboost/boosting.py#L343-L367
def iter_predict_proba(self, X, include_init=False): """Returns the predicted probabilities for ``X`` at every stage of the boosting procedure. Arguments: X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples. Sparse matrices are accepted only i...
[ "def", "iter_predict_proba", "(", "self", ",", "X", ",", "include_init", "=", "False", ")", ":", "utils", ".", "validation", ".", "check_is_fitted", "(", "self", ",", "'init_estimator_'", ")", "X", "=", "utils", ".", "check_array", "(", "X", ",", "accept_s...
Returns the predicted probabilities for ``X`` at every stage of the boosting procedure. Arguments: X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples. Sparse matrices are accepted only if they are supported by the weak model. include_init...
[ "Returns", "the", "predicted", "probabilities", "for", "X", "at", "every", "stage", "of", "the", "boosting", "procedure", "." ]
python
train
47.44
tensorflow/tensor2tensor
tensor2tensor/utils/diet.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/diet.py#L34-L51
def diet_adam_optimizer_params(): """Default hyperparameters for a DietAdamOptimizer. Returns: a hyperparameters object. """ return hparam.HParams( quantize=True, # use 16-bit fixed-point quantization_scale=10.0 / tf.int16.max, optimizer="DietAdam", learning_rate=1.0, learnin...
[ "def", "diet_adam_optimizer_params", "(", ")", ":", "return", "hparam", ".", "HParams", "(", "quantize", "=", "True", ",", "# use 16-bit fixed-point", "quantization_scale", "=", "10.0", "/", "tf", ".", "int16", ".", "max", ",", "optimizer", "=", "\"DietAdam\"", ...
Default hyperparameters for a DietAdamOptimizer. Returns: a hyperparameters object.
[ "Default", "hyperparameters", "for", "a", "DietAdamOptimizer", "." ]
python
train
30.555556
unt-libraries/pyuntl
pyuntl/untldoc.py
https://github.com/unt-libraries/pyuntl/blob/f92413302897dab948aac18ee9e482ace0187bd4/pyuntl/untldoc.py#L826-L835
def etd_ms_dict2xmlfile(filename, metadata_dict): """Create an ETD MS XML file.""" try: f = open(filename, 'w') f.write(generate_etd_ms_xml(metadata_dict).encode("utf-8")) f.close() except: raise MetadataGeneratorException( 'Failed to create an XML file. Filename:...
[ "def", "etd_ms_dict2xmlfile", "(", "filename", ",", "metadata_dict", ")", ":", "try", ":", "f", "=", "open", "(", "filename", ",", "'w'", ")", "f", ".", "write", "(", "generate_etd_ms_xml", "(", "metadata_dict", ")", ".", "encode", "(", "\"utf-8\"", ")", ...
Create an ETD MS XML file.
[ "Create", "an", "ETD", "MS", "XML", "file", "." ]
python
train
33.8
unt-libraries/pyuntl
pyuntl/dc_structure.py
https://github.com/unt-libraries/pyuntl/blob/f92413302897dab948aac18ee9e482ace0187bd4/pyuntl/dc_structure.py#L247-L270
def identifier_director(**kwargs): """Direct how to handle the identifier element.""" ark = kwargs.get('ark', None) domain_name = kwargs.get('domain_name', None) # Set default scheme if it is None or is not supplied. scheme = kwargs.get('scheme') or 'http' qualifier = kwargs.get('qualifier', Non...
[ "def", "identifier_director", "(", "*", "*", "kwargs", ")", ":", "ark", "=", "kwargs", ".", "get", "(", "'ark'", ",", "None", ")", "domain_name", "=", "kwargs", ".", "get", "(", "'domain_name'", ",", "None", ")", "# Set default scheme if it is None or is not s...
Direct how to handle the identifier element.
[ "Direct", "how", "to", "handle", "the", "identifier", "element", "." ]
python
train
40.958333
monarch-initiative/dipper
dipper/sources/FlyBase.py
https://github.com/monarch-initiative/dipper/blob/24cc80db355bbe15776edc5c7b41e0886959ba41/dipper/sources/FlyBase.py#L1424-L1509
def _process_feature_dbxref(self, limit): """ This is the mapping between the flybase features and external repositories. Generally we want to leave the flybase feature id as the primary identifier. But we need to make the equivalences/sameAs. :param limit: :return: ...
[ "def", "_process_feature_dbxref", "(", "self", ",", "limit", ")", ":", "if", "self", ".", "test_mode", ":", "graph", "=", "self", ".", "testgraph", "else", ":", "graph", "=", "self", ".", "graph", "model", "=", "Model", "(", "graph", ")", "line_counter",...
This is the mapping between the flybase features and external repositories. Generally we want to leave the flybase feature id as the primary identifier. But we need to make the equivalences/sameAs. :param limit: :return:
[ "This", "is", "the", "mapping", "between", "the", "flybase", "features", "and", "external", "repositories", ".", "Generally", "we", "want", "to", "leave", "the", "flybase", "feature", "id", "as", "the", "primary", "identifier", ".", "But", "we", "need", "to"...
python
train
41.511628
jlmadurga/yowsup-celery
yowsup_celery/layer.py
https://github.com/jlmadurga/yowsup-celery/blob/f694950e5746ec9a6bf7d88ff5a68c71652a50ae/yowsup_celery/layer.py#L193-L205
def send_location(self, number, name, url, latitude, longitude): """ Send location message :param str number: phone number with cc (country code) :param str name: indentifier for the location :param str url: location url :param str longitude: location longitude :p...
[ "def", "send_location", "(", "self", ",", "number", ",", "name", ",", "url", ",", "latitude", ",", "longitude", ")", ":", "location_message", "=", "LocationMediaMessageProtocolEntity", "(", "latitude", ",", "longitude", ",", "name", ",", "url", ",", "encoding"...
Send location message :param str number: phone number with cc (country code) :param str name: indentifier for the location :param str url: location url :param str longitude: location longitude :param str latitude: location latitude
[ "Send", "location", "message", ":", "param", "str", "number", ":", "phone", "number", "with", "cc", "(", "country", "code", ")", ":", "param", "str", "name", ":", "indentifier", "for", "the", "location", ":", "param", "str", "url", ":", "location", "url"...
python
train
48.615385
openstack/hacking
hacking/checks/localization.py
https://github.com/openstack/hacking/blob/10e58f907181cac91d3b2af422c2458b04a1ec79/hacking/checks/localization.py#L33-L95
def check_i18n(): """Generator that checks token stream for localization errors. Expects tokens to be ``send``ed one by one. Raises LocalizationError if some error is found. """ while True: try: token_type, text, _, _, line = yield except GeneratorExit: retur...
[ "def", "check_i18n", "(", ")", ":", "while", "True", ":", "try", ":", "token_type", ",", "text", ",", "_", ",", "_", ",", "line", "=", "yield", "except", "GeneratorExit", ":", "return", "if", "text", "==", "\"def\"", "and", "token_type", "==", "tokeniz...
Generator that checks token stream for localization errors. Expects tokens to be ``send``ed one by one. Raises LocalizationError if some error is found.
[ "Generator", "that", "checks", "token", "stream", "for", "localization", "errors", "." ]
python
train
38.460317