当前位置: 首页>>代码示例>>Python>>正文


Python models.State类代码示例

本文整理汇总了Python中models.State的典型用法代码示例。如果您正苦于以下问题:Python State类的具体用法?Python State怎么用?Python State使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了State类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_state

def get_state():
  try:
    state = State.objects.get()
  except State.DoesNotExist:
    state = State()
    state.save()
  return state
开发者ID:mcdermott-scholars,项目名称:mcdermott,代码行数:7,代码来源:views.py

示例2: post

	def post(self):
		action = self.request.POST.get('managerAction')

		if 'toggle' == action:
			state = self.get_state(self.request.POST.get('abbreviation'))
			if state:
				state.striking = not state.striking
				state.put()

		elif 'delete' == action:
			state = self.get_state(self.request.POST.get('abbreviation'))
			if state:
				state.delete()

		elif 'add' == action:
			state = self.get_state(self.request.POST.get('abbreviation'))
			if not state:
				stateName = self.request.POST.get('stateName')
				stateAbbr = self.request.POST.get('abbreviation')
				striking = 'striking' in self.request.POST
				newState = State(name=stateName, abbreviation=stateAbbr, striking=striking)
				newState.put()

		memcache.delete('template_values')
		self.redirect("/manager")
开发者ID:scompt,项目名称:Streikt-die-Bahn,代码行数:25,代码来源:manager.py

示例3: flush

def flush():
    ndb.delete_multi(School.query().fetch(keys_only=True))
    ndb.delete_multi(QuestionInstance.query().fetch(keys_only=True))
    ndb.delete_multi(State_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_States.query().fetch(keys_only=True))
    ndb.delete_multi(Question.query().fetch(keys_only=True))
    ndb.delete_multi(State.query().fetch(keys_only=True))
    ndb.delete_multi(Address.query().fetch(keys_only=True))
    ndb.delete_multi(Teacher.query().fetch(keys_only=True))
    ndb.delete_multi(Class.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment_Record.query().fetch(keys_only=True))
    ndb.delete_multi(Student.query().fetch(keys_only=True))
    ndb.delete_multi(UserInfo.query().fetch(keys_only=True))
    ndb.delete_multi(Student_Assessments.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment.query().fetch(keys_only=True))
    ndb.delete_multi(Subject.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(State_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_States.query().fetch(keys_only=True))
    ndb.delete_multi(Subject_Topics.query().fetch(keys_only=True))
    ndb.delete_multi(Student_Assessments.query().fetch(keys_only=True))
    ndb.delete_multi(Topic.query().fetch(keys_only=True))
    ndb.delete_multi(User.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment_Record.query().fetch(keys_only=True))
    ndb.delete_multi(State_Types.query().fetch(keys_only=True))
开发者ID:anks315,项目名称:Assesment2,代码行数:25,代码来源:dummydata3.py

示例4: wipe_status

def wipe_status():
    """
    Blanks the status fields for congress and presidential races.
    """

    rq = Race.update(
        precincts_reporting=0,
        ap_called=False,
        ap_called_time=None,
        npr_called=False,
        npr_called_time=None
    )
    rq.execute()

    cq = Candidate.update(
        vote_count=0,
        ap_winner=False,
        npr_winner=False
    )
    cq.execute()

    sq = State.update(
        ap_call='u',
        ap_called_at=None,
        npr_call='u',
        npr_called_at=None,
        precincts_reporting=0,
        rep_vote_count=0,
        dem_vote_count=0
    )
    sq.execute()
    write_www_files()
开发者ID:imclab,项目名称:electris,代码行数:32,代码来源:fabfile.py

示例5: bootstrap_president

def bootstrap_president():
    """
    Creates/overwrites presidential state results with initial data.
    """
    with open('initial_data/president_bootstrap.csv') as f:
        reader = csv.DictReader(f)
        for row in reader:
            for field in ['total_precincts', 'precincts_reporting', 'rep_vote_count', 'dem_vote_count']:
                if row[field] == '':
                    row[field] = 0
            try:
                state = State.select().where(
                    State.id == row['id']
                ).get()
                state.update(**row)
            except State.DoesNotExist:
                state = State.create(**row)

            state.save()
开发者ID:imclab,项目名称:electris,代码行数:19,代码来源:input.py

示例6: update_polls

def update_polls():
    pollster = Pollster()

    for state in State.select().where(State.electoral_votes > 1):
        charts = pollster.charts(topic='2012-president', state=state.id)

        if charts:
            chart = charts[0]
        else:
            print 'NO DATA FOR %s' % state.id.upper()
            continue

        obama = 0
        romney = 0

        if chart.estimates:
            for estimate in chart.estimates:
                if estimate['choice'] == "Obama":
                    obama = estimate['value']
                elif estimate['choice'] == "Romney":
                    romney = estimate['value']
        else:
            print 'NO ESTIMATES FOR %s' % state.id.upper()
            continue

        prediction = "t"

        if abs(obama - romney) > 15:
            if obama > romney:
                prediction = "sd"
            else:
                prediction = "sr"
        elif abs(obama - romney) > 7.5:
            if obama > romney:
                prediction = "ld"
            else:
                prediction = "lr"

        uq = State.update(prediction=prediction).where(State.id == state)
        uq.execute()
开发者ID:imclab,项目名称:electris,代码行数:40,代码来源:input.py

示例7: produce_bop_json

def produce_bop_json():
    """
    Loops through houses/parties to count seats and calculate deltas.
    """
    # Party mapping.
    parties = [('republicans', 'r'), ('democrats', 'd'), ('other', 'o')]

    # House/seats/delta mapping.
    houses = [('house', 'H'), ('senate', 'S')]

    # Blank dataset.
    data = bootstrap_bop_data()

    # President.
    for state in State.select().where(State.called == True):
        for party, abbr in parties:
            if state.winner == abbr:
                data['president'][party] = calculate_president_bop(data['president'][party], state.electoral_votes)

    # House/senate.
    for office, short in houses:
        for race in Race.select().where(
            (Race.ap_called == True) | (Race.npr_called == True), Race.office_code == short):
            for party, abbr in parties:
                if race.winner == abbr:
                    if short == 'H':
                        data[office][party] = calculate_house_bop(data[office][party])
                    if short == 'S':
                        data[office][party] = calculate_senate_bop(race, data[office][party])

            if short == 'S':
                data[office] = calculate_net_pickups(race, data[office])

        # Write the number of uncalled races.
        # First, the races where we accept AP calls but no calls have come in.
        data[office]['not_called'] += Race.select()\
            .where(
                Race.accept_ap_call == True,
                Race.ap_called == False,
                Race.office_code == short)\
            .count()

        # Second, the races where we don't accept AP calls and no NPR calls are in.
        data[office]['not_called'] += Race.select()\
            .where(
                Race.accept_ap_call == False,
                Race.npr_called == False,
                Race.office_code == short)\
            .count()

    return data
开发者ID:imclab,项目名称:electris,代码行数:51,代码来源:output.py

示例8: template_values

def template_values():
	values = memcache.get("template_values")
	if(values is not None):
		return values
	
	laender = dict([(s.name, s.striking) for s in State.all()])
	striking = any(laender.values())
	values = {'streik': striking, 
		'laender': laender,
		'title': title(striking),
		'twitter_text': twitter_text(striking)}
	
	memcache.add("template_values", values)
	return values
开发者ID:scompt,项目名称:Streikt-die-Bahn,代码行数:14,代码来源:main.py

示例9: parse_president_district

def parse_president_district(state_code, row):
    race_data = dict(zip(DISTRICT_RACE_FIELDS, row[:len(DISTRICT_RACE_FIELDS)]))
    candidate_count = (len(row) - len(DISTRICT_RACE_FIELDS)) / len(DISTRICT_CANDIDATE_FIELDS)

    i = 0
    obama_data = None
    romney_data = None
    total_vote_count = 0

    while i < candidate_count:
        first_field = len(DISTRICT_RACE_FIELDS) + (i * len(DISTRICT_CANDIDATE_FIELDS))
        last_field = first_field + len(DISTRICT_CANDIDATE_FIELDS)

        candidate_data = dict(zip(DISTRICT_CANDIDATE_FIELDS, row[first_field:last_field]))

        if candidate_data['last_name'] == 'Obama':
            obama_data = candidate_data
        elif candidate_data['last_name'] == 'Romney':
            romney_data = candidate_data

        total_vote_count += int(candidate_data['vote_count'])

        i += 1

    assert obama_data and romney_data

    if race_data['district_name'] == state_code:
        q = (State.id == state_code.lower())
    else:
        district_number = race_data['district_name'][-1:]
        q = (State.id == state_code.lower() + district_number)

    state = State.select().where(q).get()
    ap_call = 'r' if romney_data['ap_winner'] else 'd' if obama_data['ap_winner'] else 'u'

    ap_called_at = state.ap_called_at

    if ap_call != state.ap_call:
        ap_called_at = datetime.datetime.now(tz=pytz.utc)

    state.ap_call = ap_call
    state.ap_called_at = ap_called_at
    state.total_precincts = race_data['total_precincts']
    state.precincts_reporting = race_data['precincts_reporting']
    state.rep_vote_count = romney_data['vote_count']
    state.dem_vote_count = obama_data['vote_count']
    state.total_vote_count = total_vote_count

    state.save()
开发者ID:imclab,项目名称:electris,代码行数:49,代码来源:input.py

示例10: check_servers

def check_servers(id, host, port, timeout, server):

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(float(timeout))

        if sock.connect_ex((host, int(port))) == 0:
            b = State(id=id, active=True, server=server)
            b.save()
        else:
            b = State(id=id, active=False, server=server)
            b.save()
开发者ID:METAJIJI,项目名称:la2,代码行数:11,代码来源:cron.py

示例11: start

 def start(self):
     """
     Start new Game with width, height
         Initial the State from the Game
         Build all the blocks one by one
         Pick weak robot as a default Robot
         Let the player play first as default
         Set the result label to 'Playing'
         Unlock the application
     """
     self.game = Game(self.width, self.height)
     self.state = State(self.game)
     # generate the blocks
     self.block = {}
     for k in self.state.board.keys():
         self.block[k] = Block(self, k)
     self.pick_weak_robot()
     self.player_first()
     self.result_label.config(text='Playing')
     self.lock = False
开发者ID:BenThomas33,项目名称:practice,代码行数:20,代码来源:views.py

示例12: write_electris_json

def write_electris_json():
    """
    Rewrites JSON files from the DB for president.
    """
    output_states = []

    for state in State.select().order_by(State.electoral_votes.desc(), State.name.asc()):
        state = state._data

        if state['npr_call'] != 'n' and state['npr_call'] != 'u':
            state['call'] = state['npr_call']
            state['called_at'] = state['npr_called_at']
            state['called_by'] = 'npr'
        elif state['accept_ap_call'] and state['ap_call'] != 'u':
            state['call'] = state['ap_call']
            state['called_at'] = state['ap_called_at']
            state['called_by'] = 'ap'
        else:
            state['call'] = None
            state['called_at'] = None
            state['called_by'] = None

        del state['npr_call']
        del state['npr_called_at']
        del state['ap_call']
        del state['ap_called_at']

        del state['called_by']
        del state['accept_ap_call']
        del state['rowid']
        del state['prediction']

        output_states.append(state)

    output = json.dumps({
        'balance_of_power': produce_bop_json(),
        'states': output_states
    })

    with open(settings.PRESIDENT_FILENAME, 'w') as f:
        f.write(output)
开发者ID:imclab,项目名称:electris,代码行数:41,代码来源:output.py

示例13: write_replay_json

def write_replay_json():
    def _scale_time(time):
        first_time = datetime.datetime(2012, 11, 06, 19, 04, 02)
        delta = time - first_time
        return round(delta.seconds * 0.00321, 0) * 1000

    output = []
    states = sorted(State.select(), key=lambda state: state.called_time)
    for state in states:
        state_dict = state._data
        state_dict['scaled_time'] = _scale_time(state.called_time)

        if state_dict['npr_call'] != 'n' and state_dict['npr_call'] != 'u':
            state_dict['call'] = state_dict['npr_call']
            state_dict['called_at'] = state_dict['npr_called_at']
            state_dict['called_by'] = 'npr'
        elif state_dict['accept_ap_call'] and state_dict['ap_call'] != 'u':
            state_dict['call'] = state_dict['ap_call']
            state_dict['called_at'] = state_dict['ap_called_at']
            state_dict['called_by'] = 'ap'
        else:
            state_dict['call'] = None
            state_dict['called_at'] = None
            state_dict['called_by'] = None

        del state_dict['npr_call']
        del state_dict['npr_called_at']
        del state_dict['ap_call']
        del state_dict['ap_called_at']

        del state_dict['called_by']
        del state_dict['accept_ap_call']
        del state_dict['rowid']
        del state_dict['prediction']

        output.append(state_dict)

    with open('www/replay.json', 'w') as f:
        f.write(json.dumps(output))
开发者ID:imclab,项目名称:electris,代码行数:39,代码来源:output.py

示例14: test04_layermap_unique_multigeometry_fk

    def test04_layermap_unique_multigeometry_fk(self):
        "Testing the `unique`, and `transform`, geometry collection conversion, and ForeignKey mappings."
        # All the following should work.
        try:
            # Telling LayerMapping that we want no transformations performed on the data.
            lm = LayerMapping(County, co_shp, co_mapping, transform=False)

            # Specifying the source spatial reference system via the `source_srs` keyword.
            lm = LayerMapping(County, co_shp, co_mapping, source_srs=4269)
            lm = LayerMapping(County, co_shp, co_mapping, source_srs='NAD83')

            # Unique may take tuple or string parameters.
            for arg in ('name', ('name', 'mpoly')):
                lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique=arg)
        except:
            self.fail('No exception should be raised for proper use of keywords.')

        # Testing invalid params for the `unique` keyword.
        for e, arg in ((TypeError, 5.0), (ValueError, 'foobar'), (ValueError, ('name', 'mpolygon'))):
            self.assertRaises(e, LayerMapping, County, co_shp, co_mapping, transform=False, unique=arg)

        # No source reference system defined in the shapefile, should raise an error.
        if not mysql:
            self.assertRaises(LayerMapError, LayerMapping, County, co_shp, co_mapping)

        # Passing in invalid ForeignKey mapping parameters -- must be a dictionary
        # mapping for the model the ForeignKey points to.
        bad_fk_map1 = copy(co_mapping); bad_fk_map1['state'] = 'name'
        bad_fk_map2 = copy(co_mapping); bad_fk_map2['state'] = {'nombre' : 'State'}
        self.assertRaises(TypeError, LayerMapping, County, co_shp, bad_fk_map1, transform=False)
        self.assertRaises(LayerMapError, LayerMapping, County, co_shp, bad_fk_map2, transform=False)

        # There exist no State models for the ForeignKey mapping to work -- should raise
        # a MissingForeignKey exception (this error would be ignored if the `strict`
        # keyword is not set).
        lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique='name')
        self.assertRaises(MissingForeignKey, lm.save, silent=True, strict=True)

        # Now creating the state models so the ForeignKey mapping may work.
        co, hi, tx = State(name='Colorado'), State(name='Hawaii'), State(name='Texas')
        co.save(), hi.save(), tx.save()

        # If a mapping is specified as a collection, all OGR fields that
        # are not collections will be converted into them.  For example,
        # a Point column would be converted to MultiPoint. Other things being done
        # w/the keyword args:
        #  `transform=False`: Specifies that no transform is to be done; this
        #    has the effect of ignoring the spatial reference check (because the
        #    county shapefile does not have implicit spatial reference info).
        #
        #  `unique='name'`: Creates models on the condition that they have
        #    unique county names; geometries from each feature however will be
        #    appended to the geometry collection of the unique model.  Thus,
        #    all of the various islands in Honolulu county will be in in one
        #    database record with a MULTIPOLYGON type.
        lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique='name')
        lm.save(silent=True, strict=True)

        # A reference that doesn't use the unique keyword; a new database record will
        # created for each polygon.
        lm = LayerMapping(CountyFeat, co_shp, cofeat_mapping, transform=False)
        lm.save(silent=True, strict=True)

        # The county helper is called to ensure integrity of County models.
        self.county_helper()
开发者ID:ChrisEdson,项目名称:Inquire,代码行数:65,代码来源:tests.py

示例15: test02_proxy

    def test02_proxy(self):
        "Testing Lazy-Geometry support (using the GeometryProxy)."
        #### Testing on a Point
        pnt = Point(0, 0)
        nullcity = City(name='NullCity', point=pnt)
        nullcity.save()

        # Making sure TypeError is thrown when trying to set with an
        #  incompatible type.
        for bad in [5, 2.0, LineString((0, 0), (1, 1))]:
            try:
                nullcity.point = bad
            except TypeError:
                pass
            else:
                self.fail('Should throw a TypeError')

        # Now setting with a compatible GEOS Geometry, saving, and ensuring
        #  the save took, notice no SRID is explicitly set.
        new = Point(5, 23)
        nullcity.point = new

        # Ensuring that the SRID is automatically set to that of the 
        #  field after assignment, but before saving.
        self.assertEqual(4326, nullcity.point.srid)
        nullcity.save()

        # Ensuring the point was saved correctly after saving
        self.assertEqual(new, City.objects.get(name='NullCity').point)

        # Setting the X and Y of the Point
        nullcity.point.x = 23
        nullcity.point.y = 5
        # Checking assignments pre & post-save.
        self.assertNotEqual(Point(23, 5), City.objects.get(name='NullCity').point)
        nullcity.save()
        self.assertEqual(Point(23, 5), City.objects.get(name='NullCity').point)
        nullcity.delete()

        #### Testing on a Polygon
        shell = LinearRing((0, 0), (0, 100), (100, 100), (100, 0), (0, 0))
        inner = LinearRing((40, 40), (40, 60), (60, 60), (60, 40), (40, 40))

        # Creating a State object using a built Polygon
        ply = Polygon(shell, inner)
        nullstate = State(name='NullState', poly=ply)
        self.assertEqual(4326, nullstate.poly.srid) # SRID auto-set from None
        nullstate.save()

        ns = State.objects.get(name='NullState')
        self.assertEqual(ply, ns.poly)
        
        # Testing the `ogr` and `srs` lazy-geometry properties.
        if gdal.HAS_GDAL:
            self.assertEqual(True, isinstance(ns.poly.ogr, gdal.OGRGeometry))
            self.assertEqual(ns.poly.wkb, ns.poly.ogr.wkb)
            self.assertEqual(True, isinstance(ns.poly.srs, gdal.SpatialReference))
            self.assertEqual('WGS 84', ns.poly.srs.name)

        # Changing the interior ring on the poly attribute.
        new_inner = LinearRing((30, 30), (30, 70), (70, 70), (70, 30), (30, 30))
        ns.poly[1] = new_inner
        ply[1] = new_inner
        self.assertEqual(4326, ns.poly.srid)
        ns.save()
        self.assertEqual(ply, State.objects.get(name='NullState').poly)
        ns.delete()
开发者ID:hugs,项目名称:django,代码行数:67,代码来源:tests_mysql.py


注:本文中的models.State类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。