def setUp(self): # Cleanup self.addCleanup(patch.stopall) self.goog_provider = namedtuple("resp",['headers'])({'Location':'google'}) self.oauth_response = { 'access_token': 'access_token' } module.google_remote_app = Mock( return_value=namedtuple('google_remote_app', ['authorize', 'authorized_response']) (authorize=lambda **kwargs: self.goog_provider, authorized_response=lambda **kwargs: self.oauth_response) ) module.get_user = Mock( return_value=namedtuple('User', ['name','email','avatar_url']) ('moshe','*****@*****.**','http://google.com') ) module.get_user_profile = Mock( return_value={ 'id': 'userid', 'idhash': self.IDHASH, 'name': 'Moshe', 'email': '*****@*****.**', 'picture': 'http://moshe.com/picture' } )
def test_propset_dict_simple(self): ObjectContent = collections.namedtuple("ObjectContent", ["propSet"]) DynamicProperty = collections.namedtuple("Property", ["name", "val"]) object = ObjectContent(propSet=[DynamicProperty(name="foo", val="bar")]) propdict = vm_util.propset_dict(object.propSet) self.assertEqual("bar", propdict["foo"])
def test_area_area2rect(): Rect = namedtuple('Rect', 'width height x y') Area = namedtuple('Area', 'width height x') test_rect = Rect(width=15, height=15, x=0, y=0) assert (area(test_rect) == 15 * 15) test_area = Area(width=15, height=15, x=0) assert (area2rect(test_area, 14) == test_rect)
def test_can_insert_nested_registered_udts_with_different_namedtuples(self): """ Test for ensuring nested udts are inserted correctly when the created namedtuples are use names that are different the cql type. """ c = Cluster(protocol_version=PROTOCOL_VERSION) s = c.connect(self.keyspace_name, wait_for_all_pools=True) s.row_factory = dict_factory MAX_NESTING_DEPTH = 16 # create the schema self.nested_udt_schema_helper(s, MAX_NESTING_DEPTH) # create and register the seed udt type udts = [] udt = namedtuple('level_0', ('age', 'name')) udts.append(udt) c.register_user_type(self.keyspace_name, "depth_0", udts[0]) # create and register the nested udt types for i in range(MAX_NESTING_DEPTH): udt = namedtuple('level_{0}'.format(i + 1), ('value')) udts.append(udt) c.register_user_type(self.keyspace_name, "depth_{0}".format(i + 1), udts[i + 1]) # insert udts and verify inserts with reads self.nested_udt_verification_helper(s, MAX_NESTING_DEPTH, udts) c.shutdown()
def test_new_request_event_no_profile_id(self): Event = namedtuple('Event', ['request', 'response']) Registry = namedtuple('Registry', ['settings']) request = self.mk_request() request.registry = Registry(settings={}) new_request(Event(request=request, response=None)) self.assertEqual(request.google_analytics, {})
def benchmark_complex_object_loading(iterations=1000): Foo = namedtuple('Foo', ['a', 'b', 'c', 'd']) Bar = namedtuple('Bar', ['x', 'y', 'foo', 'foos']) FOO = lt.Object({ 'a': lt.Integer(), 'b': lt.FunctionField(lt.Integer(), lambda o: o.b + 10), 'c': lt.String(), 'd': lt.Integer(), }) BAR = lt.Object({ 'x': lt.String(), 'y': lt.Integer(), 'foo': FOO, 'foos': lt.List(FOO), }) data = { 'x': 'bar', 'y': 123, 'foo': {'a': 123, 'b': 456, 'c': 'foo', 'd': 789}, 'foos': [{'a': 123+i, 'b': 456+i, 'c': 'foo', 'd': 789+i} for i in xrange(10)], } BAR.load(data) # warmup time = timeit.timeit(lambda: BAR.load(data), number=iterations) print 'Complex object loading: %s' % time
def benchmark_complex_object_dumping(iterations=1000): Foo = namedtuple('Foo', ['a', 'b', 'c', 'd']) Bar = namedtuple('Bar', ['x', 'y', 'foo', 'foos']) FOO = lt.Object({ 'a': lt.Integer(), 'b': lt.FunctionField(lt.Integer(), lambda o: o.b + 10), 'c': lt.String(), 'd': lt.Integer(), }) BAR = lt.Object({ 'x': lt.String(), 'y': lt.Integer(), 'foo': FOO, 'foos': lt.List(FOO), }) bar = Bar( 'bar', 123, Foo(123, 456, 'foo', 789), [Foo(123+i, 456+i, 'foo', 789+i) for i in xrange(10)] ) BAR.dump(bar) # warmup time = timeit.timeit(lambda: BAR.dump(bar), number=iterations) print 'Complex object dumping: %s' % time
def test_30_to_namedtuple(self): _point = collections.namedtuple("Point", "x y") _triangle = collections.namedtuple("Triangle", "p0 p1 p2") itpl = _triangle(_point(0, 0), _point(1, 0), _point(0, 1)) md0 = TT.make(itpl) otpl = TT.convert_to(md0, to_namedtuple=True) self.assertEqual(otpl, itpl)
def test_functionality(self): """ Nested named tuples work more or less as expected. Lower-level tuples must be built first, because the tuples are immutable. """ # creation of lower-level tuple two_pair = namedtuple('TwoPair', ['c__', 'd__']) duo = two_pair(13, 'dddD') # create upper-level tuple threesome = namedtuple('Threesome', ['a__', 'b__', 'e__']) trio = threesome(a__='val0', b__=duo, e__=42) # attribute notation self.assertEqual(trio.a__, 'val0') self.assertEqual(trio.b__.c__, 13) self.assertEqual(trio.b__.d__, 'dddD') self.assertEqual(trio.e__, 42) # indexed access self.assertEqual(trio[0], 'val0') self.assertEqual(trio[1][0], 13) self.assertEqual(trio[1][1], 'dddD') self.assertEqual(trio[2], 42) # Immutability, attribute access. try: trio.a__ = 997 self.fail("trio.a__ isn't immutable") # pragma: no cover except AttributeError: self.assertEqual(trio.a__, 'val0') try: trio.b__ = 'happiness' self.fail("trio.b__ isn't immutable") # pragma: no cover except AttributeError: # __eq__ works too self.assertEqual(trio.b__, duo) try: trio.b__.c__ = 'foo' self.fail("trio.b__.c__ isn't immutable") # pragma: no cover except AttributeError: self.assertEqual(trio.b__.c__, 13) # Immutability, indexed assignment: we get a TypeError: # "object does not support item assignment" try: trio[1][1] = 1942 self.fail("trio[1][1] isn't immutable") # pragma: no cover except TypeError: self.assertEqual(trio[1][1], 'dddD') try: # pylint: disable=unsupported-assignment-operation trio[2] = 'baz' self.fail("trio[2] isn't immutable") # pragma: no cover except TypeError: self.assertEqual(trio[2], 42)
def login_user_by_private_id(private_id, idporten_parameters): dict_user = user_service_proxy.create_or_update_user( private_id ) dict_person = get_person_by_nin(dict_user, private_id) if not dict_person: # create person dict_person = organisations_service_proxy.create_person( private_id, auth_token_username=dict_user['id'] ) misc = {"misc": idporten_parameters} data = {'person_id': dict_person["id"]} data.update(misc) dict_user = user_service_proxy.update_user( dict_user['id'], data ) # everything has been saved, we can login with flask-login user_struct = namedtuple('UserStruct', ' '.join(dict_user.keys())) user = user_struct(**dict_user) dict_person = get_person_by_nin(dict_user, private_id) person_struct = namedtuple('PersonStruct', ' '.join(dict_person.keys())) person = person_struct(**dict_person) auth_user = AuthUser(user, person) login_user(auth_user, remember=True) return auth_user
def get_leader_stats(self): """Returns leader and follower information. :returns: Tuple of leader name and follower dictionary :rtype: namedtuple """ r = self.client.send(2, 'get', '/stats/leader', return_raw=True) data = r.json() F = namedtuple('LStatFollower', ['counts', 'latency']) C = namedtuple('LStatCounts', ['fail', 'success']) L = namedtuple('LStatLatency', ['average', 'current', 'maximum', 'minimum', 'standard_deviation']) followers = {} for name, block in data['followers'].iteritems(): counts_raw = block['counts'] counts = C(fail=counts_raw['fail'], success=counts_raw['success']) latency_raw = block['latency'] latency = L(average=latency_raw['average'], current=latency_raw['current'], maximum=latency_raw['maximum'], minimum=latency_raw['minimum'], standard_deviation=latency_raw['standardDeviation']) followers[name] = F(counts=counts, latency=latency) return (data['leader'], followers)
def update(self): self._calc_md5_score() c = { "cms": namedtuple("CMS", ["name", "version"]), "platform": namedtuple("Platform", ["name", "version"]), "js": namedtuple("JavaScript", ["name", "version"]), "os": namedtuple("OS", ["name", "version"]), } for category in self.scores: # loop over the entries for the category for name in sorted(self.scores[category]): # get the versions and remove the ones that are most unlikely v = self.scores[category][name] versions = sorted(v.items(), key=lambda x: x[1], reverse=True) # if the highest rated version is blank, move it to the end of the list if versions[0][0] == "": versions = versions[1:] + [versions[0]] relevant = sorted(i[0] for i in versions if i[1] == versions[0][1]) for version in relevant: self.results.append(c[category](name, version)) # check if there are multiple precise version detection of the same platform platforms = self.platform_observations for platform in platforms: versions = platforms[platform] if len(versions) > 1: for version in versions: urls = list(versions[version]) self.add_platform_note(platform + " " + version, sorted(urls, key=lambda x: len(x))[0])
def compare_statistics(self, **kwargs): """ @type kwargs: object """ curr_values = self.unset_attributes.intersection(set(kwargs.keys())) changed_value = namedtuple('changed_value', 'previous, current') Ps = namedtuple('Ps', curr_values) self.logger.debug("Interface: moving {} attributes to previous".format(str(curr_values))) self.previous_statistics = Ps(**{eval("'{}'".format(value)):eval("self.{}".format(value)) for value in curr_values}) self.logger.debug("Interface: updating values {}".format(kwargs)) self.update(**kwargs) changed_values = {} for value in curr_values: if int(kwargs[value]) != int(eval('self.previous_statistics.{}'.format(value))): changed_values[value] = changed_value(int(eval('self.previous_statistics.{}'.format(value))), int(kwargs[value])) self.logger.debug("Interface: {} has changed from {} to {}".format(value, changed_values[value].previous,changed_values[value].current )) self.logger.debug("Interface: changed_values is {}".format(changed_values)) return changed_values
def gpapoints(letter, weight): #Defining how we are naming the elements in our named tuples ugpa = namedtuple('ugpa', ['grade','points']) wgpa = namedtuple('wgpa', ['grade','points']) #actually creating our tuples with the naming schemes defined above gradea = ugpa('a', 4) #named based on 'ugpa' scheme gradeb = ugpa('b', 3) gradec = ugpa('c', 2) graded = ugpa('d', 1) gradef = ugpa('f', 0) gradewa = wgpa('a', 5)#named based on the 'wgpa' scheme gradewb = wgpa('b', 4) gradewc = wgpa('c', 3) gradewd = wgpa('d', 1) gradewf = wgpa('f', 0) #creating lists of our tuples for later for loops wgrades = [gradewa, gradewb, gradewc, gradewd, gradewf] grades = [gradea, gradeb, gradec, graded, gradef] if weight == 'y': for grade in wgrades: if letter == grade.grade: gpa = grade.points break else: gpa = 0 if weight == 'n': for grade in grades: if letter == grade.grade: gpa = grade.points break else: gpa = 0 return gpa
def test_stateful_validator(): Locked = namedtuple('Locked', '') Unlocked = namedtuple('Unlocked', '') validator = StatefulStreamValidator({ Unlocked: { 'coin': lambda state, event: Unlocked(), 'push': lambda state, event: Locked(), }, Locked: { 'coin': lambda state, event: Unlocked(), 'push': lambda state, event: Locked(), }, }, start=Locked()) assertions = ( ('push', Locked()), ('coin', Unlocked()), ('coin', Unlocked()), ('push', Locked()), ('push', Locked()), ) inputs = (i[0] for i in assertions) validated = validator(i[0] for i in assertions) expected = (i[1] for i in assertions) for input, (state, event), expected in itertools.izip(inputs, validated, expected): assert input == event assert state == expected with pytest.raises(InvalidEventError): next(validator(('kick',)))
def pixel(xp, yp, channel_is_used, min_equ_ref, mean_equ_ref, eof, max_usable_eof, ss, ms, r): from constant import R17600, COMPONENT_PARTICLE channel_is_used_p = np.transpose(channel_is_used[xp, yp, :, :]).astype(bool) min_equ_ref_p = np.transpose(min_equ_ref[xp, yp, :, :]) mean_equ_ref_p = np.transpose(mean_equ_ref[xp, yp, :, :]) reg_scale = R17600 / r if r > 1100: eof_p = eof[xp, yp, :, :, :] max_usable_eof_p = max_usable_eof[xp, yp, :] else: eof_p = eof[xp, yp, :, :] max_usable_eof_p = max_usable_eof[xp, yp] tau_cam_ss = np.asfortranarray(np.transpose(ss[:, math.ceil(xp/reg_scale), math.ceil(yp/reg_scale), COMPONENT_PARTICLE, :, :], [0, 3, 1, 2])) tau_cam_ms = np.asfortranarray(np.transpose(ms[:, math.ceil(xp/reg_scale), math.ceil(yp/reg_scale), COMPONENT_PARTICLE, :, :], [0, 3, 1, 2])) reg = collections.namedtuple('reg', 'channel_is_used min_equ_ref mean_equ_ref eof max_usable_eof') smart = collections.namedtuple('smart', 'ss ms') reg_p = reg(channel_is_used_p, min_equ_ref_p, mean_equ_ref_p, eof_p, max_usable_eof_p) smart_p = smart(tau_cam_ss, tau_cam_ms) return reg_p, smart_p
def main(argv): _parseargs(argv) path = PARAM.path_to_expmap with open(path) as fh: KeyCoords, ValCoords = [namedtuple(n, c) for n, c in zip(('KeyCoords', 'ValCoords'), parse_line(fh.next()))] _ii = set([KeyCoords._fields.index('ligand_name'), KeyCoords._fields.index('ligand_concentration')]) _is = [i for i in range(len(KeyCoords._fields)) if i not in _ii] _j = ValCoords._fields.index('plate') _k = ValCoords._fields.index('well') del _ii def _reduced_kv(key, val): return tuple([key[i] for i in _is] + [val[_j], val[_k][1:]]) def _delete_field(tuple_, _i=ValCoords._fields.index('field')): return tuple_[:_i] + tuple_[_i + 1:] control_conc = mkd(len(_reduced_kv(KeyCoords._fields, ValCoords._fields)), noclobber=True) OutputValCoords = namedtuple('OutputValCoords', _delete_field(ValCoords._fields)) print_record([nt._fields for nt in KeyCoords, OutputValCoords])
def _one_scatterplot(cl_metadata, xy_data, xy_metadata, output=None, lims=None, specs=None, _spd=sp.ScatterplotData, _anno=co.namedtuple('_annotation', CellLineMetadata._fields + ('x', 'y')), _annopxl=co.namedtuple('_annotated_pixel', 'coords annotation')): if specs is None: specs = get_specs(cl_metadata) readouts = zip(*xy_data) if lims is None and WITHLIMITS: lims = limits(readouts) points = tuple(_spd(*(k + (x, y))) for k, x, y in zip(specs, *xy_data)) fig = sp.scatterplot(points, xy_metadata, lims=lims, outpath=output) pixels = sp.pixels(points, fig) annotations = tuple(_anno(*(m + r)) for m, r in zip(cl_metadata, readouts)) return tuple(sorted([_annopxl(p, a) for p, a in zip(pixels, annotations)], key=lambda r: (r.coords.y, r.coords.x, r.annotation.cell_line_name)))
def createParams(type_Experiment): if type_Experiment == 'scoreRandomFrames': list_params=['path_to_db', 'class_labels_map', 'npz_path', 'numberOfFrames', 'max_idx', 'n_jobs', 'table_idx_all', 'out_file_html', 'rel_path', 'width_height', 'out_file_frames', 'frameCountNorm'] params = namedtuple('Params_scoreRandomFrames',list_params); elif type_Experiment == 'testNpzScoreAccuracy': list_params=['path_to_db', 'path_to_hash', 'total_class_counts', 'class_idx', 'video_id', 'shot_id', 'num_hash_tables', 'num_hash_vals', 'tube_id', 'deep_features_idx', 'tube_file'] params = namedtuple('Params_testNpzSchoreAccuracy',list_params); elif type_Experiment == 'saveNpzScorePerShot': list_params=['path_to_db', 'total_class_counts', 'class_idx', 'video_id', 'shot_id', 'out_file_scores', 'path_to_hash', 'num_hash_tables'] params = namedtuple('Params_saveNpzScorePerShot',list_params); elif type_Experiment == 'visualizeBestTubeRank': list_params=['class_labels_map', 'rel_path', 'out_file_html', 'out_dir', 'score_info_file']; params = namedtuple('Params_visualizeBestTubeRank',list_params); elif type_Experiment =='verifyRecordedScoreMatchesDBScore': list_params=['path_to_db', 'path_to_hash', 'total_class_counts', 'img_path', 'class_label', 'video_id', 'shot_id', 'class_idx', 'score_file'] params = namedtuple('Params_verifyRecordedScoreMatchesDBScore',list_params); else: params=None; return params
def __init__(self, filenames, debugger): self.source = None #sources self.filenames = filenames try: self.source = open(self.filenames) # or "a+", whatever you need except IOError: print "Could not open file!" return #mandar llamar instancia de error y terminar self.line = 0 self.status = "" self.flags = {} self.debugger = debugger self.terminals = [] self.nonterminals = [] self.parsing_table = [] TokenWithDelimiter = namedtuple('Token', ('name', 'regexp', 'regexp_at_start', )) Token = namedtuple('Token', ('name', 'regexp', )) self.tokens = [Token( token[0], re.compile(token[1])) for token in util.TOKENS] self.tokens_with_del = [TokenWithDelimiter( token[0], re.compile(token[1]), re.compile(token[2])) for token in util.TOKENS_WITH_DELIMITERS] self.t = [] self.d = []
def test_get_dynamic_properties_with_token(self): ObjectContent = collections.namedtuple('ObjectContent', ['propSet']) DynamicProperty = collections.namedtuple('Property', ['name', 'val']) # Add a token to our results, indicating that more are available result = fake.FakeRetrieveResult(token='fake_token') # We expect these properties to be returned result.add_object(ObjectContent(propSet=[ DynamicProperty(name='name1', val='value1'), DynamicProperty(name='name2', val='value2') ])) # These properties should be ignored result.add_object(ObjectContent(propSet=[ DynamicProperty(name='name3', val='value3') ])) retrievePropertiesEx = mock.MagicMock(name='RetrievePropertiesEx') retrievePropertiesEx.return_value = result calls = {'RetrievePropertiesEx': retrievePropertiesEx} with stubs.fake_suds_context(calls): session = driver.VMwareAPISession() service_content = session.vim.get_service_content() props = session._call_method(vim_util, "get_dynamic_properties", service_content.propertyCollector, 'fake_type', None) self.assertEqual(props, { 'name1': 'value1', 'name2': 'value2' })
def get_all_valid_reqs(cls, requirements, requirements_txt): from collections import namedtuple from pkg_resources import Requirement import re numbered_item = namedtuple("numbered_item", ["position", "data"]) numbered_list = lambda dataset: [numbered_item(*ni) for ni in enumerate(dataset)] named_dataset = namedtuple("named_dataset", ["name", "dataset"]) inputs = [ named_dataset(name="command line", dataset=numbered_list(requirements)), ] if requirements_txt is not None: file_lines = re.split("[\n\r]", open(requirements_txt).read()) inputs.append(named_dataset( name="file: {0}".format(requirements_txt), dataset=numbered_list(file_lines) )) valid_reqs = [] whitespace = re.compile("^\s*$") for name, dataset in inputs: for position, req in dataset: try: Requirement.parse(req) valid_reqs.append(req) except ValueError: if whitespace.match(req) is None: # Don't warn if empty string or whitespace cls.logger.warn("Invalid requirement \"{0}\" at " \ "position {1} from {2}\n".format(req, position + 1, name)) return valid_reqs
def see(self): Marker=collections.namedtuple("MarkerBasis", "info dist rot_y"); MarkerInfo=collections.namedtuple("MarkerInfo", "code marker_type"); i=random.randint(0, 5) dist=random.randint(0, 8) if i == 0: return [] else: global inf if i == 1: inf = MarkerInfo(random.randint(0, 27), 0) elif i == 2: inf = MarkerInfo(random.randint(28, 31), 1) elif i == 3: inf = MarkerInfo(random.randint(32, 40), 2) elif i == 4: inf = MarkerInfo(random.randint(41, 64), 3) marker = Marker(inf, dist, random.randint(-180, 180)) return [marker] time.sleep(0.5)
def search(self, x, quota=10, with_dists=False): """ Return euclidean distance ranked results, along with the number of cells traversed to fill the quota. :param ndarray x: a query vector :param int quota: the number of desired results :param bool with_dists: boolean indicating whether result items should be returned with their distance :returns list results: the list of ranked results :returns int visited: the number of cells visited in the query """ # Retrieve results with multi-index retrieved, visited = self.get_result_quota(x, quota) # Compute distance for results results = self.compute_distances(x, retrieved) # Sort by distance results = sorted(results, key=lambda d: d[0]) if with_dists: Result = namedtuple('Result', ['id', 'code', 'dist']) results = map(lambda d: Result(d[1][0], d[1][1], d[0]), results) else: Result = namedtuple('Result', ['id', 'code']) results = map(lambda d: Result(d[1][0], d[1]), results) return results, visited
def test_extract_cite_history(): FakeRevision = namedtuple("Revision", ['id', 'timestamp', 'text']) FakeExtractor = namedtuple("Extractor", ['extract']) class FakePage: def __init__(self, id, title): self.id = id self.title = title def __iter__(self): return iter([ FakeRevision(1, Timestamp(1), "id1 id2"), FakeRevision(2, Timestamp(2), "id1 id3"), FakeRevision(3, Timestamp(3), "id1 id2 id3"), FakeRevision(4, Timestamp(4), "id1 id2 id4"), FakeRevision(5, Timestamp(5), "id1 id2 id4"), ]) fake_page = FakePage(1, "Title") def extract(text): return (Identifier('fake', id) for id in text.split(" ")) extractor = FakeExtractor(extract) expected = [(1, "Title", 1, Timestamp(1), "fake", "id1"), (1, "Title", 1, Timestamp(1), "fake", "id2"), (1, "Title", 4, Timestamp(4), "fake", "id4")] citations = list(extract_cite_history(fake_page, [extractor])) eq_(len(citations), len(expected)) for cite in extract_cite_history(fake_page, [extractor]): assert cite in expected
def get_thermo_data(output): """ traverse output of runs and extract thermo data columns """ if isinstance(output, str): lines = output.splitlines() else: lines = output runs = [] columns = [] in_run = False for line in lines: if line.startswith("Memory usage per processor"): in_run = True elif in_run and len(columns) == 0: # first line after memory usage are column names columns = line.split() current_run = {} for col in columns: current_run[col] = [] elif line.startswith("Loop time of "): in_run = False columns = None thermo_data = namedtuple('ThermoData', list(current_run.keys()))(*list(current_run.values())) r = {'thermo' : thermo_data } runs.append(namedtuple('Run', list(r.keys()))(*list(r.values()))) elif in_run and len(columns) > 0: values = [float(x) for x in line.split()] for i, col in enumerate(columns): current_run[col].append(values[i]) return runs
def parse_code_listing_file(group_filename): ''' Parse file and return list of named tuples and flag indicating if alternate id is included true: list of tuples is (code_id, max_number_plants, alternate_id) false: list of tuples is (code_id, max_number_plants) ''' code_listings = [] alternate_ids_included = False CodeListing = namedtuple('CodeListing', 'id max_plants') CodeListingAlternate = namedtuple('CodeListingAlternate', 'id max_plants alternate_id') with open(group_filename, 'r') as group_file: lines = group_file.readlines() for line in lines: if line.isspace(): continue fields = [field.strip() for field in line.split(',')] if len(fields) == 0: continue try: code_id = fields[0] max_plants = int(fields[1]) if len(fields) > 2 and fields[2] != '': alternate_id = fields[2] alternate_ids_included = True new_listing = CodeListingAlternate(code_id, max_plants, alternate_id) else: new_listing = CodeListing(code_id, max_plants) code_listings.append(new_listing) except (IndexError, ValueError): print 'Bad line: {0}'.format(line) continue return code_listings, alternate_ids_included
def build_diet_model(**kwargs): # Create tuples with named fields for foods and nutrients Food = namedtuple("Food", ["name", "unit_cost", "qmin", "qmax"]) food = [Food(*f) for f in FOODS] Nutrient = namedtuple("Nutrient", ["name", "qmin", "qmax"]) nutrients = [Nutrient(*row) for row in NUTRIENTS] food_nutrients = {(fn[0], nutrients[n].name): fn[1 + n] for fn in FOOD_NUTRIENTS for n in range(len(NUTRIENTS))} # Model mdl = Model("diet", **kwargs) # Decision variables, limited to be >= Food.qmin and <= Food.qmax qty = dict((f, mdl.continuous_var(f.qmin, f.qmax, f.name)) for f in food) # Limit range of nutrients, and mark them as KPIs for n in nutrients: amount = mdl.sum(qty[f] * food_nutrients[f.name, n.name] for f in food) mdl.add_range(n.qmin, amount, n.qmax) mdl.add_kpi(amount, publish_name="Total %s" % n.name) # Minimize cost mdl.minimize(mdl.sum(qty[f] * f.unit_cost for f in food)) mdl.print_information() return mdl
def test_alter_udt(self): """ Test to ensure that altered UDT's are properly surfaced without needing to restart the underlying session. @since 3.0.0 @jira_ticket PYTHON-226 @expected_result UDT's will reflect added columns without a session restart. @test_category data_types, udt """ # Create udt ensure it has the proper column names. self.session.set_keyspace(self.keyspace_name) self.session.execute("CREATE TYPE typetoalter (a int)") typetoalter = namedtuple('typetoalter', ('a')) self.session.execute("CREATE TABLE {0} (pk int primary key, typetoalter frozen<typetoalter>)".format(self.function_table_name)) insert_statement = self.session.prepare("INSERT INTO {0} (pk, typetoalter) VALUES (?, ?)".format(self.function_table_name)) self.session.execute(insert_statement, [1, typetoalter(1)]) results = self.session.execute("SELECT * from {0}".format(self.function_table_name)) for result in results: self.assertTrue(hasattr(result.typetoalter, 'a')) self.assertFalse(hasattr(result.typetoalter, 'b')) # Alter UDT and ensure the alter is honored in results self.session.execute("ALTER TYPE typetoalter add b int") typetoalter = namedtuple('typetoalter', ('a', 'b')) self.session.execute(insert_statement, [2, typetoalter(2, 2)]) results = self.session.execute("SELECT * from {0}".format(self.function_table_name)) for result in results: self.assertTrue(hasattr(result.typetoalter, 'a')) self.assertTrue(hasattr(result.typetoalter, 'b'))
def userInterface4(): master = Tk() dialog = MyDialog2(master) print dialog.result[0] selectOS = dialog.result[0] hostIPAdd = dialog.result[1] hostUserID = dialog.result[2] hostPassword = dialog.result[3] macAddress = dialog.result[4] OSID = dialog.result[5] selectDevice = dialog.result[6] sAnotherOS = dialog.result[7] if sAnotherOS == 1: if selectOS == 1: WinXP = collections.namedtuple('WinXP', ['a', 'b', 'c', 'd', 'e', 'f', 'g']) WinXPData = WinXP(selectOS, hostIPAdd, hostUserID, hostPassword, macAddress, OSID, selectDevice) elif selectOS == 2: WinVista = collections.namedtuple('WinVista', ['a', 'b', 'c', 'd', 'e', 'f', 'g']) WinVistaData = WinVista(selectOS, hostIPAdd, hostUserID, hostPassword, macAddress, OSID, selectDevice) elif selectOS == 3: Win7 = collections.namedtuple('Win7', ['a', 'b', 'c', 'd', 'e', 'f', 'g']) Win7Data = Win7(selectOS, hostIPAdd, hostUserID, hostPassword, macAddress, OSID, selectDevice) elif selectOS == 4: Win8 = collections.namedtuple('Win8', ['a', 'b', 'c', 'd', 'e', 'f', 'g']) Win8Data = Win8(selectOS, hostIPAdd, hostUserID, hostPassword, macAddress, OSID, selectDevice) mainloop() #Data = collections.namedtuple('Data', ['a', 'b', 'c', 'd', 'e', 'f', 'g']) #testdata = Data(selectOS, hostIPAdd, hostUserID, hostPassword, macAddress, OSID, selectDevice) return WinXPData, WinVistaData, Win7Data, Win8Data
# -*- coding: utf-8 -*- """Efficient serialization of Django Models for use in Celery that ensure the state of the world.""" # :copyright: (c) 2015 Alex Hayes and individual contributors, # All rights reserved. # :license: MIT License, see LICENSE for more details. from collections import namedtuple version_info_t = namedtuple( 'version_info_t', ('major', 'minor', 'micro', 'releaselevel', 'serial'), ) VERSION = version_info_t(0, 2, 1, '', '') __version__ = '{0.major}.{0.minor}.{0.micro}{0.releaselevel}'.format(VERSION) __author__ = 'Alex Hayes' __contact__ = '*****@*****.**' __homepage__ = 'http://github.com/alexhayes/django-cereal' __docformat__ = 'restructuredtext' # -eof meta-
def __init__(self): self.store = {} self.item_type = namedtuple('PkTuple', 'pk resource_obj')
# -*- coding: utf-8 -*- # Copyright (C) 2019 tribe29 GmbH - License: GNU General Public License v2 # This file is part of Checkmk (https://checkmk.com). It is subject to the terms and # conditions defined in the file COPYING, which is part of this source code package. # pylint: disable=redefined-outer-name # flake8: noqa import logging import collections import pytest # type: ignore[import] from testlib.utils import api_str_type from testlib.fixtures import web # pylint: disable=unused-import DefaultConfig = collections.namedtuple("DefaultConfig", ["core"]) logger = logging.getLogger(__name__) @pytest.fixture(scope="module", params=["nagios", "cmc"]) def test_cfg(request, web, site): config = DefaultConfig(core=request.param) site.set_config("CORE", config.core, with_restart=True) print("Applying default config") web.add_host("test-host", attributes={ "ipaddress": "127.0.0.1", "tag_agent": "no-agent", })
class Scheduler(threading.Thread): Event = collections.namedtuple('Event', ['timestamp', 'data']) Event.__eq__ = lambda self, other: self.timestamp == other.timestamp Event.__ne__ = lambda self, other: self.timestamp != other.timestamp Event.__gt__ = lambda self, other: self.timestamp > other.timestamp Event.__ge__ = lambda self, other: self.timestamp >= other.timestamp Event.__lt__ = lambda self, other: self.timestamp < other.timestamp Event.__le__ = lambda self, other: self.timestamp <= other.timestamp def __init__(self): """Reentrant lock to allow locked method calling locked method.""" super(Bot.Scheduler, self).__init__() self._eventq = [] self._lock = threading.RLock() self._event_handler = None def _locked(fn): def k(self, *args, **kwargs): with self._lock: return fn(self, *args, **kwargs) return k @_locked def _insert_event(self, data, when): ev = self.Event(when, data) bisect.insort(self._eventq, ev) return ev @_locked def _remove_event(self, event): # Find event according to its timestamp. # Index returned should be one behind. i = bisect.bisect(self._eventq, event) """ Having two events with identical timestamp is unlikely but possible. I am going to move forward and compare timestamp AND object address to make sure the correct object is found.""" while i > 0: i -= 1 e = self._eventq[i] if e.timestamp != event.timestamp: raise exception.EventNotFound(event) elif id(e) == id(event): self._eventq.pop(i) return raise exception.EventNotFound(event) @_locked def _pop_expired_event(self): if not self._eventq: return None if self._eventq[0].timestamp <= time.time(): return self._eventq.pop(0) else: return None def event_at(self, when, data): """ Schedule some data to emit at an absolute timestamp. :type when: int or float :type data: dictionary :return: an internal Event object """ return self._insert_event(data, when) def event_later(self, delay, data): """ Schedule some data to emit after a number of seconds. :type delay: int or float :type data: dictionary :return: an internal Event object """ return self._insert_event(data, time.time() + delay) def event_now(self, data): """ Emit some data as soon as possible. :type data: dictionary :return: an internal Event object """ return self._insert_event(data, time.time()) def cancel(self, event): """ Cancel an event. :type event: an internal Event object """ self._remove_event(event) def run(self): while 1: e = self._pop_expired_event() while e: if callable(e.data): d = e.data() # call the data-producing function if d is not None: self._event_handler(d) else: self._event_handler(e.data) e = self._pop_expired_event() time.sleep(0.1) def run_as_thread(self): self.daemon = True self.start() def on_event(self, fn): self._event_handler = fn
def _mock_head(url): from collections import namedtuple HeadInfo = namedtuple('HeadInfo', ['headers']) return HeadInfo(headers={})
# Copyright (C) 2018 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from collections import namedtuple CacheEntry = namedtuple('CacheEntry', 'model_plural class_name cache_type') MappingEntry = namedtuple('MappingEntry', 'class_name attr polymorph') def resource(model_plural, class_name, cache_type='memcache'): return CacheEntry(model_plural, class_name, cache_type) def mapping(class_name, attr, polymorph=False): return MappingEntry(class_name, attr, polymorph) def all_cache_entries(): ret = [ resource('access_groups', 'AccessGroup'), resource('audits', 'Audit'), resource('custom_attribute_values', 'CustomAttributeValue'), resource('categorizations', 'Categorization'), resource('category_bases', 'CategoryBase'), resource('comments', 'Comment'), resource('control_categories', 'ControlCategory'), resource('control_assertions', 'ControlAssertion'), resource('contexts', 'Context'), resource('controls', 'Control'), resource('assessments', 'Assessments'), resource('assessment_templates', 'AssessmentTemplate'),
sentiment_net.eval() correct = 0 total = 0 for data in TEST_LOADER: ins, labels = data ins, labels = ins.cuda(), labels.cuda() outputs = sentiment_net(Variable(ins)) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum() test_acc = correct / total return dev_acc, test_acc torch.manual_seed(77) np.random.seed(77) Result = namedtuple('Result', 'hidden_dim learning_rate weight_decay dev test') RESULTS = [] for hidden_layer_dim in HIDDEN_LAYER_DIMS: for learning_rate in LEARNING_RATES: for weight_decay in WEIGHT_DECAYS: start = time.time() print('Hidden Layer Dimension: '+str(hidden_layer_dim)+' Learning Rate: '+str(learning_rate)+' Weight Decay: '+str(weight_decay)) dev_acc, test_acc = train(hidden_layer_dim, learning_rate, weight_decay) print('Dev Accuracy: ', dev_acc) RESULTS.append(Result(hidden_layer_dim, learning_rate, weight_decay, dev_acc, test_acc)) print('Time: ', time.time() - start) RESULTS = sorted(RESULTS, key=lambda x: x.dev, reverse=True) print('Best Result:', RESULTS[0]) ################################################################## # Graphs
# DistributedDelegate and so can be used directly in cross-tower mode. class Mirrored(DistributedDelegate): """Holds a map from device to values which are kept in sync.""" def _get_cross_tower(self): device = device_util.canonicalize(device_util.current()) if device in self._index: return self._index[device] return list(self._index.values())[0] def _assign_on_device(device, variable, tensor): with ops.device(device): return variable.assign(array_ops.identity(tensor)) DistributedVarOp = collections.namedtuple("DistributedVarOp", ["name", "graph", "type"]) class DistributedVariable(DistributedDelegate): """Holds a map from device to variables.""" # TODO(josh11b): Support changing the set of variables if e.g. if new # devices are joining or a device is to leave. def __init__(self, index): # Child class must set self._primary_var before calling # super(...).__init__(index). self._common_name = self._primary_var.name.split(":")[0] # Use a weakref to make it easy to map from the contained values # to the container without introducing a reference cycle. for v in six.itervalues(index):
from collections import namedtuple import testcase case = namedtuple("Testcase", ["Input", "Output"]) class Testcase(testcase.Testcase): def __init__(self): self.testcases = [] self.testcases.append(case(Input=([1, 2, 0, 3, 0], 1), Output=3)) self.testcases.append(case(Input=([3, 4, 5, 2, 1, 7, 3, 4, 7], 3), Output=3)) self.testcases.append(case(Input=([1, 2, 4, 1, 2, 5, 1, 2, 6], 3), Output=3)) def get_testcases(self): return self.testcases
# Builds and run test archery build --targets=all --targets=test build """ # Arrow's cpp cmake configuration conf = CppConfiguration(**kwargs) # This is a closure around cmake invocation, e.g. calling `def.build()` # yields a directory ready to be run with the generator cmake_def = CppCMakeDefinition(src.cpp, conf) # Create build directory build = cmake_def.build(build_dir, force=force) for target in targets: build.run(target) LintCheck = namedtuple('LintCheck', ('option_name', 'help')) lint_checks = [ LintCheck('clang-format', "Format C++ files with clang-format."), LintCheck('clang-tidy', "Lint C++ files with clang-tidy."), LintCheck('cpplint', "Lint C++ files with cpplint."), LintCheck('iwyu', "Lint changed C++ files with Include-What-You-Use."), LintCheck('python', "Format and lint Python files with autopep8 and flake8."), LintCheck('numpydoc', "Lint Python files with numpydoc."), LintCheck('cmake-format', "Format CMake files with cmake-format.py."), LintCheck('rat', "Check all sources files for license texts via Apache RAT."), LintCheck('r', "Lint R files."), LintCheck('rust', "Lint Rust files."), LintCheck('docker', "Lint Dockerfiles with hadolint."),
class ParameterSet(namedtuple('ParameterSet', 'values, marks, id')): @classmethod def param(cls, *values, **kw): marks = kw.pop('marks', ()) if isinstance(marks, MarkDecorator): marks = marks, else: assert isinstance(marks, (tuple, list, set)) def param_extract_id(id=None): return id id = param_extract_id(**kw) return cls(values, marks, id) @classmethod def extract_from(cls, parameterset, legacy_force_tuple=False): """ :param parameterset: a legacy style parameterset that may or may not be a tuple, and may or may not be wrapped into a mess of mark objects :param legacy_force_tuple: enforce tuple wrapping so single argument tuple values don't get decomposed and break tests """ if isinstance(parameterset, cls): return parameterset if not isinstance(parameterset, MarkDecorator) and legacy_force_tuple: return cls.param(parameterset) newmarks = [] argval = parameterset while isinstance(argval, MarkDecorator): newmarks.append(MarkDecorator(Mark( argval.markname, argval.args[:-1], argval.kwargs))) argval = argval.args[-1] assert not isinstance(argval, ParameterSet) if legacy_force_tuple: argval = argval, if newmarks: warnings.warn(MARK_PARAMETERSET_UNPACKING) return cls(argval, marks=newmarks, id=None) @classmethod def _for_parametrize(cls, argnames, argvalues, function, config): if not isinstance(argnames, (tuple, list)): argnames = [x.strip() for x in argnames.split(",") if x.strip()] force_tuple = len(argnames) == 1 else: force_tuple = False parameters = [ ParameterSet.extract_from(x, legacy_force_tuple=force_tuple) for x in argvalues] del argvalues if not parameters: mark = get_empty_parameterset_mark(config, argnames, function) parameters.append(ParameterSet( values=(NOTSET,) * len(argnames), marks=[mark], id=None, )) return argnames, parameters
for _uri, _prefix in DEFAULT_NAMESPACES: ET.register_namespace(_prefix, _uri) XPACKET_BEGIN = b"""<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>\n""" XMP_EMPTY = b"""<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="pikepdf"> <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> </rdf:RDF> </x:xmpmeta> """ XPACKET_END = b"""<?xpacket end="w"?>\n""" TRIVIAL_XMP = (XPACKET_BEGIN + XMP_EMPTY + XPACKET_END) XmpContainer = namedtuple('XmpContainer', ['rdf_type', 'py_type', 'insert_fn']) XMP_CONTAINERS = [ XmpContainer('Bag', set, set.add), XmpContainer('Seq', list, list.append), ] # These are the illegal characters in XML 1.0. (XML 1.1 is a bit more permissive, # but we'll be strict to ensure wider compatibility.) re_xml_illegal_chars = re.compile( r"(?u)[^\x09\x0A\x0D\x20-\uD7FF\uE000-\uFFFD\u10000-\u10FFFF]" ) # Repeat this to avoid circular from top package's pikepdf.__version__ try: pikepdf_version = _get_distribution(__name__).version
buf_len = 0 buf.append(data_bytes) buf_len += data_len if buf: send_buf(buf) msg_number += 1 return msg_number def get_func_for_call(self, call_name): """ Return callable object implementing the named call, or None. """ return self.factory.get_func_for_call(call_name) ClientCallState = collections.namedtuple( 'ClientCallState', ('d', 'cancel_dc', 'streaming_cb')) class ClientProtocol(Protocol): default_timeout = 60 * 60 # 1h def __init__(self, *args, **kwargs): super(ClientProtocol, self).__init__(*args, **kwargs) # Key: call ID. Value: ClientCallState. self.calls = {} def send_early_error(self, error): """ Clients don't respond to invalid messages. """
# https://www.hackerrank.com/challenges/py-collections-namedtuple/problem?h_r=next-challenge&h_v=zen from collections import namedtuple # actual solution n = int(input()) Student = namedtuple('Student', input()) total = 0 for _ in range(n): pupil = Student(*input().split()) total += int(pupil.MARKS) print(total / n) # some examples of usage: # a very fun usage Point = namedtuple('Point', 'x,y') pt1 = Point(1, 2) pt2 = Point(3, 4) # mock dot product dot_product = pt1.x * pt2.x + pt1.y * pt2.y print(dot_product) # another interesting usage. Car = namedtuple('Car', 'PRICE Mileage Color Make') myCar = Car(30000, Mileage=35, Color='Silver', Make=2020) print(myCar) # wtf! wow, that's so nice. print(myCar.Color) # damn! this is so convenient newCar = Car(*[24000, 21, 'Black', 2013])
import os import threading from collections import defaultdict, namedtuple from ycmd import responses from ycmd.completers.general.filename_completer import ( GetPathType, GetPathTypeName ) from ycmd.utils import GetModificationTime, ListDirectory """ Represents single include completion candidate. name is the name/string of the completion candidate, entry_type is an integer indicating whether the candidate is a 'File', 'Dir' or both (See EXTRA_INFO_MAP in filename_completer). """ IncludeEntry = namedtuple( 'IncludeEntry', [ 'name', 'entry_type' ] ) class IncludeList( object ): """ Helper class for combining include completion candidates from several include paths. self._includes is a dictionary whose keys are IncludeEntry `name`s and values are IncludeEntry `entry_type`s. """ def __init__( self ): self._includes = defaultdict( int ) def AddIncludes( self, includes ):
class PeerStatus(Enum): CLOSED = 1 TEMP = 2 PEER = 3 class EndpointStatus(Enum): # Endpoint will be used for peering PEERING = 1 # Endpoint will be used to request peers TOPOLOGY = 2 EndpointInfo = namedtuple('EndpointInfo', ['status', 'time', "retry_threshold"]) StaticPeerInfo = namedtuple('StaticPeerInfo', ['time', 'retry_threshold', 'count']) INITIAL_RETRY_FREQUENCY = 10 MAXIMUM_RETRY_FREQUENCY = 300 MAXIMUM_STATIC_RETRY_FREQUENCY = 3600 MAXIMUM_STATIC_RETRIES = 24 TIME_TO_LIVE = 3 # This is the protocol version number. It should only be incremented when # there are changes to the network protocols, as well as only once per # release.
from ...robot.io import AbstractIO from ..conversion import (dxl_code_all, dxl_decode_all, decode_error, dxl_to_model, position_range) logger = logging.getLogger(__name__) # With this logger you should always provide as extra: # - the port # - the baudrate # - the timeout _DxlControl = namedtuple('_DxlControl', ('name', 'address', 'length', 'nb_elem', 'access', 'models', 'dxl_to_si', 'si_to_dxl', 'getter_name', 'setter_name')) class _DxlAccess(object): readonly, writeonly, readwrite = range(3) class AbstractDxlIO(AbstractIO): """ Low-level class to handle the serial communication with the robotis motors. """ __used_ports = set() __controls = [] _protocol = None
from collections import namedtuple # Use this named tuple in your config.py to give your stations a name URI = namedtuple("URI", "uri name") uris = [URI('x-sonosapi-radio:<the_first_uri>', "Radio Station 1"), URI('x-sonosapi-radio:<the_second_uri>', "Radio Station 2"), URI('x-sonos-spotify:<a_spotify_uri>', "My Cool Playlist"), ] rooms = [("A room"), ("Some other room"), ("A room", "Some other room"), ("Room 3", "A room", "A different room entirely"), ]
)) # ---------- form_blob() end ---------------------------------------------------------------------------------------- # ************ PROGRAM BODY ********************************************************************************************* ave = 20 # Load inputs -------------------------------------------------------------------- image = misc.imread('./../images/raccoon_eye.jpg', flatten=True).astype(int) height, width = image.shape # Main --------------------------------------------------------------------------- start_time = time() nt_blob = namedtuple('blob', 'I Derts sign alt rng box map root_blob seg_') frame_of_blobs = image_to_blobs(image) # from intra_blob_debug import intra_blob_hypot # not yet functional, comment-out to run # frame_of_blobs = intra_blob(hypot_g, frame_of_blobs) # evaluate for deeper clustering inside each blob, recursively # DEBUG -------------------------------------------------------------------------- from DEBUG import draw, over_draw, map_blobs, map_blob, map_segment, empty_map # draw('./../debug/root_blobs', map_blobs(frame_of_blobs)) from intra_comp import intra_comp, hypot_g from comp_range import comp_range from comp_angle import comp_angle from comp_gradient import comp_gradient
# maxJerk = 30 # # waypoints = [ # pf.Waypoint(0.5 * X_ROBOT_LENGTH, Y_WALL_TO_START + 0.5 * Y_ROBOT_WIDTH, 0), # pf.Waypoint(X_WALL_TO_SWITCH_CENTER - 4, Y_WALL_TO_START + 0.5 * Y_ROBOT_WIDTH - 1.5, 0), # pf.Waypoint(X_WALL_TO_SWITCH_CENTER, Y_WALL_TO_START + 0.5 * Y_ROBOT_WIDTH + 2, pf.d2r(90.0)), # ] # # GeneratePath(os.path.dirname(__file__), "left_start_left_switch", waypoints, settings) #=================================================================================================== PathFinderSettings = namedtuple("PathFinderSettings", ["order", "samples", "period", "maxVelocity", "maxAcceleration", "maxJerk"]) settings = PathFinderSettings(order=pf.FIT_HERMITE_QUINTIC, samples=1000000, period=0.01, maxVelocity=5.0, maxAcceleration=10, maxJerk=30) # The waypoints are entered as X, Y, and Theta. +X is forward, +Y is left, and +Theta is measured from +X to +Y xOffset = 0.5 * X_ROBOT_LENGTH yOffset = -(Y_WALL_TO_START + 0.5 * Y_ROBOT_WIDTH) waypoints = [ pf.Waypoint(xOffset, yOffset, 0), pf.Waypoint(X_WALL_TO_SWITCH_CENTER - 48 /12, 18 / 12 + yOffset, 0), pf.Waypoint(X_WALL_TO_SWITCH_CENTER, -24 / 12 + yOffset, pf.d2r(90.0)),
import re import shutil import sys import xml.etree.ElementTree import generate_v14_compatible_resources from util import build_utils # Import jinja2 from third_party/jinja2 sys.path.insert( 1, os.path.join(os.path.dirname(__file__), '../../../third_party')) from jinja2 import Template # pylint: disable=F0401 # Represents a line from a R.txt file. TextSymbolsEntry = collections.namedtuple( 'RTextEntry', ('java_type', 'resource_type', 'name', 'value')) def _ParseArgs(args): """Parses command line options. Returns: An options object as from optparse.OptionsParser.parse_args() """ parser = optparse.OptionParser() build_utils.AddDepfileOption(parser) parser.add_option('--android-sdk-jar', help='the path to android jar file.') parser.add_option('--aapt-path', help='path to the Android aapt tool') parser.add_option('--non-constant-id', action='store_true')
from collections import defaultdict, namedtuple import itertools import typing from cached_property import cached_property from .. import utils, consts Size = namedtuple("Size", "height,width") class Cell: def __init__(self, row, col, style, value, row_height, col_width): self.row = row self.col = col self.value = value self.style = style self.row_height = row_height self.col_width = col_width def move(self, row, col): self.row += row self.col += col def __eq__(self, other): return (self.row == other.row and self.col == other.col and self.value == other.value and self.style == other.style) def __str__(self): # pragma: no cover return "Cell({}, {}, {})".format(self.row, self.col, self.value)
import os import sys import re import math import cv2 import numpy as np import collections import torch.utils.data as data import random import torch left_nose_idx=12 right_nose_idx=20 DataPath = collections.namedtuple('DataPath', ['imgfile_fullpath', 'ptfile_fullpath']) ImgWithLabel = collections.namedtuple('ImgWithLabel', ['img', 'label']) dst_dir='/Users/momo/Downloads//60point/test_Data/' landmark_order=[6,8,7,10,9,1,3,2,5,4, 20,22,21,23,24,26,25,28,27, 11,13,12,14,15,17,16,19,18, 30,29,31,32, 33,35,34,39,38,37,36,40,44,43,42,41, 45,46,48,47,50,49,52,51,60,59,58,57,56,55,54,53] class FaceDataSet(data.Dataset): def __init__(self, root, load_size =300): super(FaceDataSet, self).__init__() self.all_data = [] self.dst_size = 128 self.src_map = {}
class Block(collections.namedtuple('Block', ['scope', 'unit_fn', 'args'])): """A named tuple describing a ResNet block.
# # pylint: disable=invalid-name """anyconfig globals. """ import collections import anyconfig.init PACKAGE = "anyconfig" AUTHOR = "Satoru SATOH <*****@*****.**>" VERSION = "0.9.4" LOGGER = anyconfig.init.getLogger(PACKAGE) IOI_KEYS = "src type path processor opener".split() IOInfo = collections.namedtuple("IOInfo", IOI_KEYS) IOI_TYPES = (IOI_NONE, IOI_PATH_STR, IOI_PATH_OBJ, IOI_STREAM) = \ (None, "path", "pathlib.Path", "stream") class UnknownParserTypeError(RuntimeError): """Raise if no parsers were found for given type.""" def __init__(self, forced_type): msg = "No parser found for type '%s'" % forced_type super(UnknownParserTypeError, self).__init__(msg) class UnknownFileTypeError(RuntimeError): """Raise if not parsers were found for given file path.""" def __init__(self, path):
class User(namedtuple("User", USER_FIELDS)): """
from os import environ from collections import namedtuple MySQLConfig = namedtuple('MySQLConfig', 'host port user password db') def read_mysql_config(): """ Reads the environment variables injected by docker/docker-compose/virtualenv to connect to the mysql database. """ return MySQLConfig(host=environ.get('MSQL_HOST', None), port=int(environ.get('MSQL_PORT', 0)), user=environ.get('MSQL_USER', None), password=environ.get('MSQL_PWD', None), db=environ.get('MSQL_DATABASE', None)) def read_config(): return { "max_rating": float(environ.get('MAX_RATING', 1)), "min_rating": float(environ.get('MIN_RATING', 0)), "positive_cutoff": float(environ.get('POS_CUTOFF', 0)) # rating > cutoff -> 1, sonst -1 }
"""This file defines a transition. Transition from state A to state B includes -- observation_tm1 - observation at time t - 1 -- action_tm1 - action at time t - 1 -- reward_t - reward at time t for taking action_tm1 while at observation_tm1 -- observation_t - observation at time t. -- legal_moves_t - legal moves for observation_t -- terminal_t - whether the transition is terminal. """ from collections import namedtuple Transition = namedtuple( "Transition", ["observation_tm1", "action_tm1", "reward_t", "observation_t", "legal_moves_t", "terminal_t"])
arr = extract(dstore, 'rupture_info') if export.sanity_check: bad = view('bad_ruptures', dstore) if len(bad): # nonempty print(text_table(bad), file=sys.stderr) comment = dstore.metadata comment.update(investigation_time=oq.investigation_time, ses_per_logic_tree_path=oq.ses_per_logic_tree_path) arr.array.sort(order='rup_id') writers.write_csv(dest, arr, comment=comment) return [dest] # ####################### export hazard curves ############################ # HazardCurve = collections.namedtuple('HazardCurve', 'location poes') def export_hmaps_csv(key, dest, sitemesh, array, comment): """ Export the hazard maps of the given realization into CSV. :param key: output_type and export_type :param dest: name of the exported file :param sitemesh: site collection :param array: a composite array of dtype hmap_dt :param comment: comment to use as header of the exported CSV file """ curves = util.compose_arrays(sitemesh, array) writers.write_csv(dest, curves, comment=comment) return [dest]
""" Uses the official Khronos-XML specs to generate a GL/GLES/EGL/GLX/WGL Loader made for your needs. Glad currently supports the languages C, D, Nim and Volt. """ from collections import namedtuple import logging import sys from glad.opener import URLOpener from glad.spec import SPECS import glad.lang Version = namedtuple('Version', ['major', 'minor']) logger = logging.getLogger('glad') def main(): import os.path import argparse from argparse import ArgumentParser opener = URLOpener() def get_spec(value): if value not in SPECS: raise argparse.ArgumentTypeError('Unknown specification')