code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class ObjectGroupMapping(ImportObjectsMixin, ImportMapping): <NEW_LINE> <INDENT> MAP_TYPE = "ObjectGroup" <NEW_LINE> def _import_row(self, source_data, state, mapped_data): <NEW_LINE> <INDENT> object_class_name = state[ImportKey.OBJECT_CLASS_NAME] <NEW_LINE> group_name = state.get(ImportKey.OBJECT_NAME) <NEW_LINE> if group_name is None: <NEW_LINE> <INDENT> raise KeyError(ImportKey.GROUP_NAME) <NEW_LINE> <DEDENT> member_name = str(source_data) <NEW_LINE> mapped_data.setdefault("object_groups", list()).append((object_class_name, group_name, member_name)) <NEW_LINE> if self.import_objects: <NEW_LINE> <INDENT> objects = [(object_class_name, group_name), (object_class_name, member_name)] <NEW_LINE> mapped_data.setdefault("objects", list()).extend(objects) <NEW_LINE> <DEDENT> raise KeyFix(ImportKey.MEMBER_NAME)
Maps object groups. Cannot be used as the topmost mapping; must have :class:`ObjectClassMapping` and :class:`ObjectMapping` as parents.
62598fd6099cdd3c6367566b
class I2cScan(Test): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__( name="scan", summary="I2C Scanner", descr="This plugin scans the I2C bus and displays all the " "addresses connected to the bus.", author="Arun Magesh", email="arun.m@payatu.com", ref=["https://github.com/eblot/pyftdi"], category=TCategory(TCategory.I2C, TCategory.HW, TCategory.ANALYSIS), target=TTarget(TTarget.GENERIC, TTarget.GENERIC, TTarget.GENERIC), ) <NEW_LINE> self.argparser.add_argument( "-u", "--url", default=DEFAULT_FTDI_URL, help="URL of the connected FTDI device. Default is {}. " "For more details on the URL scheme check " "https://eblot.github.io/pyftdi/urlscheme.html".format(DEFAULT_FTDI_URL), ) <NEW_LINE> <DEDENT> def execute(self): <NEW_LINE> <INDENT> TLog.generic("Scanning for I2C devices...") <NEW_LINE> passed = 0 <NEW_LINE> fail = 0 <NEW_LINE> try: <NEW_LINE> <INDENT> i2c = I2cController() <NEW_LINE> i2c.set_retry_count(1) <NEW_LINE> i2c.configure(self.args.url) <NEW_LINE> for address in range(i2c.HIGHEST_I2C_ADDRESS + 1): <NEW_LINE> <INDENT> port = i2c.get_port(address) <NEW_LINE> try: <NEW_LINE> <INDENT> port.read(0) <NEW_LINE> self.output_handler(address_found="{}".format(hex(address))) <NEW_LINE> passed = passed + 1 <NEW_LINE> <DEDENT> except I2cNackError: <NEW_LINE> <INDENT> fail = fail + 1 <NEW_LINE> <DEDENT> <DEDENT> self.output_handler(total_found=passed, total_not_found=fail) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.result.exception() <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> i2c.terminate()
Scan the I2C bus for connected units. Output Format: [ {"address_found"="0x51"}, # Address for an I2C device on PCB # ... May be more than one address found { "total_found":6, "total_not_found": 7 } ]
62598fd6a219f33f346c6d20
class BFSWithQueue: <NEW_LINE> <INDENT> def __init__(self, graph): <NEW_LINE> <INDENT> self.graph = graph <NEW_LINE> self.color = dict(((node, "WHITE") for node in self.graph.iternodes())) <NEW_LINE> self.distance = dict(((node, float("inf")) for node in self.graph.iternodes())) <NEW_LINE> self.parent = dict(((node, None) for node in self.graph.iternodes())) <NEW_LINE> self.dag = self.graph.__class__(self.graph.v(), directed=True) <NEW_LINE> for node in self.graph.iternodes(): <NEW_LINE> <INDENT> self.dag.add_node(node) <NEW_LINE> <DEDENT> <DEDENT> def run(self, source=None, pre_action=None, post_action=None): <NEW_LINE> <INDENT> if source is not None: <NEW_LINE> <INDENT> self._visit(source, pre_action, post_action) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for node in self.graph.iternodes(): <NEW_LINE> <INDENT> if self.color[node] == "WHITE": <NEW_LINE> <INDENT> self._visit(node, pre_action, post_action) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def _visit(self, node, pre_action=None, post_action=None): <NEW_LINE> <INDENT> self.color[node] = "GREY" <NEW_LINE> self.distance[node] = 0 <NEW_LINE> self.parent[node] = None <NEW_LINE> Q = Queue() <NEW_LINE> Q.put(node) <NEW_LINE> if pre_action: <NEW_LINE> <INDENT> pre_action(node) <NEW_LINE> <DEDENT> while not Q.empty(): <NEW_LINE> <INDENT> source = Q.get() <NEW_LINE> for edge in self.graph.iteroutedges(source): <NEW_LINE> <INDENT> if self.color[edge.target] == "WHITE": <NEW_LINE> <INDENT> self.color[edge.target] = "GREY" <NEW_LINE> self.distance[edge.target] = self.distance[source] + 1 <NEW_LINE> self.parent[edge.target] = source <NEW_LINE> self.dag.add_edge(edge) <NEW_LINE> Q.put(edge.target) <NEW_LINE> if pre_action: <NEW_LINE> <INDENT> pre_action(edge.target) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.color[source] = "BLACK" <NEW_LINE> if post_action: <NEW_LINE> <INDENT> post_action(source) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def path(self, source, target): <NEW_LINE> <INDENT> if source == target: <NEW_LINE> <INDENT> return [source] <NEW_LINE> <DEDENT> elif self.parent[target] is None: <NEW_LINE> <INDENT> raise ValueError("no path to target") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.path(source, self.parent[target]) + [target]
Breadth-First Search. Attributes ---------- graph : input graph color : dict with nodes, private distance : dict with nodes (distances to source node) parent : dict (BFS tree) dag : graph (BFS tree) Examples -------- >>> from graphtheory.structures.edges import Edge >>> from graphtheory.structures.graphs import Graph >>> from graphtheory.traversing.bfs import BFSWithQueue >>> G = Graph(n=10, False) # an exemplary undirected graph # Add nodes and edges here. >>> order = list() >>> algorithm = BFSWithQueue(G) >>> algorithm.run(source=0, pre_action=lambda node: order.append(node)) >>> order # visited nodes >>> algorithm.distance[target] # distance from source to target >>> algorithm.parent # BFS tree as a dict >>> algorithm.dag # BFS tree as a directed graph >>> algorithm.path(source, target) Notes ----- Based on: Cormen, T. H., Leiserson, C. E., Rivest, R. L., and Stein, C., 2009, Introduction to Algorithms, third edition, The MIT Press, Cambridge, London. https://en.wikipedia.org/wiki/Breadth-first_search
62598fd626238365f5fad07e
class EconomicIndicator(Base): <NEW_LINE> <INDENT> __tablename__ = 'EconomicIndicators' <NEW_LINE> Date = Column(Date, ForeignKey('Quotes.Date'),primary_key=True) <NEW_LINE> bank_prime_loan_rate = Column(Float) <NEW_LINE> primary_credit_rate = Column(Float) <NEW_LINE> consumer_price_index = Column(Float) <NEW_LINE> real_gdp = Column(Float) <NEW_LINE> civillian_unemployment_rate = Column(Float) <NEW_LINE> m2_money_stock = Column(Float) <NEW_LINE> dow_jones_industrial = Column(Float) <NEW_LINE> dow_jones_composite = Column(Float) <NEW_LINE> dow_jones_transportation = Column(Float) <NEW_LINE> dow_jones_utility = Column(Float) <NEW_LINE> sp_500 = Column(Float) <NEW_LINE> sp_500_volatility = Column(Float) <NEW_LINE> libor_overnight = Column(Float) <NEW_LINE> libor_1wk = Column(Float) <NEW_LINE> libor_1mo = Column(Float) <NEW_LINE> libor_3mo = Column(Float) <NEW_LINE> libor_6mo = Column(Float) <NEW_LINE> libor_12mo = Column(Float) <NEW_LINE> def __init__(self, Date): <NEW_LINE> <INDENT> self.Date = Date <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<Economic Indicators on %s>" % self.Date
Economic Indicators Table Model
62598fd650812a4eaa620e70
class ExtensionsV1beta1RunAsGroupStrategyOptions(object): <NEW_LINE> <INDENT> openapi_types = { 'ranges': 'list[ExtensionsV1beta1IDRange]', 'rule': 'str' } <NEW_LINE> attribute_map = { 'ranges': 'ranges', 'rule': 'rule' } <NEW_LINE> def __init__(self, ranges=None, rule=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._ranges = None <NEW_LINE> self._rule = None <NEW_LINE> self.discriminator = None <NEW_LINE> if ranges is not None: <NEW_LINE> <INDENT> self.ranges = ranges <NEW_LINE> <DEDENT> self.rule = rule <NEW_LINE> <DEDENT> @property <NEW_LINE> def ranges(self): <NEW_LINE> <INDENT> return self._ranges <NEW_LINE> <DEDENT> @ranges.setter <NEW_LINE> def ranges(self, ranges): <NEW_LINE> <INDENT> self._ranges = ranges <NEW_LINE> <DEDENT> @property <NEW_LINE> def rule(self): <NEW_LINE> <INDENT> return self._rule <NEW_LINE> <DEDENT> @rule.setter <NEW_LINE> def rule(self, rule): <NEW_LINE> <INDENT> if self.local_vars_configuration.client_side_validation and rule is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `rule`, must not be `None`") <NEW_LINE> <DEDENT> self._rule = rule <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.openapi_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 pprint.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> if not isinstance(other, ExtensionsV1beta1RunAsGroupStrategyOptions): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ExtensionsV1beta1RunAsGroupStrategyOptions): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict()
NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually.
62598fd68a349b6b4368675b
class Connection: <NEW_LINE> <INDENT> def __init__(self, ssh_input=None): <NEW_LINE> <INDENT> self._sshHost = None <NEW_LINE> self._dataFile = None <NEW_LINE> self._pathToDir = None <NEW_LINE> self._pathToTool = None <NEW_LINE> self._pathToData = None <NEW_LINE> self._sshInput = ssh_input <NEW_LINE> self._errorObject = None <NEW_LINE> self.reload_config() <NEW_LINE> <DEDENT> def get_error_object(self): <NEW_LINE> <INDENT> return self._errorObject <NEW_LINE> <DEDENT> def reload_config(self): <NEW_LINE> <INDENT> config = Config() <NEW_LINE> self._sshHost = config.get("SSH", "host") <NEW_LINE> self._dataFile = config.get("Data", "file") <NEW_LINE> self._pathToDir = config.get("Data", "path_to_dir") <NEW_LINE> self._pathToTool = config.get("Data", "path_to_tool") <NEW_LINE> self._pathToData = config.get("Data", "path_to_data") <NEW_LINE> <DEDENT> def send_print_data(self, print_amounts, printer): <NEW_LINE> <INDENT> data = { "amounts": print_amounts, "printer": printer } <NEW_LINE> json_data = json.dumps(data, separators=(',',':')) <NEW_LINE> return self._send_to_server("print", "'" + json_data + "'") <NEW_LINE> <DEDENT> def synchronize_data(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> process = pexpect.spawn( "rsync", ["-vt", self._sshHost + ":" + self._pathToData, self._dataFile] ) <NEW_LINE> process.expect("oe@rzssh1.informatik.uni-hamburg.de's password:") <NEW_LINE> time.sleep(0.1) <NEW_LINE> process.sendline(self._sshInput.readline()) <NEW_LINE> time.sleep(2) <NEW_LINE> process.expect(pexpect.EOF) <NEW_LINE> return True <NEW_LINE> <DEDENT> except CalledProcessError as cpe: <NEW_LINE> <INDENT> self._errorObject = cpe <NEW_LINE> return False <NEW_LINE> <DEDENT> <DEDENT> def _send_to_server(self, command, data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> process = pexpect.spawn( "ssh", [self._sshHost, "cd " + self._pathToDir + "; ./" + self._pathToTool, command, data] ) <NEW_LINE> process.expect("oe@rzssh1.informatik.uni-hamburg.de's password:") <NEW_LINE> time.sleep(0.1) <NEW_LINE> process.sendline(self._sshInput.readline()) <NEW_LINE> time.sleep(2) <NEW_LINE> process.expect(pexpect.EOF) <NEW_LINE> return True <NEW_LINE> <DEDENT> except CalledProcessError as cpe: <NEW_LINE> <INDENT> self._errorObject = cpe <NEW_LINE> return False
Manages the connection with the server.
62598fd6099cdd3c6367566c
class PasswordResetView(GenericAPIView): <NEW_LINE> <INDENT> serializer_class = PasswordResetSerializer <NEW_LINE> permission_classes = (AllowAny,) <NEW_LINE> def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> serializer = self.get_serializer(data=request.data) <NEW_LINE> if not serializer.is_valid(): <NEW_LINE> <INDENT> return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> serializer.save() <NEW_LINE> msg = _("Instructions on how to reset the password have been sent to '{email}'.") <NEW_LINE> return Response( {'success': msg.format(**serializer.data)}, status=status.HTTP_200_OK )
Calls Django Auth PasswordResetForm save method. Accepts the following POST parameters: email Returns the success/fail message.
62598fd6ab23a570cc2d4ffb
class PrivateIngredientsApiTests(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.client = APIClient() <NEW_LINE> self.user = get_user_model().objects.create_user( 'test@testmail.com', 'password123' ) <NEW_LINE> self.client.force_authenticate(self.user) <NEW_LINE> <DEDENT> def test_retrieve_ingredient_list(self): <NEW_LINE> <INDENT> Ingredient.objects.create(user=self.user, name='Onion') <NEW_LINE> Ingredient.objects.create(user=self.user, name='Garlic') <NEW_LINE> response = self.client.get(INGREDIENTS_URL) <NEW_LINE> ingredients = Ingredient.objects.all().order_by('-name') <NEW_LINE> serializer = IngredientSerializer(ingredients, many=True) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_200_OK) <NEW_LINE> self.assertEqual(response.data, serializer.data) <NEW_LINE> <DEDENT> def test_ingredients_to_user(self): <NEW_LINE> <INDENT> user2 = get_user_model().objects.create_user( 'another@testmail.com', 'password123' ) <NEW_LINE> Ingredient.objects.create(user=user2, name='Salt') <NEW_LINE> ingredient = Ingredient.objects.create(user=self.user, name='Vinegar') <NEW_LINE> response = self.client.get(INGREDIENTS_URL) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_200_OK) <NEW_LINE> self.assertEqual(len(response.data), 1) <NEW_LINE> self.assertEqual(response.data[0]['name'], ingredient.name) <NEW_LINE> <DEDENT> def test_create_ingredient_successful(self): <NEW_LINE> <INDENT> payload = {'name': 'Cabbage'} <NEW_LINE> self.client.post(INGREDIENTS_URL, payload) <NEW_LINE> exists = Ingredient.objects.filter( user=self.user, name=payload['name'], ).exists() <NEW_LINE> self.assertTrue(exists) <NEW_LINE> <DEDENT> def test_create_ingredient_invalid(self): <NEW_LINE> <INDENT> payload = {'name': ''} <NEW_LINE> response = self.client.post(INGREDIENTS_URL, payload) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
Test the private ingredients api
62598fd63617ad0b5ee06663
class ComponentQuotaStatusOperations(object): <NEW_LINE> <INDENT> models = models <NEW_LINE> def __init__(self, client, config, serializer, deserializer): <NEW_LINE> <INDENT> self._client = client <NEW_LINE> self._serialize = serializer <NEW_LINE> self._deserialize = deserializer <NEW_LINE> self.api_version = "2015-05-01" <NEW_LINE> self.config = config <NEW_LINE> <DEDENT> def get( self, resource_group_name, resource_name, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{resourceName}/quotastatus' <NEW_LINE> path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceName': self._serialize.url("resource_name", resource_name, 'str') } <NEW_LINE> url = self._client.format_url(url, **path_format_arguments) <NEW_LINE> query_parameters = {} <NEW_LINE> query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') <NEW_LINE> header_parameters = {} <NEW_LINE> header_parameters['Content-Type'] = 'application/json; charset=utf-8' <NEW_LINE> if self.config.generate_client_request_id: <NEW_LINE> <INDENT> header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) <NEW_LINE> <DEDENT> if custom_headers: <NEW_LINE> <INDENT> header_parameters.update(custom_headers) <NEW_LINE> <DEDENT> if self.config.accept_language is not None: <NEW_LINE> <INDENT> header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') <NEW_LINE> <DEDENT> request = self._client.get(url, query_parameters) <NEW_LINE> response = self._client.send(request, header_parameters, stream=False, **operation_config) <NEW_LINE> if response.status_code not in [200]: <NEW_LINE> <INDENT> exp = CloudError(response) <NEW_LINE> exp.request_id = response.headers.get('x-ms-request-id') <NEW_LINE> raise exp <NEW_LINE> <DEDENT> deserialized = None <NEW_LINE> if response.status_code == 200: <NEW_LINE> <INDENT> deserialized = self._deserialize('ApplicationInsightsComponentQuotaStatus', response) <NEW_LINE> <DEDENT> if raw: <NEW_LINE> <INDENT> client_raw_response = ClientRawResponse(deserialized, response) <NEW_LINE> return client_raw_response <NEW_LINE> <DEDENT> return deserialized
ComponentQuotaStatusOperations operations. :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An objec model deserializer. :ivar api_version: Client Api Version. Constant value: "2015-05-01".
62598fd67cff6e4e811b5f49
class DirectoryListingResultsSchema(BaseSchema): <NEW_LINE> <INDENT> directories = fields.List( cls_or_instance=fields.Dict, required=True, description="A list of directories in the given path", example=[ { 'value': "home", 'label': "/home", }, { 'value': "tmp", 'label': "/tmp", }, ], validate=validate.Length(min=0), ) <NEW_LINE> files = fields.List( cls_or_instance=fields.Dict, required=True, description="A list of files in the given path", example=[ { 'value': "file1.txt", 'label': "/file1.txt", }, { 'value': "file2.txt", 'label': "/file2.txt", }, ], validate=validate.Length(min=0), )
Schema for directory listing results returned
62598fd6ec188e330fdf8db6
class CloudToDeviceMethod(Model): <NEW_LINE> <INDENT> _validation = { 'payload': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'method_name': {'key': 'methodName', 'type': 'str'}, 'payload': {'key': 'payload', 'type': 'object'}, 'response_timeout_in_seconds': {'key': 'responseTimeoutInSeconds', 'type': 'int'}, 'connect_timeout_in_seconds': {'key': 'connectTimeoutInSeconds', 'type': 'int'}, } <NEW_LINE> def __init__(self, method_name=None, response_timeout_in_seconds=None, connect_timeout_in_seconds=None): <NEW_LINE> <INDENT> super(CloudToDeviceMethod, self).__init__() <NEW_LINE> self.method_name = method_name <NEW_LINE> self.payload = None <NEW_LINE> self.response_timeout_in_seconds = response_timeout_in_seconds <NEW_LINE> self.connect_timeout_in_seconds = connect_timeout_in_seconds
Parameters to execute a direct method on the device. Variables are only populated by the server, and will be ignored when sending a request. :param method_name: Method to run :type method_name: str :ivar payload: Payload :vartype payload: object :param response_timeout_in_seconds: :type response_timeout_in_seconds: int :param connect_timeout_in_seconds: :type connect_timeout_in_seconds: int
62598fd7099cdd3c6367566f
class ProductIndex(dict): <NEW_LINE> <INDENT> def __init__(self, filepath): <NEW_LINE> <INDENT> for product in load_data(filepath): <NEW_LINE> <INDENT> if product['shop_id'] not in self: <NEW_LINE> <INDENT> self[product['shop_id']] = [] <NEW_LINE> <DEDENT> product['popularity'] = float(product['popularity']) <NEW_LINE> product['quantity'] = int(product['quantity']) <NEW_LINE> self[product['shop_id']].append(product) <NEW_LINE> <DEDENT> <DEDENT> def products_in_shops(self, shops): <NEW_LINE> <INDENT> for shop in shops: <NEW_LINE> <INDENT> for product in self[shop['id']]: <NEW_LINE> <INDENT> product['shop'] = shop <NEW_LINE> yield product
The index of products, this is a subclass of `dict` with extra convenience methods. Each `key` is the id of a shop. The data is loaded when this class is initialized.
62598fd7091ae3566870513d
class ValueIterationAgent(ValueEstimationAgent): <NEW_LINE> <INDENT> def __init__(self, mdp, discount = 0.9, iterations = 100): <NEW_LINE> <INDENT> self.mdp = mdp <NEW_LINE> self.discount = discount <NEW_LINE> self.iterations = iterations <NEW_LINE> self.values = util.Counter() <NEW_LINE> states = mdp.getStates(); <NEW_LINE> for state in states: <NEW_LINE> <INDENT> self.values[state] = 0; <NEW_LINE> <DEDENT> for i in range(0, iterations): <NEW_LINE> <INDENT> newValues = util.Counter(); <NEW_LINE> for state in states: <NEW_LINE> <INDENT> if not self.mdp.isTerminal(state): <NEW_LINE> <INDENT> maxActionAndQValue = self.ComputeMaxActionAndQValuesTuple(state); <NEW_LINE> newValues[state] = maxActionAndQValue[0]; <NEW_LINE> <DEDENT> <DEDENT> self.values = newValues; <NEW_LINE> <DEDENT> return; <NEW_LINE> <DEDENT> def getValue(self, state): <NEW_LINE> <INDENT> return self.values[state] <NEW_LINE> <DEDENT> def computeQValueFromValues(self, state, action): <NEW_LINE> <INDENT> total = 0; <NEW_LINE> if (action != None): <NEW_LINE> <INDENT> transitionStatesAndProbs =self.mdp.getTransitionStatesAndProbs(state, action); <NEW_LINE> for transitionStatesAndProb in transitionStatesAndProbs: <NEW_LINE> <INDENT> reward = self.mdp.getReward(state, action, transitionStatesAndProb[0]); <NEW_LINE> value = self.values[transitionStatesAndProb[0]]; <NEW_LINE> discountAndValue = self.discount * value; <NEW_LINE> partialTotal = transitionStatesAndProb[1] * (reward + discountAndValue); <NEW_LINE> total += partialTotal; <NEW_LINE> <DEDENT> <DEDENT> return total; <NEW_LINE> <DEDENT> def computeActionFromValues(self, state): <NEW_LINE> <INDENT> maxTuple = self.ComputeMaxActionAndQValuesTuple(state); <NEW_LINE> return maxTuple[1]; <NEW_LINE> <DEDENT> def getPolicy(self, state): <NEW_LINE> <INDENT> return self.computeActionFromValues(state) <NEW_LINE> <DEDENT> def getAction(self, state): <NEW_LINE> <INDENT> return self.computeActionFromValues(state) <NEW_LINE> <DEDENT> def getQValue(self, state, action): <NEW_LINE> <INDENT> return self.computeQValueFromValues(state, action) <NEW_LINE> <DEDENT> def ComputeMaxActionAndQValuesTuple(self, state): <NEW_LINE> <INDENT> actions = self.mdp.getPossibleActions(state); <NEW_LINE> qValues = []; <NEW_LINE> maxTuple = (float('-inf'), None); <NEW_LINE> for action in actions: <NEW_LINE> <INDENT> qValue = self.computeQValueFromValues(state, action); <NEW_LINE> localTuple = (qValue, action); <NEW_LINE> qValues.append(localTuple); <NEW_LINE> if (localTuple[1] == None or localTuple[0] > maxTuple[0]): <NEW_LINE> <INDENT> maxTuple = localTuple; <NEW_LINE> <DEDENT> <DEDENT> return maxTuple;
* Please read learningAgents.py before reading this.* A ValueIterationAgent takes a Markov decision process (see mdp.py) on initialization and runs value iteration for a given number of iterations using the supplied discount factor.
62598fd7fbf16365ca7945e0
class MTPostalCodeField(RegexField): <NEW_LINE> <INDENT> default_error_messages = { 'invalid': _('Enter a valid postal code in format AAA 0000.'), } <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super().__init__(r'^[A-Z]{3}\ \d{4}$', **kwargs)
A form field that validates its input as a Maltese postal code. Maltese postal code is a seven digits string, with first three being letters and the final four numbers.
62598fd7377c676e912f700b
class NTP(Page): <NEW_LINE> <INDENT> def __init__(self, display): <NEW_LINE> <INDENT> self._display = display <NEW_LINE> self._current_ticks = 0 <NEW_LINE> self._previous_ticks = 0 <NEW_LINE> self._previous_connected = False <NEW_LINE> self._sta_if = network.WLAN(network.STA_IF) <NEW_LINE> <DEDENT> def ready(self, current_ticks, now): <NEW_LINE> <INDENT> self._current_ticks = current_ticks <NEW_LINE> return True <NEW_LINE> <DEDENT> def show(self, now): <NEW_LINE> <INDENT> if not self._sta_if.isconnected(): <NEW_LINE> <INDENT> self._display.text('WS', 0) <NEW_LINE> return True <NEW_LINE> <DEDENT> elif not self._previous_connected or utime.ticks_diff(self._current_ticks, self._previous_ticks) > 300000: <NEW_LINE> <INDENT> self._previous_ticks = self._current_ticks <NEW_LINE> try: <NEW_LINE> <INDENT> ntptime.settime() <NEW_LINE> if not self._previous_connected: <NEW_LINE> <INDENT> self._display.text('WH', 0) <NEW_LINE> self._previous_connected = True <NEW_LINE> return True <NEW_LINE> <DEDENT> <DEDENT> except OSError: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False
Page to check the clock is connected to WiFi and get time from NTP
62598fd7dc8b845886d53ae0
class ElevationLimit(Constraint): <NEW_LINE> <INDENT> def __init__(self, limit): <NEW_LINE> <INDENT> self.limit = limit * u.deg <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'Elevation limit: {0:.2f}'.format(self.limit) <NEW_LINE> <DEDENT> def get(self, source_coord, frame): <NEW_LINE> <INDENT> altaz = source_coord.transform_to(frame) <NEW_LINE> observable = altaz.alt >= self.limit <NEW_LINE> return observable <NEW_LINE> <DEDENT> def get_limit(self): <NEW_LINE> <INDENT> return self.limit
Elevation limit: only sources above a specified elevation are observable.
62598fd7099cdd3c63675670
class TestSessionManagement(object): <NEW_LINE> <INDENT> @pytest.fixture(autouse=True) <NEW_LINE> def setup_teardown(self, auth_session): <NEW_LINE> <INDENT> self.admin_slot = hsm_config["test_slot"] <NEW_LINE> self.h_session = auth_session <NEW_LINE> <DEDENT> def test_c_get_session_info(self): <NEW_LINE> <INDENT> ret, sess_info = sess_mang.c_get_session_info(self.h_session) <NEW_LINE> assert ret == CKR_OK <NEW_LINE> assert isinstance(sess_info["state"], integer_types) <NEW_LINE> assert isinstance(sess_info["flags"], integer_types) <NEW_LINE> assert isinstance(sess_info["slotID"], integer_types) <NEW_LINE> assert isinstance(sess_info["usDeviceError"], integer_types) <NEW_LINE> <DEDENT> def test_ca_get_session_info(self): <NEW_LINE> <INDENT> ret, sess_info = ca_get_session_info(self.h_session) <NEW_LINE> assert ret == CKR_OK <NEW_LINE> assert isinstance(sess_info["aidHigh"], integer_types) <NEW_LINE> assert isinstance(sess_info["aidLow"], integer_types) <NEW_LINE> assert isinstance(sess_info["containerNumber"], integer_types) <NEW_LINE> assert isinstance(sess_info["authenticationLevel"], integer_types) <NEW_LINE> <DEDENT> def test_get_slot_dict(self): <NEW_LINE> <INDENT> ret, slot_dict = sess_mang.get_slot_dict() <NEW_LINE> logger.debug("Slots: %s", slot_dict) <NEW_LINE> assert ret == CKR_OK <NEW_LINE> assert isinstance(slot_dict, dict) <NEW_LINE> <DEDENT> def test_get_slot_dict_token_present(self): <NEW_LINE> <INDENT> slot_dict = sess_mang.get_slot_dict_ex(token_present=True) <NEW_LINE> for slot in slot_dict.keys(): <NEW_LINE> <INDENT> assert sess_mang.c_get_token_info(slot)[0] == CKR_OK <NEW_LINE> <DEDENT> <DEDENT> def test_get_slot_list(self): <NEW_LINE> <INDENT> slot_list = sess_mang.c_get_slot_list_ex(token_present=True) <NEW_LINE> for slot in slot_list: <NEW_LINE> <INDENT> assert isinstance(slot, integer_types) <NEW_LINE> assert sess_mang.c_get_token_info(slot)[0] == CKR_OK
Tests session management functions
62598fd7091ae3566870513f
class ProdConfig(Config): <NEW_LINE> <INDENT> ENV = 'prod' <NEW_LINE> DEBUG = False <NEW_LINE> SQLALCHEMY_DATABASE_URI = 'postgresql://postgres@localhost:5432/postgres' <NEW_LINE> DEBUG_TB_ENABLED = False <NEW_LINE> ASSETS_DEBUG = True
Production configuration.
62598fd7a219f33f346c6d2a
class played_track(Event): <NEW_LINE> <INDENT> pass
Evemt when x time of current track are played
62598fd7956e5f7376df590f
class MultipleResultsException(Exception): <NEW_LINE> <INDENT> pass
Raised when more than one item was found where at most one was expected.
62598fd73617ad0b5ee0666b
class Nbody(IntegrateBase): <NEW_LINE> <INDENT> def __init__(self, dt=0., time=0., iteration=0, restart=False, **kwargs): <NEW_LINE> <INDENT> super(Nbody, self).__init__(dt=dt, time=time, iteration=iteration, restart=restart) <NEW_LINE> <DEDENT> def set_gravity_tree(self, gravity_tree): <NEW_LINE> <INDENT> self.gravity_tree = gravity_tree <NEW_LINE> <DEDENT> def initialize(self): <NEW_LINE> <INDENT> if not self.particles or not self.domain_manager or not self.gravity_tree: <NEW_LINE> <INDENT> raise RuntimeError("ERROR: Not all setters defined in %s!" % self.__class__.__name__) <NEW_LINE> <DEDENT> if phd._in_parallel: <NEW_LINE> <INDENT> if not self.load_balance: <NEW_LINE> <INDENT> raise RuntimeError("ERROR: Load Balance setter not defined") <NEW_LINE> <DEDENT> self.load_balance.add_domain_info(self.domain_manager) <NEW_LINE> self.load_balance.initialize() <NEW_LINE> self.domain_manager.set_load_balance( self.load_balance) <NEW_LINE> <DEDENT> self.domain_manager.register_fields(self.particles) <NEW_LINE> self.gravity_tree.add_fields(self.particles) <NEW_LINE> self.gravity_tree.register_fields(self.particles) <NEW_LINE> self.gravity_tree.set_domain_manager(self.domain_manager) <NEW_LINE> self.gravity_tree.initialize() <NEW_LINE> dim = len(self.particles.carray_named_groups["position"]) <NEW_LINE> self.axis = "xyz"[:dim] <NEW_LINE> <DEDENT> def before_loop(self, simulation): <NEW_LINE> <INDENT> if phd._in_parallel: <NEW_LINE> <INDENT> self.load_balance.decomposition(self.particles) <NEW_LINE> <DEDENT> self.gravity_tree._build_tree(self.particles) <NEW_LINE> self.gravity_tree.walk(self.particles) <NEW_LINE> simulation.simulation_time_manager.output(simulation) <NEW_LINE> <DEDENT> def compute_time_step(self): <NEW_LINE> <INDENT> return self.dt <NEW_LINE> <DEDENT> def evolve_timestep(self): <NEW_LINE> <INDENT> for ax in self.axis: <NEW_LINE> <INDENT> self.particles["velocity-"+ax][:] += 0.5*self.dt*self.particles["acceleration-"+ax][:] <NEW_LINE> <DEDENT> for ax in self.axis: <NEW_LINE> <INDENT> self.particles["position-"+ax][:] += self.dt*self.particles["velocity-"+ax][:] <NEW_LINE> <DEDENT> if phd._in_parallel: <NEW_LINE> <INDENT> self.load_balance.decomposition(self.particles) <NEW_LINE> <DEDENT> self.gravity_tree._build_tree(self.particles) <NEW_LINE> self.gravity_tree.walk(self.particles) <NEW_LINE> for ax in self.axis: <NEW_LINE> <INDENT> self.particles["velocity-"+ax][:] += 0.5*self.dt*self.particles["acceleration-"+ax][:] <NEW_LINE> <DEDENT> self.iteration += 1; self.time += self.dt <NEW_LINE> <DEDENT> def after_loop(self, simulation): <NEW_LINE> <INDENT> pass
Class that solves nbody problem. Nbody solver for collisionless particles without hydrodynamics. Attributes ---------- domain_manager : DomainManager Class that handels all things related with the domain. dt : float Time step of the simulation. particles : CarrayContainer Class that holds all information pertaining to the particles in the simulation. time : float Current time of the simulation. iteration : int Current iteration of the simulation.
62598fd78a349b6b43686765
class StartRHSMTask(Task): <NEW_LINE> <INDENT> def __init__(self, verify_ssl=True): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._verify_ssl = verify_ssl <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return "Start RHSM DBus service" <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> if not os.path.exists("/etc/yum.repos.d"): <NEW_LINE> <INDENT> log.debug("subscription: creating /etc/yum.repos.d") <NEW_LINE> os.mkdir("/etc/yum.repos.d") <NEW_LINE> <DEDENT> rc = start_service(RHSM_SERVICE_NAME) <NEW_LINE> if rc: <NEW_LINE> <INDENT> log.warning( "subscription: RHSM systemd service failed to start with error code: %s", rc ) <NEW_LINE> return False <NEW_LINE> <DEDENT> rhsm_config_proxy = RHSM.get_proxy(RHSM_CONFIG, interface_name=RHSM_CONFIG) <NEW_LINE> log.debug("subscription: setting RHSM log level to DEBUG") <NEW_LINE> config_dict = {"logging.default_log_level": get_variant(Str, "DEBUG")} <NEW_LINE> if not self._verify_ssl: <NEW_LINE> <INDENT> log.debug("subscription: disabling RHSM SSL certificate validation") <NEW_LINE> config_dict["server.insecure"] = get_variant(Str, "1") <NEW_LINE> <DEDENT> rhsm_config_proxy.SetAll(config_dict, "") <NEW_LINE> log.debug("subscription: RHSM service start successfully.") <NEW_LINE> return True <NEW_LINE> <DEDENT> def is_service_available(self, timeout=RHSM_SERVICE_TIMEOUT): <NEW_LINE> <INDENT> if self.is_running: <NEW_LINE> <INDENT> thread = threadMgr.get(self._thread_name) <NEW_LINE> if thread: <NEW_LINE> <INDENT> log.debug("subscription: waiting for RHSM service to start for up to %f seconds.", timeout) <NEW_LINE> thread.join(timeout) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log.error("subscription: RHSM startup task is running but no thread found.") <NEW_LINE> return False <NEW_LINE> <DEDENT> <DEDENT> if self.is_running: <NEW_LINE> <INDENT> log.debug("subscription: RHSM service not available after waiting for %f seconds.", timeout) <NEW_LINE> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = self.get_result() <NEW_LINE> <DEDENT> except NoResultError: <NEW_LINE> <INDENT> log.error("subscription: got no result from StartRHSMTask") <NEW_LINE> result = False <NEW_LINE> <DEDENT> return result
Task for starting the RHSM DBus service.
62598fd7adb09d7d5dc0aa9e
class EmaneEventService(Wrapper): <NEW_LINE> <INDENT> def register(self, registrar): <NEW_LINE> <INDENT> registrar.register_argument('loglevel', 3, 'log level - [0,3]') <NEW_LINE> registrar.register_argument('daemonize', True, 'Run as daemon [True, False].') <NEW_LINE> registrar.register_infile_name('eventservice.xml') <NEW_LINE> registrar.register_outfile_name('emaneeventservice.log') <NEW_LINE> registrar.run_with_sudo() <NEW_LINE> <DEDENT> def run(self, ctx): <NEW_LINE> <INDENT> if not ctx.args.infile: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> hourminsec = ctx.args.starttime.split('T')[1] <NEW_LINE> daemonize_option = '--daemonize' if ctx.args.daemonize else '' <NEW_LINE> argstr = '%s ' '%s ' '--realtime ' '--loglevel %d ' '--logfile %s ' '--pidfile %s ' '--starttime %s' % (ctx.args.infile, daemonize_option, ctx.args.loglevel, ctx.args.outfile, ctx.args.default_pidfilename, hourminsec) <NEW_LINE> ctx.run('emaneeventservice', argstr, genpidfile=False) <NEW_LINE> <DEDENT> def postrun(self, ctx): <NEW_LINE> <INDENT> if not ctx.args.infile: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> time.sleep(1) <NEW_LINE> name = 'emaneeventservice' <NEW_LINE> pids = ctx.platform.getpids(name) <NEW_LINE> if len(pids) == 0: <NEW_LINE> <INDENT> e = 'postrun fail: no %s running' % name <NEW_LINE> raise PostconditionError(e) <NEW_LINE> <DEDENT> if len(pids) > 1: <NEW_LINE> <INDENT> e = 'postrun fail: multiple %s instances running' % name <NEW_LINE> raise PostconditionError(e) <NEW_LINE> <DEDENT> <DEDENT> def stop(self, ctx): <NEW_LINE> <INDENT> ctx.stop()
Run emaneeventservice with the provided configuration file.
62598fd7656771135c489b98
class RocketgramStopRequest(RocketgramError): <NEW_LINE> <INDENT> pass
A special exception that can be raised to abort request processing. Should never be intercepted in user code.
62598fd73617ad0b5ee0666d
class ProgressLogger(CallbackAny2Vec): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.epoch = 1 <NEW_LINE> self.epoch_start_time = 0 <NEW_LINE> self.last_training_loss = 0 <NEW_LINE> <DEDENT> def on_epoch_begin(self, model): <NEW_LINE> <INDENT> self.epoch_start_time = time.time() <NEW_LINE> <DEDENT> def on_epoch_end(self, model): <NEW_LINE> <INDENT> loss = model.get_latest_training_loss() - self.last_training_loss <NEW_LINE> self.last_training_loss = model.get_latest_training_loss() <NEW_LINE> print('-' * 70) <NEW_LINE> print('| end of epoch {:3d} | time: {:5.2f}s | loss {:5.2f} | ' .format(self.epoch, (time.time() - self.epoch_start_time), loss)) <NEW_LINE> print('-' * 70) <NEW_LINE> self.epoch += 1
Callback to show progress and training parameters
62598fd7ad47b63b2c5a7d78
class ClassTime(models.Model): <NEW_LINE> <INDENT> id = models.AutoField(primary_key=True) <NEW_LINE> section = models.CharField(blank=True,max_length=1) <NEW_LINE> day = models.CharField(blank=True,max_length=1) <NEW_LINE> start_time = models.TimeField() <NEW_LINE> end_time = models.TimeField() <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return "星期" + str(self.day) + " " + str(self.section) + "節"
it have 16 period per day,and 7 days per week.
62598fd7ad47b63b2c5a7d79
class PowerWallEnergyDirectionSensor(PowerWallEntity, SensorEntity): <NEW_LINE> <INDENT> _attr_state_class = SensorStateClass.TOTAL_INCREASING <NEW_LINE> _attr_native_unit_of_measurement = ENERGY_KILO_WATT_HOUR <NEW_LINE> _attr_device_class = SensorDeviceClass.ENERGY <NEW_LINE> def __init__( self, powerwall_data: PowerwallRuntimeData, meter: MeterType, meter_direction: str, ) -> None: <NEW_LINE> <INDENT> super().__init__(powerwall_data) <NEW_LINE> self._meter = meter <NEW_LINE> self._attr_name = f"Powerwall {meter.value.title()} {meter_direction.title()}" <NEW_LINE> self._attr_unique_id = f"{self.base_unique_id}_{meter.value}_{meter_direction}" <NEW_LINE> <DEDENT> @property <NEW_LINE> def available(self) -> bool: <NEW_LINE> <INDENT> return super().available and self.native_value != 0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def meter(self) -> Meter: <NEW_LINE> <INDENT> return self.data.meters.get_meter(self._meter)
Representation of an Powerwall Direction Energy sensor.
62598fd70fa83653e46f5410
class NubiaTogglExtraPlugin(PluginInterface): <NEW_LINE> <INDENT> def create_context(self): <NEW_LINE> <INDENT> return NubiaTogglExtraContext() <NEW_LINE> <DEDENT> def validate_args(self, args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_commands(self): <NEW_LINE> <INDENT> return [ AutoCommand(nubia_commands.dump_entries), ] <NEW_LINE> <DEDENT> def get_opts_parser(self, add_help=True): <NEW_LINE> <INDENT> opts_parser = argparse.ArgumentParser( description="Nubia Toggl Extra Utility", formatter_class=argparse.ArgumentDefaultsHelpFormatter, add_help=add_help, ) <NEW_LINE> opts_parser.add_argument( "--config", "-c", default="", type=str, help="Configuration File" ) <NEW_LINE> opts_parser.add_argument( "--verbose", "-v", action="count", default=0, help="Increase verbosity, can be specified " "multiple times", ) <NEW_LINE> opts_parser.add_argument( "--stderr", "-s", action="store_true", help="By default the logging output goes to a " "temporary file. This disables this feature " "by sending the logging output to stderr", ) <NEW_LINE> return opts_parser <NEW_LINE> <DEDENT> def get_completion_datasource_for_global_argument(self, argument): <NEW_LINE> <INDENT> if argument == "--config": <NEW_LINE> <INDENT> return ConfigFileCompletionDataSource() <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def create_usage_logger(self, context): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def get_status_bar(self, context): <NEW_LINE> <INDENT> return NubiaTogglExtraStatusBar(context) <NEW_LINE> <DEDENT> def getBlacklistPlugin(self): <NEW_LINE> <INDENT> black_lister = CommandBlacklist() <NEW_LINE> black_lister.add_blocked_command("be-blocked") <NEW_LINE> return black_lister
The PluginInterface class is a way to customize nubia_wiring for every customer use case. It allows custom argument validation, control over command loading, custom context objects, and much more.
62598fd7956e5f7376df5911
class ELKFormatter(logging.Formatter): <NEW_LINE> <INDENT> def format(self, record: logging.LogRecord) -> str: <NEW_LINE> <INDENT> if not hasattr(record, 'asctime'): <NEW_LINE> <INDENT> record.asctime = self.formatTime(record, self.datefmt) <NEW_LINE> <DEDENT> log = { 'timestamp': record.asctime, 'timestamp_msec': record.created * 1000, 'message': record.getMessage(), 'variables': record.args, '@fields.level': record.levelname or 'NONE', '@fields.logger': 'app-%s' % record.name or 'unknown', '@fields.source_path': '%s#%s' % (record.pathname or '?', record.lineno or '0'), } <NEW_LINE> if record.exc_info: <NEW_LINE> <INDENT> if not record.exc_text: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> record.exc_text = self.formatException(record.exc_info) <NEW_LINE> <DEDENT> except (AttributeError, TypeError): <NEW_LINE> <INDENT> record.exc_text = str(record.exc_info) <NEW_LINE> <DEDENT> <DEDENT> log['@fields.exception'] = record.exc_text <NEW_LINE> <DEDENT> if hasattr(record, 'elk_fields') and isinstance(record.elk_fields, dict): <NEW_LINE> <INDENT> log.update(record.elk_fields) <NEW_LINE> <DEDENT> return json.dumps(log, default=str, ensure_ascii=False)
Formats log records as JSON for shipping to ELK
62598fd7377c676e912f700e
class DevicePackagesTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def testPackages(self): <NEW_LINE> <INDENT> dev1 = DiskDevice("name", fmt=getFormat("mdmember")) <NEW_LINE> dev2 = DiskDevice("other", fmt=getFormat("mdmember")) <NEW_LINE> dev = MDRaidArrayDevice("dev", level="raid1", parents=[dev1,dev2]) <NEW_LINE> luks = LUKSDevice("luks", parents=[dev]) <NEW_LINE> packages = luks.packages <NEW_LINE> self.assertListEqual(packages, list(set(packages))) <NEW_LINE> for package in dev1.packages + dev2.packages + dev.packages: <NEW_LINE> <INDENT> self.assertIn(package, packages) <NEW_LINE> <DEDENT> for package in dev1.format.packages + dev2.format.packages + dev.format.packages: <NEW_LINE> <INDENT> self.assertIn(package, packages)
Test device name validation
62598fd7dc8b845886d53ae6
class CameraEntityPreferences: <NEW_LINE> <INDENT> def __init__(self, prefs): <NEW_LINE> <INDENT> self._prefs = prefs <NEW_LINE> <DEDENT> def as_dict(self): <NEW_LINE> <INDENT> return self._prefs <NEW_LINE> <DEDENT> @property <NEW_LINE> def preload_stream(self): <NEW_LINE> <INDENT> return self._prefs.get(PREF_PRELOAD_STREAM, False)
Handle preferences for camera entity.
62598fd79f28863672818b12
class Worker(threading.Thread): <NEW_LINE> <INDENT> def __init__(self, path_queue, result_queue): <NEW_LINE> <INDENT> threading.Thread.__init__(self) <NEW_LINE> self.path_queue = path_queue <NEW_LINE> self.result_queue = result_queue <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> path, params = self.path_queue.get() <NEW_LINE> errors = run(path, **params) <NEW_LINE> self.result_queue.put(errors) <NEW_LINE> self.path_queue.task_done()
Get tasks from queue and run.
62598fd7a219f33f346c6d30
class Cylinder(ThreeDimensionalShape): <NEW_LINE> <INDENT> def __init__( self, diameter: float, width: float, ): <NEW_LINE> <INDENT> self.diameter = diameter <NEW_LINE> self.width = width <NEW_LINE> self._validate_args() <NEW_LINE> <DEDENT> def _validate_args( self, ) -> None: <NEW_LINE> <INDENT> args = { "diameter": self.diameter, "width": self.width, } <NEW_LINE> if None in args.values(): <NEW_LINE> <INDENT> raise TypeError( f"Cannot create {self.__class__} with {args} as one or more is None" ) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def radius(self): <NEW_LINE> <INDENT> return self.diameter / 2 <NEW_LINE> <DEDENT> def volume(self) -> float: <NEW_LINE> <INDENT> return circle_area(self.radius) * self.width <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_tire_dimensions( cls, outer_diameter: float, width: float, inner_diameter: float ) -> Cylinder: <NEW_LINE> <INDENT> return cls(outer_diameter, width)
A right angled cylinder. Parameters ---------- diameter : float the length of the straight line that passes through the center of the circular cross section width : float The length of the side orthagonol to the circular cross section
62598fd7956e5f7376df5912
class TestReportFilters(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testReportFilters(self): <NEW_LINE> <INDENT> pass
ReportFilters unit test stubs
62598fd7dc8b845886d53ae8
class HOST(CIMElement): <NEW_LINE> <INDENT> def __init__(self, pcdata): <NEW_LINE> <INDENT> Element.__init__(self, 'HOST') <NEW_LINE> self.appendChild(Text(pcdata))
The HOST element is used to define a single Host. The element content MUST specify a legal value for a hostname in accordance with the CIM specification. <!ELEMENT HOST (#PCDATA)>
62598fd7656771135c489b9c
class Command(MuxCommand): <NEW_LINE> <INDENT> pass
Note that in the code, most of the default commands most likely do NOT inherit from this class, so be careful if you change this class. Inherit from this if you want to create your own command styles from scratch. Note that Evennia's default commands inherits from MuxCommand instead. Note that the class's `__doc__` string (this text) is used by Evennia to create the automatic help entry for the command, so make sure to document consistently here. Each Command implements the following methods, called in this order (only func() is actually required): - at_pre_command(): If this returns True, execution is aborted. - parse(): Should perform any extra parsing needed on self.args and store the result on self. - func(): Performs the actual work. - at_post_command(): Extra actions, often things done after every command, like prompts.
62598fd7956e5f7376df5913
class ServiceReference(pb.Referenceable): <NEW_LINE> <INDENT> def __init__(self, service, name, monitor, routes, executors): <NEW_LINE> <INDENT> self.__service = service <NEW_LINE> self.__name = name <NEW_LINE> self.__monitor = monitor <NEW_LINE> self.__executors = executors <NEW_LINE> self.__routes = routes <NEW_LINE> self.__log = getLogger(self) <NEW_LINE> self.callTime = 0.0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def service(self): <NEW_LINE> <INDENT> return self.__service <NEW_LINE> <DEDENT> @defer.inlineCallbacks <NEW_LINE> def remoteMessageReceived(self, broker, message, args, kw): <NEW_LINE> <INDENT> begin = time.time() <NEW_LINE> success = False <NEW_LINE> try: <NEW_LINE> <INDENT> args = broker.unserialize(args) <NEW_LINE> kw = broker.unserialize(kw) <NEW_LINE> call = ServiceCall( monitor=self.__monitor, service=self.__name, method=message, args=args, kwargs=kw, ) <NEW_LINE> executor = self.__get_executor(call) <NEW_LINE> self.__log.debug( "Begin processing remote message " "message=%s service=%s monitor=%s", message, self.__name, self.__monitor, ) <NEW_LINE> state = yield executor.submit(call) <NEW_LINE> response = broker.serialize(state, self.perspective) <NEW_LINE> success = True <NEW_LINE> defer.returnValue(response) <NEW_LINE> <DEDENT> except _PropagatingErrors as ex: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> self.__log.exception( "Failed to process remote message " "message=%s service=%s monitor=%s error=(%s) %s", message, self.__name, self.__monitor, ex.__class__.__name__, ex, ) <NEW_LINE> raise pb.Error( "Internal ZenHub error: (%s) %s" % (ex.__class__.__name__, ex), ) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> end = time.time() <NEW_LINE> elapsed = end - begin <NEW_LINE> self.callTime += elapsed <NEW_LINE> self.__log.debug( "Completed processing remote message " "message=%s service=%s monitor=%s status=%s duration=%0.2f", message, self.__name, self.__monitor, "OK" if success else "ERROR", elapsed, ) <NEW_LINE> <DEDENT> <DEDENT> def __get_executor(self, call): <NEW_LINE> <INDENT> name = self.__routes.get(call) <NEW_LINE> if not name: <NEW_LINE> <INDENT> raise KeyError( "No route found service=%s method=%s" % (call.service, call.method), ) <NEW_LINE> <DEDENT> executor = self.__executors.get(name) <NEW_LINE> if not executor: <NEW_LINE> <INDENT> raise KeyError( "Executor not registered executor=%s service=%s method=%s" % (name, call.service, call.method), ) <NEW_LINE> <DEDENT> return executor <NEW_LINE> <DEDENT> def __getattr__(self, attr): <NEW_LINE> <INDENT> return getattr(self.__service, attr)
Delegates remote message handling to another object. An 'executor' object is used to execute the method of the named service.
62598fd7dc8b845886d53aea
class PhysicalTest(unittest.TestCase): <NEW_LINE> <INDENT> @unittest.skip("skip until all test runners have poppler >= 0.88") <NEW_LINE> def test_physical_vs_not(self): <NEW_LINE> <INDENT> filename = "three_columns.pdf" <NEW_LINE> pdf = pdftotext.PDF(get_file(filename)) <NEW_LINE> physical_pdf = pdftotext.PDF(get_file(filename), physical=True) <NEW_LINE> self.assertNotEqual(pdf[0], physical_pdf[0]) <NEW_LINE> <DEDENT> def test_physical_invalid_type(self): <NEW_LINE> <INDENT> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> pdftotext.PDF(get_file("blank.pdf"), physical="") <NEW_LINE> <DEDENT> <DEDENT> def test_physical_invalid_value(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> pdftotext.PDF(get_file("blank.pdf"), physical=-10) <NEW_LINE> <DEDENT> <DEDENT> def test_physical_is_not_default(self): <NEW_LINE> <INDENT> filename = "three_columns.pdf" <NEW_LINE> pdf_default = pdftotext.PDF(get_file(filename)) <NEW_LINE> pdf_physical_false = pdftotext.PDF(get_file(filename), physical=False) <NEW_LINE> self.assertEqual(pdf_default[0], pdf_physical_false[0]) <NEW_LINE> <DEDENT> def test_raw_and_physical(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> pdftotext.PDF(get_file("blank.pdf"), raw=True, physical=True) <NEW_LINE> <DEDENT> <DEDENT> def test_raw_vs_physical(self): <NEW_LINE> <INDENT> filename = "three_columns.pdf" <NEW_LINE> pdf_raw = pdftotext.PDF(get_file(filename), raw=True) <NEW_LINE> pdf_physical = pdftotext.PDF(get_file(filename), physical=True) <NEW_LINE> self.assertNotEqual(pdf_raw[0], pdf_physical[0])
Test reading in physical layout.
62598fd7283ffb24f3cf3dad
class BacktestingBroker(backtesting.Broker): <NEW_LINE> <INDENT> def __init__(self, cash, barFeed, commission=None): <NEW_LINE> <INDENT> if commission is None: <NEW_LINE> <INDENT> commission = backtesting.TradePercentage(0.006) <NEW_LINE> <DEDENT> backtesting.Broker.__init__(self, cash, barFeed, commission) <NEW_LINE> <DEDENT> def createMarketOrder(self, action, instrument, quantity, onClose=False): <NEW_LINE> <INDENT> if action not in [broker.Order.Action.BUY, broker.Order.Action.SELL]: <NEW_LINE> <INDENT> raise Exception("Only BUY/SELL orders are supported") <NEW_LINE> <DEDENT> if instrument != "BTC": <NEW_LINE> <INDENT> raise Exception("Only BTC instrument is supported") <NEW_LINE> <DEDENT> return backtesting.Broker.createMarketOrder(self, action, instrument, quantity, onClose) <NEW_LINE> <DEDENT> def createLimitOrder(self, action, instrument, limitPrice, quantity): <NEW_LINE> <INDENT> if action not in [broker.Order.Action.BUY, broker.Order.Action.SELL]: <NEW_LINE> <INDENT> raise Exception("Only BUY/SELL orders are supported") <NEW_LINE> <DEDENT> if instrument != "BTC": <NEW_LINE> <INDENT> raise Exception("Only BTC instrument is supported") <NEW_LINE> <DEDENT> return backtesting.Broker.createLimitOrder(self, action, instrument, limitPrice, quantity) <NEW_LINE> <DEDENT> def createStopOrder(self, action, instrument, stopPrice, quantity): <NEW_LINE> <INDENT> raise Exception("Stop orders are not supported") <NEW_LINE> <DEDENT> def createStopLimitOrder(self, action, instrument, stopPrice, limitPrice, quantity): <NEW_LINE> <INDENT> raise Exception("Stop limit orders are not supported")
A backtesting broker. :param cash: The initial amount of cash. :type cash: int/float. :param barFeed: The bar feed that will provide the bars. :type barFeed: :class:`pyalgotrade.barfeed.BarFeed` :param commission: An object responsible for calculating order commissions. **If None, a 0.6% trade commision will be used**. :type commission: :class:`pyalgotrade.broker.backtesting.Commission` .. note:: Neither stop nor stop limit orders are supported.
62598fd70fa83653e46f5416
class UserEditForm(UserNewForm): <NEW_LINE> <INDENT> original = forms.CharField(widget=forms.PasswordInput(), label=_("Original")) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = get_user_model() <NEW_LINE> fields = ('password', 'password_confirm', 'original') <NEW_LINE> widgets = {'password': forms.PasswordInput(attrs={'autocomplete': 'off'})}
Formulaire de modification du mot de passe du compte
62598fd7a219f33f346c6d34
class DataFrameSelector(BaseEstimator, TransformerMixin): <NEW_LINE> <INDENT> def __init__(self, attribute_names): <NEW_LINE> <INDENT> self.atrribute_names = attribute_names <NEW_LINE> <DEDENT> def fit(self, X, y=None): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def transform(self, X): <NEW_LINE> <INDENT> return X[self.atrribute_names].values
Scikit-Learn doesn't know how to handle Pandas DataFrames.
62598fd750812a4eaa620e7a
class FdtPropertyWords(FdtProperty): <NEW_LINE> <INDENT> def __init__(self, name, words): <NEW_LINE> <INDENT> FdtProperty.__init__(self, name) <NEW_LINE> for word in words: <NEW_LINE> <INDENT> if not 0 <= word <= 4294967295: <NEW_LINE> <INDENT> raise Exception(("Invalid word value %d, requires " + "0 <= number <= 4294967295") % word) <NEW_LINE> <DEDENT> <DEDENT> if not len(words): <NEW_LINE> <INDENT> raise Exception("Invalid Words") <NEW_LINE> <DEDENT> self.words = words <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def init_raw(cls, name, raw_value): <NEW_LINE> <INDENT> if len(raw_value) % 4 == 0: <NEW_LINE> <INDENT> words = [unpack(">I", raw_value[i:i+4])[0] for i in range(0, len(raw_value), 4)] <NEW_LINE> return cls(name, words) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("Invalid raw Words") <NEW_LINE> <DEDENT> <DEDENT> def dts_represent(self, depth=0): <NEW_LINE> <INDENT> return INDENT*depth + self.name + ' = <' + ' '.join(["0x%08x" % word for word in self.words]) + ">;" <NEW_LINE> <DEDENT> def dtb_represent(self, string_store, pos=0, version=17): <NEW_LINE> <INDENT> strpos = string_store.find(self.name+'\0') <NEW_LINE> if strpos < 0: <NEW_LINE> <INDENT> strpos = len(string_store) <NEW_LINE> string_store += self.name+'\0' <NEW_LINE> <DEDENT> blob = pack('>III', FDT_PROP, len(self.words)*4, strpos) + pack('').join([pack('>I', word) for word in self.words]) <NEW_LINE> pos += len(blob) <NEW_LINE> return (blob, string_store, pos) <NEW_LINE> <DEDENT> def json_represent(self, depth=0): <NEW_LINE> <INDENT> result = '%s: ["words", "' % json.dumps(self.name) <NEW_LINE> result += '", "'.join(["0x%08x" % word for word in self.words]) <NEW_LINE> result += '"]' <NEW_LINE> return result <NEW_LINE> <DEDENT> def to_raw(self): <NEW_LINE> <INDENT> return ''.join([pack('>I', word) for word in self.words]) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Property(%s,Words:%s)" % (self.name, self.words) <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> return self.words[index] <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.words) <NEW_LINE> <DEDENT> def __eq__(self, node): <NEW_LINE> <INDENT> if not FdtProperty.__eq__(self, node): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.__len__() != len(node): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for index in range(self.__len__()): <NEW_LINE> <INDENT> if self.words[index] != node[index]: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True
Property with words as value
62598fd7ad47b63b2c5a7d80
class FakturaUpdate(views.LoginRequiredMixin, generic.UpdateView): <NEW_LINE> <INDENT> form_class = FakturaUpdateForm <NEW_LINE> form_valid_message = 'Faktūra pataisyta.' <NEW_LINE> template_name = 'update_form.html' <NEW_LINE> def get_object(self, queryset=None): <NEW_LINE> <INDENT> obj = Sf.objects.get(pk=self.kwargs['id_pk']) <NEW_LINE> return obj <NEW_LINE> <DEDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(FakturaUpdate, self).get_context_data(**kwargs) <NEW_LINE> id_pk = self.kwargs['id_pk'] <NEW_LINE> sut_id = Sf.objects.get(pk=id_pk).sutartisid_id <NEW_LINE> context['formos_pavadinimas'] = 'Sąskaitos faktūros redagavimas' <NEW_LINE> context['papildoma_info'] = { 'Tiekėjas': Sutartis.objects.get(pk=sut_id).tiekejas, 'Sutarties data': Sutartis.objects.get(pk=sut_id).data, 'Sutarties suma': Sutartis.objects.get(pk=sut_id).suma} <NEW_LINE> return context <NEW_LINE> <DEDENT> def get_success_url(self): <NEW_LINE> <INDENT> if 'id_pk' in self.kwargs: <NEW_LINE> <INDENT> id_pk = self.kwargs['id_pk'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> id_pk = '404' <NEW_LINE> <DEDENT> return reverse_lazy('faktura', kwargs={'id_pk': id_pk})
Saskaitos fakturos redagavimas
62598fd7ad47b63b2c5a7d81
class MB_IntervalMul: <NEW_LINE> <INDENT> def get_result_interval(self, lhs, rhs): <NEW_LINE> <INDENT> if lhs.interval is None or rhs.interval is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return lhs.interval * rhs.interval
Parent virtual class for meta-multiplication
62598fd70fa83653e46f5418
class Converter(_Converter): <NEW_LINE> <INDENT> pass
Converter for PROZA simulation.
62598fd7c4546d3d9def751b
class IsThisReaction(Reaction): <NEW_LINE> <INDENT> IDENTIFIER = "THIS IS PATRICK" <NEW_LINE> SOURCE = "https://www.youtube.com/watch?v=YSzOXtXm8p0" <NEW_LINE> CHANNEL_TYPES = [ChannelType.Channel, ChannelType.Group] <NEW_LINE> THIS_IS_PATRICK_MOOD_DICT = {0: "No this is Patrick :slightly_smiling_face:", 1: "No this is Patrick! :angry:", 2: "NO THIS IS PATRICK! :rage:"} <NEW_LINE> def __init__(self, patrick): <NEW_LINE> <INDENT> self.is_this_pattern = re.compile(r"[Ii]s this [\s\S]*\?") <NEW_LINE> self.asked_if_its_patrick = False <NEW_LINE> super(IsThisReaction, self).__init__(patrick) <NEW_LINE> <DEDENT> def condition(self, message): <NEW_LINE> <INDENT> text = message['text'].lower() <NEW_LINE> if text == "is this patrick?": <NEW_LINE> <INDENT> self.asked_if_its_patrick = True <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.asked_if_its_patrick = False <NEW_LINE> return self.is_this_pattern.match(text) <NEW_LINE> <DEDENT> <DEDENT> def consequence(self, channel_id): <NEW_LINE> <INDENT> if self.asked_if_its_patrick: <NEW_LINE> <INDENT> self.patrick.post_message(channel_id, "Yes this is Patrick :blush:") <NEW_LINE> self.patrick.make_happy() <NEW_LINE> self.asked_if_its_patrick = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.patrick.post_message(channel_id, self.THIS_IS_PATRICK_MOOD_DICT[self.patrick.mood]) <NEW_LINE> self.patrick.make_angry()
Reaction when somebody asks if sth is sth
62598fd7dc8b845886d53af0
class Tag(db.Model): <NEW_LINE> <INDENT> tag = models.CharField(max_length=100, unique=True) <NEW_LINE> users = models.ManyToManyField(User, related_name="tags") <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.tag
A Tag which can be applied to a user.
62598fd78a349b6b43686773
class NewsImageForm(ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = NewsImages <NEW_LINE> widgets = { 'image' : AdminImageWidget, }
Image Admin Form
62598fd7283ffb24f3cf3db3
class OneHotCharacterExtractor(BaseExtractor): <NEW_LINE> <INDENT> def __init__(self, field=None, include_space=True): <NEW_LINE> <INDENT> super().__init__(field) <NEW_LINE> self.include_space = include_space <NEW_LINE> <DEDENT> def _process(self, symbols): <NEW_LINE> <INDENT> if self.include_space and " " not in symbols: <NEW_LINE> <INDENT> symbols = [" "] + list(symbols) <NEW_LINE> <DEDENT> features = np.eye(len(symbols), dtype=np.int) <NEW_LINE> return dict(zip(symbols, features))
Convert your characters to one hot features. Note: if your data contains diacritics, such as 'é', you might be better off normalizing these. The OneHotCharacterExtractor will assign these completely dissimilar representations. Example ------- >>> from wordkit.feature_extraction import OneHotCharacterExtractor >>> words = ["c'est", "stéphan"] >>> o = OneHotCharacterExtractor(field=None) >>> o.extract(words)
62598fd7656771135c489ba4
class PassivateWiggler(Person): <NEW_LINE> <INDENT> next_target = movement.person_next_target_random <NEW_LINE> def act_at_node(self, node): <NEW_LINE> <INDENT> if 'amenity' in node.tags: <NEW_LINE> <INDENT> if node.tags['amenity'] == 'cafe': <NEW_LINE> <INDENT> sys.stderr.write(' '+self.name+' visited '+str(node.id)+' '+str(node.tags)+' at '+str(self.sim.now())+'\n') <NEW_LINE> self.passivate = True <NEW_LINE> self.sim.a.passive_persons[self] = self.next_node
Random moving person, when arriving at an cafe road node being passivated.
62598fd7ab23a570cc2d5007
class IdGenerator(object): <NEW_LINE> <INDENT> instances = [] <NEW_LINE> def __init__(self, prefix): <NEW_LINE> <INDENT> self.instances.append(self) <NEW_LINE> self.prefix = prefix <NEW_LINE> self.uid = str(uuid.uuid4()) <NEW_LINE> self.generator = self.get_generator() <NEW_LINE> <DEDENT> def get_generator(self): <NEW_LINE> <INDENT> i = 0 <NEW_LINE> j = 1 <NEW_LINE> while True: <NEW_LINE> <INDENT> i += 1 <NEW_LINE> yield self.prefix + '/' + self.uid + '/' + str(j) + '/' + str(i) <NEW_LINE> if i > 10000: <NEW_LINE> <INDENT> j += 1 <NEW_LINE> i = 0 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def reset(cls, uid=None): <NEW_LINE> <INDENT> for instance in cls.instances: <NEW_LINE> <INDENT> if uid: <NEW_LINE> <INDENT> instance.uid = uid <NEW_LINE> <DEDENT> instance.generator = instance.get_generator() <NEW_LINE> <DEDENT> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> return next(self.generator)
Generate some uuid for actions: .. code-block:: python >>> g = IdGenerator('mycounter') .. >>> IdGenerator.reset(uid='an_uuid4') It increment counters at each calls: .. code-block:: python >>> print(g()) mycounter/an_uuid4/1/1 >>> print(g()) mycounter/an_uuid4/1/2
62598fd7099cdd3c63675678
class TestChrootName(TestChroot): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def command(cls, arch, *args): <NEW_LINE> <INDENT> return super(TestChrootName, cls).command( arch, "-n", "testname", *args) <NEW_LINE> <DEDENT> def test_exists_different_name_fails(self): <NEW_LINE> <INDENT> with self.assertRaises(subprocess.CalledProcessError): <NEW_LINE> <INDENT> subprocess.check_call(super(TestChrootName, self).command( self.arch, "-n", "testname2", "exists"))
Run the chroot tests again with a different --name.
62598fd73617ad0b5ee0667b
class IStored(zope.interface.Interface): <NEW_LINE> <INDENT> metadata = zope.interface.Attribute("A dictionary of metadata returned by the storage provider.")
Placeholder interface for post-Storage (WorkedStored) events.
62598fd78a349b6b43686775
class UrlRewriteEztv(object): <NEW_LINE> <INDENT> def url_rewritable(self, task, entry): <NEW_LINE> <INDENT> return urlparse(entry['url']).netloc == 'eztv.ch' <NEW_LINE> <DEDENT> def url_rewrite(self, task, entry): <NEW_LINE> <INDENT> url = entry['url'] <NEW_LINE> page = None <NEW_LINE> for (scheme, netloc) in EZTV_MIRRORS: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _, _, path, params, query, fragment = urlparse(url) <NEW_LINE> url = urlunparse((scheme, netloc, path, params, query, fragment)) <NEW_LINE> page = task.requests.get(url).content <NEW_LINE> <DEDENT> except RequestException as e: <NEW_LINE> <INDENT> log.debug('Eztv mirror `%s` seems to be down', url) <NEW_LINE> continue <NEW_LINE> <DEDENT> break <NEW_LINE> <DEDENT> if not page: <NEW_LINE> <INDENT> raise UrlRewritingError('No mirrors found for url %s' % entry['url']) <NEW_LINE> <DEDENT> log.debug('Eztv mirror `%s` chosen', url) <NEW_LINE> try: <NEW_LINE> <INDENT> soup = get_soup(page) <NEW_LINE> mirrors = soup.find_all('a', attrs={'class': re.compile(r'download_\d')}) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise UrlRewritingError(e) <NEW_LINE> <DEDENT> log.debug('%d torrent mirrors found', len(mirrors)) <NEW_LINE> if not mirrors: <NEW_LINE> <INDENT> raise UrlRewritingError('Unable to locate download link from url %s' % url) <NEW_LINE> <DEDENT> entry['urls'] = [m.get('href') for m in mirrors] <NEW_LINE> entry['url'] = mirrors[0].get('href')
Eztv url rewriter.
62598fd7ad47b63b2c5a7d86
class TestInterfaceFunctional(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> payments.app.debug = True <NEW_LINE> if not payments.app.config['TESTING']: <NEW_LINE> <INDENT> payments.app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('LOCAL_DB') <NEW_LINE> <DEDENT> app_db.create_all() <NEW_LINE> payments_to_add = (CREDIT, DEBIT, PAYPAL) <NEW_LINE> for p in payments_to_add: <NEW_LINE> <INDENT> payment = Payment() <NEW_LINE> payment.deserialize(p) <NEW_LINE> app_db.session.add(payment) <NEW_LINE> app_db.session.commit() <NEW_LINE> <DEDENT> self.ps = PaymentService() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> app_db.session.remove() <NEW_LINE> app_db.drop_all() <NEW_LINE> <DEDENT> def test_successful_query(self): <NEW_LINE> <INDENT> result = self.ps._query_payments(QUERY_ATTRIBUTES) <NEW_LINE> PP_RETURN['payment_id'] = 3 <NEW_LINE> assert result[0].serialize() == PP_RETURN <NEW_LINE> <DEDENT> def test_unsuccessful_query(self): <NEW_LINE> <INDENT> result = self.ps._query_payments(BAD_QUERY_ATTRIBUTES) <NEW_LINE> assert result == []
A class for doing more functional tests involving the interface.py classes. Actual db connections are used, so db resources are created and destroyed.
62598fd7ad47b63b2c5a7d87
class SlotDefaultAccess: <NEW_LINE> <INDENT> def __init__(self, instance=None): <NEW_LINE> <INDENT> object.__setattr__(self, '_instance', instance) <NEW_LINE> <DEDENT> def _get_plug(self, name, default=None): <NEW_LINE> <INDENT> slot = getattr(type(self._instance), name) <NEW_LINE> if not isinstance(slot, Slot): <NEW_LINE> <INDENT> raise AttributeError( "'{}' object has no attribute '{}' of type '{}'".format( type(self._instance), name, Slot ) ) <NEW_LINE> <DEDENT> return slot.get_plug(self._instance, default=default) <NEW_LINE> <DEDENT> def __get__(self, instance, owner): <NEW_LINE> <INDENT> return type(self)(instance) <NEW_LINE> <DEDENT> def __set__(self, instance, value): <NEW_LINE> <INDENT> new = type(self)(instance) <NEW_LINE> if not isinstance(value, dict): <NEW_LINE> <INDENT> raise TypeError("Can only directly set default values using a dict!") <NEW_LINE> <DEDENT> for key, val in value.items(): <NEW_LINE> <INDENT> setattr(new, key, val) <NEW_LINE> <DEDENT> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> return self._get_plug(name).default <NEW_LINE> <DEDENT> def __setattr__(self, name, value): <NEW_LINE> <INDENT> self._get_plug(name, default=value).default = value <NEW_LINE> <DEDENT> def __delattr__(self, name): <NEW_LINE> <INDENT> del self._get_plug(name).default <NEW_LINE> <DEDENT> def __dir__(self): <NEW_LINE> <INDENT> return list(type(self._instance).collect(Slot))
A proxy-object descriptor class to access Plug default values of the owning class, since Plug-instances can not be returned except by accessing a classes' __dict__. See Also -------- :obj:`Slot` :obj:`Plugboard` :obj:`Plug`
62598fd70fa83653e46f541e
class MDWCdma(SCPINode, SCPISet): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> _cmd = "MDWCdma" <NEW_LINE> args = []
MEMory:DELete:MDWCdma Arguments:
62598fd7c4546d3d9def751d
class Library(object): <NEW_LINE> <INDENT> def object(func, name=None): <NEW_LINE> <INDENT> if name is None: <NEW_LINE> <INDENT> name = getattr(func, '__name__') <NEW_LINE> <DEDENT> env.globals[name] = func <NEW_LINE> return func <NEW_LINE> <DEDENT> object = staticmethod(object) <NEW_LINE> def filter(func, name=None): <NEW_LINE> <INDENT> if name is None: <NEW_LINE> <INDENT> name = func.__name__ <NEW_LINE> <DEDENT> env.filters[name] = func <NEW_LINE> return func <NEW_LINE> <DEDENT> filter = staticmethod(filter) <NEW_LINE> def test(func, name): <NEW_LINE> <INDENT> if name is None: <NEW_LINE> <INDENT> name = func.__name__ <NEW_LINE> <DEDENT> env.tests[name] = func <NEW_LINE> return func <NEW_LINE> <DEDENT> test = staticmethod(test) <NEW_LINE> def context_inclusion(func, template, name=None): <NEW_LINE> <INDENT> def wrapper(env, context, *args, **kwargs): <NEW_LINE> <INDENT> context = func(context.to_dict(), *args, **kwargs) <NEW_LINE> return render_to_string(template, context) <NEW_LINE> <DEDENT> wrapper.jinja_context_callable = True <NEW_LINE> if name is None: <NEW_LINE> <INDENT> name = func.__name__ <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> wrapper.__name__ = func.__name__ <NEW_LINE> wrapper.__doc__ = func.__doc__ <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> env.globals[name] = wrapper <NEW_LINE> <DEDENT> context_inclusion = staticmethod(context_inclusion) <NEW_LINE> def clean_inclusion(func, template, name=None, run_processors=False): <NEW_LINE> <INDENT> def wrapper(env, context, *args, **kwargs): <NEW_LINE> <INDENT> if run_processors: <NEW_LINE> <INDENT> request = context['request'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> request = None <NEW_LINE> <DEDENT> context = func({}, *args, **kwargs) <NEW_LINE> return render_to_string(template, context, request) <NEW_LINE> <DEDENT> wrapper.jinja_context_callable = True <NEW_LINE> if name is None: <NEW_LINE> <INDENT> name = func.__name__ <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> wrapper.__name__ = func.__name__ <NEW_LINE> wrapper.__doc__ = func.__doc__ <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> env.globals[name] = wrapper <NEW_LINE> <DEDENT> clean_inclusion = staticmethod(clean_inclusion)
Continues a general feel of wrapping all the registration methods for easy importing. This is available in `jinja.contrib.djangosupport` as `register`. For more details see the docstring of the `jinja.contrib.djangosupport` module.
62598fd7dc8b845886d53af4
class CloseAllAction(PyFaceAction): <NEW_LINE> <INDENT> name = 'C&lose All' <NEW_LINE> tooltip = "Close all open editors" <NEW_LINE> description = tooltip <NEW_LINE> def perform(self, event=None): <NEW_LINE> <INDENT> while len(self.window.editors) > 0: <NEW_LINE> <INDENT> editor = self.window.editors[0] <NEW_LINE> if editor is not None: <NEW_LINE> <INDENT> if editor._dirty: <NEW_LINE> <INDENT> file = '%s%s' % (editor.obj.name, editor.obj.ext) <NEW_LINE> if file != '': <NEW_LINE> <INDENT> message = "'%s' has been modified. Save changes?" % file <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> message = "Contents have been modified. Save?" <NEW_LINE> <DEDENT> result = self.window.workbench.confirm(message, title='Save File', cancel=True, default=CANCEL ) <NEW_LINE> if result == YES: <NEW_LINE> <INDENT> editor.save_as() <NEW_LINE> <DEDENT> elif result == CANCEL: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> elif result == NO: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> editor.close()
...
62598fd7d8ef3951e32c80f7
class TokenNotSpecifiedException(Exception): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return 'Bot token is not specified.'
Исключение в случае не указанного токена бота.
62598fd7c4546d3d9def751e
class Value(Node): <NEW_LINE> <INDENT> def __init__(self, type=None, source=None): <NEW_LINE> <INDENT> self.type = type <NEW_LINE> self.source = source <NEW_LINE> <DEDENT> def depends(self): <NEW_LINE> <INDENT> if self.source is None: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [self.source] <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<Value: " + str(self.type) + ">"
Represents single value (array, slice, constant). Once created, cannot be changed, can be reused.
62598fd79f28863672818b19
class Player(pygame.sprite.Sprite): <NEW_LINE> <INDENT> def __init__(self, com): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.image = pygame.Surface([60, 10]) <NEW_LINE> self.image.fill(RED) <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.coms = com <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> x, y = self.coms.updateCoords() <NEW_LINE> self.rect.x = x
This class represents the Player.
62598fd7adb09d7d5dc0aab2
class SubmissionData(Base): <NEW_LINE> <INDENT> __tablename__ = 'submissiondata' <NEW_LINE> submissiondata_id = Column(Integer, primary_key=True) <NEW_LINE> bucketname = Column(String) <NEW_LINE> event_id = Column(Integer, ForeignKey('events.event_id'), nullable=False) <NEW_LINE> eventName = Column(String) <NEW_LINE> eventTime = Column(String) <NEW_LINE> sourceIPAddress = Column(postgresql.INET) <NEW_LINE> eTag = Column(String) <NEW_LINE> key = Column(String) <NEW_LINE> size = Column(String) <NEW_LINE> fullRecord = Column(String, nullable=False) <NEW_LINE> @staticmethod <NEW_LINE> def insert(subdata): <NEW_LINE> <INDENT> db.add(subdata) <NEW_LINE> db.commit() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def insertEx(event_id, subdata_jsonstring): <NEW_LINE> <INDENT> subdata = json.loads(subdata_jsonstring) <NEW_LINE> for record in subdata['Records']: <NEW_LINE> <INDENT> SD = SubmissionData(bucketname=record['s3']['bucket']['name'], event_id=event_id, eventName=record['eventName'], eventTime=record['eventTime'], sourceIPAddress=record['requestParameters']['sourceIPAddress'], eTag=record['s3']['object']['eTag'], key=record['s3']['object']['key'], size=record['s3']['object']['size'], fullRecord=subdata_jsonstring ) <NEW_LINE> SubmissionData.insert(SD) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def delete(subdata): <NEW_LINE> <INDENT> db.delete(subdata) <NEW_LINE> db.commit() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def select(**kwargs): <NEW_LINE> <INDENT> return db.query(SubmissionData).filter_by(**kwargs).all() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get(eventname): <NEW_LINE> <INDENT> return db.query(SubmissionData).join(Event).filter(Event.event_name == eventname).all()
Class to hold submission data messages produced from S3 and sent to SQS
62598fd7ab23a570cc2d500a
class Alien(Sprite): <NEW_LINE> <INDENT> def __init__(self, ai_game): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.screen = ai_game.screen <NEW_LINE> self.settings = ai_game.settings <NEW_LINE> self.image = pygame.image.load("images/alien.bmp") <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.x = self.rect.width <NEW_LINE> self.rect.y = self.rect.height <NEW_LINE> self.x = float(self.rect.x) <NEW_LINE> <DEDENT> def check_edges(self): <NEW_LINE> <INDENT> screen_rect = self.screen.get_rect() <NEW_LINE> if self.rect.right >= screen_rect.right or self.rect.left <= 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.x += self.settings.alien_speed * self.settings.fleet_direction <NEW_LINE> self.rect.x = self.x
A class to represent a single alien in the fleet
62598fd77cff6e4e811b5f63
class TopologyParameters(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'target_resource_group_name': {'key': 'targetResourceGroupName', 'type': 'str'}, 'target_virtual_network': {'key': 'targetVirtualNetwork', 'type': 'SubResource'}, 'target_subnet': {'key': 'targetSubnet', 'type': 'SubResource'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(TopologyParameters, self).__init__(**kwargs) <NEW_LINE> self.target_resource_group_name = kwargs.get('target_resource_group_name', None) <NEW_LINE> self.target_virtual_network = kwargs.get('target_virtual_network', None) <NEW_LINE> self.target_subnet = kwargs.get('target_subnet', None)
Parameters that define the representation of topology. :param target_resource_group_name: The name of the target resource group to perform topology on. :type target_resource_group_name: str :param target_virtual_network: The reference to the Virtual Network resource. :type target_virtual_network: ~azure.mgmt.network.v2019_12_01.models.SubResource :param target_subnet: The reference to the Subnet resource. :type target_subnet: ~azure.mgmt.network.v2019_12_01.models.SubResource
62598fd7a219f33f346c6d40
class Square: <NEW_LINE> <INDENT> def __init__(self, size): <NEW_LINE> <INDENT> self.__size = size
class whit atribute
62598fd79f28863672818b1a
class NoTestResultsTests(unittest.TestCase): <NEW_LINE> <INDENT> def test_properties_return_correct_values(self): <NEW_LINE> <INDENT> MODULE_NAME = 'module' <NEW_LINE> CASE_NAME = 'case' <NEW_LINE> test_results = NoTestResults(MODULE_NAME, CASE_NAME) <NEW_LINE> self.assertEqual(test_results.module_name, MODULE_NAME) <NEW_LINE> self.assertEqual(test_results.case_name, CASE_NAME) <NEW_LINE> self.assertEqual(test_results.runtime, 0) <NEW_LINE> self.assertEqual(test_results.run_tests, 0) <NEW_LINE> self.assertEqual(test_results.failed_tests, 0) <NEW_LINE> self.assertEqual(test_results.output, '')
Tests for `NoTestResults`.
62598fd7656771135c489bac
@ALGORITHMS.register_module() <NEW_LINE> class DeepCluster(BaseModel): <NEW_LINE> <INDENT> def __init__(self, backbone, with_sobel=True, neck=None, head=None, init_cfg=None): <NEW_LINE> <INDENT> super(DeepCluster, self).__init__(init_cfg) <NEW_LINE> self.with_sobel = with_sobel <NEW_LINE> if with_sobel: <NEW_LINE> <INDENT> self.sobel_layer = Sobel() <NEW_LINE> <DEDENT> self.backbone = build_backbone(backbone) <NEW_LINE> if neck is not None: <NEW_LINE> <INDENT> self.neck = build_neck(neck) <NEW_LINE> <DEDENT> assert head is not None <NEW_LINE> self.head = build_head(head) <NEW_LINE> self.num_classes = self.head.num_classes <NEW_LINE> self.loss_weight = torch.ones((self.num_classes, ), dtype=torch.float32) <NEW_LINE> self.loss_weight /= self.loss_weight.sum() <NEW_LINE> <DEDENT> def extract_feat(self, img): <NEW_LINE> <INDENT> if self.with_sobel: <NEW_LINE> <INDENT> img = self.sobel_layer(img) <NEW_LINE> <DEDENT> x = self.backbone(img) <NEW_LINE> return x <NEW_LINE> <DEDENT> def forward_train(self, img, pseudo_label, **kwargs): <NEW_LINE> <INDENT> x = self.extract_feat(img) <NEW_LINE> if self.with_neck: <NEW_LINE> <INDENT> x = self.neck(x) <NEW_LINE> <DEDENT> outs = self.head(x) <NEW_LINE> loss_inputs = (outs, pseudo_label) <NEW_LINE> losses = self.head.loss(*loss_inputs) <NEW_LINE> return losses <NEW_LINE> <DEDENT> def forward_test(self, img, **kwargs): <NEW_LINE> <INDENT> x = self.extract_feat(img) <NEW_LINE> if self.with_neck: <NEW_LINE> <INDENT> x = self.neck(x) <NEW_LINE> <DEDENT> outs = self.head(x) <NEW_LINE> keys = [f'head{i}' for i in range(len(outs))] <NEW_LINE> out_tensors = [out.cpu() for out in outs] <NEW_LINE> return dict(zip(keys, out_tensors)) <NEW_LINE> <DEDENT> def set_reweight(self, labels, reweight_pow=0.5): <NEW_LINE> <INDENT> histogram = np.bincount( labels, minlength=self.num_classes).astype(np.float32) <NEW_LINE> inv_histogram = (1. / (histogram + 1e-10))**reweight_pow <NEW_LINE> weight = inv_histogram / inv_histogram.sum() <NEW_LINE> self.loss_weight.copy_(torch.from_numpy(weight)) <NEW_LINE> self.head.criterion = nn.CrossEntropyLoss(weight=self.loss_weight)
DeepCluster. Implementation of `Deep Clustering for Unsupervised Learning of Visual Features <https://arxiv.org/abs/1807.05520>`_. The clustering operation is in `core/hooks/deepcluster_hook.py`. Args: backbone (dict): Config dict for module of backbone. with_sobel (bool): Whether to apply a Sobel filter on images. Defaults to True. neck (dict): Config dict for module of deep features to compact feature vectors. Defaults to None. head (dict): Config dict for module of loss functions. Defaults to None.
62598fd7ab23a570cc2d500b
class Molecule(object): <NEW_LINE> <INDENT> def __init__(self, name, formula, cell_volume=None, density=None, charge=0): <NEW_LINE> <INDENT> elements = default_table() <NEW_LINE> M = parse_formula(formula, natural_density=density) <NEW_LINE> if elements.T in M.atoms: <NEW_LINE> <INDENT> warnings.warn("Use of tritium for labile hydrogen is deprecated." " Use H[1] instead of T in your formula.") <NEW_LINE> M = M.replace(elements.T, elements.H[1]) <NEW_LINE> <DEDENT> if cell_volume is not None: <NEW_LINE> <INDENT> M.density = 1e24*M.molecular_mass/cell_volume if cell_volume > 0 else 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cell_volume = 1e24*M.molecular_mass/M.density <NEW_LINE> <DEDENT> H = M.replace(elements.H[1], elements.H) <NEW_LINE> D = M.replace(elements.H[1], elements.D) <NEW_LINE> self.name = name <NEW_LINE> self.cell_volume = cell_volume <NEW_LINE> self.sld, self.Dsld = neutron_sld(H)[0], neutron_sld(D)[0] <NEW_LINE> self.mass, self.Dmass = H.mass, D.mass <NEW_LINE> self.D2Omatch = D2Omatch(self.sld, self.Dsld) <NEW_LINE> self.charge = charge <NEW_LINE> self.natural_formula = H <NEW_LINE> self.labile_formula = M <NEW_LINE> self.formula = self.labile_formula <NEW_LINE> <DEDENT> def D2Osld(self, volume_fraction=1., D2O_fraction=0.): <NEW_LINE> <INDENT> solvent_sld = D2O_fraction*D2O_SLD + (1-D2O_fraction)*H2O_SLD <NEW_LINE> solute_sld = D2O_fraction*self.Dsld + (1-D2O_fraction)*self.sld <NEW_LINE> return volume_fraction*solute_sld + (1-volume_fraction)*solvent_sld
Specify a biomolecule by name, chemical formula, cell volume and charge. Labile hydrogen positions should be coded using H[1] rather than H. H[1] will be substituded with H for solutions with natural water or D for solutions with heavy water. Any deuterated non-labile hydrogen can be marked with D, and they will stay as D regardless of the solvent. *name* is the molecule name. *formula* is the chemical formula as string or atom dictionary, with H[1] for labile hydrogen. *cell_volume* is the volume of the molecule. If None, cell volume will be inferred from the natural density of the molecule. Cell volume is assumed to be independent of isotope. *density* is the natural density of the molecule. If None, density will be inferred from cell volume. *charge* is the overall charge on the molecule. **Attributes** *labile_formula* is the original formula, with H[1] for the labile H. You can retrieve the deuterated from using:: molecule.labile_formula.replace(elements.H[1], elements.D) *natural_formula* has H substituted for H[1] in *labile_formula*. *D2Omatch* is percentage of D2O by volume in H2O required to match the SLD of the molecule, including substitution of labile hydrogen in proportion to the D/H ratio in the solvent. Values will be outside the range [0, 100] if the contrast match is impossible. *sld*/*Dsld* are the the SLDs of the molecule with H[1] replaced by naturally occurring H/D ratios and pure D respectively. *mass*/*Dmass* are the masses for natural H/D and pure D respectively. *charge* is the charge on the molecule *cell_volume* is the estimated cell volume for the molecule *density* is the estimated molecule density Change 1.5.3: drop *Hmass* and *Hsld*. Move *formula* to *labile_formula*. Move *Hnatural* to *formula*.
62598fd70fa83653e46f5424
class Foundation(Stack): <NEW_LINE> <INDENT> def __init__(self, location): <NEW_LINE> <INDENT> self._location = location <NEW_LINE> self._type = None <NEW_LINE> super().__init__() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(super().peek()) if not self.is_empty() else Color.GREEN.value + '-:-' + Color.GREEN.value <NEW_LINE> <DEDENT> def add_card(self, card): <NEW_LINE> <INDENT> if super().is_empty(): <NEW_LINE> <INDENT> if card.get_number() == 1: <NEW_LINE> <INDENT> card.set_location(self._location) <NEW_LINE> super().add_card(card) <NEW_LINE> self._type = card.get_cardsuit() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("The first card must be an ACE of any suit") <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if card.get_cardsuit() is self._type and card.get_number() == super().peek().get_number() + 1: <NEW_LINE> <INDENT> card.set_location(self._location) <NEW_LINE> super().add_card(card) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("Cannot add card for different type or unmatched number") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_location(self): <NEW_LINE> <INDENT> return self._location <NEW_LINE> <DEDENT> def set_location(self, location): <NEW_LINE> <INDENT> self._location = location <NEW_LINE> <DEDENT> def add_cards(self, cards): <NEW_LINE> <INDENT> raise NotImplementedError("Cannot take card from foundation")
This class is sometimes called as winner deck, because it will hold stack of cards that will be moved from either Tableau or Cells. All cards must be placed according to its suit and number sequentially. The number of foundation object will depend on the number of suits that will be created in the beginning, with the exception of if the number of suits is less than 4, the number of foundation will only still be 4.
62598fd79f28863672818b1b
class SilacData(BaseData): <NEW_LINE> <INDENT> mass = FloatField() <NEW_LINE> ratio = FloatField(index=True) <NEW_LINE> rsquared = FloatField(index=True) <NEW_LINE> charge = IntegerField(index=True) <NEW_LINE> segment = IntegerField(index=True) <NEW_LINE> num_ms2 = IntegerField(index=True)
Holds actual experimental data.
62598fd78a349b6b4368677d
class VNFSvcKeystoneContext(wsgi.Middleware): <NEW_LINE> <INDENT> @webob.dec.wsgify <NEW_LINE> def __call__(self, req): <NEW_LINE> <INDENT> user_id = req.headers.get('X_USER_ID') <NEW_LINE> if not user_id: <NEW_LINE> <INDENT> LOG.debug(_("X_USER_ID is not found in request")) <NEW_LINE> return webob.exc.HTTPUnauthorized() <NEW_LINE> <DEDENT> tenant_id = req.headers.get('X_PROJECT_ID') <NEW_LINE> roles = [r.strip() for r in req.headers.get('X_ROLES', '').split(',')] <NEW_LINE> tenant_name = req.headers.get('X_PROJECT_NAME') <NEW_LINE> user_name = req.headers.get('X_USER_NAME') <NEW_LINE> req_id = req.environ.get(request_id.ENV_REQUEST_ID) <NEW_LINE> auth_token = req.headers.get('X_AUTH_TOKEN', req.headers.get('X_STORAGE_TOKEN')) <NEW_LINE> ctx = context.Context(user_id, tenant_id, roles=roles, user_name=user_name, tenant_name=tenant_name, request_id=req_id, auth_token=auth_token) <NEW_LINE> req.environ['vnfsvc.context'] = ctx <NEW_LINE> return self.application
Make a request context from keystone headers.
62598fd7656771135c489bae
class OmptInstallation(CMakeInstallation): <NEW_LINE> <INDENT> def __init__(self, sources, target_arch, target_os, compilers): <NEW_LINE> <INDENT> if sources['ompt'] == 'download-tr6': <NEW_LINE> <INDENT> sources['ompt'] = [ 'http://tau.uoregon.edu/LLVM-openmp-ompt-tr6.tar.gz', 'http://fs.paratools.com/tau-mirror/LLVM-openmp-ompt-tr6.tar.gz' ] <NEW_LINE> <DEDENT> elif sources['ompt'] == 'download-tr4': <NEW_LINE> <INDENT> sources['ompt'] = [ 'http://tau.uoregon.edu/LLVM-openmp-0.2.tar.gz', 'https://fs.paratools.com/tau-mirror/LLVM-openmp-0.2.tar.gz' ] <NEW_LINE> <DEDENT> super().__init__('ompt', 'ompt', sources, target_arch, target_os, compilers, REPOS, None, LIBRARIES, HEADERS) <NEW_LINE> <DEDENT> def cmake(self, flags): <NEW_LINE> <INDENT> flags.extend(['-DCMAKE_C_COMPILER=' + self.compilers[CC].unwrap().absolute_path, '-DCMAKE_CXX_COMPILER=' + self.compilers[CXX].unwrap().absolute_path, '-DCMAKE_C_FLAGS=-fPIC', '-DCMAKE_CXX_FLAGS=-fPIC', '-DCMAKE_BUILD_TYPE=Release', '-DCMAKE_DISABLE_FIND_PACKAGE_CUDA:BOOL=TRUE']) <NEW_LINE> return super().cmake(flags) <NEW_LINE> <DEDENT> def make(self, flags): <NEW_LINE> <INDENT> super().make(flags + ['libomp-needed-headers']) <NEW_LINE> return super().make(flags)
Encapsulates an OMPT installation.
62598fd7ad47b63b2c5a7d8e
class DeleteUserInputSet(InputSet): <NEW_LINE> <INDENT> def set_APIKey(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'APIKey', value) <NEW_LINE> <DEDENT> def set_ID(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'ID', value)
An InputSet with methods appropriate for specifying the inputs to the DeleteUser Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
62598fd7fbf16365ca7945fc
class BBoxCanvasController: <NEW_LINE> <INDENT> debug_output = Output(layout={'border': '1px solid black'}) <NEW_LINE> def __init__(self, gui: BBoxCanvasGUI, state: BBoxCanvasState): <NEW_LINE> <INDENT> self._state = state <NEW_LINE> self._gui = gui <NEW_LINE> state.subscribe(self._draw_all_bbox, 'bbox_coords') <NEW_LINE> state.subscribe(self._draw_image, 'image_path') <NEW_LINE> pub.subscribe(self._draw_all_bbox, f'{state.root_topic}.coord_changed') <NEW_LINE> self.bbox = BoundingBox() <NEW_LINE> <DEDENT> @debug_output.capture(clear_output=True) <NEW_LINE> def _draw_all_bbox(self, bbox_coords: List[BboxCoordinate]): <NEW_LINE> <INDENT> self._gui.clear_layer(BBoxLayer.box) <NEW_LINE> self._gui.clear_layer(BBoxLayer.highlight) <NEW_LINE> self._gui.clear_layer(BBoxLayer.drawing) <NEW_LINE> all_bbox = [] <NEW_LINE> for bbox_coord in bbox_coords: <NEW_LINE> <INDENT> coord = list(asdict(bbox_coord).values()) <NEW_LINE> coord = coords_scaled(coord, self._state.image_scale) <NEW_LINE> all_bbox.append(BboxCoordinate(*coord)) <NEW_LINE> <DEDENT> self.bbox.draw( canvas=self._gui.multi_canvas[BBoxLayer.box], coords=all_bbox, clear=False ) <NEW_LINE> <DEDENT> def clear_all_bbox(self): <NEW_LINE> <INDENT> self._gui.clear_layer(BBoxLayer.box) <NEW_LINE> self._gui.clear_layer(BBoxLayer.highlight) <NEW_LINE> self._gui.clear_layer(BBoxLayer.drawing) <NEW_LINE> self._state.set_quietly('bbox_coords', []) <NEW_LINE> <DEDENT> @debug_output.capture(clear_output=True) <NEW_LINE> def _draw_image(self, image_path: str): <NEW_LINE> <INDENT> self.clear_all_bbox() <NEW_LINE> image_width, image_height, scale = draw_img( self._gui.multi_canvas[BBoxLayer.image], image_path, clear=True, has_border=self._gui.has_border ) <NEW_LINE> self._state.set_quietly('image_width', image_width) <NEW_LINE> self._state.set_quietly('image_height', image_height) <NEW_LINE> self._state.image_scale = scale <NEW_LINE> self._gui.im_name_box.value = Path(image_path).name
Handle the GUI and state communication
62598fd7377c676e912f7019
class FollowManager(GFKManager): <NEW_LINE> <INDENT> def for_object(self, instance): <NEW_LINE> <INDENT> content_type = ContentType.objects.get_for_model(instance).pk <NEW_LINE> return self.filter(content_type=content_type, object_id=instance.pk) <NEW_LINE> <DEDENT> def is_following(self, user, instance): <NEW_LINE> <INDENT> if not user or user.is_anonymous(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> queryset = self.for_object(instance) <NEW_LINE> return queryset.filter(user=user).exists() <NEW_LINE> <DEDENT> def are_friends(self, user1, user2): <NEW_LINE> <INDENT> return self.is_following(user1, user2) and self.is_following(user2, user1) <NEW_LINE> <DEDENT> def followers(self, actor): <NEW_LINE> <INDENT> return [follow.user for follow in self.filter( content_type=ContentType.objects.get_for_model(actor), object_id=actor.pk ).select_related('user')] <NEW_LINE> <DEDENT> def following(self, user, *models): <NEW_LINE> <INDENT> qs = self.filter(user=user) <NEW_LINE> if len(models): <NEW_LINE> <INDENT> qs = qs.filter(content_type__in=( ContentType.objects.get_for_model(model) for model in models) ) <NEW_LINE> <DEDENT> return [follow.follow_object for follow in qs.fetch_generic_relations()] <NEW_LINE> <DEDENT> def friends(self, actor, **kwargs): <NEW_LINE> <INDENT> q = Q() <NEW_LINE> followers = self.filter(content_type = ContentType.objects.get_for_model(actor), object_id = actor.pk).select_related('user') <NEW_LINE> followings = self.following(actor, User) <NEW_LINE> if len(followings): <NEW_LINE> <INDENT> friends = followers.filter(user__in=(followings)).exclude(user=actor) <NEW_LINE> return [friend.user for friend in friends.select_related('user')] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return list() <NEW_LINE> <DEDENT> <DEDENT> def followers_without_friends(self, actor, **kwargs): <NEW_LINE> <INDENT> followers = self.filter(content_type = ContentType.objects.get_for_model(actor), object_id = actor.pk).select_related('user') <NEW_LINE> followers_without_friends = followers.exclude(user__in=self.friends(actor)).exclude(user=actor) <NEW_LINE> return [follower.user for follower in followers_without_friends] <NEW_LINE> <DEDENT> def followings_without_friends(self, user): <NEW_LINE> <INDENT> qs = self.filter(user=user) <NEW_LINE> qs = qs.exclude(object_id__in=(friend.id for friend in self.friends(user))).exclude(object_id=user.id) <NEW_LINE> return [follow.follow_object for follow in qs.fetch_generic_relations()]
Manager for Follow model.
62598fd78a349b6b4368677e
class Meta(SelfClosingTag): <NEW_LINE> <INDENT> tag = 'meta'
renders meta tag
62598fd7656771135c489bb0
class GitRepoInstaller(KVMBaseInstaller, base_installer.GitRepoInstaller): <NEW_LINE> <INDENT> pass
Installer that deals with source code on Git repositories
62598fd73617ad0b5ee06687
class Individual(AbstractIndividual, Accessible): <NEW_LINE> <INDENT> ex = models.ForeignKey( IndividualEx, related_name="individuals", null=True, on_delete=models.CASCADE ) <NEW_LINE> group = models.ForeignKey( Group, on_delete=models.CASCADE, related_name="individuals" ) <NEW_LINE> name = models.CharField(max_length=CHAR_MAX_LENGTH) <NEW_LINE> characteristica_all_normed = models.ManyToManyField("Characteristica", related_name="individuals", through="IndividualCharacteristica") <NEW_LINE> study = models.ForeignKey('studies.Study', on_delete=models.CASCADE, related_name="individuals") <NEW_LINE> objects = IndividualManager() <NEW_LINE> @property <NEW_LINE> def source(self): <NEW_LINE> <INDENT> return self.ex.source <NEW_LINE> <DEDENT> @property <NEW_LINE> def image(self): <NEW_LINE> <INDENT> return self.ex.image <NEW_LINE> <DEDENT> @property <NEW_LINE> def _characteristica_normed(self): <NEW_LINE> <INDENT> return self.characteristica.filter(normed=True) <NEW_LINE> <DEDENT> @property <NEW_LINE> def _characteristica_all_normed(self): <NEW_LINE> <INDENT> _characteristica_normed = self._characteristica_normed <NEW_LINE> this_measurements = _characteristica_normed.exclude( measurement_type__info_node__name__in=ADDITIVE_CHARACTERISTICA).values_list("measurement_type", flat=True) <NEW_LINE> return (_characteristica_normed | self.group._characteristica_all_normed.exclude( measurement_type__in=this_measurements)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def group_indexing(self): <NEW_LINE> <INDENT> return self.group.name <NEW_LINE> <DEDENT> @property <NEW_LINE> def characteristica_measurements(self): <NEW_LINE> <INDENT> return [characteristica.measurement_type for characteristica in self.characteristica_all_normed.all()] <NEW_LINE> <DEDENT> @property <NEW_LINE> def characteristica_choices(self): <NEW_LINE> <INDENT> return {characteristica.measurement_type: characteristica.choice for characteristica in self.characteristica_all_normed.all()}
Single individual in data base. This does not contain any mappings are splits any more.
62598fd78a349b6b43686780
class PrivateLinkResourcesListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[PrivateLinkResource]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, value: Optional[List["PrivateLinkResource"]] = None, next_link: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(PrivateLinkResourcesListResult, self).__init__(**kwargs) <NEW_LINE> self.value = value <NEW_LINE> self.next_link = next_link
Result of the List private link resources operation. :param value: A collection of private link resources. :type value: list[~azure.mgmt.servicebus.v2021_01_01_preview.models.PrivateLinkResource] :param next_link: A link for the next page of private link resources. :type next_link: str
62598fd8fbf16365ca794600
class Ctrl(object): <NEW_LINE> <INDENT> info = logger.info <NEW_LINE> warn = logger.warn <NEW_LINE> error = logger.error <NEW_LINE> debug = logger.debug <NEW_LINE> def __init__(self, trials, current_trial=None): <NEW_LINE> <INDENT> if trials is None: <NEW_LINE> <INDENT> self.trials = Trials() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.trials = trials <NEW_LINE> <DEDENT> self.current_trial = current_trial <NEW_LINE> <DEDENT> def checkpoint(self, r=None): <NEW_LINE> <INDENT> assert self.current_trial in self.trials._trials <NEW_LINE> if r is not None: <NEW_LINE> <INDENT> self.current_trial['result'] = r <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def attachments(self): <NEW_LINE> <INDENT> return self.trials.trial_attachments(trial=self.current_trial) <NEW_LINE> <DEDENT> def inject_results(self, specs, results, miscs, new_tids=None): <NEW_LINE> <INDENT> trial = self.current_trial <NEW_LINE> assert trial is not None <NEW_LINE> num_news = len(specs) <NEW_LINE> assert len(specs) == len(results) == len(miscs) <NEW_LINE> if new_tids is None: <NEW_LINE> <INDENT> new_tids = self.trials.new_trial_ids(num_news) <NEW_LINE> <DEDENT> new_trials = self.trials.source_trial_docs(tids=new_tids, specs=specs, results=results, miscs=miscs, sources=[trial]) <NEW_LINE> for t in new_trials: <NEW_LINE> <INDENT> t['state'] = JOB_STATE_DONE <NEW_LINE> <DEDENT> return self.trials.insert_trial_docs(new_trials)
Control object for interruptible, checkpoint-able evaluation
62598fd826238365f5fad0a5
class RunMetrics(dict): <NEW_LINE> <INDENT> _metrics = [] <NEW_LINE> ignore = "|".join(["tmp", "tx", "-split", "log"]) <NEW_LINE> reignore = re.compile(ignore) <NEW_LINE> def __init__(self, log=None): <NEW_LINE> <INDENT> self["_id"] = uuid4().hex <NEW_LINE> self["entity_type"] = self.entity_type() <NEW_LINE> self["name"] = None <NEW_LINE> self["creation_time"] = None <NEW_LINE> self["modification_time"] = None <NEW_LINE> self.files = [] <NEW_LINE> self.path=None <NEW_LINE> self.log = LOG <NEW_LINE> if log: <NEW_LINE> <INDENT> self.log = log <NEW_LINE> <DEDENT> <DEDENT> def entity_type(self): <NEW_LINE> <INDENT> return type(self).__name__ <NEW_LINE> <DEDENT> def get_db_id(self): <NEW_LINE> <INDENT> return self["_id"] <NEW_LINE> <DEDENT> def to_json(self): <NEW_LINE> <INDENT> return json.dumps(self) <NEW_LINE> <DEDENT> def parse(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def _collect_files(self): <NEW_LINE> <INDENT> if not self.path: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not os.path.exists(self.path): <NEW_LINE> <INDENT> raise IOError <NEW_LINE> <DEDENT> self.files = [] <NEW_LINE> for root, dirs, files in os.walk(self.path): <NEW_LINE> <INDENT> if re.search(self.reignore, root): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self.files = self.files + [os.path.join(root, x) for x in files] <NEW_LINE> <DEDENT> <DEDENT> def filter_files(self, pattern, filter_fn=None): <NEW_LINE> <INDENT> def filter_function(f): <NEW_LINE> <INDENT> return re.search(pattern, f) != None <NEW_LINE> <DEDENT> if not filter_fn: <NEW_LINE> <INDENT> filter_fn = filter_function <NEW_LINE> <DEDENT> return [x for x in filter(filter_fn, self.files)]
Generic Run class
62598fd8adb09d7d5dc0aabc
class KMSKey(KMSBase): <NEW_LINE> <INDENT> def __init__(self, ctx_node, resource_id=None, client=None, logger=None): <NEW_LINE> <INDENT> KMSBase.__init__(self, ctx_node, resource_id, client, logger) <NEW_LINE> self.type_name = RESOURCE_TYPE <NEW_LINE> <DEDENT> @property <NEW_LINE> def properties(self): <NEW_LINE> <INDENT> params = {KEY_ID: self.resource_id} <NEW_LINE> try: <NEW_LINE> <INDENT> resource = self.client.describe_key(**params) <NEW_LINE> <DEDENT> except ClientError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return resource.get(KEY_META, {}) <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> @property <NEW_LINE> def status(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def create(self, params): <NEW_LINE> <INDENT> return self.make_client_call('create_key', params) <NEW_LINE> <DEDENT> def enable(self, params): <NEW_LINE> <INDENT> self.logger.debug('Enabling %s with parameters: %s' % (self.type_name, params)) <NEW_LINE> res = self.client.enable_key(**params) <NEW_LINE> self.logger.debug('Response: %s' % res) <NEW_LINE> return res <NEW_LINE> <DEDENT> def disable(self, params): <NEW_LINE> <INDENT> self.logger.debug('Disabling %s with parameters: %s' % (self.type_name, params)) <NEW_LINE> res = self.client.disable_key(**params) <NEW_LINE> self.logger.debug('Response: %s' % res) <NEW_LINE> return res <NEW_LINE> <DEDENT> def delete(self, params=None): <NEW_LINE> <INDENT> self.logger.debug('Deleting %s with parameters: %s' % (self.type_name, params)) <NEW_LINE> self.client.schedule_key_deletion(**params)
AWS KMS Key interface
62598fd89f28863672818b1f
class TipoEntregaAddForm(base.AddForm): <NEW_LINE> <INDENT> grok.context(INavigationRoot) <NEW_LINE> grok.name('add-tipoentrega') <NEW_LINE> grok.require('cmf.ManagePortal') <NEW_LINE> schema = ITipoEntrega <NEW_LINE> klass = TipoEntrega <NEW_LINE> label = _(u'Adicionar Tipo de Entrega') <NEW_LINE> description = _(u'Formulário de cadastro de um tipo de entrega.') <NEW_LINE> @log <NEW_LINE> def createAndAdd(self, data): <NEW_LINE> <INDENT> tipoentrega = TipoEntrega() <NEW_LINE> tipoentrega.nome = data['nome'] <NEW_LINE> session = Session() <NEW_LINE> session.add(tipoentrega) <NEW_LINE> session.flush()
Formulário de cadastro de um tipo de entrega.
62598fd8ad47b63b2c5a7d96
@base.Hidden <NEW_LINE> @base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA) <NEW_LINE> class VpcAccess(base.Group): <NEW_LINE> <INDENT> def Filter(self, context, args): <NEW_LINE> <INDENT> del context, args <NEW_LINE> base.EnableUserProjectQuota()
Manage VPC Access Service resources. Commands for managing Google VPC Access Service resources.
62598fd8fbf16365ca794604
class Store(Base, Store, Explicit): <NEW_LINE> <INDENT> pass
`Store` wrapper facilitating access to the request (and the Zope session).
62598fd8fbf16365ca794606
class Widget(EventHandler): <NEW_LINE> <INDENT> event_mask = EventMask.Exposure <NEW_LINE> override_redirect = False <NEW_LINE> def __init__(self, client=None, manager=None, config=None, **kwargs): <NEW_LINE> <INDENT> self.client = client <NEW_LINE> self.manager = manager <NEW_LINE> self.conn = manager.conn <NEW_LINE> self.screen = manager.screen <NEW_LINE> self.config = config <NEW_LINE> self.window = self.create_window(**kwargs) <NEW_LINE> <DEDENT> def create_window(self, parent=None, geometry=None, event_mask=None, override_redirect=None): <NEW_LINE> <INDENT> self.parent = parent if parent else self.screen.root <NEW_LINE> self.geometry = geometry <NEW_LINE> self.window = self.conn.generate_id() <NEW_LINE> self.conn.core.CreateWindow(self.screen.root_depth, self.window, self.parent, geometry.x, geometry.y, geometry.width, geometry.height, geometry.border_width, WindowClass.InputOutput, self.screen.root_visual, CW.OverrideRedirect | CW.EventMask, [(override_redirect if override_redirect is not None else self.override_redirect), (event_mask if event_mask is not None else self.event_mask)]) <NEW_LINE> self.manager.register_window_handler(self.window, self) <NEW_LINE> return self.window <NEW_LINE> <DEDENT> def map(self): <NEW_LINE> <INDENT> self.conn.core.MapWindow(self.window) <NEW_LINE> <DEDENT> def unmap(self): <NEW_LINE> <INDENT> self.conn.core.UnmapWindow(self.window) <NEW_LINE> <DEDENT> def destroy(self): <NEW_LINE> <INDENT> self.conn.core.DestroyWindow(self.window) <NEW_LINE> <DEDENT> def configure(self, geometry): <NEW_LINE> <INDENT> self.geometry = geometry <NEW_LINE> self.conn.core.ConfigureWindow(self.window, ConfigWindow.Width, [geometry.width]) <NEW_LINE> return geometry <NEW_LINE> <DEDENT> def draw(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @handler(ExposeEvent) <NEW_LINE> def handle_expose(self, event): <NEW_LINE> <INDENT> if event.count == 0: <NEW_LINE> <INDENT> self.draw() <NEW_LINE> <DEDENT> <DEDENT> @handler((KeyPressEvent, KeyReleaseEvent)) <NEW_LINE> def handle_key_press(self, event): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> action = self.config.key_bindings[event] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise UnhandledEvent(event) <NEW_LINE> <DEDENT> action(self, event) <NEW_LINE> <DEDENT> @handler((ButtonPressEvent, ButtonReleaseEvent)) <NEW_LINE> def handle_button_press(self, event): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> action = self.config.button_bindings[event] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise UnhandledEvent(event) <NEW_LINE> <DEDENT> action(self, event)
A manager for a window, possibly on behalf of some client.
62598fd850812a4eaa620e86
class AgentCreator: <NEW_LINE> <INDENT> def __init__(self, agent_class, agent_kwargs, crs="epsg:3857"): <NEW_LINE> <INDENT> if "unique_id" in agent_kwargs: <NEW_LINE> <INDENT> agent_kwargs.remove("unique_id") <NEW_LINE> warnings.warn("Unique_id should not be in the agent_kwargs") <NEW_LINE> <DEDENT> self.agent_class = agent_class <NEW_LINE> self.agent_kwargs = agent_kwargs <NEW_LINE> self.crs = crs <NEW_LINE> <DEDENT> def create_agent(self, shape, unique_id): <NEW_LINE> <INDENT> if not isinstance(shape, BaseGeometry): <NEW_LINE> <INDENT> raise TypeError("Shape must be a Shapely Geometry") <NEW_LINE> <DEDENT> new_agent = self.agent_class( unique_id=unique_id, shape=shape, **self.agent_kwargs ) <NEW_LINE> return new_agent <NEW_LINE> <DEDENT> def from_GeoDataFrame(self, gdf, unique_id="index", set_attributes=True): <NEW_LINE> <INDENT> if unique_id != "index": <NEW_LINE> <INDENT> gdf = gdf.set_index(unique_id) <NEW_LINE> <DEDENT> gdf = gdf.to_crs(self.crs) <NEW_LINE> agents = list() <NEW_LINE> for index, row in gdf.iterrows(): <NEW_LINE> <INDENT> shape = row.geometry <NEW_LINE> new_agent = self.create_agent(shape=shape, unique_id=index) <NEW_LINE> if set_attributes: <NEW_LINE> <INDENT> for col in row.index: <NEW_LINE> <INDENT> if not col == "geometry": <NEW_LINE> <INDENT> setattr(new_agent, col, row[col]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> agents.append(new_agent) <NEW_LINE> <DEDENT> return agents <NEW_LINE> <DEDENT> def from_file(self, filename, unique_id="index", set_attributes=True): <NEW_LINE> <INDENT> gdf = gpd.read_file(filename) <NEW_LINE> agents = self.from_GeoDataFrame( gdf, unique_id=unique_id, set_attributes=set_attributes ) <NEW_LINE> return agents <NEW_LINE> <DEDENT> def from_GeoJSON(self, GeoJSON, unique_id="index", set_attributes=True): <NEW_LINE> <INDENT> if type(GeoJSON) is str: <NEW_LINE> <INDENT> gj = json.loads(GeoJSON) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> gj = GeoJSON <NEW_LINE> <DEDENT> gdf = gpd.GeoDataFrame.from_features(gj) <NEW_LINE> gdf.crs = "epsg:4326" <NEW_LINE> agents = self.from_GeoDataFrame( gdf, unique_id=unique_id, set_attributes=set_attributes ) <NEW_LINE> return agents
Create GeoAgents from files, GeoDataFrames, GeoJSON or Shapely objects.
62598fd8956e5f7376df5921
class DbtAssetResource: <NEW_LINE> <INDENT> def __init__(self, asset_key_prefix: List[str]): <NEW_LINE> <INDENT> self._asset_key_prefix = asset_key_prefix <NEW_LINE> <DEDENT> def _get_metadata(self, result: Dict[str, Any]) -> List[MetadataEntry]: <NEW_LINE> <INDENT> return [ MetadataEntry.float(value=result["execution_time"], label="Execution Time (seconds)") ] <NEW_LINE> <DEDENT> def get_asset_materializations(self, dbt_output: DbtOutput) -> List[AssetMaterialization]: <NEW_LINE> <INDENT> ret = [] <NEW_LINE> for result in dbt_output.result["results"]: <NEW_LINE> <INDENT> if result["status"] != "success": <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> unique_id = result["unique_id"] <NEW_LINE> asset_key = AssetKey(self._asset_key_prefix + unique_id.split(".")) <NEW_LINE> ret.append( AssetMaterialization( description=f"dbt node: {unique_id}", metadata_entries=self._get_metadata(result), asset_key=asset_key, ) ) <NEW_LINE> <DEDENT> return ret
This class defines a resource that is capable of producing a list of AssetMaterializations from a DbtOutput. It has one public function, get_asset_materializations(), which finds all the generated models in the dbt output and produces corresponding asset materializations. Putting this logic in a resource makes it easier to swap out between modes. You probably want your local testing / development pipelines to produce different assets than your production pipelines, as they will ideally be writing to different tables (with different dbt profiles).
62598fd8ab23a570cc2d5012
class Cross_section(): <NEW_LINE> <INDENT> def __init__(self,ax): <NEW_LINE> <INDENT> self.ax = ax <NEW_LINE> <DEDENT> def create_data(self, directory, data_list): <NEW_LINE> <INDENT> f = open(directory, newline="") <NEW_LINE> reader = csv.reader(f, quoting=csv.QUOTE_NONNUMERIC) <NEW_LINE> for row in reader: <NEW_LINE> <INDENT> rowlist = [] <NEW_LINE> for value in row: <NEW_LINE> <INDENT> rowlist.append(float(value)) <NEW_LINE> <DEDENT> data_list.append(rowlist) <NEW_LINE> <DEDENT> f.close() <NEW_LINE> <DEDENT> def set_extents(self, raw_data, x_data, y_data): <NEW_LINE> <INDENT> ypoint = 1 <NEW_LINE> while ypoint <= len(raw_data[0]): <NEW_LINE> <INDENT> ypoints = 1 <NEW_LINE> ylist = [] <NEW_LINE> while ypoints <= len(raw_data[0]): <NEW_LINE> <INDENT> ylist.append(ypoint) <NEW_LINE> ypoints += 1 <NEW_LINE> <DEDENT> y_data.append(ylist) <NEW_LINE> ypoint += 1 <NEW_LINE> <DEDENT> xpoint = 1 <NEW_LINE> xlist = [] <NEW_LINE> while xpoint <= len(raw_data): <NEW_LINE> <INDENT> xlist.append(xpoint) <NEW_LINE> xpoint += 1 <NEW_LINE> <DEDENT> xpoints = 1 <NEW_LINE> while xpoints <= len(raw_data): <NEW_LINE> <INDENT> x_data.append(xlist) <NEW_LINE> xpoints += 1 <NEW_LINE> <DEDENT> <DEDENT> def limit_surface(self, surface, new_surface, upper_limit, lower_limit): <NEW_LINE> <INDENT> for i in surface: <NEW_LINE> <INDENT> list = [] <NEW_LINE> for j in i: <NEW_LINE> <INDENT> if j >= upper_limit: <NEW_LINE> <INDENT> j = np.nan <NEW_LINE> <DEDENT> if j <= lower_limit: <NEW_LINE> <INDENT> j = np.nan <NEW_LINE> <DEDENT> list.append(j) <NEW_LINE> <DEDENT> new_surface.append(list) <NEW_LINE> <DEDENT> <DEDENT> def set_axes(self, x, y, z): <NEW_LINE> <INDENT> self.ax.set_xlim(min(x), max(x)) <NEW_LINE> self.ax.set_ylim(min(y), max(y)) <NEW_LINE> self.ax.set_zlim(min(z), max(z)) <NEW_LINE> <DEDENT> def define_limits(self, data, limits): <NEW_LINE> <INDENT> for i in data: <NEW_LINE> <INDENT> for j in i: <NEW_LINE> <INDENT> limits.append(j)
Provide methods to build and slice 3D surfaces. Build 3D surfaces within a matplotlib figure. Take in user-specified X, Y, and Z coordinates and slice the data along upper and lower limits. Assign NaN to any data outside of these limits.
62598fd8099cdd3c63675683
class LibraryResultPage(TypedItem): <NEW_LINE> <INDENT> type_name = "LibraryResultPage" <NEW_LINE> title = Field() <NEW_LINE> link = Field() <NEW_LINE> browse_url = Field() <NEW_LINE> document_type = Field()
Stores individual results pages, for debugging
62598fd850812a4eaa620e87
class ProductTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.form_submission = PackageScanFormSubmission(VOUCHER_JSON) <NEW_LINE> <DEDENT> def test_voucher_qr_codes(self): <NEW_LINE> <INDENT> self.assertEqual(['test'], self.form_submission.get_qr_codes()) <NEW_LINE> <DEDENT> def test_package_qr_codes(self): <NEW_LINE> <INDENT> self.form_submission = PackageScanFormSubmission(PACKAGE_JSON) <NEW_LINE> self.assertEqual(set(['test']), self.form_submission.get_qr_codes()) <NEW_LINE> <DEDENT> def test_gps(self): <NEW_LINE> <INDENT> self.assertEqual(VOUCHER_JSON['gps'], self.form_submission.gps) <NEW_LINE> <DEDENT> def test_no_gps(self): <NEW_LINE> <INDENT> data = VOUCHER_JSON.copy() <NEW_LINE> data.pop('gps') <NEW_LINE> self.form_submission = PackageScanFormSubmission(data) <NEW_LINE> self.assertFalse(hasattr(self.form_submission, 'gps')) <NEW_LINE> <DEDENT> def test_submission_time(self): <NEW_LINE> <INDENT> self.assertEqual( VOUCHER_JSON['_submission_time'], self.form_submission._submission_time.strftime(SUBMITTED_AT_FORMAT)) <NEW_LINE> <DEDENT> def test_get_latitude(self): <NEW_LINE> <INDENT> value = float(VOUCHER_JSON['gps'].split(' ')[0]) <NEW_LINE> self.assertEqual(value, self.form_submission.get_lat()) <NEW_LINE> <DEDENT> def test_get_latitude_no_gps(self): <NEW_LINE> <INDENT> data = VOUCHER_JSON.copy() <NEW_LINE> data.pop('gps') <NEW_LINE> self.form_submission = PackageScanFormSubmission(data) <NEW_LINE> self.assertIsNone(self.form_submission.get_lat()) <NEW_LINE> <DEDENT> def test_get_longitude(self): <NEW_LINE> <INDENT> value = float(VOUCHER_JSON['gps'].split(' ')[1]) <NEW_LINE> self.assertEqual(value, self.form_submission.get_lng()) <NEW_LINE> <DEDENT> def test_get_altitude(self): <NEW_LINE> <INDENT> value = float(VOUCHER_JSON['gps'].split(' ')[2]) <NEW_LINE> self.assertEqual(value, self.form_submission.get_altitude()) <NEW_LINE> <DEDENT> def test_get_accuracy(self): <NEW_LINE> <INDENT> value = float(VOUCHER_JSON['gps'].split(' ')[3]) <NEW_LINE> self.assertEqual(value, self.form_submission.get_accuracy()) <NEW_LINE> <DEDENT> def test_get_gps_data_out_of_range(self): <NEW_LINE> <INDENT> self.assertIsNone(self.form_submission.get_gps_data(100))
Basic test for Product object.
62598fd8c4546d3d9def7527
class DDQNAgent(object): <NEW_LINE> <INDENT> def __init__(self, state_size, action_size, buffer_size=BUFFER_SIZE, batch_size=BATCH_SIZE, gamma=GAMMA, tau=TAU, lr=LR, update_every=UPDATE_EVERY, seed=0): <NEW_LINE> <INDENT> self.state_size = state_size <NEW_LINE> self.action_size = action_size <NEW_LINE> self.buffer_size = buffer_size <NEW_LINE> self.batch_size = batch_size <NEW_LINE> self.gamma = gamma <NEW_LINE> self.tau = tau <NEW_LINE> self.lr = lr <NEW_LINE> self.update_every = update_every <NEW_LINE> self.seed = seed <NEW_LINE> self.rng = np.random.RandomState(seed) <NEW_LINE> self.qnetwork_local = QNetwork(state_size, action_size, seed).to(device) <NEW_LINE> self.qnetwork_target = QNetwork(state_size, action_size, seed).to(device) <NEW_LINE> self.optimizer = optim.Adam(self.qnetwork_local.parameters(), lr=LR) <NEW_LINE> self.memory = ReplayBuffer(action_size, self.buffer_size, self.batch_size, seed) <NEW_LINE> self.t_step = 0 <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> self.t_step = (self.t_step + 1) % self.update_every <NEW_LINE> if self.t_step == 0: <NEW_LINE> <INDENT> if len(self.memory) > self.batch_size: <NEW_LINE> <INDENT> experiences = self.memory.sample() <NEW_LINE> self.learn(experiences, self.gamma) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def act(self, state, eps=0.): <NEW_LINE> <INDENT> state = torch.from_numpy(state).float().unsqueeze(0).to(device) <NEW_LINE> self.qnetwork_local.eval() <NEW_LINE> with torch.no_grad(): <NEW_LINE> <INDENT> action_values = self.qnetwork_local(state) <NEW_LINE> <DEDENT> self.qnetwork_local.train() <NEW_LINE> if self.rng.random() > eps: <NEW_LINE> <INDENT> return np.argmax(action_values.cpu().data.numpy()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.rng.choice(np.arange(self.action_size)) <NEW_LINE> <DEDENT> <DEDENT> def learn(self, experiences, gamma): <NEW_LINE> <INDENT> states, actions, rewards, next_states, dones = experiences <NEW_LINE> outputs = self.qnetwork_local(states).gather(1, actions) <NEW_LINE> Q_targets = self.qnetwork_target(next_states).detach().max(1, keepdim=True)[0] <NEW_LINE> targets = rewards + gamma * Q_targets * (1 - dones) <NEW_LINE> self.optimizer.zero_grad() <NEW_LINE> loss = nn.MSELoss(reduction='sum') <NEW_LINE> output = loss(outputs, targets) <NEW_LINE> output.backward() <NEW_LINE> self.optimizer.step() <NEW_LINE> self.soft_update(self.qnetwork_local, self.qnetwork_target, self.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)
Double DQN agent. Interacts with and learns from the environment.
62598fd83617ad0b5ee06691
class QuestionModel(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.db = questions <NEW_LINE> if len(self.db) == 0: <NEW_LINE> <INDENT> self.id = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.id = len(self.db)+1 <NEW_LINE> <DEDENT> <DEDENT> def save(self): <NEW_LINE> <INDENT> parser.parse_args() <NEW_LINE> data = { 'id': self.id, 'title': request.json.get('title'), 'question':request.json.get('question'), 'dateposted': datetime.datetime.utcnow() } <NEW_LINE> self.db.append(data) <NEW_LINE> return self.id <NEW_LINE> <DEDENT> def get_all(self): <NEW_LINE> <INDENT> return self.db <NEW_LINE> <DEDENT> def find(self, question_id): <NEW_LINE> <INDENT> for question in self.db: <NEW_LINE> <INDENT> if question['id'] == question_id: <NEW_LINE> <INDENT> return question <NEW_LINE> <DEDENT> <DEDENT> return "question does not exist" <NEW_LINE> <DEDENT> def delete(self, question): <NEW_LINE> <INDENT> self.db.remove(question) <NEW_LINE> return "deleted" <NEW_LINE> <DEDENT> def edit_question(self, question): <NEW_LINE> <INDENT> question['question'] = request.json.get('question') <NEW_LINE> return "updated" <NEW_LINE> <DEDENT> def edit_question_title(self, question): <NEW_LINE> <INDENT> parser_edit_title.parse_args() <NEW_LINE> question['title'] = request.json.get('title') <NEW_LINE> return "updated" <NEW_LINE> <DEDENT> def edit_quest(self, question): <NEW_LINE> <INDENT> parser_edit_question.parse_args() <NEW_LINE> question['question'] = request.json.get('question') <NEW_LINE> return "updated"
Class with methods to perform CRUD operations on the DB
62598fd826238365f5fad0ad
class TestOpenFlowController(unittest.TestCase): <NEW_LINE> <INDENT> @mock.patch("ryu.controller.controller.CONF") <NEW_LINE> def _test_ssl(self, this_dir, port, conf_mock): <NEW_LINE> <INDENT> conf_mock.ofp_ssl_listen_port = port <NEW_LINE> conf_mock.ofp_listen_host = "127.0.0.1" <NEW_LINE> conf_mock.ca_certs = None <NEW_LINE> conf_mock.ctl_cert = os.path.join(this_dir, 'cert.crt') <NEW_LINE> conf_mock.ctl_privkey = os.path.join(this_dir, 'cert.key') <NEW_LINE> c = controller.OpenFlowController() <NEW_LINE> c() <NEW_LINE> <DEDENT> def test_ssl(self): <NEW_LINE> <INDENT> this_dir = os.path.dirname(sys.modules[__name__].__file__) <NEW_LINE> saved_exception = None <NEW_LINE> try: <NEW_LINE> <INDENT> ssl_version = ssl.PROTOCOL_TLS <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> ssl_version = ssl.PROTOCOL_TLSv1 <NEW_LINE> <DEDENT> for i in range(3): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> port = random.randint(5000, 10000) <NEW_LINE> server = hub.spawn(self._test_ssl, this_dir, port) <NEW_LINE> hub.sleep(1) <NEW_LINE> client = hub.StreamClient(("127.0.0.1", port), timeout=5, ssl_version=ssl_version) <NEW_LINE> if client.connect() is not None: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> saved_exception = e <NEW_LINE> continue <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> hub.kill(server) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.fail("Failed to connect: " + str(saved_exception))
Test cases for OpenFlowController
62598fd8283ffb24f3cf3dcb
class ValueIterationAgent(ValueEstimationAgent): <NEW_LINE> <INDENT> def __init__(self, mdp, discount = 0.9, iterations = 100): <NEW_LINE> <INDENT> self.mdp = mdp <NEW_LINE> self.discount = discount <NEW_LINE> self.iterations = iterations <NEW_LINE> self.values = util.Counter() <NEW_LINE> self.runValueIteration() <NEW_LINE> <DEDENT> def runValueIteration(self): <NEW_LINE> <INDENT> for i in range(self.iterations): <NEW_LINE> <INDENT> val = util.Counter() <NEW_LINE> for state in self.mdp.getStates(): <NEW_LINE> <INDENT> if not self.mdp.isTerminal(state): <NEW_LINE> <INDENT> optimalval = -9999999999 <NEW_LINE> actions = self.mdp.getPossibleActions(state) <NEW_LINE> for action in actions: <NEW_LINE> <INDENT> qvalue = self.computeQValueFromValues(state, action) <NEW_LINE> if qvalue >= optimalval: <NEW_LINE> <INDENT> optimalval = qvalue <NEW_LINE> <DEDENT> <DEDENT> val[state] = optimalval <NEW_LINE> <DEDENT> <DEDENT> self.values = val <NEW_LINE> <DEDENT> <DEDENT> def getValue(self, state): <NEW_LINE> <INDENT> return self.values[state] <NEW_LINE> <DEDENT> def computeQValueFromValues(self, state, action): <NEW_LINE> <INDENT> qvalue = 0 <NEW_LINE> transitions = self.mdp.getTransitionStatesAndProbs(state,action) <NEW_LINE> for i in transitions: <NEW_LINE> <INDENT> qvalue += i[1] * ( self.mdp.getReward(state,action,i[0]) + self.discount * self.getValue(i[0])) <NEW_LINE> <DEDENT> return qvalue <NEW_LINE> <DEDENT> def computeActionFromValues(self, state): <NEW_LINE> <INDENT> if self.mdp.isTerminal(state): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> actions = self.mdp.getPossibleActions(state) <NEW_LINE> optimalval = -9999999999 <NEW_LINE> bestaction = 0 <NEW_LINE> if len(actions) == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> for action in actions: <NEW_LINE> <INDENT> qvalue = self.computeQValueFromValues(state, action) <NEW_LINE> if qvalue >= optimalval: <NEW_LINE> <INDENT> optimalval = qvalue <NEW_LINE> bestaction = action <NEW_LINE> <DEDENT> <DEDENT> return bestaction <NEW_LINE> <DEDENT> def getPolicy(self, state): <NEW_LINE> <INDENT> return self.computeActionFromValues(state) <NEW_LINE> <DEDENT> def getAction(self, state): <NEW_LINE> <INDENT> return self.computeActionFromValues(state) <NEW_LINE> <DEDENT> def getQValue(self, state, action): <NEW_LINE> <INDENT> return self.computeQValueFromValues(state, action)
* Please read learningAgents.py before reading this.* A ValueIterationAgent takes a Markov decision process (see mdp.py) on initialization and runs value iteration for a given number of iterations using the supplied discount factor.
62598fd87cff6e4e811b5f74
class Character: <NEW_LINE> <INDENT> def __init__(self, dir_path, rotation=0): <NEW_LINE> <INDENT> self.dir_path = dir_path <NEW_LINE> self.rotation = rotation <NEW_LINE> self._cache = {} <NEW_LINE> <DEDENT> def sample(self, num_images): <NEW_LINE> <INDENT> names = [f for f in os.listdir(self.dir_path) if f.endswith('.png')] <NEW_LINE> random.shuffle(names) <NEW_LINE> images = [] <NEW_LINE> for name in names[:num_images]: <NEW_LINE> <INDENT> images.append(self._read_image(os.path.join(self.dir_path, name))) <NEW_LINE> <DEDENT> return images <NEW_LINE> <DEDENT> def _read_image(self, path): <NEW_LINE> <INDENT> if path in self._cache: <NEW_LINE> <INDENT> return self._cache[path] <NEW_LINE> <DEDENT> with open(path, 'rb') as in_file: <NEW_LINE> <INDENT> img = Image.open(in_file).resize((28, 28)).rotate(self.rotation) <NEW_LINE> self._cache[path] = np.array(img).astype('float32') <NEW_LINE> return self._cache[path]
A single character class.
62598fd8c4546d3d9def7528
class UUIDUserAdmin(UserAdmin): <NEW_LINE> <INDENT> fieldsets = ( (None, {'fields': ('username', 'password')}), ('Personal info', {'fields': ('name', 'short_name')}), ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), ('Important dates', {'fields': ('last_login', 'date_joined')}), ) <NEW_LINE> list_display = ('username', 'name', 'short_name', 'is_staff') <NEW_LINE> search_fields = ('username', 'name', 'short_name')
Handle a UUIDUser-based User model properly in the admin.
62598fd8377c676e912f7020
class Database: <NEW_LINE> <INDENT> def __init__(self, db_name): <NEW_LINE> <INDENT> self.db_name = name <NEW_LINE> <DEDENT> def create_database(): <NEW_LINE> <INDENT> mycursor.execute(CREATE_DB.format(DB_NAME)) <NEW_LINE> print("Database {} created!".format(DB_NAME)) <NEW_LINE> <DEDENT> def create_tables(): <NEW_LINE> <INDENT> mycursor.execute("USE {}".format(DB_NAME)) <NEW_LINE> for table_name in TABLES: <NEW_LINE> <INDENT> table_description = TABLES[table_name] <NEW_LINE> try: <NEW_LINE> <INDENT> print("Creating table ({}) ".format(table_name), end="") <NEW_LINE> mycursor.execute(table_description) <NEW_LINE> <DEDENT> except mysql.connector.Error as err: <NEW_LINE> <INDENT> print(err.msg)
op project Openfoodfacts database
62598fd8656771135c489bbe
class Element(Base): <NEW_LINE> <INDENT> def __init__(self, name, bucket, parent, content): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.bucket = bucket <NEW_LINE> self.parent = parent <NEW_LINE> self.content = content <NEW_LINE> if parent is None: <NEW_LINE> <INDENT> self.path = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.path = parent.path[:] <NEW_LINE> self.path.append(self.name) <NEW_LINE> <DEDENT> self._action = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def action(self): <NEW_LINE> <INDENT> return self._action <NEW_LINE> <DEDENT> @property <NEW_LINE> def level(self): <NEW_LINE> <INDENT> parent = self.parent <NEW_LINE> res = 0 <NEW_LINE> while parent is not None: <NEW_LINE> <INDENT> parent = parent.parent <NEW_LINE> res += 1 <NEW_LINE> <DEDENT> return res <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_node(self): <NEW_LINE> <INDENT> return isinstance(self, Node) <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_file(self): <NEW_LINE> <INDENT> return isinstance(self, File) <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_dir(self): <NEW_LINE> <INDENT> return isinstance(self, Directory) <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_attr(self): <NEW_LINE> <INDENT> return isinstance(self, Attribute) <NEW_LINE> <DEDENT> def ls(self, *args, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @property <NEW_LINE> def type(self): <NEW_LINE> <INDENT> return self.__class__.__name__ <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return txt_type(self.name)
The Element class.
62598fd8adb09d7d5dc0aac6