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
senaite/senaite.core
bika/lims/browser/dashboard/dashboard.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/dashboard/dashboard.py#L230-L241
def is_filter_selected(self, selection_id, value): """ Compares whether the 'selection_id' parameter value saved in the cookie is the same value as the "value" parameter. :param selection_id: a string as a dashboard_cookie key. :param value: The value to compare against the valu...
[ "def", "is_filter_selected", "(", "self", ",", "selection_id", ",", "value", ")", ":", "selected", "=", "self", ".", "dashboard_cookie", ".", "get", "(", "selection_id", ")", "return", "selected", "==", "value" ]
Compares whether the 'selection_id' parameter value saved in the cookie is the same value as the "value" parameter. :param selection_id: a string as a dashboard_cookie key. :param value: The value to compare against the value from dashboard_cookie key. :return: Boolean.
[ "Compares", "whether", "the", "selection_id", "parameter", "value", "saved", "in", "the", "cookie", "is", "the", "same", "value", "as", "the", "value", "parameter", "." ]
python
train
39.583333
buckket/twtxt
twtxt/cache.py
https://github.com/buckket/twtxt/blob/6c8ad8ef3cbcf0dd335a12285d8b6bbdf93ce851/twtxt/cache.py#L94-L101
def add_tweets(self, url, last_modified, tweets): """Adds new tweets to the cache.""" try: self.cache[url] = {"last_modified": last_modified, "tweets": tweets} self.mark_updated() return True except TypeError: return False
[ "def", "add_tweets", "(", "self", ",", "url", ",", "last_modified", ",", "tweets", ")", ":", "try", ":", "self", ".", "cache", "[", "url", "]", "=", "{", "\"last_modified\"", ":", "last_modified", ",", "\"tweets\"", ":", "tweets", "}", "self", ".", "ma...
Adds new tweets to the cache.
[ "Adds", "new", "tweets", "to", "the", "cache", "." ]
python
valid
35.875
ruipgil/TrackToTrip
tracktotrip/segment.py
https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L134-L152
def simplify(self, eps, max_dist_error, max_speed_error, topology_only=False): """ In-place segment simplification See `drp` and `compression` modules Args: eps (float): Distance threshold for the `drp` function max_dist_error (float): Max distance error, in meters ...
[ "def", "simplify", "(", "self", ",", "eps", ",", "max_dist_error", ",", "max_speed_error", ",", "topology_only", "=", "False", ")", ":", "if", "topology_only", ":", "self", ".", "points", "=", "drp", "(", "self", ".", "points", ",", "eps", ")", "else", ...
In-place segment simplification See `drp` and `compression` modules Args: eps (float): Distance threshold for the `drp` function max_dist_error (float): Max distance error, in meters max_speed_error (float): Max speed error, in km/h topology_only (bool, ...
[ "In", "-", "place", "segment", "simplification" ]
python
train
39.263158
ArchiveTeam/wpull
wpull/application/tasks/download.py
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/download.py#L51-L95
def _build_document_scrapers(cls, session: AppSession): '''Create the document scrapers. Returns: A list of document scrapers ''' html_parser = session.factory['HTMLParser'] element_walker = session.factory.new('ElementWalker') scrapers = [ sessi...
[ "def", "_build_document_scrapers", "(", "cls", ",", "session", ":", "AppSession", ")", ":", "html_parser", "=", "session", ".", "factory", "[", "'HTMLParser'", "]", "element_walker", "=", "session", ".", "factory", ".", "new", "(", "'ElementWalker'", ")", "scr...
Create the document scrapers. Returns: A list of document scrapers
[ "Create", "the", "document", "scrapers", "." ]
python
train
34.6
marcomusy/vtkplotter
vtkplotter/colors.py
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/colors.py#L265-L279
def getColorName(c): """Find the name of a color. .. hint:: |colorpalette| |colorpalette.py|_ """ c = np.array(getColor(c)) # reformat to rgb mdist = 99.0 kclosest = "" for key in colors.keys(): ci = np.array(getColor(key)) d = np.linalg.norm(c - ci) if d < mdist: ...
[ "def", "getColorName", "(", "c", ")", ":", "c", "=", "np", ".", "array", "(", "getColor", "(", "c", ")", ")", "# reformat to rgb", "mdist", "=", "99.0", "kclosest", "=", "\"\"", "for", "key", "in", "colors", ".", "keys", "(", ")", ":", "ci", "=", ...
Find the name of a color. .. hint:: |colorpalette| |colorpalette.py|_
[ "Find", "the", "name", "of", "a", "color", "." ]
python
train
25.2
lwcook/horsetail-matching
horsetailmatching/surrogates.py
https://github.com/lwcook/horsetail-matching/blob/f3d5f8d01249debbca978f412ce4eae017458119/horsetailmatching/surrogates.py#L100-L138
def train(self, ftrain): '''Trains the polynomial expansion. :param numpy.ndarray/function ftrain: output values corresponding to the quadrature points given by the getQuadraturePoints method to which the expansion should be trained. Or a function that should be evaluated ...
[ "def", "train", "(", "self", ",", "ftrain", ")", ":", "self", ".", "coeffs", "=", "0", "*", "self", ".", "coeffs", "upoints", ",", "wpoints", "=", "self", ".", "getQuadraturePointsAndWeights", "(", ")", "try", ":", "fpoints", "=", "[", "ftrain", "(", ...
Trains the polynomial expansion. :param numpy.ndarray/function ftrain: output values corresponding to the quadrature points given by the getQuadraturePoints method to which the expansion should be trained. Or a function that should be evaluated at the quadrature points to gi...
[ "Trains", "the", "polynomial", "expansion", "." ]
python
train
32.820513
chrissimpkins/crypto
lib/crypto/library/cryptor.py
https://github.com/chrissimpkins/crypto/blob/6b95fa81b26312e46f02557dca0b5f5c898a76fd/lib/crypto/library/cryptor.py#L36-L81
def encrypt_file(self, inpath, force_nocompress=False, force_compress=False, armored=False, checksum=False): """public method for single file encryption with optional compression, ASCII armored formatting, and file hash digest generation""" if armored: if force_compress: comm...
[ "def", "encrypt_file", "(", "self", ",", "inpath", ",", "force_nocompress", "=", "False", ",", "force_compress", "=", "False", ",", "armored", "=", "False", ",", "checksum", "=", "False", ")", ":", "if", "armored", ":", "if", "force_compress", ":", "comman...
public method for single file encryption with optional compression, ASCII armored formatting, and file hash digest generation
[ "public", "method", "for", "single", "file", "encryption", "with", "optional", "compression", "ASCII", "armored", "formatting", "and", "file", "hash", "digest", "generation" ]
python
train
50.826087
AkihikoITOH/capybara
capybara/virtualenv/lib/python2.7/site-packages/wheel/tool/__init__.py
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/wheel/tool/__init__.py#L226-L242
def install_scripts(distributions): """ Regenerate the entry_points console_scripts for the named distribution. """ try: from setuptools.command import easy_install import pkg_resources except ImportError: raise RuntimeError("'wheel install_scripts' needs setuptools.") f...
[ "def", "install_scripts", "(", "distributions", ")", ":", "try", ":", "from", "setuptools", ".", "command", "import", "easy_install", "import", "pkg_resources", "except", "ImportError", ":", "raise", "RuntimeError", "(", "\"'wheel install_scripts' needs setuptools.\"", ...
Regenerate the entry_points console_scripts for the named distribution.
[ "Regenerate", "the", "entry_points", "console_scripts", "for", "the", "named", "distribution", "." ]
python
test
38.705882
apache/incubator-heron
heron/tools/cli/src/python/config.py
https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/cli/src/python/config.py#L126-L140
def run(command, parser, cl_args, unknown_args): ''' :param command: :param parser: :param args: :param unknown_args: :return: ''' configcommand = cl_args.get('configcommand', None) if configcommand == 'set': return _set(cl_args) elif configcommand == 'unset': return _unset(cl_args) else: ...
[ "def", "run", "(", "command", ",", "parser", ",", "cl_args", ",", "unknown_args", ")", ":", "configcommand", "=", "cl_args", ".", "get", "(", "'configcommand'", ",", "None", ")", "if", "configcommand", "==", "'set'", ":", "return", "_set", "(", "cl_args", ...
:param command: :param parser: :param args: :param unknown_args: :return:
[ ":", "param", "command", ":", ":", "param", "parser", ":", ":", "param", "args", ":", ":", "param", "unknown_args", ":", ":", "return", ":" ]
python
valid
22.066667
eng-tools/sfsimodels
sfsimodels/loader.py
https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/loader.py#L98-L111
def load_building_sample_data(bd): """ Sample data for the Building object :param bd: :return: """ number_of_storeys = 6 interstorey_height = 3.4 # m masses = 40.0e3 # kg bd.interstorey_heights = interstorey_height * np.ones(number_of_storeys) bd.floor_length = 18.0 # m b...
[ "def", "load_building_sample_data", "(", "bd", ")", ":", "number_of_storeys", "=", "6", "interstorey_height", "=", "3.4", "# m", "masses", "=", "40.0e3", "# kg", "bd", ".", "interstorey_heights", "=", "interstorey_height", "*", "np", ".", "ones", "(", "number_of...
Sample data for the Building object :param bd: :return:
[ "Sample", "data", "for", "the", "Building", "object", ":", "param", "bd", ":", ":", "return", ":" ]
python
train
27.928571
singularityhub/sregistry-cli
sregistry/main/base/__init__.py
https://github.com/singularityhub/sregistry-cli/blob/abc96140a1d15b5e96d83432e1e0e1f4f8f36331/sregistry/main/base/__init__.py#L85-L97
def speak(self): ''' a function for the client to announce him or herself, depending on the level specified. If you want your client to have additional announced things here, then implement the class `_speak` for your client. ''' if self.quiet is Fals...
[ "def", "speak", "(", "self", ")", ":", "if", "self", ".", "quiet", "is", "False", ":", "bot", ".", "info", "(", "'[client|%s] [database|%s]'", "%", "(", "self", ".", "client_name", ",", "self", ".", "database", ")", ")", "self", ".", "_speak", "(", "...
a function for the client to announce him or herself, depending on the level specified. If you want your client to have additional announced things here, then implement the class `_speak` for your client.
[ "a", "function", "for", "the", "client", "to", "announce", "him", "or", "herself", "depending", "on", "the", "level", "specified", ".", "If", "you", "want", "your", "client", "to", "have", "additional", "announced", "things", "here", "then", "implement", "th...
python
test
36.384615
etcher-be/emiz
emiz/edit_miz.py
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/edit_miz.py#L19-L80
def edit_miz( # noqa: C901 infile: str, outfile: str = None, metar: typing.Union[str, Metar] = None, time: str = None, min_wind: int = 0, max_wind: int = 40 ) -> str: # noinspection SpellCheckingInspection """ Edit an opened MIZ file and sets the time and dat...
[ "def", "edit_miz", "(", "# noqa: C901", "infile", ":", "str", ",", "outfile", ":", "str", "=", "None", ",", "metar", ":", "typing", ".", "Union", "[", "str", ",", "Metar", "]", "=", "None", ",", "time", ":", "str", "=", "None", ",", "min_wind", ":"...
Edit an opened MIZ file and sets the time and date and the weather Args: infile: source file outfile: output file (will default to source file) metar: metar string, ICAO or object to apply time: time string to apply (YYYYMMDDHHMMSS) min_wind: minimum wind max_wind: m...
[ "Edit", "an", "opened", "MIZ", "file", "and", "sets", "the", "time", "and", "date", "and", "the", "weather" ]
python
train
30.790323
twisted/mantissa
xmantissa/product.py
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/product.py#L29-L40
def installProductOn(self, userstore): """ Creates an Installation in this user store for our collection of powerups, and then install those powerups on the user's store. """ def install(): i = Installation(store=userstore) i.types = self.types ...
[ "def", "installProductOn", "(", "self", ",", "userstore", ")", ":", "def", "install", "(", ")", ":", "i", "=", "Installation", "(", "store", "=", "userstore", ")", "i", ".", "types", "=", "self", ".", "types", "i", ".", "install", "(", ")", "userstor...
Creates an Installation in this user store for our collection of powerups, and then install those powerups on the user's store.
[ "Creates", "an", "Installation", "in", "this", "user", "store", "for", "our", "collection", "of", "powerups", "and", "then", "install", "those", "powerups", "on", "the", "user", "s", "store", "." ]
python
train
30.5
ga4gh/ga4gh-server
ga4gh/server/backend.py
https://github.com/ga4gh/ga4gh-server/blob/1aa18922ef136db8604f6f098cb1732cba6f2a76/ga4gh/server/backend.py#L787-L795
def runGetReference(self, id_): """ Runs a getReference request for the specified ID. """ compoundId = datamodel.ReferenceCompoundId.parse(id_) referenceSet = self.getDataRepository().getReferenceSet( compoundId.reference_set_id) reference = referenceSet.getRe...
[ "def", "runGetReference", "(", "self", ",", "id_", ")", ":", "compoundId", "=", "datamodel", ".", "ReferenceCompoundId", ".", "parse", "(", "id_", ")", "referenceSet", "=", "self", ".", "getDataRepository", "(", ")", ".", "getReferenceSet", "(", "compoundId", ...
Runs a getReference request for the specified ID.
[ "Runs", "a", "getReference", "request", "for", "the", "specified", "ID", "." ]
python
train
41
plandes/actioncli
src/python/zensols/actioncli/config.py
https://github.com/plandes/actioncli/blob/d1c4ea27e6f3394b30a1652ddd4b916160662773/src/python/zensols/actioncli/config.py#L208-L214
def get_option_list(self, name, section=None, vars=None, expect=None, separator=','): """Just like ``get_option`` but parse as a list using ``split``. """ val = self.get_option(name, section, vars, expect) return val.split(separator) if val else []
[ "def", "get_option_list", "(", "self", ",", "name", ",", "section", "=", "None", ",", "vars", "=", "None", ",", "expect", "=", "None", ",", "separator", "=", "','", ")", ":", "val", "=", "self", ".", "get_option", "(", "name", ",", "section", ",", ...
Just like ``get_option`` but parse as a list using ``split``.
[ "Just", "like", "get_option", "but", "parse", "as", "a", "list", "using", "split", "." ]
python
train
42.714286
astraw/stdeb
stdeb/util.py
https://github.com/astraw/stdeb/blob/493ab88e8a60be053b1baef81fb39b45e17ceef5/stdeb/util.py#L475-L496
def expand_zip(zip_fname,cwd=None): "expand a zip" unzip_path = '/usr/bin/unzip' if not os.path.exists(unzip_path): log.error('ERROR: {} does not exist'.format(unzip_path)) sys.exit(1) args = [unzip_path, zip_fname] # Does it have a top dir res = subprocess.Popen( [args[0...
[ "def", "expand_zip", "(", "zip_fname", ",", "cwd", "=", "None", ")", ":", "unzip_path", "=", "'/usr/bin/unzip'", "if", "not", "os", ".", "path", ".", "exists", "(", "unzip_path", ")", ":", "log", ".", "error", "(", "'ERROR: {} does not exist'", ".", "forma...
expand a zip
[ "expand", "a", "zip" ]
python
train
33.409091
bitesofcode/projexui
projexui/widgets/xtabwidget.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtabwidget.py#L206-L213
def setShowOptionsButton(self, state): """ Sets whether or not the option button is visible. :param state | <bool> """ self._showOptionsButton = state self._optionsButton.setVisible(state)
[ "def", "setShowOptionsButton", "(", "self", ",", "state", ")", ":", "self", ".", "_showOptionsButton", "=", "state", "self", ".", "_optionsButton", ".", "setVisible", "(", "state", ")" ]
Sets whether or not the option button is visible. :param state | <bool>
[ "Sets", "whether", "or", "not", "the", "option", "button", "is", "visible", ".", ":", "param", "state", "|", "<bool", ">" ]
python
train
31.25
majuss/lupupy
lupupy/__main__.py
https://github.com/majuss/lupupy/blob/71af6c397837ffc393c7b8122be175602638d3c6/lupupy/__main__.py#L102-L160
def call(): """Execute command line helper.""" args = get_arguments() if args.debug: log_level = logging.DEBUG elif args.quiet: log_level = logging.WARN else: log_level = logging.INFO setup_logging(log_level) lupusec = None if not args.username or not args.pas...
[ "def", "call", "(", ")", ":", "args", "=", "get_arguments", "(", ")", "if", "args", ".", "debug", ":", "log_level", "=", "logging", ".", "DEBUG", "elif", "args", ".", "quiet", ":", "log_level", "=", "logging", ".", "WARN", "else", ":", "log_level", "...
Execute command line helper.
[ "Execute", "command", "line", "helper", "." ]
python
train
32.084746
solvebio/solvebio-python
solvebio/query.py
https://github.com/solvebio/solvebio-python/blob/b29614643043afd19c1d8074e8f25c6700d51a73/solvebio/query.py#L389-L415
def facets(self, *args, **kwargs): """ Returns a dictionary with the requested facets. The facets function supports string args, and keyword args. q.facets('field_1', 'field_2') will return facets for field_1 and field_2. q.facets(field_1={'limit': 0}, field_2={...
[ "def", "facets", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Combine args and kwargs into facet format.", "facets", "=", "dict", "(", "(", "a", ",", "{", "}", ")", "for", "a", "in", "args", ")", "facets", ".", "update", "(", ...
Returns a dictionary with the requested facets. The facets function supports string args, and keyword args. q.facets('field_1', 'field_2') will return facets for field_1 and field_2. q.facets(field_1={'limit': 0}, field_2={'limit': 10}) will return all facets for field_...
[ "Returns", "a", "dictionary", "with", "the", "requested", "facets", "." ]
python
test
33.666667
rwl/pylon
pyreto/discrete/task.py
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pyreto/discrete/task.py#L156-L166
def addReward(self, r=None): """ A filtered mapping towards performAction of the underlying environment. """ r = self.getReward() if r is None else r # by default, the cumulative reward is just the sum over the episode if self.discount: self.cumulativeRew...
[ "def", "addReward", "(", "self", ",", "r", "=", "None", ")", ":", "r", "=", "self", ".", "getReward", "(", ")", "if", "r", "is", "None", "else", "r", "# by default, the cumulative reward is just the sum over the episode", "if", "self", ".", "discount", ":", ...
A filtered mapping towards performAction of the underlying environment.
[ "A", "filtered", "mapping", "towards", "performAction", "of", "the", "underlying", "environment", "." ]
python
train
37.090909
google/google-visualization-python
gviz_api.py
https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L378-L525
def TableDescriptionParser(table_description, depth=0): """Parses the table_description object for internal use. Parses the user-submitted table description into an internal format used by the Python DataTable class. Returns the flat list of parsed columns. Args: table_description: A description...
[ "def", "TableDescriptionParser", "(", "table_description", ",", "depth", "=", "0", ")", ":", "# For the recursion step, we check for a scalar object (string or tuple)", "if", "isinstance", "(", "table_description", ",", "(", "six", ".", "string_types", ",", "tuple", ")", ...
Parses the table_description object for internal use. Parses the user-submitted table description into an internal format used by the Python DataTable class. Returns the flat list of parsed columns. Args: table_description: A description of the table which should comply with...
[ "Parses", "the", "table_description", "object", "for", "internal", "use", "." ]
python
train
50.22973
fprimex/zdesk
zdesk/zdesk_api.py
https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L247-L251
def apps_installations_job_status_show(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/apps#get-requirements-install-status" api_path = "/api/v2/apps/installations/job_statuses/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
[ "def", "apps_installations_job_status_show", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/apps/installations/job_statuses/{id}.json\"", "api_path", "=", "api_path", ".", "format", "(", "id", "=", "id", ")", "return", "self...
https://developer.zendesk.com/rest_api/docs/core/apps#get-requirements-install-status
[ "https", ":", "//", "developer", ".", "zendesk", ".", "com", "/", "rest_api", "/", "docs", "/", "core", "/", "apps#get", "-", "requirements", "-", "install", "-", "status" ]
python
train
61.8
blockstack/blockstack-core
blockstack/lib/nameset/virtualchain_hooks.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/virtualchain_hooks.py#L162-L177
def get_or_instantiate_db_state(working_dir): """ Get a read-only handle to the DB. Instantiate it first if it doesn't exist. DO NOT CALL WHILE INDEXING Returns the handle on success Raises on error """ # instantiates new_db = BlockstackDB.borrow_readwrite_instance(working_dir, -1...
[ "def", "get_or_instantiate_db_state", "(", "working_dir", ")", ":", "# instantiates", "new_db", "=", "BlockstackDB", ".", "borrow_readwrite_instance", "(", "working_dir", ",", "-", "1", ")", "BlockstackDB", ".", "release_readwrite_instance", "(", "new_db", ",", "-", ...
Get a read-only handle to the DB. Instantiate it first if it doesn't exist. DO NOT CALL WHILE INDEXING Returns the handle on success Raises on error
[ "Get", "a", "read", "-", "only", "handle", "to", "the", "DB", ".", "Instantiate", "it", "first", "if", "it", "doesn", "t", "exist", "." ]
python
train
25
abw333/dominoes
dominoes/game.py
https://github.com/abw333/dominoes/blob/ea9f532c9b834117a5c07d214711515872f7537e/dominoes/game.py#L16-L28
def _validate_player(player): ''' Checks that a player is a valid player. Valid players are: 0, 1, 2, and 3. :param int player: player to be validated :return: None :raises NoSuchPlayerException: if the player is invalid ''' valid_players = range(4) if player not in valid_players: ...
[ "def", "_validate_player", "(", "player", ")", ":", "valid_players", "=", "range", "(", "4", ")", "if", "player", "not", "in", "valid_players", ":", "valid_players", "=", "', '", ".", "join", "(", "str", "(", "p", ")", "for", "p", "in", "valid_players", ...
Checks that a player is a valid player. Valid players are: 0, 1, 2, and 3. :param int player: player to be validated :return: None :raises NoSuchPlayerException: if the player is invalid
[ "Checks", "that", "a", "player", "is", "a", "valid", "player", ".", "Valid", "players", "are", ":", "0", "1", "2", "and", "3", "." ]
python
train
41.615385
suds-community/suds
suds/xsd/depsort.py
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/xsd/depsort.py#L27-L57
def dependency_sort(dependency_tree): """ Sorts items 'dependencies first' in a given dependency tree. A dependency tree is a dictionary mapping an object to a collection its dependency objects. Result is a properly sorted list of items, where each item is a 2-tuple containing an object and it...
[ "def", "dependency_sort", "(", "dependency_tree", ")", ":", "sorted", "=", "[", "]", "processed", "=", "set", "(", ")", "for", "key", ",", "deps", "in", "dependency_tree", ".", "iteritems", "(", ")", ":", "_sort_r", "(", "sorted", ",", "processed", ",", ...
Sorts items 'dependencies first' in a given dependency tree. A dependency tree is a dictionary mapping an object to a collection its dependency objects. Result is a properly sorted list of items, where each item is a 2-tuple containing an object and its dependency list, as given in the input depen...
[ "Sorts", "items", "dependencies", "first", "in", "a", "given", "dependency", "tree", "." ]
python
train
35.516129
tonyfischetti/sake
sakelib/build.py
https://github.com/tonyfischetti/sake/blob/b7ad20fe8e7137db99a20ac06b8da26492601b00/sakelib/build.py#L68-L84
def check_shastore_version(from_store, settings): """ This function gives us the option to emit errors or warnings after sake upgrades """ sprint = settings["sprint"] error = settings["error"] sprint("checking .shastore version for potential incompatibilities", level="verbose") ...
[ "def", "check_shastore_version", "(", "from_store", ",", "settings", ")", ":", "sprint", "=", "settings", "[", "\"sprint\"", "]", "error", "=", "settings", "[", "\"error\"", "]", "sprint", "(", "\"checking .shastore version for potential incompatibilities\"", ",", "le...
This function gives us the option to emit errors or warnings after sake upgrades
[ "This", "function", "gives", "us", "the", "option", "to", "emit", "errors", "or", "warnings", "after", "sake", "upgrades" ]
python
valid
39.588235
tjcsl/cslbot
cslbot/commands/isup.py
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/isup.py#L24-L40
def cmd(send, msg, args): """Checks if a website is up. Syntax: {command} <website> """ if not msg: send("What are you trying to get to?") return nick = args['nick'] isup = get("http://isup.me/%s" % msg).text if "looks down from here" in isup: send("%s: %s is down" ...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "not", "msg", ":", "send", "(", "\"What are you trying to get to?\"", ")", "return", "nick", "=", "args", "[", "'nick'", "]", "isup", "=", "get", "(", "\"http://isup.me/%s\"", "%", "msg"...
Checks if a website is up. Syntax: {command} <website>
[ "Checks", "if", "a", "website", "is", "up", "." ]
python
train
27.941176
librosa/librosa
librosa/display.py
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/display.py#L746-L777
def __mesh_coords(ax_type, coords, n, **kwargs): '''Compute axis coordinates''' if coords is not None: if len(coords) < n: raise ParameterError('Coordinate shape mismatch: ' '{}<{}'.format(len(coords), n)) return coords coord_map = {'linear': __...
[ "def", "__mesh_coords", "(", "ax_type", ",", "coords", ",", "n", ",", "*", "*", "kwargs", ")", ":", "if", "coords", "is", "not", "None", ":", "if", "len", "(", "coords", ")", "<", "n", ":", "raise", "ParameterError", "(", "'Coordinate shape mismatch: '",...
Compute axis coordinates
[ "Compute", "axis", "coordinates" ]
python
test
36.15625
gwastro/pycbc
pycbc/rate.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/rate.py#L196-L215
def compute_efficiency(f_dist, m_dist, dbins): ''' Compute the efficiency as a function of distance for the given sets of found and missed injection distances. Note that injections that do not fit into any dbin get lost :( ''' efficiency = numpy.zeros(len(dbins) - 1) error = numpy.zeros(len(...
[ "def", "compute_efficiency", "(", "f_dist", ",", "m_dist", ",", "dbins", ")", ":", "efficiency", "=", "numpy", ".", "zeros", "(", "len", "(", "dbins", ")", "-", "1", ")", "error", "=", "numpy", ".", "zeros", "(", "len", "(", "dbins", ")", "-", "1",...
Compute the efficiency as a function of distance for the given sets of found and missed injection distances. Note that injections that do not fit into any dbin get lost :(
[ "Compute", "the", "efficiency", "as", "a", "function", "of", "distance", "for", "the", "given", "sets", "of", "found", "and", "missed", "injection", "distances", ".", "Note", "that", "injections", "that", "do", "not", "fit", "into", "any", "dbin", "get", "...
python
train
40.6
RedHatQE/python-stitches
stitches/connection.py
https://github.com/RedHatQE/python-stitches/blob/957e9895e64ffd3b8157b38b9cce414969509288/stitches/connection.py#L274-L306
def recv_exit_status(self, command, timeout=10, get_pty=False): """ Execute a command and get its return value @param command: command to execute @type command: str @param timeout: command execution timeout @type timeout: int @param get_pty: get pty @ty...
[ "def", "recv_exit_status", "(", "self", ",", "command", ",", "timeout", "=", "10", ",", "get_pty", "=", "False", ")", ":", "status", "=", "None", "self", ".", "last_command", "=", "command", "stdin", ",", "stdout", ",", "stderr", "=", "self", ".", "cli...
Execute a command and get its return value @param command: command to execute @type command: str @param timeout: command execution timeout @type timeout: int @param get_pty: get pty @type get_pty: bool @return: the exit code of the process or None in case of t...
[ "Execute", "a", "command", "and", "get", "its", "return", "value" ]
python
train
30.333333
ambitioninc/django-query-builder
querybuilder/fields.py
https://github.com/ambitioninc/django-query-builder/blob/113a7d845d3ddc6a45621b9880308e756f87c5bf/querybuilder/fields.py#L123-L144
def get_alias(self): """ Gets the alias for the field or the auto_alias if one is set. If there isn't any kind of alias, None is returned. :return: The field alias, auto_alias, or None :rtype: str or None """ alias = None if self.alias: alias ...
[ "def", "get_alias", "(", "self", ")", ":", "alias", "=", "None", "if", "self", ".", "alias", ":", "alias", "=", "self", ".", "alias", "elif", "self", ".", "auto_alias", ":", "alias", "=", "self", ".", "auto_alias", "if", "self", ".", "table", "and", ...
Gets the alias for the field or the auto_alias if one is set. If there isn't any kind of alias, None is returned. :return: The field alias, auto_alias, or None :rtype: str or None
[ "Gets", "the", "alias", "for", "the", "field", "or", "the", "auto_alias", "if", "one", "is", "set", ".", "If", "there", "isn", "t", "any", "kind", "of", "alias", "None", "is", "returned", "." ]
python
train
30.863636
NoviceLive/intellicoder
intellicoder/utils.py
https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/utils.py#L233-L235
def sort_item(iterable, number, reverse=False): """Sort the itertable according to the given number item.""" return sorted(iterable, key=itemgetter(number), reverse=reverse)
[ "def", "sort_item", "(", "iterable", ",", "number", ",", "reverse", "=", "False", ")", ":", "return", "sorted", "(", "iterable", ",", "key", "=", "itemgetter", "(", "number", ")", ",", "reverse", "=", "reverse", ")" ]
Sort the itertable according to the given number item.
[ "Sort", "the", "itertable", "according", "to", "the", "given", "number", "item", "." ]
python
train
59.666667
UCL-INGI/INGInious
inginious/frontend/template_helper.py
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/template_helper.py#L76-L96
def get_custom_renderer(self, dir_path, layout=True): """ Create a template renderer on templates in the directory specified, and returns it. :param dir_path: the path to the template dir. If it is not absolute, it will be taken from the root of the inginious package. :param layout: can ...
[ "def", "get_custom_renderer", "(", "self", ",", "dir_path", ",", "layout", "=", "True", ")", ":", "# if dir_path/base is a absolute path, os.path.join(something, an_absolute_path) returns an_absolute_path.", "root_path", "=", "inginious", ".", "get_root_path", "(", ")", "if",...
Create a template renderer on templates in the directory specified, and returns it. :param dir_path: the path to the template dir. If it is not absolute, it will be taken from the root of the inginious package. :param layout: can either be True (use the base layout of the running app), False (use no lay...
[ "Create", "a", "template", "renderer", "on", "templates", "in", "the", "directory", "specified", "and", "returns", "it", ".", ":", "param", "dir_path", ":", "the", "path", "to", "the", "template", "dir", ".", "If", "it", "is", "not", "absolute", "it", "w...
python
train
52.952381
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/util.py
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/util.py#L273-L290
def try_serialize_handler(handler): """Try to serialize map/reduce handler. Args: handler: handler function/instance. Handler can be a function or an instance of a callable class. In the latter case, the handler will be serialized across slices to allow users to save states. Returns: seriali...
[ "def", "try_serialize_handler", "(", "handler", ")", ":", "if", "(", "isinstance", "(", "handler", ",", "types", ".", "InstanceType", ")", "or", "# old style class", "(", "isinstance", "(", "handler", ",", "object", ")", "and", "# new style class", "not", "ins...
Try to serialize map/reduce handler. Args: handler: handler function/instance. Handler can be a function or an instance of a callable class. In the latter case, the handler will be serialized across slices to allow users to save states. Returns: serialized handler string or None.
[ "Try", "to", "serialize", "map", "/", "reduce", "handler", "." ]
python
train
35.055556
ronhanson/python-tbx
tbx/code.py
https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/code.py#L19-L42
def static_singleton(*args, **kwargs): """ STATIC Singleton Design Pattern Decorator Class is initialized with arguments passed into the decorator. :Usage: >>> @static_singleton('yop') class Bob(Person): def __init__(arg1): self.info = arg1 def says...
[ "def", "static_singleton", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "__static_singleton_wrapper", "(", "cls", ")", ":", "if", "cls", "not", "in", "__singleton_instances", ":", "__singleton_instances", "[", "cls", "]", "=", "cls", "(", "*...
STATIC Singleton Design Pattern Decorator Class is initialized with arguments passed into the decorator. :Usage: >>> @static_singleton('yop') class Bob(Person): def __init__(arg1): self.info = arg1 def says(self): print self.info b1 ...
[ "STATIC", "Singleton", "Design", "Pattern", "Decorator", "Class", "is", "initialized", "with", "arguments", "passed", "into", "the", "decorator", "." ]
python
train
33.25
yinkaisheng/Python-UIAutomation-for-Windows
uiautomation/uiautomation.py
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L4662-L4670
def GetActiveComposition(self) -> TextRange: """ Call IUIAutomationTextEditPattern::GetActiveComposition. Return `TextRange` or None, the active composition. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtexteditpattern-g...
[ "def", "GetActiveComposition", "(", "self", ")", "->", "TextRange", ":", "textRange", "=", "self", ".", "pattern", ".", "GetActiveComposition", "(", ")", "if", "textRange", ":", "return", "TextRange", "(", "textRange", "=", "textRange", ")" ]
Call IUIAutomationTextEditPattern::GetActiveComposition. Return `TextRange` or None, the active composition. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtexteditpattern-getactivecomposition
[ "Call", "IUIAutomationTextEditPattern", "::", "GetActiveComposition", ".", "Return", "TextRange", "or", "None", "the", "active", "composition", ".", "Refer", "https", ":", "//", "docs", ".", "microsoft", ".", "com", "/", "en", "-", "us", "/", "windows", "/", ...
python
valid
52.333333
numberoverzero/bloop
bloop/conditions.py
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/conditions.py#L914-L935
def iter_conditions(condition): """Yield all conditions within the given condition. If the root condition is and/or/not, it is not yielded (unless a cyclic reference to it is found).""" conditions = list() visited = set() # Has to be split out, since we don't want to visit the root (for cyclic cond...
[ "def", "iter_conditions", "(", "condition", ")", ":", "conditions", "=", "list", "(", ")", "visited", "=", "set", "(", ")", "# Has to be split out, since we don't want to visit the root (for cyclic conditions)", "# but we don't want to yield it (if it's non-cyclic) because this onl...
Yield all conditions within the given condition. If the root condition is and/or/not, it is not yielded (unless a cyclic reference to it is found).
[ "Yield", "all", "conditions", "within", "the", "given", "condition", "." ]
python
train
41.772727
allenai/allennlp
allennlp/training/tensorboard_writer.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/tensorboard_writer.py#L84-L112
def log_parameter_and_gradient_statistics(self, # pylint: disable=invalid-name model: Model, batch_grad_norm: float) -> None: """ Send the mean and std of all parameters and gradients to tensorboard, as well ...
[ "def", "log_parameter_and_gradient_statistics", "(", "self", ",", "# pylint: disable=invalid-name", "model", ":", "Model", ",", "batch_grad_norm", ":", "float", ")", "->", "None", ":", "if", "self", ".", "_should_log_parameter_statistics", ":", "# Log parameter values to ...
Send the mean and std of all parameters and gradients to tensorboard, as well as logging the average gradient norm.
[ "Send", "the", "mean", "and", "std", "of", "all", "parameters", "and", "gradients", "to", "tensorboard", "as", "well", "as", "logging", "the", "average", "gradient", "norm", "." ]
python
train
56.068966
DataDog/integrations-core
couch/datadog_checks/couch/couch.py
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/couch/datadog_checks/couch/couch.py#L30-L68
def get(self, url, instance, service_check_tags, run_check=False): "Hit a given URL and return the parsed json" self.log.debug('Fetching CouchDB stats at url: %s' % url) auth = None if 'user' in instance and 'password' in instance: auth = (instance['user'], instance['passwor...
[ "def", "get", "(", "self", ",", "url", ",", "instance", ",", "service_check_tags", ",", "run_check", "=", "False", ")", ":", "self", ".", "log", ".", "debug", "(", "'Fetching CouchDB stats at url: %s'", "%", "url", ")", "auth", "=", "None", "if", "'user'",...
Hit a given URL and return the parsed json
[ "Hit", "a", "given", "URL", "and", "return", "the", "parsed", "json" ]
python
train
41.923077
fprimex/zdesk
zdesk/zdesk_api.py
https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L2957-L2961
def role_show(self, role_id, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/roles#get-role" api_path = "/api/v2/roles/{role_id}" api_path = api_path.format(role_id=role_id) return self.call(api_path, **kwargs)
[ "def", "role_show", "(", "self", ",", "role_id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/roles/{role_id}\"", "api_path", "=", "api_path", ".", "format", "(", "role_id", "=", "role_id", ")", "return", "self", ".", "call", "(", "api_pa...
https://developer.zendesk.com/rest_api/docs/chat/roles#get-role
[ "https", ":", "//", "developer", ".", "zendesk", ".", "com", "/", "rest_api", "/", "docs", "/", "chat", "/", "roles#get", "-", "role" ]
python
train
50.2
jtwhite79/pyemu
pyemu/utils/geostats.py
https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/utils/geostats.py#L1075-L1088
def rotation_coefs(self): """ get the rotation coefficents in radians Returns ------- rotation_coefs : list the rotation coefficients implied by Vario2d.bearing """ return [np.cos(self.bearing_rads), np.sin(self.bearing_rads), ...
[ "def", "rotation_coefs", "(", "self", ")", ":", "return", "[", "np", ".", "cos", "(", "self", ".", "bearing_rads", ")", ",", "np", ".", "sin", "(", "self", ".", "bearing_rads", ")", ",", "-", "1.0", "*", "np", ".", "sin", "(", "self", ".", "beari...
get the rotation coefficents in radians Returns ------- rotation_coefs : list the rotation coefficients implied by Vario2d.bearing
[ "get", "the", "rotation", "coefficents", "in", "radians" ]
python
train
27.357143
inveniosoftware-attic/invenio-knowledge
invenio_knowledge/utils.py
https://github.com/inveniosoftware-attic/invenio-knowledge/blob/b31722dc14243ca8f626f8b3bce9718d0119de55/invenio_knowledge/utils.py#L27-L42
def load_kb_mappings_file(kbname, kbfile, separator): """Add KB values from file to given KB returning rows added.""" num_added = 0 with open(kbfile) as kb_fd: for line in kb_fd: if not line.strip(): continue try: key, value = line.split(separa...
[ "def", "load_kb_mappings_file", "(", "kbname", ",", "kbfile", ",", "separator", ")", ":", "num_added", "=", "0", "with", "open", "(", "kbfile", ")", "as", "kb_fd", ":", "for", "line", "in", "kb_fd", ":", "if", "not", "line", ".", "strip", "(", ")", "...
Add KB values from file to given KB returning rows added.
[ "Add", "KB", "values", "from", "file", "to", "given", "KB", "returning", "rows", "added", "." ]
python
train
35.75
google/apitools
apitools/gen/service_registry.py
https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/gen/service_registry.py#L166-L179
def __WriteProtoServiceDeclaration(self, printer, name, method_info_map): """Write a single service declaration to a proto file.""" printer() printer('service %s {', self.__GetServiceClassName(name)) with printer.Indent(): for method_name, method_info in method_info_map.items...
[ "def", "__WriteProtoServiceDeclaration", "(", "self", ",", "printer", ",", "name", ",", "method_info_map", ")", ":", "printer", "(", ")", "printer", "(", "'service %s {'", ",", "self", ".", "__GetServiceClassName", "(", "name", ")", ")", "with", "printer", "."...
Write a single service declaration to a proto file.
[ "Write", "a", "single", "service", "declaration", "to", "a", "proto", "file", "." ]
python
train
51.071429
marrabld/planarradpy
libplanarradpy/planrad.py
https://github.com/marrabld/planarradpy/blob/5095d1cb98d4f67a7c3108c9282f2d59253e89a8/libplanarradpy/planrad.py#L504-L510
def build_c(self): """Calculates the total attenuation from the total absorption and total scattering c = a + b """ lg.info('Building total attenuation C') self.c = self.a + self.b
[ "def", "build_c", "(", "self", ")", ":", "lg", ".", "info", "(", "'Building total attenuation C'", ")", "self", ".", "c", "=", "self", ".", "a", "+", "self", ".", "b" ]
Calculates the total attenuation from the total absorption and total scattering c = a + b
[ "Calculates", "the", "total", "attenuation", "from", "the", "total", "absorption", "and", "total", "scattering" ]
python
test
30.714286
scanny/python-pptx
pptx/text/fonts.py
https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/text/fonts.py#L221-L226
def read(self, offset, length): """ Return *length* bytes from this stream starting at *offset*. """ self._file.seek(offset) return self._file.read(length)
[ "def", "read", "(", "self", ",", "offset", ",", "length", ")", ":", "self", ".", "_file", ".", "seek", "(", "offset", ")", "return", "self", ".", "_file", ".", "read", "(", "length", ")" ]
Return *length* bytes from this stream starting at *offset*.
[ "Return", "*", "length", "*", "bytes", "from", "this", "stream", "starting", "at", "*", "offset", "*", "." ]
python
train
31.666667
pandas-dev/pandas
pandas/core/indexes/multi.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/multi.py#L2260-L2314
def slice_locs(self, start=None, end=None, step=None, kind=None): """ For an ordered MultiIndex, compute the slice locations for input labels. The input labels can be tuples representing partial levels, e.g. for a MultiIndex with 3 levels, you can pass a single value (correspond...
[ "def", "slice_locs", "(", "self", ",", "start", "=", "None", ",", "end", "=", "None", ",", "step", "=", "None", ",", "kind", "=", "None", ")", ":", "# This function adds nothing to its parent implementation (the magic", "# happens in get_slice_bound method), but it adds...
For an ordered MultiIndex, compute the slice locations for input labels. The input labels can be tuples representing partial levels, e.g. for a MultiIndex with 3 levels, you can pass a single value (corresponding to the first level), or a 1-, 2-, or 3-tuple. Parameters ...
[ "For", "an", "ordered", "MultiIndex", "compute", "the", "slice", "locations", "for", "input", "labels", "." ]
python
train
34.527273
agile-geoscience/striplog
striplog/striplog.py
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/striplog.py#L1941-L1964
def thickest(self, n=1, index=False): """ Returns the thickest interval(s) as a striplog. Args: n (int): The number of thickest intervals to return. Default: 1. index (bool): If True, only the indices of the intervals are returned. You can use this to ind...
[ "def", "thickest", "(", "self", ",", "n", "=", "1", ",", "index", "=", "False", ")", ":", "s", "=", "sorted", "(", "range", "(", "len", "(", "self", ")", ")", ",", "key", "=", "lambda", "k", ":", "self", "[", "k", "]", ".", "thickness", ")", ...
Returns the thickest interval(s) as a striplog. Args: n (int): The number of thickest intervals to return. Default: 1. index (bool): If True, only the indices of the intervals are returned. You can use this to index into the striplog. Returns: Interv...
[ "Returns", "the", "thickest", "interval", "(", "s", ")", "as", "a", "striplog", "." ]
python
test
33.708333
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Action.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Action.py#L949-L964
def get_presig(self, target, source, env, executor=None): """Return the signature contents of this action's command line. This strips $(-$) and everything in between the string, since those parts don't affect signatures. """ from SCons.Subst import SUBST_SIG cmd = self.c...
[ "def", "get_presig", "(", "self", ",", "target", ",", "source", ",", "env", ",", "executor", "=", "None", ")", ":", "from", "SCons", ".", "Subst", "import", "SUBST_SIG", "cmd", "=", "self", ".", "cmd_list", "if", "is_List", "(", "cmd", ")", ":", "cmd...
Return the signature contents of this action's command line. This strips $(-$) and everything in between the string, since those parts don't affect signatures.
[ "Return", "the", "signature", "contents", "of", "this", "action", "s", "command", "line", "." ]
python
train
38
fastai/fastai
old/fastai/dataset.py
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L303-L315
def resize_imgs(self, targ, new_path, resume=True, fn=None): """ resize all images in the dataset and save them to `new_path` Arguments: targ (int): the target size new_path (string): the new folder to save the images resume (bool): if true (default), allow resum...
[ "def", "resize_imgs", "(", "self", ",", "targ", ",", "new_path", ",", "resume", "=", "True", ",", "fn", "=", "None", ")", ":", "dest", "=", "resize_imgs", "(", "self", ".", "fnames", ",", "targ", ",", "self", ".", "path", ",", "new_path", ",", "res...
resize all images in the dataset and save them to `new_path` Arguments: targ (int): the target size new_path (string): the new folder to save the images resume (bool): if true (default), allow resuming a partial resize operation by checking for the existence of individua...
[ "resize", "all", "images", "in", "the", "dataset", "and", "save", "them", "to", "new_path", "Arguments", ":", "targ", "(", "int", ")", ":", "the", "target", "size", "new_path", "(", "string", ")", ":", "the", "new", "folder", "to", "save", "the", "imag...
python
train
51
kristianfoerster/melodist
melodist/radiation.py
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/radiation.py#L180-L221
def bristow_campbell(tmin, tmax, pot_rad_daily, A, C): """calculates potential shortwave radiation based on minimum and maximum temperature This routine calculates global radiation as described in: Bristow, Keith L., and Gaylon S. Campbell: On the relationship between incoming solar radiation and ...
[ "def", "bristow_campbell", "(", "tmin", ",", "tmax", ",", "pot_rad_daily", ",", "A", ",", "C", ")", ":", "assert", "tmin", ".", "index", ".", "equals", "(", "tmax", ".", "index", ")", "temp", "=", "pd", ".", "DataFrame", "(", "data", "=", "dict", "...
calculates potential shortwave radiation based on minimum and maximum temperature This routine calculates global radiation as described in: Bristow, Keith L., and Gaylon S. Campbell: On the relationship between incoming solar radiation and daily maximum and minimum temperature. Agricultural and fo...
[ "calculates", "potential", "shortwave", "radiation", "based", "on", "minimum", "and", "maximum", "temperature", "This", "routine", "calculates", "global", "radiation", "as", "described", "in", ":", "Bristow", "Keith", "L", ".", "and", "Gaylon", "S", ".", "Campbe...
python
train
37.071429
CalebBell/thermo
thermo/utils.py
https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L1730-L1772
def select_valid_methods(self, T): r'''Method to obtain a sorted list of methods which are valid at `T` according to `test_method_validity`. Considers either only user methods if forced is True, or all methods. User methods are first tested according to their listed order, and unless for...
[ "def", "select_valid_methods", "(", "self", ",", "T", ")", ":", "# Consider either only the user's methods or all methods", "# Tabular data will be in both when inserted", "if", "self", ".", "forced", ":", "considered_methods", "=", "list", "(", "self", ".", "user_methods",...
r'''Method to obtain a sorted list of methods which are valid at `T` according to `test_method_validity`. Considers either only user methods if forced is True, or all methods. User methods are first tested according to their listed order, and unless forced is True, then all methods are t...
[ "r", "Method", "to", "obtain", "a", "sorted", "list", "of", "methods", "which", "are", "valid", "at", "T", "according", "to", "test_method_validity", ".", "Considers", "either", "only", "user", "methods", "if", "forced", "is", "True", "or", "all", "methods",...
python
valid
40.883721
maas/python-libmaas
maas/client/bones/__init__.py
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/bones/__init__.py#L391-L397
def call(self, **data): """Issue the call. :param data: Data to pass in the *body* of the request. """ uri, body, headers = self.prepare(data) return self.dispatch(uri, body, headers)
[ "def", "call", "(", "self", ",", "*", "*", "data", ")", ":", "uri", ",", "body", ",", "headers", "=", "self", ".", "prepare", "(", "data", ")", "return", "self", ".", "dispatch", "(", "uri", ",", "body", ",", "headers", ")" ]
Issue the call. :param data: Data to pass in the *body* of the request.
[ "Issue", "the", "call", "." ]
python
train
31.142857
jazzband/django-mongonaut
mongonaut/sites.py
https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/sites.py#L53-L55
def has_delete_permission(self, request): """ Can delete this object """ return request.user.is_authenticated and request.user.is_active and request.user.is_superuser
[ "def", "has_delete_permission", "(", "self", ",", "request", ")", ":", "return", "request", ".", "user", ".", "is_authenticated", "and", "request", ".", "user", ".", "is_active", "and", "request", ".", "user", ".", "is_superuser" ]
Can delete this object
[ "Can", "delete", "this", "object" ]
python
valid
60
zhmcclient/python-zhmcclient
zhmcclient/_session.py
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_session.py#L78-L112
def _request_exc_message(exc): """ Return a reasonable exception message from a :exc:`request.exceptions.RequestException` exception. The approach is to dig deep to the original reason, if the original exception is present, skipping irrelevant exceptions such as `urllib3.exceptions.MaxRetryErro...
[ "def", "_request_exc_message", "(", "exc", ")", ":", "if", "exc", ".", "args", ":", "if", "isinstance", "(", "exc", ".", "args", "[", "0", "]", ",", "Exception", ")", ":", "org_exc", "=", "exc", ".", "args", "[", "0", "]", "if", "isinstance", "(", ...
Return a reasonable exception message from a :exc:`request.exceptions.RequestException` exception. The approach is to dig deep to the original reason, if the original exception is present, skipping irrelevant exceptions such as `urllib3.exceptions.MaxRetryError`, and eliminating useless object repr...
[ "Return", "a", "reasonable", "exception", "message", "from", "a", ":", "exc", ":", "request", ".", "exceptions", ".", "RequestException", "exception", "." ]
python
train
35.028571
AnalogJ/lexicon
lexicon/providers/hetzner.py
https://github.com/AnalogJ/lexicon/blob/9330b871988753cad44fe2876a217b4c67b1fa0e/lexicon/providers/hetzner.py#L372-L396
def _list_records_in_zone(self, zone, rdtype=None, name=None, content=None): """ Iterates over all records of the zone and returns a list of records filtered by record type, name and content. The list is empty if no records found. """ records = [] rrsets = zone.iterate_rd...
[ "def", "_list_records_in_zone", "(", "self", ",", "zone", ",", "rdtype", "=", "None", ",", "name", "=", "None", ",", "content", "=", "None", ")", ":", "records", "=", "[", "]", "rrsets", "=", "zone", ".", "iterate_rdatasets", "(", ")", "if", "zone", ...
Iterates over all records of the zone and returns a list of records filtered by record type, name and content. The list is empty if no records found.
[ "Iterates", "over", "all", "records", "of", "the", "zone", "and", "returns", "a", "list", "of", "records", "filtered", "by", "record", "type", "name", "and", "content", ".", "The", "list", "is", "empty", "if", "no", "records", "found", "." ]
python
train
51.72
wal-e/wal-e
wal_e/operator/backup.py
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/operator/backup.py#L248-L291
def wal_archive(self, wal_path, concurrency=1): """ Uploads a WAL file to S3 or Windows Azure Blob Service This code is intended to typically be called from Postgres's archive_command feature. """ # Upload the segment expressly indicated. It's special # relativ...
[ "def", "wal_archive", "(", "self", ",", "wal_path", ",", "concurrency", "=", "1", ")", ":", "# Upload the segment expressly indicated. It's special", "# relative to other uploads when parallel wal-push is enabled,", "# in that it's not desirable to tweak its .ready/.done files", "# in...
Uploads a WAL file to S3 or Windows Azure Blob Service This code is intended to typically be called from Postgres's archive_command feature.
[ "Uploads", "a", "WAL", "file", "to", "S3", "or", "Windows", "Azure", "Blob", "Service" ]
python
train
36.909091
StorjOld/heartbeat
heartbeat/Merkle/Merkle.py
https://github.com/StorjOld/heartbeat/blob/4d54f2011f1e9f688073d4347bc51bb7bd682718/heartbeat/Merkle/Merkle.py#L308-L316
def fromdict(dict): """Takes a dictionary as an argument and returns a new Proof object from the dictionary. :param dict: the dictionary to convert """ key = hb_decode(dict['key']) check_fraction = dict['check_fraction'] return Merkle(check_fraction, key)
[ "def", "fromdict", "(", "dict", ")", ":", "key", "=", "hb_decode", "(", "dict", "[", "'key'", "]", ")", "check_fraction", "=", "dict", "[", "'check_fraction'", "]", "return", "Merkle", "(", "check_fraction", ",", "key", ")" ]
Takes a dictionary as an argument and returns a new Proof object from the dictionary. :param dict: the dictionary to convert
[ "Takes", "a", "dictionary", "as", "an", "argument", "and", "returns", "a", "new", "Proof", "object", "from", "the", "dictionary", "." ]
python
train
33.777778
NetEaseGame/ATX
atx/ext/report/__init__.py
https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/ext/report/__init__.py#L251-L267
def _add_assert(self, **kwargs): """ if screenshot is None, only failed case will take screenshot """ # convert screenshot to relative path from <None|True|False|PIL.Image> screenshot = kwargs.get('screenshot') is_success = kwargs.get('success') screenshot = (not ...
[ "def", "_add_assert", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# convert screenshot to relative path from <None|True|False|PIL.Image>", "screenshot", "=", "kwargs", ".", "get", "(", "'screenshot'", ")", "is_success", "=", "kwargs", ".", "get", "(", "'success...
if screenshot is None, only failed case will take screenshot
[ "if", "screenshot", "is", "None", "only", "failed", "case", "will", "take", "screenshot" ]
python
train
51.411765
DataDog/integrations-core
datadog_checks_base/datadog_checks/base/checks/prometheus/mixins.py
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/datadog_checks_base/datadog_checks/base/checks/prometheus/mixins.py#L239-L253
def _text_filter_input(self, input_gen): """ Filters out the text input line by line to avoid parsing and processing metrics we know we don't want to process. This only works on `text/plain` payloads, and is an INTERNAL FEATURE implemented for the kubelet check :param input_get: ...
[ "def", "_text_filter_input", "(", "self", ",", "input_gen", ")", ":", "for", "line", "in", "input_gen", ":", "for", "item", "in", "self", ".", "_text_filter_blacklist", ":", "if", "item", "in", "line", ":", "break", "else", ":", "# No blacklist matches, passin...
Filters out the text input line by line to avoid parsing and processing metrics we know we don't want to process. This only works on `text/plain` payloads, and is an INTERNAL FEATURE implemented for the kubelet check :param input_get: line generator :output: generator of filtered lines
[ "Filters", "out", "the", "text", "input", "line", "by", "line", "to", "avoid", "parsing", "and", "processing", "metrics", "we", "know", "we", "don", "t", "want", "to", "process", ".", "This", "only", "works", "on", "text", "/", "plain", "payloads", "and"...
python
train
42
miguelgrinberg/python-socketio
socketio/asyncio_namespace.py
https://github.com/miguelgrinberg/python-socketio/blob/c0c1bf8d21e3597389b18938550a0724dd9676b7/socketio/asyncio_namespace.py#L118-L128
async def disconnect(self, sid, namespace=None): """Disconnect a client. The only difference with the :func:`socketio.Server.disconnect` method is that when the ``namespace`` argument is not given the namespace associated with the class is used. Note: this method is a coroutine...
[ "async", "def", "disconnect", "(", "self", ",", "sid", ",", "namespace", "=", "None", ")", ":", "return", "await", "self", ".", "server", ".", "disconnect", "(", "sid", ",", "namespace", "=", "namespace", "or", "self", ".", "namespace", ")" ]
Disconnect a client. The only difference with the :func:`socketio.Server.disconnect` method is that when the ``namespace`` argument is not given the namespace associated with the class is used. Note: this method is a coroutine.
[ "Disconnect", "a", "client", "." ]
python
train
38.545455
Cue/scales
src/greplin/scales/flaskhandler.py
https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/flaskhandler.py#L53-L61
def registerStatsHandler(app, serverName, prefix='/status/'): """Register the stats handler with a Flask app, serving routes with a given prefix. The prefix defaults to '/status/', which is generally what you want.""" if prefix[-1] != '/': prefix += '/' handler = functools.partial(statsHandler, serverName...
[ "def", "registerStatsHandler", "(", "app", ",", "serverName", ",", "prefix", "=", "'/status/'", ")", ":", "if", "prefix", "[", "-", "1", "]", "!=", "'/'", ":", "prefix", "+=", "'/'", "handler", "=", "functools", ".", "partial", "(", "statsHandler", ",", ...
Register the stats handler with a Flask app, serving routes with a given prefix. The prefix defaults to '/status/', which is generally what you want.
[ "Register", "the", "stats", "handler", "with", "a", "Flask", "app", "serving", "routes", "with", "a", "given", "prefix", ".", "The", "prefix", "defaults", "to", "/", "status", "/", "which", "is", "generally", "what", "you", "want", "." ]
python
train
51.888889
MycroftAI/mycroft-precise
precise/scripts/train_generated.py
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/scripts/train_generated.py#L203-L215
def samples_to_batches(samples: Iterable, batch_size: int): """Chunk a series of network inputs and outputs into larger batches""" it = iter(samples) while True: with suppress(StopIteration): batch_in, batch_out = [], [] for i in range(batch_size): ...
[ "def", "samples_to_batches", "(", "samples", ":", "Iterable", ",", "batch_size", ":", "int", ")", ":", "it", "=", "iter", "(", "samples", ")", "while", "True", ":", "with", "suppress", "(", "StopIteration", ")", ":", "batch_in", ",", "batch_out", "=", "[...
Chunk a series of network inputs and outputs into larger batches
[ "Chunk", "a", "series", "of", "network", "inputs", "and", "outputs", "into", "larger", "batches" ]
python
train
44.307692
maas/python-libmaas
maas/client/viscera/__init__.py
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/__init__.py#L193-L230
def get_pk_descriptors(cls): """Return tuple of tuples with attribute name and descriptor on the `cls` that is defined as the primary keys.""" pk_fields = { name: descriptor for name, descriptor in vars_class(cls).items() if isinstance(descriptor, ObjectField) and is_pk_descriptor(de...
[ "def", "get_pk_descriptors", "(", "cls", ")", ":", "pk_fields", "=", "{", "name", ":", "descriptor", "for", "name", ",", "descriptor", "in", "vars_class", "(", "cls", ")", ".", "items", "(", ")", "if", "isinstance", "(", "descriptor", ",", "ObjectField", ...
Return tuple of tuples with attribute name and descriptor on the `cls` that is defined as the primary keys.
[ "Return", "tuple", "of", "tuples", "with", "attribute", "name", "and", "descriptor", "on", "the", "cls", "that", "is", "defined", "as", "the", "primary", "keys", "." ]
python
train
40.447368
sernst/cauldron
cauldron/session/naming.py
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/naming.py#L36-L117
def explode_filename(name: str, scheme: str) -> dict: """ Removes any path components from the input filename and returns a dictionary containing the name of the file without extension and the extension (if an extension exists) :param name: :param scheme: :return: """ if not scheme...
[ "def", "explode_filename", "(", "name", ":", "str", ",", "scheme", ":", "str", ")", "->", "dict", ":", "if", "not", "scheme", ":", "return", "split_filename", "(", "name", ")", "replacements", "=", "{", "'name'", ":", "'(?P<name>.*)'", ",", "'ext'", ":",...
Removes any path components from the input filename and returns a dictionary containing the name of the file without extension and the extension (if an extension exists) :param name: :param scheme: :return:
[ "Removes", "any", "path", "components", "from", "the", "input", "filename", "and", "returns", "a", "dictionary", "containing", "the", "name", "of", "the", "file", "without", "extension", "and", "the", "extension", "(", "if", "an", "extension", "exists", ")" ]
python
train
27.304878
merll/docker-map
dockermap/map/runner/cmd.py
https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/map/runner/cmd.py#L21-L53
def exec_commands(self, action, c_name, run_cmds, **kwargs): """ Runs a single command inside a container. :param action: Action configuration. :type action: dockermap.map.runner.ActionConfig :param c_name: Container name. :type c_name: unicode | str :param run_c...
[ "def", "exec_commands", "(", "self", ",", "action", ",", "c_name", ",", "run_cmds", ",", "*", "*", "kwargs", ")", ":", "client", "=", "action", ".", "client", "exec_results", "=", "[", "]", "for", "run_cmd", "in", "run_cmds", ":", "cmd", "=", "run_cmd"...
Runs a single command inside a container. :param action: Action configuration. :type action: dockermap.map.runner.ActionConfig :param c_name: Container name. :type c_name: unicode | str :param run_cmds: Commands to run. :type run_cmds: list[dockermap.map.input.ExecComman...
[ "Runs", "a", "single", "command", "inside", "a", "container", "." ]
python
train
47.181818
wagtail/django-modelcluster
modelcluster/utils.py
https://github.com/wagtail/django-modelcluster/blob/bfc8bd755af0ddd49e2aee2f2ca126921573d38b/modelcluster/utils.py#L1-L19
def sort_by_fields(items, fields): """ Sort a list of objects on the given fields. The field list works analogously to queryset.order_by(*fields): each field is either a property of the object, or is prefixed by '-' (e.g. '-name') to indicate reverse ordering. """ # To get the desired behaviour,...
[ "def", "sort_by_fields", "(", "items", ",", "fields", ")", ":", "# To get the desired behaviour, we need to order by keys in reverse order", "# See: https://docs.python.org/2/howto/sorting.html#sort-stability-and-complex-sorts", "for", "key", "in", "reversed", "(", "fields", ")", "...
Sort a list of objects on the given fields. The field list works analogously to queryset.order_by(*fields): each field is either a property of the object, or is prefixed by '-' (e.g. '-name') to indicate reverse ordering.
[ "Sort", "a", "list", "of", "objects", "on", "the", "given", "fields", ".", "The", "field", "list", "works", "analogously", "to", "queryset", ".", "order_by", "(", "*", "fields", ")", ":", "each", "field", "is", "either", "a", "property", "of", "the", "...
python
test
46.947368
sethmlarson/virtualbox-python
virtualbox/library.py
https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L29858-L29890
def set_network_settings(self, mtu, sock_snd, sock_rcv, tcp_wnd_snd, tcp_wnd_rcv): """Sets network configuration of the NAT engine. in mtu of type int MTU (maximum transmission unit) of the NAT engine in bytes. in sock_snd of type int Capacity of the socket send buffer ...
[ "def", "set_network_settings", "(", "self", ",", "mtu", ",", "sock_snd", ",", "sock_rcv", ",", "tcp_wnd_snd", ",", "tcp_wnd_rcv", ")", ":", "if", "not", "isinstance", "(", "mtu", ",", "baseinteger", ")", ":", "raise", "TypeError", "(", "\"mtu can only be an in...
Sets network configuration of the NAT engine. in mtu of type int MTU (maximum transmission unit) of the NAT engine in bytes. in sock_snd of type int Capacity of the socket send buffer in bytes when creating a new socket. in sock_rcv of type int Capacity of ...
[ "Sets", "network", "configuration", "of", "the", "NAT", "engine", "." ]
python
train
47.666667
pypa/pipenv
pipenv/vendor/distlib/manifest.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/manifest.py#L57-L82
def findall(self): """Find all files under the base and set ``allfiles`` to the absolute pathnames of files found. """ from stat import S_ISREG, S_ISDIR, S_ISLNK self.allfiles = allfiles = [] root = self.base stack = [root] pop = stack.pop push = ...
[ "def", "findall", "(", "self", ")", ":", "from", "stat", "import", "S_ISREG", ",", "S_ISDIR", ",", "S_ISLNK", "self", ".", "allfiles", "=", "allfiles", "=", "[", "]", "root", "=", "self", ".", "base", "stack", "=", "[", "root", "]", "pop", "=", "st...
Find all files under the base and set ``allfiles`` to the absolute pathnames of files found.
[ "Find", "all", "files", "under", "the", "base", "and", "set", "allfiles", "to", "the", "absolute", "pathnames", "of", "files", "found", "." ]
python
train
31.153846
vortec/versionbump
versionbump/versionbump.py
https://github.com/vortec/versionbump/blob/6945d316af700c3c3ceaf3882283b3f1f4876d9e/versionbump/versionbump.py#L37-L42
def pre_release(self): """ Return true if version is a pre-release. """ label = self.version_info.get('label', None) pre = self.version_info.get('pre', None) return True if (label is not None and pre is not None) else False
[ "def", "pre_release", "(", "self", ")", ":", "label", "=", "self", ".", "version_info", ".", "get", "(", "'label'", ",", "None", ")", "pre", "=", "self", ".", "version_info", ".", "get", "(", "'pre'", ",", "None", ")", "return", "True", "if", "(", ...
Return true if version is a pre-release.
[ "Return", "true", "if", "version", "is", "a", "pre", "-", "release", "." ]
python
train
41.833333
rtfd/sphinx-autoapi
autoapi/mappers/python/astroid_utils.py
https://github.com/rtfd/sphinx-autoapi/blob/9735f43a8d9ff4620c7bcbd177fd1bb7608052e9/autoapi/mappers/python/astroid_utils.py#L178-L202
def get_assign_annotation(node): """Get the type annotation of the assignment of the given node. :param node: The node to get the annotation for. :type node: astroid.nodes.Assign or astroid.nodes.AnnAssign :returns: The type annotation as a string, or None if one does not exist. :type: str or None...
[ "def", "get_assign_annotation", "(", "node", ")", ":", "annotation", "=", "None", "annotation_node", "=", "None", "try", ":", "annotation_node", "=", "node", ".", "annotation", "except", "AttributeError", ":", "# Python 2 has no support for type annotations, so use getatt...
Get the type annotation of the assignment of the given node. :param node: The node to get the annotation for. :type node: astroid.nodes.Assign or astroid.nodes.AnnAssign :returns: The type annotation as a string, or None if one does not exist. :type: str or None
[ "Get", "the", "type", "annotation", "of", "the", "assignment", "of", "the", "given", "node", "." ]
python
train
31.2
hobson/pug-dj
pug/dj/db.py
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1373-L1484
def field_dict_from_row(row, model, field_names=None, ignore_fields=('id', 'pk'), strip=True, blank_none=True, ignore_related=True, ignore_values=(None,), ignore_errors=Tr...
[ "def", "field_dict_from_row", "(", "row", ",", "model", ",", "field_names", "=", "None", ",", "ignore_fields", "=", "(", "'id'", ",", "'pk'", ")", ",", "strip", "=", "True", ",", "blank_none", "=", "True", ",", "ignore_related", "=", "True", ",", "ignore...
Construct a Mapping (dict) from field names to values from a row of data Args: row (list or dict): Data (values) to be assigned to field_names in the dict. If `row` is a list, then the column names (header row) can be provided in `field_names`. If `row` is a list and no field_names are provid...
[ "Construct", "a", "Mapping", "(", "dict", ")", "from", "field", "names", "to", "values", "from", "a", "row", "of", "data" ]
python
train
52.035714
CityOfZion/neo-python
neo/Core/State/AccountState.py
https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/State/AccountState.py#L232-L242
def AllBalancesZeroOrLess(self): """ Flag indicating if all balances are 0 or less. Returns: bool: True if all balances are <= 0. False, otherwise. """ for key, fixed8 in self.Balances.items(): if fixed8.value > 0: return False ret...
[ "def", "AllBalancesZeroOrLess", "(", "self", ")", ":", "for", "key", ",", "fixed8", "in", "self", ".", "Balances", ".", "items", "(", ")", ":", "if", "fixed8", ".", "value", ">", "0", ":", "return", "False", "return", "True" ]
Flag indicating if all balances are 0 or less. Returns: bool: True if all balances are <= 0. False, otherwise.
[ "Flag", "indicating", "if", "all", "balances", "are", "0", "or", "less", "." ]
python
train
28.909091
google/grr
grr/server/grr_response_server/aff4_objects/filestore.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/aff4_objects/filestore.py#L57-L82
def CheckHashes(self, hashes, external=True): """Checks a list of hashes for presence in the store. Sub stores need to pass back the original HashDigest objects since they carry state about the original file source. Only unique hashes are checked, if there is duplication in the hashes input it is ...
[ "def", "CheckHashes", "(", "self", ",", "hashes", ",", "external", "=", "True", ")", ":", "hashes", "=", "set", "(", "hashes", ")", "for", "child", "in", "self", ".", "GetChildrenByPriority", "(", "allow_external", "=", "external", ")", ":", "for", "urn"...
Checks a list of hashes for presence in the store. Sub stores need to pass back the original HashDigest objects since they carry state about the original file source. Only unique hashes are checked, if there is duplication in the hashes input it is the caller's responsibility to maintain any necessary...
[ "Checks", "a", "list", "of", "hashes", "for", "presence", "in", "the", "store", "." ]
python
train
33.115385
hobson/aima
aima/search.py
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/search.py#L439-L441
def connect1(self, A, B, distance): "Add a link from A to B of given distance, in one direction only." self.dict.setdefault(A,{})[B] = distance
[ "def", "connect1", "(", "self", ",", "A", ",", "B", ",", "distance", ")", ":", "self", ".", "dict", ".", "setdefault", "(", "A", ",", "{", "}", ")", "[", "B", "]", "=", "distance" ]
Add a link from A to B of given distance, in one direction only.
[ "Add", "a", "link", "from", "A", "to", "B", "of", "given", "distance", "in", "one", "direction", "only", "." ]
python
valid
52.333333
bhmm/bhmm
bhmm/hmm/generic_sampled_hmm.py
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_sampled_hmm.py#L208-L213
def timescales_samples(self): r""" Samples of the timescales """ res = np.empty((self.nsamples, self.nstates-1), dtype=config.dtype) for i in range(self.nsamples): res[i, :] = self._sampled_hmms[i].timescales return res
[ "def", "timescales_samples", "(", "self", ")", ":", "res", "=", "np", ".", "empty", "(", "(", "self", ".", "nsamples", ",", "self", ".", "nstates", "-", "1", ")", ",", "dtype", "=", "config", ".", "dtype", ")", "for", "i", "in", "range", "(", "se...
r""" Samples of the timescales
[ "r", "Samples", "of", "the", "timescales" ]
python
train
43
theiviaxx/python-perforce
perforce/models.py
https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/models.py#L138-L166
def __getVariables(self): """Parses the P4 env vars using 'set p4'""" try: startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW output = subprocess.check_ou...
[ "def", "__getVariables", "(", "self", ")", ":", "try", ":", "startupinfo", "=", "None", "if", "os", ".", "name", "==", "'nt'", ":", "startupinfo", "=", "subprocess", ".", "STARTUPINFO", "(", ")", "startupinfo", ".", "dwFlags", "|=", "subprocess", ".", "S...
Parses the P4 env vars using 'set p4
[ "Parses", "the", "P4", "env", "vars", "using", "set", "p4" ]
python
train
38.793103
mcieslik-mctp/papy
src/papy/core.py
https://github.com/mcieslik-mctp/papy/blob/708e50827b5db46bbea081982cb74b9b0e464064/src/papy/core.py#L346-L374
def del_piper(self, piper, forced=False): """ Removes a ``Piper`` from the ``Dagger`` instance. Arguments: - piper(``Piper`` or id(``Piper``)) ``Piper`` instance or ``Piper`` instance id. - forced(bool) [default: ``False``] If "forced" is ``True``, wil...
[ "def", "del_piper", "(", "self", ",", "piper", ",", "forced", "=", "False", ")", ":", "self", ".", "log", ".", "debug", "(", "'%s trying to delete piper %s'", "%", "(", "repr", "(", "self", ")", ",", "repr", "(", "piper", ")", ")", ")", "try", ":", ...
Removes a ``Piper`` from the ``Dagger`` instance. Arguments: - piper(``Piper`` or id(``Piper``)) ``Piper`` instance or ``Piper`` instance id. - forced(bool) [default: ``False``] If "forced" is ``True``, will not raise a ``DaggerError`` if the ``Piper`` ha...
[ "Removes", "a", "Piper", "from", "the", "Dagger", "instance", "." ]
python
train
45.931034
Becksteinlab/GromacsWrapper
gromacs/utilities.py
https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/utilities.py#L689-L695
def unlink_f(path): """Unlink path but do not complain if file does not exist.""" try: os.unlink(path) except OSError as err: if err.errno != errno.ENOENT: raise
[ "def", "unlink_f", "(", "path", ")", ":", "try", ":", "os", ".", "unlink", "(", "path", ")", "except", "OSError", "as", "err", ":", "if", "err", ".", "errno", "!=", "errno", ".", "ENOENT", ":", "raise" ]
Unlink path but do not complain if file does not exist.
[ "Unlink", "path", "but", "do", "not", "complain", "if", "file", "does", "not", "exist", "." ]
python
valid
27.857143
Erotemic/utool
utool/util_alg.py
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L440-L484
def grouping_delta_stats(old, new): """ Returns statistics about grouping changes Args: old (set of frozenset): old grouping new (set of frozenset): new grouping Returns: pd.DataFrame: df: data frame of size statistics Example: >>> # ENABLE_DOCTEST >>> from...
[ "def", "grouping_delta_stats", "(", "old", ",", "new", ")", ":", "import", "pandas", "as", "pd", "import", "utool", "as", "ut", "group_delta", "=", "ut", ".", "grouping_delta", "(", "old", ",", "new", ")", "stats", "=", "ut", ".", "odict", "(", ")", ...
Returns statistics about grouping changes Args: old (set of frozenset): old grouping new (set of frozenset): new grouping Returns: pd.DataFrame: df: data frame of size statistics Example: >>> # ENABLE_DOCTEST >>> from utool.util_alg import * # NOQA >>> imp...
[ "Returns", "statistics", "about", "grouping", "changes" ]
python
train
35.711111
TrainerDex/TrainerDex.py
trainerdex/client.py
https://github.com/TrainerDex/TrainerDex.py/blob/a693e1321abf2825f74bcbf29f0800f0c6835b62/trainerdex/client.py#L48-L71
def create_trainer(self, username, team, start_date=None, has_cheated=None, last_cheated=None, currently_cheats=None, statistics=True, daily_goal=None, total_goal=None, prefered=True, account=None, verified=False): """Add a trainer to the database""" args = locals() url = api_url+'trainers/' payload = { 'use...
[ "def", "create_trainer", "(", "self", ",", "username", ",", "team", ",", "start_date", "=", "None", ",", "has_cheated", "=", "None", ",", "last_cheated", "=", "None", ",", "currently_cheats", "=", "None", ",", "statistics", "=", "True", ",", "daily_goal", ...
Add a trainer to the database
[ "Add", "a", "trainer", "to", "the", "database" ]
python
train
36
spyder-ide/spyder
spyder/utils/syntaxhighlighters.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/syntaxhighlighters.py#L852-L867
def make_gettext_patterns(): "Strongly inspired from idlelib.ColorDelegator.make_pat" kwstr = 'msgid msgstr' kw = r"\b" + any("keyword", kwstr.split()) + r"\b" fuzzy = any("builtin", [r"#,[^\n]*"]) links = any("normal", [r"#:[^\n]*"]) comment = any("comment", [r"#[^\n]*"]) number = an...
[ "def", "make_gettext_patterns", "(", ")", ":", "kwstr", "=", "'msgid msgstr'", "kw", "=", "r\"\\b\"", "+", "any", "(", "\"keyword\"", ",", "kwstr", ".", "split", "(", ")", ")", "+", "r\"\\b\"", "fuzzy", "=", "any", "(", "\"builtin\"", ",", "[", "r\"#,[^\...
Strongly inspired from idlelib.ColorDelegator.make_pat
[ "Strongly", "inspired", "from", "idlelib", ".", "ColorDelegator", ".", "make_pat" ]
python
train
47.75
zhmcclient/python-zhmcclient
zhmcclient/_console.py
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_console.py#L209-L217
def users(self): """ :class:`~zhmcclient.UserManager`: Access to the :term:`Users <User>` in this Console. """ # We do here some lazy loading. if not self._users: self._users = UserManager(self) return self._users
[ "def", "users", "(", "self", ")", ":", "# We do here some lazy loading.", "if", "not", "self", ".", "_users", ":", "self", ".", "_users", "=", "UserManager", "(", "self", ")", "return", "self", ".", "_users" ]
:class:`~zhmcclient.UserManager`: Access to the :term:`Users <User>` in this Console.
[ ":", "class", ":", "~zhmcclient", ".", "UserManager", ":", "Access", "to", "the", ":", "term", ":", "Users", "<User", ">", "in", "this", "Console", "." ]
python
train
30.333333
Fuyukai/asyncwebsockets
asyncwebsockets/websocket.py
https://github.com/Fuyukai/asyncwebsockets/blob/e33e75fd51ce5ae0feac244e8407d2672c5b4745/asyncwebsockets/websocket.py#L133-L150
async def close(self, code: int = 1006, reason: str = "Connection closed"): """ Closes the websocket. """ if self._closed: return self._closed = True if self._scope is not None: await self._scope.cancel() # cancel any outstanding list...
[ "async", "def", "close", "(", "self", ",", "code", ":", "int", "=", "1006", ",", "reason", ":", "str", "=", "\"Connection closed\"", ")", ":", "if", "self", ".", "_closed", ":", "return", "self", ".", "_closed", "=", "True", "if", "self", ".", "_scop...
Closes the websocket.
[ "Closes", "the", "websocket", "." ]
python
train
28.5
brocade/pynos
pynos/versions/ver_7/ver_7_1_0/yang/brocade_tunnels.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_tunnels.py#L817-L831
def overlay_gateway_access_lists_ipv6_out_ipv6_acl_out_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels") name_key = ET.SubElement(overlay_gateway,...
[ "def", "overlay_gateway_access_lists_ipv6_out_ipv6_acl_out_name", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "overlay_gateway", "=", "ET", ".", "SubElement", "(", "config", ",", "\"overlay-gateway\"...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
49.533333
RudolfCardinal/pythonlib
cardinal_pythonlib/pdf.py
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/pdf.py#L405-L438
def get_pdf_from_html(html: str, header_html: str = None, footer_html: str = None, wkhtmltopdf_filename: str = _WKHTMLTOPDF_FILENAME, wkhtmltopdf_options: Dict[str, Any] = None, file_encoding: str = "utf-8", ...
[ "def", "get_pdf_from_html", "(", "html", ":", "str", ",", "header_html", ":", "str", "=", "None", ",", "footer_html", ":", "str", "=", "None", ",", "wkhtmltopdf_filename", ":", "str", "=", "_WKHTMLTOPDF_FILENAME", ",", "wkhtmltopdf_options", ":", "Dict", "[", ...
Takes HTML and returns a PDF. See the arguments to :func:`make_pdf_from_html` (except ``on_disk``). Returns: the PDF binary as a ``bytes`` object
[ "Takes", "HTML", "and", "returns", "a", "PDF", "." ]
python
train
37.941176
c0fec0de/anytree
anytree/util/__init__.py
https://github.com/c0fec0de/anytree/blob/775477e206a75e697983e70dae6372b5a7e42dcf/anytree/util/__init__.py#L37-L61
def leftsibling(node): """ Return Left Sibling of `node`. >>> from anytree import Node >>> dan = Node("Dan") >>> jet = Node("Jet", parent=dan) >>> jan = Node("Jan", parent=dan) >>> joe = Node("Joe", parent=dan) >>> leftsibling(dan) >>> leftsibling(jet) >>> leftsibling(jan) N...
[ "def", "leftsibling", "(", "node", ")", ":", "if", "node", ".", "parent", ":", "pchildren", "=", "node", ".", "parent", ".", "children", "idx", "=", "pchildren", ".", "index", "(", "node", ")", "if", "idx", ":", "return", "pchildren", "[", "idx", "-"...
Return Left Sibling of `node`. >>> from anytree import Node >>> dan = Node("Dan") >>> jet = Node("Jet", parent=dan) >>> jan = Node("Jan", parent=dan) >>> joe = Node("Joe", parent=dan) >>> leftsibling(dan) >>> leftsibling(jet) >>> leftsibling(jan) Node('/Dan/Jet') >>> leftsibling...
[ "Return", "Left", "Sibling", "of", "node", "." ]
python
train
23.36
NetEaseGame/aircv
aircv/__init__.py
https://github.com/NetEaseGame/aircv/blob/d479e49ef98347bbbe6ac2e4aa9119cecc15c8ca/aircv/__init__.py#L80-L88
def imread(filename): ''' Like cv2.imread This function will make sure filename exists ''' im = cv2.imread(filename) if im is None: raise RuntimeError("file: '%s' not exists" % filename) return im
[ "def", "imread", "(", "filename", ")", ":", "im", "=", "cv2", ".", "imread", "(", "filename", ")", "if", "im", "is", "None", ":", "raise", "RuntimeError", "(", "\"file: '%s' not exists\"", "%", "filename", ")", "return", "im" ]
Like cv2.imread This function will make sure filename exists
[ "Like", "cv2", ".", "imread", "This", "function", "will", "make", "sure", "filename", "exists" ]
python
train
25.111111
phn/lineid_plot
lineid_plot/lineid_plot.py
https://github.com/phn/lineid_plot/blob/7c7a1af53fe439b3a7c5a57f01680575837fb978/lineid_plot/lineid_plot.py#L40-L42
def get_line_flux(line_wave, wave, flux, **kwargs): """Interpolated flux at a given wavelength (calls np.interp).""" return np.interp(line_wave, wave, flux, **kwargs)
[ "def", "get_line_flux", "(", "line_wave", ",", "wave", ",", "flux", ",", "*", "*", "kwargs", ")", ":", "return", "np", ".", "interp", "(", "line_wave", ",", "wave", ",", "flux", ",", "*", "*", "kwargs", ")" ]
Interpolated flux at a given wavelength (calls np.interp).
[ "Interpolated", "flux", "at", "a", "given", "wavelength", "(", "calls", "np", ".", "interp", ")", "." ]
python
train
57.333333
openpaperwork/paperwork-backend
paperwork_backend/common/page.py
https://github.com/openpaperwork/paperwork-backend/blob/114b831e94e039e68b339751fd18250877abad76/paperwork_backend/common/page.py#L166-L171
def _get_filepath(self, ext): """ Returns a file path relative to this page """ filename = ("%s%d.%s" % (self.FILE_PREFIX, self.page_nb + 1, ext)) return self.fs.join(self.doc.path, filename)
[ "def", "_get_filepath", "(", "self", ",", "ext", ")", ":", "filename", "=", "(", "\"%s%d.%s\"", "%", "(", "self", ".", "FILE_PREFIX", ",", "self", ".", "page_nb", "+", "1", ",", "ext", ")", ")", "return", "self", ".", "fs", ".", "join", "(", "self"...
Returns a file path relative to this page
[ "Returns", "a", "file", "path", "relative", "to", "this", "page" ]
python
train
37.666667
jsommers/switchyard
switchyard/lib/packet/packet.py
https://github.com/jsommers/switchyard/blob/fdcb3869c937dcedbd6ea7a7822ebd412bf1e2b0/switchyard/lib/packet/packet.py#L135-L142
def has_header(self, hdrclass): ''' Return True if the packet has a header of the given hdrclass, False otherwise. ''' if isinstance(hdrclass, str): return self.get_header_by_name(hdrclass) is not None return self.get_header(hdrclass) is not None
[ "def", "has_header", "(", "self", ",", "hdrclass", ")", ":", "if", "isinstance", "(", "hdrclass", ",", "str", ")", ":", "return", "self", ".", "get_header_by_name", "(", "hdrclass", ")", "is", "not", "None", "return", "self", ".", "get_header", "(", "hdr...
Return True if the packet has a header of the given hdrclass, False otherwise.
[ "Return", "True", "if", "the", "packet", "has", "a", "header", "of", "the", "given", "hdrclass", "False", "otherwise", "." ]
python
train
37.5
graphql-python/graphql-core-next
graphql/execution/execute.py
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/execute.py#L537-L553
def does_fragment_condition_match( self, fragment: Union[FragmentDefinitionNode, InlineFragmentNode], type_: GraphQLObjectType, ) -> bool: """Determine if a fragment is applicable to the given type.""" type_condition_node = fragment.type_condition if not type_conditio...
[ "def", "does_fragment_condition_match", "(", "self", ",", "fragment", ":", "Union", "[", "FragmentDefinitionNode", ",", "InlineFragmentNode", "]", ",", "type_", ":", "GraphQLObjectType", ",", ")", "->", "bool", ":", "type_condition_node", "=", "fragment", ".", "ty...
Determine if a fragment is applicable to the given type.
[ "Determine", "if", "a", "fragment", "is", "applicable", "to", "the", "given", "type", "." ]
python
train
39.411765
AnalogJ/lexicon
lexicon/providers/localzone.py
https://github.com/AnalogJ/lexicon/blob/9330b871988753cad44fe2876a217b4c67b1fa0e/lexicon/providers/localzone.py#L40-L58
def _create_record(self, rtype, name, content): """ Create a resource record. If a record already exists with the same content, do nothing. """ result = False name = self._relative_name(name) ttl = None # TODO: shoud assert that this is an int if ...
[ "def", "_create_record", "(", "self", ",", "rtype", ",", "name", ",", "content", ")", ":", "result", "=", "False", "name", "=", "self", ".", "_relative_name", "(", "name", ")", "ttl", "=", "None", "# TODO: shoud assert that this is an int", "if", "self", "."...
Create a resource record. If a record already exists with the same content, do nothing.
[ "Create", "a", "resource", "record", ".", "If", "a", "record", "already", "exists", "with", "the", "same", "content", "do", "nothing", "." ]
python
train
32.421053
ihgazni2/edict
edict/edict.py
https://github.com/ihgazni2/edict/blob/44a08ccc10b196aa3854619b4c51ddb246778a34/edict/edict.py#L2037-L2074
def get_vndmat_attr(d,keypath,attr,**kwargs): ''' get_vndmat_attr(d,['x'],'lsib_path',path2keypath=True) get_vndmat_attr(d,['t'],'lsib_path',path2keypath=True) get_vndmat_attr(d,['u'],'lsib_path',path2keypath=True) get_vndmat_attr(d,['y'],'lsib_path',path2keypath=True) ''' kt...
[ "def", "get_vndmat_attr", "(", "d", ",", "keypath", ",", "attr", ",", "*", "*", "kwargs", ")", ":", "kt", ",", "vn", "=", "_d2kvmatrix", "(", "d", ")", "kdmat", "=", "_scankm", "(", "kt", ")", "ltree", "=", "elel", ".", "ListTree", "(", "vn", ")"...
get_vndmat_attr(d,['x'],'lsib_path',path2keypath=True) get_vndmat_attr(d,['t'],'lsib_path',path2keypath=True) get_vndmat_attr(d,['u'],'lsib_path',path2keypath=True) get_vndmat_attr(d,['y'],'lsib_path',path2keypath=True)
[ "get_vndmat_attr", "(", "d", "[", "x", "]", "lsib_path", "path2keypath", "=", "True", ")", "get_vndmat_attr", "(", "d", "[", "t", "]", "lsib_path", "path2keypath", "=", "True", ")", "get_vndmat_attr", "(", "d", "[", "u", "]", "lsib_path", "path2keypath", "...
python
train
32.473684
apple/turicreate
src/unity/python/turicreate/toolkits/recommender/util.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/recommender/util.py#L1811-L1830
def export_coreml(self, filename): """ Export the model in Core ML format. Parameters ---------- filename: str A valid filename where the model can be saved. Examples -------- >>> model.export_coreml('myModel.mlmodel') """ print...
[ "def", "export_coreml", "(", "self", ",", "filename", ")", ":", "print", "(", "'This model is exported as a custom Core ML model. In order to use it in your\\n'", "'application, you must also include \"libRecommender.dylib\". For additional\\n'", "'details see:\\n'", "'https://apple.github...
Export the model in Core ML format. Parameters ---------- filename: str A valid filename where the model can be saved. Examples -------- >>> model.export_coreml('myModel.mlmodel')
[ "Export", "the", "model", "in", "Core", "ML", "format", "." ]
python
train
34.5
csirtgadgets/csirtgsdk-py
csirtgsdk/client/http.py
https://github.com/csirtgadgets/csirtgsdk-py/blob/5a7ed9c5e6fa27170366ecbdef710dc80d537dc2/csirtgsdk/client/http.py#L119-L135
def _post(self, uri, data): """ HTTP POST function :param uri: REST endpoint to POST to :param data: list of dicts to be passed to the endpoint :return: list of dicts, usually will be a list of objects or id's Example: ret = cli.post('/indicators', { 'indica...
[ "def", "_post", "(", "self", ",", "uri", ",", "data", ")", ":", "if", "not", "uri", ".", "startswith", "(", "self", ".", "remote", ")", ":", "uri", "=", "'{}/{}'", ".", "format", "(", "self", ".", "remote", ",", "uri", ")", "self", ".", "logger",...
HTTP POST function :param uri: REST endpoint to POST to :param data: list of dicts to be passed to the endpoint :return: list of dicts, usually will be a list of objects or id's Example: ret = cli.post('/indicators', { 'indicator': 'example.com' })
[ "HTTP", "POST", "function" ]
python
train
30.588235
serhatbolsu/robotframework-appiumlibrary
AppiumLibrary/keywords/_keyevent.py
https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_keyevent.py#L9-L33
def press_keycode(self, keycode, metastate=None): """Sends a press of keycode to the device. Android only. Possible keycodes & meta states can be found in http://developer.android.com/reference/android/view/KeyEvent.html Meta state describe the pressed state of key modifiers s...
[ "def", "press_keycode", "(", "self", ",", "keycode", ",", "metastate", "=", "None", ")", ":", "driver", "=", "self", ".", "_current_application", "(", ")", "driver", ".", "press_keycode", "(", "keycode", ",", "metastate", ")" ]
Sends a press of keycode to the device. Android only. Possible keycodes & meta states can be found in http://developer.android.com/reference/android/view/KeyEvent.html Meta state describe the pressed state of key modifiers such as Shift, Ctrl & Alt keys. The Meta State is an i...
[ "Sends", "a", "press", "of", "keycode", "to", "the", "device", "." ]
python
train
34.08
CEA-COSMIC/ModOpt
modopt/opt/proximity.py
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/proximity.py#L219-L253
def _op_method(self, data, extra_factor=1.0): """Operator This method returns the input data after the singular values have been thresholded Parameters ---------- data : np.ndarray Input data array extra_factor : float Additional multipli...
[ "def", "_op_method", "(", "self", ",", "data", ",", "extra_factor", "=", "1.0", ")", ":", "# Update threshold with extra factor.", "threshold", "=", "self", ".", "thresh", "*", "extra_factor", "if", "self", ".", "lowr_type", "==", "'standard'", ":", "data_matrix...
Operator This method returns the input data after the singular values have been thresholded Parameters ---------- data : np.ndarray Input data array extra_factor : float Additional multiplication factor Returns ------- np...
[ "Operator" ]
python
train
28.971429
alecthomas/voluptuous
voluptuous/schema_builder.py
https://github.com/alecthomas/voluptuous/blob/36c8c11e2b7eb402c24866fa558473661ede9403/voluptuous/schema_builder.py#L305-L436
def _compile_mapping(self, schema, invalid_msg=None): """Create validator for given mapping.""" invalid_msg = invalid_msg or 'mapping value' # Keys that may be required all_required_keys = set(key for key in schema if key is not Extra and ...
[ "def", "_compile_mapping", "(", "self", ",", "schema", ",", "invalid_msg", "=", "None", ")", ":", "invalid_msg", "=", "invalid_msg", "or", "'mapping value'", "# Keys that may be required", "all_required_keys", "=", "set", "(", "key", "for", "key", "in", "schema", ...
Create validator for given mapping.
[ "Create", "validator", "for", "given", "mapping", "." ]
python
train
46.333333
kislyuk/aegea
aegea/packages/github3/session.py
https://github.com/kislyuk/aegea/blob/94957e9dba036eae3052e2662c208b259c08399a/aegea/packages/github3/session.py#L36-L48
def basic_auth(self, username, password): """Set the Basic Auth credentials on this Session. :param str username: Your GitHub username :param str password: Your GitHub password """ if not (username and password): return self.auth = (username, password) ...
[ "def", "basic_auth", "(", "self", ",", "username", ",", "password", ")", ":", "if", "not", "(", "username", "and", "password", ")", ":", "return", "self", ".", "auth", "=", "(", "username", ",", "password", ")", "# Disable token authentication", "self", "....
Set the Basic Auth credentials on this Session. :param str username: Your GitHub username :param str password: Your GitHub password
[ "Set", "the", "Basic", "Auth", "credentials", "on", "this", "Session", "." ]
python
train
30
VisualOps/cli
visualops/utils/dockervisops.py
https://github.com/VisualOps/cli/blob/e9ee9a804df0de3cce54be4c623528fd658838dc/visualops/utils/dockervisops.py#L431-L456
def kill(config, container, *args, **kwargs): ''' Kill a running container :type container: string :param container: The container id to kill :rtype: dict :returns: boolean ''' err = "Unknown" client = _get_client(config) try: dcontainer = _get_container_infos(config, c...
[ "def", "kill", "(", "config", ",", "container", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "err", "=", "\"Unknown\"", "client", "=", "_get_client", "(", "config", ")", "try", ":", "dcontainer", "=", "_get_container_infos", "(", "config", ",", ...
Kill a running container :type container: string :param container: The container id to kill :rtype: dict :returns: boolean
[ "Kill", "a", "running", "container" ]
python
train
27.192308