prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
t(ctxt, self.host) # FIXME volume count for exporting is wrong LOG.debug("Re-exporting %s volumes" % len(volumes)) try: self.stats['pools'] = {} self.stats.update({'allocated_capacity_gb': 0}) for volume in volumes: # available volume should also be counted into allocated if volume['status'] in ['in-use', 'available']: # calculate allocated capacity for driver self._count_allocated_capacity(ctxt, volume) try: if volume['status'] in ['in-use']: self.driver.ensure_export(ctxt, volume) except Exception as export_ex: LOG.error(_LE("Failed to re-export volume %s: " "setting to error state"), volume['id']) LOG.exception(export_ex) self.db.volume_update(ctxt, volume['id'], {'status': 'error'}) elif volume['status'] in ('downloading', 'creating'): LOG.info(_LI("volume %(volume_id)s stuck in " "%(volume_stat)s state. " "Changing to error state."), {'volume_id': volume['id'], 'volume_stat': volume['status']}) if volume['status'] == 'downloading': self.driver.clear_download(ctxt, volume) self.db.volume_update(ctxt, volume['id'], {'status': 'error'}) else: LOG.info(_LI("volume %s: skipping export"), volume['id']) snapshots = self.db.snapshot_get_by_host(ctxt, self.host, {'status': 'creating'}) for snapshot in snapshots: LOG.info(_LI("snapshot %(snap_id)s stuck in " "%(snap_stat)s state. " "Changing to error state."), {'snap_id': snapshot['id'], 'snap_stat': snapshot['status']}) self.db.snapshot_update(ctxt, snapshot['id'], {'status': 'error'}) except Exception as ex: LOG.error(_LE("Error encountered during " "re-exporting phase of driver initialization: " " %(name)s") % {'name': self.driver.__class__.__name__}) LOG.exception(ex) return self.driver.set_throttle() # at this point the driver is considered initialized. self.driver.set_initialized() LOG.debug('Resuming any in progress delete operations') for volume in volumes: if volume['status'] == 'deleting': LOG.info(_LI('Resuming delete on volume: %s') % volume['id']) if CONF.volume_service_inithost_offload: # Offload all the pending volume delete operations to the # threadpool to prevent the main volume service thread # from being blocked. self._add_to_threadpool(self.delete_volume, ctxt, volume['id']) else: # By default, delete volumes sequentially self.delete_volume(ctxt, volume['id']) # collect and publish service capabilities self.publish_service_capabilities(ctxt) # conditionally run replication status task stats = self.driver.get_volume_stats(refresh=True) if stats and stats.get('replication', False): @periodic_task.periodic_task def run_replication_task(self, ctxt): self._update_replication_relationship_status(ctxt) self.add_periodic_task(run_replication_task) def create_volume(self, context, volume_id, request_spec=None, filter_properties=None, allow_reschedule=True, snapshot_id=None, image_id=None, source_volid=None, source_replicaid=None, consistencygroup_id=None, cgsnapshot_id=None): """Creates the volume.""" context_elevated = context.elevated() if filter_properties is None: filter_properties = {} try: # NOTE(flaper87): Driver initialization is # verified by the task itself. flow_engine = create_volume.get_flow( context_elevated, self.db, self.driver, self.scheduler_rpcapi, self.host, volume_id, allow_reschedule,
context, request_spec, filter_properties, snapshot_id=snapshot_id, image_id=image_id, source_volid=source_volid, source_replicaid=source_replicaid, consistencygroup_id=consistencygroup_id, cg
snapshot_id=cgsnapshot_id) except Exception: LOG.exception(_LE("Failed to create manager volume flow")) raise exception.CinderException( _("Failed to create manager volume flow.")) if snapshot_id is not None: # Make sure the snapshot is not deleted until we are done with it. locked_action = "%s-%s" % (snapshot_id, 'delete_snapshot') elif source_volid is not None: # Make sure the volume is not deleted until we are done with it. locked_action = "%s-%s" % (source_volid, 'delete_volume') elif source_replicaid is not None: # Make sure the volume is not deleted until we are done with it. locked_action = "%s-%s" % (source_replicaid, 'delete_volume') else: locked_action = None def _run_flow(): # This code executes create volume flow. If something goes wrong, # flow reverts all job that was done and reraises an exception. # Otherwise, all data that was generated by flow becomes available # in flow engine's storage. with flow_utils.DynamicLogListener(flow_engine, logger=LOG): flow_engine.run() @utils.synchronized(locked_action, external=True) def _run_flow_locked(): _run_flow() # NOTE(dulek): Flag to indicate if volume was rescheduled. Used to # decide if allocated_capacity should be incremented. rescheduled = False try: if locked_action is None: _run_flow() else: _run_flow_locked() except Exception as e: if hasattr(e, 'rescheduled'): rescheduled = e.rescheduled raise finally: try: vol_ref = flow_engine.storage.fetch('volume_ref') except tfe.NotFound as e: # Flow was reverted, fetching volume_ref from the DB. vol_ref = self.db.volume_get(context, volume_id) if not rescheduled: # NOTE(dulek): Volume wasn't rescheduled so we need to update # volume stats as these are decremented on delete. self._update_allocated_capacity(vol_ref) return vol_ref['id'] @locked_volume_operation def delete_volume(self, context, volume_id, unmanage_only=False): """Deletes and unexports volume. 1. Delete a volume(normal case) Delete a volume and update quotas. 2. Delete a migration source volume If deleting the source volume in a migration, we want to skip quotas. Also we want to skip other d
d[1] < 0: return True return False def takeAction(self, sCoord, action): """ Receives an action value, performs associated movement. """ if action is 0: return self.up(sCoord) if action is 1: return self.down(sCoord) if action is 2: return self.left(sCoord) if action is 3: return self.right(sCoord) if action is 4: return sCoord if action is 5: return self.upleft(sCoord) if action is 6: return self.upright(sCoord) if action is 7: return self.downleft(sCoord) if action is 8: return self.downright(sCoord) def up(self, sCoord): """ Move agent up, uses state coordinate. """ newCoord = np.copy(sCoord) newCoord[0] -= 1 # Check if action takes you to a wall/obstacle if not self.isObstacle(newCoord): return newCoord # You hit a wall, return original coord else: return sCoord def upright(self, sCoord): """ Move agent up and right, uses state coordinate. """ newCoord = np.copy(sCoord) newCoord[0] -= 1 newCoord[1] += 1 # Check if action takes you to a wall/obstacle if not self.isObstacle(newCoord): return newCoord # You hit a wall, return original coord else: return sCoord def upleft(self, sCoord): """ Move agent up and left, uses state coordinate. """ newCoord = np.copy(sCoord) newCoord[0] -= 1 newCoord[1] -= 1 # Check if action takes you to a wall/obstacle if not self.isObstacle(newCoord): return newCoord # You hit a wall, return original coord else: return sCoord def down(self, sCoord): """ Move agent down, uses state coordinate. """ newCoord = np.copy(sCoord) newCoord[0] += 1 # Check if action takes you to a wall/obstacle if not self.isObstacle(newCoord): return newCoord # You hit a wall, return original coord else: return sCoord def downleft(self, sCoord): """ Move agent down, uses state coordinate. """ newCoord = np.copy(sCoord) newCoord[0] += 1 newCoord[1] -= 1 # Check if action takes you to a wall/obstacle if not self.isObstacle(newCoord): return newCoord # You hit a wall, return original coord else: return sCoord def downright(self, sCoord): """ Move agent down, uses state coordinate. """ newCoord = np.copy(sCoord) newCoord[0] += 1 newCoord[1] += 1 # Check if action takes you to a wall/obstacle if not self.isObstacle(newCoord): return newCoord # You hit a wall, return original coord else: return sCoord def left(self, sCoord): """ Move agent left, uses state coordinate. """ newCoord = np.copy(sCoord) newCoord[1] -= 1 # Check if action takes you to a wall/obstacle if not self.isObstacle(newCoord): return newCoord # You hit a wall, return original coord else: return sCoord def right(self, sCoord): """ Move agent right, uses state coordinate. """ newCoord = np.copy(sCoord) newCoord[1] += 1 # Check if action takes you to a wall/obstacle if not self.isObstacle(newCoord): return newCoord # You hit a wall, return original coord else: return sCoord def coordToScalar(self, sCoord): """ Convert state coordinates to corresponding scalar state value. """ return sCoord[0]*(self.grid.col) + sCoord[1] def scalarToCoord(self, scalar): """ Convert scalar state value into coordinates. """ return np.array([scalar / self.grid.col, scalar % self.grid.col]) def getPossibleActions(self, sCoord): """ Will return a list of all possible actions from a current state. """ possibleActions = list() if self.up(sCoord) is not sCoord: possibleActions.append(0) if self.down(sCoord) is not sCoord: possibleActions.append(1) if self.left(sCoord) is not sCoord: possibleActions.append(2) if self.right(sCoord) is not sCoord: possibleActions.append(3) if self.upleft(sCoord) is not sCoord: possibleActions.append(5) if self.upright(sCoord) is not sCoord: possibleActions.append(6) if self.downleft(sCoord) is not sCoord: possibleActions.append(7) if self.downright(sCoord) is not sCoord: possibleActions.append(8) return possibleActions def setGridWorld(self): """ Initializes states, actions, rewards, transition matrix. """ # Possible coordinate positions + Death State self.s = np.arange(self.grid.row*self.grid.col + 1) # 4 Actions {Up, Down, Left, Right} self.a = np.arange(9) # Reward Zones self.r = np.zeros(len(self.s)) for i in range(len(self.grid.objects)): self.r[self.coordToScalar(self.grid.objects.values()[i])] = self.goalVals[i] self.r_sa = np.zeros([len(self.s),len(self.a)]) for i in range(len(self.s)): for j in range(len(self.a)): if j <= 4: self.r_sa[i][j] = self.r[self.coordToScalar(self.takeAction(self.scalarToCoord(i),j))]-1.0 else: self.r_sa[i][j] = self.r[self.coordToScalar(self.takeAction(self.scalarToCoord(i),j))]-np.sqrt(2) self.r = self.r_sa # Transition Matrix self.t = np.zeros([len(self.s),len(self.a),len(self.s)]) for state in range(len(self.s)): possibleActions = self.getPossibleActions(self.scalarToCoord(state)) if self.isTerminal(state): for i in range(len(self.a)): if i == 4: self.t[state][4][state]=1.0 else: self.t[state][i][len(self.s)-1] = 1.0 continue for action in self.a: # Up if action == 0: currentState = self.scalarToCoord(state) nextState = self.takeAction(currentState, 0) self.t[state][action][self.coordToScalar(nextState)] = 1.0 if action == 1: currentState = self.scalarToCoord(state) nextState = self.takeAction(currentState, 1) self.t[state][action][self.coordToScalar(nextState)] = 1.0 if action == 2: currentState = self.scalarToCoord(state) nextState = self.takeAction(currentState, 2) self.t[state][action][self.coordToScalar(nextState)] = 1.0 if action == 3: currentState = self.scalarToCoord(state) nextState
= self.takeAction(currentState, 3) self.t[state][action][self.coordToScalar(nextState)] = 1.0 if action == 4: self.t[state][action][state] = 1.0 if action == 5: currentState = self.scalarToCoord(state) nextState = sel
f.takeAction(currentState, 5) self.t[state][action][self.coordToScalar(nextState)] = 1.0 if action == 6: currentState = self.scalarToCoord(state) nextState = self.takeAction(currentState, 6) self.t[state][action][self.coordToScalar(nextState)] = 1.0 if action == 7: currentState = self.scalarToCoord(state) nextState = self.takeAction(currentState, 7) self.t[state][action][self.coordToScalar(nextState)] = 1.0 if action == 8: currentState = self.scalarToCoord(state) nextState = self.takeAction(currentState, 8) self.t[state][action][self.coordToScalar(nextState)] = 1.0 def simulate(self, state): """ Runs the solver for the MDP, conducts value iteration, extracts policy, then runs simulation of problem. NOTE: Be sure to run value iteration (solve values for states) and to extract some policy (fill in policy vector) before running simulation """ # Run simulation using policy until terminal condition met actions = ['up', 'down', 'left', 'right'] count = 0 while not self.isTerminal(state): # Determine which policy to use (non-deterministic) policy = self.policy[np.where(self.s == state)[0][0]] p_policy = self.policy[np.where(self.s == state)[0][0]] / \ self.policy[np.where(self.s == state)[0][0]].sum() # Get the parameters to perform one move stateIndex = np.where(self.s == state)[0][0] policyChoice = np.random.choice(policy, p=p_policy) actionIndex = np.random.choice(np.array(np.where(self.policy[state][:] == policyChoice)).ravel()) # print actionIndex if actionIndex <= 3: count += 1 else: count += np.sqrt(2) # Take an action, move to next state nextState = self.takeAction(self.scalarToCoord(int(stateIndex)), int(actionIndex)) nextState = self.coordToScalar(nextState) # print "In state: {}, taking action: {}, moving to state: {}".form
import pylab import string import matplotlib matplotlib.rcParams['figure.subplot.hspace']=.45 matplotlib.rcParams['figure.subplot.wspace']=.3 labels=('Step=1','Step=.5','Step=.25','Step=.01') steps=(1,.5,.25,.01) pylab.figure(figsize=(8.5,11)) for i,intxt in enumerate(('O_RK1.txt','O_RK_5.txt','O_RK_25.txt','O_RK_1.txt')): infile=open(intxt,'r') t=[] xs=[] ys=[] Es=[] for line in infile.readlines(): line=string.split(line) t.append(float(line[0])) xs.append(float(line[1])) ys.append(float(line[2])) Es.append(float(line[5])) pylab.subplot(4,2,2*i+1) pylab.plot(xs,ys,'-',lw=2) pylab.ylim(-1,1) pylab.xlim(-1,1) pylab.xlabel('X') pylab.ylabel('Y') pylab.title('Step=%f'%(steps[i])) pylab.subplot(4,2,2*i+2) pylab.plot(t,Es,'-',lw=1) pylab.xlim
(0,100) pylab.xlabel('Time') pylab.ylabel('Energy') pylab.suptitle('RK4 Orbit Integration') pylab.savefig('RK4_orbit_int.pdf') pylab.close() pylab.figure(figsize=(8.5,11)) for i,intxt in enumerate(('O_LF1.txt','O_LF_5.txt','O_LF_25.txt','O_LF_1.txt')): infile=open(intxt,'r') t=[] xs=[] ys=[] Es=[] for line in infile.readlines(): line=string.split(line) t.append(float(line[0])) xs.append(float(line[1])) ys.appe
nd(float(line[2])) Es.append(float(line[5])) pylab.subplot(4,2,2*i+1) pylab.plot(xs,ys,'-',lw=2) pylab.ylim(-1,1) pylab.xlim(-1,1) pylab.xlabel('X') pylab.ylabel('Y') pylab.title('Step=%f'%(steps[i])) pylab.subplot(4,2,2*i+2) pylab.plot(t,Es,'-',lw=1) pylab.xlim(0,100) pylab.xlabel('Time') pylab.ylabel('Energy') pylab.suptitle('Leapfrog Orbit integration') pylab.savefig('Leapfrog_orbit_int.pdf') pylab.close()
estatus # and the ingress resource actually getting updated is longer than the # time spent waiting for resources to be ready, so this test will fail (most of the time) time.sleep(1) yield Query(self.url(self.name + "/")) yield Query(self.url(f'need-normalization/../{self.name}/')) def check(self): if not parse_bool(os.environ.get("AMBASSADOR_PYTEST_INGRESS_TEST", "false")): pytest.xfail('AMBASSADOR_PYTEST_INGRESS_TEST not set, xfailing...') if sys.platform == 'darwin': pytest.xfail('not supported on Darwin') for r in self.results: if r.backend: assert r.backend.name == self.target.path.k8s, (r.backend.name, self.target.path.k8s) assert r.backend.request.headers['x-envoy-original-path'][0] == f'/{self.name}/' # check for Ingress IP here ingress_cmd = ["kubectl", "get", "-o", "json", "ingress", self.path.k8s, "-n", "alt-namespace"] ingress_run = subprocess.Popen(ingress_cmd, stdout=subprocess.PIPE) ingress_out, _ = ingress_run.communicate() ingress_json = json.loads(ingress_out) assert ingress_json['status'] == self.status_update, f"Expected Ingress status to be {self.status_update}, got {ingress_json['status']} instead" class IngressStatusTestWithAnnotations(AmbassadorTest): status_update = { "loadBalancer": { "ingress": [{ "ip": "200.200.200.200" }] } } def init(self): self.target = HTTP() def manifests(self) -> str: return """ --- apiVersion: extensions/v1beta1 kind: Ingress metadata: annotations: getambassador.io/config: | --- apiVersion: ambassador/v1 kind: Mapping name: {self.name}-nested prefix: /{self.name}-nested/ service: http://{self.target.path.fqdn} ambassador_id: {self.ambassador_id} kubernetes.io/ingress.class: ambassador getambassador.io/ambassador-id: {self.ambassador_id} name: {self.name.k8s} spec: rules: - http: paths: - backend: serviceName: {self.target.path.k8s} servicePort: 80 path: /{self.name}/ """ + super().manifests() def queries(self): text = json.dumps(self.status_update) update_cmd = [KUBESTATUS_PATH, 'Service', '-n', 'default', '-f', f'metadata.name={self.name.k8s}', '-u', '/dev/fd/0'] subprocess.run(update_cmd, input=text.encode('utf-8'), timeout=10) # If you run these tests individually, the time between running kubestatus # and the ingress resource actually getting updated is longer than the # time spent waiting for resources to be ready, so this test will fail (most of the time) time.sleep(1) yield Query(self.url(self.name + "/")) yield Query(self.url(self.name + "-nested/")) yield Query(self.url(f'need-normalization/../{self.name}/')) def check(self): if not parse_bool(os.environ.get("AMBASSADOR_PYTEST_INGRESS_TEST", "false")): pytest.xfail('AMBASSADOR_PYTEST_INGRESS_TEST not set, xfailing...') # check for Ingress IP here ingress_cmd = ["kubectl", "get", "-n", "default", "-o", "json", "ingress", self.path.k8s] ingress_run = subprocess.Popen(ingress_cmd, stdout=subprocess.PIPE) ingress_out, _ = ingress_run.communicate() ingress_json = json.loads(ingress_out) assert ingress_json['status'] == self.status_update, f"Expected Ingress status to be {self.status_update}, got {ingress_json['status']} instead" class SameIngressMultipleNamespaces(AmbassadorTest): status_update = { "loadBalancer": { "ingress": [{ "ip": "210.210.210.210" }] } } def init(self): self.target = HTTP() self.target1 = HTTP(name="target1", namespace="same-ingress-1") self.target2 = HTTP(name="target2", namespace="same-ingress-2") def manifests(self) -> str: return namespace_manifest("same-ingress-1") + """ --- apiVersion: extensions/v1beta1 kind: Ingress metadata: annotations: kubernetes.io/ingress.class: ambassador getambassador.io/ambassador-id: {self.ambassador_id} name: {self.name.k8s} namespace: same-ingress-1 spec: rules: - http: paths: - backend: serviceName: {self.target.path.k8s}-target1 servicePort: 80 path: /{self.name}-target1/ """ + namespace_manifest("same-ingress-2") + """ --- apiVersion: extensions/v1beta1 kind: Ingress metadata: annotations: kubernetes.io/ingress.class: ambassador getambassador.io/ambassador-id: {self.ambassador_id} name: {self.name.k8s} namespace: same-ingress-2 spec: rules: - http: paths: - backend:
serviceName: {self.target.path.k8s}-target2 servicePort: 80 path: /{self.name}-target2/ """ + super().manifests() def queries(self): if sys.platform != 'darw
in': text = json.dumps(self.status_update) update_cmd = [KUBESTATUS_PATH, 'Service', '-n', 'default', '-f', f'metadata.name={self.name.k8s}', '-u', '/dev/fd/0'] subprocess.run(update_cmd, input=text.encode('utf-8'), timeout=10) # If you run these tests individually, the time between running kubestatus # and the ingress resource actually getting updated is longer than the # time spent waiting for resources to be ready, so this test will fail (most of the time) time.sleep(1) yield Query(self.url(self.name + "-target1/")) yield Query(self.url(self.name + "-target2/")) def check(self): if not parse_bool(os.environ.get("AMBASSADOR_PYTEST_INGRESS_TEST", "false")): pytest.xfail('AMBASSADOR_PYTEST_INGRESS_TEST not set, xfailing...') if sys.platform == 'darwin': pytest.xfail('not supported on Darwin') for namespace in ['same-ingress-1', 'same-ingress-2']: # check for Ingress IP here ingress_cmd = ["kubectl", "get", "-n", "default", "-o", "json", "ingress", self.path.k8s, "-n", namespace] ingress_run = subprocess.Popen(ingress_cmd, stdout=subprocess.PIPE) ingress_out, _ = ingress_run.communicate() ingress_json = json.loads(ingress_out) assert ingress_json['status'] == self.status_update, f"Expected Ingress status to be {self.status_update}, got {ingress_json['status']} instead" class IngressStatusTestWithIngressClass(AmbassadorTest): status_update = { "loadBalancer": { "ingress": [{ "ip": "42.42.42.42" }] } } def init(self): self.target = HTTP() if not is_ingress_class_compatible(): self.xfail = 'IngressClass is not supported in this cluster' def manifests(self) -> str: return """ --- apiVersion: rbac.authorization.k8s.io/v1beta1 kind: ClusterRole metadata: name: {self.name.k8s}-ext rules: - apiGroups: ["networking.k8s.io"] resources: ["ingressclasses"] verbs: ["get", "list", "watch"] --- apiVersion: rbac.authorization.k8s.io/v1beta1 kind: ClusterRoleBinding metadata: name: {self.name.k8s}-ext roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: {self.name.k8s}-ext subjects: - kind: ServiceAccount name: {self.path.k8s} namespace: {self.namespace} --- apiVersion: networking.k8s.io/v1beta1 kind: IngressClass metadata: annotations: getambassador.io/ambassador-id: {self.ambassador_id} name: {self.name.k8s} spec: controller: getambassador.io/ingress-controller --- apiVersion: networking.k8s.io/v1beta1 kind: Ingress metadata: annotations: getambassador.io/ambassador-id: {self.ambassador_id} name: {self.name.k8s} spec: ingressClassName: {self.name.k8s} rules: - http: paths: - backend: serviceName: {self.target.path.k8s} servicePort: 80 path: /{self.name}/ """ + super().manifests() def queries(self): if sys.platform != 'd
"target.restrict.aqd-unittest.ms.com, but ", cmd) def test_201_verify_autocreate(self): cmd = ["search", "dns", "--fullinfo", "--fqdn", "target.restrict.aqd-unittest.ms.com"] out = self.commandtest(cmd) self.matchoutput(out, "Reserved Name: target.restrict.aqd-unittest.ms.com", cmd) def test_201_verify_noprimary(self): cmd = ["search", "dns", "--noprimary_name", "--record_type", "reserved_name"] out = self.commandtest(cmd) self.matchoutput(out, "target.restrict.aqd-unittest.ms.com", cmd) def test_210_autocreate_second_alias(self): cmd = ["add", "alias", "--fqdn", "restrict2.aqd-unittest.ms.com", "--target", "target.restrict.aqd-unittest.ms.com"] self.noouttest(cmd) def test_220_restricted_alias_no_dsdb(self): cmd = ["add", "alias", "--fqdn", "restrict.ms.com", "--target", "no-dsdb.restrict.aqd-unittest.ms.com"] out = self.statustest(cmd) self.matchoutput(out, "WARNING: Will create a reference to " "no-dsdb.restrict.aqd-unittest.ms.com, but ", cmd) self.dsdb_verify(empty=True) def test_400_verify_alias2host(self): cmd = "show alias --fqdn alias2host.aqd-unittest.ms.com" out = self.commandtest(cmd.split(" ")) self.matchoutput(out, "Alias: alias2host.aqd-unittest.ms.com", cmd) self.matchoutput(out, "Target: arecord13.aqd-unittest.ms.com", cmd) self.matchoutput(out, "DNS Environment: internal", cmd) def test_405_verify_host_shows_alias(self): cmd = "show address --fqdn arecord13.aqd-unittest.ms.com" out = self.commandtest(cmd.split(" ")) self.matchoutput(out, "Aliases: alias.ms.com, " "alias13.aqd-unittest.ms.com [environment: ut-env], " "alias2alias.aqd-unittest-ut-env.ms.com [environment: ut-env], " "alias2host.aqd-unittest-ut-env.ms.com [environment: ut-env], " "alias2host.aqd-unittest.ms.com", cmd) def test_410_verify_mscom_alias(self): cmd = "show alias --fqdn alias.ms.com" out = self.commandtest(cmd.split(" ")) self.matchoutput(out, "Alias: alias.ms.com", cmd) self.matchoutput(out, "Target: arecord13.aqd-unittest.ms.com", cmd) self.matchoutput(out, "DNS Environment: internal", cmd) self.matchoutput(out, "Comments: Some alias comments", cmd) def test_420_verify_alias2diff_environment(self): cmd = "show alias --fqdn alias2host.aqd-unittest-ut-env.ms.com --dns_environment ut-env" out = self.commandtest(cmd.split(" ")) self.matchoutput(out, "Alias: alias2host.aqd-unittest-ut-env.ms.com", cmd) self.matchoutput(out, "Target: arecord13.aqd-unittest.ms.com [environment: internal]", cmd) self.matchoutput(out, "DNS Environment: ut-env", cmd) def test_425_verify_alias2alias_with_diff_environment(self): cmd = "show alias --fqdn alias2alias.aqd-unittest-ut-env.ms.com --dns_environment ut-env" out = self.commandtest(cmd.split(" ")) self.matchoutput(out, "Alias: alias2alias.aqd-unittest-ut-env.ms.com", cmd) self.matchoutput(out, "Target: alias2host.aqd-unittest-ut-env.ms.com", cmd) self.matchoutput(out, "DNS Environment: ut-env", cmd) def test_500_add_alias2alias(self): cmd = ['add', 'alias', '--fqdn', 'alias2alias.aqd-unittest.ms.com', '--target', 'alias2host.aqd-unittest.ms.com', '--ttl', 60] self.noouttest(cmd) def test_510_add_alias3alias(self): cmd = ['add', 'alias', '--fqdn', 'alias3alias.aqd-unittest.ms.com', '--target', 'alias2alias.aqd-unittest.ms.com'] self.noouttest(cmd) def test_520_add_alias4alias(self): cmd = ['add', 'alias', '--fqdn', 'alias4alias.aqd-unittest.ms.com', '--target', 'alias3alias.aqd-unittest.ms.com'] self.noouttest(cmd) def test_530_add_alias5alias_fail(self): cmd = ['add', 'alias', '--fqdn', 'alias5alias.aqd-unittest.ms.com', '--target', 'alias4alias.aqd-unittest.ms.com'] out = self.badrequesttest(cmd) self.matchoutput(out, "Maximum alias depth exceeded", cmd) def test_600_verify_alias2alias(self): cmd = 'show alias --fqdn alias2alias.aqd-unittest.ms.com' out = self.commandtest(cmd.split(" ")) self.matchoutput(out, 'Alias: alias2alias.aqd-unittest.ms.com', cmd) self.matchoutput(out, 'TTL: 60', cmd) def test_601_verify_alias2alias_backwards(self): cmd = 'show alias --fqdn alias2host.aqd-unittest.ms.com' out = self.commandtest(cmd.split(" ")) self.matchoutput(out, "Aliases: alias2alias.aqd-unittest.ms.com", cmd) def test_602_verify_alias2alias_recursive(self): cmd = 'show address --fqdn arecord13.aqd-unittest.ms.com' out = self.commandtest(cmd.split(" ")) self.matchoutput(out, "Aliases: alias.ms.com, " "alias13.aqd-unittest.ms.com [environment: ut-env], " "alias2alias.aqd-unittest-ut-env.ms.com [environment: ut-env], " "alias2alias.aqd-unittest.ms.com, " "alias2host.aqd-unittest-ut-env.ms.com [environment: ut-env], " "alias2host.aqd-unittest.ms.com, " "alias3alias.aqd-unittest.ms.com, " "alias4alias.aqd-unittest.ms.com", cmd) def test_700_show_alias_host(self): ip = self.net["zebra_eth0"].usable[0] command = ["add", "alias", "--fqdn", "alias0.aqd-unittest.ms.com", "--target", "unittest20-e0.aqd-unittest.ms.com"] out = self.commandtest(command) command = ["add", "alias", "--fqdn", "alias01.aqd-unittest.ms.com", "--target", "alias0.aqd-unittest.ms.com"] out = self.commandtest(command) command = ["show", "host", "--hostname", "unittest20.aqd-unittest.ms.com"] out = self.commandtest(command) self.searchoutput(out, r'Provides: unittest20-e0.aqd-unittest.ms.com \[%s\]\s*' r'Aliases: alias0.aqd-unittest.ms.com, alias01.aqd-unittest.ms.com' % ip, command) command = ["show", "host", "--hostname", "unittest20.aqd-unittest.ms.com", "--format", "proto"] host = self.protobuftest(command, expect=1)[0] self.assertEqual(host.hostname, 'unittest20') interfaces = {iface.device: iface for iface in host.machine.interfaces}
self.assertIn("eth0", interfaces) self.assertEqual(interfaces["eth0"].aliases[0], 'alias0.aqd-unittest.ms.com') self.assertEqual(interfaces["eth0"].aliases[1], 'alias01.aqd-unittest.ms.com') self.assertEqual(interfaces["eth0"].ip, str(ip)) self.assertEqual(interfaces["eth0"].fqdn, 'unittest20-e0.aqd-un
ittest.ms.com') command = ["del", "alias", "--fqdn", "alias01.aqd-unittest.ms.com"] out = self.commandtest(command) command = ["del", "alias", "--fqdn", "alias0.aqd-unittest.ms.com"] out = self.commandtest(command) def test_710_show_alias_host(self): ip = self.net["zebra_eth1"].usable[3] command = ["add", "alias", "--fqdn", "alias1.aqd-unittest.ms.com", "--target", "unittest20-e1-1.aqd-unittest.ms.com"] out = self.commandtest(command) command = ["add", "alias", "--fqdn", "alias11.aqd-unittest.ms.com", "--target", "alias1.aqd-unittest.ms.com"] out = self.commandtest(command) command = ["show", "host", "--hostname", "unittest20.aqd-unittest.ms.com"] out = self.commandtest(command) self.searchoutput(out, r'Provides: unittest20-e1-1.aqd-unitt
[u'/rw/', u'5'], [u'/si/', u'21'], [u'/sk/', u'875'], [u'/sl/', u'530'], [u'/son/', u'1'], [u'/sq/', u'27'], [u'/sr-Cyrl/', u'256'], [u'/sv/', u'1488'], [u'/ta-LK/', u'13'], [u'/ta/', u'13'], [u'/te/', u'6'], [u'/th/', u'2936'], [u'/tr/', u'3470'], [u'/uk/', u'434'], [u'/vi/', u'4880'], [u'/zh-CN/', u'5640'], [u'/zh-TW/', u'3508'] ], u'containsSampledData': False, u'profileInfo': { u'webPropertyId': u'UA-1234567890', u'internalWebPropertyId': u'1234567890', u'tableId': u'ga:1234567890', u'profileId': u'1234567890', u'profileName': u'support.mozilla.org - Production Only', u'accountId': u'1234567890' }, u'itemsPerPage': 1000, u'totalsForAllResults': { u'ga:visitors': u'437598'}, u'columnHeaders': [ {u'dataType': u'STRING', u'columnType': u'DIMENSION', u'name': u'ga:pagePathLevel1'}, {u'dataType': u'INTEGER', u'columnType': u'METRIC', u'name': u'ga:visitors'} ], u'query': { u'max-results': 1000, u'dimensions': u'ga:pagePathLevel1', u'start-date': u'2013-01-16', u'start-index': 1, u'ids': u'ga:1234567890', u'metrics': [u'ga:visitors'], u'end-date': u'2013-01-16' }, u'totalResults': 83, u'id': ('https://www.googleapis.com/analytics/v3/data/ga' '?ids=ga:1234567890&dimensions=ga:pagePathLevel1' '&metrics=ga:visitors&start-date=2013-01-16&end-date=2013-01-16'), u'selfLink': ('https://www.googleapis.com/analytics/v3/data/ga' '?ids=ga:1234567890&dimensions=ga:pagePathLevel1' '&metrics=ga:visitors&start-date=2013-01-16' '&end-date=2013-01-16'), } PAGEVIEWS_BY_DOCUMENT_RESPONSE = { u'kind': u'analytics#gaData', u'rows': [ [u'/en-US/kb/doc-1', u'1'], # Counts as a pageview. [u'/en-US/kb/doc-1/edit', u'2'], # Doesn't count as a pageview [u'/en-US/kb/doc-1/history', u'1'], # Doesn't count as a pageview [u'/en-US/kb/doc-2', u'2'], # Counts as a pageview. [u'/en-US/kb/doc-3', u'10'], # Counts as a pageview. [u'/en-US/kb/doc-4', u'39'], # Counts as a pageview. [u'/en-US/kb/doc-5', u'40'], # Counts a
s a pageview. [u'/en-US/kb/doc-5/discuss', u'1'], # Doesn't count as a pageview
[u'/en-US/kb/doc-5?param=ab', u'2'], # Counts as a pageview. [u'/en-US/kb/doc-5?param=cd', u'4']], # Counts as a pageview. u'containsSampledData': False, u'columnHeaders': [ {u'dataType': u'STRING', u'columnType': u'DIMENSION', u'name': u'ga:pagePath'}, {u'dataType': u'INTEGER', u'columnType': u'METRIC', u'name': u'ga:pageviews'} ], u'profileInfo': { u'webPropertyId': u'UA-1234567890', u'internalWebPropertyId': u'1234567890', u'tableId': u'ga:1234567890', u'profileId': u'1234567890', u'profileName': u'support.mozilla.org - Production Only', u'accountId': u'1234567890'}, u'itemsPerPage': 10, u'totalsForAllResults': { u'ga:pageviews': u'164293'}, u'nextLink': ('https://www.googleapis.com/analytics/v3/data/ga' '?ids=ga:1234567890&dimensions=ga:pagePath' '&metrics=ga:pageviews&filters=ga:pagePathLevel2%3D%3D/kb/' ';ga:pagePathLevel1%3D%3D/en-US/&start-date=2013-01-17' '&end-date=2013-01-17&start-index=11&max-results=10'), u'query': { u'max-results': 10, u'dimensions': u'ga:pagePath', u'start-date': u'2013-01-17', u'start-index': 1, u'ids': u'ga:1234567890', u'metrics': [u'ga:pageviews'], u'filters': u'ga:pagePathLevel2==/kb/;ga:pagePathLevel1==/en-US/', u'end-date': u'2013-01-17'}, u'totalResults': 10, u'id': ('https://www.googleapis.com/analytics/v3/data/ga?ids=ga:1234567890' '&dimensions=ga:pagePath&metrics=ga:pageviews' '&filters=ga:pagePathLevel2%3D%3D/kb/;' 'ga:pagePathLevel1%3D%3D/en-US/&start-date=2013-01-17' '&end-date=2013-01-17&start-index=1&max-results=10'), u'selfLink': ('https://www.googleapis.com/analytics/v3/data/ga' '?ids=ga:1234567890&dimensions=ga:pagePath&' 'metrics=ga:pageviews&filters=ga:pagePathLevel2%3D%3D/kb/;' 'ga:pagePathLevel1%3D%3D/en-US/&start-date=2013-01-17' '&end-date=2013-01-17&start-index=1&max-results=10') } PAGEVIEWS_BY_QUESTION_RESPONSE = { u'columnHeaders': [ {u'columnType': u'DIMENSION', u'dataType': u'STRING', u'name': u'ga:pagePath'}, {u'columnType': u'METRIC', u'dataType': u'INTEGER', u'name': u'ga:pageviews'}], u'containsSampledData': False, u'id': ('https://www.googleapis.com/analytics/v3/data/ga?ids=ga:65912487' '&dimensions=ga:pagePath&metrics=ga:pageviews' '&filters=ga:pagePathLevel2%3D%3D/questions/&start-date=2013-01-01' '&end-date=2013-01-02&start-index=1&max-results=10'), u'itemsPerPage': 10, u'kind': u'analytics#gaData', u'nextLink': ('https://www.googleapis.com/analytics/v3/data/ga' '?ids=ga:65912487&dimensions=ga:pagePath' '&metrics=ga:pageviews' '&filters=ga:pagePathLevel2%3D%3D/questions/' '&start-date=2013-01-01&end-date=2013-01-02' '&start-index=11&max-results=10'), u'profileInfo': { u'accountId': u'36116321', u'internalWebPropertyId': u'64136921', u'profileId': u'65912487', u'profileName': u'support.mozilla.org - Production Only', u'tableId': u'ga:65912487', u'webPropertyId': u'UA-36116321-2'}, u'query': { u'dimensions': u'ga:pagePath', u'end-date': u'2013-01-02', u'filters': u'ga:pagePathLevel2==/questions/', u'ids': u'ga:65912487', u'max-results': 10, u'metrics': [u'ga:pageviews'], u'start-date': u'2013-01-01', u'start-index': 1}, u'rows': [ [u'/en-US/questions/1', u'2'], # Counts as a pageview. [u'/es/questions/1', u'1'], # Counts as a pageview. [u'/en-US/questions/1/edit', u'3'], # Doesn't count as a pageview [u'/en-US/questions/stats', u'1'], # Doesn't count as a pageview [u'/en-US/questions/2', u'1'], # Counts as a pageview. [u'/en-US/questions/2?mobile=1', u'1'], # Counts as a pageview. [u'/en-US/questions/2/foo', u'2'], # Doesn't count as a pageview [u'/en-US/questions/bar', u'1'], # Doesn't count as a pageview [u'/es/questions/3?mobile=0', u'10'], # Counts as a pageview. [u'/es/questions/3?lang=en-US', u'1']], # Counts as a pageview. u'selfLink': ('https://www.googleapis.com/analytics/v3/data/ga' '?ids=ga:65912487&dimensions=ga:pagePath' '&metrics=ga:pageviews' '&filters=ga:pagePathLevel2%3D%3D/questions/' '&start-date=2013-01-01&end-date=2013-01-02' '&start-index=1&max-results=10'), u'totalResults': 10, u'totalsForAllResults': {u'ga:pageviews': u'242403'}} SEARCH_CTR_RESPONSE = { u'kind': u'analytics#gaData', u'rows': [[u'74.88925980111263']], # <~ The number we are looking for. u'containsSampledData': False, u'profileInfo': { u'webPropertyId': u'UA-36116321-2', u'internalWebPropertyId': u'64136921', u'tableId': u'ga:65912487', u'profileId': u'65912487', u'profileName': u'support.mozilla.org - Production Only', u'accountId': u'36116321'}, u'itemsPerPage': 1000, u'totalsForAllResults': { u'ga:goal11ConversionRate': u'74.88925980111263'}, u'columnHeaders': [ {u'dataType': u'PERCENT', u'columnType': u'METRIC', u'name': u'ga:goal11ConversionRate'}], u'query': {
# coding: utf-8 import sys from setuptools import setup, find_packages NAME = "pollster" VERSION = "2.0.2" # To install the library, run the following # # python setup.py install # # prerequisite: setuptools # http://pypi.python.org/pypi/setu
ptools REQUIRES = ["urllib3 >= 1.15", "six >= 1.10", "certifi", "python-dateutil", "pandas >= 0.19.1"] setup( name=NAME, version=VERSION, description="Pollster API", author_email="Adam Hooper <adam.hooper@huffingtonpost.com>", url="https://github.com/huffpostdata/python-pollster", keywords=["Pollster API"], install_requires=REQU
IRES, packages=find_packages(), include_package_data=True, long_description="""Download election-related polling data from Pollster.""" )
lepath is {}'.format(filepath)) database.add_results_to_cache(query, user, results, filepath) base_reference = 'https://www.passivetotal.org/search/whois/email' # Use our config defined indicator type of whois email objects crits_indicator_type = it.WHOIS_REGISTRANT_EMAIL_ADDRESS bucket_list.append('registrant') elif re.match(phone_pattern, query): if args.test: results = pt.get_test_results(field='phone') else: results = pt.whois_search(query=query, field='phone') # Now add the results to the db if we have it if database and not cache_file and config.core.cache_enabled: filepath = os.path.join(config.core.cache_dir, str(uuid.uuid4())) log.debug('Filepath is {}'.format(filepath)) database.add_results_to_cache(query, user, results, filepath) base_reference = 'https://www.passivetotal.org/search/whois/phone' crits_indicator_type = it.WHOIS_TELEPHONE bucket_list.append('registrant') elif re.match(domain_pattern, query): if args.test: results = pt.get_test_results(field='domain') else: results = pt.whois_search(query=query, field='domain') # Now add the results to the db if we have it if database and not cache_file and config.core.cache_enabled: filepath = os.path.join(config.core.cache_dir, str(uuid.uuid4())) log.debug('Filepath is {}'.format(filepath)) database.add_results_to_cache(query, user, results, filepath) base_reference = 'https://www.passivetotal.org/search/whois/domain' crits_indicator_type = it.DOMAIN else: raise SystemExit("Your query didn't match a known pattern.") # Add the query to CRITs regardless of the number of results # TODO: Add campaigns if args.crits: found = False # Search for it with raw mongo because API is slow crits_result = crits_mongo.find('indicators', {'value': query, 'type': crits_indicator_type}) if crits_result.count() > 0: for r in crits_result: if r['value'] == query: indicator = r found = True if not found: indicator = crits.add_indicator( value=query, itype=crits_indicator_type, source=config.crits.default_source, reference='Added via pt_query.py', method='pt_query.py', bucket_list=bucket_list, indicator_confidence='low', indicator_impact='low', description='Queried with pt_query.py', ) # This is pretty hacky - Since we use both the raw DB and the API, we might # receive either an '_id' or an 'id' back. We are going to standardize on # 'id', rather than '_id' if 'id' not in indicator: if '_id' not in indicator: print(repr(indicator)) raise SystemExit('id and _id not found for query: ' '{} in new indicator'.format(query)) else: indicator['id'] = indicator['_id'] # Iterate through all results and print/add to CRITs (if args provided) formatted_results = [] for result in results['results']: if 'domain' in result: crits_indicators_to_add = [] # Row contains: # Domain, Registrant Email, Registrant Name, Registrant Date, # Expiration Date, Tags row = ['', '', '', '', '', ''] row[0] = result['domain'] # Email address used to register if 'registrant' in result: # Append the registrant email if 'email' in result['registrant']: row[1] = result['registrant']['email'] email_obj = { 'value': result['registrant']['email'], 'type': it.WHOIS_REGISTRANT_EMAIL_ADDRESS, 'related_to': result['domain'] } crits_indicators_to_add.append(email_obj) if 'name' in result['registrant']: row[2] = result['registrant']['name'] name_obj = { 'value': result['registrant']['name'], 'type': it.WHOIS_NAME, 'related_to': result['domain'] } crits_indicators_to_add.append(name_obj) if 'telephone' in result['registrant']: row[3] = result['registrant']['telephone'] phone_obj = { 'value': result['registrant']['telephone'], 'type': it.WHOIS_TELEPHONE, 'related_to': result['domain'] } crits_indicators_to_add.append(phone_obj) if 'street' in result['registrant']: addr1_obj = { 'value': result['registrant']['street'], 'type': it.WHOIS_ADDR1, 'related_to': result['domain'] } crits_indicators_to_add.append(addr1_obj) # Date the domain was registered if 'registered' in result: row[4] = result['registered'] if 'expiresAt' in result: row[5] = result['expiresAt'] formatted_results.append(row) # TODO: Tags. They appear to be an extra API query which is annoying reference = '{0}/{1}'.format(base_reference, query) if args.crits: # Let's try getting the confidence and impact from the parent whois # indicator confidence = 'low' impact = 'low' if 'confidence' in indicator: if 'rating' in indicator['confidence']: confidence = indicator['confidence']['rating'] if 'impact' in indicator: if 'rating' in indicator['impact']: impact = indicator['impact']['rating'] # If
not in CRITs, add all the associated indicators bucket_list = ['whois pivoting', 'pt:found'] for t in args.tags: bucket_list.append(t)
new_ind = crits.add_indicator( value=result['domain'], itype=it.DOMAIN, source=config.crits.default_source, reference=reference, method='pt_query.py', bucket_list=bucket_list, indicator_confidence=confidence, indicator_impact=impact, description='Discovered through PT whois pivots' ) # The CRITs API allows us to add a campaign to the indicator, but # not multiple campaigns at one time, # so we will do it directly with the DB. # We want to replicate the campaigns of the WHOIS indicator (if # a campaign exists) to the new indicator. if 'campaign' in indicator: for campaign in indicator['campaign']: crits_mongo.add_embedded_campaign( new_ind['id'], 'indicators', campaign['name'], campaign['confidence'], campaign['analyst'], datetime.datetime.now(), campaign['description'] ) # If the new indicator and the indicator are not related, # relate them. if not crits.has_relationship(indicator['id'], 'Indicator', new_ind['id'], 'Indicator', rel_type='Registered'): crits.forge_relationship(indicator['id'], 'Indicator', new_ind['id'], 'Indicator', rel_type='Registered') # Now we can add the rest of the WHOIS indicators (if necessary) for ind in crits_indicators_to_add: # If the indicator exists, just get the id and use it to build # relationships. We will look for one with the same source. # If not in CRITs, add it and relate it. whois_indicator = crits_
from __future__ import absolute_import, print_function from datetime import timedelta from django.utils import timezone from freezegun import freeze_time from sentry.models import CheckInStatus, Monitor, MonitorCheckIn, MonitorStatus, MonitorType from sentry.testutils import APITestCase @freeze_time("2019-01-01") class Cre
ateMonitorCheckInTest(APITestCase): def test_passing(self): user = self.create_user() org = self.create_organization(owner=user) team = self.create_team(organization=org, members=[use
r]) project = self.create_project(teams=[team]) monitor = Monitor.objects.create( organization_id=org.id, project_id=project.id, next_checkin=timezone.now() - timedelta(minutes=1), type=MonitorType.CRON_JOB, config={"schedule": "* * * * *"}, ) self.login_as(user=user) with self.feature({"organizations:monitors": True}): resp = self.client.post( "/api/0/monitors/{}/checkins/".format(monitor.guid), data={"status": "ok"} ) assert resp.status_code == 201, resp.content checkin = MonitorCheckIn.objects.get(guid=resp.data["id"]) assert checkin.status == CheckInStatus.OK monitor = Monitor.objects.get(id=monitor.id) assert monitor.status == MonitorStatus.OK assert monitor.last_checkin == checkin.date_added assert monitor.next_checkin == monitor.get_next_scheduled_checkin(checkin.date_added) def test_failing(self): user = self.create_user() org = self.create_organization(owner=user) team = self.create_team(organization=org, members=[user]) project = self.create_project(teams=[team]) monitor = Monitor.objects.create( organization_id=org.id, project_id=project.id, next_checkin=timezone.now() - timedelta(minutes=1), type=MonitorType.CRON_JOB, config={"schedule": "* * * * *"}, ) self.login_as(user=user) with self.feature({"organizations:monitors": True}): resp = self.client.post( "/api/0/monitors/{}/checkins/".format(monitor.guid), data={"status": "error"} ) assert resp.status_code == 201, resp.content checkin = MonitorCheckIn.objects.get(guid=resp.data["id"]) assert checkin.status == CheckInStatus.ERROR monitor = Monitor.objects.get(id=monitor.id) assert monitor.status == MonitorStatus.ERROR assert monitor.last_checkin == checkin.date_added assert monitor.next_checkin == monitor.get_next_scheduled_checkin(checkin.date_added) def test_disabled(self): user = self.create_user() org = self.create_organization(owner=user) team = self.create_team(organization=org, members=[user]) project = self.create_project(teams=[team]) monitor = Monitor.objects.create( organization_id=org.id, project_id=project.id, next_checkin=timezone.now() - timedelta(minutes=1), type=MonitorType.CRON_JOB, status=MonitorStatus.DISABLED, config={"schedule": "* * * * *"}, ) self.login_as(user=user) with self.feature({"organizations:monitors": True}): resp = self.client.post( "/api/0/monitors/{}/checkins/".format(monitor.guid), data={"status": "error"} ) assert resp.status_code == 201, resp.content checkin = MonitorCheckIn.objects.get(guid=resp.data["id"]) assert checkin.status == CheckInStatus.ERROR monitor = Monitor.objects.get(id=monitor.id) assert monitor.status == MonitorStatus.DISABLED assert monitor.last_checkin == checkin.date_added assert monitor.next_checkin == monitor.get_next_scheduled_checkin(checkin.date_added) def test_pending_deletion(self): user = self.create_user() org = self.create_organization(owner=user) team = self.create_team(organization=org, members=[user]) project = self.create_project(teams=[team]) monitor = Monitor.objects.create( organization_id=org.id, project_id=project.id, next_checkin=timezone.now() - timedelta(minutes=1), type=MonitorType.CRON_JOB, status=MonitorStatus.PENDING_DELETION, config={"schedule": "* * * * *"}, ) self.login_as(user=user) with self.feature({"organizations:monitors": True}): resp = self.client.post( "/api/0/monitors/{}/checkins/".format(monitor.guid), data={"status": "error"} ) assert resp.status_code == 404, resp.content def test_deletion_in_progress(self): user = self.create_user() org = self.create_organization(owner=user) team = self.create_team(organization=org, members=[user]) project = self.create_project(teams=[team]) monitor = Monitor.objects.create( organization_id=org.id, project_id=project.id, next_checkin=timezone.now() - timedelta(minutes=1), type=MonitorType.CRON_JOB, status=MonitorStatus.DELETION_IN_PROGRESS, config={"schedule": "* * * * *"}, ) self.login_as(user=user) with self.feature({"organizations:monitors": True}): resp = self.client.post( "/api/0/monitors/{}/checkins/".format(monitor.guid), data={"status": "error"} ) assert resp.status_code == 404, resp.content
from dataclasses import asdict, dataclass from typing import List, Optional from license_grep.licenses import UnknownLicense, canonicalize_licenses from lic
ense_grep.utils import unique_in_order @dataclass class PackageInfo: name: str version: str type: str raw_licenses: Optional[List[str]] location: str context: Optional[str] @property def licenses(self): for license, canonicalized_license in canonicalize_licenses(self.raw_licenses
): yield canonicalized_license @property def licenses_string(self): return ", ".join( unique_in_order(str(license or "<UNKNOWN>") for license in self.licenses) ) @property def spec(self): return f"{self.name}@{self.version}" @property def full_spec(self): return f"{self.type}:{self.name}@{self.version}" def as_json_dict(self): return { **asdict(self), "licenses": list( unique_in_order( f"?{l}" if isinstance(l, UnknownLicense) else l for l in self.licenses ) ), "spec": self.spec, }
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Top level script for running all python unittests in the NaCl SDK. """ from __future__ import print_function import argparse import os import subprocess import sys import unittest # add tools folder to sys.path SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) TOOLS_DIR = os.path.join(SCRIPT_DIR, 'tools') BUILD_TOOLS_DIR = os.path.join(SCRIPT_DIR, 'build_tools') sys.path.append(TOOLS_DIR) sys.path.append(os.path.join(TOOLS_DIR, 'tests')) sys.path.append(os.path.join(TOOLS_DIR, 'lib', 'tests')) sys.path.append(BUILD_TOOLS_DIR) sys.path.append(os.path.join(BUILD_TOOLS_DIR, 'tests')) import build_paths PKG_VER_DIR = os.path.join(build_paths.NACL_DIR, 'build', 'package_version') TAR_DIR = os.path.join(build_paths.NACL_DIR, 'toolchain', '.tars') PKG_VER = os.path.join(PKG_VER_DIR, 'package_version.py') EXTRACT_PACKAGES = ['nacl_x86_glibc'] TOOLCHAIN_OUT = os.path.join(build_paths.OUT_DIR, 'sdk_tests', 'toolchain') # List of modules containing unittests. The goal is to keep the total # runtime of these tests under 2 seconds. Any slower tests should go # in TEST_MODULES_BIG. TEST_MODULES = [ 'build_artifacts_test', 'build_version_test', 'create_html_test', 'create_nmf_test', 'easy_template_test', 'elf_test', 'fix_deps_test', 'getos_test', 'get_shared_deps_test', 'httpd_test', 'nacl_config_test', 'oshelpers_test', 'parse_dsc_test', 'quote_test', 'sdktools_config_test', 'sel_ldr_test', 'update_nacl_manifest_test', 'verify_filelist_test', 'verify_ppapi_test', ] # Slower tests. For example the 'sdktools' are mostly slower system tests # that longer to run. If --quick is passed then we don't run these. TEST_MODULES_BIG = [ 'sdktools_commands_test', 'sdktools_test', ] def ExtractToolchains(): cmd = [sys.executable, PKG_VER, '--packages', ','.join(EXTRACT_PACKAGES), '--tar-dir', TAR_DIR, '--dest-dir', TOOLCHAIN_OUT,
'extract'] subprocess.check_call(cmd) def main(args): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') parser.add_argument('--quick', action='store_tru
e') options = parser.parse_args(args) # Some of the unit tests use parts of toolchains. Extract to TOOLCHAIN_OUT. print('Extracting toolchains...') ExtractToolchains() suite = unittest.TestSuite() modules = TEST_MODULES if not options.quick: modules += TEST_MODULES_BIG for module_name in modules: module = __import__(module_name) suite.addTests(unittest.defaultTestLoader.loadTestsFromModule(module)) if options.verbose: verbosity = 2 else: verbosity = 1 print('Running unittests...') result = unittest.TextTestRunner(verbosity=verbosity).run(suite) return int(not result.wasSuccessful()) if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
import unittest from ncclient.devices.alu import * from ncclient.xml_ import * import re xml = """<rpc-reply xmlns:junos="http://xml.alu.net/alu/12.1x46/alu"> <routing-engin> <name>reX</name> <commit-success/> <!-- This is a comment --> </routing-engin> <ok/> </rpc-reply>""" class TestAluDevice(unittest.TestCase): def setUp(self): self.obj = AluDeviceHandler({'name': 'alu'}) def test_remove_namespaces(self): xmlObj = to_ele(xml) expected = re.sub(r'<rpc-reply xmlns:junos="http://xml.alu.net/alu/12.1x46/alu">', r'<?xml version="1.0" encoding="UTF-8"?><rpc-reply>', xml) self.assertEqual(expected, to_xml(remove_namespaces(xmlObj))) def test_get_capabilities(self): expected = ["urn:ietf:params:netconf:base:1.0", ] self.assertListEqual(expected, self.obj.get_capabilities()) def test_get_xml_base_namespace_dict(self): expected = {None: BASE_NS_1_0} self.assertDictEqual(expected, self.obj.get_xml_base_namespace_dict()) def test_get_xml_extra_prefix_kwargs(self): expected = dict() expected["nsmap"] = self.obj.get_xml_base_namespace_dict() self.assertDictEqual(expected, self.obj.get_xml_extra_prefix_kwargs()) def test_add_additional_operations(self): expected=dict() expected["get_configuration"] = GetConfig
uration expected["show_cli"] = Sh
owCLI expected["load_configuration"] = LoadConfiguration self.assertDictEqual(expected, self.obj.add_additional_operations()) def test_transform_reply(self): expected = re.sub(r'<rpc-reply xmlns:junos="http://xml.alu.net/alu/12.1x46/alu">', r'<?xml version="1.0" encoding="UTF-8"?><rpc-reply>', xml) actual = self.obj.transform_reply() xmlObj = to_ele(xml) self.assertEqual(expected, to_xml(actual(xmlObj)))
"""Commands related to networks are in this module""" import click import sys from hil.cli.client_setup import client @click.group() def network(): """Commands related to network""" @network.command(name='create', short_help='Create a new network') @click.argument('network') @click.argument('owner') @click.option('--access', help='Projects that can access this network. ' 'Defaults to the owner of the network') @click.option('--net-id', help='Network ID for network. Only admins can specify this.') def network_create(network, owner, access, net_id): """Create a link-layer <network>. See docs/networks.md for details""" if net_id is None: net_id = '' if access is None: access = owner client.network.create(network, owner, access, net_id) @network.command(name='delete') @click.argument('network') def network_delete(network): """Delete a network""" client.network.delete(network) @network.command(name='show') @click.ar
gument('network') def network_show(network): """Display information about network""" q = client.network.show(network) for item in q.items(): sys.stdout.write("%s\t : %s\n" % (item[0], item[1])) @network.command(name='list') def network_list(): """List all networks""" q = client.network.list() for item in q.items(): sys.stdout.write('%s \t : %s\n' % (item[0], item[1]
)) @network.command('list-attachments') @click.argument('network') @click.option('--project', help='Name of project.') def list_network_attachments(network, project): """Lists all the attachments from <project> for <network> If <project> is `None`, lists all attachments for <network> """ print client.network.list_network_attachments(network, project) @network.command(name='grant-access') @click.argument('network') @click.argument('project') def network_grant_project_access(project, network): """Add <project> to <network> access""" client.network.grant_access(project, network) @network.command(name='revoke-access') @click.argument('network') @click.argument('project') def network_revoke_project_access(project, network): """Remove <project> from <network> access""" client.network.revoke_access(project, network)
""" Python Interchangeable Virtual Instrument Library Copyright (c) 2012 Alex Forencich Permission is hereby granted, free of charge, to any person obtaining a copy of this s
oftware and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS"
, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from .lecroyWRXIA import * class lecroyWR64XIA(lecroyWRXIA): "Lecroy WaveRunner 64Xi-A IVI oscilloscope driver" def __init__(self, *args, **kwargs): self.__dict__.setdefault('_instrument_id', 'WaveRunner 64Xi-A') super(lecroy104MXiA, self).__init__(*args, **kwargs) self._analog_channel_count = 4 self._digital_channel_count = 0 self._channel_count = self._analog_channel_count + self._digital_channel_count self._bandwidth = 600e6 self._init_channels()
# -*- coding: utf-8 -*- # # test_pp_psc_delta_stdp.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # NEST is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NEST. If not, see <http://www.gnu.org/licenses/>. # # Moritz Deger, moritz.deger@epfl.ch, Aug 14, 2015 # # # Python script to reproduce failure of pp_psc_delta to show spike timing # dependent plasticity (STDP), as opposed to iaf_psc_delta. # The problem is probably related to the setting of 'archiver_length' # (printed at the end of the script) import nest import nest.raster_plot import numpy as np import pylab Dt = 1. nsteps = 100 w_0 = 100. nest.ResetKernel() nrn_pre = nest.Create('parrot_neuron') nrn_post1 = nest.Create('iaf_psc_delta') nrn_post2 = nest.Create('pp_psc_delta') nest.Connect(nrn_pre, nrn_post1 + nrn_post2, syn_spec={'model': 'stdp_synapse', 'weight': w_0}) conn1 = nest.GetConnections(nrn_pre, nrn_post1) conn2 = nest.GetConnections(nrn_pre, nrn_post2) sg_pre = nest.Create('spike_generator') nest.SetStatus(sg_pre, {'spike_times': np.arange(Dt, nsteps * Dt, 10. * Dt)}) nest.Connect(sg_pre, nrn_pre) mm = nest.Create('multimeter') nest.SetStatus(mm, {'record_from': ['V_m']}) nest.Connect(mm, nrn_post1 + nrn_post2) sd = nest.Create('spike_detector') nest.Connect(nrn_pre + nrn_post1 + nrn_post2, sd) t = [] w1 = [] w2 = [] t.append(0.) w1.append(nest.GetStatus(conn1, keys=['weight'])[0][0]) w2.append(nest.GetStatus(conn2, keys=['weight'])[0][0]) for i in xrange(nsteps): nest.Simulate(Dt) t.append(i * Dt) w1.append(nest.GetStatus(conn1, keys=['weight'])[0][0]) w2.append(nest.GetStatus(conn2, keys=['weight'])[0][0]) pylab.figure(1) pylab.plot(t, w1, 'g', label='iaf_psc_delta, ' + str(nrn_post1[0])) pylab.plot(t, w2, 'r', label='pp_psc_delta, ' + str(nrn_post2[0])) pylab.xl
abel('time [ms]') pylab.ylabel('weight [mV]') pylab.legend(loc='best') ylims = pylab.ylim()
pylab.ylim(ylims[0] - 5, ylims[1] + 5) # pylab.savefig('test_pp_psc_delta_stdp_fig1.png') nest.raster_plot.from_device(sd) ylims = pylab.ylim() pylab.ylim(ylims[0] - .5, ylims[1] + .5) pylab.show() # pylab.savefig('test_pp_psc_delta_stdp_fig2.png') print 'Archiver lengths shall be equal:' for nrn in [nrn_post1, nrn_post2]: print nest.GetStatus(nrn, keys=['model', 'archiver_length'])[0]
s calculation from temperature dependences # to speed up pass def _GEOS(self, xi): """Definition of parameters of generalized cubic equation of state, each child class must define in this procedure the values of mixture a, b, delta, epsilon. The returned values are not dimensionless. Parameters ---------- xi : list Molar fraction of component in mixture, [-] Returns ------- parameters : list Mixture parameters of equation, a, b, c, d """ pass def _Z(self, xi, T, P): """Calculate root of cubic polynomial in terms of GCEoS as give in [1]_. Parameters ---------- xi : list Molar fraction of component in mixture, [-] T : float Temperature, [K] P : float Pressure, [Pa] Returns ------- Z : list List with real root of equation """ self._cubicDefinition(T) tita, b, delta, epsilon = self._GEOS(xi) B = b*P/self.R/T A = tita*P/(self.R*T)**2 D = delta*P/self.R/T E = epsilon*(P/self.R/T)**2 # Eq 4-6.3 in [1]_ # η by default set to b to reduce terms, if any equations need that # term redefine this procedure coeff = (1, D-B-1, A+E-D*(B+1), -E*(B+1)-A*B) Z = cubicCardano(*coeff) # Sort Z values, if typeerror is raise return is because there is # complex root, so return only the real root try: Z = sorted(map(float, Z)) except TypeError: Z = Z[0:1] return Z def _fug(self, xi, yi, T, P): """Fugacities of component in mixture calculation Parameters ---------- xi : list Molar fraction of component in liquid phase, [-] yi : list Molar fraction of component in vapor phase, [-] T : float Temperature, [K] P : float Pressure, [Pa] Returns ------- tital : list List with liquid phase component fugacities titav : list List with vapour phase component fugacities """ self._cubicDefinition(T) Bi = [bi*P/self.R/T for bi in self.bi] Ai = [ai*P/(self.R*T)**2 for ai in self.ai] al, bl, deltal, epsilonl = self._GEOS(xi) Bl = bl*P/self.R/T Al = al*P/(self.R*T)**2 Zl = self._Z(xi, T, P)[0] tital = self._fugacity(Zl, xi, Al, Bl, Ai, Bi) Zv = self._Z(yi, T, P)[-1] av, bv, deltav, epsilonv = self._GEOS(yi) Bv = bv*P/self.R/T Av = av*P/(self.R*T)**2 titav = self._fugacity(Zv, yi, Av, Bv, Ai, Bi) return tital, titav def _fugacity(self, Z, zi, A, B, Ai, Bi): """Fugacity for individual components in a mixture using the GEoS in the Schmidt-Wenzel formulation, so the subclass must define the parameters u and w in the EoS Any other subclass with different formulation must overwrite this method """ # Precalculation of inner sum in equation aij = [] for
ai, kiji in zip(Ai, self.kij): suma = 0 for xj, aj, kij in zip(zi, Ai, kiji): suma += xj*(1-kij)*(ai*aj)**0.5 aij.append(suma) tita = [] for bi, aai in zip(Bi, aij): rhs = bi/B*(Z-1) - log(Z-B) + A/B/(self.u-self.w)*( bi/B-2/A*aai) * log((Z+self.u*B)/(Z+self.w*B)) tita.append(exp(rhs)) return tita def _mixture(self, eq, xi, par): """Apply mix
ing rules to individual parameters to get the mixture parameters for EoS Although it possible use any of available mixing rules, for now other properties calculation as fugacity helmholtz free energy are defined using the vdW mixing rules. Parameters ---------- eq : str codename of equation, PR, SRK... xi : list Molar fraction of component, [-] par : list list with individual parameters of equation, [-] Returns ------- mixpar : list List with mixture parameters, [-] """ self.kij = Kij(self.mezcla.ids, eq) mixpar = Mixing_Rule(xi, par, self.kij) return mixpar def _Tr(self): """Definition of reducing parameters""" if len(self.mezcla.componente) > 1: # Mixture as one-fluid Tr = 1 rhor = 1 else: # Pure fluid Tr = self.mezcla.Tc rhor = 1/self.mezcla.Vc/1000 # m3/mol return Tr, rhor def _phir(self, T, rho, xi): Tr, rhor = self._Tr() tau = Tr/T delta = rho/rhor a, b, d, e = self._GEOS(xi) kw = self._da(tau, xi) Tr, rhor = self._Tr() kw["rhoc"] = rhor kw["Tc"] = Tr kw["Delta1"] = self.u kw["Delta2"] = self.w kw["bi"] = self.bi kw["b"] = b kw["a"] = a kw["R"] = self.R fir = CubicHelmholtz(tau, delta, **kw) # print(self._excess(tau, delta, fir)) # print("fir: ", fir["fir"]) # print("fird: ", fir["fird"]*delta) # print("firt: ", fir["firt"]*tau) # print("firdd: ", fir["firdd"]*delta**2) # print("firdt: ", fir["firdt"]*delta*tau) # print("firtt: ", fir["firtt"]*tau**2) # print("firddd: ", fir["firddd"]*delta**3) # print("firddt: ", fir["firddt"]*delta**2*tau) # print("firdtt: ", fir["firdtt"]*delta*tau**2) # print("firttt: ", fir["firttt"]*tau**3) # T = Tr/tau # rho = rhor*delta # print("P", (1+delta*fir["fird"])*R*T*rho) # print(delta, fir["fird"], R, T, rho) return fir def _excess(self, tau, delta, phir): fir = phir["fir"] fird = phir["fird"] firt = phir["firt"] firtt = phir["firtt"] p = {} p["Z"] = 1 + delta*fird p["H"] = tau*firt + delta*fird p["S"] = tau*firt - fir p["cv"] = -tau**2*firtt return p def _departure(self, a, b, d, e, TdadT, V, T): """Calculate departure function, Table 6-3 from [1]""" Z = 1 + b/(V-b) - a*V/R_atml/T/(V**2+d*V+e) # Numerador and denominator used in several expression K = (d**2-4*e)**0.5 num = 2*V + d - K den = 2*V + d + K kw = {} kw["Z"] = Z if K: kw["H"] = 1 - (a+TdadT)/R_atml/T/K*log(num/den) - Z kw["S"] = TdadT/R_atml/K*log(num/den) - log(Z*(1-b/V)) kw["A"] = -a/R_atml/T/K*log(num/den) + log(Z*(1-b/V)) kw["f"] = a/R_atml/T/K*log(num/den) - log(Z*(1-b/V)) - (1-Z) else: kw["H"] = 1 - Z kw["S"] = -log(Z*(1-b/V)) kw["A"] = log(Z*(1-b/V)) kw["f"] = -log(Z*(1-b/V)) - (1-Z) return kw # def _fug2(self, Z, xi): # """Calculate partial fugacities coefficieint of components # References # ---------- # mollerup, Chap 2, pag 64 and so # """ # V = Z*R_atml*self.T/self.P # g = log(V-self.b) - log(V) # Eq 61 # f = 1/R_atml/self.b/(self.delta1-self.delta2) * \ # log((V+self.delta1*self.b)/(V+self.delta2*self.b)) # Eq 62 # gB = -1/(V-self.b) # Eq 80 # An = -g # Eq 75 # AB = -n*gB-D/self.T*fB # Eq 78 # AD = -f/self.T # Eq 79 # # Ch.3, Eq 66 # dAni = An+AB*Bi+AD*Di # # Ch.2, Eq 13 # fi = dAni - log(Z) # return fi # def _fug(self, Z, xi): # Ai=[] # for i in range(len(self.componente)): # suma=0 # for j in range(len(self.componente)):
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('taxbrain', '0002_taxoutput_tax_result'), ] operations = [ migrations.AddF
ield( model_name='taxsa
veinputs', name='parameters', field=models.TextField(default=None), preserve_default=True, ), ]
from __future__ import absolute_import from rest_framework.response import Response from sentry import filters from sentry.api.bases.project import ProjectEndpoint class ProjectFiltersEndpoint(ProjectEndpoint): def get(self, request, project): """ List a project's filters Retrieve a list of filters for a given project. {method} {path} """ results = [] for f_cls in filters.all(): filter = f_cls(project) results.append({ 'id': filter.id
, # 'active' will be either a boolean or list for the legacy browser filters # all other filters will be boolean 'active': filter.is_enabled(), 'description': filter.description,
'name': filter.name, }) results.sort(key=lambda x: x['name']) return Response(results)
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from .update_resource import UpdateResource class VirtualMachineUpdate(UpdateResource): """Describes a Virtual Machine. Variables are only populated by the server, and will be ignored when sending a request. :param tags: Resource tags :type tags: dict[str, str] :param plan: Specifies information about the marketplace image used to create the virtual machine. This element is only used for marketplace images. Before you can use a marketplace image from an API, you must enable the image for programmatic use. In the Azure portal, find the marketplace image that you want to use and then click **Want to deploy programmatically, Get Started ->**. Enter any required information and then click **Save**. :type plan: ~azure.mgmt.compute.v2017_12_01.models.Plan :param hardware_profile: Specifies the hardware settings for the virtual machine. :type hardware_profile: ~azure.mgmt.compute.v2017_12_01.models.HardwareProfile :param storage_profile: Specifies the storage settings for the virtual machine disks. :type storage_profile: ~azure.mgmt.compute.v2017_12_01.models.StorageProfile :param os_profile: Specifies the operating system settings for the virtual machine. :type os_profile: ~azure.mgmt.compute.v2017_12_01.models.OSProfile :param network_profile: Specifies the network interfaces of the virtual machine. :type network_profile: ~azure.mgmt.compute.v2017_12_01.models.NetworkProfile :param diagnostics_profile: Specifies the boot diagnostic settings state. <br><br>Minimum api-version: 2015-06-15. :type diagnostics_profile: ~azure.mgmt.compute.v2017_12_01.models.DiagnosticsProfile :param availability_set: Specifies information about the availability set that the virtual machine should be assigned to. Virtual machines specified in the same availability set are allocated to different nodes to maximize availability. For more information about availability sets, see [Manage the availability of virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-manage-availability?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). <br><br> For more information on Azure planned maintainance, see [Planned maintenance for virtual machines in Azure](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-planned-maintenance?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json) <br><br> Currently, a VM can only be added to availability set at creation time. An existing VM cannot be added to an availability set. :type availability_set: ~azure.mgmt.compute.v2017_12_01.models.SubResource :ivar provisioning_state: The provisioning state, which only appears in the response. :vartype provisioning_state: str :ivar instance_view: The virtual machine instance view. :vartype instance_view: ~azure.mgmt.compute.v2017_12_01.models.VirtualMachineInstanceView :param license_type: Specifies that the image or disk that is being used was licensed on-premises. This element is only used for images that contain the Windows Server operating system. <br><br> Possible values are: <br><br> Windows_Client <br><br> Windows_Server <br><br> If this element is included in a request for an update, the value must match the initial value. This value cannot be updated. <br><br> For more information, see [Azure Hybrid Use Benefit for Windows Server](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-hybrid-use-benefit-licensing?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json) <br><br> Minimum api-version: 2015-06-15 :type license_type: str :ivar vm_id: Specifies the VM unique ID which is a 128-bits identifier that is encoded and stored in all Azure IaaS VMs SMBIOS and can be read using platform BIOS commands. :vartype vm_id: str :param identity: The identity of the virtual machine, if configured. :type identity: ~azure.mgmt.compute.v2017_12_01.models.VirtualMachineIdentity :param zones: The virtual machine zones. :type zones: list[str] """ _validation = { 'provisioning_state': {'readonly': True}, 'instance_view': {'readonly': True}, 'vm_id': {'readonly': True}, } _attribute_map = { 'tags': {'key': 'tags', 'type': '{str}'}, 'plan': {'key': 'plan', 'type': 'Plan'}, 'hardware_profile': {'key': 'properties.hardwareProfile', 'type': 'HardwareProfile'}, 'storage_profile': {'key': 'properties.storageProfile', 'type': 'StorageProfile'}, 'os_profile': {'key': 'properties.osProfile', 'type': 'OSProfile'}, 'network_profile': {'key': 'properties.networkProfile', 'type': 'NetworkProfile'}, 'diagnostics_profile': {'key': 'properties.diagnosticsProfile', 'type': 'DiagnosticsProfile'}, 'availability_set': {'key': 'properties.availabilitySet', 'type': 'SubResource'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'instance_view': {'ke
y': 'properties.instanceView', 'type': 'VirtualMachineInstanceView'}, 'license_type': {'key': 'properties.licenseType', 'type': 'str'}, 'vm_id'
: {'key': 'properties.vmId', 'type': 'str'}, 'identity': {'key': 'identity', 'type': 'VirtualMachineIdentity'}, 'zones': {'key': 'zones', 'type': '[str]'}, } def __init__(self, **kwargs): super(VirtualMachineUpdate, self).__init__(**kwargs) self.plan = kwargs.get('plan', None) self.hardware_profile = kwargs.get('hardware_profile', None) self.storage_profile = kwargs.get('storage_profile', None) self.os_profile = kwargs.get('os_profile', None) self.network_profile = kwargs.get('network_profile', None) self.diagnostics_profile = kwargs.get('diagnostics_profile', None) self.availability_set = kwargs.get('availability_set', None) self.provisioning_state = None self.instance_view = None self.license_type = kwargs.get('license_type', None) self.vm_id = None self.identity = kwargs.get('identity', None) self.zones = kwargs.get('zones', None)
class resonance(): """ This class represents a resonance. """ def __init__(self,cR=1.0,wR=[],w0=1.,r0=.5,phase=0.
): self.wR=wR self.cR=cR self.w0=w0 self.r0=r0
self.phase=phase def toString(self): """ Returns a string of the resonance data memebers delimited by newlines. """ return "\n".join(["wR="+str(self.wR),"cR="+str(self.cR),"w0="+str(self.w0),"r0="+str(self.r0)])
''' Convert a table from a nested list to a nested dictionary and back. ----------------------------------------------------------- (c) 2013 Allegra Via and Kristian Rother Licensed under the conditions of the Python License This code appears in section 7.4.3 of the book "Managing Biological Data with Python". ----------------------------------------------------------- ''' table = [ ['protein', 'ext1', 'ext2', 'ext3'], [0.16, 0.038, 0.044, 0.040], [0.33, 0.089, 0.095, 0.091], [0.66, 0.184, 0.191, 0.191], [1.00, 0.280, 0.292, 0.283], [1.32, 0.365, 0.367, 0.365], [1.66, 0.441, 0.443, 0.444] ] # convert nested list to nested dict nested_dict = {} n = 0 key = table[0] # to include the header , run the for loop over # All table elements (including the first one) for row in table[1:]: n = n + 1 entry = {key[0]:
row[0], key[1]: row[1], key[2]: row[2], key[3]: row[3]} nested_dict['row'+str(n)] = entry # Test # print(table[1:]) print(nested_dict) nested_list = [] for entry in nested_dict: key = nested_d
ict[entry] nested_list.append([key['protein'], key['ext1'], key['ext2'], key['ext3']]) print(nested_list)
error = e if too_many: Log.error( "multiple keys in {{bucket}} with prefix={{prefix|quote}}: {{list}}", bucket=self.name, prefix=key, list=[k.name for k in metas], ) if not perfect and error: Log.error("Problem with key request", error) return coalesce(perfect, favorite) except Exception as e: Log.error( READ_ERROR + " can not read {{key}} from {{bucket}}", key=key, bucket=self.bucket.name, cause=e, ) def keys(self, prefix=None, delimiter=None): """ :param prefix: NOT A STRING PREFIX, RATHER PATH ID PREFIX (MUST MATCH TO NEXT "." OR ":") :param delimiter: TO GET Prefix OBJECTS, RATHER THAN WHOLE KEYS :return: SET OF KEYS IN BUCKET, OR """ if delimiter: # WE REALLY DO NOT GET KEYS, BUT RATHER Prefix OBJECTS # AT LEAST THEY ARE UNIQUE candidates = [ k.name.rstrip(delimiter) for k in self.bucket.list(prefix=str(prefix), delimiter=str(delimiter)) ] else: candidates = [ strip_extension(k.key) for k in self.bucket.list(prefix=str(prefix)) ] if prefix == None: return set(c for c in candidates if c != "0.json") else: return set( k for k in candidates if k == prefix or k.startswith(prefix + ".") or k.startswith(prefix + ":") ) def metas(self, prefix=None, limit=None, delimiter=None): """ RETURN THE METADATA DESCRIPTORS FOR EACH KEY """ limit = coalesce(limit, TOO_MANY_KEYS) keys = self.bucket.list(prefix=str(prefix), delimiter=str(delimiter)) prefix_len = len(prefix) output = [] for i, k in enumerate( k for k in keys if len(k.key) == prefix_len or k.key[prefix_len] in [".", ":"] ): output.append( { "key": strip_extension(k.key), "etag": convert.quote2string(k.etag), "expiry_date": Date(k.expiry_date), "last_modified": Date(k.last_modified), } ) if i >= limit: break return to_data(output) def read(self, key): source = self.get_meta(key) try: json = safe_size(source) except Exception as e: Log.error(READ_ERROR, e) if json == None: return None if source.key.endswith(".zip"): json = _unzip(json) elif source.key.endswith(".gz"): json = convert.zip2bytes(json) return json.decode("utf8") def read_bytes(self, key): source = self.get_meta(key) return safe_size(source) def read_lines(self, key): source = self.get_meta(key) if source is None: Log.error("{{key}} does not exist", key=key) elif source.key.endswith(".gz"): return LazyLines(ibytes2ilines(scompressed2ibytes(source))) elif source.size < MAX_STRING_SIZE: return source.read().decode("utf8").split("\n") else: return LazyLines(source) def write(self, key, value, disable_zip=False): if key.endswith(".json") or key.endswith(".zip"): Log.error("Expecting a pure key") try: if hasattr(value, "read"): if disable_zip: storage = self.bucket.new_key(str(key + ".json")) string_length = len(value) headers = {"Content-Type": mimetype.JSON} else: storage = self.bucket.new_key(str(key + ".json.gz")) string_length = len(value) value = convert.bytes2zip(value) headers = {"Content-Type": mimetype.GZIP} file_length = len(value) Log.note( "Sending contents with length {{file_length|comma}} (from string with length {{string_lengt
h|comma}})", file_length=file_length, string_length=string_length, ) value.seek(0) storage.set_contents_from_file(value, headers=headers) if self.settings.public: storage.set_acl("public-read") return if len(value) > 20 * 1000 and not disable_zip: self.bucket.delete_key(str(key + ".json")) self.bucket.delete_key(s
tr(key + ".json.gz")) if is_binary(value): value = convert.bytes2zip(value) key += ".json.gz" else: value = convert.bytes2zip(value).encode("utf8") key += ".json.gz" headers = {"Content-Type": mimetype.GZIP} else: self.bucket.delete_key(str(key + ".json.gz")) if is_binary(value): key += ".json" else: key += ".json" headers = {"Content-Type": mimetype.JSON} storage = self.bucket.new_key(str(key)) storage.set_contents_from_string(value, headers=headers) if self.settings.public: storage.set_acl("public-read") except Exception as e: Log.error( "Problem writing {{bytes}} bytes to {{key}} in {{bucket}}", key=key, bucket=self.bucket.name, bytes=len(value), cause=e, ) def write_lines(self, key, lines): self._verify_key_format(key) storage = self.bucket.new_key(str(key + ".json.gz")) if VERIFY_UPLOAD: lines = list(lines) with mo_files.TempFile() as tempfile: with open(tempfile.abspath, "wb") as buff: DEBUG and Log.note("Temp file {{filename}}", filename=tempfile.abspath) archive = gzip.GzipFile(filename=str(key + ".json"), fileobj=buff, mode="w") count = 0 for l in lines: if is_many(l): for ll in l: archive.write(ll.encode("utf8")) archive.write(b"\n") count += 1 else: archive.write(l.encode("utf8")) archive.write(b"\n") count += 1 archive.close() retry = 3 while retry: try: with Timer( "Sending {{count}} lines in {{file_length|comma}} bytes for {{key}}", {"key": key, "file_length": tempfile.length, "count": count}, verbose=self.settings.debug, ): storage.set_contents_from_filename( tempfile.abspath, headers={"Content-Type": mimetype.GZIP} ) break except Exception as e: e = Except.wrap(e) retry -= 1 if ( retry == 0 or "Access Denied" in e or "No space left on device" in e ): Log.error("could not push data to s3", cause=e) else: Log.warning("could not push data to s3, will retry", cause=e) if self.settings.public: storage.set_acl("public-read") if VERIFY_UPLOAD: try: with open(tempfile.abspath, mode="rb") as source:
# -*- encoding: utf-8 -*- from abjad import * def test_p
itchtools_PitchClass_is_pitch_class_number_01(): assert pitchtools.PitchClass.is_pitch_class_number(0) assert pitchtools.PitchClass.is_pitch_class_number(0.5) assert pitchtools.PitchClass.is_pitch_class_number(11) assert pitchtools.PitchClass.is_pitch_class_number(11.5) def test_pitchtools_PitchClass_is_pitch_class_number_02(): assert not pitchtools.PitchClass.is_pitch_class_number(-1) assert not pitchtools.PitchClass.is_pitch_class_number(-0.5) assert not pitchtools.P
itchClass.is_pitch_class_number(12) assert not pitchtools.PitchClass.is_pitch_class_number(99) assert not pitchtools.PitchClass.is_pitch_class_number('foo')
# OpenShot Video Editor is a program that creates, modifies, and edits video files. # Copyright (C) 2009 Jonathan Thomas # # This file is part of OpenShot Video Editor (http://launchpad.net/openshot/). # # OpenShot Video Editor is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # OpenShot Video Editor is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with OpenShot Video Editor. If not, see <http://www.gnu.org/licenses/>. # Import Blender's python API. This only works when the script is being # run from the context of Blender. Blender contains it's own version of Python # with this library pre-installed. import bpy # Load a font def load_font(font_path): """ Load a new TTF font into Blender, and return the font object """ # get the original list of fonts (before we add a new one) original_fonts = bpy.data.fonts.keys() # load new font bpy.ops.font.open(filepath=font_path) # get the new list of fonts (after we added a new one) for font_name in bpy.data.fonts.keys(): if font_name not in original_fonts: return bpy.data.fonts[font_name] # no new font was added return None # Debug Info: # ./blender -b test.blend -P demo.py # -b = background mode # -P = run a Python script within the context of the project file # Init all of the variables needed by this script. Because Blender executes # this script, OpenShot will inject a dictionary of the required parameters # before this script is executed. params = { 'title' : 'Oh Yeah! OpenShot!', 'extrude' : 0.1, 'bevel_depth' : 0.02, 'spacemode' : 'CENTER', 'text_size' : 1.5, 'width' : 1.0, 'fontname' : 'Bfont', 'color' : [0.8,0.8,0.8], 'alpha' : 1.0, 'line1_color' : [0.8,0.8,0.8], 'line2_color' : [0.8,0.8,0.8], 'line3_color' : [0.8,0.8,0.8], 'line4_color' : [0.8,0.8,0.8], 'output_path' : '/tmp/', 'fps' : 24, 'quality' : 90, 'file_format' : 'PNG', 'color_mode' : 'RGBA', 'horizon_color' : [0.57, 0.57, 0.57], 'resolution_x' : 1920, 'resolution_y' : 1080, 'resolution_percentage' : 100, 'start_frame' : 20, 'end_frame' : 25, 'animation' : True, } #INJECT_PARAMS_HERE # The remainder of this script will modify the current Blender .blend project # file, and adjust the settings. The .blend file is specified in the XML file # that defines this template in OpenShot. #---------------------------------------------------------------------------- # Modify Text / Curve settings #print (bpy.data.curves.keys()) text_object = bpy.data.curves["Text.001"] text_object.extrude = params["extrude"] text_object.bevel_depth = params["bevel_depth"] text_object.body = params["title"] text_object.align = params["spacemode"] text_object.size = params["text_size"] text_object.space_character = params["width"] # Get font object font = None if params["fontname"] != "Bfont": # Add font so it's available to Blender font = load_font(params["fontname"]) else: # Get default font font = bpy.data.fonts["Bfont"] text_object.font = font # Change the material settings (color, alpha, etc...) material_object = bpy.data.materials["Material.title"] material_object.diffuse_color = params["diffuse_color"] material_object.specular_color = params["specular_color"] material_object.specular_intensity = params["specular_intensity"] material_object.alpha = params["alpha"] # Change line colors material_object = bpy.data.materials["Material.line1"] material_object.diffuse_color = params["line1_color"] material_object = bpy.data.materials["Material.line2"] material_object.diffuse_color = params["line2_color"] material_object =
bpy.data.materials["Material.line3"] material_object.diffuse_color = params["line3_color"] material_object =
bpy.data.materials["Material.line4"] material_object.diffuse_color = params["line4_color"] # Set the render options. It is important that these are set # to the same values as the current OpenShot project. These # params are automatically set by OpenShot bpy.context.scene.render.filepath = params["output_path"] bpy.context.scene.render.fps = params["fps"] #bpy.context.scene.render.quality = params["quality"] try: bpy.context.scene.render.file_format = params["file_format"] bpy.context.scene.render.color_mode = params["color_mode"] except: bpy.context.scene.render.image_settings.file_format = params["file_format"] bpy.context.scene.render.image_settings.color_mode = params["color_mode"] #bpy.data.worlds[0].horizon_color = params["horizon_color"] bpy.context.scene.render.resolution_x = params["resolution_x"] bpy.context.scene.render.resolution_y = params["resolution_y"] bpy.context.scene.render.resolution_percentage = params["resolution_percentage"] bpy.context.scene.frame_start = params["start_frame"] bpy.context.scene.frame_end = params["end_frame"] # Animation Speed (use Blender's time remapping to slow or speed up animation) animation_speed = int(params["animation_speed"]) # time remapping multiplier new_length = int(params["end_frame"]) * animation_speed # new length (in frames) bpy.context.scene.frame_end = new_length bpy.context.scene.render.frame_map_old = 1 bpy.context.scene.render.frame_map_new = animation_speed if params["start_frame"] == params["end_frame"]: bpy.context.scene.frame_start = params["end_frame"] bpy.context.scene.frame_end = params["end_frame"] # Render the current animation to the params["output_path"] folder bpy.ops.render.render(animation=params["animation"])
#!/user/bin/python ''' This script uses SimpleCV to grab an image from the camera and numpy to find an infrared LED and report its position relative to the camera view centre and whether it is inside the target area. Attempted stabilisation of the output by tracking a circular object instead and altering exposure of the camera. ''' # make it possible to import from parent directory: import sys sys.path.insert(0,'..') ## Change terminal window header for easier identification of contents sys.stdout.write("\x1b]2;Sensors/simpleCV_3.py\x07") import time, math, SimpleCV import zmq, json import subprocess as sp from globalVars import CHANNEL_TARGETDATA from globalVars import CAMERA_ID_NUMBER printing = True dpx = 0.0025 # approximate amount of degrees per pixel for Trust eLight width = 1920 height = 1080 camera_id = 'video' + str(CAMERA_ID_NUMBER) # To increase framerate, count the search() loops and render every n frames renderFrame = 5 frame = 0 # Adjust camera settings from OS, since SimpleCV's commands don't do anything: sp.call(["uvcdynctrl -d '"+camera_id+"' -s 'Exposure, Auto' 1"], shell = True) # Disable auto exposure sp.call(["uvcdynctrl -d '"+camera_id+"' -s 'Exposure (Absolute)' 12"], shell = True) # Set absolute exposure display = SimpleCV.Display() cam = SimpleCV.Camera(CAMERA_ID_NUMBER, {"width":width,"height":height}) #target box for the marker box_d = 20 yTgt = (height/2-box_d, height/2+box_d) xTgt = (width/2-box_d, width/2+box_d) box_clr = SimpleCV.Color.RED centre = (height/2, width/2) context = zmq.Context() socket = context.socket(zmq.PUB) socket.bind(CHANNEL_TARGETDATA) def search(): global frame, renderFrame img = cam.getImage() objective = img.colorDistance(color=(255,255,255)).invert() seg_objective = objective.stretch(200,255) blobs = seg_objective.findBlobs() if blobs: center_point = (blobs[-1].x, blobs[-1].y) if frame is renderFrame: img.drawCircle((blobs[-1].x, blobs[-1].y), 10,SimpleCV.Color.YELLOW,3) img.dl().rectangle2pts((xTgt[0], yTgt[0]), (xTgt[1],yTgt[1]), box_clr) img.show() frame = 0 frame +=1 return center_point if frame is renderFrame: img.dl().rectangle2pts((xTgt[0], yTgt[0]), (xTgt[1],yTgt[1]), box_clr) img.show() frame = 0 frame +=1 return None #get current time in milliseconds millis = lambda: int(round(time.time() * 1000)) ############################################################# # RUNNING CODE BELOW # ############################################################# tar_x = 0 tar_y = 0 deg_x = 0 deg_y = 0 last_tar = tar_x found = False findTime = 0 lastFound = findTime lossReported = False while display.isNotDone(): target = search() if target is not None: tar_x = target[0]-width/2 tar_y = target[1]-height/2 findTime = millis() found = True lossReported = False else: found = False lastFound = findTime # Angular difference between the box and the target # Having the target within the box is acceptable if abs(tar_x) > box_d: deg_x = tar_x * dpx else: deg_x = 0 if abs(tar_y) > box_d: deg_y = tar_y * dpx else: deg_y =
0 # If the target is in the box, indicate this with the box colour if deg_y is 0 and deg_x is 0 and found: box_clr = SimpleCV.Color.GREEN else: box_clr
= SimpleCV.Color.RED #output the data # not needed if there's no new data to report if not lossReported: message = { 't' : millis(), 'findTime': findTime, 'found' : found, 'tar_px' : {'x':tar_x, 'y':tar_y}, 'tar_dg' : {'x':deg_x, 'y':deg_y} } # wait 20 ms to make sure Scan picks up on the last hit if not found and millis() - findTime < 100: continue socket.send_json(message) print "Sent targetData: ", print message if lastFound == findTime: lossReported = False #spam to keep data flowing
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2015 NLPY.ORG # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html import numpy as np from line_iterator import LineIterator class FeatureContainer(object): def __init__(self, path=None, dtype="libsvm", feature_n=-1): self.N = 0 self.data = np.zeros(0) self.targets = np.zeros(0) self.feature_n = feature_n self.path = path self.dtype = dtype # if path: # self.read(path, dtype) def read(self): """ Read feature matrix from data :param path: data path :param type: libsvm (only) """ ys = [] xs = [] for line in LineIterator(self.path): items = line.split(" ") feature_map = {} y = 0 for item in items: if ":" in item: feature_idx, value = item.split(":") feature_map[int(feature_idx)] = float(value) else: y = int(item) if self.featur
e_n == -1: max_key = max(feature_map.keys()) if feature_map else 0 else: max_key = self.feature_n features = [] for fidx in range(1, max_key + 1): if fidx in feature_map: features.append(feature_map[fidx]) else: features.append(0) yield features, y # xs.append(features) # ys.append(y)
# # self.data = np.array(xs) # self.targets = np.array(ys)
''' Task Coach - Your friendly task manager Copyright (C) 2004-2010 Task Coach developers <developers@taskcoach.org> Task Coach is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Task Coach is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import test from taskcoachlib.widgets import treectrl class DummyEvent(object): def __init__(self, item=None): self.item = item self.vetoed = self.allowed = False def GetItem(self): return self.item def Veto(self): self.vetoed = True def Allow(self): self.allowed = True class TreeCtrlDragAndDropMixinTest(test.wxTestCase): # pylint: disable-msg=E1101 def setUp(self): self.treeCtrl = treectrl.HyperTreeList(self.frame) self.treeCtrl.AddColumn('First') self.rootItem = self.treeCtrl.AddRoot('root') self.item = self.treeCtrl.AppendItem(self.rootItem, 'item') def assertEventIsVetoed(self, event): self.failUnless(event.vetoed) self.failIf(event.allowed) def assertEventIsAllowed(self, event): self.failUnless(event.allowed) self.failIf(event.vetoed) def testEventIsVetoedWhenDragBeginsWithoutItem(self): event = DummyEvent() self.treeCtrl.OnBeginDrag(event) self.assertEventIsVetoed(event)
def testEventIsAllowedWhenDragBeginsWithItem(self):
event = DummyEvent(self.item) self.treeCtrl.OnBeginDrag(event) self.assertEventIsAllowed(event) def testEventIsAllowedWhenDragBeginWithSelectedItem(self): self.treeCtrl.SelectItem(self.item) event = DummyEvent(self.item) self.treeCtrl.OnBeginDrag(event) self.assertEventIsAllowed(event)
dFile, render from olympia.bandwagon.models import Collection from olympia.files.models import File, FileUpload from olympia.stats.search import get_mappings as get_stats_mappings from olympia.versions.models import Version from .decorators import admin_required from .forms import ( AddonStatusForm, FeaturedCollectionFormSet, FileFormSet, MonthlyPickFormSet) log = olympia.core.logger.getLogger('z.zadmin') @admin_required def show_settings(request): settings_dict = debug.get_safe_settings() return render(request, 'zadmin/settings.html', {'settings_dict': settings_dict, 'title': 'Settings!'}) @admin_required def env(request): env = {} for k in request.META.keys(): env[k] = debug.cleanse_setting(k, request.META[k]) return render(request, 'zadmin/settings.html', {'settings_dict': env, 'title': 'Env!'}) @admin.site.admin_view def fix_disabled_file(request): file_ = None if request.method == 'POST' and 'file' in request.POST: file_ = get_object_or_404(File, id=request.POST['file']) if 'confirm' in request.POST: file_.unhide_disabled_file() messages.success(request, 'We have done a great thing.') return redirect('zadmin.fix-disabled') return render(request, 'zadmin/fix-disabled.html', {'file': file_, 'file_id': request.POST.get('file', '')}) @admin_required @json_view def collections_json(request): app = request.GET.get('app', '') q = request.GET.get('q', '') data = [] if not q: return data qs = Collection.objects.all() try: qs = qs.filter(pk=int(q)) except ValueError: qs = qs.filter(slug__startswith=q) try: qs = qs.filter(application=int(app)) except ValueError: pass for c in qs[:7]: data.append({'id': c.id, 'name': six.text_type(c.name), 'slug': six.text_type(c.slug), 'all_personas': c.all_personas, 'url': c.get_url_path()}) return data @admin_required @post_required def featured_collection(request): try: pk = int(request.POST.get('collection', 0)) except ValueError: pk = 0 c = get_object_or_404(Collection, pk=pk) return render(request, 'zadmin/featured_collection.html', dict(collection=c)) @admin_required def features(request): form = FeaturedCollectionFormSet(request.POST or None) if request.method == 'POST' and form.is_valid(): form.save(commit=False) for obj in form.deleted_objects: obj.delete() messages.success(request, 'Changes successfully saved.') return redirect('zadmin.features') return render(request, 'zadmin/features.html', dict(form=form)) @admin_required def monthly_pick(request): form = MonthlyPickFormSet(request.POST or None) if request.method == 'POST' and form.is_valid(): form.save() messages.success(request, 'Changes successfully saved.') return redirect('zadmin.monthly_pick') return render(request, 'zadmin/monthly_pick.html', dict(form=form)) @admin_required def elastic(request): INDEX = settings.ES_INDEXES['default'] es = search.get_es() indexes = set(settings.ES_INDEXES.values()) es_mappings = { 'addons': get_addons_mappings(), 'addons_stats': get_stats_mappings(), } ctx = { 'index': INDEX, 'nodes': es.nodes.stats(), 'health': es.cluster.health(), 'state': es.cluster.state(), 'mappings': [(index, es_mappings.get(index, {})) for index in indexes], } return render(request, 'zadmin/elastic.html', ctx) @admin.site.admin_view def mail(request): backend = DevEmailBackend() if request.method == 'POST': backend.clear() return redirect('zadmin.mail') return render(request, 'zadmin/mail.html', dict(mail=backend.view_all())) @permission_required(amo.permissions.ANY_ADMIN) def index(request): log = ActivityLog.objects.admin_events()[:5] return render(request, 'zadmin/index.html', {'log': log}) @admin_required def addon_search(request): ctx = {} if 'q' in request.GET: q = ctx['q'] = request.GET['q'] if q.isdigit(): qs = Addon.objects.filter(id=int(q))
else: qs = Addon.search().query(name__text=q.lower())[:100] if len(qs) == 1:
return redirect('zadmin.addon_manage', qs[0].id) ctx['addons'] = qs return render(request, 'zadmin/addon-search.html', ctx) @never_cache @json_view def general_search(request, app_id, model_id): if not admin.site.has_permission(request): raise PermissionDenied try: model = apps.get_model(app_id, model_id) except LookupError: raise http.Http404 limit = 10 obj = admin.site._registry[model] ChangeList = obj.get_changelist(request) # This is a hideous api, but uses the builtin admin search_fields API. # Expecting this to get replaced by ES so soon, that I'm not going to lose # too much sleep about it. args = [request, obj.model, [], [], [], [], obj.search_fields, [], obj.list_max_show_all, limit, [], obj] try: # python3.2+ only from inspect import signature if 'sortable_by' in signature(ChangeList.__init__).parameters: args.append('None') # sortable_by is a django2.1+ addition except ImportError: pass cl = ChangeList(*args) qs = cl.get_queryset(request) # Override search_fields_response on the ModelAdmin object # if you'd like to pass something else back to the front end. lookup = getattr(obj, 'search_fields_response', None) return [{'value': o.pk, 'label': getattr(o, lookup) if lookup else str(o)} for o in qs[:limit]] @admin_required @addon_view_factory(qs=Addon.objects.all) def addon_manage(request, addon): form = AddonStatusForm(request.POST or None, instance=addon) pager = amo.utils.paginate( request, Version.unfiltered.filter(addon=addon), 30) # A list coercion so this doesn't result in a subquery with a LIMIT which # MySQL doesn't support (at this time). versions = list(pager.object_list) files = File.objects.filter(version__in=versions).select_related('version') formset = FileFormSet(request.POST or None, queryset=files) if form.is_valid() and formset.is_valid(): if 'status' in form.changed_data: ActivityLog.create(amo.LOG.CHANGE_STATUS, addon, form.cleaned_data['status']) log.info('Addon "%s" status changed to: %s' % ( addon.slug, form.cleaned_data['status'])) form.save() for form in formset: if 'status' in form.changed_data: log.info('Addon "%s" file (ID:%d) status changed to: %s' % ( addon.slug, form.instance.id, form.cleaned_data['status'])) form.save() return redirect('zadmin.addon_manage', addon.slug) # Build a map from file.id to form in formset for precise form display form_map = dict((form.instance.id, form) for form in formset.forms) # A version to file map to avoid an extra query in the template file_map = {} for file in files: file_map.setdefault(file.version_id, []).append(file) return render(request, 'zadmin/addon_manage.html', { 'addon': addon, 'pager': pager, 'versions': versions, 'form': form, 'formset': formset, 'form_map': form_map, 'file_map': file_map}) @admin_required def download_file_upload(request, uuid): upload = get_object_or_404(FileUpload, uuid=uuid) return HttpResponseSendFile(request, upload.path, content_type='application/octet-stream') @admin.site.admin_view @post_required @json_view def recalc_hash(request, file_id): file = get_object_or_404(File, pk=file_id) file.size = storage.size(file.file_path) file.hash = file.generate_hash() file.save() log.info('Recalculated hash f
xit with 128 + {reiceived SIG} # 128 - 141 == -13 == -SIGPIPE, sometimes python receives -13 for some subprocesses raise RuntimeError('Error reading from pipe. Subcommand exited with non-zero exit status %s.' % self._process.returncode) def close(self): self._finish() def __del__(self): self._finish() def __enter__(self): return self def _abort(self): """ Call _finish, but eat the exception (if any). """ try: self._finish() except KeyboardInterrupt: raise except BaseException: pass def __exit__(self, type, value, traceback): if type: self._abort() else: self._finish() def __getattr__(self, name): if name == '_process': raise AttributeError(name) try: return getattr(self._process.stdout, name) except AttributeError: return getattr(self._input_pipe, name) def __iter__(self): for line in self._process.stdout: yield line self._finish() def readable(self): return True def writable(self): return False def seekable(self): return False class OutputPipeProcessWrapper(object): WRITES_BEFORE_FLUSH = 10000 def __init__(self, command, output_pipe=None): self.closed = False self._command = command self._output_pipe = output_pipe self._process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=output_pipe, close_fds=True) self._flushcount = 0 def write(self, *args, **kwargs): self._process.stdin.write(*args, **kwargs) self._flushcount += 1 if self._flushcount == self.WRITES_BEFORE_FLUSH: self._process.stdin.flush() self._flushcount = 0 def writeLine(self, line): assert '\n' not in line self.write(line + '\n') def _finish(self): """ Closes and waits for subprocess to exit. """ if self._process.returncode is None: self._process.stdin.flush() self._process.stdin.close() self._process.wait() self.closed = True def __del__(self): if not self.closed: self.abort() def __exit__(self, type, value, traceback): if type is None: self.close() else: self.abort() def __enter__(self): return self def close(self): self._finish() if self._process.returncode == 0: if self._output_pipe is not None: self._output_pipe.close() else: raise RuntimeError('Error when executing command %s' % self._command) def abort(self): self._finish() def __getattr__(self, name): if name == '_process': raise AttributeError(name) try: return getattr(self._process.stdin, name) except AttributeError: return getattr(self._output_pipe, name) def readable(self): return False def writable(self): return True def seekable(self): return False class BaseWrapper(object): def __init__(self, stream, *args, **kwargs): self._stream = stream try: super(BaseWrapper, self).__init__(stream, *args, **kwargs) except TypeError: pass def __getattr__(self, name): if name == '_stream': raise AttributeError(name) return getattr(self._stream, name) def __enter__(self): self._stream.__enter__() return self def __exit__(self, *args): self._stream.__exit__(*args) def __iter__(self): try: for line in self._stream: yield line finally: self.close() class NewlineWrapper(BaseWrapper): def __init__(self, stream, newline=None): if newline is None: self.newline = newline else: self.newline = newline.encode('ascii') if self.newline not in (b'', b'\r\n', b'\n', b'\r', None): raise ValueError("newline need to be one of {b'', b'\r\n', b'\n', b'\r', None}") super(NewlineWrapper, self).__init__(stream) def read(self, n=-1): b = self._stream.read(n) if self.newline == b'': return b if self.newline is None: newline = b'\n' return re.sub(b'(\n|\r\n|\r)', newline, b) def writelines(self, lines): if self.newline is None or self.newline == '': newline = os.linesep.encode('ascii') else: newline = self.newline self._stream.writelines( (re.sub(b'(\n|\r\n|\r)', newline, line) for line in lines) ) def write(self, b): if self.newline is None or self.newline == '': newline = os.linesep.encode('ascii') else: newline = self.newline self._stream.write(re.sub(b'(\n|\r\n|\r)', newline, b)) class MixedUnicodeBytesWrapper(BaseWrapper): """ """ def __init__(self, stream, encoding=None): if encoding is None: encoding = locale.getpreferredencoding() self.encoding = encoding super(MixedUnicodeBytesWrapper, self).__init__(st
ream) def write(self, b): self._stream.write(self._convert(b)) def writelines(self, lines): self._stream.writelines((self._convert(line) for line in lines)) def _convert(self, b): if isinstance(b, six.text_type): b = b.encode(self.encoding) warnings.warn('Writing unicode to byte stream', stacklevel=2) return b class Format(object)
: """ Interface for format specifications. """ @classmethod def pipe_reader(cls, input_pipe): raise NotImplementedError() @classmethod def pipe_writer(cls, output_pipe): raise NotImplementedError() def __rshift__(a, b): return ChainFormat(a, b) class ChainFormat(Format): def __init__(self, *args, **kwargs): self.args = args try: self.input = args[0].input except AttributeError: pass try: self.output = args[-1].output except AttributeError: pass if not kwargs.get('check_consistency', True): return for x in range(len(args) - 1): try: if args[x].output != args[x + 1].input: raise TypeError( 'The format chaining is not valid, %s expect %s' 'but %s provide %s' % ( args[x].__class__.__name__, args[x].input, args[x + 1].__class__.__name__, args[x + 1].output, ) ) except AttributeError: pass def pipe_reader(self, input_pipe): for x in reversed(self.args): input_pipe = x.pipe_reader(input_pipe) return input_pipe def pipe_writer(self, output_pipe): for x in reversed(self.args): output_pipe = x.pipe_writer(output_pipe) return output_pipe class TextWrapper(io.TextIOWrapper): def __exit__(self, *args): # io.TextIOWrapper close the file on __exit__, let the underlying file decide if not self.closed and self.writable(): super(TextWrapper, self).flush() self._stream.__exit__(*args) def __del__(self, *args): # io.TextIOWrapper close the file on __del__, let the underlying file decide if not self.closed and self.writable(): super(TextWrapper, self).flush() try: self._stream.__del__(*args) except AttributeError: pass def __init__(self, stream, *args, **kwargs): self._stream = stream
import unittest from card import Card class CardT
est(unittest.TestCase): def test_create(self): suit = 'Hearts' rank = 'Ace' card1 = Card(suit, rank) self.assertEqual((suit, rank), card1.get_value()) def test___eq__(self): card1 = Card('Spades', 'Queen') card2 = Card('Spades', 'Queen') self.assertEqual(card1, card2) card3 = Card('Hearts',
'Queen') self.assertNotEqual(card1, card3) if __name__ == '__main__': unittest.main(verbosity=2)
import logging from logging.handlers import RotatingFileHandler from flask import Flask, render_template from flask_login import LoginManager from flask_restful import Api from flask_wtf.csrf import CsrfProtect from itsdangerous import URLSafeTimedSerializer from sqlalchemy import create_engine import AppConfig from RestRes
ources.Resources import PostsList, Posts from services.Services import UserService from views import Login, Common, Post, Admin app = Flask(__name__) CsrfProtect(app) login_serializer = URLSafeTimedSerializer(AppConfig.APPSECRETKEY) @app.errorhandler(404) def not_found(error): return render_template('404.html'), 404 # set the secret key. keep this really secret: app.secret_key = AppCon
fig.APPSECRETKEY def register_mods(): app.register_blueprint(Common.mod) app.register_blueprint(Login.mod) app.register_blueprint(Post.mod) app.register_blueprint(Admin.mod) def create_db_engine(): return create_engine(AppConfig.CONNECTIONSTRING, pool_recycle=3600, echo=True) def build_db_engine(): AppConfig.DBENGINE = create_db_engine() def init_login(): login_manager = LoginManager() login_manager.init_app(app) AppConfig.LOGINMANAGER = login_manager # Create user loader function @login_manager.user_loader def load_user(user_id): return UserService().getAll().filter_by(id=user_id).first() @login_manager.token_loader def get_user_token(token): max_age = app.config["REMEMBER_COOKIE_DURATION"].total_seconds() #Decrypt the Security Token, data = [username, hashpass] data = login_serializer.loads(token, max_age=max_age) userService = UserService() #Find the User user = userService.getById(data[0]) #Check Password and return user or None if user and userService.validate(user.username, user.password): return user return None def init_logger(): handler = RotatingFileHandler('FlaskTest.log', maxBytes=10000, backupCount=1) handler.setLevel(logging.INFO) app.logger.addHandler(handler) def register_rest_api(): return Api(app) def register_rest_resources(): api.add_resource(PostsList, '/api/posts') api.add_resource(Posts, '/api/posts/<string:post_id>') def set_app_configuration(): app.config['REMEMBER_COOKIE_DURATION'] = AppConfig.REMEMBER_COOKIE_DURATION register_mods() api = register_rest_api() register_rest_resources() build_db_engine() init_login() init_logger() set_app_configuration() app.run(AppConfig.APPHOST, AppConfig.APPPORT)
import pytest from bughouse.models import ( BLACK, WHITE, OVERALL_OVERALL, ) from bughouse.ratings.engines.overall import ( rate_teams, rate_players, ) def test_rate_single_game(factories, models, elo_settings): game = factories.GameFactory() r1, r2 = rate_teams(game) assert r1.rating == 1006 assert r2.rating == 994 def test_rate_multiple_games(factories, models): team_a = factories.TeamFactory() team_b = factories.TeamFactory() rate_teams(factories.GameFactory(winning_team=team_a, losing_team=team_b)) rate_teams(factories.GameFactory(winning_team=team_a, losing_team=team_b)) assert team_a.get_latest_rating(OVERALL_OVERALL) == 1012 assert team_b.get_latest_rating(OVERALL_OVERALL) == 988 @pytest.mark.parametrize( 'losing_color', (BLACK, WHITE), ) def test_individual_ratings(factories, models, losing_color): game = factories.GameFactory(losing_color=losing_color) if game.losing_color == game.BLACK: wtwr, wtbr, ltwr, ltbr = rate_players(game) assert wtwr.player.get_latest_rating(OVERALL_OVERALL) == 1007 assert wtbr.player.get_latest_rating(OVERALL_OVERALL) == 1006 assert ltwr.player.get_latest_rating(OVERALL_OVERALL) == 994 assert ltbr.player.get_latest_rating(OVERALL_OVERALL) == 993 else: wtwr, wtbr, ltwr, ltbr = rate_players(game) assert wtwr.player.get_latest_rating(OVERALL_OVERALL) == 1006 assert wtbr.player.get_latest_rating(OVERALL_OVERALL) == 1007 assert ltwr.player.get_latest_rating(OVERALL_OVERALL) == 993 assert ltbr.player.get_latest_rating(OVERALL_OVERALL) == 994 def test_ratings_computation_is_idempotent(factories, models): """ Ensure that going back and re-computing old game ratings is an idempotent process. """ team_a = factories.TeamFactory() team_b = factories.TeamFactory() factories.GameFactory(winning_team=team_a, losing_team=team_b) game_b = f
actories.GameFactory(winning_team=team_a, losing_team=team_b) factories.GameFactory(winning_team=team_a, losing_team=team_b) first_rating_initial = team_a.ratings.get( game=game_b, ).rating rate_teams(game_b) first_rating_recomputed = team_a.ratings.get( game=game_b, ).rating assert first_rating_initial == first_rating
_recomputed
# License AGPL-3.0 or late
r (https://www.gnu.org/licenses/agpl). from . im
port mod123
__problem_title__ = "Integer sided triangles for which the area/perimeter ratio is integral" __problem_url___ = "https://projecteuler.net/problem=283" __problem_description__ = "Consider the triangle with sides 6, 8 and 10. It can be seen that the " \ "perimeter and the area are both equal to 24. So the area/perimeter " \ "ratio is equal to 1. Consider also the triangle with sides 13, 14 and " \ "15. The perimeter equals 42 while the area is equal to 84. So for " \ "this triangle the area/perimeter ratio is equa
l to 2. Find the sum of " \ "the perimeters of all integer
sided triangles for which the " \ "area/perimeter ratios are equal to positive integers not exceeding " \ "1000." import timeit class Solution(): @staticmethod def solution1(): pass @staticmethod def time_solutions(): setup = 'from __main__ import Solution' print('Solution 1:', timeit.timeit('Solution.solution1()', setup=setup, number=1)) if __name__ == '__main__': s = Solution() print(s.solution1()) s.time_solutions()
n wrest: try: select.append(all_lines.index(iwrest)) except ValueError: pass select.sort() # GUIs self.vplt_widg.llist['List'] = llist['List'] self.vplt_widg.llist['show_line'] = select self.vplt_widg.idx_line = 0 self.slines.selected = select #QtCore.pyqtRemoveInputHook() #xdb.set_trace() #QtCore.pyqtRestoreInputHook() self.slines.on_list_change(llist[llist['List']]) # Write def set_outfil(self): self.outfil = str(self.out_box.text()) print('XVelPlot: Will write to {:s}'.format(self.outfil)) # Write def write_out(self): self.vplt_widg.abs_sys.absid_file = self.outfil self.vplt_widg.abs_sys.write_absid_file() # Write + Quit def write_quit(self): self.write_out() self.flg_quit = 1 self.abs_sys = self.vplt_widg.abs_sys self.done(1) # Write + Quit def quit(self): #self.abs_sys = self.vplt_widg.abs_sys # Have to write to pass back self.flg_quit = 0 self.done(1) # x_specplot replacement class XAODMGui(QtGui.QDialog): ''' GUI to show AODM plots 28-Dec-2014 by JXP ''' def __init__(self, spec, z, wrest, vmnx=[-300., 300.]*u.km/u.s, parent=None, norm=True): super(XAODMGui, self).__init__(parent) ''' spec = Spectrum1D ''' # Grab the pieces and tie together self.aodm_widg = xspw.AODMWidget(spec,z,wrest,vmnx=vmnx,norm=norm) self.aodm_widg.canvas.mpl_connect('key_press_event', self.on_key) vbox = QtGui.QVBoxLayout() vbox.addWidget(self.aodm_widg) self.setLayout(vbox) self.aodm_widg.on_draw() def on_key(self,event): if event.key == 'q': # Quit self.done(1) # Script to run XSpec from the command line def run_xspec(*args, **kwargs): ''' Runs the XSpecGui Command line or from Python Examples: 1. python ~/xastropy/xastropy/xguis/spec_guis.py 1 2. spec_guis.run_xspec(filename) 3. spec_guis.run_xspec(spec1d) ''' import argparse from specutils import Spectrum1D from xastropy.spec.utils import XSpectrum1D parser = argparse.ArgumentParser(description='Parse for XSpec') parser.add_argument("flag", type=int, help="GUI flag (ignored)") parser.add_argument("file", type=str, help="Spectral file") parser.add_argument("-zsys", type=float, help="System Redshift") parser.add_argument("--un_norm", help="Spectrum is NOT normalized", action="store_true") if len(args) == 0: pargs = parser.parse_args() else: # better know what you are doing! #xdb.set_trace() if type(args[0]) in [XSpectrum1D, Spectrum1D]: app = QtGui.QApplication(sys.argv) gui = XSpecGui(args[0], **kwargs) gui.show() app.exec_() return else: # String parsing largs = ['1'] + [iargs for iargs in args] pargs = parser.parse_args(largs) # Normalized? norm=True if pargs.un_norm: norm=False # Second spectral file? try: zsys = pargs.zsys except AttributeError: zsys=None app = QtGui.QApplication(sys.argv) gui = XSpecGui(pargs.file, zsys=zsys, norm=norm) gui.show() app.exec_() # Script to run XAbsID from the command line def run_xabsid(): import argparse parser = argparse.ArgumentParser(description='Script for XSpec') parser.add_argument("flag", type=int, help="GUI flag (ignored)") parser.add_argument("file", type=str, help="Spectral file") parser.add_argument("--un_norm", help="Spectrum is NOT normalized", action="store_true") parser.add_argument("-id_dir", type=str, help="Directory for ID files (ID_LINES is default)") parser.add_argument("-secondfile", type=str, help="Second spectral file") args = parser.parse_args() # Normalized? norm=True if args.un_norm: norm=False # Second spectral file? second_file=None if args.secondfile: second_file=args.secondfile # Launch app = QtGui.QApplication(sys.argv) gui = XAbsIDGui(args.file, norm=norm, second_file=second_file) gui.show() app.exec_() # ################ if __name__ == "__main__": import sys from linetools.spectra import io as lsi from xastropy.igm import abs_sys as xiabs if len(sys.argv) == 1: # TESTING flg_fig = 0 #flg_fig += 2**0 # XSpec #flg_fig += 2**1 # XAbsID #flg_fig += 2**2 # XVelPlt Gui flg_fig += 2**3 # XVelPlt Gui without ID list; Also tests select wave #flg_fig += 2**4 # XAODM Gui # Read spectrum spec_fil = '/u/xavier/Keck/HIRES/RedData/PH957/PH957_f.fits' spec = lsi.readspec(spec_fil) # XSpec if (flg_fig % 2) == 1: app = QtGui.QApplication(sys.argv) gui = XSpecGui(spec) gui.show() app.exec_() # XAbsID if (flg_fig % 2**2) >= 2**1: #spec_fil = '/u/xavier/PROGETTI/LLSZ3/data/normalize/SDSSJ1004+0018_nF.fits' #spec = xspec.readwrite.readspec(spec_fil) #norm = True spec_fil = '/Users/xavier/Dropbox/CASBAH/jxp_analysis/FBQS0751+2919/fbqs0751_nov2014bin.fits' norm = False absid_fil = '/Users/xavier/paper/LLS/Optical/Data/Analysis/MAGE/SDSSJ1004+0018_z2.746_id.fits' absid_fil2 = '/Users/xavier/paper/LLS/Optical/Data/Analysis/MAGE/SDSSJ2348-1041_z2.997_id.fits' app = QtGui.QApplication(sys.argv) gui = XAbsIDGui(spec_fil,norm=norm) #,absid_list=[absid_fil, absid_fil2]) gui.show() app.exec_() # XVelPlt with existing AbsID file if (flg_fig % 2**3) >= 2**2: spec_fil = '/u/xavier/PROGETTI/LLSZ3/data/normalize/SDSSJ1004+0018_nF.fits' #spec = xspec.readwrite.readspec(spec_fil) absid_fil = '/Users/xavier/paper/LLS/Optical/Data/Analysis/MAGE/SDSSJ1004+0018_z2.746_id.fits' abs_sys = xiabs.abssys_utils.Generic_System(None) abs_sys.parse_absid_file(absid_fil) # app = QtGui.QApplication(sys.argv) app.setApplicationName('XVelPlt') gui = XVelPltGui(spec_fil,abs_sys=abs_sys, outfil='/Users/xavier/Desktop/tmp.fits') gui.show() sys.exit(app.exec_()) # XVelPlt without existing AbsID file if (flg_fig % 2**4) >= 2**3: #spec_fil = '/u/xavier/PROGETTI/LLSZ3/data/normalize/SDSSJ1004+0018_nF.fits' #z=2.746 #outfil='/Users/xavier/Desktop/J1004+0018_z2.746_id.fits' spec_fil = '/Users/xavier/Dropbox/CASBAH/jxp_analysis/FBQS0751+2919/fbqs0751_nov2014bin.fits' z=0. outfil='/Users/xavier/Desktop/tmp.fits' # app = QtGui.QApplication(sys.argv) app.setApplicationName('XVelPlt') gui = XVelPltGui(spec_fil, z=z, outfil=outfil,norm=False, sel_wv=1526.80) gui.show() sys.exit(app.exec_()) # AODM GUI if (flg_fig % 2**5) >= 2**4: #spec_fil = '/Users/xavier/PROGETTI/LLSZ3/data/normalize/UM184_nF.fits'
#z=2.96916 #lines = [1548.195, 1550.770] norm = True spec_fil = '/Users/xavier/Dropbox/CASBAH/jxp_analysis/FBQS0751+2919/fbqs0751_nov2014bin.fits' z=0.4391 lines = [1215.6701, 1025.7223] * u.AA
norm = False # Launch spec = lsi.readspec(spec_fil) app = QtGui.QApplication(sys.argv) app.setApplicationName('AODM') main = XAODMGui(spec, z, lines, norm=norm) main.show() sys.exit(app.exec_()) else: # RUN A GUI id_gui = int(sys.argv[1]) # 1 = XSpec, 2=XAbsId if id_gui == 1: run_xspec()
# -*- coding: utf-8 -*- """ example1-simpleloop ~~~~~~~~~~~~~~~~~~~ This example shows how to use the loop block backend and frontend. :copyright: 2015 by Lantz Authors, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ # From lantz, you import a helper function. from lantz.ui.app import start_gui_app # and the loop block and its user interface from lantz.ui.blocks import Loop, LoopUi # the drivers you need (In this case just simulated dummy driv
ers). from lantz.drivers.examples.dummydrivers import DummyOsci # Drivers are instantiated in the usual way. osci = DummyOsci('COM2') # You create a function that will be called by the loop # It requires three parameters # counter - the iteration number # iterations - total number of iterations # overrun - a boolean indicating if the time required for the operati
on # is longer than the interval. def measure(counter, iterations, overrun): print(counter, iterations, overrun) data = osci.measure() print(data) # You instantiate the loop app = Loop() # and assign the function to the body of the loop app.body = measure # Finally you start the program start_gui_app(app, LoopUi) # This contains a very complete GUI for a loop you can easily create a customized version!
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'cmsplugin_filer_image_translated.imagetranslation': { 'Meta': {'object_name': 'ImageTranslation'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'translation'", 'unique': 'True', 'to': "orm['filer.Image']"}) }, 'cmsplugin_filer_image_translated.imagetranslationrenamed': { 'Meta': {'object_name': 'ImageTranslationRenamed'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['filer.Image']"}), 'language': ('django.db.models.fields.CharField', [], {'max_length': '2'}), 'trans_alt_text': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'trans_caption': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'trans_description': ('django.db.models.fields.TextField', [], {'max_length': '256', 'blank': 'True'}), 'trans_name': ('django.db.models.fields.CharField', [], {'max_length': '256', 'blank': 'True'}) }, 'cmsplugin_filer_image_translated.imagetranslationtranslation': { 'Meta': {'unique_together': "[('language_code', 'master')]", 'object_name': 'ImageTranslationTranslation', 'db_table': "'cmsplugin_filer_image_translated_imagetranslation_translation'"}, 'alt_text': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'caption': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'max_length': '256', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language_code': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}), 'master': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'translations'", 'null': 'True', 'to': "orm['cmsplugin_filer_image_translated.ImageTranslation']"}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '256', 'blank': 'True'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'filer.file': { 'Meta': {'object_name': 'File'}, '_file_size': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'file': ('django.db.models.fields.files.FileField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'folder': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'all_files'", 'null': 'True', 'to': "orm['filer.Folder']"}), 'has_all_mandatory_data': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'modified_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'blank': 'True'}), 'original_filename': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'owned_files'", 'null': 'True', 'to': "orm['auth.User']"}), 'polymorphic_ctype': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'polymorphic_filer.file_set'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}), 'sha1': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '40', 'blank': 'True'}), 'uploaded_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}) }, 'filer.folder': { 'Meta': {'ordering': "('name',)", 'unique_to
gether': "(('parent', 'name'),)", 'object_name': 'Folder'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'modified_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'filer_owned_folders'", 'null': 'True', 'to': "orm['auth.User']"}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['filer.Folder']"}), 'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'uploaded_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}) }, 'filer.image': { 'Meta': {'object_name': 'Image', '_ormbases': ['filer.File']}, '_height': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), '_width': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'author': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'date_taken': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'default_alt_text': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'default_caption': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'file_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['filer.File']", 'unique': 'True', 'primary_key': 'True'}), 'must_always_publish_author_credit': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'must_always_publish_copyright': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'subject_location': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '64', 'null': 'True', 'blank': 'True'}) } } complete_apps =
lat1) * LOCATION_SCAL
ING_FACTOR, (lon2 - lon1) * LOCATION_SCALING_FACTOR * longitude_scale(lat1*1.0e-7)) def add_offset(lat_e7, lon_e7, ofs_north, ofs_east): '''add offset in meters to a position''' dlat = int(float(ofs_north) * LOCATION_SCALING_FACTOR_INV) dlng = int((float(ofs_east) * LOCATION_SCALING_FACTOR_INV) / longitude_scale(lat_e7*1.0e-7))
return (int(lat_e7+dlat), int(lon_e7+dlng)) def east_blocks(lat_e7, lon_e7): '''work out how many blocks per stride on disk''' lat2_e7 = lat_e7 lon2_e7 = lon_e7 + 10*1000*1000 # shift another two blocks east to ensure room is available lat2_e7, lon2_e7 = add_offset(lat2_e7, lon2_e7, 0, 2*GRID_SPACING*TERRAIN_GRID_BLOCK_SIZE_Y) offset = get_distance_NE_e7(lat_e7, lon_e7, lat2_e7, lon2_e7) return int(offset[1] / (GRID_SPACING*TERRAIN_GRID_BLOCK_SPACING_Y)) def pos_from_file_offset(lat_degrees, lon_degrees, file_offset): '''return a lat/lon in 1e7 format given a file offset''' ref_lat = int(lat_degrees*10*1000*1000) ref_lon = int(lon_degrees*10*1000*1000) stride = east_blocks(ref_lat, ref_lon) blocks = file_offset // IO_BLOCK_SIZE grid_idx_x = blocks // stride grid_idx_y = blocks % stride idx_x = grid_idx_x * TERRAIN_GRID_BLOCK_SPACING_X idx_y = grid_idx_y * TERRAIN_GRID_BLOCK_SPACING_Y offset = (idx_x * GRID_SPACING, idx_y * GRID_SPACING) (lat_e7, lon_e7) = add_offset(ref_lat, ref_lon, offset[0], offset[1]) offset = get_distance_NE_e7(ref_lat, ref_lon, lat_e7, lon_e7) grid_idx_x = int(idx_x / TERRAIN_GRID_BLOCK_SPACING_X) grid_idx_y = int(idx_y / TERRAIN_GRID_BLOCK_SPACING_Y) (lat_e7, lon_e7) = add_offset(ref_lat, ref_lon, grid_idx_x * TERRAIN_GRID_BLOCK_SPACING_X * float(GRID_SPACING), grid_idx_y * TERRAIN_GRID_BLOCK_SPACING_Y * float(GRID_SPACING)) return (lat_e7, lon_e7) class GridBlock(object): def __init__(self, lat_int, lon_int, lat, lon): ''' a grid block is a structure in a local file containing height information. Each grid block is 2048 bytes in size, to keep file IO to block oriented SD cards efficient ''' # crc of whole block, taken with crc=0 self.crc = 0 # format version number self.version = TERRAIN_GRID_FORMAT_VERSION # grid spacing in meters self.spacing = GRID_SPACING # heights in meters over a 32*28 grid self.height = [] for x in range(TERRAIN_GRID_BLOCK_SIZE_X): self.height.append([0]*TERRAIN_GRID_BLOCK_SIZE_Y) # bitmap of 4x4 grids filled in from GCS (56 bits are used) self.bitmap = (1<<56)-1 lat_e7 = int(lat * 1.0e7) lon_e7 = int(lon * 1.0e7) # grids start on integer degrees. This makes storing terrain data on # the SD card a bit easier. Note that this relies on the python floor # behaviour with integer division self.lat_degrees = lat_int self.lon_degrees = lon_int # create reference position for this rounded degree position ref_lat = self.lat_degrees*10*1000*1000 ref_lon = self.lon_degrees*10*1000*1000 # find offset from reference offset = get_distance_NE_e7(ref_lat, ref_lon, lat_e7, lon_e7) offset = (round(offset[0]), round(offset[1])) # get indices in terms of grid_spacing elements idx_x = int(offset[0] / GRID_SPACING) idx_y = int(offset[1] / GRID_SPACING) # find indexes into 32*28 grids for this degree reference. Note # the use of TERRAIN_GRID_BLOCK_SPACING_{X,Y} which gives a one square # overlap between grids self.grid_idx_x = idx_x // TERRAIN_GRID_BLOCK_SPACING_X self.grid_idx_y = idx_y // TERRAIN_GRID_BLOCK_SPACING_Y # calculate lat/lon of SW corner of 32*28 grid_block (ref_lat, ref_lon) = add_offset(ref_lat, ref_lon, self.grid_idx_x * TERRAIN_GRID_BLOCK_SPACING_X * float(GRID_SPACING), self.grid_idx_y * TERRAIN_GRID_BLOCK_SPACING_Y * float(GRID_SPACING)) self.lat = ref_lat self.lon = ref_lon def fill(self, gx, gy, altitude): '''fill a square''' self.height[gx][gy] = int(altitude) def blocknum(self): '''find IO block number''' stride = east_blocks(self.lat_degrees*1e7, self.lon_degrees*1e7) return stride * self.grid_idx_x + self.grid_idx_y class DataFile(object): def __init__(self, lat, lon): if lat < 0: NS = 'S' else: NS = 'N' if lon < 0: EW = 'W' else: EW = 'E' name = "terrain/%c%02u%c%03u.DAT" % (NS, min(abs(int(lat)), 99), EW, min(abs(int(lon)), 999)) try: os.mkdir("terrain") except Exception: pass if not os.path.exists(name): self.fh = open(name, 'w+b') else: self.fh = open(name, 'r+b') def seek_offset(self, block): '''seek to right offset''' # work out how many longitude blocks there are at this latitude file_offset = block.blocknum() * IO_BLOCK_SIZE self.fh.seek(file_offset) def pack(self, block): '''pack into a block''' buf = bytes() buf += struct.pack("<QiiHHH", block.bitmap, block.lat, block.lon, block.crc, block.version, block.spacing) for gx in range(TERRAIN_GRID_BLOCK_SIZE_X): buf += struct.pack("<%uh" % TERRAIN_GRID_BLOCK_SIZE_Y, *block.height[gx]) buf += struct.pack("<HHhb", block.grid_idx_x, block.grid_idx_y, block.lon_degrees, block.lat_degrees) return buf def write(self, block): '''write a grid block''' self.seek_offset(block) block.crc = 0 buf = self.pack(block) block.crc = crc16.crc16xmodem(buf) buf = self.pack(block) self.fh.write(buf) def check_filled(self, block): '''read a grid block and check if already filled''' self.seek_offset(block) buf = self.fh.read(IO_BLOCK_SIZE) if len(buf) != IO_BLOCK_SIZE: return False (bitmap, lat, lon, crc, version, spacing) = struct.unpack("<QiiHHH", buf[:22]) if (version != TERRAIN_GRID_FORMAT_VERSION or abs(lat - block.lat)>2 or abs(lon - block.lon)>2 or spacing != GRID_SPACING or bitmap != (1<<56)-1): return False buf = buf[:16] + struct.pack("<H", 0) + buf[18:] crc2 = crc16.crc16xmodem(buf[:1821]) if crc2 != crc: return False return True def create_degree(lat, lon): '''create data file for one degree lat/lon''' lat_int = int(math.floor(lat)) lon_int = int(math.floor((lon))) tiles = {} dfile = DataFile(lat_int, lon_int) print("Creating for %d %d" % (lat_int, lon_int)) total_blocks = east_blocks(lat_int*1e7, lon_int*1e7) * TERRAIN_GRID_BLOCK_SIZE_Y for blocknum in range(total_blocks): (lat_e7, lon_e7) = pos_from_file_offset(lat_int, lon_int, blocknum * IO_BLOCK_SIZE) lat = lat_e7 * 1.0e-7 lon = lon_e7 * 1.0e-7 grid = GridBlock(lat_int, lon_int, lat, lon) if grid.blocknum() != blocknum: continue if not args.force and dfile.check_filled(grid): continue for gx in range(TERRAIN_GRID_BLOCK_SIZE_X): for gy in range(TERRAIN_GRID_BLOCK_SIZE_Y): lat_e7, lon_e7 = add_offset(lat*1.0e7, lon*1.0e7, gx*GRID_SPACING, gy*GRID_SPACING) lat2_int = int(math.floor(lat_e7*1.0e-7)) lon2_int = int(math.floor(lon_e7*1.0e-7)) tile_idx = (lat2_int, lon2_int) while not tile_idx in tiles: tile = downloader.getTile(lat2_int, lon2_int) waited = False if tile == 0: print("waiting on download of %d,%d" % (lat2_int, lon2_int))
import os class Program: socke
tColorBoTe = "255 2
55 255 255" socketColorBa = "77 87 152 255" progColorRareBoTe = "0 0 0 255" progColorRareBa = "240 220 180 255" progColorElseBoTe = "77 87 152 255" progColorElseBa = "0 0 0 255" def createFile(self): filepath = os.path.join('~/dest', "filterZZ.filter") if not os.path.exists('~/dest'): os.makedirs('~/dest') setattr(self, 'f', open(filepath, "w")) def addNewLine(self): self.f.write("\n\n")
# Generated by Django 2.2.12 on 2020-05-09 06:28 from django.db import migrations # Can't use fixtures because load_fixtures method is janky with django-tenant-schemas def load_initial_data(apps, schema_editor): Grade = apps.get_model('courses', 'Grade') # add some initial data if none has been created yet if not Grade.objects.exists(): Grade.objects.create( name="8", value=8 ) Grade.objects.create( name="9", value=9 ) Grade.objects.create( name="10", value=10 ) Grade.objects.create( name="11
", value=11 ) Grade.objects.create( name="12", value=12 )
class Migration(migrations.Migration): dependencies = [ ('courses', '0015_auto_20200508_1957'), ] operations = [ migrations.RunPython(load_initial_data), ]
"""A Python module for interacting and consuming responses from Slack.""" import logging import slack.errors as e from slack.web.internal_utils import _next_cursor_is_present class AsyncSlackResponse: """An iterable container of response data. Attributes: data (dict): The json-encoded content of the response. Along with the headers and status code information. Methods: validate: Check if the response from Slack was successful. get: Retrieves any key from the response data. next: Retrieves the next portion of results, if 'next_cursor' is present. Example: ```python import os import slack client = slack.AsyncWebClient(token=os.environ['SLACK_API_TOKEN']) response1 = await client.auth_revoke(test='true') assert not response1['revoked'] response2 = await client.auth_test() assert response2.get('ok', False) users = [] async for page in await client.users_list(limit=2): users = users + page['members'] ``` Note: Some responses return collections of information like channel and user lists. If they do it's likely that you'll only receive a portion of results. This object allows you to iterate over the response which makes subsequent API requests until your code hits 'break' or there are no more results to be found. Any attributes or methods prefixed with _underscores are intended to be "private" internal use only. They may be changed or removed at anytime. """ def __init__( self, *, client, # AsyncWebClient http_verb: str, api_url: str, req_args: dict, data: dict, headers: dict, status_code: int, ): self.http_verb = http_verb self.api_url = api_url self.req_args = req_args self.data = data self.headers = headers self.status_code = status_code self._initial_data = data self._iteration = None # for __iter__ & __next__ self._client = client self._logger = logging.getLogger(__name__) def __str__(self): """Return the Response data if object is converted to a string.""" if isinstance(self.data, bytes): raise ValueError( "As the response.data is binary data, this operation is unsupported" ) return f"{self.data}" def __contains__(self, key: str) -> bool: return self.get(key) is not None def __getitem__(self, key): """Retrieves any key from the data store. Note: This is implemented so users can reference the SlackResponse object like a dictionary. e.g. response["ok"] Returns: The value from data or None. """ if isinstance(self.data, bytes): raise ValueError( "As the response.data is binary data, this operation is unsupported" ) if self.data is None: raise ValueError( "As the response.data is empty, this operation is unsupported" ) return self.data.get(key, None) def __aiter__(self): """Enables the ability to iterate over the response. It's required async-for the iterator protocol. Note: This enables Slack cursor-based pagination. Returns: (AsyncSlackResponse) self """ self._iteration = 0 self.data = self._initial_data return self async def __anext__(self): """Retrieves the next portion of results, if 'next_cursor' is present. Note: Some responses return collections of information like channel and user lists. If they do it's likely that you'll only receive a portion of results. This method allows you to iterate over the response until your code hits 'break' or there are no more results to be found. Returns: (AsyncSlackResponse) self With the new response data now attached to this object. Raises: SlackApiError: If the request to the Slack API failed. StopAsyncIteration: If 'next_cursor' is not present or empty. """ self._iteration += 1 if self._iteration == 1: return self if _next_cursor_is_present(self.data): # skipcq: PYL-R1705 params = self.req_args.get("params", {}) if params is None: params = {} params.update({"cursor": self.data["response_metadata"]["next_cursor"]}) self.req_args.update({"params": params}) response = await self._client._request( # skipcq: PYL-W0212 http_verb=self.http_verb, api_url=self.api_url, req_args=self.req_args, ) self.data = response["data"] self.headers = response["headers"] self.status_code = response["status_code"] return self.validate() else: raise StopAsyncIteration def get(self, key, default=None): """Retrieves any key from the response data. Note: This is implemented so users can reference the SlackResponse object like a dictionary. e.g. response.get("ok", False) Returns: The value from data or the specified default. """ if isinstance(self.data, bytes): raise ValueError( "As the response.data is binary data, this operation is unsupported" ) if self.data is None: return None return self.data.get(key, default) def validate(self): """Check if the response from Slack was successful.
Returns: (AsyncSlackResponse) This method returns it's own object. e.g. 'self' Raises: SlackApiError: The request to the Slack API failed. """ if self.status_code == 200 and self.data and self.data.get("ok", False): return self msg = "The request to the Slack API failed.
" raise e.SlackApiError(message=msg, response=self)
""" Dynamic DNS updates =================== Ensure a DNS record is present or absent utilizing RFC 2136 type dynamic updates. :depends: - `dnspython <http://www.dnspython.org/>`_ .. note:: The ``dnspython`` module is required when managing DDNS using a TSIG key. If you are not using a TSIG key, DDNS is allowed by ACLs based on IP address and the ``dnspython`` module is not required. Example: .. code-block:: yaml webserver: ddns.present: - zone: example.com - ttl: 60 - data: 111.222.333.444 - nameserver: 123.234.345.456 - keyfile: /srv/salt/dnspy_tsig_key.txt """ def __virtual__(): if "ddns.update" in __salt__: return "ddns" return (False, "ddns module could not be loaded") def present(name, zone, ttl, data, rdtype="A", **kwargs): """ Ensures that the named DNS record is present with the given ttl. name The host portion of the DNS record, e.g., 'webserver'. Name and zone are concatenated when the entry is created unless name includes a trailing dot, so make sure that information is not duplicated in these two arguments. zone The zone to check/update ttl TTL for the record data Data for the DNS record. E.g., the IP address for an A record. rdtype DNS resource type. Default 'A'. ``**kwargs`` Additional arguments the ddns.update function may need (e.g. nameserver, keyfile, keyname). Note that the nsupdate key file can’t be reused by this function, the keyfile and other arguments must follow the `dnspython <http://www.dnspython.org/>`_ spec. """ ret = {"name": name, "changes": {}, "result": False, "comment": ""} if __opts__["test"]: ret["result"] = None ret["c
omment"] = '{} record "{}" will be updated'.format(rdtype, name) re
turn ret status = __salt__["ddns.update"](zone, name, ttl, rdtype, data, **kwargs) if status is None: ret["result"] = True ret["comment"] = '{} record "{}" already present with ttl of {}'.format( rdtype, name, ttl ) elif status: ret["result"] = True ret["comment"] = 'Updated {} record for "{}"'.format(rdtype, name) ret["changes"] = { "name": name, "zone": zone, "ttl": ttl, "rdtype": rdtype, "data": data, } else: ret["result"] = False ret["comment"] = 'Failed to create or update {} record for "{}"'.format( rdtype, name ) return ret def absent(name, zone, data=None, rdtype=None, **kwargs): """ Ensures that the named DNS record is absent. name The host portion of the DNS record, e.g., 'webserver'. Name and zone are concatenated when the entry is created unless name includes a trailing dot, so make sure that information is not duplicated in these two arguments. zone The zone to check data Data for the DNS record. E.g., the IP address for an A record. If omitted, all records matching name (and rdtype, if provided) will be purged. rdtype DNS resource type. If omitted, all types will be purged. ``**kwargs`` Additional arguments the ddns.update function may need (e.g. nameserver, keyfile, keyname). Note that the nsupdate key file can’t be reused by this function, the keyfile and other arguments must follow the `dnspython <http://www.dnspython.org/>`_ spec. """ ret = {"name": name, "changes": {}, "result": False, "comment": ""} if __opts__["test"]: ret["result"] = None ret["comment"] = '{} record "{}" will be deleted'.format(rdtype, name) return ret status = __salt__["ddns.delete"](zone, name, rdtype, data, **kwargs) if status is None: ret["result"] = True ret["comment"] = "No matching DNS record(s) present" elif status: ret["result"] = True ret["comment"] = "Deleted DNS record(s)" ret["changes"] = {"Deleted": {"name": name, "zone": zone}} else: ret["result"] = False ret["comment"] = "Failed to delete DNS record(s)" return ret
"""Launch the interactive command-line interface. Returns: The OnRunStartResponse specified by the user using the "run" command. """ self._register_this_run_info(self._run_cli) response = self._run_cli.run_ui( init_command=self._init_command, title=self._title, title_color=self._title_color) return response def _run_info_handler(self, args, screen_info=None): output = debugger_cli_common.RichTextLines([]) if self._run_call_count == 1: output.extend(cli_shared.get_tfdbg_logo()) output.extend(self._run_info) if (not self._is_run_start and debugger_cli_common.MAIN_MENU_KEY in output.annotations): menu = output.annotations[debugger_cli_common.MAIN_MENU_KEY] if "list_tensors" not in menu.captions(): menu.insert( 0, debugger_cli_common.MenuItem("list_tensors", "list_tensors")) return output def _print_feed_handler(self, args, screen_info=None): np_printoptions = cli_shared.numpy_printoptions_from_screen_info( screen_info) if not self._feed_dict: return cli_shared.error( "The feed_dict of the current run is None or empty.") parsed = self._argparsers["print_feed"].parse_args(args) tensor_name, tensor_slicing = ( command_parser.parse_tensor_name_with_slicing(parsed.tensor_name)) feed_key = None feed_value = None for key in self._feed_dict: key_name = common.get_graph_element_name(key) if key_name == tensor_name: feed_key = key_name feed_value = self._feed_dict[key] break if feed_key is None: return cli_shared.error( "The feed_dict of the current run does not contain the key %s" % tensor_name) else: return cli_shared.format_tensor( feed_value, feed_key + " (feed)", np_printoptions, print_all=parsed.print_all, tensor_slicing=tensor_slicing, highlight_options=cli_shared.parse_ranges_highlight(parsed.ranges), include_numeric_summary=parsed.numeric_summary) def _run_handler(self, args, screen_info=None): """Command handler for "run" command during on-run-start.""" del screen_info # Currently unused. parsed = self._argparsers["run"].parse_args(args) parsed.node_name_filter = parsed.node_name_filter or None parsed.op_type_filter = parsed.op_type_filter or None parsed.tensor_dtype_filter = parsed.tensor_dtype_filter or None if parsed.profile: raise debugger_cli_common.CommandLineExit( exit_token=framework.OnRunStartResponse( framework.OnRunStartAction.PROFILE_RUN, [])) self._skip_debug = parsed.no_debug self._run_through_times = parsed.times if parsed.times > 1 or parsed.no_debug: # If requested -t times > 1, the very next run will be a non-debug run. action = framework.OnRunStartAction.NON_DEBUG_RUN debug_urls = [] else: action = framework.OnRunStartAction.DEBUG_RUN debug_urls = self._get_run_debug_urls() run_start_response = framework.OnRunStartResponse( action, debug_urls, node_name_regex_whitelist=parsed.node_name_filter, op_type_regex_whitelist=parsed.op_type_filter, tensor_dtype_regex_whitelist=parsed.tensor_dtype_filter) if parsed.till_filter_pass: # For the run-till-filter-pass (run -f) mode, use the DEBUG_RUN # option to access the intermediate tensors, and set the corresponding # state flag of the class itself to True. if parsed.till_filter_pass in self._tensor_filters: action = framework.OnRunStartAction.DEBUG_RUN self._active_tensor_filter = parsed.till_filter_pass self._active_tensor_filter_run_start_response = run_start_response else: # Handle invalid filter name. return debugger_cli_common.RichTextLines( ["ERROR:
tensor filter \"%s\" does not exist." % parsed
.till_filter_pass]) # Raise CommandLineExit exception to cause the CLI to exit. raise debugger_cli_common.CommandLineExit(exit_token=run_start_response) def _register_this_run_info(self, curses_cli): curses_cli.register_command_handler( "run", self._run_handler, self._argparsers["run"].format_help(), prefix_aliases=["r"]) curses_cli.register_command_handler( "invoke_stepper", self._on_run_start_step_handler, self._argparsers["invoke_stepper"].format_help(), prefix_aliases=["s"]) curses_cli.register_command_handler( "run_info", self._run_info_handler, self._argparsers["run_info"].format_help(), prefix_aliases=["ri"]) curses_cli.register_command_handler( "print_feed", self._print_feed_handler, self._argparsers["print_feed"].format_help(), prefix_aliases=["pf"]) if self._tensor_filters: # Register tab completion for the filter names. curses_cli.register_tab_comp_context(["run", "r"], list(self._tensor_filters.keys())) if self._feed_dict: # Register tab completion for feed_dict keys. feed_keys = [common.get_graph_element_name(key) for key in self._feed_dict.keys()] curses_cli.register_tab_comp_context(["print_feed", "pf"], feed_keys) def _on_run_start_step_handler(self, args, screen_info=None): """Command handler for "invoke_stepper" command during on-run-start.""" _ = screen_info # Currently unused. # No parsing is currently necessary for invoke_stepper. This may change # in the future when the command has arguments. # Raise CommandLineExit exception to cause the CLI to exit. raise debugger_cli_common.CommandLineExit( exit_token=framework.OnRunStartResponse( framework.OnRunStartAction.INVOKE_STEPPER, [])) def _get_run_debug_urls(self): """Get the debug_urls value for the current run() call. Returns: debug_urls: (list of str) Debug URLs for the current run() call. Currently, the list consists of only one URL that is a file:// URL. """ return ["file://" + self._dump_root] def _update_run_calls_state(self, run_call_count, fetches, feed_dict, is_callable_runner=False): """Update the internal state with regard to run() call history. Args: run_call_count: (int) Number of run() calls that have occurred. fetches: a node/tensor or a list of node/tensor that are the fetches of the run() call. This is the same as the fetches argument to the run() call. feed_dict: None of a dict. This is the feed_dict argument to the run() call. is_callable_runner: (bool) whether a runner returned by Session.make_callable is being run. """ self._run_call_count = run_call_count self._feed_dict = feed_dict self._run_description = cli_shared.get_run_short_description( run_call_count, fetches, feed_dict, is_callable_runner=is_callable_runner) self._run_through_times -= 1 self._run_info = cli_shared.get_run_start_intro( run_call_count, fetches, feed_dict, self._tensor_filters, is_callable_runner=is_callable_runner) def invoke_node_stepper(self, node_stepper, restore_variable_values_on_exit=True): """Overrides method in base class to implement interactive node stepper. Args: node_stepper: (`stepper.NodeStepper`) The underlying NodeStepper API object. restore_variable_values_on_exit: (`bool`) Whether any variables whose values have been altered during this node-stepper invocation should be restored to their old values when this invocation ends. Returns: The same return values as the `Session.run()` call on the same fetches as the NodeStepper. """ stepper = stepper_cli.NodeStepperC
from django.test import TestCase from store.forms import ReviewForm from store.models import Review from .factories import * class ReviewFormTest(TestCase): def test_form_validation_for_blank_items(self): p1 = ProductFactory.create() form = ReviewForm( data={'name':'', 'text': '', 'product':p1.id}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['text'],["Please fill in the review"]) self.assertEqual(form.errors['rating'],["Please leave a rating"]) def test_form_validation_for_invalid_review(self): p1 = ProductFactory.create() form = ReviewForm( data={'name':'', 'text': '', 'rating': 0, 'product':p1.id}) self.assertFalse(form.is_v
alid()) self.assertEqual(form.errors['text'],["Please fill in the
review"]) self.assertEqual(form.errors['rating'],["Please leave a valid rating"]) def test_form_validation_for_required_name_field(self): p1 = ProductFactory.create() form = ReviewForm( data={'name':'', 'text': 'Hello', 'rating': 2, 'product':p1.id}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['name'],['Please fill in your name']) def test_form_save_handles_saving_product_reviews(self): prod = ProductFactory.create() form = ReviewForm( data={'name':'Kevin', 'text': 'Review', 'rating': 3, 'product':prod.id}) new_review = form.save() self.assertEqual(new_review, Review.objects.first()) self.assertEqual(new_review.name, 'Kevin') self.assertEqual(new_review.product, prod)
{ "name" : "Add sales team to website
leads (OBSOLETE)",
"version" : "0.1", "author" : "IT-Projects LLC, Ivan Yelizariev", 'license': 'GPL-3', "category" : "Website", "website" : "https://yelizariev.github.io", "depends" : ["website_crm"], #"init_xml" : [], #"update_xml" : [], #"active": True, "installable": True }
#-*- coding: utf-8 -*- # Author : Jeonghoonkang, github.com/jeonghoonkang import platform import sys import os import time import traceb
ack import requests import RPi.GPIO as GPIO from socket import gethostname hostname = gethostname() SERVER_ADDR = '211.184.76.80' GPIO.setwarnings(False) GPIO.cleanup() GPIO.setmode(GPIO.BCM) GPIO.setup(19,
GPIO.OUT) # for LED indicating GPIO.setup(26, GPIO.OUT) # for LED indicating def query_last_data_point(bridge_id): url = 'http://%s/api/raw_bridge_last/?bridge_id=%d' % (SERVER_ADDR, bridge_id) try: ret = requests.get(url, timeout=10) if ret.ok: ctx = ret.json() if ctx['code'] == 0: return ctx['result']['time'], ctx['result']['value'] except Exception: #print Exception pass return None bridge_id = int(hostname[5:10]) GPIO.output(26, True) # server connection is OK, showing through LED while True: try: ret = query_last_data_point(bridge_id) except: pass if ret is not None: t, v = ret if t > time.time() - 30: dt = time.time() - t GPIO.output(19, True) GPIO.output(26, False) else: GPIO.output(19, True) GPIO.output(26, True) else: GPIO.output(19, False) GPIO.output(26, True) time.sleep(5.0)
import time import os import posixpath import datetime import math import re import logging from django import template from django.utils.encoding import smart_unicode from django.utils.safestring import mark_safe from forum.models import Question, Answer, QuestionRevision, AnswerRevision, NodeRevision from django.utils.translation import ugettext as _ from django.utils.translation import ungettext from django.utils import simplejson from forum import settings from django.template.defaulttags import url as default_url from forum import skins from forum.utils import html from extra_filters import decorated_int from django.core.urlresolvers import reverse register = template.Library() GRAVATAR_TEMPLATE = ('<img class="gravatar" width="%(size)s" height="%(size)s" ' 'src="http://www.gravatar.com/avatar/%(gravatar_hash)s' '?s=%(size)s&amp;d=%(default)s&amp;r=%(rating)s" ' 'alt="%(username)s\'s gravatar image" />') @register.simple_tag def gravatar(user, size): try: gravatar = user['gravatar'] username = user['username'] except (TypeError, AttributeError, KeyError): gravatar = user.gravatar username = user.username return mark_safe(GRAVATAR_TEMPLATE % { 'size': size, 'gravatar_hash': gravatar, 'default': settings.GRAVATAR_DEFAULT_IMAGE, 'rating': settings.GRAVATAR_ALLOWED_RATING, 'username': template.defaultfilters.urlencode(username), }) @register.simple_tag def get_score_badge(user): if user.is_suspended(): return _("(suspended)") repstr = decorated_int(user.reputation, "") BADGE_TEMPLATE = '<span class="score" title="%(reputation)s %(reputationword)s">%(repstr)s</span>' if user.gold > 0 : BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(gold)s %(badgesword)s">' '<span class="badge1">&#9679;</span>' '<span class="badgecount">%(gold)s</span>' '</span>') if user.silver > 0: BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(silver)s %(badgesword)s">' '<span class="silver">&#9679;</span>' '<span class="badgecount">%(silver)s</span>' '</span>') if user.bronze > 0: BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(bronze)s %(badgesword)s">' '<span class="bronze">&#9679;</span>' '<span class="badgecount">%(bronze)s</span>' '</span>') BADGE_TEMPLATE = smart_unicode(BADGE_TEMPLATE, encoding='utf-8', strings_only=False, errors='strict') return mark_safe(BADGE_TEMPLATE % { 'reputation' : user.reputation, 'repstr': repstr, 'gold' : user.gold, 'silver' : user.silver, 'bronze' : user.bronze, 'badgesword' : _('badges'), 'reputationword' : _('reputation points'), }) @register.simple_tag def get_age(birthday): current_time = datetime.datetime(*time.localtime()[0:6]) year = birthday.year month = birthday.month day = birthday.day diff = current_time - datetime.datetime(year, month, day, 0, 0, 0) return diff.days / 365 @register.simple_tag def diff_date(date, limen=2): if not date: return _('unknown') now = datetime.datetime.now() diff = now - date days = diff.days hours = int(diff.seconds/3600) minutes = int(diff.seconds/60) if days > 2: if date.year == now.year: return date.strftime(_("%b %d at %H:%M").encode()) else: return date.strftime(_("%b %d '%y at %H:%M").encode()) elif days == 2: return _('2 days ago') elif days == 1: return _('yesterday') elif minutes >= 60: return ungettext('%(hr)d ' + _("hour ago"), '%(hr)d ' + _("hours ago"), hours) % {'hr':hours} elif diff.seconds >= 60: return ungettext('%(min)d ' + _("min ago"), '%(min)d ' + _("mins ago"), minutes) % {'min':minutes} else: return ungettext('%(sec)d ' + _("sec ago"), '%(sec)d ' + _("secs ago"), diff.seconds) % {'sec':diff.seconds} @register.simple_tag def media(url): url = skins.find_media_source(url) if url: # Create the URL prefix. url_prefix = settings.FORCE_SCRIPT_NAME + '/m/' # Make sure any duplicate forward slashes are replaced with a single # forward slash. url_prefix = re.sub("/+", "/", url_prefix) url = url_prefix + url return url class ItemSeparatorNode(template.Node): def __init__(self, separator): sep = separator.strip() if sep[0] == sep[-1] and sep[0] in ('\'', '"'): sep = sep[1:-1] else: raise template.TemplateSyntaxError('separator in joinitems tag must be quoted') self.content = sep def render(self, context): return self.content class BlockMediaUrlNode(template.Node): def __init__(self, nodelist): self.items = nodelist def render(self, context): prefix = settings.APP_URL + 'm/' url = '' if self.items: url += '/' for item in self.items: url += item.render(context) url = skins.find_media_source(url) url = prefix + url out = url return out.replace(' ', '') @register.tag(name='blockmedia') def blockmedia(parser, token): try: tagname = token.split_contents() except ValueError: raise template.TemplateSyntaxError("blockmedia tag does not use arguments") nodelist = [] while True: nodelist.append(parser.parse(('endblockmedia'))) next = parser.next_token() if next.contents == 'endblockmedia': break return BlockMediaUrlNode(nodelist) @register.simple_tag def fullmedia(url): domain = settings.APP_BASE_URL #protocol = getattr(settings, "PROTOCOL", "http") path = media(url) return "%s%s" % (domain, path) class SimpleVarNode(template.Node): def __init__(self, name, value): self.name = name self.value = template.Variable(value) def render(self, context): context[self.name] = self.value.resolve(context) return '' class BlockVarNode(template.Node): def __init__(self, name, block): self.name = name self.block = block def render(self, context): source = self.block.render(context) context[self.name] = source.strip() return '' @register.tag(name='var') def do_var(parser, token): tokens = token.split_contents()[1:] if not len(tokens) or not re.match('^\w+$', tokens[0]): raise template.TemplateSyntaxError("Expected variable name") if len(tokens) == 1: nodelist = parser.parse(('endvar',)) parser.delete_first_token() return BlockVarNode(tokens[0], nodelist) elif len(tokens) == 3: return SimpleVarNode(tokens[0], tokens[2]) raise template.TemplateSyntaxError("Invalid number of arguments") class DeclareNode(template.Node): dec_re = re.compile('^\s*(\w+)\s*(:?=)\s*(.*)$') def __init__(self, block): self.block = block def render(self, context): source = self.block.rend
er(context) for line in source.splitlines(): m = self.dec_re.search(line) if m: clist = list(context) clist.reverse() d = {} d['_'] = _ d['os'] = os d['html'] = html d['reverse'] = reverse for c in clist: d.update(c) try: context[m.group(1).strip()] = eval(m.group(3).strip(), d)
except Exception, e: logging.error("Error in declare tag, when evaluating: %s" % m.group(3).strip()) raise return '' @register.tag(name='declare') def do_declare(parser, token): nodelist = parser.parse(('enddeclare',)) parser.delete_first_token() return DeclareNode(nodelist)
# Copright (C) 2015 Eric Skoglund # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied
warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not,
see http://www.gnu.org/licenses/gpl-2.0.html import requests import sys class NotSupported(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class PasteSite(object): def __init__(self, url): self.url = url self.paste_url = None self.data = None @staticmethod def siteFactory(site_name): if site_name == 'slexy.org': return Slexy() elif site_name == 'pastebin.mozilla.org': return Mozilla() else: raise NotSupported("This site is not supported") def parse(self, args): """ Internal method used by the PasteSite class. Returns a dictionary of the parsed input arguments. Parses the arguments given at the command line. Many pastebin like sites use different arguments for the paste so this method should be implemented for each subclass of PasteSite. See the slexy class for an example of how to implement this method for subclasses. """ self.data = args def paste(self): """Posts the data to the paste site. This method tries to post the data to the paste site. If the resulting request does not have a ok status the program exits else we return the resulting paste url. The method assumes that the data is in a dictionary. """ if self.data == None: print('You can only paste after a parse') sys.exit(-1) res = requests.post(self.url, self.data) if not res.ok: print('Bad response {0} {1}'.format(res.reason, res.status_code)) sys.exit(-1) self.paste_url = res.url class Slexy(PasteSite): def __init__(self): super(Slexy, self).__init__('http://slexy.org/submit') def parse(self, args): form_data = {} arg_translation = {'text' : 'raw_paste', 'language' : 'language', 'expiration' : 'expire', 'comment' : 'comment', 'description' : 'descr', 'visibility' : 'permissions', 'linum' : 'linenumbers', 'author' : 'author'} for k,v in args.items(): if arg_translation.get(k): form_data[arg_translation[k]] = v form_data['submit'] = 'Submit Paste' self.data = form_data class Mozilla(PasteSite): def __init__(self): super(Mozilla, self).__init__('https://pastebin.mozilla.org') def parse(self, args): form_data = {} arg_translation = {'text' : 'code2', 'expiration' : 'expiry', 'syntax_highlight' : 'format', 'author' : 'poster'} for k,v in args.items(): if arg_translation.get(k): form_data[arg_translation[k]] = v form_data['paste'] = 'Send' form_data['parent_pid'] = '' self.data = form_data
########################################################### # # Copyright (c) 2005, Southpaw Technology # All Rights Reserved # # PROPRIETARY INFORMATION. This software is proprietary to # Southpaw Technology, and is not to be reproduced, transmitted, # or disclosed in any way without written permission. # # # import os,unittest from pyasm.security import Batch from pyasm.command import Command from pyasm.prod.biz import Asset from pyams.prod.maya import * from maya_checkin import * class MayaCheckinTest(unittest.TestCase): def setUp(my): batch = Batch() def test_all(my): # create a scene that will be checked in asset_code = "prp101" si
d = "12345" # create an asset mel('sphere -n sphere1') mel('circle -n circle1') mel('group -n |%s |circle1 |sphere1' % asset_code ) # convert node into a maya asset node =
MayaNode("|%s" % asset_code ) asset_node = MayaAssetNode.add_sid( node, sid ) # checkin the asset checkin = MayaAssetNodeCheckin(asset_node) Command.execute_cmd(checkin) # create a file from this node asset_node.export() if __name__ == '__main__': unittest.main()
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Methods to allow pandas.DataFrame.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib.learn.python.learn.dataframe.queues import feeding_functions try: # pylint: disable=g-import-not-at-top import pandas as pd HAS_PANDAS = True except ImportError: HAS_PANDAS = False PANDAS_DTYPES = { 'int8': 'int', 'int16': 'int', 'int32': 'int', 'int64': 'int', 'uint8': 'int', 'uint16': 'int', 'uint32': 'int', 'uint64': 'int', 'float16': 'float', 'float32': 'float', 'float64': 'float', 'bool': 'i' } def extract_pandas_data(data): """Extract data from pandas.DataFrame for predictors. Given a DataFrame, will extract the values and cast them to float. The DataFrame is expected to contain values of type int, float or bool. Args: data: `pandas.DataFrame` containing the data to be extracted. Returns: A numpy `ndarray` of the DataFrame's values as floats. Raises: ValueError: if data contains types other than int, float or bool. """ if not isinstance(data, pd.DataFrame): return data bad_data = [column for column in data if data[column].dtype.name not in PANDAS_DTYPES] if not bad_data: return data.values.astype('float') else: error_report = [("'" + str(column) + "' type='" + data[column].dtype.name + "'") for column in bad_data] raise ValueError('Data types for extracting pandas data must be int, ' 'float, or bool. Found: ' + ', '.join(error_report)) def extract_pandas_matrix(data): """Extracts numpy matrix from pandas DataFrame. Args: data: `pandas.DataFrame` containing the data to be
extracted. Returns: A numpy `ndarray` of the DataFrame's values. """ if not isinstance(data, pd.DataFrame): return data return data.as_matrix() def extract_pandas_labels(labels): """Extract data from pandas.DataFrame for labels. Args:
labels: `pandas.DataFrame` or `pandas.Series` containing one column of labels to be extracted. Returns: A numpy `ndarray` of labels from the DataFrame. Raises: ValueError: if more than one column is found or type is not int, float or bool. """ if isinstance(labels, pd.DataFrame): # pandas.Series also belongs to DataFrame if len(labels.columns) > 1: raise ValueError('Only one column for labels is allowed.') bad_data = [column for column in labels if labels[column].dtype.name not in PANDAS_DTYPES] if not bad_data: return labels.values else: error_report = ["'" + str(column) + "' type=" + str(labels[column].dtype.name) for column in bad_data] raise ValueError('Data types for extracting labels must be int, ' 'float, or bool. Found: ' + ', '.join(error_report)) else: return labels def pandas_input_fn(x, y=None, batch_size=128, num_epochs=None, shuffle=True, queue_capacity=1000, num_threads=1, target_column='target', index_column='index'): """Returns input function that would feed pandas DataFrame into the model. Note: If y's index doesn't match x's index exception will be raised. Args: x: pandas `DataFrame` object. y: pandas `Series` object. batch_size: int, size of batches to return. num_epochs: int, number of epochs to iterate over data. If `None` will run indefinetly. shuffle: int, if shuffle the queue. Please make sure you don't shuffle at prediction time. queue_capacity: int, size of queue to accumulate. num_threads: int, number of threads used for reading and enqueueing. target_column: str, used to pack `y` into `x` DataFrame under this column. index_column: str, name of the feature return with index. Returns: Function, that has signature of ()->(dict of `features`, `target`) Raises: ValueError: if `target_column` column is already in `x` DataFrame. """ def input_fn(): """Pandas input function.""" if y is not None: if target_column in x: raise ValueError('Found already column \'%s\' in x, please change ' 'target_column to something else. Current columns ' 'in x: %s', target_column, x.columns) if not np.array_equal(x.index, y.index): raise ValueError('Index for x and y are mismatch, this will lead ' 'to missing values. Please make sure they match or ' 'use .reset_index() method.\n' 'Index for x: %s\n' 'Index for y: %s\n', x.index, y.index) x[target_column] = y queue = feeding_functions.enqueue_data( x, queue_capacity, shuffle=shuffle, num_threads=num_threads, enqueue_size=batch_size, num_epochs=num_epochs) if num_epochs is None: features = queue.dequeue_many(batch_size) else: features = queue.dequeue_up_to(batch_size) features = dict(zip([index_column] + list(x.columns), features)) if y is not None: target = features.pop(target_column) return features, target return features return input_fn
from euler_functions import is_pandigital_set, number_digits for x in range(9123, 987
6): # much smaller range: http://www.mathblog.dk/project-euler-38-pandigital-multiplying-fixed-number/ products = [] n = 1 num_digits_in_products = 0 while num_digits_in_products < 9: products.append(x * n) n += 1 num_digits_in_products = 0 for p in products: num_digits_in_products += number_digits(p) if is_pand
igital_set(*products): print products break
iscovery_timeout(), _patch_discovery_interval(): await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.SETUP_RETRY with patch(f"{MODULE}.AsyncBulb", return_value=_mocked_bulb()), _patch_discovery( no_device=True ), _patch_discovery_timeout(), _patch_discovery_interval(): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=2)) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.LOADED async def test_async_listen_error_late_discovery(hass, caplog): """Test the async listen error.""" config_entry = MockConfigEntry(domain=DOMAIN, data=CONFIG_ENTRY_DATA) config_entry.add_to_hass(hass) mocked_bulb = _mocked_bulb(cannot_connect=True) with _patch_discovery(), patch(f"{MODULE}.AsyncBulb", return_value=mocked_bulb): await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.SETUP_RETRY await hass.async_block_till_done() assert "Waiting for 0x15243f to be discovered" in caplog.text with _patch_discovery(), patch(f"{MODULE}.AsyncBulb", return_value=_mocked_bulb()): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=5)) await hass.async_block_till_done() async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=10)) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.LOADED assert config_entry.data[CONF_DETECTED_MODEL] == MODEL async def test_fail_to_fetch_initial_state(hass, caplog): """Test failing to fetch initial state results in a retry.""" config_entry = MockConfigEntry( domain=DOMAIN, data={CONF_HOST: IP_ADDRESS, **CONFIG_ENTRY_DATA} ) config_entry.add_to_hass(hass) mocked_bulb = _mocked_bulb() del mocked_bulb.last_properties["power"] del mocked_bulb.last_properties["main_power"] with _patch_discovery(), patch(f"{MODULE}.AsyncBulb", return_value=mocked_bulb): await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.SETUP_RETRY await hass.async_block_till_done() assert "Could not fetch initial state; try power cycling the device" in caplog.text with _patch_discovery(), patch(f"{MODULE}.AsyncBulb", return_value=_mocked_bulb()): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=5)) await hass.async_block_till_done() async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=10)) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.LOADED async def test_unload_before_discovery(hass, caplog): """Test unloading before discovery.""" config_entry = MockConfigEntry(domain=DOMAIN, data=CONFIG_ENTRY_DATA) config_entry.add_to_hass(hass) mocked_bulb = _mocked_bulb(cannot_connect=True) with _patch_discovery(no_device=True), patch( f"{MODULE}.AsyncBulb", return_value=mocked_bulb ): await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.SETUP_RETRY await hass.config_entries.async_unload(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.NOT_LOADED async def test_async_listen_error_has_host_with_id(hass: HomeAssistant): """Test the async listen error.""" config_entry = MockConfigEntry( domain=DOMAIN, data={CONF_ID: ID, CONF_HOST: "127.0.0.1"} ) config_entry.add_to_hass(hass) with _patch_discovery( no_device=True ), _patch_discovery_timeout(), _patch_discovery_interval(), patch( f"{MODULE}.AsyncBulb", return_value=_mocked_bulb(cannot_connect=True) ): await hass.config_entries.async_setup(config_entry.entry_id) assert config_entry.state is ConfigEntryState.SETUP_RETRY async def test_async_listen_error_has_host_without_id(hass: HomeAssistant): """Test the async listen error but no id.""" config_entry = MockConfigEntry(domain=DOMAIN, data={CONF_HOST: "127.0.0.1"}) config_entry.add_to_hass(hass) with _patch_discovery( no_device=True ), _patch_discovery_timeout(), _patch_discovery_interval(), patch( f"{MODULE}.AsyncBulb", return_value=_mocked_bulb(cannot_connect=True) ): await hass.config_entries.async_setup(config_entry.entry_id) assert config_entry.state is ConfigEntryState.SETUP_RETRY async def test_async_setup_with_missing_id(hass: HomeAssistant): """Test that setting adds the missing CONF_ID from unique_id.""" config_entry = MockConfigEntry( domain=DOMAIN, unique_id=ID, data={CONF_HOST: "127.0.0.1"}, options={CONF_NAME: "Test name"}, ) config_entry.add_to_hass(hass) with _patch_discovery(), _patch_discovery_timeout(), _patch_discovery_interval(), patch( f"{MODULE}.AsyncBulb", return_value=_mocked_bulb(cannot_connect=True) ): await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.SETUP_RETRY assert config_entry.data[CONF_ID] == ID with _patch_discovery(), _patch_discovery_timeout(), _patch_discovery_interval(), patch( f"{MODULE}.AsyncBulb", return_value=_mocked_bulb() ): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=2)) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.LOADED async def test_async_setup_with_missing_unique_id(hass: HomeAssistant): """Test that setting adds the missing unique_id from CONF_ID.""" config_entry = MockConfigEntry( domain=DOMAIN, data={CONF_HOST: "127.0.0.1", CONF_ID: ID}, options={CONF_NAME: "Test name"}, ) config_entry.add_to_hass(hass) with _patch_discovery(), _patch_discovery_timeout(), _patch_discovery_interval(), patch( f"{MODULE}.AsyncBulb", return_value=_mocked_bulb(cannot_connect=True) ): await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.SETUP_RETRY assert config_entry.unique_id == ID with _patch_discovery(), _patch_discovery_timeout(), _patch_discovery_interval(), patch( f"{MODULE}.AsyncBulb", return_value=_mocked_bulb() ): async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=2)) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.LOADED async def test_connection_dropped_resyncs_properties(hass: HomeAssistant): """Test handling a connection drop results in a property resync.""" config_entry = MockConfigEntry( domain=DOMAIN, unique_id=ID, data={CONF_HOST: "127.0.0.1"}, options={CONF_NAME: "Test name"}, ) config_entry.add_to_hass(hass) mocked_bulb = _mocked_bulb() with _patch_discovery(), _patch_discovery_timeout(), _patch_discovery_interval(), patch( f"{M
ODULE}.AsyncBulb", return_value=mocked_bulb ): await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert len(mocked_bulb.async_get_properties.mock_calls) == 1 mocked_bulb._async_callback({KEY_CONNECT
ED: False}) await hass.async_block_till_done() assert hass.states.get("light.test_name").state == STATE_UNAVAILABLE assert len(mocked_bulb.async_get_properties.mock_calls) == 1 mocked_bulb._async_callback({KEY_CONNECTED: True}) async_fire_time_changed( hass, dt_util.utcnow() + timedelta(seconds=STATE_CHANGE_TIME) ) await hass.async_block_till_done() assert hass.states.get("light.test_name").state == STATE_ON ass
numerate(self.important_ops):
op_types[idx] = self.type_dict[node.op] # output shape op_name = node.name for i, output_prop in enumerate(self.node_properties[op_name]): if output_prop.shape.__str__() == "<unknown>":
continue shape = output_prop.shape for j, dim in enumerate(shape.dim): if dim.size >= 0: if i * self.hparams.max_output_size + j >= output_embed_dim: break op_output_shapes[idx, i * self.hparams.max_output_size + j] = dim.size # adj for padding op_adj = np.full( [self.num_ops, self.hparams.adj_embed_dim], 0, dtype=np.float32) for idx in adj_dict: neighbors = adj_dict[int(idx)] min_dim = min(self.hparams.adj_embed_dim, len(neighbors)) padding_size = self.hparams.adj_embed_dim - min_dim neighbors = neighbors[:min_dim] + [0] * padding_size op_adj[int(idx)] = neighbors # op_embedding starts here op_embeddings = np.zeros( [ self.num_ops, 1 + self.hparams.max_num_outputs * self.hparams.max_output_size + self.hparams.adj_embed_dim ], dtype=np.float32) for idx, op_name in enumerate(topo_order): op_embeddings[idx] = np.concatenate( (np.array([op_types[idx]]), op_output_shapes[idx], op_adj[int(idx)])) self.op_embeddings = constant_op.constant( op_embeddings, dtype=dtypes.float32) if verbose: print("num_ops = {}".format(self.num_ops)) print("num_types = {}".format(len(self.type_dict))) def get_groupings(self, *args, **kwargs): num_children = self.hparams.num_children with variable_scope.variable_scope("controller_{}".format(self.ctrl_id)): grouping_actions_cache = variable_scope.get_local_variable( "grouping_actions_cache", initializer=init_ops.zeros_initializer, dtype=dtypes.int32, shape=[num_children, self.num_ops], trainable=False) input_layer = self.op_embeddings input_layer = array_ops.expand_dims(input_layer, 0) feed_ff_input_layer = array_ops.tile(input_layer, [num_children, 1, 1]) grouping_actions, grouping_log_probs = {}, {} grouping_actions["sample"], grouping_log_probs[ "sample"] = self.make_grouping_predictions(feed_ff_input_layer) grouping_actions["sample"] = state_ops.assign(grouping_actions_cache, grouping_actions["sample"]) self.grouping_actions_cache = grouping_actions_cache return grouping_actions, grouping_log_probs def make_grouping_predictions(self, input_layer, reuse=None): """model that predicts grouping (grouping_actions). Args: input_layer: group_input_layer reuse: reuse Returns: grouping_actions: actions grouping_log_probs: log probabilities corresponding to actions """ with variable_scope.variable_scope(self.hparams.name, reuse=True): # input_layer: tensor of size [1, num_ops, hidden_size] w_grouping_ff = variable_scope.get_variable("w_grouping_ff") w_grouping_softmax = variable_scope.get_variable("w_grouping_softmax") batch_size = array_ops.shape(input_layer)[0] embedding_dim = array_ops.shape(input_layer)[2] reshaped = array_ops.reshape(input_layer, [batch_size * self.num_ops, embedding_dim]) ff_output = math_ops.matmul(reshaped, w_grouping_ff) logits = math_ops.matmul(ff_output, w_grouping_softmax) if self.hparams.logits_std_noise > 0: num_in_logits = math_ops.cast( array_ops.size(logits), dtype=dtypes.float32) avg_norm = math_ops.divide( linalg_ops.norm(logits), math_ops.sqrt(num_in_logits)) logits_noise = random_ops.random_normal( array_ops.shape(logits), stddev=self.hparams.logits_std_noise * avg_norm) logits = control_flow_ops.cond( self.global_step > self.hparams.stop_noise_step, lambda: logits, lambda: logits + logits_noise) logits = array_ops.reshape(logits, [batch_size * self.num_ops, self.num_groups]) actions = random_ops.multinomial(logits, 1, seed=self.hparams.seed) actions = math_ops.to_int32(actions) actions = array_ops.reshape(actions, [batch_size, self.num_ops]) action_label = array_ops.reshape(actions, [-1]) log_probs = nn_ops.sparse_softmax_cross_entropy_with_logits( logits=logits, labels=action_label) log_probs = array_ops.reshape(log_probs, [batch_size, -1]) log_probs = math_ops.reduce_sum(log_probs, 1) grouping_actions = actions grouping_log_probs = log_probs return grouping_actions, grouping_log_probs def create_group_embeddings(self, grouping_actions, verbose=False): """Approximating the blocks of a TF graph from a graph_def. Args: grouping_actions: grouping predictions. verbose: print stuffs. Returns: groups: list of groups. """ groups = [ self._create_group_embeddings(grouping_actions, i, verbose) for i in range(self.hparams.num_children) ] return np.stack(groups, axis=0) def _create_group_embeddings(self, grouping_actions, child_id, verbose=False): """Approximating the blocks of a TF graph from a graph_def for each child. Args: grouping_actions: grouping predictions. child_id: child_id for the group. verbose: print stuffs. Returns: groups: group embedding for the child_id. """ if verbose: print("Processing input_graph") # TODO(azalia): Build inter-adjacencies dag matrix. # record dag_matrix dag_matrix = np.zeros([self.num_groups, self.num_groups], dtype=np.float32) for op in self.important_ops: topo_op_index = self.name_to_topo_order_index[op.name] group_index = grouping_actions[child_id][topo_op_index] for output_op in self.get_node_fanout(op): if output_op.name not in self.important_op_names: continue output_group_index = ( grouping_actions[child_id][self.name_to_topo_order_index[ output_op.name]]) dag_matrix[group_index, output_group_index] += 1.0 num_connections = np.sum(dag_matrix) num_intra_group_connections = dag_matrix.trace() num_inter_group_connections = num_connections - num_intra_group_connections if verbose: print("grouping evaluation metric") print(("num_connections={} num_intra_group_connections={} " "num_inter_group_connections={}").format( num_connections, num_intra_group_connections, num_inter_group_connections)) self.dag_matrix = dag_matrix # output_shape op_output_shapes = np.zeros( [ len(self.important_ops), self.hparams.max_num_outputs * self.hparams.max_output_size ], dtype=np.float32) for idx, op in enumerate(self.important_ops): for i, output_properties in enumerate(self.node_properties[op.name]): if output_properties.shape.__str__() == "<unknown>": continue if i > self.hparams.max_num_outputs: break shape = output_properties.shape for j, dim in enumerate(shape.dim): if dim.size > 0: k = i * self.hparams.max_output_size + j if k >= self.hparams.max_num_outputs * self.hparams.max_output_size: break op_output_shapes[idx, k] = dim.size # group_embedding group_embedding = np.zeros( [ self.num_groups, len(self.type_dict) + self.hparams.max_num_outputs * self.hparams.max_output_size ], dtype=np.float32) for op_index, op in enumerate(self.important_ops): group_index = grouping_actions[child_id][ self.name_to_topo_order_index[op.name]] type_name = str(op.op) type_index = self.type_dict[type_name] group_embedding[group_index, type_index] += 1 group_embedding[group_index, :self.hparams.max_num_outputs * self.hparams. max_o
idget=forms.Select(choices=colleges)) number = forms.IntegerField(label=u"الدفعة", widget=forms.Select(choices=[(i, i) for i in range(1, 17)])) def clean(self): cleaned_data = super(RegistrationForm, self).clean() batch_msg = u"الدفعة التي اخترت غير موجودة." if 'college' in cleaned_data and 'number' in cleaned_data: try: Batch.objects.get( college=cleaned_data['college'], number=int(cleaned_data['number'])) except Batch.DoesNotExist: self._errors['college'] = self.error_class([batch_msg]) self._errors['number'] = self.error_class([batch_msg]) del cleaned_data['college'] del cleaned_data['number'] return cleaned_data def save(self): new_registration = super(RegistrationForm, self).save() batch = Batch.objects.get( college=self.cleaned_data['college'], number=int(self.cleaned_data['number']), ) new_registration.group = batch new_registration.save() return new_registration class Meta: model = Registration fields = ['email', 'college', 'number', 'unisersity_id'] widgets = { 'university_id': forms.TextInput(), } class ResetPasswordForm(forms.Form): email = forms.EmailField(label=u'بريدك الجامعي', max_length=100) @csrf_exempt def register(request): if request.method == 'POST': password = generate_password() initial_registration = Registration(password=password) form = RegistrationForm(request.POST, instance=initial_registration) if form.is_valid(): email = form.cleaned_data['email'] if not email.endswith('ksau-hs.edu.sa'): context = {'form': form, 'error_message': 'university_email'} elif Registration.objects.filter(email__iexact=email, is_successful=True): context = {'form': form, 'error_message': u'already_registered'} else: user = email.split('@')[0].lower() registration = form.save() group = str(registration.group) if createuser(user, password, group): registration.is_successful = True registration.save() send_mail(u'حسابك على السحابة الطبية', new_message % (user, password), 'info@ksauhs-med.com', [email], fail_silently=False) return HttpResponseRedirect(reverse('register:thanks')) else: context = {'form': form, 'error_message': 'unknown'} else: context = {'form': form} else: form = RegistrationForm() context = {'form': form} return render(request, 'register/register.html', context) @csrf_exempt def forgotten(request): if request.method == 'POST': form = ResetPasswordForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] if not email.endswith('ksau-hs.edu.sa'): context = {'form': form, 'error_message': 'university_email'} else: try: previous_registration = Registration.objects.get(email__iexact=email, is_successful=True) except ObjectDoesNotExist: previous_registration = None context = {'form': form, 'error_message': 'not_registered'} if previous_registration: new_password = generate_password() user = previous_registration.email.split('@')[0] if reset_password(user, new_password): previous_registration.password = new_password previous_registration.forgotten_password = True previous_registration.save() send_mail(u'حسابك على السحابة الطبية', forgotten_message % (user, new_password), 'info@ksauhs-med.com', [email], fail_silently=False) return HttpResponseRedirect(reverse('register:thanks')) else: context = {'form': form, 'error_message': 'unknown'} else: context = {'form': form} else: form = ResetPasswordForm() context = {'form': form} return render(request, 'register/reset.html', context) def generate_password(): return ''.join(random.choice(string.ascii_uppercase) for i in range(6)) def login(): homepage_url = "https://www.ksauhs-med.com" homepage = requests.get(homepage_url) oc1d6beae686 = homepage.cookies['oc1d6beae686'] cookies = {'oc1d6beae686': oc1d6beae686} login_requesttoken_regex = re.compile('data-requesttoken="(.+?)"', re.U) login_requesttoken = re.findall(login_requesttoken_regex, homepage.content)[0] login_data = {'user': config.OWNCLOUD_ADMIN_USERNAME, 'password': config.OWNCLOUD_ADMIN_PASSWORD, 'requesttoken': login_requesttoken, 'remember_login': '1', 'timezone-offset': 'Asia/Baghdad', } login_page = requests.post(homepa
ge_url, data=login_data, cookies=cookies) login_cookies = login_page.history[0].cookies cookies = {#'oc_username': login_cookies['oc_username'], #'oc_token': login_cookies['oc_token'], #'oc_remember_login': login_cookies['oc_remember_login'], 'oc1d6beae686': login_cookies['oc1d6beae
686'], } return cookies def createuser(user, password, group): os.environ['OC_PASS'] = password command = "/usr/local/bin/php70 /home/medcloud/webapps/ownphp70/occ user:add {} --password-from-env -g {} -n".format(user, group) output = subprocess.call(command, shell=True) if output == 0: return True else: return False # createuser_url = "https://www.ksauhs-med.com/index.php/settings/users/users" # user_url = "https://www.ksauhs-med.com/index.php/settings/users" # login_cookies = login() # user_page = requests.post(user_url, cookies=login_cookies) # regex = re.findall("data-requesttoken=\"([^\"]+)\"", user_page.text) # requesttoken = regex[0] # user_data = {'username': user, # 'password': password, # 'groups[]': group} # headers = {'requesttoken': requesttoken} # createuser_page = requests.post(createuser_url, data=user_data, cookies=login_cookies, headers=headers) # json_object = json.loads(createuser_page.text) # if createuser_page.status_code == 201: # return True # else: # print json_object # REMOVE def reset_password(user, password): os.environ['OC_PASS'] = password command = "/usr/local/bin/php70 /home/medcloud/webapps/ownphp70/occ user:resetpassword {} --password-from-env -n".format(user) output = subprocess.call(command, shell=True) if output == 0: return True else: return False # changepassword_url = "https://www.ksauhs-med.com/index.php/settings/users/changepassword" # user_url = "https://www.ksauhs-med.com/index.php/settings/users" # login_cookies = login() # user_page = requests.post(user_url, cookies=login_cookies) # regex = re.findall("data-requesttoken=\"([^\"]+)\"", user_page.text) # requesttoken = regex[0] # user_data = {'username': user, # 'password': password} # headers = {'requesttoken': requesttoken, # 'X-Requested-With': 'XMLHttpRequest', # 'Referer': user_url} # changepassword_page = requests.post(changepassword_url, # data=user_data, # cookies=login_cookies, # headers=headers) # tr
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.utils import timezone from django.db import models, migrations def fill_tables(apps, schema_editor): eventsforbusv2 = apps.get_model('AndroidRequests', 'EventForBusv2') eventsforbusstop = apps.get_model('AndroidRequests', 'EventForBusStop') hhperiods = apps.get_model('AndroidRequests', 'HalfHourPeriod') for ev in eventsforbusv2.objects.all(): creationTime = timezone.localtime(ev.timeCreation).time().replace(microsecond=0) hhperiod = hhperiods.objects.get(initial_time__lte = creationTime , end_time__gte = creationTime) ev.halfHourPeriod = hhperiod ev.save() for ev in eventsforbusstop.objects.all(): creationTime = timezone.localtime(ev.timeCreation).time().replace(microsecond=0)
hhperiod = hhperiods.objects.get(initial_time__lte = creationTime , end_time__gte = creationTime) ev.halfHourPeriod = hhperiod ev.save() class Migration(migrations.Migration): dependencies = [ ('AndroidRequests', '0903_transformation_halfhourperiod'), ] operations = [ migrations.AddField( model_name='e
ventforbusv2', name='halfHourPeriod', field=models.ForeignKey(verbose_name=b'Half Hour Period', to='AndroidRequests.HalfHourPeriod', null=True), preserve_default=False, ), migrations.AddField( model_name='eventforbusstop', name='halfHourPeriod', field=models.ForeignKey(verbose_name=b'Half Hour Period', to='AndroidRequests.HalfHourPeriod', null=True), preserve_default=False, ), migrations.RunPython(fill_tables, reverse_code=migrations.RunPython.noop), migrations.AlterField( model_name='eventforbusv2', name='halfHourPeriod', field=models.ForeignKey(verbose_name=b'Half Hour Period', to='AndroidRequests.HalfHourPeriod', null=False), ), migrations.AlterField( model_name='eventforbusstop', name='halfHourPeriod', field=models.ForeignKey(verbose_name=b'Half Hour Period', to='AndroidRequests.HalfHourPeriod', null=False), ), ]
import exceptions # thr
ows by anything which doesn't like what was passed to it class DataError(exceptions.StandardError): pass # thrown by MojoMessage class MojoMessageError(DataError): pass # thrown by DataTypes class BadFormatError(DataError): pass # throws by things which do block reassembly class ReassemblyErr
or(IOError): pass
from setuptools import setup setup( name = "zml", packages = ["zml"], ve
rsion = "0.8.1", description = "zero markup language", author = "Christof Hagedorn", author_email = "team@zml.org", ur
l = "http://www.zml.org/", download_url = "https://pypi.python.org/pypi/zml", keywords = ["zml", "zero", "markup", "language", "template", "templating"], install_requires = ['pyparsing', 'html5lib', 'pyyaml', 'asteval' ], classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Development Status :: 3 - Alpha", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Topic :: Internet", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", "Topic :: Internet :: WWW/HTTP :: WSGI", "Topic :: Software Development :: Libraries :: Python Modules", ], long_description = """\ zml - zero markup language ------------------------------------- Features - zero markup templates - clean syntax - extensible - components - namespaces - lean code This version requires Python 3 or later. """ )
tr is_implemented: bool # True iff all unions required by the goal are implemented. consumed_scopes: Tuple[str, ...] # The scopes of subsystems consumed by this goal. @dataclass(frozen=True) class TargetFieldHelpInfo: """A container for help information for a field in a target type.""" alias: str description: Optional[str] type_hint: str required: bool default: Optional[str] @classmethod def create(cls, field: Type[Field]) -> TargetFieldHelpInfo: description: Optional[str] if hasattr(field, "help"): description = field.help else: # NB: It is very common (and encouraged) to subclass Fields to give custom behavior, e.g. # `PythonSources` subclassing `Sources`. Here, we set `fallback_to_ancestors=True` so that # we can still generate meaningful documentation for all these custom fields without # requiring the Field author to rewrite the docstring. # # However, if the original plugin author did not define docstring, then this means we # would typically fall back to the docstring for `Field` or a template like `StringField`. # This is a an awkward edge of our heuristic and it's not intentional since these core # `Field` types have documentation oriented to the plugin author and not the end user # filling in fields in a BUILD file. description = get_docstring( field, flatten=True, fallback_to_ancestors=True, ignored_ancestors={ *Field.mro(), AsyncFieldMixin, BoolField, DictStringToStringField, DictStringToStringSequenceField, FloatField, Generic, # type: ignore[arg-type] IntField, ScalarField, SequenceField, StringField, StringSequenceField, }, ) raw_value_type = get_type_hints(field.compute_value)["raw_value"] type_hint = pretty_print_type_hint(raw_value_type) # Check if the field only allows for certain choices. if issubclass(field, StringField) and field.valid_choices is not None: valid_choices = sorted( field.valid_choices if isinstance(field.valid_choices, tuple) else (choice.value for choice in field.valid_choices) ) type_hint = " | ".join([*(repr(c) for c in valid_choices), "None"]) if field.required: # We hackily remove `None` as a valid option for the field when it's required. This # greatly simplifies Field definitions because it means that they don't need to # override the type hints for `PrimitiveField.compute_value()` and # `AsyncField.sanitize_raw_value()` to indicate that `None` is an invalid type. type_hint = type_hint.replace(" | None", "") return cls( alias=field.alias, description=description, type_hint=type_hint, required=field.required, default=( repr(field.default) if (not field.required and field.default is not None) else None ), ) @dataclass(frozen=True) class TargetTypeHelpInfo: """A container for help information for a target type.""" alias: str summary: Optional[str] description: Optional[str] fields: Tuple[TargetFieldHelpInfo, ...] @classmethod def create( cls, target_type: Type[Target], *, union_membership: UnionMembership ) -> TargetTypeHelpInfo: description: Optional[str] summary: Optional[str] if hasattr(target_type, "help"): description = target_type.help summary = first_paragraph(description) else: description = get_docstring(target_type) summary = get_docstring_summary(target_type) return cls( alias=target_type.alias, summary=summary, description=description, fields=tuple( TargetFieldHelpInfo.create(field) for field in target_type.class_field_types(union_membership=union_membership) if not field.alias.startswith("_") and field.deprecated_removal_version is None ), ) @dataclass(frozen=True) class AllHelpInfo: """All available help info.""" scope_to_help_info: Dict[str, OptionScopeHelpInfo] name_to_goal_info: Dict[str, GoalHelpInfo] name_to_target_type_info: Dict[str, TargetTypeHelpInfo] ConsumedScopesMapper = Callable[[str], Tuple[str, ...]] class HelpInfoExtracter: """Extracts information useful for displaying help from option registration args.""" @classmethod def get_all_help_info( cls, options: Options, union_membership: UnionMembership, consumed_scopes_mapper: ConsumedScopesMapper, registered_target_types: RegisteredTargetTypes, ) -> AllHelpInfo: scope_to_help_info = {} name_to_goal_info = {} for scope_info in sorted(options.known_scope_to_info.values(), key=lambda x: x.scope): options.for_scope(scope_info.scope) # Force parsing. optionable_cls = scope_info.optionable_cls if not scope_info.description: cls_name = ( f"{optionable_cls.__module__}.{optionable_cls.__qualname__}" if optionable_cls else "" ) raise ValueError( f"Subsystem {cls_name} with scope `{scope_info.scope}` has no description. " f"Add a class property `help`." ) is_goal = optionable_cls is not None and issubclass(optionable_cls, GoalSubsystem) oshi = HelpInfoExtracter(scope_info.scope).get_option_scope_help_info( scope_info.description, options.get_parser(scope_info.scope), is_goal ) scope_to_help_info[oshi.scope] = oshi if is_goal: goal_subsystem_cls = cast(Type[GoalSubsystem], optionable_cls) is_implemented = union_membership.has_members_for_all( goal_subsystem_cls.required_union_implementations ) name_to_goal_info[scope_info.scope] = GoalHelpInfo( goal_subsystem_cls.name,
scope_info.description,
is_implemented, consumed_scopes_mapper(scope_info.scope), ) name_to_target_type_info = { alias: TargetTypeHelpInfo.create(target_type, union_membership=union_membership) for alias, target_type in registered_target_types.aliases_to_types.items() if not alias.startswith("_") and target_type.deprecated_removal_version is None } return AllHelpInfo( scope_to_help_info=scope_to_help_info, name_to_goal_info=name_to_goal_info, name_to_target_type_info=name_to_target_type_info, ) @staticmethod def compute_default(**kwargs) -> Any: """Compute the default val for help display for an option registered with these kwargs. Returns a pair (default, stringified default suitable for display). """ ranked_default = kwargs.get("default") fallback: Any = None if is_list_option(kwargs): fallback = [] elif is_dict_option(kwargs): fallback = {} default = ( ranked_default.value if ranked_default and ranked_default.value is not None else fallback ) return default @staticmethod def stringify_type(t: Type) -> str: if t == dict: return "{'key1': val1, 'key2': val2, ...}" return f"<{t.__name__}>" @staticmethod def compute_metavar(kwargs): """
""") expected_meta = {'page_title': ['custom title']} self.assertEqual(html.strip(), expected_html) self.assertEqual(str(toc).strip(), expected_toc) self.assertEqual(meta, expected_meta) def test_convert_internal_link(self): md_text = 'An [internal link](internal.md) to another document.' expected = '<p>An <a href="internal/">internal link</a> to another document.</p>' html, toc, meta = build.convert_markdown(md_text) self.assertEqual(html.strip(), expected.strip()) def test_convert_multiple_internal_links(self): md_text = '[First link](first.md) [second link](second.md).' expected = '<p><a href="first/">First link</a> <a href="second/">second link</a>.</p>' html, toc, meta = build.convert_markdown(md_text) self.assertEqual(html.strip(), expected.strip()) def test_convert_internal_link_differing_directory(self): md_text = 'An [internal link](../internal.md) to another document.' expected = '<p>An <a href="../internal/">internal link</a> to another document.</p>' html, toc, meta = build.convert_markdown(md_text) self.assertEqual(html.strip(), expected.strip()) def test_convert_internal_link_with_anchor(self): md_text = 'An [internal link](internal.md#section1.1) to another document.' expected = '<p>An <a href="internal/#section1.1">internal link</a> to another document.</p>' html, toc, meta = build.convert_markdown(md_text) self.assertEqual(html.strip(), expected.strip()) def test_convert_internal_media(self): """Test relative image URL's are the same for different base_urls""" pages = [ ('index.md',), ('internal.md',), ('sub/internal.md') ] site_navigation = nav.SiteNavigation(pages) expected_results = ( './img/initial-layout.png', '../img/initial-layout.png', '../img/initial-layout.png', ) template = '<p><img alt="The initial MkDocs layout" src="%s" /></p>' for (page, expected) in zip(site_navigation.walk_pages(), expected_results): md_text = '![The initial MkDocs layout](img/initial-layout.png)' html, _, _ = build.convert_markdown(md_text, site_navigation=site_navigation) self.assertEqual(html, template % expected) def test_convert_internal_asbolute_media(self): """Test absolute image URL's are correct for different base_urls""" pages = [ ('index.md',), ('internal.md',), ('sub/internal.md') ] site_navigation = nav.SiteNavigation(pages) expected_results = ( './img/initial-layout.png', '../img/initial-layout.png', '../../img/initial-layout.png', ) template = '<p><img alt="The initial MkDocs layout" src="%s" /></p>' for (page, expected) in zip(site_navigation.walk_pages(), expected_results): md_text = '![The initial MkDocs layout](/img/initial-layout.png)' html, _, _ = build.convert_markdown(md_text, site_navigation=site_navigation) self.assertEqual(html, template % expected) def test_dont_convert_code_block_urls(self): pages = [ ('index.md',), ('internal.md',), ('sub/internal.md') ] site_navigation = nav.SiteNavigation(pages) expected = dedent(""" <p>An HTML Anchor::</p> <pre><code>&lt;a href="index.md"&gt;My example link&lt;/a&gt; </code></pre> """) for page in site_navigation.walk_pages(): markdown = 'An HTML Anchor::\n\n <a href="index.md">My example link</a>\n' html, _, _ = build.convert_markdown(markdown, site_navigation=site_navigation) self.assertEqual(dedent(html), expected) def test_anchor_only_link(self): pages = [ ('index.md',), ('internal.md',), ('sub/internal.md') ] site_navigation = nav.SiteNavigation(pages) for page in site_navigation.walk_pages(): markdown = '[test](#test)' html, _, _ = build.convert_markdown(markdown, site_navigation=site_navigation) self.assertEqual(html, '<p><a href="#test">test</a></p>') def test_ignore_external_link(self): md_text = 'An [external link](http://example.com/external.md).' expected = '<p>An <a href="http://example.com/external.md">external link</a>.</p>' html, toc, meta = build.convert_markdown(md_text) self.assertEqual(html.strip(), expected.strip()) def test_not_use_directory_urls(self): md_text = 'An [internal link](internal.md) to another document.' expected = '<p>An <a href="internal/index.html">internal link</a> to another document.</p>' pages = [ ('internal.md',) ] site_navigation = nav.SiteNavigation(pages, use_directory_urls=False) html, toc, meta = build.convert_markdown(md_text, site_navigation=site_navigation) self.assertEqual(html.strip(), expected.strip()) def test_markdown_table_extension(self): """ Ensure that the table extension is supported. """ html, toc, meta = build.convert_markdown(dedent(""" First Header | Second Header -------------- | -------------- Content Cell 1 | Content Cell 2 Content Cell 3 | Content Cell 4 """)) expected_html = dedent(""" <table> <thead> <tr> <th>First Header</th> <th>Second Header</th> </tr> </thead> <tbody> <tr> <td>Content Cell 1</td> <td>Content Cell 2</td> </tr> <tr> <td>Content Cell 3</td> <td>Content Cell 4</td> </tr> </tbody> </table> """) self.assertEqual(html.strip(), expected_html) def test_markdow
n_fenced_code_extension(self): """ Ensure that the fenced code extension is supported. """ html, toc, meta = build.convert_markdown(dedent(""" ``` print 'foo' ``` """)) expected_html = dedent(""" <pre><code>print 'foo'\n</code></pre> """) self.assertEqual(html.strip(), expected_html) def test_markdown_custom_extension(self): """ Check th
at an extension applies when requested in the arguments to `convert_markdown`. """ md_input = "foo__bar__baz" # Check that the plugin is not active when not requested. expected_without_smartstrong = "<p>foo<strong>bar</strong>baz</p>" html_base, _, _ = build.convert_markdown(md_input) self.assertEqual(html_base.strip(), expected_without_smartstrong) # Check that the plugin is active when requested. expected_with_smartstrong = "<p>foo__bar__baz</p>" html_ext, _, _ = build.convert_markdown(md_input, extensions=['smart_strong']) self.assertEqual(html_ext.strip(), expected_with_smartstrong) def test_markdown_duplicate_custom_extension(self): """ Duplicated extension names should not cause problems. """ md_input = "foo" html_ext, _, _ = build.convert_markdown(md_input, ['toc']) self.assertEqual(html_ext.strip(), '<p>foo</p>') def test_copying_media(self): docs_dir = tempfile.mkdtemp() site_dir = tempfile.mkdtemp() try: # Create a non-empty markdown file, image, dot file and dot directory. f = open(os.path.join(docs_dir, 'index.md'), 'w') f.write(dedent(""" page_title: custom title # Heading 1 This is some text. # Heading 2 And some more text. """)) f.close() open(os.path.join(docs_dir, 'img.jpg'), 'w').close() open(os.path.join(docs_dir, '.hidden'), 'w').close() os.mkdir
def func(): va
lue = "not-none" # Is none <caret>if value is None: print("None") else: p
rint("Not none")
from geojson_rewind import rewind from geomet import wkt import decimal import statistics def wkt_rewind(x, digits=None): """ reverse WKT winding order :param x: [str] WKT string :param digits: [int] number of digits after decimal to use for the return string. by default, we use the mean number of digits in your string. :return: a string Usage:: from pygbif import wkt_rewind x = 'POLYGON((144.6 13.2, 144.6 13.6, 144.9 13.6, 144.9 13.2, 144.6 13.2))' wkt_rewind(x) wkt_rewind(x, digits = 0) wkt_rewind(x, digits = 3) wkt_rewind(x, digits = 7) """
z = wkt.loads(x) if digits is None: coords = z["coordinates"] nums = __flatten(coords) dec_n = [decimal.Decimal(str(w)).as_tuple().exponent for w in nums] digits = abs(statistics.mean(dec_n)) else: if not isinstance(digits, int): raise TypeError("'digits' must be an int") wound = rewind(z) back_to_wkt = wkt.dumps(wound, decimals=digits) return back
_to_wkt # from https://stackoverflow.com/a/12472564/1091766 def __flatten(S): if S == []: return S if isinstance(S[0], list): return __flatten(S[0]) + __flatten(S[1:]) return S[:1] + __flatten(S[1:])
`` None | ``required:`` False | ``default:`` None :param select: The list of attributes to return for each DeviceServiceService. V
alid values are DeviceServiceServiceID, DeviceID, DataSourceID, ParentDeviceServiceID, ChildDeviceServiceID, SvsvFirstSeenTime, SvsvStartTime, SvsvEndTime, SvsvTimestamp, SvsvChangedCols, SvsvUsage, SvsvProvisionData. If empty or omitted, all attributes will be returned. :type select: Array |
``api version min:`` 2.8 | ``api version max:`` None | ``required:`` False | ``default:`` None :param goto_field: The field name for NIOS GOTO that is used for locating a row position of records. :type goto_field: String | ``api version min:`` 2.8 | ``api version max:`` None | ``required:`` False | ``default:`` None :param goto_value: The value of goto_field for NIOS GOTO that is used for locating a row position of records. :type goto_value: String **Outputs** | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :return device_service_services: An array of the DeviceServiceService objects that match the specified input criteria. :rtype device_service_services: Array of DeviceServiceService """ return self.api_list_request(self._get_method_fullname("index"), kwargs) def search(self, **kwargs): """Lists the available device service services matching the input criteria. This method provides a more flexible search interface than the index method, but searching using this method is more demanding on the system and will not perform to the same level as the index method. The input fields listed below will be used as in the index method, to filter the result, along with the optional query string and XML filter described below. **Inputs** | ``api version min:`` 2.6 | ``api version max:`` None | ``required:`` False | ``default:`` None :param ChildDeviceServiceID: The internal NetMRI identifier of the child service (the used service). :type ChildDeviceServiceID: Array of Integer | ``api version min:`` 2.6 | ``api version max:`` None | ``required:`` False | ``default:`` None :param DataSourceID: The internal NetMRI identifier for the collector NetMRI that collected this data record. :type DataSourceID: Array of Integer | ``api version min:`` 2.6 | ``api version max:`` None | ``required:`` False | ``default:`` None :param DeviceID: The internal NetMRI identifier for the device to which belongs this services. :type DeviceID: Array of Integer | ``api version min:`` 2.6 | ``api version max:`` None | ``required:`` False | ``default:`` None :param DeviceServiceServiceID: The internal NetMRI identifier of this usage relationship between service objects. :type DeviceServiceServiceID: Array of Integer | ``api version min:`` 2.6 | ``api version max:`` None | ``required:`` False | ``default:`` None :param ParentDeviceServiceID: The internal NetMRI identifier of the parent service (the user). :type ParentDeviceServiceID: Array of Integer | ``api version min:`` 2.6 | ``api version max:`` None | ``required:`` False | ``default:`` None :param SvsvChangedCols: The fields that changed between this revision of the record and the previous revision. :type SvsvChangedCols: Array of String | ``api version min:`` 2.6 | ``api version max:`` None | ``required:`` False | ``default:`` None :param SvsvEndTime: The ending effective time of this record, or empty if still in effect. :type SvsvEndTime: Array of DateTime | ``api version min:`` 2.6 | ``api version max:`` None | ``required:`` False | ``default:`` None :param SvsvFirstSeenTime: The timestamp of when NetMRI saw for the first time this relationship. :type SvsvFirstSeenTime: Array of DateTime | ``api version min:`` 2.6 | ``api version max:`` None | ``required:`` False | ``default:`` None :param SvsvProvisionData: Internal data - do not modify, may change without warning. :type SvsvProvisionData: Array of String | ``api version min:`` 2.6 | ``api version max:`` None | ``required:`` False | ``default:`` None :param SvsvStartTime: The starting effective time of this record. :type SvsvStartTime: Array of DateTime | ``api version min:`` 2.6 | ``api version max:`` None | ``required:`` False | ``default:`` None :param SvsvTimestamp: The date and time this record was collected or calculated. :type SvsvTimestamp: Array of DateTime | ``api version min:`` 2.6 | ``api version max:`` None | ``required:`` False | ``default:`` None :param SvsvUsage: An indicator of the kind of relationship. One of : child, protID, srcPrtID, dstPrtID, protDstID. The regular indicator is 'child'. :type SvsvUsage: Array of String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param DeviceGroupID: The internal NetMRI identifier of the device groups to which to limit the results. :type DeviceGroupID: Array of Integer | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param timestamp: The data returned will represent the device service services as of this date and time. If omitted, the result will indicate the most recently collected data. :type timestamp: DateTime | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param methods: A list of device service service methods. The listed methods will be called on each device service service returned and included in the output. Available methods are: parent_device_service, child_device_service, data_source, device. :type methods: Array of String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` None :param include: A list of associated object types to include in the output. The listed associations will be returned as outputs named according to the association name (see outputs below). Available includes are: parent_device_service, child_device_service, data_source, device. :type include: Array of String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` 0 :param start: The record number to return in the selected page of data. It will always appear, although it may not be the first record. See the :limit for more information. :type start: Integer | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` 1000 :param limit: The size of the page of data, that is, the maximum number of records returned. The limit size will be used to brea
on except ImportError: import common from autotest.client.shared.global_config import global_config require_atfork = global_config.get_config_value( 'AUTOSERV', 'require_atfork_module', type=bool, default=True) try: import atfork atfork.monkeypatch_os_fork_functions() import atfork.stdlib_fixer # Fix the Python standard library for threading+fork safety with its # internal locks. http://code.google.com/p/python-atfork/ import warnings warnings.filterwarnings('ignore', 'logging module already imported') atfork.stdlib_fixer.fix_logging_module() except ImportError, e: from autotest.client.shared import global_config if global_config.global_config.get_config_value( 'AUTOSERV', 'require_atfork_module', type=bool, default=False): print >>sys.stderr, 'Please run utils/build_externals.py' print e sys.exit(1) from autotest.server import server_logging_config from autotest.server import server_job, autoserv_parser from autotest.server import autotest_remote from autotest.client.shared import pidfile, logging_manager def run_autoserv(pid_file_manager, results, parser): # send stdin to /dev/null dev_null = os.open(os.devnull, os.O_RDONLY) os.dup2(dev_null, sys.stdin.fileno()) os.close(dev_null) # Create separate process group os.setpgrp() # Implement SIGTERM handler def handle_sigterm(signum, frame): if pid_file_manager: pid_file_manager.close_file(1, signal.SIGTERM) os.killpg(os.getpgrp(), signal.SIGKILL) # Set signal handler signal.signal(signal.SIGTERM, handle_sigterm) # Ignore SIGTTOU's generated by output from forked children. signal.signal(signal.SIGTTOU, signal.SIG_IGN)
# Server side tests that call shell scripts often depend on $USER being set # but depending on how you launch your autotest scheduler it may not be set. os.environ['USER'] = getpass.getuser() if parser.options.machines: machines = parser.options.machines.replace(',', ' ').strip().split()
else: machines = [] machines_file = parser.options.machines_file label = parser.options.label group_name = parser.options.group_name user = parser.options.user client = parser.options.client server = parser.options.server install_before = parser.options.install_before install_after = parser.options.install_after verify = parser.options.verify repair = parser.options.repair cleanup = parser.options.cleanup no_tee = parser.options.no_tee parse_job = parser.options.parse_job execution_tag = parser.options.execution_tag if not execution_tag: execution_tag = parse_job host_protection = parser.options.host_protection ssh_user = parser.options.ssh_user ssh_port = parser.options.ssh_port ssh_pass = parser.options.ssh_pass collect_crashinfo = parser.options.collect_crashinfo control_filename = parser.options.control_filename # can't be both a client and a server side test if client and server: parser.parser.error("Can not specify a test as both server and client!") if len(parser.args) < 1 and not (verify or repair or cleanup or collect_crashinfo): parser.parser.error("Missing argument: control file") # We have a control file unless it's just a verify/repair/cleanup job if len(parser.args) > 0: control = parser.args[0] else: control = None if machines_file: machines = [] for m in open(machines_file, 'r').readlines(): # remove comments, spaces m = re.sub('#.*', '', m).strip() if m: machines.append(m) print "Read list of machines from file: %s" % machines_file print ','.join(machines) if machines: for machine in machines: if not machine or re.search('\s', machine): parser.parser.error("Invalid machine: %s" % str(machine)) machines = list(set(machines)) machines.sort() if group_name and len(machines) < 2: parser.parser.error("-G %r may only be supplied with more than one machine." % group_name) kwargs = {'group_name': group_name, 'tag': execution_tag} if control_filename: kwargs['control_filename'] = control_filename job = server_job.server_job(control, parser.args[1:], results, label, user, machines, client, parse_job, ssh_user, ssh_port, ssh_pass, **kwargs) job.logging.start_logging() job.init_parser() # perform checks job.precheck() # run the job exit_code = 0 try: try: if repair: job.repair(host_protection) elif verify: job.verify() else: job.run(cleanup, install_before, install_after, only_collect_crashinfo=collect_crashinfo) finally: while job.hosts: host = job.hosts.pop() host.close() except: exit_code = 1 traceback.print_exc() if pid_file_manager: pid_file_manager.num_tests_failed = job.num_tests_failed pid_file_manager.close_file(exit_code) job.cleanup_parser() sys.exit(exit_code) def main(): # grab the parser parser = autoserv_parser.autoserv_parser parser.parse_args() if len(sys.argv) == 1: parser.parser.print_help() sys.exit(1) if parser.options.no_logging: results = None else: output_dir = global_config.get_config_value('COMMON', 'test_output_dir', default="") results = parser.options.results if not results: results = 'results.' + time.strftime('%Y-%m-%d-%H.%M.%S') if output_dir: results = os.path.join(output_dir, results) results = os.path.abspath(results) resultdir_exists = False for filename in ('control.srv', 'status.log', '.autoserv_execute'): if os.path.exists(os.path.join(results, filename)): resultdir_exists = True if not parser.options.use_existing_results and resultdir_exists: error = "Error: results directory already exists: %s\n" % results sys.stderr.write(error) sys.exit(1) # Now that we certified that there's no leftover results dir from # previous jobs, lets create the result dir since the logging system # needs to create the log file in there. if not os.path.isdir(results): os.makedirs(results) logging_manager.configure_logging( server_logging_config.ServerLoggingConfig(), results_dir=results, use_console=not parser.options.no_tee, verbose=parser.options.verbose, no_console_prefix=parser.options.no_console_prefix) if results: logging.info("Results placed in %s" % results) # wait until now to perform this check, so it get properly logged if parser.options.use_existing_results and not resultdir_exists: logging.error("No existing results directory found: %s", results) sys.exit(1) if parser.options.write_pidfile: pid_file_manager = pidfile.PidFileManager(parser.options.pidfile_label, results) pid_file_manager.open_file() else: pid_file_manager = None autotest_remote.BaseAutotest.set_install_in_tmpdir( parser.options.install_in_tmpdir) exit_code = 0 try: try: run_autoserv(pid_file_manager, results, parser) except SystemExit, e: exit_code = e.code except: traceback.print_exc() # If we don't know what happened, we'll classify it as # an 'abort' and return 1. exit_code = 1 finally: if pid_file_manager:
e else reduced_to_budgets self.scenario = scenario self.original_runhistory = original_runhistory self.validated_runhistory = validated_runhistory self.trajectory = trajectory self.ta_exec_dir = ta_exec_dir self.file_format = file_format self.validation_format = validation_format if not output_dir: self.logger.debug("New outputdir") output_dir = tempfile.mkdtemp() self.output_dir = os.path.join(output_dir, 'analysis_data', self.get_identifier()) os.makedirs(self.output_dir, exist_ok=True) self.default = self.scenario.cs.get_default_configuration() self.incumbent = self.trajectory[-1]['incumbent'] if self.trajectory else None self.feature_names = self._get_feature_names() # Create combined runhistory to collect all "real" runs self.combined_runhistory = RunHistory() self.combined_runhistory.update(self.original_runhistory, origin=DataOrigin.INTERNAL) if self.validated_runhistory is not None: self.combined_runhistory.update(self.validated_runhistory, origin=DataOrigin.EXTERNAL_SAME_INSTANCES) # Create runhistory with estimated runs (create Importance-object of pimp and use epm-model for validation) self.epm_runhistory = RunHistory() self.epm_runhistory.update(self.combined_runhistory) # Initialize importance and validator self._init_pimp_and_validator() try: self._validate_default_and_incumbents("epm", self.ta_exec_dir) except KeyError as err: self.logger.debug(err, exc_inf
o=True) msg = "Validation of default and incumbent failed. SMAC (v: {}) does not support vali
dation of budgets+ins"\ "tances yet, if you use budgets but no instances ignore this warning.".format(str(smac_version)) if self.feature_names: self.logger.warning(msg) else: self.logger.debug(msg) # Set during execution, to share information between Analyzers self.share_information = {'parameter_importance': OrderedDict(), 'feature_importance': OrderedDict(), 'evaluators': OrderedDict(), 'validator': None, 'hpbandster_result': None, # Only for file-format BOHB } def get_identifier(self): return self.identify(self.path_to_folder, self.reduced_to_budgets) @classmethod def identify(cls, path, budget): path = path if path is not None else "all_folders" budget = str(budget) if budget is not None else "all_budgets" res = "_".join([path, budget]).replace('/', '_') if len(res) > len(str(hash(res))): res = str(hash(res)) return res def get_budgets(self): return set([k.budget for k in self.original_runhistory.data.keys()]) @classmethod def from_folder(cls, folder: str, ta_exec_dir: str, options, file_format: str='SMAC3', validation_format: str='NONE', output_dir=None, ): """Initialize scenario, runhistory and incumbent from folder Parameters ---------- folder: string output-dir of this configurator-run -> this is also the 'id' for a single run in parallel optimization ta_exec_dir: string if the execution directory for the SMAC-run differs from the cwd, there might be problems loading instance-, feature- or PCS-files in the scenario-object. since instance- and PCS-files are necessary, specify the path to the execution-dir of SMAC here file_format: string from [SMAC2, SMAC3, BOHB, APT, CSV] validation_format: string from [SMAC2, SMAC3, APT, CSV, NONE], in which format to look for validated data """ logger = logging.getLogger("cave.ConfiguratorRun.{}".format(folder)) logger.debug("Loading from \'%s\' with ta_exec_dir \'%s\' with file-format '%s' and validation-format %s. ", folder, ta_exec_dir, file_format, validation_format) if file_format == 'BOHB' or file_format == "APT": logger.debug("File format is BOHB or APT, assmuming data was converted to SMAC3-format using " "HpBandSter2SMAC from cave.reader.converter.hpbandster2smac.") validation_format = validation_format if validation_format != 'NONE' else None # Read in data (scenario, runhistory & trajectory) reader = cls.get_reader(file_format, folder, ta_exec_dir) scenario = reader.get_scenario() scenario_sanity_check(scenario, logger) original_runhistory = reader.get_runhistory(scenario.cs) validated_runhistory = None if validation_format == "NONE" or validation_format is None: validation_format = None else: logger.debug('Using format %s for validation', validation_format) vali_reader = cls.get_reader(validation_format, folder, ta_exec_dir) vali_reader.scen = scenario validated_runhistory = vali_reader.get_validated_runhistory(scenario.cs) #self._check_rh_for_inc_and_def(self.validated_runhistory, 'validated runhistory') logger.info("Found validated runhistory for \"%s\" and using " "it for evaluation. #configs in validated rh: %d", folder, len(validated_runhistory.config_ids)) trajectory = reader.get_trajectory(scenario.cs) return cls(scenario, original_runhistory, validated_runhistory, trajectory, options, path_to_folder=folder, ta_exec_dir=ta_exec_dir, file_format=file_format, validation_format=validation_format, output_dir=output_dir, ) def get_incumbent(self): return self.incumbent def _init_pimp_and_validator(self, alternative_output_dir=None, ): """ Create ParameterImportance-object and use it's trained model for validation and further predictions. We pass a combined (original + validated) runhistory, so that the returned model will be based on as much information as possible Parameters ---------- alternative_output_dir: str e.g. for budgets we want pimp to use an alternative output-dir (subfolders per budget) """ self.logger.debug("Using '%s' as output for pimp", alternative_output_dir if alternative_output_dir else self.output_dir) self.pimp = Importance(scenario=copy.deepcopy(self.scenario), runhistory=self.combined_runhistory, incumbent=self.incumbent if self.incumbent else self.default, save_folder=alternative_output_dir if alternative_output_dir is not None else self.output_dir, seed=self.rng.randint(1, 100000), max_sample_size=self.options['fANOVA'].getint("pimp_max_samples"), fANOVA_pairwise=self.options['fANOVA'].getboolean("fanova_pairwise"), preprocess=False, verbose=False, # disable progressbars in pimp... ) # Validator (initialize without trajectory) self.validator = Validator(self.scenario, None, None) self.validator.epm = self.pimp.model @timing def _validate_default_and_incumbents(self, method, ta_exec_dir,
from django.contrib import admin from workflow.model
s import State, StateLog, NextState, Project, Location from workflow.activities import StateActivity class NextStateInline(admin.StackedInline): model = NextState fk_name = 'current_state' extra = 0 class StateAdmin
(admin.ModelAdmin): inlines = [NextStateInline, ] list_display = ('name', 'is_work_state',) class StateLogAdmin(admin.ModelAdmin): readonly_fields = ['start', 'end', 'state', 'user'] list_display = ('user', 'state', 'project', 'location', 'start', 'end',) admin.site.register(State, StateAdmin) admin.site.register(StateLog, StateLogAdmin) admin.site.register(Project) admin.site.register(Location)
import unittest import instruction_set class TestInstructionSet(unittest.TestCase): def test_generate(self): self.assertIsInstance(instruction_set.generate(), list) self.assertEqual(len(instruction_set.generate()), 64) self.assertEqual(len(instruction_set.generate(32)), 32) inset = instruction_set.generate() for instruction in inset: self.assertGreaterEqual(instruction, 0) self.assertLess(instruction, 256) def test_crossover(self): parent1 = instruction_set.generate() parent2 = instruction_set.generate() children = instruction_set.crossover(parent1, parent2) random_children = instruction_set.crossover(parent1, parent2, take_random=True) self.assertIsInstance(children, tuple) self.assertIsInstance(children[0], list) self.assertIsInstance(children[1], list) self.assertEqual(len(children[0]), len(parent1)) self.assertEqual(len(children[1]), len(parent1)) for i, _ in enumerate(parent1): self.assertTrue( (children[0][i] in parent1 and children[1][i] in parent2) or (children[0][i] in parent2 and children[1][i] in parent1) ) self.assertTrue( (random_children[0][i] in parent1 and random_children[1][i] in parent2) or (random_children[0][i] in parent2 and random_children[1][i] in parent1) ) def test_mutate_bits(self): inset = instruction_set.generate() self.assertEqual(len(inset), len(instruction_set.mutate_bits(inset))) self.assertEqual(inset, instruction_set.mutate_bits(inset, mutation_chance=0)) self.assertNotEqual(inset, instruction_set.mutate_bits(inset, mutation_chance=100)) for instruction in instruction_set.mutate_bits(inset): self.assertGreaterEqual(instruction, 0) self.a
ssertLess(instruction, 256) def test_mutate_bytes(self): inset = instruction_set.generate() self.assertEqual(len(inset), len(instruction_set.mutate_bytes(inset))) self.assertEqual(inset, instruction_set.mutate_bytes(inset, mutation_chance=0)) self.assertNotEqual(inset, instruction_set.mutate_bytes(inset, mutation_chance=100)) for instruction in instruction_set.mutate_bytes(inset)
: self.assertGreaterEqual(instruction, 0) self.assertLess(instruction, 256) def test_mutate_combined(self): inset = instruction_set.generate() self.assertEqual(len(inset), len(instruction_set.mutate_combined(inset))) for instruction in instruction_set.mutate_combined(inset): self.assertGreaterEqual(instruction, 0) self.assertLess(instruction, 256) if __name__ == '__main__': unittest.main()
= StringIO(json.dumps(data_dict)) with pytest.raises(VerifyError) as err: site.content_manager.verifyFile("data/test_include/content.json", data, ignore_same=False) assert "File not allowed" in str(err) # Reset del data_dict["files"]["notallowed.exe"] del data_dict["signs"] # Should work again data_dict["signs"] = {"1TeSTvb4w2PWE81S2rEELgmX2GCCExQGT": CryptBitcoin.sign(json.dumps(data_dict), self.privatekey)} data = StringIO(json.dumps(data_dict)) assert site.content_manager.verifyFile("data/test_include/content.json", data, ignore_same=False) @pytest.mark.parametrize("inner_path", ["content.json", "data/test_include/content.json", "data/users/content.json"]) def testSign(self, site, inner_path): # Bad privatekey with pytest.raises(SignError) as err: site.content_manager.sign(inner_path, privatekey="5aaa3PvNm5HUWoCfSUfcYvfQ2g3PrRNJWr6Q9eqdBGu23mtMnaa", filewrite=False) assert "Private key invalid" in str(err) # Good privatekey content = site.content_manager.sign(inner_path, privatekey=self.privatekey, filewrite=False) content_old = site.content_manager.contents[inner_path] # Content before the sign assert not content_old == content # Timestamp changed assert site.address in content["signs"] # Used the site's private key to sign if inner_path == "content.json": assert len(content["files"]) == 17 elif inner_path == "data/test-include/content.json": assert len(content["files"]) == 1 elif inner_path == "data/users/content.json": assert len(content["files"]) == 0 # Everything should be same as before except the modified timestamp and the signs assert ( {key: val for key, val in content_old.items() if key not in ["modified", "signs", "sign", "zeronet_version"]} == {key: val for key, val in content.items() if key not in ["modified", "signs", "sign", "zeronet_version"]} ) def testSignOptionalFiles(self, site): for hash in list(site.content_manager.hashfield): site.content_manager.hashfield.remove(hash) assert len(site.content_manager.hashfield) == 0 site.content_manager.contents["content.json"]["optional"] = "((data/img/zero.*))" content_optional = site.content_manager.sign(privatekey=self.privatekey, filewrite=False, remove_missing_optional=True) del site.content_manager.contents["content.json"]["optional"] content_nooptional = site.content_manager.sign(privatekey=self.privatekey, filewrite=False, remove_missing_optional=True) assert len(content_nooptional.get("files_optional", {})) == 0 # No optional files if no pattern assert len(content_optional["files_optional"]) > 0 assert len(site.content_manager.hashfield) == len(content_optional["files_optional"]) # Hashed optional files should be added to hashfield assert len(content_nooptional["files"]) > len(content_optional["files"]) def testFileInfo(self, site): assert "sha512" in site.content_manager.getFileInfo("index.html") assert site.content_manager.getFileInfo("data/img/domain.png")["content_inner_path"] == "content.json" assert site.content_manager.getFileInfo("data/users/hello.png")["content_inner_path"] == "data/users/content.json" assert site.content_manager.getFileInfo("data/users/content.json")["content_inner_path"] == "data/users/content.json" assert not site.content_manager.getFileInfo("notexist") # Optional file file_info_optional = site.content_manager.getFileInfo("data/optional.txt") assert "sha512" in file_info_optional assert file_info_optional["optional"] is True # Not exists yet user content.json assert "cert_signers" in site.content_manager.getFileInfo("data/users/unknown/content.json") # Optional user file file_info_optional = site.content_manager.getFileInfo("data/users/1CjfbrbwtP8Y2QjPy12vpTATkUT7oSiPQ9/peanut-butter-jelly-time.gif") assert "sha512" in file_info_optional assert file_info_optional["optional"] is True def testVerify(self, site): inner_path = "data/test_include/content.json" data_dict = site.storage.loadJson(inner_path) data = StringIO(json.dumps(data_dict)) # Re-sign data_dict["signs"] = { "1TeSTvb4w2PWE81S2rEELgmX2GCCExQGT": CryptBitcoin.sign(json.dumps(data_dict, sort_keys=True), self.privatekey) } assert sit
e.content_manager.verifyFile(inner_path, data, ignore_same=False)
# Wrong address data_dict["address"] = "Othersite" del data_dict["signs"] data_dict["signs"] = { "1TeSTvb4w2PWE81S2rEELgmX2GCCExQGT": CryptBitcoin.sign(json.dumps(data_dict, sort_keys=True), self.privatekey) } data = StringIO(json.dumps(data_dict)) with pytest.raises(VerifyError) as err: site.content_manager.verifyFile(inner_path, data, ignore_same=False) assert "Wrong site address" in str(err) # Wrong inner_path data_dict["address"] = "1TeSTvb4w2PWE81S2rEELgmX2GCCExQGT" data_dict["inner_path"] = "content.json" del data_dict["signs"] data_dict["signs"] = { "1TeSTvb4w2PWE81S2rEELgmX2GCCExQGT": CryptBitcoin.sign(json.dumps(data_dict, sort_keys=True), self.privatekey) } data = StringIO(json.dumps(data_dict)) with pytest.raises(VerifyError) as err: site.content_manager.verifyFile(inner_path, data, ignore_same=False) assert "Wrong inner_path" in str(err) # Everything right again data_dict["address"] = "1TeSTvb4w2PWE81S2rEELgmX2GCCExQGT" data_dict["inner_path"] = inner_path del data_dict["signs"] data_dict["signs"] = { "1TeSTvb4w2PWE81S2rEELgmX2GCCExQGT": CryptBitcoin.sign(json.dumps(data_dict, sort_keys=True), self.privatekey) } data = StringIO(json.dumps(data_dict)) assert site.content_manager.verifyFile(inner_path, data, ignore_same=False) def testVerifyInnerPath(self, site): inner_path = "content.json" data_dict = site.storage.loadJson(inner_path) for good_relative_path in ["data.json", "out/data.json", "Any File [by none] (1).jpg"]: data_dict["files"] = {good_relative_path: {"sha512": "369d4e780cc80504285f13774ca327fe725eed2d813aad229e62356b07365906", "size": 505}} if "sign" in data_dict: del data_dict["sign"] del data_dict["signs"] data_dict["signs"] = { "1TeSTvb4w2PWE81S2rEELgmX2GCCExQGT": CryptBitcoin.sign(json.dumps(data_dict, sort_keys=True), self.privatekey) } data = StringIO(json.dumps(data_dict)) assert site.content_manager.verifyFile(inner_path, data, ignore_same=False) for bad_relative_path in ["../data.json", "data/" * 100, "invalid|file.jpg"]: data_dict["files"] = {bad_relative_path: {"sha512": "369d4e780cc80504285f13774ca327fe725eed2d813aad229e62356b07365906", "size": 505}} if "sign" in data_dict: del data_dict["sign"] del data_dict["signs"] data_dict["signs"] = { "1TeSTvb4w2PWE81S2rEELgmX2GCCExQGT": CryptBitcoin.sign(json.dumps(data_dict, sort_keys=True), self.privatekey) } data = StringIO(json.dumps(data_dict)) with pytest.raises(VerifyError) as err: site.content_manager.verifyFile(inner_path, data, ignore_same=False) assert "Invalid relative path" in str(err) @pytest.mark.parametrize("key", ["ignore", "optional"]) def testSignUnsafePattern(self, site, key): site.content_manager.contents["content.json"][key] = "([a-zA-Z]+)*" with pytest.raises(UnsafePatternError) as err: site.content_manager.sign("content.json", privatekey=self.privatekey, filewrite=False) assert "Potentiall
# pylint: dis
able=missing-module-docstring, missing-class-docstring from __future__ import unicode_literals from django.conf import settings from django.db import migrations class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('rdrhc_calendar', '0013_auto_2
0171016_1915'), ] operations = [ migrations.RenameField( model_name='shift', old_name='user', new_name='sb_user', ), migrations.RenameField( model_name='shiftcode', old_name='user', new_name='sb_user', ), migrations.AlterUniqueTogether( name='shiftcode', unique_together=set([('code', 'sb_user', 'role')]), ), ]
from sdoc.sdoc1.data_type.DataType import DataType class StringDataType(DataType): """ Class for string data types. """ # ------------------------------------------------------------------------------------------------------------------ def __init__(self, value: str): """ Object constructor. :param str value: The value of this string constant. """ self._value: str = value """ The value of this constant integer. """ # ------------------------------------------------------------------------------------------------------------------ def debug(self, indent: int = 0) -> str: """ Returns a string for debugging. :param int indent: Unused. """ return "'" + self._value + "'" # ------------------------------------------------------------------------------------------------------------------ def dereference(self): """ Returns a clone of this string. :rtype: sdoc.sdoc1.data_type.StringDataType.StringDataType """ return StringDataType(self._value) # ------------------------------------------------------------------------------------------------------------------ def get_value(self) -> str: """ Returns the underling value of this data type. """ return self._value # ------------------------------------------------------
------------------------------------------------------------ def get_type_id(self) -> int: """ Returns the ID of this data type. """ return DataType.STRING # ------------------------------------------------------------------------------------------------------------------ def is_constant(self) -> bool: """ Returns False always. """ return False # -
----------------------------------------------------------------------------------------------------------------- def is_defined(self) -> bool: """ Returns True always. """ return True # ------------------------------------------------------------------------------------------------------------------ def is_scalar(self) -> bool: """ Returns True always. """ return True # ------------------------------------------------------------------------------------------------------------------ def is_true(self) -> bool: """ Returns True if this string is not empty. Returns False otherwise. """ return self._value != '' # ------------------------------------------------------------------------------------------------------------------ def __str__(self) -> str: """ Returns the string representation of the string constant. """ return self._value # ----------------------------------------------------------------------------------------------------------------------
import pytest from mitmproxy.addons import intercept from mitmproxy import exceptions from mitmproxy.test import taddons from mitmproxy.test import tflow @pytest.mark.asyncio async def test_simple(): r = intercept.Intercept() with taddons.context(r) as tctx: assert not r.filt tctx.configure(r, intercept="~q") assert r.filt assert tctx.options.intercept_active with pytest.raises(exceptions.OptionsError): tctx.configure(r, intercept="~~") tctx.configure(r, intercept=None) assert not r.filt assert not tctx.options.intercept_active tctx.configure(r, intercept="~s") f = tflow.tflow(resp=True) await tctx.cycle(r, f) assert f.intercepted f = tflow.tflow(resp=False) await tctx.cycle(r, f) assert not f.intercepted f = tflow.tflow(resp=True) r.response(f) assert f.intercepted tctx.configure(r, intercept_active=False) f = tflow.tflow(resp=True) await tctx.cycle(r, f) assert not f.intercepted tctx.configure(r, intercept_active=True) f = tflow.tflow(resp=True) await tctx.cycle(r, f) assert f.intercepted @pytest.mark.asyncio async def test_tcp(): r = intercept.Intercept() with taddons.context(r) as tctx: tctx.configure(r, intercept="~tcp") f = tflow.ttcpflow()
await tctx.cycle(r, f) asser
t f.intercepted tctx.configure(r, intercept_active=False) f = tflow.ttcpflow() await tctx.cycle(r, f) assert not f.intercepted
""" ============== Non-linear SVM ============== Perform binary classification using non-linear SVC with RBF kernel. The target to predict is a XOR of the inputs. The color map illustrates the decision function learned by the SVC. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import svm xx, yy = np.meshgrid(np.linspace(-3, 3, 500), np.linspace(-3, 3, 500)) np.random.seed(0) X = np.random.randn(300, 2) Y = np.logical_xor(X[:, 0] > 0, X[:, 1] > 0) # fit the model clf = svm.NuSVC(gamma='auto') clf.fit(X, Y) # plot the decision function for each datapoint on the grid Z = clf.decision_function(np.c_[xx.ravel(),
yy.ravel()]) Z = Z.reshape(xx.shape) plt.imshow(Z, interpolation='nearest', extent=(xx.min(), xx.max(), yy.min(), yy.max()), aspect='auto', origin='lower', cmap=plt.cm.PuOr_r) contours = plt.contour(xx, yy, Z, levels=[0], linewidths=2, linestyles='dashed') plt.scatter(X[:, 0
], X[:, 1], s=30, c=Y, cmap=plt.cm.Paired, edgecolors='k') plt.xticks(()) plt.yticks(()) plt.axis([-3, 3, -3, 3]) plt.show()
from geonode.maps.models import MapLayer return MapLayer.objects.filter(name=self.typename) @property def class_name(self): return self.__class__.__name__ class Layer_Styles(models.Model): layer = models.ForeignKey(Layer) style = models.ForeignKey(Style) class AttributeManager(models.Manager): """Helper class to access filtered attributes """ def visible(self): return self.get_query_set().filter(visible=True).order_by('display_order') class Attribute(models.Model): """ Auxiliary model for storing layer attributes. This helps reduce the need for runtime lookups to GeoServer, and lets users customize attribute titles, sort order, and visibility. """ layer = models.ForeignKey(Layer, blank=False, null=False, unique=False, related_name='attribute_set') attribute = models.CharField(_('attribute name'), help_text=_('name of attribute as stored in shapefile/spatial database'), max_length=255, blank=False, null=True, unique=False) description = models.CharField(_('attribute description'), help_text=_('description of attribute to be used in metadata'), max_length=255, blank=True, null=True) attribute_label = models.CharField(_('attribute label'), help_text=_('title of attribute as displayed in GeoNode'), max_length=255, blank=False, null=True, unique=False) attribute_type = models.CharField(_('attribute type'), help_text=_('the data type of the attribute (integer, string, geometry, etc)'), max_length=50, blank=False, null=False, default='xsd:string', unique=False) visible = models.BooleanField(_('visible?'), help_text=_('specifies if the attribute should be displayed in identify results'), default=True) display_order = models.IntegerField(_('display order'), help_text=_('specifies the order in which attribute should be displayed in identify results'), default=1) # statistical derivations count = models.IntegerField(_('count'), help_text=_('count value for this field'), default=1) min = models.CharField(_('min'), help_text=_('minimum value for this field'), max_length=255, blank=False, null=True, unique=False, default='NA') max = models.CharField(_('max'), help_text=_('maximum value for this field'), max_length=255, blank=False, null=True, unique=False, default='NA') average = models.CharField(_('average'), help_text=_('average value for this field'), max_length=255, blank=False, null=True, unique=False, default='NA') median = models.CharField(_('median'), help_text=_('median value for this field'), max_length=255, blank=False, null=True, unique=False, default='NA') stddev = models.CharField(_('standard deviation'), help_text=_('standard deviation for this field'), max_length=255, blank=False, null=True, unique=False, default='NA') sum = models.CharField(_('sum'), help_text=_('sum value for this field'), max_length=255, blank=False, null=True, unique=False, default='NA') unique_values = models.TextField(_('unique values for this field'), null=True, blank=True, default='NA') last_stats_updated = models.DateTimeField(_('last modified'), default=datetime.now, help_text=_('date when attribute statistics were last updated')) # passing the method itself, not objects = AttributeManager() def __str__(self): return "%s" % self.attribute_label.encode("utf-8") if self.attribute_label else self.attribute.encode("utf-8") def unique_values_as_list(self): return self.unique_values.split(',') def geoserver_pre_delete(instance, sender, **kwargs): """Removes the layer from GeoServer """ ct = ContentType.objects.get_for_model(instance) OverallRating.objects.filter(content_type = ct, object_id = instance.id).delete() #cascading_delete should only be called if ogc_server_settings.BACKEND_WRITE_ENABLED == True if getattr(ogc_server_settings,"BACKEND_WRITE_ENABLED", True): cascading_delete(Layer.objects.gs_catalog, instance.typename) def pre_save_layer(instance, sender, **kwargs): if kwargs.get('raw', False): instance.owner = instance.resourcebase_ptr.owner instance.uuid = instance.resourcebase_ptr.uuid instance.bbox_x0 = instance.resourcebase_ptr.bbox_x0 instance.bbox_x1 = instance.resourcebase_ptr.bbox_x1 instance.bbox_y0 = instance.resourcebase_ptr.bbox_y0 instance.bbox_y1 = instance.resourcebase_ptr.bbox_y1 if instance.abstract == '' or instance.abstract is None: instance.abstract = 'No abstract provided' if instance.title == '' or instance.title is None: instance.title = instance.name def pre_delete_layer(instance, sender, **kwargs): """ Remove any associated style to the layer, if it is not used by other layers. Default style will be deleted in post_delete_layer """ logger.debug("Going to delete the styles associated for [%s]", instance.typename.encode('utf-8')) default_style = instance.default_style for style in instance.styles.all(): if style.layer_styles.all().count()==1: if style != default_style: style.delete() def post_delete_layer(instance, sender, **kwargs): """ Removed the layer from any associated map, if any. Remove the layer default style. """ from geonode.maps.models import MapLayer logger.debug("Going to delete associated maplayers for [%s]", instance.typename.encode('utf-8')) MapLayer.objects.filter(name=instance.typename).delete() logger.debug("Going to delete the default style for [%s]", instance.typename.encode('utf-8')) if instance.default_style and Layer.objects.filter(default_style__id=instance.default_style.id).count() == 0: instance.default_style.delete() def geoserver_pre_save(instance, sender, **kwargs): """Send information to geoserver. The attributes sent include: * Title * Abstract * Name * Keywords * Metadata Links, * Point of Contact name and url """ url = ogc_server_settings.internal_rest try: gs_catalog = Catalog(url, _user, _password) gs_resource = gs_catalog.get_resource(instance.name) except (EnvironmentError, FailedRequestError) as e: gs_resource = None msg = ('Could not connect to geoserver at "%s"' 'to save information for layer "%s"' % ( ogc_server_settings.LOCATION, instance.name.encode('utf-8')) ) logger.warn(msg, e) # If geoserver is not online, there is no need to continue return # If there is no resource returned it could mean one of two things: # a) There is a synchronization problem in geoserver # b) The unit tests are running and another geoserver is running in the # background. # For both cases it is sensible to stop processing the layer if gs_resource is None: logger.w
arn('Could not get geoserver resource for %s' % instance) return gs_resource.title = instance.title gs_resource.abstract = instance.abstract gs_resource.name= instance.name # Get metadata links metadata_links = [] for link in ins
tance.link_set.metadata(): metadata_links.append((link.name, link.mime, link.url)) gs_resource.metadata_links = metadata_links #gs_resource should only be called if ogc_server_settings.BACKEND_WRITE_ENABLED == True if getattr(ogc_server_settings,"BACKEND_WRITE_ENABLED", True): gs_catalog.save(gs_resource) gs_layer = gs_catalog.get_layer(instance.name) if instance.poc and instance.poc.user: gs_layer.attribution = str(instance.poc.user) profile = Profile.objects.get(user=instance.poc.user) gs_layer.attribution_link = settings.SITEURL[:-1] + profile.get_absolute_url() #gs_layer should only be called if ogc_server_settings.BACKEND_WRITE_ENABLED == True if getattr(ogc_server_settings,"BACKEND_WRITE_ENABLED", True): gs_catalog.save(gs_layer) """Get information from geoserver. The attributes retrieved include: * Bounding Box * SRID *
__author__ = 'tauren' from flask import abort from flask_restful import Resource from flask.ext.restful import fields, marshal, reqparse from flask_login import current_user from models import User, db user_fields = { 'username': fields.String, 'id':
fields.Integer, 'uri': fields.Url('user') } class UserApi(Resource):
def __init__(self): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('username', type=str, required=True, help='No username provided', location='json') self.reqparse.add_argument('password', type=str, required=True, help='No password provided', location='json') super(UserApi, self).__init__() def post(self): args = self.reqparse.parse_args() new_user = User(args['username'], args['password']) db.session.add(new_user) db.session.commit() return 201 def get(self): user = User.query.filter_by(id=current_user.id).all() if not user: return abort(404) return {'results': marshal(user, user_fields)}
from flask.ext.wtf import Form from wtforms import StringFie
ld, BooleanField, PasswordField, SelectField, DateTimeField, Tex
tAreaField
#!/usr/bin/python ''' Wrapper for the SRTM module (srtm.py) It will grab the altitude of a long,lat pair from the SRTM database Created by Stephen Dade (stephen_dade@hotmail.com) ''' import os import sys import time import numpy from MAVProxy.modules.mavproxy_map import srtm class ElevationModel(): '''Elevation Model. Only SRTM for now''' def __init__(self, database='srtm', offline=0): '''Use offline=1 to disable any downloading of tiles, regardless of whether the tile exists''' self.database = database if self.database == 'srtm': self.downloader = srtm.SRTMDownloader(offline=offline) self.downloader.loadFileList() self.tileDict = dict() '''Use the Geoscience Australia database instead - watch for the correct database path''' if self.database == 'geoscience': from MAVProxy.modules.mavproxy_map import GAreader self.mappy = GAreader.ERMap() self.mappy.read_ermapper(os.path.join(os.environ['HOME'], './Documents/Elevation/Canberra/GSNSW_P756demg')) def GetElevation(self, latitude, longitude, timeout=0): '''Returns the altitude (m ASL) of a given lat/long pair, or None if unknown''' if self.database == 'srtm': TileID = (numpy.floor(latitude), numpy.floor(longitude)) if TileID in self.tileDict: alt = self.tileDict[TileID].getAltitudeFromLatLon(latitude, longitude) else: tile = self.downloader.getTile(numpy.floor(latitude), numpy.floor(longitude)) if tile == 0: if timeout > 0: t0 = time.time() while time.time() < t0+timeout and tile == 0: tile = self.downloader.getTile(numpy.floor(latitude), numpy.floor(longitude)) if tile == 0: time.sleep(0.1) if tile == 0: return None self.tileDict[TileID] = tile alt = tile.getAltitudeFromLatLon(latitude, longitude) if self.database == 'geoscience': alt = self.mappy.getAltitudeAtPoint(latitude, longitude) return alt if __name__ == "__main__": from optparse import OptionParser parser = OptionParser("mp_elevation.py [options]") parser.add_option("--lat", type='float', default=-35.052544, help="start latitude") parser.add_option("--lon", type='float', default=149.509165, help="start longitude") parser.add_option("--database", type='string', default='srtm', help="elevation database") (opts, args) = parser.parse_args() EleModel = ElevationModel(opts.database) lat = opts.lat lon = opts.lon '''Do a few lat/long pairs to demonstrate the caching Note the +0.000001 to the time. On faster PCs, the two time periods may in fact be equal, so we add a little extra time on the end to account for this''' t0 = time.time() alt = EleModel.GetElevation(lat, lon, timeout=10) if alt is None: print("Tile not available") sys.exit(1) t1 = time.time()+.000001 print("Altitude at (%.6f, %.6f) is %u m. Pulled at %.1f FPS" % (lat, lon, alt, 1/(t1-t0))) lat = opts.lat+
0.001 lon = opts.lon+0.001 t0 = time.time() alt = EleModel.GetElevation(lat, lon, timeout=10) t1 = time.time()+.000001 print("Altitude at (%.6f, %.6f) is %u m. Pulled at %.1f FPS" % (lat, lon, alt, 1/(t1-t0))) lat = opts.la
t-0.001 lon = opts.lon-0.001 t0 = time.time() alt = EleModel.GetElevation(lat, lon, timeout=10) t1 = time.time()+.000001 print("Altitude at (%.6f, %.6f) is %u m. Pulled at %.1f FPS" % (lat, lon, alt, 1/(t1-t0)))
# Copyright (C) 2016 Nippon Telegraph and Telephone Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from base import * class Quagga(Container): CONTAINER_NAME = None GUEST_DIR = '/root/config' def __init__(self, host_dir, conf, image='bgperf/quagga'): super(Quagga, self).__init__(self.CONTAINER_NAME, image, host_dir, self.GUEST_DIR, conf) @classmethod def build_image(cls, force=False, tag='bgperf/quagga', checkout='HEAD', nocache=False): cls.dockerfile = ''' FROM ubuntu:latest WORKDIR /root RUN useradd -M quagga RUN mkdir /var/log/quagga && chown quagga:quagga /var/log/quagga RUN mkdir /var/run/quagga && chown quagga:quagga /var/run/quagga RUN apt-get update && apt-get install -qy git autoconf libtool gawk make telnet libreadline6-dev RUN git clone git://git.sv.gnu.org/quagga.git quagga RUN cd quagga && git checkout {0} && ./bootstrap.sh && \ ./configure --disable-doc --localstatedir=/var/run/quagga && make && make install RUN ldconfig '''.format(checkout) super(Quagga, cls).build_image(force, tag, nocache) class QuaggaTarget(Quagga, Target): CONTAINER_NAME = 'bgperf_quagga_target' CONFIG_FILE_NAME = 'bgpd.conf' def write_config(self, scenario_global_conf): config = """hostname bgpd password zebra router bgp {0} bgp router-id {1} """.format(self.conf['as'], self.conf['router-id']) def gen_neighbor_config(n): local_addr = n['local-address'] c = """neighbor {0} remote-as {1} neighbor {0} advertisement-interval 1 neighbor {0} route-server-client neighbor {0} timers 30 90 """.format(local_addr, n['as']) if 'filter' in n: for p in (n['filter']['in'] if 'in' in n['filter'] else []): c += 'neighbor {0} route-map {1} export\n'.format(local_addr, p) return c with open('{0}/{1}'.format(self.host_dir, self.CONFIG_FILE_NAME), 'w') as f: f.write(config) for n in list(flatten(t.get('neighbors', {}).values() for t in scenario_global_conf['testers'])) + [scenario_global_conf['monitor']]: f.write(gen_neighbor_config(n)) if 'policy' in scenario_global_conf: seq = 10 for k, v in scenario_global_conf['policy'].iteritems():
match_info = [] for i, match in enumerate(v['match']): n = '{0}_match_{1}'.format(k, i) if match['type'] == 'prefix': f.write(''.join('ip prefix-list {0} deny {1}\n'.format(n, p) for p in match['value'])) f.write('ip
prefix-list {0} permit any\n'.format(n)) elif match['type'] == 'as-path': f.write(''.join('ip as-path access-list {0} deny _{1}_\n'.format(n, p) for p in match['value'])) f.write('ip as-path access-list {0} permit .*\n'.format(n)) elif match['type'] == 'community': f.write(''.join('ip community-list standard {0} permit {1}\n'.format(n, p) for p in match['value'])) f.write('ip community-list standard {0} permit\n'.format(n)) elif match['type'] == 'ext-community': f.write(''.join('ip extcommunity-list standard {0} permit {1} {2}\n'.format(n, *p.split(':', 1)) for p in match['value'])) f.write('ip extcommunity-list standard {0} permit\n'.format(n)) match_info.append((match['type'], n)) f.write('route-map {0} permit {1}\n'.format(k, seq)) for info in match_info: if info[0] == 'prefix': f.write('match ip address prefix-list {0}\n'.format(info[1])) elif info[0] == 'as-path': f.write('match as-path {0}\n'.format(info[1])) elif info[0] == 'community': f.write('match community {0}\n'.format(info[1])) elif info[0] == 'ext-community': f.write('match extcommunity {0}\n'.format(info[1])) seq += 10 def get_startup_cmd(self): return '\n'.join( ['#!/bin/bash', 'ulimit -n 65536', 'bgpd -u root -f {guest_dir}/{config_file_name}'] ).format( guest_dir=self.guest_dir, config_file_name=self.CONFIG_FILE_NAME)
#!/usr/bin/env python3 # Copyright (c) 2009-2019 The Bitcoin Core developers # Copyright (c) 2014-2019 The DigiByte Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Check RPC argument consistency.""" from collections import defaultdict import os import re import sys # Source files (relative to root) to scan for dispatch tables SOURCES = [ "src/rpc/server.cpp", "src/rpc/blockchain.cpp", "src/rpc/mining.cpp", "src/rpc/misc.cpp", "src/rpc/net.cpp", "src/rpc/rawtransaction.cpp", "src/wallet/rpcwallet.cpp", ] # Source file (relative to root) containing conversion mapping SOURCE_CLIENT = 'src/rpc/client.cpp' # Argument names that should be ignored in consistency checks IGNORE_DUMMY_ARGS = {'dummy', 'arg0', 'arg1', 'arg2', 'arg3', 'arg4', 'arg5', 'arg6', 'arg7', 'arg8', 'arg9'} class RPCCommand: def __init__(self, name, args): self.name = name self.args = args class RPCArgument: def __init__(self, names, idx): self.names = names self.idx = idx self.convert = False def parse_string(s): assert s[0] == '"' assert s[-1] == '"' return s[1:-1] def process_commands(fname): """Find and parse dispatch table in implementation file `fname`.""" cmds = [] in_rpcs = False with open(fname, "r", encoding="utf8") as f: for line in f: line = line.rstrip() if not in_rpcs: if re.match("static const CRPCCommand .*\[\] =", line): in_rpcs = True else: if line.startswith('};'): in_rpcs = False elif '{' in line and '"' in line: m = re.search('{ *("[^"]*"), *("[^"]*"), *&([^,]*), *{([^}]*)} *},', line) assert m, 'No match to table expression: %s' % line name = parse_string(m.group(2)) args_str = m.group(4).strip() if args_str: args = [RPCArgument(parse_string(x.strip()).split('|'), idx) for idx, x in enumerate(args_str.split(','))] else: args = [] cmds.append(RPCCommand(name, args)) assert not in_rpcs and cmds, "Something went wrong with parsing the C++ file: update the regexps" return cmds def process_mapping(fname): """Find and parse conversion table in implementation
file `fname`.""" cmds = [] in_rpcs = False with open(fname, "r", encoding="utf8") as f: for line in f: line = line.rstrip() if not in_rpcs: if line == 'static const CRPCConvertParam vRPCConvertParams[] =': in_rpcs = True else: if line.startswith('};'):
in_rpcs = False elif '{' in line and '"' in line: m = re.search('{ *("[^"]*"), *([0-9]+) *, *("[^"]*") *},', line) assert m, 'No match to table expression: %s' % line name = parse_string(m.group(1)) idx = int(m.group(2)) argname = parse_string(m.group(3)) cmds.append((name, idx, argname)) assert not in_rpcs and cmds return cmds def main(): root = sys.argv[1] # Get all commands from dispatch tables cmds = [] for fname in SOURCES: cmds += process_commands(os.path.join(root, fname)) cmds_by_name = {} for cmd in cmds: cmds_by_name[cmd.name] = cmd # Get current convert mapping for client client = SOURCE_CLIENT mapping = set(process_mapping(os.path.join(root, client))) print('* Checking consistency between dispatch tables and vRPCConvertParams') # Check mapping consistency errors = 0 for (cmdname, argidx, argname) in mapping: try: rargnames = cmds_by_name[cmdname].args[argidx].names except IndexError: print('ERROR: %s argument %i (named %s in vRPCConvertParams) is not defined in dispatch table' % (cmdname, argidx, argname)) errors += 1 continue if argname not in rargnames: print('ERROR: %s argument %i is named %s in vRPCConvertParams but %s in dispatch table' % (cmdname, argidx, argname, rargnames), file=sys.stderr) errors += 1 # Check for conflicts in vRPCConvertParams conversion # All aliases for an argument must either be present in the # conversion table, or not. Anything in between means an oversight # and some aliases won't work. for cmd in cmds: for arg in cmd.args: convert = [((cmd.name, arg.idx, argname) in mapping) for argname in arg.names] if any(convert) != all(convert): print('ERROR: %s argument %s has conflicts in vRPCConvertParams conversion specifier %s' % (cmd.name, arg.names, convert)) errors += 1 arg.convert = all(convert) # Check for conversion difference by argument name. # It is preferable for API consistency that arguments with the same name # have the same conversion, so bin by argument name. all_methods_by_argname = defaultdict(list) converts_by_argname = defaultdict(list) for cmd in cmds: for arg in cmd.args: for argname in arg.names: all_methods_by_argname[argname].append(cmd.name) converts_by_argname[argname].append(arg.convert) for argname, convert in converts_by_argname.items(): if all(convert) != any(convert): if argname in IGNORE_DUMMY_ARGS: # these are testing or dummy, don't warn for them continue print('WARNING: conversion mismatch for argument named %s (%s)' % (argname, list(zip(all_methods_by_argname[argname], converts_by_argname[argname])))) sys.exit(errors > 0) if __name__ == '__main__': main()
offset'), and the __heap segment is # placed after all others. segment_ptr = {} ptr = offset if '__startup' in segment_size: segment_ptr['__startup'] = ptr ptr += segment_size['__startup'] for segment in sorted(segment_size): if segment not in ('__startup', '__heap'): segment_ptr[segment] = ptr ptr += segment_size[segment] if '__heap' in segment_size: segment_ptr['__heap'] = ptr ptr += segment_size['__heap'] total_size = ptr - offset # Step 3: Create the segment map. For each segment in each # object, record the memory offset where it will be # mapped. segment_map = [] for obj in object_files: obj_segment_map = {} for segment in obj.seg_data: obj_segment_map[segment] = segment_ptr[segment] segment_ptr[segment] += len(obj.seg_data[segment]) segment_map.append(obj_segment_map) return segment_map, total_size def _collect_exports(self, object_files): """ Collects the exported symbols from all the objects. Verifies that exported symbols are unique and notifies of collisions. The returned data structure is a dict mapping export symbol names to a pair: (object_index, addr) where object_index is the index in object_files of the object that exports this symbol, and addr is the address of the symbol (SegAddr) taken from the export table of that object. """ exports = {} for idx, obj in enumerate(object_files): for export in obj.export_table: sym_name = export.export_symbol if sym_name in exports: other_idx = exports[sym_name][0] self._linker_error( "Duplicated export symbol '%s' at objects [%s] and [%s]" % ( sym_name, self._object_id(object_files[idx]), self._object_id(object_files[other_idx]))) exports[sym_name] = (idx, export.addr) return exports def _resolve_relocations(self, object_files, segment_map): """ Resolves the relocations in object files according to their relocation tables and the updated segment_map information. """ # Look at the relocation tables of all objects # for idx, obj in enumerate(object_files): for reloc_seg, type, addr in obj.reloc_table: # The requested relocation segment should exist # in the segment map for this object. # if not reloc_seg in segment_map[idx]: self._linker_error("Relocation entry in object [%t] refers to unknown segment %s" % ( self._object_id(obj), reloc_seg)) # This is where the relocated segment was mapped # mapped_address = segment_map[idx][reloc_seg] # Patch the instruction asking for relocation with # the mapped address of the requested segment. # self._patch_segment_data( seg_data=obj.seg_data[addr.segment], instr_offset=addr.offset, type=type, mapped_address=mapped_address, name=reloc_seg) def _resolve_imports(self, object_files, segment_map, exports): """ Resolves the imports in object files according to the exported symbols collected in exports and the mapping of segments into memory (segment_map). """ # Look at the import tables of all objects # for idx, obj in enumerate(object_files): import_table = object_files[idx].import_table # All imported symbols # for sym, import_type, import_addr in import_table: # Make sure this symbol was indeed exported by # some object # if not sym in exports: self._linker_error("Failed import of symbol '%s' at object [%s]" % ( sym, self._object_id(obj))) exp_obj_idx, exp_address = exports[sym] # From the export table, build the final mapped # address of this symbol. # It is the mapped value of the segment in which # this symbol is located, plus its offset in that # segment. # mapped_address = segment_map[exp_obj_idx][exp_address.segment] mapped_address += exp_address.offset # Now patch the segment data of this object. # The instruction(s) to patch and the patch type # are taken from the import table, and the address # to insert is the mapped_address computed from # the matching exported symbol. # self._patch_segment_data( seg_data=obj.seg_data[import_addr.segment], instr_offset=import_addr.offset, type=import_type, mapped_address=mapped_address, name=sym) def _patch_segment_data(self, seg_data, instr_offset, type, mapped_address, name='<unknown>'): """ Performs a patch of segment data. seg_data: The segment data of the relevant segment instr_offset: Offset of the instruction that is to be patched in the segment. type: Patch type (one of types listed in ImportType or RelocType) mapped_address: The address that will be patched into the instruction(s). name: Symbol/segment name used for debugging The segment data is modified as a result of this call. """ if instr_offset > len(seg_data) - 4: self._linker_error("Patching (%s) of '%s', bad offset into segment" % ( type, name)) # At the moment only CALL and LI patches are supported # patch_call = type in (ImportType.CALL, RelocType.CALL) # For import patc
hes, the address stored in the # instruction is replaced with the mapped address. # For reloc patches, the two addresses are added # do_replace = type in (ImportType.CALL, ImportType.LI) if patch_call: orig_instr_bytes = seg_data[instr_offset:instr_offset+4] orig_instr_word = bytes2word(orig_instr_bytes) # Break the instruction into opcode and destination
# address. Make sure it's indeed a CALL # opcode = extract_opcode(orig_instr_word) if opcode != OP_CALL: self._linker_error("Patching (%s) of '%s': expected CALL, got %d" % ( type, name, opcode)) # CALL destinations are in words # mapped_address //= 4 # Patch the address # if do_replace: destination = mapped_address else: destination = extract_bitfield(orig_instr_word, 25, 0) destination += mapped_address if not num_fits_in_nbits(destination, 26): self._linker_error("Patching (%s) of '%s': patched destination address %x too large" % ( type, name, destination)) # Build the new instruction and shove it back into # the segment data # new_instr_bytes = word2bytes( build_bitfield(31, 26, opcode) | build_bitfield(25, 0, destination)) seg_data[instr_offset:i
#!/usr/bin/env python """Distutils installer for extras.""" from setuptools import setup import os.path import extras testtools_cmd = extras.try_import('testtools.TestCommand') def get_version(): """Return the version of extras that we are building.""" version = '.'.join( str(component) for component in extras.__version__[0:3]) return version def get_long_description(): readme_path = os.path.join( os.path.dirname(__file__), 'README.rst') return open(readme_path).read() cmdclass = {} if testtools_cmd is not None: cmdclass['test'] = testtools_cmd setup(name='extras', author='Testing cabal', author
_email='testtools-dev@lists.launchpad.net', url='https://github.com/testing-cabal/extras', description=('Useful extra bits for Python - things that shold be ' 'in the standard library'), long_
description=get_long_description(), version=get_version(), classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", ], packages=[ 'extras', 'extras.tests', ], cmdclass=cmdclass)
it'] == 1000000) assert('weightlimit' not in tmpl) assert(tmpl['sigoplimit'] == 20000) assert(tmpl['transactions'][0]['hash'] == txid) assert(tmpl['transactions'][0]['sigops'] == 2) tmpl = self.nodes[0].getblocktemplate({'rules':['segwit']}) assert(tmpl['sizelimit'] == 1000000) assert('weightlimit' not in tmpl) assert(tmpl['sigoplimit'] == 20000) assert(tmpl['transactions'][0]['hash'] == txid) assert(tmpl['transactions'][0]['sigops'] == 2) self.nodes[0].generate(1) #block 162 balance_presetup = self.nodes[0].getbalance() self.pubkey = [] p2sh_ids = [] # p2sh_ids[NODE][VER] is an array of txids that spend to a witness version VER pkscript to an address for NODE embedded in p2sh wit_ids = [] # wit_ids[NODE][VER] is an array of txids that spend to a witness version VER pkscript to an address for NODE via bare witness for i in range(3): newaddress = self.nodes[i].getnewaddress() self.pubkey.append(self.nodes[i].validateaddress(newaddress)["pubkey"]) multiaddress = self.nodes[i].addmultisigaddress(1, [self.pubkey[-1]]) multiscript = CScript([OP_1, hex_str_to_bytes(self.pubkey[-1]), OP_1, OP_CHECKMULTISIG]) p2sh_addr = self.nodes[i].addwitnessaddress(newaddress) bip173_addr = self.nodes[i].addwitnessaddress(newaddress, False) p2sh_ms_addr = self.nodes[i].addwitnessaddress(multiaddress) bip173_ms_addr = self.nodes[i].addwitnessaddress(multiaddress, False) assert_equal(p2sh_addr, key_to_p2sh_p2wpkh(self.pubkey[-1])) assert_equal(bip173_addr, key_to_p2wpkh(self.pubkey[-1])) assert_equal(p2sh_ms_addr, script_to_p2sh_p2wsh(multiscript)) assert_equal(bip173_ms_addr, script_to_p2wsh(multiscript)) p2sh_ids.append([]) wit_ids.append([]) for v in range(2): p2sh_ids[i].append([]) wit_ids[i].append([]) for i in range(5): for n in range(3): for v in range(2): wit_ids[n][v].append(send_to_witness(v, self.nodes[0], find_unspent(self.nodes[0], 50), self.pubkey[n], False, Decimal("49.999"))) p2sh_ids[n][v].append(send_to_witness(v, self.nodes[0], find_unspent(self.nodes[0], 50), self.pubkey[n], True, Decimal("49.999"))) self.nodes[0].generate(1) #block 163 sync_blocks(self.nodes) # Make sure all nodes recognize the transactions as theirs assert_equal(self.nodes[0].getbalance(), balance_presetup - 60*50 + 20*Decimal("49.999") + 50) assert_equal(self.nodes[1].getbalance(), 20*Decimal("49.999")) assert_equal(self.nodes[2].getbalance(), 20*Decimal("49.999")) self.nodes[0].generate(260) #block 423 sync_blocks(self.nodes) self.log.info("Verify default node can't accept any witness format txs before fork") # unsigned, no scriptsig self.fail_accept(self.nodes[0], "mandatory-script-verify-flag", wit_ids[NODE_0][WIT_V0][0], False) self.fail_accept(self.nodes[0], "mandatory-script-verify-flag", wit_ids[NODE_0][WIT_V1][0], False) self.fail_accept(self.nodes[0], "mandatory-script-verify-flag", p2sh_ids[NODE_0][WIT_V0][0], False) self.fail_accept(self.nodes[0], "mandatory-script-verify-flag", p2sh_ids[NODE_0][WIT_V1][0], False) # unsigned with redeem script self.fail_accept(self.nodes[0], "mandatory-script-verify-flag", p2sh_ids[NODE_0][WIT_V0][0], False, witness_script(False, self.pubkey[0])) self.fail_accept(self.nodes[0], "mandatory-script-verify-flag", p2sh_ids[NODE_0][WIT_V1][0], False, witness_script(True, self.pubkey[0])) # signed self.fail_accept(self.nodes[0], "no-witness-yet", wit_ids[NODE_0][WIT_V0][0], True) self.fail_accept(self.nodes[0], "no-witness-yet", wit_ids[NODE_0][WIT_V1][0], True) self.fail_accept(self.nodes[0], "no-witness-yet", p2sh_ids[NODE_0][WIT_V0][0], True) self.fail_accept(self.nodes[0], "no-witness-yet", p2sh_ids[NODE_0][WIT_V1][0], True) self.log.info("Verify witness txs are skipped for mining before the fork") self.skip_mine(self.nodes[2], wit_ids[NODE_2][WIT_V0][0], True) #block 424 self.skip_mine(self.nodes[2], wit_ids[NODE_2][WIT_V1][0], True) #block 425 self.skip_mine(self.nodes[2], p2sh_ids[NODE_2][WIT_V0][0], True) #block 426 self.skip_mine(self.nodes[2], p2sh_ids[NODE_2][WIT_V1][0], True) #block 427 # TODO: An old node would see these txs without witnesses and be able to mine them self.log.info("Verify unsigned bare witness txs in versionbits-setting blocks are valid before the fork") self.success_mine(self.nodes[2], wit_ids[NODE_2][WIT_V0][1], False) #block 428 self.success_mine(self.nodes[2], wit_ids[NODE_2][WIT_V1][1], False) #block 429 self.log.info("Verify unsigned p2sh witness txs without a redeem script are invalid") self.fail_accept(self.nodes[2], "mandatory-script-verify-flag", p2sh_ids[NODE_2][WIT_V0][1], False) self.fail_accept(self.nodes[2], "mandatory-script-verify-flag", p2sh_ids[NODE_2][WIT_V1][1], False) self.log.info("Verify unsigned p2sh witness txs with a redeem script in versionbits-settings blocks are valid before the fork") self.success_mine(self.nodes[2], p2sh_ids[NODE_2][WIT_V0][1], False, witness_script(False, self.pubkey[2])) #block 430 self.success_mine(self.nodes[2], p2sh_ids[NODE_2][WIT_V1][1], False, witness_script(True, self.pubkey[2])) #block 431 self.log.info("Verify previous witness txs skipped for mining can now be mined") assert_equal(len(self.nodes[2].getrawmempool()), 4) block = self.nodes[2].generate(1) #block 432 (first block with new rules; 432 = 144 * 3) sync_blocks(self.nodes) assert_equal(len(self.nodes[2].getrawmempool()), 0) segwit_tx_list = self.nodes[2].getblock(block[0])["tx"] assert_equal(len(segwit_tx_list), 5) self.log.info("Verify block and transaction serialization rpcs return differing serializations depending on rpc serialization flag") assert(self.nodes[2].getblock(block[0], False) != self.nodes[0].getblock(block[0], False)) assert(self.nodes[1].getblock(block[0], False) == self.nodes[2].getblock(block[0], False
)) for i in range(len(segwit_tx_list)): tx = FromHex(CTransaction(), self.nodes[2].gettransaction(segwit_tx_list[i
])["hex"]) assert(self.nodes[2].getrawtransaction(segwit_tx_list[i]) != self.nodes[0].getrawtransaction(segwit_tx_list[i])) assert(self.nodes[1].getrawtransaction(segwit_tx_list[i], 0) == self.nodes[2].getrawtransaction(segwit_tx_list[i])) assert(self.nodes[0].getrawtransaction(segwit_tx_list[i]) != self.nodes[2].gettransaction(segwit_tx_list[i])["hex"]) assert(self.nodes[1].getrawtransaction(segwit_tx_list[i]) == self.nodes[2].gettransaction(segwit_tx_list[i])["hex"]) assert(self.nodes[0].getrawtransaction(segwit_tx_list[i]) == bytes_to_hex_str(tx.serialize_without_witness())) self.log.info("Verify witness txs without witness data are invalid after the fork") self.fail_mine(self.nodes[2], wit_ids[NODE_2][WIT_V0][2], False) self.fail_mine(self.nodes[2], wit_ids[NODE_2][WIT_V1][2], False) self.fail_mine(self.nodes[2], p2sh_ids[NODE_2][WIT_V0][2], False, witness_script(False, self.pubkey[2])) self.fail_mine(self.nodes[2], p2sh_ids[NODE_2][WIT_V1][2], False, witness_script(True, self.pubkey[2])) self.log.info("Verify default node can now use witness txs") self.success_mine(self.nodes[0], wit_ids[NODE_0][WIT_V0][0], True) #block 432 self.success_mine(self.nodes[0], wit_ids[NODE_0][WIT_V1][0], True) #block 433 self.success_mine(self.nodes[0], p2sh_ids[NODE_0][WIT_V0][0], True) #block 434 self.success_mine(self.nodes[0], p2sh_ids[NODE_0][WIT_V1][0], True) #block 435 self.log.info("Verify sigops
"""Yelp API setup and random business selection function""" import io import json import random from yelp.client import Client from yelp.oauth1_authenticator import Oauth1Authenticator with io.open('config_yelp_secret.json') as cred: creds = json.load(cred) auth = Oauth1Authenticator(**creds) yelp_client = Client(auth) group_activity = ['arcades', 'amusementparks', 'lasertag', 'rock_climbing', 'gokarts', 'escapegames', 'mini_golf', 'trampoline', 'zoos', 'bowling', 'galleries'] fitness_activity = ['yoga', 'pilates', 'hiking', 'cyclingclasses'] relax_activity = ['spas', 'hair', 'skincare', 'othersalons', 'massage', 'outlet_stores', 'shoppingcenters', 'massage_therapy', 'acupuncture', 'ayurveda', 'chiropractors', 'venues', 'galleries', 'landmarks', 'gardens', 'museums', 'paintandsip', 'beaches'] night_activity = ['cabaret', 'movietheaters', 'musicvenues', 'opera', 'theater', 'co
cktailbars', 'lounges', 'sportsbars', 'wine_bar', 'poolhalls', 'pianobars', 'karaoke', 'jazzandblues', 'danceclubs'] eat_activity = ['wineries', 'farmersmarket', 'cafes', 'bakeries', '
bubbletea', 'coffee', 'restaurants','beer_and_wine', 'icecream', 'gourmet', 'juicebars', 'asianfusion', 'japanese', 'seafood', 'breweries'] def yelp_random_pick(event, city): """Generate a top business pick for user.""" if event == 'food': category_filter = random.choice(eat_activity) elif event == 'friends': category_filter = random.choice(group_activity) elif event == 'relax': category_filter = random.choice(relax_activity) elif event == 'nightlife': category_filter = random.choice(night_activity) elif event == 'fitness': category_filter = random.choice(fitness_activity) params = { 'sort': 2, 'category_filter': category_filter } response = yelp_client.search(city, **params) biz = response.businesses[0] return biz
rsion 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from selenium.webdriver.common.by import By from selenium.common.exceptions import NoSuchElementException, UnexpectedTagNameException class Select: def __init__(self, webelement): """ Constructor. A check is made that the given element is, indeed, a SELECT tag. If it is not, then an UnexpectedTagNameException is thrown. :Args: - webelement - element SELECT element to wrap Example: from selenium.webdriver.support.ui import Select \n Select(driver.find_element_by_tag_name("select")).select_by_index(2) """ if webelement.tag_name.lower() != "select": raise UnexpectedTagNameException( "Select only works on <select> elements, not on <%s>" % webelement.tag_name) self._el = webelement multi = self._el.get_attribute("multiple") self.is_multiple = multi and multi != "false" @property def options(self): """Returns a list of all options belonging to this select tag""" return self._el.find_elements(By.TAG_NAME, 'option') @property def all_selected_options(self): """Returns a list of all selected options belonging to this select tag""" ret = [] for opt in self.options: if opt.is_selected(): ret.append(opt) return ret @property def first_selected_option(self): """The first selected option in this select tag (or the currently selected option in a normal select)""" for opt in self.options: if opt.is_selected(): return opt raise NoSuchElementException("No options are selected") def select_by_value(self, value): """Select all options that have a value matching the argument. That is, when given "foo" this would select an option like: <option value="foo">Bar</option> :Args: - value - The value to match against throws NoSuchElementException If there is no option with specisied value in SELECT """ css = "option[value =%s]" % self._escapeString(value) opts = self._el.find_elements(By.CSS_SELECTOR, css) matched = False for opt in opts: self._setSelected(opt) if not self.is_multiple: return matched = True if not matched: raise NoSuchElementException("Cannot locate option with value: %s" % value) def select_by_index(self, index): """Select the option at the given index. This is done by examing the "index" attribute of an element, and not merely by counting. :Args: - index - The option at this index will be selected throws NoSuchElementException If there is no option with specisied index in SELECT """ match = str(index) for opt in self.options: if opt.get_attribute("index") == match: self._setSelected(opt) return raise NoSuchElementException("Could not locate element with index %d" % index) def select_by_visible_text(self, text): """Select all options that display text matching the argument. That is, when given "Bar" this would select an option like: <option value="foo">Bar</option> :Args: - text - The visible text to match against throws NoSuchElementException If there is no option with specisied text in SELECT """ xpath = ".//option[normalize-space(.) = %s]" % self._escapeString(text) opts = self._el.find_elements(By.XPATH, xpath) matched = False for opt in opts: self._setSelected(opt) if not self.is_multiple: return matched = True if len(opts) == 0 and " " in text: subStringWithoutSpace = self._get_longest_token(text) if subStringWithoutSpace == "": candidates = self.options else: xpath = ".//option[contains(.,%s)]" % self._escapeString(subStringWithoutSpace) candidates = self._el.find_elements(By.XPATH, xpath) for candidate in candidates: if text == candidate.text: self._setSelected(candidate) if not self.is_multiple: return matched = True if not matched: raise NoSuchElementException("Could not locate element with visible text: %s" % text) def deselect_all(self): """Clear all selected entries. This is only valid when t
he SELECT supports multiple selections. throws NotImplementedError If the SELECT does not support multiple selections """ if not self.is_multiple: raise NotImplementedError("You may only deselect all options of a multi-select") for opt in self.options: self._unsetSelected(opt) def deselect_by_value(self, value): """Deselect all options that have a value matching the argument. That is, when
given "foo" this would deselect an option like: <option value="foo">Bar</option> :Args: - value - The value to match against throws NoSuchElementException If there is no option with specisied value in SELECT """ if not self.is_multiple: raise NotImplementedError("You may only deselect options of a multi-select") matched = False css = "option[value = %s]" % self._escapeString(value) opts = self._el.find_elements(By.CSS_SELECTOR, css) for opt in opts: self._unsetSelected(opt) matched = True if not matched: raise NoSuchElementException("Could not locate element with value: %s" % value) def deselect_by_index(self, index): """Deselect the option at the given index. This is done by examing the "index" attribute of an element, and not merely by counting. :Args: - index - The option at this index will be deselected throws NoSuchElementException If there is no option with specisied index in SELECT """ if not self.is_multiple: raise NotImplementedError("You may only deselect options of a multi-select") for opt in self.options: if opt.get_attribute("index") == str(index): self._unsetSelected(opt) return raise NoSuchElementException("Could not locate element with index %d" % index) def deselect_by_visible_text(self, text): """Deselect all options that display text matching the argument. That is, when given "Bar" this would deselect an option like: <option value="foo">Bar</option> :Args: - text - The visible text to match against """ if not self.is_multiple: raise NotImplementedError("You may only deselect options of a multi-select") matched = False xpath = ".//option[normalize-space(.) = %s]" % self._escapeString(text) opts = self._el.find_elements(By.XPATH, xpath) for opt in opts: self._unsetSelected(opt) matched = True if not matched: raise NoSuchElementException("Could not locate element with visible text: %s" % text) def _setSelected(self, option): if not option.is_selected(): option.click() def _unsetSelected(self, option): if option.is_se
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from __future__ import unicode_literals from ..minc import Voliso def test_Voliso_inputs(): input_map = dict(args=dict(argstr='%s', ), avgstep=dict(argstr='--avgstep', ), clobber=dict(argstr='--clobber', usedefault=True, ), environ=dict(nohash=True, usedefault=True, ), ignore_exception=dict(nohash=True, usedefault=True, ), input_file=dict(argstr='%s',
mandatory=True, position=-2, ), maxstep=dict(argstr='--maxstep %s', ), minstep=dict(argstr='--minstep %s', ), output_file=dict(argstr='%s', genfile=True, hash_files=False, name_source=['input_file'], name_template='%s_voliso.mnc', position=-1, ), terminal_output=dict(deprecated='1.0.0', nohash=True, ), verbose=dict(argstr='--verbose', ),
) inputs = Voliso.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value def test_Voliso_outputs(): output_map = dict(output_file=dict(), ) outputs = Voliso.output_spec() for key, metadata in list(output_map.items()): for metakey, value in list(metadata.items()): assert getattr(outputs.traits()[key], metakey) == value
_source_fields()[0].geography and self.srid == 4326 def convert_value(self, value, expression, connection, context): if value is None: return None geo_field = GeometryField(srid=self.srid) # Fake field to get SRID info if geo_field.geodetic(connection): dist_att = 'm' else: units = geo_field.units_name(connection) if units: dist_att = DistanceMeasure.unit_attname(units) else: dist_att = None if dist_att: return DistanceMeasure(**{dist_att: value}) return value class Distance(DistanceResultMixin, OracleToleranceMixin, GeoFuncWithGeoParam): output_field_class = FloatField spheroid = None def __init__(self, expr1, expr2, spheroid=None, **extra): expressions = [expr1, expr2] if spheroid is not None: self.spheroid = spheroid expressions += (self._handle_param(spheroid, 'spheroid', bool),) super(Distance, self).__init__(*expressions, **extra) def as_postgresql(self, compiler, connection): geo_field = GeometryField(srid=self.srid) # Fake field to get SRID info if self.source_is_geography(): # Set parameters as geography if base field is geography for pos, expr in enumerate( self.source_expressions[self.geom_param_pos + 1:], start=self.geom_param_pos + 1): if isinstance(expr, GeomValue): expr.geography = True elif geo_field.geodetic(connection): # Geometry fields with geodetic (lon/lat) coordinates need special distance functions if self.spheroid: self.function = 'ST_Distance_Spheroid' # More accurate, resource intensive # Replace boolean param by the real spheroid of the base field self.source_expressions[2] = Value(geo_field._spheroid) else: self.function = 'ST_Distance_Sphere' return super(Distance, self).as_sql(compiler, connection) def as_oracle(self, compiler, connection): if self.spheroid: self.source_expressions.pop(2) return super(Distance, self).as_oracle(compiler, connection) class Envelope(GeoFunc): arity = 1 class ForceRHR(GeoFunc): arity = 1 class GeoHash(GeoFunc): output_field_class = TextField def __init__(self, expression, precision=None, **extra): expressions = [expression] if precision is not None: expressions.append(self._handle_param(precision, 'precision', six.integer_types)) super(GeoHash, self).__init__(*expressions, **extra) class Intersection(OracleToleranceMixin, GeoFuncWithGeoParam): arity = 2 class Length(DistanceResultMixin, OracleToleranceMixin, GeoFunc): output_field_class = FloatField def __init__(self, expr1, spheroid=True, **extra): self.spheroid = spheroid super(Length, self).__init__(expr1, **extra) def as_sql(self, compiler, connection): geo_field = GeometryField(srid=self.srid) # Fake field to get SRID info if geo_field.geodetic(connection) and not connection.features.supports_length_geodetic: raise NotImplementedError("This backend doesn't support Length on geodetic fields") return super(Length, self).as_sql(compiler, connection) def as_postgresql(self, compiler, connection): geo_field = GeometryField(srid=self.srid) # Fake field to get SRID info if self.source_is_geography(): self.source_expressions.append(Value(self.spheroid)) elif geo_field.geodetic(connection): # Geometry fields with geodetic (lon/lat) coordinates need length_spheroid self.function = 'ST_Length_Spheroid' self.source_expressions.append(Value(geo_field._spheroid)) else: dim = min(f.dim for f in self.get_source_fields() if f) if dim > 2: self.function = connection.ops.length3d return super(Length, self).as_sql(compiler, connection) def as_sqlite(self, compiler, connection): geo_field = GeometryField(srid=self.srid) if geo_field.geodetic(connection): if self.spheroid: self.function = 'GeodesicLength' else: self.function = 'GreatCircleLength' return super(Length, self).as_sql(compiler, connection) class MemSize(GeoFunc): output_field_class = IntegerField arity = 1 class NumGeometries(GeoFunc): output_field_class = IntegerField arity = 1 class NumPoints(GeoFunc): output_field_class = IntegerField arity = 1 def as_sqlite(self, compiler, connection): if self.source_expressions[self.geom_param_pos].output_field.geom_type != 'LINESTRING': raise TypeError("Spatialite NumPoints can only operate on LineString content") return super(NumPoints, self).as_sql(compiler, connection) class Perimeter(DistanceResultMixin, OracleToleranceMixin, GeoFunc): output_field_class = FloatField arity = 1 def as_postgresql(self, compiler, connection): geo_field = GeometryField(srid=self.srid) # Fake field to get SRID info if geo_field.geodetic(connection) and not self.source_is_geography(): raise NotImplementedError("ST_Perimeter cannot use a non-projected non-geography field.") dim = min(f.dim for f in self.get_source_fields()) if dim > 2: self.function = connection.ops.perimeter3d return super(Perimeter, self).as_sql(compiler, connection) def as_sqlite(self, compiler, connection): geo_field = GeometryField(srid=self.srid) # Fake field to get SRID info if geo_field.geodetic(connection): raise NotImplementedError("Perimeter cannot use a non-projected field.
") return super(Perimeter, self).as_sql(compiler, connection) class PointOnSurface(OracleToleranceMixin, GeoFunc): arity = 1 class Reverse(GeoFunc): arity = 1 class Scale(SQLiteDecimalToFloatMixin, GeoFunc): def __init__(self, expression, x, y,
z=0.0, **extra): expressions = [ expression, self._handle_param(x, 'x', NUMERIC_TYPES), self._handle_param(y, 'y', NUMERIC_TYPES), ] if z != 0.0: expressions.append(self._handle_param(z, 'z', NUMERIC_TYPES)) super(Scale, self).__init__(*expressions, **extra) class SnapToGrid(SQLiteDecimalToFloatMixin, GeoFunc): def __init__(self, expression, *args, **extra): nargs = len(args) expressions = [expression] if nargs in (1, 2): expressions.extend( [self._handle_param(arg, '', NUMERIC_TYPES) for arg in args] ) elif nargs == 4: # Reverse origin and size param ordering expressions.extend( [self._handle_param(arg, '', NUMERIC_TYPES) for arg in args[2:]] ) expressions.extend( [self._handle_param(arg, '', NUMERIC_TYPES) for arg in args[0:2]] ) else: raise ValueError('Must provide 1, 2, or 4 arguments to `SnapToGrid`.') super(SnapToGrid, self).__init__(*expressions, **extra) class SymDifference(OracleToleranceMixin, GeoFuncWithGeoParam): arity = 2 class Transform(GeoFunc): def __init__(self, expression, srid, **extra): expressions = [ expression, self._handle_param(srid, 'srid', six.integer_types), ] super(Transform, self).__init__(*expressions, **extra) @property def srid(self): # Make srid the resulting srid of the transformation return self.source_expressions[self.geom_param_pos + 1].value def convert_value(self, value, expression, connection, context): value = super(Transform, self).con
), # New line ( "rco2r", lambda data: [0.0] * data["mco2r"], "path length in cm of radial CO2 density chord", ), # read(neqdsk, 1040)(dco2r(jj, k), k = 1, mco2r) (None, None, None), # New line ( "dco2r", lambda data: [0.0] * data["mco2r"], "line average electron density in cm3 from radial CO2 chord", ), (None, None, None), # New line ("shearb", 0.0, ""), ( "bpolav", 1.0, "average poloidal magnetic field in Tesla defined through Ampere's law", ), ("s1", 0.0, "Shafranov boundary line integrals"), ("s2", 0.0, "Shafranov boundary line integrals"), ("s3", 0.0, "Shafranov boundary line integrals"), ("qout", 0.0, "q at plasma boundary"), ("olefs", 0.0, ""), ("orighs", 0.0, "outer gap of external second separatrix in cm"), ("otops", 0.0, "top gap of external second separatrix in cm"), ("sibdry", 1.0, ""), ("areao", 100.0, "cross sectional area in cm2"), ("wplasm", 0.0, ""), ("terror", 0.0, "equilibrium convergence error"), ("elongm", 0.0, "elongation at magnetic axis"), ("qqmagx", 0.0, "axial safety factor q(0)"), ("cdflux", 0.0, "computed diamagnetic flux in Volt-sec"), ("alpha", 0.0, "Shafranov boundary line integral parameter"), ("rttt", 0.0, "Shafranov boundary line integral parameter"), ("psiref", 1.0, "reference poloidal flux in VS/rad"), ( "xndnt", 0.0, "vertical stability parameter, vacuum field index normalized to critical index value", ), ("rseps1", 1.0, "major radius of x point in cm"), ("zseps1", -1.0, ""), ("rseps2", 1.0, "major radius of x point in cm"), ("zseps2", 1.0, ""), ("sepexp", 0.0, "separatrix radial expansion in cm"), ("obots", 0.0, "bottom gap of external second separatrix in cm"), ("btaxp", 1.0, "toroidal magnetic field at magnetic axis in Tesla"), ("btaxv", 1.0, "vacuum toroidal magnetic field at magnetic axis in Tesla"), ("aaq1", 100.0, "minor radius of q=1 surface in cm, 100 if not found"), ("aaq2", 100.0, "minor radius of q=2 surface in cm, 100 if not found"), ("aaq3", 100.0, "minor radius of q=3 surface in cm, 100 if not found"), ( "seplim", 0.0, "> 0 for minimum gap in cm in divertor configurations, < 0 absolute value for minimum distance to external separatrix in limiter configurations", ), ("rmagx", 100.0, "major radius in cm at magnetic axis"), ("zmagx", 0.0, ""), ("simagx", 0.0, "Poloidal flux at the magnetic axis"), ("taumhd", 0.0, "energy confinement time in ms"), ("betapd", 0.0, "diamagnetic poloidal b"), ("betatd", 0.0, "diamagnetic toroidal b in %"), ("wplasmd", 0.0, "diamagnetic plasma stored energy in Joule"), ("diamag", 0.0, "measured diamagnetic flux in Volt-sec"), ("vloopt", 0.0, "measured loop voltage in volt"
), ("taudia", 0.0, "diamagnetic energy confinement time in ms"), ( "qmerci", 0.0, "Mercier stability criterion on axial q(0), q(0) > QMERCI for
stability", ), ("tavem", 0.0, "average time in ms for magnetic and MSE data"), # ishot > 91000 # The next section is dependent on the EFIT version # New version of EFIT on 05/24/97 writes aeqdsk that includes # data values for parameters nsilop,magpri,nfcoil and nesum. (None, True, None), # New line ( "nsilop", lambda data: len(data.get("csilop", [])), "Number of flux loop signals, len(csilop)", ), ( "magpri", lambda data: len(data.get("cmpr2", [])), "Number of flux loop signals, len(cmpr2) (added to nsilop)", ), ( "nfcoil", lambda data: len(data.get("ccbrsp", [])), "Number of calculated external coil currents, len(ccbrsp)", ), ( "nesum", lambda data: len(data.get("eccurt", [])), "Number of measured E-coil currents", ), (None, None, None), # New line ( "csilop", lambda data: [0.0] * data.get("nsilop", 0), "computed flux loop signals in Weber", ), ("cmpr2", lambda data: [0.0] * data.get("magpri", 0), ""), ( "ccbrsp", lambda data: [0.0] * data.get("nfcoil", 0), "computed external coil currents in Ampere", ), ( "eccurt", lambda data: [0.0] * data.get("nesum", 0), "measured E-coil current in Ampere", ), ("pbinj", 0.0, "neutral beam injection power in Watts"), ("rvsin", 0.0, "major radius of vessel inner hit spot in cm"), ("zvsin", 0.0, "Z of vessel inner hit spot in cm"), ("rvsout", 0.0, "major radius of vessel outer hit spot in cm"), ("zvsout", 0.0, "Z of vessel outer hit spot in cm"), ("vsurfa", 0.0, "plasma surface loop voltage in volt, E EQDSK only"), ("wpdot", 0.0, "time derivative of plasma stored energy in Watt, E EQDSK only"), ("wbdot", 0.0, "time derivative of poloidal magnetic energy in Watt, E EQDSK only"), ("slantu", 0.0, ""), ("slantl", 0.0, ""), ("zuperts", 0.0, ""), ("chipre", 0.0, "total chi2 pressure"), ("cjor95", 0.0, ""), ("pp95", 0.0, "normalized P'(y) at 95% normalized poloidal flux"), ("ssep", 0.0, ""), ("yyy2", 0.0, "Shafranov Y2 current moment"), ("xnnc", 0.0, ""), ("cprof", 0.0, "current profile parametrization parameter"), ("oring", 0.0, "not used"), ( "cjor0", 0.0, "normalized flux surface average current density at 99% of normalized poloidal flux", ), ("fexpan", 0.0, "flux expansion at x point"), ("qqmin", 0.0, "minimum safety factor qmin"), ("chigamt", 0.0, "total chi2 MSE"), ("ssi01", 0.0, "magnetic shear at 1% of normalized poloidal flux"), ("fexpvs", 0.0, "flux expansion at outer lower vessel hit spot"), ( "sepnose", 0.0, "radial distance in cm between x point and external field line at ZNOSE", ), ("ssi95", 0.0, "magnetic shear at 95% of normalized poloidal flux"), ("rqqmin", 0.0, "normalized radius of qmin , square root of normalized volume"), ("cjor99", 0.0, ""), ( "cj1ave", 0.0, "normalized average current density in plasma outer 5% normalized poloidal flux region", ), ("rmidin", 0.0, "inner major radius in m at Z=0.0"), ("rmidout", 0.0, "outer major radius in m at Z=0.0"), ] def write(data, fh): """ data [dict] - keys are given with documentation in the `fields` list. Also includes shot [int] - The shot number time - in ms """ # First line identification string # Default to date > 1997 since that format includes nsilop etc. fh.write("{0:11s}\n".format(data.get("header", " 26-OCT-98 09/07/98 "))) # Second line shot number fh.write(" {:d} 1\n".format(data.get("shot", 0))) # Third line time fh.write(" " + fu.f2s(data.get("time", 0.0)) + "\n") # Fourth line # time(jj),jflag(jj),lflag,limloc(jj), mco2v,mco2r,qmflag # jflag = 0 if error (? Seems to contradict example) # lflag > 0 if error (? Seems to contradict example) # limloc IN/OUT/TOP/BOT: limiter inside/outside/top/bot SNT/SNB: single null top/bottom DN: double null # mco2v number of vertical CO2 density chords # mco2r number of radial CO2 density chords # qmflag axial q(0) flag, FIX if constrained and CLC for float fh.write( "*{:s} {:d} {:d} {:s} {:d} {:d} {:s}\n".format( fu.f2s(data.get("time", 0.0)).strip(), data.get("jflag", 1), data.get("lflag", 0), data.get("limloc", "DN"), data.get("mco2v", 0), data.get("mco2r", 0), data.get("qmflag", "CLC"), ) ) # Output data in lines of 4 values each with fu.ChunkOutput(fh, chunksize=4) as output: for key, default, description in fields: if callable(default): # Replace the default function with the value, which may depend on previously read data default = default(data)
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unittest from appengine_module.test_results.handlers import redirector class RedirectorTest(unittest.TestCase): def test_url
_from_commit_positions(self): def mock_load_url(url): if url == 'https://cr-rev.appspot.com/_ah/api/crrev/v1/redirect/1': git_sha = 'aaaaaaa' else: git_sha = 'bbbbbbb' return '''{ "git_sha": "%s", "repo": "chromium/src", "redirect_url": "https://chromium.googlesource.com/chromium/src/+/%s", "project": "chromium", "redirect_type": "GIT_FROM_NUMBER", "repo_url": "https://chromium.googlesource.com/chromium/src/", "kind": "crre
v#redirectItem", "etag": "\\\"vOastG91kaV9uxC3-P-4NolRM6s/U8-bHfeejPZOn0ELRGhed-nrIX4\\\"" }''' % (git_sha, git_sha) old_load_url = redirector.load_url try: redirector.load_url = mock_load_url expected = ('https://chromium.googlesource.com/chromium/src/+log/' 'aaaaaaa^..bbbbbbb?pretty=fuller') self.assertEqual(redirector.url_from_commit_positions(1, 2), expected) finally: redirector.load_url = old_load_url
#!/usr/bin/env python # -*- coding: utf-8-*- import getopt import time import re import os,sys reload(sys) sys.setdefaultencoding('utf-8') from pdfminer.pdfparser import PDFParser from pdfminer.pdfdocument import PDFDocument from bs4 import BeautifulSoup import requests import webbrowser import subprocess class Outline(): def getToc(self, pdfPath): infile = open(pdfPath, 'rb') parser = PDFParser(infile) document = PDFDocument(parser) toc = list() for (level,title,dest,a,structelem) in document.get_outlines(): toc.append((level, title)) return toc def toOutline(self, source): if source.endswith('.pdf') and source.startswith('http') == False: items = '' for item in self.getToc(source): items += item[1] + '\n' return items elif source.startswith('http'): #url = 'https://gsnedders.html5.org/outliner/process.py?url=' + source #webbrowser.open(url) r = requests.get('http
s://gsnedders.html5.org/outliner/process.py?url=' + source) return r.text #soup = BeautifulSoup(r.text) #for li in soup.find_all('li'): # print li.text.strip() ''' r = requests.get(source) #script = "var data = new Array();" #for line in r.text: # script += "data.push('" + line + "')"
script = '' script += "var HTML5Outline = require('h5o');" script += "var outline = HTML5Outline('<html></html>');" output = subprocess.check_output('node -p "' + script + '"' , shell=True) return output ''' return '' def main(argv): source = '' try: opts, args = getopt.getopt(sys.argv[1:],'i:', ['input']) except getopt.GetoptError, err: print str(err) sys.exit(2) for o, a in opts: if o in ('-i', '--input'): source = a outline = Outline() print outline.toOutline(source) if __name__ == '__main__': main(sys.argv)
import numpy as np import matplotlib.pyplot as plt def bernstein(t, n, i): cn = 1.0 ci = 1.0 cni = 1.0 for k in range(2, n, 1): cn = cn * k for k in range(1, i, 1): if i == 1: break ci = ci * k for k in range(1, n - i + 1, 1): if n == i: break cni = cni * k j = t**(i - 1) * (1 - t)**(n - i) * cn / (ci * cni) return j def bezierplot(t, cp): n = len(cp) r = np.zeros([len(t), 2]) for k in range(len(t)): sum1 = 0.0 sum2 = 0.0 for i in range(1, n + 1, 1): bt = bernstein(t[k], n, i
) sum1 += cp[i - 1,
0] * bt sum2 += cp[i - 1, 1] * bt r[k, :] = [sum1, sum2] return np.array(r) cp = np.array([[0, -2], [1, -3], [2, -2], [3, 2], [4, 2], [5, 0]]) t = np.arange(0, 1 + 0.01, 0.01) p = bezierplot(t, cp) plt.figure() plt.plot(p[:, 0], p[:, 1]) plt.plot(cp[:, 0], cp[:, 1], ls=':', marker='o') plt.show()
from pygraz_website import filters class TestFilters(object): def test_url_detection(self): """ Test that urls are found correctly. """ no_urls_string = '''This is a test without any urls in it.''' urls_string = '''This string has one link in it: http://pygraz.org . But it also has some text after it :D''' assert filters.urlize(no_urls_string) == no_urls_string assert filters.urlize(urls_string) == '''This string has one link in it: <a href="http://pygraz.org">http://pygraz.org</a> . But it also has some text after it :D''' assert filters.urlize(urls_string, True).matches == {'urls': set(['http://pygraz.org'])} assert filters.urlize(None) == u'' assert filters.urlize("'http://test.com'") == """'<a href="http://test.com">http://test.com</a>'""" def test_namehandles(self): """ Tests the discory of linkable names. """ string_with_handles = 'Hallo @pygraz.' assert filters.urlize(string_with_handles) == 'H
allo <a href="http://twitter.com/pygraz">@pygraz</a>.' assert filters.urlize(string_with_handles, True).matches == {'handles': set(['pygraz'])}
def test_hashtags(self): string_with_tags = 'This is a #test for #hashtags' assert filters.urlize(string_with_tags) == 'This is a <a href="http://twitter.com/search?q=%23test">#test</a> for <a href="http://twitter.com/search?q=%23hashtags">#hashtags</a>' assert filters.urlize(string_with_tags, True).matches == {'hashtags': set(['test', 'hashtags'])}
ef __init__(self): super().__init__() self.add_from_file("main.glade") self.connect_signals(self) self.spin_buttons = ( self.get_object("spinbutton_h"), self.get_object("spinbutton_min"), self.get_object("spinbutton_s"), ) self.css_provider = Gtk.CssProvider() self.get_object("togglebutton1").get_style_context().add_provider( self.css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) self.start_seconds_left = 0 self.config = configparser.ConfigParser() self.config.read('settings.ini') if 'default' in self.config.sections(): try: self.spin_buttons[2].set_value(int(self.config['default']['seconds'])) self.get_object(self.config['default']['mode']).set_active(True) if self.config['default']['mute'] == 'True': self.get_object('checkbutton1').set_active(True) except ValueError as err: print(err) except KeyError as err: print('KeyError: {}'.format(err)) else: self.config['default'] = {} self.spin_buttons[0].set_value(1) self.window = self.get_object("window1") self.window.show_all() def on_timer(self): """ Deincreases by one second """ if not self.get_object("togglebutton1").get_active(): return False seconds = self.spin_buttons[2].get_value_as_int() if seconds == 0: seconds = 60 minutes = self.spin_buttons[1].get_value_as_int() if minutes == 0: minutes = 60 hours = self.spin_buttons[0].get_value_as_int() if hours == 0: try: if self.get_object("checkbutton1").get_active(): if platform.system() == "Windows": subprocess.check_output("nircmd.exe mutesysvolume 1") else: subprocess.check_output("pactl set-sink-mute 0 1", shell=True)
verb = "hibernate" if platform.system() == "Windows": if self.get_object("standby").get_active(): verb = "standby" elif self.get_object("shutdown").get_active():
verb = "exitwin poweroff" subprocess.check_output("nircmd.exe " + verb) else: if self.get_object("standby").get_active(): verb = "suspend" elif self.get_object("shutdown").get_active(): verb = "poweroff" subprocess.check_output("systemctl " + verb + " -i", shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as err: dialog = Gtk.MessageDialog( parent=self.window, message_type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.CLOSE, text="`{}` failed with exit code {}".format(err.cmd, err.returncode)) dialog.format_secondary_text(err.stdout.decode('utf-8', 'ignore').strip()) dialog.run() dialog.destroy() Gtk.main_quit() return False self.spin_buttons[0].set_value(hours - 1) self.spin_buttons[1].set_value(minutes - 1) self.spin_buttons[2].set_value(seconds - 1) self.css_provider.load_from_data(".install-progress {{ background-size: {}%; }}".format( int(self.get_seconds_left() * 100 / self.start_seconds_left) ).encode()) return True def on_toggled(self, button): """ Start button toggled """ self.spin_buttons[2].set_sensitive(not button.get_active()) # seconds context = button.get_style_context() if button.get_active(): context.add_class("install-progress") context.remove_class("suggested-action") self.css_provider.load_from_data(b".install-progress { background-size: 100%; }") self.start_seconds_left = self.get_seconds_left() with open('settings.ini', 'w') as file: self.config['default']['seconds'] = str(int(self.start_seconds_left)) self.config['default']['mode'] = 'standby' if self.get_object('hibernate').get_active(): self.config['default']['mode'] = 'hibernate' elif self.get_object('shutdown').get_active(): self.config['default']['mode'] = 'shutdown' self.config['default']['mute'] = str(self.get_object("checkbutton1").get_active()) self.config.write(file) self.previous_label = button.get_label() button.set_label("_Stop") else: context.remove_class("install-progress") context.add_class("suggested-action") button.set_label(self.previous_label) if button.get_active(): GLib.timeout_add(1000, self.on_timer) def on_time_changed(self): self.get_object("togglebutton1").set_sensitive( self.spin_buttons[0].get_value() != 0 or self.spin_buttons[1].get_value() != 0 or self.spin_buttons[2].get_value() != 0 ) # If the user increases the time while it's running this could result in a negative # percentage for the progress bar. Adjust the start time so that it never happens: self.start_seconds_left = max(self.start_seconds_left, self.get_seconds_left()) def on_h_changed(self, spin_button): self.on_time_changed() def on_min_changed(self, spin_button): """ When minutes drop below 0 deincrease hours and when they get above 59 increase hours """ while spin_button.get_value() < 0: if self.spin_buttons[0].get_value() == 0: spin_button.set_value(0) else: spin_button.set_value(spin_button.get_value() + 60) self.spin_buttons[0].set_value(self.spin_buttons[0].get_value() - 1) while spin_button.get_value() > 59: spin_button.set_value(spin_button.get_value() - 60) self.spin_buttons[0].set_value(self.spin_buttons[0].get_value() + 1) self.on_time_changed() def on_s_changed(self, spin_button): """ When seconds drop below 0 deincrease minutes and when they get above 59 increase minutes """ while spin_button.get_value() < 0: if self.spin_buttons[0].get_value() == 0 and self.spin_buttons[1].get_value() == 0: spin_button.set_value(0) else: spin_button.set_value(spin_button.get_value() + 60) self.spin_buttons[1].set_value(self.spin_buttons[1].get_value() - 1) while spin_button.get_value() > 59: spin_button.set_value(spin_button.get_value() - 60) self.spin_buttons[1].set_value(self.spin_buttons[1].get_value() + 1) self.on_time_changed() def on_delete_window(self, *args): Gtk.main_quit(*args) def get_seconds_left(self): return self.spin_buttons[0].get_value() * 3600 + self.spin_buttons[1].get_value() * 60 + \ self.spin_buttons[2].get_value() style_provider = Gtk.CssProvider() style_provider.load_from_data(b""".install-progress { background-image: linear-gradient(to top, @theme_selected_bg_color 2px, alpha(@theme_selected_bg_color, 0) 2px); background-repeat: no-repeat; background-position: 0 bottom; transition: none; } .install-progress { background-position: 100% bottom; } """) Gtk.StyleContext.add_provider_for_screen( Gdk.Screen.get_default(), style_
#!/usr/bin/env python """ Send message to '#gis.lab' IRC chat room. Requires to run script 'utils/join-gislab-network.py' first to get connection with server. USAGE: send-message.py <message> """ import os, sys import re import socket try: message = sys.argv[1] except IndexError: print __doc__ sys.exit(0) DIR=os.path.dirname(os.path.abspath(__file__)) def get_config(variable): c = open(os.path.join(os.path.dirname(DIR), "config.cfg"), "ro") for line in c: if re.match("^" + variable, line): value = line.split("=")[1].replace("'", "").replace('"', '') c.close() break c = open(os.path.join(os.path.dirname(DIR), "config-user.cfg"), "ro") for line in c: if re.match("^" + variable, line): value = line.split("=")[1].replace("'", "").replace('"', '') c.close() break return value.strip() GISLAB_NETWORK = get_config("GISLAB_NETWORK") HOST="{0}.5".format(GISLAB_NETWORK) PORT=6667 NICK=IDENT=os.environ['USER'] REALNAME="script" CHANNEL="gis.lab" s=socket.socket( socket.AF_INET, socket.SOCK_STREAM ) s.connect((HOST, PORT)) print s.recv(4096) s.send("NICK %s\r\n" % NICK) s.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME)) s.send("JOIN #%s\r\n" % CHANNEL) s.send("PRIVMSG #g
islab :%s\r\n" % me
ssage) s.send("QUIT: End of message.\r\n") s.recv(4096) s.close() print "Done." # vim: ts=8 sts=4 sw=4 et:
#!/usr/bin/python3 import logging from operator import itemgetter from timeit import default_timer as timer import rdflib from .abstract_instruction_set import AbstractInstructionSet from readers import rdf from writers import rule_set, pickler from samplers import by_definition as sampler from algorithms.semantic_rule_learning import generate_semantic_association_rules,\ generate_semantic_item_sets,\ generate_common_behaviour_sets,\ support_of,\ confidence_of class PakbonLD(AbstractInstructionSet): def __init__(self, time=""): self.time = time self.logger = logging.getLogger(__name__) def print_header(self): header = "PAKBON: Context ('Sporen') with 12 attributes" print(header) print('-' * len(header)) def load_dataset(self, abox, tbox): """ # pakbonLD SPARQL endpoint endpoint = "http://pakbon-ld.spider.d2s.labs.vu.nl/sparql/" # query query_string = "" " prefix pbont: <http://pakbon-ld.spider.d2s.labs.vu.nl/ont/> prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> SELECT DISTINCT ?s ?p ?o WHERE { ?s a pbont:SIKB0102S_Vondstcontext; ?p ?o. FILTER (?p != rdf:type) } LIMIT 1000"" " # perform query and return a KnowledgeGraph instance kg_i = rdf.query(query_string, endpoint) """ # read graphs kg_i = rdf.read(local_path=abox) kg_s = rdf.read(local_path=tbox) # sample by pattern pattern = (None, rdflib.URIRef("http://pakbon-ld.spider.d2s.labs.vu.nl/ont/SIKB0102S_grondspoortype"), None) # define context # spoor with vulling context = [rdflib.URIRef("http://pakbon-ld.spider.d2s.labs.vu.nl/ont/SIKB0102S_grondspoortype"), rdflib.URIRef("http://
www.cidoc-crm.org/cidoc-crm/P53i_is_former_or_current_location_of"), (rdflib.URIRef("htt
p://www.cidoc-crm.org/cidoc-crm/P89_falls_within"), rdflib.URIRef("http://pakbon-ld.spider.d2s.labs.vu.nl/ont/SIKB0102S_contexttype")), (rdflib.URIRef("http://purl.org/crmeh#EHP3i"), rdflib.URIRef("http://pakbon-ld.spider.d2s.labs.vu.nl/ont/SIKB0102S_kleur")), (rdflib.URIRef("http://purl.org/crmeh#EHP3i"), rdflib.URIRef("http://pakbon-ld.spider.d2s.labs.vu.nl/ont/SIKB0102S_textuur")), (rdflib.URIRef("http://www.cidoc-crm.org/cidoc-crm/P53i_is_former_or_current_location_of"), rdflib.URIRef("http://pakbon-ld.spider.d2s.labs.vu.nl/ont/SIKB0102S_structuurtype")), (rdflib.URIRef("http://pakbon-ld.spider.d2s.labs.vu.nl/ont/SIKB0102S_diepte"), rdflib.URIRef("http://www.cidoc-crm.org/cidoc-crm/P40_observed_dimension"), rdflib.URIRef("http://www.cidoc-crm.org/cidoc-crm/P90_has_value")), (rdflib.URIRef("http://pakbon-ld.spider.d2s.labs.vu.nl/ont/SIKB0102S_diepte"), rdflib.URIRef("http://www.cidoc-crm.org/cidoc-crm/P40_observed_dimension"), rdflib.URIRef("http://www.cidoc-crm.org/cidoc-crm/P91_has_unit")), (rdflib.URIRef("http://www.cidoc-crm.org/cidoc-crm/P140i_was_attributed_by"), rdflib.URIRef("http://www.cidoc-crm.org/cidoc-crm/P141_assigned"), rdflib.URIRef("http://pakbon-ld.spider.d2s.labs.vu.nl/ont/SIKB0102S_beginperiode")), (rdflib.URIRef("http://www.cidoc-crm.org/cidoc-crm/P140i_was_attributed_by"), rdflib.URIRef("http://www.cidoc-crm.org/cidoc-crm/P141_assigned"), rdflib.URIRef("http://pakbon-ld.spider.d2s.labs.vu.nl/ont/SIKB0102S_eindperiode")), (rdflib.URIRef("http://www.cidoc-crm.org/cidoc-crm/P53i_is_former_or_current_location_of"), rdflib.URIRef("http://www.cidoc-crm.org/cidoc-crm/P140i_was_attributed_by"), rdflib.URIRef("http://www.cidoc-crm.org/cidoc-crm/P141_assigned"), rdflib.URIRef("http://pakbon-ld.spider.d2s.labs.vu.nl/ont/SIKB0102S_beginperiode")), (rdflib.URIRef("http://www.cidoc-crm.org/cidoc-crm/P53i_is_former_or_current_location_of"), rdflib.URIRef("http://www.cidoc-crm.org/cidoc-crm/P140i_was_attributed_by"), rdflib.URIRef("http://www.cidoc-crm.org/cidoc-crm/P141_assigned"), rdflib.URIRef("http://pakbon-ld.spider.d2s.labs.vu.nl/ont/SIKB0102S_eindperiode"))] kg_i_sampled = kg_i.sample(sampler, patterns=[pattern], context=context) return (kg_i_sampled, kg_s) def run_program(self, dataset, hyperparameters): self.logger.info("Starting run\nParameters:\n{}".format( "\n".join(["\t{}: {}".format(k,v) for k,v in hyperparameters.items()]))) kg_i, kg_s = dataset # fit model t0 = timer() # generate semantic item sets from sampled graph si_sets = generate_semantic_item_sets(kg_i) # generate common behaviour sets cbs_sets = generate_common_behaviour_sets(si_sets, hyperparameters["similarity_threshold"], hyperparameters["max_cbs_size"]) # generate semantic association rules rules = generate_semantic_association_rules(kg_i, kg_s, cbs_sets, hyperparameters["minimal_local_support"]) # calculate support and confidence, skip those not meeting minimum requirements final_rule_set = [] for rule in rules: support = support_of(kg_i, rule) confidence = confidence_of(kg_i, rule) if support >= hyperparameters["minimal_support"] and\ confidence >= hyperparameters["minimal_confidence"]: final_rule_set.append((rule, support, confidence)) # sorting rules on both support and confidence final_rule_set.sort(key=itemgetter(2, 1), reverse=True) # time took t1 = timer() dt = t1 - t0 print(" Program completed in {:.3f} ms".format(dt)) print(" Found {} rules".format(len(final_rule_set))) return final_rule_set def write_to_file(self, path="./of/latest", output=[]): overwrite = False print(" Writing output to {}...".format(path)) rule_set.pretty_write(output, path, overwrite) pickler.write(output, path+".pickle", overwrite) def run(self, abox, tbox, output_path): self.print_header() print(" {}\n".format(self.time)) hyperparameters = {} hyperparameters["similarity_threshold"] = .8 hyperparameters["max_cbs_size"] = 4 hyperparameters["minimal_local_support"] = 0.0 hyperparameters["minimal_support"] = 0.0 hyperparameters["minimal_confidence"] = 0.0 print(" Importing Data Sets...") dataset = self.load_dataset(abox, tbox) print(" Initiated Pattern Learning...") output = self.run_program(dataset, hyperparameters) if len(output) > 0: self.write_to_file(output_path, output)
meout == '': timeout = 10 timeout = int(timeout) print '\n\nStarting the load balancing application...\n\n' while True: print '\n\nQuerying for network core interface monitoring triggered events...\n\n' print '\n\nChecking for Interface/Link Failures in the Network Core..\n\n' delete_links = {} update_link_weights = {} int_failures = {} high_utis = {} int_failures = core_mon.int_fail_events() if int_failures != {}: for key in int_failures: agent_node = int_failures[key]['Agent'] agent_interface_id = int_failures[key]['Interface ID'] agent_interface = sflow_if_map[agent_interface_id] if delete_links != {}: m = 0 for key in delete_links: if key == agent_node: m += 1 if m != 0: old_link_list = delete_links[agent_node] old_link_list.append(agent_interface) delete_links[agent_node] = old_link_list else: new_link_list = [] new_link_list.append(agent_interface) delete_links[agent_node] = new_link_list else: new_link_list = [] new_link_list.append(agent_interface) delete_links[agent_node] = new_link_list paths = optimal_testbed_network_1().optimal_path(delete_links, update_link_weights) if paths != {}: all_paths_right = paths['All Paths Right'] all_paths_left = paths['All Paths Left'] shortest_path_right = paths['Shortest Path Right'] shortest_path_left = paths['Shortest Path Left'] no_path_labels = [] shortest_path_right_label = '' shortest_path_left_label = '' for key in testbed_1_lsps: if testbed_1_lsps[key] == shortest_path_right: shortest_path_right_label = key if testbed_1_lsps[key] == shortest_path_left: shortest_path_left_label = key for key in testbed_1_lsps: m = 0 for apr in all_paths_right: if testbed_1_lsps[key] == apr: m += 1 for apl in all_paths_left: if testbed_1_lsps[key] == apl: m += 1 if m == 0: no_path_labels.append(key) with open("Statistics_Logs/Testbed_1_Basic_Connectivity_Flow_Stats.json") as json_file: basic_connectivity_flow_stats = json.load(json_file) installed_path_labels = [] deleted_path_labels = [] for key in basic_connectivity_flow_stats: installed_path_labels.append(basic_connectivity_flow_stats[key]['MPLS Label']) deleted_path_labels = set(installed_path_labels).intersection(no_path_labels) deleted_flows = {} for dpl in deleted_path_labels: for key in basic_connectivity_flow_stats: if basic_connectivity_flow_stats[key]['MPLS Label'] == dpl: deleted_flows[key] = basic_connectivity_flow_stats[key] for key in deleted_flows: flow_id = key mpls_push_stats = {} mpls_push_flow_stats = {} mpls_push_flow = flow.odl_mpls_push_json() mpls_push_stats = stat.odl_mpls_push_stat() mpls_push_flow_stats = mpls_push_stats['stat'] mpls_push_flow_counter = mpls_push_stats['counter'] switch_id = deleted_flows[key]['Switch ID'] dst_add = deleted_flows[key]['IP Destination'] src_add = '' in_port = '' dl_dst = '' dl_src = '' protocol = '' tcp_src_port = '' tcp_dst_port = '' udp_src_port = '' udp_dst_port = '' vlan_id = '' vlan_priority = '' table_id = '0' priority = '10' for key in odl_switches_ip: if odl_switches_ip[key] == switch_id: switch_ip = key if switch_ip == shortest_path_right[0]: label = shortest_path_right_label if switch_ip == shortest_path_left[0]: label = shortest_path_left_label action_mpls_label = label con_switch = testbed_1_lsps[label][1] for key in testbed_1_topo[switch_ip]: if testbed_1_topo[switch_ip][key] == con_switch: con_port = key for key in sflow_if_map: if sflow_if_map[key] == con_port: port = key action_out_port = port flow_stat = {} fl
ow_stat = odl.odl_mpls_push_flow_inst(url_odl, name, password, odl_header, mpls_push_flow, mpls_push_flow_counter, switch_id, dst_add, src_add, in_port, dl_dst, dl_src, protocol, tcp_src_port, tcp_dst_port, udp_src_port, udp_dst_port, vlan_id, vlan_priority, action_mpls_label, action_out_port, table_id, priority)
if flow_stat: flow_name = flow_stat['Flow ID'] mpls_push_flow_stats[flow_name] = flow_stat basic_connectivity_flow_stats[flow_name] = {'Switch ID': switch_id, 'IP Destination' : dst_add, 'MPLS Label' : label} with open("Statistics_Logs/MPLS_Push_Flow_Stats.json", "w") as json_file: json.dump(mpls_push_flow_stats, json_file) with open("Statistics_Logs/Testbed_1_Basic_Connectivity_Flow_Stats.json", "w") as json_file: json.dump(basic_connectivity_flow_stats, json_file) if mpls_push_flow_stats: del(mpls_push_flow_stats[flow_id]) del(basic_connectivity_flow_stats[flow_id]) with open("Statistics_Lo
import itert
ools import numpy import math def ncr(n, r): f = math.factorial return f(n) // f(r) // f(n-r) def subset_pairs(s): for a_size in range(1, len(s)): for a in itertools.combinations(s, a_size): remaining = s.difference(a) for b_size in range(1, len(remaining) + 1): for b in itertools.combinations(remaining, b_size): yield a, b [11, 18, 19, 20,
22, 25]
from PyQt5 import QtCore from src.business.configuration.constants import project as p from src.ui.commons.verification import cb class ConfigProject: def __init__(self): self._settings = QtCore.QSettings(p.CONFIG_FILE, QtCore.QSettings.IniFormat) def get_value(self, menu, value): return self._settings.value(menu + '/' + value) def set_site_settings(self, name, site_id, imager_id): self._settings.beginGroup(p.SITE_TITLE) self._settings.setValue(p.NAME, name) self._settings.setValue(p.SITE_ID, site_id) self._settings.setValue(p.IMAGER_ID, imager_id) self._settings.endGroup() def set_geographic_settings(self, lat, long, elev, press, temp): self._settings.beginGroup(p.GEOGRAPHIC_TITLE) self._settings.setValue(p.LATITUDE, lat) self._settings.setValue(p.LONGITUDE, long) self._settings.setValue(p.ELEVATION, elev) self._settings.setValue(p.PRESSURE, press) self._settings.setValue(p.TEMPERATURE, temp) self._settings.endGroup() def set_moonsun_settings(self, solarelev, ignoreLunar, lunarph, lunarpos): self._settings.beginGroup(p.SUN_MOON_TITLE) self._settings.setValue(p.MAX_SOLAR_ELEVATION, solarelev) self._settings.setValue(p.IGNORE_LUNAR_POSITION, ignoreL
unar) self._settings.setValue(p.MAX_LUNAR_PHASE, lunarph) self._settings.setValue(p.MAX_LUNAR_ELEVATION, lunarpos) self._settings.endGroup() def save_settings(self): self._settings.sync() def get_site_settings(self):
return self.get_value(p.SITE_TITLE, p.NAME),\ self.get_value(p.SITE_TITLE, p.SITE_ID),\ self.get_value(p.SITE_TITLE, p.IMAGER_ID) def get_geographic_settings(self): m = p.GEOGRAPHIC_TITLE return self.get_value(m, p.LATITUDE),\ self.get_value(m, p.LONGITUDE),\ self.get_value(m, p.ELEVATION),\ self.get_value(m, p.PRESSURE),\ self.get_value(m, p.TEMPERATURE) def get_moonsun_settings(self): m = p.SUN_MOON_TITLE return self.get_value(m, p.MAX_SOLAR_ELEVATION),\ cb(self.get_value(m, p.IGNORE_LUNAR_POSITION)),\ self.get_value(m, p.MAX_LUNAR_PHASE),\ self.get_value(m, p.MAX_LUNAR_ELEVATION)
from Scouting2017.model.models2017 import ScoreResult from django.db.models.aggregates import Avg from django.db.models.expressions import Case, When import json import math import collections def get_statistics(regional_code, teams_at_competition, team=0): ''' The get_statistics function() returns two lists of metrics. The first thing it returns, stats, is a dictionary containing the values of overall averages for all score results, along with standard deviations for those same score results along the mean. The function also returns a list called skills, which contains data for each team including their z-scores, calculated fuel scores for autonomous, teleop, and overall, and their accuracy in climbing the rope. ''' skills = [] competition_srs = ScoreResult.objects.filter(competition__code=regional_code) competition_averages = competition_srs.aggregate(Avg('auto_gears'), Avg('auto_fuel_high_score'), Avg('tele_gears'), Avg('tele_fuel_high_score'), rope__avg=Avg(Case(When(rope=True, then=1), When(rope=False, then=0)))) rope_avg = competition_averages['rope__avg'] gear_avg = competition_averages['tele_gears__avg'] if competition_averages['auto_fuel_high_score__avg'] and competition_averages['tele_fuel_high_score__avg']: fuel_avg = competition_averages['auto_fuel_high_score__avg'] + (competition_averages['tele_fuel_high_score__avg'] / 3) else: fuel_avg = 0 # This part of the function (above) obtains overall averages for all score results gear_v2 = 0 fuel_v2 = 0 rope_v2 = 0 num_srs = 0 for sr in competition_srs: if sr.rope: sr_rope = 1 - rope_avg else: sr_rope = 0 - rope_avg sr_gear = sr.tele_gears - gear_avg sr_fuel = ((sr.auto_fuel_high_score) + (sr.tele_fuel_high_score / 3)) - fuel_avg gear_v2 += sr_gear * sr_gear fuel_v2 += sr_fuel * sr_fuel rope_v2 += sr_rope * sr_rope num_srs += 1 if num_srs == 0: gear_stdev = 0 fuel_stdev = 0 rope_stdev = 0 else: gear_stdev = math.sqrt(gear_v2 / num_srs) fuel_stdev = math.sqrt(fuel_v2 / num_srs) rope_stdev = math.sqrt(ro
pe_v2 / num_srs) team_avgs = collections.defaultdict(int) # This part of the function (above) obtains overall standard deviations for all score results teams = team if bool(team) else teams_at_c
ompetition for team in teams: teams_srs = team.scoreresult_set.filter(competition__code=regional_code) team_avgs = teams_srs.aggregate(Avg('tele_gears'), Avg('tele_fuel_high_score'), Avg('auto_fuel_high_score'), team_rope__avg=Avg(Case(When(rope=True, then=1), When(rope=False, then=0)))) team.skills = {} team.skills['fuel_z'] = 'NA' team.skills['gear_z'] = 'NA' team.skills['rope_z'] = 'NA' team.skills['rope_pct'] = 'NA' if len(teams_srs) != 0: team.skills['fuel_score'] = ((team_avgs['auto_fuel_high_score__avg']) + (team_avgs['tele_fuel_high_score__avg'] / 3)) team.skills['gear_z'] = (team_avgs['tele_gears__avg'] - gear_avg) / gear_stdev if gear_stdev != 0 else 0 team.skills['fuel_z'] = (((team_avgs['auto_fuel_high_score__avg']) + (team_avgs['tele_fuel_high_score__avg'] / 3)) - fuel_avg) / fuel_stdev if fuel_stdev != 0 else 0 team.skills['rope_z'] = (team_avgs['team_rope__avg'] - rope_avg) / rope_stdev if rope_stdev != 0 else 0 team.skills['rope_pct'] = team_avgs['team_rope__avg'] * 100 skills.append({'team': team.teamNumber, 'skills': team.skills}) stats = {'gear_avg': gear_avg, 'rope_avg': rope_avg, 'fuel_avg': fuel_avg, 'fuel_hi_avg': team_avgs['tele_fuel_high_score__avg'], 'fuel_hi_auto_avg': team_avgs['auto_fuel_high_score__avg'], 'auto_gear_avg': competition_averages['auto_gears__avg'], 'gear_stdev': gear_stdev, 'rope_stdev': rope_stdev, 'fuel_stdev': fuel_stdev} return (stats, json.dumps(skills))
# Copyright 2010 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). import re from django import forms from django.utils.translation import ugettext as _ from identityprovider.widgets import CommaSeparatedWidget class CommaSeparatedField(forms.MultipleChoiceField): widget = CommaSeparatedWidget def clean(self, value): return ',
'.join(super(CommaSeparatedField, self).clean(value)) class OATHPasswordField(forms.CharField): """A string of between 6 or 8 digits.""" widget = forms.widgets.TextInput(attrs={ 'autocomplete': 'off', 'autofocus': 'autofocus' }) SIX = re.compile('[0-9]{6}$') EIGHT = re.compile('[0-9]{8}$') def clean(self, value): """
Validate otp and detect type""" # remove any whitespace from the string if value: value = value.strip().replace(' ', '') value = super(OATHPasswordField, self).clean(value) if self.SIX.match(value): return value elif self.EIGHT.match(value): return value raise forms.ValidationError( _('Please enter a 6-digit or 8-digit one-time password.'))
from GangaCore.testlib.GangaUnitTest import GangaUnitTest from GangaGUI.api import internal # ******************** Test Class ******************** # # Templates API Tests class TestGangaGUIInternalTemplatesAPI(GangaUnitTest): # Setup def setUp(self, extra_opts=[]): super(TestGangaGUIInternalTemplatesAPI, self).setUp(extra_opts=[]) # App config and database creation internal.config["TESTING"] = True # Flask test client self.app = internal.test_client() # Templates API - GET Method def test_GET_method_templates_list(self): from GangaCore.GPI import templates, JobTemplate, GenericSplitter, Local # Create 20 test templates for i in range(0, 20): t = JobTemplate() t.name = f"Template Test {i}" t.application.exe = "sleep" t.splitter = GenericSplitter() t.splitter.attribute = 'application.args' t.splitter.values = [['3'] for _ in range(0, 3)] t.backend = Local() # GET request res = self.app.get(f"/internal/templates") self.assertTrue(res.status_code == 200) self.assertTrue(len(res.json) == 20) # Response data assertions supported_attributes = ["id", "fqid", "name", "application", "backend", "comment", "backend.actualCE"] for i in range(0, 20): for attribute in supported_attributes: self.assertTrue(attribute in res.json[i]) self.assertTrue(res.json[i]["name"] == f"Template Test {i}") # Templates API - DELETE Method, ID Out of Index def test_DELETE_method_id_out_of_range(
self): res = self.app.delete(f"/internal/templates/1") self.assertTrue(res.status_code == 400) # Templates API - DELETE Method, ID is Negative def test_DELETE_method_id_negative(self): res = self.app.delete(f"/internal/templates/-1") self.assertTrue(res.status_code == 404) # Templates API - DELETE Method, ID is String def test_DELETE_method_id_string(self): res = s
elf.app.delete(f"/internal/templates/test") self.assertTrue(res.status_code == 404) # Templates API - DELETE Method def test_DELETE_method_templates_list(self): from GangaCore.GPI import templates, JobTemplate, GenericSplitter, Local # Clean template repository check self.assertTrue(len(templates) == 0) # Create 20 test templates created_template_ids = [] for i in range(0, 20): t = JobTemplate() t.name = f"Template Test {i}" created_template_ids.append(t.id) self.assertTrue(len(templates) == 20) self.assertTrue(len(created_template_ids) == 20) # Delete one template every request and assert the deletion for i in range(0,20): self.assertTrue(created_template_ids[i] in templates.ids()) res = self.app.delete(f"/internal/templates/{created_template_ids[i]}") self.assertTrue(res.status_code == 200) self.assertTrue(len(templates) == (20-(i+1))) self.assertTrue(created_template_ids[i] not in templates.ids()) # Tear down def tearDown(self): super(TestGangaGUIInternalTemplatesAPI, self).tearDown() # ******************** EOF ******************** #
# CamJam EduKit 3 - Robotics # Worksheet 7 - Controlling the motors with PWM import RPi.GPIO as GPIO # Import the GPIO Library import time # Import the Time library # Set the GPIO modes GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) # Se
t variables for the GPIO motor pins pinMotorAForwards = 10 pinMotorABackwards = 9 pinMotorBForwards = 8 pinMotorBBackwards = 7 # How ma
ny times to turn the pin on and off each second Frequency = 20 # How long the pin stays on each cycle, as a percent (here, it's 30%) DutyCycle = 30 # Setting the duty cycle to 0 means the motors will not turn Stop = 0 # Set the GPIO Pin mode to be Output GPIO.setup(pinMotorAForwards, GPIO.OUT) GPIO.setup(pinMotorABackwards, GPIO.OUT) GPIO.setup(pinMotorBForwards, GPIO.OUT) GPIO.setup(pinMotorBBackwards, GPIO.OUT) # Set the GPIO to software PWM at 'Frequency' Hertz pwmMotorAForwards = GPIO.PWM(pinMotorAForwards, Frequency) pwmMotorABackwards = GPIO.PWM(pinMotorABackwards, Frequency) pwmMotorBForwards = GPIO.PWM(pinMotorBForwards, Frequency) pwmMotorBBackwards = GPIO.PWM(pinMotorBBackwards, Frequency) # Start the software PWM with a duty cycle of 0 (i.e. not moving) pwmMotorAForwards.start(Stop) pwmMotorABackwards.start(Stop) pwmMotorBForwards.start(Stop) pwmMotorBBackwards.start(Stop) # Turn all motors off def stopmotors(): pwmMotorAForwards.ChangeDutyCycle(Stop) pwmMotorABackwards.ChangeDutyCycle(Stop) pwmMotorBForwards.ChangeDutyCycle(Stop) pwmMotorBBackwards.ChangeDutyCycle(Stop) # Turn both motors forwards def forwards(): pwmMotorAForwards.ChangeDutyCycle(DutyCycle) pwmMotorABackwards.ChangeDutyCycle(Stop) pwmMotorBForwards.ChangeDutyCycle(DutyCycle) pwmMotorBBackwards.ChangeDutyCycle(Stop) # Turn both motors backwards def backwards(): pwmMotorAForwards.ChangeDutyCycle(Stop) pwmMotorABackwards.ChangeDutyCycle(DutyCycle) pwmMotorBForwards.ChangeDutyCycle(Stop) pwmMotorBBackwards.ChangeDutyCycle(DutyCycle) # Turn left def left(): pwmMotorAForwards.ChangeDutyCycle(Stop) pwmMotorABackwards.ChangeDutyCycle(DutyCycle) pwmMotorBForwards.ChangeDutyCycle(DutyCycle) pwmMotorBBackwards.ChangeDutyCycle(Stop) # Turn Right def right(): pwmMotorAForwards.ChangeDutyCycle(DutyCycle) pwmMotorABackwards.ChangeDutyCycle(Stop) pwmMotorBForwards.ChangeDutyCycle(Stop) pwmMotorBBackwards.ChangeDutyCycle(DutyCycle) # Your code to control the robot goes below this line forwards() time.sleep(1) # Pause for 1 second left() time.sleep(0.5) # Pause for half a second forwards() time.sleep(1) right() time.sleep(0.5) backwards() time.sleep(0.5) stopmotors() GPIO.cleanup()
#!/usr/bin/python # Script to Check the difference in 2 files # 1 fevereiro de 2015 # https://github.com/thezakman file1 = raw_input('[file1:] ') modified = open(file1,"r").readlines()[0] file2 = raw_input('[file2:] ') pi = open(file2, "r").readlines()[0] # [:len(modified)] resultado = "".join( x for x,y in zip(modified, pi) if x != y) resultado2 = "".join( x for x,y in zip(pi, modified) if x != y) pr
int "[Diff
er:] print '\n-------------------------------------' print "[file1] -> [file2]", resultado print '-------------------------------------' print "[file2] -> [file1]", resultado2