code
stringlengths
1
18.2k
if not parameters: track_local_parameters = True parameters = set() parameter_values = {} else: track_local_parameters = False stoichiometry_matrix = np.zeros((len(species), len(reactions)), dtype=int) propensities = [] for reaction_index, reaction in enumerate(reactions): if track_local_parameters: for param, value in...
= Model(species, compartments_and_parameters, propensities, stoichiometry_matrix) return model, parameter_values_list, initial_conditions
def build_items(self): u"""This method called by Executer. /proc/net/tcp -> {host:host, key:key, value:value, clock:clock} """ protocols = ['tcp', 'tcp6'] for protocol in protocols: procfile = open('/proc/net/{0}'.format(protocol), 'r') stats = self.count(procfile) for key, value in stats.items(): item = NetstatItem(ke...
def count(procfile): u"""Take arguments as intermediate data. {protocol:[...]} -> {key1:value1, key2:value2} e.g: {linux.net.tcp.LISTEN: 20} """ state_tcp = { '01': 'ESTABLISHED', '02': 'SYN_SENT', '03': 'SYN_RECV', '04': 'FIN_WAIT1', '05': 'FIN_WAIT2', '06': 'TIME_WAIT', '07': 'CLOSE', '08': 'CLOSE_WAIT', '09': 'LAST_...
def _init_map(self): """stub""" ItemTextsFormRecord._init_map(self) ItemFilesFormRecord._init_map(self) super(ItemTextsAndFilesMixin, self)._init_map()
def _init_metadata(self): """stub""" ItemTextsFormRecord._init_metadata(self) ItemFilesFormRecord._init_metadata(self) super(ItemTextsAndFilesMixin, self)._init_metadata()
def _init_map(self): """stub""" QuestionTextFormRecord._init_map(self) QuestionFilesFormRecord._init_map(self) super(QuestionTextAndFilesMixin, self)._init_map()
def _init_metadata(self): """stub""" QuestionTextFormRecord._init_metadata(self) QuestionFilesFormRecord._init_metadata(self) super(QuestionTextAndFilesMixin, self)._init_metadata()
def _init_map(self): """stub""" QuestionTextsFormRecord._init_map(self) QuestionFilesFormRecord._init_map(self) super(QuestionTextsAndFilesMixin, self)._init_map()
def _init_metadata(self): """stub""" QuestionTextsFormRecord._init_metadata(self) QuestionFilesFormRecord._init_metadata(self) super(QuestionTextsAndFilesMixin, self)._init_metadata()
def _init_map(self): """stub""" super(TextAnswerFormRecord, self)._init_map() self.my_osid_object_form._my_map['minStringLength'] = \ self._min_string_length_metadata['default_cardinal_values'][0] self.my_osid_object_form._my_map['maxStringLength'] = \ self._max_string_length_metadata['default_cardinal_values'][0]
def _init_metadata(self): """stub""" super(TextAnswerFormRecord, self)._init_metadata() self._min_string_length_metadata = { 'element_id': Id(self.my_osid_object_form._authority, self.my_osid_object_form._namespace, 'min-string-length'), 'element_label': 'min string length', 'instructions': 'enter minimum string length...
def clear_min_string_length(self): """stub""" if (self.get_min_string_length_metadata().is_read_only() or self.get_min_string_length_metadata().is_required()): raise NoAccess() self.my_osid_object_form._my_map['minStringLength'] = \ self.get_min_string_length_metadata().get_default_cardinal_values()[0]
def clear_max_string_length(self): """stub""" if (self.get_max_string_length_metadata().is_read_only() or self.get_max_string_length_metadata().is_required()): raise NoAccess() self.my_osid_object_form._my_map['maxStringLength'] = \ self.get_max_string_length_metadata().get_default_cardinal_values()[0]
def _init_map(self): """stub""" super(TextsAnswerFormRecord, self)._init_map() self.my_osid_object_form._my_map['minStringLength'] = \ self._min_string_length_metadata['default_cardinal_values'][0] self.my_osid_object_form._my_map['maxStringLength'] = \ self._max_string_length_metadata['default_cardinal_values'][0]
def set_min_string_length(self, length=None): """stub""" if self.get_min_string_length_metadata().is_read_only(): raise NoAccess() if not self.my_osid_object_form._is_valid_cardinal( length, self.get_min_string_length_metadata()): raise InvalidArgument() if self.my_osid_object_form.max_string_length is not None and \ l...
def set_max_string_length(self, length=None): """stub""" if self.get_max_string_length_metadata().is_read_only(): raise NoAccess() if not self.my_osid_object_form._is_valid_cardinal( length, self.get_max_string_length_metadata()): raise InvalidArgument() if self.my_osid_object_form.min_string_length is not None and \ l...
def _init_map(self): """stub""" TextAnswerFormRecord._init_map(self) FilesAnswerFormRecord._init_map(self) super(AnswerTextAndFilesMixin, self)._init_map()
def _init_metadata(self): """stub""" TextAnswerFormRecord._init_metadata(self) FilesAnswerFormRecord._init_metadata(self) super(AnswerTextAndFilesMixin, self)._init_metadata()
def is_response_correct(self, response): """returns True if response evaluates to an Item Answer that is 100 percent correct""" for answer in self.my_osid_object.get_answers(): if self._is_match(response, answer): return True return False
def add_exercises(self, *exercises): """Add the exercises to the day. The method will automatically infer whether a static or dynamic exercise is passed to it. Parameters ---------- *exercises An unpacked tuple of exercises. Examples ------- >>> monday = Day(name = 'Monday') >>> curls = StaticExercise('Curls', '3 x 12'...
def parseSOAP(xml_str, rules = None): """ Replacement for SOAPpy._parseSOAP method to spoof SOAPParser. """ try: from cStringIO import StringIO except ImportError: from StringIO import StringIO parser = xml.sax.make_parser() t = ZimbraSOAPParser(rules = rules) parser.setContentHandler(t) e = xml.sax.handler.ErrorHandle...
def build_opener(self): """ Builds url opener, initializing proxy. @return: OpenerDirector """ http_handler = urllib2.HTTPHandler() # debuglevel=self.transport.debug if util.empty(self.transport.proxy_url): return urllib2.build_opener(http_handler) proxy_handler = urllib2.ProxyHandler( {self.transport.proxy_url[:4]: se...
def init_soap_exception(self, exc): """ Initializes exception based on soap error response. @param exc: URLError @return: SoapException """ if not isinstance(exc, urllib2.HTTPError): return SoapException(unicode(exc), exc) if isinstance(exc, urllib2.HTTPError): try: data = exc.read() self.log.debug(data) t = SOAPpy.Par...
def _init_metadata(self): """stub""" self._first_angle_metadata = { 'element_id': Id(self.my_osid_object_form._authority, self.my_osid_object_form._namespace, 'first_angle'), 'element_label': 'First Angle', 'instructions': 'set boolean, is this a first angle projection', 'required': False, 'read_only': False, 'linked':...
def set_first_angle_projection(self, value=None): """stub""" if value is None: raise NullArgument() if self.get_first_angle_projection_metadata().is_read_only(): raise NoAccess() if not self.my_osid_object_form._is_valid_boolean(value): raise InvalidArgument() self.my_osid_object_form._my_map['firstAngle'] = value
def clear_first_angle_projection(self): """stub""" if (self.get_first_angle_projection_metadata().is_read_only() or self.get_first_angle_projection_metadata().is_required()): raise NoAccess() self.my_osid_object_form._my_map['firstAngle'] = \ self._first_angle_metadata['default_boolean_values'][0]
def _init_metadata(self): """stub""" super(BaseOrthoQuestionFormRecord, self)._init_metadata() self._ortho_view_set_metadata = { 'element_id': Id(self.my_osid_object_form._authority, self.my_osid_object_form._namespace, 'ortho_view_set'), 'element_label': 'Orthographic View Set', 'instructions': '', 'required': False, ...
def set_manip(self, manipulatable): """stub""" if not isinstance(manipulatable, DataInputStream): raise InvalidArgument('Manipulatable object be an ' + 'osid.transport.DataInputStream object') self.add_file(manipulatable, label='manip', asset_type=MANIP_ASSET_TYPE, asset_content_type=MANIP_ASSET_CONTENT_TYPE)
def set_ortho_view_set(self, front_view, side_view, top_view): """stub""" if (not isinstance(front_view, DataInputStream) or not isinstance(top_view, DataInputStream) or not isinstance(side_view, DataInputStream)): raise InvalidArgument('views must be osid.transport.DataInputStream objects') self.add_file(front_view, l...
def clear_ortho_view_set(self): """stub""" if (self.get_ortho_view_set_metadata().is_read_only() or self.get_ortho_view_set_metadata().is_required()): raise NoAccess() self.clear_file('frontView') self.clear_file('sideView') self.clear_file('topView')
def set_ovs_view(self, asset_data, view_name): """ view_name should be frontView, sideView, or topView """ if not isinstance(asset_data, DataInputStream): raise InvalidArgument('view file must be an ' + 'osid.transport.DataInputStream object') if view_name not in ['frontView', 'sideView', 'topView']: raise InvalidArgum...
def _init_metadata(self): """stub""" super(LabelOrthoFacesAnswerFormRecord, self)._init_metadata() self._face_values_metadata = { 'element_id': Id(self.my_osid_object_form._authority, self.my_osid_object_form._namespace, 'face_values'), 'element_label': 'Orthographic Face Values', 'instructions': '', 'required': True, ...
def set_face_values(self, front_face_value, side_face_value, top_face_value): """stub""" if front_face_value is None or side_face_value is None or top_face_value is None: raise NullArgument() self.add_integer_value(value=int(front_face_value), label='frontFaceValue') self.add_integer_value(value=int(side_face_value), l...
def clear_face_values(self): """stub""" if (self.get_face_values_metadata().is_read_only() or self.get_face_values_metadata().is_required()): raise NoAccess() self.clear_integer_value('frontFaceValue') self.clear_integer_value('sideFaceValue') self.clear_integer_value('topFaceValue')
def _init_metadata(self): """stub""" super(EulerRotationAnswerFormRecord, self)._init_metadata() self._euler_rotation_metadata = { 'element_id': Id(self.my_osid_object_form._authority, self.my_osid_object_form._namespace, 'angle_values'), 'element_label': 'Euler Angle Values', 'instructions': 'Provide X, Y, and Z euler...
def set_euler_angle_values(self, x_angle, y_angle, z_angle): """stub""" if x_angle is None or y_angle is None or z_angle is None: raise NullArgument() self.add_integer_value(value=x_angle, label='xAngle') self.add_integer_value(value=y_angle, label='yAngle') self.add_integer_value(value=z_angle, label='zAngle')
def clear_angle_values(self): """stub""" if (self.get_euler_rotation_values_metadata().is_read_only() or self.get_euler_rotation_values_metadata().is_required()): raise NoAccess() self.clear_integer_value('xAngle') self.clear_integer_value('yAngle') self.clear_integer_value('zAngle')
def get_type_data(name): """Return dictionary representation of type. Can be used to initialize primordium.type.primitives.Type """ try: return { 'authority': 'birdland.mit.edu', 'namespace': 'Genus Types', 'identifier': name, 'domain': 'Generic Types', 'display_name': OBJECTIVE_TYPES[name] + ' Genus Type', 'display_la...
def _set_gradebook_view(self, session): """Sets the underlying gradebook view to match current view""" if self._gradebook_view == COMPARATIVE: try: session.use_comparative_gradebook_view() except AttributeError: pass else: try: session.use_plenary_gradebook_view() except AttributeError: pass
def _get_provider_session(self, session_name, proxy=None): """Gets the session for the provider""" agent_key = self._get_agent_key(proxy) if session_name in self._provider_sessions[agent_key]: return self._provider_sessions[agent_key][session_name] else: session = self._instantiate_session('get_' + session_name, self._...
def use_comparative_gradebook_view(self): """Pass through to provider GradeSystemGradebookSession.use_comparative_gradebook_view""" self._gradebook_view = COMPARATIVE # self._get_provider_session('grade_system_gradebook_session') # To make sure the session is tracked for session in self._get_provider_sessions(): try: s...
def use_plenary_gradebook_view(self): """Pass through to provider GradeSystemGradebookSession.use_plenary_gradebook_view""" self._gradebook_view = PLENARY # self._get_provider_session('grade_system_gradebook_session') # To make sure the session is tracked for session in self._get_provider_sessions(): try: session.use_p...
def get_gradebooks_by_parent_genus_type(self, *args, **kwargs): """Pass through to provider GradebookLookupSession.get_gradebooks_by_parent_genus_type""" # Implemented from kitosid template for - # osid.resource.BinLookupSession.get_bins_by_parent_genus_type catalogs = self._get_provider_session('gradebook_lookup_sessi...
def get_gradebooks(self): """Pass through to provider GradebookLookupSession.get_gradebooks""" # Implemented from kitosid template for - # osid.resource.BinLookupSession.get_bins_template catalogs = self._get_provider_session('gradebook_lookup_session').get_gradebooks() cat_list = [] for cat in catalogs: cat_list.appen...
def get_gradebook_form(self, *args, **kwargs): """Pass through to provider GradebookAdminSession.get_gradebook_form_for_update""" # Implemented from kitosid template for - # osid.resource.BinAdminSession.get_bin_form_for_update_template # This method might be a bit sketchy. Time will tell. if isinstance(args[-1], list)...
def update_gradebook(self, *args, **kwargs): """Pass through to provider GradebookAdminSession.update_gradebook""" # Implemented from kitosid template for - # osid.resource.BinAdminSession.update_bin # OSID spec does not require returning updated catalog return Gradebook( self._provider_manager, self._get_provider_sess...
def save_gradebook(self, gradebook_form, *args, **kwargs): """Pass through to provider GradebookAdminSession.update_gradebook""" # Implemented from kitosid template for - # osid.resource.BinAdminSession.update_bin if gradebook_form.is_for_update(): return self.update_gradebook(gradebook_form, *args, **kwargs) else: ret...
def _set_gradebook_view(self, session): """Sets the underlying gradebook view to match current view""" if self._gradebook_view == FEDERATED: try: session.use_federated_gradebook_view() except AttributeError: pass else: try: session.use_isolated_gradebook_view() except AttributeError: pass
def use_comparative_grade_system_view(self): """Pass through to provider GradeSystemLookupSession.use_comparative_grade_system_view""" self._object_views['grade_system'] = COMPARATIVE # self._get_provider_session('grade_system_lookup_session') # To make sure the session is tracked for session in self._get_provider_sess...
def use_plenary_grade_system_view(self): """Pass through to provider GradeSystemLookupSession.use_plenary_grade_system_view""" self._object_views['grade_system'] = PLENARY # self._get_provider_session('grade_system_lookup_session') # To make sure the session is tracked for session in self._get_provider_sessions(): try:...
def use_federated_gradebook_view(self): """Pass through to provider GradeSystemLookupSession.use_federated_gradebook_view""" self._gradebook_view = FEDERATED # self._get_provider_session('grade_system_lookup_session') # To make sure the session is tracked for session in self._get_provider_sessions(): try: session.use_f...
def use_isolated_gradebook_view(self): """Pass through to provider GradeSystemLookupSession.use_isolated_gradebook_view""" self._gradebook_view = ISOLATED # self._get_provider_session('grade_system_lookup_session') # To make sure the session is tracked for session in self._get_provider_sessions(): try: session.use_isol...
def get_grade_system_form(self, *args, **kwargs): """Pass through to provider GradeSystemAdminSession.get_grade_system_form_for_update""" # Implemented from kitosid template for - # osid.resource.ResourceAdminSession.get_resource_form_for_update # This method might be a bit sketchy. Time will tell. if isinstance(args[-...
def save_grade_system(self, grade_system_form, *args, **kwargs): """Pass through to provider GradeSystemAdminSession.update_grade_system""" # Implemented from kitosid template for - # osid.resource.ResourceAdminSession.update_resource if grade_system_form.is_for_update(): return self.update_grade_system(grade_system_fo...
def use_comparative_grade_entry_view(self): """Pass through to provider GradeEntryLookupSession.use_comparative_grade_entry_view""" self._object_views['grade_entry'] = COMPARATIVE # self._get_provider_session('grade_entry_lookup_session') # To make sure the session is tracked for session in self._get_provider_sessions(...
def use_plenary_grade_entry_view(self): """Pass through to provider GradeEntryLookupSession.use_plenary_grade_entry_view""" self._object_views['grade_entry'] = PLENARY # self._get_provider_session('grade_entry_lookup_session') # To make sure the session is tracked for session in self._get_provider_sessions(): try: sess...
def get_grade_entry_form(self, *args, **kwargs): """Pass through to provider GradeEntryAdminSession.get_grade_entry_form_for_update""" # Implemented from kitosid template for - # osid.resource.ResourceAdminSession.get_resource_form_for_update # This method might be a bit sketchy. Time will tell. if isinstance(args[-1],...
def save_grade_entry(self, grade_entry_form, *args, **kwargs): """Pass through to provider GradeEntryAdminSession.update_grade_entry""" # Implemented from kitosid template for - # osid.resource.ResourceAdminSession.update_resource if grade_entry_form.is_for_update(): return self.update_grade_entry(grade_entry_form, *ar...
def use_comparative_gradebook_column_view(self): """Pass through to provider GradebookColumnLookupSession.use_comparative_gradebook_column_view""" self._object_views['gradebook_column'] = COMPARATIVE # self._get_provider_session('gradebook_column_lookup_session') # To make sure the session is tracked for session in sel...
def use_plenary_gradebook_column_view(self): """Pass through to provider GradebookColumnLookupSession.use_plenary_gradebook_column_view""" self._object_views['gradebook_column'] = PLENARY # self._get_provider_session('gradebook_column_lookup_session') # To make sure the session is tracked for session in self._get_provi...
def get_gradebook_column_form(self, *args, **kwargs): """Pass through to provider GradebookColumnAdminSession.get_gradebook_column_form_for_update""" # Implemented from kitosid template for - # osid.resource.ResourceAdminSession.get_resource_form_for_update # This method might be a bit sketchy. Time will tell. if isins...
def save_gradebook_column(self, gradebook_column_form, *args, **kwargs): """Pass through to provider GradebookColumnAdminSession.update_gradebook_column""" # Implemented from kitosid template for - # osid.resource.ResourceAdminSession.update_resource if gradebook_column_form.is_for_update(): return self.update_gradeboo...
def memoize(f): """Cache value returned by the function.""" @wraps(f) def w(*args, **kw): memoize.mem[f] = v = f(*args, **kw) return v return w
def project2module(project): """Convert project name into a module name.""" # Name unification in accordance with PEP 426. project = project.lower().replace("-", "_") if project.startswith("python_"): # Remove conventional "python-" prefix. project = project[7:] return project
def get_requirements( self, install=True, extras=True, setup=False, tests=False): """Get package requirements.""" requires = [] if install: requires.extend(parse_requirements( self.keywords.get('install_requires', ()), )) if extras: for r in self.keywords.get('extras_require', {}).values(): requires.extend(parse_requir...
def visit_Call(self, node): """Call visitor - used for finding setup() call.""" self.generic_visit(node) # Setup() is a keywords-only function. if node.args: return keywords = set() for k in node.keywords: if k.arg is not None: keywords.add(k.arg) # Simple case for dictionary expansion for Python >= 3.5. if k.arg is No...
tuple(keywords), score) return # Redirect call to our setup() tap function. node.func = ast.Name(id='__f8r_setup', ctx=node.func.ctx) self.redirected = True
def add_options(cls, manager): """Register plug-in specific options.""" kw = {} if flake8.__version__ >= '3.0.0': kw['parse_from_config'] = True manager.add_option( "--known-modules", action='store', default="", help=( "User defined mapping between a project name and a list of" " provided modules. For example: ``--know...
def parse_options(cls, options): """Parse plug-in specific options.""" cls.known_modules = { project2module(k): v.split(",") for k, v in [ x.split(":[") for x in re.split(r"],?", options.known_modules)[:-1] ] }
def get_requirements(cls): """Get package requirements.""" try: with open("requirements.txt") as f: return tuple(parse_requirements(f.readlines())) except IOError as e: LOG.debug("Couldn't open requirements file: %s", e) return ()
def get_setup(cls): """Get package setup.""" try: with open("setup.py") as f: return SetupVisitor(ast.parse(f.read())) except IOError as e: LOG.warning("Couldn't open setup file: %s", e) return SetupVisitor(ast.parse(""))
def run(self): """Run checker.""" def split(module): """Split module into submodules.""" return tuple(module.split(".")) def modcmp(lib=(), test=()): """Compare import modules.""" if len(lib) > len(test): return False return all(a == b for a, b in zip(lib, test)) mods_1st_party = set() mods_3rd_party = set() # Get 1st ...
# project requirements. Setuptools might be required to build the # project, even though it is not listed as a requirement - this # package is required to run setup.py, so listing it as a setup # requirement would be pointless. if self.processing_setup_py: mods_3rd_party.add(split("setuptools")) for node in ImportVisit...
def getUserInfoError(sAccessToken): """ May be return {u'msg': u'Access_token repealed', u'errno': u'-102', u'data': []} """ import urllib.request, urllib.parse, urllib.error payload = urllib.parse.urlencode({'access_token': sAccessToken}) c = http.client.HTTPSConnection('796.com') c.request("GET", "/v1/user/get_info?"...
def as_html(self): """ Returns the image of the Yahoo rss feed as an html string """ return '<a href="{0}"><img height="{1}" width="{2}" src="{3}" alt="{4}"></a>'.format( self.link, self.height, self.width, self.url, self.title)
def ffprobe(input_file, verbose=False): """Runs ffprobe on file and returns python dict with result""" if isinstance(input_file, FileObject): exists = input_file.exists path = input_file.path elif type(input_file) in string_types: exists = os.path.exists(input_file) path = input_file else: raise TypeError("input_path m...
def class_check_para(**kw): """ force check accept and return, decorator, @class_check_para(accept=, returns=, mail=) :param kw: :return: """ try: def decorator(f): def new_f(*args): if "accepts" in kw: assert len(args) == len(kw["accepts"]) + 1 arg_types = tuple(map(type, args[1:])) if arg_types != kw["accepts"]: msg ...
def decorator_info(f_name, expected, actual, flag): """ Convenience function returns nicely formatted error/warning msg. :param f_name: :param expected: :param actual: :param flag: :return: """ format = lambda types: ', '.join([str(t).split("'")[1] for t in types]) expected, actual = format(expected), format(actual) ms...
def pay_loan(self, loan_name): """additional when step for loan payments""" loan_payments = { 'student': 600, 'car': 200 } payment_amount = loan_payments[loan_name] self.withdraw(payment_amount)
def withdraw(self, amount): """Extends withdraw method to make sure enough funds are in the account, then call withdraw from superclass""" if amount > self.balance: raise ValueError('Insufficient Funds') super().withdraw(amount)
def compare_balance(self, operator, or_equals, amount): """Additional step using regex matcher to compare the current balance with some number""" amount = int(amount) if operator == 'less': if or_equals: self.assertLessEqual(self.balance, amount) else: self.assertLess(self.balance, amount) elif or_equals: self.assertGr...
def _compute_closed_central_moments(self, central_from_raw_exprs, n_counter, k_counter): r""" Computes parametric expressions (e.g. in terms of mean, variance, covariances) for all central moments up to max_order + 1 order. :param central_from_raw_exprs: the expression of central moments in terms of raw moments :param ...
obtain expression of central moments in terms of low order raw moments closed_central_moments = substitute_all(central_from_raw_exprs, substitution_pairs) return closed_central_moments
def close(self, mfk, central_from_raw_exprs, n_counter, k_counter): """ In MFK, replaces symbol for high order (order == max_order+1) by parametric expressions. That is expressions depending on lower order moments such as means, variances, covariances and so on. :param mfk: the right hand side equations containing symb...
Typically, :math: `[yx2, yx3, ...,yxN]`. # now we want to replace the new mfk (i.e. without highest order moment) any # symbol for highest order central moment by the corresponding expression (computed above) positive_n_counter = [n for n in n_counter if n.order > 0] substitutions_pairs = [(n.symbol, ccm) for n,ccm in ...
def _set_mixed_moments_to_zero(self, closed_central_moments, n_counter): r""" In univariate case, set the cross-terms to 0. :param closed_central_moments: matrix of closed central moment :param n_counter: a list of :class:`~means.core.descriptors.Moment`\s representing central moments :type n_counter: list[:class:`~mea...
def _compute_closed_central_moments(self, central_from_raw_exprs, n_counter, k_counter): r""" Replace raw moment terms in central moment expressions by parameters (e.g. mean, variance, covariances) :param central_from_raw_exprs: the expression of central moments in terms of raw moments :param n_counter: a list of :clas...
def read_tgf(filename): """Reads a file in Trivial Graph Format.""" g = Graph() with open(filename) as file: states = {} # Nodes for line in file: line = line.strip() if line == "": continue elif line == "#": break i, q = line.split(None, 1) q, attrs = syntax.string_to_state(q) states[i] = q g.add_node(q, attrs) # Edge...
def only_path(self): """Finds the only path from the start node. If there is more than one, raises ValueError.""" start = [v for v in self.nodes if self.nodes[v].get('start', False)] if len(start) != 1: raise ValueError("graph does not have exactly one start node") path = [] [v] = start while True: path.append(v) u = v...
def _init_catalog(self, proxy=None, runtime=None): """Initialize this session as an OsidCatalog based session.""" self._init_proxy_and_runtime(proxy, runtime) osid_name = self._session_namespace.split('.')[0] try: config = self._runtime.get_configuration() parameter_id = Id('parameter:' + osid_name + 'CatalogingProvide...
def _init_object(self, catalog_id, proxy, runtime, db_name, cat_name, cat_class): """Initialize this session an OsidObject based session.""" self._catalog_identifier = None self._init_proxy_and_runtime(proxy, runtime) uses_cataloging = False if catalog_id is not None and catalog_id.get_identifier() != PHANTOM_ROOT_IDEN...
identifier=self._catalog_identifier) if not uses_cataloging: self._catalog = cat_class(osid_object_map=self._my_catalog_map, runtime=self._runtime, proxy=self._proxy) self._catalog._authority = self._authority # there should be a better way... self._catalog_id = self._catalog.get_id() self._forms = dict()
def _get_phantom_root_catalog(self, cat_name, cat_class): """Get's the catalog id corresponding to the root of all implementation catalogs.""" catalog_map = make_catalog_map(cat_name, identifier=PHANTOM_ROOT_IDENTIFIER) return cat_class(osid_object_map=catalog_map, runtime=self._runtime, proxy=self._proxy)
def _create_orchestrated_cat(self, foreign_catalog_id, db_name, cat_name): """Creates a catalog in the current service orchestrated with a foreign service Id.""" if (foreign_catalog_id.identifier_namespace == db_name + '.' + cat_name and foreign_catalog_id.authority == self._authority): raise errors.NotFound() # This i...
def _get_id(self, id_, pkg_name): """ Returns the primary id given an alias. If the id provided is not in the alias table, it will simply be returned as is. Only looks within the Id Alias namespace for the session package """ collection = JSONClientValidated('id', collection=pkg_name + 'Ids', runtime=self._runtime) try...
def _alias_id(self, primary_id, equivalent_id): """Adds the given equivalent_id as an alias for primary_id if possible""" pkg_name = primary_id.get_identifier_namespace().split('.')[0] obj_name = primary_id.get_identifier_namespace().split('.')[1] collection = JSONClientValidated(pkg_name, collection=obj_name, runtime=...
def _get_catalog_idstrs(self): """Returns the proper list of catalog idstrs based on catalog view""" if self._catalog_view == ISOLATED: return [str(self._catalog_id)] else: return self._get_descendent_cat_idstrs(self._catalog_id)
def _get_descendent_cat_idstrs(self, cat_id, hierarchy_session=None): """Recursively returns a list of all descendent catalog ids, inclusive""" def get_descendent_ids(h_session): idstr_list = [str(cat_id)] if h_session is None: pkg_name = cat_id.get_identifier_namespace().split('.')[0] cat_name = cat_id.get_identifier_...
import memcache caching_host = '127.0.0.1:11211' try: config = self._runtime.get_configuration() parameter_id = Id('parameter:cachingHostURI@json') caching_host = config.get_value_by_parameter(parameter_id).get_string_value() except (AttributeError, KeyError, errors.NotFound): pass mc = memcache.Client([caching_host], ...