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
bitesofcode/projex
projex/text.py
https://github.com/bitesofcode/projex/blob/d31743ec456a41428709968ab11a2cf6c6c76247/projex/text.py#L119-L132
def capitalize(text): """ Capitalizes the word using the normal string capitalization method, however if the word contains only capital letters and numbers, then it will not be affected. :param text | <str> :return <str> """ text = nativestring(text) if EXPR_CAPITALS.match(text): return text return text.capitalize()
[ "def", "capitalize", "(", "text", ")", ":", "text", "=", "nativestring", "(", "text", ")", "if", "EXPR_CAPITALS", ".", "match", "(", "text", ")", ":", "return", "text", "return", "text", ".", "capitalize", "(", ")" ]
Capitalizes the word using the normal string capitalization method, however if the word contains only capital letters and numbers, then it will not be affected. :param text | <str> :return <str>
[ "Capitalizes", "the", "word", "using", "the", "normal", "string", "capitalization", "method", "however", "if", "the", "word", "contains", "only", "capital", "letters", "and", "numbers", "then", "it", "will", "not", "be", "affected", ".", ":", "param", "text", ...
python
train
zeromake/aiko
aiko/response.py
https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/response.py#L352-L361
def flush_body(self) -> bool: """ 发送内容体 """ if self._body is None: return False elif isinstance(self._body, bytes): self.write(self._body) return True return False
[ "def", "flush_body", "(", "self", ")", "->", "bool", ":", "if", "self", ".", "_body", "is", "None", ":", "return", "False", "elif", "isinstance", "(", "self", ".", "_body", ",", "bytes", ")", ":", "self", ".", "write", "(", "self", ".", "_body", ")...
发送内容体
[ "发送内容体" ]
python
train
tango-controls/pytango
tango/encoded_attribute.py
https://github.com/tango-controls/pytango/blob/9cf78c517c9cdc1081ff6d080a9646a740cc1d36/tango/encoded_attribute.py#L358-L430
def __EncodedAttribute_encode_jpeg_rgb32(self, rgb32, width=0, height=0, quality=100.0): """Encode a 32 bit rgb color image as JPEG format. :param rgb32: an object containning image information :type rgb32: :py:obj:`str` or :class:`numpy.ndarray` or seq< seq<element> > :param width: image width. **MUST** be given if rgb32 is a string or if it is a :class:`numpy.ndarray` with ndims != 2. Otherwise it is calculated internally. :type width: :py:obj:`int` :param height: image height. **MUST** be given if rgb32 is a string or if it is a :class:`numpy.ndarray` with ndims != 2. Otherwise it is calculated internally. :type height: :py:obj:`int` .. note:: When :class:`numpy.ndarray` is given: - rgb32 **MUST** be CONTIGUOUS, ALIGNED - if rgb32.ndims != 2, width and height **MUST** be given and rgb32.nbytes/4 **MUST** match width*height - if rgb32.ndims == 2, rgb32.itemsize **MUST** be 4 (typically, rgb32.dtype is one of `numpy.dtype.int32`, `numpy.dtype.uint32`) Example:: def read_myattr(self, attr): enc = tango.EncodedAttribute() data = numpy.arange(100, dtype=numpy.int32) data = numpy.array((data,data,data)) enc.encode_jpeg_rgb32(data) attr.set_value(enc) """ if not is_seq(rgb32): raise TypeError("Expected sequence (str, numpy.ndarray, list, tuple " "or bytearray) as first argument") is_str = is_pure_str(rgb32) if is_str: if not width or not height: raise ValueError("When giving a string as data, you must also " "supply width and height") if np and isinstance(rgb32, np.ndarray): if rgb32.ndim != 2: if not width or not height: raise ValueError("When giving a non 2D numpy array, width and " "height must be supplied") if rgb32.nbytes / 4 != width * height: raise ValueError("numpy array size mismatch") else: if rgb32.itemsize != 4: raise TypeError("Expected numpy array with itemsize == 4") if not rgb32.flags.c_contiguous: raise TypeError("Currently, only contiguous, aligned numpy arrays " "are supported") if not rgb32.flags.aligned: raise TypeError("Currently, only contiguous, aligned numpy arrays " "are supported") if not is_str and (not width or not height): height = len(rgb32) if height < 1: raise IndexError("Expected sequence with at least one row") row0 = rgb32[0] if not is_seq(row0): raise IndexError("Expected sequence (str, numpy.ndarray, list, tuple or " "bytearray) inside a sequence") width = len(row0) if is_pure_str(row0) or type(row0) == bytearray: width /= 4 self._encode_jpeg_rgb32(rgb32, width, height, quality)
[ "def", "__EncodedAttribute_encode_jpeg_rgb32", "(", "self", ",", "rgb32", ",", "width", "=", "0", ",", "height", "=", "0", ",", "quality", "=", "100.0", ")", ":", "if", "not", "is_seq", "(", "rgb32", ")", ":", "raise", "TypeError", "(", "\"Expected sequenc...
Encode a 32 bit rgb color image as JPEG format. :param rgb32: an object containning image information :type rgb32: :py:obj:`str` or :class:`numpy.ndarray` or seq< seq<element> > :param width: image width. **MUST** be given if rgb32 is a string or if it is a :class:`numpy.ndarray` with ndims != 2. Otherwise it is calculated internally. :type width: :py:obj:`int` :param height: image height. **MUST** be given if rgb32 is a string or if it is a :class:`numpy.ndarray` with ndims != 2. Otherwise it is calculated internally. :type height: :py:obj:`int` .. note:: When :class:`numpy.ndarray` is given: - rgb32 **MUST** be CONTIGUOUS, ALIGNED - if rgb32.ndims != 2, width and height **MUST** be given and rgb32.nbytes/4 **MUST** match width*height - if rgb32.ndims == 2, rgb32.itemsize **MUST** be 4 (typically, rgb32.dtype is one of `numpy.dtype.int32`, `numpy.dtype.uint32`) Example:: def read_myattr(self, attr): enc = tango.EncodedAttribute() data = numpy.arange(100, dtype=numpy.int32) data = numpy.array((data,data,data)) enc.encode_jpeg_rgb32(data) attr.set_value(enc)
[ "Encode", "a", "32", "bit", "rgb", "color", "image", "as", "JPEG", "format", "." ]
python
train
gmr/tredis
tredis/client.py
https://github.com/gmr/tredis/blob/2e91c6a58a35460be0525c51ac6a98fde3b506ad/tredis/client.py#L358-L368
def ready(self): """Indicates that the client is connected to the Redis server or cluster and is ready for use. :rtype: bool """ if self._clustering: return (all([c.connected for c in self._cluster.values()]) and len(self._cluster)) return (self._connection and self._connection.connected)
[ "def", "ready", "(", "self", ")", ":", "if", "self", ".", "_clustering", ":", "return", "(", "all", "(", "[", "c", ".", "connected", "for", "c", "in", "self", ".", "_cluster", ".", "values", "(", ")", "]", ")", "and", "len", "(", "self", ".", "...
Indicates that the client is connected to the Redis server or cluster and is ready for use. :rtype: bool
[ "Indicates", "that", "the", "client", "is", "connected", "to", "the", "Redis", "server", "or", "cluster", "and", "is", "ready", "for", "use", "." ]
python
train
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/breakpoint.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/breakpoint.py#L2112-L2137
def __cleanup_thread(self, event): """ Auxiliary method for L{_notify_exit_thread} and L{_notify_exit_process}. """ tid = event.get_tid() # Cleanup running breakpoints try: for bp in self.__runningBP[tid]: self.__cleanup_breakpoint(event, bp) del self.__runningBP[tid] except KeyError: pass # Cleanup hardware breakpoints try: for bp in self.__hardwareBP[tid]: self.__cleanup_breakpoint(event, bp) del self.__hardwareBP[tid] except KeyError: pass # Cleanup set of threads being traced if tid in self.__tracing: self.__tracing.remove(tid)
[ "def", "__cleanup_thread", "(", "self", ",", "event", ")", ":", "tid", "=", "event", ".", "get_tid", "(", ")", "# Cleanup running breakpoints", "try", ":", "for", "bp", "in", "self", ".", "__runningBP", "[", "tid", "]", ":", "self", ".", "__cleanup_breakpo...
Auxiliary method for L{_notify_exit_thread} and L{_notify_exit_process}.
[ "Auxiliary", "method", "for", "L", "{", "_notify_exit_thread", "}", "and", "L", "{", "_notify_exit_process", "}", "." ]
python
train
brainiak/brainiak
brainiak/funcalign/sssrm.py
https://github.com/brainiak/brainiak/blob/408f12dec2ff56559a26873a848a09e4c8facfeb/brainiak/funcalign/sssrm.py#L584-L638
def _objective_function(self, data_align, data_sup, labels, w, s, theta, bias): """Compute the objective function of the Semi-Supervised SRM See :eq:`sssrm-eq`. Parameters ---------- data_align : list of 2D arrays, element i has shape=[voxels_i, n_align] Each element in the list contains the fMRI data for alignment of one subject. There are n_align samples for each subject. data_sup : list of 2D arrays, element i has shape=[voxels_i, samples_i] Each element in the list contains the fMRI data of one subject for the classification task. labels : list of arrays of int, element i has shape=[samples_i] Each element in the list contains the labels for the data samples in data_sup. w : list of array, element i has shape=[voxels_i, features] The orthogonal transforms (mappings) :math:`W_i` for each subject. s : array, shape=[features, samples] The shared response. theta : array, shape=[classes, features] The MLR class plane parameters. bias : array, shape=[classes] The MLR class biases. Returns ------- f_val : float The SS-SRM objective function evaluated based on the parameters to this function. """ subjects = len(data_align) # Compute the SRM loss f_val = 0.0 for subject in range(subjects): samples = data_align[subject].shape[1] f_val += (1 - self.alpha) * (0.5 / samples) \ * np.linalg.norm(data_align[subject] - w[subject].dot(s), 'fro')**2 # Compute the MLR loss f_val += self._loss_lr(data_sup, labels, w, theta, bias) return f_val
[ "def", "_objective_function", "(", "self", ",", "data_align", ",", "data_sup", ",", "labels", ",", "w", ",", "s", ",", "theta", ",", "bias", ")", ":", "subjects", "=", "len", "(", "data_align", ")", "# Compute the SRM loss", "f_val", "=", "0.0", "for", ...
Compute the objective function of the Semi-Supervised SRM See :eq:`sssrm-eq`. Parameters ---------- data_align : list of 2D arrays, element i has shape=[voxels_i, n_align] Each element in the list contains the fMRI data for alignment of one subject. There are n_align samples for each subject. data_sup : list of 2D arrays, element i has shape=[voxels_i, samples_i] Each element in the list contains the fMRI data of one subject for the classification task. labels : list of arrays of int, element i has shape=[samples_i] Each element in the list contains the labels for the data samples in data_sup. w : list of array, element i has shape=[voxels_i, features] The orthogonal transforms (mappings) :math:`W_i` for each subject. s : array, shape=[features, samples] The shared response. theta : array, shape=[classes, features] The MLR class plane parameters. bias : array, shape=[classes] The MLR class biases. Returns ------- f_val : float The SS-SRM objective function evaluated based on the parameters to this function.
[ "Compute", "the", "objective", "function", "of", "the", "Semi", "-", "Supervised", "SRM" ]
python
train
rasky/geventconnpool
src/geventconnpool/pool.py
https://github.com/rasky/geventconnpool/blob/47c65c64e051cb62061f3ed072991d6b0a83bbf5/src/geventconnpool/pool.py#L112-L144
def retry(f, exc_classes=DEFAULT_EXC_CLASSES, logger=None, retry_log_level=logging.INFO, retry_log_message="Connection broken in '{f}' (error: '{e}'); " "retrying with new connection.", max_failures=None, interval=0, max_failure_log_level=logging.ERROR, max_failure_log_message="Max retries reached for '{f}'. Aborting."): """ Decorator to automatically reexecute a function if the connection is broken for any reason. """ exc_classes = tuple(exc_classes) @wraps(f) def deco(*args, **kwargs): failures = 0 while True: try: return f(*args, **kwargs) except exc_classes as e: if logger is not None: logger.log(retry_log_level, retry_log_message.format(f=f.func_name, e=e)) gevent.sleep(interval) failures += 1 if max_failures is not None \ and failures > max_failures: if logger is not None: logger.log(max_failure_log_level, max_failure_log_message.format( f=f.func_name, e=e)) raise return deco
[ "def", "retry", "(", "f", ",", "exc_classes", "=", "DEFAULT_EXC_CLASSES", ",", "logger", "=", "None", ",", "retry_log_level", "=", "logging", ".", "INFO", ",", "retry_log_message", "=", "\"Connection broken in '{f}' (error: '{e}'); \"", "\"retrying with new connection.\""...
Decorator to automatically reexecute a function if the connection is broken for any reason.
[ "Decorator", "to", "automatically", "reexecute", "a", "function", "if", "the", "connection", "is", "broken", "for", "any", "reason", "." ]
python
train
tylertreat/BigQuery-Python
bigquery/client.py
https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L528-L552
def get_dataset(self, dataset_id, project_id=None): """Retrieve a dataset if it exists, otherwise return an empty dict. Parameters ---------- dataset_id : str Dataset unique id project_id: str, optional The project the dataset is in Returns ------- dict Contains dataset object if it exists, else empty """ project_id = self._get_project_id(project_id) try: dataset = self.bigquery.datasets().get( projectId=project_id, datasetId=dataset_id).execute( num_retries=self.num_retries) except HttpError: dataset = {} return dataset
[ "def", "get_dataset", "(", "self", ",", "dataset_id", ",", "project_id", "=", "None", ")", ":", "project_id", "=", "self", ".", "_get_project_id", "(", "project_id", ")", "try", ":", "dataset", "=", "self", ".", "bigquery", ".", "datasets", "(", ")", "."...
Retrieve a dataset if it exists, otherwise return an empty dict. Parameters ---------- dataset_id : str Dataset unique id project_id: str, optional The project the dataset is in Returns ------- dict Contains dataset object if it exists, else empty
[ "Retrieve", "a", "dataset", "if", "it", "exists", "otherwise", "return", "an", "empty", "dict", "." ]
python
train
collectiveacuity/labPack
labpack/records/time.py
https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/records/time.py#L145-L178
def humanFriendly(self, time_zone='', include_day=True, include_time=True): ''' a method to report a human friendly string from a labDT object :param time_zone: [optional] string with timezone to report in :return: string with date and time info ''' # validate inputs zeroHourPattern = re.compile('\s0\d:') title = 'Timezone input for labDT.humanFriendly' human_format = '' if include_day: human_format += '%A, ' human_format += '%B %d, %Y' if include_time: human_format += ' %I:%M%p %Z' get_tz = get_localzone() if time_zone: # if time_zone.lower() in ('utc', 'uct', 'universal', 'zulu'): # raise ValueError('time_zone cannot be UTC. %s requires a local timezone value. Try:\nfor tz in pytz.all_timezones:\n print tz' % title) try: get_tz = tz.gettz(time_zone) except: raise ValueError('%s is not a valid timezone format. Try:\nfor tz in pytz.all_timezones:\n print tz' % title) # construct human friendly string from labDT dtLocal = self.astimezone(get_tz) dtString = format(dtLocal, human_format) zeroHour = zeroHourPattern.findall(dtString) if zeroHour: noZero = zeroHour[0].replace(' 0',' ') dtString = zeroHourPattern.sub(noZero,dtString) return dtString
[ "def", "humanFriendly", "(", "self", ",", "time_zone", "=", "''", ",", "include_day", "=", "True", ",", "include_time", "=", "True", ")", ":", "# validate inputs\r", "zeroHourPattern", "=", "re", ".", "compile", "(", "'\\s0\\d:'", ")", "title", "=", "'Timezo...
a method to report a human friendly string from a labDT object :param time_zone: [optional] string with timezone to report in :return: string with date and time info
[ "a", "method", "to", "report", "a", "human", "friendly", "string", "from", "a", "labDT", "object", ":", "param", "time_zone", ":", "[", "optional", "]", "string", "with", "timezone", "to", "report", "in", ":", "return", ":", "string", "with", "date", "an...
python
train
NeuroML/NeuroMLlite
neuromllite/SonataReader.py
https://github.com/NeuroML/NeuroMLlite/blob/f3fa2ff662e40febfa97c045e7f0e6915ad04161/neuromllite/SonataReader.py#L699-L831
def add_neuroml_components(self, nml_doc): """ Based on cell & synapse properties found, create the corresponding NeuroML components """ is_nest = False print_v("Adding NeuroML cells to: %s"%nml_doc.id) #pp.pprint(self.pop_comp_info) for c in self.pop_comp_info: info = self.pop_comp_info[c] model_template = info['model_template'] if 'model_template' in info else \ (info['dynamics_params']['type'] if 'dynamics_params' in info else info['model_type']) print_v(" - Adding %s: %s"%(model_template, info)) if info['model_type'] == 'point_process' and model_template == 'nest:iaf_psc_alpha': is_nest = True from neuroml import IF_curr_alpha pynn0 = IF_curr_alpha(id=c, cm=info['dynamics_params']['C_m']/1000.0, i_offset="0", tau_m=info['dynamics_params']['tau_m'], tau_refrac=info['dynamics_params']['t_ref'], tau_syn_E="1", tau_syn_I="1", v_init='-70', v_reset=info['dynamics_params']['V_reset'], v_rest=info['dynamics_params']['E_L'], v_thresh=info['dynamics_params']['V_th']) nml_doc.IF_curr_alpha.append(pynn0) elif info['model_type'] == 'point_process' and model_template == 'NEURON_IntFire1': contents = '''<Lems> <intFire1Cell id="%s" thresh="1mV" reset="0mV" tau="%sms" refract="%sms"/> </Lems>'''%(c, info['dynamics_params']['tau']*1000, info['dynamics_params']['refrac']*1000) cell_file_name = '%s.xml'%c cell_file = open(cell_file_name,'w') cell_file.write(contents) cell_file.close() self.nml_includes.append(cell_file_name) self.nml_includes.append('../../../examples/sonatatest/IntFireCells.xml') else: from neuroml import IafRefCell IafRefCell0 = IafRefCell(id=DUMMY_CELL, C=".2 nF", thresh = "1mV", reset="0mV", refract="3ms", leak_conductance="1.2 nS", leak_reversal="0mV") print_v(" - Adding: %s"%IafRefCell0) nml_doc.iaf_ref_cells.append(IafRefCell0) print_v("Adding NeuroML synapses to: %s"%nml_doc.id) #pp.pprint(self.syn_comp_info) for s in self.syn_comp_info: dyn_params = self.syn_comp_info[s]['dynamics_params'] print_v(" - Syn: %s: %s"%(s, dyn_params)) if 'level_of_detail' in dyn_params and dyn_params['level_of_detail'] == 'exp2syn': from neuroml import ExpTwoSynapse syn = ExpTwoSynapse(id=s, gbase="1nS", erev="%smV"%dyn_params['erev'], tau_rise="%sms"%dyn_params['tau1'], tau_decay="%sms"%dyn_params['tau2']) #print("Adding syn: %s"%syn) nml_doc.exp_two_synapses.append(syn) elif 'level_of_detail' in dyn_params and dyn_params['level_of_detail'] == 'instanteneous': contents = '''<Lems> <impulseSynapse id="%s"/> </Lems>'''%(s) syn_file_name = '%s.xml'%s syn_file = open(syn_file_name,'w') syn_file.write(contents) syn_file.close() self.nml_includes.append(syn_file_name) #self.nml_includes.append('../examples/sonatatest/IntFireCells.xml') else: from neuroml import AlphaCurrSynapse pynnSynn0 = AlphaCurrSynapse(id=s, tau_syn="2") #print("Adding syn: %s"%pynnSynn0) nml_doc.alpha_curr_synapses.append(pynnSynn0) print_v("Adding NeuroML inputs to: %s"%nml_doc.id) #pp.pprint(self.input_comp_info) for input in self.input_comp_info: for input_type in self.input_comp_info[input]: if input_type == 'spikes': for comp_id in self.input_comp_info[input][input_type]: info = self.input_comp_info[input][input_type][comp_id] print_v("Adding input %s: %s"%(comp_id, info.keys())) nest_syn = _get_default_nest_syn(nml_doc) from neuroml import TimedSynapticInput, Spike tsi = TimedSynapticInput(id=comp_id, synapse=nest_syn.id, spike_target="./%s"%nest_syn.id) nml_doc.timed_synaptic_inputs.append(tsi) for ti in range(len(info['times'])): tsi.spikes.append(Spike(id=ti, time='%sms'%info['times'][ti])) elif input_type == 'current_clamp': from neuroml import PulseGenerator for comp_id in self.input_comp_info[input][input_type]: info = self.input_comp_info[input][input_type][comp_id] #TODO remove when https://github.com/AllenInstitute/sonata/issues/42 is fixed! amp_template = '%spA' if is_nest else '%snA' # pg = PulseGenerator(id=comp_id,delay='%sms'%info['delay'],duration='%sms'%info['duration'],amplitude=amp_template%info['amp']) nml_doc.pulse_generators.append(pg)
[ "def", "add_neuroml_components", "(", "self", ",", "nml_doc", ")", ":", "is_nest", "=", "False", "print_v", "(", "\"Adding NeuroML cells to: %s\"", "%", "nml_doc", ".", "id", ")", "#pp.pprint(self.pop_comp_info)", "for", "c", "in", "self", ".", "pop_comp_info", ":...
Based on cell & synapse properties found, create the corresponding NeuroML components
[ "Based", "on", "cell", "&", "synapse", "properties", "found", "create", "the", "corresponding", "NeuroML", "components" ]
python
train
wakatime/wakatime
wakatime/packages/ntlm_auth/compute_keys.py
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/ntlm_auth/compute_keys.py#L76-L96
def get_seal_key(negotiate_flags, exported_session_key, magic_constant): """ 3.4.5.3. SEALKEY Main method to use to calculate the seal_key used to seal (encrypt) messages. This will determine the correct method below to use based on the compatibility flags set and should be called instead of the others @param exported_session_key: A 128-bit session key used to derive signing and sealing keys @param negotiate_flags: The negotiate_flags structure sent by the server @param magic_constant: A constant value set in the MS-NLMP documentation (constants.SignSealConstants) @return seal_key: Key used to seal messages """ if negotiate_flags & NegotiateFlags.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY: seal_key = _get_seal_key_ntlm2(negotiate_flags, exported_session_key, magic_constant) elif negotiate_flags & NegotiateFlags.NTLMSSP_NEGOTIATE_LM_KEY: seal_key = _get_seal_key_ntlm1(negotiate_flags, exported_session_key) else: seal_key = exported_session_key return seal_key
[ "def", "get_seal_key", "(", "negotiate_flags", ",", "exported_session_key", ",", "magic_constant", ")", ":", "if", "negotiate_flags", "&", "NegotiateFlags", ".", "NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY", ":", "seal_key", "=", "_get_seal_key_ntlm2", "(", "negotiate_flags...
3.4.5.3. SEALKEY Main method to use to calculate the seal_key used to seal (encrypt) messages. This will determine the correct method below to use based on the compatibility flags set and should be called instead of the others @param exported_session_key: A 128-bit session key used to derive signing and sealing keys @param negotiate_flags: The negotiate_flags structure sent by the server @param magic_constant: A constant value set in the MS-NLMP documentation (constants.SignSealConstants) @return seal_key: Key used to seal messages
[ "3", ".", "4", ".", "5", ".", "3", ".", "SEALKEY", "Main", "method", "to", "use", "to", "calculate", "the", "seal_key", "used", "to", "seal", "(", "encrypt", ")", "messages", ".", "This", "will", "determine", "the", "correct", "method", "below", "to", ...
python
train
sdispater/eloquent
eloquent/query/builder.py
https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/query/builder.py#L1365-L1380
def delete(self, id=None): """ Delete a record from the database :param id: The id of the row to delete :type id: mixed :return: The number of rows deleted :rtype: int """ if id is not None: self.where('id', '=', id) sql = self._grammar.compile_delete(self) return self._connection.delete(sql, self.get_bindings())
[ "def", "delete", "(", "self", ",", "id", "=", "None", ")", ":", "if", "id", "is", "not", "None", ":", "self", ".", "where", "(", "'id'", ",", "'='", ",", "id", ")", "sql", "=", "self", ".", "_grammar", ".", "compile_delete", "(", "self", ")", "...
Delete a record from the database :param id: The id of the row to delete :type id: mixed :return: The number of rows deleted :rtype: int
[ "Delete", "a", "record", "from", "the", "database" ]
python
train
potash/drain
drain/drake.py
https://github.com/potash/drain/blob/ddd62081cb9317beb5d21f86c8b4bb196ca3d222/drain/drake.py#L52-L77
def to_drake_step(inputs, output): """ Args: inputs: collection of input Steps output: output Step Returns: a string of the drake step for the given inputs and output """ i = [output._yaml_filename] i.extend(map(lambda i: i._target_filename, list(inputs))) i.extend(output.dependencies) # add source file of output and its non-target inputs # if they're not in the drain library objects = get_inputs(output, target=False) objects.add(output) sources = set([os.path.abspath(inspect.getsourcefile(o.__class__)) for o in objects]) i.extend([s for s in sources if not s.startswith(os.path.dirname(__file__))]) output_str = '%' + output.__class__.__name__ if output.name: output_str += ', %' + output.name if output.target: output_str += ', ' + os.path.join(output._target_filename) return '{output} <- {inputs} [method:drain]\n\n'.format( output=output_str, inputs=str.join(', ', i))
[ "def", "to_drake_step", "(", "inputs", ",", "output", ")", ":", "i", "=", "[", "output", ".", "_yaml_filename", "]", "i", ".", "extend", "(", "map", "(", "lambda", "i", ":", "i", ".", "_target_filename", ",", "list", "(", "inputs", ")", ")", ")", "...
Args: inputs: collection of input Steps output: output Step Returns: a string of the drake step for the given inputs and output
[ "Args", ":", "inputs", ":", "collection", "of", "input", "Steps", "output", ":", "output", "Step" ]
python
train
coagulant/cleanweb
cleanweb.py
https://github.com/coagulant/cleanweb/blob/cc8f368d917037bf77772cd9fb068f898fd63d7e/cleanweb.py#L22-L32
def request(self, *args, **kwargs): """ Error handling in requests http://api.yandex.ru/cleanweb/doc/dg/concepts/error-codes.xml """ r = self.session.request(*args, **kwargs) if r.status_code != requests.codes.ok: error = ET.fromstring(r.content) message = error.findtext('message') code = error.attrib['key'] raise CleanwebError('%s (%s)' % (message, code)) return r
[ "def", "request", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "r", "=", "self", ".", "session", ".", "request", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "r", ".", "status_code", "!=", "requests", ".", "codes", ...
Error handling in requests http://api.yandex.ru/cleanweb/doc/dg/concepts/error-codes.xml
[ "Error", "handling", "in", "requests", "http", ":", "//", "api", ".", "yandex", ".", "ru", "/", "cleanweb", "/", "doc", "/", "dg", "/", "concepts", "/", "error", "-", "codes", ".", "xml" ]
python
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/public_ip.py
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/public_ip.py#L233-L246
def AddSourceRestrictions(self,cidrs): """Create one or more CIDR source restriction policies. Include a list of CIDR strings. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0] .AddSourceRestrictions(cidrs=["132.200.20.1/32","132.200.20.100/32"]).WaitUntilComplete() 0 """ for cidr in cidrs: self.source_restrictions.append(SourceRestriction(self,cidr)) return(self.Update())
[ "def", "AddSourceRestrictions", "(", "self", ",", "cidrs", ")", ":", "for", "cidr", "in", "cidrs", ":", "self", ".", "source_restrictions", ".", "append", "(", "SourceRestriction", "(", "self", ",", "cidr", ")", ")", "return", "(", "self", ".", "Update", ...
Create one or more CIDR source restriction policies. Include a list of CIDR strings. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0] .AddSourceRestrictions(cidrs=["132.200.20.1/32","132.200.20.100/32"]).WaitUntilComplete() 0
[ "Create", "one", "or", "more", "CIDR", "source", "restriction", "policies", "." ]
python
train
spacetelescope/pysynphot
pysynphot/spectrum.py
https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/spectrum.py#L906-L919
def GetWaveSet(self): """Obtain the wavelength set for the composite spectrum. This is done by using :func:`MergeWaveSets` to form a union of wavelength sets from its components. Returns ------- waveset : array_like Composite wavelength set. """ waveset1 = self.component1.GetWaveSet() waveset2 = self.component2.GetWaveSet() return MergeWaveSets(waveset1, waveset2)
[ "def", "GetWaveSet", "(", "self", ")", ":", "waveset1", "=", "self", ".", "component1", ".", "GetWaveSet", "(", ")", "waveset2", "=", "self", ".", "component2", ".", "GetWaveSet", "(", ")", "return", "MergeWaveSets", "(", "waveset1", ",", "waveset2", ")" ]
Obtain the wavelength set for the composite spectrum. This is done by using :func:`MergeWaveSets` to form a union of wavelength sets from its components. Returns ------- waveset : array_like Composite wavelength set.
[ "Obtain", "the", "wavelength", "set", "for", "the", "composite", "spectrum", ".", "This", "is", "done", "by", "using", ":", "func", ":", "MergeWaveSets", "to", "form", "a", "union", "of", "wavelength", "sets", "from", "its", "components", "." ]
python
train
Azure/msrestazure-for-python
msrestazure/azure_operation.py
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_operation.py#L166-L190
def _deserialize(self, response): """Attempt to deserialize resource from response. :param requests.Response response: latest REST call response. """ # Hacking response with initial status_code previous_status = response.status_code response.status_code = self.initial_status_code resource = self.get_outputs(response) response.status_code = previous_status # Hack for Storage or SQL, to workaround the bug in the Python generator if resource is None: previous_status = response.status_code for status_code_to_test in [200, 201]: try: response.status_code = status_code_to_test resource = self.get_outputs(response) except ClientException: pass else: return resource finally: response.status_code = previous_status return resource
[ "def", "_deserialize", "(", "self", ",", "response", ")", ":", "# Hacking response with initial status_code", "previous_status", "=", "response", ".", "status_code", "response", ".", "status_code", "=", "self", ".", "initial_status_code", "resource", "=", "self", ".",...
Attempt to deserialize resource from response. :param requests.Response response: latest REST call response.
[ "Attempt", "to", "deserialize", "resource", "from", "response", "." ]
python
train
base4sistemas/satcfe
satcfe/clientelocal.py
https://github.com/base4sistemas/satcfe/blob/cb8e8815f4133d3e3d94cf526fa86767b4521ed9/satcfe/clientelocal.py#L89-L96
def consultar_sat(self): """Sobrepõe :meth:`~satcfe.base.FuncoesSAT.consultar_sat`. :return: Uma resposta SAT padrão. :rtype: satcfe.resposta.padrao.RespostaSAT """ retorno = super(ClienteSATLocal, self).consultar_sat() return RespostaSAT.consultar_sat(retorno)
[ "def", "consultar_sat", "(", "self", ")", ":", "retorno", "=", "super", "(", "ClienteSATLocal", ",", "self", ")", ".", "consultar_sat", "(", ")", "return", "RespostaSAT", ".", "consultar_sat", "(", "retorno", ")" ]
Sobrepõe :meth:`~satcfe.base.FuncoesSAT.consultar_sat`. :return: Uma resposta SAT padrão. :rtype: satcfe.resposta.padrao.RespostaSAT
[ "Sobrepõe", ":", "meth", ":", "~satcfe", ".", "base", ".", "FuncoesSAT", ".", "consultar_sat", "." ]
python
train
mrcagney/gtfstk
gtfstk/miscellany.py
https://github.com/mrcagney/gtfstk/blob/c91494e6fefc02523889655a0dc92d1c0eee8d03/gtfstk/miscellany.py#L258-L286
def convert_dist(feed: "Feed", new_dist_units: str) -> "Feed": """ Convert the distances recorded in the ``shape_dist_traveled`` columns of the given Feed to the given distance units. New distance units must lie in :const:`.constants.DIST_UNITS`. Return the resulting feed. """ feed = feed.copy() if feed.dist_units == new_dist_units: # Nothing to do return feed old_dist_units = feed.dist_units feed.dist_units = new_dist_units converter = hp.get_convert_dist(old_dist_units, new_dist_units) if hp.is_not_null(feed.stop_times, "shape_dist_traveled"): feed.stop_times["shape_dist_traveled"] = feed.stop_times[ "shape_dist_traveled" ].map(converter) if hp.is_not_null(feed.shapes, "shape_dist_traveled"): feed.shapes["shape_dist_traveled"] = feed.shapes[ "shape_dist_traveled" ].map(converter) return feed
[ "def", "convert_dist", "(", "feed", ":", "\"Feed\"", ",", "new_dist_units", ":", "str", ")", "->", "\"Feed\"", ":", "feed", "=", "feed", ".", "copy", "(", ")", "if", "feed", ".", "dist_units", "==", "new_dist_units", ":", "# Nothing to do", "return", "feed...
Convert the distances recorded in the ``shape_dist_traveled`` columns of the given Feed to the given distance units. New distance units must lie in :const:`.constants.DIST_UNITS`. Return the resulting feed.
[ "Convert", "the", "distances", "recorded", "in", "the", "shape_dist_traveled", "columns", "of", "the", "given", "Feed", "to", "the", "given", "distance", "units", ".", "New", "distance", "units", "must", "lie", "in", ":", "const", ":", ".", "constants", ".",...
python
train
yyuu/botornado
boto/rds/__init__.py
https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/rds/__init__.py#L884-L939
def restore_dbinstance_from_point_in_time(self, source_instance_id, target_instance_id, use_latest=False, restore_time=None, dbinstance_class=None, port=None, availability_zone=None): """ Create a new DBInstance from a point in time. :type source_instance_id: string :param source_instance_id: The identifier for the source DBInstance. :type target_instance_id: string :param target_instance_id: The identifier of the new DBInstance. :type use_latest: bool :param use_latest: If True, the latest snapshot availabile will be used. :type restore_time: datetime :param restore_time: The date and time to restore from. Only used if use_latest is False. :type instance_class: str :param instance_class: The compute and memory capacity of the DBInstance. Valid values are: db.m1.small | db.m1.large | db.m1.xlarge | db.m2.2xlarge | db.m2.4xlarge :type port: int :param port: Port number on which database accepts connections. Valid values [1115-65535]. Defaults to 3306. :type availability_zone: str :param availability_zone: Name of the availability zone to place DBInstance into. :rtype: :class:`boto.rds.dbinstance.DBInstance` :return: The newly created DBInstance """ params = {'SourceDBInstanceIdentifier' : source_instance_id, 'TargetDBInstanceIdentifier' : target_instance_id} if use_latest: params['UseLatestRestorableTime'] = 'true' elif restore_time: params['RestoreTime'] = restore_time.isoformat() if dbinstance_class: params['DBInstanceClass'] = dbinstance_class if port: params['Port'] = port if availability_zone: params['AvailabilityZone'] = availability_zone return self.get_object('RestoreDBInstanceToPointInTime', params, DBInstance)
[ "def", "restore_dbinstance_from_point_in_time", "(", "self", ",", "source_instance_id", ",", "target_instance_id", ",", "use_latest", "=", "False", ",", "restore_time", "=", "None", ",", "dbinstance_class", "=", "None", ",", "port", "=", "None", ",", "availability_z...
Create a new DBInstance from a point in time. :type source_instance_id: string :param source_instance_id: The identifier for the source DBInstance. :type target_instance_id: string :param target_instance_id: The identifier of the new DBInstance. :type use_latest: bool :param use_latest: If True, the latest snapshot availabile will be used. :type restore_time: datetime :param restore_time: The date and time to restore from. Only used if use_latest is False. :type instance_class: str :param instance_class: The compute and memory capacity of the DBInstance. Valid values are: db.m1.small | db.m1.large | db.m1.xlarge | db.m2.2xlarge | db.m2.4xlarge :type port: int :param port: Port number on which database accepts connections. Valid values [1115-65535]. Defaults to 3306. :type availability_zone: str :param availability_zone: Name of the availability zone to place DBInstance into. :rtype: :class:`boto.rds.dbinstance.DBInstance` :return: The newly created DBInstance
[ "Create", "a", "new", "DBInstance", "from", "a", "point", "in", "time", "." ]
python
train
RSEmail/smtp-health-check
smtphealth/__init__.py
https://github.com/RSEmail/smtp-health-check/blob/7407ba4239dc609caeceec720f33c5d664e739cf/smtphealth/__init__.py#L207-L233
def run(self, host, port=25, with_ssl=False): """Executes a single health check against a remote host and port. This method may only be called once per object. :param host: The hostname or IP address of the SMTP server to check. :type host: str :param port: The port number of the SMTP server to check. :type port: int :param with_ssl: If ``True``, SSL will be initiated before attempting to get the banner message. :type with_ssl: bool """ try: dns_rec = self._lookup(host, port) self._connect(dns_rec) if with_ssl: self._wrap_ssl() banner = self._get_banner() self._check_banner(banner) except Exception: exc_type, exc_value, exc_tb = sys.exc_info() self.results['Exception-Type'] = str(exc_type.__name__) self.results['Exception-Value'] = str(exc_value) self.results['Exception-Traceback'] = repr(traceback.format_exc()) finally: self._close(with_ssl)
[ "def", "run", "(", "self", ",", "host", ",", "port", "=", "25", ",", "with_ssl", "=", "False", ")", ":", "try", ":", "dns_rec", "=", "self", ".", "_lookup", "(", "host", ",", "port", ")", "self", ".", "_connect", "(", "dns_rec", ")", "if", "with_...
Executes a single health check against a remote host and port. This method may only be called once per object. :param host: The hostname or IP address of the SMTP server to check. :type host: str :param port: The port number of the SMTP server to check. :type port: int :param with_ssl: If ``True``, SSL will be initiated before attempting to get the banner message. :type with_ssl: bool
[ "Executes", "a", "single", "health", "check", "against", "a", "remote", "host", "and", "port", ".", "This", "method", "may", "only", "be", "called", "once", "per", "object", "." ]
python
train
chaoss/grimoirelab-perceval
perceval/client.py
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/client.py#L225-L248
def setup_rate_limit_handler(self, sleep_for_rate=False, min_rate_to_sleep=MIN_RATE_LIMIT, rate_limit_header=RATE_LIMIT_HEADER, rate_limit_reset_header=RATE_LIMIT_RESET_HEADER): """Setup the rate limit handler. :param sleep_for_rate: sleep until rate limit is reset :param min_rate_to_sleep: minimun rate needed to make the fecthing process sleep :param rate_limit_header: header from where extract the rate limit data :param rate_limit_reset_header: header from where extract the rate limit reset data """ self.rate_limit = None self.rate_limit_reset_ts = None self.sleep_for_rate = sleep_for_rate self.rate_limit_header = rate_limit_header self.rate_limit_reset_header = rate_limit_reset_header if min_rate_to_sleep > self.MAX_RATE_LIMIT: msg = "Minimum rate to sleep value exceeded (%d)." msg += "High values might cause the client to sleep forever." msg += "Reset to %d." self.min_rate_to_sleep = self.MAX_RATE_LIMIT logger.warning(msg, min_rate_to_sleep, self.MAX_RATE_LIMIT) else: self.min_rate_to_sleep = min_rate_to_sleep
[ "def", "setup_rate_limit_handler", "(", "self", ",", "sleep_for_rate", "=", "False", ",", "min_rate_to_sleep", "=", "MIN_RATE_LIMIT", ",", "rate_limit_header", "=", "RATE_LIMIT_HEADER", ",", "rate_limit_reset_header", "=", "RATE_LIMIT_RESET_HEADER", ")", ":", "self", "....
Setup the rate limit handler. :param sleep_for_rate: sleep until rate limit is reset :param min_rate_to_sleep: minimun rate needed to make the fecthing process sleep :param rate_limit_header: header from where extract the rate limit data :param rate_limit_reset_header: header from where extract the rate limit reset data
[ "Setup", "the", "rate", "limit", "handler", "." ]
python
test
draperjames/qtpandas
qtpandas/ui/fallback/easygui/boxes/derived_boxes.py
https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/ui/fallback/easygui/boxes/derived_boxes.py#L30-L69
def ynbox(msg="Shall I continue?", title=" ", choices=("[<F1>]Yes", "[<F2>]No"), image=None, default_choice='[<F1>]Yes', cancel_choice='[<F2>]No'): """ Display a msgbox with choices of Yes and No. The returned value is calculated this way:: if the first choice ("Yes") is chosen, or if the dialog is cancelled: return True else: return False If invoked without a msg argument, displays a generic request for a confirmation that the user wishes to continue. So it can be used this way:: if ynbox(): pass # continue else: sys.exit(0) # exit the program :param msg: the msg to be displayed :type msg: str :param str title: the window title :param list choices: a list or tuple of the choices to be displayed :param str image: Filename of image to display :param str default_choice: The choice you want highlighted when the gui appears :param str cancel_choice: If the user presses the 'X' close, which button should be pressed :return: True if 'Yes' or dialog is cancelled, False if 'No' """ return boolbox(msg=msg, title=title, choices=choices, image=image, default_choice=default_choice, cancel_choice=cancel_choice)
[ "def", "ynbox", "(", "msg", "=", "\"Shall I continue?\"", ",", "title", "=", "\" \"", ",", "choices", "=", "(", "\"[<F1>]Yes\"", ",", "\"[<F2>]No\"", ")", ",", "image", "=", "None", ",", "default_choice", "=", "'[<F1>]Yes'", ",", "cancel_choice", "=", "'[<F2...
Display a msgbox with choices of Yes and No. The returned value is calculated this way:: if the first choice ("Yes") is chosen, or if the dialog is cancelled: return True else: return False If invoked without a msg argument, displays a generic request for a confirmation that the user wishes to continue. So it can be used this way:: if ynbox(): pass # continue else: sys.exit(0) # exit the program :param msg: the msg to be displayed :type msg: str :param str title: the window title :param list choices: a list or tuple of the choices to be displayed :param str image: Filename of image to display :param str default_choice: The choice you want highlighted when the gui appears :param str cancel_choice: If the user presses the 'X' close, which button should be pressed :return: True if 'Yes' or dialog is cancelled, False if 'No'
[ "Display", "a", "msgbox", "with", "choices", "of", "Yes", "and", "No", "." ]
python
train
projectshift/shift-boiler
boiler/collections/paginated_collection.py
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/collections/paginated_collection.py#L66-L74
def fetch_items(self): """ Fetch items Performs a query to retrieve items based on current query and pagination settings. """ offset = self.per_page * (self.page - 1) items = self._query.limit(self.per_page).offset(offset).all() return items
[ "def", "fetch_items", "(", "self", ")", ":", "offset", "=", "self", ".", "per_page", "*", "(", "self", ".", "page", "-", "1", ")", "items", "=", "self", ".", "_query", ".", "limit", "(", "self", ".", "per_page", ")", ".", "offset", "(", "offset", ...
Fetch items Performs a query to retrieve items based on current query and pagination settings.
[ "Fetch", "items", "Performs", "a", "query", "to", "retrieve", "items", "based", "on", "current", "query", "and", "pagination", "settings", "." ]
python
train
shmir/PyIxExplorer
ixexplorer/ixe_port.py
https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_port.py#L268-L274
def start_transmit(self, blocking=False): """ Start transmit on port. :param blocking: True - wait for traffic end, False - return after traffic start. """ self.session.start_transmit(blocking, False, self)
[ "def", "start_transmit", "(", "self", ",", "blocking", "=", "False", ")", ":", "self", ".", "session", ".", "start_transmit", "(", "blocking", ",", "False", ",", "self", ")" ]
Start transmit on port. :param blocking: True - wait for traffic end, False - return after traffic start.
[ "Start", "transmit", "on", "port", "." ]
python
train
jadolg/rocketchat_API
rocketchat_API/rocketchat.py
https://github.com/jadolg/rocketchat_API/blob/f220d094434991cb9892418245f054ea06f28aad/rocketchat_API/rocketchat.py#L348-L350
def channels_leave(self, room_id, **kwargs): """Causes the callee to be removed from the channel.""" return self.__call_api_post('channels.leave', roomId=room_id, kwargs=kwargs)
[ "def", "channels_leave", "(", "self", ",", "room_id", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "__call_api_post", "(", "'channels.leave'", ",", "roomId", "=", "room_id", ",", "kwargs", "=", "kwargs", ")" ]
Causes the callee to be removed from the channel.
[ "Causes", "the", "callee", "to", "be", "removed", "from", "the", "channel", "." ]
python
train
kxgames/vecrec
vecrec/shapes.py
https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L418-L423
def get_interpolated(self, target, extent): """ Return a new vector that has been moved towards the given target by the given extent. The extent should be between 0 and 1. """ result = self.copy() result.interpolate(target, extent) return result
[ "def", "get_interpolated", "(", "self", ",", "target", ",", "extent", ")", ":", "result", "=", "self", ".", "copy", "(", ")", "result", ".", "interpolate", "(", "target", ",", "extent", ")", "return", "result" ]
Return a new vector that has been moved towards the given target by the given extent. The extent should be between 0 and 1.
[ "Return", "a", "new", "vector", "that", "has", "been", "moved", "towards", "the", "given", "target", "by", "the", "given", "extent", ".", "The", "extent", "should", "be", "between", "0", "and", "1", "." ]
python
train
JarryShaw/PyPCAPKit
src/protocols/internet/hopopt.py
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/hopopt.py#L494-L622
def _read_opt_smf_dpd(self, code, *, desc): """Read HOPOPT SMF_DPD option. Structure of HOPOPT SMF_DPD option [RFC 5570]: * IPv6 SMF_DPD Option Header in I-DPD mode 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ... |0|0|0| 01000 | Opt. Data Len | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0|TidTy| TidLen| TaggerId (optional) ... | +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | Identifier ... +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 hopopt.smf_dpd.type Option Type 0 0 hopopt.smf_dpd.type.value Option Number 0 0 hopopt.smf_dpd.type.action Action (00) 0 2 hopopt.smf_dpd.type.change Change Flag (0) 1 8 hopopt.smf_dpd.length Length of Option Data 2 16 hopopt.smf_dpd.dpd_type DPD Type (0) 2 17 hopopt.smf_dpd.tid_type TaggerID Type 2 20 hopopt.smf_dpd.tid_len TaggerID Length 3 24 hopopt.smf_dpd.tid TaggerID ? ? hopopt.smf_dpd.id Identifier * IPv6 SMF_DPD Option Header in H-DPD Mode 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ... |0|0|0| OptType | Opt. Data Len | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |1| Hash Assist Value (HAV) ... +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 hopopt.smf_dpd.type Option Type 0 0 hopopt.smf_dpd.type.value Option Number 0 0 hopopt.smf_dpd.type.action Action (00) 0 2 hopopt.smf_dpd.type.change Change Flag (0) 1 8 hopopt.smf_dpd.length Length of Option Data 2 16 hopopt.smf_dpd.dpd_type DPD Type (1) 2 17 hopopt.smf_dpd.hav Hash Assist Value """ _type = self._read_opt_type(code) _size = self._read_unpack(1) _tidd = self._read_binary(1) if _tidd[0] == '0': _mode = 'I-DPD' _tidt = _TID_TYPE.get(_tidd[1:4], 'Unassigned') _tidl = int(_tidd[4:], base=2) if _tidt == 'NULL': if _tidl != 0: raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format') _iden = self._read_fileng(_size-1) opt = dict( desc=desc, type=_type, length=_size + 2, dpd_type=_mode, tid_type=_tidt, tid_len=_tidl, id=_iden, ) elif _tidt == 'IPv4': if _tidl != 3: raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format') _tidf = self._read_fileng(4) _iden = self._read_fileng(_size-4) opt = dict( desc=desc, type=_type, length=_size + 2, dpd_type=_mode, tid_type=_tidt, tid_len=_tidl, tid=ipaddress.ip_address(_tidf), id=_iden, ) elif _tidt == 'IPv6': if _tidl != 15: raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format') _tidf = self._read_fileng(15) _iden = self._read_fileng(_size-15) opt = dict( desc=desc, type=_type, length=_size + 2, dpd_type=_mode, tid_type=_tidt, tid_len=_tidl, tid=ipaddress.ip_address(_tidf), id=_iden, ) else: _tidf = self._read_unpack(_tidl+1) _iden = self._read_fileng(_size-_tidl-2) opt = dict( desc=desc, type=_type, length=_size + 2, dpd_type=_mode, tid_type=_tidt, tid_len=_tidl, tid=_tidf, id=_iden, ) elif _tidd[0] == '1': _data = self._read_binary(_size-1) opt = dict( desc=desc, type=_type, length=_size + 2, dpd_type=_mode, tid_type=_tidt, hav=_tidd[1:] + _data, ) else: raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format') return opt
[ "def", "_read_opt_smf_dpd", "(", "self", ",", "code", ",", "*", ",", "desc", ")", ":", "_type", "=", "self", ".", "_read_opt_type", "(", "code", ")", "_size", "=", "self", ".", "_read_unpack", "(", "1", ")", "_tidd", "=", "self", ".", "_read_binary", ...
Read HOPOPT SMF_DPD option. Structure of HOPOPT SMF_DPD option [RFC 5570]: * IPv6 SMF_DPD Option Header in I-DPD mode 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ... |0|0|0| 01000 | Opt. Data Len | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0|TidTy| TidLen| TaggerId (optional) ... | +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | Identifier ... +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 hopopt.smf_dpd.type Option Type 0 0 hopopt.smf_dpd.type.value Option Number 0 0 hopopt.smf_dpd.type.action Action (00) 0 2 hopopt.smf_dpd.type.change Change Flag (0) 1 8 hopopt.smf_dpd.length Length of Option Data 2 16 hopopt.smf_dpd.dpd_type DPD Type (0) 2 17 hopopt.smf_dpd.tid_type TaggerID Type 2 20 hopopt.smf_dpd.tid_len TaggerID Length 3 24 hopopt.smf_dpd.tid TaggerID ? ? hopopt.smf_dpd.id Identifier * IPv6 SMF_DPD Option Header in H-DPD Mode 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ... |0|0|0| OptType | Opt. Data Len | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |1| Hash Assist Value (HAV) ... +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 hopopt.smf_dpd.type Option Type 0 0 hopopt.smf_dpd.type.value Option Number 0 0 hopopt.smf_dpd.type.action Action (00) 0 2 hopopt.smf_dpd.type.change Change Flag (0) 1 8 hopopt.smf_dpd.length Length of Option Data 2 16 hopopt.smf_dpd.dpd_type DPD Type (1) 2 17 hopopt.smf_dpd.hav Hash Assist Value
[ "Read", "HOPOPT", "SMF_DPD", "option", "." ]
python
train
6809/MC6809
MC6809/components/mc6809_stack.py
https://github.com/6809/MC6809/blob/6ba2f5106df46689017b5d0b6d84d43b7ee6a240/MC6809/components/mc6809_stack.py#L149-L186
def instruction_PUL(self, opcode, m, register): """ All, some, or none of the processor registers are pulled from stack (with the exception of stack pointer itself). A single register may be pulled from the stack with condition codes set by doing an autoincrement load from the stack (example: LDX ,S++). source code forms: b7 b6 b5 b4 b3 b2 b1 b0 PC U Y X DP B A CC = pull order CC bits "HNZVC": ccccc """ assert register in (self.system_stack_pointer, self.user_stack_pointer) def pull(register_str, stack_pointer): reg_obj = self.register_str2object[register_str] reg_width = reg_obj.WIDTH # 8 / 16 if reg_width == 8: data = self.pull_byte(stack_pointer) else: assert reg_width == 16 data = self.pull_word(stack_pointer) reg_obj.set(data) # log.debug("$%x PUL%s:", self.program_counter, register.name) # m = postbyte if m & 0x01: pull(REG_CC, register) # 8 bit condition code register if m & 0x02: pull(REG_A, register) # 8 bit accumulator if m & 0x04: pull(REG_B, register) # 8 bit accumulator if m & 0x08: pull(REG_DP, register) # 8 bit direct page register if m & 0x10: pull(REG_X, register) # 16 bit index register if m & 0x20: pull(REG_Y, register) # 16 bit index register if m & 0x40: pull(REG_U, register) # 16 bit user-stack pointer if m & 0x80: pull(REG_PC, register)
[ "def", "instruction_PUL", "(", "self", ",", "opcode", ",", "m", ",", "register", ")", ":", "assert", "register", "in", "(", "self", ".", "system_stack_pointer", ",", "self", ".", "user_stack_pointer", ")", "def", "pull", "(", "register_str", ",", "stack_poin...
All, some, or none of the processor registers are pulled from stack (with the exception of stack pointer itself). A single register may be pulled from the stack with condition codes set by doing an autoincrement load from the stack (example: LDX ,S++). source code forms: b7 b6 b5 b4 b3 b2 b1 b0 PC U Y X DP B A CC = pull order CC bits "HNZVC": ccccc
[ "All", "some", "or", "none", "of", "the", "processor", "registers", "are", "pulled", "from", "stack", "(", "with", "the", "exception", "of", "stack", "pointer", "itself", ")", "." ]
python
train
wbond/asn1crypto
asn1crypto/x509.py
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/x509.py#L976-L1034
def build(cls, name_dict, use_printable=False): """ Creates a Name object from a dict of unicode string keys and values. The keys should be from NameType._map, or a dotted-integer OID unicode string. :param name_dict: A dict of name information, e.g. {"common_name": "Will Bond", "country_name": "US", "organization": "Codex Non Sufficit LC"} :param use_printable: A bool - if PrintableString should be used for encoding instead of UTF8String. This is for backwards compatibility with old software. :return: An x509.Name object """ rdns = [] if not use_printable: encoding_name = 'utf8_string' encoding_class = UTF8String else: encoding_name = 'printable_string' encoding_class = PrintableString # Sort the attributes according to NameType.preferred_order name_dict = OrderedDict( sorted( name_dict.items(), key=lambda item: NameType.preferred_ordinal(item[0]) ) ) for attribute_name, attribute_value in name_dict.items(): attribute_name = NameType.map(attribute_name) if attribute_name == 'email_address': value = EmailAddress(attribute_value) elif attribute_name == 'domain_component': value = DNSName(attribute_value) elif attribute_name in set(['dn_qualifier', 'country_name', 'serial_number']): value = DirectoryString( name='printable_string', value=PrintableString(attribute_value) ) else: value = DirectoryString( name=encoding_name, value=encoding_class(attribute_value) ) rdns.append(RelativeDistinguishedName([ NameTypeAndValue({ 'type': attribute_name, 'value': value }) ])) return cls(name='', value=RDNSequence(rdns))
[ "def", "build", "(", "cls", ",", "name_dict", ",", "use_printable", "=", "False", ")", ":", "rdns", "=", "[", "]", "if", "not", "use_printable", ":", "encoding_name", "=", "'utf8_string'", "encoding_class", "=", "UTF8String", "else", ":", "encoding_name", "=...
Creates a Name object from a dict of unicode string keys and values. The keys should be from NameType._map, or a dotted-integer OID unicode string. :param name_dict: A dict of name information, e.g. {"common_name": "Will Bond", "country_name": "US", "organization": "Codex Non Sufficit LC"} :param use_printable: A bool - if PrintableString should be used for encoding instead of UTF8String. This is for backwards compatibility with old software. :return: An x509.Name object
[ "Creates", "a", "Name", "object", "from", "a", "dict", "of", "unicode", "string", "keys", "and", "values", ".", "The", "keys", "should", "be", "from", "NameType", ".", "_map", "or", "a", "dotted", "-", "integer", "OID", "unicode", "string", "." ]
python
train
opencobra/memote
memote/support/consistency_helpers.py
https://github.com/opencobra/memote/blob/276630fcd4449fb7b914186edfd38c239e7052df/memote/support/consistency_helpers.py#L197-L212
def get_interface(model): """ Return the interface specific classes. Parameters ---------- model : cobra.Model The metabolic model under investigation. """ return ( model.solver.interface.Model, model.solver.interface.Constraint, model.solver.interface.Variable, model.solver.interface.Objective )
[ "def", "get_interface", "(", "model", ")", ":", "return", "(", "model", ".", "solver", ".", "interface", ".", "Model", ",", "model", ".", "solver", ".", "interface", ".", "Constraint", ",", "model", ".", "solver", ".", "interface", ".", "Variable", ",", ...
Return the interface specific classes. Parameters ---------- model : cobra.Model The metabolic model under investigation.
[ "Return", "the", "interface", "specific", "classes", "." ]
python
train
DancingQuanta/pyusbiss
usbiss/spi.py
https://github.com/DancingQuanta/pyusbiss/blob/fc64e123f1c97f53ad153c474d230ad38044c3cb/usbiss/spi.py#L118-L140
def exchange(self, data): """ Perform SPI transaction. The first received byte is either ACK or NACK. :TODO: enforce rule that up to 63 bytes of data can be sent. :TODO: enforce rule that there is no gaps in data bytes (what define a gap?) :param data: List of bytes :returns: List of bytes :rtype: List of bytes """ self._usbiss.write_data([self._usbiss.SPI_CMD] + data) response = self._usbiss.read_data(1 + len(data)) if len(response) != 0: response = self._usbiss.decode(response) status = response.pop(0) if status == 0: raise USBISSError('SPI Transmission Error') return response else: raise USBISSError('SPI Transmission Error: No bytes received!')
[ "def", "exchange", "(", "self", ",", "data", ")", ":", "self", ".", "_usbiss", ".", "write_data", "(", "[", "self", ".", "_usbiss", ".", "SPI_CMD", "]", "+", "data", ")", "response", "=", "self", ".", "_usbiss", ".", "read_data", "(", "1", "+", "le...
Perform SPI transaction. The first received byte is either ACK or NACK. :TODO: enforce rule that up to 63 bytes of data can be sent. :TODO: enforce rule that there is no gaps in data bytes (what define a gap?) :param data: List of bytes :returns: List of bytes :rtype: List of bytes
[ "Perform", "SPI", "transaction", "." ]
python
train
splunk/splunk-sdk-python
splunklib/results.py
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/results.py#L129-L154
def read(self, n=None): """Read at most *n* characters from this stream. If *n* is ``None``, return all available characters. """ response = b"" while n is None or n > 0: c = self.stream.read(1) if c == b"": break elif c == b"<": c += self.stream.read(1) if c == b"<?": while True: q = self.stream.read(1) if q == b">": break else: response += c if n is not None: n -= len(c) else: response += c if n is not None: n -= 1 return response
[ "def", "read", "(", "self", ",", "n", "=", "None", ")", ":", "response", "=", "b\"\"", "while", "n", "is", "None", "or", "n", ">", "0", ":", "c", "=", "self", ".", "stream", ".", "read", "(", "1", ")", "if", "c", "==", "b\"\"", ":", "break", ...
Read at most *n* characters from this stream. If *n* is ``None``, return all available characters.
[ "Read", "at", "most", "*", "n", "*", "characters", "from", "this", "stream", "." ]
python
train
rbarrois/mpdlcd
mpdlcd/vendor/lcdproc/screen.py
https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/vendor/lcdproc/screen.py#L94-L99
def set_timeout(self, timeout): """ Set Screen Timeout Duration """ if timeout > 0: self.timeout = timeout self.server.request("screen_set %s timeout %i" % (self.ref, (self.timeout * 8)))
[ "def", "set_timeout", "(", "self", ",", "timeout", ")", ":", "if", "timeout", ">", "0", ":", "self", ".", "timeout", "=", "timeout", "self", ".", "server", ".", "request", "(", "\"screen_set %s timeout %i\"", "%", "(", "self", ".", "ref", ",", "(", "se...
Set Screen Timeout Duration
[ "Set", "Screen", "Timeout", "Duration" ]
python
train
LuqueDaniel/pybooru
pybooru/api_danbooru.py
https://github.com/LuqueDaniel/pybooru/blob/60cd5254684d293b308f0b11b8f4ac2dce101479/pybooru/api_danbooru.py#L487-L494
def dmail_delete(self, dmail_id): """Delete a dmail. You can only delete dmails you own (Requires login). Parameters: dmail_id (int): where dmail_id is the dmail id. """ return self._get('dmails/{0}.json'.format(dmail_id), method='DELETE', auth=True)
[ "def", "dmail_delete", "(", "self", ",", "dmail_id", ")", ":", "return", "self", ".", "_get", "(", "'dmails/{0}.json'", ".", "format", "(", "dmail_id", ")", ",", "method", "=", "'DELETE'", ",", "auth", "=", "True", ")" ]
Delete a dmail. You can only delete dmails you own (Requires login). Parameters: dmail_id (int): where dmail_id is the dmail id.
[ "Delete", "a", "dmail", ".", "You", "can", "only", "delete", "dmails", "you", "own", "(", "Requires", "login", ")", "." ]
python
train
benmoran56/esper
esper.py
https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L67-L75
def remove_processor(self, processor_type: Processor) -> None: """Remove a Processor from the World, by type. :param processor_type: The class type of the Processor to remove. """ for processor in self._processors: if type(processor) == processor_type: processor.world = None self._processors.remove(processor)
[ "def", "remove_processor", "(", "self", ",", "processor_type", ":", "Processor", ")", "->", "None", ":", "for", "processor", "in", "self", ".", "_processors", ":", "if", "type", "(", "processor", ")", "==", "processor_type", ":", "processor", ".", "world", ...
Remove a Processor from the World, by type. :param processor_type: The class type of the Processor to remove.
[ "Remove", "a", "Processor", "from", "the", "World", "by", "type", "." ]
python
train
pymupdf/PyMuPDF
fitz/utils.py
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L528-L571
def getToC(doc, simple = True): """Create a table of contents. Args: simple: a bool to control output. Returns a list, where each entry consists of outline level, title, page number and link destination (if simple = False). For details see PyMuPDF's documentation. """ def recurse(olItem, liste, lvl): '''Recursively follow the outline item chain and record item information in a list.''' while olItem: if olItem.title: title = olItem.title else: title = " " if not olItem.isExternal: if olItem.uri: page = olItem.page + 1 else: page = -1 else: page = -1 if not simple: link = getLinkDict(olItem) liste.append([lvl, title, page, link]) else: liste.append([lvl, title, page]) if olItem.down: liste = recurse(olItem.down, liste, lvl+1) olItem = olItem.next return liste # check if document is open and not encrypted if doc.isClosed: raise ValueError("illegal operation on closed document") olItem = doc.outline if not olItem: return [] lvl = 1 liste = [] return recurse(olItem, liste, lvl)
[ "def", "getToC", "(", "doc", ",", "simple", "=", "True", ")", ":", "def", "recurse", "(", "olItem", ",", "liste", ",", "lvl", ")", ":", "'''Recursively follow the outline item chain and record item information in a list.'''", "while", "olItem", ":", "if", "olItem", ...
Create a table of contents. Args: simple: a bool to control output. Returns a list, where each entry consists of outline level, title, page number and link destination (if simple = False). For details see PyMuPDF's documentation.
[ "Create", "a", "table", "of", "contents", "." ]
python
train
praekelt/panya
panya/view_modifiers/items.py
https://github.com/praekelt/panya/blob/0fd621e15a7c11a2716a9554a2f820d6259818e5/panya/view_modifiers/items.py#L33-L38
def modify(self, view): """ adds the get item as extra context """ view.params['extra_context'][self.get['name']] = self.get['value'] return view
[ "def", "modify", "(", "self", ",", "view", ")", ":", "view", ".", "params", "[", "'extra_context'", "]", "[", "self", ".", "get", "[", "'name'", "]", "]", "=", "self", ".", "get", "[", "'value'", "]", "return", "view" ]
adds the get item as extra context
[ "adds", "the", "get", "item", "as", "extra", "context" ]
python
train
axltxl/m2bk
m2bk/config.py
https://github.com/axltxl/m2bk/blob/980083dfd17e6e783753a946e9aa809714551141/m2bk/config.py#L62-L72
def set_entry(key, value): """ Set a configuration entry :param key: key name :param value: value for this key :raises KeyError: if key is not str """ if type(key) != str: raise KeyError('key must be str') _config[key] = value
[ "def", "set_entry", "(", "key", ",", "value", ")", ":", "if", "type", "(", "key", ")", "!=", "str", ":", "raise", "KeyError", "(", "'key must be str'", ")", "_config", "[", "key", "]", "=", "value" ]
Set a configuration entry :param key: key name :param value: value for this key :raises KeyError: if key is not str
[ "Set", "a", "configuration", "entry" ]
python
train
ARMmbed/mbed-connector-api-python
mbed_connector_api/mbed_connector_api.py
https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L688-L715
def debug(self,onOff,level='DEBUG'): ''' Enable / Disable debugging :param bool onOff: turn debugging on / off :return: none ''' if onOff: if level == 'DEBUG': self.log.setLevel(logging.DEBUG) self._ch.setLevel(logging.DEBUG) self.log.debug("Debugging level DEBUG enabled") elif level == "INFO": self.log.setLevel(logging.INFO) self._ch.setLevel(logging.INFO) self.log.info("Debugging level INFO enabled") elif level == "WARN": self.log.setLevel(logging.WARN) self._ch.setLevel(logging.WARN) self.log.warn("Debugging level WARN enabled") elif level == "ERROR": self.log.setLevel(logging.ERROR) self._ch.setLevel(logging.ERROR) self.log.error("Debugging level ERROR enabled") else: self.log.setLevel(logging.ERROR) self._ch.setLevel(logging.ERROR) self.log.error("Unrecognized debug level `%s`, set to default level `ERROR` instead",level)
[ "def", "debug", "(", "self", ",", "onOff", ",", "level", "=", "'DEBUG'", ")", ":", "if", "onOff", ":", "if", "level", "==", "'DEBUG'", ":", "self", ".", "log", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "self", ".", "_ch", ".", "setLevel",...
Enable / Disable debugging :param bool onOff: turn debugging on / off :return: none
[ "Enable", "/", "Disable", "debugging", ":", "param", "bool", "onOff", ":", "turn", "debugging", "on", "/", "off", ":", "return", ":", "none" ]
python
train
apache/incubator-mxnet
python/mxnet/rtc.py
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/rtc.py#L112-L171
def get_kernel(self, name, signature): r"""Get CUDA kernel from compiled module. Parameters ---------- name : str String name of the kernel. signature : str Function signature for the kernel. For example, if a kernel is declared as:: extern "C" __global__ void axpy(const float *x, double *y, int alpha) Then its signature should be:: const float *x, double *y, int alpha or:: const float *, double *, int Note that `*` in signature marks an argument as array and `const` marks an argument as constant (input) array. Returns ------- CudaKernel CUDA kernels that can be launched on GPUs. """ hdl = CudaKernelHandle() is_ndarray = [] is_const = [] dtypes = [] pattern = re.compile(r"""^\s*(const)?\s*([\w_]+)\s*(\*)?\s*([\w_]+)?\s*$""") args = re.sub(r"\s+", " ", signature).split(",") for arg in args: match = pattern.match(arg) if not match or match.groups()[1] == 'const': raise ValueError( 'Invalid function prototype "%s". Must be in the ' 'form of "(const) type (*) (name)"'%arg) is_const.append(bool(match.groups()[0])) dtype = match.groups()[1] is_ndarray.append(bool(match.groups()[2])) if dtype not in _DTYPE_CPP_TO_NP: raise TypeError( "Unsupported kernel argument type %s. Supported types are: %s."%( arg, ','.join(_DTYPE_CPP_TO_NP.keys()))) dtypes.append(_DTYPE_NP_TO_MX[_DTYPE_CPP_TO_NP[dtype]]) check_call(_LIB.MXRtcCudaKernelCreate( self.handle, c_str(name), len(dtypes), c_array_buf(ctypes.c_int, array('i', is_ndarray)), c_array_buf(ctypes.c_int, array('i', is_const)), c_array_buf(ctypes.c_int, array('i', dtypes)), ctypes.byref(hdl))) return CudaKernel(hdl, name, is_ndarray, dtypes)
[ "def", "get_kernel", "(", "self", ",", "name", ",", "signature", ")", ":", "hdl", "=", "CudaKernelHandle", "(", ")", "is_ndarray", "=", "[", "]", "is_const", "=", "[", "]", "dtypes", "=", "[", "]", "pattern", "=", "re", ".", "compile", "(", "r\"\"\"^...
r"""Get CUDA kernel from compiled module. Parameters ---------- name : str String name of the kernel. signature : str Function signature for the kernel. For example, if a kernel is declared as:: extern "C" __global__ void axpy(const float *x, double *y, int alpha) Then its signature should be:: const float *x, double *y, int alpha or:: const float *, double *, int Note that `*` in signature marks an argument as array and `const` marks an argument as constant (input) array. Returns ------- CudaKernel CUDA kernels that can be launched on GPUs.
[ "r", "Get", "CUDA", "kernel", "from", "compiled", "module", "." ]
python
train
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_system_monitor_ext.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_system_monitor_ext.py#L81-L93
def show_system_monitor_output_switch_status_switch_state(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_system_monitor = ET.Element("show_system_monitor") config = show_system_monitor output = ET.SubElement(show_system_monitor, "output") switch_status = ET.SubElement(output, "switch-status") switch_state = ET.SubElement(switch_status, "switch-state") switch_state.text = kwargs.pop('switch_state') callback = kwargs.pop('callback', self._callback) return callback(config)
[ "def", "show_system_monitor_output_switch_status_switch_state", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "show_system_monitor", "=", "ET", ".", "Element", "(", "\"show_system_monitor\"", ")", "con...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
wummel/dosage
dosagelib/util.py
https://github.com/wummel/dosage/blob/a0109c3a46219f280e6e5e77183674e40da0f304/dosagelib/util.py#L132-L163
def tagre(tag, attribute, value, quote='"', before="", after=""): """Return a regular expression matching the given HTML tag, attribute and value. It matches the tag and attribute names case insensitive, and skips arbitrary whitespace and leading HTML attributes. The "<>" at the start and end of the HTML tag is also matched. @param tag: the tag name @ptype tag: string @param attribute: the attribute name @ptype attribute: string @param value: the attribute value @ptype value: string @param quote: the attribute quote (default ") @ptype quote: string @param after: match after attribute value but before end @ptype after: string @return: the generated regular expression suitable for re.compile() @rtype: string """ if before: prefix = r"[^>]*%s[^>]*\s+" % before else: prefix = r"(?:[^>]*\s+)?" attrs = dict( tag=case_insensitive_re(tag), attribute=case_insensitive_re(attribute), value=value, quote=quote, prefix=prefix, after=after, ) return r'<\s*%(tag)s\s+%(prefix)s%(attribute)s\s*=\s*%(quote)s%(value)s%(quote)s[^>]*%(after)s[^>]*>' % attrs
[ "def", "tagre", "(", "tag", ",", "attribute", ",", "value", ",", "quote", "=", "'\"'", ",", "before", "=", "\"\"", ",", "after", "=", "\"\"", ")", ":", "if", "before", ":", "prefix", "=", "r\"[^>]*%s[^>]*\\s+\"", "%", "before", "else", ":", "prefix", ...
Return a regular expression matching the given HTML tag, attribute and value. It matches the tag and attribute names case insensitive, and skips arbitrary whitespace and leading HTML attributes. The "<>" at the start and end of the HTML tag is also matched. @param tag: the tag name @ptype tag: string @param attribute: the attribute name @ptype attribute: string @param value: the attribute value @ptype value: string @param quote: the attribute quote (default ") @ptype quote: string @param after: match after attribute value but before end @ptype after: string @return: the generated regular expression suitable for re.compile() @rtype: string
[ "Return", "a", "regular", "expression", "matching", "the", "given", "HTML", "tag", "attribute", "and", "value", ".", "It", "matches", "the", "tag", "and", "attribute", "names", "case", "insensitive", "and", "skips", "arbitrary", "whitespace", "and", "leading", ...
python
train
tensorlayer/tensorlayer
examples/data_process/tutorial_fast_affine_transform.py
https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/examples/data_process/tutorial_fast_affine_transform.py#L52-L59
def example2(): """ Example 2: Applying all transforms in one is very FAST ! """ st = time.time() for _ in range(100): # Repeat 100 times and compute the averaged speed transform_matrix = create_transformation_matrix() result = tl.prepro.affine_transform_cv2(image, transform_matrix) # Transform the image using a single operation print("apply all transforms once took %fs for each image" % ((time.time() - st) / 100)) # usually 50x faster tl.vis.save_image(result, '_result_fast.png')
[ "def", "example2", "(", ")", ":", "st", "=", "time", ".", "time", "(", ")", "for", "_", "in", "range", "(", "100", ")", ":", "# Repeat 100 times and compute the averaged speed", "transform_matrix", "=", "create_transformation_matrix", "(", ")", "result", "=", ...
Example 2: Applying all transforms in one is very FAST !
[ "Example", "2", ":", "Applying", "all", "transforms", "in", "one", "is", "very", "FAST", "!" ]
python
valid
chaoss/grimoirelab-perceval
perceval/archive.py
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/archive.py#L285-L302
def _verify_archive(self): """Check whether the archive is valid or not. This method will check if tables were created and if they contain valid data. """ nentries = self._count_table_rows(self.ARCHIVE_TABLE) nmetadata = self._count_table_rows(self.METADATA_TABLE) if nmetadata > 1: msg = "archive %s metadata corrupted; multiple metadata entries" % (self.archive_path) raise ArchiveError(cause=msg) if nmetadata == 0 and nentries > 0: msg = "archive %s metadata is empty but %s entries were achived" % (self.archive_path) raise ArchiveError(cause=msg) logger.debug("Integrity of archive %s OK; entries: %s rows, metadata: %s rows", self.archive_path, nentries, nmetadata)
[ "def", "_verify_archive", "(", "self", ")", ":", "nentries", "=", "self", ".", "_count_table_rows", "(", "self", ".", "ARCHIVE_TABLE", ")", "nmetadata", "=", "self", ".", "_count_table_rows", "(", "self", ".", "METADATA_TABLE", ")", "if", "nmetadata", ">", "...
Check whether the archive is valid or not. This method will check if tables were created and if they contain valid data.
[ "Check", "whether", "the", "archive", "is", "valid", "or", "not", "." ]
python
test
RaRe-Technologies/smart_open
smart_open/smart_open_lib.py
https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/smart_open_lib.py#L504-L568
def _open_binary_stream(uri, mode, transport_params): """Open an arbitrary URI in the specified binary mode. Not all modes are supported for all protocols. :arg uri: The URI to open. May be a string, or something else. :arg str mode: The mode to open with. Must be rb, wb or ab. :arg transport_params: Keyword argumens for the transport layer. :returns: A file object and the filename :rtype: tuple """ if mode not in ('rb', 'rb+', 'wb', 'wb+', 'ab', 'ab+'): # # This should really be a ValueError, but for the sake of compatibility # with older versions, which raise NotImplementedError, we do the same. # raise NotImplementedError('unsupported mode: %r' % mode) if isinstance(uri, six.string_types): # this method just routes the request to classes handling the specific storage # schemes, depending on the URI protocol in `uri` filename = uri.split('/')[-1] parsed_uri = _parse_uri(uri) unsupported = "%r mode not supported for %r scheme" % (mode, parsed_uri.scheme) if parsed_uri.scheme == "file": fobj = io.open(parsed_uri.uri_path, mode) return fobj, filename elif parsed_uri.scheme in smart_open_ssh.SCHEMES: fobj = smart_open_ssh.open( parsed_uri.uri_path, mode, host=parsed_uri.host, user=parsed_uri.user, port=parsed_uri.port, ) return fobj, filename elif parsed_uri.scheme in smart_open_s3.SUPPORTED_SCHEMES: return _s3_open_uri(parsed_uri, mode, transport_params), filename elif parsed_uri.scheme == "hdfs": _check_kwargs(smart_open_hdfs.open, transport_params) return smart_open_hdfs.open(parsed_uri.uri_path, mode), filename elif parsed_uri.scheme == "webhdfs": kw = _check_kwargs(smart_open_webhdfs.open, transport_params) return smart_open_webhdfs.open(parsed_uri.uri_path, mode, **kw), filename elif parsed_uri.scheme.startswith('http'): # # The URI may contain a query string and fragments, which interfere # with our compressed/uncompressed estimation, so we strip them. # filename = P.basename(urlparse.urlparse(uri).path) kw = _check_kwargs(smart_open_http.open, transport_params) return smart_open_http.open(uri, mode, **kw), filename else: raise NotImplementedError("scheme %r is not supported", parsed_uri.scheme) elif hasattr(uri, 'read'): # simply pass-through if already a file-like # we need to return something as the file name, but we don't know what # so we probe for uri.name (e.g., this works with open() or tempfile.NamedTemporaryFile) # if the value ends with COMPRESSED_EXT, we will note it in _compression_wrapper() # if there is no such an attribute, we return "unknown" - this effectively disables any compression filename = getattr(uri, 'name', 'unknown') return uri, filename else: raise TypeError("don't know how to handle uri %r" % uri)
[ "def", "_open_binary_stream", "(", "uri", ",", "mode", ",", "transport_params", ")", ":", "if", "mode", "not", "in", "(", "'rb'", ",", "'rb+'", ",", "'wb'", ",", "'wb+'", ",", "'ab'", ",", "'ab+'", ")", ":", "#", "# This should really be a ValueError, but fo...
Open an arbitrary URI in the specified binary mode. Not all modes are supported for all protocols. :arg uri: The URI to open. May be a string, or something else. :arg str mode: The mode to open with. Must be rb, wb or ab. :arg transport_params: Keyword argumens for the transport layer. :returns: A file object and the filename :rtype: tuple
[ "Open", "an", "arbitrary", "URI", "in", "the", "specified", "binary", "mode", "." ]
python
train
HazyResearch/fonduer
src/fonduer/utils/data_model_utils/visual.py
https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/utils/data_model_utils/visual.py#L285-L326
def get_page_vert_percentile( mention, page_width=DEFAULT_WIDTH, page_height=DEFAULT_HEIGHT ): """Return which percentile from the TOP in the page the Mention is located in. Percentile is calculated where the top of the page is 0.0, and the bottom of the page is 1.0. For example, a Mention in at the top 1/4 of the page will have a percentile of 0.25. Page width and height are based on pt values:: Letter 612x792 Tabloid 792x1224 Ledger 1224x792 Legal 612x1008 Statement 396x612 Executive 540x720 A0 2384x3371 A1 1685x2384 A2 1190x1684 A3 842x1190 A4 595x842 A4Small 595x842 A5 420x595 B4 729x1032 B5 516x729 Folio 612x936 Quarto 610x780 10x14 720x1008 and should match the source documents. Letter size is used by default. Note that if a candidate is passed in, only the vertical percentil of its first Mention is returned. :param mention: The Mention to evaluate :param page_width: The width of the page. Default to Letter paper width. :param page_height: The heigh of the page. Default to Letter paper height. :rtype: float in [0.0, 1.0] """ span = _to_span(mention) return bbox_from_span(span).top / page_height
[ "def", "get_page_vert_percentile", "(", "mention", ",", "page_width", "=", "DEFAULT_WIDTH", ",", "page_height", "=", "DEFAULT_HEIGHT", ")", ":", "span", "=", "_to_span", "(", "mention", ")", "return", "bbox_from_span", "(", "span", ")", ".", "top", "/", "page_...
Return which percentile from the TOP in the page the Mention is located in. Percentile is calculated where the top of the page is 0.0, and the bottom of the page is 1.0. For example, a Mention in at the top 1/4 of the page will have a percentile of 0.25. Page width and height are based on pt values:: Letter 612x792 Tabloid 792x1224 Ledger 1224x792 Legal 612x1008 Statement 396x612 Executive 540x720 A0 2384x3371 A1 1685x2384 A2 1190x1684 A3 842x1190 A4 595x842 A4Small 595x842 A5 420x595 B4 729x1032 B5 516x729 Folio 612x936 Quarto 610x780 10x14 720x1008 and should match the source documents. Letter size is used by default. Note that if a candidate is passed in, only the vertical percentil of its first Mention is returned. :param mention: The Mention to evaluate :param page_width: The width of the page. Default to Letter paper width. :param page_height: The heigh of the page. Default to Letter paper height. :rtype: float in [0.0, 1.0]
[ "Return", "which", "percentile", "from", "the", "TOP", "in", "the", "page", "the", "Mention", "is", "located", "in", "." ]
python
train
astropy/photutils
photutils/detection/core.py
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/detection/core.py#L18-L126
def detect_threshold(data, snr, background=None, error=None, mask=None, mask_value=None, sigclip_sigma=3.0, sigclip_iters=None): """ Calculate a pixel-wise threshold image that can be used to detect sources. Parameters ---------- data : array_like The 2D array of the image. snr : float The signal-to-noise ratio per pixel above the ``background`` for which to consider a pixel as possibly being part of a source. background : float or array_like, optional The background value(s) of the input ``data``. ``background`` may either be a scalar value or a 2D image with the same shape as the input ``data``. If the input ``data`` has been background-subtracted, then set ``background`` to ``0.0``. If `None`, then a scalar background value will be estimated using sigma-clipped statistics. error : float or array_like, optional The Gaussian 1-sigma standard deviation of the background noise in ``data``. ``error`` should include all sources of "background" error, but *exclude* the Poisson error of the sources. If ``error`` is a 2D image, then it should represent the 1-sigma background error in each pixel of ``data``. If `None`, then a scalar background rms value will be estimated using sigma-clipped statistics. mask : array_like, bool, optional A boolean mask with the same shape as ``data``, where a `True` value indicates the corresponding element of ``data`` is masked. Masked pixels are ignored when computing the image background statistics. mask_value : float, optional An image data value (e.g., ``0.0``) that is ignored when computing the image background statistics. ``mask_value`` will be ignored if ``mask`` is input. sigclip_sigma : float, optional The number of standard deviations to use as the clipping limit when calculating the image background statistics. sigclip_iters : int, optional The number of iterations to perform sigma clipping, or `None` to clip until convergence is achieved (i.e., continue until the last iteration clips nothing) when calculating the image background statistics. Returns ------- threshold : 2D `~numpy.ndarray` A 2D image with the same shape as ``data`` containing the pixel-wise threshold values. See Also -------- :func:`photutils.segmentation.detect_sources` Notes ----- The ``mask``, ``mask_value``, ``sigclip_sigma``, and ``sigclip_iters`` inputs are used only if it is necessary to estimate ``background`` or ``error`` using sigma-clipped background statistics. If ``background`` and ``error`` are both input, then ``mask``, ``mask_value``, ``sigclip_sigma``, and ``sigclip_iters`` are ignored. """ if background is None or error is None: if astropy_version < '3.1': data_mean, data_median, data_std = sigma_clipped_stats( data, mask=mask, mask_value=mask_value, sigma=sigclip_sigma, iters=sigclip_iters) else: data_mean, data_median, data_std = sigma_clipped_stats( data, mask=mask, mask_value=mask_value, sigma=sigclip_sigma, maxiters=sigclip_iters) bkgrd_image = np.zeros_like(data) + data_mean bkgrdrms_image = np.zeros_like(data) + data_std if background is None: background = bkgrd_image else: if np.isscalar(background): background = np.zeros_like(data) + background else: if background.shape != data.shape: raise ValueError('If input background is 2D, then it ' 'must have the same shape as the input ' 'data.') if error is None: error = bkgrdrms_image else: if np.isscalar(error): error = np.zeros_like(data) + error else: if error.shape != data.shape: raise ValueError('If input error is 2D, then it ' 'must have the same shape as the input ' 'data.') return background + (error * snr)
[ "def", "detect_threshold", "(", "data", ",", "snr", ",", "background", "=", "None", ",", "error", "=", "None", ",", "mask", "=", "None", ",", "mask_value", "=", "None", ",", "sigclip_sigma", "=", "3.0", ",", "sigclip_iters", "=", "None", ")", ":", "if"...
Calculate a pixel-wise threshold image that can be used to detect sources. Parameters ---------- data : array_like The 2D array of the image. snr : float The signal-to-noise ratio per pixel above the ``background`` for which to consider a pixel as possibly being part of a source. background : float or array_like, optional The background value(s) of the input ``data``. ``background`` may either be a scalar value or a 2D image with the same shape as the input ``data``. If the input ``data`` has been background-subtracted, then set ``background`` to ``0.0``. If `None`, then a scalar background value will be estimated using sigma-clipped statistics. error : float or array_like, optional The Gaussian 1-sigma standard deviation of the background noise in ``data``. ``error`` should include all sources of "background" error, but *exclude* the Poisson error of the sources. If ``error`` is a 2D image, then it should represent the 1-sigma background error in each pixel of ``data``. If `None`, then a scalar background rms value will be estimated using sigma-clipped statistics. mask : array_like, bool, optional A boolean mask with the same shape as ``data``, where a `True` value indicates the corresponding element of ``data`` is masked. Masked pixels are ignored when computing the image background statistics. mask_value : float, optional An image data value (e.g., ``0.0``) that is ignored when computing the image background statistics. ``mask_value`` will be ignored if ``mask`` is input. sigclip_sigma : float, optional The number of standard deviations to use as the clipping limit when calculating the image background statistics. sigclip_iters : int, optional The number of iterations to perform sigma clipping, or `None` to clip until convergence is achieved (i.e., continue until the last iteration clips nothing) when calculating the image background statistics. Returns ------- threshold : 2D `~numpy.ndarray` A 2D image with the same shape as ``data`` containing the pixel-wise threshold values. See Also -------- :func:`photutils.segmentation.detect_sources` Notes ----- The ``mask``, ``mask_value``, ``sigclip_sigma``, and ``sigclip_iters`` inputs are used only if it is necessary to estimate ``background`` or ``error`` using sigma-clipped background statistics. If ``background`` and ``error`` are both input, then ``mask``, ``mask_value``, ``sigclip_sigma``, and ``sigclip_iters`` are ignored.
[ "Calculate", "a", "pixel", "-", "wise", "threshold", "image", "that", "can", "be", "used", "to", "detect", "sources", "." ]
python
train
BYU-PCCL/holodeck
holodeck/environments.py
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L327-L333
def teleport_camera(self, location, rotation): """Queue up a teleport camera command to stop the day cycle. By the next tick, the camera's location and rotation will be updated """ self._should_write_to_command_buffer = True command_to_send = TeleportCameraCommand(location, rotation) self._commands.add_command(command_to_send)
[ "def", "teleport_camera", "(", "self", ",", "location", ",", "rotation", ")", ":", "self", ".", "_should_write_to_command_buffer", "=", "True", "command_to_send", "=", "TeleportCameraCommand", "(", "location", ",", "rotation", ")", "self", ".", "_commands", ".", ...
Queue up a teleport camera command to stop the day cycle. By the next tick, the camera's location and rotation will be updated
[ "Queue", "up", "a", "teleport", "camera", "command", "to", "stop", "the", "day", "cycle", ".", "By", "the", "next", "tick", "the", "camera", "s", "location", "and", "rotation", "will", "be", "updated" ]
python
train
juju/charm-helpers
charmhelpers/contrib/network/ufw.py
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ufw.py#L122-L151
def enable(soft_fail=False): """ Enable ufw :param soft_fail: If set to True silently disables IPv6 support in ufw, otherwise a UFWIPv6Error exception is raised when IP6 support is broken. :returns: True if ufw is successfully enabled """ if is_enabled(): return True if not is_ipv6_ok(soft_fail): disable_ipv6() output = subprocess.check_output(['ufw', 'enable'], universal_newlines=True, env={'LANG': 'en_US', 'PATH': os.environ['PATH']}) m = re.findall('^Firewall is active and enabled on system startup\n', output, re.M) hookenv.log(output, level='DEBUG') if len(m) == 0: hookenv.log("ufw couldn't be enabled", level='WARN') return False else: hookenv.log("ufw enabled", level='INFO') return True
[ "def", "enable", "(", "soft_fail", "=", "False", ")", ":", "if", "is_enabled", "(", ")", ":", "return", "True", "if", "not", "is_ipv6_ok", "(", "soft_fail", ")", ":", "disable_ipv6", "(", ")", "output", "=", "subprocess", ".", "check_output", "(", "[", ...
Enable ufw :param soft_fail: If set to True silently disables IPv6 support in ufw, otherwise a UFWIPv6Error exception is raised when IP6 support is broken. :returns: True if ufw is successfully enabled
[ "Enable", "ufw" ]
python
train
thespacedoctor/sherlock
sherlock/transient_classifier.py
https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/transient_classifier.py#L1613-L1823
def _create_tables_if_not_exist( self): """*create the sherlock helper tables if they don't yet exist* **Key Arguments:** # - **Return:** - None **Usage:** .. todo:: - add usage info - create a sublime snippet for usage - write a command-line tool for this method - update package tutorial with command-line tool info if needed .. code-block:: python usage code .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip any useful text to docs mindmap - regenerate the docs and check redendering of this docstring """ self.log.debug('starting the ``_create_tables_if_not_exist`` method') transientTable = self.settings["database settings"][ "transients"]["transient table"] transientTableClassCol = self.settings["database settings"][ "transients"]["transient classification column"] transientTableIdCol = self.settings["database settings"][ "transients"]["transient primary id column"] crossmatchTable = "sherlock_crossmatches" createStatement = """ CREATE TABLE IF NOT EXISTS `%(crossmatchTable)s` ( `transient_object_id` bigint(20) unsigned DEFAULT NULL, `catalogue_object_id` varchar(30) DEFAULT NULL, `catalogue_table_id` smallint(5) unsigned DEFAULT NULL, `separationArcsec` double DEFAULT NULL, `northSeparationArcsec` DOUBLE DEFAULT NULL, `eastSeparationArcsec` DOUBLE DEFAULT NULL, `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `z` double DEFAULT NULL, `scale` double DEFAULT NULL, `distance` double DEFAULT NULL, `distance_modulus` double DEFAULT NULL, `photoZ` double DEFAULT NULL, `photoZErr` double DEFAULT NULL, `association_type` varchar(45) DEFAULT NULL, `dateCreated` datetime DEFAULT CURRENT_TIMESTAMP, `physical_separation_kpc` double DEFAULT NULL, `catalogue_object_type` varchar(45) DEFAULT NULL, `catalogue_object_subtype` varchar(45) DEFAULT NULL, `association_rank` int(11) DEFAULT NULL, `catalogue_table_name` varchar(100) DEFAULT NULL, `catalogue_view_name` varchar(100) DEFAULT NULL, `rank` int(11) DEFAULT NULL, `rankScore` double DEFAULT NULL, `search_name` varchar(100) DEFAULT NULL, `major_axis_arcsec` double DEFAULT NULL, `direct_distance` double DEFAULT NULL, `direct_distance_scale` double DEFAULT NULL, `direct_distance_modulus` double DEFAULT NULL, `raDeg` double DEFAULT NULL, `decDeg` double DEFAULT NULL, `original_search_radius_arcsec` double DEFAULT NULL, `catalogue_view_id` int(11) DEFAULT NULL, `U` double DEFAULT NULL, `UErr` double DEFAULT NULL, `B` double DEFAULT NULL, `BErr` double DEFAULT NULL, `V` double DEFAULT NULL, `VErr` double DEFAULT NULL, `R` double DEFAULT NULL, `RErr` double DEFAULT NULL, `I` double DEFAULT NULL, `IErr` double DEFAULT NULL, `J` double DEFAULT NULL, `JErr` double DEFAULT NULL, `H` double DEFAULT NULL, `HErr` double DEFAULT NULL, `K` double DEFAULT NULL, `KErr` double DEFAULT NULL, `_u` double DEFAULT NULL, `_uErr` double DEFAULT NULL, `_g` double DEFAULT NULL, `_gErr` double DEFAULT NULL, `_r` double DEFAULT NULL, `_rErr` double DEFAULT NULL, `_i` double DEFAULT NULL, `_iErr` double DEFAULT NULL, `_z` double DEFAULT NULL, `_zErr` double DEFAULT NULL, `_y` double DEFAULT NULL, `_yErr` double DEFAULT NULL, `G` double DEFAULT NULL, `GErr` double DEFAULT NULL, `unkMag` double DEFAULT NULL, `unkMagErr` double DEFAULT NULL, `dateLastModified` datetime DEFAULT CURRENT_TIMESTAMP, `updated` TINYINT NULL DEFAULT 0, `classificationReliability` TINYINT NULL DEFAULT NULL, `transientAbsMag` DOUBLE NULL DEFAULT NULL, PRIMARY KEY (`id`), KEY `key_transient_object_id` (`transient_object_id`), KEY `key_catalogue_object_id` (`catalogue_object_id`), KEY `idx_separationArcsec` (`separationArcsec`), KEY `idx_rank` (`rank`) ) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=latin1 ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=8; CREATE TABLE IF NOT EXISTS `sherlock_classifications` ( `transient_object_id` bigint(20) NOT NULL, `classification` varchar(45) DEFAULT NULL, `annotation` TEXT COLLATE utf8_unicode_ci DEFAULT NULL, `summary` VARCHAR(50) COLLATE utf8_unicode_ci DEFAULT NULL, `separationArcsec` DOUBLE DEFAULT NULL, `matchVerified` TINYINT NULL DEFAULT NULL, `developmentComment` VARCHAR(100) NULL, `dateLastModified` datetime DEFAULT CURRENT_TIMESTAMP, `dateCreated` datetime DEFAULT CURRENT_TIMESTAMP, `updated` varchar(45) DEFAULT '0', PRIMARY KEY (`transient_object_id`), KEY `key_transient_object_id` (`transient_object_id`), KEY `idx_summary` (`summary`), KEY `idx_classification` (`classification`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; """ % locals() # A FIX FOR MYSQL VERSIONS < 5.6 triggers = [] if float(self.dbVersions["transients"][:3]) < 5.6: createStatement = createStatement.replace( "`dateLastModified` datetime DEFAULT CURRENT_TIMESTAMP,", "`dateLastModified` datetime DEFAULT NULL,") createStatement = createStatement.replace( "`dateCreated` datetime DEFAULT CURRENT_TIMESTAMP,", "`dateCreated` datetime DEFAULT NULL,") triggers.append(""" CREATE TRIGGER dateCreated BEFORE INSERT ON `%(crossmatchTable)s` FOR EACH ROW BEGIN IF NEW.dateCreated IS NULL THEN SET NEW.dateCreated = NOW(); SET NEW.dateLastModified = NOW(); END IF; END""" % locals()) try: writequery( log=self.log, sqlQuery=createStatement, dbConn=self.transientsDbConn, Force=True ) except: self.log.info( "Could not create table (`%(crossmatchTable)s`). Probably already exist." % locals()) sqlQuery = u""" SHOW TRIGGERS; """ % locals() rows = readquery( log=self.log, sqlQuery=sqlQuery, dbConn=self.transientsDbConn, ) # DON'T ADD TRIGGERS IF THEY ALREADY EXIST for r in rows: if r["Trigger"] in ("sherlock_classifications_BEFORE_INSERT", "sherlock_classifications_AFTER_INSERT"): return None triggers.append("""CREATE TRIGGER `sherlock_classifications_BEFORE_INSERT` BEFORE INSERT ON `sherlock_classifications` FOR EACH ROW BEGIN IF new.classification = "ORPHAN" THEN SET new.annotation = "The transient location is not matched against any known catalogued source", new.summary = "No catalogued match"; END IF; END""" % locals()) triggers.append("""CREATE TRIGGER `sherlock_classifications_AFTER_INSERT` AFTER INSERT ON `sherlock_classifications` FOR EACH ROW BEGIN update `%(transientTable)s` set `%(transientTableClassCol)s` = new.classification where `%(transientTableIdCol)s` = new.transient_object_id; END""" % locals()) for t in triggers: try: writequery( log=self.log, sqlQuery=t, dbConn=self.transientsDbConn, Force=True ) except: self.log.info( "Could not create trigger (`%(crossmatchTable)s`). Probably already exist." % locals()) self.log.debug('completed the ``_create_tables_if_not_exist`` method') return None
[ "def", "_create_tables_if_not_exist", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``_create_tables_if_not_exist`` method'", ")", "transientTable", "=", "self", ".", "settings", "[", "\"database settings\"", "]", "[", "\"transients\"", ...
*create the sherlock helper tables if they don't yet exist* **Key Arguments:** # - **Return:** - None **Usage:** .. todo:: - add usage info - create a sublime snippet for usage - write a command-line tool for this method - update package tutorial with command-line tool info if needed .. code-block:: python usage code .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip any useful text to docs mindmap - regenerate the docs and check redendering of this docstring
[ "*", "create", "the", "sherlock", "helper", "tables", "if", "they", "don", "t", "yet", "exist", "*" ]
python
train
CyberReboot/vent
vent/menus/main.py
https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/main.py#L68-L72
def add_form(self, form, form_name, form_args): """ Add new form and switch to it """ self.parentApp.addForm(form_name, form, **form_args) self.parentApp.change_form(form_name) return
[ "def", "add_form", "(", "self", ",", "form", ",", "form_name", ",", "form_args", ")", ":", "self", ".", "parentApp", ".", "addForm", "(", "form_name", ",", "form", ",", "*", "*", "form_args", ")", "self", ".", "parentApp", ".", "change_form", "(", "for...
Add new form and switch to it
[ "Add", "new", "form", "and", "switch", "to", "it" ]
python
train
woolfson-group/isambard
isambard/ampal/interactions.py
https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/ampal/interactions.py#L264-L293
def generate_bond_subgraphs_from_break(bond_graph, atom1, atom2): """Splits the bond graph between two atoms to producing subgraphs. Notes ----- This will not work if there are cycles in the bond graph. Parameters ---------- bond_graph: networkx.Graph Graph of covalent bond network atom1: isambard.ampal.Atom First atom in the bond. atom2: isambard.ampal.Atom Second atom in the bond. Returns ------- subgraphs: [networkx.Graph] A list of subgraphs generated when a bond is broken in the covalent bond network. """ bond_graph.remove_edge(atom1, atom2) try: subgraphs=list(networkx.connected_component_subgraphs( bond_graph, copy=False)) finally: # Add edge bond_graph.add_edge(atom1, atom2) return subgraphs
[ "def", "generate_bond_subgraphs_from_break", "(", "bond_graph", ",", "atom1", ",", "atom2", ")", ":", "bond_graph", ".", "remove_edge", "(", "atom1", ",", "atom2", ")", "try", ":", "subgraphs", "=", "list", "(", "networkx", ".", "connected_component_subgraphs", ...
Splits the bond graph between two atoms to producing subgraphs. Notes ----- This will not work if there are cycles in the bond graph. Parameters ---------- bond_graph: networkx.Graph Graph of covalent bond network atom1: isambard.ampal.Atom First atom in the bond. atom2: isambard.ampal.Atom Second atom in the bond. Returns ------- subgraphs: [networkx.Graph] A list of subgraphs generated when a bond is broken in the covalent bond network.
[ "Splits", "the", "bond", "graph", "between", "two", "atoms", "to", "producing", "subgraphs", "." ]
python
train
JIC-CSB/jicimagelib
jicimagelib/image.py
https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/image.py#L186-L208
def parse_manifest(self, fpath): """Parse manifest file to build up the collection of images. :param fpath: path to the manifest file """ with open(fpath, 'r') as fh: for entry in json.load(fh): # Every entry of a manifest file needs to have a "filename" # attribute. It is the only requirement so we check for it in a # strict fashion. if "filename" not in entry: raise(RuntimeError( 'Entries in {} need to have "filename"'.format(fpath))) filename = entry.pop("filename") proxy_image = None if isinstance(self, MicroscopyCollection): proxy_image = MicroscopyImage(filename, entry) else: proxy_image = ProxyImage(filename, entry) self.append(proxy_image)
[ "def", "parse_manifest", "(", "self", ",", "fpath", ")", ":", "with", "open", "(", "fpath", ",", "'r'", ")", "as", "fh", ":", "for", "entry", "in", "json", ".", "load", "(", "fh", ")", ":", "# Every entry of a manifest file needs to have a \"filename\"", "# ...
Parse manifest file to build up the collection of images. :param fpath: path to the manifest file
[ "Parse", "manifest", "file", "to", "build", "up", "the", "collection", "of", "images", ".", ":", "param", "fpath", ":", "path", "to", "the", "manifest", "file" ]
python
train
twilio/twilio-python
twilio/rest/api/v2010/account/call/__init__.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/call/__init__.py#L297-L309
def feedback_summaries(self): """ Access the feedback_summaries :returns: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryList :rtype: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryList """ if self._feedback_summaries is None: self._feedback_summaries = FeedbackSummaryList( self._version, account_sid=self._solution['account_sid'], ) return self._feedback_summaries
[ "def", "feedback_summaries", "(", "self", ")", ":", "if", "self", ".", "_feedback_summaries", "is", "None", ":", "self", ".", "_feedback_summaries", "=", "FeedbackSummaryList", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[...
Access the feedback_summaries :returns: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryList :rtype: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryList
[ "Access", "the", "feedback_summaries" ]
python
train
numenta/htmresearch
projects/sequence_prediction/discrete_sequences/lstm/suite.py
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/sequence_prediction/discrete_sequences/lstm/suite.py#L263-L320
def killCells(self, killCellPercent): """ kill a fraction of LSTM cells from the network :param killCellPercent: :return: """ if killCellPercent <= 0: return inputLayer = self.net['in'] lstmLayer = self.net['hidden0'] numLSTMCell = lstmLayer.outdim numDead = round(killCellPercent * numLSTMCell) zombiePermutation = numpy.random.permutation(numLSTMCell) deadCells = zombiePermutation[0:numDead] # remove connections from input layer to dead LSTM cells connectionInputToHidden = self.net.connections[inputLayer][0] weightInputToHidden = reshape(connectionInputToHidden.params, (connectionInputToHidden.outdim, connectionInputToHidden.indim)) for cell in deadCells: for dim in range(4): weightInputToHidden[dim * numLSTMCell + cell, :] *= 0 newParams = reshape(weightInputToHidden, (connectionInputToHidden.paramdim,)) self.net.connections[inputLayer][0]._setParameters( newParams, connectionInputToHidden.owner) # remove dead connections within LSTM layer connectionHiddenToHidden = self.net.recurrentConns[0] weightHiddenToHidden = reshape(connectionHiddenToHidden.params, (connectionHiddenToHidden.outdim, connectionHiddenToHidden.indim)) for cell in deadCells: weightHiddenToHidden[:, cell] *= 0 newParams = reshape(weightHiddenToHidden, (connectionHiddenToHidden.paramdim,)) self.net.recurrentConns[0]._setParameters( newParams, connectionHiddenToHidden.owner) # remove connections from dead LSTM cell to output layer connectionHiddenToOutput = self.net.connections[lstmLayer][0] weightHiddenToOutput = reshape(connectionHiddenToOutput.params, (connectionHiddenToOutput.outdim, connectionHiddenToOutput.indim)) for cell in deadCells: weightHiddenToOutput[:, cell] *= 0 newParams = reshape(weightHiddenToOutput, (connectionHiddenToOutput.paramdim,)) self.net.connections[lstmLayer][0]._setParameters( newParams, connectionHiddenToOutput.owner)
[ "def", "killCells", "(", "self", ",", "killCellPercent", ")", ":", "if", "killCellPercent", "<=", "0", ":", "return", "inputLayer", "=", "self", ".", "net", "[", "'in'", "]", "lstmLayer", "=", "self", ".", "net", "[", "'hidden0'", "]", "numLSTMCell", "="...
kill a fraction of LSTM cells from the network :param killCellPercent: :return:
[ "kill", "a", "fraction", "of", "LSTM", "cells", "from", "the", "network", ":", "param", "killCellPercent", ":", ":", "return", ":" ]
python
train
saltstack/salt
salt/modules/aptpkg.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L1464-L1469
def _split_repo_str(repo): ''' Return APT source entry as a tuple. ''' split = sourceslist.SourceEntry(repo) return split.type, split.architectures, split.uri, split.dist, split.comps
[ "def", "_split_repo_str", "(", "repo", ")", ":", "split", "=", "sourceslist", ".", "SourceEntry", "(", "repo", ")", "return", "split", ".", "type", ",", "split", ".", "architectures", ",", "split", ".", "uri", ",", "split", ".", "dist", ",", "split", "...
Return APT source entry as a tuple.
[ "Return", "APT", "source", "entry", "as", "a", "tuple", "." ]
python
train
HewlettPackard/python-hpOneView
hpOneView/resources/task_monitor.py
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/task_monitor.py#L225-L261
def get_associated_resource(self, task): """ Retrieve a resource associated with a task. Args: task: task dict Returns: tuple: task (updated), the entity found (dict) """ if not task: raise HPOneViewUnknownType(MSG_INVALID_TASK) if task['category'] != 'tasks' and task['category'] != 'backups': # it is an error if type is not in obj, so let the except flow raise HPOneViewUnknownType(MSG_UNKNOWN_OBJECT_TYPE) if task['type'] == 'TaskResourceV2': resource_uri = task['associatedResource']['resourceUri'] if resource_uri and resource_uri.startswith("/rest/appliance/support-dumps/"): # Specific for support dumps return task, resource_uri elif task['type'] == 'BACKUP': task = self._connection.get(task['taskUri']) resource_uri = task['uri'] else: raise HPOneViewInvalidResource(MSG_TASK_TYPE_UNRECONIZED % task['type']) entity = {} if resource_uri: entity = self._connection.get(resource_uri) return task, entity
[ "def", "get_associated_resource", "(", "self", ",", "task", ")", ":", "if", "not", "task", ":", "raise", "HPOneViewUnknownType", "(", "MSG_INVALID_TASK", ")", "if", "task", "[", "'category'", "]", "!=", "'tasks'", "and", "task", "[", "'category'", "]", "!=",...
Retrieve a resource associated with a task. Args: task: task dict Returns: tuple: task (updated), the entity found (dict)
[ "Retrieve", "a", "resource", "associated", "with", "a", "task", "." ]
python
train
django-extensions/django-extensions
django_extensions/templatetags/widont.py
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/templatetags/widont.py#L15-L35
def widont(value, count=1): """ Add an HTML non-breaking space between the final two words of the string to avoid "widowed" words. Examples: >>> print(widont('Test me out')) Test me&nbsp;out >>> print("'",widont('It works with trailing spaces too '), "'") ' It works with trailing spaces&nbsp;too ' >>> print(widont('NoEffect')) NoEffect """ def replace(matchobj): return force_text('&nbsp;%s' % matchobj.group(1)) for i in range(count): value = re_widont.sub(replace, force_text(value)) return value
[ "def", "widont", "(", "value", ",", "count", "=", "1", ")", ":", "def", "replace", "(", "matchobj", ")", ":", "return", "force_text", "(", "'&nbsp;%s'", "%", "matchobj", ".", "group", "(", "1", ")", ")", "for", "i", "in", "range", "(", "count", ")"...
Add an HTML non-breaking space between the final two words of the string to avoid "widowed" words. Examples: >>> print(widont('Test me out')) Test me&nbsp;out >>> print("'",widont('It works with trailing spaces too '), "'") ' It works with trailing spaces&nbsp;too ' >>> print(widont('NoEffect')) NoEffect
[ "Add", "an", "HTML", "non", "-", "breaking", "space", "between", "the", "final", "two", "words", "of", "the", "string", "to", "avoid", "widowed", "words", "." ]
python
train
althonos/moclo
moclo/moclo/core/vectors.py
https://github.com/althonos/moclo/blob/28a03748df8a2fa43f0c0c8098ca64d11559434e/moclo/moclo/core/vectors.py#L39-L60
def structure(cls): # type: () -> Text """Get the vector structure, as a DNA regex pattern. Warning: If overloading this method, the returned pattern must include 3 capture groups to capture the following features: 1. The downstream (3') overhang sequence 2. The vector placeholder sequence 3. The upstream (5') overhang sequence """ downstream = cls.cutter.elucidate() upstream = str(Seq(downstream).reverse_complement()) return "".join( [ upstream.replace("^", ")(").replace("_", "("), "N*", downstream.replace("^", ")(").replace("_", ")"), ] )
[ "def", "structure", "(", "cls", ")", ":", "# type: () -> Text", "downstream", "=", "cls", ".", "cutter", ".", "elucidate", "(", ")", "upstream", "=", "str", "(", "Seq", "(", "downstream", ")", ".", "reverse_complement", "(", ")", ")", "return", "\"\"", "...
Get the vector structure, as a DNA regex pattern. Warning: If overloading this method, the returned pattern must include 3 capture groups to capture the following features: 1. The downstream (3') overhang sequence 2. The vector placeholder sequence 3. The upstream (5') overhang sequence
[ "Get", "the", "vector", "structure", "as", "a", "DNA", "regex", "pattern", "." ]
python
train
DinoTools/python-overpy
overpy/__init__.py
https://github.com/DinoTools/python-overpy/blob/db8f80eeb1b4d1405816bd62c16ddb3364e0c46d/overpy/__init__.py#L1521-L1535
def _handle_start_area(self, attrs): """ Handle opening area element :param attrs: Attributes of the element :type attrs: Dict """ self._curr = { 'attributes': dict(attrs), 'tags': {}, 'area_id': None } if attrs.get('id', None) is not None: self._curr['area_id'] = int(attrs['id']) del self._curr['attributes']['id']
[ "def", "_handle_start_area", "(", "self", ",", "attrs", ")", ":", "self", ".", "_curr", "=", "{", "'attributes'", ":", "dict", "(", "attrs", ")", ",", "'tags'", ":", "{", "}", ",", "'area_id'", ":", "None", "}", "if", "attrs", ".", "get", "(", "'id...
Handle opening area element :param attrs: Attributes of the element :type attrs: Dict
[ "Handle", "opening", "area", "element" ]
python
train
sentinel-hub/eo-learn
features/eolearn/features/hog.py
https://github.com/sentinel-hub/eo-learn/blob/b8c390b9f553c561612fe9eb64e720611633a035/features/eolearn/features/hog.py#L80-L94
def execute(self, eopatch): """ Execute computation of HoG features on input eopatch :param eopatch: Input eopatch :type eopatch: eolearn.core.EOPatch :return: EOPatch instance with new keys holding the HoG features and HoG image for visualisation. :rtype: eolearn.core.EOPatch """ for feature_type, feature_name, new_feature_name in self.feature: result = self._compute_hog(eopatch[feature_type][feature_name]) eopatch[feature_type][new_feature_name] = result[0] if self.visualize: eopatch[feature_type][self.visualize_name] = result[1] return eopatch
[ "def", "execute", "(", "self", ",", "eopatch", ")", ":", "for", "feature_type", ",", "feature_name", ",", "new_feature_name", "in", "self", ".", "feature", ":", "result", "=", "self", ".", "_compute_hog", "(", "eopatch", "[", "feature_type", "]", "[", "fea...
Execute computation of HoG features on input eopatch :param eopatch: Input eopatch :type eopatch: eolearn.core.EOPatch :return: EOPatch instance with new keys holding the HoG features and HoG image for visualisation. :rtype: eolearn.core.EOPatch
[ "Execute", "computation", "of", "HoG", "features", "on", "input", "eopatch" ]
python
train
fastai/fastai
fastai/vision/transform.py
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L15-L17
def _brightness(x, change:uniform): "Apply `change` in brightness of image `x`." return x.add_(scipy.special.logit(change))
[ "def", "_brightness", "(", "x", ",", "change", ":", "uniform", ")", ":", "return", "x", ".", "add_", "(", "scipy", ".", "special", ".", "logit", "(", "change", ")", ")" ]
Apply `change` in brightness of image `x`.
[ "Apply", "change", "in", "brightness", "of", "image", "x", "." ]
python
train
allenai/allennlp
allennlp/state_machines/transition_functions/basic_transition_function.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/transition_functions/basic_transition_function.py#L393-L412
def attend_on_question(self, query: torch.Tensor, encoder_outputs: torch.Tensor, encoder_output_mask: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """ Given a query (which is typically the decoder hidden state), compute an attention over the output of the question encoder, and return a weighted sum of the question representations given this attention. We also return the attention weights themselves. This is a simple computation, but we have it as a separate method so that the ``forward`` method on the main parser module can call it on the initial hidden state, to simplify the logic in ``take_step``. """ # (group_size, question_length) question_attention_weights = self._input_attention(query, encoder_outputs, encoder_output_mask) # (group_size, encoder_output_dim) attended_question = util.weighted_sum(encoder_outputs, question_attention_weights) return attended_question, question_attention_weights
[ "def", "attend_on_question", "(", "self", ",", "query", ":", "torch", ".", "Tensor", ",", "encoder_outputs", ":", "torch", ".", "Tensor", ",", "encoder_output_mask", ":", "torch", ".", "Tensor", ")", "->", "Tuple", "[", "torch", ".", "Tensor", ",", "torch"...
Given a query (which is typically the decoder hidden state), compute an attention over the output of the question encoder, and return a weighted sum of the question representations given this attention. We also return the attention weights themselves. This is a simple computation, but we have it as a separate method so that the ``forward`` method on the main parser module can call it on the initial hidden state, to simplify the logic in ``take_step``.
[ "Given", "a", "query", "(", "which", "is", "typically", "the", "decoder", "hidden", "state", ")", "compute", "an", "attention", "over", "the", "output", "of", "the", "question", "encoder", "and", "return", "a", "weighted", "sum", "of", "the", "question", "...
python
train
pyviz/holoviews
holoviews/core/spaces.py
https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/spaces.py#L962-L978
def unbounded(self): """ Returns a list of key dimensions that are unbounded, excluding stream parameters. If any of theses key dimensions are unbounded, the DynamicMap as a whole is also unbounded. """ unbounded_dims = [] # Dimensioned streams do not need to be bounded stream_params = set(util.stream_parameters(self.streams)) for kdim in self.kdims: if str(kdim) in stream_params: continue if kdim.values: continue if None in kdim.range: unbounded_dims.append(str(kdim)) return unbounded_dims
[ "def", "unbounded", "(", "self", ")", ":", "unbounded_dims", "=", "[", "]", "# Dimensioned streams do not need to be bounded", "stream_params", "=", "set", "(", "util", ".", "stream_parameters", "(", "self", ".", "streams", ")", ")", "for", "kdim", "in", "self",...
Returns a list of key dimensions that are unbounded, excluding stream parameters. If any of theses key dimensions are unbounded, the DynamicMap as a whole is also unbounded.
[ "Returns", "a", "list", "of", "key", "dimensions", "that", "are", "unbounded", "excluding", "stream", "parameters", ".", "If", "any", "of", "theses", "key", "dimensions", "are", "unbounded", "the", "DynamicMap", "as", "a", "whole", "is", "also", "unbounded", ...
python
train
singularityhub/singularity-cli
spython/oci/cmd/actions.py
https://github.com/singularityhub/singularity-cli/blob/cb36b4504812ca87e29c6a40b222a545d1865799/spython/oci/cmd/actions.py#L40-L75
def create(self, bundle, container_id=None, empty_process=False, log_path=None, pid_file=None, sync_socket=None, log_format="kubernetes"): ''' use the client to create a container from a bundle directory. The bundle directory should have a config.json. You must be the root user to create a runtime. Equivalent command line example: singularity oci create [create options...] <container_ID> Parameters ========== bundle: the full path to the bundle folder container_id: an optional container_id. If not provided, use same container_id used to generate OciImage instance empty_process: run container without executing container process (for example, for a pod container waiting for signals). This is a specific use case for tools like Kubernetes log_path: the path to store the log. pid_file: specify the pid file path to use sync_socket: the path to the unix socket for state synchronization. log_format: defaults to kubernetes. Can also be "basic" or "json" ''' return self._run(bundle, container_id=container_id, empty_process=empty_process, log_path=log_path, pid_file=pid_file, sync_socket=sync_socket, command="create", log_format=log_format)
[ "def", "create", "(", "self", ",", "bundle", ",", "container_id", "=", "None", ",", "empty_process", "=", "False", ",", "log_path", "=", "None", ",", "pid_file", "=", "None", ",", "sync_socket", "=", "None", ",", "log_format", "=", "\"kubernetes\"", ")", ...
use the client to create a container from a bundle directory. The bundle directory should have a config.json. You must be the root user to create a runtime. Equivalent command line example: singularity oci create [create options...] <container_ID> Parameters ========== bundle: the full path to the bundle folder container_id: an optional container_id. If not provided, use same container_id used to generate OciImage instance empty_process: run container without executing container process (for example, for a pod container waiting for signals). This is a specific use case for tools like Kubernetes log_path: the path to store the log. pid_file: specify the pid file path to use sync_socket: the path to the unix socket for state synchronization. log_format: defaults to kubernetes. Can also be "basic" or "json"
[ "use", "the", "client", "to", "create", "a", "container", "from", "a", "bundle", "directory", ".", "The", "bundle", "directory", "should", "have", "a", "config", ".", "json", ".", "You", "must", "be", "the", "root", "user", "to", "create", "a", "runtime"...
python
train
ergo/ziggurat_foundations
ziggurat_foundations/models/services/resource_tree.py
https://github.com/ergo/ziggurat_foundations/blob/9eeec894d08e8d7defa60ddc04b63f69cd4cbeba/ziggurat_foundations/models/services/resource_tree.py#L125-L143
def shift_ordering_down( self, parent_id, position, db_session=None, *args, **kwargs ): """ Shifts ordering to "close gaps" after node deletion or being moved to another branch, begins the shift from given position :param parent_id: :param position: :param db_session: :return: """ return self.service.shift_ordering_down( parent_id=parent_id, position=position, db_session=db_session, *args, **kwargs )
[ "def", "shift_ordering_down", "(", "self", ",", "parent_id", ",", "position", ",", "db_session", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "service", ".", "shift_ordering_down", "(", "parent_id", "=", "parent_...
Shifts ordering to "close gaps" after node deletion or being moved to another branch, begins the shift from given position :param parent_id: :param position: :param db_session: :return:
[ "Shifts", "ordering", "to", "close", "gaps", "after", "node", "deletion", "or", "being", "moved", "to", "another", "branch", "begins", "the", "shift", "from", "given", "position" ]
python
train
georgemarshall/django-cryptography
django_cryptography/utils/crypto.py
https://github.com/georgemarshall/django-cryptography/blob/4c5f60fec98bcf71495d6084f801ea9c01c9a725/django_cryptography/utils/crypto.py#L21-L56
def salted_hmac(key_salt, value, secret=None): """ Returns the HMAC-HASH of 'value', using a key generated from key_salt and a secret (which defaults to settings.SECRET_KEY). A different key_salt should be passed in for every application of HMAC. :type key_salt: any :type value: any :type secret: any :rtype: HMAC """ if secret is None: secret = settings.SECRET_KEY key_salt = force_bytes(key_salt) secret = force_bytes(secret) # We need to generate a derived key from our base key. We can do this by # passing the key_salt and our base key through a pseudo-random function and # SHA1 works nicely. digest = hashes.Hash( settings.CRYPTOGRAPHY_DIGEST, backend=settings.CRYPTOGRAPHY_BACKEND) digest.update(key_salt + secret) key = digest.finalize() # If len(key_salt + secret) > sha_constructor().block_size, the above # line is redundant and could be replaced by key = key_salt + secret, since # the hmac module does the same thing for keys longer than the block size. # However, we need to ensure that we *always* do this. h = HMAC( key, settings.CRYPTOGRAPHY_DIGEST, backend=settings.CRYPTOGRAPHY_BACKEND) h.update(force_bytes(value)) return h
[ "def", "salted_hmac", "(", "key_salt", ",", "value", ",", "secret", "=", "None", ")", ":", "if", "secret", "is", "None", ":", "secret", "=", "settings", ".", "SECRET_KEY", "key_salt", "=", "force_bytes", "(", "key_salt", ")", "secret", "=", "force_bytes", ...
Returns the HMAC-HASH of 'value', using a key generated from key_salt and a secret (which defaults to settings.SECRET_KEY). A different key_salt should be passed in for every application of HMAC. :type key_salt: any :type value: any :type secret: any :rtype: HMAC
[ "Returns", "the", "HMAC", "-", "HASH", "of", "value", "using", "a", "key", "generated", "from", "key_salt", "and", "a", "secret", "(", "which", "defaults", "to", "settings", ".", "SECRET_KEY", ")", "." ]
python
valid
PSPC-SPAC-buyandsell/von_anchor
von_anchor/cache.py
https://github.com/PSPC-SPAC-buyandsell/von_anchor/blob/78ac1de67be42a676274f4bf71fe12f66e72f309/von_anchor/cache.py#L169-L179
def schemata(self) -> list: """ Return list with schemata in cache. :return: list of schemata """ LOGGER.debug('SchemaCache.schemata >>>') LOGGER.debug('SchemaCache.schemata <<<') return [self._schema_key2schema[seq_no] for seq_no in self._schema_key2schema]
[ "def", "schemata", "(", "self", ")", "->", "list", ":", "LOGGER", ".", "debug", "(", "'SchemaCache.schemata >>>'", ")", "LOGGER", ".", "debug", "(", "'SchemaCache.schemata <<<'", ")", "return", "[", "self", ".", "_schema_key2schema", "[", "seq_no", "]", "for",...
Return list with schemata in cache. :return: list of schemata
[ "Return", "list", "with", "schemata", "in", "cache", "." ]
python
train
googledatalab/pydatalab
google/datalab/ml/_summary.py
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_summary.py#L44-L62
def _glob_events_files(self, paths, recursive): """Find all tf events files under a list of paths recursively. """ event_files = [] for path in paths: dirs = tf.gfile.Glob(path) dirs = filter(lambda x: tf.gfile.IsDirectory(x), dirs) for dir in dirs: if recursive: dir_files_pair = [(root, filenames) for root, _, filenames in tf.gfile.Walk(dir)] else: dir_files_pair = [(dir, tf.gfile.ListDirectory(dir))] for root, filenames in dir_files_pair: file_names = fnmatch.filter(filenames, '*.tfevents.*') file_paths = [os.path.join(root, x) for x in file_names] file_paths = filter(lambda x: not tf.gfile.IsDirectory(x), file_paths) event_files += file_paths return event_files
[ "def", "_glob_events_files", "(", "self", ",", "paths", ",", "recursive", ")", ":", "event_files", "=", "[", "]", "for", "path", "in", "paths", ":", "dirs", "=", "tf", ".", "gfile", ".", "Glob", "(", "path", ")", "dirs", "=", "filter", "(", "lambda",...
Find all tf events files under a list of paths recursively.
[ "Find", "all", "tf", "events", "files", "under", "a", "list", "of", "paths", "recursively", "." ]
python
train
ella/ella
ella/core/cache/utils.py
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/cache/utils.py#L70-L107
def get_cached_object(model, timeout=CACHE_TIMEOUT, **kwargs): """ Return a cached object. If the object does not exist in the cache, create it. Params: model - ContentType instance representing the model's class or the model class itself timeout - TTL for the item in cache, defaults to CACHE_TIMEOUT **kwargs - lookup parameters for content_type.get_object_for_this_type and for key creation Throws: model.DoesNotExist is propagated from content_type.get_object_for_this_type """ if not isinstance(model, ContentType): model_ct = ContentType.objects.get_for_model(model) else: model_ct = model key = _get_key(KEY_PREFIX, model_ct, **kwargs) obj = cache.get(key) if obj is None: # if we are looking for a publishable, fetch just the actual content # type and then fetch the actual object if model_ct.app_label == 'core' and model_ct.model == 'publishable': actual_ct_id = model_ct.model_class()._default_manager.values('content_type_id').get(**kwargs)['content_type_id'] model_ct = ContentType.objects.get_for_id(actual_ct_id) # fetch the actual object we want obj = model_ct.model_class()._default_manager.get(**kwargs) # since 99% of lookups are done via PK make sure we set the cache for # that lookup even if we retrieved it using a different one. if 'pk' in kwargs: cache.set(key, obj, timeout) elif not isinstance(cache, DummyCache): cache.set_many({key: obj, _get_key(KEY_PREFIX, model_ct, pk=obj.pk): obj}, timeout=timeout) return obj
[ "def", "get_cached_object", "(", "model", ",", "timeout", "=", "CACHE_TIMEOUT", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "model", ",", "ContentType", ")", ":", "model_ct", "=", "ContentType", ".", "objects", ".", "get_for_model", ...
Return a cached object. If the object does not exist in the cache, create it. Params: model - ContentType instance representing the model's class or the model class itself timeout - TTL for the item in cache, defaults to CACHE_TIMEOUT **kwargs - lookup parameters for content_type.get_object_for_this_type and for key creation Throws: model.DoesNotExist is propagated from content_type.get_object_for_this_type
[ "Return", "a", "cached", "object", ".", "If", "the", "object", "does", "not", "exist", "in", "the", "cache", "create", "it", "." ]
python
train
mitsei/dlkit
dlkit/authz_adapter/osid/sessions.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/authz_adapter/osid/sessions.py#L52-L72
def _can(self, func_name, qualifier_id=None): """Tests if the named function is authorized with agent and qualifier. Also, caches authz's in a dict. It is expected that this will not grow to big, as there are typically only a small number of qualifier + function combinations to store for the agent. However, if this becomes an issue, we can switch to something like cachetools. """ function_id = self._get_function_id(func_name) if qualifier_id is None: qualifier_id = self._qualifier_id agent_id = self.get_effective_agent_id() try: return self._authz_cache[str(agent_id) + str(function_id) + str(qualifier_id)] except KeyError: authz = self._authz_session.is_authorized(agent_id=agent_id, function_id=function_id, qualifier_id=qualifier_id) self._authz_cache[str(agent_id) + str(function_id) + str(qualifier_id)] = authz return authz
[ "def", "_can", "(", "self", ",", "func_name", ",", "qualifier_id", "=", "None", ")", ":", "function_id", "=", "self", ".", "_get_function_id", "(", "func_name", ")", "if", "qualifier_id", "is", "None", ":", "qualifier_id", "=", "self", ".", "_qualifier_id", ...
Tests if the named function is authorized with agent and qualifier. Also, caches authz's in a dict. It is expected that this will not grow to big, as there are typically only a small number of qualifier + function combinations to store for the agent. However, if this becomes an issue, we can switch to something like cachetools.
[ "Tests", "if", "the", "named", "function", "is", "authorized", "with", "agent", "and", "qualifier", "." ]
python
train
kyuupichan/aiorpcX
aiorpcx/session.py
https://github.com/kyuupichan/aiorpcX/blob/707c989ed1c67ac9a40cd20b0161b1ce1f4d7db0/aiorpcx/session.py#L393-L414
async def _throttled_message(self, message): '''Process a single request, respecting the concurrency limit.''' try: timeout = self.processing_timeout async with timeout_after(timeout): async with self._incoming_concurrency: if self._cost_fraction: await sleep(self._cost_fraction * self.cost_sleep) await self.handle_message(message) except ProtocolError as e: self.logger.error(f'{e}') self._bump_errors(e) except TaskTimeout: self.logger.info(f'incoming request timed out after {timeout} secs') self._bump_errors() except ExcessiveSessionCostError: await self.close() except CancelledError: raise except Exception: self.logger.exception(f'exception handling {message}') self._bump_errors()
[ "async", "def", "_throttled_message", "(", "self", ",", "message", ")", ":", "try", ":", "timeout", "=", "self", ".", "processing_timeout", "async", "with", "timeout_after", "(", "timeout", ")", ":", "async", "with", "self", ".", "_incoming_concurrency", ":", ...
Process a single request, respecting the concurrency limit.
[ "Process", "a", "single", "request", "respecting", "the", "concurrency", "limit", "." ]
python
train
timothyb0912/pylogit
pylogit/choice_calcs.py
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_calcs.py#L492-L520
def create_matrix_block_indices(row_to_obs): """ Parameters ---------- row_to_obs: 2D ndarray. There should be one row per observation per available alternative and one column per observation. This matrix maps the rows of the design matrix to the unique observations (on the columns). Returns ------- output_indices : list of arrays. There will be one array per column in `row_to_obs`. The array will note which rows correspond to which observations. """ # Initialize the list of index arrays to be returned output_indices = [] # Determine the number of observations in the dataset num_obs = row_to_obs.shape[1] # Get the indices of the non-zero elements and their values row_indices, col_indices, values = scipy.sparse.find(row_to_obs) # Iterate over each observation, i.e. each column in row_to_obs, and # determine which rows belong to that observation (i.e. the rows with ones # in them). for col in xrange(num_obs): # Store the array of row indices belonging to the current observation output_indices.append(row_indices[np.where(col_indices == col)]) return output_indices
[ "def", "create_matrix_block_indices", "(", "row_to_obs", ")", ":", "# Initialize the list of index arrays to be returned", "output_indices", "=", "[", "]", "# Determine the number of observations in the dataset", "num_obs", "=", "row_to_obs", ".", "shape", "[", "1", "]", "# G...
Parameters ---------- row_to_obs: 2D ndarray. There should be one row per observation per available alternative and one column per observation. This matrix maps the rows of the design matrix to the unique observations (on the columns). Returns ------- output_indices : list of arrays. There will be one array per column in `row_to_obs`. The array will note which rows correspond to which observations.
[ "Parameters", "----------", "row_to_obs", ":", "2D", "ndarray", ".", "There", "should", "be", "one", "row", "per", "observation", "per", "available", "alternative", "and", "one", "column", "per", "observation", ".", "This", "matrix", "maps", "the", "rows", "of...
python
train
KieranWynn/pyquaternion
pyquaternion/quaternion.py
https://github.com/KieranWynn/pyquaternion/blob/d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9/pyquaternion/quaternion.py#L784-L803
def distance(cls, q0, q1): """Quaternion intrinsic distance. Find the intrinsic geodesic distance between q0 and q1. Params: q0: the first quaternion q1: the second quaternion Returns: A positive amount corresponding to the length of the geodesic arc connecting q0 to q1. Note: Although the q0^(-1)*q1 != q1^(-1)*q0, the length of the path joining them is given by the logarithm of those product quaternions, the norm of which is the same. """ q = Quaternion.log_map(q0, q1) return q.norm
[ "def", "distance", "(", "cls", ",", "q0", ",", "q1", ")", ":", "q", "=", "Quaternion", ".", "log_map", "(", "q0", ",", "q1", ")", "return", "q", ".", "norm" ]
Quaternion intrinsic distance. Find the intrinsic geodesic distance between q0 and q1. Params: q0: the first quaternion q1: the second quaternion Returns: A positive amount corresponding to the length of the geodesic arc connecting q0 to q1. Note: Although the q0^(-1)*q1 != q1^(-1)*q0, the length of the path joining them is given by the logarithm of those product quaternions, the norm of which is the same.
[ "Quaternion", "intrinsic", "distance", "." ]
python
train
its-rigs/Trolly
trolly/organisation.py
https://github.com/its-rigs/Trolly/blob/483dc94c352df40dc05ead31820b059b2545cf82/trolly/organisation.py#L38-L53
def get_members(self, **query_params): ''' Get all members attached to this organisation. Returns a list of Member objects Returns: list(Member): The members attached to this organisation ''' members = self.get_members_json(self.base_uri, query_params=query_params) members_list = [] for member_json in members: members_list.append(self.create_member(member_json)) return members_list
[ "def", "get_members", "(", "self", ",", "*", "*", "query_params", ")", ":", "members", "=", "self", ".", "get_members_json", "(", "self", ".", "base_uri", ",", "query_params", "=", "query_params", ")", "members_list", "=", "[", "]", "for", "member_json", "...
Get all members attached to this organisation. Returns a list of Member objects Returns: list(Member): The members attached to this organisation
[ "Get", "all", "members", "attached", "to", "this", "organisation", ".", "Returns", "a", "list", "of", "Member", "objects" ]
python
test
DataONEorg/d1_python
lib_common/src/d1_common/types/exceptions.py
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/types/exceptions.py#L155-L186
def create_exception_by_name( name, detailCode='0', description='', traceInformation=None, identifier=None, nodeId=None, ): """Create a DataONEException based object by name. Args: name: str The type name of a DataONE Exception. E.g. NotFound. If an unknown type name is used, it is automatically set to ServiceFailure. As the XML Schema for DataONE Exceptions does not restrict the type names, this may occur when deserializing an exception not defined by DataONE. detailCode: int Optional index into a table of predefined error conditions. See Also: For remaining args, see: ``DataONEException()`` """ try: dataone_exception = globals()[name] except LookupError: dataone_exception = ServiceFailure return dataone_exception( detailCode, description, traceInformation, identifier, nodeId )
[ "def", "create_exception_by_name", "(", "name", ",", "detailCode", "=", "'0'", ",", "description", "=", "''", ",", "traceInformation", "=", "None", ",", "identifier", "=", "None", ",", "nodeId", "=", "None", ",", ")", ":", "try", ":", "dataone_exception", ...
Create a DataONEException based object by name. Args: name: str The type name of a DataONE Exception. E.g. NotFound. If an unknown type name is used, it is automatically set to ServiceFailure. As the XML Schema for DataONE Exceptions does not restrict the type names, this may occur when deserializing an exception not defined by DataONE. detailCode: int Optional index into a table of predefined error conditions. See Also: For remaining args, see: ``DataONEException()``
[ "Create", "a", "DataONEException", "based", "object", "by", "name", "." ]
python
train
ssato/python-anyconfig
src/anyconfig/backend/base.py
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L328-L336
def dump_to_path(self, cnf, filepath, **kwargs): """ Dump config 'cnf' to a file 'filepath'. :param cnf: Configuration data to dump :param filepath: Config file path :param kwargs: optional keyword parameters to be sanitized :: dict """ _not_implemented(self, cnf, filepath, **kwargs)
[ "def", "dump_to_path", "(", "self", ",", "cnf", ",", "filepath", ",", "*", "*", "kwargs", ")", ":", "_not_implemented", "(", "self", ",", "cnf", ",", "filepath", ",", "*", "*", "kwargs", ")" ]
Dump config 'cnf' to a file 'filepath'. :param cnf: Configuration data to dump :param filepath: Config file path :param kwargs: optional keyword parameters to be sanitized :: dict
[ "Dump", "config", "cnf", "to", "a", "file", "filepath", "." ]
python
train
modin-project/modin
modin/pandas/__init__.py
https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/pandas/__init__.py#L133-L168
def initialize_ray(): """Initializes ray based on environment variables and internal defaults.""" if threading.current_thread().name == "MainThread": plasma_directory = None object_store_memory = os.environ.get("MODIN_MEMORY", None) if os.environ.get("MODIN_OUT_OF_CORE", "False").title() == "True": from tempfile import gettempdir plasma_directory = gettempdir() # We may have already set the memory from the environment variable, we don't # want to overwrite that value if we have. if object_store_memory is None: # Round down to the nearest Gigabyte. mem_bytes = ray.utils.get_system_memory() // 10 ** 9 * 10 ** 9 # Default to 8x memory for out of core object_store_memory = 8 * mem_bytes # In case anything failed above, we can still improve the memory for Modin. if object_store_memory is None: # Round down to the nearest Gigabyte. object_store_memory = int( 0.6 * ray.utils.get_system_memory() // 10 ** 9 * 10 ** 9 ) # If the memory pool is smaller than 2GB, just use the default in ray. if object_store_memory == 0: object_store_memory = None else: object_store_memory = int(object_store_memory) ray.init( include_webui=False, ignore_reinit_error=True, plasma_directory=plasma_directory, object_store_memory=object_store_memory, ) # Register custom serializer for method objects to avoid warning message. # We serialize `MethodType` objects when we use AxisPartition operations. ray.register_custom_serializer(types.MethodType, use_pickle=True)
[ "def", "initialize_ray", "(", ")", ":", "if", "threading", ".", "current_thread", "(", ")", ".", "name", "==", "\"MainThread\"", ":", "plasma_directory", "=", "None", "object_store_memory", "=", "os", ".", "environ", ".", "get", "(", "\"MODIN_MEMORY\"", ",", ...
Initializes ray based on environment variables and internal defaults.
[ "Initializes", "ray", "based", "on", "environment", "variables", "and", "internal", "defaults", "." ]
python
train
hydpy-dev/hydpy
hydpy/models/dam/dam_model.py
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/dam/dam_model.py#L933-L999
def calc_possibleremoterelieve_v1(self): """Calculate the highest possible water release that can be routed to a remote location based on an artificial neural network describing the relationship between possible release and water stage. Required control parameter: |WaterLevel2PossibleRemoteRelieve| Required aide sequence: |WaterLevel| Calculated flux sequence: |PossibleRemoteRelieve| Example: For simplicity, the example of method |calc_flooddischarge_v1| is reused. See the documentation on the mentioned method for further information: >>> from hydpy.models.dam import * >>> parameterstep() >>> waterlevel2possibleremoterelieve( ... nmb_inputs=1, ... nmb_neurons=(2,), ... nmb_outputs=1, ... weights_input=[[50., 4]], ... weights_output=[[2.], [30]], ... intercepts_hidden=[[-13000, -1046]], ... intercepts_output=[0.]) >>> from hydpy import UnitTest >>> test = UnitTest( ... model, model.calc_possibleremoterelieve_v1, ... last_example=21, ... parseqs=(aides.waterlevel, fluxes.possibleremoterelieve)) >>> test.nexts.waterlevel = numpy.arange(257, 261.1, 0.2) >>> test() | ex. | waterlevel | possibleremoterelieve | -------------------------------------------- | 1 | 257.0 | 0.0 | | 2 | 257.2 | 0.000001 | | 3 | 257.4 | 0.000002 | | 4 | 257.6 | 0.000005 | | 5 | 257.8 | 0.000011 | | 6 | 258.0 | 0.000025 | | 7 | 258.2 | 0.000056 | | 8 | 258.4 | 0.000124 | | 9 | 258.6 | 0.000275 | | 10 | 258.8 | 0.000612 | | 11 | 259.0 | 0.001362 | | 12 | 259.2 | 0.003031 | | 13 | 259.4 | 0.006745 | | 14 | 259.6 | 0.015006 | | 15 | 259.8 | 0.033467 | | 16 | 260.0 | 1.074179 | | 17 | 260.2 | 2.164498 | | 18 | 260.4 | 2.363853 | | 19 | 260.6 | 2.79791 | | 20 | 260.8 | 3.719725 | | 21 | 261.0 | 5.576088 | """ con = self.parameters.control.fastaccess flu = self.sequences.fluxes.fastaccess aid = self.sequences.aides.fastaccess con.waterlevel2possibleremoterelieve.inputs[0] = aid.waterlevel con.waterlevel2possibleremoterelieve.process_actual_input() flu.possibleremoterelieve = con.waterlevel2possibleremoterelieve.outputs[0]
[ "def", "calc_possibleremoterelieve_v1", "(", "self", ")", ":", "con", "=", "self", ".", "parameters", ".", "control", ".", "fastaccess", "flu", "=", "self", ".", "sequences", ".", "fluxes", ".", "fastaccess", "aid", "=", "self", ".", "sequences", ".", "aid...
Calculate the highest possible water release that can be routed to a remote location based on an artificial neural network describing the relationship between possible release and water stage. Required control parameter: |WaterLevel2PossibleRemoteRelieve| Required aide sequence: |WaterLevel| Calculated flux sequence: |PossibleRemoteRelieve| Example: For simplicity, the example of method |calc_flooddischarge_v1| is reused. See the documentation on the mentioned method for further information: >>> from hydpy.models.dam import * >>> parameterstep() >>> waterlevel2possibleremoterelieve( ... nmb_inputs=1, ... nmb_neurons=(2,), ... nmb_outputs=1, ... weights_input=[[50., 4]], ... weights_output=[[2.], [30]], ... intercepts_hidden=[[-13000, -1046]], ... intercepts_output=[0.]) >>> from hydpy import UnitTest >>> test = UnitTest( ... model, model.calc_possibleremoterelieve_v1, ... last_example=21, ... parseqs=(aides.waterlevel, fluxes.possibleremoterelieve)) >>> test.nexts.waterlevel = numpy.arange(257, 261.1, 0.2) >>> test() | ex. | waterlevel | possibleremoterelieve | -------------------------------------------- | 1 | 257.0 | 0.0 | | 2 | 257.2 | 0.000001 | | 3 | 257.4 | 0.000002 | | 4 | 257.6 | 0.000005 | | 5 | 257.8 | 0.000011 | | 6 | 258.0 | 0.000025 | | 7 | 258.2 | 0.000056 | | 8 | 258.4 | 0.000124 | | 9 | 258.6 | 0.000275 | | 10 | 258.8 | 0.000612 | | 11 | 259.0 | 0.001362 | | 12 | 259.2 | 0.003031 | | 13 | 259.4 | 0.006745 | | 14 | 259.6 | 0.015006 | | 15 | 259.8 | 0.033467 | | 16 | 260.0 | 1.074179 | | 17 | 260.2 | 2.164498 | | 18 | 260.4 | 2.363853 | | 19 | 260.6 | 2.79791 | | 20 | 260.8 | 3.719725 | | 21 | 261.0 | 5.576088 |
[ "Calculate", "the", "highest", "possible", "water", "release", "that", "can", "be", "routed", "to", "a", "remote", "location", "based", "on", "an", "artificial", "neural", "network", "describing", "the", "relationship", "between", "possible", "release", "and", "...
python
train
BernardFW/bernard
src/bernard/engine/request.py
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/engine/request.py#L229-L240
async def get_locale(self) -> Text: """ Get the locale to use for this request. It's either the overridden locale or the locale provided by the platform. :return: Locale to use for this request """ if self._locale_override: return self._locale_override else: return await self.user.get_locale()
[ "async", "def", "get_locale", "(", "self", ")", "->", "Text", ":", "if", "self", ".", "_locale_override", ":", "return", "self", ".", "_locale_override", "else", ":", "return", "await", "self", ".", "user", ".", "get_locale", "(", ")" ]
Get the locale to use for this request. It's either the overridden locale or the locale provided by the platform. :return: Locale to use for this request
[ "Get", "the", "locale", "to", "use", "for", "this", "request", ".", "It", "s", "either", "the", "overridden", "locale", "or", "the", "locale", "provided", "by", "the", "platform", "." ]
python
train
happyleavesaoc/python-fedexdeliverymanager
fedexdeliverymanager/__init__.py
https://github.com/happyleavesaoc/python-fedexdeliverymanager/blob/cff2f1104a86573569500d41e69be54b90b596c6/fedexdeliverymanager/__init__.py#L90-L123
def get_packages(session): """Get packages.""" resp = session.post(TRACKING_URL, { 'data': json.dumps(SHIPMENT_LIST_REQUEST), 'action': SHIPMENT_LIST_ACTION, 'format': SHIPMENT_LIST_FORMAT, 'locale': session.auth.locale, 'version': 1 }) data = resp.json().get('ShipmentListLightResponse') if not data.get('successful'): err = 'failed to get shipment list: {}'.format(data.get('errorList')[0] .get('message')) raise FedexError(err) packages = [] for package in data.get('shipmentLightList'): if 'trkNbr' not in package or not package['trkNbr']: continue if 'isOut' in package and package['isOut'] == '1': continue packages.append({ 'weight': package['dispPkgLbsWgt'], 'dimensions': package['pkgDimIn'], 'tracking_number': package['trkNbr'], 'from': package['shpBy'], 'shipped_from': '{} {} {} {}'.format(package['shprAddr1'], package['shprCity'], package['shprStCD'], package['shprCntryCD']), 'primary_status': package['keyStat'], 'secondary_status': package['mainStat'], 'estimated_delivery_date': (str(parse(package['estDelTs']).date()) if package['estDelTs'] else ''), 'delivery_date': str(parse(package['delTs']).date()) if package['delTs'] else '' }) return packages
[ "def", "get_packages", "(", "session", ")", ":", "resp", "=", "session", ".", "post", "(", "TRACKING_URL", ",", "{", "'data'", ":", "json", ".", "dumps", "(", "SHIPMENT_LIST_REQUEST", ")", ",", "'action'", ":", "SHIPMENT_LIST_ACTION", ",", "'format'", ":", ...
Get packages.
[ "Get", "packages", "." ]
python
train
prometheus/client_python
prometheus_client/metrics.py
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/metrics.py#L525-L531
def observe(self, amount): """Observe the given amount.""" self._sum.inc(amount) for i, bound in enumerate(self._upper_bounds): if amount <= bound: self._buckets[i].inc(1) break
[ "def", "observe", "(", "self", ",", "amount", ")", ":", "self", ".", "_sum", ".", "inc", "(", "amount", ")", "for", "i", ",", "bound", "in", "enumerate", "(", "self", ".", "_upper_bounds", ")", ":", "if", "amount", "<=", "bound", ":", "self", ".", ...
Observe the given amount.
[ "Observe", "the", "given", "amount", "." ]
python
train
ly0/baidupcsapi
baidupcsapi/api.py
https://github.com/ly0/baidupcsapi/blob/6f6feeef0767a75b3b968924727460eb09242d76/baidupcsapi/api.py#L1281-L1301
def rename(self, rename_pair_list, **kwargs): """重命名 :param rename_pair_list: 需要重命名的文件(夹)pair (路径,新名称)列表,如[('/aa.txt','bb.txt')] :type rename_pair_list: list """ foo = [] for path, newname in rename_pair_list: foo.append({'path': path, 'newname': newname }) data = {'filelist': json.dumps(foo)} params = { 'opera': 'rename' } url = 'http://{0}/api/filemanager'.format(BAIDUPAN_SERVER) logging.debug('rename ' + str(data) + 'URL:' + url) return self._request('filemanager', 'rename', url=url, data=data, extra_params=params, **kwargs)
[ "def", "rename", "(", "self", ",", "rename_pair_list", ",", "*", "*", "kwargs", ")", ":", "foo", "=", "[", "]", "for", "path", ",", "newname", "in", "rename_pair_list", ":", "foo", ".", "append", "(", "{", "'path'", ":", "path", ",", "'newname'", ":"...
重命名 :param rename_pair_list: 需要重命名的文件(夹)pair (路径,新名称)列表,如[('/aa.txt','bb.txt')] :type rename_pair_list: list
[ "重命名" ]
python
train
SpamScope/mail-parser
mailparser/mailparser.py
https://github.com/SpamScope/mail-parser/blob/814b56d0b803feab9dea04f054b802ce138097e2/mailparser/mailparser.py#L586-L591
def date_json(self): """ Return the JSON of date """ if self.date: return json.dumps(self.date.isoformat(), ensure_ascii=False)
[ "def", "date_json", "(", "self", ")", ":", "if", "self", ".", "date", ":", "return", "json", ".", "dumps", "(", "self", ".", "date", ".", "isoformat", "(", ")", ",", "ensure_ascii", "=", "False", ")" ]
Return the JSON of date
[ "Return", "the", "JSON", "of", "date" ]
python
train
HumanCellAtlas/dcp-cli
hca/upload/lib/s3_agent.py
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/lib/s3_agent.py#L16-L28
def sizeof_fmt(num, suffix='B'): """ Adapted from https://stackoverflow.com/a/1094933 Re: precision - display enough decimals to show progress on a slow (<5 MB/s) Internet connection """ precision = {'': 0, 'Ki': 0, 'Mi': 0, 'Gi': 3, 'Ti': 6, 'Pi': 9, 'Ei': 12, 'Zi': 15} for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: format_string = "{number:.%df} {unit}{suffix}" % precision[unit] return format_string.format(number=num, unit=unit, suffix=suffix) num /= 1024.0 return "%.18f %s%s" % (num, 'Yi', suffix)
[ "def", "sizeof_fmt", "(", "num", ",", "suffix", "=", "'B'", ")", ":", "precision", "=", "{", "''", ":", "0", ",", "'Ki'", ":", "0", ",", "'Mi'", ":", "0", ",", "'Gi'", ":", "3", ",", "'Ti'", ":", "6", ",", "'Pi'", ":", "9", ",", "'Ei'", ":"...
Adapted from https://stackoverflow.com/a/1094933 Re: precision - display enough decimals to show progress on a slow (<5 MB/s) Internet connection
[ "Adapted", "from", "https", ":", "//", "stackoverflow", ".", "com", "/", "a", "/", "1094933", "Re", ":", "precision", "-", "display", "enough", "decimals", "to", "show", "progress", "on", "a", "slow", "(", "<5", "MB", "/", "s", ")", "Internet", "connec...
python
train
OpenHydrology/floodestimation
floodestimation/analysis.py
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/analysis.py#L324-L346
def _qmed_from_descriptors_1999(self, as_rural=False): """ Return QMED estimation based on FEH catchment descriptors, 1999 methodology. Methodology source: FEH, Vol. 3, p. 14 :param as_rural: assume catchment is fully rural. Default: false. :type as_rural: bool :return: QMED in m³/s :rtype: float """ try: qmed_rural = 1.172 * self.catchment.descriptors.dtm_area ** self._area_exponent() \ * (self.catchment.descriptors.saar / 1000.0) ** 1.560 \ * self.catchment.descriptors.farl ** 2.642 \ * (self.catchment.descriptors.sprhost / 100.0) ** 1.211 * \ 0.0198 ** self._residual_soil() if as_rural: return qmed_rural else: return qmed_rural * self.urban_adj_factor() except (TypeError, KeyError): raise InsufficientDataError("Catchment `descriptors` attribute must be set first.")
[ "def", "_qmed_from_descriptors_1999", "(", "self", ",", "as_rural", "=", "False", ")", ":", "try", ":", "qmed_rural", "=", "1.172", "*", "self", ".", "catchment", ".", "descriptors", ".", "dtm_area", "**", "self", ".", "_area_exponent", "(", ")", "*", "(",...
Return QMED estimation based on FEH catchment descriptors, 1999 methodology. Methodology source: FEH, Vol. 3, p. 14 :param as_rural: assume catchment is fully rural. Default: false. :type as_rural: bool :return: QMED in m³/s :rtype: float
[ "Return", "QMED", "estimation", "based", "on", "FEH", "catchment", "descriptors", "1999", "methodology", "." ]
python
train
basecrm/basecrm-python
basecrm/services.py
https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L653-L666
def list(self, **params): """ Retrieve all leads Returns all leads available to the user, according to the parameters provided :calls: ``get /leads`` :param dict params: (optional) Search options. :return: List of dictionaries that support attriubte-style access, which represent collection of Leads. :rtype: list """ _, _, leads = self.http_client.get("/leads", params=params) return leads
[ "def", "list", "(", "self", ",", "*", "*", "params", ")", ":", "_", ",", "_", ",", "leads", "=", "self", ".", "http_client", ".", "get", "(", "\"/leads\"", ",", "params", "=", "params", ")", "return", "leads" ]
Retrieve all leads Returns all leads available to the user, according to the parameters provided :calls: ``get /leads`` :param dict params: (optional) Search options. :return: List of dictionaries that support attriubte-style access, which represent collection of Leads. :rtype: list
[ "Retrieve", "all", "leads" ]
python
train
jmgilman/Neolib
neolib/pyamf/amf3.py
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/amf3.py#L1212-L1222
def serialiseString(self, s): """ Writes a raw string to the stream. @type s: C{str} @param s: The string data to be encoded to the AMF3 data stream. """ if type(s) is unicode: s = self.context.getBytesForString(s) self.serialiseBytes(s)
[ "def", "serialiseString", "(", "self", ",", "s", ")", ":", "if", "type", "(", "s", ")", "is", "unicode", ":", "s", "=", "self", ".", "context", ".", "getBytesForString", "(", "s", ")", "self", ".", "serialiseBytes", "(", "s", ")" ]
Writes a raw string to the stream. @type s: C{str} @param s: The string data to be encoded to the AMF3 data stream.
[ "Writes", "a", "raw", "string", "to", "the", "stream", "." ]
python
train
radjkarl/fancyTools
fancytools/pystructure/getMembers.py
https://github.com/radjkarl/fancyTools/blob/4c4d961003dc4ed6e46429a0c24f7e2bb52caa8b/fancytools/pystructure/getMembers.py#L11-L18
def getAvailableClassesInModule(prooveModule): """ return a list of all classes in the given module that dont begin with '_' """ l = tuple(x[1] for x in inspect.getmembers(prooveModule, inspect.isclass)) l = [x for x in l if x.__name__[0] != "_"] return l
[ "def", "getAvailableClassesInModule", "(", "prooveModule", ")", ":", "l", "=", "tuple", "(", "x", "[", "1", "]", "for", "x", "in", "inspect", ".", "getmembers", "(", "prooveModule", ",", "inspect", ".", "isclass", ")", ")", "l", "=", "[", "x", "for", ...
return a list of all classes in the given module that dont begin with '_'
[ "return", "a", "list", "of", "all", "classes", "in", "the", "given", "module", "that", "dont", "begin", "with", "_" ]
python
train
gpoulter/fablib
fablib.py
https://github.com/gpoulter/fablib/blob/5d14c4d998f79dd1aa3207063c3d06e30e3e2bf9/fablib.py#L19-L32
def default_roles(*role_list): """Decorate task with these roles by default, but override with -R, -H""" def selectively_attach(func): """Only decorate if nothing specified on command line""" # pylint: disable=W0142 if not env.roles and not env.hosts: return roles(*role_list)(func) else: if env.hosts: func = hosts(*env.hosts)(func) if env.roles: func = roles(*env.roles)(func) return func return selectively_attach
[ "def", "default_roles", "(", "*", "role_list", ")", ":", "def", "selectively_attach", "(", "func", ")", ":", "\"\"\"Only decorate if nothing specified on command line\"\"\"", "# pylint: disable=W0142", "if", "not", "env", ".", "roles", "and", "not", "env", ".", "hosts...
Decorate task with these roles by default, but override with -R, -H
[ "Decorate", "task", "with", "these", "roles", "by", "default", "but", "override", "with", "-", "R", "-", "H" ]
python
train
OpenGov/carpenter
carpenter/blocks/tableanalyzer.py
https://github.com/OpenGov/carpenter/blob/0ab3c54c05133b9b0468c63e834a7ce3a6fb575b/carpenter/blocks/tableanalyzer.py#L198-L223
def _find_valid_block(self, table, worksheet, flags, units, used_cells, start_pos, end_pos): ''' Searches for the next location where a valid block could reside and constructs the block object representing that location. ''' for row_index in range(len(table)): if row_index < start_pos[0] or row_index > end_pos[0]: continue convRow = table[row_index] used_row = used_cells[row_index] for column_index, conv in enumerate(convRow): if (column_index < start_pos[1] or column_index > end_pos[1] or used_row[column_index]): continue # Is non empty cell? if not is_empty_cell(conv): block_start, block_end = self._find_block_bounds(table, used_cells, (row_index, column_index), start_pos, end_pos) if (block_end[0] > block_start[0] and block_end[1] > block_start[1]): try: return TableBlock(table, used_cells, block_start, block_end, worksheet, flags, units, self.assume_complete_blocks, self.max_title_rows) except InvalidBlockError: pass # Prevent infinite loops if something goes wrong used_cells[row_index][column_index] = True
[ "def", "_find_valid_block", "(", "self", ",", "table", ",", "worksheet", ",", "flags", ",", "units", ",", "used_cells", ",", "start_pos", ",", "end_pos", ")", ":", "for", "row_index", "in", "range", "(", "len", "(", "table", ")", ")", ":", "if", "row_i...
Searches for the next location where a valid block could reside and constructs the block object representing that location.
[ "Searches", "for", "the", "next", "location", "where", "a", "valid", "block", "could", "reside", "and", "constructs", "the", "block", "object", "representing", "that", "location", "." ]
python
train
dhhagan/py-opc
opc/__init__.py
https://github.com/dhhagan/py-opc/blob/2c8f19530fb64bf5fd4ee0d694a47850161ed8a7/opc/__init__.py#L1041-L1103
def read_histogram(self): """Read and reset the histogram. The expected return is a dictionary containing the counts per bin, MToF for bins 1, 3, 5, and 7, temperature, pressure, the sampling period, the checksum, PM1, PM2.5, and PM10. **NOTE:** The sampling period for the OPCN1 seems to be incorrect. :returns: dictionary """ resp = [] data = {} # command byte command = 0x30 # Send the command byte self.cnxn.xfer([command]) # Wait 10 ms sleep(10e-3) # read the histogram for i in range(62): r = self.cnxn.xfer([0x00])[0] resp.append(r) # convert to real things and store in dictionary! data['Bin 0'] = self._16bit_unsigned(resp[0], resp[1]) data['Bin 1'] = self._16bit_unsigned(resp[2], resp[3]) data['Bin 2'] = self._16bit_unsigned(resp[4], resp[5]) data['Bin 3'] = self._16bit_unsigned(resp[6], resp[7]) data['Bin 4'] = self._16bit_unsigned(resp[8], resp[9]) data['Bin 5'] = self._16bit_unsigned(resp[10], resp[11]) data['Bin 6'] = self._16bit_unsigned(resp[12], resp[13]) data['Bin 7'] = self._16bit_unsigned(resp[14], resp[15]) data['Bin 8'] = self._16bit_unsigned(resp[16], resp[17]) data['Bin 9'] = self._16bit_unsigned(resp[18], resp[19]) data['Bin 10'] = self._16bit_unsigned(resp[20], resp[21]) data['Bin 11'] = self._16bit_unsigned(resp[22], resp[23]) data['Bin 12'] = self._16bit_unsigned(resp[24], resp[25]) data['Bin 13'] = self._16bit_unsigned(resp[26], resp[27]) data['Bin 14'] = self._16bit_unsigned(resp[28], resp[29]) data['Bin 15'] = self._16bit_unsigned(resp[30], resp[31]) data['Bin1 MToF'] = self._calculate_mtof(resp[32]) data['Bin3 MToF'] = self._calculate_mtof(resp[33]) data['Bin5 MToF'] = self._calculate_mtof(resp[34]) data['Bin7 MToF'] = self._calculate_mtof(resp[35]) data['Temperature'] = self._calculate_temp(resp[36:40]) data['Pressure'] = self._calculate_pressure(resp[40:44]) data['Sampling Period'] = self._calculate_period(resp[44:48]) data['Checksum'] = self._16bit_unsigned(resp[48], resp[49]) data['PM1'] = self._calculate_float(resp[50:54]) data['PM2.5'] = self._calculate_float(resp[54:58]) data['PM10'] = self._calculate_float(resp[58:]) # Calculate the sum of the histogram bins histogram_sum = data['Bin 0'] + data['Bin 1'] + data['Bin 2'] + \ data['Bin 3'] + data['Bin 4'] + data['Bin 5'] + data['Bin 6'] + \ data['Bin 7'] + data['Bin 8'] + data['Bin 9'] + data['Bin 10'] + \ data['Bin 11'] + data['Bin 12'] + data['Bin 13'] + data['Bin 14'] + \ data['Bin 15'] return data
[ "def", "read_histogram", "(", "self", ")", ":", "resp", "=", "[", "]", "data", "=", "{", "}", "# command byte", "command", "=", "0x30", "# Send the command byte", "self", ".", "cnxn", ".", "xfer", "(", "[", "command", "]", ")", "# Wait 10 ms", "sleep", "...
Read and reset the histogram. The expected return is a dictionary containing the counts per bin, MToF for bins 1, 3, 5, and 7, temperature, pressure, the sampling period, the checksum, PM1, PM2.5, and PM10. **NOTE:** The sampling period for the OPCN1 seems to be incorrect. :returns: dictionary
[ "Read", "and", "reset", "the", "histogram", ".", "The", "expected", "return", "is", "a", "dictionary", "containing", "the", "counts", "per", "bin", "MToF", "for", "bins", "1", "3", "5", "and", "7", "temperature", "pressure", "the", "sampling", "period", "t...
python
valid
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/transforms/_util.py
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/transforms/_util.py#L143-L164
def get(self, path): """ Get a transform from the cache that maps along *path*, which must be a list of Transforms to apply in reverse order (last transform is applied first). Accessed items have their age reset to 0. """ key = tuple(map(id, path)) item = self._cache.get(key, None) if item is None: logger.debug("Transform cache miss: %s", key) item = [0, self._create(path)] self._cache[key] = item item[0] = 0 # reset age for this item # make sure the chain is up to date #tr = item[1] #for i, node in enumerate(path[1:]): # if tr.transforms[i] is not node.transform: # tr[i] = node.transform return item[1]
[ "def", "get", "(", "self", ",", "path", ")", ":", "key", "=", "tuple", "(", "map", "(", "id", ",", "path", ")", ")", "item", "=", "self", ".", "_cache", ".", "get", "(", "key", ",", "None", ")", "if", "item", "is", "None", ":", "logger", ".",...
Get a transform from the cache that maps along *path*, which must be a list of Transforms to apply in reverse order (last transform is applied first). Accessed items have their age reset to 0.
[ "Get", "a", "transform", "from", "the", "cache", "that", "maps", "along", "*", "path", "*", "which", "must", "be", "a", "list", "of", "Transforms", "to", "apply", "in", "reverse", "order", "(", "last", "transform", "is", "applied", "first", ")", "." ]
python
train
mongodb/mongo-python-driver
pymongo/collection.py
https://github.com/mongodb/mongo-python-driver/blob/c29c21449e3aae74154207058cf85fd94018d4cd/pymongo/collection.py#L1625-L1702
def count_documents(self, filter, session=None, **kwargs): """Count the number of documents in this collection. The :meth:`count_documents` method is supported in a transaction. All optional parameters should be passed as keyword arguments to this method. Valid options include: - `skip` (int): The number of matching documents to skip before returning results. - `limit` (int): The maximum number of documents to count. Must be a positive integer. If not provided, no limit is imposed. - `maxTimeMS` (int): The maximum amount of time to allow this operation to run, in milliseconds. - `collation` (optional): An instance of :class:`~pymongo.collation.Collation`. This option is only supported on MongoDB 3.4 and above. - `hint` (string or list of tuples): The index to use. Specify either the index name as a string or the index specification as a list of tuples (e.g. [('a', pymongo.ASCENDING), ('b', pymongo.ASCENDING)]). This option is only supported on MongoDB 3.6 and above. The :meth:`count_documents` method obeys the :attr:`read_preference` of this :class:`Collection`. .. note:: When migrating from :meth:`count` to :meth:`count_documents` the following query operators must be replaced: +-------------+-------------------------------------+ | Operator | Replacement | +=============+=====================================+ | $where | `$expr`_ | +-------------+-------------------------------------+ | $near | `$geoWithin`_ with `$center`_ | +-------------+-------------------------------------+ | $nearSphere | `$geoWithin`_ with `$centerSphere`_ | +-------------+-------------------------------------+ $expr requires MongoDB 3.6+ :Parameters: - `filter` (required): A query document that selects which documents to count in the collection. Can be an empty document to count all documents. - `session` (optional): a :class:`~pymongo.client_session.ClientSession`. - `**kwargs` (optional): See list of options above. .. versionadded:: 3.7 .. _$expr: https://docs.mongodb.com/manual/reference/operator/query/expr/ .. _$geoWithin: https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ .. _$center: https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center .. _$centerSphere: https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere """ pipeline = [{'$match': filter}] if 'skip' in kwargs: pipeline.append({'$skip': kwargs.pop('skip')}) if 'limit' in kwargs: pipeline.append({'$limit': kwargs.pop('limit')}) pipeline.append({'$group': {'_id': 1, 'n': {'$sum': 1}}}) cmd = SON([('aggregate', self.__name), ('pipeline', pipeline), ('cursor', {})]) if "hint" in kwargs and not isinstance(kwargs["hint"], string_type): kwargs["hint"] = helpers._index_document(kwargs["hint"]) collation = validate_collation_or_none(kwargs.pop('collation', None)) cmd.update(kwargs) def _cmd(session, server, sock_info, slave_ok): result = self._aggregate_one_result( sock_info, slave_ok, cmd, collation, session) if not result: return 0 return result['n'] return self.__database.client._retryable_read( _cmd, self._read_preference_for(session), session)
[ "def", "count_documents", "(", "self", ",", "filter", ",", "session", "=", "None", ",", "*", "*", "kwargs", ")", ":", "pipeline", "=", "[", "{", "'$match'", ":", "filter", "}", "]", "if", "'skip'", "in", "kwargs", ":", "pipeline", ".", "append", "(",...
Count the number of documents in this collection. The :meth:`count_documents` method is supported in a transaction. All optional parameters should be passed as keyword arguments to this method. Valid options include: - `skip` (int): The number of matching documents to skip before returning results. - `limit` (int): The maximum number of documents to count. Must be a positive integer. If not provided, no limit is imposed. - `maxTimeMS` (int): The maximum amount of time to allow this operation to run, in milliseconds. - `collation` (optional): An instance of :class:`~pymongo.collation.Collation`. This option is only supported on MongoDB 3.4 and above. - `hint` (string or list of tuples): The index to use. Specify either the index name as a string or the index specification as a list of tuples (e.g. [('a', pymongo.ASCENDING), ('b', pymongo.ASCENDING)]). This option is only supported on MongoDB 3.6 and above. The :meth:`count_documents` method obeys the :attr:`read_preference` of this :class:`Collection`. .. note:: When migrating from :meth:`count` to :meth:`count_documents` the following query operators must be replaced: +-------------+-------------------------------------+ | Operator | Replacement | +=============+=====================================+ | $where | `$expr`_ | +-------------+-------------------------------------+ | $near | `$geoWithin`_ with `$center`_ | +-------------+-------------------------------------+ | $nearSphere | `$geoWithin`_ with `$centerSphere`_ | +-------------+-------------------------------------+ $expr requires MongoDB 3.6+ :Parameters: - `filter` (required): A query document that selects which documents to count in the collection. Can be an empty document to count all documents. - `session` (optional): a :class:`~pymongo.client_session.ClientSession`. - `**kwargs` (optional): See list of options above. .. versionadded:: 3.7 .. _$expr: https://docs.mongodb.com/manual/reference/operator/query/expr/ .. _$geoWithin: https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ .. _$center: https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center .. _$centerSphere: https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere
[ "Count", "the", "number", "of", "documents", "in", "this", "collection", "." ]
python
train
biosustain/optlang
optlang/interface.py
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/interface.py#L229-L241
def set_bounds(self, lb, ub): """ Change the lower and upper bounds of a variable. """ if lb is not None and ub is not None and lb > ub: raise ValueError( "The provided lower bound {} is larger than the provided upper bound {}".format(lb, ub) ) self._lb = lb self._ub = ub if self.problem is not None: self.problem._pending_modifications.var_lb.append((self, lb)) self.problem._pending_modifications.var_ub.append((self, ub))
[ "def", "set_bounds", "(", "self", ",", "lb", ",", "ub", ")", ":", "if", "lb", "is", "not", "None", "and", "ub", "is", "not", "None", "and", "lb", ">", "ub", ":", "raise", "ValueError", "(", "\"The provided lower bound {} is larger than the provided upper bound...
Change the lower and upper bounds of a variable.
[ "Change", "the", "lower", "and", "upper", "bounds", "of", "a", "variable", "." ]
python
train
AkihikoITOH/capybara
capybara/virtualenv/lib/python2.7/site-packages/setuptools/command/easy_install.py
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/setuptools/command/easy_install.py#L758-L766
def install_script(self, dist, script_name, script_text, dev_path=None): """Generate a legacy script wrapper and install it""" spec = str(dist.as_requirement()) is_script = is_python_script(script_text, script_name) if is_script: script_text = (ScriptWriter.get_header(script_text) + self._load_template(dev_path) % locals()) self.write_script(script_name, _to_ascii(script_text), 'b')
[ "def", "install_script", "(", "self", ",", "dist", ",", "script_name", ",", "script_text", ",", "dev_path", "=", "None", ")", ":", "spec", "=", "str", "(", "dist", ".", "as_requirement", "(", ")", ")", "is_script", "=", "is_python_script", "(", "script_tex...
Generate a legacy script wrapper and install it
[ "Generate", "a", "legacy", "script", "wrapper", "and", "install", "it" ]
python
test
eventbrite/eventbrite-sdk-python
eventbrite/access_methods.py
https://github.com/eventbrite/eventbrite-sdk-python/blob/f2e5dc5aa1aa3e45766de13f16fd65722163d91a/eventbrite/access_methods.py#L213-L222
def get_event_questions(self, id, **data): """ GET /events/:id/questions/ Eventbrite allows event organizers to add custom questions that attendees fill out upon registration. This endpoint can be helpful for determining what custom information is collected and available per event. This endpoint will return :format:`question`. """ return self.get("/events/{0}/questions/".format(id), data=data)
[ "def", "get_event_questions", "(", "self", ",", "id", ",", "*", "*", "data", ")", ":", "return", "self", ".", "get", "(", "\"/events/{0}/questions/\"", ".", "format", "(", "id", ")", ",", "data", "=", "data", ")" ]
GET /events/:id/questions/ Eventbrite allows event organizers to add custom questions that attendees fill out upon registration. This endpoint can be helpful for determining what custom information is collected and available per event. This endpoint will return :format:`question`.
[ "GET", "/", "events", "/", ":", "id", "/", "questions", "/", "Eventbrite", "allows", "event", "organizers", "to", "add", "custom", "questions", "that", "attendees", "fill", "out", "upon", "registration", ".", "This", "endpoint", "can", "be", "helpful", "for"...
python
train
pysathq/pysat
pysat/solvers.py
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/solvers.py#L1046-L1052
def conf_budget(self, budget): """ Set limit on the number of conflicts. """ if self.glucose: pysolvers.glucose3_cbudget(self.glucose, budget)
[ "def", "conf_budget", "(", "self", ",", "budget", ")", ":", "if", "self", ".", "glucose", ":", "pysolvers", ".", "glucose3_cbudget", "(", "self", ".", "glucose", ",", "budget", ")" ]
Set limit on the number of conflicts.
[ "Set", "limit", "on", "the", "number", "of", "conflicts", "." ]
python
train
limpyd/redis-limpyd-jobs
limpyd_jobs/models.py
https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/models.py#L298-L372
def add_job(cls, identifier, queue_name=None, priority=0, queue_model=None, prepend=False, delayed_for=None, delayed_until=None, **fields_if_new): """ Add a job to a queue. If this job already exists, check it's current priority. If its higher than the new one, don't touch it, else move the job to the wanted queue. Before setting/moving the job to the queue, check for a `delayed_for` (int/foat/timedelta) or `delayed_until` (datetime) argument to see if it must be delayed instead of queued. If the job is created, fields in fields_if_new will be set for the new job. Finally return the job. """ # check for delayed_for/delayed_until arguments delayed_until = compute_delayed_until(delayed_for, delayed_until) # create the job or get an existing one job_kwargs = {'identifier': identifier, 'queued': '1'} retries = 0 while retries < 10: retries += 1 try: job, created = cls.get_or_connect(**job_kwargs) except IndexError: # Failure during the retrieval https://friendpaste.com/5U63a8aFuV44SEgQckgMP # => retry continue except ValueError: # more than one already in the queue ! try: job = cls.collection(**job_kwargs).instances()[0] except IndexError: # but no more now ?! # => retry continue else: created = False # ok we have our job, stop now break try: # check queue_name queue_name = cls._get_queue_name(queue_name) # if the job already exists, and we want a higher priority or move it, # start by updating it if not created: current_priority = int(job.priority.hget() or 0) # if the job has a higher priority, or don't need to be moved, # don't move it if not prepend and current_priority >= priority: return job # cancel it temporarily, we'll set it as waiting later job.status.hset(STATUSES.CANCELED) # remove it from the current queue, we'll add it to the new one later if queue_model is None: queue_model = cls.queue_model current_queue = queue_model.get_queue(queue_name, current_priority) current_queue.waiting.lrem(0, job.ident) else: job.set_fields(added=str(datetime.utcnow()), **(fields_if_new or {})) # add the job to the queue job.enqueue_or_delay(queue_name, priority, delayed_until, prepend, queue_model) return job except Exception: job.queued.delete() raise
[ "def", "add_job", "(", "cls", ",", "identifier", ",", "queue_name", "=", "None", ",", "priority", "=", "0", ",", "queue_model", "=", "None", ",", "prepend", "=", "False", ",", "delayed_for", "=", "None", ",", "delayed_until", "=", "None", ",", "*", "*"...
Add a job to a queue. If this job already exists, check it's current priority. If its higher than the new one, don't touch it, else move the job to the wanted queue. Before setting/moving the job to the queue, check for a `delayed_for` (int/foat/timedelta) or `delayed_until` (datetime) argument to see if it must be delayed instead of queued. If the job is created, fields in fields_if_new will be set for the new job. Finally return the job.
[ "Add", "a", "job", "to", "a", "queue", ".", "If", "this", "job", "already", "exists", "check", "it", "s", "current", "priority", ".", "If", "its", "higher", "than", "the", "new", "one", "don", "t", "touch", "it", "else", "move", "the", "job", "to", ...
python
train