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
atztogo/phonopy
phonopy/harmonic/derivative_dynmat.py
https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/harmonic/derivative_dynmat.py#L209-L233
def _nac(self, q_direction): """nac_term = (A1 (x) A2) / B * coef. """ num_atom = self._pcell.get_number_of_atoms() nac_q = np.zeros((num_atom, num_atom, 3, 3), dtype='double') if (np.abs(q_direction) < 1e-5).all(): return nac_q rec_lat = np.linalg.inv(self._pcell.get_cell()) nac_factor = self._dynmat.get_nac_factor() Z = self._dynmat.get_born_effective_charges() e = self._dynmat.get_dielectric_constant() q = np.dot(rec_lat, q_direction) B = self._B(e, q) for i in range(num_atom): A_i = self._A(q, Z, i) for j in range(num_atom): A_j = self._A(q, Z, j) nac_q[i, j] = np.outer(A_i, A_j) / B num_satom = self._scell.get_number_of_atoms() N = num_satom // num_atom return nac_q * nac_factor / N
[ "def", "_nac", "(", "self", ",", "q_direction", ")", ":", "num_atom", "=", "self", ".", "_pcell", ".", "get_number_of_atoms", "(", ")", "nac_q", "=", "np", ".", "zeros", "(", "(", "num_atom", ",", "num_atom", ",", "3", ",", "3", ")", ",", "dtype", ...
nac_term = (A1 (x) A2) / B * coef.
[ "nac_term", "=", "(", "A1", "(", "x", ")", "A2", ")", "/", "B", "*", "coef", "." ]
python
train
Fantomas42/mots-vides
mots_vides/factory.py
https://github.com/Fantomas42/mots-vides/blob/eaeccf73bdb415d0c5559ccd74de360b37a2bbac/mots_vides/factory.py#L94-L100
def get_collection_filename(self, language): """ Returns the filename containing the stop words collection for a specific language. """ filename = os.path.join(self.data_directory, '%s.txt' % language) return filename
[ "def", "get_collection_filename", "(", "self", ",", "language", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "self", ".", "data_directory", ",", "'%s.txt'", "%", "language", ")", "return", "filename" ]
Returns the filename containing the stop words collection for a specific language.
[ "Returns", "the", "filename", "containing", "the", "stop", "words", "collection", "for", "a", "specific", "language", "." ]
python
train
santoshphilip/eppy
eppy/modeleditor.py
https://github.com/santoshphilip/eppy/blob/55410ff7c11722f35bc4331ff5e00a0b86f787e1/eppy/modeleditor.py#L818-L838
def getextensibleindex(self, key, name): """ Get the index of the first extensible item. Only for internal use. # TODO : hide this Parameters ---------- key : str The type of IDF object. This must be in ALL_CAPS. name : str The name of the object to fetch. Returns ------- int """ return getextensibleindex( self.idfobjects, self.model, self.idd_info, key, name)
[ "def", "getextensibleindex", "(", "self", ",", "key", ",", "name", ")", ":", "return", "getextensibleindex", "(", "self", ".", "idfobjects", ",", "self", ".", "model", ",", "self", ".", "idd_info", ",", "key", ",", "name", ")" ]
Get the index of the first extensible item. Only for internal use. # TODO : hide this Parameters ---------- key : str The type of IDF object. This must be in ALL_CAPS. name : str The name of the object to fetch. Returns ------- int
[ "Get", "the", "index", "of", "the", "first", "extensible", "item", "." ]
python
train
WebarchivCZ/WA-KAT
src/wa_kat/db/request_info.py
https://github.com/WebarchivCZ/WA-KAT/blob/16d064a3a775dc1d2713debda7847ded52dd2a06/src/wa_kat/db/request_info.py#L119-L131
def _get_all_set_properties(self): """ Collect names of set properties. Returns: set: Set containing names of all properties, which are set to \ non-None value. """ return set( property_name for property_name in worker_mapping().keys() if getattr(self, property_name) is not None )
[ "def", "_get_all_set_properties", "(", "self", ")", ":", "return", "set", "(", "property_name", "for", "property_name", "in", "worker_mapping", "(", ")", ".", "keys", "(", ")", "if", "getattr", "(", "self", ",", "property_name", ")", "is", "not", "None", "...
Collect names of set properties. Returns: set: Set containing names of all properties, which are set to \ non-None value.
[ "Collect", "names", "of", "set", "properties", "." ]
python
train
twilio/twilio-python
twilio/rest/preview/marketplace/installed_add_on/__init__.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/preview/marketplace/installed_add_on/__init__.py#L271-L289
def update(self, configuration=values.unset, unique_name=values.unset): """ Update the InstalledAddOnInstance :param dict configuration: The JSON object representing the configuration :param unicode unique_name: The string that uniquely identifies this Add-on installation :returns: Updated InstalledAddOnInstance :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnInstance """ data = values.of({'Configuration': serialize.object(configuration), 'UniqueName': unique_name, }) payload = self._version.update( 'POST', self._uri, data=data, ) return InstalledAddOnInstance(self._version, payload, sid=self._solution['sid'], )
[ "def", "update", "(", "self", ",", "configuration", "=", "values", ".", "unset", ",", "unique_name", "=", "values", ".", "unset", ")", ":", "data", "=", "values", ".", "of", "(", "{", "'Configuration'", ":", "serialize", ".", "object", "(", "configuratio...
Update the InstalledAddOnInstance :param dict configuration: The JSON object representing the configuration :param unicode unique_name: The string that uniquely identifies this Add-on installation :returns: Updated InstalledAddOnInstance :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnInstance
[ "Update", "the", "InstalledAddOnInstance" ]
python
train
horazont/aioxmpp
aioxmpp/xml.py
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xml.py#L1122-L1152
def read_xso(src, xsomap): """ Read a single XSO from a binary file-like input `src` containing an XML document. `xsomap` must be a mapping which maps :class:`~.XSO` subclasses to callables. These will be registered at a newly created :class:`.xso.XSOParser` instance which will be used to parse the document in `src`. The `xsomap` is thus used to determine the class parsing the root element of the XML document. This can be used to support multiple versions. """ xso_parser = xso.XSOParser() for class_, cb in xsomap.items(): xso_parser.add_class(class_, cb) driver = xso.SAXDriver(xso_parser) parser = xml.sax.make_parser() parser.setFeature( xml.sax.handler.feature_namespaces, True) parser.setFeature( xml.sax.handler.feature_external_ges, False) parser.setContentHandler(driver) parser.parse(src)
[ "def", "read_xso", "(", "src", ",", "xsomap", ")", ":", "xso_parser", "=", "xso", ".", "XSOParser", "(", ")", "for", "class_", ",", "cb", "in", "xsomap", ".", "items", "(", ")", ":", "xso_parser", ".", "add_class", "(", "class_", ",", "cb", ")", "d...
Read a single XSO from a binary file-like input `src` containing an XML document. `xsomap` must be a mapping which maps :class:`~.XSO` subclasses to callables. These will be registered at a newly created :class:`.xso.XSOParser` instance which will be used to parse the document in `src`. The `xsomap` is thus used to determine the class parsing the root element of the XML document. This can be used to support multiple versions.
[ "Read", "a", "single", "XSO", "from", "a", "binary", "file", "-", "like", "input", "src", "containing", "an", "XML", "document", "." ]
python
train
UCSBarchlab/PyRTL
pyrtl/simulation.py
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L457-L468
def inspect_mem(self, mem): """ Get the values in a map during the current simulation cycle. :param mem: the memory to inspect :return: {address: value} Note that this returns the current memory state. Modifying the dictonary will also modify the state in the simulator """ if isinstance(mem, RomBlock): raise PyrtlError("ROM blocks are not stored in the simulation object") return self.mems[self._mem_varname(mem)]
[ "def", "inspect_mem", "(", "self", ",", "mem", ")", ":", "if", "isinstance", "(", "mem", ",", "RomBlock", ")", ":", "raise", "PyrtlError", "(", "\"ROM blocks are not stored in the simulation object\"", ")", "return", "self", ".", "mems", "[", "self", ".", "_me...
Get the values in a map during the current simulation cycle. :param mem: the memory to inspect :return: {address: value} Note that this returns the current memory state. Modifying the dictonary will also modify the state in the simulator
[ "Get", "the", "values", "in", "a", "map", "during", "the", "current", "simulation", "cycle", "." ]
python
train
IBMStreams/pypi.streamsx
streamsx/rest_primitives.py
https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L2362-L2373
def submit_job(self, job_config=None): """Submit this Streams Application Bundle (sab file) to its associated instance. Args: job_config(JobConfig): a job configuration overlay Returns: Job: Resulting job instance. """ job_id = self._delegator._submit_bundle(self, job_config) return self._instance.get_job(job_id)
[ "def", "submit_job", "(", "self", ",", "job_config", "=", "None", ")", ":", "job_id", "=", "self", ".", "_delegator", ".", "_submit_bundle", "(", "self", ",", "job_config", ")", "return", "self", ".", "_instance", ".", "get_job", "(", "job_id", ")" ]
Submit this Streams Application Bundle (sab file) to its associated instance. Args: job_config(JobConfig): a job configuration overlay Returns: Job: Resulting job instance.
[ "Submit", "this", "Streams", "Application", "Bundle", "(", "sab", "file", ")", "to", "its", "associated", "instance", ".", "Args", ":", "job_config", "(", "JobConfig", ")", ":", "a", "job", "configuration", "overlay", "Returns", ":", "Job", ":", "Resulting",...
python
train
ltworf/typedload
typedload/__init__.py
https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/__init__.py#L183-L192
def attrdump(value: Any, **kwargs) -> Any: """ Quick function to do a dump that supports the "attr" module. """ from . import datadumper from .plugins import attrdump as dumpplugin dumper = datadumper.Dumper(**kwargs) dumpplugin.add2dumper(dumper) return dumper.dump(value)
[ "def", "attrdump", "(", "value", ":", "Any", ",", "*", "*", "kwargs", ")", "->", "Any", ":", "from", ".", "import", "datadumper", "from", ".", "plugins", "import", "attrdump", "as", "dumpplugin", "dumper", "=", "datadumper", ".", "Dumper", "(", "*", "*...
Quick function to do a dump that supports the "attr" module.
[ "Quick", "function", "to", "do", "a", "dump", "that", "supports", "the", "attr", "module", "." ]
python
train
scikit-tda/kepler-mapper
kmapper/drawing.py
https://github.com/scikit-tda/kepler-mapper/blob/d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d/kmapper/drawing.py#L11-L65
def draw_matplotlib(g, ax=None, fig=None): """Draw the graph using NetworkX drawing functionality. Parameters ------------ g: graph object returned by ``map`` The Mapper graph as constructed by ``KeplerMapper.map`` ax: matplotlib Axes object A matplotlib axes object to plot graph on. If none, then use ``plt.gca()`` fig: matplotlib Figure object A matplotlib Figure object to plot graph on. If none, then use ``plt.figure()`` Returns -------- nodes: nx node set object list List of nodes constructed with Networkx ``draw_networkx_nodes``. This can be used to further customize node attributes. """ import networkx as nx import matplotlib.pyplot as plt fig = fig if fig else plt.figure() ax = ax if ax else plt.gca() if not isinstance(g, nx.Graph): from .adapter import to_networkx g = to_networkx(g) # Determine a fine size for nodes bbox = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) width, height = bbox.width, bbox.height area = width * height * fig.dpi n_nodes = len(g.nodes) # size of node should be related to area and number of nodes -- heuristic node_size = np.pi * area / n_nodes node_r = np.sqrt(node_size / np.pi) node_edge = node_r / 3 pos = nx.spring_layout(g) nodes = nx.draw_networkx_nodes(g, node_size=node_size, pos=pos) edges = nx.draw_networkx_edges(g, pos=pos) nodes.set_edgecolor("w") nodes.set_linewidth(node_edge) plt.axis("square") plt.axis("off") return nodes
[ "def", "draw_matplotlib", "(", "g", ",", "ax", "=", "None", ",", "fig", "=", "None", ")", ":", "import", "networkx", "as", "nx", "import", "matplotlib", ".", "pyplot", "as", "plt", "fig", "=", "fig", "if", "fig", "else", "plt", ".", "figure", "(", ...
Draw the graph using NetworkX drawing functionality. Parameters ------------ g: graph object returned by ``map`` The Mapper graph as constructed by ``KeplerMapper.map`` ax: matplotlib Axes object A matplotlib axes object to plot graph on. If none, then use ``plt.gca()`` fig: matplotlib Figure object A matplotlib Figure object to plot graph on. If none, then use ``plt.figure()`` Returns -------- nodes: nx node set object list List of nodes constructed with Networkx ``draw_networkx_nodes``. This can be used to further customize node attributes.
[ "Draw", "the", "graph", "using", "NetworkX", "drawing", "functionality", "." ]
python
train
sassoo/goldman
goldman/queryparams/filter.py
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/queryparams/filter.py#L140-L169
def _parse_param(key): """ Parse the query param looking for filters Determine the field to filter on & the operator to be used when filtering. :param key: The query parameter to the left of the equal sign :return: tuple of string field name & string operator """ regex = re.compile(r'filter\[([A-Za-z0-9_./]+)\]') match = regex.match(key) if match: field_and_oper = match.groups()[0].split('__') if len(field_and_oper) == 1: return field_and_oper[0], 'eq' elif len(field_and_oper) == 2: return tuple(field_and_oper) else: raise InvalidQueryParams(**{ 'detail': 'The filter query param of "%s" is not ' 'supported. Multiple filter operators are ' 'not allowed in a single expression.' % key, 'links': LINK, 'parameter': PARAM, })
[ "def", "_parse_param", "(", "key", ")", ":", "regex", "=", "re", ".", "compile", "(", "r'filter\\[([A-Za-z0-9_./]+)\\]'", ")", "match", "=", "regex", ".", "match", "(", "key", ")", "if", "match", ":", "field_and_oper", "=", "match", ".", "groups", "(", "...
Parse the query param looking for filters Determine the field to filter on & the operator to be used when filtering. :param key: The query parameter to the left of the equal sign :return: tuple of string field name & string operator
[ "Parse", "the", "query", "param", "looking", "for", "filters" ]
python
train
data-8/datascience
datascience/tables.py
https://github.com/data-8/datascience/blob/4cee38266903ca169cea4a53b8cc39502d85c464/datascience/tables.py#L2872-L2879
def _vertical_x(axis, ticks=None, max_width=5): """Switch labels to vertical if they are long.""" if ticks is None: ticks = axis.get_xticks() if (np.array(ticks) == np.rint(ticks)).all(): ticks = np.rint(ticks).astype(np.int) if max([len(str(tick)) for tick in ticks]) > max_width: axis.set_xticklabels(ticks, rotation='vertical')
[ "def", "_vertical_x", "(", "axis", ",", "ticks", "=", "None", ",", "max_width", "=", "5", ")", ":", "if", "ticks", "is", "None", ":", "ticks", "=", "axis", ".", "get_xticks", "(", ")", "if", "(", "np", ".", "array", "(", "ticks", ")", "==", "np",...
Switch labels to vertical if they are long.
[ "Switch", "labels", "to", "vertical", "if", "they", "are", "long", "." ]
python
train
reingart/pyafipws
wslsp.py
https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslsp.py#L766-L779
def ConsultarCortes(self, sep="||"): "Retorna listado de cortes -carnes- (código, descripción)" ret = self.client.consultarCortes( auth={ 'token': self.Token, 'sign': self.Sign, 'cuit': self.Cuit, }, )['respuesta'] self.__analizar_errores(ret) array = ret.get('corte', []) + ret.get('cortePorcino', []) if sep is None: return dict([(it['codigo'], it['descripcion']) for it in array]) else: return [("%s %%s %s %%s %s" % (sep, sep, sep)) % (it['codigo'], it['descripcion']) for it in array]
[ "def", "ConsultarCortes", "(", "self", ",", "sep", "=", "\"||\"", ")", ":", "ret", "=", "self", ".", "client", ".", "consultarCortes", "(", "auth", "=", "{", "'token'", ":", "self", ".", "Token", ",", "'sign'", ":", "self", ".", "Sign", ",", "'cuit'"...
Retorna listado de cortes -carnes- (código, descripción)
[ "Retorna", "listado", "de", "cortes", "-", "carnes", "-", "(", "código", "descripción", ")" ]
python
train
NYUCCL/psiTurk
psiturk/experiment.py
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/experiment.py#L596-L623
def quitter(): """ Mark quitter as such. """ unique_id = request.form['uniqueId'] if unique_id[:5] == "debug": debug_mode = True else: debug_mode = False if debug_mode: resp = {"status": "didn't mark as quitter since this is debugging"} return jsonify(**resp) else: try: unique_id = request.form['uniqueId'] app.logger.info("Marking quitter %s" % unique_id) user = Participant.query.\ filter(Participant.uniqueid == unique_id).\ one() user.status = QUITEARLY db_session.add(user) db_session.commit() except exc.SQLAlchemyError: raise ExperimentError('tried_to_quit') else: resp = {"status": "marked as quitter"} return jsonify(**resp)
[ "def", "quitter", "(", ")", ":", "unique_id", "=", "request", ".", "form", "[", "'uniqueId'", "]", "if", "unique_id", "[", ":", "5", "]", "==", "\"debug\"", ":", "debug_mode", "=", "True", "else", ":", "debug_mode", "=", "False", "if", "debug_mode", ":...
Mark quitter as such.
[ "Mark", "quitter", "as", "such", "." ]
python
train
dropbox/stone
stone/frontend/parser.py
https://github.com/dropbox/stone/blob/2e95cbcd1c48e05cca68c919fd8d24adec6b0f58/stone/frontend/parser.py#L258-L272
def p_args(self, p): """args : LPAR pos_args_list COMMA kw_args RPAR | LPAR pos_args_list RPAR | LPAR kw_args RPAR | LPAR RPAR | empty""" if len(p) > 3: if p[3] == ',': p[0] = (p[2], p[4]) elif isinstance(p[2], dict): p[0] = ([], p[2]) else: p[0] = (p[2], {}) else: p[0] = ([], {})
[ "def", "p_args", "(", "self", ",", "p", ")", ":", "if", "len", "(", "p", ")", ">", "3", ":", "if", "p", "[", "3", "]", "==", "','", ":", "p", "[", "0", "]", "=", "(", "p", "[", "2", "]", ",", "p", "[", "4", "]", ")", "elif", "isinstan...
args : LPAR pos_args_list COMMA kw_args RPAR | LPAR pos_args_list RPAR | LPAR kw_args RPAR | LPAR RPAR | empty
[ "args", ":", "LPAR", "pos_args_list", "COMMA", "kw_args", "RPAR", "|", "LPAR", "pos_args_list", "RPAR", "|", "LPAR", "kw_args", "RPAR", "|", "LPAR", "RPAR", "|", "empty" ]
python
train
twilio/twilio-python
twilio/rest/api/v2010/account/recording/add_on_result/__init__.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/recording/add_on_result/__init__.py#L119-L133
def get(self, sid): """ Constructs a AddOnResultContext :param sid: The unique string that identifies the resource to fetch :returns: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultContext :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultContext """ return AddOnResultContext( self._version, account_sid=self._solution['account_sid'], reference_sid=self._solution['reference_sid'], sid=sid, )
[ "def", "get", "(", "self", ",", "sid", ")", ":", "return", "AddOnResultContext", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]", ",", "reference_sid", "=", "self", ".", "_solution", "[", "'referen...
Constructs a AddOnResultContext :param sid: The unique string that identifies the resource to fetch :returns: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultContext :rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultContext
[ "Constructs", "a", "AddOnResultContext" ]
python
train
gopalkoduri/pypeaks
pypeaks/data.py
https://github.com/gopalkoduri/pypeaks/blob/59b1e4153e80c6a4c523dda241cc1713fd66161e/pypeaks/data.py#L255-L280
def extend_peaks(self, prop_thresh=50): """Each peak in the peaks of the object is checked for its presence in other octaves. If it does not exist, it is created. prop_thresh is the cent range within which the peak in the other octave is expected to be present, i.e., only if there is a peak within this cent range in other octaves, then the peak is considered to be present in that octave. Note that this does not change the peaks of the object. It just returns the extended peaks. """ # octave propagation of the reference peaks temp_peaks = [i + 1200 for i in self.peaks["peaks"][0]] temp_peaks.extend([i - 1200 for i in self.peaks["peaks"][0]]) extended_peaks = [] extended_peaks.extend(self.peaks["peaks"][0]) for i in temp_peaks: # if a peak exists around, don't add this new one. nearest_ind = slope.find_nearest_index(self.peaks["peaks"][0], i) diff = abs(self.peaks["peaks"][0][nearest_ind] - i) diff = np.mod(diff, 1200) if diff > prop_thresh: extended_peaks.append(i) return extended_peaks
[ "def", "extend_peaks", "(", "self", ",", "prop_thresh", "=", "50", ")", ":", "# octave propagation of the reference peaks", "temp_peaks", "=", "[", "i", "+", "1200", "for", "i", "in", "self", ".", "peaks", "[", "\"peaks\"", "]", "[", "0", "]", "]", "temp_p...
Each peak in the peaks of the object is checked for its presence in other octaves. If it does not exist, it is created. prop_thresh is the cent range within which the peak in the other octave is expected to be present, i.e., only if there is a peak within this cent range in other octaves, then the peak is considered to be present in that octave. Note that this does not change the peaks of the object. It just returns the extended peaks.
[ "Each", "peak", "in", "the", "peaks", "of", "the", "object", "is", "checked", "for", "its", "presence", "in", "other", "octaves", ".", "If", "it", "does", "not", "exist", "it", "is", "created", ".", "prop_thresh", "is", "the", "cent", "range", "within", ...
python
train
sdispater/pendulum
pendulum/datetime.py
https://github.com/sdispater/pendulum/blob/94d28b0d3cb524ae02361bd1ed7ea03e2e655e4e/pendulum/datetime.py#L1283-L1294
def _last_of_quarter(self, day_of_week=None): """ Modify to the last occurrence of a given day of the week in the current quarter. If no day_of_week is provided, modify to the last day of the quarter. Use the supplied consts to indicate the desired day_of_week, ex. DateTime.MONDAY. :type day_of_week: int or None :rtype: DateTime """ return self.on(self.year, self.quarter * 3, 1).last_of("month", day_of_week)
[ "def", "_last_of_quarter", "(", "self", ",", "day_of_week", "=", "None", ")", ":", "return", "self", ".", "on", "(", "self", ".", "year", ",", "self", ".", "quarter", "*", "3", ",", "1", ")", ".", "last_of", "(", "\"month\"", ",", "day_of_week", ")" ...
Modify to the last occurrence of a given day of the week in the current quarter. If no day_of_week is provided, modify to the last day of the quarter. Use the supplied consts to indicate the desired day_of_week, ex. DateTime.MONDAY. :type day_of_week: int or None :rtype: DateTime
[ "Modify", "to", "the", "last", "occurrence", "of", "a", "given", "day", "of", "the", "week", "in", "the", "current", "quarter", ".", "If", "no", "day_of_week", "is", "provided", "modify", "to", "the", "last", "day", "of", "the", "quarter", ".", "Use", ...
python
train
core/uricore
uricore/wkz_urls.py
https://github.com/core/uricore/blob/dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a/uricore/wkz_urls.py#L313-L334
def url_encode(obj, charset='utf-8', encode_keys=False, sort=False, key=None, separator='&'): """URL encode a dict/`MultiDict`. If a value is `None` it will not appear in the result string. Per default only values are encoded into the target charset strings. If `encode_keys` is set to ``True`` unicode keys are supported too. If `sort` is set to `True` the items are sorted by `key` or the default sorting algorithm. .. versionadded:: 0.5 `sort`, `key`, and `separator` were added. :param obj: the object to encode into a query string. :param charset: the charset of the query string. :param encode_keys: set to `True` if you have unicode keys. :param sort: set to `True` if you want parameters to be sorted by `key`. :param separator: the separator to be used for the pairs. :param key: an optional function to be used for sorting. For more details check out the :func:`sorted` documentation. """ return separator.join(_url_encode_impl(obj, charset, encode_keys, sort, key))
[ "def", "url_encode", "(", "obj", ",", "charset", "=", "'utf-8'", ",", "encode_keys", "=", "False", ",", "sort", "=", "False", ",", "key", "=", "None", ",", "separator", "=", "'&'", ")", ":", "return", "separator", ".", "join", "(", "_url_encode_impl", ...
URL encode a dict/`MultiDict`. If a value is `None` it will not appear in the result string. Per default only values are encoded into the target charset strings. If `encode_keys` is set to ``True`` unicode keys are supported too. If `sort` is set to `True` the items are sorted by `key` or the default sorting algorithm. .. versionadded:: 0.5 `sort`, `key`, and `separator` were added. :param obj: the object to encode into a query string. :param charset: the charset of the query string. :param encode_keys: set to `True` if you have unicode keys. :param sort: set to `True` if you want parameters to be sorted by `key`. :param separator: the separator to be used for the pairs. :param key: an optional function to be used for sorting. For more details check out the :func:`sorted` documentation.
[ "URL", "encode", "a", "dict", "/", "MultiDict", ".", "If", "a", "value", "is", "None", "it", "will", "not", "appear", "in", "the", "result", "string", ".", "Per", "default", "only", "values", "are", "encoded", "into", "the", "target", "charset", "strings...
python
train
ilblackdragon/django-misc
misc/utils.py
https://github.com/ilblackdragon/django-misc/blob/0accd2dc97de656a1c9e275be81e817f78a2eb9d/misc/utils.py#L44-L51
def str_to_class(class_name): """ Returns a class based on class name """ mod_str, cls_str = class_name.rsplit('.', 1) mod = __import__(mod_str, globals(), locals(), ['']) cls = getattr(mod, cls_str) return cls
[ "def", "str_to_class", "(", "class_name", ")", ":", "mod_str", ",", "cls_str", "=", "class_name", ".", "rsplit", "(", "'.'", ",", "1", ")", "mod", "=", "__import__", "(", "mod_str", ",", "globals", "(", ")", ",", "locals", "(", ")", ",", "[", "''", ...
Returns a class based on class name
[ "Returns", "a", "class", "based", "on", "class", "name" ]
python
train
oceanprotocol/squid-py
squid_py/keeper/token.py
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/token.py#L31-L50
def token_approve(self, spender_address, price, from_account): """ Approve the passed address to spend the specified amount of tokens. :param spender_address: Account address, str :param price: Asset price, int :param from_account: Account address, str :return: bool """ if not Web3Provider.get_web3().isChecksumAddress(spender_address): spender_address = Web3Provider.get_web3().toChecksumAddress(spender_address) tx_hash = self.send_transaction( 'approve', (spender_address, price), transact={'from': from_account.address, 'passphrase': from_account.password} ) return self.get_tx_receipt(tx_hash).status == 1
[ "def", "token_approve", "(", "self", ",", "spender_address", ",", "price", ",", "from_account", ")", ":", "if", "not", "Web3Provider", ".", "get_web3", "(", ")", ".", "isChecksumAddress", "(", "spender_address", ")", ":", "spender_address", "=", "Web3Provider", ...
Approve the passed address to spend the specified amount of tokens. :param spender_address: Account address, str :param price: Asset price, int :param from_account: Account address, str :return: bool
[ "Approve", "the", "passed", "address", "to", "spend", "the", "specified", "amount", "of", "tokens", "." ]
python
train
pycontribs/pyrax
pyrax/object_storage.py
https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/object_storage.py#L1217-L1223
def get_container_streaming_uri(self, container): """ Returns the URI for streaming content, or None if CDN is not enabled. """ resp, resp_body = self.api.cdn_request("/%s" % utils.get_name(container), method="HEAD") return resp.headers.get("x-cdn-streaming-uri")
[ "def", "get_container_streaming_uri", "(", "self", ",", "container", ")", ":", "resp", ",", "resp_body", "=", "self", ".", "api", ".", "cdn_request", "(", "\"/%s\"", "%", "utils", ".", "get_name", "(", "container", ")", ",", "method", "=", "\"HEAD\"", ")",...
Returns the URI for streaming content, or None if CDN is not enabled.
[ "Returns", "the", "URI", "for", "streaming", "content", "or", "None", "if", "CDN", "is", "not", "enabled", "." ]
python
train
Julius2342/pyvlx
pyvlx/alias_array.py
https://github.com/Julius2342/pyvlx/blob/ee78e1324bcb1be5b8d1a9d05ab5496b72eae848/pyvlx/alias_array.py#L26-L36
def parse_raw(self, raw): """Parse alias array from raw bytes.""" if not isinstance(raw, bytes): raise PyVLXException("AliasArray::invalid_type_if_raw", type_raw=type(raw)) if len(raw) != 21: raise PyVLXException("AliasArray::invalid_size", size=len(raw)) nbr_of_alias = raw[0] if nbr_of_alias > 5: raise PyVLXException("AliasArray::invalid_nbr_of_alias", nbr_of_alias=nbr_of_alias) for i in range(0, nbr_of_alias): self.alias_array_.append((raw[i*4+1:i*4+3], raw[i*4+3:i*4+5]))
[ "def", "parse_raw", "(", "self", ",", "raw", ")", ":", "if", "not", "isinstance", "(", "raw", ",", "bytes", ")", ":", "raise", "PyVLXException", "(", "\"AliasArray::invalid_type_if_raw\"", ",", "type_raw", "=", "type", "(", "raw", ")", ")", "if", "len", ...
Parse alias array from raw bytes.
[ "Parse", "alias", "array", "from", "raw", "bytes", "." ]
python
train
obulpathi/cdn-fastly-python
fastly/__init__.py
https://github.com/obulpathi/cdn-fastly-python/blob/db2564b047e8af4bce72c3b88d6c27d3d0291425/fastly/__init__.py#L894-L897
def get_generated_vcl(self, service_id, version_number): """Display the generated VCL for a particular service and version.""" content = self._fetch("/service/%s/version/%d/generated_vcl" % (service_id, version_number)) return FastlyVCL(self, content)
[ "def", "get_generated_vcl", "(", "self", ",", "service_id", ",", "version_number", ")", ":", "content", "=", "self", ".", "_fetch", "(", "\"/service/%s/version/%d/generated_vcl\"", "%", "(", "service_id", ",", "version_number", ")", ")", "return", "FastlyVCL", "("...
Display the generated VCL for a particular service and version.
[ "Display", "the", "generated", "VCL", "for", "a", "particular", "service", "and", "version", "." ]
python
train
tanghaibao/jcvi
jcvi/algorithms/lpsolve.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/algorithms/lpsolve.py#L321-L414
def tsp_gurobi(edges): """ Modeled using GUROBI python example. """ from gurobipy import Model, GRB, quicksum edges = populate_edge_weights(edges) incoming, outgoing, nodes = node_to_edge(edges) idx = dict((n, i) for i, n in enumerate(nodes)) nedges = len(edges) n = len(nodes) m = Model() def step(x): return "u_{0}".format(x) # Create variables vars = {} for i, (a, b, w) in enumerate(edges): vars[i] = m.addVar(obj=w, vtype=GRB.BINARY, name=str(i)) for u in nodes[1:]: u = step(u) vars[u] = m.addVar(obj=0, vtype=GRB.INTEGER, name=u) m.update() # Bounds for step variables for u in nodes[1:]: u = step(u) vars[u].lb = 1 vars[u].ub = n - 1 # Add degree constraint for v in nodes: incoming_edges = incoming[v] outgoing_edges = outgoing[v] m.addConstr(quicksum(vars[x] for x in incoming_edges) == 1) m.addConstr(quicksum(vars[x] for x in outgoing_edges) == 1) # Subtour elimination edge_store = dict(((idx[a], idx[b]), i) for i, (a, b, w) in enumerate(edges)) # Given a list of edges, finds the shortest subtour def subtour(s_edges): visited = [False] * n cycles = [] lengths = [] selected = [[] for i in range(n)] for x, y in s_edges: selected[x].append(y) while True: current = visited.index(False) thiscycle = [current] while True: visited[current] = True neighbors = [x for x in selected[current] if not visited[x]] if len(neighbors) == 0: break current = neighbors[0] thiscycle.append(current) cycles.append(thiscycle) lengths.append(len(thiscycle)) if sum(lengths) == n: break return cycles[lengths.index(min(lengths))] def subtourelim(model, where): if where != GRB.callback.MIPSOL: return selected = [] # make a list of edges selected in the solution sol = model.cbGetSolution([model._vars[i] for i in range(nedges)]) selected = [edges[i] for i, x in enumerate(sol) if x > .5] selected = [(idx[a], idx[b]) for a, b, w in selected] # find the shortest cycle in the selected edge list tour = subtour(selected) if len(tour) == n: return # add a subtour elimination constraint c = tour incident = [edge_store[a, b] for a, b in pairwise(c + [c[0]])] model.cbLazy(quicksum(model._vars[x] for x in incident) <= len(tour) - 1) m.update() m._vars = vars m.params.LazyConstraints = 1 m.optimize(subtourelim) selected = [v.varName for v in m.getVars() if v.x > .5] selected = [int(x) for x in selected if x[:2] != "u_"] results = sorted(x for i, x in enumerate(edges) if i in selected) \ if selected else None return results
[ "def", "tsp_gurobi", "(", "edges", ")", ":", "from", "gurobipy", "import", "Model", ",", "GRB", ",", "quicksum", "edges", "=", "populate_edge_weights", "(", "edges", ")", "incoming", ",", "outgoing", ",", "nodes", "=", "node_to_edge", "(", "edges", ")", "i...
Modeled using GUROBI python example.
[ "Modeled", "using", "GUROBI", "python", "example", "." ]
python
train
SmartDeveloperHub/agora-client
agora/client/execution.py
https://github.com/SmartDeveloperHub/agora-client/blob/53e126d12c2803ee71cf0822aaa0b0cf08cc3df4/agora/client/execution.py#L166-L177
def get_fragment(self, **kwargs): """ Return a complete fragment. :param gp: :return: """ gen, namespaces, plan = self.get_fragment_generator(**kwargs) graph = ConjunctiveGraph() [graph.bind(prefix, u) for (prefix, u) in namespaces] [graph.add((s, p, o)) for (_, s, p, o) in gen] return graph
[ "def", "get_fragment", "(", "self", ",", "*", "*", "kwargs", ")", ":", "gen", ",", "namespaces", ",", "plan", "=", "self", ".", "get_fragment_generator", "(", "*", "*", "kwargs", ")", "graph", "=", "ConjunctiveGraph", "(", ")", "[", "graph", ".", "bind...
Return a complete fragment. :param gp: :return:
[ "Return", "a", "complete", "fragment", ".", ":", "param", "gp", ":", ":", "return", ":" ]
python
train
hyperledger-archives/indy-anoncreds
anoncreds/protocol/verifier.py
https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/verifier.py#L27-L59
async def verify(self, proofRequest: ProofRequest, proof: FullProof): """ Verifies a proof from the prover. :param proofRequest: description of a proof to be presented (revealed attributes, predicates, timestamps for non-revocation) :param proof: a proof :return: True if verified successfully and false otherwise. """ if proofRequest.verifiableAttributes.keys() != proof.requestedProof.revealed_attrs.keys(): raise ValueError('Received attributes ={} do not correspond to requested={}'.format( proof.requestedProof.revealed_attrs.keys(), proofRequest.verifiableAttributes.keys())) if proofRequest.predicates.keys() != proof.requestedProof.predicates.keys(): raise ValueError('Received predicates ={} do not correspond to requested={}'.format( proof.requestedProof.predicates.keys(), proofRequest.predicates.keys())) TauList = [] for (uuid, proofItem) in proof.proofs.items(): if proofItem.proof.nonRevocProof: TauList += await self._nonRevocVerifier.verifyNonRevocation( proofRequest, proofItem.schema_seq_no, proof.aggregatedProof.cHash, proofItem.proof.nonRevocProof) if proofItem.proof.primaryProof: TauList += await self._primaryVerifier.verify(proofItem.schema_seq_no, proof.aggregatedProof.cHash, proofItem.proof.primaryProof) CHver = self._get_hash(proof.aggregatedProof.CList, self._prepare_collection(TauList), cmod.integer(proofRequest.nonce)) return CHver == proof.aggregatedProof.cHash
[ "async", "def", "verify", "(", "self", ",", "proofRequest", ":", "ProofRequest", ",", "proof", ":", "FullProof", ")", ":", "if", "proofRequest", ".", "verifiableAttributes", ".", "keys", "(", ")", "!=", "proof", ".", "requestedProof", ".", "revealed_attrs", ...
Verifies a proof from the prover. :param proofRequest: description of a proof to be presented (revealed attributes, predicates, timestamps for non-revocation) :param proof: a proof :return: True if verified successfully and false otherwise.
[ "Verifies", "a", "proof", "from", "the", "prover", "." ]
python
train
tylertreat/BigQuery-Python
bigquery/client.py
https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L510-L526
def check_dataset(self, dataset_id, project_id=None): """Check to see if a dataset exists. Parameters ---------- dataset_id : str Dataset unique id project_id: str, optional The project the dataset is in Returns ------- bool True if dataset at `dataset_id` exists, else Fasle """ dataset = self.get_dataset(dataset_id, project_id) return bool(dataset)
[ "def", "check_dataset", "(", "self", ",", "dataset_id", ",", "project_id", "=", "None", ")", ":", "dataset", "=", "self", ".", "get_dataset", "(", "dataset_id", ",", "project_id", ")", "return", "bool", "(", "dataset", ")" ]
Check to see if a dataset exists. Parameters ---------- dataset_id : str Dataset unique id project_id: str, optional The project the dataset is in Returns ------- bool True if dataset at `dataset_id` exists, else Fasle
[ "Check", "to", "see", "if", "a", "dataset", "exists", "." ]
python
train
carsongee/flask-htpasswd
flask_htpasswd.py
https://github.com/carsongee/flask-htpasswd/blob/db6fe596dd167f33aeb3d77e975c861d0534cecf/flask_htpasswd.py#L163-L192
def authenticate(self): """Authenticate user by any means and return either true or false. Args: Returns: tuple (is_valid, username): True is valid user, False if not """ basic_auth = request.authorization is_valid = False user = None if basic_auth: is_valid, user = self.check_basic_auth( basic_auth.username, basic_auth.password ) else: # Try token auth token = request.headers.get('Authorization', None) param_token = request.args.get('access_token') if token or param_token: if token: # slice the 'token ' piece of the header (following # github style): token = token[6:] else: # Grab it from query dict instead token = param_token log.debug('Received token: %s', token) is_valid, user = self.check_token_auth(token) return (is_valid, user)
[ "def", "authenticate", "(", "self", ")", ":", "basic_auth", "=", "request", ".", "authorization", "is_valid", "=", "False", "user", "=", "None", "if", "basic_auth", ":", "is_valid", ",", "user", "=", "self", ".", "check_basic_auth", "(", "basic_auth", ".", ...
Authenticate user by any means and return either true or false. Args: Returns: tuple (is_valid, username): True is valid user, False if not
[ "Authenticate", "user", "by", "any", "means", "and", "return", "either", "true", "or", "false", "." ]
python
train
gwastro/pycbc
pycbc/io/record.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/io/record.py#L296-L301
def _ensure_array_list(arrays): """Ensures that every element in a list is an instance of a numpy array.""" # Note: the isinstance test is needed below so that instances of FieldArray # are not converted to numpy arrays return [numpy.array(arr, ndmin=1) if not isinstance(arr, numpy.ndarray) else arr for arr in arrays]
[ "def", "_ensure_array_list", "(", "arrays", ")", ":", "# Note: the isinstance test is needed below so that instances of FieldArray", "# are not converted to numpy arrays", "return", "[", "numpy", ".", "array", "(", "arr", ",", "ndmin", "=", "1", ")", "if", "not", "isinsta...
Ensures that every element in a list is an instance of a numpy array.
[ "Ensures", "that", "every", "element", "in", "a", "list", "is", "an", "instance", "of", "a", "numpy", "array", "." ]
python
train
h2oai/h2o-3
h2o-py/h2o/h2o.py
https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-py/h2o/h2o.py#L978-L1006
def download_pojo(model, path="", get_jar=True, jar_name=""): """ Download the POJO for this model to the directory specified by path; if path is "", then dump to screen. :param model: the model whose scoring POJO should be retrieved. :param path: an absolute path to the directory where POJO should be saved. :param get_jar: retrieve the h2o-genmodel.jar also (will be saved to the same folder ``path``). :param jar_name: Custom name of genmodel jar. :returns: location of the downloaded POJO file. """ assert_is_type(model, ModelBase) assert_is_type(path, str) assert_is_type(get_jar, bool) if not model.have_pojo: raise H2OValueError("Export to POJO not supported") if path == "": java_code = api("GET /3/Models.java/%s" % model.model_id) print(java_code) return None else: filename = api("GET /3/Models.java/%s" % model.model_id, save_to=path) if get_jar: if jar_name == "": api("GET /3/h2o-genmodel.jar", save_to=os.path.join(path, "h2o-genmodel.jar")) else: api("GET /3/h2o-genmodel.jar", save_to=os.path.join(path, jar_name)) return filename
[ "def", "download_pojo", "(", "model", ",", "path", "=", "\"\"", ",", "get_jar", "=", "True", ",", "jar_name", "=", "\"\"", ")", ":", "assert_is_type", "(", "model", ",", "ModelBase", ")", "assert_is_type", "(", "path", ",", "str", ")", "assert_is_type", ...
Download the POJO for this model to the directory specified by path; if path is "", then dump to screen. :param model: the model whose scoring POJO should be retrieved. :param path: an absolute path to the directory where POJO should be saved. :param get_jar: retrieve the h2o-genmodel.jar also (will be saved to the same folder ``path``). :param jar_name: Custom name of genmodel jar. :returns: location of the downloaded POJO file.
[ "Download", "the", "POJO", "for", "this", "model", "to", "the", "directory", "specified", "by", "path", ";", "if", "path", "is", "then", "dump", "to", "screen", "." ]
python
test
rapidpro/expressions
python/temba_expressions/functions/excel.py
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L96-L106
def right(ctx, text, num_chars): """ Returns the last characters in a text string """ num_chars = conversions.to_integer(num_chars, ctx) if num_chars < 0: raise ValueError("Number of chars can't be negative") elif num_chars == 0: return '' else: return conversions.to_string(text, ctx)[-num_chars:]
[ "def", "right", "(", "ctx", ",", "text", ",", "num_chars", ")", ":", "num_chars", "=", "conversions", ".", "to_integer", "(", "num_chars", ",", "ctx", ")", "if", "num_chars", "<", "0", ":", "raise", "ValueError", "(", "\"Number of chars can't be negative\"", ...
Returns the last characters in a text string
[ "Returns", "the", "last", "characters", "in", "a", "text", "string" ]
python
train
walidsa3d/sabertooth
sabertooth/providers/subscene.py
https://github.com/walidsa3d/sabertooth/blob/329fbc2aaa385714e4373150577e191d0a17da39/sabertooth/providers/subscene.py#L49-L59
def download(self, sub_url): """download and unzip subtitle archive to a temp location""" response = requests.get(sub_url, headers=self.headers).text soup = BS(response, 'lxml') downlink = self.base_url+soup.select('.download a')[0]['href'] data = requests.get(downlink, headers=self.headers) z = zipfile.ZipFile(cStringIO.StringIO(data.content)) srt_files = [f.filename for f in z.filelist if f.filename.rsplit('.')[-1].lower() in ['srt', 'ass']] z.extract(srt_files[0], '/tmp/') return srt_files[0]
[ "def", "download", "(", "self", ",", "sub_url", ")", ":", "response", "=", "requests", ".", "get", "(", "sub_url", ",", "headers", "=", "self", ".", "headers", ")", ".", "text", "soup", "=", "BS", "(", "response", ",", "'lxml'", ")", "downlink", "=",...
download and unzip subtitle archive to a temp location
[ "download", "and", "unzip", "subtitle", "archive", "to", "a", "temp", "location" ]
python
train
reflexsc/reflex
dev/action.py
https://github.com/reflexsc/reflex/blob/cee6b0ccfef395ca5e157d644a2e3252cea9fe62/dev/action.py#L124-L149
def run(self, name, replace=None, actions=None): """ Do an action. If `replace` is provided as a dictionary, do a search/replace using %{} templates on content of action (unique to action type) """ self.actions = actions # incase we use group action = actions.get(name) if not action: self.die("Action not found: {}", name) action['name'] = name action_type = action.get('type', "none") try: func = getattr(self, '_run__' + action_type) except AttributeError: self.die("Unsupported action type " + action_type) try: return func(action, replace) except Exception as err: # pylint: disable=broad-except if self._debug: self.debug(traceback.format_exc()) self.die("Error running action name={} type={} error={}", name, action_type, err)
[ "def", "run", "(", "self", ",", "name", ",", "replace", "=", "None", ",", "actions", "=", "None", ")", ":", "self", ".", "actions", "=", "actions", "# incase we use group", "action", "=", "actions", ".", "get", "(", "name", ")", "if", "not", "action", ...
Do an action. If `replace` is provided as a dictionary, do a search/replace using %{} templates on content of action (unique to action type)
[ "Do", "an", "action", "." ]
python
train
raiden-network/raiden
raiden/transfer/mediated_transfer/mediator.py
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/mediator.py#L612-L668
def set_onchain_secret( state: MediatorTransferState, channelidentifiers_to_channels: ChannelMap, secret: Secret, secrethash: SecretHash, block_number: BlockNumber, ) -> List[Event]: """ Set the secret to all mediated transfers. The secret should have been learned from the secret registry. """ state.secret = secret for pair in state.transfers_pair: payer_channel = channelidentifiers_to_channels.get( pair.payer_transfer.balance_proof.channel_identifier, ) if payer_channel: channel.register_onchain_secret( payer_channel, secret, secrethash, block_number, ) payee_channel = channelidentifiers_to_channels.get( pair.payee_transfer.balance_proof.channel_identifier, ) if payee_channel: channel.register_onchain_secret( channel_state=payee_channel, secret=secret, secrethash=secrethash, secret_reveal_block_number=block_number, ) # Like the off-chain secret reveal, the secret should never be revealed # on-chain if there is a waiting transfer. if state.waiting_transfer: payer_channel = channelidentifiers_to_channels.get( state.waiting_transfer.transfer.balance_proof.channel_identifier, ) if payer_channel: channel.register_onchain_secret( channel_state=payer_channel, secret=secret, secrethash=secrethash, secret_reveal_block_number=block_number, ) unexpected_reveal = EventUnexpectedSecretReveal( secrethash=secrethash, reason='The mediator has a waiting transfer.', ) return [unexpected_reveal] return list()
[ "def", "set_onchain_secret", "(", "state", ":", "MediatorTransferState", ",", "channelidentifiers_to_channels", ":", "ChannelMap", ",", "secret", ":", "Secret", ",", "secrethash", ":", "SecretHash", ",", "block_number", ":", "BlockNumber", ",", ")", "->", "List", ...
Set the secret to all mediated transfers. The secret should have been learned from the secret registry.
[ "Set", "the", "secret", "to", "all", "mediated", "transfers", "." ]
python
train
StackStorm/pybind
pybind/slxos/v17s_1_02/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/__init__.py#L2942-L2965
def _set_acl_state(self, v, load=False): """ Setter method for acl_state, mapped from YANG variable /acl_state (container) If this variable is read-only (config: false) in the source YANG file, then _set_acl_state is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_acl_state() directly. YANG Description: Vxlan ACL information """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=acl_state.acl_state, is_container='container', presence=False, yang_name="acl-state", rest_name="acl-state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'callpoint': u'ssm-acl', u'cli-suppress-show-path': None}}, namespace='urn:brocade.com:mgmt:brocade-ssm-operational', defining_module='brocade-ssm-operational', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """acl_state must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=acl_state.acl_state, is_container='container', presence=False, yang_name="acl-state", rest_name="acl-state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'callpoint': u'ssm-acl', u'cli-suppress-show-path': None}}, namespace='urn:brocade.com:mgmt:brocade-ssm-operational', defining_module='brocade-ssm-operational', yang_type='container', is_config=True)""", }) self.__acl_state = t if hasattr(self, '_set'): self._set()
[ "def", "_set_acl_state", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base...
Setter method for acl_state, mapped from YANG variable /acl_state (container) If this variable is read-only (config: false) in the source YANG file, then _set_acl_state is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_acl_state() directly. YANG Description: Vxlan ACL information
[ "Setter", "method", "for", "acl_state", "mapped", "from", "YANG", "variable", "/", "acl_state", "(", "container", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "false", ")", "in", "the", "source", "YANG", "file", "then", "...
python
train
twisted/txacme
src/txacme/util.py
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/util.py#L105-L133
def csr_for_names(names, key): """ Generate a certificate signing request for the given names and private key. .. seealso:: `acme.client.Client.request_issuance` .. seealso:: `generate_private_key` :param ``List[str]``: One or more names (subjectAltName) for which to request a certificate. :param key: A Cryptography private key object. :rtype: `cryptography.x509.CertificateSigningRequest` :return: The certificate request message. """ if len(names) == 0: raise ValueError('Must have at least one name') if len(names[0]) > 64: common_name = u'san.too.long.invalid' else: common_name = names[0] return ( x509.CertificateSigningRequestBuilder() .subject_name(x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, common_name)])) .add_extension( x509.SubjectAlternativeName(list(map(x509.DNSName, names))), critical=False) .sign(key, hashes.SHA256(), default_backend()))
[ "def", "csr_for_names", "(", "names", ",", "key", ")", ":", "if", "len", "(", "names", ")", "==", "0", ":", "raise", "ValueError", "(", "'Must have at least one name'", ")", "if", "len", "(", "names", "[", "0", "]", ")", ">", "64", ":", "common_name", ...
Generate a certificate signing request for the given names and private key. .. seealso:: `acme.client.Client.request_issuance` .. seealso:: `generate_private_key` :param ``List[str]``: One or more names (subjectAltName) for which to request a certificate. :param key: A Cryptography private key object. :rtype: `cryptography.x509.CertificateSigningRequest` :return: The certificate request message.
[ "Generate", "a", "certificate", "signing", "request", "for", "the", "given", "names", "and", "private", "key", "." ]
python
train
tensorflow/datasets
tensorflow_datasets/image/corruptions.py
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/corruptions.py#L104-L159
def plasma_fractal(mapsize=512, wibbledecay=3): """Generate a heightmap using diamond-square algorithm. Modification of the algorithm in https://github.com/FLHerne/mapgen/blob/master/diamondsquare.py Args: mapsize: side length of the heightmap, must be a power of two. wibbledecay: integer, decay factor. Returns: numpy 2d array, side length 'mapsize', of floats in [0,255]. """ if mapsize & (mapsize - 1) != 0: raise ValueError('mapsize must be a power of two.') maparray = np.empty((mapsize, mapsize), dtype=np.float_) maparray[0, 0] = 0 stepsize = mapsize wibble = 100 def wibbledmean(array): return array / 4 + wibble * np.random.uniform(-wibble, wibble, array.shape) def fillsquares(): """For each square, calculate middle value as mean of points + wibble.""" cornerref = maparray[0:mapsize:stepsize, 0:mapsize:stepsize] squareaccum = cornerref + np.roll(cornerref, shift=-1, axis=0) squareaccum += np.roll(squareaccum, shift=-1, axis=1) maparray[stepsize // 2:mapsize:stepsize, stepsize // 2:mapsize:stepsize] = wibbledmean(squareaccum) def filldiamonds(): """For each diamond, calculate middle value as meanof points + wibble.""" mapsize = maparray.shape[0] drgrid = maparray[stepsize // 2:mapsize:stepsize, stepsize // 2:mapsize:stepsize] ulgrid = maparray[0:mapsize:stepsize, 0:mapsize:stepsize] ldrsum = drgrid + np.roll(drgrid, 1, axis=0) lulsum = ulgrid + np.roll(ulgrid, -1, axis=1) ltsum = ldrsum + lulsum maparray[0:mapsize:stepsize, stepsize // 2:mapsize:stepsize] = wibbledmean(ltsum) tdrsum = drgrid + np.roll(drgrid, 1, axis=1) tulsum = ulgrid + np.roll(ulgrid, -1, axis=0) ttsum = tdrsum + tulsum maparray[stepsize // 2:mapsize:stepsize, 0:mapsize:stepsize] = wibbledmean(ttsum) while stepsize >= 2: fillsquares() filldiamonds() stepsize //= 2 wibble /= wibbledecay maparray -= maparray.min() return maparray / maparray.max()
[ "def", "plasma_fractal", "(", "mapsize", "=", "512", ",", "wibbledecay", "=", "3", ")", ":", "if", "mapsize", "&", "(", "mapsize", "-", "1", ")", "!=", "0", ":", "raise", "ValueError", "(", "'mapsize must be a power of two.'", ")", "maparray", "=", "np", ...
Generate a heightmap using diamond-square algorithm. Modification of the algorithm in https://github.com/FLHerne/mapgen/blob/master/diamondsquare.py Args: mapsize: side length of the heightmap, must be a power of two. wibbledecay: integer, decay factor. Returns: numpy 2d array, side length 'mapsize', of floats in [0,255].
[ "Generate", "a", "heightmap", "using", "diamond", "-", "square", "algorithm", "." ]
python
train
mabuchilab/QNET
src/qnet/algebra/toolbox/equation.py
https://github.com/mabuchilab/QNET/blob/cc20d26dad78691d34c67173e5cd67dcac94208a/src/qnet/algebra/toolbox/equation.py#L238-L243
def copy(self): """Return a copy of the equation""" return Eq( self._lhs, self._rhs, tag=self._tag, _prev_lhs=self._prev_lhs, _prev_rhs=self._prev_rhs, _prev_tags=self._prev_tags)
[ "def", "copy", "(", "self", ")", ":", "return", "Eq", "(", "self", ".", "_lhs", ",", "self", ".", "_rhs", ",", "tag", "=", "self", ".", "_tag", ",", "_prev_lhs", "=", "self", ".", "_prev_lhs", ",", "_prev_rhs", "=", "self", ".", "_prev_rhs", ",", ...
Return a copy of the equation
[ "Return", "a", "copy", "of", "the", "equation" ]
python
train
xolox/python-qpass
qpass/__init__.py
https://github.com/xolox/python-qpass/blob/43ce447b0904ff42a54b8f1dd4d2479f950f258f/qpass/__init__.py#L244-L272
def context(self): """ An execution context created using :mod:`executor.contexts`. The value of :attr:`context` defaults to a :class:`~executor.contexts.LocalContext` object with the following characteristics: - The working directory of the execution context is set to the value of :attr:`directory`. - The environment variable given by :data:`DIRECTORY_VARIABLE` is set to the value of :attr:`directory`. :raises: :exc:`.MissingPasswordStoreError` when :attr:`directory` doesn't exist. """ # Make sure the directory exists. self.ensure_directory_exists() # Prepare the environment variables. environment = {DIRECTORY_VARIABLE: self.directory} try: # Try to enable the GPG agent in headless sessions. environment.update(get_gpg_variables()) except Exception: # If we failed then let's at least make sure that the # $GPG_TTY environment variable is set correctly. environment.update(GPG_TTY=execute("tty", capture=True, check=False, tty=True, silent=True)) return LocalContext(directory=self.directory, environment=environment)
[ "def", "context", "(", "self", ")", ":", "# Make sure the directory exists.", "self", ".", "ensure_directory_exists", "(", ")", "# Prepare the environment variables.", "environment", "=", "{", "DIRECTORY_VARIABLE", ":", "self", ".", "directory", "}", "try", ":", "# Tr...
An execution context created using :mod:`executor.contexts`. The value of :attr:`context` defaults to a :class:`~executor.contexts.LocalContext` object with the following characteristics: - The working directory of the execution context is set to the value of :attr:`directory`. - The environment variable given by :data:`DIRECTORY_VARIABLE` is set to the value of :attr:`directory`. :raises: :exc:`.MissingPasswordStoreError` when :attr:`directory` doesn't exist.
[ "An", "execution", "context", "created", "using", ":", "mod", ":", "executor", ".", "contexts", "." ]
python
train
devision-io/metasdk
metasdk/services/ApiProxyService.py
https://github.com/devision-io/metasdk/blob/1a1af5ceeb8ade843fd656c9c27c8b9ff789fc68/metasdk/services/ApiProxyService.py#L117-L149
def check_err(resp, analyze_json_error_param=False, retry_request_substr_variants=None): """ :type retry_request_substr_variants: list Список вхождений строк, при налиции которых в ошибке апи будет произведен повторный запрос к апи """ if retry_request_substr_variants is None: retry_request_substr_variants = [] # РКН блокировки вызывают ошибку SSL retry_request_substr_variants.append("TLSV1_ALERT_ACCESS_DENIED") if resp.status_code in [502, 503, 504]: raise RetryHttpRequestError(resp.text) if resp.status_code >= 400: rtext = resp.text for v_ in retry_request_substr_variants: if v_ in rtext: raise RetryHttpRequestError(rtext) raise UnexpectedError("HTTP request failed: {} {}".format(resp.status_code, rtext)) if analyze_json_error_param: data_ = resp.json() if 'error' in data_ and data_.get('error'): error = data_.get('error') full_err_ = json.dumps(error) if error.get("type") == "RateLimitError": raise RateLimitError(error.get("message"), waiting_time=error.get("waiting_time")) for v_ in retry_request_substr_variants: if v_ in full_err_: raise RetryHttpRequestError(full_err_) raise ApiProxyError(full_err_) return resp
[ "def", "check_err", "(", "resp", ",", "analyze_json_error_param", "=", "False", ",", "retry_request_substr_variants", "=", "None", ")", ":", "if", "retry_request_substr_variants", "is", "None", ":", "retry_request_substr_variants", "=", "[", "]", "# РКН блокировки вызыв...
:type retry_request_substr_variants: list Список вхождений строк, при налиции которых в ошибке апи будет произведен повторный запрос к апи
[ ":", "type", "retry_request_substr_variants", ":", "list", "Список", "вхождений", "строк", "при", "налиции", "которых", "в", "ошибке", "апи", "будет", "произведен", "повторный", "запрос", "к", "апи" ]
python
train
OnroerendErfgoed/skosprovider_getty
skosprovider_getty/utils.py
https://github.com/OnroerendErfgoed/skosprovider_getty/blob/5aa0b5a8525d607e07b631499ff31bac7a0348b7/skosprovider_getty/utils.py#L29-L55
def conceptscheme_from_uri(conceptscheme_uri, **kwargs): ''' Read a SKOS Conceptscheme from a :term:`URI` :param string conceptscheme_uri: URI of the conceptscheme. :rtype: skosprovider.skos.ConceptScheme ''' # get the conceptscheme # ensure it only ends in one slash conceptscheme_uri = conceptscheme_uri.strip('/') + '/' s = kwargs.get('session', requests.Session()) graph = uri_to_graph('%s.rdf' % (conceptscheme_uri), session=s) notes = [] labels = [] if graph is not False: for s, p, o in graph.triples((URIRef(conceptscheme_uri), RDFS.label, None)): label = Label(o.toPython(), "prefLabel", 'en') labels.append(label) conceptscheme = ConceptScheme( conceptscheme_uri, labels=labels, notes=notes ) return conceptscheme
[ "def", "conceptscheme_from_uri", "(", "conceptscheme_uri", ",", "*", "*", "kwargs", ")", ":", "# get the conceptscheme", "# ensure it only ends in one slash", "conceptscheme_uri", "=", "conceptscheme_uri", ".", "strip", "(", "'/'", ")", "+", "'/'", "s", "=", "kwargs",...
Read a SKOS Conceptscheme from a :term:`URI` :param string conceptscheme_uri: URI of the conceptscheme. :rtype: skosprovider.skos.ConceptScheme
[ "Read", "a", "SKOS", "Conceptscheme", "from", "a", ":", "term", ":", "URI" ]
python
train
gabstopper/smc-python
smc/api/web.py
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/api/web.py#L33-L147
def send_request(user_session, method, request): """ Send request to SMC :param Session user_session: session object :param str method: method for request :param SMCRequest request: request object :raises SMCOperationFailure: failure with reason :rtype: SMCResult """ if user_session.session: session = user_session.session # requests session try: method = method.upper() if method else '' if method == GET: if request.filename: # File download request return file_download(user_session, request) response = session.get( request.href, params=request.params, headers=request.headers, timeout=user_session.timeout) response.encoding = 'utf-8' counters.update(read=1) if logger.isEnabledFor(logging.DEBUG): debug(response) if response.status_code not in (200, 204, 304): raise SMCOperationFailure(response) elif method == POST: if request.files: # File upload request return file_upload(user_session, method, request) response = session.post( request.href, data=json.dumps(request.json, cls=CacheEncoder), headers=request.headers, params=request.params) response.encoding = 'utf-8' counters.update(create=1) if logger.isEnabledFor(logging.DEBUG): debug(response) if response.status_code not in (200, 201, 202): # 202 is asynchronous response with follower link raise SMCOperationFailure(response) elif method == PUT: if request.files: # File upload request return file_upload(user_session, method, request) # Etag should be set in request object request.headers.update(Etag=request.etag) response = session.put( request.href, data=json.dumps(request.json, cls=CacheEncoder), params=request.params, headers=request.headers) counters.update(update=1) if logger.isEnabledFor(logging.DEBUG): debug(response) if response.status_code != 200: raise SMCOperationFailure(response) elif method == DELETE: response = session.delete( request.href, headers=request.headers) counters.update(delete=1) # Conflict (409) if ETag is not current if response.status_code in (409,): req = session.get(request.href) etag = req.headers.get('ETag') response = session.delete( request.href, headers={'if-match': etag}) response.encoding = 'utf-8' if logger.isEnabledFor(logging.DEBUG): debug(response) if response.status_code not in (200, 204): raise SMCOperationFailure(response) else: # Unsupported method return SMCResult(msg='Unsupported method: %s' % method, user_session=user_session) except SMCOperationFailure as error: if error.code in (401,): user_session.refresh() return send_request(user_session, method, request) raise error except requests.exceptions.RequestException as e: raise SMCConnectionError('Connection problem to SMC, ensure the API ' 'service is running and host is correct: %s, exiting.' % e) else: return SMCResult(response, user_session=user_session) else: raise SMCConnectionError('No session found. Please login to continue')
[ "def", "send_request", "(", "user_session", ",", "method", ",", "request", ")", ":", "if", "user_session", ".", "session", ":", "session", "=", "user_session", ".", "session", "# requests session", "try", ":", "method", "=", "method", ".", "upper", "(", ")",...
Send request to SMC :param Session user_session: session object :param str method: method for request :param SMCRequest request: request object :raises SMCOperationFailure: failure with reason :rtype: SMCResult
[ "Send", "request", "to", "SMC", ":", "param", "Session", "user_session", ":", "session", "object", ":", "param", "str", "method", ":", "method", "for", "request", ":", "param", "SMCRequest", "request", ":", "request", "object", ":", "raises", "SMCOperationFail...
python
train
spyder-ide/spyder
spyder/config/base.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/base.py#L102-L113
def debug_print(*message): """Output debug messages to stdout""" warnings.warn("debug_print is deprecated; use the logging module instead.") if get_debug_level(): ss = STDOUT if PY3: # This is needed after restarting and using debug_print for m in message: ss.buffer.write(str(m).encode('utf-8')) print('', file=ss) else: print(*message, file=ss)
[ "def", "debug_print", "(", "*", "message", ")", ":", "warnings", ".", "warn", "(", "\"debug_print is deprecated; use the logging module instead.\"", ")", "if", "get_debug_level", "(", ")", ":", "ss", "=", "STDOUT", "if", "PY3", ":", "# This is needed after restarting ...
Output debug messages to stdout
[ "Output", "debug", "messages", "to", "stdout" ]
python
train
hugapi/hug
hug/decorators.py
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/decorators.py#L150-L167
def reqresp_middleware(api=None): """Registers a middleware function that will be called on every request and response""" def decorator(middleware_generator): apply_to_api = hug.API(api) if api else hug.api.from_object(middleware_generator) class MiddlewareRouter(object): __slots__ = ('gen', ) def process_request(self, request, response): self.gen = middleware_generator(request) return self.gen.__next__() def process_response(self, request, response, resource, req_succeeded): return self.gen.send((response, resource)) apply_to_api.http.add_middleware(MiddlewareRouter()) return middleware_generator return decorator
[ "def", "reqresp_middleware", "(", "api", "=", "None", ")", ":", "def", "decorator", "(", "middleware_generator", ")", ":", "apply_to_api", "=", "hug", ".", "API", "(", "api", ")", "if", "api", "else", "hug", ".", "api", ".", "from_object", "(", "middlewa...
Registers a middleware function that will be called on every request and response
[ "Registers", "a", "middleware", "function", "that", "will", "be", "called", "on", "every", "request", "and", "response" ]
python
train
ElementAI/greensim
greensim/__init__.py
https://github.com/ElementAI/greensim/blob/f160e8b57d69f6ef469f2e991cc07b7721e08a91/greensim/__init__.py#L529-L549
def interrupt(self, inter: Optional[Interrupt] = None) -> None: """ Interrupts a process that has been previously :py:meth:`pause`d or made to :py:meth:`advance`, by resuming it immediately and raising an :py:class:`Interrupt` exception on it. This exception can be captured by the interrupted process and leveraged for various purposes, such as timing out on a wait or generating activity prompting immediate reaction. :param inter: Exception to raise on the :py:class:`Process`; if ``None`` is given, an instance of :py:class:`Interrupt` is raised. This allows one to use specialized :py:class:`Interrupt` subclasses to as to implement non-interfering mixed interruption stacks. For instance, a process may advance towards a certain timeout as it waits for multiple resources concurrently. Should it hit the timeout, it would :py:meth:`interrupt` the waiting processes so as to clean up after itself. If these processes have themselves a timeout mechanism of their own, also based on interrupts, using a subclass can help them distinguish between these and the clean-up interrupts. """ if inter is None: inter = Interrupt() if _logger is not None: _log(INFO, "Process", self.local.name, "interrupt", type=type(inter).__name__) self.rsim()._schedule(0.0, self.throw, inter)
[ "def", "interrupt", "(", "self", ",", "inter", ":", "Optional", "[", "Interrupt", "]", "=", "None", ")", "->", "None", ":", "if", "inter", "is", "None", ":", "inter", "=", "Interrupt", "(", ")", "if", "_logger", "is", "not", "None", ":", "_log", "(...
Interrupts a process that has been previously :py:meth:`pause`d or made to :py:meth:`advance`, by resuming it immediately and raising an :py:class:`Interrupt` exception on it. This exception can be captured by the interrupted process and leveraged for various purposes, such as timing out on a wait or generating activity prompting immediate reaction. :param inter: Exception to raise on the :py:class:`Process`; if ``None`` is given, an instance of :py:class:`Interrupt` is raised. This allows one to use specialized :py:class:`Interrupt` subclasses to as to implement non-interfering mixed interruption stacks. For instance, a process may advance towards a certain timeout as it waits for multiple resources concurrently. Should it hit the timeout, it would :py:meth:`interrupt` the waiting processes so as to clean up after itself. If these processes have themselves a timeout mechanism of their own, also based on interrupts, using a subclass can help them distinguish between these and the clean-up interrupts.
[ "Interrupts", "a", "process", "that", "has", "been", "previously", ":", "py", ":", "meth", ":", "pause", "d", "or", "made", "to", ":", "py", ":", "meth", ":", "advance", "by", "resuming", "it", "immediately", "and", "raising", "an", ":", "py", ":", "...
python
train
Robpol86/libnl
libnl/list_.py
https://github.com/Robpol86/libnl/blob/274e9fdaa39822d06ef70b799ed4a95937a4d923/libnl/list_.py#L28-L39
def _nl_list_add(obj, prev, next_): """https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink/list.h#L27. Positional arguments: obj -- nl_list_head class instance. prev -- nl_list_head class instance. next_ -- nl_list_head class instance. """ prev.next_ = obj obj.prev = prev next_.prev = obj obj.next_ = next_
[ "def", "_nl_list_add", "(", "obj", ",", "prev", ",", "next_", ")", ":", "prev", ".", "next_", "=", "obj", "obj", ".", "prev", "=", "prev", "next_", ".", "prev", "=", "obj", "obj", ".", "next_", "=", "next_" ]
https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink/list.h#L27. Positional arguments: obj -- nl_list_head class instance. prev -- nl_list_head class instance. next_ -- nl_list_head class instance.
[ "https", ":", "//", "github", ".", "com", "/", "thom311", "/", "libnl", "/", "blob", "/", "libnl3_2_25", "/", "include", "/", "netlink", "/", "list", ".", "h#L27", "." ]
python
train
BernardFW/bernard
src/bernard/storage/register/redis.py
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/storage/register/redis.py#L62-L68
async def _finish(self, key: Text) -> None: """ Remove the lock. """ with await self.pool as r: await r.delete(self.lock_key(key))
[ "async", "def", "_finish", "(", "self", ",", "key", ":", "Text", ")", "->", "None", ":", "with", "await", "self", ".", "pool", "as", "r", ":", "await", "r", ".", "delete", "(", "self", ".", "lock_key", "(", "key", ")", ")" ]
Remove the lock.
[ "Remove", "the", "lock", "." ]
python
train
lexibank/pylexibank
src/pylexibank/lingpy_util.py
https://github.com/lexibank/pylexibank/blob/c28e7f122f20de1232623dd7003cb5b01535e581/src/pylexibank/lingpy_util.py#L33-L41
def _cldf2lexstat( dataset, segments='segments', transcription='value', row='parameter_id', col='language_id'): """Read LexStat object from cldf dataset.""" D = _cldf2wld(dataset) return lingpy.LexStat(D, segments=segments, transcription=transcription, row=row, col=col)
[ "def", "_cldf2lexstat", "(", "dataset", ",", "segments", "=", "'segments'", ",", "transcription", "=", "'value'", ",", "row", "=", "'parameter_id'", ",", "col", "=", "'language_id'", ")", ":", "D", "=", "_cldf2wld", "(", "dataset", ")", "return", "lingpy", ...
Read LexStat object from cldf dataset.
[ "Read", "LexStat", "object", "from", "cldf", "dataset", "." ]
python
train
jesford/cluster-lensing
clusterlensing/utils.py
https://github.com/jesford/cluster-lensing/blob/2815c1bb07d904ca91a80dae3f52090016768072/clusterlensing/utils.py#L58-L75
def check_array_or_list(input): """Return 1D ndarray, if input can be converted and elements are non-negative.""" if type(input) != np.ndarray: if type(input) == list: output = np.array(input) else: raise TypeError('Expecting input type as ndarray or list.') else: output = input if output.ndim != 1: raise ValueError('Input array must have 1 dimension.') if np.sum(output < 0.) > 0: raise ValueError("Input array values cannot be negative.") return output
[ "def", "check_array_or_list", "(", "input", ")", ":", "if", "type", "(", "input", ")", "!=", "np", ".", "ndarray", ":", "if", "type", "(", "input", ")", "==", "list", ":", "output", "=", "np", ".", "array", "(", "input", ")", "else", ":", "raise", ...
Return 1D ndarray, if input can be converted and elements are non-negative.
[ "Return", "1D", "ndarray", "if", "input", "can", "be", "converted", "and", "elements", "are", "non", "-", "negative", "." ]
python
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L519-L556
def sanitize_op( self, op_data ): """ Remove unnecessary fields for an operation, i.e. prior to committing it. This includes any invariant tags we've added with our invariant decorators (such as @state_create or @state_transition). TODO: less ad-hoc way to do this """ op_data = super(BlockstackDB, self).sanitize_op(op_data) # remove invariant tags (i.e. added by our invariant state_* decorators) to_remove = get_state_invariant_tags() for tag in to_remove: if tag in op_data.keys(): del op_data[tag] # NOTE: this is called the opcode family, because # different operation names can have the same operation code # (such as NAME_RENEWAL and NAME_REGISTRATION). They must # have the same mutation fields. opcode_family = op_get_opcode_name( op_data['op'] ) # for each column in the appropriate state table, # if the column is not identified in the operation's # MUTATE_FIELDS list, then set it to None here. mutate_fields = op_get_mutate_fields( opcode_family ) for mf in mutate_fields: if not op_data.has_key( mf ): log.debug("Adding NULL mutate field '%s.%s'" % (opcode_family, mf )) op_data[mf] = None # TODO: less ad-hoc for extra_field in ['opcode']: if extra_field in op_data: del op_data[extra_field] return op_data
[ "def", "sanitize_op", "(", "self", ",", "op_data", ")", ":", "op_data", "=", "super", "(", "BlockstackDB", ",", "self", ")", ".", "sanitize_op", "(", "op_data", ")", "# remove invariant tags (i.e. added by our invariant state_* decorators)", "to_remove", "=", "get_sta...
Remove unnecessary fields for an operation, i.e. prior to committing it. This includes any invariant tags we've added with our invariant decorators (such as @state_create or @state_transition). TODO: less ad-hoc way to do this
[ "Remove", "unnecessary", "fields", "for", "an", "operation", "i", ".", "e", ".", "prior", "to", "committing", "it", ".", "This", "includes", "any", "invariant", "tags", "we", "ve", "added", "with", "our", "invariant", "decorators", "(", "such", "as" ]
python
train
davidblaisonneau-orange/foreman
foreman/subItemPuppetClasses.py
https://github.com/davidblaisonneau-orange/foreman/blob/acb8fd8d74657cfac3b25c82e9c6028b93eb6c92/foreman/subItemPuppetClasses.py#L34-L45
def getPayloadStruct(self, attributes, objType): """ Function getPayloadStruct Get the payload structure to do a creation or a modification @param attribute: The data @param objType: SubItem type (e.g: hostgroup for hostgroup_class) @return RETURN: the payload """ payload = {self.payloadObj: attributes, objType + "_class": {self.payloadObj: attributes}} return payload
[ "def", "getPayloadStruct", "(", "self", ",", "attributes", ",", "objType", ")", ":", "payload", "=", "{", "self", ".", "payloadObj", ":", "attributes", ",", "objType", "+", "\"_class\"", ":", "{", "self", ".", "payloadObj", ":", "attributes", "}", "}", "...
Function getPayloadStruct Get the payload structure to do a creation or a modification @param attribute: The data @param objType: SubItem type (e.g: hostgroup for hostgroup_class) @return RETURN: the payload
[ "Function", "getPayloadStruct", "Get", "the", "payload", "structure", "to", "do", "a", "creation", "or", "a", "modification" ]
python
train
muckamuck/stackility
stackility/utility/get_ssm_parameter.py
https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/utility/get_ssm_parameter.py#L6-L26
def get_ssm_parameter(parameter_name): ''' Get the decrypted value of an SSM parameter Args: parameter_name - the name of the stored parameter of interest Return: Value if allowed and present else None ''' try: response = boto3.client('ssm').get_parameters( Names=[parameter_name], WithDecryption=True ) return response.get('Parameters', None)[0].get('Value', '') except Exception: pass return ''
[ "def", "get_ssm_parameter", "(", "parameter_name", ")", ":", "try", ":", "response", "=", "boto3", ".", "client", "(", "'ssm'", ")", ".", "get_parameters", "(", "Names", "=", "[", "parameter_name", "]", ",", "WithDecryption", "=", "True", ")", "return", "r...
Get the decrypted value of an SSM parameter Args: parameter_name - the name of the stored parameter of interest Return: Value if allowed and present else None
[ "Get", "the", "decrypted", "value", "of", "an", "SSM", "parameter" ]
python
train
PythonCharmers/python-future
src/future/backports/http/server.py
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/server.py#L410-L439
def send_error(self, code, message=None): """Send and log an error reply. Arguments are the error code, and a detailed message. The detailed message defaults to the short entry matching the response code. This sends an error response (so it must be called before any output has been generated), logs the error, and finally sends a piece of HTML explaining the error to the user. """ try: shortmsg, longmsg = self.responses[code] except KeyError: shortmsg, longmsg = '???', '???' if message is None: message = shortmsg explain = longmsg self.log_error("code %d, message %s", code, message) # using _quote_html to prevent Cross Site Scripting attacks (see bug #1100201) content = (self.error_message_format % {'code': code, 'message': _quote_html(message), 'explain': explain}) self.send_response(code, message) self.send_header("Content-Type", self.error_content_type) self.send_header('Connection', 'close') self.end_headers() if self.command != 'HEAD' and code >= 200 and code not in (204, 304): self.wfile.write(content.encode('UTF-8', 'replace'))
[ "def", "send_error", "(", "self", ",", "code", ",", "message", "=", "None", ")", ":", "try", ":", "shortmsg", ",", "longmsg", "=", "self", ".", "responses", "[", "code", "]", "except", "KeyError", ":", "shortmsg", ",", "longmsg", "=", "'???'", ",", "...
Send and log an error reply. Arguments are the error code, and a detailed message. The detailed message defaults to the short entry matching the response code. This sends an error response (so it must be called before any output has been generated), logs the error, and finally sends a piece of HTML explaining the error to the user.
[ "Send", "and", "log", "an", "error", "reply", "." ]
python
train
tcalmant/ipopo
pelix/shell/parser.py
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/parser.py#L359-L380
def get_ns_commands(self, cmd_name): """ Retrieves the possible name spaces and commands associated to the given command name. :param cmd_name: The given command name :return: A list of 2-tuples (name space, command) :raise ValueError: Unknown command name """ namespace, command = _split_ns_command(cmd_name) if not namespace: # Name space not given, look for the commands spaces = self.__find_command_ns(command) if not spaces: # Unknown command raise ValueError("Unknown command {0}".format(command)) else: # Return a sorted list of tuples return sorted((namespace, command) for namespace in spaces) # Single match return [(namespace, command)]
[ "def", "get_ns_commands", "(", "self", ",", "cmd_name", ")", ":", "namespace", ",", "command", "=", "_split_ns_command", "(", "cmd_name", ")", "if", "not", "namespace", ":", "# Name space not given, look for the commands", "spaces", "=", "self", ".", "__find_command...
Retrieves the possible name spaces and commands associated to the given command name. :param cmd_name: The given command name :return: A list of 2-tuples (name space, command) :raise ValueError: Unknown command name
[ "Retrieves", "the", "possible", "name", "spaces", "and", "commands", "associated", "to", "the", "given", "command", "name", "." ]
python
train
Microsoft/nni
tools/nni_cmd/updater.py
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/updater.py#L59-L64
def load_search_space(path): '''load search space content''' content = json.dumps(get_json_content(path)) if not content: raise ValueError('searchSpace file should not be empty') return content
[ "def", "load_search_space", "(", "path", ")", ":", "content", "=", "json", ".", "dumps", "(", "get_json_content", "(", "path", ")", ")", "if", "not", "content", ":", "raise", "ValueError", "(", "'searchSpace file should not be empty'", ")", "return", "content" ]
load search space content
[ "load", "search", "space", "content" ]
python
train
Fantomas42/django-blog-zinnia
zinnia/templatetags/zinnia.py
https://github.com/Fantomas42/django-blog-zinnia/blob/b4949304b104a8e1a7a7a0773cbfd024313c3a15/zinnia/templatetags/zinnia.py#L331-L346
def zinnia_loop_template(context, default_template): """ Return a selected template from his position within a loop and the filtering context. """ matching, context_object = get_context_first_matching_object( context, ['category', 'tag', 'author', 'pattern', 'year', 'month', 'week', 'day']) context_positions = get_context_loop_positions(context) templates = loop_template_list( context_positions, context_object, matching, default_template, ENTRY_LOOP_TEMPLATES) return select_template(templates)
[ "def", "zinnia_loop_template", "(", "context", ",", "default_template", ")", ":", "matching", ",", "context_object", "=", "get_context_first_matching_object", "(", "context", ",", "[", "'category'", ",", "'tag'", ",", "'author'", ",", "'pattern'", ",", "'year'", "...
Return a selected template from his position within a loop and the filtering context.
[ "Return", "a", "selected", "template", "from", "his", "position", "within", "a", "loop", "and", "the", "filtering", "context", "." ]
python
train
secdev/scapy
scapy/layers/dns.py
https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/layers/dns.py#L890-L906
def dyndns_add(nameserver, name, rdata, type="A", ttl=10): """Send a DNS add message to a nameserver for "name" to have a new "rdata" dyndns_add(nameserver, name, rdata, type="A", ttl=10) -> result code (0=ok) example: dyndns_add("ns1.toto.com", "dyn.toto.com", "127.0.0.1") RFC2136 """ zone = name[name.find(".") + 1:] r = sr1(IP(dst=nameserver) / UDP() / DNS(opcode=5, qd=[DNSQR(qname=zone, qtype="SOA")], # noqa: E501 ns=[DNSRR(rrname=name, type="A", ttl=ttl, rdata=rdata)]), verbose=0, timeout=5) if r and r.haslayer(DNS): return r.getlayer(DNS).rcode else: return -1
[ "def", "dyndns_add", "(", "nameserver", ",", "name", ",", "rdata", ",", "type", "=", "\"A\"", ",", "ttl", "=", "10", ")", ":", "zone", "=", "name", "[", "name", ".", "find", "(", "\".\"", ")", "+", "1", ":", "]", "r", "=", "sr1", "(", "IP", "...
Send a DNS add message to a nameserver for "name" to have a new "rdata" dyndns_add(nameserver, name, rdata, type="A", ttl=10) -> result code (0=ok) example: dyndns_add("ns1.toto.com", "dyn.toto.com", "127.0.0.1") RFC2136
[ "Send", "a", "DNS", "add", "message", "to", "a", "nameserver", "for", "name", "to", "have", "a", "new", "rdata", "dyndns_add", "(", "nameserver", "name", "rdata", "type", "=", "A", "ttl", "=", "10", ")", "-", ">", "result", "code", "(", "0", "=", "...
python
train
buildbot/buildbot
master/buildbot/secrets/manager.py
https://github.com/buildbot/buildbot/blob/5df3cfae6d760557d99156633c32b1822a1e130c/master/buildbot/secrets/manager.py#L33-L45
def get(self, secret, *args, **kwargs): """ get secrets from the provider defined in the secret using args and kwargs @secrets: secrets keys @type: string @return type: SecretDetails """ for provider in self.services: value = yield provider.get(secret) source_name = provider.__class__.__name__ if value is not None: return SecretDetails(source_name, secret, value)
[ "def", "get", "(", "self", ",", "secret", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "provider", "in", "self", ".", "services", ":", "value", "=", "yield", "provider", ".", "get", "(", "secret", ")", "source_name", "=", "provider", ...
get secrets from the provider defined in the secret using args and kwargs @secrets: secrets keys @type: string @return type: SecretDetails
[ "get", "secrets", "from", "the", "provider", "defined", "in", "the", "secret", "using", "args", "and", "kwargs" ]
python
train
allenai/allennlp
allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py#L392-L472
def _get_linking_probabilities(self, worlds: List[WikiTablesWorld], linking_scores: torch.FloatTensor, question_mask: torch.LongTensor, entity_type_dict: Dict[int, int]) -> torch.FloatTensor: """ Produces the probability of an entity given a question word and type. The logic below separates the entities by type since the softmax normalization term sums over entities of a single type. Parameters ---------- worlds : ``List[WikiTablesWorld]`` linking_scores : ``torch.FloatTensor`` Has shape (batch_size, num_question_tokens, num_entities). question_mask: ``torch.LongTensor`` Has shape (batch_size, num_question_tokens). entity_type_dict : ``Dict[int, int]`` This is a mapping from ((batch_index * num_entities) + entity_index) to entity type id. Returns ------- batch_probabilities : ``torch.FloatTensor`` Has shape ``(batch_size, num_question_tokens, num_entities)``. Contains all the probabilities for an entity given a question word. """ _, num_question_tokens, num_entities = linking_scores.size() batch_probabilities = [] for batch_index, world in enumerate(worlds): all_probabilities = [] num_entities_in_instance = 0 # NOTE: The way that we're doing this here relies on the fact that entities are # implicitly sorted by their types when we sort them by name, and that numbers come # before "fb:cell", and "fb:cell" comes before "fb:row". This is not a great # assumption, and could easily break later, but it should work for now. for type_index in range(self._num_entity_types): # This index of 0 is for the null entity for each type, representing the case where a # word doesn't link to any entity. entity_indices = [0] entities = world.table_graph.entities for entity_index, _ in enumerate(entities): if entity_type_dict[batch_index * num_entities + entity_index] == type_index: entity_indices.append(entity_index) if len(entity_indices) == 1: # No entities of this type; move along... continue # We're subtracting one here because of the null entity we added above. num_entities_in_instance += len(entity_indices) - 1 # We separate the scores by type, since normalization is done per type. There's an # extra "null" entity per type, also, so we have `num_entities_per_type + 1`. We're # selecting from a (num_question_tokens, num_entities) linking tensor on _dimension 1_, # so we get back something of shape (num_question_tokens,) for each index we're # selecting. All of the selected indices together then make a tensor of shape # (num_question_tokens, num_entities_per_type + 1). indices = linking_scores.new_tensor(entity_indices, dtype=torch.long) entity_scores = linking_scores[batch_index].index_select(1, indices) # We used index 0 for the null entity, so this will actually have some values in it. # But we want the null entity's score to be 0, so we set that here. entity_scores[:, 0] = 0 # No need for a mask here, as this is done per batch instance, with no padding. type_probabilities = torch.nn.functional.softmax(entity_scores, dim=1) all_probabilities.append(type_probabilities[:, 1:]) # We need to add padding here if we don't have the right number of entities. if num_entities_in_instance != num_entities: zeros = linking_scores.new_zeros(num_question_tokens, num_entities - num_entities_in_instance) all_probabilities.append(zeros) # (num_question_tokens, num_entities) probabilities = torch.cat(all_probabilities, dim=1) batch_probabilities.append(probabilities) batch_probabilities = torch.stack(batch_probabilities, dim=0) return batch_probabilities * question_mask.unsqueeze(-1).float()
[ "def", "_get_linking_probabilities", "(", "self", ",", "worlds", ":", "List", "[", "WikiTablesWorld", "]", ",", "linking_scores", ":", "torch", ".", "FloatTensor", ",", "question_mask", ":", "torch", ".", "LongTensor", ",", "entity_type_dict", ":", "Dict", "[", ...
Produces the probability of an entity given a question word and type. The logic below separates the entities by type since the softmax normalization term sums over entities of a single type. Parameters ---------- worlds : ``List[WikiTablesWorld]`` linking_scores : ``torch.FloatTensor`` Has shape (batch_size, num_question_tokens, num_entities). question_mask: ``torch.LongTensor`` Has shape (batch_size, num_question_tokens). entity_type_dict : ``Dict[int, int]`` This is a mapping from ((batch_index * num_entities) + entity_index) to entity type id. Returns ------- batch_probabilities : ``torch.FloatTensor`` Has shape ``(batch_size, num_question_tokens, num_entities)``. Contains all the probabilities for an entity given a question word.
[ "Produces", "the", "probability", "of", "an", "entity", "given", "a", "question", "word", "and", "type", ".", "The", "logic", "below", "separates", "the", "entities", "by", "type", "since", "the", "softmax", "normalization", "term", "sums", "over", "entities",...
python
train
biocore/burrito-fillings
bfillings/raxml_v730.py
https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/raxml_v730.py#L767-L822
def build_tree_from_alignment(aln, moltype=DNA, best_tree=False, params={}): """Returns a tree from Alignment object aln. aln: an xxx.Alignment object, or data that can be used to build one. moltype: cogent.core.moltype.MolType object best_tree: best_tree suppport is currently not implemented params: dict of parameters to pass in to the RAxML app controller. The result will be an xxx.Alignment object, or None if tree fails. """ if best_tree: raise NotImplementedError if '-m' not in params: if moltype == DNA or moltype == RNA: #params["-m"] = 'GTRMIX' # in version 7.2.3, GTRMIX is no longer supported but says GTRCAT # behaves like GTRMIX (http://www.phylo.org/tools/raxmlhpc2.html) params["-m"] = 'GTRGAMMA' elif moltype == PROTEIN: params["-m"] = 'PROTGAMMAmatrixName' else: raise ValueError, "Moltype must be either DNA, RNA, or PROTEIN" if not hasattr(aln, 'toPhylip'): aln = Alignment(aln) seqs, align_map = aln.toPhylip() # generate temp filename for output params["-w"] = "/tmp/" params["-n"] = get_tmp_filename().split("/")[-1] params["-k"] = True params["-p"] = randint(1,100000) params["-x"] = randint(1,100000) ih = '_input_as_multiline_string' raxml_app = Raxml(params=params, InputHandler=ih, WorkingDir=None, SuppressStderr=True, SuppressStdout=True) raxml_result = raxml_app(seqs) tree = DndParser(raxml_result['Bootstrap'], constructor=PhyloNode) for node in tree.tips(): node.Name = align_map[node.Name] raxml_result.cleanUp() return tree
[ "def", "build_tree_from_alignment", "(", "aln", ",", "moltype", "=", "DNA", ",", "best_tree", "=", "False", ",", "params", "=", "{", "}", ")", ":", "if", "best_tree", ":", "raise", "NotImplementedError", "if", "'-m'", "not", "in", "params", ":", "if", "m...
Returns a tree from Alignment object aln. aln: an xxx.Alignment object, or data that can be used to build one. moltype: cogent.core.moltype.MolType object best_tree: best_tree suppport is currently not implemented params: dict of parameters to pass in to the RAxML app controller. The result will be an xxx.Alignment object, or None if tree fails.
[ "Returns", "a", "tree", "from", "Alignment", "object", "aln", "." ]
python
train
nanvel/c2p2
c2p2/models.py
https://github.com/nanvel/c2p2/blob/3900a9bb54d35e1332b92d6560f3cb1e77943209/c2p2/models.py#L189-L194
def _update_page(self, uri, path): """Update page content.""" if uri in self._pages: self._pages[uri].update() else: self._pages[uri] = Page(uri=uri, path=path)
[ "def", "_update_page", "(", "self", ",", "uri", ",", "path", ")", ":", "if", "uri", "in", "self", ".", "_pages", ":", "self", ".", "_pages", "[", "uri", "]", ".", "update", "(", ")", "else", ":", "self", ".", "_pages", "[", "uri", "]", "=", "Pa...
Update page content.
[ "Update", "page", "content", "." ]
python
train
CityOfZion/neo-boa
boa/compiler.py
https://github.com/CityOfZion/neo-boa/blob/5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b/boa/compiler.py#L79-L108
def load_and_save(path, output_path=None, use_nep8=True): """ Call `load_and_save` to load a Python file to be compiled to the .avm format and save the result. By default, the resultant .avm file is saved along side the source file. :param path: The path of the Python file to compile :param output_path: Optional path to save the compiled `.avm` file :return: the instance of the compiler The following returns the compiler object for inspection .. code-block:: python from boa.compiler import Compiler Compiler.load_and_save('path/to/your/file.py') """ compiler = Compiler.load(os.path.abspath(path), use_nep8=use_nep8) data = compiler.write() if output_path is None: fullpath = os.path.realpath(path) path, filename = os.path.split(fullpath) newfilename = filename.replace('.py', '.avm') output_path = '%s/%s' % (path, newfilename) Compiler.write_file(data, output_path) compiler.entry_module.export_debug(output_path) return data
[ "def", "load_and_save", "(", "path", ",", "output_path", "=", "None", ",", "use_nep8", "=", "True", ")", ":", "compiler", "=", "Compiler", ".", "load", "(", "os", ".", "path", ".", "abspath", "(", "path", ")", ",", "use_nep8", "=", "use_nep8", ")", "...
Call `load_and_save` to load a Python file to be compiled to the .avm format and save the result. By default, the resultant .avm file is saved along side the source file. :param path: The path of the Python file to compile :param output_path: Optional path to save the compiled `.avm` file :return: the instance of the compiler The following returns the compiler object for inspection .. code-block:: python from boa.compiler import Compiler Compiler.load_and_save('path/to/your/file.py')
[ "Call", "load_and_save", "to", "load", "a", "Python", "file", "to", "be", "compiled", "to", "the", ".", "avm", "format", "and", "save", "the", "result", ".", "By", "default", "the", "resultant", ".", "avm", "file", "is", "saved", "along", "side", "the", ...
python
train
santoshphilip/eppy
eppy/loops.py
https://github.com/santoshphilip/eppy/blob/55410ff7c11722f35bc4331ff5e00a0b86f787e1/eppy/loops.py#L94-L102
def branch_inlet_outlet(data, commdct, branchname): """return the inlet and outlet of a branch""" objkey = 'Branch'.upper() theobjects = data.dt[objkey] theobject = [obj for obj in theobjects if obj[1] == branchname] theobject = theobject[0] inletindex = 6 outletindex = len(theobject) - 2 return [theobject[inletindex], theobject[outletindex]]
[ "def", "branch_inlet_outlet", "(", "data", ",", "commdct", ",", "branchname", ")", ":", "objkey", "=", "'Branch'", ".", "upper", "(", ")", "theobjects", "=", "data", ".", "dt", "[", "objkey", "]", "theobject", "=", "[", "obj", "for", "obj", "in", "theo...
return the inlet and outlet of a branch
[ "return", "the", "inlet", "and", "outlet", "of", "a", "branch" ]
python
train
pypa/pipenv
pipenv/vendor/attr/filters.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/attr/filters.py#L38-L52
def exclude(*what): """ Blacklist *what*. :param what: What to blacklist. :type what: :class:`list` of classes or :class:`attr.Attribute`\\ s. :rtype: :class:`callable` """ cls, attrs = _split_what(what) def exclude_(attribute, value): return value.__class__ not in cls and attribute not in attrs return exclude_
[ "def", "exclude", "(", "*", "what", ")", ":", "cls", ",", "attrs", "=", "_split_what", "(", "what", ")", "def", "exclude_", "(", "attribute", ",", "value", ")", ":", "return", "value", ".", "__class__", "not", "in", "cls", "and", "attribute", "not", ...
Blacklist *what*. :param what: What to blacklist. :type what: :class:`list` of classes or :class:`attr.Attribute`\\ s. :rtype: :class:`callable`
[ "Blacklist", "*", "what", "*", "." ]
python
train
djtaylor/python-lsbinit
lsbinit/__init__.py
https://github.com/djtaylor/python-lsbinit/blob/a41fc551226f61ac2bf1b8b0f3f5395db85e75a2/lsbinit/__init__.py#L51-L70
def _colorize(self, msg, color=None, encode=False): """ Colorize a string. """ # Valid colors colors = { 'red': '31', 'green': '32', 'yellow': '33' } # No color specified or unsupported color if not color or not color in colors: return msg # The colorized string if encode: return u'\x1b[1;{}m{}\x1b[0m'.format(colors[color], msg) return '\x1b[1;{}m{}\x1b[0m'.format(colors[color], msg)
[ "def", "_colorize", "(", "self", ",", "msg", ",", "color", "=", "None", ",", "encode", "=", "False", ")", ":", "# Valid colors", "colors", "=", "{", "'red'", ":", "'31'", ",", "'green'", ":", "'32'", ",", "'yellow'", ":", "'33'", "}", "# No color speci...
Colorize a string.
[ "Colorize", "a", "string", "." ]
python
train
aliyun/aliyun-odps-python-sdk
odps/df/expr/strings.py
https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/df/expr/strings.py#L331-L341
def _endswith(expr, pat): """ Return boolean sequence or scalar indicating whether each string in the sequence or scalar ends with passed pattern. Equivalent to str.endswith(). :param expr: :param pat: Character sequence :return: sequence or scalar """ return _string_op(expr, Endswith, output_type=types.boolean, _pat=pat)
[ "def", "_endswith", "(", "expr", ",", "pat", ")", ":", "return", "_string_op", "(", "expr", ",", "Endswith", ",", "output_type", "=", "types", ".", "boolean", ",", "_pat", "=", "pat", ")" ]
Return boolean sequence or scalar indicating whether each string in the sequence or scalar ends with passed pattern. Equivalent to str.endswith(). :param expr: :param pat: Character sequence :return: sequence or scalar
[ "Return", "boolean", "sequence", "or", "scalar", "indicating", "whether", "each", "string", "in", "the", "sequence", "or", "scalar", "ends", "with", "passed", "pattern", ".", "Equivalent", "to", "str", ".", "endswith", "()", "." ]
python
train
openstax/cnx-archive
cnxarchive/scripts/hits_counter.py
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/scripts/hits_counter.py#L34-L58
def parse_log(log, url_pattern): """Parse ``log`` buffer based on ``url_pattern``. Given a buffer as ``log``, parse the log buffer into a mapping of ident-hashes to a hit count, the timestamp of the initial log, and the last timestamp in the log. """ hits = {} initial_timestamp = None def clean_timestamp(v): return ' '.join(v).strip('[]') for line in log: data = line.split() if not initial_timestamp: initial_timestamp = clean_timestamp(data[3:5]) match = url_pattern.match(data[6]) if match: ident_hash = '@'.join(match.groups()) if ident_hash: hits[ident_hash] = hits.get(ident_hash, 0) + 1 else: end_timestamp = clean_timestamp(data[3:5]) return hits, initial_timestamp, end_timestamp
[ "def", "parse_log", "(", "log", ",", "url_pattern", ")", ":", "hits", "=", "{", "}", "initial_timestamp", "=", "None", "def", "clean_timestamp", "(", "v", ")", ":", "return", "' '", ".", "join", "(", "v", ")", ".", "strip", "(", "'[]'", ")", "for", ...
Parse ``log`` buffer based on ``url_pattern``. Given a buffer as ``log``, parse the log buffer into a mapping of ident-hashes to a hit count, the timestamp of the initial log, and the last timestamp in the log.
[ "Parse", "log", "buffer", "based", "on", "url_pattern", "." ]
python
train
dpgaspar/Flask-AppBuilder
flask_appbuilder/security/manager.py
https://github.com/dpgaspar/Flask-AppBuilder/blob/c293734c1b86e176a3ba57ee2deab6676d125576/flask_appbuilder/security/manager.py#L1005-L1023
def is_item_public(self, permission_name, view_name): """ Check if view has public permissions :param permission_name: the permission: can_show, can_edit... :param view_name: the name of the class view (child of BaseView) """ permissions = self.get_public_permissions() if permissions: for i in permissions: if (view_name == i.view_menu.name) and ( permission_name == i.permission.name ): return True return False else: return False
[ "def", "is_item_public", "(", "self", ",", "permission_name", ",", "view_name", ")", ":", "permissions", "=", "self", ".", "get_public_permissions", "(", ")", "if", "permissions", ":", "for", "i", "in", "permissions", ":", "if", "(", "view_name", "==", "i", ...
Check if view has public permissions :param permission_name: the permission: can_show, can_edit... :param view_name: the name of the class view (child of BaseView)
[ "Check", "if", "view", "has", "public", "permissions" ]
python
train
twisted/mantissa
xmantissa/people.py
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L1697-L1713
def peopleFilters(self, request, tag): """ Return an instance of C{tag}'s I{filter} pattern for each filter we get from L{Organizer.getPeopleFilters}, filling the I{name} slot with the filter's name. The first filter will be rendered using the I{selected-filter} pattern. """ filters = iter(self.organizer.getPeopleFilters()) # at some point we might actually want to look at what filter is # yielded first, and filter the person list accordingly. we're just # going to assume it's the "All" filter, and leave the person list # untouched for now. yield tag.onePattern('selected-filter').fillSlots( 'name', filters.next().filterName) pattern = tag.patternGenerator('filter') for filter in filters: yield pattern.fillSlots('name', filter.filterName)
[ "def", "peopleFilters", "(", "self", ",", "request", ",", "tag", ")", ":", "filters", "=", "iter", "(", "self", ".", "organizer", ".", "getPeopleFilters", "(", ")", ")", "# at some point we might actually want to look at what filter is", "# yielded first, and filter the...
Return an instance of C{tag}'s I{filter} pattern for each filter we get from L{Organizer.getPeopleFilters}, filling the I{name} slot with the filter's name. The first filter will be rendered using the I{selected-filter} pattern.
[ "Return", "an", "instance", "of", "C", "{", "tag", "}", "s", "I", "{", "filter", "}", "pattern", "for", "each", "filter", "we", "get", "from", "L", "{", "Organizer", ".", "getPeopleFilters", "}", "filling", "the", "I", "{", "name", "}", "slot", "with...
python
train
saltstack/salt
salt/client/__init__.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/__init__.py#L1953-L1958
def __load_functions(self): ''' Find out what functions are available on the minion ''' return set(self.local.cmd(self.minion, 'sys.list_functions').get(self.minion, []))
[ "def", "__load_functions", "(", "self", ")", ":", "return", "set", "(", "self", ".", "local", ".", "cmd", "(", "self", ".", "minion", ",", "'sys.list_functions'", ")", ".", "get", "(", "self", ".", "minion", ",", "[", "]", ")", ")" ]
Find out what functions are available on the minion
[ "Find", "out", "what", "functions", "are", "available", "on", "the", "minion" ]
python
train
stbraun/fuzzing
fuzzing/fuzzer.py
https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/fuzzing/fuzzer.py#L271-L292
def _execute(self, app_, file_): """Run app with file as input. :param app_: application to run. :param file_: file to run app with. :return: success True, else False :rtype: bool """ app_name = os.path.basename(app_) args = [app_] args.extend(self.args[app_]) args.append(file_) process = subprocess.Popen(args) time.sleep(1) status = {True: Status.SUCCESS, False: Status.FAILED} crashed = process.poll() result = status[crashed is None] self.stats_.add(app_name, result) if result is Status.SUCCESS: # process did not crash, so just terminate it process.terminate()
[ "def", "_execute", "(", "self", ",", "app_", ",", "file_", ")", ":", "app_name", "=", "os", ".", "path", ".", "basename", "(", "app_", ")", "args", "=", "[", "app_", "]", "args", ".", "extend", "(", "self", ".", "args", "[", "app_", "]", ")", "...
Run app with file as input. :param app_: application to run. :param file_: file to run app with. :return: success True, else False :rtype: bool
[ "Run", "app", "with", "file", "as", "input", "." ]
python
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/swig.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/swig.py#L63-L80
def _find_modules(src): """Find all modules referenced by %module lines in `src`, a SWIG .i file. Returns a list of all modules, and a flag set if SWIG directors have been requested (SWIG will generate an additional header file in this case.)""" directors = 0 mnames = [] try: matches = _reModule.findall(open(src).read()) except IOError: # If the file's not yet generated, guess the module name from the file stem matches = [] mnames.append(os.path.splitext(os.path.basename(src))[0]) for m in matches: mnames.append(m[2]) directors = directors or m[0].find('directors') >= 0 return mnames, directors
[ "def", "_find_modules", "(", "src", ")", ":", "directors", "=", "0", "mnames", "=", "[", "]", "try", ":", "matches", "=", "_reModule", ".", "findall", "(", "open", "(", "src", ")", ".", "read", "(", ")", ")", "except", "IOError", ":", "# If the file'...
Find all modules referenced by %module lines in `src`, a SWIG .i file. Returns a list of all modules, and a flag set if SWIG directors have been requested (SWIG will generate an additional header file in this case.)
[ "Find", "all", "modules", "referenced", "by", "%module", "lines", "in", "src", "a", "SWIG", ".", "i", "file", ".", "Returns", "a", "list", "of", "all", "modules", "and", "a", "flag", "set", "if", "SWIG", "directors", "have", "been", "requested", "(", "...
python
train
openstack/python-scciclient
scciclient/irmc/scci.py
https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/scci.py#L355-L384
def get_virtual_cd_set_params_cmd(remote_image_server, remote_image_user_domain, remote_image_share_type, remote_image_share_name, remote_image_deploy_iso, remote_image_username, remote_image_user_password): """get Virtual CD Media Set Parameters Command This function returns Virtual CD Media Set Parameters Command :param remote_image_server: remote image server name or IP :param remote_image_user_domain: domain name of remote image server :param remote_image_share_type: share type of ShareType :param remote_image_share_name: share name :param remote_image_deploy_iso: deploy ISO image file name :param remote_image_username: username of remote image server :param remote_image_user_password: password of the username :returns: SCCI command """ cmd = _VIRTUAL_MEDIA_CD_SETTINGS % ( remote_image_server, remote_image_user_domain, remote_image_share_type, remote_image_share_name, remote_image_deploy_iso, remote_image_username, remote_image_user_password) return cmd
[ "def", "get_virtual_cd_set_params_cmd", "(", "remote_image_server", ",", "remote_image_user_domain", ",", "remote_image_share_type", ",", "remote_image_share_name", ",", "remote_image_deploy_iso", ",", "remote_image_username", ",", "remote_image_user_password", ")", ":", "cmd", ...
get Virtual CD Media Set Parameters Command This function returns Virtual CD Media Set Parameters Command :param remote_image_server: remote image server name or IP :param remote_image_user_domain: domain name of remote image server :param remote_image_share_type: share type of ShareType :param remote_image_share_name: share name :param remote_image_deploy_iso: deploy ISO image file name :param remote_image_username: username of remote image server :param remote_image_user_password: password of the username :returns: SCCI command
[ "get", "Virtual", "CD", "Media", "Set", "Parameters", "Command" ]
python
train
Erotemic/utool
utool/util_cache.py
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_cache.py#L1121-L1169
def load(self, cachedir=None, cfgstr=None, fpath=None, verbose=None, quiet=QUIET, ignore_keys=None): """ Loads the result from the given database """ if verbose is None: verbose = getattr(self, 'verbose', VERBOSE) if fpath is None: fpath = self.get_fpath(cachedir, cfgstr=cfgstr) if verbose: print('[Cachable] cache tryload: %r' % (basename(fpath),)) try: self._unsafe_load(fpath, ignore_keys) if verbose: print('... self cache hit: %r' % (basename(fpath),)) except ValueError as ex: import utool as ut msg = '[!Cachable] Cachable(%s) is likely corrupt' % (self.get_cfgstr()) print('CORRUPT fpath = %s' % (fpath,)) ut.printex(ex, msg, iswarning=True) raise #except BadZipFile as ex: except zipfile.error as ex: import utool as ut msg = '[!Cachable] Cachable(%s) has bad zipfile' % (self.get_cfgstr()) print('CORRUPT fpath = %s' % (fpath,)) ut.printex(ex, msg, iswarning=True) raise #if exists(fpath): # #print('[Cachable] Removing corrupted file: %r' % fpath) # #os.remove(fpath) # raise hsexcept.HotsNeedsRecomputeError(msg) #else: # raise Exception(msg) except IOError as ex: import utool as ut if not exists(fpath): msg = '... self cache miss: %r' % (basename(fpath),) if verbose: print(msg) raise print('CORRUPT fpath = %s' % (fpath,)) msg = '[!Cachable] Cachable(%s) is corrupt' % (self.get_cfgstr()) ut.printex(ex, msg, iswarning=True) raise except Exception as ex: import utool as ut ut.printex(ex, 'unknown exception while loading query result') raise
[ "def", "load", "(", "self", ",", "cachedir", "=", "None", ",", "cfgstr", "=", "None", ",", "fpath", "=", "None", ",", "verbose", "=", "None", ",", "quiet", "=", "QUIET", ",", "ignore_keys", "=", "None", ")", ":", "if", "verbose", "is", "None", ":",...
Loads the result from the given database
[ "Loads", "the", "result", "from", "the", "given", "database" ]
python
train
gem/oq-engine
openquake/calculators/extract.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L988-L1001
def dump(self, fname): """ Dump the remote datastore on a local path. """ url = '%s/v1/calc/%d/datastore' % (self.server, self.calc_id) resp = self.sess.get(url, stream=True) down = 0 with open(fname, 'wb') as f: logging.info('Saving %s', fname) for chunk in resp.iter_content(CHUNKSIZE): f.write(chunk) down += len(chunk) println('Downloaded {:,} bytes'.format(down)) print()
[ "def", "dump", "(", "self", ",", "fname", ")", ":", "url", "=", "'%s/v1/calc/%d/datastore'", "%", "(", "self", ".", "server", ",", "self", ".", "calc_id", ")", "resp", "=", "self", ".", "sess", ".", "get", "(", "url", ",", "stream", "=", "True", ")...
Dump the remote datastore on a local path.
[ "Dump", "the", "remote", "datastore", "on", "a", "local", "path", "." ]
python
train
ellmetha/django-machina
machina/apps/forum_permission/handler.py
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L61-L72
def forum_list_filter(self, qs, user): """ Filters the given queryset in order to return a list of forums that can be seen and read by the specified user (at least). """ # Any superuser should see all the forums if user.is_superuser: return qs # Check whether the forums can be viewed by the given user forums_to_hide = self._get_hidden_forum_ids(qs, user) return qs.exclude(id__in=forums_to_hide)
[ "def", "forum_list_filter", "(", "self", ",", "qs", ",", "user", ")", ":", "# Any superuser should see all the forums", "if", "user", ".", "is_superuser", ":", "return", "qs", "# Check whether the forums can be viewed by the given user", "forums_to_hide", "=", "self", "."...
Filters the given queryset in order to return a list of forums that can be seen and read by the specified user (at least).
[ "Filters", "the", "given", "queryset", "in", "order", "to", "return", "a", "list", "of", "forums", "that", "can", "be", "seen", "and", "read", "by", "the", "specified", "user", "(", "at", "least", ")", "." ]
python
train
pyroscope/pyrocore
src/pyrocore/torrent/jobs.py
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/jobs.py#L99-L107
def _influxdb_url(self): """ Return REST API URL to access time series. """ url = "{0}/db/{1}/series".format(self.influxdb.url.rstrip('/'), self.config.dbname) if self.influxdb.user and self.influxdb.password: url += "?u={0}&p={1}".format(self.influxdb.user, self.influxdb.password) return url
[ "def", "_influxdb_url", "(", "self", ")", ":", "url", "=", "\"{0}/db/{1}/series\"", ".", "format", "(", "self", ".", "influxdb", ".", "url", ".", "rstrip", "(", "'/'", ")", ",", "self", ".", "config", ".", "dbname", ")", "if", "self", ".", "influxdb", ...
Return REST API URL to access time series.
[ "Return", "REST", "API", "URL", "to", "access", "time", "series", "." ]
python
train
UB-UNIBAS/simple-elastic
simple_elastic/index.py
https://github.com/UB-UNIBAS/simple-elastic/blob/54f2fdd3405a7eafbf8873f337da263b8d47532a/simple_elastic/index.py#L93-L112
def search(self, query=None, size=100, unpack=True): """Search the index with a query. Can at most return 10'000 results from a search. If the search would yield more than 10'000 hits, only the first 10'000 are returned. The default number of hits returned is 100. """ logging.info('Download all documents from index %s.', self.index) if query is None: query = self.match_all results = list() data = self.instance.search(index=self.index, doc_type=self.doc_type, body=query, size=size) if unpack: for items in data['hits']['hits']: if '_source' in items: results.append(items['_source']) else: results.append(items) else: results = data['hits']['hits'] return results
[ "def", "search", "(", "self", ",", "query", "=", "None", ",", "size", "=", "100", ",", "unpack", "=", "True", ")", ":", "logging", ".", "info", "(", "'Download all documents from index %s.'", ",", "self", ".", "index", ")", "if", "query", "is", "None", ...
Search the index with a query. Can at most return 10'000 results from a search. If the search would yield more than 10'000 hits, only the first 10'000 are returned. The default number of hits returned is 100.
[ "Search", "the", "index", "with", "a", "query", "." ]
python
train
fracpete/python-weka-wrapper3
python/weka/classifiers.py
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/classifiers.py#L988-L1006
def get_element(self, row, col, inst=None): """ Returns the value at the specified location. :param row: the 0-based index of the row :type row: int :param col: the 0-based index of the column :type col: int :param inst: the Instace :type inst: Instance :return: the value in that cell :rtype: float """ if inst is None: return javabridge.call( self.jobject, "getElement", "(II)D", row, col) else: return javabridge.call( self.jobject, "getElement", "(IILweka/core/Instance;)D", row, col, inst.jobject)
[ "def", "get_element", "(", "self", ",", "row", ",", "col", ",", "inst", "=", "None", ")", ":", "if", "inst", "is", "None", ":", "return", "javabridge", ".", "call", "(", "self", ".", "jobject", ",", "\"getElement\"", ",", "\"(II)D\"", ",", "row", ","...
Returns the value at the specified location. :param row: the 0-based index of the row :type row: int :param col: the 0-based index of the column :type col: int :param inst: the Instace :type inst: Instance :return: the value in that cell :rtype: float
[ "Returns", "the", "value", "at", "the", "specified", "location", "." ]
python
train
starofrainnight/rabird.core
rabird/core/distutils/__init__.py
https://github.com/starofrainnight/rabird.core/blob/477b48e24fa1aff6c63e0614c2ff86f12f54dfa4/rabird/core/distutils/__init__.py#L44-L168
def preprocess_source(base_dir=os.curdir): """ A special method for convert all source files to compatible with current python version during installation time. The source directory layout must like this : base_dir --+ | +-- src (All sources are placed into this directory) | +-- preprocessed (Preprocessed sources are placed into this | directory) | +-- setup.py | ... @return Preprocessed source directory """ source_path = os.path.join(base_dir, SOURCE_DIR) destination_path = os.path.join(base_dir, PREPROCESSED_DIR) # The 'build' and 'dist' folder sometimes will not update! So we need to # remove them all ! shutil.rmtree(os.path.join(base_dir, 'build'), ignore_errors=True) shutil.rmtree(os.path.join(base_dir, 'dist'), ignore_errors=True) # Remove all unused directories directories = [] directory_patterns = ['__pycache__', '*.egg-info'] for root, dirs, files in os.walk(destination_path): for adir in dirs: for pattern in directory_patterns: if fnmatch.fnmatch(adir, pattern): directories.append(os.path.join(root, adir)) break for adir in directories: shutil.rmtree(adir, ignore_errors=True) if sys.version_info[0] >= 3: # We wrote program implicated by version 3, if python version # large or equal than 3, we need not change the sources. return source_path # Check and prepare 3to2 module. try: from lib3to2.main import main as lib3to2_main except ImportError: try: from pip import main as pipmain except: from pip._internal import main as pipmain pipmain(['install', '3to2']) from lib3to2.main import main as lib3to2_main # Remove old preprocessed sources. if not os.path.exists(destination_path): __copy_tree(source_path, destination_path) lib3to2_main("lib3to2.fixes", ["-w", "-n", "--no-diffs"] + [destination_path]) else: # Remove all files that only in right side # Copy all files that only in left side to right side, then # 3to2 on these files files = [] dirs = [] cmp_result = filecmp.dircmp(source_path, destination_path) dirs.append(cmp_result) while len(dirs) > 0: # Get the last one compare result cmp_result = dirs[-1] del dirs[-1] # Append all sub-dirs compare results, so that we could # continue our loop. dirs.extend(list(cmp_result.subdirs.values())) # Remove all files that only in right side for file_name in cmp_result.right_only: file_path = os.path.join(cmp_result.right, file_name) if os.path.isdir(file_path): shutil.rmtree(file_path, ignore_errors=True) continue # Only parse files. try: os.remove(file_path) except: pass # Copy all files that only in left side to right side or # different files, then 3to2 on these files for file_name in (cmp_result.left_only + cmp_result.diff_files): left_file_path = os.path.join(cmp_result.left, file_name) right_file_path = os.path.join(cmp_result.right, file_name) if os.path.isdir(left_file_path): __copy_tree(left_file_path, right_file_path) files.append(right_file_path) continue if not fnmatch.fnmatch(file_name, "*.py"): continue try: os.remove(right_file_path) except: pass shutil.copy2(left_file_path, right_file_path) files.append(right_file_path) if len(files) > 0: lib3to2_main("lib3to2.fixes", ["-w", "-n", "--no-diffs"] + files) return destination_path
[ "def", "preprocess_source", "(", "base_dir", "=", "os", ".", "curdir", ")", ":", "source_path", "=", "os", ".", "path", ".", "join", "(", "base_dir", ",", "SOURCE_DIR", ")", "destination_path", "=", "os", ".", "path", ".", "join", "(", "base_dir", ",", ...
A special method for convert all source files to compatible with current python version during installation time. The source directory layout must like this : base_dir --+ | +-- src (All sources are placed into this directory) | +-- preprocessed (Preprocessed sources are placed into this | directory) | +-- setup.py | ... @return Preprocessed source directory
[ "A", "special", "method", "for", "convert", "all", "source", "files", "to", "compatible", "with", "current", "python", "version", "during", "installation", "time", ".", "The", "source", "directory", "layout", "must", "like", "this", ":", "base_dir", "--", "+",...
python
train
uber/tchannel-python
tchannel/tornado/response.py
https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/response.py#L172-L195
def write_header(self, chunk): """Write to header. Note: the header stream is only available to write before write body. :param chunk: content to write to header :except TChannelError: Raise TChannelError if the response's flush() has been called """ if self.serializer: header = self.serializer.serialize_header(chunk) else: header = chunk if self.flushed: raise TChannelError("write operation invalid after flush call") if (self.argstreams[0].state != StreamState.completed and self.argstreams[0].auto_close): self.argstreams[0].close() return self.argstreams[1].write(header)
[ "def", "write_header", "(", "self", ",", "chunk", ")", ":", "if", "self", ".", "serializer", ":", "header", "=", "self", ".", "serializer", ".", "serialize_header", "(", "chunk", ")", "else", ":", "header", "=", "chunk", "if", "self", ".", "flushed", "...
Write to header. Note: the header stream is only available to write before write body. :param chunk: content to write to header :except TChannelError: Raise TChannelError if the response's flush() has been called
[ "Write", "to", "header", "." ]
python
train
Qiskit/qiskit-terra
qiskit/qasm/node/gatebody.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qasm/node/gatebody.py#L31-L37
def calls(self): """Return a list of custom gate names in this gate body.""" lst = [] for children in self.children: if children.type == "custom_unitary": lst.append(children.name) return lst
[ "def", "calls", "(", "self", ")", ":", "lst", "=", "[", "]", "for", "children", "in", "self", ".", "children", ":", "if", "children", ".", "type", "==", "\"custom_unitary\"", ":", "lst", ".", "append", "(", "children", ".", "name", ")", "return", "ls...
Return a list of custom gate names in this gate body.
[ "Return", "a", "list", "of", "custom", "gate", "names", "in", "this", "gate", "body", "." ]
python
test
balloob/pychromecast
pychromecast/controllers/__init__.py
https://github.com/balloob/pychromecast/blob/831b09c4fed185a7bffe0ea330b7849d5f4e36b6/pychromecast/controllers/__init__.py#L46-L53
def registered(self, socket_client): """ Called when a controller is registered. """ self._socket_client = socket_client if self.target_platform: self._message_func = self._socket_client.send_platform_message else: self._message_func = self._socket_client.send_app_message
[ "def", "registered", "(", "self", ",", "socket_client", ")", ":", "self", ".", "_socket_client", "=", "socket_client", "if", "self", ".", "target_platform", ":", "self", ".", "_message_func", "=", "self", ".", "_socket_client", ".", "send_platform_message", "els...
Called when a controller is registered.
[ "Called", "when", "a", "controller", "is", "registered", "." ]
python
train
adamchainz/django-mysql
django_mysql/rewrite_query.py
https://github.com/adamchainz/django-mysql/blob/967daa4245cf55c9bc5dc018e560f417c528916a/django_mysql/rewrite_query.py#L115-L161
def modify_sql(sql, add_comments, add_hints, add_index_hints): """ Parse the start of the SQL, injecting each string in add_comments in individual SQL comments after the first keyword, and adding the named SELECT hints from add_hints, taking the latest in the list in cases of multiple mutually exclusive hints being given """ match = query_start_re.match(sql) if not match: # We don't understand what kind of query this is, don't rewrite it return sql tokens = [match.group('keyword')] comments = match.group('comments').strip() if comments: tokens.append(comments) # Inject comments after all existing comments for comment in add_comments: tokens.append('/*{}*/'.format(comment)) # Don't bother with SELECT rewrite rules on non-SELECT queries if tokens[0] == "SELECT": for group_name, hint_set in SELECT_HINTS.items(): try: # Take the last hint we were told to add from this hint_set to_add = [hint for hint in add_hints if hint in hint_set][-1] tokens.append(to_add) except IndexError: # We weren't told to add any, so just add any hint from this # set that was already there existing = match.group(group_name) if existing is not None: tokens.append(existing.rstrip()) # Maybe rewrite the remainder of the statement for index hints remainder = sql[match.end():] if tokens[0] == "SELECT" and add_index_hints: for index_hint in add_index_hints: remainder = modify_sql_index_hints(remainder, *index_hint) # Join everything tokens.append(remainder) return ' '.join(tokens)
[ "def", "modify_sql", "(", "sql", ",", "add_comments", ",", "add_hints", ",", "add_index_hints", ")", ":", "match", "=", "query_start_re", ".", "match", "(", "sql", ")", "if", "not", "match", ":", "# We don't understand what kind of query this is, don't rewrite it", ...
Parse the start of the SQL, injecting each string in add_comments in individual SQL comments after the first keyword, and adding the named SELECT hints from add_hints, taking the latest in the list in cases of multiple mutually exclusive hints being given
[ "Parse", "the", "start", "of", "the", "SQL", "injecting", "each", "string", "in", "add_comments", "in", "individual", "SQL", "comments", "after", "the", "first", "keyword", "and", "adding", "the", "named", "SELECT", "hints", "from", "add_hints", "taking", "the...
python
train
Azure/azure-sdk-for-python
azure-mgmt-storage/azure/mgmt/storage/storage_management_client.py
https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-mgmt-storage/azure/mgmt/storage/storage_management_client.py#L242-L273
def storage_accounts(self): """Instance depends on the API version: * 2015-06-15: :class:`StorageAccountsOperations<azure.mgmt.storage.v2015_06_15.operations.StorageAccountsOperations>` * 2016-01-01: :class:`StorageAccountsOperations<azure.mgmt.storage.v2016_01_01.operations.StorageAccountsOperations>` * 2016-12-01: :class:`StorageAccountsOperations<azure.mgmt.storage.v2016_12_01.operations.StorageAccountsOperations>` * 2017-06-01: :class:`StorageAccountsOperations<azure.mgmt.storage.v2017_06_01.operations.StorageAccountsOperations>` * 2017-10-01: :class:`StorageAccountsOperations<azure.mgmt.storage.v2017_10_01.operations.StorageAccountsOperations>` * 2018-02-01: :class:`StorageAccountsOperations<azure.mgmt.storage.v2018_02_01.operations.StorageAccountsOperations>` * 2018-03-01-preview: :class:`StorageAccountsOperations<azure.mgmt.storage.v2018_03_01_preview.operations.StorageAccountsOperations>` * 2018-07-01: :class:`StorageAccountsOperations<azure.mgmt.storage.v2018_07_01.operations.StorageAccountsOperations>` """ api_version = self._get_api_version('storage_accounts') if api_version == '2015-06-15': from .v2015_06_15.operations import StorageAccountsOperations as OperationClass elif api_version == '2016-01-01': from .v2016_01_01.operations import StorageAccountsOperations as OperationClass elif api_version == '2016-12-01': from .v2016_12_01.operations import StorageAccountsOperations as OperationClass elif api_version == '2017-06-01': from .v2017_06_01.operations import StorageAccountsOperations as OperationClass elif api_version == '2017-10-01': from .v2017_10_01.operations import StorageAccountsOperations as OperationClass elif api_version == '2018-02-01': from .v2018_02_01.operations import StorageAccountsOperations as OperationClass elif api_version == '2018-03-01-preview': from .v2018_03_01_preview.operations import StorageAccountsOperations as OperationClass elif api_version == '2018-07-01': from .v2018_07_01.operations import StorageAccountsOperations as OperationClass else: raise NotImplementedError("APIVersion {} is not available".format(api_version)) return OperationClass(self._client, self.config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)))
[ "def", "storage_accounts", "(", "self", ")", ":", "api_version", "=", "self", ".", "_get_api_version", "(", "'storage_accounts'", ")", "if", "api_version", "==", "'2015-06-15'", ":", "from", ".", "v2015_06_15", ".", "operations", "import", "StorageAccountsOperations...
Instance depends on the API version: * 2015-06-15: :class:`StorageAccountsOperations<azure.mgmt.storage.v2015_06_15.operations.StorageAccountsOperations>` * 2016-01-01: :class:`StorageAccountsOperations<azure.mgmt.storage.v2016_01_01.operations.StorageAccountsOperations>` * 2016-12-01: :class:`StorageAccountsOperations<azure.mgmt.storage.v2016_12_01.operations.StorageAccountsOperations>` * 2017-06-01: :class:`StorageAccountsOperations<azure.mgmt.storage.v2017_06_01.operations.StorageAccountsOperations>` * 2017-10-01: :class:`StorageAccountsOperations<azure.mgmt.storage.v2017_10_01.operations.StorageAccountsOperations>` * 2018-02-01: :class:`StorageAccountsOperations<azure.mgmt.storage.v2018_02_01.operations.StorageAccountsOperations>` * 2018-03-01-preview: :class:`StorageAccountsOperations<azure.mgmt.storage.v2018_03_01_preview.operations.StorageAccountsOperations>` * 2018-07-01: :class:`StorageAccountsOperations<azure.mgmt.storage.v2018_07_01.operations.StorageAccountsOperations>`
[ "Instance", "depends", "on", "the", "API", "version", ":" ]
python
test
earwig/mwparserfromhell
mwparserfromhell/parser/tokenizer.py
https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L294-L299
def _handle_template_param_value(self): """Handle a template parameter's value at the head of the string.""" self._emit_all(self._pop()) self._context ^= contexts.TEMPLATE_PARAM_KEY self._context |= contexts.TEMPLATE_PARAM_VALUE self._emit(tokens.TemplateParamEquals())
[ "def", "_handle_template_param_value", "(", "self", ")", ":", "self", ".", "_emit_all", "(", "self", ".", "_pop", "(", ")", ")", "self", ".", "_context", "^=", "contexts", ".", "TEMPLATE_PARAM_KEY", "self", ".", "_context", "|=", "contexts", ".", "TEMPLATE_P...
Handle a template parameter's value at the head of the string.
[ "Handle", "a", "template", "parameter", "s", "value", "at", "the", "head", "of", "the", "string", "." ]
python
train
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/handlers.py
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/handlers.py#L1683-L1698
def _get_required_param(self, param_name): """Get a required request parameter. Args: param_name: name of request parameter to fetch. Returns: parameter value Raises: errors.NotEnoughArgumentsError: if parameter is not specified. """ value = self.request.get(param_name) if not value: raise errors.NotEnoughArgumentsError(param_name + " not specified") return value
[ "def", "_get_required_param", "(", "self", ",", "param_name", ")", ":", "value", "=", "self", ".", "request", ".", "get", "(", "param_name", ")", "if", "not", "value", ":", "raise", "errors", ".", "NotEnoughArgumentsError", "(", "param_name", "+", "\" not sp...
Get a required request parameter. Args: param_name: name of request parameter to fetch. Returns: parameter value Raises: errors.NotEnoughArgumentsError: if parameter is not specified.
[ "Get", "a", "required", "request", "parameter", "." ]
python
train
mar10/wsgidav
wsgidav/fs_dav_provider.py
https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/fs_dav_provider.py#L100-L109
def delete(self): """Remove this resource or collection (recursive). See DAVResource.delete() """ if self.provider.readonly: raise DAVError(HTTP_FORBIDDEN) os.unlink(self._file_path) self.remove_all_properties(True) self.remove_all_locks(True)
[ "def", "delete", "(", "self", ")", ":", "if", "self", ".", "provider", ".", "readonly", ":", "raise", "DAVError", "(", "HTTP_FORBIDDEN", ")", "os", ".", "unlink", "(", "self", ".", "_file_path", ")", "self", ".", "remove_all_properties", "(", "True", ")"...
Remove this resource or collection (recursive). See DAVResource.delete()
[ "Remove", "this", "resource", "or", "collection", "(", "recursive", ")", "." ]
python
valid
edibledinos/pwnypack
pwnypack/flow.py
https://github.com/edibledinos/pwnypack/blob/e0a5a8e6ef3f4f1f7e1b91ee379711f4a49cb0e6/pwnypack/flow.py#L426-L447
def read_until(self, s, echo=None): """ Read until a certain string is encountered.. Args: s(bytes): The string to wait for. echo(bool): Whether to write the read data to stdout. Returns: bytes: The data up to and including *s*. Raises: EOFError: If the channel was closed. """ s_len = len(s) buf = self.read(s_len, echo) while buf[-s_len:] != s: buf += self.read(1, echo) return buf
[ "def", "read_until", "(", "self", ",", "s", ",", "echo", "=", "None", ")", ":", "s_len", "=", "len", "(", "s", ")", "buf", "=", "self", ".", "read", "(", "s_len", ",", "echo", ")", "while", "buf", "[", "-", "s_len", ":", "]", "!=", "s", ":", ...
Read until a certain string is encountered.. Args: s(bytes): The string to wait for. echo(bool): Whether to write the read data to stdout. Returns: bytes: The data up to and including *s*. Raises: EOFError: If the channel was closed.
[ "Read", "until", "a", "certain", "string", "is", "encountered", ".." ]
python
train
mbedmicro/pyOCD
pyocd/probe/stlink_probe.py
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/probe/stlink_probe.py#L122-L129
def disconnect(self): """! @brief Deinitialize the DAP I/O pins""" # TODO Close the APs. When this is attempted, we get an undocumented 0x1d error. Doesn't # seem to be necessary, anyway. self._memory_interfaces = {} self._link.enter_idle() self._is_connected = False
[ "def", "disconnect", "(", "self", ")", ":", "# TODO Close the APs. When this is attempted, we get an undocumented 0x1d error. Doesn't", "# seem to be necessary, anyway.", "self", ".", "_memory_interfaces", "=", "{", "}", "self", ".", "_link", ".", "enter_idle", "(", ")",...
! @brief Deinitialize the DAP I/O pins
[ "!" ]
python
train
ltworf/typedload
typedload/dataloader.py
https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/dataloader.py#L268-L278
def _listload(l: Loader, value, type_) -> List: """ This loads into something like List[int] """ t = type_.__args__[0] try: return [l.load(v, t, annotation=Annotation(AnnotationType.INDEX, i)) for i, v in enumerate(value)] except TypeError as e: if isinstance(e, TypedloadException): raise raise TypedloadTypeError(str(e), value=value, type_=type_)
[ "def", "_listload", "(", "l", ":", "Loader", ",", "value", ",", "type_", ")", "->", "List", ":", "t", "=", "type_", ".", "__args__", "[", "0", "]", "try", ":", "return", "[", "l", ".", "load", "(", "v", ",", "t", ",", "annotation", "=", "Annota...
This loads into something like List[int]
[ "This", "loads", "into", "something", "like", "List", "[", "int", "]" ]
python
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py#L176-L196
def __detect_cl_tool(env, chainkey, cdict, cpriority=None): """ Helper function, picks a command line tool from the list and initializes its environment variables. """ if env.get(chainkey,'') == '': clpath = '' if cpriority is None: cpriority = cdict.keys() for cltool in cpriority: if __debug_tool_location: print("DocBook: Looking for %s"%cltool) clpath = env.WhereIs(cltool) if clpath: if __debug_tool_location: print("DocBook: Found:%s"%cltool) env[chainkey] = clpath if not env[chainkey + 'COM']: env[chainkey + 'COM'] = cdict[cltool] break
[ "def", "__detect_cl_tool", "(", "env", ",", "chainkey", ",", "cdict", ",", "cpriority", "=", "None", ")", ":", "if", "env", ".", "get", "(", "chainkey", ",", "''", ")", "==", "''", ":", "clpath", "=", "''", "if", "cpriority", "is", "None", ":", "cp...
Helper function, picks a command line tool from the list and initializes its environment variables.
[ "Helper", "function", "picks", "a", "command", "line", "tool", "from", "the", "list", "and", "initializes", "its", "environment", "variables", "." ]
python
train
dlecocq/nsq-py
nsq/checker.py
https://github.com/dlecocq/nsq-py/blob/3ecacf6ab7719d38031179277113d875554a0c16/nsq/checker.py#L34-L38
def delay(self): '''How long to wait before the next check''' if self._last_checked: return self._interval - (time.time() - self._last_checked) return self._interval
[ "def", "delay", "(", "self", ")", ":", "if", "self", ".", "_last_checked", ":", "return", "self", ".", "_interval", "-", "(", "time", ".", "time", "(", ")", "-", "self", ".", "_last_checked", ")", "return", "self", ".", "_interval" ]
How long to wait before the next check
[ "How", "long", "to", "wait", "before", "the", "next", "check" ]
python
train
assemblerflow/flowcraft
flowcraft/templates/fastqc.py
https://github.com/assemblerflow/flowcraft/blob/fc3f4bddded1efc76006600016dc71a06dd908c0/flowcraft/templates/fastqc.py#L81-L129
def convert_adatpers(adapter_fasta): """Generates an adapter file for FastQC from a fasta file. The provided adapters file is assumed to be a simple fasta file with the adapter's name as header and the corresponding sequence:: >TruSeq_Universal_Adapter AATGATACGGCGACCACCGAGATCTACACTCTTTCCCTACACGACGCTCTTCCGATCT >TruSeq_Adapter_Index 1 GATCGGAAGAGCACACGTCTGAACTCCAGTCACATCACGATCTCGTATGCCGTCTTCTGCTTG Parameters ---------- adapter_fasta : str Path to Fasta file with adapter sequences. Returns ------- adapter_out : str or None The path to the reformatted adapter file. Returns ``None`` if the adapters file does not exist or the path is incorrect. """ adapter_out = "fastqc_adapters.tab" logger.debug("Setting output adapters file to: {}".format(adapter_out)) try: with open(adapter_fasta) as fh, \ open(adapter_out, "w") as adap_fh: for line in fh: if line.startswith(">"): head = line[1:].strip() # Get the next line with the sequence string sequence = next(fh).strip() adap_fh.write("{}\\t{}\\n".format(head, sequence)) logger.info("Converted adapters file") return adapter_out # If an invalid adapters file is provided, return None. except FileNotFoundError: logger.warning("Could not find the provided adapters file: {}".format( adapter_fasta)) return
[ "def", "convert_adatpers", "(", "adapter_fasta", ")", ":", "adapter_out", "=", "\"fastqc_adapters.tab\"", "logger", ".", "debug", "(", "\"Setting output adapters file to: {}\"", ".", "format", "(", "adapter_out", ")", ")", "try", ":", "with", "open", "(", "adapter_f...
Generates an adapter file for FastQC from a fasta file. The provided adapters file is assumed to be a simple fasta file with the adapter's name as header and the corresponding sequence:: >TruSeq_Universal_Adapter AATGATACGGCGACCACCGAGATCTACACTCTTTCCCTACACGACGCTCTTCCGATCT >TruSeq_Adapter_Index 1 GATCGGAAGAGCACACGTCTGAACTCCAGTCACATCACGATCTCGTATGCCGTCTTCTGCTTG Parameters ---------- adapter_fasta : str Path to Fasta file with adapter sequences. Returns ------- adapter_out : str or None The path to the reformatted adapter file. Returns ``None`` if the adapters file does not exist or the path is incorrect.
[ "Generates", "an", "adapter", "file", "for", "FastQC", "from", "a", "fasta", "file", "." ]
python
test
fitnr/convertdate
convertdate/indian_civil.py
https://github.com/fitnr/convertdate/blob/e920f168a87f99183b0aa7290d6c3af222582d43/convertdate/indian_civil.py#L47-L74
def to_jd(year, month, day): '''Obtain Julian day for Indian Civil date''' gyear = year + 78 leap = isleap(gyear) # // Is this a leap year ? # 22 - leap = 21 if leap, 22 non-leap start = gregorian.to_jd(gyear, 3, 22 - leap) if leap: Caitra = 31 else: Caitra = 30 if month == 1: jd = start + (day - 1) else: jd = start + Caitra m = month - 2 m = min(m, 5) jd += m * 31 if month >= 8: m = month - 7 jd += m * 30 jd += day - 1 return jd
[ "def", "to_jd", "(", "year", ",", "month", ",", "day", ")", ":", "gyear", "=", "year", "+", "78", "leap", "=", "isleap", "(", "gyear", ")", "# // Is this a leap year ?", "# 22 - leap = 21 if leap, 22 non-leap", "start", "=", "gregorian", ".", "to_jd", "(", "...
Obtain Julian day for Indian Civil date
[ "Obtain", "Julian", "day", "for", "Indian", "Civil", "date" ]
python
train
mromanello/hucitlib
knowledge_base/surfext/__init__.py
https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L185-L199
def get_urn(self): """ Assumes that each HucitAuthor has only one CTS URN. """ # TODO: check type try: type_ctsurn = self.session.get_resource(BASE_URI_TYPES % "CTS_URN" , self.session.get_class(surf.ns.ECRM['E55_Type'])) urn = [CTS_URN(urnstring.rdfs_label.one) for urnstring in self.ecrm_P1_is_identified_by if urnstring.uri == surf.ns.ECRM['E42_Identifier'] and urnstring.ecrm_P2_has_type.first == type_ctsurn][0] return urn except Exception as e: return None
[ "def", "get_urn", "(", "self", ")", ":", "# TODO: check type", "try", ":", "type_ctsurn", "=", "self", ".", "session", ".", "get_resource", "(", "BASE_URI_TYPES", "%", "\"CTS_URN\"", ",", "self", ".", "session", ".", "get_class", "(", "surf", ".", "ns", "....
Assumes that each HucitAuthor has only one CTS URN.
[ "Assumes", "that", "each", "HucitAuthor", "has", "only", "one", "CTS", "URN", "." ]
python
train
kubernetes-client/python
kubernetes/client/apis/autoscaling_v2beta1_api.py
https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/autoscaling_v2beta1_api.py#L1341-L1365
def replace_namespaced_horizontal_pod_autoscaler_status(self, name, namespace, body, **kwargs): """ replace status of the specified HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_horizontal_pod_autoscaler_status(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the HorizontalPodAutoscaler (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V2beta1HorizontalPodAutoscaler body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :return: V2beta1HorizontalPodAutoscaler If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.replace_namespaced_horizontal_pod_autoscaler_status_with_http_info(name, namespace, body, **kwargs) else: (data) = self.replace_namespaced_horizontal_pod_autoscaler_status_with_http_info(name, namespace, body, **kwargs) return data
[ "def", "replace_namespaced_horizontal_pod_autoscaler_status", "(", "self", ",", "name", ",", "namespace", ",", "body", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'",...
replace status of the specified HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_horizontal_pod_autoscaler_status(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the HorizontalPodAutoscaler (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V2beta1HorizontalPodAutoscaler body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :return: V2beta1HorizontalPodAutoscaler If the method is called asynchronously, returns the request thread.
[ "replace", "status", "of", "the", "specified", "HorizontalPodAutoscaler", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "pass", "async_req", "=", "True", "...
python
train
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L666-L693
def _remove_overlap_sub(self, also_remove_contiguous: bool) -> bool: """ Called by :meth:`remove_overlap`. Removes the first overlap found. Args: also_remove_contiguous: treat contiguous (as well as overlapping) intervals as worthy of merging? Returns: bool: ``True`` if an overlap was removed; ``False`` otherwise """ # Returns for i in range(len(self.intervals)): for j in range(i + 1, len(self.intervals)): first = self.intervals[i] second = self.intervals[j] if also_remove_contiguous: test = first.contiguous(second) else: test = first.overlaps(second) if test: newint = first.union(second) self.intervals.pop(j) self.intervals.pop(i) # note that i must be less than j self.intervals.append(newint) return True return False
[ "def", "_remove_overlap_sub", "(", "self", ",", "also_remove_contiguous", ":", "bool", ")", "->", "bool", ":", "# Returns", "for", "i", "in", "range", "(", "len", "(", "self", ".", "intervals", ")", ")", ":", "for", "j", "in", "range", "(", "i", "+", ...
Called by :meth:`remove_overlap`. Removes the first overlap found. Args: also_remove_contiguous: treat contiguous (as well as overlapping) intervals as worthy of merging? Returns: bool: ``True`` if an overlap was removed; ``False`` otherwise
[ "Called", "by", ":", "meth", ":", "remove_overlap", ".", "Removes", "the", "first", "overlap", "found", "." ]
python
train
phaethon/kamene
kamene/contrib/gsm_um.py
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2628-L2644
def activatePdpContextRequest(AccessPointName_presence=0, ProtocolConfigurationOptions_presence=0): """ACTIVATE PDP CONTEXT REQUEST Section 9.5.1""" a = TpPd(pd=0x8) b = MessageType(mesType=0x41) # 01000001 c = NetworkServiceAccessPointIdentifier() d = LlcServiceAccessPointIdentifier() e = QualityOfService() f = PacketDataProtocolAddress() packet = a / b / c / d / e / f if AccessPointName_presence is 1: g = AccessPointName(ieiAPN=0x28) packet = packet / g if ProtocolConfigurationOptions_presence is 1: h = ProtocolConfigurationOptions(ieiPCO=0x27) packet = packet / h return packet
[ "def", "activatePdpContextRequest", "(", "AccessPointName_presence", "=", "0", ",", "ProtocolConfigurationOptions_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x8", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x41", ")", "# 0100000...
ACTIVATE PDP CONTEXT REQUEST Section 9.5.1
[ "ACTIVATE", "PDP", "CONTEXT", "REQUEST", "Section", "9", ".", "5", ".", "1" ]
python
train