Python get operations
49 Python code examples are found related to "
get operations".
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: workflow_ops.py From ontask_b with MIT License | 6 votes |
def get_operations_context(workflow: models.Workflow) -> Dict: """Create the context to render the operations page. :param workflow: Workflow being manipulated. :return: Dictionary with the context. """ return { 'workflow': workflow, 'attribute_table': AttributeTable([ {'id': idx, 'name': key, 'value': kval} for idx, (key, kval) in enumerate(sorted( workflow.attributes.items()))], orderable=False, ), 'share_table': WorkflowShareTable( workflow.shared.values('email', 'id').order_by('email'), ), 'unique_columns': workflow.get_unique_columns(), }
Example 2
Source File: ops.py From keras-lambda with MIT License | 6 votes |
def get_operations(self): """Return the list of operations in the graph. You can modify the operations in place, but modifications to the list such as inserts/delete have no effect on the list of operations known to the graph. This method may be called concurrently from multiple threads. Returns: A list of Operations. """ if self._finalized: return list(self._nodes_by_id.values()) with self._lock: return list(self._nodes_by_id.values())
Example 3
Source File: managers.py From allianceauth with GNU General Public License v2.0 | 6 votes |
def get_fleetup_operations(cls): url = "{}/Operations/{}".format(cls.BASE_URL, cls.GROUP_ID) foperations = cls.get_endpoint(url) if foperations is None: return None return {row["StartString"]: {"subject": row["Subject"], "start": timezone.make_aware( datetime.strptime(row["StartString"], "%Y-%m-%d %H:%M:%S"), cls.TZ), "end": timezone.make_aware( datetime.strptime(row["EndString"], "%Y-%m-%d %H:%M:%S"), cls.TZ), "operation_id": row["OperationId"], "location": row["Location"], "location_info": row["LocationInfo"], "details": row["Details"], "url": row["Url"], "doctrine": row["Doctrines"], "organizer": row["Organizer"]} for row in foperations["Data"]}
Example 4
Source File: clrtype.py From unity-python with MIT License | 6 votes |
def get_dynamic_operations_field(): if ClrClass.dynamic_operations_field: return ClrClass.dynamic_operations_field python_context = clr.GetCurrentRuntime().GetLanguage(PythonContext) dynamic_operations = DynamicOperations(python_context) typegen = Snippets.Shared.DefineType( "DynamicOperationsHolder" + str(hash(python_context)), object, True, False) typebld = typegen.TypeBuilder typebld.DefineField( "DynamicOperations", DynamicOperations, FieldAttributes.Public | FieldAttributes.Static) new_type = typebld.CreateType() ClrClass.dynamic_operations_field = new_type.GetField("DynamicOperations") ClrClass.dynamic_operations_field.SetValue(None, dynamic_operations) return ClrClass.dynamic_operations_field
Example 5
Source File: websocket.py From cate with MIT License | 6 votes |
def get_operations(self, registry=None) -> List[dict]: """ Get registered operations. :return: JSON-serializable list of data sources, sorted by name. """ registry = registry or OP_REGISTRY op_list = [] for op_name, op_reg in registry.op_registrations.items(): if op_reg.op_meta_info.header.get('deprecated') or op_name.startswith('_'): # do not list deprecated and private operations continue op_json_dict = op_reg.op_meta_info.to_json_dict() op_json_dict['name'] = op_name op_json_dict['inputs'] = [dict(name=name, **props) for name, props in op_json_dict['inputs'].items() if not (props.get('deprecated') or props.get('context'))] op_json_dict['outputs'] = [dict(name=name, **props) for name, props in op_json_dict['outputs'].items() if not props.get('deprecated')] op_list.append(op_json_dict) return sorted(op_list, key=lambda op: op['name'])
Example 6
Source File: events.py From polyaxon with Apache License 2.0 | 6 votes |
def get_archived_operations_events( event_kind: str, run_uuids: Set[str], event_names: Set[str], orient: str = V1Events.ORIENT_CSV, check_cache: bool = True, ) -> Dict[str, List]: events = {} for run_uuid in run_uuids: run_events = await get_archived_operation_events( run_uuid=run_uuid, event_kind=event_kind, event_names=event_names, orient=orient, check_cache=check_cache, ) events[run_uuid] = run_events return events
Example 7
Source File: hot_resource.py From heat-translator with Apache License 2.0 | 6 votes |
def get_all_operations(node): operations = {} for operation in node.interfaces: operations[operation.name] = operation # workaround bug in the parser base_type = HotResource.get_base_type_str(node.type_definition) if base_type in policy_type: return operations node_type = node.type_definition while True: type_operations = HotResource._get_interface_operations_from_type( node_type, node, 'Standard') type_operations.update(operations) operations = type_operations if node_type.parent_type is not None: node_type = node_type.parent_type else: return operations
Example 8
Source File: permutation.py From Cirq with Apache License 2.0 | 6 votes |
def get_logical_operations(operations: 'cirq.OP_TREE', initial_mapping: Dict[ops.Qid, ops.Qid] ) -> Iterable['cirq.Operation']: """Gets the logical operations specified by the physical operations and initial mapping. Args: operations: The physical operations. initial_mapping: The initial mapping of physical to logical qubits. Raises: ValueError: A non-permutation physical operation acts on an unmapped qubit. """ mapping = initial_mapping.copy() for op in cast(Iterable['cirq.Operation'], ops.flatten_op_tree(operations)): if (isinstance(op, ops.GateOperation) and isinstance(op.gate, PermutationGate)): op.gate.update_mapping(mapping, op.qubits) else: for q in op.qubits: if mapping.get(q) is None: raise ValueError( f'Operation {op} acts on unmapped qubit {q}.') yield op.transform_qubits(mapping.__getitem__)
Example 9
Source File: util.py From pythonflow with Apache License 2.0 | 6 votes |
def get_slow_operations(self, num_operations=None): """ Get the slowest operations. Parameters ---------- num_operations : int or None Maximum number of operations to return or `None` Returns ------- times : collections.OrderedDict Mapping of execution times keyed by operations. """ items = list(sorted(self.times.items(), key=lambda x: x[1], reverse=True)) if num_operations is not None: items = items[:num_operations] return collections.OrderedDict(items)
Example 10
Source File: 0002_auto_20150507_1708.py From django-andablog with BSD 2-Clause "Simplified" License | 6 votes |
def get_operations(): """ This will break things if you upgrade Django to 1.8 having already applied this migration in 1.7. Since this is for a demo site it doesn't really matter (simply blow away the DB if you want to go to 1.8) Our demo site is a unusual in that we want to run it's tests (for integration testing) in multiple Django versions. Typical sites don't have to worry about that sort of thing. """ compatible = (1, 8) <= DJANGO_VERSION < (1, 10) if not compatible: return [] return [ migrations.AlterField( model_name='user', name='groups', field=models.ManyToManyField(related_query_name='user', related_name='user_set', to='auth.Group', blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', verbose_name='groups'), ), migrations.AlterField( model_name='user', name='last_login', field=models.DateTimeField(null=True, verbose_name='last login', blank=True), ), ]
Example 11
Source File: introspection.py From aws_list_all with MIT License | 6 votes |
def get_listing_operations(service, region=None, selected_operations=()): """Return a list of API calls which (probably) list resources created by the user in the given service (in contrast to AWS-managed or default resources)""" client = get_client(service, region) operations = [] for operation in client.meta.service_model.operation_names: if not any(operation.startswith(prefix) for prefix in VERBS_LISTINGS): continue op_model = client.meta.service_model.operation_model(operation) required_members = op_model.input_shape.required_members if op_model.input_shape else [] required_members = [m for m in required_members if m != 'MaxResults'] if required_members: continue if operation in PARAMETERS_REQUIRED.get(service, []): continue if operation in AWS_RESOURCE_QUERIES.get(service, []): continue if operation in NOT_RESOURCE_DESCRIPTIONS.get(service, []): continue if operation in DEPRECATED_OR_DISALLOWED.get(service, []): continue if selected_operations and operation not in selected_operations: continue operations.append(operation) return operations
Example 12
Source File: models.py From packone with Apache License 2.0 | 5 votes |
def get_ready_operations(self): return self.get_operation_model().objects.filter( started_time__isnull=True, completed_time__isnull=True, status=OPERATION_STATUS.running.value, target=self ).exclude(target__deleting=True, manual=False).order_by("pk")
Example 13
Source File: OperationStack.py From Uranium with GNU Lesser General Public License v3.0 | 5 votes |
def getOperations(self): """Get the list of operations in the stack. The end of the list represents the more recent operations. :return: A list of the operations on the stack, in order. """ with self._lock: return self._operations
Example 14
Source File: graph_interface.py From mesh with Apache License 2.0 | 5 votes |
def get_num_operations(self): """The number of operations in the graph. Returns: an integer, the number of operations. """ return len(self._operations)
Example 15
Source File: main.py From professional-services with Apache License 2.0 | 5 votes |
def get_finished_stt_operations(job_entry: dict, credentials: google.auth.credentials.Credentials) -> dict: """Sends HTTP request to get responses from STT. Args: job_entry: Dict in format {'file': file1, 'id': id1} credentials: google.auth.Credentials of Oauth2 holding credentials Returns: Dict response from STT API """ log_message = f'Starting get_finished_stt_operations for {job_entry}' logging.info(log_message) endpoint = f'https://speech.googleapis.com/v1/operations/{job_entry["id"]}' token = credentials.token headers = { 'Authorization': f'Bearer {token}', 'Content-Type': 'application/json; charset=utf-8' } response_json = None try: response = requests.get(endpoint, headers=headers) response.raise_for_status() response_json = response.json() logging.info(f'Response json: {response_json}') except HTTPError as http_err: logging.error(f'HTTP error occurred: {http_err}') except Exception as err: logging.error(f'Python Exception occurred: {err}') return response_json
Example 16
Source File: main.py From python-compat-runtime with Apache License 2.0 | 5 votes |
def GetOperations(self, active=False, limit=100): """Obtain a list of operation, ordered by last_updated.""" query = utils.DatastoreAdminOperation.all() if active: query.filter('status = ', utils.DatastoreAdminOperation.STATUS_ACTIVE) else: query.filter('status IN ', [ utils.DatastoreAdminOperation.STATUS_COMPLETED, utils.DatastoreAdminOperation.STATUS_FAILED, utils.DatastoreAdminOperation.STATUS_ABORTED]) operations = query.fetch(max(10000, limit) if limit else 1000) operations = sorted(operations, key=operator.attrgetter('last_updated'), reverse=True) return operations[:limit]
Example 17
Source File: subset.py From PVGeo with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_operations(): """Returns the extraction operation methods as callable objects in a dictionary """ ops = dict( underneath=ExtractTopography._underneath, intersection=ExtractTopography._intersection, ) return ops
Example 18
Source File: models.py From packone with Apache License 2.0 | 5 votes |
def get_next_operations(self): return self.get_operation_model().objects.filter( target=self, started_time__isnull=True, completed_time__isnull=True, status__in=[OPERATION_STATUS.waiting.value,OPERATION_STATUS.running.value], ).exclude(target__deleting=True, manual=False).order_by("pk")
Example 19
Source File: file_api.py From Apfell with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_current_operations_files_meta(request, user): if user['auth'] not in ['access_token', 'apitoken']: abort(status_code=403, message="Cannot access via Cookies. Use CLI or access via JS in browser") if user['current_operation'] != "": try: query = await db_model.operation_query() operation = await db_objects.get(query, name=user['current_operation']) query = await db_model.filemeta_query() files = await db_objects.prefetch(query.where(FileMeta.operation == operation), Task.select(), Command.select(), Callback.select()) except Exception as e: return json({'status': 'error', 'error': 'failed to get files'}) return json([f.to_json() for f in files if not "screenshots" in f.path ]) else: return json({"status": 'error', 'error': 'must be part of an active operation'})
Example 20
Source File: models.py From packone with Apache License 2.0 | 5 votes |
def get_running_operations(self): return self.get_operation_model().objects.filter( started_time__isnull=False, completed_time__isnull=True, target=self ).order_by("started_time")
Example 21
Source File: Scheduled.py From pyArubaCloud with Apache License 2.0 | 5 votes |
def get_scheduled_operations(self, start, end): get_shed_ops_request = { "GetScheduledOperations": { "EndDate": end, "StartDate": start } } scheme = self.gen_def_json_scheme('GetScheduledOperations', method_fields=get_shed_ops_request) json_obj = self.call_method_post('GetScheduledOperations', json_scheme=scheme) return json_obj
Example 22
Source File: audi_services.py From audi_connect_ha with MIT License | 5 votes |
def get_operations_list(self, vin: str): self._api.use_token(self.vwToken) return await self._api.get( "https://mal-1a.prd.ece.vwg-connect.com/api/rolesrights/operationlist/v3/vehicles/" + vin.upper() )
Example 23
Source File: stuff.py From ir with Mozilla Public License 2.0 | 5 votes |
def get_operations_dataframe(filepath=None): if not filepath: filepath = OPERATIONS_FILEPATH try: df = pd.read_csv(filepath, delim_whitespace=True, header=None, parse_dates=[3], dayfirst=True) except: return pd.DataFrame(columns=todas_as_colunas()) try: df.columns = colunas_obrigatorias() except: columns = colunas_obrigatorias() columns.insert(6, 'id_carteira') df.columns = columns df = df.drop(['id_carteira'], axis=1) if len(df): df['data'] = df['data'].dt.date df['valor'] = df.apply(lambda row: calcula_valor(row.qtd, row.preco), axis=1) df['qtd_ajustada'] = df.apply(lambda row: calculate_add(row), axis=1) else: return pd.DataFrame(columns=todas_as_colunas()) return df
Example 24
Source File: apidoc.py From flask-apispec with MIT License | 5 votes |
def get_operations(self, rule, resource): return { method: getattr(resource, method.lower()) for method in rule.methods if hasattr(resource, method.lower()) }
Example 25
Source File: executor.py From Cirq with Apache License 2.0 | 5 votes |
def get_operations(self, indices: Sequence[LogicalIndex], qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE': index_set = frozenset(indices) if index_set in self.index_set_to_gates: gates = self.index_set_to_gates.pop(index_set) index_to_qubit = dict(zip(indices, qubits)) for gate_indices, gate in sorted(gates.items()): yield gate(*[index_to_qubit[i] for i in gate_indices])
Example 26
Source File: symmetry.py From CatKit with GNU General Public License v3.0 | 5 votes |
def get_symmetry_operations(self, affine=True): """Return the symmetry operations for a given atomic structure. Parameters ---------- affine : bool Whether to return the affine matrix operations. Returns ------- rotations : ndarray (N, 3, 3) Rotation matices of the symmetry operations. translations ndarray (N, 3) Translation vector components of the symmetry operations. affine_matrices ndarray (N, 4, 4) Affine matrix operations, combinations of the rotation and translation with ones along the diagonal. """ rotations = self.data['rotations'][1:] translations = self.data['translations'][1:] if affine: affine_matrices = np.zeros((rotations.shape[0], 4, 4)) affine_matrices[:, :3, :3] = rotations affine_matrices[:, -1, :3] = translations affine_matrices[:, -1, -1] = 1 return affine_matrices return rotations, translations
Example 27
Source File: client_factory.py From azure-devops-cli-extension with MIT License | 5 votes |
def get_operations_client(self): """get_operations_client. Gets the 5.1 version of the OperationsClient :rtype: :class:`<OperationsClient> <azure.devops.v5_1.operations.operations_client.OperationsClient>` """ return self._connection.get_client('azure.devops.v5_1.operations.operations_client.OperationsClient')
Example 28
Source File: lux.py From lux with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_operations(self, spec): """Get all API operations for a given path The path is represented by the router attribute :param spec: instance of OpenAPI where to add the path info """ for method in METHODS: handle = getattr(self.router, method, None) if not hasattr(handle, '__call__'): continue info = None if hasattr(handle, 'rule_method'): info = handle.rule_method.parameters.get('openapi') doc = load_yaml_from_docstring(handle.__doc__) op = ApiOperation(doc, method, extra_info=info) if not op.doc and op.method == 'head': get = self.operations.get('get') if get: doc = get.copy() if 'summary' in doc: doc['summary'] = 'Same as get but does not return body' doc.pop('description', None) else: doc['description'] = ( 'Same as get but does not return body' ) op.doc = doc else: continue self.operations[method] = op.add_to_path(self, spec)
Example 29
Source File: module.py From BoomER with GNU General Public License v3.0 | 5 votes |
def get_all_operations(self): return list(self.get_multiple_parameter_operations())\ + list(self.get_parameter_operations())\ + list(self.get_single_operations()) # If a module needs more operations, use the following functions # Remember!! You enter new operations after calling up super in the init function. # Operation without arguments
Example 30
Source File: add_product_partition_tree.py From googleads-python-lib with Apache License 2.0 | 5 votes |
def GetOperations(self): """Returns the set of mutate operations needed to create the current tree. Returns: The set of operations """ return self.operations
Example 31
Source File: datastore.py From fuzz-lightyear with Apache License 2.0 | 5 votes |
def get_non_vulnerable_operations() -> Dict[str, Optional[str]]: """ This is a global dictionary containing non-vulnerable operations. Operation ids are keys. Tags are values, if the user provided them. If you don't care about the operation's tag, you can get just the excluded operations with `get_excluded_operations().keys()`. :rtype: dict(str => str) """ return {}
Example 32
Source File: datastore.py From fuzz-lightyear with Apache License 2.0 | 5 votes |
def get_excluded_operations() -> Dict[str, Optional[str]]: """ This is a global dictionary containing fuzzing-excluded operations. Operation id's are keys. Tags are values, if the user provided them. If you don't care about the operation's tag, you can get just the excluded operations with `get_excluded_operations().keys()`. :rtype: dict(str => str) """ return {}
Example 33
Source File: operation_api.py From Apfell with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_all_operations(request, user): if user['auth'] not in ['access_token', 'apitoken']: abort(status_code=403, message="Cannot access via Cookies. Use CLI or access via JS in browser") # we already get this information populated as part of our user authentication output = [] if user['admin']: query = await db_model.operation_query() db_ops = await db_objects.execute(query) operations = [o.name for o in db_ops] else: operations = user['operations'] for op in operations: # for each operation you're a member of, get all members and the admin name query = await db_model.operation_query() operation = await db_objects.get(query, name=op) data = operation.to_json() data['members'] = [] added_users = [] query = await db_model.operatoroperation_query() operationmap = await db_objects.execute(query.where(OperatorOperation.operation == operation)) for map in operationmap: o = map.operator if o.username not in added_users: data['members'].append({**o.to_json(), 'base_disabled_commands': map.base_disabled_commands.name if map.base_disabled_commands is not None else map.base_disabled_commands}) added_users.append(o.username) output.append(data) return json(output)
Example 34
Source File: utils.py From snn_toolbox with MIT License | 5 votes |
def get_layer_synaptic_operations(spiketrains_b_l, fanout): """ Return total number of synaptic operations in the layer for a batch of samples. Parameters ---------- spiketrains_b_l: ndarray Batch of spiketrains of a layer. Shape: (batch_size, layer_shape) fanout: Union[int, ndarray] Number of outgoing connections per neuron. Can be a single integer, or an array of the same shape as the layer, if the fanout varies from neuron to neuron (as is the case in convolution layers with stride > 1). Returns ------- layer_ops: int The total number of operations in the layer for a batch of samples. """ if np.isscalar(fanout): return np.array([np.count_nonzero(s) for s in spiketrains_b_l]) * \ fanout elif hasattr(fanout, 'shape'): # For conv layers with stride > 1 return np.array([np.sum(fanout[s != 0]) for s in spiketrains_b_l]) else: raise TypeError("The 'fanout' parameter should either be integer or " "ndarray.")
Example 35
Source File: stub.py From dsub with Apache License 2.0 | 5 votes |
def get_operations(self): return self._operations # 3) Methods that return information. # Meant to be called by the code under test, they rely on the fake # state set via group (2) above.
Example 36
Source File: ops.py From blendercam with GNU General Public License v2.0 | 5 votes |
def getChainOperations(chain): '''return chain operations, currently chain object can't store operations directly due to blender limitations''' chop = [] for cho in chain.operations: for so in bpy.context.scene.cam_operations: if so.name == cho.name: chop.append(so) return chop
Example 37
Source File: Home_Core.py From termite-data-server with BSD 3-Clause "New" or "Revised" License | 5 votes |
def GetOperations(self, server): operations = [ { 'value' : 'dataset', 'name' : 'Upload a new dataset' } ] self.configs.update({ 'AvailableOperations' : operations }) return operations
Example 38
Source File: agent.py From qpid-dispatch with Apache License 2.0 | 5 votes |
def get_operations(self, request): type = self.requested_type(request) return (OK, dict((t, et.operations) for t, et in dict_iteritems(self._schema.entity_types) if not type or type.name == t))
Example 39
Source File: interfaces.py From incubator-ariatosca with Apache License 2.0 | 5 votes |
def get_inherited_operations(context, presentation): """ Returns our operation definitions added on top of those of our parent, if we have one (recursively). Allows overriding all aspects of parent operations except input data types. """ # Get operations from parent parent = presentation._get_parent(context) operations = get_inherited_operations(context, parent) if parent is not None else OrderedDict() # Add/merge our operations our_operations = presentation.operations # OperationDefinition merge_operation_definitions(context, operations, our_operations, presentation._name, presentation, 'type') for operation in operations.itervalues(): operation._reset_method_cache() return operations # # InterfaceDefinition #
Example 40
Source File: checks.py From visma with GNU General Public License v3.0 | 4 votes |
def getOperationsExpression(variables, tokens): """[Returns a list of operations which can be performed on given equation tokens Arguments: variables {list} -- list of Function(Variable/Constant) tokens tokens {list} -- list of function tokens Returns: operations {list} -- list of operations which can be performed """ operations = [] for i, token in enumerate(tokens): if isinstance(token, Binary): if token.value in ['*', '/']: prev = False nxt = False if i != 0: if isinstance(tokens[i - 1], Function): prev = True if i + 1 < len(tokens): if isinstance(tokens[i + 1], Variable) or isinstance(tokens[i + 1], Constant) or isinstance(tokens[i - 1], Expression): nxt = True if nxt and prev: op = token.value if op not in operations: operations.append(op) elif isinstance(token, Expression): ops = getOperationsExpression([], token.tokens) for op in ops: if op not in operations: operations.append(op) for i, variable in enumerate(variables): if isinstance(variable, Constant): if len(variable.value) > 1: count = 0 opCount = 0 ops = [] for j in range(len(variable.value)): if variable.after[j] in ['+', '-', ''] and variable.before[j] in ['+', '-']: count += 1 opCount += 1 if not (variable.before[j] in ops): ops.append(variable.before[j]) elif variable.after[j] in ['+', '-', ''] and variable.before[j] in ['+', '-', '']: count += 1 if count > 1: for op in ops: if op not in operations: operations.append(op) elif isinstance(variable, Variable): if len(variable.power) > 1: count = 0 ops = [] power = [] opCount = 0 for j in range(len(variable.power)): if variable.after[j] in ['+', '-', ''] and variable.before[j] in ['+', '-']: count += 1 opCount += 1 if not (variable.before[j] in ops): ops.append(variable.before[j]) power.append(variable.power[j]) elif variable.after[j] in ['+', '-', ''] and variable.before[j] in ['+', '-', '']: count += 1 if count > 1 and opCount > 0: for i, op in enumerate(ops): if not (op in operations): operations.append(op) elif isinstance(variable, Expression): ops = getOperationsExpression(variable.value, variable.tokens) for op in ops: if op not in operations: operations.append(op) return operations
Example 41
Source File: members.py From byro with Apache License 2.0 | 4 votes |
def get_operations(self): """Return a list of tuples. Each one: + internal name/prefix of the form + Title of the form + A callable returning a Form instance + (Ordered)Dict of submit buttons {button_name: button_text} + Callback function for successful submit of the form """ member = self.get_object() now_ = now() retval = [] # Add Leave forms for all current memberships def _create_ms_leave_form(*args, **kwargs): f = self.membership_form_class(instance=ms, *args, **kwargs) f.fields["start"].disabled = True f.fields["interval"].disabled = True f.fields["amount"].disabled = True f.fields["end"].required = True f.fields["end"].widget.attrs["class"] = "datepicker" return f for ms in member.memberships.all().order_by("-start"): if ms.start <= now_.date() and (not ms.end or ms.end > now_.date()): retval.append( ( "ms_{}_leave".format(ms.pk), _("End membership"), _create_ms_leave_form, {"end": _("End membership")}, lambda *args, **kwargs: self.end_membership( ms, *args, **kwargs ), ) ) # Add account adjustment form retval.append( ( "member_account_adjustment", _("Adjust member account balance"), MemberAccountAdjustmentForm, {"adjust": _("Adjust balance")}, self.adjust_balance, ) ) return retval
Example 42
Source File: cif.py From PyChemia with MIT License | 4 votes |
def get_symmetry_operations(self): ret = [] for x in self.data.keys(): if x.startswith('loop'): for symmetry_label in ["_symmetry_equiv_pos_as_xyz", "_symmetry_equiv_pos_as_xyz_", "_space_group_symop_operation_xyz", "_space_group_symop_operation_xyz_"]: if symmetry_label in self.data[x].keys(): ret = [self.data[x][y] for y in self.data[x].keys() if self.data[x][y] != ''] break if not ret: print(self.data.keys()) for symmetry_label in ["_space_group_IT_number", "_space_group_IT_number_", "_symmetry_Int_Tables_number", "_symmetry_Int_Tables_number_"]: if symmetry_label in self.data.keys(): spg = self.data[symmetry_label] print(spg) break if not ret: print(self.data.keys()) for symmetry_label in ["_symmetry_space_group_name_H-M", "_symmetry_space_group_name_H_M", "_symmetry_space_group_name_H-M_", "_symmetry_space_group_name_H_M_", "_space_group_name_Hall", "_space_group_name_Hall_", "_space_group_name_H-M_alt", "_space_group_name_H-M_alt_", "_symmetry_space_group_name_hall", "_symmetry_space_group_name_hall_", "_symmetry_space_group_name_h-m", "_symmetry_space_group_name_h-m_"]: if symmetry_label in self.data.keys(): spg = self.data[symmetry_label] print(spg) break return ret
Example 43
Source File: keylog_api.py From Apfell with BSD 3-Clause "New" or "Revised" License | 4 votes |
def get_operations_keystrokes(request, user): if user['auth'] not in ['access_token', 'apitoken']: abort(status_code=403, message="Cannot access via Cookies. Use CLI or access via JS in browser") try: query = await db_model.operation_query() operation = await db_objects.get(query, name=user['current_operation']) query = await db_model.keylog_query() keylogs = await db_objects.execute(query.where(Keylog.operation == operation).order_by(Keylog.timestamp)) except Exception as e: print(e) return json({'status': 'error', 'error': 'failed to find current operation'}) # default configuration values grouping = "host" output = {} # if you POST to this method, you can configure the grouping options if request.method == "POST": data = request.json if "grouping" in data and data['grouping'] is not None: grouping = data['grouping'] # this can be by host or user # we will make our higher-level grouping by the log.task.callback.host that our keylogs came from query = await db_model.callback_query() for log in keylogs: if grouping == "host": group = log.task.callback.host if group not in output: output[group] = {} if log.user not in output[group]: output[group][log.user] = {} if log.window not in output[group][log.user]: output[group][log.user][log.window] = {'keylogs': []} callback = await db_objects.get(query, id=log.task.callback) output[group][log.user][log.window]['keylogs'].append({**log.to_json(), "callback": callback.to_json()}) elif grouping == "user": group = log.user callback = await db_objects.get(query, id=log.task.callback) if group not in output: output[group] = {} if callback.host not in output[group]: output[group][callback.host] = {} if log.window not in output[group][callback.host]: output[group][callback.host][log.window] = {'keylogs': []} output[group][callback.host][log.window]['keylogs'].append({**log.to_json(), "callback": callback.to_json()}) else: return json({'status': 'error', 'error': 'grouping type not recognized'}) return json({'status': 'success', 'grouping': grouping, "keylogs": output})