code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class ABCMutableSetMap(ABCSetMap, MutableSet): <NEW_LINE> <INDENT> pass
Abstract SetMap class that allows mutation via add/update/discard/remove In addition to abstract methods `__getitem__` and `data` as for SetMap, this class requires methods `add` and `discard`. From those it supplies methods `update`, `remove`, `clear`, `pop` and the in-place set operations.
62598fd4dc8b845886d53a82
class AnimReplacementSet(Structure): <NEW_LINE> <INDENT> fields = Skeleton( IDField(), UnknownField(), )
AnimReplacementSet.dbc New in 4.0.0.11927
62598fd497e22403b383b3ce
class QuadPotentialFullInv(QuadPotential): <NEW_LINE> <INDENT> def __init__(self, A, dtype=None): <NEW_LINE> <INDENT> if dtype is None: <NEW_LINE> <INDENT> dtype = "float32" <NEW_LINE> <DEDENT> self.dtype = dtype <NEW_LINE> self.L = scipy.linalg.cholesky(A, lower=True) <NEW_LINE> <DEDENT> def velocity(self, x, out=None): <NEW_LINE> <INDENT> vel = scipy.linalg.cho_solve((self.L, True), x) <NEW_LINE> if out is None: <NEW_LINE> <INDENT> return vel <NEW_LINE> <DEDENT> out[:] = vel <NEW_LINE> <DEDENT> def random(self): <NEW_LINE> <INDENT> n = normal(size=self.L.shape[0]) <NEW_LINE> return np.dot(self.L, n) <NEW_LINE> <DEDENT> def energy(self, x, velocity=None): <NEW_LINE> <INDENT> if velocity is None: <NEW_LINE> <INDENT> velocity = self.velocity(x) <NEW_LINE> <DEDENT> return 0.5 * x.dot(velocity) <NEW_LINE> <DEDENT> def velocity_energy(self, x, v_out): <NEW_LINE> <INDENT> self.velocity(x, out=v_out) <NEW_LINE> return 0.5 * np.dot(x, v_out)
QuadPotential object for Hamiltonian calculations using inverse of covariance matrix.
62598fd4bf627c535bcb1974
class TestScriptInputArguments(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.__input_args_parser = config_parse_input_args() <NEW_LINE> <DEDENT> def test_help_argument(self): <NEW_LINE> <INDENT> self.assertIsNotNone(self.__input_args_parser.format_help()) <NEW_LINE> <DEDENT> def test_dev_mode_help_argument(self): <NEW_LINE> <INDENT> self.__input_args_parser = config_parse_dev_mode(self.__input_args_parser) <NEW_LINE> self.assertIsNotNone(self.__input_args_parser.format_help()) <NEW_LINE> <DEDENT> def test_web_site_argument_no(self): <NEW_LINE> <INDENT> msg_str = "The default value of the web source must be tripadvisor" <NEW_LINE> input_args = self.__input_args_parser.parse_args([]) <NEW_LINE> self.assertEqual(input_args.web_source, "tripadvisor", msg_str) <NEW_LINE> <DEDENT> def test_web_site_argument_yes(self): <NEW_LINE> <INDENT> msg_str = "The web source argument value is not booking" <NEW_LINE> input_args = self.__input_args_parser.parse_args(["-w", "tripadvisor"]) <NEW_LINE> self.assertEqual(input_args.web_source, "tripadvisor", msg=msg_str) <NEW_LINE> <DEDENT> def test_output_template_argument_no(self): <NEW_LINE> <INDENT> msg_str = "The default output template is csv" <NEW_LINE> input_args = self.__input_args_parser.parse_args([]) <NEW_LINE> self.assertEqual(input_args.output_template, "csv", msg_str) <NEW_LINE> <DEDENT> def test_output_template_argument_yes(self): <NEW_LINE> <INDENT> msg_str = "The value of the output template must be xml" <NEW_LINE> input_args = self.__input_args_parser.parse_args(["-t", "xml"]) <NEW_LINE> self.assertEqual(input_args.output_template, "xml", msg_str) <NEW_LINE> <DEDENT> def test_output_path_argument_no(self): <NEW_LINE> <INDENT> msg_str = "The default output is stdout" <NEW_LINE> input_args = self.__input_args_parser.parse_args([]) <NEW_LINE> self.assertEqual(input_args.output_path, "stdout", msg_str) <NEW_LINE> <DEDENT> def test_output_path_argument_yes(self): <NEW_LINE> <INDENT> msg_str = "The value of the output path must be /home/geni/reviews.txt" <NEW_LINE> input_args = self.__input_args_parser.parse_args(["-o", "/home/geni/reviews.txt"]) <NEW_LINE> self.assertEqual(input_args.output_path, "/home/geni/reviews.txt", msg_str) <NEW_LINE> <DEDENT> def test_verbose_argument(self): <NEW_LINE> <INDENT> self.__input_args_parser.parse_args(["--verbose"]) <NEW_LINE> input_args = self.__input_args_parser.parse_args(["--verbose"]) <NEW_LINE> self.assertTrue(input_args.verbose)
Class for testing the parsing of the input of the script
62598fd40fa83653e46f53af
class DefensiveReflexAgent(ReflexCaptureAgent): <NEW_LINE> <INDENT> def chooseAction(self,gameState): <NEW_LINE> <INDENT> self.invader = [] <NEW_LINE> for i in self.getOpponents(gameState): <NEW_LINE> <INDENT> if gameState.getAgentState(i).isPacman and gameState.getAgentState(i).getPosition() != None: <NEW_LINE> <INDENT> self.invader.append(i) <NEW_LINE> <DEDENT> <DEDENT> self.invader.insert(0,self.index) <NEW_LINE> action,_ = self.alphabeta(gameState, 0, 0,self.invader) <NEW_LINE> return action <NEW_LINE> <DEDENT> def getFeatures(self, gameState): <NEW_LINE> <INDENT> features = util.Counter() <NEW_LINE> myState = gameState.getAgentState(self.index) <NEW_LINE> myPos = myState.getPosition() <NEW_LINE> features['onDefense'] = 1 <NEW_LINE> if myState.isPacman: features['onDefense'] = 0 <NEW_LINE> enemies = [gameState.getAgentState(i) for i in self.getOpponents(gameState)] <NEW_LINE> invaders = [a for a in enemies if a.isPacman and a.getPosition() != None] <NEW_LINE> features['numInvaders'] = len(invaders) <NEW_LINE> if len(invaders) > 0: <NEW_LINE> <INDENT> dists = [self.getMazeDistance(myPos, a.getPosition()) for a in invaders] <NEW_LINE> features['invaderDistance'] = min(dists) <NEW_LINE> <DEDENT> foodList = self.getFoodYouAreDefending(gameState).asList() <NEW_LINE> foodDstSum = 0.0 <NEW_LINE> foodDst = [self.getMazeDistance(myPos, food) for food in foodList] <NEW_LINE> foodDstSum = sum(foodDst) <NEW_LINE> features['defendFoodDst'] = foodDstSum <NEW_LINE> capsuleList = self.getCapsulesYouAreDefending(gameState) <NEW_LINE> capDstSum = 0.0 <NEW_LINE> capDst = [self.getMazeDistance(myPos, cap) for cap in capsuleList] <NEW_LINE> capSum = sum(capDst) <NEW_LINE> features['defendCapDst'] = capSum <NEW_LINE> return features <NEW_LINE> <DEDENT> def getWeights(self, gameState): <NEW_LINE> <INDENT> return {'numInvaders': -1, 'onDefense': 100,'invaderDistance': -50, 'defendFoodDst': -1, 'defendCapDst': -1}
A reflex agent that keeps its side Pacman-free. Again, this is to give you an idea of what a defensive agent could be like. It is not the best or only way to make such an agent.
62598fd4dc8b845886d53a84
class Array8(Generic[A1, A2, A3, A4, A5, A6, A7, A8], _ArrayBase): <NEW_LINE> <INDENT> pass
A tensor of rank 4.
62598fd4fbf16365ca794584
class V1PodTemplate(object): <NEW_LINE> <INDENT> def __init__(self, api_version=None, metadata=None, kind=None, template=None): <NEW_LINE> <INDENT> self.swagger_types = { 'api_version': 'str', 'metadata': 'V1ObjectMeta', 'kind': 'str', 'template': 'V1PodTemplateSpec' } <NEW_LINE> self.attribute_map = { 'api_version': 'apiVersion', 'metadata': 'metadata', 'kind': 'kind', 'template': 'template' } <NEW_LINE> self._api_version = api_version <NEW_LINE> self._metadata = metadata <NEW_LINE> self._kind = kind <NEW_LINE> self._template = template <NEW_LINE> <DEDENT> @property <NEW_LINE> def api_version(self): <NEW_LINE> <INDENT> return self._api_version <NEW_LINE> <DEDENT> @api_version.setter <NEW_LINE> def api_version(self, api_version): <NEW_LINE> <INDENT> self._api_version = api_version <NEW_LINE> <DEDENT> @property <NEW_LINE> def metadata(self): <NEW_LINE> <INDENT> return self._metadata <NEW_LINE> <DEDENT> @metadata.setter <NEW_LINE> def metadata(self, metadata): <NEW_LINE> <INDENT> self._metadata = metadata <NEW_LINE> <DEDENT> @property <NEW_LINE> def kind(self): <NEW_LINE> <INDENT> return self._kind <NEW_LINE> <DEDENT> @kind.setter <NEW_LINE> def kind(self, kind): <NEW_LINE> <INDENT> self._kind = kind <NEW_LINE> <DEDENT> @property <NEW_LINE> def template(self): <NEW_LINE> <INDENT> return self._template <NEW_LINE> <DEDENT> @template.setter <NEW_LINE> def template(self, template): <NEW_LINE> <INDENT> self._template = template <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598fd497e22403b383b3d0
class SqlData(NamedTuple): <NEW_LINE> <INDENT> text: List[str] <NEW_LINE> text_with_variables: List[str] <NEW_LINE> variable_tags: List[str] <NEW_LINE> sql: List[str] <NEW_LINE> text_variables: Dict[str, str] <NEW_LINE> sql_variables: Dict[str, str]
A utility class for reading in text2sql data. Parameters ---------- text : ``List[str]`` The tokens in the text of the query. text_with_variables : ``List[str]`` The tokens in the text of the query with variables mapped to table names/abstract variables. variable_tags : ``List[str]`` Labels for each word in ``text`` which correspond to which variable in the sql the token is linked to. "O" is used to denote no tag. sql : ``List[str]`` The tokens in the SQL query which corresponds to the text. text_variables : ``Dict[str, str]`` A dictionary of variables associated with the text, e.g. {"city_name0": "san fransisco"} sql_variables : ``Dict[str, str]`` A dictionary of variables associated with the sql query.
62598fd43d592f4c4edbb37d
class Repne(X86InstructionBase): <NEW_LINE> <INDENT> def __init__(self, prefix, mnemonic, operands, architecture_mode): <NEW_LINE> <INDENT> super(Repne, self).__init__(prefix, mnemonic, operands, architecture_mode) <NEW_LINE> <DEDENT> @property <NEW_LINE> def source_operands(self): <NEW_LINE> <INDENT> return [ ] <NEW_LINE> <DEDENT> @property <NEW_LINE> def destination_operands(self): <NEW_LINE> <INDENT> return [ ]
Representation of Repne x86 instruction.
62598fd4ad47b63b2c5a7d19
class Constant(InitializerMixin): <NEW_LINE> <INDENT> def _run_backend_specific_init(self): <NEW_LINE> <INDENT> self._initializer = tf.constant_initializer( value=self.args['value'], dtype=self._get_dtype())
Implement Constant in Tensorflow backend. See :any:`ConstantInitializer` for detail.
62598fd4377c676e912f6fdd
class UserTVShowCollectionView(APIView): <NEW_LINE> <INDENT> authentication_classes = (authentication.TokenAuthentication,) <NEW_LINE> @staticmethod <NEW_LINE> def get(request): <NEW_LINE> <INDENT> profile = get_object_or_404(UserProfile, user=request.user) <NEW_LINE> serializer = TVShowCollectionSerializer(profile.tv_shows, many=True, context={'profile': profile, 'request': request}) <NEW_LINE> return Response(serializer.data, status=status.HTTP_202_ACCEPTED)
A view for the tv-shows collection of current user.
62598fd40fa83653e46f53b0
class Match(object): <NEW_LINE> <INDENT> def __init__(self, c, p): <NEW_LINE> <INDENT> self.conf = c <NEW_LINE> self.point = p <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> if isinstance(other, Match): <NEW_LINE> <INDENT> return self.conf < other.conf <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> <DEDENT> def __le__(self, other): <NEW_LINE> <INDENT> if isinstance(other, Match): <NEW_LINE> <INDENT> return self.conf <= other.conf <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> <DEDENT> def __gt__(self, other): <NEW_LINE> <INDENT> if isinstance(other, Match): <NEW_LINE> <INDENT> return self.conf > other.conf <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> <DEDENT> def __ge__(self, other): <NEW_LINE> <INDENT> if isinstance(other, Match): <NEW_LINE> <INDENT> return self.conf >= other.conf <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return (self.conf, self.point).__str__()
This class stores a match of an image recognition task. :param c: The confidence with which the match was performed (between 0 and 1). :type c: float :param p: The point at which the template was found. :type p: :class:`Point` Comparison of ``Match``-objects is implemented by comparing the confidence-values. Therefore we can conveniently sort a list of ``Match``-objects.
62598fd43617ad0b5ee06611
class ControlElement(Disconnectable): <NEW_LINE> <INDENT> class ProxiedInterface(object): <NEW_LINE> <INDENT> send_midi = nop <NEW_LINE> reset_state = nop <NEW_LINE> def __init__(self, outer = None, *a, **k): <NEW_LINE> <INDENT> super(ControlElement.ProxiedInterface, self).__init__(*a, **k) <NEW_LINE> self._outer = outer <NEW_LINE> <DEDENT> @property <NEW_LINE> def outer(self): <NEW_LINE> <INDENT> return self._outer <NEW_LINE> <DEDENT> <DEDENT> @lazy_attribute <NEW_LINE> def proxied_interface(self): <NEW_LINE> <INDENT> return self.ProxiedInterface(outer=self) <NEW_LINE> <DEDENT> canonical_parent = None <NEW_LINE> name = '' <NEW_LINE> optimized_send_midi = True <NEW_LINE> _has_resource = False <NEW_LINE> _resource_type = StackingResource <NEW_LINE> _has_task_group = False <NEW_LINE> @depends(send_midi=None, register_control=None) <NEW_LINE> def __init__(self, name = '', resource_type = None, optimized_send_midi = None, send_midi = None, register_control = None, *a, **k): <NEW_LINE> <INDENT> super(ControlElement, self).__init__(*a, **k) <NEW_LINE> self._send_midi = send_midi <NEW_LINE> self.name = name <NEW_LINE> if resource_type is not None: <NEW_LINE> <INDENT> self._resource_type = resource_type <NEW_LINE> <DEDENT> if optimized_send_midi is not None: <NEW_LINE> <INDENT> self.optimized_send_midi = optimized_send_midi <NEW_LINE> <DEDENT> register_control(self) <NEW_LINE> <DEDENT> def disconnect(self): <NEW_LINE> <INDENT> self.reset() <NEW_LINE> super(ControlElement, self).disconnect() <NEW_LINE> <DEDENT> def send_midi(self, message): <NEW_LINE> <INDENT> raise message != None or AssertionError <NEW_LINE> return self._send_midi(message, optimized=self.optimized_send_midi) <NEW_LINE> <DEDENT> def clear_send_cache(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def reset_state(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @property <NEW_LINE> def resource(self): <NEW_LINE> <INDENT> return self._resource <NEW_LINE> <DEDENT> @lazy_attribute <NEW_LINE> def _resource(self): <NEW_LINE> <INDENT> self._has_resource = True <NEW_LINE> return self._resource_type(self._on_resource_received, self._on_resource_lost) <NEW_LINE> <DEDENT> @lazy_attribute <NEW_LINE> @depends(parent_task_group=Task.TaskGroup) <NEW_LINE> def _tasks(self, parent_task_group = None): <NEW_LINE> <INDENT> tasks = parent_task_group.add(Task.TaskGroup()) <NEW_LINE> self._has_task_group = True <NEW_LINE> return tasks <NEW_LINE> <DEDENT> def _on_resource_received(self, client, *a, **k): <NEW_LINE> <INDENT> self.notify_ownership_change(client, True) <NEW_LINE> <DEDENT> def _on_resource_lost(self, client): <NEW_LINE> <INDENT> self.notify_ownership_change(client, False) <NEW_LINE> <DEDENT> @depends(element_ownership_handler=const(ElementOwnershipHandler())) <NEW_LINE> def notify_ownership_change(self, client, grabbed, element_ownership_handler = None): <NEW_LINE> <INDENT> element_ownership_handler.handle_ownership_change(self, client, grabbed)
Base class for all classes representing control elements on a control surface
62598fd47cff6e4e811b5ef2
class FT6336U(): <NEW_LINE> <INDENT> read_buffer = bytearray(2) <NEW_LINE> write_buffer = bytearray(1) <NEW_LINE> def __init__(self, i2c, rst=None): <NEW_LINE> <INDENT> if I2C_ADDRESS not in i2c.scan(): <NEW_LINE> <INDENT> raise OSError("Chip not detected") <NEW_LINE> <DEDENT> self.i2c = i2c <NEW_LINE> self.rst = rst <NEW_LINE> if self._readfrom_mem(REG_ID_G_CIPHER_LOW) != CHIP_CODE_FT6336U: <NEW_LINE> <INDENT> raise OSError("Unsupported chip") <NEW_LINE> <DEDENT> self.set_mode_working() <NEW_LINE> <DEDENT> def _readfrom_mem(self, register, num_bytes=1): <NEW_LINE> <INDENT> self.i2c.readfrom_mem_into(I2C_ADDRESS, register, self.read_buffer) <NEW_LINE> if num_bytes == 1: <NEW_LINE> <INDENT> return int.from_bytes(self.read_buffer, "large") >> 8 <NEW_LINE> <DEDENT> if num_bytes == 2: <NEW_LINE> <INDENT> return int.from_bytes(self.read_buffer, "large") <NEW_LINE> <DEDENT> raise ValueError("Unsupported buffer size") <NEW_LINE> <DEDENT> def _writeto_mem(self, register, *data): <NEW_LINE> <INDENT> self.write_buffer[0] = data[0] <NEW_LINE> self.i2c.writeto_mem(I2C_ADDRESS, register, self.write_buffer) <NEW_LINE> <DEDENT> def set_mode_working(self): <NEW_LINE> <INDENT> self._writeto_mem(REG_MODE_SWITCH, DEVICE_MODE_WORKING) <NEW_LINE> <DEDENT> def set_mode_factory(self): <NEW_LINE> <INDENT> self._writeto_mem(REG_MODE_SWITCH, DEVICE_MODE_FACTORY) <NEW_LINE> <DEDENT> def get_points(self): <NEW_LINE> <INDENT> return self._readfrom_mem(REG_TD_STATUS) <NEW_LINE> <DEDENT> def get_p1_x(self): <NEW_LINE> <INDENT> return self._readfrom_mem(REG_P1_XH, num_bytes=2) & 0x0FFF <NEW_LINE> <DEDENT> def get_p1_y(self): <NEW_LINE> <INDENT> return self._readfrom_mem(REG_P1_YH, num_bytes=2) & 0x0FFF <NEW_LINE> <DEDENT> def get_p2_x(self): <NEW_LINE> <INDENT> return self._readfrom_mem(REG_P2_XH, num_bytes=2) & 0x0FFF <NEW_LINE> <DEDENT> def get_p2_y(self): <NEW_LINE> <INDENT> return self._readfrom_mem(REG_P2_YH, num_bytes=2) & 0x0FFF <NEW_LINE> <DEDENT> def get_positions(self): <NEW_LINE> <INDENT> positions = [] <NEW_LINE> num_points = self.get_points() <NEW_LINE> if num_points > 0: <NEW_LINE> <INDENT> positions.append((self.get_p1_x(),self.get_p1_y())) <NEW_LINE> <DEDENT> if num_points > 1: <NEW_LINE> <INDENT> positions.append((self.get_p2_x(),self.get_p2_y())) <NEW_LINE> <DEDENT> return positions
Focus LCDs' FT6336U driver and its interfaces
62598fd4ab23a570cc2d4fd2
class XEP_0300(BasePlugin): <NEW_LINE> <INDENT> name = 'xep_0300' <NEW_LINE> description = 'XEP-0300: Use of Cryptographic Hash Functions in XMPP' <NEW_LINE> dependencies = {'xep_0030'} <NEW_LINE> stanza = stanza <NEW_LINE> default_config = { 'block_size': 1024 * 1024, 'preferred': 'sha-256', 'enable_sha-1': False, 'enable_sha-256': True, 'enable_sha-512': True, 'enable_sha3-256': True, 'enable_sha3-512': True, 'enable_BLAKE2b256': True, 'enable_BLAKE2b512': True, } <NEW_LINE> _hashlib_function = { 'sha-1': hashlib.sha1, 'sha-256': hashlib.sha256, 'sha-512': hashlib.sha512, 'sha3-256': hashlib.sha3_256, 'sha3-512': hashlib.sha3_512, 'BLAKE2b256': lambda: hashlib.blake2b(digest_size=32), 'BLAKE2b512': lambda: hashlib.blake2b(digest_size=64), } <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self.enabled_hashes = [] <NEW_LINE> <DEDENT> def plugin_init(self): <NEW_LINE> <INDENT> namespace = 'urn:xmpp:hash-function-text-names:%s' <NEW_LINE> self.enabled_hashes.clear() <NEW_LINE> for algo in self._hashlib_function: <NEW_LINE> <INDENT> if getattr(self, 'enable_' + algo, False): <NEW_LINE> <INDENT> self.enabled_hashes.append(namespace % algo) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def session_bind(self, jid): <NEW_LINE> <INDENT> self.xmpp['xep_0030'].add_feature(Hash.namespace) <NEW_LINE> for namespace in self.enabled_hashes: <NEW_LINE> <INDENT> self.xmpp['xep_0030'].add_feature(namespace) <NEW_LINE> <DEDENT> <DEDENT> def plugin_end(self): <NEW_LINE> <INDENT> for namespace in self.enabled_hashes: <NEW_LINE> <INDENT> self.xmpp['xep_0030'].del_feature(feature=namespace) <NEW_LINE> <DEDENT> self.enabled_hashes.clear() <NEW_LINE> self.xmpp['xep_0030'].del_feature(feature=Hash.namespace) <NEW_LINE> <DEDENT> def compute_hash(self, filename, function=None): <NEW_LINE> <INDENT> if function is None: <NEW_LINE> <INDENT> function = self.preferred <NEW_LINE> <DEDENT> h = self._hashlib_function[function]() <NEW_LINE> with open(filename, 'rb') as f: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> block = f.read(self.block_size) <NEW_LINE> if not block: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> h.update(block) <NEW_LINE> <DEDENT> <DEDENT> hash_elem = Hash() <NEW_LINE> hash_elem['algo'] = function <NEW_LINE> hash_elem['value'] = b64encode(h.digest()) <NEW_LINE> return hash_elem
XEP-0300: Use of Cryptographic Hash Functions in XMPP
62598fd4d8ef3951e32c80c0
class PageFactory(): <NEW_LINE> <INDENT> def get_page_object(page_name,base_url=conf.base_url_conf.base_url): <NEW_LINE> <INDENT> test_obj = None <NEW_LINE> page_name = page_name.lower() <NEW_LINE> if page_name in ["zero","zero page","agent zero"]: <NEW_LINE> <INDENT> test_obj = Zero_Page(base_url=base_url) <NEW_LINE> <DEDENT> return test_obj <NEW_LINE> <DEDENT> get_page_object = staticmethod(get_page_object)
PageFactory uses the factory design pattern.
62598fd4377c676e912f6fde
@tienda_nube <NEW_LINE> class MailMessageRecordImport(TiendaNubeImporter): <NEW_LINE> <INDENT> _model_name = 'tienda_nube.mail.message' <NEW_LINE> def _import_dependencies(self): <NEW_LINE> <INDENT> record = self.tienda_nube_record <NEW_LINE> self._import_dependency(record['id_order'], 'tienda_nube.sale.order') <NEW_LINE> if record['id_customer'] != '0': <NEW_LINE> <INDENT> self._import_dependency( record['id_customer'], 'tienda_nube.res.partner' ) <NEW_LINE> <DEDENT> <DEDENT> def _has_to_skip(self): <NEW_LINE> <INDENT> record = self.tienda_nube_record <NEW_LINE> binder = self.binder_for('tienda_nube.sale.order') <NEW_LINE> ps_so_id = binder.to_odoo(record['id_order']).id <NEW_LINE> return record['id_order'] == '0' or not ps_so_id
Import one simple record
62598fd4fbf16365ca794588
class IxnOFSwitchChannelEmulation(IxnEmulationHost): <NEW_LINE> <INDENT> STATE_DOWN = 'down' <NEW_LINE> STATE_NOTSTARTED = 'notStarted' <NEW_LINE> STATE_UP = 'up' <NEW_LINE> def __init__(self, ixnhttp): <NEW_LINE> <INDENT> super(IxnOFSwitchChannelEmulation, self).__init__(ixnhttp) <NEW_LINE> <DEDENT> def find(self, vport_name=None, emulation_host=None, **filters): <NEW_LINE> <INDENT> return super(IxnOFSwitchChannelEmulation, self).find(["topology","deviceGroup","ipv4Loopback","ldpTargetedRouter","ldppwvpls","ipv6Loopback","ldpTargetedRouterV6","ldpotherpws","ethernet","ipv6","greoipv6","ipv4","openFlowSwitch","OFSwitchChannel"], vport_name, emulation_host, filters) <NEW_LINE> <DEDENT> def restartdown(self, expected_state=None, timeout=None): <NEW_LINE> <INDENT> super(IxnOFSwitchChannelEmulation, self).call_operation('restartDown', expected_state, timeout) <NEW_LINE> <DEDENT> def start(self, expected_state=None, timeout=None): <NEW_LINE> <INDENT> super(IxnOFSwitchChannelEmulation, self).call_operation('start', expected_state, timeout) <NEW_LINE> <DEDENT> def stop(self, expected_state=None, timeout=None): <NEW_LINE> <INDENT> super(IxnOFSwitchChannelEmulation, self).call_operation('stop', expected_state, timeout)
Generated NGPF OFSwitchChannel emulation host
62598fd4bf627c535bcb197a
class SignalGenerator(with_metaclass(abc.ABCMeta, Instrument)): <NEW_LINE> <INDENT> @abc.abstractproperty <NEW_LINE> def channel(self): <NEW_LINE> <INDENT> raise NotImplementedError
Python abstract base class for signal generators (eg microwave sources). This ABC is not for function generators, which have their own separate ABC. .. seealso:: `~instruments.FunctionGenerator`
62598fd460cbc95b0636480a
@implementer(interfaces.ISavepoint) <NEW_LINE> class Savepoint(object): <NEW_LINE> <INDENT> def __init__(self, transaction, optimistic, *resources): <NEW_LINE> <INDENT> self.transaction = transaction <NEW_LINE> self._savepoints = savepoints = [] <NEW_LINE> for datamanager in resources: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> savepoint = datamanager.savepoint <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> if not optimistic: <NEW_LINE> <INDENT> raise TypeError("Savepoints unsupported", datamanager) <NEW_LINE> <DEDENT> savepoint = NoRollbackSavepoint(datamanager) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> savepoint = savepoint() <NEW_LINE> <DEDENT> savepoints.append(savepoint) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def valid(self): <NEW_LINE> <INDENT> return self.transaction is not None <NEW_LINE> <DEDENT> def rollback(self): <NEW_LINE> <INDENT> transaction = self.transaction <NEW_LINE> if transaction is None: <NEW_LINE> <INDENT> raise interfaces.InvalidSavepointRollbackError( 'invalidated by a later savepoint') <NEW_LINE> <DEDENT> transaction._remove_and_invalidate_after(self) <NEW_LINE> try: <NEW_LINE> <INDENT> for savepoint in self._savepoints: <NEW_LINE> <INDENT> savepoint.rollback() <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> transaction._saveAndRaiseCommitishError()
Implementation of `~transaction.interfaces.ISavepoint`, a transaction savepoint. Transaction savepoints coordinate savepoints for data managers participating in a transaction.
62598fd43617ad0b5ee06615
class ToolbarMiddleware(object): <NEW_LINE> <INDENT> def process_request(self, request): <NEW_LINE> <INDENT> edit_on = get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON') <NEW_LINE> edit_off = get_cms_setting('CMS_TOOLBAR_URL__EDIT_OFF') <NEW_LINE> build = get_cms_setting('CMS_TOOLBAR_URL__BUILD') <NEW_LINE> disable = get_cms_setting('CMS_TOOLBAR_URL__DISABLE') <NEW_LINE> if disable in request.GET: <NEW_LINE> <INDENT> request.session['cms_toolbar_disabled'] = True <NEW_LINE> <DEDENT> if edit_on in request.GET: <NEW_LINE> <INDENT> request.session['cms_toolbar_disabled'] = False <NEW_LINE> <DEDENT> if request.user.is_staff or request.user.is_anonymous(): <NEW_LINE> <INDENT> if edit_on in request.GET and not request.session.get('cms_edit', False): <NEW_LINE> <INDENT> if not request.session.get('cms_edit', False): <NEW_LINE> <INDENT> menu_pool.clear() <NEW_LINE> <DEDENT> request.session['cms_edit'] = True <NEW_LINE> if request.session.get('cms_build', False): <NEW_LINE> <INDENT> request.session['cms_build'] = False <NEW_LINE> <DEDENT> <DEDENT> if edit_off in request.GET and request.session.get('cms_edit', True): <NEW_LINE> <INDENT> if request.session.get('cms_edit', True): <NEW_LINE> <INDENT> menu_pool.clear() <NEW_LINE> <DEDENT> request.session['cms_edit'] = False <NEW_LINE> if request.session.get('cms_build', False): <NEW_LINE> <INDENT> request.session['cms_build'] = False <NEW_LINE> <DEDENT> <DEDENT> if build in request.GET and not request.session.get('cms_build', False): <NEW_LINE> <INDENT> request.session['cms_build'] = True <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> request.session['cms_build'] = False <NEW_LINE> request.session['cms_edit'] = False <NEW_LINE> <DEDENT> if request.user.is_staff: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> request.cms_latest_entry = LogEntry.objects.filter( user=request.user, action_flag__in=(ADDITION, CHANGE) ).only('pk').order_by('-pk')[0].pk <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> request.cms_latest_entry = -1 <NEW_LINE> <DEDENT> <DEDENT> request.toolbar = CMSToolbar(request) <NEW_LINE> <DEDENT> def process_view(self, request, view_func, view_args, view_kwarg): <NEW_LINE> <INDENT> response = request.toolbar.request_hook() <NEW_LINE> if isinstance(response, HttpResponse): <NEW_LINE> <INDENT> return response <NEW_LINE> <DEDENT> <DEDENT> def process_response(self, request, response): <NEW_LINE> <INDENT> from django.utils.cache import add_never_cache_headers <NEW_LINE> if ((hasattr(request, 'toolbar') and request.toolbar.edit_mode) or not all(ph.cache_placeholder for ph in getattr(request, 'placeholders', ()))): <NEW_LINE> <INDENT> add_never_cache_headers(response) <NEW_LINE> <DEDENT> if hasattr(request, 'user') and request.user.is_staff and response.status_code != 500: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> pk = LogEntry.objects.filter( user=request.user, action_flag__in=(ADDITION, CHANGE) ).only('pk').order_by('-pk')[0].pk <NEW_LINE> if hasattr(request, 'cms_latest_entry') and request.cms_latest_entry != pk: <NEW_LINE> <INDENT> log = LogEntry.objects.filter(user=request.user, action_flag__in=(ADDITION, CHANGE))[0] <NEW_LINE> request.session['cms_log_latest'] = log.pk <NEW_LINE> <DEDENT> <DEDENT> except IndexError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return response
Middleware to set up CMS Toolbar.
62598fd4ad47b63b2c5a7d1e
class PDSViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = ProtocolDataSource.objects.all() <NEW_LINE> serializer_class = ProtocolDataSourceSerializer <NEW_LINE> def list(self, request, *args, **kwargs): <NEW_LINE> <INDENT> pds = [] <NEW_LINE> for p in ProtocolDataSource.objects.all(): <NEW_LINE> <INDENT> if request.user in p.protocol.users.all(): <NEW_LINE> <INDENT> pds.append(ProtocolDataSourceSerializer(p, context={'request': request}).data) <NEW_LINE> <DEDENT> <DEDENT> return Response(pds)
API endpoint that allows protocols to be viewed.
62598fd460cbc95b0636480c
class ScaleSpace: <NEW_LINE> <INDENT> def __init__(self, gray_image, sigma, s, filters=FilterDict()): <NEW_LINE> <INDENT> if isinstance(gray_image, np.ndarray) and not isinstance(gray_image, Image): <NEW_LINE> <INDENT> gray_image = Image(0, gray_image) <NEW_LINE> <DEDENT> elif not isinstance(gray_image, Image): <NEW_LINE> <INDENT> raise ValueError('gray_img must be either numpy.ndarray type or scale_space.Image type.') <NEW_LINE> <DEDENT> self._images = [gray_image, ] <NEW_LINE> self._sigma = sigma <NEW_LINE> self._s = s <NEW_LINE> self._update_filter_dict(filters) <NEW_LINE> self._filters = filters <NEW_LINE> self._generate_space() <NEW_LINE> self._dog_space = self._generate_dog_space() <NEW_LINE> self._next_octave = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def _k(self): <NEW_LINE> <INDENT> return np.power(2, 1 / self._s) <NEW_LINE> <DEDENT> @property <NEW_LINE> def images(self): <NEW_LINE> <INDENT> return tuple(self._images) <NEW_LINE> <DEDENT> @property <NEW_LINE> def DoG_space(self): <NEW_LINE> <INDENT> return self._dog_space <NEW_LINE> <DEDENT> @property <NEW_LINE> def next_octave(self): <NEW_LINE> <INDENT> if not self._next_octave: <NEW_LINE> <INDENT> self._next_octave = self._generate_next_octave() <NEW_LINE> <DEDENT> return self._next_octave <NEW_LINE> <DEDENT> def _update_filter_dict(self, filter_set): <NEW_LINE> <INDENT> for i in range(0, self._s + 1): <NEW_LINE> <INDENT> sigma = np.power(self._k, i) * self._sigma <NEW_LINE> if sigma not in filter_set: <NEW_LINE> <INDENT> filter_set.add(GaussianFilter(sigma)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _generate_space(self): <NEW_LINE> <INDENT> for sigma in self._filters: <NEW_LINE> <INDENT> self._images.append(self._filters[sigma].apply(self._images[0])) <NEW_LINE> <DEDENT> <DEDENT> def _generate_dog_space(self): <NEW_LINE> <INDENT> dogs = [] <NEW_LINE> logging.debug('Start to create DoGs.') <NEW_LINE> for i in range(1, len(self._images)): <NEW_LINE> <INDENT> dogs.append(DoGImage(self._images[i], self._images[i - 1])) <NEW_LINE> <DEDENT> return dogs <NEW_LINE> <DEDENT> def _generate_next_octave(self): <NEW_LINE> <INDENT> source_image = self._images[-1] <NEW_LINE> sampled_image = Image(0, width=source_image.width/2, height=source_image.height/2) <NEW_LINE> for i in range(0, len(source_image) / 2): <NEW_LINE> <INDENT> for j in range(0, len(source_image[i]) / 2): <NEW_LINE> <INDENT> sampled_image[i][j] = source_image[i * 2][j * 2] <NEW_LINE> <DEDENT> <DEDENT> return ScaleSpace(sampled_image, self._sigma, self._s, self._filters) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self._images.__iter__()
Scale Space インスタンス化されると同時に Scale Space と それに基づく DoG の空間を生成して保持する。 また、next_octave プロパティを使うことによって、次のオクターブの空間を生成し、それを返す。 Scale space を構成する画像は、images プロパティを使って参照可能。並び順は σ の小さいもの順。 また、イテレータを用いて for image in scale_space のように参照することもできる。 Dog の空間は、DoG_space プロパティを用いて参照可能。並び順は元画像と同様。
62598fd4be7bc26dc92520bf
class TestStorageCollection(BaseTest): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> with open( 'oneview_redfish_toolkit/mockups/redfish/StorageCollection.json' ) as f: <NEW_LINE> <INDENT> self.storage_collection_mockup = json.load(f) <NEW_LINE> <DEDENT> <DEDENT> def test_serialize(self): <NEW_LINE> <INDENT> storage_collection = StorageCollection('b425802b-a6a5-4941-8885-aab68dfa2ee2') <NEW_LINE> result = json.loads(storage_collection.serialize()) <NEW_LINE> self.assertEqualMockup(self.storage_collection_mockup, result)
Tests for StorageCollection class
62598fd4ad47b63b2c5a7d20
class NengoException(Exception): <NEW_LINE> <INDENT> pass
Base class for Nengo exceptions. NengoException instances should not be created; this base class exists so that all exceptions raised by Nengo can be caught in a try / except block.
62598fd455399d3f056269ea
class SourceRaw: <NEW_LINE> <INDENT> def __init__(self, s): <NEW_LINE> <INDENT> self.s = s <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.s
raw string for source persistence.
62598fd4656771135c489b42
class DataProvider(object): <NEW_LINE> <INDENT> def __init__(self, inputs, targets, batch_size, max_num_batches=-1, shuffle_order=True, rng=None): <NEW_LINE> <INDENT> self.inputs = inputs <NEW_LINE> self.targets = targets <NEW_LINE> if batch_size < 1: <NEW_LINE> <INDENT> raise ValueError('batch_size must be >= 1') <NEW_LINE> <DEDENT> self._batch_size = batch_size <NEW_LINE> if max_num_batches == 0 or max_num_batches < -1: <NEW_LINE> <INDENT> raise ValueError('max_num_batches must be -1 or > 0') <NEW_LINE> <DEDENT> self._max_num_batches = max_num_batches <NEW_LINE> self._update_num_batches() <NEW_LINE> self.shuffle_order = shuffle_order <NEW_LINE> self._current_order = np.arange(inputs.shape[0]) <NEW_LINE> if rng is None: <NEW_LINE> <INDENT> rng = np.random.RandomState(DEFAULT_SEED) <NEW_LINE> <DEDENT> self.rng = rng <NEW_LINE> self.new_epoch() <NEW_LINE> <DEDENT> @property <NEW_LINE> def batch_size(self): <NEW_LINE> <INDENT> return self._batch_size <NEW_LINE> <DEDENT> @batch_size.setter <NEW_LINE> def batch_size(self, value): <NEW_LINE> <INDENT> if value < 1: <NEW_LINE> <INDENT> raise ValueError('batch_size must be >= 1') <NEW_LINE> <DEDENT> self._batch_size = value <NEW_LINE> self._update_num_batches() <NEW_LINE> <DEDENT> @property <NEW_LINE> def max_num_batches(self): <NEW_LINE> <INDENT> return self._max_num_batches <NEW_LINE> <DEDENT> @max_num_batches.setter <NEW_LINE> def max_num_batches(self, value): <NEW_LINE> <INDENT> if value == 0 or value < -1: <NEW_LINE> <INDENT> raise ValueError('max_num_batches must be -1 or > 0') <NEW_LINE> <DEDENT> self._max_num_batches = value <NEW_LINE> self._update_num_batches() <NEW_LINE> <DEDENT> def _update_num_batches(self): <NEW_LINE> <INDENT> possible_num_batches = self.inputs.shape[0] // self.batch_size <NEW_LINE> if self.max_num_batches == -1: <NEW_LINE> <INDENT> self.num_batches = possible_num_batches <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.num_batches = min(self.max_num_batches, possible_num_batches) <NEW_LINE> <DEDENT> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def new_epoch(self): <NEW_LINE> <INDENT> self._curr_batch = 0 <NEW_LINE> if self.shuffle_order: <NEW_LINE> <INDENT> self.shuffle() <NEW_LINE> <DEDENT> <DEDENT> def __next__(self): <NEW_LINE> <INDENT> return self.next() <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> inv_perm = np.argsort(self._current_order) <NEW_LINE> self._current_order = self._current_order[inv_perm] <NEW_LINE> self.inputs = self.inputs[inv_perm] <NEW_LINE> self.targets = self.targets[inv_perm] <NEW_LINE> self.new_epoch() <NEW_LINE> <DEDENT> def shuffle(self): <NEW_LINE> <INDENT> perm = self.rng.permutation(self.inputs.shape[0]) <NEW_LINE> self._current_order = self._current_order[perm] <NEW_LINE> self.inputs = self.inputs[perm] <NEW_LINE> self.targets = self.targets[perm] <NEW_LINE> <DEDENT> def next(self): <NEW_LINE> <INDENT> if self._curr_batch + 1 > self.num_batches: <NEW_LINE> <INDENT> self.new_epoch() <NEW_LINE> raise StopIteration() <NEW_LINE> <DEDENT> batch_slice = slice(self._curr_batch * self.batch_size, (self._curr_batch + 1) * self.batch_size) <NEW_LINE> inputs_batch = self.inputs[batch_slice] <NEW_LINE> targets_batch = self.targets[batch_slice] <NEW_LINE> self._curr_batch += 1 <NEW_LINE> return inputs_batch, targets_batch
Generic data provider.
62598fd4956e5f7376df58e6
class TripletLoss(nn.Module): <NEW_LINE> <INDENT> def __init__(self, margin=0.3): <NEW_LINE> <INDENT> super(TripletLoss, self).__init__() <NEW_LINE> self.margin = margin <NEW_LINE> self.ranking_loss = nn.MarginRankingLoss(margin=margin) <NEW_LINE> <DEDENT> def forward(self, inputs, targets): <NEW_LINE> <INDENT> n = inputs.size(0) <NEW_LINE> dist = torch.pow(inputs, 2).sum(dim=1, keepdim=True).expand(n, n) <NEW_LINE> dist = dist + dist.t() <NEW_LINE> dist.addmm_(1, -2, inputs, inputs.t()) <NEW_LINE> dist = dist.clamp(min=1e-12).sqrt() <NEW_LINE> mask = targets.expand(n, n).eq(targets.expand(n, n).t()) <NEW_LINE> dist_ap, dist_an = [], [] <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> dist_ap.append(dist[i][mask[i]].max().unsqueeze(0)) <NEW_LINE> dist_an.append(dist[i][mask[i] == 0].min().unsqueeze(0)) <NEW_LINE> <DEDENT> dist_ap = torch.cat(dist_ap) <NEW_LINE> dist_an = torch.cat(dist_an) <NEW_LINE> y = torch.ones_like(dist_an) <NEW_LINE> loss = self.ranking_loss(dist_an, dist_ap, y) <NEW_LINE> return loss
Triplet loss with hard positive/negative mining. Reference: Hermans et al. In Defense of the Triplet Loss for Person Re-Identification. arXiv:1703.07737. Code imported from https://github.com/Cysu/open-reid/blob/master/reid/loss/triplet.py. Args: - margin (float): margin for triplet.
62598fd4656771135c489b44
class CharEmbed(nn.Module): <NEW_LINE> <INDENT> def __init__(self, args): <NEW_LINE> <INDENT> super(CharEmbed, self).__init__() <NEW_LINE> self.embd_size = args.char_embd_dim <NEW_LINE> self.embedding = nn.Embedding(args.char_vocab_size, args.char_embd_dim) <NEW_LINE> self.conv = nn.ModuleList([nn.Conv2d(1, args.out_chs, (f[0], f[1])) for f in args.filters]) <NEW_LINE> self.dropout = nn.Dropout(0.2) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> input_shape = x.size() <NEW_LINE> word_len = x.size(2) <NEW_LINE> x = x.view(-1, word_len) <NEW_LINE> x = self.embedding(x) <NEW_LINE> x = x.view(*input_shape, -1) <NEW_LINE> x = x.sum(2) <NEW_LINE> x = x.unsqueeze(1) <NEW_LINE> x = [F.relu(conv(x)) for conv in self.conv] <NEW_LINE> x = [xx.view((xx.size(0), xx.size(2), xx.size(3), xx.size(1))) for xx in x] <NEW_LINE> x = [torch.sum(xx, 2) for xx in x] <NEW_LINE> x = torch.cat(x, 1) <NEW_LINE> x = self.dropout(x) <NEW_LINE> return x
In : (N, sentence_len, word_len, vocab_size_c) Out: (N, sentence_len, c_embd_size)
62598fd4dc8b845886d53a90
class Product(db.Model): <NEW_LINE> <INDENT> __tablename__ = "products" <NEW_LINE> product_id = db.Column(db.Integer, primary_key=True) <NEW_LINE> name = db.Column(db.String(80), nullable=False) <NEW_LINE> description_txt = db.Column(db.Text) <NEW_LINE> media_files = db.relationship( 'MediaFile', backref='product', lazy=True, cascade="all, delete-orphan", ) <NEW_LINE> thumbnail = db.Column(db.Text, default='default-thumbnail.jpg') <NEW_LINE> is_displayed = db.Column(db.Boolean, nullable=False, default=True) <NEW_LINE> def __init__(self, product_id): <NEW_LINE> <INDENT> if allowed_product_id(product_id) and not Product.product_exists(product_id): <NEW_LINE> <INDENT> self.product_id = product_id <NEW_LINE> self.name = "Item {}".format(product_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Product id not allowed') <NEW_LINE> <DEDENT> <DEDENT> def add_thumbnail_filename(self, filename): <NEW_LINE> <INDENT> if allowed_file(filename, ALLOWED_FILE_EXTENSIONS): <NEW_LINE> <INDENT> self.thumbnail = filename <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Thumbnail filename not allowed') <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def product_exists(product_id): <NEW_LINE> <INDENT> exists = Product.query.filter_by(product_id=product_id).scalar() is not None <NEW_LINE> return exists <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "{}".format(self.name)
Products to be showcased by the UI
62598fd4a219f33f346c6cd9
class DebianSsoUserMiddleware(RemoteUserMiddleware): <NEW_LINE> <INDENT> dacs_header = 'REMOTE_USER' <NEW_LINE> cert_header = 'SSL_CLIENT_S_DN_CN' <NEW_LINE> @staticmethod <NEW_LINE> def dacs_user_to_email(username): <NEW_LINE> <INDENT> parts = [part for part in username.split(':') if part] <NEW_LINE> federation, jurisdiction = parts[:2] <NEW_LINE> if (federation, jurisdiction) != ('DEBIANORG', 'DEBIAN'): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> username = parts[-1] <NEW_LINE> if '@' in username: <NEW_LINE> <INDENT> return username <NEW_LINE> <DEDENT> return username + '@debian.org' <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def is_debian_member(user): <NEW_LINE> <INDENT> return any( email.email.endswith('@debian.org') for email in user.emails.all() ) <NEW_LINE> <DEDENT> def process_request(self, request): <NEW_LINE> <INDENT> if not hasattr(request, 'user'): <NEW_LINE> <INDENT> raise ImproperlyConfigured( "The Django remote user auth middleware requires the" " authentication middleware to be installed. Edit your" " MIDDLEWARE_CLASSES setting to insert" " 'django.contrib.auth.middleware.AuthenticationMiddleware'" " before the DebianSsoUserMiddleware class.") <NEW_LINE> <DEDENT> dacs_user = request.META.get(self.dacs_header) <NEW_LINE> cert_user = request.META.get(self.cert_header) <NEW_LINE> if cert_user is not None: <NEW_LINE> <INDENT> remote_user = cert_user <NEW_LINE> <DEDENT> elif dacs_user is not None: <NEW_LINE> <INDENT> remote_user = self.dacs_user_to_email(dacs_user) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if request.user.is_authenticated(): <NEW_LINE> <INDENT> if self.is_debian_member(request.user): <NEW_LINE> <INDENT> auth.logout(request) <NEW_LINE> <DEDENT> <DEDENT> return <NEW_LINE> <DEDENT> if request.user.is_authenticated(): <NEW_LINE> <INDENT> if request.user.emails.filter(email=remote_user).exists(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> user = auth.authenticate(remote_user=remote_user) <NEW_LINE> if user: <NEW_LINE> <INDENT> request.user = user <NEW_LINE> auth.login(request, user)
Middleware that initiates user authentication based on the REMOTE_USER field provided by Debian's SSO system, or based on the SSL_CLIENT_S_DN_CN field provided by the validation of the SSL client certificate generated by sso.debian.org. If the currently logged in user is a DD (as identified by having a @debian.org address), he is forcefully logged out if the header is no longer found or is invalid.
62598fd4091ae356687050ef
class Solution: <NEW_LINE> <INDENT> def removeDuplicates(self, A): <NEW_LINE> <INDENT> if A is None or len(A) == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> value = A[0] <NEW_LINE> count = 1 <NEW_LINE> newIdx = 0 <NEW_LINE> for i in range(1, len(A)): <NEW_LINE> <INDENT> if A[i] != value: <NEW_LINE> <INDENT> newIdx += 1 <NEW_LINE> A[newIdx] = A[i] <NEW_LINE> value = A[i] <NEW_LINE> count = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> count += 1 <NEW_LINE> if count <= 2: <NEW_LINE> <INDENT> newIdx += 1 <NEW_LINE> A[newIdx] = A[i] <NEW_LINE> value = A[i] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return newIdx + 1
@param A: a list of integers @return an integer
62598fd4d8ef3951e32c80c5
@provides(IOperation) <NEW_LINE> class ThresholdOp(HasStrictTraits): <NEW_LINE> <INDENT> id = Constant('edu.mit.synbio.cytoflow.operations.threshold') <NEW_LINE> friendly_id = Constant("Threshold") <NEW_LINE> name = Str <NEW_LINE> channel = Str <NEW_LINE> threshold = Float(None) <NEW_LINE> _selection_view = Instance('ThresholdSelection', transient = True) <NEW_LINE> def apply(self, experiment): <NEW_LINE> <INDENT> if experiment is None: <NEW_LINE> <INDENT> raise util.CytoflowOpError('experiment', "No experiment specified") <NEW_LINE> <DEDENT> if not self.name: <NEW_LINE> <INDENT> raise util.CytoflowOpError('name', "You have to set the gate's name " "before applying it!") <NEW_LINE> <DEDENT> if self.name != util.sanitize_identifier(self.name): <NEW_LINE> <INDENT> raise util.CytoflowOpError('name', "Name can only contain letters, numbers and underscores." .format(self.name)) <NEW_LINE> <DEDENT> if(self.name in experiment.data.columns): <NEW_LINE> <INDENT> raise util.CytoflowOpError('name', "Experiment already contains a column {0}" .format(self.name)) <NEW_LINE> <DEDENT> if self.channel not in experiment.channels: <NEW_LINE> <INDENT> raise util.CytoflowOpError('channel', "{0} isn't a channel in the experiment" .format(self.channel)) <NEW_LINE> <DEDENT> if self.threshold is None: <NEW_LINE> <INDENT> raise util.CytoflowOpError('threshold', "must set 'threshold'") <NEW_LINE> <DEDENT> gate = pd.Series(experiment[self.channel] > self.threshold) <NEW_LINE> new_experiment = experiment.clone(deep = False) <NEW_LINE> new_experiment.add_condition(self.name, "bool", gate) <NEW_LINE> new_experiment.history.append(self.clone_traits(transient = lambda t: True)) <NEW_LINE> return new_experiment <NEW_LINE> <DEDENT> def default_view(self, **kwargs): <NEW_LINE> <INDENT> self._selection_view = ThresholdSelection(op = self) <NEW_LINE> self._selection_view.trait_set(**kwargs) <NEW_LINE> return self._selection_view
Apply a threshold gate to a cytometry experiment. Attributes ---------- name : Str The operation name. Used to name the new column in the experiment that's created by `apply` channel : Str The name of the channel to apply the threshold on. threshold : Float The value at which to threshold this channel. Examples -------- .. plot:: :context: close-figs Make a little data set. >>> import cytoflow as flow >>> import_op = flow.ImportOp() >>> import_op.tubes = [flow.Tube(file = "Plate01/RFP_Well_A3.fcs", ... conditions = {'Dox' : 10.0}), ... flow.Tube(file = "Plate01/CFP_Well_A4.fcs", ... conditions = {'Dox' : 1.0})] >>> import_op.conditions = {'Dox' : 'float'} >>> ex = import_op.apply() Create and parameterize the operation. .. plot:: :context: close-figs >>> thresh_op = flow.ThresholdOp(name = 'Threshold', ... channel = 'Y2-A', ... threshold = 2000) Plot a diagnostic view .. plot:: :context: close-figs >>> tv = thresh_op.default_view(scale = 'log') >>> tv.plot(ex) .. note:: If you want to use the interactive default view in a Jupyter notebook, make sure you say ``%matplotlib notebook`` in the first cell (instead of ``%matplotlib inline`` or similar). Then call ``default_view()`` with ``interactive = True``:: tv = thresh_op.default_view(scale = 'log', interactive = True) tv.plot(ex) Apply the gate, and show the result .. plot:: :context: close-figs >>> ex2 = thresh_op.apply(ex) >>> ex2.data.groupby('Threshold').size() Threshold False 15786 True 4214 dtype: int64
62598fd40fa83653e46f53bc
class EduDataGetter(XMLDataGetter): <NEW_LINE> <INDENT> def __fix_iterator(self, element, fields): <NEW_LINE> <INDENT> return self._make_iterator( element, lambda iterator, logger, encoding: EduKind2Object(iterator, logger, fields, encoding)) <NEW_LINE> <DEDENT> def iter_stprog(self, tag="studprog"): <NEW_LINE> <INDENT> return self.__fix_iterator(tag, ("studieprogramkode", "status_utdplan", "institusjonsnr_studieansv", "faknr_studieansv", "instituttnr_studieansv", "gruppenr_studieansv", "status_utgatt", "studieprognavn", "status_eksport_lms",)) <NEW_LINE> <DEDENT> def iter_undenh(self, tag="enhet"): <NEW_LINE> <INDENT> return self.__fix_iterator(tag, ("institusjonsnr", "terminnr", "terminkode", "emnekode", "arstall", "versjonskode", "status_eksport_lms", "institusjonsnr_kontroll", "faknr_kontroll", "instituttnr_kontroll", "gruppenr_kontroll", "emnenavn_bokmal", "emnenavnfork", "lmsrommalkode",)) <NEW_LINE> <DEDENT> def iter_undakt(self, tag="aktivitet"): <NEW_LINE> <INDENT> return self.__fix_iterator(tag, ("institusjonsnr", "terminnr", "terminkode", "emnekode", "arstall", "versjonskode", "aktivitetkode", "status_eksport_lms", "aktivitetsnavn", "institusjonsnr_kontroll", "faknr_kontroll", "instituttnr_kontroll", "gruppenr_kontroll", "lmsrommalkode",)) <NEW_LINE> <DEDENT> def iter_evu(self, tag="evu"): <NEW_LINE> <INDENT> return self.__fix_iterator(tag, ("kurstidsangivelsekode", "etterutdkurskode", "status_eksport_lms", "institusjonsnr_adm_ansvar", "faknr_adm_ansvar", "instituttnr_adm_ansvar", "gruppenr_adm_ansvar", "etterutdkursnavn", "lmsrommalkode",)) <NEW_LINE> <DEDENT> def iter_kursakt(self, tag="kursakt"): <NEW_LINE> <INDENT> return self.__fix_iterator(tag, ("kurstidsangivelsekode", "etterutdkurskode", "aktivitetskode", "status_eksport_lms", "aktivitetsnavn", "lmsrommalkode",)) <NEW_LINE> <DEDENT> def iter_kull(self, tag="kull"): <NEW_LINE> <INDENT> return self.__fix_iterator(tag, ("arstall", "studieprogramkode", "terminkode", "institusjonsnr_studieansv", "faknr_studieansv", "instituttnr_studieansv", "gruppenr_studieansv", "studiekullnavn", "lmsrommalkode",))
An abstraction layer for FS files pertaining to educational information.
62598fd4656771135c489b46
class TestCourseTagAPI(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.user = UserFactory.create() <NEW_LINE> self.course_id = SlashSeparatedCourseKey('test_org', 'test_course_number', 'test_run') <NEW_LINE> self.test_key = 'test_key' <NEW_LINE> <DEDENT> def test_get_set_course_tag(self): <NEW_LINE> <INDENT> tag = course_tag_api.get_course_tag(self.user, self.course_id, self.test_key) <NEW_LINE> self.assertIsNone(tag) <NEW_LINE> test_value = 'value' <NEW_LINE> course_tag_api.set_course_tag(self.user, self.course_id, self.test_key, test_value) <NEW_LINE> tag = course_tag_api.get_course_tag(self.user, self.course_id, self.test_key) <NEW_LINE> self.assertEqual(tag, test_value) <NEW_LINE> test_value = 'value2' <NEW_LINE> course_tag_api.set_course_tag(self.user, self.course_id, self.test_key, test_value) <NEW_LINE> tag = course_tag_api.get_course_tag(self.user, self.course_id, self.test_key) <NEW_LINE> self.assertEqual(tag, test_value)
Test the user service
62598fd4adb09d7d5dc0aa4e
class Queue(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.items = deque() <NEW_LINE> <DEDENT> def isempty(self): <NEW_LINE> <INDENT> return self.items == deque() <NEW_LINE> <DEDENT> def enqueue(self, item): <NEW_LINE> <INDENT> self.items.appendleft(item) <NEW_LINE> <DEDENT> def dequeue(self): <NEW_LINE> <INDENT> if len(self.items) > 0: <NEW_LINE> <INDENT> return self.items.pop() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "Queue is empty!" <NEW_LINE> <DEDENT> <DEDENT> def peekfirstin(self): <NEW_LINE> <INDENT> if len(self.items) > 0: <NEW_LINE> <INDENT> return self.items[-1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "Queue is empty!" <NEW_LINE> <DEDENT> <DEDENT> def peeklastin(self): <NEW_LINE> <INDENT> if len(self.items) > 0: <NEW_LINE> <INDENT> return self.items[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "Queue is empty!" <NEW_LINE> <DEDENT> <DEDENT> def size(self): <NEW_LINE> <INDENT> return len(self.items) <NEW_LINE> <DEDENT> def show(self): <NEW_LINE> <INDENT> return self.items
An implementation of a queue using the Deque("double-ended queue") Python data structure
62598fd4a219f33f346c6cdb
class Stochastic(Benchmark): <NEW_LINE> <INDENT> def __init__(self, dimensions=2): <NEW_LINE> <INDENT> Benchmark.__init__(self, dimensions) <NEW_LINE> self.bounds = zip([-5.0] * self.dimensions, [5.0] * self.dimensions) <NEW_LINE> self.global_optimum = [1.0/_ for _ in range(1, self.dimensions+1)] <NEW_LINE> self.fglob = 0.0 <NEW_LINE> self.change_dimensionality = True <NEW_LINE> <DEDENT> def evaluator(self, x, *args): <NEW_LINE> <INDENT> self.fun_evals += 1 <NEW_LINE> rnd = uniform(0.0, 1.0, size=(self.dimensions, )) <NEW_LINE> rng = arange(1, self.dimensions+1) <NEW_LINE> return sum(rnd*abs(x - 1.0/rng))
Stochastic test objective function. This class defines a Stochastic global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Stochastic}}(\mathbf{x}) = \sum_{i=1}^{n} \epsilon_i \left | {x_i - \frac{1}{i}} \right | The variable :math:`\epsilon_i, (i=1,...,n)` is a random variable uniformly distributed in :math:`[0, 1]`. Here, :math:`n` represents the number of dimensions and :math:`x_i \in [-5, 5]` for :math:`i=1,...,n`. .. figure:: figures/Stochastic.png :alt: Stochastic function :align: center **Two-dimensional Stochastic function** *Global optimum*: :math:`f(x_i) = 0` for :math:`x_i = [1/n]` for :math:`i=1,...,n`
62598fd48a349b6b43686716
class TestComputePbest(object): <NEW_LINE> <INDENT> def test_return_values(self, swarm): <NEW_LINE> <INDENT> expected_cost = np.array([1, 2, 2]) <NEW_LINE> expected_pos = np.array([[1, 2, 3], [4, 5, 6], [1, 1, 1]]) <NEW_LINE> pos, cost = P.compute_pbest(swarm) <NEW_LINE> assert (pos == expected_pos).all() <NEW_LINE> assert (cost == expected_cost).all() <NEW_LINE> <DEDENT> @pytest.mark.parametrize("swarm", [0, (1, 2, 3)]) <NEW_LINE> def test_input_swarm(self, swarm): <NEW_LINE> <INDENT> with pytest.raises(AttributeError): <NEW_LINE> <INDENT> P.compute_pbest(swarm)
Test suite for compute_pbest()
62598fd47cff6e4e811b5efe
class ReadFilter(object): <NEW_LINE> <INDENT> def __call__(self, row, header): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def getSQL(self): <NEW_LINE> <INDENT> return ""
A callable class which can pre-filters a row and determine whether the row can be skipped. If the call returns true, the row is examined but if it returns false, the row should be skipped.
62598fd4377c676e912f6fe4
class ConfigU(object): <NEW_LINE> <INDENT> def __init__(self, fileName): <NEW_LINE> <INDENT> super(ConfigU, self).__init__() <NEW_LINE> try: <NEW_LINE> <INDENT> self.fileName = fileName <NEW_LINE> self.config = ConfigParser() <NEW_LINE> self.config.read(fileName, 'utf-8') <NEW_LINE> <DEDENT> except IOError as e: <NEW_LINE> <INDENT> print(traceback.print_exc()) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def get_common(): <NEW_LINE> <INDENT> return ConfigU('./common.cfg') <NEW_LINE> <DEDENT> def get(self, section, key): <NEW_LINE> <INDENT> return self.config.get(section, key) <NEW_LINE> <DEDENT> def getint(self, section, key): <NEW_LINE> <INDENT> return self.config.getint(section, key) <NEW_LINE> <DEDENT> def set(self, section, key, value): <NEW_LINE> <INDENT> self.config.set(section, key, value) <NEW_LINE> self.config.write(open(self.fileName, "w")) <NEW_LINE> <DEDENT> def sections(self): <NEW_LINE> <INDENT> return self.config.sections() <NEW_LINE> <DEDENT> def add_section(self, section): <NEW_LINE> <INDENT> return self.config.add_section(section) <NEW_LINE> <DEDENT> def remove_section(self, section): <NEW_LINE> <INDENT> return self.config.remove_section(section) <NEW_LINE> <DEDENT> def items(self, section): <NEW_LINE> <INDENT> return self.config.items(section)
配置文件工具类: (1) 依赖ConfigParser包 (2) 文件夹外部必须导入 from smutils.ConfigU import ConfigU (文件夹内部可导入import ConfigU, 但是这样将无法调用静态方法) 1. 配置文件如:ini.cfg [admin] user = smalle password = aezocn 2.初始化读取配置文件:config = ConfigU('ini.cfg') # 注意文件路径 3.取值:config.items(self, 'admin')
62598fd43617ad0b5ee0661e
class ViewEventListener(object): <NEW_LINE> <INDENT> def __init__(self, view): <NEW_LINE> <INDENT> self.view = view <NEW_LINE> self.busy = False <NEW_LINE> self.events = 0 <NEW_LINE> self.latest_time = 0.0 <NEW_LINE> self.delay = 0 <NEW_LINE> <DEDENT> def push(self, event_id): <NEW_LINE> <INDENT> self.latest_time = time.time() <NEW_LINE> self.events |= event_id <NEW_LINE> if not self.busy: <NEW_LINE> <INDENT> self.delay = 200 <NEW_LINE> self.start_timer(200) <NEW_LINE> <DEDENT> <DEDENT> def start_timer(self, delay): <NEW_LINE> <INDENT> start_time = self.latest_time <NEW_LINE> def worker(): <NEW_LINE> <INDENT> if start_time < self.latest_time: <NEW_LINE> <INDENT> self.start_timer(self.delay) <NEW_LINE> return <NEW_LINE> <DEDENT> self.busy = False <NEW_LINE> if not self.is_view_visible(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.view.run_command('json_where', {'events': self.events}) <NEW_LINE> self.events = 0 <NEW_LINE> <DEDENT> self.busy = True <NEW_LINE> set_timeout(worker, delay) <NEW_LINE> <DEDENT> def is_view_visible(self): <NEW_LINE> <INDENT> window = self.view.window() <NEW_LINE> if window: <NEW_LINE> <INDENT> view_id = self.view.id() <NEW_LINE> for group in range(window.num_groups()): <NEW_LINE> <INDENT> active_view = window.active_view_in_group(group) <NEW_LINE> if active_view and active_view.id() == view_id: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return False
The class queues and forwards view events to GitGutterCommand. A ViewEventListener object queues all events received from a view and starts a single sublime timer to forward the event to GitGutterCommand after some idle time. This ensures not to bloat sublime API due to dozens of timers running for debouncing events.
62598fd48a349b6b43686718
class aerodynamic_resistance(object): <NEW_LINE> <INDENT> thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> raise AttributeError("No constructor defined - class is abstract") <NEW_LINE> <DEDENT> __repr__ = _swig_repr <NEW_LINE> get_aerodynamic_resistance = _swig_new_instance_method(_cmf_core.aerodynamic_resistance_get_aerodynamic_resistance) <NEW_LINE> __swig_destroy__ = _cmf_core.delete_aerodynamic_resistance
Abstract class. Child classes can be used to calculate aerodynamic resistances against turbulent heat fluxes. C++ includes: meteorology.h
62598fd4ec188e330fdf8d6e
@optional_args <NEW_LINE> class qc(object): <NEW_LINE> <INDENT> def __init__(self, tests=None): <NEW_LINE> <INDENT> self.tests_count = tests <NEW_LINE> <DEDENT> def __call__(self, func): <NEW_LINE> <INDENT> func_args, _, _, func_defaults = inspect.getargspec(func) <NEW_LINE> func_args, func_defaults = func_args or [], func_defaults or [] <NEW_LINE> free_args_count = len(func_args) - len(func_defaults) <NEW_LINE> if free_args_count > 0: <NEW_LINE> <INDENT> raise TypeError("property has unbound variables: %s" % func_args[:free_args_count]) <NEW_LINE> <DEDENT> return Property(func=func, data=dict(zip(func_args, func_defaults)), tests_count=self.tests_count)
Decorator for Python functions that define properties to be tested by pyqcy. It is expected that default values for function arguments define generators that will be used to generate data for test cases. See the section about :doc:`using generators <arbitraries>` for more information. Example of using ``@qc`` to define a test property:: @qc def len_behaves_correctly( l=list_(int, min_length=1, max_length=64) ): assert len(l) == l.__len__()
62598fd497e22403b383b3e2
class FailTwicePlug(base_plugs.BasePlug): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.count = 0 <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.count += 1 <NEW_LINE> print('FailTwicePlug: Run number %s' % (self.count)) <NEW_LINE> if self.count < 3: <NEW_LINE> <INDENT> raise RuntimeError('Fails a couple times') <NEW_LINE> <DEDENT> return True
Plug that fails twice raising an exception.
62598fd4a219f33f346c6cdf
class PatientDataset(Dataset): <NEW_LINE> <INDENT> def __init__(self, feature_file, outcome_file, ablation=None): <NEW_LINE> <INDENT> self.features = pd.read_csv(feature_file) <NEW_LINE> if ablation is not None: <NEW_LINE> <INDENT> replace = pd.read_csv('C:/Users/Andrew/Documents/Stanford/cs230/cs230-code-examples/pytorch/vision/data/abl_replace.csv') <NEW_LINE> for ind in ablation: <NEW_LINE> <INDENT> self.features.iloc[:, ind] = replace.iloc[ind, 1] <NEW_LINE> <DEDENT> <DEDENT> self.csns = self.features['patient_csn_clean'].unique() <NEW_LINE> self.labels = pd.read_csv(outcome_file)['disc.24.hr'] <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.csns) <NEW_LINE> <DEDENT> def __getitem__(self, idx): <NEW_LINE> <INDENT> pat_inds = np.where(self.features['patient_csn_clean'] == self.csns[idx]) <NEW_LINE> pat_data = self.features.iloc[pat_inds] <NEW_LINE> pat_data = np.array(np.array(self.features.iloc[pat_inds]).astype(np.float32)) <NEW_LINE> pat_data = torch.from_numpy(np.array(self.features.iloc[pat_inds]).astype(np.float32)) <NEW_LINE> pat_data = pat_data[:,2:] <NEW_LINE> return pat_data, np.array(self.labels.iloc[pat_inds]).astype(np.float32)
A standard PyTorch definition of Dataset which defines the functions __len__ and __getitem__.
62598fd48a349b6b4368671a
class NomineeError(ElectionError): <NEW_LINE> <INDENT> pass
Raised when an invalid nominee is nominated.
62598fd4c4546d3d9def74ef
class DeleteModelObject(task.Task): <NEW_LINE> <INDENT> def execute(self, object): <NEW_LINE> <INDENT> object.delete()
Task to delete an object in a model.
62598fd455399d3f056269f4
class Agent(): <NEW_LINE> <INDENT> def __init__(self, state_size, action_size, random_seed): <NEW_LINE> <INDENT> self.state_size = state_size <NEW_LINE> self.action_size = action_size <NEW_LINE> self.seed = random.seed(random_seed) <NEW_LINE> self.actor_local = Actor(state_size, action_size, random_seed).to(device) <NEW_LINE> self.actor_target = Actor(state_size, action_size, random_seed).to(device) <NEW_LINE> self.actor_optimizer = optim.Adam(self.actor_local.parameters(), lr=LR_ACTOR) <NEW_LINE> self.critic_local = Critic(state_size, action_size, random_seed).to(device) <NEW_LINE> self.critic_target = Critic(state_size, action_size, random_seed).to(device) <NEW_LINE> self.critic_optimizer = optim.Adam(self.critic_local.parameters(), lr=LR_CRITIC, weight_decay=WEIGHT_DECAY) <NEW_LINE> self.noise = OUNoise(action_size, random_seed) <NEW_LINE> self.memory = ReplayBuffer(action_size, BUFFER_SIZE, BATCH_SIZE, random_seed) <NEW_LINE> <DEDENT> def step(self, state, action, reward, next_state, done): <NEW_LINE> <INDENT> self.memory.add(state, action, reward, next_state, done) <NEW_LINE> if len(self.memory) > BATCH_SIZE: <NEW_LINE> <INDENT> experiences = self.memory.sample() <NEW_LINE> self.learn(experiences, GAMMA) <NEW_LINE> <DEDENT> <DEDENT> def act(self, state, add_noise=True): <NEW_LINE> <INDENT> state = torch.from_numpy(state).float().unsqueeze(0).to(device) <NEW_LINE> self.actor_local.eval() <NEW_LINE> with torch.no_grad(): <NEW_LINE> <INDENT> action = self.actor_local(state).cpu().data.numpy() <NEW_LINE> <DEDENT> self.actor_local.train() <NEW_LINE> if add_noise: <NEW_LINE> <INDENT> action += self.noise.sample() <NEW_LINE> <DEDENT> return action <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.noise.reset() <NEW_LINE> <DEDENT> def learn(self, experiences, gamma): <NEW_LINE> <INDENT> states, actions, rewards, next_states, dones = experiences <NEW_LINE> actions_next = self.actor_target(next_states) <NEW_LINE> Q_targets_next = self.critic_target(next_states, actions_next) <NEW_LINE> Q_targets = rewards + (gamma * Q_targets_next * (1 - dones)) <NEW_LINE> Q_expected = self.critic_local(states, actions) <NEW_LINE> critic_loss = F.mse_loss(Q_expected, Q_targets) <NEW_LINE> self.critic_optimizer.zero_grad() <NEW_LINE> critic_loss.backward() <NEW_LINE> self.critic_optimizer.step() <NEW_LINE> actions_pred = self.actor_local(states) <NEW_LINE> actor_loss = -self.critic_local(states, actions_pred).mean() <NEW_LINE> self.actor_optimizer.zero_grad() <NEW_LINE> actor_loss.backward() <NEW_LINE> self.actor_optimizer.step() <NEW_LINE> self.soft_update(self.critic_local, self.critic_target, TAU) <NEW_LINE> self.soft_update(self.actor_local, self.actor_target, TAU) <NEW_LINE> <DEDENT> def soft_update(self, local_model, target_model, tau): <NEW_LINE> <INDENT> for target_param, local_param in zip(target_model.parameters(), local_model.parameters()): <NEW_LINE> <INDENT> target_param.data.copy_(tau*local_param.data + (1.0-tau)*target_param.data)
Interacts with and learns from the environment.
62598fd40fa83653e46f53c2
class UpdateError(ModelNormal): <NEW_LINE> <INDENT> allowed_values = { } <NEW_LINE> validations = { } <NEW_LINE> additional_properties_type = None <NEW_LINE> _nullable = False <NEW_LINE> @cached_property <NEW_LINE> def openapi_types(): <NEW_LINE> <INDENT> return { 'parameter': (str,), 'current_value': (str,), 'requested_value': (str,), 'message': (str,), } <NEW_LINE> <DEDENT> @cached_property <NEW_LINE> def discriminator(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> attribute_map = { 'parameter': 'parameter', 'current_value': 'currentValue', 'requested_value': 'requestedValue', 'message': 'message', } <NEW_LINE> _composed_schemas = {} <NEW_LINE> required_properties = set([ '_data_store', '_check_type', '_spec_property_naming', '_path_to_item', '_configuration', '_visited_composed_classes', ]) <NEW_LINE> @convert_js_args_to_python_args <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> _check_type = kwargs.pop('_check_type', True) <NEW_LINE> _spec_property_naming = kwargs.pop('_spec_property_naming', False) <NEW_LINE> _path_to_item = kwargs.pop('_path_to_item', ()) <NEW_LINE> _configuration = kwargs.pop('_configuration', None) <NEW_LINE> _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) <NEW_LINE> if args: <NEW_LINE> <INDENT> raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) <NEW_LINE> <DEDENT> self._data_store = {} <NEW_LINE> self._check_type = _check_type <NEW_LINE> self._spec_property_naming = _spec_property_naming <NEW_LINE> self._path_to_item = _path_to_item <NEW_LINE> self._configuration = _configuration <NEW_LINE> self._visited_composed_classes = _visited_composed_classes + (self.__class__,) <NEW_LINE> for var_name, var_value in kwargs.items(): <NEW_LINE> <INDENT> if var_name not in self.attribute_map and self._configuration is not None and self._configuration.discard_unknown_keys and self.additional_properties_type is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> setattr(self, var_name, var_value)
NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict with a capitalized key describing the allowed value and an allowed value. These dicts store the allowed enum values. attribute_map (dict): The key is attribute name and the value is json key in definition. discriminator_value_class_map (dict): A dict to go from the discriminator variable value to the discriminator class name. validations (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict that stores validations for max_length, min_length, max_items, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, inclusive_minimum, and regex. additional_properties_type (tuple): A tuple of classes accepted as additional properties values.
62598fd4091ae356687050f7
class PostHandler(Handler): <NEW_LINE> <INDENT> def get(self, post_name): <NEW_LINE> <INDENT> if not post_name: <NEW_LINE> <INDENT> self.redirect('/') <NEW_LINE> <DEDENT> post_name = post_name.lower() <NEW_LINE> post_dict = dbwrap.post_dict <NEW_LINE> if post_name in post_dict: <NEW_LINE> <INDENT> post = dbwrap.get_post(post_name) <NEW_LINE> prev_post, next_post = posts.get_adj_posts(post_name) <NEW_LINE> self.render("post-page.html", post=post, prev_post=prev_post, next_post=next_post, url=self.request.url, ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.redirect('/')
Serves a specific post by post-name.
62598fd4ec188e330fdf8d72
class IPv4Network(_BaseIPNetwork, _BaseIPv4): <NEW_LINE> <INDENT> __slots__ = ('_ip', '_private', '_prefixlen', '_size', '_netmask', '_networkaddress', '_netmaskaddress', '_hostmask', '_broadcastaddress') <NEW_LINE> _address_class = IPv4Address <NEW_LINE> def __init__(self, address, strict=True): <NEW_LINE> <INDENT> prefix = None <NEW_LINE> if isinstance(address, tuple): <NEW_LINE> <INDENT> if len(address) == 1: <NEW_LINE> <INDENT> address = address[0] <NEW_LINE> <DEDENT> elif len(address) == 2: <NEW_LINE> <INDENT> address, prefix = address <NEW_LINE> <DEDENT> <DEDENT> if isinstance(address, bytes): <NEW_LINE> <INDENT> address = int.from_bytes(address, 'big') <NEW_LINE> <DEDENT> if isinstance(address, int): <NEW_LINE> <INDENT> if address < 0 or address > self._max_address: <NEW_LINE> <INDENT> raise AddressValueError('invalid network: %r' % (address,)) <NEW_LINE> <DEDENT> ip = address <NEW_LINE> <DEDENT> elif isinstance(address, str): <NEW_LINE> <INDENT> if prefix is None: <NEW_LINE> <INDENT> ip, prefix = self.from_string(address) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ip = self._address_class.from_string(address) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise AddressValueError('invalid address: %r' % (address,)) <NEW_LINE> <DEDENT> if isinstance(prefix, int): <NEW_LINE> <INDENT> self._prefixlen = prefix <NEW_LINE> <DEDENT> elif isinstance(prefix, str): <NEW_LINE> <INDENT> self._prefixlen = self._prefix_from_string(prefix) <NEW_LINE> <DEDENT> elif prefix is None: <NEW_LINE> <INDENT> self._prefixlen = self._address_len <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NetmaskValueError('invalid prefix: %r' % address) <NEW_LINE> <DEDENT> if not 0 <= self._prefixlen <= self._address_len: <NEW_LINE> <INDENT> raise NetmaskValueError('invalid prefix: %r' % address) <NEW_LINE> <DEDENT> self._size = 2**(self._address_len - self._prefixlen) <NEW_LINE> self._netmask = self._max_address - self._size + 1 <NEW_LINE> self._ip = ip & self._netmask <NEW_LINE> if strict and self._ip != ip: <NEW_LINE> <INDENT> raise ValueError('%r (%x) has host bits set' % (address, addr)) <NEW_LINE> <DEDENT> self._private = None <NEW_LINE> self._networkaddress = None <NEW_LINE> self._broadcastaddress = None <NEW_LINE> self._netmaskaddress = None <NEW_LINE> self._hostmask = None <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self._to_string(self._ip, self._prefixlen) <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash((self._ip, self._size)) <NEW_LINE> <DEDENT> def __reduce__(self): <NEW_LINE> <INDENT> return self.__class__, ((self._ip, self._prefixlen),) <NEW_LINE> <DEDENT> def hosts(self): <NEW_LINE> <INDENT> for i in range(self._ip + 1, self._ip + self._size - 1): <NEW_LINE> <INDENT> yield self._address_class(i) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def is_global(self): <NEW_LINE> <INDENT> return (not self._constants._public_net._contains_net(self) and not self.is_private) <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_loopback(self): <NEW_LINE> <INDENT> return self._constants._loopback_net._contains_net(self) <NEW_LINE> <DEDENT> def _get_mixed_type_key(self): <NEW_LINE> <INDENT> return self._version, self._ip, '', self._size, 2
An IPv4 Network.
62598fd4dc8b845886d53a9a
class HighlightSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> comment = serializers.CharField(required=False) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Highlight <NEW_LINE> fields = ("highlighter", "article_id", "highlight", "comment")
This class defines a highlight datafields
62598fd43d592f4c4edbb393
class TankParameter(db.Model): <NEW_LINE> <INDENT> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> timestamp = db.Column(db.DateTime) <NEW_LINE> value = db.Column(db.Float) <NEW_LINE> tank_id = db.Column(db.Integer, db.ForeignKey('tank.id')) <NEW_LINE> tank = db.relationship('Tank', backref=db.backref('tankparameter', lazy='dynamic')) <NEW_LINE> param_id = db.Column(db.Integer, db.ForeignKey('parameter.id')) <NEW_LINE> param = db.relationship('Parameter', backref=db.backref('tankparameter', lazy='dynamic')) <NEW_LINE> def __init__(self, param, value, tank, timestamp=None): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> self.tank = tank <NEW_LINE> self.param = param <NEW_LINE> if not timestamp: <NEW_LINE> <INDENT> self.timestamp = datetime.utcnow()
These are specific instances of metrics. Example: Tank 1 had a pH of 7.1 yesterday, and a pH of 7.0 today.
62598fd4377c676e912f6fe8
class TwoRNA(_object): <NEW_LINE> <INDENT> __swig_setmethods__ = {} <NEW_LINE> __setattr__ = lambda self, name, value: _swig_setattr(self, TwoRNA, name, value) <NEW_LINE> __swig_getmethods__ = {} <NEW_LINE> __getattr__ = lambda self, name: _swig_getattr(self, TwoRNA, name) <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __init__(self, *args): <NEW_LINE> <INDENT> this = _RNAstructure_wrap.new_TwoRNA(*args) <NEW_LINE> try: <NEW_LINE> <INDENT> self.this.append(this) <NEW_LINE> <DEDENT> except __builtin__.Exception: <NEW_LINE> <INDENT> self.this = this <NEW_LINE> <DEDENT> <DEDENT> def SetTemperature(self, temperature): <NEW_LINE> <INDENT> return _RNAstructure_wrap.TwoRNA_SetTemperature(self, temperature) <NEW_LINE> <DEDENT> def GetTemperature(self): <NEW_LINE> <INDENT> return _RNAstructure_wrap.TwoRNA_GetTemperature(self) <NEW_LINE> <DEDENT> def GetErrorCode(self): <NEW_LINE> <INDENT> return _RNAstructure_wrap.TwoRNA_GetErrorCode(self) <NEW_LINE> <DEDENT> def GetErrorMessage(self, error): <NEW_LINE> <INDENT> return _RNAstructure_wrap.TwoRNA_GetErrorMessage(self, error) <NEW_LINE> <DEDENT> def GetErrorDetails(self): <NEW_LINE> <INDENT> return _RNAstructure_wrap.TwoRNA_GetErrorDetails(self) <NEW_LINE> <DEDENT> def SetErrorDetails(self, details): <NEW_LINE> <INDENT> return _RNAstructure_wrap.TwoRNA_SetErrorDetails(self, details) <NEW_LINE> <DEDENT> def GetErrorMessageString(self, error): <NEW_LINE> <INDENT> return _RNAstructure_wrap.TwoRNA_GetErrorMessageString(self, error) <NEW_LINE> <DEDENT> def ResetError(self): <NEW_LINE> <INDENT> return _RNAstructure_wrap.TwoRNA_ResetError(self) <NEW_LINE> <DEDENT> def GetRNA1(self): <NEW_LINE> <INDENT> return _RNAstructure_wrap.TwoRNA_GetRNA1(self) <NEW_LINE> <DEDENT> def GetRNA2(self): <NEW_LINE> <INDENT> return _RNAstructure_wrap.TwoRNA_GetRNA2(self) <NEW_LINE> <DEDENT> __swig_destroy__ = _RNAstructure_wrap.delete_TwoRNA <NEW_LINE> __del__ = lambda self: None <NEW_LINE> __swig_setmethods__["compoundmessage"] = _RNAstructure_wrap.TwoRNA_compoundmessage_set <NEW_LINE> __swig_getmethods__["compoundmessage"] = _RNAstructure_wrap.TwoRNA_compoundmessage_get <NEW_LINE> if _newclass: <NEW_LINE> <INDENT> compoundmessage = _swig_property(_RNAstructure_wrap.TwoRNA_compoundmessage_get, _RNAstructure_wrap.TwoRNA_compoundmessage_set)
TwoRNA Class. The TwoRNA class provides an entry point for all the two sequence prediction routines of RNAstructure. This contains two instances of the RNA class to provide the functionality of RNA. C++ includes: TwoRNA.h
62598fd4956e5f7376df58ec
class Review(BaseModel): <NEW_LINE> <INDENT> place_id = "" <NEW_LINE> user_id = "" <NEW_LINE> text = ""
Public Class attributes
62598fd5fbf16365ca79459c
class Logger(object): <NEW_LINE> <INDENT> def __init__( self, task_name, level=logging.NOTSET, to_file=True, file_path=None, additional=None, ): <NEW_LINE> <INDENT> self.task_name = task_name <NEW_LINE> self.logger = ( get_task_logger(task_name) if task_name else logging.getLogger(__name__) ) <NEW_LINE> self.logger.setLevel(level) <NEW_LINE> self.log_file = None <NEW_LINE> if not task_name: <NEW_LINE> <INDENT> self.logger.addHandler(logging.StreamHandler()) <NEW_LINE> <DEDENT> if to_file: <NEW_LINE> <INDENT> if file_path: <NEW_LINE> <INDENT> if additional: <NEW_LINE> <INDENT> raise ValueError("file_path and additional can't be both defined") <NEW_LINE> <DEDENT> if not os.path.isdir(os.path.dirname(file_path)): <NEW_LINE> <INDENT> self.logger.error( "{} is not a directory".format(os.path.dirname(file_path)) ) <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> file_path = self.file_path(additional=additional) <NEW_LINE> <DEDENT> except RuntimeError as exc: <NEW_LINE> <INDENT> self.logger.error(exc) <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> self.log_file = file_path <NEW_LINE> file_handler = logging.FileHandler(file_path) <NEW_LINE> self.logger.addHandler(file_handler) <NEW_LINE> <DEDENT> <DEDENT> def file_path(self, additional=None, date=True): <NEW_LINE> <INDENT> logs_dir = os.getenv("LOGS_DIR") or "/var/log/bots" <NEW_LINE> if not os.path.isdir(logs_dir): <NEW_LINE> <INDENT> raise RuntimeError("{} is not a directory".format(logs_dir)) <NEW_LINE> <DEDENT> return ( "{dir}/{task}{additional}.log{date}".format( dir=logs_dir, task=self.task_name, additional="-" + additional if additional else "", date="-" + datetime.now().strftime("%Y%m%d"), ) if date else "" ) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def format(msg, args): <NEW_LINE> <INDENT> if isinstance(msg, bytes): <NEW_LINE> <INDENT> msg = msg.decode("utf-8") <NEW_LINE> <DEDENT> return msg % args if args else msg <NEW_LINE> <DEDENT> def log(self, level, report_dict): <NEW_LINE> <INDENT> msg = self.serialize(level, report_dict) <NEW_LINE> if level == logging.CRITICAL: <NEW_LINE> <INDENT> self.logger.critical(msg) <NEW_LINE> <DEDENT> elif level == logging.ERROR: <NEW_LINE> <INDENT> self.logger.error(msg) <NEW_LINE> <DEDENT> elif level == logging.WARNING: <NEW_LINE> <INDENT> self.logger.warning(msg) <NEW_LINE> <DEDENT> elif level == logging.INFO: <NEW_LINE> <INDENT> self.logger.info(msg) <NEW_LINE> <DEDENT> elif level == logging.DEBUG: <NEW_LINE> <INDENT> self.logger.debug(msg) <NEW_LINE> <DEDENT> <DEDENT> def serialize(self, level, report_dict): <NEW_LINE> <INDENT> report_dict.update( { "level": logging.getLevelName(level), "task": self.task_name, "time": str(datetime.utcnow()), } ) <NEW_LINE> serialized = json.dumps(report_dict, sort_keys=True, indent=2) <NEW_LINE> serialized = serialized.replace("\\n", "\n") <NEW_LINE> return serialized
Log by - logging to stderr (default) - writing json to file
62598fd5adb09d7d5dc0aa58
class UpdateProfileRequest(BaseModel): <NEW_LINE> <INDENT> user_id: ObjectIdStr <NEW_LINE> bio: str = None <NEW_LINE> gender: str = None
Request for update profile usecase
62598fd5bf627c535bcb198e
class LException: <NEW_LINE> <INDENT> def __init__(self,msg): <NEW_LINE> <INDENT> self.msg = msg <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.msg
L-System exception class
62598fd5be7bc26dc92520c7
class SpikesVector(MultiFieldVector): <NEW_LINE> <INDENT> fields = [ ('receiver_neuron_index', types.address), ]
Вектор для IS_SPIKED нейронов. Используется в remote_domain.send_spikes и local_domain.receive_spikes
62598fd5377c676e912f6fe9
class SearchForm(Form): <NEW_LINE> <INDENT> search = StringField('search', validators=[DataRequired()])
搜索表单,用于搜索相关帖子 search:查找的内容
62598fd5ad47b63b2c5a7d31
class OpenAccount(Wizard): <NEW_LINE> <INDENT> __name__ = 'account.move.open_account' <NEW_LINE> start_state = 'open_' <NEW_LINE> open_ = StateAction('account.act_move_line_form') <NEW_LINE> def do_open_(self, action): <NEW_LINE> <INDENT> FiscalYear = Pool().get('account.fiscalyear') <NEW_LINE> if not Transaction().context.get('fiscalyear'): <NEW_LINE> <INDENT> fiscalyears = FiscalYear.search([ ('state', '=', 'open'), ('company', '=', self.record.company.id if self.record else None), ]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fiscalyears = [FiscalYear(Transaction().context['fiscalyear'])] <NEW_LINE> <DEDENT> periods = [p for f in fiscalyears for p in f.periods] <NEW_LINE> action['pyson_domain'] = [ ('period', 'in', [p.id for p in periods]), ('account', '=', self.record.id if self.record else None), ('state', '=', 'valid'), ] <NEW_LINE> if Transaction().context.get('posted'): <NEW_LINE> <INDENT> action['pyson_domain'].append(('move.state', '=', 'posted')) <NEW_LINE> <DEDENT> if Transaction().context.get('date'): <NEW_LINE> <INDENT> action['pyson_domain'].append(('move.date', '<=', Transaction().context['date'])) <NEW_LINE> <DEDENT> if self.record: <NEW_LINE> <INDENT> action['name'] += ' (%s)' % self.record.rec_name <NEW_LINE> <DEDENT> action['pyson_domain'] = PYSONEncoder().encode(action['pyson_domain']) <NEW_LINE> action['pyson_context'] = PYSONEncoder().encode({ 'fiscalyear': Transaction().context.get('fiscalyear'), }) <NEW_LINE> return action, {}
Open Account
62598fd5dc8b845886d53a9e
class FeaturesManager(object): <NEW_LINE> <INDENT> def __init__(self, parser, feature_threshold, prefix_flag, extended_mode=False): <NEW_LINE> <INDENT> self.parser = parser <NEW_LINE> self.prefix_flag = prefix_flag <NEW_LINE> self.feature_templates = [] <NEW_LINE> self.add_baseline_features() <NEW_LINE> if extended_mode: <NEW_LINE> <INDENT> self.add_extended_features() <NEW_LINE> <DEDENT> for sentence in parser.get_train_sentences(): <NEW_LINE> <INDENT> for labeled_token in sentence[1:]: <NEW_LINE> <INDENT> head = labeled_token.head <NEW_LINE> modifier = labeled_token.idx <NEW_LINE> for template in self.feature_templates: <NEW_LINE> <INDENT> template.add_local_feature(sentence, head, modifier) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> idx = 0 <NEW_LINE> for i, t in enumerate(self.feature_templates): <NEW_LINE> <INDENT> temp = idx <NEW_LINE> idx = t.filter(feature_threshold, idx) <NEW_LINE> print("template number",i,":", idx - temp) <NEW_LINE> <DEDENT> self.num_features = idx <NEW_LINE> <DEDENT> def calc_feature_vec(self, sentence, head, modifier): <NEW_LINE> <INDENT> return [t.get_feature_index(sentence, head, modifier) for t in self.feature_templates if t.eval(sentence, head, modifier) == 1] <NEW_LINE> <DEDENT> def calc_feature_vec_for_tree(self, sentence, dep_parse_tree): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for (head, modifier) in dep_parse_tree: <NEW_LINE> <INDENT> indices = self.calc_feature_vec(sentence, head, modifier) <NEW_LINE> for idx in indices: <NEW_LINE> <INDENT> cnt = result.get(idx, 0) <NEW_LINE> result[idx] = cnt + 1 <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def get_num_features(self): <NEW_LINE> <INDENT> return self.num_features <NEW_LINE> <DEDENT> def add_baseline_features(self): <NEW_LINE> <INDENT> self.feature_templates += [BasicLFT1(), BasicLFT2(), BasicLFT3(), BasicLFT4(), BasicLFT5(), BasicLFT6(), BasicLFT8(), BasicLFT10(), BasicLFT13()] <NEW_LINE> <DEDENT> def add_extended_features(self): <NEW_LINE> <INDENT> self.feature_templates += [ExtendedLFT1(),ExtendedLFT2(),ExtendedLFT3(), ExtendedLFT4(), ExtendedLFT5(), ExtendedLFT6(), ExtendedLFT7(), ExtendedLFT8(), ExtendedLFT9() ] <NEW_LINE> if self.prefix_flag: <NEW_LINE> <INDENT> self.feature_templates += [ExtendedLFT10(self.parser.get_prefix())] <NEW_LINE> <DEDENT> <DEDENT> def add_in_between_features(self): <NEW_LINE> <INDENT> TAGS = {'CD', 'POS', 'UH', 'JJR', 'PRP', 'WDT', 'EX', 'SYM', 'NNPS', 'WP', 'CC', 'JJ', 'VBP', 'WRB', 'RBR', 'MD', 'IN', 'VB', 'DT', 'RBS', 'VBG', 'RP', 'JJS', 'NN', 'PDT', 'RB', 'VBN', 'TO', 'LS', 'NNS', 'VBZ', 'FW', 'NNP', 'VBD'} <NEW_LINE> self.feature_templates += [InBetweenLFT1(tag) for tag in TAGS] <NEW_LINE> self.feature_templates += [InBetweenLFT2()]
Generates set of features out of a given training data
62598fd5adb09d7d5dc0aa5a
class FileObjectInputReader(CLIInputReader): <NEW_LINE> <INDENT> def __init__(self, file_object, encoding=u'utf-8'): <NEW_LINE> <INDENT> super(FileObjectInputReader, self).__init__(encoding=encoding) <NEW_LINE> self._errors = u'strict' <NEW_LINE> self._file_object = file_object <NEW_LINE> <DEDENT> def Read(self): <NEW_LINE> <INDENT> encoded_string = self._file_object.readline() <NEW_LINE> try: <NEW_LINE> <INDENT> string = encoded_string.decode(self._encoding, errors=self._errors) <NEW_LINE> <DEDENT> except UnicodeDecodeError: <NEW_LINE> <INDENT> if self._errors == u'strict': <NEW_LINE> <INDENT> logging.error( u'Unable to properly read input due to encoding error. ' u'Switching to error tolerant encoding which can result in ' u'non Basic Latin (C0) characters to be replaced with "?" or ' u'"\\ufffd".') <NEW_LINE> self._errors = u'replace' <NEW_LINE> <DEDENT> string = encoded_string.decode(self._encoding, errors=self._errors) <NEW_LINE> <DEDENT> return string
Class that implements a file-like object input reader. This input reader relies on the file-like object having a readline method.
62598fd53617ad0b5ee06628
class NonPooledPanelOLS(object): <NEW_LINE> <INDENT> ATTRIBUTES = [ 'beta', 'df', 'df_model', 'df_resid', 'f_stat', 'p_value', 'r2', 'r2_adj', 'resid', 'rmse', 'std_err', 'summary_as_matrix', 't_stat', 'var_beta', 'x', 'y', 'y_fitted', 'y_predict' ] <NEW_LINE> def __init__(self, y, x, window_type='full_sample', window=None, min_periods=None, intercept=True, nw_lags=None, nw_overlap=False): <NEW_LINE> <INDENT> import warnings <NEW_LINE> warnings.warn("The pandas.stats.plm module is deprecated and will be " "removed in a future version. We refer to external packages " "like statsmodels, see some examples here: " "http://www.statsmodels.org/stable/mixed_linear.html", FutureWarning, stacklevel=4) <NEW_LINE> for attr in self.ATTRIBUTES: <NEW_LINE> <INDENT> setattr(self.__class__, attr, create_ols_attr(attr)) <NEW_LINE> <DEDENT> results = {} <NEW_LINE> for entity in y: <NEW_LINE> <INDENT> entity_y = y[entity] <NEW_LINE> entity_x = {} <NEW_LINE> for x_var in x: <NEW_LINE> <INDENT> entity_x[x_var] = x[x_var][entity] <NEW_LINE> <DEDENT> from pandas.stats.interface import ols <NEW_LINE> results[entity] = ols(y=entity_y, x=entity_x, window_type=window_type, window=window, min_periods=min_periods, intercept=intercept, nw_lags=nw_lags, nw_overlap=nw_overlap) <NEW_LINE> <DEDENT> self.results = results
Implements non-pooled panel OLS. Parameters ---------- y : DataFrame x : Series, DataFrame, or dict of Series intercept : bool True if you want an intercept. nw_lags : None or int Number of Newey-West lags. window_type : {'full_sample', 'rolling', 'expanding'} 'full_sample' by default window : int size of window (for rolling/expanding OLS)
62598fd5a219f33f346c6ce7
class Course(CommonInfo): <NEW_LINE> <INDENT> grade = models.ForeignKey('classes.ClassCategory', default=default_uuid) <NEW_LINE> code = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) <NEW_LINE> objects = CourseManager() <NEW_LINE> class Meta(CommonInfo.Meta): <NEW_LINE> <INDENT> verbose_name_plural = "1. Stream" <NEW_LINE> verbose_name = "Stream" <NEW_LINE> unique_together = ['title', 'grade'] <NEW_LINE> ordering = ('grade__title', 'title',) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return name_definition(self.title, self.grade) <NEW_LINE> <DEDENT> def get_uuid_name_definition(self): <NEW_LINE> <INDENT> return uuid_name_definition(self.grade, str(self.code)) <NEW_LINE> <DEDENT> def chained_relation(self): <NEW_LINE> <INDENT> print('Hello gaurav ...') <NEW_LINE> return self.item_set.filter(is_present=True)
Course class for CRUD
62598fd5ab23a570cc2d4fde
class AuthorizationForm(FormMixin): <NEW_LINE> <INDENT> pass
Not yet implemented
62598fd5d8ef3951e32c80cc
class StringKPI(KPI): <NEW_LINE> <INDENT> value = EAttribute(eType=EString, unique=True, derived=False, changeable=True) <NEW_LINE> target = EReference(ordered=True, unique=True, containment=True, derived=False, upper=-1) <NEW_LINE> def __init__(self, *, value=None, target=None, **kwargs): <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> if value is not None: <NEW_LINE> <INDENT> self.value = value <NEW_LINE> <DEDENT> if target: <NEW_LINE> <INDENT> self.target.extend(target)
Specifies a KPI value as a string
62598fd5adb09d7d5dc0aa5c
class Caltech101(tfds.core.GeneratorBasedBuilder): <NEW_LINE> <INDENT> VERSION = tfds.core.Version( "3.0.0", "New split API (https://tensorflow.org/datasets/splits)") <NEW_LINE> def _info(self): <NEW_LINE> <INDENT> names_file = tfds.core.get_tfds_path(_LABELS_FNAME) <NEW_LINE> return tfds.core.DatasetInfo( builder=self, description=_DESCRIPTION, features=tfds.features.FeaturesDict({ "image": tfds.features.Image(), "label": tfds.features.ClassLabel(names_file=names_file), "image/file_name": tfds.features.Text(), }), supervised_keys=("image", "label"), homepage=_URL, citation=_CITATION ) <NEW_LINE> <DEDENT> def _split_generators(self, dl_manager): <NEW_LINE> <INDENT> path = dl_manager.download_and_extract(os.path.join(_URL, _IMAGES_FNAME)) <NEW_LINE> return [ tfds.core.SplitGenerator( name=tfds.Split.TRAIN, gen_kwargs={ "images_dir_path": path, "is_train_split": True, }), tfds.core.SplitGenerator( name=tfds.Split.TEST, gen_kwargs={ "images_dir_path": path, "is_train_split": False, }), ] <NEW_LINE> <DEDENT> def _generate_examples(self, images_dir_path, is_train_split): <NEW_LINE> <INDENT> numpy_original_state = np.random.get_state() <NEW_LINE> np.random.seed(1234) <NEW_LINE> parent_dir = tf.io.gfile.listdir(images_dir_path)[0] <NEW_LINE> walk_dir = os.path.join(images_dir_path, parent_dir) <NEW_LINE> dirs = tf.io.gfile.listdir(walk_dir) <NEW_LINE> for d in dirs: <NEW_LINE> <INDENT> if tf.io.gfile.isdir(os.path.join(walk_dir, d)): <NEW_LINE> <INDENT> for full_path, _, fnames in tf.io.gfile.walk(os.path.join(walk_dir, d)): <NEW_LINE> <INDENT> if _TRAIN_POINTS_PER_CLASS > len(fnames): <NEW_LINE> <INDENT> raise ValueError("Fewer than {} ({}) points in class {}".format( _TRAIN_POINTS_PER_CLASS, len(fnames), d)) <NEW_LINE> <DEDENT> train_fnames = np.random.choice(fnames, _TRAIN_POINTS_PER_CLASS, replace=False) <NEW_LINE> test_fnames = set(fnames).difference(train_fnames) <NEW_LINE> fnames_to_emit = train_fnames if is_train_split else test_fnames <NEW_LINE> for image_file in fnames_to_emit: <NEW_LINE> <INDENT> if image_file.endswith(".jpg"): <NEW_LINE> <INDENT> image_path = os.path.join(full_path, image_file) <NEW_LINE> record = { "image": image_path, "label": d.lower(), "image/file_name": image_file, } <NEW_LINE> yield "%s/%s" % (d, image_file), record <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> np.random.set_state(numpy_original_state)
Caltech-101.
62598fd5ad47b63b2c5a7d34
class FileBlob(): <NEW_LINE> <INDENT> def __init__(self, key: str, file_path: Path, data: LoadableType) -> None: <NEW_LINE> <INDENT> self.__key = key <NEW_LINE> self.__file_path = file_path <NEW_LINE> self.__class_object = data <NEW_LINE> <DEDENT> @property <NEW_LINE> def key(self) -> str: <NEW_LINE> <INDENT> return self.__key <NEW_LINE> <DEDENT> @property <NEW_LINE> def file_path(self) -> Path: <NEW_LINE> <INDENT> return self.__file_path <NEW_LINE> <DEDENT> @property <NEW_LINE> def data(self) -> LoadableType: <NEW_LINE> <INDENT> return self.__class_object
A FileBlob is a keyed data blob for everything that is loadable from a file and can be converted to a VaRA DataClass. Args: key: identifier for the file file_path: path to the file data: a blob of data in memory
62598fd53d592f4c4edbb399
class ThreadPoolPlugin(colony.Plugin): <NEW_LINE> <INDENT> id = "pt.hive.colony.plugins.threads.pool" <NEW_LINE> name = "Thread Pool" <NEW_LINE> description = "Thread Pool Plugin" <NEW_LINE> version = "1.0.0" <NEW_LINE> author = "Hive Solutions Lda. <development@hive.pt>" <NEW_LINE> platforms = [ colony.CPYTHON_ENVIRONMENT, colony.JYTHON_ENVIRONMENT, colony.IRON_PYTHON_ENVIRONMENT ] <NEW_LINE> capabilities = [ "threads", "thread_pool", "system_information" ] <NEW_LINE> main_modules = [ "thread_pool" ] <NEW_LINE> def load_plugin(self): <NEW_LINE> <INDENT> colony.Plugin.load_plugin(self) <NEW_LINE> import thread_pool <NEW_LINE> self.system = thread_pool.ThreadPool(self) <NEW_LINE> <DEDENT> def unload_plugin(self): <NEW_LINE> <INDENT> colony.Plugin.unload_plugin(self) <NEW_LINE> self.system.unload() <NEW_LINE> <DEDENT> def create_new_thread_pool(self, name, description, number_threads, scheduling_algorithm, maximum_number_threads): <NEW_LINE> <INDENT> return self.system.create_new_thread_pool(name, description, number_threads, scheduling_algorithm, maximum_number_threads) <NEW_LINE> <DEDENT> def get_thread_task_descriptor_class(self): <NEW_LINE> <INDENT> return self.system.get_thread_task_descriptor_class() <NEW_LINE> <DEDENT> def get_system_information(self): <NEW_LINE> <INDENT> return self.system.get_system_information()
The main class for the Thread Pool plugin
62598fd5ab23a570cc2d4fdf
class ZeroBridge(Bridge): <NEW_LINE> <INDENT> def __init__(self, params, encoder_output, mode, name=None, verbose=True): <NEW_LINE> <INDENT> super(ZeroBridge, self).__init__( params=params, encoder_output=encoder_output, mode=mode, name=name, verbose=verbose) <NEW_LINE> if self.verbose: <NEW_LINE> <INDENT> tf.logging.info("Using ZeroBridge. Initialize decoder state with all zero vectors.") <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def default_params(): <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> def _create(self, decoder_state_size, **kwargs): <NEW_LINE> <INDENT> batch_size = self.batch_size <NEW_LINE> return rnn_cell_impl._zero_state_tensors( decoder_state_size, batch_size, tf.float32)
Define a bridge that does not pass any information between encoder and decoder, and sets the initial decoder state to 0.
62598fd5ad47b63b2c5a7d35
class PlainProvisioner(Base): <NEW_LINE> <INDENT> def cleanup(self): <NEW_LINE> <INDENT> pass
Plain Provisioner
62598fd555399d3f056269fe
class CmdAccept(CmdTradeBase): <NEW_LINE> <INDENT> key = "accept" <NEW_LINE> aliases = ["agree"] <NEW_LINE> locks = "cmd:all()" <NEW_LINE> help_category = "Trading" <NEW_LINE> def func(self): <NEW_LINE> <INDENT> caller = self.caller <NEW_LINE> if not self.trade_started: <NEW_LINE> <INDENT> caller.msg("Wait until the other party has accepted to trade with you.") <NEW_LINE> return <NEW_LINE> <DEDENT> if self.tradehandler.accept(self.caller): <NEW_LINE> <INDENT> caller.msg(self.str_caller % "You {gaccept{n the deal. {gDeal is made and goods changed hands.{n") <NEW_LINE> self.msg_other(caller, self.str_other % "%s {gaccepts{n the deal. {gDeal is made and goods changed hands.{n" % caller.key) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> caller.msg(self.str_caller % "You {Gaccept{n the offer. %s must now also accept." % self.other.key) <NEW_LINE> self.msg_other(caller, self.str_other % "%s {Gaccepts{n the offer. You must now also accept." % caller.key)
accept the standing offer Usage: accept [:emote] agreee [:emote] This will accept the current offer. The other party must also accept for the deal to go through. You can use the 'decline' command to change your mind as long as the other party has not yet accepted. You can inspect the current offer using the 'offers' command.
62598fd5fbf16365ca7945a2
class get_templates_by_template_args(object): <NEW_LINE> <INDENT> def __init__( self, template_name=None, ): <NEW_LINE> <INDENT> self.template_name = template_name <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if ( iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None ): <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.template_name = ( iprot.readString().decode("utf-8", errors="replace") if sys.version_info[0] == 2 else iprot.readString() ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write( oprot._fast_encode(self, [self.__class__, self.thrift_spec]) ) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin("get_templates_by_template_args") <NEW_LINE> if self.template_name is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin("template_name", TType.STRING, 1) <NEW_LINE> oprot.writeString( self.template_name.encode("utf-8") if sys.version_info[0] == 2 else self.template_name ) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = [f"{key}={value!r}" for key, value in self.__dict__.items()] <NEW_LINE> return f"{self.__class__.__name__}({', '.join(L)})" <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - template_name
62598fd5091ae35668705101
class entry(object): <NEW_LINE> <INDENT> def __init__(self, path, name, extension, permission, url, extras={}, sortorder=999999, right=False, icon=None): <NEW_LINE> <INDENT> self._path = path <NEW_LINE> self._mpath = [x.strip() for x in path.split('||')] <NEW_LINE> self._name = name <NEW_LINE> self._extension = extension <NEW_LINE> self._permission = permission <NEW_LINE> self._url = url <NEW_LINE> self.func = None <NEW_LINE> self.base = None <NEW_LINE> self.extras = deepcopy(extras) <NEW_LINE> self.sortorder = sortorder <NEW_LINE> self.icon = icon <NEW_LINE> if 'class' not in self.extras: <NEW_LINE> <INDENT> self.extras['class'] = [] <NEW_LINE> <DEDENT> if not(hasattr(self.extras['class'], 'append')): <NEW_LINE> <INDENT> self.extras['class'] = [self.extras['class'],] <NEW_LINE> <DEDENT> if right: <NEW_LINE> <INDENT> self.extras['class'].append('right') <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '%s at %s' % (str(self._path), str(self._url))
This class contains all of the pieces of information about a given menu entry. It is the only public portion of this particular file. Everything else in here is private, and should not be used by any external code.
62598fd560cbc95b06364822
class TestStlinkSetMem32(_TestStlink): <NEW_LINE> <INDENT> def test(self): <NEW_LINE> <INDENT> self._com.xfer_mock.set_return_data([ [0x80, 0x00], ]) <NEW_LINE> self._stlink.set_mem32(0x20000000, 0x12345678) <NEW_LINE> self.assertEqual(self._com.xfer_mock.get_call_log(), [ {'command': [ 0xf2, 0x35, 0x00, 0x00, 0x00, 0x20, 0x78, 0x56, 0x34, 0x12, ], 'data': None, 'rx_length': 2, 'tout': 200}, ]) <NEW_LINE> <DEDENT> def test_unaligned_address(self): <NEW_LINE> <INDENT> with self.assertRaises(swd.stlink.StlinkException) as context: <NEW_LINE> <INDENT> self._stlink.set_mem32(0x20000001, 0x12345678) <NEW_LINE> <DEDENT> self.assertEqual(str(context.exception), 'Address is not aligned to 4 Bytes')
Tests for Stlink.set_mem32()
62598fd5ad47b63b2c5a7d36
class NotGate(Gate): <NEW_LINE> <INDENT> def logic(self): <NEW_LINE> <INDENT> self.output = not self.input[0]
class for NOT gate
62598fd5377c676e912f6fec
class CommandError(Exception): <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> Exception.__init__(self, message)
Raised to provide a generic way to abort a command with an error.
62598fd59f28863672818af0
class FormulaFactory(object): <NEW_LINE> <INDENT> def __listToTree(self, BinOperation, formulas, leftAssoc=True): <NEW_LINE> <INDENT> if not issubclass(BinOperation, BinaryOperation): <NEW_LINE> <INDENT> raise TypeError("BinOperation must be subclass of BinaryOperation class") <NEW_LINE> <DEDENT> if leftAssoc: <NEW_LINE> <INDENT> formula = BinOperation(formulas[0], formulas[1]) <NEW_LINE> for subf in formulas[2:]: <NEW_LINE> <INDENT> formula = BinOperation(formula, subf) <NEW_LINE> <DEDENT> return formula <NEW_LINE> <DEDENT> formulas.reverse() <NEW_LINE> formula = BinOperation(formulas[1], formulas[0]) <NEW_LINE> for subf in formulas[2:]: <NEW_LINE> <INDENT> formula = BinOperation(subf, formula) <NEW_LINE> <DEDENT> return formula <NEW_LINE> <DEDENT> def createLogicTruth(self, tokens): <NEW_LINE> <INDENT> return LogicTruth() <NEW_LINE> <DEDENT> def createLogicFalse(self, tokens): <NEW_LINE> <INDENT> return LogicFalse() <NEW_LINE> <DEDENT> def createLogicVariable(self, tokens): <NEW_LINE> <INDENT> logging.debug("Tworzę zmienną losową o nazwie: %s", tokens[0]) <NEW_LINE> return LogicVariable(tokens[0]) <NEW_LINE> <DEDENT> def createNotOperation(self, tokens): <NEW_LINE> <INDENT> return NotOperation(tokens[0][1]) <NEW_LINE> <DEDENT> def createAndOperation(self, tokens): <NEW_LINE> <INDENT> return self.__listToTree(AndOperation, tokens[0][0::2]) <NEW_LINE> <DEDENT> def createOrOperation(self, tokens): <NEW_LINE> <INDENT> return self.__listToTree(OrOperation, tokens[0][0::2]) <NEW_LINE> <DEDENT> def createImpicationOperation(self, tokens): <NEW_LINE> <INDENT> return self.__listToTree(ImplicationOperation, tokens[0][0::2], False) <NEW_LINE> <DEDENT> def createEquvalenceOperation(self, tokens): <NEW_LINE> <INDENT> return self.__listToTree(EquivalenceOperation, tokens[0][0::2])
Fabryka formuł logicznych klasa pomocnicza do tworzenia formuł logicznych z parsowanych stringów
62598fd555399d3f05626a00
class TestResult(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def loads(string): <NEW_LINE> <INDENT> return cPickle.loads(string) <NEW_LINE> <DEDENT> def __init__(self, test_name, failures=None, test_run_time=None, has_stderr=False): <NEW_LINE> <INDENT> self.test_name = test_name <NEW_LINE> self.failures = failures or [] <NEW_LINE> self.test_run_time = test_run_time or 0 <NEW_LINE> self.has_stderr = has_stderr <NEW_LINE> self.type = test_failures.determine_result_type(failures) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return (self.test_name == other.test_name and self.failures == other.failures and self.test_run_time == other.test_run_time) <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) <NEW_LINE> <DEDENT> def has_failure_matching_types(self, *failure_classes): <NEW_LINE> <INDENT> for failure in self.failures: <NEW_LINE> <INDENT> if type(failure) in failure_classes: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def dumps(self): <NEW_LINE> <INDENT> return cPickle.dumps(self)
Data object containing the results of a single test.
62598fd5dc8b845886d53aa4
class SMS(dict): <NEW_LINE> <INDENT> __allowed = ('to', 'message', 'uuid') <NEW_LINE> def __init__(self, to, message): <NEW_LINE> <INDENT> self['to'] = to <NEW_LINE> self['message'] = message <NEW_LINE> self['uuid'] = str(uuid4()) <NEW_LINE> <DEDENT> def __setitem__(self, k, v): <NEW_LINE> <INDENT> if k not in self.__allowed: <NEW_LINE> <INDENT> raise KeyError('key not allowed: %s' % k) <NEW_LINE> <DEDENT> return super(SMS, self).__setitem__(k, v)
Basic SMS Object
62598fd5adb09d7d5dc0aa60
class Surface: <NEW_LINE> <INDENT> def __init__(self, cor): <NEW_LINE> <INDENT> self.point_cor = cor
Surface class
62598fd5ad47b63b2c5a7d38
class KR_type_box(KirillovReshetikhinGenericCrystal, AffineCrystalFromClassical): <NEW_LINE> <INDENT> def __init__(self, cartan_type, r, s): <NEW_LINE> <INDENT> KirillovReshetikhinGenericCrystal.__init__(self, cartan_type, r ,s) <NEW_LINE> AffineCrystalFromClassical.__init__(self, cartan_type, self.classical_decomposition()) <NEW_LINE> <DEDENT> def classical_decomposition(self): <NEW_LINE> <INDENT> return CrystalOfTableaux(self.cartan_type().classical(), shapes = partitions_in_box(self.r(),self.s())) <NEW_LINE> <DEDENT> def ambient_crystal(self): <NEW_LINE> <INDENT> return KR_type_C(['C', self.cartan_type().classical().rank(),1], self.r(), 2*self.s()) <NEW_LINE> <DEDENT> @cached_method <NEW_LINE> def highest_weight_dict(self): <NEW_LINE> <INDENT> return dict( (Partition([2*i for i in x.lift().to_tableau().shape()]),x) for x in self.module_generators ) <NEW_LINE> <DEDENT> @cached_method <NEW_LINE> def ambient_highest_weight_dict(self): <NEW_LINE> <INDENT> return dict( (x.lift().to_tableau().shape(),x) for x in self.ambient_crystal().module_generators ) <NEW_LINE> <DEDENT> def similarity_factor(self): <NEW_LINE> <INDENT> C = self.cartan_type().classical() <NEW_LINE> p = dict( (i,2) for i in C.index_set() ) <NEW_LINE> if C.type() == 'B': <NEW_LINE> <INDENT> p[C.rank()] = 1 <NEW_LINE> <DEDENT> return p <NEW_LINE> <DEDENT> @cached_method <NEW_LINE> def to_ambient_crystal(self): <NEW_LINE> <INDENT> keys = self.highest_weight_dict().keys() <NEW_LINE> pdict = dict( (self.highest_weight_dict()[key], self.ambient_highest_weight_dict()[key]) for key in keys ) <NEW_LINE> classical = self.cartan_type().classical() <NEW_LINE> return self.crystal_morphism( pdict, codomain=self.ambient_crystal(), index_set=classical.index_set(), scaling_factors=self.similarity_factor(), cartan_type=classical, check=False ) <NEW_LINE> <DEDENT> @cached_method <NEW_LINE> def from_ambient_crystal(self): <NEW_LINE> <INDENT> keys = self.highest_weight_dict().keys() <NEW_LINE> pdict_inv = dict( (self.ambient_highest_weight_dict()[key], self.highest_weight_dict()[key]) for key in keys ) <NEW_LINE> return AmbientRetractMap( self, self.ambient_crystal(), pdict_inv, index_set=self.cartan_type().classical().index_set(), similarity_factor_domain=self.similarity_factor() )
Class of Kirillov-Reshetikhin crystals `B^{r,s}` of type `A_{2n}^{(2)}` for `r\le n` and type `D_{n+1}^{(2)}` for `r<n`. EXAMPLES:: sage: K = crystals.KirillovReshetikhin(['A',4,2], 1,1) sage: K Kirillov-Reshetikhin crystal of type ['BC', 2, 2] with (r,s)=(1,1) sage: b = K(rows=[]) sage: b.f(0) [[1]] sage: b.e(0) [[-1]]
62598fd560cbc95b06364824
class VirtualNetworkGatewayListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'next_link': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': '[VirtualNetworkGateway]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(VirtualNetworkGatewayListResult, self).__init__(**kwargs) <NEW_LINE> self.value = kwargs.get('value', None) <NEW_LINE> self.next_link = None
Response for the ListVirtualNetworkGateways API service call. Variables are only populated by the server, and will be ignored when sending a request. :param value: Gets a list of VirtualNetworkGateway resources that exists in a resource group. :type value: list[~azure.mgmt.network.v2018_06_01.models.VirtualNetworkGateway] :ivar next_link: The URL to get the next set of results. :vartype next_link: str
62598fd5ab23a570cc2d4fe1
class Dollar(Money): <NEW_LINE> <INDENT> def times(self, multiplier: int): <NEW_LINE> <INDENT> return Dollar(self._amount * multiplier)
dollar class
62598fd53d592f4c4edbb39d
class ConcatenateTests(TestCase): <NEW_LINE> <INDENT> def test_action(self): <NEW_LINE> <INDENT> action, _ = actions.concatenate([u'http://example.com/input1', u'http://example.com/input2']) <NEW_LINE> self.assertThat( action, Equals({u'action': u'concatenate', u'parameters': { u'inputs': [u'http://example.com/input1', u'http://example.com/input2']}})) <NEW_LINE> <DEDENT> def test_parser(self): <NEW_LINE> <INDENT> _, parser = actions.concatenate([u'http://example.com/input1', u'http://example.com/input2']) <NEW_LINE> result = {u'links': {u'result': [u'http://example.com/output1']}} <NEW_LINE> self.assertThat( parser(result), Equals(u'http://example.com/output1'))
Tests for `txdocumint.actions.concatenate`.
62598fd59f28863672818af1
class OpenEnergyPlatformManagementServiceAPIsConfiguration(Configuration): <NEW_LINE> <INDENT> def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any ) -> None: <NEW_LINE> <INDENT> super(OpenEnergyPlatformManagementServiceAPIsConfiguration, self).__init__(**kwargs) <NEW_LINE> if credential is None: <NEW_LINE> <INDENT> raise ValueError("Parameter 'credential' must not be None.") <NEW_LINE> <DEDENT> if subscription_id is None: <NEW_LINE> <INDENT> raise ValueError("Parameter 'subscription_id' must not be None.") <NEW_LINE> <DEDENT> self.credential = credential <NEW_LINE> self.subscription_id = subscription_id <NEW_LINE> self.api_version = "2021-06-01-preview" <NEW_LINE> self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) <NEW_LINE> kwargs.setdefault('sdk_moniker', 'mgmt-oep/{}'.format(VERSION)) <NEW_LINE> self._configure(**kwargs) <NEW_LINE> <DEDENT> def _configure( self, **kwargs: Any ) -> None: <NEW_LINE> <INDENT> self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) <NEW_LINE> self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) <NEW_LINE> self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) <NEW_LINE> self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) <NEW_LINE> self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) <NEW_LINE> self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) <NEW_LINE> self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) <NEW_LINE> self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) <NEW_LINE> self.authentication_policy = kwargs.get('authentication_policy') <NEW_LINE> if self.credential and not self.authentication_policy: <NEW_LINE> <INDENT> self.authentication_policy = AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)
Configuration for OpenEnergyPlatformManagementServiceAPIs. Note that all parameters used to create this instance are saved as instance attributes. :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The ID of the target subscription. :type subscription_id: str
62598fd50fa83653e46f53d0
class XMLRPCProxyServer(BaseImplServer): <NEW_LINE> <INDENT> def __init__(self, host, port, use_builtin_types=True): <NEW_LINE> <INDENT> self.host = host <NEW_LINE> self.port = port
not a real working server, but a stub for a proxy server connection
62598fd5fbf16365ca7945a6
class TimerQT(TimerBase): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> TimerBase.__init__(self, *args, **kwargs) <NEW_LINE> self._timer = QtCore.QTimer() <NEW_LINE> self._timer.timeout.connect(self._on_timer) <NEW_LINE> self._timer_set_interval() <NEW_LINE> <DEDENT> def _timer_set_single_shot(self): <NEW_LINE> <INDENT> self._timer.setSingleShot(self._single) <NEW_LINE> <DEDENT> def _timer_set_interval(self): <NEW_LINE> <INDENT> self._timer.setInterval(self._interval) <NEW_LINE> <DEDENT> def _timer_start(self): <NEW_LINE> <INDENT> self._timer.start() <NEW_LINE> <DEDENT> def _timer_stop(self): <NEW_LINE> <INDENT> self._timer.stop()
Subclass of :class:`backend_bases.TimerBase` that uses Qt4 timer events. Attributes: * interval: The time between timer events in milliseconds. Default is 1000 ms. * single_shot: Boolean flag indicating whether this timer should operate as single shot (run once and then stop). Defaults to False. * callbacks: Stores list of (func, args) tuples that will be called upon timer events. This list can be manipulated directly, or the functions add_callback and remove_callback can be used.
62598fd5283ffb24f3cf3d69
class MediaContainer(PlexObject): <NEW_LINE> <INDENT> TAG = 'MediaContainer' <NEW_LINE> def _loadData(self, data): <NEW_LINE> <INDENT> self._data = data <NEW_LINE> self.allowSync = utils.cast(int, data.attrib.get('allowSync')) <NEW_LINE> self.augmentationKey = data.attrib.get('augmentationKey') <NEW_LINE> self.identifier = data.attrib.get('identifier') <NEW_LINE> self.librarySectionID = utils.cast(int, data.attrib.get('librarySectionID')) <NEW_LINE> self.librarySectionTitle = data.attrib.get('librarySectionTitle') <NEW_LINE> self.librarySectionUUID = data.attrib.get('librarySectionUUID') <NEW_LINE> self.mediaTagPrefix = data.attrib.get('mediaTagPrefix') <NEW_LINE> self.mediaTagVersion = data.attrib.get('mediaTagVersion') <NEW_LINE> self.size = utils.cast(int, data.attrib.get('size'))
Represents a single MediaContainer. Attributes: TAG (str): 'MediaContainer' allowSync (int): Sync/Download is allowed/disallowed for feature. augmentationKey (str): API URL (/library/metadata/augmentations/<augmentationKey>). identifier (str): "com.plexapp.plugins.library" librarySectionID (int): :class:`~plexapi.library.LibrarySection` ID. librarySectionTitle (str): :class:`~plexapi.library.LibrarySection` title. librarySectionUUID (str): :class:`~plexapi.library.LibrarySection` UUID. mediaTagPrefix (str): "/system/bundle/media/flags/" mediaTagVersion (int): Unknown size (int): The number of items in the hub.
62598fd560cbc95b06364826
class DescribeServiceTemplateGroupsRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Filters = None <NEW_LINE> self.Offset = None <NEW_LINE> self.Limit = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> if params.get("Filters") is not None: <NEW_LINE> <INDENT> self.Filters = [] <NEW_LINE> for item in params.get("Filters"): <NEW_LINE> <INDENT> obj = Filter() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.Filters.append(obj) <NEW_LINE> <DEDENT> <DEDENT> self.Offset = params.get("Offset") <NEW_LINE> self.Limit = params.get("Limit") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set))
DescribeServiceTemplateGroups请求参数结构体
62598fd5bf627c535bcb1998
class TestWebServiceObfuscation(TestCaseWithFactory): <NEW_LINE> <INDENT> layer = DatabaseFunctionalLayer <NEW_LINE> email_address = "joe@example.com" <NEW_LINE> email_address_obfuscated = "<email address hidden>" <NEW_LINE> email_address_obfuscated_escaped = "&lt;email address hidden&gt;" <NEW_LINE> bug_title = "Title with address %s in it" <NEW_LINE> bug_description = "Description with address %s in it" <NEW_LINE> def _makeBug(self): <NEW_LINE> <INDENT> bug = self.factory.makeBug( title=self.bug_title % self.email_address, description=self.bug_description % self.email_address) <NEW_LINE> transaction.commit() <NEW_LINE> return bug <NEW_LINE> <DEDENT> def test_email_address_obfuscated(self): <NEW_LINE> <INDENT> bug = self._makeBug() <NEW_LINE> logout() <NEW_LINE> webservice = LaunchpadWebServiceCaller() <NEW_LINE> result = webservice(ws_url(bug)).jsonBody() <NEW_LINE> self.assertEqual( self.bug_title % self.email_address_obfuscated, result['title']) <NEW_LINE> self.assertEqual( self.bug_description % self.email_address_obfuscated, result['description']) <NEW_LINE> <DEDENT> def test_email_address_not_obfuscated(self): <NEW_LINE> <INDENT> bug = self._makeBug() <NEW_LINE> user = self.factory.makePerson() <NEW_LINE> webservice = webservice_for_person(user) <NEW_LINE> result = webservice(ws_url(bug)).jsonBody() <NEW_LINE> self.assertEqual(self.bug_title % self.email_address, result['title']) <NEW_LINE> self.assertEqual( self.bug_description % self.email_address, result['description']) <NEW_LINE> <DEDENT> def test_xhtml_email_address_not_obfuscated(self): <NEW_LINE> <INDENT> bug = self._makeBug() <NEW_LINE> user = self.factory.makePerson() <NEW_LINE> webservice = webservice_for_person(user) <NEW_LINE> result = webservice( ws_url(bug), headers={'Accept': 'application/xhtml+xml'}) <NEW_LINE> self.assertIn(self.email_address, result.body) <NEW_LINE> self.assertNotIn( self.email_address_obfuscated_escaped, result.body) <NEW_LINE> <DEDENT> def test_xhtml_email_address_obfuscated(self): <NEW_LINE> <INDENT> bug = self._makeBug() <NEW_LINE> logout() <NEW_LINE> webservice = LaunchpadWebServiceCaller() <NEW_LINE> result = webservice( ws_url(bug), headers={'Accept': 'application/xhtml+xml'}) <NEW_LINE> self.assertNotIn(self.email_address, result.body) <NEW_LINE> self.assertIn(self.email_address_obfuscated_escaped, result.body) <NEW_LINE> <DEDENT> def test_etags_differ_for_anon_and_non_anon_represetations(self): <NEW_LINE> <INDENT> bug = self._makeBug() <NEW_LINE> user = self.factory.makePerson() <NEW_LINE> webservice = webservice_for_person(user) <NEW_LINE> etag_logged_in = webservice(ws_url(bug)).getheader('etag') <NEW_LINE> logout() <NEW_LINE> webservice = LaunchpadWebServiceCaller() <NEW_LINE> etag_logged_out = webservice(ws_url(bug)).getheader('etag') <NEW_LINE> self.assertNotEqual(etag_logged_in, etag_logged_out)
Integration test for obfuscation marshaller. Not using WebServiceTestCase because that assumes too much about users
62598fd59f28863672818af2
class GUIGrid(): <NEW_LINE> <INDENT> def button_box(self, message: str, choices: list) -> str: <NEW_LINE> <INDENT> reply = easygui.buttonbox(message, choices=choices) <NEW_LINE> return reply <NEW_LINE> <DEDENT> def integer_box(self, message: str, title="", min: int = 0, max: int = sys.maxsize, image=None) -> str: <NEW_LINE> <INDENT> reply = easygui.integerbox(message, title=title, lowerbound=min, upperbound=max, image=image) <NEW_LINE> return reply <NEW_LINE> <DEDENT> def string_box(self, message: str, default="", title="", strip=False, image=None) -> str: <NEW_LINE> <INDENT> reply = easygui.enterbox(message, title=title, default=default, strip=strip, image=image) <NEW_LINE> return reply <NEW_LINE> <DEDENT> def message_box(self, message): <NEW_LINE> <INDENT> easygui.msgbox(message)
Das GUI-Grid erlaubt es Pop-Up Fenster mit GUI Elementen einzublenden.
62598fd550812a4eaa620e58
class HmSearch(object): <NEW_LINE> <INDENT> def __init__(self, source=None, database=None): <NEW_LINE> <INDENT> if source is not None: <NEW_LINE> <INDENT> self.source = source <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.source = os.path.join(os.getcwd(), 'hmsearch') <NEW_LINE> <DEDENT> self.database = database <NEW_LINE> <DEDENT> def _run_cmd(self, script, *params): <NEW_LINE> <INDENT> if not os.path.isfile(os.path.join(self.source, script)): <NEW_LINE> <INDENT> raise Exception('Cannot find {} in {}'.format(script, self.source)) <NEW_LINE> <DEDENT> cmd = [os.path.join(self.source, script)] + [str(p) for p in params] <NEW_LINE> try: <NEW_LINE> <INDENT> response = subprocess.check_output(cmd, stderr=subprocess.STDOUT) <NEW_LINE> <DEDENT> except subprocess.CalledProcessError as e: <NEW_LINE> <INDENT> raise Exception(e.output) <NEW_LINE> <DEDENT> if response: <NEW_LINE> <INDENT> return response <NEW_LINE> <DEDENT> <DEDENT> def create(self, database, hash_size, max_error, max_hashes): <NEW_LINE> <INDENT> self._run_cmd('hm_initdb', database, hash_size, max_error, max_hashes) <NEW_LINE> if self.database is None: <NEW_LINE> <INDENT> self.database = database <NEW_LINE> <DEDENT> <DEDENT> def lookup(self, hash_str): <NEW_LINE> <INDENT> results = [] <NEW_LINE> response = self._run_cmd('hm_lookup', self.database, hash_str) <NEW_LINE> if response: <NEW_LINE> <INDENT> lines = response.split('\n') <NEW_LINE> for i in lines: <NEW_LINE> <INDENT> if not i: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> key, distance = i.split(' ') <NEW_LINE> results.append((key, distance)) <NEW_LINE> <DEDENT> <DEDENT> return results <NEW_LINE> <DEDENT> def insert(self, hashes): <NEW_LINE> <INDENT> hashes = ' '.join(hashes) <NEW_LINE> p = subprocess.Popen([os.path.join(self.source, 'hm_insert'), self.database], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT) <NEW_LINE> p.communicate(hashes)[0]
Use: Initialise by specifying location of `hmsearch` directory (default: current): >>> db = hmsearch.HmSearch(source='/path/to/hmsearch/') Either connect to an existing database: >>> db = hmsearch.HmSearch(source='/path/to/dir/', database='/path/to/db.kch') or create a new database: >>> db.create('hashes.kch', hash_size=128, max_error=10, max_hashes=1000000) Search for a hash: >>> result = db.lookup('f0d0d4c494f4fcccfffff0ff7f270002') >>> type(result) <type 'list'> Add a list of new hashes >>> hashes = ['y2dfd4c494f4fc5cfffff0f17f270002', 'f0d04vc494f4fcccffguff0ff7f270006'] >>> db.insert(hashes)
62598fd50fa83653e46f53d2
class MoveCost(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): <NEW_LINE> <INDENT> ZERO = "Zero" <NEW_LINE> LOW = "Low" <NEW_LINE> MEDIUM = "Medium" <NEW_LINE> HIGH = "High"
Specifies the move cost for the service.
62598fd5dc8b845886d53aa8
class ClientError(Exception): <NEW_LINE> <INDENT> pass
The client did something wrong
62598fd58a349b6b4368672c
class DeadDataFileTest(ImmutableDataFileTest): <NEW_LINE> <INDENT> file_class = DeadDataFile <NEW_LINE> def create_dead_file(self): <NEW_LINE> <INDENT> rw_file = DataFile(self.base_dir) <NEW_LINE> self.addCleanup(rw_file.close) <NEW_LINE> tstamp, value_pos, value_sz = rw_file.write(0, b'foo', b'bar') <NEW_LINE> immutable_file = rw_file.make_immutable() <NEW_LINE> immutable_file.get_hint_file().close() <NEW_LINE> data_file = immutable_file.make_zombie() <NEW_LINE> data_file.close() <NEW_LINE> return DeadDataFile(self.base_dir, os.path.basename(data_file.filename)) <NEW_LINE> <DEDENT> def test_delete(self): <NEW_LINE> <INDENT> dead_file = self.create_dead_file() <NEW_LINE> self.assertTrue(os.path.exists(dead_file.filename)) <NEW_LINE> self.assertTrue(os.path.exists(dead_file.hint_filename)) <NEW_LINE> dead_file.delete() <NEW_LINE> self.assertFalse(os.path.exists(dead_file.filename)) <NEW_LINE> self.assertFalse(os.path.exists(dead_file.hint_filename)) <NEW_LINE> <DEDENT> def test_write(self): <NEW_LINE> <INDENT> dead_file = self.create_dead_file() <NEW_LINE> self.assertRaises(NotImplementedError, dead_file.write, b'1') <NEW_LINE> <DEDENT> test_write_after_read_after_write = test_write <NEW_LINE> def test_read(self): <NEW_LINE> <INDENT> dead_file = self.create_dead_file() <NEW_LINE> self.assertRaises(NotImplementedError, dead_file.read) <NEW_LINE> <DEDENT> test_read_bad_crc = test_read <NEW_LINE> test_read_bad_header = test_read <NEW_LINE> def test__open(self): <NEW_LINE> <INDENT> dead_file = self.create_dead_file() <NEW_LINE> self.assertRaises(NotImplementedError, dead_file._open) <NEW_LINE> <DEDENT> def test_close(self): <NEW_LINE> <INDENT> dead_file = self.create_dead_file() <NEW_LINE> self.assertRaises(NotImplementedError, dead_file.close) <NEW_LINE> <DEDENT> def test_make_immutable(self): <NEW_LINE> <INDENT> dead_file = self.create_dead_file() <NEW_LINE> self.assertRaises(NotImplementedError, dead_file.make_immutable) <NEW_LINE> <DEDENT> def test_make_zombie(self): <NEW_LINE> <INDENT> dead_file = self.create_dead_file() <NEW_LINE> self.assertRaises(NotImplementedError, dead_file.make_zombie) <NEW_LINE> <DEDENT> test_make_zombie_with_hint = test_make_zombie <NEW_LINE> def test__getitem__(self): <NEW_LINE> <INDENT> dead_file = self.create_dead_file() <NEW_LINE> self.assertRaises(NotImplementedError, dead_file.__getitem__) <NEW_LINE> <DEDENT> test__getitem__no_slice = test__getitem__ <NEW_LINE> def test_iter_entries(self): <NEW_LINE> <INDENT> dead_file = self.create_dead_file() <NEW_LINE> self.assertRaises(NotImplementedError, dead_file.iter_entries) <NEW_LINE> <DEDENT> def test_exists(self): <NEW_LINE> <INDENT> dead_file = self.create_dead_file() <NEW_LINE> self.assertTrue(dead_file.exists()) <NEW_LINE> <DEDENT> def test_size(self): <NEW_LINE> <INDENT> dead_file = self.create_dead_file() <NEW_LINE> self.assertEqual(len(b'bar') + len(b'foo') + header_size + crc32_size, dead_file.size)
Tests for DeadDataFile.
62598fd560cbc95b06364828
class LayoutContainer(object): <NEW_LINE> <INDENT> def canSetDefaultPage(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def aggregateSearchableText(self): <NEW_LINE> <INDENT> data = [super(LayoutContainer, self).SearchableText(),] <NEW_LINE> for child in self.contentValues(): <NEW_LINE> <INDENT> data.append(child.SearchableText()) <NEW_LINE> <DEDENT> data = ' '.join(data) <NEW_LINE> return data
Container that provides aggregate search and display functionality.
62598fd597e22403b383b3f5
@dataclass <NEW_LINE> class IdentType: <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> name = "identType" <NEW_LINE> <DEDENT> value: Optional[str] = field( default=None, metadata={ "required": True, } ) <NEW_LINE> system: Optional[str] = field( default=None, metadata={ "type": "Attribute", "required": True, } )
Type for a long-term globally meaningful identifier, consisting of a string (ID) and a URI of the naming scheme within which the name is meaningful.
62598fd5656771135c489b5e
class TestSubComputeApi(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.api = SubComputeApi() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_sub_compute_all_by_child_child_compute_guid_get(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_sub_compute_all_by_parent_parent_compute_guid_get(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_sub_compute_all_index_get(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_sub_compute_get_get(self): <NEW_LINE> <INDENT> pass
SubComputeApi unit test stubs
62598fd5dc8b845886d53aaa