code stringlengths 1 18.2k |
|---|
def get_log_lookup_session(self, proxy): """Gets the ``OsidSession`` associated with the log lookup service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.logging.LogLookupSession) - a ``LogLookupSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to complete request raise: Unim... |
def get_log_admin_session(self, proxy): """Gets the ``OsidSession`` associated with the log administrative service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.logging.LogAdminSession) - a ``LogAdminSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to complete request raise:... |
def get_log_hierarchy_session(self, proxy): """Gets the ``OsidSession`` associated with the log hierarchy service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.logging.LogHierarchySession) - a ``LogHierarchySession`` for logs raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to complet... |
def get_log_hierarchy_design_session(self, proxy): """Gets the ``OsidSession`` associated with the log hierarchy design service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.logging.LogHierarchyDesignSession) - a ``HierarchyDesignSession`` for logs raise: NullArgument - ``proxy`` is ``null`` raise: OperationFai... |
def _add_opt_argument(self, opt_args, arg_parser): """Add an argument to an instantiated parser. :param opt_args: ``dict`` :param arg_parser: ``object`` """ option_args = opt_args.copy() groups = option_args.pop('groups', None) if groups: self._add_group( parser=arg_parser, groups=groups, option_args=option_args ) excl... |
def _setup_parser(self): """Setup a configuration parser. Contains built in ``--system-config`` || ``-SC`` variable which is used to allow a user to set arguments in a configuration file which would then be processed from the "default" section of the provided file, assuming the file exists. :return: ``tuple`` """ # Set... |
description=self.description, epilog=self.epilog) # Setup for the positional Arguments if self.detail is not None: self.detail = '%s\n' % self.detail if 'subparsed_args' in self.arguments: subparser = parser.add_subparsers( title=self.title, metavar=self.detail ) else: subparser = None return parser, subparser, remaini... |
def arg_parser(self, passed_args=None): """Setup argument Parsing. If preset args are to be specified use the ``passed_args`` tuple. :param passed_args: ``list`` :return: ``dict`` """ parser, subpar, remaining_argv = self._setup_parser() if not isinstance(passed_args, list): passed_args = list() # Extend the passed arg... |
as a dict return vars(parser.parse_args(args=passed_args)) |
def start(client, container, interactive=True, stdout=None, stderr=None, stdin=None, **kwargs): """ Present the PTY of the container inside the current process. This is just a wrapper for PseudoTerminal(client, container).start() """ PseudoTerminal(client, container, interactive=interactive, stdout=stdout, stderr=stder... |
def xml_import(self, filepath=None, xml_content=None, markings=None, identifier_ns_uri=None, initialize_importer=True, **kwargs): """ Import an OpenIOC indicator xml (root element 'ioc') from file <filepath> or from a string <xml_content> You can provide: - a list of markings with which all generated Information Object... |
import commands (the class passes all command line arguments to the xml_import function, so without the **kwargs parameter, an error would occur. """ if initialize_importer: # Clear state in case xml_import is used several times, but keep namespace info self.__init__() # Initialize default arguments # '[]' would be mut... |
element of the form # {'id': ... , 'timestamp': ...} # 'elt_name': Element name of top-level element # 'dict_repr': Dictionary representation of XML, minus the embedded objects -- for # those, an 'idref' reference has been generated # 'embedded_objects': List of embedded objects, as dictionary # {"id_and_revision_info"... |
family_info_dict = search_by_re_list(self.RE_LIST_NS_TYPE_FROM_NS_URL,default_ns) if family_info_dict: self.iobject_family_name="%s.mandiant.com" % family_info_dict['family'] self.iobject_family_revision_name=family_info_dict['revision'] # Initialize stack with import_results. # First, the result from the top-level imp... |
def id_and_revision_extractor(self,xml_elt): """ Function for determing an identifier (and, where applicable, timestamp/revision information) for extracted embedded content; to be used for DINGO's xml-import hook 'id_and_revision_extractor'. This function is called - for the top-level node of the XML to be imported. - ... |
is contained in the 'id' attribute of an element; the top-level 'ioc' element carries a timestamp in the 'last-modified' attribute. Note: the xml_elt is an XMLNode defined by the Python libxml2 bindings. If you have never worked with these, have a look at - Mike Kneller's brief intro: http://mikekneller.com/kb/python/l... |
for filling in the 'last-modified' attribute, then # this serves the main purpose of time stamps for our # means: we can find out the latest revision of a # given piece of data. if not timezone.is_aware(naive): aware = timezone.make_aware(naive,timezone.utc) else: aware = naive result['timestamp']= aware return result |
def openioc_embedding_pred(self,parent, child, ns_mapping): """ Predicate for recognizing inlined content in an XML; to be used for DINGO's xml-import hook 'embedded_predicate'. The question this predicate must answer is whether the child should be extracted into a separate object. The function returns either - False (... |
object type as string} Note: the 'parent' and 'child' arguments are XMLNodes as defined by the Python libxml2 bindings. If you have never worked with these, have a look at - Mike Kneller's brief intro: http://mikekneller.com/kb/python/libxml2python/part1 - the functions in django-dingos core.xml_utils module """ # For ... |
of type X). # In OpenIOC, The IndicatorItems have the following form:: # # <IndicatorItem id="b9ef2559-cc59-4463-81d9-52800545e16e" condition="contains"> # <Context document="FileItem" search="FileItem/PEInfo/Sections/Section/Name" type="mir"/> # <Content type="string">.stub</Content> # </IndicatorItem> # # We take the... |
def transformer(self,elt_name,contents): """ The OpenIOC indicator contains the actual observable bits of an indicator in the following form:: <IndicatorItem id="b9ef2559-cc59-4463-81d9-52800545e16e" condition="contains"> <Context document="FileItem" search="FileItem/PEInfo/Sections/Section/Name" type="mir"/> <Content ... |
'IndicatorItem': return (elt_name,contents) else: # We have an indicator item. # We initialize the resulting DingoObjDict result = DingoObjDict() # We initialize the dictionary that will contain the leaf (in the example given # above, that would be the dictionary representing the following bit of # XML:: # # <Name cond... |
structure: set_dict(result,leaf,'set',*search_term) return (document_type,result) |
def reference_handler(self,iobject, fact, attr_info, add_fact_kargs): """ Handler for facts that contain a reference to a fact. See below in the comment regarding the fact_handler_list for a description of the signature of handler functions. As shown below in the handler list, this handler is called when a attribute wi... |
(self.identifier_ns_uri,attr_info['idref']) # We are always able to extract the timestamp from the referencing node, because for OpenIOC, # all references are created by DINGO's generic import, and the import writes the timestamp # information into the created reference. timestamp = attr_info['@timestamp'] # The follow... |
def synthesize_firmware_module_info(modules, module_types): """ Modules are allowed to define attributes on their inputs and outputs that override the values defined in their respective module types. This function takes as input a dictionary of `modules` (mapping module IDs to :class:`~openag.models.FirmwareModule` obj... |
"status_codes" in mod_type: mod_info["status_codes"] = mod_type["status_codes"] # Update the arguments mod_info["arguments"] = process_args( mod_id, mod_info.get("arguments", []), mod_type.get("arguments", []) ) # Update the categories if not "categories" in mod_info: mod_info["categories"] = mod_type.get( "categories"... |
def synthesize_software_module_info(modules, module_types): """ This function takes as input a dictionary of `modules` (mapping module IDs to :class:`~openag.models.SoftwareModule` objects) and a dictionary of `module_types` (mapping module type IDs to :class:`~openag.models.FirmwareModuleType` objects). For each modul... |
mod_id, mod_info.get("parameters", {}), mod_type["parameters"] ) res[mod_id] = mod_info return res |
def process_args(mod_id, args, type_args): """ Takes as input a list of arguments defined on a module and the information about the required arguments defined on the corresponding module type. Validates that the number of supplied arguments is valid and fills any missing arguments with their default values from the mod... |
def process_params(mod_id, params, type_params): """ Takes as input a dictionary of parameters defined on a module and the information about the required parameters defined on the corresponding module type. Validatates that are required parameters were supplied and fills any missing parameters with their default values... |
not defined for module ' '"{}"'.format(param_name, mod_id) ) return res |
def dedupe_by(things, key=None): """ Given an iterator of things and an optional key generation function, return a new iterator of deduped things. Things are compared and de-duped by the key function, which is hash() by default. """ if not key: key = hash index = {key(thing): thing for thing in things} return index.val... |
def make_dir_name_from_url(url): """This function attempts to emulate something like Git's "humanish" directory naming for clone. It's probably not a perfect facimile, but it's close.""" url_path = urlparse(url).path head, tail = os.path.split(url_path) # If tail happens to be empty as in case `/foo/`, use foo. # If we... |
def safe_cpp_var(s): """ Given a string representing a variable, return a new string that is safe for C++ codegen. If string is already safe, will leave it alone. """ s = str(s) # Remove non-word, non-space characters s = re.sub(r"[^\w\s]", '', s) # Replace spaces with _ s = re.sub(r"\s+", '_', s) # Prefix with undersc... |
def booleanise(b): """Normalise a 'stringified' Boolean to a proper Python Boolean. ElasticSearch has a habit of returning "true" and "false" in its JSON responses when it should be returning `true` and `false`. If `b` looks like a stringified Boolean true, return True. If `b` looks like a stringified Boolean false, re... |
def fmt_bytes(bytes, precision=2): """Reduce a large number of `bytes` down to a humanised SI equivalent and return the result as a string with trailing unit abbreviation. """ UNITS = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB'] if bytes == 0: return '0 bytes' log = math.floor(math.log(bytes, 1000)) return "%.*f %s" % (prec... |
def get_index_translog_disable_flush(self): """Return a dictionary showing the position of the 'translog.disable_flush' knob for each index in the cluster. The dictionary will look like this: { "index1": True, # Autoflushing DISABLED "index2": False, # Autoflushing ENABLED "index3": "unknown", # Using default setting (... |
def allocator_disabled(self): """Return a simplified one-word answer to the question, 'Has the automatic shard allocator been disabled for this cluster?' The answer will be one of "disabled" (yes), "enabled" (no), or "unknown". """ state = "unknown" setting_getters = [ lambda s: s['cluster.routing.allocation.disable_al... |
def flushing_disabled(self): """Return a simplified one-word answer to the question, 'Has automatic transaction log flushing been disabled on all indexes in the cluster?' The answer will be one of "disabled" (yes, on all), "enabled" (no, on all), "some" (yes, only on some), or "unknown". """ states = self.get_index_tra... |
def nontruncating_zip(*seqs): """Return a list of tuples, where each tuple contains the i-th element from each of the argument sequences. The returned list is as long as the longest argument sequence. Shorter argument sequences will be represented in the output as None padding elements: nontruncating_zip([1, 2, 3], ['a... |
def pearson(x, y): """ Pearson's correlation implementation without scipy or numpy. :param list x: Dataset x :param list y: Dataset y :return: Population pearson correlation coefficient :rtype: float """ mx = Decimal(mean(x)) my = Decimal(mean(y)) xm = [Decimal(i) - mx for i in x] ym = [Decimal(j) - my for j in y] sx =... |
TODO: Better message raise NoAffinityError("Standard deviation of either " "users' scores is zero") return float(num / den) |
def clean_up_datetime(obj_map): """convert datetime objects to dictionaries for storage""" clean_map = {} for key, value in obj_map.items(): if isinstance(value, datetime.datetime): clean_map[key] = { 'year': value.year, 'month': value.month, 'day': value.day, 'hour': value.hour, 'minute': value.minute, 'second': value... |
def convert_dict_to_datetime(obj_map): """converts dictionary representations of datetime back to datetime obj""" converted_map = {} for key, value in obj_map.items(): if isinstance(value, dict) and 'tzinfo' in value.keys(): converted_map[key] = datetime.datetime(**value) elif isinstance(value, dict): converted_map[key... |
def convert_ids_to_object_ids(obj_map): """converts string representations of _id back to ObjectId obj""" converted_map = {} for key, value in obj_map.items(): if key == '_id': # hacky, but using alias sends back the whole ID string, like # assessment.Item%3A5758326b4a40452d6eee1fa1%40ODL.MIT.EDU # so we have to preser... |
def fix_reserved_word(word, is_module=False): """ Replaces words that may be problematic In particular the term 'type' is used in the osid spec, primarily as an argument parameter where a type is provided to a method. 'type' is a reserved word in python, so we give ours a trailing underscore. If we come across any othe... |
def remove_null_proxy_kwarg(func): """decorator, to remove a 'proxy' keyword argument. For wrapping certain Manager methods""" def wrapper(*args, **kwargs): if 'proxy' in kwargs: # if kwargs['proxy'] is None: del kwargs['proxy'] # else: # raise InvalidArgument('Manager sessions cannot be called with Proxies. Use ProxyM... |
def arguments_not_none(func): """decorator, to check if any arguments are None; raise exception if so""" def wrapper(*args, **kwargs): for arg in args: if arg is None: raise NullArgument() for arg, val in kwargs.items(): if val is None: raise NullArgument() try: return func(*args, **kwargs) except TypeError as ex: if a... |
def handle_simple_sequencing(func): """decorator, deal with simple sequencing cases""" from .assessment import assessment_utilities def wrapper(*args, **kwargs): # re-order these things because have to delete the part after # removing it from the parent sequence map if 'create_assessment_part' in func.__name__: result ... |
def get_provider_manager(osid, runtime=None, proxy=None, local=False): """ Gets the most appropriate provider manager depending on config. If local is True, then don't bother with the runtime/config and try to get the requested service manager directly from the local service implementations known to this mongodb implem... |
is_module=True) + '.managers') manager_name = ''.join((osid.title()).split('_')) + mgr_str manager = getattr(module, manager_name)() except (ImportError, AttributeError): raise OperationFailed() if runtime is not None: manager.initialize(runtime) return manager |
def get_registry(entry, runtime): """Returns a record registry given an entry and runtime""" try: records_location_param_id = Id('parameter:recordsRegistry@mongo') registry = runtime.get_configuration().get_value_by_parameter( records_location_param_id).get_string_value() return import_module(registry).__dict__.get(ent... |
def is_authenticated_with_proxy(proxy): """Given a Proxy, checks whether a user is authenticated""" if proxy is None: return False elif proxy.has_authentication(): return proxy.get_authentication().is_valid() else: return False |
def get_effective_agent_id_with_proxy(proxy): """Given a Proxy, returns the Id of the effective Agent""" if is_authenticated_with_proxy(proxy): if proxy.has_effective_agent(): return proxy.get_effective_agent_id() else: return proxy.get_authentication().get_agent_id() else: return Id( identifier='MC3GUE$T@MIT.EDU', nam... |
def get_locale_with_proxy(proxy): """Given a Proxy, returns the Locale This assumes that instantiating a dlkit.mongo.locale.objects.Locale without constructor arguments wlll return the default Locale. """ from .locale.objects import Locale if proxy is not None: locale = proxy.get_locale() if locale is not None: return ... |
def convert_catalog_id_to_object_id_string(catalog_id): """When doing hierarchies, need to convert a catalogId into an ObjectId, so convert to a string, then into a hex format. i.e. Bank Assessment hierarchy should become BANKASSESSME '42414e4b4153534553534d45' """ if not isinstance(catalog_id, Id): raise TypeError('in... |
def create(name, config_file=None, template=None, backing_store=None, template_options=None): ''' Create a new container raises ContainerAlreadyExists exception if the container name is reserved already. :param template_options: Options passed to the specified template :type template_options: list or None ''' if exists... |
%s", name, cmd[3:]) return 0 else: return 1 |
def all_as_dict(): ''' returns a dict {'Running': ['cont1', 'cont2'], 'Stopped': ['cont3', 'cont4'] } ''' cmd = ['lxc-list'] out = subprocess.check_output(cmd).splitlines() stopped = [] running = [] frozen = [] current = None for c in out: c = c.strip() if c == 'RUNNING': current = running continue if c == 'STOPPED': c... |
def all_as_list(): ''' returns a list of all defined containers ''' as_dict = all_as_dict() containers = as_dict['Running'] + as_dict['Frozen'] + as_dict['Stopped'] containers_list = [] for i in containers: i = i.replace(' (auto)', '') containers_list.append(i) return containers_list |
def start(name, config_file=None): ''' starts a container in daemon mode ''' if not exists(name): raise ContainerNotExists("The container (%s) does not exist!" % name) if name in running(): raise ContainerAlreadyRunning('The container %s is already started!' % name) cmd = ['lxc-start', '-n', name, '-d'] if config_file:... |
def stop(name): ''' stops a container ''' if not exists(name): raise ContainerNotExists("The container (%s) does not exist!" % name) cmd = ['lxc-stop', '-n', name] subprocess.check_call(cmd) |
def kill(name, signal): ''' sends a kill signal to process 1 of ths container <name> :param signal: numeric signal ''' if not exists(name): raise ContainerNotExists("The container (%s) does not exist!" % name) cmd = ['lxc-kill', '--name=%s' % name, signal] subprocess.check_call(cmd) |
def shutdown(name, wait=False, reboot=False): ''' graceful shutdown sent to the container :param wait: should we wait for the shutdown to complete? :param reboot: reboot a container, ignores wait ''' if not exists(name): raise ContainerNotExists("The container (%s) does not exist!" % name) cmd = ['lxc-shutdown', '-n', ... |
def destroy(name): ''' removes a container [stops a container if it's running and] raises ContainerNotExists exception if the specified name is not created ''' if not exists(name): raise ContainerNotExists("The container (%s) does not exist!" % name) cmd = ['lxc-destroy', '-f', '-n', name] subprocess.check_call(cmd) |
def monitor(name, callback): ''' monitors actions on the specified container, callback is a function to be called on ''' global _monitor if not exists(name): raise ContainerNotExists("The container (%s) does not exist!" % name) if _monitor: if _monitor.is_monitored(name): raise Exception("You are already monitoring thi... |
def freeze(name): ''' freezes the container ''' if not exists(name): raise ContainerNotExists("The container (%s) does not exist!" % name) cmd = ['lxc-freeze', '-n', name] subprocess.check_call(cmd) |
def unfreeze(name): ''' unfreezes the container ''' if not exists(name): raise ContainerNotExists("The container (%s) does not exist!" % name) cmd = ['lxc-unfreeze', '-n', name] subprocess.check_call(cmd) |
def info(name): ''' returns info dict about the specified container ''' if not exists(name): raise ContainerNotExists("The container (%s) does not exist!" % name) cmd = ['lxc-info', '-n', name] out = subprocess.check_output(cmd).splitlines() info = {} for line in out: k, v = line.split() info[k] = v return info |
def checkconfig(): ''' returns the output of lxc-checkconfig ''' cmd = ['lxc-checkconfig'] return subprocess.check_output(cmd).replace('[1;32m', '').replace('[1;33m', '').replace('[0;39m', '').replace('[1;32m', '').replace(' ', '').split('\n') |
def notify(name, states, callback): ''' executes the callback function with no parameters when the container reaches the specified state or states states can be or-ed or and-ed notify('test', 'STOPPED', letmeknow) notify('test', 'STOPPED|RUNNING', letmeknow) ''' if not exists(name): raise ContainerNotExists("The contai... |
def get_grade_mdata(): """Return default mdata map for Grade""" return { 'output_score': { 'element_label': { 'text': 'output score', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'instructions': { 'text': 'enter a decimal value.', '... |
str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'required': False, 'read_only': False, 'linked': False, 'array': False, 'default_decimal_values': [None], 'syntax': 'DECIMAL', 'decimal_scale': None, 'minimum_decimal': None, 'maximum_decimal': None, 'decimal_set': [], }, 'input_score_start_range': ... |
def get_grade_system_mdata(): """Return default mdata map for GradeSystem""" return { 'numeric_score_increment': { 'element_label': { 'text': 'numeric score increment', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'instructions': { ... |
'enter either true or false.', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'required': False, 'read_only': False, 'linked': False, 'array': False, 'default_boolean_values': [None], 'syntax': 'BOOLEAN', }, 'highest_numeric_score': {... |
def get_grade_entry_mdata(): """Return default mdata map for GradeEntry""" return { 'resource': { 'element_label': { 'text': 'resource', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'instructions': { 'text': 'accepts an osid.id.Id o... |
'linked': False, 'array': False, 'default_boolean_values': [None], 'syntax': 'BOOLEAN', }, 'score': { 'element_label': { 'text': 'score', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'instructions': { 'text': 'enter a decimal value.... |
def get_gradebook_column_mdata(): """Return default mdata map for GradebookColumn""" return { 'grade_system': { 'element_label': { 'text': 'grade system', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'instructions': { 'text': 'accep... |
def get_gradebook_column_summary_mdata(): """Return default mdata map for GradebookColumnSummary""" return { 'gradebook_column': { 'element_label': { 'text': 'gradebook column', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'instruct... |
def add_die(self, die, count=1): '''Add ``Die`` to Roll. :param die: Die instance :param count: number of times die is rolled ''' for x in range(count): self._dice.append(die) self._odds = None |
def remove_die(self, die): '''Remove ``Die`` (first matching) from Roll. :param die: Die instance ''' if die in self._dice: self._dice.remove(die) |
def roll(self, count=0, func=sum): '''Roll some dice! :param count: [0] Return list of sums :param func: [sum] Apply func to list of individual die rolls func([]) :return: A single sum or list of ``count`` sums ''' if count: return [func([die.roll() for die in self._dice]) for x in range(0, count)] else: return func([d... |
def x_rolls(self, number, count=0, func=sum): '''Iterator of number dice rolls. :param count: [0] Return list of ``count`` sums :param func: [sum] Apply func to list of individual die rolls func([]) ''' for x in range(number): yield self.roll(count, func) |
def iter(self, count=0, func=sum): '''Iterator of infinite dice rolls. :param count: [0] Return list of ``count`` sums :param func: [sum] Apply func to list of individual die rolls func([]) ''' while True: yield self.roll(count, func) |
def _calc_odds(self): '''Calculates the absolute probability of all posible rolls.''' def recur(val, h, dice, combinations): for pip in dice[0]: tot = val + pip if len(dice) > 1: combinations = recur(tot, h, dice[1:], combinations) else: combinations += 1 h[tot] = h.get(tot, 0) + 1 return combinations if self.summable:... |
def roll(self, count=0): '''Roll some dice! :param count: [0] Return list of sums :return: A single sum or list of ``count`` sums ''' return super(FuncRoll, self).roll(count, self._func) |
def x_rolls(self, number, count=0): '''Iterator of number dice rolls. :param count: [0] Return list of ``count`` sums ''' for x in range(number): yield super(FuncRoll, self).roll(count, self._func) |
def iter(self, count=0): '''Iterator of infinite dice rolls. :param count: [0] Return list of ``count`` sums ''' while True: yield super(FuncRoll, self).roll(count, self._func) |
def get_resource(self, resource_id): """Gets the ``Resource`` specified by its ``Id``. In plenary mode, the exact ``Id`` is found or a ``NotFound`` results. Otherwise, the returned ``Resource`` may have a different ``Id`` than requested, such as the case where a duplicate ``Id`` was assigned to a ``Resource`` and retai... |
'resource').get_identifier())}, **self._view_filter())) return objects.Resource(osid_object_map=result, runtime=self._runtime, proxy=self._proxy) |
def get_resources_by_ids(self, resource_ids): """Gets a ``ResourceList`` corresponding to the given ``IdList``. In plenary mode, the returned list contains all of the resources specified in the ``Id`` list, in the order of the list, including duplicates, or an error results if an ``Id`` in the supplied list is not foun... |
for # osid.resource.ResourceLookupSession.get_resources_by_ids # NOTE: This implementation currently ignores plenary view collection = JSONClientValidated('resource', collection='Resource', runtime=self._runtime) object_id_list = [] for i in resource_ids: object_id_list.append(ObjectId(self._get_id(i, 'resource').get_i... |
def get_resources_by_genus_type(self, resource_genus_type): """Gets a ``ResourceList`` corresponding to the given resource genus ``Type`` which does not include resources of types derived from the specified ``Type``. In plenary mode, the returned list contains all known resources or an error results. Otherwise, the ret... |
def get_resources(self): """Gets all ``Resources``. In plenary mode, the returned list contains all known resources or an error results. Otherwise, the returned list may contain only those resources that are accessible through this session. return: (osid.resource.ResourceList) - a list of ``Resources`` raise: Operation... |
def get_resources_by_query(self, resource_query): """Gets a list of ``Resources`` matching the given resource query. arg: resource_query (osid.resource.ResourceQuery): the resource query return: (osid.resource.ResourceList) - the returned ``ResourceList`` raise: NullArgument - ``resource_query`` is ``null`` raise: Oper... |
else: result = [] return objects.ResourceList(result, runtime=self._runtime, proxy=self._proxy) |
def get_resources_by_search(self, resource_query, resource_search): """Gets the search results matching the given search query using the given search. arg: resource_query (osid.resource.ResourceQuery): the resource query arg: resource_search (osid.resource.ResourceSearch): the resource search return: (osid.resource.Res... |
view_filter: and_list.append(view_filter) if and_list: query_terms = {'$and': and_list} collection = JSONClientValidated('resource', collection='Resource', runtime=self._runtime) if resource_search.start is not None and resource_search.end is not None: result = collection.find(query_terms)[resource_search.start:resourc... |
def get_resource_form_for_create(self, resource_record_types): """Gets the resource form for creating new resources. A new form should be requested for each create transaction. arg: resource_record_types (osid.type.Type[]): array of resource record types return: (osid.resource.ResourceForm) - the resource form raise: N... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.