repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
minttu/tmc.py
tmc/__main__.py
https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/__main__.py#L403-L459
def update(course=False): """ Update the data of courses and or exercises from server. """ if course: with Spinner.context(msg="Updated course metadata.", waitmsg="Updating course metadata."): for course in api.get_courses(): old = None try: old = Course.get(Course.tid == course["id"]) except peewee.DoesNotExist: old = None if old: old.details_url = course["details_url"] old.save() continue Course.create(tid=course["id"], name=course["name"], details_url=course["details_url"]) else: selected = Course.get_selected() # with Spinner.context(msg="Updated exercise metadata.", # waitmsg="Updating exercise metadata."): print("Updating exercise data.") for exercise in api.get_exercises(selected): old = None try: old = Exercise.byid(exercise["id"]) except peewee.DoesNotExist: old = None if old is not None: old.name = exercise["name"] old.course = selected.id old.is_attempted = exercise["attempted"] old.is_completed = exercise["completed"] old.deadline = exercise.get("deadline") old.is_downloaded = os.path.isdir(old.path()) old.return_url = exercise["return_url"] old.zip_url = exercise["zip_url"] old.submissions_url = exercise["exercise_submissions_url"] old.save() download_exercise(old, update=True) else: ex = Exercise.create(tid=exercise["id"], name=exercise["name"], course=selected.id, is_attempted=exercise["attempted"], is_completed=exercise["completed"], deadline=exercise.get("deadline"), return_url=exercise["return_url"], zip_url=exercise["zip_url"], submissions_url=exercise[("exercise_" "submissions_" "url")]) ex.is_downloaded = os.path.isdir(ex.path()) ex.save()
[ "def", "update", "(", "course", "=", "False", ")", ":", "if", "course", ":", "with", "Spinner", ".", "context", "(", "msg", "=", "\"Updated course metadata.\"", ",", "waitmsg", "=", "\"Updating course metadata.\"", ")", ":", "for", "course", "in", "api", "."...
Update the data of courses and or exercises from server.
[ "Update", "the", "data", "of", "courses", "and", "or", "exercises", "from", "server", "." ]
python
valid
ampl/amplpy
amplpy/ampl.py
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L349-L381
def readAsync(self, fileName, callback, **kwargs): """ Interprets the specified file asynchronously, interpreting it as a model or a script file. As a side effect, it invalidates all entities (as the passed file can contain any arbitrary command); the lists of entities will be re-populated lazily (at first access). Args: fileName: Path to the file (Relative to the current working directory or absolute). callback: Callback to be executed when the file has been interpreted. """ if self._langext is not None: with open(fileName, 'r') as fin: newmodel = self._langext.translate(fin.read(), **kwargs) with open(fileName+'.translated', 'w') as fout: fout.write(newmodel) fileName += '.translated' def async_call(): self._lock.acquire() try: self._impl.read(fileName) self._errorhandler_wrapper.check() except Exception: self._lock.release() raise else: self._lock.release() callback.run() Thread(target=async_call).start()
[ "def", "readAsync", "(", "self", ",", "fileName", ",", "callback", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_langext", "is", "not", "None", ":", "with", "open", "(", "fileName", ",", "'r'", ")", "as", "fin", ":", "newmodel", "=", "sel...
Interprets the specified file asynchronously, interpreting it as a model or a script file. As a side effect, it invalidates all entities (as the passed file can contain any arbitrary command); the lists of entities will be re-populated lazily (at first access). Args: fileName: Path to the file (Relative to the current working directory or absolute). callback: Callback to be executed when the file has been interpreted.
[ "Interprets", "the", "specified", "file", "asynchronously", "interpreting", "it", "as", "a", "model", "or", "a", "script", "file", ".", "As", "a", "side", "effect", "it", "invalidates", "all", "entities", "(", "as", "the", "passed", "file", "can", "contain",...
python
train
pypa/pipenv
pipenv/vendor/delegator.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/delegator.py#L125-L135
def out(self): """Std/out output (cached)""" if self.__out is not None: return self.__out if self._uses_subprocess: self.__out = self.std_out.read() else: self.__out = self._pexpect_out return self.__out
[ "def", "out", "(", "self", ")", ":", "if", "self", ".", "__out", "is", "not", "None", ":", "return", "self", ".", "__out", "if", "self", ".", "_uses_subprocess", ":", "self", ".", "__out", "=", "self", ".", "std_out", ".", "read", "(", ")", "else",...
Std/out output (cached)
[ "Std", "/", "out", "output", "(", "cached", ")" ]
python
train
python-openxml/python-docx
docx/image/png.py
https://github.com/python-openxml/python-docx/blob/6756f6cd145511d3eb6d1d188beea391b1ddfd53/docx/image/png.py#L281-L291
def from_offset(cls, chunk_type, stream_rdr, offset): """ Return a _pHYsChunk instance containing the image resolution extracted from the pHYs chunk in *stream* at *offset*. """ horz_px_per_unit = stream_rdr.read_long(offset) vert_px_per_unit = stream_rdr.read_long(offset, 4) units_specifier = stream_rdr.read_byte(offset, 8) return cls( chunk_type, horz_px_per_unit, vert_px_per_unit, units_specifier )
[ "def", "from_offset", "(", "cls", ",", "chunk_type", ",", "stream_rdr", ",", "offset", ")", ":", "horz_px_per_unit", "=", "stream_rdr", ".", "read_long", "(", "offset", ")", "vert_px_per_unit", "=", "stream_rdr", ".", "read_long", "(", "offset", ",", "4", ")...
Return a _pHYsChunk instance containing the image resolution extracted from the pHYs chunk in *stream* at *offset*.
[ "Return", "a", "_pHYsChunk", "instance", "containing", "the", "image", "resolution", "extracted", "from", "the", "pHYs", "chunk", "in", "*", "stream", "*", "at", "*", "offset", "*", "." ]
python
train
clalancette/pycdlib
pycdlib/udf.py
https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/udf.py#L1336-L1375
def parse(self, data): # type: (bytes) -> None ''' Parse the passed in data into a UDF Partition Header Descriptor. Parameters: data - The data to parse. Returns: Nothing. ''' if self._initialized: raise pycdlibexception.PyCdlibInternalError('UDF Partition Header Descriptor already initialized') (unalloc_table_length, unalloc_table_pos, unalloc_bitmap_length, unalloc_bitmap_pos, part_integrity_table_length, part_integrity_table_pos, freed_table_length, freed_table_pos, freed_bitmap_length, freed_bitmap_pos, reserved_unused) = struct.unpack_from(self.FMT, data, 0) if unalloc_table_length != 0: raise pycdlibexception.PyCdlibInvalidISO('Partition Header unallocated table length not 0') if unalloc_table_pos != 0: raise pycdlibexception.PyCdlibInvalidISO('Partition Header unallocated table position not 0') if unalloc_bitmap_length != 0: raise pycdlibexception.PyCdlibInvalidISO('Partition Header unallocated bitmap length not 0') if unalloc_bitmap_pos != 0: raise pycdlibexception.PyCdlibInvalidISO('Partition Header unallocated bitmap position not 0') if part_integrity_table_length != 0: raise pycdlibexception.PyCdlibInvalidISO('Partition Header partition integrity length not 0') if part_integrity_table_pos != 0: raise pycdlibexception.PyCdlibInvalidISO('Partition Header partition integrity position not 0') if freed_table_length != 0: raise pycdlibexception.PyCdlibInvalidISO('Partition Header freed table length not 0') if freed_table_pos != 0: raise pycdlibexception.PyCdlibInvalidISO('Partition Header freed table position not 0') if freed_bitmap_length != 0: raise pycdlibexception.PyCdlibInvalidISO('Partition Header freed bitmap length not 0') if freed_bitmap_pos != 0: raise pycdlibexception.PyCdlibInvalidISO('Partition Header freed bitmap position not 0') self._initialized = True
[ "def", "parse", "(", "self", ",", "data", ")", ":", "# type: (bytes) -> None", "if", "self", ".", "_initialized", ":", "raise", "pycdlibexception", ".", "PyCdlibInternalError", "(", "'UDF Partition Header Descriptor already initialized'", ")", "(", "unalloc_table_length",...
Parse the passed in data into a UDF Partition Header Descriptor. Parameters: data - The data to parse. Returns: Nothing.
[ "Parse", "the", "passed", "in", "data", "into", "a", "UDF", "Partition", "Header", "Descriptor", "." ]
python
train
PGower/PyCanvas
pycanvas/apis/base.py
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/base.py#L164-L170
def _validate_iso8601_string(self, value): """Return the value or raise a ValueError if it is not a string in ISO8601 format.""" ISO8601_REGEX = r'(\d{4})-(\d{2})-(\d{2})T(\d{2})\:(\d{2})\:(\d{2})([+-](\d{2})\:(\d{2})|Z)' if re.match(ISO8601_REGEX, value): return value else: raise ValueError('{} must be in ISO8601 format.'.format(value))
[ "def", "_validate_iso8601_string", "(", "self", ",", "value", ")", ":", "ISO8601_REGEX", "=", "r'(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2})\\:(\\d{2})\\:(\\d{2})([+-](\\d{2})\\:(\\d{2})|Z)'", "if", "re", ".", "match", "(", "ISO8601_REGEX", ",", "value", ")", ":", "return", "valu...
Return the value or raise a ValueError if it is not a string in ISO8601 format.
[ "Return", "the", "value", "or", "raise", "a", "ValueError", "if", "it", "is", "not", "a", "string", "in", "ISO8601", "format", "." ]
python
train
postlund/pyatv
pyatv/interface.py
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/interface.py#L213-L221
def hash(self): """Create a unique hash for what is currently playing. The hash is based on title, artist, album and total time. It should always be the same for the same content, but it is not guaranteed. """ base = '{0}{1}{2}{3}'.format( self.title, self.artist, self.album, self.total_time) return hashlib.sha256(base.encode('utf-8')).hexdigest()
[ "def", "hash", "(", "self", ")", ":", "base", "=", "'{0}{1}{2}{3}'", ".", "format", "(", "self", ".", "title", ",", "self", ".", "artist", ",", "self", ".", "album", ",", "self", ".", "total_time", ")", "return", "hashlib", ".", "sha256", "(", "base"...
Create a unique hash for what is currently playing. The hash is based on title, artist, album and total time. It should always be the same for the same content, but it is not guaranteed.
[ "Create", "a", "unique", "hash", "for", "what", "is", "currently", "playing", "." ]
python
train
IndicoDataSolutions/IndicoIo-python
indicoio/image/image_recognition.py
https://github.com/IndicoDataSolutions/IndicoIo-python/blob/6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa/indicoio/image/image_recognition.py#L7-L29
def image_recognition(image, cloud=None, batch=False, api_key=None, version=None, **kwargs): """ Given an input image, returns a dictionary of image classifications with associated scores * Input can be either grayscale or rgb color and should either be a numpy array or nested list format. * Input data should be either uint8 0-255 range values or floating point between 0 and 1. * Large images (i.e. 1024x768+) are much bigger than needed, minaxis resizing will be done internally to 144 if needed. * For ideal performance, images should be square aspect ratio but non-square aspect ratios are supported as well. Example usage: .. code-block:: python >>> from indicoio import image_recognition >>> features = image_recognition(<filename>) :param image: The image to be analyzed. :type image: str :rtype: dict containing classifications """ image = data_preprocess(image, batch=batch, size=144, min_axis=True) url_params = {"batch": batch, "api_key": api_key, "version": version} return api_handler(image, cloud=cloud, api="imagerecognition", url_params=url_params, **kwargs)
[ "def", "image_recognition", "(", "image", ",", "cloud", "=", "None", ",", "batch", "=", "False", ",", "api_key", "=", "None", ",", "version", "=", "None", ",", "*", "*", "kwargs", ")", ":", "image", "=", "data_preprocess", "(", "image", ",", "batch", ...
Given an input image, returns a dictionary of image classifications with associated scores * Input can be either grayscale or rgb color and should either be a numpy array or nested list format. * Input data should be either uint8 0-255 range values or floating point between 0 and 1. * Large images (i.e. 1024x768+) are much bigger than needed, minaxis resizing will be done internally to 144 if needed. * For ideal performance, images should be square aspect ratio but non-square aspect ratios are supported as well. Example usage: .. code-block:: python >>> from indicoio import image_recognition >>> features = image_recognition(<filename>) :param image: The image to be analyzed. :type image: str :rtype: dict containing classifications
[ "Given", "an", "input", "image", "returns", "a", "dictionary", "of", "image", "classifications", "with", "associated", "scores" ]
python
train
Damgaard/PyImgur
pyimgur/__init__.py
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L1407-L1425
def send_message(self, body, subject=None, reply_to=None): """ Send a message to this user from the logged in user. :param body: The body of the message. :param subject: The subject of the message. Note that if the this message is a reply, then the subject of the first message will be used instead. :param reply_to: Messages can either be replies to other messages or start a new message thread. If this is None it will start a new message thread. If it's a Message object or message_id, then the new message will be sent as a reply to the reply_to message. """ url = self._imgur._base_url + "/3/message" parent_id = reply_to.id if isinstance(reply_to, Message) else reply_to payload = {'recipient': self.name, 'body': body, 'subject': subject, 'parent_id': parent_id} self._imgur._send_request(url, params=payload, needs_auth=True, method='POST')
[ "def", "send_message", "(", "self", ",", "body", ",", "subject", "=", "None", ",", "reply_to", "=", "None", ")", ":", "url", "=", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/message\"", "parent_id", "=", "reply_to", ".", "id", "if", "isinstance",...
Send a message to this user from the logged in user. :param body: The body of the message. :param subject: The subject of the message. Note that if the this message is a reply, then the subject of the first message will be used instead. :param reply_to: Messages can either be replies to other messages or start a new message thread. If this is None it will start a new message thread. If it's a Message object or message_id, then the new message will be sent as a reply to the reply_to message.
[ "Send", "a", "message", "to", "this", "user", "from", "the", "logged", "in", "user", "." ]
python
train
diux-dev/ncluster
ncluster/util.py
https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/util.py#L23-L28
def now_micros(absolute=False) -> int: """Return current micros since epoch as integer.""" micros = int(time.time() * 1e6) if absolute: return micros return micros - EPOCH_MICROS
[ "def", "now_micros", "(", "absolute", "=", "False", ")", "->", "int", ":", "micros", "=", "int", "(", "time", ".", "time", "(", ")", "*", "1e6", ")", "if", "absolute", ":", "return", "micros", "return", "micros", "-", "EPOCH_MICROS" ]
Return current micros since epoch as integer.
[ "Return", "current", "micros", "since", "epoch", "as", "integer", "." ]
python
train
joferkington/mplstereonet
mplstereonet/stereonet_math.py
https://github.com/joferkington/mplstereonet/blob/f6d78ca49807915d4223e864e12bb24d497cc2d6/mplstereonet/stereonet_math.py#L382-L437
def fisher_stats(lons, lats, conf=95): """ Returns the resultant vector from a series of longitudes and latitudes. If a confidence is set the function additionally returns the opening angle of the confidence small circle (Fisher, 19..) and the dispersion factor (kappa). Parameters ---------- lons : array-like A sequence of longitudes (in radians) lats : array-like A sequence of latitudes (in radians) conf : confidence value The confidence used for the calculation (float). Defaults to None. Returns ------- mean vector: tuple The point that lies in the center of a set of vectors. (Longitude, Latitude) in radians. If 1 vector is passed to the function it returns two None-values. For more than one vector the following 3 values are returned as a tuple: r_value: float The magnitude of the resultant vector (between 0 and 1) This represents the degree of clustering in the data. angle: float The opening angle of the small circle that corresponds to confidence of the calculated direction. kappa: float A measure for the amount of dispersion of a group of layers. For one vector the factor is undefined. Approaches infinity for nearly parallel vectors and zero for highly dispersed vectors. """ xyz = sph2cart(lons, lats) xyz = np.vstack(xyz).T mean_vec = xyz.mean(axis=0) r_value = np.linalg.norm(mean_vec) num = xyz.shape[0] mean_vec = cart2sph(*mean_vec) if num > 1: p = (100.0 - conf) / 100.0 vector_sum = xyz.sum(axis=0) result_vect = np.sqrt(np.sum(np.square(vector_sum))) fract1 = (num - result_vect) / result_vect fract3 = 1.0 / (num - 1.0) angle = np.arccos(1 - fract1 * ((1 / p) ** fract3 - 1)) angle = np.degrees(angle) kappa = (num - 1.0) / (num - result_vect) return mean_vec, (r_value, angle, kappa) else: return None, None
[ "def", "fisher_stats", "(", "lons", ",", "lats", ",", "conf", "=", "95", ")", ":", "xyz", "=", "sph2cart", "(", "lons", ",", "lats", ")", "xyz", "=", "np", ".", "vstack", "(", "xyz", ")", ".", "T", "mean_vec", "=", "xyz", ".", "mean", "(", "axi...
Returns the resultant vector from a series of longitudes and latitudes. If a confidence is set the function additionally returns the opening angle of the confidence small circle (Fisher, 19..) and the dispersion factor (kappa). Parameters ---------- lons : array-like A sequence of longitudes (in radians) lats : array-like A sequence of latitudes (in radians) conf : confidence value The confidence used for the calculation (float). Defaults to None. Returns ------- mean vector: tuple The point that lies in the center of a set of vectors. (Longitude, Latitude) in radians. If 1 vector is passed to the function it returns two None-values. For more than one vector the following 3 values are returned as a tuple: r_value: float The magnitude of the resultant vector (between 0 and 1) This represents the degree of clustering in the data. angle: float The opening angle of the small circle that corresponds to confidence of the calculated direction. kappa: float A measure for the amount of dispersion of a group of layers. For one vector the factor is undefined. Approaches infinity for nearly parallel vectors and zero for highly dispersed vectors.
[ "Returns", "the", "resultant", "vector", "from", "a", "series", "of", "longitudes", "and", "latitudes", ".", "If", "a", "confidence", "is", "set", "the", "function", "additionally", "returns", "the", "opening", "angle", "of", "the", "confidence", "small", "cir...
python
train
milesgranger/gap_statistic
gap_statistic/optimalK.py
https://github.com/milesgranger/gap_statistic/blob/146f868febfac37823114e87819df5e8bfc16ac8/gap_statistic/optimalK.py#L129-L135
def _process_with_rust(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, cluster_array: np.ndarray): """ Process gap stat using pure rust """ from gap_statistic.rust import gapstat for label, gap_value in gapstat.optimal_k(X, list(cluster_array)): yield (gap_value, label)
[ "def", "_process_with_rust", "(", "self", ",", "X", ":", "Union", "[", "pd", ".", "DataFrame", ",", "np", ".", "ndarray", "]", ",", "n_refs", ":", "int", ",", "cluster_array", ":", "np", ".", "ndarray", ")", ":", "from", "gap_statistic", ".", "rust", ...
Process gap stat using pure rust
[ "Process", "gap", "stat", "using", "pure", "rust" ]
python
train
camptocamp/Studio
studio/controllers/error.py
https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/controllers/error.py#L41-L49
def document(self): """Render the error document""" resp = request.environ.get('pylons.original_response') content = literal(resp.body) or cgi.escape(request.GET.get('message')) page = error_document_template % \ dict(prefix=request.environ.get('SCRIPT_NAME', ''), code=cgi.escape(request.GET.get('code', str(resp.status_int))), message=content) return page
[ "def", "document", "(", "self", ")", ":", "resp", "=", "request", ".", "environ", ".", "get", "(", "'pylons.original_response'", ")", "content", "=", "literal", "(", "resp", ".", "body", ")", "or", "cgi", ".", "escape", "(", "request", ".", "GET", ".",...
Render the error document
[ "Render", "the", "error", "document" ]
python
train
fermiPy/fermipy
fermipy/jobs/target_collect.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/target_collect.py#L344-L389
def build_job_configs(self, args): """Hook to build job configurations """ job_configs = {} ttype = args['ttype'] (targets_yaml, sim) = NAME_FACTORY.resolve_targetfile( args, require_sim_name=True) if targets_yaml is None: return job_configs write_full = args['write_full'] targets = load_yaml(targets_yaml) base_config = dict(config=args['config'], nsims=args['nsims'], seed=args['seed']) first = args['seed'] last = first + args['nsims'] - 1 for target_name, profile_list in targets.items(): for profile in profile_list: full_key = "%s:%s:%s" % (target_name, profile, sim) name_keys = dict(target_type=ttype, target_name=target_name, sim_name=sim, profile=profile, fullpath=True) sed_file = NAME_FACTORY.sim_sedfile(**name_keys) outfile = sed_file.replace( '_SEED.fits', '_collected_%06i_%06i.fits' % (first, last)) logfile = make_nfs_path(outfile.replace('.fits', '.log')) if not write_full: outfile = None summaryfile = sed_file.replace( '_SEED.fits', '_summary_%06i_%06i.fits' % (first, last)) job_config = base_config.copy() job_config.update(dict(sed_file=sed_file, outfile=outfile, summaryfile=summaryfile, logfile=logfile)) job_configs[full_key] = job_config return job_configs
[ "def", "build_job_configs", "(", "self", ",", "args", ")", ":", "job_configs", "=", "{", "}", "ttype", "=", "args", "[", "'ttype'", "]", "(", "targets_yaml", ",", "sim", ")", "=", "NAME_FACTORY", ".", "resolve_targetfile", "(", "args", ",", "require_sim_na...
Hook to build job configurations
[ "Hook", "to", "build", "job", "configurations" ]
python
train
CalebBell/fluids
fluids/geometry.py
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/geometry.py#L1336-L1458
def V_from_h(h, D, L, horizontal=True, sideA=None, sideB=None, sideA_a=0, sideB_a=0, sideA_f=None, sideA_k=None, sideB_f=None, sideB_k=None): r'''Calculates partially full volume of a vertical or horizontal tank with different head types according to [1]_. Parameters ---------- h : float Height of the liquid in the tank, [m] D : float Diameter of the cylindrical section of the tank, [m] L : float Length of the main cylindrical section of the tank, [m] horizontal : bool, optional Whether or not the tank is a horizontal or vertical tank sideA : string, optional The left (or bottom for vertical) head of the tank's type; one of [None, 'conical', 'ellipsoidal', 'torispherical', 'guppy', 'spherical']. sideB : string, optional The right (or top for vertical) head of the tank's type; one of [None, 'conical', 'ellipsoidal', 'torispherical', 'guppy', 'spherical']. sideA_a : float, optional The distance the head as specified by sideA extends down or to the left from the main cylindrical section, [m] sideB_a : float, optional The distance the head as specified by sideB extends up or to the right from the main cylindrical section, [m] sideA_f : float, optional Dish-radius parameter for side A; fD = dish radius [1/m] sideA_k : float, optional knuckle-radius parameter for side A; kD = knuckle radius [1/m] sideB_f : float, optional Dish-radius parameter for side B; fD = dish radius [1/m] sideB_k : float, optional knuckle-radius parameter for side B; kD = knuckle radius [1/m] Returns ------- V : float Volume up to h [m^3] Examples -------- >>> V_from_h(h=7, D=1.5, L=5., horizontal=False, sideA='conical', ... sideB='conical', sideA_a=2., sideB_a=1.) 10.013826583317465 References ---------- .. [1] Jones, D. "Compute Fluid Volumes in Vertical Tanks." Chemical Processing. December 18, 2003. http://www.chemicalprocessing.com/articles/2003/193/ ''' if sideA not in [None, 'conical', 'ellipsoidal', 'torispherical', 'spherical', 'guppy']: raise Exception('Unspoorted head type for side A') if sideB not in [None, 'conical', 'ellipsoidal', 'torispherical', 'spherical', 'guppy']: raise Exception('Unspoorted head type for side B') R = D/2. V = 0 if horizontal: # Conical case if sideA == 'conical': V += V_horiz_conical(D, L, sideA_a, h, headonly=True) if sideB == 'conical': V += V_horiz_conical(D, L, sideB_a, h, headonly=True) # Elliosoidal case if sideA == 'ellipsoidal': V += V_horiz_ellipsoidal(D, L, sideA_a, h, headonly=True) if sideB == 'ellipsoidal': V += V_horiz_ellipsoidal(D, L, sideB_a, h, headonly=True) # Guppy case if sideA == 'guppy': V += V_horiz_guppy(D, L, sideA_a, h, headonly=True) if sideB == 'guppy': V += V_horiz_guppy(D, L, sideB_a, h, headonly=True) # Spherical case if sideA == 'spherical': V += V_horiz_spherical(D, L, sideA_a, h, headonly=True) if sideB == 'spherical': V += V_horiz_spherical(D, L, sideB_a, h, headonly=True) # Torispherical case if sideA == 'torispherical': V += V_horiz_torispherical(D, L, sideA_f, sideA_k, h, headonly=True) if sideB == 'torispherical': V += V_horiz_torispherical(D, L, sideB_f, sideB_k, h, headonly=True) if h > D: # Must be before Af, which will raise a domain error raise Exception('Input height is above top of tank') Af = R**2*acos((R-h)/R) - (R-h)*(2*R*h - h**2)**0.5 V += L*Af else: # Bottom head if sideA in ['conical', 'ellipsoidal', 'torispherical', 'spherical']: if sideA == 'conical': V += V_vertical_conical(D, sideA_a, h=min(sideA_a, h)) if sideA == 'ellipsoidal': V += V_vertical_ellipsoidal(D, sideA_a, h=min(sideA_a, h)) if sideA == 'spherical': V += V_vertical_spherical(D, sideA_a, h=min(sideA_a, h)) if sideA == 'torispherical': V += V_vertical_torispherical(D, sideA_f, sideA_k, h=min(sideA_a, h)) # Cylindrical section if h >= sideA_a + L: V += pi/4*D**2*L # All middle elif h > sideA_a: V += pi/4*D**2*(h - sideA_a) # Partial middle # Top head if h > sideA_a + L: h2 = sideB_a - (h - sideA_a - L) if sideB == 'conical': V += V_vertical_conical(D, sideB_a, h=sideB_a) V -= V_vertical_conical(D, sideB_a, h=h2) if sideB == 'ellipsoidal': V += V_vertical_ellipsoidal(D, sideB_a, h=sideB_a) V -= V_vertical_ellipsoidal(D, sideB_a, h=h2) if sideB == 'spherical': V += V_vertical_spherical(D, sideB_a, h=sideB_a) V -= V_vertical_spherical(D, sideB_a, h=h2) if sideB == 'torispherical': V += V_vertical_torispherical(D, sideB_f, sideB_k, h=sideB_a) V -= V_vertical_torispherical(D, sideB_f, sideB_k, h=h2) if h > L + sideA_a + sideB_a: raise Exception('Input height is above top of tank') return V
[ "def", "V_from_h", "(", "h", ",", "D", ",", "L", ",", "horizontal", "=", "True", ",", "sideA", "=", "None", ",", "sideB", "=", "None", ",", "sideA_a", "=", "0", ",", "sideB_a", "=", "0", ",", "sideA_f", "=", "None", ",", "sideA_k", "=", "None", ...
r'''Calculates partially full volume of a vertical or horizontal tank with different head types according to [1]_. Parameters ---------- h : float Height of the liquid in the tank, [m] D : float Diameter of the cylindrical section of the tank, [m] L : float Length of the main cylindrical section of the tank, [m] horizontal : bool, optional Whether or not the tank is a horizontal or vertical tank sideA : string, optional The left (or bottom for vertical) head of the tank's type; one of [None, 'conical', 'ellipsoidal', 'torispherical', 'guppy', 'spherical']. sideB : string, optional The right (or top for vertical) head of the tank's type; one of [None, 'conical', 'ellipsoidal', 'torispherical', 'guppy', 'spherical']. sideA_a : float, optional The distance the head as specified by sideA extends down or to the left from the main cylindrical section, [m] sideB_a : float, optional The distance the head as specified by sideB extends up or to the right from the main cylindrical section, [m] sideA_f : float, optional Dish-radius parameter for side A; fD = dish radius [1/m] sideA_k : float, optional knuckle-radius parameter for side A; kD = knuckle radius [1/m] sideB_f : float, optional Dish-radius parameter for side B; fD = dish radius [1/m] sideB_k : float, optional knuckle-radius parameter for side B; kD = knuckle radius [1/m] Returns ------- V : float Volume up to h [m^3] Examples -------- >>> V_from_h(h=7, D=1.5, L=5., horizontal=False, sideA='conical', ... sideB='conical', sideA_a=2., sideB_a=1.) 10.013826583317465 References ---------- .. [1] Jones, D. "Compute Fluid Volumes in Vertical Tanks." Chemical Processing. December 18, 2003. http://www.chemicalprocessing.com/articles/2003/193/
[ "r", "Calculates", "partially", "full", "volume", "of", "a", "vertical", "or", "horizontal", "tank", "with", "different", "head", "types", "according", "to", "[", "1", "]", "_", "." ]
python
train
ktbyers/netmiko
netmiko/fortinet/fortinet_ssh.py
https://github.com/ktbyers/netmiko/blob/54e6116c0b4664de2123081937e0a9a27bdfdfea/netmiko/fortinet/fortinet_ssh.py#L27-L62
def disable_paging(self, delay_factor=1): """Disable paging is only available with specific roles so it may fail.""" check_command = "get system status | grep Virtual" output = self.send_command_timing(check_command) self.allow_disable_global = True self.vdoms = False self._output_mode = "more" if "Virtual domain configuration: enable" in output: self.vdoms = True vdom_additional_command = "config global" output = self.send_command_timing(vdom_additional_command, delay_factor=2) if "Command fail" in output: self.allow_disable_global = False self.remote_conn.close() self.establish_connection(width=100, height=1000) new_output = "" if self.allow_disable_global: self._retrieve_output_mode() disable_paging_commands = [ "config system console", "set output standard", "end", ] # There is an extra 'end' required if in multi-vdoms are enabled if self.vdoms: disable_paging_commands.append("end") outputlist = [ self.send_command_timing(command, delay_factor=2) for command in disable_paging_commands ] # Should test output is valid new_output = self.RETURN.join(outputlist) return output + new_output
[ "def", "disable_paging", "(", "self", ",", "delay_factor", "=", "1", ")", ":", "check_command", "=", "\"get system status | grep Virtual\"", "output", "=", "self", ".", "send_command_timing", "(", "check_command", ")", "self", ".", "allow_disable_global", "=", "True...
Disable paging is only available with specific roles so it may fail.
[ "Disable", "paging", "is", "only", "available", "with", "specific", "roles", "so", "it", "may", "fail", "." ]
python
train
inveniosoftware-contrib/invenio-classifier
invenio_classifier/reader.py
https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/reader.py#L428-L468
def refreshCompositeOf(self, single_keywords, composite_keywords, store=None, namespace=None): """Re-check sub-parts of this keyword. This should be called after the whole RDF was processed, because it is using a cache of single keywords and if that one is incomplete, you will not identify all parts. """ def _get_ckw_components(new_vals, label): if label in single_keywords: new_vals.append(single_keywords[label]) elif ('Composite.%s' % label) in composite_keywords: for l in composite_keywords['Composite.{0}'.format(label)].compositeof: # noqa _get_ckw_components(new_vals, l) elif label in composite_keywords: for l in composite_keywords[label].compositeof: _get_ckw_components(new_vals, l) else: # One single or composite keyword is missing from the taxonomy. # This is due to an error in the taxonomy description. message = "The composite term \"%s\""\ " should be made of single keywords,"\ " but at least one is missing." % self.id if store is not None: message += "Needed components: %s"\ % list(store.objects(self.id, namespace["compositeOf"])) message += " Missing is: %s" % label raise TaxonomyError(message) if self.compositeof: new_vals = [] try: for label in self.compositeof: _get_ckw_components(new_vals, label) self.compositeof = new_vals except TaxonomyError as err: # the composites will be empty # (better than to have confusing, partial matches) self.compositeof = [] current_app.logger.error(err)
[ "def", "refreshCompositeOf", "(", "self", ",", "single_keywords", ",", "composite_keywords", ",", "store", "=", "None", ",", "namespace", "=", "None", ")", ":", "def", "_get_ckw_components", "(", "new_vals", ",", "label", ")", ":", "if", "label", "in", "sing...
Re-check sub-parts of this keyword. This should be called after the whole RDF was processed, because it is using a cache of single keywords and if that one is incomplete, you will not identify all parts.
[ "Re", "-", "check", "sub", "-", "parts", "of", "this", "keyword", "." ]
python
train
StackStorm/pybind
pybind/slxos/v17s_1_02/overlay/access_list/type/vxlan/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/overlay/access_list/type/vxlan/__init__.py#L127-L148
def _set_extended(self, v, load=False): """ Setter method for extended, mapped from YANG variable /overlay/access_list/type/vxlan/extended (list) If this variable is read-only (config: false) in the source YANG file, then _set_extended is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_extended() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("ext_user_acl_name",extended.extended, yang_name="extended", rest_name="extended", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='ext-user-acl-name', extensions={u'tailf-common': {u'info': u'extended <user-acl-name>', u'cli-sequence-commands': None, u'callpoint': u'VxlanVisibilityExtendedCallpoint', u'cli-mode-name': u'config-overlay-vxlan-ext-$(ext-user-acl-name)'}}), is_container='list', yang_name="extended", rest_name="extended", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'extended <user-acl-name>', u'cli-sequence-commands': None, u'callpoint': u'VxlanVisibilityExtendedCallpoint', u'cli-mode-name': u'config-overlay-vxlan-ext-$(ext-user-acl-name)'}}, namespace='urn:brocade.com:mgmt:brocade-vxlan-visibility', defining_module='brocade-vxlan-visibility', yang_type='list', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """extended must be of a type compatible with list""", 'defined-type': "list", 'generated-type': """YANGDynClass(base=YANGListType("ext_user_acl_name",extended.extended, yang_name="extended", rest_name="extended", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='ext-user-acl-name', extensions={u'tailf-common': {u'info': u'extended <user-acl-name>', u'cli-sequence-commands': None, u'callpoint': u'VxlanVisibilityExtendedCallpoint', u'cli-mode-name': u'config-overlay-vxlan-ext-$(ext-user-acl-name)'}}), is_container='list', yang_name="extended", rest_name="extended", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'extended <user-acl-name>', u'cli-sequence-commands': None, u'callpoint': u'VxlanVisibilityExtendedCallpoint', u'cli-mode-name': u'config-overlay-vxlan-ext-$(ext-user-acl-name)'}}, namespace='urn:brocade.com:mgmt:brocade-vxlan-visibility', defining_module='brocade-vxlan-visibility', yang_type='list', is_config=True)""", }) self.__extended = t if hasattr(self, '_set'): self._set()
[ "def", "_set_extended", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base"...
Setter method for extended, mapped from YANG variable /overlay/access_list/type/vxlan/extended (list) If this variable is read-only (config: false) in the source YANG file, then _set_extended is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_extended() directly.
[ "Setter", "method", "for", "extended", "mapped", "from", "YANG", "variable", "/", "overlay", "/", "access_list", "/", "type", "/", "vxlan", "/", "extended", "(", "list", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "false...
python
train
inveniosoftware-attic/invenio-upgrader
invenio_upgrader/engine.py
https://github.com/inveniosoftware-attic/invenio-upgrader/blob/cee4bcb118515463ecf6de1421642007f79a9fcd/invenio_upgrader/engine.py#L211-L227
def _check_errors(self, errors, prefix): """Check for errors and possible raise and format an error message. :param errors: List of error messages. :param prefix: str, Prefix message for error messages """ args = [] for uid, messages in errors: error_msg = [] error_msg.append(prefix % uid) for msg in messages: error_msg.append(" (-) %s" % msg) args.append("\n".join(error_msg)) if args: raise RuntimeError(*args)
[ "def", "_check_errors", "(", "self", ",", "errors", ",", "prefix", ")", ":", "args", "=", "[", "]", "for", "uid", ",", "messages", "in", "errors", ":", "error_msg", "=", "[", "]", "error_msg", ".", "append", "(", "prefix", "%", "uid", ")", "for", "...
Check for errors and possible raise and format an error message. :param errors: List of error messages. :param prefix: str, Prefix message for error messages
[ "Check", "for", "errors", "and", "possible", "raise", "and", "format", "an", "error", "message", "." ]
python
train
inveniosoftware-contrib/invenio-groups
invenio_groups/models.py
https://github.com/inveniosoftware-contrib/invenio-groups/blob/109481d6b02701db00b72223dd4a65e167c589a6/invenio_groups/models.py#L562-L570
def _filter(cls, query, state=MembershipState.ACTIVE, eager=None): """Filter a query result.""" query = query.filter_by(state=state) eager = eager or [] for field in eager: query = query.options(joinedload(field)) return query
[ "def", "_filter", "(", "cls", ",", "query", ",", "state", "=", "MembershipState", ".", "ACTIVE", ",", "eager", "=", "None", ")", ":", "query", "=", "query", ".", "filter_by", "(", "state", "=", "state", ")", "eager", "=", "eager", "or", "[", "]", "...
Filter a query result.
[ "Filter", "a", "query", "result", "." ]
python
valid
django-haystack/pysolr
pysolr.py
https://github.com/django-haystack/pysolr/blob/ee28b39324fa21a99842d297e313c1759d8adbd2/pysolr.py#L700-L720
def _is_null_value(self, value): """ Check if a given value is ``null``. Criteria for this is based on values that shouldn't be included in the Solr ``add`` request at all. """ if value is None: return True if IS_PY3: # Python 3.X if isinstance(value, str) and len(value) == 0: return True else: # Python 2.X if isinstance(value, basestring) and len(value) == 0: # NOQA: F821 return True # TODO: This should probably be removed when solved in core Solr level? return False
[ "def", "_is_null_value", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "return", "True", "if", "IS_PY3", ":", "# Python 3.X", "if", "isinstance", "(", "value", ",", "str", ")", "and", "len", "(", "value", ")", "==", "0", ":",...
Check if a given value is ``null``. Criteria for this is based on values that shouldn't be included in the Solr ``add`` request at all.
[ "Check", "if", "a", "given", "value", "is", "null", "." ]
python
train
markfinger/assembla
assembla/api.py
https://github.com/markfinger/assembla/blob/967a77a5ba718df94f60e832b6e0cf14c72426aa/assembla/api.py#L42-L112
def _get_json(self, model, space=None, rel_path=None, extra_params=None, get_all=None): """ Base level method for fetching data from the API """ # Only API.spaces and API.event should not provide # the `space argument if space is None and model not in (Space, Event): raise Exception( 'In general, `API._get_json` should always ' 'be called with a `space` argument.' ) if not extra_params: extra_params = {} # Handle pagination for requests carrying large amounts of data extra_params['page'] = extra_params.get('page', 1) # Generate the url to hit url = '{0}/{1}/{2}.json?{3}'.format( settings.API_ROOT_PATH, settings.API_VERSION, rel_path or model.rel_path, urllib.urlencode(extra_params), ) # If the cache is being used and the url has been hit already if self.cache_responses and url in self.cache: response = self.cache[url] else: # Fetch the data headers = { 'X-Api-Key': self.key, 'X-Api-Secret': self.secret, } response = self.session.get(url=url, headers=headers) # If the cache is being used, update it if self.cache_responses: self.cache[url] = response if response.status_code == 200: # OK results = [] json_response = response.json() for obj in json_response: instance = model(data=obj) instance.api = self if space: instance.space = space results.append(instance) # If it looks like there are more pages to fetch, # try and fetch the next one per_page = extra_params.get('per_page', None) if ( get_all and per_page and len(json_response) and per_page == len(json_response) ): extra_params['page'] += 1 results = results + self._get_json(model, space, rel_path, extra_params, get_all=get_all) return results elif response.status_code == 204: # No Content return [] else: # Most likely a 404 Not Found raise Exception( 'Code {0} returned from `{1}`. Response text: "{2}".'.format( response.status_code, url, response.text ) )
[ "def", "_get_json", "(", "self", ",", "model", ",", "space", "=", "None", ",", "rel_path", "=", "None", ",", "extra_params", "=", "None", ",", "get_all", "=", "None", ")", ":", "# Only API.spaces and API.event should not provide", "# the `space argument", "if", ...
Base level method for fetching data from the API
[ "Base", "level", "method", "for", "fetching", "data", "from", "the", "API" ]
python
train
thefactory/marathon-python
marathon/client.py
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L498-L516
def list_tasks(self, app_id=None, **kwargs): """List running tasks, optionally filtered by app_id. :param str app_id: if passed, only show tasks for this application :param kwargs: arbitrary search filters :returns: list of tasks :rtype: list[:class:`marathon.models.task.MarathonTask`] """ response = self._do_request( 'GET', '/v2/apps/%s/tasks' % app_id if app_id else '/v2/tasks') tasks = self._parse_response( response, MarathonTask, is_list=True, resource_name='tasks') [setattr(t, 'app_id', app_id) for t in tasks if app_id and t.app_id is None] for k, v in kwargs.items(): tasks = [o for o in tasks if getattr(o, k) == v] return tasks
[ "def", "list_tasks", "(", "self", ",", "app_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "response", "=", "self", ".", "_do_request", "(", "'GET'", ",", "'/v2/apps/%s/tasks'", "%", "app_id", "if", "app_id", "else", "'/v2/tasks'", ")", "tasks", "=...
List running tasks, optionally filtered by app_id. :param str app_id: if passed, only show tasks for this application :param kwargs: arbitrary search filters :returns: list of tasks :rtype: list[:class:`marathon.models.task.MarathonTask`]
[ "List", "running", "tasks", "optionally", "filtered", "by", "app_id", "." ]
python
train
goldsmith/Wikipedia
wikipedia/wikipedia.py
https://github.com/goldsmith/Wikipedia/blob/2065c568502b19b8634241b47fd96930d1bf948d/wikipedia/wikipedia.py#L536-L553
def images(self): ''' List of URLs of images on the page. ''' if not getattr(self, '_images', False): self._images = [ page['imageinfo'][0]['url'] for page in self.__continued_query({ 'generator': 'images', 'gimlimit': 'max', 'prop': 'imageinfo', 'iiprop': 'url', }) if 'imageinfo' in page ] return self._images
[ "def", "images", "(", "self", ")", ":", "if", "not", "getattr", "(", "self", ",", "'_images'", ",", "False", ")", ":", "self", ".", "_images", "=", "[", "page", "[", "'imageinfo'", "]", "[", "0", "]", "[", "'url'", "]", "for", "page", "in", "self...
List of URLs of images on the page.
[ "List", "of", "URLs", "of", "images", "on", "the", "page", "." ]
python
train
ailionx/cloudflare-ddns
cloudflare_ddns/cloudflare.py
https://github.com/ailionx/cloudflare-ddns/blob/e4808b8314e447f69fab77b5bd3880846e59adbe/cloudflare_ddns/cloudflare.py#L90-L111
def setup_zone(self): """ Setup zone for current domain. It will also setup the dns records of the zone :return: """ # Initialize current zone zones_content = self.request(self.api_url, 'get') try: if len(self.domain.split('.')) == 3: domain = self.domain.split('.', 1)[1] else: domain = self.domain zone = [zone for zone in zones_content['result'] if zone['name'] == domain][0] except IndexError: raise ZoneNotFound('Cannot find zone information for the domain {domain}.' .format(domain=self.domain)) self.zone = zone # Initialize dns_records of current zone dns_content = self.request(self.api_url + zone['id'] + '/dns_records', 'get') self.dns_records = dns_content['result']
[ "def", "setup_zone", "(", "self", ")", ":", "# Initialize current zone", "zones_content", "=", "self", ".", "request", "(", "self", ".", "api_url", ",", "'get'", ")", "try", ":", "if", "len", "(", "self", ".", "domain", ".", "split", "(", "'.'", ")", "...
Setup zone for current domain. It will also setup the dns records of the zone :return:
[ "Setup", "zone", "for", "current", "domain", ".", "It", "will", "also", "setup", "the", "dns", "records", "of", "the", "zone", ":", "return", ":" ]
python
train
lsanomaly/lsanomaly
lsanomaly/__init__.py
https://github.com/lsanomaly/lsanomaly/blob/7680ccbd6eedc14ccdd84d11be56edb6f9fdca2e/lsanomaly/__init__.py#L30-L51
def pair_distance_centile(X, centile, max_pairs=5000): """ Calculate centiles of distances between random pairs in a dataset. This an alternative to the median kNN distance for setting the kernel length scale. """ N = X.shape[0] n_pairs = min(max_pairs, N**2) # randorder1 = np.random.permutation(N) # randorder2 = np.random.permutation(N) dists = np.zeros(n_pairs) for i in range(n_pairs): pair = np.random.randint(0, N, 2) pairdiff = X[pair[0], :]-X[pair[1], :] dists[i] = np.dot(pairdiff, pairdiff.T) dists.sort() out = dists[int(n_pairs*centile/100.)] return np.sqrt(out)
[ "def", "pair_distance_centile", "(", "X", ",", "centile", ",", "max_pairs", "=", "5000", ")", ":", "N", "=", "X", ".", "shape", "[", "0", "]", "n_pairs", "=", "min", "(", "max_pairs", ",", "N", "**", "2", ")", "# randorder1 = np.random.permutation(N)", "...
Calculate centiles of distances between random pairs in a dataset. This an alternative to the median kNN distance for setting the kernel length scale.
[ "Calculate", "centiles", "of", "distances", "between", "random", "pairs", "in", "a", "dataset", "." ]
python
train
neelkamath/hclib
hclib.py
https://github.com/neelkamath/hclib/blob/8678e7abe619796af85f219e280417cfa9a703f2/hclib.py#L117-L123
def _on_open(self, _): """Joins the hack.chat channel and starts pinging.""" nick = self._format_nick(self._nick, self._pwd) data = {"cmd": "join", "channel": self._channel, "nick": nick} self._send_packet(data) self._thread = True threading.Thread(target=self._ping).start()
[ "def", "_on_open", "(", "self", ",", "_", ")", ":", "nick", "=", "self", ".", "_format_nick", "(", "self", ".", "_nick", ",", "self", ".", "_pwd", ")", "data", "=", "{", "\"cmd\"", ":", "\"join\"", ",", "\"channel\"", ":", "self", ".", "_channel", ...
Joins the hack.chat channel and starts pinging.
[ "Joins", "the", "hack", ".", "chat", "channel", "and", "starts", "pinging", "." ]
python
train
greenbone/ospd
ospd/misc.py
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L444-L462
def target_to_ipv4_cidr(target): """ Attempt to return a IPv4 CIDR list from a target string. """ splitted = target.split('/') if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET, splitted[0]) block = int(splitted[1]) except (socket.error, ValueError): return None if block <= 0 or block > 30: return None start_value = int(binascii.hexlify(start_packed), 16) >> (32 - block) start_value = (start_value << (32 - block)) + 1 end_value = (start_value | (0xffffffff >> block)) - 1 start_packed = struct.pack('!I', start_value) end_packed = struct.pack('!I', end_value) return ipv4_range_to_list(start_packed, end_packed)
[ "def", "target_to_ipv4_cidr", "(", "target", ")", ":", "splitted", "=", "target", ".", "split", "(", "'/'", ")", "if", "len", "(", "splitted", ")", "!=", "2", ":", "return", "None", "try", ":", "start_packed", "=", "inet_pton", "(", "socket", ".", "AF_...
Attempt to return a IPv4 CIDR list from a target string.
[ "Attempt", "to", "return", "a", "IPv4", "CIDR", "list", "from", "a", "target", "string", "." ]
python
train
tensorflow/cleverhans
cleverhans/attacks/spsa.py
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/spsa.py#L350-L371
def _apply_gradients(self, grads, x, optim_state): """Refer to parent class documentation.""" new_x = [None] * len(x) new_optim_state = { "t": optim_state["t"] + 1., "m": [None] * len(x), "u": [None] * len(x) } t = new_optim_state["t"] for i in xrange(len(x)): g = grads[i] m_old = optim_state["m"][i] u_old = optim_state["u"][i] new_optim_state["m"][i] = ( self._beta1 * m_old + (1. - self._beta1) * g) new_optim_state["u"][i] = ( self._beta2 * u_old + (1. - self._beta2) * g * g) m_hat = new_optim_state["m"][i] / (1. - tf.pow(self._beta1, t)) u_hat = new_optim_state["u"][i] / (1. - tf.pow(self._beta2, t)) new_x[i] = ( x[i] - self._lr * m_hat / (tf.sqrt(u_hat) + self._epsilon)) return new_x, new_optim_state
[ "def", "_apply_gradients", "(", "self", ",", "grads", ",", "x", ",", "optim_state", ")", ":", "new_x", "=", "[", "None", "]", "*", "len", "(", "x", ")", "new_optim_state", "=", "{", "\"t\"", ":", "optim_state", "[", "\"t\"", "]", "+", "1.", ",", "\...
Refer to parent class documentation.
[ "Refer", "to", "parent", "class", "documentation", "." ]
python
train
briancappello/flask-unchained
flask_unchained/bundles/security/decorators/auth_required_same_user.py
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/decorators/auth_required_same_user.py#L9-L50
def auth_required_same_user(*args, **kwargs): """ Decorator for requiring an authenticated user to be the same as the user in the URL parameters. By default the user url parameter name to lookup is ``id``, but this can be customized by passing an argument:: @auth_require_same_user('user_id') @bp.route('/users/<int:user_id>/foo/<int:id>') def get(user_id, id): # do stuff Any keyword arguments are passed along to the @auth_required decorator, so roles can also be specified in the same was as it, eg:: @auth_required_same_user('user_id', role='ROLE_ADMIN') Aborts with ``HTTP 403: Forbidden`` if the user-check fails. """ auth_kwargs = {} user_id_parameter_name = 'id' if not (args and callable(args[0])): auth_kwargs = kwargs if args and isinstance(args[0], str): user_id_parameter_name = args[0] def wrapper(fn): @wraps(fn) @auth_required(**auth_kwargs) def decorated(*args, **kwargs): try: user_id = request.view_args[user_id_parameter_name] except KeyError: raise KeyError('Unable to find the user lookup parameter ' f'{user_id_parameter_name} in the url args') if not Permission(UserNeed(user_id)).can(): abort(HTTPStatus.FORBIDDEN) return fn(*args, **kwargs) return decorated if args and callable(args[0]): return wrapper(args[0]) return wrapper
[ "def", "auth_required_same_user", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "auth_kwargs", "=", "{", "}", "user_id_parameter_name", "=", "'id'", "if", "not", "(", "args", "and", "callable", "(", "args", "[", "0", "]", ")", ")", ":", "auth_kw...
Decorator for requiring an authenticated user to be the same as the user in the URL parameters. By default the user url parameter name to lookup is ``id``, but this can be customized by passing an argument:: @auth_require_same_user('user_id') @bp.route('/users/<int:user_id>/foo/<int:id>') def get(user_id, id): # do stuff Any keyword arguments are passed along to the @auth_required decorator, so roles can also be specified in the same was as it, eg:: @auth_required_same_user('user_id', role='ROLE_ADMIN') Aborts with ``HTTP 403: Forbidden`` if the user-check fails.
[ "Decorator", "for", "requiring", "an", "authenticated", "user", "to", "be", "the", "same", "as", "the", "user", "in", "the", "URL", "parameters", ".", "By", "default", "the", "user", "url", "parameter", "name", "to", "lookup", "is", "id", "but", "this", ...
python
train
crm416/semantic
semantic/numbers.py
https://github.com/crm416/semantic/blob/46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe/semantic/numbers.py#L124-L192
def parseFloat(self, words): """Convert a floating-point number described in words to a double. Supports two kinds of descriptions: those with a 'point' (e.g., "one point two five") and those with a fraction (e.g., "one and a quarter"). Args: words (str): Description of the floating-point number. Returns: A double representation of the words. """ def pointFloat(words): m = re.search(r'(.*) point (.*)', words) if m: whole = m.group(1) frac = m.group(2) total = 0.0 coeff = 0.10 for digit in frac.split(' '): total += coeff * self.parse(digit) coeff /= 10.0 return self.parseInt(whole) + total return None def fractionFloat(words): m = re.search(r'(.*) and (.*)', words) if m: whole = self.parseInt(m.group(1)) frac = m.group(2) # Replace plurals frac = re.sub(r'(\w+)s(\b)', '\g<1>\g<2>', frac) # Convert 'a' to 'one' (e.g., 'a third' to 'one third') frac = re.sub(r'(\b)a(\b)', '\g<1>one\g<2>', frac) split = frac.split(' ') # Split fraction into num (regular integer), denom (ordinal) num = split[:1] denom = split[1:] while denom: try: # Test for valid num, denom num_value = self.parse(' '.join(num)) denom_value = self.parse(' '.join(denom)) return whole + float(num_value) / denom_value except: # Add another word to num num += denom[:1] denom = denom[1:] return None # Extract "one point two five"-type float result = pointFloat(words) if result: return result # Extract "one and a quarter"-type float result = fractionFloat(words) if result: return result # Parse as integer return self.parseInt(words)
[ "def", "parseFloat", "(", "self", ",", "words", ")", ":", "def", "pointFloat", "(", "words", ")", ":", "m", "=", "re", ".", "search", "(", "r'(.*) point (.*)'", ",", "words", ")", "if", "m", ":", "whole", "=", "m", ".", "group", "(", "1", ")", "f...
Convert a floating-point number described in words to a double. Supports two kinds of descriptions: those with a 'point' (e.g., "one point two five") and those with a fraction (e.g., "one and a quarter"). Args: words (str): Description of the floating-point number. Returns: A double representation of the words.
[ "Convert", "a", "floating", "-", "point", "number", "described", "in", "words", "to", "a", "double", "." ]
python
train
saltstack/salt
salt/modules/boto_lambda.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_lambda.py#L448-L495
def update_function_code(FunctionName, ZipFile=None, S3Bucket=None, S3Key=None, S3ObjectVersion=None, Publish=False, region=None, key=None, keyid=None, profile=None): ''' Upload the given code to the named lambda function. Returns {updated: true} if the function was updated and returns {updated: False} if the function was not updated. CLI Example: .. code-block:: bash salt myminion boto_lamba.update_function_code my_function ZipFile=function.zip ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if ZipFile: if S3Bucket or S3Key or S3ObjectVersion: raise SaltInvocationError('Either ZipFile must be specified, or ' 'S3Bucket and S3Key must be provided.') r = conn.update_function_code(FunctionName=FunctionName, ZipFile=_filedata(ZipFile), Publish=Publish) else: if not S3Bucket or not S3Key: raise SaltInvocationError('Either ZipFile must be specified, or ' 'S3Bucket and S3Key must be provided.') args = { 'S3Bucket': S3Bucket, 'S3Key': S3Key, } if S3ObjectVersion: args['S3ObjectVersion'] = S3ObjectVersion r = conn.update_function_code(FunctionName=FunctionName, Publish=Publish, **args) if r: keys = ('FunctionName', 'Runtime', 'Role', 'Handler', 'CodeSha256', 'CodeSize', 'Description', 'Timeout', 'MemorySize', 'FunctionArn', 'LastModified', 'VpcConfig', 'Environment') return {'updated': True, 'function': dict([(k, r.get(k)) for k in keys])} else: log.warning('Function was not updated') return {'updated': False} except ClientError as e: return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "update_function_code", "(", "FunctionName", ",", "ZipFile", "=", "None", ",", "S3Bucket", "=", "None", ",", "S3Key", "=", "None", ",", "S3ObjectVersion", "=", "None", ",", "Publish", "=", "False", ",", "region", "=", "None", ",", "key", "=", "Non...
Upload the given code to the named lambda function. Returns {updated: true} if the function was updated and returns {updated: False} if the function was not updated. CLI Example: .. code-block:: bash salt myminion boto_lamba.update_function_code my_function ZipFile=function.zip
[ "Upload", "the", "given", "code", "to", "the", "named", "lambda", "function", "." ]
python
train
chengsoonong/wib
wib/cli.py
https://github.com/chengsoonong/wib/blob/ca701ed72cd9f23a8e887f72f36c0fb0af42ef70/wib/cli.py#L12-L29
def call(self, args, devnull=False): """Call other processes. args - list of command args devnull - whether to pipe stdout to /dev/null (or equivalent) """ if self.debug: click.echo(subprocess.list2cmdline(args)) click.confirm('Continue?', default=True, abort=True) try: kwargs = {} if devnull: # Pipe to /dev/null (or equivalent). kwargs['stderr'] = subprocess.STDOUT kwargs['stdout'] = self.FNULL ret_code = subprocess.call(args, **kwargs) except subprocess.CalledProcessError: return False return ret_code
[ "def", "call", "(", "self", ",", "args", ",", "devnull", "=", "False", ")", ":", "if", "self", ".", "debug", ":", "click", ".", "echo", "(", "subprocess", ".", "list2cmdline", "(", "args", ")", ")", "click", ".", "confirm", "(", "'Continue?'", ",", ...
Call other processes. args - list of command args devnull - whether to pipe stdout to /dev/null (or equivalent)
[ "Call", "other", "processes", ".", "args", "-", "list", "of", "command", "args", "devnull", "-", "whether", "to", "pipe", "stdout", "to", "/", "dev", "/", "null", "(", "or", "equivalent", ")" ]
python
train
jaywink/federation
federation/protocols/activitypub/protocol.py
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/activitypub/protocol.py#L69-L88
def receive( self, request: RequestType, user: UserType = None, sender_key_fetcher: Callable[[str], str] = None, skip_author_verification: bool = False) -> Tuple[str, dict]: """ Receive a request. For testing purposes, `skip_author_verification` can be passed. Authorship will not be verified. """ self.user = user self.get_contact_key = sender_key_fetcher self.payload = json.loads(decode_if_bytes(request.body)) self.request = request self.extract_actor() # Verify the message is from who it claims to be if not skip_author_verification: self.verify_signature() return self.actor, self.payload
[ "def", "receive", "(", "self", ",", "request", ":", "RequestType", ",", "user", ":", "UserType", "=", "None", ",", "sender_key_fetcher", ":", "Callable", "[", "[", "str", "]", ",", "str", "]", "=", "None", ",", "skip_author_verification", ":", "bool", "=...
Receive a request. For testing purposes, `skip_author_verification` can be passed. Authorship will not be verified.
[ "Receive", "a", "request", "." ]
python
train
ajslater/picopt
picopt/formats/comic.py
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/formats/comic.py#L117-L149
def comic_archive_compress(args): """ Called back by every optimization inside a comic archive. When they're all done it creates the new archive and cleans up. """ try: filename, old_format, settings, nag_about_gifs = args Settings.update(settings) tmp_dir = _get_archive_tmp_dir(filename) # archive into new filename new_filename = files.replace_ext(filename, _NEW_ARCHIVE_SUFFIX) _comic_archive_write_zipfile(new_filename, tmp_dir) # Cleanup tmpdir if os.path.isdir(tmp_dir): if Settings.verbose: print('.', end='') shutil.rmtree(tmp_dir) if Settings.verbose: print('done.') report_stats = files.cleanup_after_optimize( filename, new_filename, old_format, _CBZ_FORMAT) report_stats.nag_about_gifs = nag_about_gifs stats.report_saved(report_stats) return report_stats except Exception as exc: print(exc) traceback.print_exc(exc) raise exc
[ "def", "comic_archive_compress", "(", "args", ")", ":", "try", ":", "filename", ",", "old_format", ",", "settings", ",", "nag_about_gifs", "=", "args", "Settings", ".", "update", "(", "settings", ")", "tmp_dir", "=", "_get_archive_tmp_dir", "(", "filename", ")...
Called back by every optimization inside a comic archive. When they're all done it creates the new archive and cleans up.
[ "Called", "back", "by", "every", "optimization", "inside", "a", "comic", "archive", "." ]
python
train
iclab/centinel
centinel/primitives/headless_browser.py
https://github.com/iclab/centinel/blob/9a25dcf30c6a1db3c046f7ccb8ab8873e455c1a4/centinel/primitives/headless_browser.py#L281-L329
def run(self, input_files, url=None, verbose=0): """ run the headless browser with given input if url given, the proc will only run hlb with given url and ignore input_list. :param url: :param input_files: the name of the file in "index url" format. i.e. 1, www.facebook.com 1, www.google.com ... :param verbose: :return: """ if not url and not input_files: logging.warning("No input file") return {"error": "no inputs"} results = {} self.open_virtual_display() if verbose > 0: log_file = sys.stdout else: log_file = None # set up firefox driver self.binary = FirefoxBinary(os.path.join(self.cur_path, 'firefox/firefox'), log_file=log_file) self.profile = self.setup_profile() self.driver = webdriver.Firefox(firefox_profile=self.profile, firefox_binary=self.binary, timeout=60) self.driver.set_page_load_timeout(60) isfile = False if url: host, path = self.divide_url(url) results[url] = self.get(host, path) else: isfile = True for input_file in input_files.items(): logging.info("Testing input file %s..." % (input_file[0])) self.run_file(input_file, results) # foctor_core will quit the driver by itself so we only quit the driver when we don't use foctor core if not isfile: logging.info("Quit driver") self.driver.quit() self.close_virtual_display() logging.debug("Deleting har folder") shutil.rmtree(os.path.join(self.cur_path, 'har')) return results
[ "def", "run", "(", "self", ",", "input_files", ",", "url", "=", "None", ",", "verbose", "=", "0", ")", ":", "if", "not", "url", "and", "not", "input_files", ":", "logging", ".", "warning", "(", "\"No input file\"", ")", "return", "{", "\"error\"", ":",...
run the headless browser with given input if url given, the proc will only run hlb with given url and ignore input_list. :param url: :param input_files: the name of the file in "index url" format. i.e. 1, www.facebook.com 1, www.google.com ... :param verbose: :return:
[ "run", "the", "headless", "browser", "with", "given", "input", "if", "url", "given", "the", "proc", "will", "only", "run", "hlb", "with", "given", "url", "and", "ignore", "input_list", ".", ":", "param", "url", ":", ":", "param", "input_files", ":", "the...
python
train
apacha/OMR-Datasets
omrdatasettools/image_generators/HomusSymbol.py
https://github.com/apacha/OMR-Datasets/blob/d0a22a03ae35caeef211729efa340e1ec0e01ea5/omrdatasettools/image_generators/HomusSymbol.py#L64-L76
def draw_into_bitmap(self, export_path: ExportPath, stroke_thickness: int, margin: int = 0) -> None: """ Draws the symbol in the original size that it has plus an optional margin :param export_path: The path, where the symbols should be created on disk :param stroke_thickness: Pen-thickness for drawing the symbol in pixels :param margin: An optional margin for each symbol """ self.draw_onto_canvas(export_path, stroke_thickness, margin, self.dimensions.width + 2 * margin, self.dimensions.height + 2 * margin)
[ "def", "draw_into_bitmap", "(", "self", ",", "export_path", ":", "ExportPath", ",", "stroke_thickness", ":", "int", ",", "margin", ":", "int", "=", "0", ")", "->", "None", ":", "self", ".", "draw_onto_canvas", "(", "export_path", ",", "stroke_thickness", ","...
Draws the symbol in the original size that it has plus an optional margin :param export_path: The path, where the symbols should be created on disk :param stroke_thickness: Pen-thickness for drawing the symbol in pixels :param margin: An optional margin for each symbol
[ "Draws", "the", "symbol", "in", "the", "original", "size", "that", "it", "has", "plus", "an", "optional", "margin" ]
python
train
pletzer/pnumpy
src/pnDistArray.py
https://github.com/pletzer/pnumpy/blob/9e6d308be94a42637466b91ab1a7b4d64b4c29ae/src/pnDistArray.py#L15-L208
def distArrayFactory(BaseClass): """ Returns a distributed array class that derives from BaseClass @param BaseClass base class, e.g. numpy.ndarray or numpy.ma.masked_array @return dist array class """ class DistArrayAny(BaseClass): """ Distributed array. Each process owns data and can expose a subset of the data to other processes. These are known as windows. Any number of windows can be exposed and the data of windows can be overlapping. Any process can access exposed windows from any other process. This relies on MPI-2 one-sided get communication. """ def __new__(cls, *args, **kwargs): return numpy.ndarray.__new__(cls, *args, **kwargs) def __init__(self, shap, dtyp): """ Constructor @param shap array shape @param dtyp numpy type """ # default communicator self.comm = MPI.COMM_WORLD # winID: {'slice': slce, # 'dataSrc': dataSrc, # 'dataDst': dataDst, # 'window': window} self.windows = {} # the type of data self.dtyp = dtyp # this process's MPI rank self.rk = self.comm.Get_rank() # number of processes self.sz = self.comm.Get_size() # mapping of numpy data types to MPI data types, # assumes that the data are of some numpy variant self.dtypMPI = None if dtyp == numpy.float64: self.dtypMPI = MPI.DOUBLE elif dtyp == numpy.float32: self.dtypeMPI = MPI.FLOAT elif dtyp == numpy.int64: self.dtypeMPI = MPI.INT64_T elif dtyp == numpy.int32: self.dtypeMPI = MPI.INT32_T elif dtyp == numpy.int16: self.dtypeMPI = MPI.INT16_T elif dtyp == numpy.int8: self.dtypeMPI = MPI.INT8_T elif dtyp == numpy.bool_: self.dtypeMPI = MPI.BYTE else: raise NotImplementedError def setComm(self, comm): """ Set communicator @param comm communicator """ self.comm = comm self.rk = self.comm.Get_rank() self.sz = self.comm.Get_size() def getMPIRank(self): """ Get the MPI rank of this process @return rank """ return self.rk def getMPISize(self): """ Get the MPI size (number of processes) of this communicator @return rank """ return self.sz def expose(self, slce, winID): """ Collective operation to expose a sub-set of data @param slce tuple of slice objects @param winID the data window ID """ # buffer for source data dataSrc = numpy.zeros(self[slce].shape, self.dtyp) # buffer for destination data dataDst = numpy.zeros(self[slce].shape, self.dtyp) self.windows[winID] = { 'slice': slce, 'dataSrc': dataSrc, 'dataDst': dataDst, 'dataWindow': MPI.Win.Create(dataSrc, comm=self.comm), } if hasattr(self, 'mask'): maskSrc = numpy.ones(self[slce].shape, numpy.bool_) maskDst = numpy.ones(self[slce].shape, numpy.bool_) iw = self.windows[winID] iw['maskSrc'] = maskSrc iw['maskDst'] = maskDst iw['maskWindow'] = MPI.Win.Create(maskSrc, comm=self.comm) def getMask(self, pe, winID): """ Access remote mask (collective operation) @param pe remote processing element, if None then no operation @param winID remote window @return mask array or None (if there is no mask) @note this is a no operation if there is no mask attached to the data """ if 'maskWindow' not in self.windows: # no mask, no op return None iw = self.windows[winID] slce = iw['slice'] maskSrc = iw['maskSrc'] maskDst = iw['maskDst'] # copy src mask into buffer maskSrc[...] = self.mask[slce] win = iw['maskWindow'] win.Fence(MPI.MODE_NOPUT | MPI.MODE_NOPRECEDE) if pe is not None: win.Get([maskDst, MPI.BYTE], pe) win.Fence(MPI.MODE_NOSUCCEED) return maskDst def getData(self, pe, winID): """ Access remote data (collective operation) @param pe remote processing element, if None then no operation @param winID remote window @return array """ iw = self.windows[winID] slce = iw['slice'] dataSrc = iw['dataSrc'] dataDst = iw['dataDst'] # copy src data into buffer dataSrc[...] = self[slce] win = iw['dataWindow'] win.Fence(MPI.MODE_NOPRECEDE) #MPI.MODE_NOPUT | MPI.MODE_NOPRECEDE) if pe is not None: win.Get([dataDst, self.dtypMPI], pe) win.Fence(MPI.MODE_NOSUCCEED) return dataDst def free(self): """ Must be called to free all exposed windows """ for iw in self.windows: self.windows[iw]['dataWindow'].Free() def reduce(self, op, initializer=None, rootPe=0): """ Collective reduce operation @param op function (e.g. lambda x,y:x+y) @param initializer the return value if there are no elements @param rootPe the root process which receives the result @return result on rootPe, None on all other processes """ if len(self) == 0: return initializer val = functools.reduce(op, self.flat) data = self.comm.gather(val, rootPe) if self.rk == rootPe: return functools.reduce(op, data) else: return None return DistArrayAny
[ "def", "distArrayFactory", "(", "BaseClass", ")", ":", "class", "DistArrayAny", "(", "BaseClass", ")", ":", "\"\"\"\n Distributed array. Each process owns data and can expose a subset\n of the data to other processes. These are known as windows. Any\n number of windows c...
Returns a distributed array class that derives from BaseClass @param BaseClass base class, e.g. numpy.ndarray or numpy.ma.masked_array @return dist array class
[ "Returns", "a", "distributed", "array", "class", "that", "derives", "from", "BaseClass" ]
python
train
pycontribs/pyrax
pyrax/cloudloadbalancers.py
https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/cloudloadbalancers.py#L564-L572
def delete_virtualip(self, loadbalancer, vip): """Deletes the VirtualIP from its load balancer.""" lb = vip.parent if not lb: raise exc.UnattachedVirtualIP("No parent Load Balancer for this " "VirtualIP could be determined.") resp, body = self.api.method_delete("/loadbalancers/%s/virtualips/%s" % (lb.id, vip.id)) return resp, body
[ "def", "delete_virtualip", "(", "self", ",", "loadbalancer", ",", "vip", ")", ":", "lb", "=", "vip", ".", "parent", "if", "not", "lb", ":", "raise", "exc", ".", "UnattachedVirtualIP", "(", "\"No parent Load Balancer for this \"", "\"VirtualIP could be determined.\""...
Deletes the VirtualIP from its load balancer.
[ "Deletes", "the", "VirtualIP", "from", "its", "load", "balancer", "." ]
python
train
senaite/senaite.core
bika/lims/exportimport/instruments/abbott/m2000rt/m2000rt.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/exportimport/instruments/abbott/m2000rt/m2000rt.py#L206-L219
def _date_to_bika_date(self, date_time, only_date): """ Convert a string containing a date from results file to bika format :param date_time: str with Date to convert :param only_date: boolean value that specifies if there is only a date to parse (true) or date plus time (false) :return: datetime in bika format """ # if only date the input date format is: 2017/01/26 # else: 2017/01/26 12:47:09 PM if only_date: return datetime.strptime(date_time, '%Y/%m/%d').strftime('%Y%m%d') else: return datetime.strptime(date_time, "%Y/%m/%d %I:%M:%S %p").strftime("%Y%m%d %H:%M:%S")
[ "def", "_date_to_bika_date", "(", "self", ",", "date_time", ",", "only_date", ")", ":", "# if only date the input date format is: 2017/01/26", "# else: 2017/01/26 12:47:09 PM", "if", "only_date", ":", "return", "datetime", ".", "strptime", "(", "date_time", ",", "'%Y/%m/%...
Convert a string containing a date from results file to bika format :param date_time: str with Date to convert :param only_date: boolean value that specifies if there is only a date to parse (true) or date plus time (false) :return: datetime in bika format
[ "Convert", "a", "string", "containing", "a", "date", "from", "results", "file", "to", "bika", "format", ":", "param", "date_time", ":", "str", "with", "Date", "to", "convert", ":", "param", "only_date", ":", "boolean", "value", "that", "specifies", "if", "...
python
train
automl/HpBandSter
hpbandster/optimizers/config_generators/kde.py
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/optimizers/config_generators/kde.py#L84-L147
def new_result(self, job): """ function to register finished runs Every time a run has finished, this function should be called to register it with the result logger. If overwritten, make sure to call this method from the base class to ensure proper logging. Parameters: ----------- job_id: dict a dictionary containing all the info about the run job_result: dict contains all the results of the job, i.e. it's a dict with the keys 'loss' and 'info' """ super(KernelDensityEstimator, self).new_result(job) budget = job.kwargs["budget"] if budget not in self.configs.keys(): self.configs[budget] = [] self.losses[budget] = [] # We want to get a numerical representation of the configuration in the original space conf = ConfigSpace.Configuration(self.configspace, job.kwargs['config']) self.configs[budget].append(conf.get_array()) self.losses[budget].append(job.result['result']["loss"]) # Check if we have enough data points to fit a KDE if len(self.configs[budget]) % self.update_after_n_points == 0: train_configs, train_losses = [], [] train_configs.extend(self.configs[budget]) train_losses.extend(self.losses[budget]) n = int(self.top_n_percent * len(train_configs) / 100.) remaining_budgets = list(self.configs.keys()) remaining_budgets.remove(budget) remaining_budgets.sort(reverse=True) for b in remaining_budgets: if n >= self.min_points_in_model: break train_configs.extend(self.configs[b]) train_losses.extend(self.losses[b]) n = int(self.top_n_percent * len(train_configs) / 100.) if len(train_losses) < self.min_points_in_model: return n = max(self.min_points_in_model, n) # Refit KDE for the current budget idx = np.argsort(train_losses) train_data = (np.array(train_configs)[idx])[:n] self.kde_models[budget] = sm.nonparametric.KDEMultivariate(data=train_data, var_type=self.var_type, bw='cv_ls')
[ "def", "new_result", "(", "self", ",", "job", ")", ":", "super", "(", "KernelDensityEstimator", ",", "self", ")", ".", "new_result", "(", "job", ")", "budget", "=", "job", ".", "kwargs", "[", "\"budget\"", "]", "if", "budget", "not", "in", "self", ".",...
function to register finished runs Every time a run has finished, this function should be called to register it with the result logger. If overwritten, make sure to call this method from the base class to ensure proper logging. Parameters: ----------- job_id: dict a dictionary containing all the info about the run job_result: dict contains all the results of the job, i.e. it's a dict with the keys 'loss' and 'info'
[ "function", "to", "register", "finished", "runs" ]
python
train
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_common_def.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_common_def.py#L620-L636
def ip_rtm_config_route_static_route_nh_vrf_next_hop_vrf(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def") rtm_config = ET.SubElement(ip, "rtm-config", xmlns="urn:brocade.com:mgmt:brocade-rtm") route = ET.SubElement(rtm_config, "route") static_route_nh_vrf = ET.SubElement(route, "static-route-nh-vrf") static_route_next_vrf_dest_key = ET.SubElement(static_route_nh_vrf, "static-route-next-vrf-dest") static_route_next_vrf_dest_key.text = kwargs.pop('static_route_next_vrf_dest') static_route_next_hop_key = ET.SubElement(static_route_nh_vrf, "static-route-next-hop") static_route_next_hop_key.text = kwargs.pop('static_route_next_hop') next_hop_vrf = ET.SubElement(static_route_nh_vrf, "next-hop-vrf") next_hop_vrf.text = kwargs.pop('next_hop_vrf') callback = kwargs.pop('callback', self._callback) return callback(config)
[ "def", "ip_rtm_config_route_static_route_nh_vrf_next_hop_vrf", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "ip", "=", "ET", ".", "SubElement", "(", "config", ",", "\"ip\"", ",", "xmlns", "=", ...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
iclab/centinel
centinel/primitives/tcpdump.py
https://github.com/iclab/centinel/blob/9a25dcf30c6a1db3c046f7ccb8ab8873e455c1a4/centinel/primitives/tcpdump.py#L78-L88
def _tcpdump_callback(self, line, kill_switch): """Callback function to handle tcpdump""" line = line.lower() if ("listening" in line) or ("reading" in line): self.started = True if ("no suitable device" in line): self.error = True self.kill_switch() if "by kernel" in line: self.stopped = True
[ "def", "_tcpdump_callback", "(", "self", ",", "line", ",", "kill_switch", ")", ":", "line", "=", "line", ".", "lower", "(", ")", "if", "(", "\"listening\"", "in", "line", ")", "or", "(", "\"reading\"", "in", "line", ")", ":", "self", ".", "started", ...
Callback function to handle tcpdump
[ "Callback", "function", "to", "handle", "tcpdump" ]
python
train
fastai/fastai
fastai/callbacks/loss_metrics.py
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/loss_metrics.py#L30-L34
def on_epoch_end(self, last_metrics, **kwargs): "Finish the computation and sends the result to the Recorder." if not self.nums: return metrics = [self.metrics[name]/self.nums for name in self.names] return {'last_metrics': last_metrics+metrics}
[ "def", "on_epoch_end", "(", "self", ",", "last_metrics", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "nums", ":", "return", "metrics", "=", "[", "self", ".", "metrics", "[", "name", "]", "/", "self", ".", "nums", "for", "name", "in...
Finish the computation and sends the result to the Recorder.
[ "Finish", "the", "computation", "and", "sends", "the", "result", "to", "the", "Recorder", "." ]
python
train
DataBiosphere/toil
src/toil/common.py
https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/common.py#L870-L900
def createBatchSystem(config): """ Creates an instance of the batch system specified in the given config. :param toil.common.Config config: the current configuration :rtype: batchSystems.abstractBatchSystem.AbstractBatchSystem :return: an instance of a concrete subclass of AbstractBatchSystem """ kwargs = dict(config=config, maxCores=config.maxCores, maxMemory=config.maxMemory, maxDisk=config.maxDisk) from toil.batchSystems.registry import batchSystemFactoryFor try: factory = batchSystemFactoryFor(config.batchSystem) batchSystemClass = factory() except: raise RuntimeError('Unrecognised batch system: %s' % config.batchSystem) if not config.disableCaching and not batchSystemClass.supportsWorkerCleanup(): raise RuntimeError('%s currently does not support shared caching. Set the ' '--disableCaching flag if you want to ' 'use this batch system.' % config.batchSystem) logger.debug('Using the %s' % re.sub("([a-z])([A-Z])", "\g<1> \g<2>", batchSystemClass.__name__).lower()) return batchSystemClass(**kwargs)
[ "def", "createBatchSystem", "(", "config", ")", ":", "kwargs", "=", "dict", "(", "config", "=", "config", ",", "maxCores", "=", "config", ".", "maxCores", ",", "maxMemory", "=", "config", ".", "maxMemory", ",", "maxDisk", "=", "config", ".", "maxDisk", "...
Creates an instance of the batch system specified in the given config. :param toil.common.Config config: the current configuration :rtype: batchSystems.abstractBatchSystem.AbstractBatchSystem :return: an instance of a concrete subclass of AbstractBatchSystem
[ "Creates", "an", "instance", "of", "the", "batch", "system", "specified", "in", "the", "given", "config", "." ]
python
train
halcy/Mastodon.py
mastodon/Mastodon.py
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1034-L1042
def filter(self, id): """ Fetches information about the filter with the specified `id`. Returns a `filter dict`_. """ id = self.__unpack_id(id) url = '/api/v1/filters/{0}'.format(str(id)) return self.__api_request('GET', url)
[ "def", "filter", "(", "self", ",", "id", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "url", "=", "'/api/v1/filters/{0}'", ".", "format", "(", "str", "(", "id", ")", ")", "return", "self", ".", "__api_request", "(", "'GET'", ",", ...
Fetches information about the filter with the specified `id`. Returns a `filter dict`_.
[ "Fetches", "information", "about", "the", "filter", "with", "the", "specified", "id", ".", "Returns", "a", "filter", "dict", "_", "." ]
python
train
iotile/coretools
iotileemulate/iotile/emulate/transport/emulatedadapter.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/transport/emulatedadapter.py#L43-L58
async def send_rpc(self, conn_id, address, rpc_id, payload, timeout): """Asynchronously send an RPC to this IOTile device Args: conn_id (int): A unique identifier that will refer to this connection address (int): the address of the tile that we wish to send the RPC to rpc_id (int): the 16-bit id of the RPC we want to call payload (bytearray): the payload of the command timeout (float): the number of seconds to wait for the RPC to execute """ try: return await super(EmulatedDeviceAdapter, self).send_rpc(conn_id, address, rpc_id, payload, timeout) finally: for dev in self.devices.values(): dev.wait_idle()
[ "async", "def", "send_rpc", "(", "self", ",", "conn_id", ",", "address", ",", "rpc_id", ",", "payload", ",", "timeout", ")", ":", "try", ":", "return", "await", "super", "(", "EmulatedDeviceAdapter", ",", "self", ")", ".", "send_rpc", "(", "conn_id", ","...
Asynchronously send an RPC to this IOTile device Args: conn_id (int): A unique identifier that will refer to this connection address (int): the address of the tile that we wish to send the RPC to rpc_id (int): the 16-bit id of the RPC we want to call payload (bytearray): the payload of the command timeout (float): the number of seconds to wait for the RPC to execute
[ "Asynchronously", "send", "an", "RPC", "to", "this", "IOTile", "device" ]
python
train
KnuVerse/knuverse-sdk-python
knuverse/knufactor.py
https://github.com/KnuVerse/knuverse-sdk-python/blob/00f1275a452a4dcf9bc92ef345f6985504226d8e/knuverse/knufactor.py#L821-L860
def verification_start( self, client, mode=None, verification_speed=None, row_doubling="off", phone_number=None, ): """ Start a verification. Uses POST to /verifications interface. :Args: * *client*: (str) Client's Name * *mode*: (str) Verification Mode. Allowed values: "audiopin", "audiopass" * *verification_speed*: (int) Allowed values: 0, 25, 50, 75, 100 * *row_doubling*: (str) Allowed values: "off", "train", "on" * *phone_number*: (str) Phone number to call. :Returns: (dict) Verification record with animation as discussed `here <https://cloud.knuverse.com/docs/api/#api-Verifications-Start_verification>`_. """ data = { "name": client, "user_agent": "knuverse-sdk-python-v%s" % self.version } if mode: data["mode"] = mode if phone_number: data["phone_number"] = phone_number if verification_speed: data["verification_speed"] = verification_speed if row_doubling: data["row_doubling"] = row_doubling response = self._post(url.verifications, body=data) self._check_response(response, 201) return self._create_response(response)
[ "def", "verification_start", "(", "self", ",", "client", ",", "mode", "=", "None", ",", "verification_speed", "=", "None", ",", "row_doubling", "=", "\"off\"", ",", "phone_number", "=", "None", ",", ")", ":", "data", "=", "{", "\"name\"", ":", "client", ...
Start a verification. Uses POST to /verifications interface. :Args: * *client*: (str) Client's Name * *mode*: (str) Verification Mode. Allowed values: "audiopin", "audiopass" * *verification_speed*: (int) Allowed values: 0, 25, 50, 75, 100 * *row_doubling*: (str) Allowed values: "off", "train", "on" * *phone_number*: (str) Phone number to call. :Returns: (dict) Verification record with animation as discussed `here <https://cloud.knuverse.com/docs/api/#api-Verifications-Start_verification>`_.
[ "Start", "a", "verification", ".", "Uses", "POST", "to", "/", "verifications", "interface", "." ]
python
train
6809/dragonlib
dragonlib/api.py
https://github.com/6809/dragonlib/blob/faa4011e76c5857db96efdb4199e2fd49711e999/dragonlib/api.py#L100-L109
def pformat_program_dump(self, program_dump, program_start=None): """ format a BASIC program dump. Useful for debugging. returns a list of formated string lines. """ assert isinstance(program_dump, bytearray) if program_start is None: program_start = self.DEFAULT_PROGRAM_START return self.listing.pformat_program_dump(program_dump, program_start)
[ "def", "pformat_program_dump", "(", "self", ",", "program_dump", ",", "program_start", "=", "None", ")", ":", "assert", "isinstance", "(", "program_dump", ",", "bytearray", ")", "if", "program_start", "is", "None", ":", "program_start", "=", "self", ".", "DEFA...
format a BASIC program dump. Useful for debugging. returns a list of formated string lines.
[ "format", "a", "BASIC", "program", "dump", ".", "Useful", "for", "debugging", ".", "returns", "a", "list", "of", "formated", "string", "lines", "." ]
python
train
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/scrappers/zonerpress_cz/__init__.py
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/zonerpress_cz/__init__.py#L68-L89
def _parse_book_links(dom): """ Parse links to the details about publications from page with book list. Args: dom (obj): HTMLElement container of the page with book list. Returns: list: List of strings / absolute links to book details. """ links = [] picker = lambda x: x.params.get("class", "").startswith("boxProKnihy") for el in dom.find(None, fn=picker): book_ref = el.find("a") if not book_ref or "href" not in book_ref[0].params: continue links.append(book_ref[0].params["href"]) return links
[ "def", "_parse_book_links", "(", "dom", ")", ":", "links", "=", "[", "]", "picker", "=", "lambda", "x", ":", "x", ".", "params", ".", "get", "(", "\"class\"", ",", "\"\"", ")", ".", "startswith", "(", "\"boxProKnihy\"", ")", "for", "el", "in", "dom",...
Parse links to the details about publications from page with book list. Args: dom (obj): HTMLElement container of the page with book list. Returns: list: List of strings / absolute links to book details.
[ "Parse", "links", "to", "the", "details", "about", "publications", "from", "page", "with", "book", "list", "." ]
python
train
adamcharnock/swiftwind
swiftwind/costs/models.py
https://github.com/adamcharnock/swiftwind/blob/72c715800841c3b2feabded3f3b65b76388b4cea/swiftwind/costs/models.py#L236-L248
def _is_ready(self, as_of): """Is the RecurringCost ready to be enacted as of the date `as_of` This determines if `as_of` precedes the start of `initial_billing_cycle`. If so, we should not be enacting this RecurringCost yet. Args: as_of (Date): """ if self.is_one_off(): return self.initial_billing_cycle.date_range.lower <= as_of else: return True
[ "def", "_is_ready", "(", "self", ",", "as_of", ")", ":", "if", "self", ".", "is_one_off", "(", ")", ":", "return", "self", ".", "initial_billing_cycle", ".", "date_range", ".", "lower", "<=", "as_of", "else", ":", "return", "True" ]
Is the RecurringCost ready to be enacted as of the date `as_of` This determines if `as_of` precedes the start of `initial_billing_cycle`. If so, we should not be enacting this RecurringCost yet. Args: as_of (Date):
[ "Is", "the", "RecurringCost", "ready", "to", "be", "enacted", "as", "of", "the", "date", "as_of" ]
python
train
aiogram/aiogram
aiogram/utils/helper.py
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/helper.py#L59-L74
def _screaming_snake_case(cls, text): """ Transform text to SCREAMING_SNAKE_CASE :param text: :return: """ if text.isupper(): return text result = '' for pos, symbol in enumerate(text): if symbol.isupper() and pos > 0: result += '_' + symbol else: result += symbol.upper() return result
[ "def", "_screaming_snake_case", "(", "cls", ",", "text", ")", ":", "if", "text", ".", "isupper", "(", ")", ":", "return", "text", "result", "=", "''", "for", "pos", ",", "symbol", "in", "enumerate", "(", "text", ")", ":", "if", "symbol", ".", "isuppe...
Transform text to SCREAMING_SNAKE_CASE :param text: :return:
[ "Transform", "text", "to", "SCREAMING_SNAKE_CASE" ]
python
train
satellogic/telluric
telluric/georaster.py
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L1611-L1613
def to_raster(self, vector): """Return the vector in pixel coordinates, as shapely.Geometry.""" return transform(vector.get_shape(vector.crs), vector.crs, self.crs, dst_affine=~self.affine)
[ "def", "to_raster", "(", "self", ",", "vector", ")", ":", "return", "transform", "(", "vector", ".", "get_shape", "(", "vector", ".", "crs", ")", ",", "vector", ".", "crs", ",", "self", ".", "crs", ",", "dst_affine", "=", "~", "self", ".", "affine", ...
Return the vector in pixel coordinates, as shapely.Geometry.
[ "Return", "the", "vector", "in", "pixel", "coordinates", "as", "shapely", ".", "Geometry", "." ]
python
train
LuminosoInsight/python-ftfy
ftfy/fixes.py
https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/fixes.py#L133-L158
def fix_encoding_and_explain(text): """ Re-decodes text that has been decoded incorrectly, and also return a "plan" indicating all the steps required to fix it. The resulting plan could be used with :func:`ftfy.fixes.apply_plan` to fix additional strings that are broken in the same way. """ best_version = text best_cost = text_cost(text) best_plan = [] plan_so_far = [] while True: prevtext = text text, plan = fix_one_step_and_explain(text) plan_so_far.extend(plan) cost = text_cost(text) for _, _, step_cost in plan_so_far: cost += step_cost if cost < best_cost: best_cost = cost best_version = text best_plan = list(plan_so_far) if text == prevtext: return best_version, best_plan
[ "def", "fix_encoding_and_explain", "(", "text", ")", ":", "best_version", "=", "text", "best_cost", "=", "text_cost", "(", "text", ")", "best_plan", "=", "[", "]", "plan_so_far", "=", "[", "]", "while", "True", ":", "prevtext", "=", "text", "text", ",", ...
Re-decodes text that has been decoded incorrectly, and also return a "plan" indicating all the steps required to fix it. The resulting plan could be used with :func:`ftfy.fixes.apply_plan` to fix additional strings that are broken in the same way.
[ "Re", "-", "decodes", "text", "that", "has", "been", "decoded", "incorrectly", "and", "also", "return", "a", "plan", "indicating", "all", "the", "steps", "required", "to", "fix", "it", "." ]
python
train
hactar-is/frink
frink/orm.py
https://github.com/hactar-is/frink/blob/0d2c11daca8ef6d4365e98914bdc0bc65478ae72/frink/orm.py#L33-L90
def save(self): """ Save the current instance to the DB """ with rconnect() as conn: try: self.validate() except ValidationError as e: log.warn(e.messages) raise except ModelValidationError as e: log.warn(e.messages) raise except ModelConversionError as e: log.warn(e.messages) raise except ValueError as e: log.warn(e) raise except FrinkError as e: log.warn(e.messages) raise except Exception as e: log.warn(e) raise else: # If this is a new unsaved object, it'll likely have an # id of None, which RethinkDB won't like. So if it's None, # generate a UUID for it. If the save fails, we should re-set # it to None. if self.id is None: self.id = str(uuid.uuid4()) log.debug(self.id) try: query = r.db(self._db).table(self._table).insert( self.to_primitive(), conflict="replace" ) log.debug(query) rv = query.run(conn) # Returns something like this: # { # u'errors': 0, # u'deleted': 0, # u'generated_keys': [u'dd8ad1bc-8609-4484-b6c4-ed96c72c03f2'], # u'unchanged': 0, # u'skipped': 0, # u'replaced': 0, # u'inserted': 1 # } log.debug(rv) except Exception as e: log.warn(e) self.id = None raise else: return self
[ "def", "save", "(", "self", ")", ":", "with", "rconnect", "(", ")", "as", "conn", ":", "try", ":", "self", ".", "validate", "(", ")", "except", "ValidationError", "as", "e", ":", "log", ".", "warn", "(", "e", ".", "messages", ")", "raise", "except"...
Save the current instance to the DB
[ "Save", "the", "current", "instance", "to", "the", "DB" ]
python
train
gunthercox/ChatterBot
chatterbot/storage/mongodb.py
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/storage/mongodb.py#L44-L54
def get_statement_model(self): """ Return the class for the statement model. """ from chatterbot.conversation import Statement # Create a storage-aware statement statement = Statement statement.storage = self return statement
[ "def", "get_statement_model", "(", "self", ")", ":", "from", "chatterbot", ".", "conversation", "import", "Statement", "# Create a storage-aware statement", "statement", "=", "Statement", "statement", ".", "storage", "=", "self", "return", "statement" ]
Return the class for the statement model.
[ "Return", "the", "class", "for", "the", "statement", "model", "." ]
python
train
inveniosoftware/dcxml
dcxml/xmlutils.py
https://github.com/inveniosoftware/dcxml/blob/9fed6123ec0f3f2e2f645ff91653a7e86a39138d/dcxml/xmlutils.py#L18-L33
def dump_etree_helper(container_name, data, rules, nsmap, attrib): """Convert DataCite JSON format to DataCite XML. JSON should be validated before it is given to to_xml. """ output = etree.Element(container_name, nsmap=nsmap, attrib=attrib) for rule in rules: if rule not in data: continue element = rules[rule](rule, data[rule]) for e in element: output.append(e) return output
[ "def", "dump_etree_helper", "(", "container_name", ",", "data", ",", "rules", ",", "nsmap", ",", "attrib", ")", ":", "output", "=", "etree", ".", "Element", "(", "container_name", ",", "nsmap", "=", "nsmap", ",", "attrib", "=", "attrib", ")", "for", "rul...
Convert DataCite JSON format to DataCite XML. JSON should be validated before it is given to to_xml.
[ "Convert", "DataCite", "JSON", "format", "to", "DataCite", "XML", "." ]
python
train
CxAalto/gtfspy
gtfspy/import_validator.py
https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/import_validator.py#L229-L243
def _validate_danglers(self): """ Checks for rows that are not referenced in the the tables that should be linked stops <> stop_times using stop_I stop_times <> trips <> days, using trip_I trips <> routes, using route_I :return: """ for query, warning in zip(DANGLER_QUERIES, DANGLER_WARNINGS): dangler_count = self.gtfs.execute_custom_query(query).fetchone()[0] if dangler_count > 0: if self.verbose: print(str(dangler_count) + " " + warning) self.warnings_container.add_warning(warning, self.location, count=dangler_count)
[ "def", "_validate_danglers", "(", "self", ")", ":", "for", "query", ",", "warning", "in", "zip", "(", "DANGLER_QUERIES", ",", "DANGLER_WARNINGS", ")", ":", "dangler_count", "=", "self", ".", "gtfs", ".", "execute_custom_query", "(", "query", ")", ".", "fetch...
Checks for rows that are not referenced in the the tables that should be linked stops <> stop_times using stop_I stop_times <> trips <> days, using trip_I trips <> routes, using route_I :return:
[ "Checks", "for", "rows", "that", "are", "not", "referenced", "in", "the", "the", "tables", "that", "should", "be", "linked" ]
python
valid
StackStorm/pybind
pybind/slxos/v17s_1_02/routing_system/evpn_config/evpn/evpn_instance/bridge_domain/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/routing_system/evpn_config/evpn/evpn_instance/bridge_domain/__init__.py#L94-L115
def _set_bd_add(self, v, load=False): """ Setter method for bd_add, mapped from YANG variable /routing_system/evpn_config/evpn/evpn_instance/bridge_domain/bd_add (container) If this variable is read-only (config: false) in the source YANG file, then _set_bd_add is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_bd_add() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=bd_add.bd_add, is_container='container', presence=False, yang_name="bd-add", rest_name="", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Add/Remove bridge domains from EVPN Instance', u'cli-drop-node-name': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """bd_add must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=bd_add.bd_add, is_container='container', presence=False, yang_name="bd-add", rest_name="", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Add/Remove bridge domains from EVPN Instance', u'cli-drop-node-name': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='container', is_config=True)""", }) self.__bd_add = t if hasattr(self, '_set'): self._set()
[ "def", "_set_bd_add", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base", ...
Setter method for bd_add, mapped from YANG variable /routing_system/evpn_config/evpn/evpn_instance/bridge_domain/bd_add (container) If this variable is read-only (config: false) in the source YANG file, then _set_bd_add is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_bd_add() directly.
[ "Setter", "method", "for", "bd_add", "mapped", "from", "YANG", "variable", "/", "routing_system", "/", "evpn_config", "/", "evpn", "/", "evpn_instance", "/", "bridge_domain", "/", "bd_add", "(", "container", ")", "If", "this", "variable", "is", "read", "-", ...
python
train
6809/MC6809
MC6809/components/mc6809_base.py
https://github.com/6809/MC6809/blob/6ba2f5106df46689017b5d0b6d84d43b7ee6a240/MC6809/components/mc6809_base.py#L144-L165
def get_state(self): """ used in unittests """ return { REG_X: self.index_x.value, REG_Y: self.index_y.value, REG_U: self.user_stack_pointer.value, REG_S: self.system_stack_pointer.value, REG_PC: self.program_counter.value, REG_A: self.accu_a.value, REG_B: self.accu_b.value, REG_DP: self.direct_page.value, REG_CC: self.get_cc_value(), "cycles": self.cycles, "RAM": tuple(self.memory._mem) # copy of array.array() values, }
[ "def", "get_state", "(", "self", ")", ":", "return", "{", "REG_X", ":", "self", ".", "index_x", ".", "value", ",", "REG_Y", ":", "self", ".", "index_y", ".", "value", ",", "REG_U", ":", "self", ".", "user_stack_pointer", ".", "value", ",", "REG_S", "...
used in unittests
[ "used", "in", "unittests" ]
python
train
PyThaiNLP/pythainlp
pythainlp/tokenize/multi_cut.py
https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/tokenize/multi_cut.py#L121-L128
def segment(text: str, custom_dict: Trie = None) -> List[str]: """ ใช้ในการหา list ที่สามารถตัดคำได้ทั้งหมด """ if not text or not isinstance(text, str): return [] return list(_multicut(text, custom_dict=custom_dict))
[ "def", "segment", "(", "text", ":", "str", ",", "custom_dict", ":", "Trie", "=", "None", ")", "->", "List", "[", "str", "]", ":", "if", "not", "text", "or", "not", "isinstance", "(", "text", ",", "str", ")", ":", "return", "[", "]", "return", "li...
ใช้ในการหา list ที่สามารถตัดคำได้ทั้งหมด
[ "ใช้ในการหา", "list", "ที่สามารถตัดคำได้ทั้งหมด" ]
python
train
pkgw/pwkit
pwkit/environments/casa/tasks.py
https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/environments/casa/tasks.py#L658-L701
def concat(invises, outvis, timesort=False): """Concatenate visibility measurement sets. invises (list of str) Paths to the input measurement sets outvis (str) Path to the output measurement set. timesort (boolean) If true, sort the output in time after concatenation. Example:: from pwkit.environments.casa import tasks tasks.concat(['epoch1.ms', 'epoch2.ms'], 'combined.ms') """ tb = util.tools.table() ms = util.tools.ms() if os.path.exists(outvis): raise RuntimeError('output "%s" already exists' % outvis) for invis in invises: if not os.path.isdir(invis): raise RuntimeError('input "%s" does not exist' % invis) tb.open(b(invises[0])) tb.copy(b(outvis), deep=True, valuecopy=True) tb.close() ms.open(b(outvis), nomodify=False) for invis in invises[1:]: ms.concatenate(msfile=b(invis), freqtol=b(concat_freqtol), dirtol=b(concat_dirtol)) ms.writehistory(message=b'taskname=tasklib.concat', origin=b'tasklib.concat') ms.writehistory(message=b('vis = ' + ', '.join(invises)), origin=b'tasklib.concat') ms.writehistory(message=b('timesort = ' + 'FT'[int(timesort)]), origin=b'tasklib.concat') if timesort: ms.timesort() ms.close()
[ "def", "concat", "(", "invises", ",", "outvis", ",", "timesort", "=", "False", ")", ":", "tb", "=", "util", ".", "tools", ".", "table", "(", ")", "ms", "=", "util", ".", "tools", ".", "ms", "(", ")", "if", "os", ".", "path", ".", "exists", "(",...
Concatenate visibility measurement sets. invises (list of str) Paths to the input measurement sets outvis (str) Path to the output measurement set. timesort (boolean) If true, sort the output in time after concatenation. Example:: from pwkit.environments.casa import tasks tasks.concat(['epoch1.ms', 'epoch2.ms'], 'combined.ms')
[ "Concatenate", "visibility", "measurement", "sets", "." ]
python
train
QualiSystems/cloudshell-networking-devices
cloudshell/devices/flows/action_flows.py
https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/flows/action_flows.py#L109-L139
def execute_flow(self, custom_command="", is_config=False): """ Execute flow which run custom command on device :param custom_command: the command to execute on device :param is_config: if True then run command in configuration mode :return: command execution output """ responses = [] if isinstance(custom_command, str): commands = [custom_command] elif isinstance(custom_command, tuple): commands = list(custom_command) else: commands = custom_command if is_config: mode = self._cli_handler.config_mode if not mode: raise Exception(self.__class__.__name__, "CliHandler configuration is missing. Config Mode has to be defined") else: mode = self._cli_handler.enable_mode if not mode: raise Exception(self.__class__.__name__, "CliHandler configuration is missing. Enable Mode has to be defined") with self._cli_handler.get_cli_service(mode) as session: for cmd in commands: responses.append(session.send_command(command=cmd)) return '\n'.join(responses)
[ "def", "execute_flow", "(", "self", ",", "custom_command", "=", "\"\"", ",", "is_config", "=", "False", ")", ":", "responses", "=", "[", "]", "if", "isinstance", "(", "custom_command", ",", "str", ")", ":", "commands", "=", "[", "custom_command", "]", "e...
Execute flow which run custom command on device :param custom_command: the command to execute on device :param is_config: if True then run command in configuration mode :return: command execution output
[ "Execute", "flow", "which", "run", "custom", "command", "on", "device" ]
python
train
voyages-sncf-technologies/nexus_uploader
nexus_uploader/utils.py
https://github.com/voyages-sncf-technologies/nexus_uploader/blob/dca654f9080264b1dcaabfc2fd19f26b1c4f59fe/nexus_uploader/utils.py#L17-L21
def aslist(generator): 'Function decorator to transform a generator into a list' def wrapper(*args, **kwargs): return list(generator(*args, **kwargs)) return wrapper
[ "def", "aslist", "(", "generator", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "list", "(", "generator", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "return", "wrapper" ]
Function decorator to transform a generator into a list
[ "Function", "decorator", "to", "transform", "a", "generator", "into", "a", "list" ]
python
train
pypa/pipenv
pipenv/vendor/requests/adapters.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/adapters.py#L319-L327
def close(self): """Disposes of any internal state. Currently, this closes the PoolManager and any active ProxyManager, which closes any pooled connections. """ self.poolmanager.clear() for proxy in self.proxy_manager.values(): proxy.clear()
[ "def", "close", "(", "self", ")", ":", "self", ".", "poolmanager", ".", "clear", "(", ")", "for", "proxy", "in", "self", ".", "proxy_manager", ".", "values", "(", ")", ":", "proxy", ".", "clear", "(", ")" ]
Disposes of any internal state. Currently, this closes the PoolManager and any active ProxyManager, which closes any pooled connections.
[ "Disposes", "of", "any", "internal", "state", "." ]
python
train
globocom/GloboNetworkAPI-client-python
networkapiclient/ClientFactory.py
https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/ClientFactory.py#L505-L511
def create_option_vip(self): """Get an instance of option_vip services facade.""" return OptionVIP( self.networkapi_url, self.user, self.password, self.user_ldap)
[ "def", "create_option_vip", "(", "self", ")", ":", "return", "OptionVIP", "(", "self", ".", "networkapi_url", ",", "self", ".", "user", ",", "self", ".", "password", ",", "self", ".", "user_ldap", ")" ]
Get an instance of option_vip services facade.
[ "Get", "an", "instance", "of", "option_vip", "services", "facade", "." ]
python
train
KelSolaar/Foundations
foundations/environment.py
https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/environment.py#L237-L260
def get_system_application_data_directory(): """ Returns the system Application data directory. Examples directories:: - 'C:\\Users\\$USER\\AppData\\Roaming' on Windows 7. - 'C:\\Documents and Settings\\$USER\\Application Data' on Windows XP. - '/Users/$USER/Library/Preferences' on Mac Os X. - '/home/$USER' on Linux. :return: User Application data directory. :rtype: unicode """ if platform.system() == "Windows" or platform.system() == "Microsoft": environment = Environment("APPDATA") return environment.get_value() elif platform.system() == "Darwin": environment = Environment("HOME") return os.path.join(environment.get_value(), "Library", "Preferences") elif platform.system() == "Linux": environment = Environment("HOME") return environment.get_value()
[ "def", "get_system_application_data_directory", "(", ")", ":", "if", "platform", ".", "system", "(", ")", "==", "\"Windows\"", "or", "platform", ".", "system", "(", ")", "==", "\"Microsoft\"", ":", "environment", "=", "Environment", "(", "\"APPDATA\"", ")", "r...
Returns the system Application data directory. Examples directories:: - 'C:\\Users\\$USER\\AppData\\Roaming' on Windows 7. - 'C:\\Documents and Settings\\$USER\\Application Data' on Windows XP. - '/Users/$USER/Library/Preferences' on Mac Os X. - '/home/$USER' on Linux. :return: User Application data directory. :rtype: unicode
[ "Returns", "the", "system", "Application", "data", "directory", "." ]
python
train
cisco-sas/kitty
kitty/remote/actor.py
https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/remote/actor.py#L36-L42
def get_report(self): ''' need to wrap get_report, since we need to parse the report ''' report_dict = self._meta_get_report() report = Report.from_dict(report_dict) return report
[ "def", "get_report", "(", "self", ")", ":", "report_dict", "=", "self", ".", "_meta_get_report", "(", ")", "report", "=", "Report", ".", "from_dict", "(", "report_dict", ")", "return", "report" ]
need to wrap get_report, since we need to parse the report
[ "need", "to", "wrap", "get_report", "since", "we", "need", "to", "parse", "the", "report" ]
python
train
Jajcus/pyxmpp2
pyxmpp2/error.py
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/error.py#L399-L410
def _from_xml(self, element): """Initialize an ErrorElement object from an XML element. :Parameters: - `element`: XML element to be decoded. :Types: - `element`: :etree:`ElementTree.Element` """ ErrorElement._from_xml(self, element) error_type = element.get(u"type") if error_type: self.error_type = error_type
[ "def", "_from_xml", "(", "self", ",", "element", ")", ":", "ErrorElement", ".", "_from_xml", "(", "self", ",", "element", ")", "error_type", "=", "element", ".", "get", "(", "u\"type\"", ")", "if", "error_type", ":", "self", ".", "error_type", "=", "erro...
Initialize an ErrorElement object from an XML element. :Parameters: - `element`: XML element to be decoded. :Types: - `element`: :etree:`ElementTree.Element`
[ "Initialize", "an", "ErrorElement", "object", "from", "an", "XML", "element", "." ]
python
valid
noahbenson/neuropythy
neuropythy/hcp/files.py
https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/hcp/files.py#L1761-L1820
def download(sid, credentials=None, subjects_path=None, overwrite=False, release='HCP_1200', database='hcp-openaccess', file_list=None): ''' download(sid) downloads the data for subject with the given subject id. By default, the subject will be placed in the first HCP subject directory in the subjects directories list. Note: In order for downloading to work, you must have s3fs installed. This is not a requirement for the neuropythy library and does not install automatically when installing via pip. The github repository for this library can be found at https://github.com/dask/s3fs. Installation instructions can be found here: http://s3fs.readthedocs.io/en/latest/install.html Accepted options include: * credentials (default: None) may be used to specify the Amazon AWS Bucket credentials, which can be generated from the HCP db (https://db.humanconnectome.org/). If this argument can be coerced to a credentials tuple via the to_credentials function, that result will be used. If None, then the function will try to use the hcp_credentials configuration item in neuropythy.config; otherwise an error is raised. * subjects_path (default: None) specifies where the subject should be placed. If None, then the first directory in the subjects paths list is used. If there is not one of these then an error is raised. * overwrite (default: False) specifies whether or not to overwrite files that already exist. In addition to True (do overwrite) and False (don't overwrite), the value 'error' indicates that an error should be raised if a file already exists. ''' if s3fs is None: raise RuntimeError('s3fs was not successfully loaded, so downloads may not occur; check ' 'your Python configuration to make sure that s3fs is installed. See ' 'http://s3fs.readthedocs.io/en/latest/install.html for details.') if credentials is None: credentials = config['hcp_credentials'] if credentials is None: raise ValueError('No hcp_credentials specified or found') (s3fs_key, s3fs_secret) = to_credentials(credentials) if subjects_path is None: sdirs = config['hcp_subject_paths'] subjects_path = next((sd for sd in sdirs if os.path.isdir(sd)), None) if subjects_path is None: raise ValueError('No subjects path given or found') else: subjects_path = os.path.expanduser(subjects_path) # Make sure we can connect to the bucket first... fs = s3fs.S3FileSystem(key=s3fs_key, secret=s3fs_secret) # Okay, make sure the release is found if not fs.exists('/'.join([database, release])): raise ValueError('database/release (%s/%s) not found' % (database, release)) # Check on the subject id to sid = to_subject_id(sid) hcp_sdir = '/'.join([database, release, str(sid)]) if not fs.exists(hcp_sdir): raise ValueError('Subject %d not found in release' % sid) # Okay, lets download this subject! loc_sdir = os.path.join(subjects_path, str(sid)) # walk through the subject structures pulled = [] for flnm in six.iterkeys(subject_structure['filemap']): flnm = flnm.format({'id':sid}) loc_flnm = os.path.join(loc_sdir, flnm) hcp_flnm = '/'.join([hcp_sdir, flnm]) if not overwrite and os.path.isfile(loc_flnm): continue # gotta download it! basedir = os.path.split(loc_flnm)[0] if not os.path.isdir(basedir): os.makedirs(os.path.abspath(basedir), 0o755) fs.get(hcp_flnm, loc_flnm) pulled.append(loc_flnm) return pulled
[ "def", "download", "(", "sid", ",", "credentials", "=", "None", ",", "subjects_path", "=", "None", ",", "overwrite", "=", "False", ",", "release", "=", "'HCP_1200'", ",", "database", "=", "'hcp-openaccess'", ",", "file_list", "=", "None", ")", ":", "if", ...
download(sid) downloads the data for subject with the given subject id. By default, the subject will be placed in the first HCP subject directory in the subjects directories list. Note: In order for downloading to work, you must have s3fs installed. This is not a requirement for the neuropythy library and does not install automatically when installing via pip. The github repository for this library can be found at https://github.com/dask/s3fs. Installation instructions can be found here: http://s3fs.readthedocs.io/en/latest/install.html Accepted options include: * credentials (default: None) may be used to specify the Amazon AWS Bucket credentials, which can be generated from the HCP db (https://db.humanconnectome.org/). If this argument can be coerced to a credentials tuple via the to_credentials function, that result will be used. If None, then the function will try to use the hcp_credentials configuration item in neuropythy.config; otherwise an error is raised. * subjects_path (default: None) specifies where the subject should be placed. If None, then the first directory in the subjects paths list is used. If there is not one of these then an error is raised. * overwrite (default: False) specifies whether or not to overwrite files that already exist. In addition to True (do overwrite) and False (don't overwrite), the value 'error' indicates that an error should be raised if a file already exists.
[ "download", "(", "sid", ")", "downloads", "the", "data", "for", "subject", "with", "the", "given", "subject", "id", ".", "By", "default", "the", "subject", "will", "be", "placed", "in", "the", "first", "HCP", "subject", "directory", "in", "the", "subjects"...
python
train
cgarciae/phi
phi/dsl.py
https://github.com/cgarciae/phi/blob/87fd7100a76f823232f4fd8360498b4b80675265/phi/dsl.py#L661-L666
def Then3(self, f, arg1, arg2, *args, **kwargs): """ `Then3(f, ...)` is equivalent to `ThenAt(3, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information. """ args = (arg1, arg2) + args return self.ThenAt(3, f, *args, **kwargs)
[ "def", "Then3", "(", "self", ",", "f", ",", "arg1", ",", "arg2", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args", "=", "(", "arg1", ",", "arg2", ")", "+", "args", "return", "self", ".", "ThenAt", "(", "3", ",", "f", ",", "*", "a...
`Then3(f, ...)` is equivalent to `ThenAt(3, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information.
[ "Then3", "(", "f", "...", ")", "is", "equivalent", "to", "ThenAt", "(", "3", "f", "...", ")", ".", "Checkout", "phi", ".", "builder", ".", "Builder", ".", "ThenAt", "for", "more", "information", "." ]
python
train
saltstack/salt
salt/pillar/file_tree.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/file_tree.py#L174-L192
def _check_newline(prefix, file_name, keep_newline): ''' Return a boolean stating whether or not a file's trailing newline should be removed. To figure this out, first check if keep_newline is a boolean and if so, return its opposite. Otherwise, iterate over keep_newline and check if any of the patterns match the file path. If a match is found, return False, otherwise return True. ''' if isinstance(keep_newline, bool): return not keep_newline full_path = os.path.join(prefix, file_name) for pattern in keep_newline: try: if fnmatch.fnmatch(full_path, pattern): return False except TypeError: if fnmatch.fnmatch(full_path, six.text_type(pattern)): return False return True
[ "def", "_check_newline", "(", "prefix", ",", "file_name", ",", "keep_newline", ")", ":", "if", "isinstance", "(", "keep_newline", ",", "bool", ")", ":", "return", "not", "keep_newline", "full_path", "=", "os", ".", "path", ".", "join", "(", "prefix", ",", ...
Return a boolean stating whether or not a file's trailing newline should be removed. To figure this out, first check if keep_newline is a boolean and if so, return its opposite. Otherwise, iterate over keep_newline and check if any of the patterns match the file path. If a match is found, return False, otherwise return True.
[ "Return", "a", "boolean", "stating", "whether", "or", "not", "a", "file", "s", "trailing", "newline", "should", "be", "removed", ".", "To", "figure", "this", "out", "first", "check", "if", "keep_newline", "is", "a", "boolean", "and", "if", "so", "return", ...
python
train
bitesofcode/projexui
projexui/widgets/xcombobox.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xcombobox.py#L568-L583
def toggleModelIndex(self, modelIndex): """ Toggles the index's check state. :param modelIndex | <QModelIndex> """ if not self.isCheckable(): return item = self.model().item(modelIndex.row()) if item.checkState() == Qt.Checked: state = Qt.Unchecked else: state = Qt.Checked item.setCheckState(state)
[ "def", "toggleModelIndex", "(", "self", ",", "modelIndex", ")", ":", "if", "not", "self", ".", "isCheckable", "(", ")", ":", "return", "item", "=", "self", ".", "model", "(", ")", ".", "item", "(", "modelIndex", ".", "row", "(", ")", ")", "if", "it...
Toggles the index's check state. :param modelIndex | <QModelIndex>
[ "Toggles", "the", "index", "s", "check", "state", ".", ":", "param", "modelIndex", "|", "<QModelIndex", ">" ]
python
train
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_inspect.py
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L666-L672
def get_orm_column_names(cls: Type, sort: bool = False) -> List[str]: """ Gets column names (that is, database column names) from an SQLAlchemy ORM class. """ colnames = [col.name for col in get_orm_columns(cls)] return sorted(colnames) if sort else colnames
[ "def", "get_orm_column_names", "(", "cls", ":", "Type", ",", "sort", ":", "bool", "=", "False", ")", "->", "List", "[", "str", "]", ":", "colnames", "=", "[", "col", ".", "name", "for", "col", "in", "get_orm_columns", "(", "cls", ")", "]", "return", ...
Gets column names (that is, database column names) from an SQLAlchemy ORM class.
[ "Gets", "column", "names", "(", "that", "is", "database", "column", "names", ")", "from", "an", "SQLAlchemy", "ORM", "class", "." ]
python
train
bram85/topydo
topydo/lib/ChangeSet.py
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/ChangeSet.py#L36-L41
def get_backup_path(): """ Returns full path and filename of backup file """ dirname, filename = path.split(path.splitext(config().todotxt())[0]) filename = '.' + filename + '.bak' return path.join(dirname, filename)
[ "def", "get_backup_path", "(", ")", ":", "dirname", ",", "filename", "=", "path", ".", "split", "(", "path", ".", "splitext", "(", "config", "(", ")", ".", "todotxt", "(", ")", ")", "[", "0", "]", ")", "filename", "=", "'.'", "+", "filename", "+", ...
Returns full path and filename of backup file
[ "Returns", "full", "path", "and", "filename", "of", "backup", "file" ]
python
train
OpenKMIP/PyKMIP
kmip/core/messages/payloads/sign.py
https://github.com/OpenKMIP/PyKMIP/blob/b51c5b044bd05f8c85a1d65d13a583a4d8fc1b0e/kmip/core/messages/payloads/sign.py#L311-L355
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the Sign response payload and decode it. Args: input_stream (stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 1.0. Raises: ValueError: Raised if the unique_identifier or signature attributes are missing from the encoded payload. """ super(SignResponsePayload, self).read( input_stream, kmip_version=kmip_version ) local_stream = utils.BytearrayStream(input_stream.read(self.length)) if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_stream): self._unique_identifier = primitives.TextString( tag=enums.Tags.UNIQUE_IDENTIFIER ) self._unique_identifier.read( local_stream, kmip_version=kmip_version ) else: raise ValueError( "invalid payload missing the unique identifier attribute" ) if self.is_tag_next(enums.Tags.SIGNATURE_DATA, local_stream): self._signature_data = primitives.ByteString( tag=enums.Tags.SIGNATURE_DATA ) self._signature_data.read(local_stream, kmip_version=kmip_version) else: raise ValueError( "invalid payload missing the signature data attribute" )
[ "def", "read", "(", "self", ",", "input_stream", ",", "kmip_version", "=", "enums", ".", "KMIPVersion", ".", "KMIP_1_0", ")", ":", "super", "(", "SignResponsePayload", ",", "self", ")", ".", "read", "(", "input_stream", ",", "kmip_version", "=", "kmip_versio...
Read the data encoding the Sign response payload and decode it. Args: input_stream (stream): A data stream containing encoded object data, supporting a read method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults to KMIP 1.0. Raises: ValueError: Raised if the unique_identifier or signature attributes are missing from the encoded payload.
[ "Read", "the", "data", "encoding", "the", "Sign", "response", "payload", "and", "decode", "it", "." ]
python
test
6809/dragonlib
dragonlib/core/basic.py
https://github.com/6809/dragonlib/blob/faa4011e76c5857db96efdb4199e2fd49711e999/dragonlib/core/basic.py#L169-L192
def token_load(self, line_number, tokens): self.line_number = line_number assert tokens[-1] == 0x00, "line code %s doesn't ends with \\x00: %s" % ( repr(tokens), repr(tokens[-1]) ) """ NOTE: The BASIC interpreter changed REM shortcut and ELSE internaly: "'" <-> ":'" "ELSE" <-> ":ELSE" See also: http://archive.worldofdragon.org/phpBB3/viewtopic.php?f=8&t=4310&p=11632#p11630 """ for src, dst in self.tokens_replace_rules: log.info("Relace tokens %s with $%02x", pformat_byte_hex_list(src), dst ) log.debug("Before..: %s", pformat_byte_hex_list(tokens)) tokens = list_replace(tokens, src, dst) log.debug("After...: %s", pformat_byte_hex_list(tokens)) self.line_code = tokens[:-1]
[ "def", "token_load", "(", "self", ",", "line_number", ",", "tokens", ")", ":", "self", ".", "line_number", "=", "line_number", "assert", "tokens", "[", "-", "1", "]", "==", "0x00", ",", "\"line code %s doesn't ends with \\\\x00: %s\"", "%", "(", "repr", "(", ...
NOTE: The BASIC interpreter changed REM shortcut and ELSE internaly: "'" <-> ":'" "ELSE" <-> ":ELSE" See also: http://archive.worldofdragon.org/phpBB3/viewtopic.php?f=8&t=4310&p=11632#p11630
[ "NOTE", ":", "The", "BASIC", "interpreter", "changed", "REM", "shortcut", "and", "ELSE", "internaly", ":", "<", "-", ">", ":", "ELSE", "<", "-", ">", ":", "ELSE" ]
python
train
frawau/aiolifx
aiolifx/aiolifx.py
https://github.com/frawau/aiolifx/blob/9bd8c5e6d291f4c79314989402f7e2c6476d5851/aiolifx/aiolifx.py#L1248-L1259
def cleanup(self): """Method to call to cleanly terminate the connection to the device. """ if self.transport: self.transport.close() self.transport = None if self.task: self.task.cancel() self.task = None for light in self.lights.values(): light.cleanup() self.lights = {}
[ "def", "cleanup", "(", "self", ")", ":", "if", "self", ".", "transport", ":", "self", ".", "transport", ".", "close", "(", ")", "self", ".", "transport", "=", "None", "if", "self", ".", "task", ":", "self", ".", "task", ".", "cancel", "(", ")", "...
Method to call to cleanly terminate the connection to the device.
[ "Method", "to", "call", "to", "cleanly", "terminate", "the", "connection", "to", "the", "device", "." ]
python
train
angr/angr
angr/analyses/cfg/cfg_fast.py
https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/analyses/cfg/cfg_fast.py#L1404-L1498
def _scan_irsb(self, cfg_job, current_func_addr): """ Generate a list of successors (generating them each as entries) to IRSB. Updates previous CFG nodes with edges. :param CFGJob cfg_job: The CFGJob instance. :param int current_func_addr: Address of the current function :return: a list of successors :rtype: list """ addr, function_addr, cfg_node, irsb = self._generate_cfgnode(cfg_job, current_func_addr) # Add edges going to this node in function graphs cfg_job.apply_function_edges(self, clear=True) # function_addr and current_function_addr can be different. e.g. when tracing an optimized tail-call that jumps # into another function that has been identified before. if cfg_node is None: # exceptions occurred, or we cannot get a CFGNode for other reasons return [ ] self._graph_add_edge(cfg_node, cfg_job.src_node, cfg_job.jumpkind, cfg_job.src_ins_addr, cfg_job.src_stmt_idx ) self._function_add_node(cfg_node, function_addr) if self.functions.get_by_addr(function_addr).returning is not True: self._updated_nonreturning_functions.add(function_addr) # If we have traced it before, don't trace it anymore real_addr = get_real_address_if_arm(self.project.arch, addr) if real_addr in self._traced_addresses: # the address has been traced before return [ ] else: # Mark the address as traced self._traced_addresses.add(real_addr) # irsb cannot be None here # assert irsb is not None # IRSB is only used once per CFGNode. We should be able to clean up the CFGNode here in order to save memory cfg_node.irsb = None self._process_block_arch_specific(addr, irsb, function_addr) # Scan the basic block to collect data references if self._collect_data_ref: self._collect_data_references(irsb, addr) # Get all possible successors irsb_next, jumpkind = irsb.next, irsb.jumpkind successors = [ ] last_ins_addr = None ins_addr = addr if irsb.statements: for i, stmt in enumerate(irsb.statements): if isinstance(stmt, pyvex.IRStmt.Exit): successors.append((i, last_ins_addr if self.project.arch.branch_delay_slot else ins_addr, stmt.dst, stmt.jumpkind ) ) elif isinstance(stmt, pyvex.IRStmt.IMark): last_ins_addr = ins_addr ins_addr = stmt.addr + stmt.delta else: for ins_addr, stmt_idx, exit_stmt in irsb.exit_statements: successors.append(( stmt_idx, last_ins_addr if self.project.arch.branch_delay_slot else ins_addr, exit_stmt.dst, exit_stmt.jumpkind )) successors.append((DEFAULT_STATEMENT, last_ins_addr if self.project.arch.branch_delay_slot else ins_addr, irsb_next, jumpkind) ) entries = [ ] successors = self._post_process_successors(addr, irsb.size, successors) # Process each successor for suc in successors: stmt_idx, ins_addr, target, jumpkind = suc entries += self._create_jobs(target, jumpkind, function_addr, irsb, addr, cfg_node, ins_addr, stmt_idx ) return entries
[ "def", "_scan_irsb", "(", "self", ",", "cfg_job", ",", "current_func_addr", ")", ":", "addr", ",", "function_addr", ",", "cfg_node", ",", "irsb", "=", "self", ".", "_generate_cfgnode", "(", "cfg_job", ",", "current_func_addr", ")", "# Add edges going to this node ...
Generate a list of successors (generating them each as entries) to IRSB. Updates previous CFG nodes with edges. :param CFGJob cfg_job: The CFGJob instance. :param int current_func_addr: Address of the current function :return: a list of successors :rtype: list
[ "Generate", "a", "list", "of", "successors", "(", "generating", "them", "each", "as", "entries", ")", "to", "IRSB", ".", "Updates", "previous", "CFG", "nodes", "with", "edges", "." ]
python
train
trailofbits/manticore
manticore/ethereum/detectors.py
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/detectors.py#L675-L712
def _in_user_func(state): """ :param state: current state :return: whether the current execution is in a user-defined function or not. NOTE / TODO / FIXME: As this may produce false postives, this is not in the base `Detector` class. It should be fixed at some point and moved there. See below. The first 4 bytes of tx data is keccak256 hash of the function signature that is called by given tx. All transactions start within Solidity dispatcher function: it takes passed hash and dispatches the execution to given function based on it. So: if we are in the dispatcher, *and contract have some functions* one of the first four tx data bytes will effectively have more than one solutions. BUT if contract have only a fallback function, the equation below may return more solutions when we are in a dispatcher function. <--- because of that, we warn that the detector is not that stable for contracts with only a fallback function. """ # If we are already in user function (we cached it) let's just return True in_function = state.context.get('in_function', False) prev_tx_count = state.context.get('prev_tx_count', 0) curr_tx_count = len(state.platform.transactions) new_human_tx = prev_tx_count != curr_tx_count if in_function and not new_human_tx: return True # This is expensive call, so we cache it in_function = len(state.solve_n(state.platform.current_transaction.data[:4], 2)) == 1 state.context['in_function'] = in_function state.context['prev_tx_count'] = curr_tx_count return in_function
[ "def", "_in_user_func", "(", "state", ")", ":", "# If we are already in user function (we cached it) let's just return True", "in_function", "=", "state", ".", "context", ".", "get", "(", "'in_function'", ",", "False", ")", "prev_tx_count", "=", "state", ".", "context",...
:param state: current state :return: whether the current execution is in a user-defined function or not. NOTE / TODO / FIXME: As this may produce false postives, this is not in the base `Detector` class. It should be fixed at some point and moved there. See below. The first 4 bytes of tx data is keccak256 hash of the function signature that is called by given tx. All transactions start within Solidity dispatcher function: it takes passed hash and dispatches the execution to given function based on it. So: if we are in the dispatcher, *and contract have some functions* one of the first four tx data bytes will effectively have more than one solutions. BUT if contract have only a fallback function, the equation below may return more solutions when we are in a dispatcher function. <--- because of that, we warn that the detector is not that stable for contracts with only a fallback function.
[ ":", "param", "state", ":", "current", "state", ":", "return", ":", "whether", "the", "current", "execution", "is", "in", "a", "user", "-", "defined", "function", "or", "not", "." ]
python
valid
Yelp/kafka-utils
kafka_utils/kafka_check/main.py
https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_check/main.py#L123-L171
def run(): """Verify command-line arguments and run commands""" args = parse_args() logging.basicConfig(level=logging.WARN) # to prevent flooding for sensu-check. logging.getLogger('kafka').setLevel(logging.CRITICAL) if args.controller_only and args.first_broker_only: terminate( status_code.WARNING, prepare_terminate_message( "Only one of controller_only and first_broker_only should be used", ), args.json, ) if args.controller_only or args.first_broker_only: if args.broker_id is None: terminate( status_code.WARNING, prepare_terminate_message("broker_id is not specified"), args.json, ) elif args.broker_id == -1: try: args.broker_id = get_broker_id(args.data_path) except Exception as e: terminate( status_code.WARNING, prepare_terminate_message("{}".format(e)), args.json, ) try: cluster_config = config.get_cluster_config( args.cluster_type, args.cluster_name, args.discovery_base_path, ) code, msg = args.command(cluster_config, args) except ConfigurationError as e: terminate( status_code.CRITICAL, prepare_terminate_message("ConfigurationError {0}".format(e)), args.json, ) terminate(code, msg, args.json)
[ "def", "run", "(", ")", ":", "args", "=", "parse_args", "(", ")", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "WARN", ")", "# to prevent flooding for sensu-check.", "logging", ".", "getLogger", "(", "'kafka'", ")", ".", "setLevel", "(",...
Verify command-line arguments and run commands
[ "Verify", "command", "-", "line", "arguments", "and", "run", "commands" ]
python
train
Jammy2211/PyAutoLens
autolens/data/array/scaled_array.py
https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/scaled_array.py#L122-L137
def grid_pixels_to_grid_arcsec(self, grid_pixels): """Convert a grid of (y,x) pixel coordinates to a grid of (y,x) arc second values. The pixel coordinate origin is at the top left corner of the grid, such that the pixel [0,0] corresponds to \ higher y arc-second coordinate value and lowest x arc-second coordinate. The arc-second coordinate origin is defined by the class attribute origin, and coordinates are shifted to this \ origin before computing their 1D grid pixel indexes. Parameters ---------- grid_pixels : ndarray The grid of (y,x) coordinates in pixels. """ return grid_util.grid_pixels_1d_to_grid_arcsec_1d(grid_pixels_1d=grid_pixels, shape=self.shape, pixel_scales=self.pixel_scales, origin=self.origin)
[ "def", "grid_pixels_to_grid_arcsec", "(", "self", ",", "grid_pixels", ")", ":", "return", "grid_util", ".", "grid_pixels_1d_to_grid_arcsec_1d", "(", "grid_pixels_1d", "=", "grid_pixels", ",", "shape", "=", "self", ".", "shape", ",", "pixel_scales", "=", "self", "....
Convert a grid of (y,x) pixel coordinates to a grid of (y,x) arc second values. The pixel coordinate origin is at the top left corner of the grid, such that the pixel [0,0] corresponds to \ higher y arc-second coordinate value and lowest x arc-second coordinate. The arc-second coordinate origin is defined by the class attribute origin, and coordinates are shifted to this \ origin before computing their 1D grid pixel indexes. Parameters ---------- grid_pixels : ndarray The grid of (y,x) coordinates in pixels.
[ "Convert", "a", "grid", "of", "(", "y", "x", ")", "pixel", "coordinates", "to", "a", "grid", "of", "(", "y", "x", ")", "arc", "second", "values", "." ]
python
valid
dnanexus/dx-toolkit
src/python/dxpy/cli/exec_io.py
https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/cli/exec_io.py#L486-L495
def update(self, new_inputs, strip_prefix=True): """ Updates the inputs dictionary with the key/value pairs from new_inputs, overwriting existing keys. """ if strip_prefix and self.input_name_prefix is not None: for i in new_inputs: if i.startswith(self.input_name_prefix): self.inputs[i[len(self.input_name_prefix):]] = new_inputs[i] else: self.inputs.update(new_inputs)
[ "def", "update", "(", "self", ",", "new_inputs", ",", "strip_prefix", "=", "True", ")", ":", "if", "strip_prefix", "and", "self", ".", "input_name_prefix", "is", "not", "None", ":", "for", "i", "in", "new_inputs", ":", "if", "i", ".", "startswith", "(", ...
Updates the inputs dictionary with the key/value pairs from new_inputs, overwriting existing keys.
[ "Updates", "the", "inputs", "dictionary", "with", "the", "key", "/", "value", "pairs", "from", "new_inputs", "overwriting", "existing", "keys", "." ]
python
train
yvesalexandre/bandicoot
bandicoot/helper/tools.py
https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/helper/tools.py#L237-L243
def antennas_missing_locations(user, Method=None): """ Return the number of antennas missing locations in the records of a given user. """ unique_antennas = set([record.position.antenna for record in user.records if record.position.antenna is not None]) return sum([1 for antenna in unique_antennas if user.antennas.get(antenna) is None])
[ "def", "antennas_missing_locations", "(", "user", ",", "Method", "=", "None", ")", ":", "unique_antennas", "=", "set", "(", "[", "record", ".", "position", ".", "antenna", "for", "record", "in", "user", ".", "records", "if", "record", ".", "position", ".",...
Return the number of antennas missing locations in the records of a given user.
[ "Return", "the", "number", "of", "antennas", "missing", "locations", "in", "the", "records", "of", "a", "given", "user", "." ]
python
train
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L914-L925
def is_number_type_geographical(num_type, country_code): """Tests whether a phone number has a geographical association, as represented by its type and the country it belongs to. This version of isNumberGeographical exists since calculating the phone number type is expensive; if we have already done this, we don't want to do it again. """ return (num_type == PhoneNumberType.FIXED_LINE or num_type == PhoneNumberType.FIXED_LINE_OR_MOBILE or ((country_code in _GEO_MOBILE_COUNTRIES) and num_type == PhoneNumberType.MOBILE))
[ "def", "is_number_type_geographical", "(", "num_type", ",", "country_code", ")", ":", "return", "(", "num_type", "==", "PhoneNumberType", ".", "FIXED_LINE", "or", "num_type", "==", "PhoneNumberType", ".", "FIXED_LINE_OR_MOBILE", "or", "(", "(", "country_code", "in",...
Tests whether a phone number has a geographical association, as represented by its type and the country it belongs to. This version of isNumberGeographical exists since calculating the phone number type is expensive; if we have already done this, we don't want to do it again.
[ "Tests", "whether", "a", "phone", "number", "has", "a", "geographical", "association", "as", "represented", "by", "its", "type", "and", "the", "country", "it", "belongs", "to", "." ]
python
train
alberanid/python-iplib
iplib.py
https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L99-L111
def is_dot(ip): """Return true if the IP address is in dotted decimal notation.""" octets = str(ip).split('.') if len(octets) != 4: return False for i in octets: try: val = int(i) except ValueError: return False if val > 255 or val < 0: return False return True
[ "def", "is_dot", "(", "ip", ")", ":", "octets", "=", "str", "(", "ip", ")", ".", "split", "(", "'.'", ")", "if", "len", "(", "octets", ")", "!=", "4", ":", "return", "False", "for", "i", "in", "octets", ":", "try", ":", "val", "=", "int", "("...
Return true if the IP address is in dotted decimal notation.
[ "Return", "true", "if", "the", "IP", "address", "is", "in", "dotted", "decimal", "notation", "." ]
python
valid
raamana/hiwenet
hiwenet/pairwise_dist.py
https://github.com/raamana/hiwenet/blob/b12699b3722fd0a6a835e7d7ca4baf58fb181809/hiwenet/pairwise_dist.py#L674-L700
def parse_args(): """Parser/validator for the cmd line args.""" parser = get_parser() if len(sys.argv) < 2: parser.print_help() warnings.warn('Too few arguments!', UserWarning) parser.exit(1) # parsing try: params = parser.parse_args() except Exception as exc: print(exc) raise ValueError('Unable to parse command-line arguments.') in_features_path = os.path.abspath(params.in_features_path) if not os.path.exists(in_features_path): raise IOError("Given features file doesn't exist.") groups_path = os.path.abspath(params.groups_path) if not os.path.exists(groups_path): raise IOError("Given groups file doesn't exist.") return in_features_path, groups_path, params.weight_method, params.num_bins, params.edge_range, \ params.trim_outliers, params.trim_percentile, params.return_networkx_graph, params.out_weights_path
[ "def", "parse_args", "(", ")", ":", "parser", "=", "get_parser", "(", ")", "if", "len", "(", "sys", ".", "argv", ")", "<", "2", ":", "parser", ".", "print_help", "(", ")", "warnings", ".", "warn", "(", "'Too few arguments!'", ",", "UserWarning", ")", ...
Parser/validator for the cmd line args.
[ "Parser", "/", "validator", "for", "the", "cmd", "line", "args", "." ]
python
train
marshmallow-code/webargs
src/webargs/tornadoparser.py
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/tornadoparser.py#L34-L47
def parse_json_body(req): """Return the decoded JSON body from the request.""" content_type = req.headers.get("Content-Type") if content_type and core.is_json(content_type): try: return core.parse_json(req.body) except TypeError: pass except json.JSONDecodeError as e: if e.doc == "": return core.missing else: raise return {}
[ "def", "parse_json_body", "(", "req", ")", ":", "content_type", "=", "req", ".", "headers", ".", "get", "(", "\"Content-Type\"", ")", "if", "content_type", "and", "core", ".", "is_json", "(", "content_type", ")", ":", "try", ":", "return", "core", ".", "...
Return the decoded JSON body from the request.
[ "Return", "the", "decoded", "JSON", "body", "from", "the", "request", "." ]
python
train
box/flaky
flaky/_flaky_plugin.py
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/_flaky_plugin.py#L495-L512
def _get_flaky_attributes(cls, test_item): """ Get all the flaky related attributes from the test. :param test_item: The test callable from which to get the flaky related attributes. :type test_item: `callable` or :class:`nose.case.Test` or :class:`Function` :return: :rtype: `dict` of `unicode` to varies """ return { attr: cls._get_flaky_attribute( test_item, attr, ) for attr in FlakyNames() }
[ "def", "_get_flaky_attributes", "(", "cls", ",", "test_item", ")", ":", "return", "{", "attr", ":", "cls", ".", "_get_flaky_attribute", "(", "test_item", ",", "attr", ",", ")", "for", "attr", "in", "FlakyNames", "(", ")", "}" ]
Get all the flaky related attributes from the test. :param test_item: The test callable from which to get the flaky related attributes. :type test_item: `callable` or :class:`nose.case.Test` or :class:`Function` :return: :rtype: `dict` of `unicode` to varies
[ "Get", "all", "the", "flaky", "related", "attributes", "from", "the", "test", "." ]
python
train
kubernetes-client/python
kubernetes/client/apis/apps_v1_api.py
https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/apps_v1_api.py#L4963-L4984
def read_namespaced_daemon_set_status(self, name, namespace, **kwargs): """ read status of the specified DaemonSet This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_daemon_set_status(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the DaemonSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. :return: V1DaemonSet If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.read_namespaced_daemon_set_status_with_http_info(name, namespace, **kwargs) else: (data) = self.read_namespaced_daemon_set_status_with_http_info(name, namespace, **kwargs) return data
[ "def", "read_namespaced_daemon_set_status", "(", "self", ",", "name", ",", "namespace", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self"...
read status of the specified DaemonSet This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_daemon_set_status(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the DaemonSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. :return: V1DaemonSet If the method is called asynchronously, returns the request thread.
[ "read", "status", "of", "the", "specified", "DaemonSet", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "pass", "async_req", "=", "True", ">>>", "thread",...
python
train
dddomodossola/remi
remi/gui.py
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L143-L158
def decorate_set_on_listener(prototype): """ Private decorator for use in the editor. Allows the Editor to create listener methods. Args: params (str): The list of parameters for the listener method (es. "(self, new_value)") """ # noinspection PyDictCreation,PyProtectedMember def add_annotation(method): method._event_info = {} method._event_info['name'] = method.__name__ method._event_info['prototype'] = prototype return method return add_annotation
[ "def", "decorate_set_on_listener", "(", "prototype", ")", ":", "# noinspection PyDictCreation,PyProtectedMember", "def", "add_annotation", "(", "method", ")", ":", "method", ".", "_event_info", "=", "{", "}", "method", ".", "_event_info", "[", "'name'", "]", "=", ...
Private decorator for use in the editor. Allows the Editor to create listener methods. Args: params (str): The list of parameters for the listener method (es. "(self, new_value)")
[ "Private", "decorator", "for", "use", "in", "the", "editor", ".", "Allows", "the", "Editor", "to", "create", "listener", "methods", "." ]
python
train
erikrose/peep
peep.py
https://github.com/erikrose/peep/blob/c16f08c7f61e2f2afecb7cd1c93752bdd96c4968/peep.py#L935-L947
def main(): """Be the top-level entrypoint. Return a shell status code.""" commands = {'hash': peep_hash, 'install': peep_install, 'port': peep_port} try: if len(argv) >= 2 and argv[1] in commands: return commands[argv[1]](argv[2:]) else: # Fall through to top-level pip main() for everything else: return pip.main() except PipException as exc: return exc.error_code
[ "def", "main", "(", ")", ":", "commands", "=", "{", "'hash'", ":", "peep_hash", ",", "'install'", ":", "peep_install", ",", "'port'", ":", "peep_port", "}", "try", ":", "if", "len", "(", "argv", ")", ">=", "2", "and", "argv", "[", "1", "]", "in", ...
Be the top-level entrypoint. Return a shell status code.
[ "Be", "the", "top", "-", "level", "entrypoint", ".", "Return", "a", "shell", "status", "code", "." ]
python
train
hyperledger-archives/indy-anoncreds
anoncreds/protocol/issuer.py
https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/issuer.py#L34-L44
async def genSchema(self, name, version, attrNames) -> Schema: """ Generates and submits Schema. :param name: schema name :param version: schema version :param attrNames: a list of attributes the schema contains :return: submitted Schema """ schema = Schema(name, version, attrNames, self.issuerId) return await self.wallet.submitSchema(schema)
[ "async", "def", "genSchema", "(", "self", ",", "name", ",", "version", ",", "attrNames", ")", "->", "Schema", ":", "schema", "=", "Schema", "(", "name", ",", "version", ",", "attrNames", ",", "self", ".", "issuerId", ")", "return", "await", "self", "."...
Generates and submits Schema. :param name: schema name :param version: schema version :param attrNames: a list of attributes the schema contains :return: submitted Schema
[ "Generates", "and", "submits", "Schema", "." ]
python
train
projectshift/shift-schema
shiftschema/schema.py
https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/schema.py#L328-L352
def validate_properties(self, model, context=None): """ Validate simple properties Performs validation on simple properties to return a result object. :param model: object or dict :param context: object, dict or None :return: shiftschema.result.Result """ result = Result() for property_name in self.properties: prop = self.properties[property_name] value = self.get(model, property_name) errors = prop.validate( value=value, model=model, context=context ) if errors: result.add_errors( errors=errors, property_name=property_name ) return result
[ "def", "validate_properties", "(", "self", ",", "model", ",", "context", "=", "None", ")", ":", "result", "=", "Result", "(", ")", "for", "property_name", "in", "self", ".", "properties", ":", "prop", "=", "self", ".", "properties", "[", "property_name", ...
Validate simple properties Performs validation on simple properties to return a result object. :param model: object or dict :param context: object, dict or None :return: shiftschema.result.Result
[ "Validate", "simple", "properties", "Performs", "validation", "on", "simple", "properties", "to", "return", "a", "result", "object", ".", ":", "param", "model", ":", "object", "or", "dict", ":", "param", "context", ":", "object", "dict", "or", "None", ":", ...
python
train
angr/pyvex
pyvex/block.py
https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/block.py#L399-L404
def constants(self): """ The constants (excluding updates of the program counter) in the IRSB as :class:`pyvex.const.IRConst`. """ return sum( (s.constants for s in self.statements if not (type(s) is stmt.Put and s.offset == self.offsIP)), [])
[ "def", "constants", "(", "self", ")", ":", "return", "sum", "(", "(", "s", ".", "constants", "for", "s", "in", "self", ".", "statements", "if", "not", "(", "type", "(", "s", ")", "is", "stmt", ".", "Put", "and", "s", ".", "offset", "==", "self", ...
The constants (excluding updates of the program counter) in the IRSB as :class:`pyvex.const.IRConst`.
[ "The", "constants", "(", "excluding", "updates", "of", "the", "program", "counter", ")", "in", "the", "IRSB", "as", ":", "class", ":", "pyvex", ".", "const", ".", "IRConst", "." ]
python
train
ejeschke/ginga
ginga/gtk3w/Widgets.py
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/gtk3w/Widgets.py#L1446-L1449
def index_to_widget(self, idx): """Returns child corresponding to `idx`""" nchild = self.mdi_w.get_nth_page(idx) return self._native_to_child(nchild)
[ "def", "index_to_widget", "(", "self", ",", "idx", ")", ":", "nchild", "=", "self", ".", "mdi_w", ".", "get_nth_page", "(", "idx", ")", "return", "self", ".", "_native_to_child", "(", "nchild", ")" ]
Returns child corresponding to `idx`
[ "Returns", "child", "corresponding", "to", "idx" ]
python
train
osfclient/osfclient
osfclient/models/file.py
https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/models/file.py#L71-L92
def update(self, fp): """Update the remote file from a local file. Pass in a filepointer `fp` that has been opened for writing in binary mode. """ if 'b' not in fp.mode: raise ValueError("File has to be opened in binary mode.") url = self._upload_url # peek at the file to check if it is an ampty file which needs special # handling in requests. If we pass a file like object to data that # turns out to be of length zero then no file is created on the OSF if fp.peek(1): response = self._put(url, data=fp) else: response = self._put(url, data=b'') if response.status_code != 200: msg = ('Could not update {} (status ' 'code: {}).'.format(self.path, response.status_code)) raise RuntimeError(msg)
[ "def", "update", "(", "self", ",", "fp", ")", ":", "if", "'b'", "not", "in", "fp", ".", "mode", ":", "raise", "ValueError", "(", "\"File has to be opened in binary mode.\"", ")", "url", "=", "self", ".", "_upload_url", "# peek at the file to check if it is an ampt...
Update the remote file from a local file. Pass in a filepointer `fp` that has been opened for writing in binary mode.
[ "Update", "the", "remote", "file", "from", "a", "local", "file", "." ]
python
valid
Qiskit/qiskit-terra
qiskit/qasm/qasmparser.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qasm/qasmparser.py#L75-L89
def verify_declared_bit(self, obj): """Verify a qubit id against the gate prototype.""" # We are verifying gate args against the formal parameters of a # gate prototype. if obj.name not in self.current_symtab: raise QasmError("Cannot find symbol '" + obj.name + "' in argument list for gate, line", str(obj.line), 'file', obj.file) # This insures the thing is from the bitlist and not from the # argument list. sym = self.current_symtab[obj.name] if not (sym.type == 'id' and sym.is_bit): raise QasmError("Bit", obj.name, 'is not declared as a bit in the gate.')
[ "def", "verify_declared_bit", "(", "self", ",", "obj", ")", ":", "# We are verifying gate args against the formal parameters of a", "# gate prototype.", "if", "obj", ".", "name", "not", "in", "self", ".", "current_symtab", ":", "raise", "QasmError", "(", "\"Cannot find ...
Verify a qubit id against the gate prototype.
[ "Verify", "a", "qubit", "id", "against", "the", "gate", "prototype", "." ]
python
test
gophish/api-client-python
gophish/api/campaigns.py
https://github.com/gophish/api-client-python/blob/28a7790f19e13c92ef0fb7bde8cd89389df5c155/gophish/api/campaigns.py#L38-L51
def summary(self, campaign_id=None): """ Returns the campaign summary """ resource_cls = CampaignSummary single_resource = False if not campaign_id: resource_cls = CampaignSummaries single_resource = True return super(API, self).get( resource_id=campaign_id, resource_action='summary', resource_cls=resource_cls, single_resource=single_resource)
[ "def", "summary", "(", "self", ",", "campaign_id", "=", "None", ")", ":", "resource_cls", "=", "CampaignSummary", "single_resource", "=", "False", "if", "not", "campaign_id", ":", "resource_cls", "=", "CampaignSummaries", "single_resource", "=", "True", "return", ...
Returns the campaign summary
[ "Returns", "the", "campaign", "summary" ]
python
train
PlaidWeb/Publ
publ/index.py
https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/index.py#L198-L206
def prune_missing(table): """ Prune any files which are missing from the specified table """ try: for item in table.select(): if not os.path.isfile(item.file_path): logger.info("File disappeared: %s", item.file_path) item.delete() except: # pylint:disable=bare-except logger.exception("Error pruning %s", table)
[ "def", "prune_missing", "(", "table", ")", ":", "try", ":", "for", "item", "in", "table", ".", "select", "(", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "item", ".", "file_path", ")", ":", "logger", ".", "info", "(", "\"File disa...
Prune any files which are missing from the specified table
[ "Prune", "any", "files", "which", "are", "missing", "from", "the", "specified", "table" ]
python
train