positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def bind_protocol(self, proto): """Tries to bind given protocol to this peer. Should only be called by `proto` trying to bind. Once bound this protocol instance will be used to communicate with peer. If another protocol is already bound, connection collision resolution takes place. """ LOG.debug('Trying to bind protocol %s to peer %s', proto, self) # Validate input. if not isinstance(proto, BgpProtocol): raise ValueError('Currently only supports valid instances of' ' `BgpProtocol`') if proto.state != const.BGP_FSM_OPEN_CONFIRM: raise ValueError('Only protocols in OpenConfirm state can be' ' bound') # If we are not bound to any protocol is_bound = False if not self._protocol: self._set_protocol(proto) is_bound = True else: # If existing protocol is already established, we raise exception. if self.state.bgp_state != const.BGP_FSM_IDLE: LOG.debug('Currently in %s state, hence will send collision' ' Notification to close this protocol.', self.state.bgp_state) self._send_collision_err_and_stop(proto) return # If we have a collision that need to be resolved assert proto.is_colliding(self._protocol), \ ('Tried to bind second protocol that is not colliding with ' 'first/bound protocol') LOG.debug('Currently have one protocol in %s state and ' 'another protocol in %s state', self._protocol.state, proto.state) # Protocol that is already bound first_protocol = self._protocol assert ((first_protocol.is_reactive and not proto.is_reactive) or (proto.is_reactive and not first_protocol.is_reactive)) # Connection initiated by peer. reactive_proto = None # Connection initiated locally. proactive_proto = None # Identify which protocol was initiated by which peer. if proto.is_reactive: reactive_proto = proto proactive_proto = self._protocol else: reactive_proto = self._protocol proactive_proto = proto LOG.debug('Pro-active/Active protocol %s', proactive_proto) # We compare bgp local and remote router id and keep the protocol # that was initiated by peer with highest id. if proto.is_local_router_id_greater(): self._set_protocol(proactive_proto) else: self._set_protocol(reactive_proto) if self._protocol is not proto: # If new proto did not win collision we return False to # indicate this. is_bound = False else: # If first protocol did not win collision resolution we # we send notification to peer and stop it self._send_collision_err_and_stop(first_protocol) is_bound = True return is_bound
Tries to bind given protocol to this peer. Should only be called by `proto` trying to bind. Once bound this protocol instance will be used to communicate with peer. If another protocol is already bound, connection collision resolution takes place.
def get_beam(header): """ Create a :class:`AegeanTools.fits_image.Beam` object from a fits header. BPA may be missing but will be assumed to be zero. if BMAJ or BMIN are missing then return None instead of a beam object. Parameters ---------- header : HDUHeader The fits header. Returns ------- beam : :class:`AegeanTools.fits_image.Beam` Beam object, with a, b, and pa in degrees. """ if "BPA" not in header: log.warning("BPA not present in fits header, using 0") bpa = 0 else: bpa = header["BPA"] if "BMAJ" not in header: log.warning("BMAJ not present in fits header.") bmaj = None else: bmaj = header["BMAJ"] if "BMIN" not in header: log.warning("BMIN not present in fits header.") bmin = None else: bmin = header["BMIN"] if None in [bmaj, bmin, bpa]: return None beam = Beam(bmaj, bmin, bpa) return beam
Create a :class:`AegeanTools.fits_image.Beam` object from a fits header. BPA may be missing but will be assumed to be zero. if BMAJ or BMIN are missing then return None instead of a beam object. Parameters ---------- header : HDUHeader The fits header. Returns ------- beam : :class:`AegeanTools.fits_image.Beam` Beam object, with a, b, and pa in degrees.
def get_collaborator_permission(self, collaborator): """ :calls: `GET /repos/:owner/:repo/collaborators/:username/permission <http://developer.github.com/v3/repos/collaborators>`_ :param collaborator: string or :class:`github.NamedUser.NamedUser` :rtype: string """ assert isinstance(collaborator, github.NamedUser.NamedUser) or isinstance(collaborator, (str, unicode)), collaborator if isinstance(collaborator, github.NamedUser.NamedUser): collaborator = collaborator._identity headers, data = self._requester.requestJsonAndCheck( "GET", self.url + "/collaborators/" + collaborator + "/permission", ) return data["permission"]
:calls: `GET /repos/:owner/:repo/collaborators/:username/permission <http://developer.github.com/v3/repos/collaborators>`_ :param collaborator: string or :class:`github.NamedUser.NamedUser` :rtype: string
def parse_channels(self): """Creates an array of Channel objects from the project""" channels = [] for channel in self._project_dict["channels"]: channels.append(Channel(channel, self._is_sixteen_bit, self._ignore_list)) return channels
Creates an array of Channel objects from the project
def _doIdRes(self, message, endpoint, return_to): """Handle id_res responses that are not cancellations of immediate mode requests. @param message: the response paramaters. @param endpoint: the discovered endpoint object. May be None. @raises ProtocolError: If the message contents are not well-formed according to the OpenID specification. This includes missing fields or not signing fields that should be signed. @raises DiscoveryFailure: If the subject of the id_res message does not match the supplied endpoint, and discovery on the identifier in the message fails (this should only happen when using OpenID 2) @returntype: L{Response} """ # Checks for presence of appropriate fields (and checks # signed list fields) self._idResCheckForFields(message) if not self._checkReturnTo(message, return_to): raise ProtocolError( "return_to does not match return URL. Expected %r, got %r" % (return_to, message.getArg(OPENID_NS, 'return_to'))) # Verify discovery information: endpoint = self._verifyDiscoveryResults(message, endpoint) logging.info("Received id_res response from %s using association %s" % (endpoint.server_url, message.getArg(OPENID_NS, 'assoc_handle'))) self._idResCheckSignature(message, endpoint.server_url) # Will raise a ProtocolError if the nonce is bad self._idResCheckNonce(message, endpoint) signed_list_str = message.getArg(OPENID_NS, 'signed', no_default) signed_list = signed_list_str.split(',') signed_fields = ["openid." + s for s in signed_list] return SuccessResponse(endpoint, message, signed_fields)
Handle id_res responses that are not cancellations of immediate mode requests. @param message: the response paramaters. @param endpoint: the discovered endpoint object. May be None. @raises ProtocolError: If the message contents are not well-formed according to the OpenID specification. This includes missing fields or not signing fields that should be signed. @raises DiscoveryFailure: If the subject of the id_res message does not match the supplied endpoint, and discovery on the identifier in the message fails (this should only happen when using OpenID 2) @returntype: L{Response}
def login(self): """ Perform cookie based user login. """ resp = super(CookieSession, self).request( 'POST', self._session_url, data={'name': self._username, 'password': self._password}, ) resp.raise_for_status()
Perform cookie based user login.
def output_folder(self, value): """Output folder path for the rendering. :param value: output folder path :type value: str """ self._output_folder = value if not os.path.exists(self._output_folder): os.makedirs(self._output_folder)
Output folder path for the rendering. :param value: output folder path :type value: str
def handle_api_exceptions(self, method, *url_parts, **kwargs): """Call REST API and handle exceptions Params: method: 'HEAD', 'GET', 'POST', 'PATCH' or 'DELETE' url_parts: like in rest_api_url() method api_ver: like in rest_api_url() method kwargs: other parameters passed to requests.request, but the only notable parameter is: (... json=data) that works like (... headers = {'Content-Type': 'application/json'}, data=json.dumps(data)) """ # The outer part - about error handler assert method in ('HEAD', 'GET', 'POST', 'PATCH', 'DELETE') cursor_context = kwargs.pop('cursor_context', None) errorhandler = cursor_context.errorhandler if cursor_context else self.errorhandler catched_exceptions = (SalesforceError, requests.exceptions.RequestException) if errorhandler else () try: return self.handle_api_exceptions_inter(method, *url_parts, **kwargs) except catched_exceptions: # nothing is catched usually and error handler not used exc_class, exc_value, _ = sys.exc_info() errorhandler(self, cursor_context, exc_class, exc_value) raise
Call REST API and handle exceptions Params: method: 'HEAD', 'GET', 'POST', 'PATCH' or 'DELETE' url_parts: like in rest_api_url() method api_ver: like in rest_api_url() method kwargs: other parameters passed to requests.request, but the only notable parameter is: (... json=data) that works like (... headers = {'Content-Type': 'application/json'}, data=json.dumps(data))
def to_file(self, filepath=None): """Writes Torrent object into file, either :param filepath: """ if filepath is None and self._filepath is None: raise TorrentError('Unable to save torrent to file: no filepath supplied.') if filepath is not None: self._filepath = filepath with open(self._filepath, mode='wb') as f: f.write(self.to_string())
Writes Torrent object into file, either :param filepath:
def restore_used_registers(self): """Pops all used working registers after function call""" used = self.used_registers_stack.pop() self.used_registers = used[:] used.sort(reverse = True) for reg in used: self.newline_text("POP \t%s" % SharedData.REGISTERS[reg], True) self.free_registers.remove(reg)
Pops all used working registers after function call
def _to_spans(x): """Convert a Candidate, Mention, or Span to a list of spans.""" if isinstance(x, Candidate): return [_to_span(m) for m in x] elif isinstance(x, Mention): return [x.context] elif isinstance(x, TemporarySpanMention): return [x] else: raise ValueError(f"{type(x)} is an invalid argument type")
Convert a Candidate, Mention, or Span to a list of spans.
def ptb_producer(raw_data, batch_size, num_steps, name=None): """Iterate on the raw PTB data. This chunks up raw_data into batches of examples and returns Tensors that are drawn from these batches. Args: raw_data: one of the raw data outputs from ptb_raw_data. batch_size: int, the batch size. num_steps: int, the number of unrolls. name: the name of this operation (optional). Returns: A pair of Tensors, each shaped [batch_size, num_steps]. The second element of the tuple is the same data time-shifted to the right by one. Raises: tf.errors.InvalidArgumentError: if batch_size or num_steps are too high. """ with tf.name_scope(name, "PTBProducer", [raw_data, batch_size, num_steps]): raw_data = tf.convert_to_tensor(raw_data, name="raw_data", dtype=tf.int32) data_len = tf.size(raw_data) batch_len = data_len // batch_size data = tf.reshape(raw_data[0 : batch_size * batch_len], [batch_size, batch_len]) epoch_size = (batch_len - 1) // num_steps assertion = tf.assert_positive( epoch_size, message="epoch_size == 0, decrease batch_size or num_steps") with tf.control_dependencies([assertion]): epoch_size = tf.identity(epoch_size, name="epoch_size") i = tf.train.range_input_producer(epoch_size, shuffle=False).dequeue() x = tf.strided_slice(data, [0, i * num_steps], [batch_size, (i + 1) * num_steps]) x.set_shape([batch_size, num_steps]) y = tf.strided_slice(data, [0, i * num_steps + 1], [batch_size, (i + 1) * num_steps + 1]) y.set_shape([batch_size, num_steps]) return x, y
Iterate on the raw PTB data. This chunks up raw_data into batches of examples and returns Tensors that are drawn from these batches. Args: raw_data: one of the raw data outputs from ptb_raw_data. batch_size: int, the batch size. num_steps: int, the number of unrolls. name: the name of this operation (optional). Returns: A pair of Tensors, each shaped [batch_size, num_steps]. The second element of the tuple is the same data time-shifted to the right by one. Raises: tf.errors.InvalidArgumentError: if batch_size or num_steps are too high.
def prepare_hmet_lsm(self, lsm_data_var_map_array, hmet_ascii_output_folder=None, netcdf_file_path=None): """ Prepares HMET data for GSSHA simulation from land surface model data. Parameters: lsm_data_var_map_array(str): Array with connections for LSM output and GSSHA input. See: :func:`~gsshapy.grid.GRIDtoGSSHA.` hmet_ascii_output_folder(Optional[str]): Path to diretory to output HMET ASCII files. Mutually exclusice with netcdf_file_path. Default is None. netcdf_file_path(Optional[str]): If you want the HMET data output as a NetCDF4 file for input to GSSHA. Mutually exclusice with hmet_ascii_output_folder. Default is None. """ if self.l2g is None: raise ValueError("LSM converter not loaded ...") with tmp_chdir(self.project_manager.project_directory): # GSSHA simulation does not work after HMET data is finished self._update_simulation_end_from_lsm() # HMET CARDS if netcdf_file_path is not None: self.l2g.lsm_data_to_subset_netcdf(netcdf_file_path, lsm_data_var_map_array) self._update_card("HMET_NETCDF", netcdf_file_path, True) self.project_manager.deleteCard('HMET_ASCII', self.db_session) else: if "{0}" in hmet_ascii_output_folder and "{1}" in hmet_ascii_output_folder: hmet_ascii_output_folder = hmet_ascii_output_folder.format(self.simulation_start.strftime("%Y%m%d%H%M"), self.simulation_end.strftime("%Y%m%d%H%M")) self.l2g.lsm_data_to_arc_ascii(lsm_data_var_map_array, main_output_folder=os.path.join(self.gssha_directory, hmet_ascii_output_folder)) self._update_card("HMET_ASCII", os.path.join(hmet_ascii_output_folder, 'hmet_file_list.txt'), True) self.project_manager.deleteCard('HMET_NETCDF', self.db_session) # UPDATE GMT CARD self._update_gmt()
Prepares HMET data for GSSHA simulation from land surface model data. Parameters: lsm_data_var_map_array(str): Array with connections for LSM output and GSSHA input. See: :func:`~gsshapy.grid.GRIDtoGSSHA.` hmet_ascii_output_folder(Optional[str]): Path to diretory to output HMET ASCII files. Mutually exclusice with netcdf_file_path. Default is None. netcdf_file_path(Optional[str]): If you want the HMET data output as a NetCDF4 file for input to GSSHA. Mutually exclusice with hmet_ascii_output_folder. Default is None.
def _help_menu(self): """F1""" if self.help_menu is False: self.focus_pos_saved = self.top.body.focus_position help_men = "\n".join(["{} - {}".format(i, j.__name__.strip('_')) for i, j in self.keys.items() if j.__name__ != '_digits']) help_men = "KEYBINDINGS\n" + help_men + "\n<0-9> - Jump to item" docs = ("OPTIONS\n" "all_escape -- toggle unescape all URLs\n" "all_shorten -- toggle shorten all URLs\n" "bottom -- move cursor to last item\n" "clear_screen -- redraw screen\n" "clipboard -- copy highlighted URL to clipboard using xsel/xclip\n" "clipboard_pri -- copy highlighted URL to primary selection using xsel/xclip\n" "config_create -- create ~/.config/urlscan/config.json\n" "context -- show/hide context\n" "down -- cursor down\n" "help_menu -- show/hide help menu\n" "open_url -- open selected URL\n" "palette -- cycle through palettes\n" "quit -- quit\n" "shorten -- toggle shorten highlighted URL\n" "top -- move to first list item\n" "up -- cursor up\n") self.top.body = \ urwid.ListBox(urwid.SimpleListWalker([urwid.Columns([(30, urwid.Text(help_men)), urwid.Text(docs)])])) else: self.top.body = urwid.ListBox(self.items) self.top.body.focus_position = self.focus_pos_saved self.help_menu = not self.help_menu
F1
def run_validators(new_data, old_data): """ Run through all matching validators. :param new_data: New lint data. :param old_data: Old lint data (before review) :return: """ #{'validator_name': (success, score, message)} validation_data = {} for file_type, lint_data in list(new_data.items()): #TODO: What to do if old data doesn't have this filetype? old_lint_data = old_data.get(file_type, {}) validator = ValidatorFactory.get_validator(file_type) if validator is not None: validation_data[validator.name] = validator.run(lint_data, old_lint_data) return validation_data
Run through all matching validators. :param new_data: New lint data. :param old_data: Old lint data (before review) :return:
def is_early_compact_l2a(self): """Check if product is early version of compact L2A product :return: True if product is early version of compact L2A product and False otherwise :rtype: bool """ return self.data_source is DataSource.SENTINEL2_L2A and self.safe_type is EsaSafeType.COMPACT_TYPE and \ self.baseline <= '02.06'
Check if product is early version of compact L2A product :return: True if product is early version of compact L2A product and False otherwise :rtype: bool
def export_chat_invite_link(chat_id, **kwargs): """ Use this method to generate a new invite link for a chat; any previously generated link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) :param kwargs: Args that get passed down to :class:`TelegramBotRPCRequest` :return: Returns the new invite link as String on success. :rtype: str """ # required args params = dict(chat_id=chat_id) return TelegramBotRPCRequest('exportChatInviteLink', params=params, on_result=lambda result: result, **kwargs)
Use this method to generate a new invite link for a chat; any previously generated link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) :param kwargs: Args that get passed down to :class:`TelegramBotRPCRequest` :return: Returns the new invite link as String on success. :rtype: str
def get_metric_values_response(self): """ Get the faked metrics, for all metric groups and all resources that have been prepared on the manager object of this context object, as a string in the format needed for the "Get Metrics" operation response. Returns: "MetricsResponse" string as described for the "Get Metrics" operation response. """ mv_list = self.get_metric_values() resp_lines = [] for mv in mv_list: group_name = mv[0] resp_lines.append('"{}"'.format(group_name)) mo_vals = mv[1] for mo_val in mo_vals: resp_lines.append('"{}"'.format(mo_val.resource_uri)) resp_lines.append( str(timestamp_from_datetime(mo_val.timestamp))) v_list = [] for n, v in mo_val.values: if isinstance(v, six.string_types): v_str = '"{}"'.format(v) else: v_str = str(v) v_list.append(v_str) v_line = ','.join(v_list) resp_lines.append(v_line) resp_lines.append('') resp_lines.append('') resp_lines.append('') return '\n'.join(resp_lines) + '\n'
Get the faked metrics, for all metric groups and all resources that have been prepared on the manager object of this context object, as a string in the format needed for the "Get Metrics" operation response. Returns: "MetricsResponse" string as described for the "Get Metrics" operation response.
def mouseReleaseEvent(self, event): """ Overloads the mouse release event to apply the current changes. :param event | <QEvent> """ super(XGanttViewItem, self).mouseReleaseEvent(event) if not self.flags() & self.ItemIsMovable: return # force the x position to snap to the nearest date scene = self.scene() if scene: gantt = scene.ganttWidget() curr_x = self.pos().x() + gantt.cellWidth() / 2.0 new_x = curr_x - curr_x % gantt.cellWidth() self.setPos(new_x, self.pos().y()) # look for date based times gantt = self.scene().ganttWidget() # determine hour/minute information if gantt.timescale() in (gantt.Timescale.Minute, gantt.Timescale.Hour, gantt.Timescale.Day): dstart = self.scene().datetimeAt(self.pos().x()) dend = self.scene().datetimeAt(self.pos().x() + self.rect().width()) dend.addSecs(-60) else: dstart = self.scene().dateAt(self.pos().x()) dend = self.scene().dateAt(self.pos().x() + self.rect().width()) dend = dend.addDays(-1) item = self._treeItem() if item: item.viewChanged(dstart, dend)
Overloads the mouse release event to apply the current changes. :param event | <QEvent>
def set_axis_color(axis, color, alpha=None): """Sets the spine color of all sides of an axis (top, right, bottom, left).""" for side in ('top', 'right', 'bottom', 'left'): spine = axis.spines[side] spine.set_color(color) if alpha is not None: spine.set_alpha(alpha)
Sets the spine color of all sides of an axis (top, right, bottom, left).
def password(message: Text, default: Text = "", validate: Union[Type[Validator], Callable[[Text], bool], None] = None, # noqa qmark: Text = DEFAULT_QUESTION_PREFIX, style: Optional[Style] = None, **kwargs: Any) -> Question: """Question the user to enter a secret text not displayed in the prompt. This question type can be used to prompt the user for information that should not be shown in the command line. The typed text will be replaced with `*`. Args: message: Question text default: Default value will be returned if the user just hits enter. validate: Require the entered value to pass a validation. The value can not be submited until the validator accepts it (e.g. to check minimum password length). This can either be a function accepting the input and returning a boolean, or an class reference to a subclass of the prompt toolkit Validator class. qmark: Question prefix displayed in front of the question. By default this is a `?` style: A custom color and style for the question parts. You can configure colors as well as font types for different elements. Returns: Question: Question instance, ready to be prompted (using `.ask()`). """ return text.text(message, default, validate, qmark, style, is_password=True, **kwargs)
Question the user to enter a secret text not displayed in the prompt. This question type can be used to prompt the user for information that should not be shown in the command line. The typed text will be replaced with `*`. Args: message: Question text default: Default value will be returned if the user just hits enter. validate: Require the entered value to pass a validation. The value can not be submited until the validator accepts it (e.g. to check minimum password length). This can either be a function accepting the input and returning a boolean, or an class reference to a subclass of the prompt toolkit Validator class. qmark: Question prefix displayed in front of the question. By default this is a `?` style: A custom color and style for the question parts. You can configure colors as well as font types for different elements. Returns: Question: Question instance, ready to be prompted (using `.ask()`).
def append(key, val, convert=False, delimiter=DEFAULT_TARGET_DELIM): ''' .. versionadded:: 0.17.0 Append a value to a list in the grains config file. If the grain doesn't exist, the grain key is added and the value is appended to the new grain as a list item. key The grain key to be appended to val The value to append to the grain key convert If convert is True, convert non-list contents into a list. If convert is False and the grain contains non-list contents, an error is given. Defaults to False. delimiter The key can be a nested dict key. Use this parameter to specify the delimiter you use, instead of the default ``:``. You can now append values to a list in nested dictionary grains. If the list doesn't exist at this level, it will be created. .. versionadded:: 2014.7.6 CLI Example: .. code-block:: bash salt '*' grains.append key val ''' grains = get(key, [], delimiter) if convert: if not isinstance(grains, list): grains = [] if grains is None else [grains] if not isinstance(grains, list): return 'The key {0} is not a valid list'.format(key) if val in grains: return 'The val {0} was already in the list {1}'.format(val, key) if isinstance(val, list): for item in val: grains.append(item) else: grains.append(val) while delimiter in key: key, rest = key.rsplit(delimiter, 1) _grain = get(key, _infinitedict(), delimiter) if isinstance(_grain, dict): _grain.update({rest: grains}) grains = _grain return setval(key, grains)
.. versionadded:: 0.17.0 Append a value to a list in the grains config file. If the grain doesn't exist, the grain key is added and the value is appended to the new grain as a list item. key The grain key to be appended to val The value to append to the grain key convert If convert is True, convert non-list contents into a list. If convert is False and the grain contains non-list contents, an error is given. Defaults to False. delimiter The key can be a nested dict key. Use this parameter to specify the delimiter you use, instead of the default ``:``. You can now append values to a list in nested dictionary grains. If the list doesn't exist at this level, it will be created. .. versionadded:: 2014.7.6 CLI Example: .. code-block:: bash salt '*' grains.append key val
def imagetransformer_base_10l_16h_big_dr01_imgnet(): """big 1d model for conditional image generation.""" hparams = imagetransformer_base_14l_8h_big_dr01() # num_hidden_layers hparams.num_decoder_layers = 10 hparams.num_heads = 16 hparams.hidden_size = 1024 hparams.filter_size = 4096 hparams.batch_size = 1 hparams.unconditional = False hparams.layer_prepostprocess_dropout = 0.1 return hparams
big 1d model for conditional image generation.
def format_name(self): ''' Format the function name ''' if not hasattr(self.module, '__func_alias__'): # Resume normal sphinx.ext.autodoc operation return super(FunctionDocumenter, self).format_name() if not self.objpath: # Resume normal sphinx.ext.autodoc operation return super(FunctionDocumenter, self).format_name() if len(self.objpath) > 1: # Resume normal sphinx.ext.autodoc operation return super(FunctionDocumenter, self).format_name() # Use the salt func aliased name instead of the real name return self.module.__func_alias__.get(self.objpath[0], self.objpath[0])
Format the function name
def _get_events_list(object_key: str) -> List[str]: """Get list of event ids for the object with the specified key. Args: object_key (str): Key of an object in the database. """ return DB.get_list(_keys.events_list(object_key))
Get list of event ids for the object with the specified key. Args: object_key (str): Key of an object in the database.
def volume(self, volume): """See `volume`.""" # max 100 volume = int(volume) self._volume = max(0, min(volume, 100))
See `volume`.
def _add_discovery_config(self): """Add the Discovery configuration to our list of configs. This should only be called with self._config_lock. The code here assumes the lock is held. """ lookup_key = (discovery_service.DiscoveryService.API_CONFIG['name'], discovery_service.DiscoveryService.API_CONFIG['version']) self._configs[lookup_key] = discovery_service.DiscoveryService.API_CONFIG
Add the Discovery configuration to our list of configs. This should only be called with self._config_lock. The code here assumes the lock is held.
def _pick_colours(self, palette_name, selected=False): """ Pick the rendering colour for a widget based on the current state. :param palette_name: The stem name for the widget - e.g. "button". :param selected: Whether this item is selected or not. :returns: A colour tuple (fg, attr, bg) to be used. """ return self._frame.palette[self._pick_palette_key(palette_name, selected)]
Pick the rendering colour for a widget based on the current state. :param palette_name: The stem name for the widget - e.g. "button". :param selected: Whether this item is selected or not. :returns: A colour tuple (fg, attr, bg) to be used.
def creation_time(self, timeformat='unix'): """Returns the UTC time of creation of this station :param timeformat: the format for the time value. May be: '*unix*' (default) for UNIX time, '*iso*' for ISO8601-formatted string in the format ``YYYY-MM-DD HH:MM:SS+00`` or `date` for a ``datetime.datetime`` object :type timeformat: str :returns: an int or a str or a ``datetime.datetime`` object or None :raises: ValueError """ if self.created_at is None: return None return timeformatutils.timeformat(self.created_at, timeformat)
Returns the UTC time of creation of this station :param timeformat: the format for the time value. May be: '*unix*' (default) for UNIX time, '*iso*' for ISO8601-formatted string in the format ``YYYY-MM-DD HH:MM:SS+00`` or `date` for a ``datetime.datetime`` object :type timeformat: str :returns: an int or a str or a ``datetime.datetime`` object or None :raises: ValueError
def update_host_mapping(host_id, interface, nexus_ip, new_ch_grp): """Change channel_group in host/interface mapping data base.""" LOG.debug("update_host_mapping called") session = bc.get_writer_session() mapping = _lookup_one_host_mapping( session=session, host_id=host_id, if_id=interface, switch_ip=nexus_ip) mapping.ch_grp = new_ch_grp session.merge(mapping) session.flush() return mapping
Change channel_group in host/interface mapping data base.
def add_latlon_metadata(lat_var, lon_var): """Adds latitude and longitude metadata""" lat_var.long_name = 'latitude' lat_var.standard_name = 'latitude' lat_var.units = 'degrees_north' lat_var.axis = 'Y' lon_var.long_name = 'longitude' lon_var.standard_name = 'longitude' lon_var.units = 'degrees_east' lon_var.axis = 'X'
Adds latitude and longitude metadata
def _model_error_corr(self, catchment1, catchment2): """ Return model error correlation between subject catchment and other catchment. Methodology source: Kjeldsen & Jones, 2009, table 3 :param catchment1: catchment to calculate error correlation with :type catchment1: :class:`Catchment` :param catchment2: catchment to calculate error correlation with :type catchment2: :class:`Catchment` :return: correlation coefficient, r :rtype: float """ dist = catchment1.distance_to(catchment2) return self._dist_corr(dist, 0.3998, 0.0283, 0.9494)
Return model error correlation between subject catchment and other catchment. Methodology source: Kjeldsen & Jones, 2009, table 3 :param catchment1: catchment to calculate error correlation with :type catchment1: :class:`Catchment` :param catchment2: catchment to calculate error correlation with :type catchment2: :class:`Catchment` :return: correlation coefficient, r :rtype: float
def __crawler_start(self): """Spawn the first X queued request, where X is the max threads option. Note: The main thread will sleep until the crawler is finished. This enables quiting the application using sigints (see http://stackoverflow.com/a/11816038/2491049). Note: `__crawler_stop()` and `__spawn_new_requests()` are called here on the main thread to prevent thread recursion and deadlocks. """ try: self.__options.callbacks.crawler_before_start() except Exception as e: print(e) print(traceback.format_exc()) self.__spawn_new_requests() while not self.__stopped: if self.__should_stop: self.__crawler_stop() if self.__should_spawn_new_requests: self.__spawn_new_requests() time.sleep(0.1)
Spawn the first X queued request, where X is the max threads option. Note: The main thread will sleep until the crawler is finished. This enables quiting the application using sigints (see http://stackoverflow.com/a/11816038/2491049). Note: `__crawler_stop()` and `__spawn_new_requests()` are called here on the main thread to prevent thread recursion and deadlocks.
def letter_scales(counts): """Convert letter counts to frequencies, sorted increasing.""" try: scale = 1.0 / sum(counts.values()) except ZeroDivisionError: # This logo is all gaps, nothing can be done return [] freqs = [(aa, cnt*scale) for aa, cnt in counts.iteritems() if cnt] freqs.sort(key=lambda pair: pair[1]) return freqs
Convert letter counts to frequencies, sorted increasing.
def reload(self): """ Reloads the limits configuration from the database. If an error occurs loading the configuration, an error-level log message will be emitted. Additionally, the error message will be added to the set specified by the 'redis.errors_key' configuration ('errors' by default) and sent to the publishing channel specified by the 'redis.errors_channel' configuration ('errors' by default). """ # Acquire the pending semaphore. If we fail, exit--someone # else is already doing the reload if not self.pending.acquire(False): return # Do the remaining steps in a try/finally block so we make # sure to release the semaphore control_args = self.config['control'] try: # Load all the limits key = control_args.get('limits_key', 'limits') self.limits.set_limits(self.db.zrange(key, 0, -1)) except Exception: # Log an error LOG.exception("Could not load limits") # Get our error set and publish channel error_key = control_args.get('errors_key', 'errors') error_channel = control_args.get('errors_channel', 'errors') # Get an informative message msg = "Failed to load limits: " + traceback.format_exc() # Store the message into the error set. We use a set here # because it's likely that more than one node will # generate the same message if there is an error, and this # avoids an explosion in the size of the set. with utils.ignore_except(): self.db.sadd(error_key, msg) # Publish the message to a channel with utils.ignore_except(): self.db.publish(error_channel, msg) finally: self.pending.release()
Reloads the limits configuration from the database. If an error occurs loading the configuration, an error-level log message will be emitted. Additionally, the error message will be added to the set specified by the 'redis.errors_key' configuration ('errors' by default) and sent to the publishing channel specified by the 'redis.errors_channel' configuration ('errors' by default).
def commit(self, **params): """ Rebuild kevent operations by removing open files that no longer need to be watched, and adding new files if they are not currently being watched. This is done by comparing self.paths to self.paths_open. """ log = self._getparam('log', self._discard, **params) # Find all the modules that no longer need watching # removed = 0 added = 0 for path in list(self.paths_open): if path not in self.paths: fd = self.paths_open[path] if self._mode == WF_KQUEUE: # kevent automatically deletes the event when the fd is closed try: os.close(fd) except Exception as e: log.warning("close failed on watched file %r -- %s", path, e) elif self._mode == WF_INOTIFYX: try: pynotifyx.rm_watch(self._inx_fd, fd) except Exception as e: log.warning("remove failed on watched file %r -- %s", path, e) if path in self._inx_inode: del self._inx_inode[path] elif self._mode == WF_POLLING: if fd in self._poll_stat: del self._poll_stat[fd] else: log.warning("fd watched path %r missing from _poll_stat map", path) try: os.close(fd) except Exception as e: log.warning("close failed on watched file %r -- %s", path, e) if fd in self.fds_open: del self.fds_open[fd] else: log.warning("fd watched path %r missing from fd map", path) del self.paths_open[path] log.debug("Removed watch for path %r", path) removed += 1 # Find all the paths that are new and should be watched # fdlist = [] failed = [] last_exc = None log.debug("%d watched path%s", len(self.paths), ses(len(self.paths))) for path in list(self.paths): if path not in self.paths_open: try: if not self._add_file(path, **params): continue except Exception as e: last_exc = e failed.append(path) continue fdlist.append(self.paths_open[path]) if path in self.paths_pending: log.debug("pending path %r has now appeared", path) del self.paths_pending[path] self._trigger(self.paths_open[path], **params) added += 1 log.debug("Added watch for path %r with ident %d", path, self.paths_open[path]) if failed: self._clean_failed_fds(fdlist) raise Exception("Failed to set watch on %s -- %s" % (str(failed), str(last_exc))) log.debug("%d added, %d removed", added, removed)
Rebuild kevent operations by removing open files that no longer need to be watched, and adding new files if they are not currently being watched. This is done by comparing self.paths to self.paths_open.
def cigar_iter(self, reverse): """self.cigar => [(length, type) ... ] iterate the cigar :param reverse: whether to iterate in the reverse direction (right-to-left) :type reverse: boolean :return a list of pairs of the type [(length, M/D) ..] """ l = 0 P = self.cigar_pattern data = [] cigar = self.cigar parsed_cigar = re.findall(P, cigar) if reverse: parsed_cigar = parsed_cigar[::-1] for _l, t in parsed_cigar: # 1M is encoded as M l = (_l and int(_l) or 1) # int(_l) cannot be 0 data.append( (l, t) ) return data
self.cigar => [(length, type) ... ] iterate the cigar :param reverse: whether to iterate in the reverse direction (right-to-left) :type reverse: boolean :return a list of pairs of the type [(length, M/D) ..]
def get_real_stored_key(self, session_key): """Return the real key name in redis storage @return string """ prefix = settings.SESSION_REDIS_PREFIX if not prefix: return session_key return ':'.join([prefix, session_key])
Return the real key name in redis storage @return string
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None, ciphers=None, ssl_context=None, ca_cert_dir=None): """ All arguments except for server_hostname, ssl_context, and ca_cert_dir have the same meaning as they do when using :func:`ssl.wrap_socket`. :param server_hostname: When SNI is supported, the expected hostname of the certificate :param ssl_context: A pre-made :class:`SSLContext` object. If none is provided, one will be created using :func:`create_urllib3_context`. :param ciphers: A string of ciphers we wish the client to support. :param ca_cert_dir: A directory containing CA certificates in multiple separate files, as supported by OpenSSL's -CApath flag or the capath argument to SSLContext.load_verify_locations(). """ context = ssl_context if context is None: # Note: This branch of code and all the variables in it are no longer # used by urllib3 itself. We should consider deprecating and removing # this code. context = create_urllib3_context(ssl_version, cert_reqs, ciphers=ciphers) if ca_certs or ca_cert_dir: try: context.load_verify_locations(ca_certs, ca_cert_dir) except IOError as e: # Platform-specific: Python 2.7 raise SSLError(e) # Py33 raises FileNotFoundError which subclasses OSError # These are not equivalent unless we check the errno attribute except OSError as e: # Platform-specific: Python 3.3 and beyond if e.errno == errno.ENOENT: raise SSLError(e) raise elif getattr(context, 'load_default_certs', None) is not None: # try to load OS default certs; works well on Windows (require Python3.4+) context.load_default_certs() if certfile: context.load_cert_chain(certfile, keyfile) # If we detect server_hostname is an IP address then the SNI # extension should not be used according to RFC3546 Section 3.1 # We shouldn't warn the user if SNI isn't available but we would # not be using SNI anyways due to IP address for server_hostname. if ((server_hostname is not None and not is_ipaddress(server_hostname)) or IS_SECURETRANSPORT): if HAS_SNI and server_hostname is not None: return context.wrap_socket(sock, server_hostname=server_hostname) warnings.warn( 'An HTTPS request has been made, but the SNI (Server Name ' 'Indication) extension to TLS is not available on this platform. ' 'This may cause the server to present an incorrect TLS ' 'certificate, which can cause validation failures. You can upgrade to ' 'a newer version of Python to solve this. For more information, see ' 'https://urllib3.readthedocs.io/en/latest/advanced-usage.html' '#ssl-warnings', SNIMissingWarning ) return context.wrap_socket(sock)
All arguments except for server_hostname, ssl_context, and ca_cert_dir have the same meaning as they do when using :func:`ssl.wrap_socket`. :param server_hostname: When SNI is supported, the expected hostname of the certificate :param ssl_context: A pre-made :class:`SSLContext` object. If none is provided, one will be created using :func:`create_urllib3_context`. :param ciphers: A string of ciphers we wish the client to support. :param ca_cert_dir: A directory containing CA certificates in multiple separate files, as supported by OpenSSL's -CApath flag or the capath argument to SSLContext.load_verify_locations().
async def mail(self, sender, options=None): """ Sends a SMTP 'MAIL' command. - Starts the mail transfer session. For further details, please check out `RFC 5321 § 4.1.1.2`_ and `§ 3.3`_. Args: sender (str): Sender mailbox (used as reverse-path). options (list of str or None, optional): Additional options to send along with the *MAIL* command. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the MAIL command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.2`: https://tools.ietf.org/html/rfc5321#section-4.1.1.2 .. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3 """ if options is None: options = [] from_addr = "FROM:{}".format(quoteaddr(sender)) code, message = await self.do_cmd("MAIL", from_addr, *options) return code, message
Sends a SMTP 'MAIL' command. - Starts the mail transfer session. For further details, please check out `RFC 5321 § 4.1.1.2`_ and `§ 3.3`_. Args: sender (str): Sender mailbox (used as reverse-path). options (list of str or None, optional): Additional options to send along with the *MAIL* command. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the MAIL command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.2`: https://tools.ietf.org/html/rfc5321#section-4.1.1.2 .. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3
def cumulative_density_at_times(self, times, label=None): """ Return a Pandas series of the predicted cumulative density function (1-survival function) at specific times. Parameters ----------- times: iterable or float values to return the survival function at. label: string, optional Rename the series returned. Useful for plotting. Returns -------- pd.Series """ label = coalesce(label, self._label) return pd.Series(self._cumulative_density(self._fitted_parameters_, times), index=_to_array(times), name=label)
Return a Pandas series of the predicted cumulative density function (1-survival function) at specific times. Parameters ----------- times: iterable or float values to return the survival function at. label: string, optional Rename the series returned. Useful for plotting. Returns -------- pd.Series
def fit_circle_check(points, scale, prior=None, final=False, verbose=False): """ Fit a circle, and reject the fit if: * the radius is larger than tol.radius_min*scale or tol.radius_max*scale * any segment spans more than tol.seg_angle * any segment is longer than tol.seg_frac*scale * the fit deviates by more than tol.radius_frac*radius * the segments on the ends deviate from tangent by more than tol.tangent Parameters --------- points: (n, d) set of points which represent a path prior: (center, radius) tuple for best guess, or None if unknown scale: float, what is the overall scale of the set of points verbose: boolean, if True output log.debug messages for the reasons for fit rejection. Potentially generates hundreds of thousands of messages so only suggested in manual debugging. Returns --------- if fit is acceptable: (center, radius) tuple else: None """ # an arc needs at least three points if len(points) < 3: return None # do a least squares fit on the points C, R, r_deviation = fit_nsphere(points, prior=prior) # check to make sure radius is between min and max allowed if not tol.radius_min < (R / scale) < tol.radius_max: if verbose: log.debug('circle fit error: R %f', R / scale) return None # check point radius error r_error = r_deviation / R if r_error > tol.radius_frac: if verbose: log.debug('circle fit error: fit %s', str(r_error)) return None vectors = np.diff(points, axis=0) segment = np.linalg.norm(vectors, axis=1) # approximate angle in radians, segments are linear length # not arc length but this is close and avoids a cosine angle = segment / R if (angle > tol.seg_angle).any(): if verbose: log.debug('circle fit error: angle %s', str(angle)) return None if final and (angle > tol.seg_angle_min).sum() < 3: log.debug('final: angle %s', str(angle)) return None # check segment length as a fraction of drawing scale scaled = segment / scale if (scaled > tol.seg_frac).any(): if verbose: log.debug('circle fit error: segment %s', str(scaled)) return None # check to make sure the line segments on the ends are actually # tangent with the candidate circle fit mid_pt = points[[0, -2]] + (vectors[[0, -1]] * .5) radial = unitize(mid_pt - C) ends = unitize(vectors[[0, -1]]) tangent = np.abs(np.arccos(diagonal_dot(radial, ends))) tangent = np.abs(tangent - np.pi / 2).max() if tangent > tol.tangent: if verbose: log.debug('circle fit error: tangent %f', np.degrees(tangent)) return None result = {'center': C, 'radius': R} return result
Fit a circle, and reject the fit if: * the radius is larger than tol.radius_min*scale or tol.radius_max*scale * any segment spans more than tol.seg_angle * any segment is longer than tol.seg_frac*scale * the fit deviates by more than tol.radius_frac*radius * the segments on the ends deviate from tangent by more than tol.tangent Parameters --------- points: (n, d) set of points which represent a path prior: (center, radius) tuple for best guess, or None if unknown scale: float, what is the overall scale of the set of points verbose: boolean, if True output log.debug messages for the reasons for fit rejection. Potentially generates hundreds of thousands of messages so only suggested in manual debugging. Returns --------- if fit is acceptable: (center, radius) tuple else: None
def get_lattice_quanta(self, convert_to_muC_per_cm2=True, all_in_polar=True): """ Returns the dipole / polarization quanta along a, b, and c for all structures. """ lattices = [s.lattice for s in self.structures] volumes = np.array([s.lattice.volume for s in self.structures]) L = len(self.structures) e_to_muC = -1.6021766e-13 cm2_to_A2 = 1e16 units = 1.0 / np.array(volumes) units *= e_to_muC * cm2_to_A2 # convert polarizations and lattice lengths prior to adjustment if convert_to_muC_per_cm2 and not all_in_polar: # adjust lattices for i in range(L): lattice = lattices[i] l, a = lattice.lengths_and_angles lattices[i] = Lattice.from_lengths_and_angles( np.array(l) * units.ravel()[i], a) elif convert_to_muC_per_cm2 and all_in_polar: for i in range(L): lattice = lattices[-1] l, a = lattice.lengths_and_angles lattices[i] = Lattice.from_lengths_and_angles( np.array(l) * units.ravel()[-1], a) quanta = np.array( [np.array(l.lengths_and_angles[0]) for l in lattices]) return quanta
Returns the dipole / polarization quanta along a, b, and c for all structures.
def init(): """Initialize Yass in the current directory """ yass_conf = os.path.join(CWD, "yass.yml") if os.path.isfile(yass_conf): print("::ALERT::") print("It seems like Yass is already initialized here.") print("If it's a mistake, delete 'yass.yml' in this directory") else: print("Init Yass in %s ..." % CWD) copy_resource("skel/", CWD) stamp_yass_current_version(CWD) print("Yass init successfully!") print("Run 'yass serve' to view the site") footer()
Initialize Yass in the current directory
def _ploadf(ins): """ Loads from stack pointer (SP) + X, being X 2st parameter. 1st operand must be a SIGNED integer. """ output = _pload(ins.quad[2], 5) output.extend(_fpush()) return output
Loads from stack pointer (SP) + X, being X 2st parameter. 1st operand must be a SIGNED integer.
def info_post(node_id): """Create an info. The node id must be specified in the url. You must pass contents as an argument. info_type is an additional optional argument. If info_type is a custom subclass of Info it must be added to the known_classes of the experiment class. """ # get the parameters and validate them contents = request_parameter(parameter="contents") info_type = request_parameter( parameter="info_type", parameter_type="known_class", default=models.Info ) for x in [contents, info_type]: if type(x) == Response: return x # check the node exists node = models.Node.query.get(node_id) if node is None: return error_response(error_type="/info POST, node does not exist") exp = Experiment(session) try: # execute the request info = info_type(origin=node, contents=contents) assign_properties(info) # ping the experiment exp.info_post_request(node=node, info=info) session.commit() except Exception: return error_response( error_type="/info POST server error", status=403, participant=node.participant, ) # return the data return success_response(info=info.__json__())
Create an info. The node id must be specified in the url. You must pass contents as an argument. info_type is an additional optional argument. If info_type is a custom subclass of Info it must be added to the known_classes of the experiment class.
def get_block_entity_data(self, pos_or_x, y=None, z=None): """ Access block entity data. Returns: BlockEntityData subclass instance or None if no block entity data is stored for that location. """ if None not in (y, z): # x y z supplied pos_or_x = pos_or_x, y, z coord_tuple = tuple(int(floor(c)) for c in pos_or_x) return self.block_entities.get(coord_tuple, None)
Access block entity data. Returns: BlockEntityData subclass instance or None if no block entity data is stored for that location.
def has(self, relation, operator=">=", count=1, boolean="and", extra=None): """ Add a relationship count condition to the query. :param relation: The relation to count :type relation: str :param operator: The operator :type operator: str :param count: The count :type count: int :param boolean: The boolean value :type boolean: str :param extra: The extra query :type extra: Builder or callable :type: Builder """ if relation.find(".") >= 0: return self._has_nested(relation, operator, count, boolean, extra) relation = self._get_has_relation_query(relation) query = relation.get_relation_count_query( relation.get_related().new_query(), self ) # TODO: extra query if extra: if callable(extra): extra(query) return self._add_has_where( query.apply_scopes(), relation, operator, count, boolean )
Add a relationship count condition to the query. :param relation: The relation to count :type relation: str :param operator: The operator :type operator: str :param count: The count :type count: int :param boolean: The boolean value :type boolean: str :param extra: The extra query :type extra: Builder or callable :type: Builder
def get_plugin_modules(plugins): """ Get plugin modules from input strings :param tuple plugins: a tuple of plugin names in str """ if not plugins: raise MissingPluginNames("input plugin names are required") modules = [] for plugin in plugins: short_name = PLUGIN_MAPPING.get(plugin.lower(), plugin.lower()) full_path = '%s%s' % (module_prefix, short_name) modules.append(importlib.import_module(full_path)) return tuple(modules)
Get plugin modules from input strings :param tuple plugins: a tuple of plugin names in str
def clipline(x1, y1, x2, y2, xmin, ymin, xmax, ymax): 'Liang-Barsky algorithm, returns [xn1,yn1,xn2,yn2] of clipped line within given area, or None' dx = x2-x1 dy = y2-y1 pq = [ (-dx, x1-xmin), # left ( dx, xmax-x1), # right (-dy, y1-ymin), # bottom ( dy, ymax-y1), # top ] u1, u2 = 0, 1 for p, q in pq: if p < 0: # from outside to inside u1 = max(u1, q/p) elif p > 0: # from inside to outside u2 = min(u2, q/p) else: # p == 0: # parallel to bbox if q < 0: # completely outside bbox return None if u1 > u2: # completely outside bbox return None xn1 = x1 + dx*u1 yn1 = y1 + dy*u1 xn2 = x1 + dx*u2 yn2 = y1 + dy*u2 return xn1, yn1, xn2, yn2
Liang-Barsky algorithm, returns [xn1,yn1,xn2,yn2] of clipped line within given area, or None
def run(self): """A bit bulky atm...""" self.close_connection = False try: while True: self.started_response = False self.status = "" self.outheaders = [] self.sent_headers = False self.chunked_write = False self.write_buffer = StringIO.StringIO() self.content_length = None # Copy the class environ into self. ENVIRON = self.environ = self.connection_environ.copy() self.environ.update(self.server_environ) request_line = yield self.connfh.readline() if request_line == "\r\n": # RFC 2616 sec 4.1: "... it should ignore the CRLF." tolerance = 5 while tolerance and request_line == "\r\n": request_line = yield self.connfh.readline() tolerance -= 1 if not tolerance: return method, path, req_protocol = request_line.strip().split(" ", 2) ENVIRON["REQUEST_METHOD"] = method ENVIRON["CONTENT_LENGTH"] = '' scheme, location, path, params, qs, frag = urlparse(path) if frag: yield self.simple_response("400 Bad Request", "Illegal #fragment in Request-URI.") return if scheme: ENVIRON["wsgi.url_scheme"] = scheme if params: path = path + ";" + params ENVIRON["SCRIPT_NAME"] = "" # Unquote the path+params (e.g. "/this%20path" -> "this path"). # http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2 # # But note that "...a URI must be separated into its components # before the escaped characters within those components can be # safely decoded." http://www.ietf.org/rfc/rfc2396.txt, sec 2.4.2 atoms = [unquote(x) for x in quoted_slash.split(path)] path = "%2F".join(atoms) ENVIRON["PATH_INFO"] = path # Note that, like wsgiref and most other WSGI servers, # we unquote the path but not the query string. ENVIRON["QUERY_STRING"] = qs # Compare request and server HTTP protocol versions, in case our # server does not support the requested protocol. Limit our output # to min(req, server). We want the following output: # request server actual written supported response # protocol protocol response protocol feature set # a 1.0 1.0 1.0 1.0 # b 1.0 1.1 1.1 1.0 # c 1.1 1.0 1.0 1.0 # d 1.1 1.1 1.1 1.1 # Notice that, in (b), the response will be "HTTP/1.1" even though # the client only understands 1.0. RFC 2616 10.5.6 says we should # only return 505 if the _major_ version is different. rp = int(req_protocol[5]), int(req_protocol[7]) server_protocol = ENVIRON["ACTUAL_SERVER_PROTOCOL"] sp = int(server_protocol[5]), int(server_protocol[7]) if sp[0] != rp[0]: yield self.simple_response("505 HTTP Version Not Supported") return # Bah. "SERVER_PROTOCOL" is actually the REQUEST protocol. ENVIRON["SERVER_PROTOCOL"] = req_protocol self.response_protocol = "HTTP/%s.%s" % min(rp, sp) # If the Request-URI was an absoluteURI, use its location atom. if location: ENVIRON["SERVER_NAME"] = location # then all the http headers try: while True: line = yield self.connfh.readline() if line == '\r\n': # Normal end of headers break if line[0] in ' \t': # It's a continuation line. v = line.strip() else: k, v = line.split(":", 1) k, v = k.strip().upper(), v.strip() envname = "HTTP_" + k.replace("-", "_") if k in comma_separated_headers: existing = ENVIRON.get(envname) if existing: v = ", ".join((existing, v)) ENVIRON[envname] = v ct = ENVIRON.pop("HTTP_CONTENT_TYPE", None) if ct: ENVIRON["CONTENT_TYPE"] = ct cl = ENVIRON.pop("HTTP_CONTENT_LENGTH", None) if cl: ENVIRON["CONTENT_LENGTH"] = cl except ValueError, ex: yield self.simple_response("400 Bad Request", repr(ex.args)) return creds = ENVIRON.get("HTTP_AUTHORIZATION", "").split(" ", 1) ENVIRON["AUTH_TYPE"] = creds[0] if creds[0].lower() == 'basic': user, pw = base64.decodestring(creds[1]).split(":", 1) ENVIRON["REMOTE_USER"] = user # Persistent connection support if req_protocol == "HTTP/1.1": if ENVIRON.get("HTTP_CONNECTION", "") == "close": self.close_connection = True else: # HTTP/1.0 if ENVIRON.get("HTTP_CONNECTION", "").lower() != "keep-alive": self.close_connection = True # Transfer-Encoding support te = None if self.response_protocol == "HTTP/1.1": te = ENVIRON.get("HTTP_TRANSFER_ENCODING") if te: te = [x.strip().lower() for x in te.split(",") if x.strip()] if te: # reject transfer encodings for now yield self.simple_response("501 Unimplemented") self.close_connection = True return ENV_COGEN_PROXY = ENVIRON['cogen.wsgi'] = async.COGENProxy( content_length = int(ENVIRON.get('CONTENT_LENGTH', None) or 0) or None, read_count = 0, operation = None, result = None, exception = None ) ENVIRON['cogen.http_connection'] = self ENVIRON['cogen.core'] = async.COGENOperationWrapper( ENV_COGEN_PROXY, core ) ENVIRON['cogen.call'] = async.COGENCallWrapper(ENV_COGEN_PROXY) ENVIRON['cogen.input'] = async.COGENOperationWrapper( ENV_COGEN_PROXY, self.connfh ) ENVIRON['cogen.yield'] = async.COGENSimpleWrapper(ENV_COGEN_PROXY) response = self.wsgi_app(ENVIRON, self.start_response) #~ print 'WSGI RESPONSE:', response try: if isinstance(response, WSGIFileWrapper): # set tcp_cork to pack the header with the file data if hasattr(socket, "TCP_CORK"): self.conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_CORK, 1) assert self.started_response, "App returned the wsgi.file_wrapper but didn't call start_response." assert not self.sent_headers self.sent_headers = True yield sockets.SendAll(self.conn, self.render_headers()+self.write_buffer.getvalue() ) offset = response.filelike.tell() if self.chunked_write: fsize = os.fstat(response.filelike.fileno()).st_size yield sockets.SendAll(self.conn, hex(int(fsize-offset))+"\r\n") yield self.conn.sendfile( response.filelike, blocksize=response.blocksize, offset=offset, length=self.content_length, timeout=self.sendfile_timeout ) if self.chunked_write: yield sockets.SendAll(self.conn, "\r\n") # also, tcp_cork will make the file data sent on packet boundaries, # wich is a good thing if hasattr(socket, "TCP_CORK"): self.conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_CORK, 0) else: for chunk in response: if chunk: assert self.started_response, "App sended a value but hasn't called start_response." if not self.sent_headers: self.sent_headers = True headers = [self.render_headers(), self.write_buffer.getvalue()] else: headers = [] if self.chunked_write: buf = [hex(len(chunk))[2:], "\r\n", chunk, "\r\n"] if headers: headers.extend(buf) yield sockets.SendAll(self.conn, "".join(headers)) else: yield sockets.SendAll(self.conn, "".join(buf)) else: if headers: headers.append(chunk) yield sockets.SendAll(self.conn, "".join(headers)) else: yield sockets.SendAll(self.conn, chunk) else: if self.started_response: if not self.sent_headers: self.sent_headers = True yield sockets.SendAll(self.conn, self.render_headers()+self.write_buffer.getvalue()) if ENV_COGEN_PROXY.operation: op = ENV_COGEN_PROXY.operation ENV_COGEN_PROXY.operation = None try: #~ print 'WSGI OP:', op ENV_COGEN_PROXY.exception = None ENV_COGEN_PROXY.result = yield op #~ print 'WSGI OP RESULT:',ENVIRON['cogen.wsgi'].result except: #~ print 'WSGI OP EXCEPTION:', sys.exc_info() ENV_COGEN_PROXY.exception = sys.exc_info() ENV_COGEN_PROXY.result = ENV_COGEN_PROXY.exception[1] del op finally: if hasattr(response, 'close'): response.close() if self.started_response: if not self.sent_headers: self.sent_headers = True yield sockets.SendAll(self.conn, self.render_headers()+self.write_buffer.getvalue() ) else: import warnings warnings.warn("App was consumed and hasn't called start_response") if self.chunked_write: yield sockets.SendAll(self.conn, "0\r\n\r\n") if self.close_connection: return # TODO: consume any unread data except (socket.error, OSError, pywinerror), e: errno = e.args[0] if errno not in useless_socket_errors: yield self.simple_response("500 Internal Server Error", format_exc()) return except (OperationTimeout, ConnectionClosed, SocketError): return except (KeyboardInterrupt, SystemExit, GeneratorExit, MemoryError): raise except: if not self.started_response: yield self.simple_response( "500 Internal Server Error", format_exc() ) else: print "*" * 60 traceback.print_exc() print "*" * 60 sys.exc_clear() finally: self.conn.close() ENVIRON = self.environ = None
A bit bulky atm...
def remote_route(self): """ A list of all IPs that were involved in this request, starting with the client IP and followed by zero or more proxies. This does only work if all proxies support the ```X-Forwarded-For`` header. Note that this information can be forged by malicious clients. """ proxy = self.environ.get('HTTP_X_FORWARDED_FOR') if proxy: return [ip.strip() for ip in proxy.split(',')] remote = self.environ.get('REMOTE_ADDR') return [remote] if remote else []
A list of all IPs that were involved in this request, starting with the client IP and followed by zero or more proxies. This does only work if all proxies support the ```X-Forwarded-For`` header. Note that this information can be forged by malicious clients.
def get_course_fs(self, courseid): """ :param courseid: :return: a FileSystemProvider pointing to the directory of the course """ if not id_checker(courseid): raise InvalidNameException("Course with invalid name: " + courseid) return self._filesystem.from_subfolder(courseid)
:param courseid: :return: a FileSystemProvider pointing to the directory of the course
def create_geometry(self, input_geometry, upper_depth, lower_depth): ''' If geometry is defined as a numpy array then create instance of nhlib.geo.polygon.Polygon class, otherwise if already instance of class accept class :param input_geometry: Input geometry (polygon) as either i) instance of nhlib.geo.polygon.Polygon class ii) numpy.ndarray [Longitude, Latitude] :param float upper_depth: Upper seismogenic depth (km) :param float lower_depth: Lower seismogenic depth (km) ''' self._check_seismogenic_depths(upper_depth, lower_depth) # Check/create the geometry class if not isinstance(input_geometry, Polygon): if not isinstance(input_geometry, np.ndarray): raise ValueError('Unrecognised or unsupported geometry ' 'definition') if np.shape(input_geometry)[0] < 3: raise ValueError('Incorrectly formatted polygon geometry -' ' needs three or more vertices') geometry = [] for row in input_geometry: geometry.append(Point(row[0], row[1], self.upper_depth)) self.geometry = Polygon(geometry) else: self.geometry = input_geometry
If geometry is defined as a numpy array then create instance of nhlib.geo.polygon.Polygon class, otherwise if already instance of class accept class :param input_geometry: Input geometry (polygon) as either i) instance of nhlib.geo.polygon.Polygon class ii) numpy.ndarray [Longitude, Latitude] :param float upper_depth: Upper seismogenic depth (km) :param float lower_depth: Lower seismogenic depth (km)
def set_deferred_transfer(self, enable): """ Allow transfers to be delayed and buffered By default deferred transfers are turned off. All reads and writes will be completed by the time the function returns. When enabled packets are buffered and sent all at once, which increases speed. When memory is written to, the transfer might take place immediately, or might take place on a future memory write. This means that an invalid write could cause an exception to occur on a later, unrelated write. To guarantee that previous writes are complete call the flush() function. The behaviour of read operations is determined by the modes READ_START, READ_NOW and READ_END. The option READ_NOW is the default and will cause the read to flush all previous writes, and read the data immediately. To improve performance, multiple reads can be made using READ_START and finished later with READ_NOW. This allows the reads to be buffered and sent at once. Note - All READ_ENDs must be called before a call using READ_NOW can be made. """ if self._deferred_transfer and not enable: self.flush() self._deferred_transfer = enable
Allow transfers to be delayed and buffered By default deferred transfers are turned off. All reads and writes will be completed by the time the function returns. When enabled packets are buffered and sent all at once, which increases speed. When memory is written to, the transfer might take place immediately, or might take place on a future memory write. This means that an invalid write could cause an exception to occur on a later, unrelated write. To guarantee that previous writes are complete call the flush() function. The behaviour of read operations is determined by the modes READ_START, READ_NOW and READ_END. The option READ_NOW is the default and will cause the read to flush all previous writes, and read the data immediately. To improve performance, multiple reads can be made using READ_START and finished later with READ_NOW. This allows the reads to be buffered and sent at once. Note - All READ_ENDs must be called before a call using READ_NOW can be made.
def init(self, only_mount=None, skip_mount=None, swallow_exceptions=True): """Generator that mounts this volume and either yields itself or recursively generates its subvolumes. More specifically, this function will call :func:`load_fsstat_data` (iff *no_stats* is False), followed by :func:`mount`, followed by a call to :func:`detect_mountpoint`, after which ``self`` is yielded, or the result of the :func:`init` call on each subvolume is yielded :param only_mount: if specified, only volume indexes in this list are mounted. Volume indexes are strings. :param skip_mount: if specified, volume indexes in this list are not mounted. :param swallow_exceptions: if True, any error occuring when mounting the volume is swallowed and added as an exception attribute to the yielded objects. """ if swallow_exceptions: self.exception = None try: if not self._should_mount(only_mount, skip_mount): yield self return if not self.init_volume(): yield self return except ImageMounterError as e: if swallow_exceptions: self.exception = e else: raise if not self.volumes: yield self else: for v in self.volumes: for s in v.init(only_mount, skip_mount, swallow_exceptions): yield s
Generator that mounts this volume and either yields itself or recursively generates its subvolumes. More specifically, this function will call :func:`load_fsstat_data` (iff *no_stats* is False), followed by :func:`mount`, followed by a call to :func:`detect_mountpoint`, after which ``self`` is yielded, or the result of the :func:`init` call on each subvolume is yielded :param only_mount: if specified, only volume indexes in this list are mounted. Volume indexes are strings. :param skip_mount: if specified, volume indexes in this list are not mounted. :param swallow_exceptions: if True, any error occuring when mounting the volume is swallowed and added as an exception attribute to the yielded objects.
def get_total_spatial_integral(self, z=None): """ Returns the total integral (for 2D functions) or the integral over the spatial components (for 3D functions). needs to be implemented in subclasses. :return: an array of values of the integral (same dimension as z). """ if isinstance( z, u.Quantity): z = z.value return np.ones_like( z )
Returns the total integral (for 2D functions) or the integral over the spatial components (for 3D functions). needs to be implemented in subclasses. :return: an array of values of the integral (same dimension as z).
def output_results(results, metric, options): """ Output the results to stdout. TODO: add AMPQ support for efficiency """ formatter = options['Formatter'] context = metric.copy() # XXX might need to sanitize this try: context['dimension'] = list(metric['Dimensions'].values())[0] except AttributeError: context['dimension'] = '' for result in results: stat_keys = metric['Statistics'] if not isinstance(stat_keys, list): stat_keys = [stat_keys] for statistic in stat_keys: context['statistic'] = statistic # get and then sanitize metric name, first copy the unit name from the # result to the context to keep the default format happy context['Unit'] = result['Unit'] metric_name = (formatter % context).replace('/', '.').lower() line = '{0} {1} {2}\n'.format( metric_name, result[statistic], timegm(result['Timestamp'].timetuple()), ) sys.stdout.write(line)
Output the results to stdout. TODO: add AMPQ support for efficiency
def get_groups(self, username): """Get all groups of a user""" username = ldap.filter.escape_filter_chars(self._byte_p2(username)) userdn = self._get_user(username, NO_ATTR) searchfilter = self.group_filter_tmpl % { 'userdn': userdn, 'username': username } groups = self._search(searchfilter, NO_ATTR, self.groupdn) ret = [] for entry in groups: ret.append(self._uni(entry[0])) return ret
Get all groups of a user
def get_ilo_firmware_version_as_major_minor(self): """Gets the ilo firmware version for server capabilities Parse the get_host_health_data() to retreive the firmware details. :param data: the output returned by get_host_health_data() :returns: String with the format "<major>.<minor>" or None. """ data = self.get_host_health_data() firmware_details = self._get_firmware_embedded_health(data) if firmware_details: ilo_version_str = firmware_details.get('iLO', None) return common.get_major_minor(ilo_version_str)
Gets the ilo firmware version for server capabilities Parse the get_host_health_data() to retreive the firmware details. :param data: the output returned by get_host_health_data() :returns: String with the format "<major>.<minor>" or None.
def gated_linear_unit_layer(x, name=None): """Gated linear unit layer. Paper: Language Modeling with Gated Convolutional Networks. Link: https://arxiv.org/abs/1612.08083 x = Wx * sigmoid(W'x). Args: x: A tensor name: A string Returns: A tensor of the same shape as x. """ with tf.variable_scope(name, default_name="glu_layer", values=[x]): depth = shape_list(x)[-1] x = layers().Dense(depth * 2, activation=None)(x) x, gating_x = tf.split(x, 2, axis=-1) return x * tf.nn.sigmoid(gating_x)
Gated linear unit layer. Paper: Language Modeling with Gated Convolutional Networks. Link: https://arxiv.org/abs/1612.08083 x = Wx * sigmoid(W'x). Args: x: A tensor name: A string Returns: A tensor of the same shape as x.
def make_src_pkg(dest_dir, spec, sources, env=None, template=None, saltenv='base', runas='root'): ''' Create a source rpm from the given spec file and sources CLI Example: .. code-block:: bash salt '*' pkgbuild.make_src_pkg /var/www/html/ https://raw.githubusercontent.com/saltstack/libnacl/master/pkg/rpm/python-libnacl.spec https://pypi.python.org/packages/source/l/libnacl/libnacl-1.3.5.tar.gz This example command should build the libnacl SOURCE package and place it in /var/www/html/ on the minion .. versionchanged:: 2017.7.0 dest_dir The directory on the minion to place the built package(s) spec The location of the spec file (used for rpms) sources The list of package sources env A dictionary of environment variables to be set prior to execution. template Run the spec file through a templating engine Optional arguement, allows for no templating engine used to be if none is desired. saltenv The saltenv to use for files downloaded from the salt filesever runas The user to run the build process as .. versionadded:: 2018.3.3 .. note:: using SHA256 as digest and minimum level dist el6 ''' _create_rpmmacros(runas) tree_base = _mk_tree(runas) spec_path = _get_spec(tree_base, spec, template, saltenv) __salt__['file.chown'](path=spec_path, user=runas, group='mock') __salt__['file.chown'](path=tree_base, user=runas, group='mock') if isinstance(sources, six.string_types): sources = sources.split(',') for src in sources: _get_src(tree_base, src, saltenv, runas) # make source rpms for dist el6 with SHA256, usable with mock on other dists cmd = 'rpmbuild --verbose --define "_topdir {0}" -bs --define "dist .el6" {1}'.format(tree_base, spec_path) retrc = __salt__['cmd.retcode'](cmd, runas=runas) if retrc != 0: raise SaltInvocationError( 'Make source package for destination directory {0}, spec {1}, sources {2}, failed ' 'with return error {3}, check logs for further details'.format( dest_dir, spec, sources, retrc) ) srpms = os.path.join(tree_base, 'SRPMS') ret = [] if not os.path.isdir(dest_dir): __salt__['file.makedirs_perms'](name=dest_dir, user=runas, group='mock') for fn_ in os.listdir(srpms): full = os.path.join(srpms, fn_) tgt = os.path.join(dest_dir, fn_) shutil.copy(full, tgt) ret.append(tgt) return ret
Create a source rpm from the given spec file and sources CLI Example: .. code-block:: bash salt '*' pkgbuild.make_src_pkg /var/www/html/ https://raw.githubusercontent.com/saltstack/libnacl/master/pkg/rpm/python-libnacl.spec https://pypi.python.org/packages/source/l/libnacl/libnacl-1.3.5.tar.gz This example command should build the libnacl SOURCE package and place it in /var/www/html/ on the minion .. versionchanged:: 2017.7.0 dest_dir The directory on the minion to place the built package(s) spec The location of the spec file (used for rpms) sources The list of package sources env A dictionary of environment variables to be set prior to execution. template Run the spec file through a templating engine Optional arguement, allows for no templating engine used to be if none is desired. saltenv The saltenv to use for files downloaded from the salt filesever runas The user to run the build process as .. versionadded:: 2018.3.3 .. note:: using SHA256 as digest and minimum level dist el6
def _compile_expression(self, expr: Expression, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optional[List[tf.Tensor]] = None) -> TensorFluent: '''Compile the expression `expr` into a TensorFluent in the given `scope` with optional batch size. Args: expr (:obj:`rddl2tf.expr.Expression`): A RDDL expression. scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope. batch_size (Optional[size]): The batch size. Returns: :obj:`rddl2tf.fluent.TensorFluent`: The compiled TensorFluent. ''' etype2compiler = { 'constant': self._compile_constant_expression, 'pvar': self._compile_pvariable_expression, 'randomvar': self._compile_random_variable_expression, 'arithmetic': self._compile_arithmetic_expression, 'boolean': self._compile_boolean_expression, 'relational': self._compile_relational_expression, 'func': self._compile_function_expression, 'control': self._compile_control_flow_expression, 'aggregation': self._compile_aggregation_expression } etype = expr.etype if etype[0] not in etype2compiler: raise ValueError('Expression type unknown: {}'.format(etype)) with self.graph.as_default(): compiler_fn = etype2compiler[etype[0]] return compiler_fn(expr, scope, batch_size, noise)
Compile the expression `expr` into a TensorFluent in the given `scope` with optional batch size. Args: expr (:obj:`rddl2tf.expr.Expression`): A RDDL expression. scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope. batch_size (Optional[size]): The batch size. Returns: :obj:`rddl2tf.fluent.TensorFluent`: The compiled TensorFluent.
def str2url(str): """ Takes a UTF-8 string and replaces all characters with the equivalent in 7-bit ASCII. It returns a plain ASCII string usable in URLs. """ try: str = str.encode('utf-8') except: pass mfrom = "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîï" to = "AAAAAAECEEEEIIIIDNOOOOOOUUUUYSaaaaaaaceeeeiiii" mfrom += "ñòóôõöøùúûüýÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģ" to += "noooooouuuuyyaaaaaaccccccccddddeeeeeeeeeegggggggg" mfrom += "ĤĥĦħĨĩĪīĬĭĮįİıĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘř" to += "hhhhiiiiiiiiiijjkkkllllllllllnnnnnnnnnoooooooorrrrrr" mfrom += "ŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƂƃƄƅƇƈƉƊƐƑƒƓƔ" to += "ssssssssttttttuuuuuuuuuuuuwwyyyzzzzzzfbbbbbccddeffgv" mfrom += "ƖƗƘƙƚƝƞƟƠƤƦƫƬƭƮƯưƱƲƳƴƵƶǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩ" to += "likklnnoopettttuuuuyyzzaaiioouuuuuuuuuueaaaaeeggggkk" mfrom += "ǪǫǬǭǰǴǵǷǸǹǺǻǼǽǾǿȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏȐȑȒȓȔȕȖȗȘșȚțȞȟȤȥȦȧȨȩ" to += "oooojggpnnaaeeooaaaaeeeeiiiioooorrrruuuusstthhzzaaee" mfrom += "ȪȫȬȭȮȯȰȱȲȳḀḁḂḃḄḅḆḇḈḉḊḋḌḍḎḏḐḑḒḓḔḕḖḗḘḙḚḛḜḝḞḟḠḡḢḣḤḥḦḧḨḩḪḫ" to += "ooooooooyyaabbbbbbccddddddddddeeeeeeeeeeffgghhhhhhhhhh" mfrom += "ḬḭḮḯḰḱḲḳḴḵḶḷḸḹḺḻḼḽḾḿṀṁṂṃṄṅṆṇṈṉṊṋṌṍṎṏṐṑṒṓṔṕṖṗṘṙṚṛṜṝṞṟ" to += "iiiikkkkkkllllllllmmmmmmnnnnnnnnoooooooopppprrrrrrrr" mfrom += "ṠṡṢṣṤṥṦṧṨṩṪṫṬṭṮṯṰṱṲṳṴṵṶṷṸṹṺṻṼṽṾṿẀẁẂẃẄẅẆẇẈẉẊẋẌẍẎẏẐẑẒẓẔẕ" to += "ssssssssssttttttttuuuuuuuuuuvvvvwwwwwwwwwwxxxxxyzzzzzz" mfrom += "ẖẗẘẙẚẛẠạẢảẤấẦầẨẩẪẫẬậẮắẰằẲẳẴẵẶặẸẹẺẻẼẽẾếỀềỂểỄễỆệỈỉỊị" to += "htwyafaaaaaaaaaaaaaaaaaaaaaaaaeeeeeeeeeeeeeeeeiiii" mfrom += "ỌọỎỏỐốỒồỔổỖỗỘộỚớỜờỞởỠỡỢợỤụỦủỨứỪừỬửỮữỰựỲỳỴỵỶỷỸỹ" to += "oooooooooooooooooooooooouuuuuuuuuuuuuuyyyyyyyy" for i in zip(mfrom, to): str = str.replace(*i) return str
Takes a UTF-8 string and replaces all characters with the equivalent in 7-bit ASCII. It returns a plain ASCII string usable in URLs.
def putlogo(figure=None): """Puts the CREDO logo at the bottom right of the current figure (or the figure given by the ``figure`` argument if supplied). """ ip = get_ipython() if figure is None: figure=plt.gcf() curraxis= figure.gca() logoaxis = figure.add_axes([0.89, 0.01, 0.1, 0.1], anchor='NW') logoaxis.set_axis_off() logoaxis.xaxis.set_visible(False) logoaxis.yaxis.set_visible(False) logoaxis.imshow(credo_logo) figure.subplots_adjust(right=0.98) figure.sca(curraxis)
Puts the CREDO logo at the bottom right of the current figure (or the figure given by the ``figure`` argument if supplied).
def receive_verify_post(self, post_params): """ Returns true if the incoming request is an authenticated verify post. """ if isinstance(post_params, dict): required_params = ['action', 'email', 'send_id', 'sig'] if not self.check_for_valid_postback_actions(required_params, post_params): return False else: return False if post_params['action'] != 'verify': return False sig = post_params['sig'] post_params = post_params.copy() del post_params['sig'] if sig != get_signature_hash(post_params, self.secret): return False send_response = self.get_send(post_params['send_id']) try: send_body = send_response.get_body() send_json = json.loads(send_body) if 'email' not in send_body: return False if send_json['email'] != post_params['email']: return False except ValueError: return False return True
Returns true if the incoming request is an authenticated verify post.
def create_fixed_rate_shipping(cls, fixed_rate_shipping, **kwargs): """Create FixedRateShipping Create a new FixedRateShipping This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_fixed_rate_shipping(fixed_rate_shipping, async=True) >>> result = thread.get() :param async bool :param FixedRateShipping fixed_rate_shipping: Attributes of fixedRateShipping to create (required) :return: FixedRateShipping If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._create_fixed_rate_shipping_with_http_info(fixed_rate_shipping, **kwargs) else: (data) = cls._create_fixed_rate_shipping_with_http_info(fixed_rate_shipping, **kwargs) return data
Create FixedRateShipping Create a new FixedRateShipping This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_fixed_rate_shipping(fixed_rate_shipping, async=True) >>> result = thread.get() :param async bool :param FixedRateShipping fixed_rate_shipping: Attributes of fixedRateShipping to create (required) :return: FixedRateShipping If the method is called asynchronously, returns the request thread.
def __get_sentence(counts, sentence_id=None): """Let's fetch a random sentence that we then need to substitute bits of... @ :param counts: :param sentence_id: """ # First of all we need a cursor and a query to retrieve our ID's cursor = CONN.cursor() check_query = "select sen_id from sursentences" # Now we fetch the result of the query and save it into check_result cursor.execute(check_query) check_result = cursor.fetchall() # declare an empty list to be populated below id_list = [] id_to_fetch = None # Populate the id_list variable with all of the ID's we retrieved from the database query. for row in check_result: id_list.append(row[0]) if sentence_id is not None: if type(sentence_id) is int: id_to_fetch = sentence_id else: id_to_fetch = random.randint(1, counts['max_sen']) while id_to_fetch not in id_list: id_to_fetch = random.randint(1, counts['max_sen']) query = ("select * from sursentences where sen_id = {0}".format(id_to_fetch)) cursor.execute(query) result = cursor.fetchone() # cursor.close() return result
Let's fetch a random sentence that we then need to substitute bits of... @ :param counts: :param sentence_id:
def run(self): """Run the main loop. Returns exit code.""" self.exit_code = 1 self.mainloop = GLib.MainLoop() try: future = ensure_future(self._start_async_tasks()) future.callbacks.append(self.set_exit_code) self.mainloop.run() return self.exit_code except KeyboardInterrupt: return 1
Run the main loop. Returns exit code.
def attempt_reauthorization(blink): """Attempt to refresh auth token and links.""" _LOGGER.info("Auth token expired, attempting reauthorization.") headers = blink.get_auth_token(is_retry=True) return headers
Attempt to refresh auth token and links.
def serialize(self): """ Generates the messaging-type-related part of the message dictionary. """ if self.response is not None: return {'messaging_type': 'RESPONSE'} if self.update is not None: return {'messaging_type': 'UPDATE'} if self.tag is not None: return { 'messaging_type': 'MESSAGE_TAG', 'tag': self.tag.value, } if self.subscription is not None: return {'messaging_type': 'NON_PROMOTIONAL_SUBSCRIPTION'}
Generates the messaging-type-related part of the message dictionary.
def statsHandler(serverName, path=''): """Renders a GET request, by showing this nodes stats and children.""" path = path.lstrip('/') parts = path.split('/') if not parts[0]: parts = parts[1:] statDict = util.lookup(scales.getStats(), parts) if statDict is None: abort(404, 'No stats found with path /%s' % '/'.join(parts)) output = StringIO() outputFormat = request.args.get('format', 'html') query = request.args.get('query', None) if outputFormat == 'json': formats.jsonFormat(output, statDict, query) elif outputFormat == 'prettyjson': formats.jsonFormat(output, statDict, query, pretty=True) else: formats.htmlHeader(output, '/' + path, serverName, query) formats.htmlFormat(output, tuple(parts), statDict, query) return output.getvalue()
Renders a GET request, by showing this nodes stats and children.
def dumps(xs, model=None, properties=False, indent=True, **kwargs): """ Serialize Xmrs (or subclass) objects to PENMAN notation Args: xs: iterator of :class:`~delphin.mrs.xmrs.Xmrs` objects to serialize model: Xmrs subclass used to get triples properties: if `True`, encode variable properties indent: if `True`, adaptively indent; if `False` or `None`, don't indent; if a non-negative integer N, indent N spaces per level Returns: the PENMAN serialization of *xs* """ xs = list(xs) if not xs: return '' given_class = xs[0].__class__ # assume they are all the same if model is None: model = xs[0].__class__ if not hasattr(model, 'to_triples'): raise TypeError( '{} class does not implement to_triples()'.format(model.__name__) ) # convert MRS to DMRS if necessary; EDS cannot convert if given_class.__name__ in ('Mrs', 'Xmrs'): xs = [model.from_xmrs(x, **kwargs) for x in xs] elif given_class.__name__ == 'Eds' and model.__name__ != 'Eds': raise ValueError('Cannot convert EDS to non-EDS') codec = XMRSCodec() graphs = [ codec.triples_to_graph(model.to_triples(x, properties=properties)) for x in xs ] if 'pretty_print' in kwargs: indent = kwargs['pretty_print'] return penman.dumps(graphs, cls=XMRSCodec, indent=indent)
Serialize Xmrs (or subclass) objects to PENMAN notation Args: xs: iterator of :class:`~delphin.mrs.xmrs.Xmrs` objects to serialize model: Xmrs subclass used to get triples properties: if `True`, encode variable properties indent: if `True`, adaptively indent; if `False` or `None`, don't indent; if a non-negative integer N, indent N spaces per level Returns: the PENMAN serialization of *xs*
def pixdump( source, start=None, end=None, length=None, width=64, height=None, palette=None ): """Print the contents of a byte string as a 256 colour image. source The byte string to print. start Start offset to read from (default: start) end End offset to stop reading at (default: end) length Length to read in (optional replacement for end) width Width of image to render in pixels (default: 64) height Height of image to render in pixels (default: auto) palette List of Colours to use (default: test palette) """ for line in pixdump_iter( source, start, end, length, width, height, palette ): print( line )
Print the contents of a byte string as a 256 colour image. source The byte string to print. start Start offset to read from (default: start) end End offset to stop reading at (default: end) length Length to read in (optional replacement for end) width Width of image to render in pixels (default: 64) height Height of image to render in pixels (default: auto) palette List of Colours to use (default: test palette)
def pad_or_truncate( audio_reference, audio_estimates ): """Pad or truncate estimates by duration of references: - If reference > estimates: add zeros at the and of the estimated signal - If estimates > references: truncate estimates to duration of references Parameters ---------- references : np.ndarray, shape=(nsrc, nsampl, nchan) array containing true reference sources estimates : np.ndarray, shape=(nsrc, nsampl, nchan) array containing estimated sources Returns ------- references : np.ndarray, shape=(nsrc, nsampl, nchan) array containing true reference sources estimates : np.ndarray, shape=(nsrc, nsampl, nchan) array containing estimated sources """ est_shape = audio_estimates.shape ref_shape = audio_reference.shape if est_shape[1] != ref_shape[1]: if est_shape[1] >= ref_shape[1]: audio_estimates = audio_estimates[:, :ref_shape[1], :] else: # pad end with zeros audio_estimates = np.pad( audio_estimates, [ (0, 0), (0, ref_shape[1] - est_shape[1]), (0, 0) ], mode='constant' ) return audio_reference, audio_estimates
Pad or truncate estimates by duration of references: - If reference > estimates: add zeros at the and of the estimated signal - If estimates > references: truncate estimates to duration of references Parameters ---------- references : np.ndarray, shape=(nsrc, nsampl, nchan) array containing true reference sources estimates : np.ndarray, shape=(nsrc, nsampl, nchan) array containing estimated sources Returns ------- references : np.ndarray, shape=(nsrc, nsampl, nchan) array containing true reference sources estimates : np.ndarray, shape=(nsrc, nsampl, nchan) array containing estimated sources
def add_scm_info(self): """Adds SCM-related info.""" scm = get_scm() if scm: revision = scm.commit_id branch = scm.branch_name or revision else: revision, branch = 'none', 'none' self.add_infos(('revision', revision), ('branch', branch))
Adds SCM-related info.
def _rectForce(x,pot,t=0.): """ NAME: _rectForce PURPOSE: returns the force in the rectangular frame INPUT: x - current position t - current time pot - (list of) Potential instance(s) OUTPUT: force HISTORY: 2011-02-02 - Written - Bovy (NYU) """ #x is rectangular so calculate R and phi R= nu.sqrt(x[0]**2.+x[1]**2.) phi= nu.arccos(x[0]/R) sinphi= x[1]/R cosphi= x[0]/R if x[1] < 0.: phi= 2.*nu.pi-phi #calculate forces Rforce= _evaluateRforces(pot,R,x[2],phi=phi,t=t) phiforce= _evaluatephiforces(pot,R,x[2],phi=phi,t=t) return nu.array([cosphi*Rforce-1./R*sinphi*phiforce, sinphi*Rforce+1./R*cosphi*phiforce, _evaluatezforces(pot,R,x[2],phi=phi,t=t)])
NAME: _rectForce PURPOSE: returns the force in the rectangular frame INPUT: x - current position t - current time pot - (list of) Potential instance(s) OUTPUT: force HISTORY: 2011-02-02 - Written - Bovy (NYU)
def fragment(self, fragment_size, mask=False): """ Fragment the frame into a chain of fragment frames: - An initial frame with non-zero opcode - Zero or more frames with opcode = 0 and final = False - A final frame with opcode = 0 and final = True The first and last frame may be the same frame, having a non-zero opcode and final = True. Thus, this function returns a list containing at least a single frame. `fragment_size` indicates the maximum payload size of each fragment. The payload of the original frame is split into one or more parts, and each part is converted to a Frame instance. `mask` is a boolean (default False) indicating whether the payloads should be masked. If True, each frame is assigned a randomly generated masking key. """ frames = [] for start in xrange(0, len(self.payload), fragment_size): payload = self.payload[start:start + fragment_size] frames.append(Frame(OPCODE_CONTINUATION, payload, mask=mask, final=False)) frames[0].opcode = self.opcode frames[-1].final = True return frames
Fragment the frame into a chain of fragment frames: - An initial frame with non-zero opcode - Zero or more frames with opcode = 0 and final = False - A final frame with opcode = 0 and final = True The first and last frame may be the same frame, having a non-zero opcode and final = True. Thus, this function returns a list containing at least a single frame. `fragment_size` indicates the maximum payload size of each fragment. The payload of the original frame is split into one or more parts, and each part is converted to a Frame instance. `mask` is a boolean (default False) indicating whether the payloads should be masked. If True, each frame is assigned a randomly generated masking key.
def nl_socket_alloc(cb=None): """Allocate new Netlink socket. Does not yet actually open a socket. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L206 Also has code for generating local port once. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L123 Keyword arguments: cb -- custom callback handler. Returns: Newly allocated Netlink socket (nl_sock class instance) or None. """ # Allocate the callback. cb = cb or nl_cb_alloc(default_cb) if not cb: return None # Allocate the socket. sk = nl_sock() sk.s_cb = cb sk.s_local.nl_family = getattr(socket, 'AF_NETLINK', -1) sk.s_peer.nl_family = getattr(socket, 'AF_NETLINK', -1) sk.s_seq_expect = sk.s_seq_next = int(time.time()) sk.s_flags = NL_OWN_PORT # The port is 0 (unspecified), meaning NL_OWN_PORT. # Generate local port. nl_socket_get_local_port(sk) # I didn't find this in the C source, but during testing I saw this behavior. return sk
Allocate new Netlink socket. Does not yet actually open a socket. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L206 Also has code for generating local port once. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L123 Keyword arguments: cb -- custom callback handler. Returns: Newly allocated Netlink socket (nl_sock class instance) or None.
def move_to(x, y): """ Sets the mouse's location to the specified coordinates. """ for b in _button_state: if _button_state[b]: e = Quartz.CGEventCreateMouseEvent( None, _button_mapping[b][3], # Drag Event (x, y), _button_mapping[b][0]) break else: e = Quartz.CGEventCreateMouseEvent( None, Quartz.kCGEventMouseMoved, (x, y), Quartz.kCGMouseButtonLeft) Quartz.CGEventPost(Quartz.kCGHIDEventTap, e)
Sets the mouse's location to the specified coordinates.
def readable_mem(mem): """ :param mem: An integer number of bytes to convert to human-readable form. :return: A human-readable string representation of the number. """ for suffix in ["", "K", "M", "G", "T"]: if mem < 10000: return "{}{}".format(int(mem), suffix) mem /= 1024 return "{}P".format(int(mem))
:param mem: An integer number of bytes to convert to human-readable form. :return: A human-readable string representation of the number.
def get_activities_by_ids(self, activity_ids): """Gets an ``ActivityList`` corresponding to the given ``IdList``. In plenary mode, the returned list contains all of the activities specified in the ``Id`` list, in the order of the list, including duplicates, or an error results if an ``Id`` in the supplied list is not found or inaccessible. Otherwise, inaccessible ``Activities`` may be omitted from the list and may present the elements in any order including returning a unique set. arg: activity_ids (osid.id.IdList): the list of ``Ids`` to retrieve return: (osid.learning.ActivityList) - the returned ``Activity`` list raise: NotFound - an ``Id was`` not found raise: NullArgument - ``activity_ids`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for # osid.resource.ResourceLookupSession.get_resources_by_ids # NOTE: This implementation currently ignores plenary view collection = JSONClientValidated('learning', collection='Activity', runtime=self._runtime) object_id_list = [] for i in activity_ids: object_id_list.append(ObjectId(self._get_id(i, 'learning').get_identifier())) result = collection.find( dict({'_id': {'$in': object_id_list}}, **self._view_filter())) result = list(result) sorted_result = [] for object_id in object_id_list: for object_map in result: if object_map['_id'] == object_id: sorted_result.append(object_map) break return objects.ActivityList(sorted_result, runtime=self._runtime, proxy=self._proxy)
Gets an ``ActivityList`` corresponding to the given ``IdList``. In plenary mode, the returned list contains all of the activities specified in the ``Id`` list, in the order of the list, including duplicates, or an error results if an ``Id`` in the supplied list is not found or inaccessible. Otherwise, inaccessible ``Activities`` may be omitted from the list and may present the elements in any order including returning a unique set. arg: activity_ids (osid.id.IdList): the list of ``Ids`` to retrieve return: (osid.learning.ActivityList) - the returned ``Activity`` list raise: NotFound - an ``Id was`` not found raise: NullArgument - ``activity_ids`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- This method must be implemented.*
def update_asset(self, asset_form=None): """Updates an existing asset. arg: asset_form (osid.repository.AssetForm): the form containing the elements to be updated raise: IllegalState - ``asset_form`` already used in anupdate transaction raise: InvalidArgument - the form contains an invalid value raise: NullArgument - ``asset_form`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure raise: Unsupported - ``asset_form`` did not originate from ``get_asset_form_for_update()`` *compliance: mandatory -- This method must be implemented.* """ return Asset(self._provider_session.update_asset(asset_form), self._config_map)
Updates an existing asset. arg: asset_form (osid.repository.AssetForm): the form containing the elements to be updated raise: IllegalState - ``asset_form`` already used in anupdate transaction raise: InvalidArgument - the form contains an invalid value raise: NullArgument - ``asset_form`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure raise: Unsupported - ``asset_form`` did not originate from ``get_asset_form_for_update()`` *compliance: mandatory -- This method must be implemented.*
def module_description_list(head): """Convert a ModuleDescription linked list to a Python list (and release the former). """ r = [] if head: item = head while item: item = item.contents r.append((item.name, item.shortname, item.longname, item.help)) item = item.next libvlc_module_description_list_release(head) return r
Convert a ModuleDescription linked list to a Python list (and release the former).
def is_all_field_none(self): """ :rtype: bool """ if self._id_ is not None: return False if self._created is not None: return False if self._updated is not None: return False if self._year is not None: return False if self._alias_user is not None: return False return True
:rtype: bool
def delete_files(): """ Delete one or more files from the server """ session_token = request.headers['session_token'] repository = request.headers['repository'] #=== current_user = have_authenticated_user(request.environ['REMOTE_ADDR'], repository, session_token) if current_user is False: return fail(user_auth_fail_msg) #=== repository_path = config['repositories'][repository]['path'] body_data = request.get_json() def with_exclusive_lock(): if not varify_user_lock(repository_path, session_token): return fail(lock_fail_msg) try: data_store = versioned_storage(repository_path) if not data_store.have_active_commit(): return fail(no_active_commit_msg) #------------- for fle in json.loads(body_data['files']): data_store.fs_delete(fle) # updates the user lock expiry update_user_lock(repository_path, session_token) return success() except Exception: return fail() # pylint: disable=broad-except return lock_access(repository_path, with_exclusive_lock)
Delete one or more files from the server
def raise_errors(self, response): """The innermost part - report errors by exceptions""" # Errors: 400, 403 permissions or REQUEST_LIMIT_EXCEEDED, 404, 405, 415, 500) # TODO extract a case ID for Salesforce support from code 500 messages # TODO disabled 'debug_verbs' temporarily, after writing better default messages verb = self.debug_verbs # NOQA pylint:disable=unused-variable method = response.request.method data = None is_json = 'json' in response.headers.get('Content-Type', '') and response.text if is_json: data = json.loads(response.text) if not (isinstance(data, list) and data and 'errorCode' in data[0]): messages = [response.text] if is_json else [] raise OperationalError( ['HTTP error "%d %s":' % (response.status_code, response.reason)] + messages, response, ['method+url']) # Other Errors are reported in the json body err_msg = data[0]['message'] err_code = data[0]['errorCode'] if response.status_code == 404: # ResourceNotFound if method == 'DELETE' and err_code in ('ENTITY_IS_DELETED', 'INVALID_CROSS_REFERENCE_KEY'): # It was a delete command and the object is in trash bin or it is # completely deleted or it could be a valid Id for this sobject type. # Then we accept it with a warning, similarly to delete by a classic database query: # DELETE FROM xy WHERE id = 'something_deleted_yet' warn_sf([err_msg, "Object is deleted before delete or update"], response, ['method+url']) # TODO add a warning and add it to messages return None if err_code in ('NOT_FOUND', # 404 e.g. invalid object type in url path or url query?q=select ... 'METHOD_NOT_ALLOWED', # 405 e.g. patch instead of post ): # both need to report the url raise SalesforceError([err_msg], response, ['method+url']) # it is good e.g for these errorCode: ('INVALID_FIELD', 'MALFORMED_QUERY', 'INVALID_FIELD_FOR_INSERT_UPDATE') raise SalesforceError([err_msg], response)
The innermost part - report errors by exceptions
def num_throats(self, labels='all', mode='union'): r""" Return the number of throats of the specified labels Parameters ---------- labels : list of strings, optional The throat labels that should be included in the count. If not supplied, all throats are counted. mode : string, optional Specifies how the count should be performed. The options are: **'or', 'union', 'any'** : (default) Throats with *one or more* of the given labels are counted. **'and', 'intersection', 'all'** : Throats with *all* of the given labels are counted. **'xor', 'exclusive_or'** : Throats with *only one* of the given labels are counted. **'nor', 'none', 'not'** : Throats with *none* of the given labels are counted. **'nand'** : Throats with *some but not all* of the given labels are counted. **'xnor'** : Throats with *more than one* of the given labels are counted. Returns ------- Nt : int Number of throats with the specified labels See Also -------- num_pores count Notes ----- Technically, *'nand'* and *'xnor'* should also count throats with *none* of the labels, however, to make the count more useful these are not included. """ # Count number of pores of specified type Ts = self._get_indices(labels=labels, mode=mode, element='throat') Nt = sp.shape(Ts)[0] return Nt
r""" Return the number of throats of the specified labels Parameters ---------- labels : list of strings, optional The throat labels that should be included in the count. If not supplied, all throats are counted. mode : string, optional Specifies how the count should be performed. The options are: **'or', 'union', 'any'** : (default) Throats with *one or more* of the given labels are counted. **'and', 'intersection', 'all'** : Throats with *all* of the given labels are counted. **'xor', 'exclusive_or'** : Throats with *only one* of the given labels are counted. **'nor', 'none', 'not'** : Throats with *none* of the given labels are counted. **'nand'** : Throats with *some but not all* of the given labels are counted. **'xnor'** : Throats with *more than one* of the given labels are counted. Returns ------- Nt : int Number of throats with the specified labels See Also -------- num_pores count Notes ----- Technically, *'nand'* and *'xnor'* should also count throats with *none* of the labels, however, to make the count more useful these are not included.
def process_slo(self, keep_local_session=False, request_id=None, delete_session_cb=None): """ Process the SAML Logout Response / Logout Request sent by the IdP. :param keep_local_session: When false will destroy the local session, otherwise will destroy it :type keep_local_session: bool :param request_id: The ID of the LogoutRequest sent by this SP to the IdP :type request_id: string :returns: Redirection url """ self.__errors = [] self.__error_reason = None get_data = 'get_data' in self.__request_data and self.__request_data['get_data'] if get_data and 'SAMLResponse' in get_data: logout_response = OneLogin_Saml2_Logout_Response(self.__settings, get_data['SAMLResponse']) self.__last_response = logout_response.get_xml() if not self.validate_response_signature(get_data): self.__errors.append('invalid_logout_response_signature') self.__errors.append('Signature validation failed. Logout Response rejected') elif not logout_response.is_valid(self.__request_data, request_id): self.__errors.append('invalid_logout_response') self.__error_reason = logout_response.get_error() elif logout_response.get_status() != OneLogin_Saml2_Constants.STATUS_SUCCESS: self.__errors.append('logout_not_success') else: self.__last_message_id = logout_response.id if not keep_local_session: OneLogin_Saml2_Utils.delete_local_session(delete_session_cb) elif get_data and 'SAMLRequest' in get_data: logout_request = OneLogin_Saml2_Logout_Request(self.__settings, get_data['SAMLRequest']) self.__last_request = logout_request.get_xml() if not self.validate_request_signature(get_data): self.__errors.append("invalid_logout_request_signature") self.__errors.append('Signature validation failed. Logout Request rejected') elif not logout_request.is_valid(self.__request_data): self.__errors.append('invalid_logout_request') self.__error_reason = logout_request.get_error() else: if not keep_local_session: OneLogin_Saml2_Utils.delete_local_session(delete_session_cb) in_response_to = logout_request.id self.__last_message_id = logout_request.id response_builder = OneLogin_Saml2_Logout_Response(self.__settings) response_builder.build(in_response_to) self.__last_response = response_builder.get_xml() logout_response = response_builder.get_response() parameters = {'SAMLResponse': logout_response} if 'RelayState' in self.__request_data['get_data']: parameters['RelayState'] = self.__request_data['get_data']['RelayState'] security = self.__settings.get_security_data() if security['logoutResponseSigned']: self.add_response_signature(parameters, security['signatureAlgorithm']) return self.redirect_to(self.get_slo_url(), parameters) else: self.__errors.append('invalid_binding') raise OneLogin_Saml2_Error( 'SAML LogoutRequest/LogoutResponse not found. Only supported HTTP_REDIRECT Binding', OneLogin_Saml2_Error.SAML_LOGOUTMESSAGE_NOT_FOUND )
Process the SAML Logout Response / Logout Request sent by the IdP. :param keep_local_session: When false will destroy the local session, otherwise will destroy it :type keep_local_session: bool :param request_id: The ID of the LogoutRequest sent by this SP to the IdP :type request_id: string :returns: Redirection url
def stock2one(stock): """ convert stockholm to single line format """ lines = {} for line in stock: line = line.strip() if print_line(line) is True: yield line continue if line.startswith('//'): continue ID, seq = line.rsplit(' ', 1) if ID not in lines: lines[ID] = '' else: # remove preceding white space seq = seq.strip() lines[ID] += seq for ID, line in lines.items(): yield '\t'.join([ID, line]) yield '\n//'
convert stockholm to single line format
def load_snippets_html(cls, src_path, violation_lines): """ Load snippets from the file at `src_path` and format them as HTML. See `load_snippets()` for details. """ snippet_list = cls.load_snippets(src_path, violation_lines) return [snippet.html() for snippet in snippet_list]
Load snippets from the file at `src_path` and format them as HTML. See `load_snippets()` for details.
def lsf(self, astr_path=""): """ List only the "files" in the astr_path. :param astr_path: path to list :return: "files" in astr_path, empty list if no files """ d_files = self.ls(astr_path, nodes=False, data=True) l_files = d_files.keys() return l_files
List only the "files" in the astr_path. :param astr_path: path to list :return: "files" in astr_path, empty list if no files
def presence_handler(type_, from_): """ Deprecated alias of :func:`.dispatcher.presence_handler`. .. deprecated:: 0.9 """ import aioxmpp.dispatcher return aioxmpp.dispatcher.presence_handler(type_, from_)
Deprecated alias of :func:`.dispatcher.presence_handler`. .. deprecated:: 0.9
def update_number(self, number, payload_number_modification, **kwargs): # noqa: E501 """Assign number # noqa: E501 With this API call you will be able to assign a specific number to a specific account (one of your members). # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_number(number, payload_number_modification, async=True) >>> result = thread.get() :param async bool :param str number: (required) :param PayloadNumberModification payload_number_modification: (required) :return: None If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): return self.update_number_with_http_info(number, payload_number_modification, **kwargs) # noqa: E501 else: (data) = self.update_number_with_http_info(number, payload_number_modification, **kwargs) # noqa: E501 return data
Assign number # noqa: E501 With this API call you will be able to assign a specific number to a specific account (one of your members). # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_number(number, payload_number_modification, async=True) >>> result = thread.get() :param async bool :param str number: (required) :param PayloadNumberModification payload_number_modification: (required) :return: None If the method is called asynchronously, returns the request thread.
def call(self, folders, additional_fields, shape): """ Takes a folder ID and returns the full information for that folder. :param folders: a list of Folder objects :param additional_fields: the extra fields that should be returned with the folder, as FieldPath objects :param shape: The set of attributes to return :return: XML elements for the folders, in stable order """ # We can't easily find the correct folder class from the returned XML. Instead, return objects with the same # class as the folder instance it was requested with. from .folders import Folder, DistinguishedFolderId, RootOfHierarchy folders_list = list(folders) # Convert to a list, in case 'folders' is a generator for folder, elem in zip(folders_list, self._get_elements(payload=self.get_payload( folders=folders, additional_fields=additional_fields, shape=shape, ))): if isinstance(elem, Exception): yield elem continue if isinstance(folder, RootOfHierarchy): f = folder.from_xml(elem=elem, account=self.account) elif isinstance(folder, Folder): f = folder.from_xml(elem=elem, root=folder.root) elif isinstance(folder, DistinguishedFolderId): # We don't know the root, so assume account.root. for folder_cls in self.account.root.WELLKNOWN_FOLDERS: if folder_cls.DISTINGUISHED_FOLDER_ID == folder.id: break else: raise ValueError('Unknown distinguished folder ID: %s', folder.id) f = folder_cls.from_xml(elem=elem, root=self.account.root) else: # 'folder' is a generic FolderId instance. We don't know the root so assume account.root. f = Folder.from_xml(elem=elem, root=self.account.root) if isinstance(folder, DistinguishedFolderId): f.is_distinguished = True elif isinstance(folder, Folder) and folder.is_distinguished: f.is_distinguished = True yield f
Takes a folder ID and returns the full information for that folder. :param folders: a list of Folder objects :param additional_fields: the extra fields that should be returned with the folder, as FieldPath objects :param shape: The set of attributes to return :return: XML elements for the folders, in stable order
def get_exitcode_reactor(): """ This is only neccesary until a fix like the one outlined here is implemented for Twisted: http://twistedmatrix.com/trac/ticket/2182 """ from twisted.internet.main import installReactor from twisted.internet.selectreactor import SelectReactor class ExitCodeReactor(SelectReactor): def stop(self, exitStatus=0): super(ExitCodeReactor, self).stop() self.exitStatus = exitStatus def run(self, *args, **kwargs): super(ExitCodeReactor, self).run(*args, **kwargs) return self.exitStatus reactor = ExitCodeReactor() installReactor(reactor) return reactor
This is only neccesary until a fix like the one outlined here is implemented for Twisted: http://twistedmatrix.com/trac/ticket/2182
def bounds(sceneid): """ Retrieve image bounds. Attributes ---------- sceneid : str CBERS sceneid. Returns ------- out : dict dictionary with image bounds. """ scene_params = _cbers_parse_scene_id(sceneid) cbers_address = "{}/{}".format(CBERS_BUCKET, scene_params["key"]) with rasterio.open( "{}/{}_BAND{}.tif".format( cbers_address, sceneid, scene_params["reference_band"] ) ) as src: wgs_bounds = transform_bounds( *[src.crs, "epsg:4326"] + list(src.bounds), densify_pts=21 ) info = {"sceneid": sceneid} info["bounds"] = list(wgs_bounds) return info
Retrieve image bounds. Attributes ---------- sceneid : str CBERS sceneid. Returns ------- out : dict dictionary with image bounds.
def enter_cli_mode(self): """Check if at shell prompt root@ and go into CLI.""" delay_factor = self.select_delay_factor(delay_factor=0) count = 0 cur_prompt = "" while count < 50: self.write_channel(self.RETURN) time.sleep(0.1 * delay_factor) cur_prompt = self.read_channel() if re.search(r"root@", cur_prompt) or re.search(r"^%$", cur_prompt.strip()): self.write_channel("cli" + self.RETURN) time.sleep(0.3 * delay_factor) self.clear_buffer() break elif ">" in cur_prompt or "#" in cur_prompt: break count += 1
Check if at shell prompt root@ and go into CLI.
def congiguration(self): """Manage slpkg configuration file """ options = [ "-g", "--config" ] command = [ "print", "edit", "reset" ] conf = Config() if (len(self.args) == 2 and self.args[0] in options and self.args[1] == command[1]): conf.edit() elif (len(self.args) == 2 and self.args[0] in options and self.args[1] == (command[0])): conf.view() elif (len(self.args) == 2 and self.args[0] in options and self.args[1] == (command[2])): conf.reset() else: usage("")
Manage slpkg configuration file
def emit_map(self, m, _, cache): """Emits array as per default JSON spec.""" self.emit_array_start(None) self.marshal(MAP_AS_ARR, False, cache) for k, v in m.items(): self.marshal(k, True, cache) self.marshal(v, False, cache) self.emit_array_end()
Emits array as per default JSON spec.