function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
sequence
def fileConfig(fname, defaults=None, disable_existing_loggers=1): """ Read the logging configuration from a ConfigParser-format file.
babyliynfg/cross
[ 75, 39, 75, 4, 1489383147 ]
def _resolve(name): """Resolve a dotted name to a global object.""" name = string.split(name, '.') used = name.pop(0) found = __import__(used) for n in name: used = used + '.' + n try: found = getattr(found, n) except AttributeError: __import__(used) found = getattr(found, n) return found
babyliynfg/cross
[ 75, 39, 75, 4, 1489383147 ]
def _strip_spaces(alist): return map(lambda x: string.strip(x), alist)
babyliynfg/cross
[ 75, 39, 75, 4, 1489383147 ]
def _encoded(s): return s if isinstance(s, str) else s.encode('utf-8')
babyliynfg/cross
[ 75, 39, 75, 4, 1489383147 ]
def _create_formatters(cp): """Create and return formatters""" flist = cp.get("formatters", "keys") if not len(flist): return {} flist = string.split(flist, ",") flist = _strip_spaces(flist) formatters = {} for form in flist: sectname = "formatter_%s" % form opts = cp.options(sectname) if "format" in opts: fs = cp.get(sectname, "format", 1) else: fs = None if "datefmt" in opts: dfs = cp.get(sectname, "datefmt", 1) else: dfs = None c = logging.Formatter if "class" in opts: class_name = cp.get(sectname, "class") if class_name: c = _resolve(class_name) f = c(fs, dfs) formatters[form] = f return formatters
babyliynfg/cross
[ 75, 39, 75, 4, 1489383147 ]
def _install_handlers(cp, formatters): """Install and return handlers""" hlist = cp.get("handlers", "keys") if not len(hlist): return {} hlist = string.split(hlist, ",") hlist = _strip_spaces(hlist) handlers = {} fixups = [] #for inter-handler references for hand in hlist: sectname = "handler_%s" % hand klass = cp.get(sectname, "class") opts = cp.options(sectname) if "formatter" in opts: fmt = cp.get(sectname, "formatter") else: fmt = "" try: klass = eval(klass, vars(logging)) except (AttributeError, NameError): klass = _resolve(klass) args = cp.get(sectname, "args") args = eval(args, vars(logging)) h = klass(*args) if "level" in opts: level = cp.get(sectname, "level") h.setLevel(logging._levelNames[level]) if len(fmt): h.setFormatter(formatters[fmt]) if issubclass(klass, logging.handlers.MemoryHandler): if "target" in opts: target = cp.get(sectname,"target") else: target = "" if len(target): #the target handler may not be loaded yet, so keep for later... fixups.append((h, target)) handlers[hand] = h #now all handlers are loaded, fixup inter-handler references... for h, t in fixups: h.setTarget(handlers[t]) return handlers
babyliynfg/cross
[ 75, 39, 75, 4, 1489383147 ]
def _install_loggers(cp, handlers, disable_existing_loggers): """Create and install loggers"""
babyliynfg/cross
[ 75, 39, 75, 4, 1489383147 ]
def listen(port=DEFAULT_LOGGING_CONFIG_PORT): """ Start up a socket server on the specified port, and listen for new configurations.
babyliynfg/cross
[ 75, 39, 75, 4, 1489383147 ]
def handle(self): """ Handle a request.
babyliynfg/cross
[ 75, 39, 75, 4, 1489383147 ]
def __init__(self, host='localhost', port=DEFAULT_LOGGING_CONFIG_PORT, handler=None): ThreadingTCPServer.__init__(self, (host, port), handler) logging._acquireLock() self.abort = 0 logging._releaseLock() self.timeout = 1
babyliynfg/cross
[ 75, 39, 75, 4, 1489383147 ]
def serve_until_stopped(self): import select abort = 0 while not abort: rd, wr, ex = select.select([self.socket.fileno()], [], [], self.timeout) if rd: self.handle_request() logging._acquireLock() abort = self.abort logging._releaseLock()
babyliynfg/cross
[ 75, 39, 75, 4, 1489383147 ]
def serve(rcvr, hdlr, port): server = rcvr(port=port, handler=hdlr) global _listener logging._acquireLock() _listener = server logging._releaseLock() server.serve_until_stopped()
babyliynfg/cross
[ 75, 39, 75, 4, 1489383147 ]
def get_info(p_display=None, default_root_window=None, p_info=None): if p_display is None: p_display = _p_display if default_root_window is None: default_root_window = _default_root_window if p_info is None: p_info = _p_info libXss.XScreenSaverQueryInfo(p_display, default_root_window, p_info) return p_info.contents
mariano/snakefire
[ 100, 24, 100, 28, 1283111981 ]
def __init__(self, when_idle_wait=5000, when_disabled_wait=120000, idle_threshold=60000): """when_idle_wait is the interval at which you should poll when you are already idle. when_disabled_wait is how often you should poll if information is unavailable (default: 2 minutes). idle_threshold is the number of seconds of idle time to constitute being idle.""" self.when_idle_wait = when_idle_wait self.idle_threshold = idle_threshold # we start with a bogus last_state. this way, the first call to # check_idle will report whether we are idle or not. all subsequent # calls will only tell you if the screensaver state has changed self.last_state = None
mariano/snakefire
[ 100, 24, 100, 28, 1283111981 ]
def __init__(self, when_idle_wait=5000, when_disabled_wait=120000): """when_idle_wait is the interval at which you should poll when you are already idle. when_disabled_wait is how often you should poll if the screensaver is disabled and you are using XSS for your idle threshold.
mariano/snakefire
[ 100, 24, 100, 28, 1283111981 ]
def check_idle(self): """Returns a tuple: (state_change, suggested_time_till_next_check, idle_time)
mariano/snakefire
[ 100, 24, 100, 28, 1283111981 ]
def add_arguments(self, parser): parser.add_argument('--prediction-type', choices=['TUMOR', 'GLEASON'], type=str, dest='prediction_type', help='the type of the Prediction objects that are going to be reviewed') parser.add_argument('--worklist-file', dest='worklist', type=str, default=None, help='a CSV file containing the worklist, if not present reviews will be assigned randomly') parser.add_argument('--allow-duplicated', action='store_true', dest='allow_duplicated', help='create worklist even for predictions that already have a related review') parser.add_argument('--report-file', dest='report_file', type=str, default=None, help='a CSV file containing a report of the created prediction reviews')
crs4/ProMort
[ 3, 5, 3, 11, 1461311365 ]
def _get_predictions_list(self, prediction_type): return Prediction.objects.filter(type=prediction_type, review_required=True).all()
crs4/ProMort
[ 3, 5, 3, 11, 1461311365 ]
def _create_prediction_annotation(self, prediction, reviewer, allow_duplicated): if not allow_duplicated: if self._check_duplicated(prediction, reviewer): return None prev_obj = PredictionReview( label=uuid4().hex, prediction=prediction, slide=prediction.slide, reviewer=reviewer ) prev_obj.save() return { 'review_id': prev_obj.id, 'slide': prev_obj.slide.id, 'prediction': prev_obj.prediction.label, 'review_label': prev_obj.label, 'reviewer': prev_obj.reviewer.username }
crs4/ProMort
[ 3, 5, 3, 11, 1461311365 ]
def create_worklist_from_file(self, worklist_file, prediction_type, allow_duplicated, report_file=None): raise NotImplementedError()
crs4/ProMort
[ 3, 5, 3, 11, 1461311365 ]
def create(kernel): result = Building() result.template = "object/building/poi/shared_naboo_tuskcattam_medium.iff" result.attribute_template_id = -1 result.stfName("poi_n","base_poi_building")
anhstudios/swganh
[ 62, 37, 62, 37, 1297996365 ]
def create(kernel): result = Tangible() result.template = "object/tangible/component/item/quest_item/shared_momentum_compensator.iff" result.attribute_template_id = -1 result.stfName("craft_item_ingredients_n","momentum_compensator")
anhstudios/swganh
[ 62, 37, 62, 37, 1297996365 ]
def optimize_png(png_file): if os.path.exists(OPTIPNG): process = subprocess.Popen([OPTIPNG, '-quiet', '-o7', png_file]) process.wait()
solus-cold-storage/evopop-gtk-theme
[ 190, 17, 190, 5, 1424038763 ]
def start_inkscape(): process = subprocess.Popen( [INKSCAPE, '--shell'], bufsize=0, stdin=subprocess.PIPE, stdout=subprocess.PIPE ) wait_for_prompt(process) return process
solus-cold-storage/evopop-gtk-theme
[ 190, 17, 190, 5, 1424038763 ]
def __init__(self, path, force=False, filter=None): self.stack = [self.ROOT] self.inside = [self.ROOT] self.path = path self.rects = [] self.state = self.ROOT self.chars = "" self.force = force self.filter = filter
solus-cold-storage/evopop-gtk-theme
[ 190, 17, 190, 5, 1424038763 ]
def startElement(self, name, attrs): if self.inside[-1] == self.ROOT: if name == "svg": self.stack.append(self.SVG) self.inside.append(self.SVG) return elif self.inside[-1] == self.SVG: if (name == "g" and ('inkscape:groupmode' in attrs) and ('inkscape:label' in attrs) and attrs['inkscape:groupmode'] == 'layer' and attrs['inkscape:label'].startswith('Baseplate')): self.stack.append(self.LAYER) self.inside.append(self.LAYER) self.context = None self.icon_name = None self.rects = [] return elif self.inside[-1] == self.LAYER: if name == "text" and ('inkscape:label' in attrs) and attrs['inkscape:label'] == 'context': self.stack.append(self.TEXT) self.inside.append(self.TEXT) self.text = 'context' self.chars = "" return elif name == "text" and ('inkscape:label' in attrs) and attrs['inkscape:label'] == 'icon-name': self.stack.append(self.TEXT) self.inside.append(self.TEXT) self.text = 'icon-name' self.chars = "" return elif name == "rect": self.rects.append(attrs) self.stack.append(self.OTHER)
solus-cold-storage/evopop-gtk-theme
[ 190, 17, 190, 5, 1424038763 ]
def characters(self, chars): self.chars += chars.strip()
solus-cold-storage/evopop-gtk-theme
[ 190, 17, 190, 5, 1424038763 ]
def get_example_filepath(fname) -> Path: r"""Return absolute path to an example file if exist. Parameters ---------- fname : str Filename of an existing example file. Returns ------- Filepath Absolute filepath to an example file if exists. Notes ----- A ValueError is raised if the provided filename does not represent an existing example file. Examples -------- >>> fpath = get_example_filepath('examples.xlsx') """ fpath = (EXAMPLE_FILES_DIR / fname).absolute() if not fpath.exists(): AVAILABLE_EXAMPLE_FILES = os.listdir(EXAMPLE_FILES_DIR) raise ValueError(f"Example file {fname} does not exist. " f"Available example files are: {AVAILABLE_EXAMPLE_FILES}") return fpath
liam2/larray
[ 8, 5, 8, 228, 1392806323 ]
def enable_signed_values(request): """ Use signed values when running tests it this module. """ tmp = conf.SIGNED_VALUES conf.SIGNED_VALUES = True def fin(): conf.SIGNED_VALUES = tmp request.addfinalizer(fin)
AdvancedClimateSystems/python-modbus
[ 189, 68, 189, 36, 1444769179 ]
def test_response_on_single_bit_value_read_requests(sock, function): """ Validate response of a succesful Read Coils or Read Discrete Inputs request. """ slave_id, starting_address, quantity = (1, 0, 10) req_adu = function(slave_id, starting_address, quantity) assert tcp.send_message(req_adu, sock) == [0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
AdvancedClimateSystems/python-modbus
[ 189, 68, 189, 36, 1444769179 ]
def test_response_on_multi_bit_value_read_requests(sock, function): """ Validate response of a succesful Read Holding Registers or Read Input Registers request. """ slave_id, starting_address, quantity = (1, 0, 10) req_adu = function(slave_id, starting_address, quantity) assert tcp.send_message(req_adu, sock) ==\ [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
AdvancedClimateSystems/python-modbus
[ 189, 68, 189, 36, 1444769179 ]
def test_response_single_value_write_request(sock, function, value): """ Validate responde of succesful Read Single Coil and Read Single Register request. """ slave_id, starting_address, value = (1, 0, value) req_adu = function(slave_id, starting_address, value) assert tcp.send_message(req_adu, sock) == value
AdvancedClimateSystems/python-modbus
[ 189, 68, 189, 36, 1444769179 ]
def _build_from_url(attrs): if 'url' in attrs and 'content' not in attrs: try: resp = jarr_get(attrs['url'], timeout=conf.crawler.timeout, user_agent=conf.crawler.user_agent) except Exception: return attrs attrs.update({'url': resp.url, 'mimetype': resp.headers.get('content-type', None), 'content': base64.b64encode(resp.content).decode('utf8')}) return attrs
jaesivsm/pyAggr3g470r
[ 102, 11, 102, 29, 1402574029 ]
def update(self, filters, attrs, return_objs=False, commit=True): attrs = self._build_from_url(attrs) return super().update(filters, attrs, return_objs, commit)
jaesivsm/pyAggr3g470r
[ 102, 11, 102, 29, 1402574029 ]
def falseMatchDendritevsMPatterns(n_=1000): a_ = 30 theta_ = 10 s_ = 20 # Arrays used for plotting MList = [] errorList = [] print "\n\nn=%d, a=%d, theta=%d, s=%d" % (n_,a_,theta_,s_) error = 0.0 for M_ in range(1, 40): # Number of bits active in At atAfterUnion = numOnBits.subs(n, n_).subs(s, a_).subs(M,M_).evalf() if error >= 0.9999999999: error = 1.0 else: if M_ <= 8: eq3 = subsampledFpFSlow.subs(n, n_).subs(a, atAfterUnion).subs(theta, theta_) else: eq3 = subsampledFpF.subs(n, n_).subs(a, atAfterUnion).subs(theta, theta_) error = eq3.subs(s,s_).evalf() print M_,atAfterUnion,error MList.append(M_) errorList.append(error) print MList print errorList return MList,errorList
numenta/htmresearch
[ 222, 109, 222, 35, 1409632950 ]
def falseMatchvsM(n_=1000): a_ = 200 theta_ = 15 s_ = 25 # Arrays used for plotting MList = [] errorList = [] print "\n\nn=%d, a=%d, theta=%d, s=%d" % (n_,a_,theta_,s_) error = 0.0 for M_ in range(1, 20): # Need this otherwise calculation goes to 0 numSynapsesAfterUnion = numOnBits.subs(n, n_).subs(s, s_).subs(M, M_).evalf() if error >= 0.9999999999: error = 1.0 else: if M_ <= 2: eq3 = subsampledFpFSlow.subs(n, n_).subs(a, a_).subs(theta, theta_) else: eq3 = subsampledFpF.subs(n, n_).subs(a, a_).subs(theta, theta_) error = eq3.subs(s,round(numSynapsesAfterUnion)).evalf() print M_,numSynapsesAfterUnion,error MList.append(M_) errorList.append(error) print MList print errorList return MList,errorList
numenta/htmresearch
[ 222, 109, 222, 35, 1409632950 ]
def synapsesvsM(s_ = 25): # Compute number of synapses on a segment as a function of M listofMValues = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] listofSynapses = [] n_=1000 print "\n\nn=%d, s=%d" % (n_,s_) for M_ in listofMValues: numSynapsesAfterUnion = numOnBits.subs(n,n_).subs(s,s_).subs(M,M_).evalf() listofSynapses.append(numSynapsesAfterUnion) print listofSynapses
numenta/htmresearch
[ 222, 109, 222, 35, 1409632950 ]
def __init__( self, pybullet_client, mocap_data, timeStep, useFixedBase=True, arg_parser=None, useComReward=False): self._pybullet_client = pybullet_client self._mocap_data = mocap_data self._arg_parser = arg_parser print("LOADING humanoid!") flags=self._pybullet_client.URDF_MAINTAIN_LINK_ORDER+self._pybullet_client.URDF_USE_SELF_COLLISION+self._pybullet_client.URDF_USE_SELF_COLLISION_EXCLUDE_ALL_PARENTS self._sim_model = self._pybullet_client.loadURDF( "humanoid/humanoid.urdf", [0, 0.889540259, 0], globalScaling=0.25, useFixedBase=useFixedBase, flags=flags) #self._pybullet_client.setCollisionFilterGroupMask(self._sim_model,-1,collisionFilterGroup=0,collisionFilterMask=0) #for j in range (self._pybullet_client.getNumJoints(self._sim_model)): # self._pybullet_client.setCollisionFilterGroupMask(self._sim_model,j,collisionFilterGroup=0,collisionFilterMask=0) self._end_effectors = [5, 8, 11, 14] #ankle and wrist, both left and right self._kin_model = self._pybullet_client.loadURDF( "humanoid/humanoid.urdf", [0, 0.85, 0], globalScaling=0.25, useFixedBase=True, flags=self._pybullet_client.URDF_MAINTAIN_LINK_ORDER) self._pybullet_client.changeDynamics(self._sim_model, -1, lateralFriction=0.9) for j in range(self._pybullet_client.getNumJoints(self._sim_model)): self._pybullet_client.changeDynamics(self._sim_model, j, lateralFriction=0.9) self._pybullet_client.changeDynamics(self._sim_model, -1, linearDamping=0, angularDamping=0) self._pybullet_client.changeDynamics(self._kin_model, -1, linearDamping=0, angularDamping=0) #todo: add feature to disable simulation for a particular object. Until then, disable all collisions self._pybullet_client.setCollisionFilterGroupMask(self._kin_model, -1, collisionFilterGroup=0, collisionFilterMask=0) self._pybullet_client.changeDynamics( self._kin_model, -1, activationState=self._pybullet_client.ACTIVATION_STATE_SLEEP + self._pybullet_client.ACTIVATION_STATE_ENABLE_SLEEPING + self._pybullet_client.ACTIVATION_STATE_DISABLE_WAKEUP) alpha = 0.4 self._pybullet_client.changeVisualShape(self._kin_model, -1, rgbaColor=[1, 1, 1, alpha]) for j in range(self._pybullet_client.getNumJoints(self._kin_model)): self._pybullet_client.setCollisionFilterGroupMask(self._kin_model, j, collisionFilterGroup=0, collisionFilterMask=0) self._pybullet_client.changeDynamics( self._kin_model, j, activationState=self._pybullet_client.ACTIVATION_STATE_SLEEP + self._pybullet_client.ACTIVATION_STATE_ENABLE_SLEEPING + self._pybullet_client.ACTIVATION_STATE_DISABLE_WAKEUP) self._pybullet_client.changeVisualShape(self._kin_model, j, rgbaColor=[1, 1, 1, alpha]) self._poseInterpolator = humanoid_pose_interpolator.HumanoidPoseInterpolator() for i in range(self._mocap_data.NumFrames() - 1): frameData = self._mocap_data._motion_data['Frames'][i] self._poseInterpolator.PostProcessMotionData(frameData) self._stablePD = pd_controller_stable.PDControllerStableMultiDof(self._pybullet_client) self._timeStep = timeStep self._kpOrg = [ 0, 0, 0, 0, 0, 0, 0, 1000, 1000, 1000, 1000, 100, 100, 100, 100, 500, 500, 500, 500, 500, 400, 400, 400, 400, 400, 400, 400, 400, 300, 500, 500, 500, 500, 500, 400, 400, 400, 400, 400, 400, 400, 400, 300 ] self._kdOrg = [ 0, 0, 0, 0, 0, 0, 0, 100, 100, 100, 100, 10, 10, 10, 10, 50, 50, 50, 50, 50, 40, 40, 40, 40, 40, 40, 40, 40, 30, 50, 50, 50, 50, 50, 40, 40, 40, 40, 40, 40, 40, 40, 30 ] self._jointIndicesAll = [ chest, neck, rightHip, rightKnee, rightAnkle, rightShoulder, rightElbow, leftHip, leftKnee, leftAnkle, leftShoulder, leftElbow ] for j in self._jointIndicesAll: #self._pybullet_client.setJointMotorControlMultiDof(self._sim_model, j, self._pybullet_client.POSITION_CONTROL, force=[1,1,1]) self._pybullet_client.setJointMotorControl2(self._sim_model, j, self._pybullet_client.POSITION_CONTROL, targetPosition=0, positionGain=0, targetVelocity=0, force=jointFrictionForce) self._pybullet_client.setJointMotorControlMultiDof( self._sim_model, j, self._pybullet_client.POSITION_CONTROL, targetPosition=[0, 0, 0, 1], targetVelocity=[0, 0, 0], positionGain=0, velocityGain=1, force=[jointFrictionForce, jointFrictionForce, jointFrictionForce]) self._pybullet_client.setJointMotorControl2(self._kin_model, j, self._pybullet_client.POSITION_CONTROL, targetPosition=0, positionGain=0, targetVelocity=0, force=0) self._pybullet_client.setJointMotorControlMultiDof( self._kin_model, j, self._pybullet_client.POSITION_CONTROL, targetPosition=[0, 0, 0, 1], targetVelocity=[0, 0, 0], positionGain=0, velocityGain=1, force=[jointFrictionForce, jointFrictionForce, 0]) self._jointDofCounts = [4, 4, 4, 1, 4, 4, 1, 4, 1, 4, 4, 1] #only those body parts/links are allowed to touch the ground, otherwise the episode terminates fall_contact_bodies = [] if self._arg_parser is not None: fall_contact_bodies = self._arg_parser.parse_ints("fall_contact_bodies") self._fall_contact_body_parts = fall_contact_bodies #[x,y,z] base position and [x,y,z,w] base orientation! self._totalDofs = 7 for dof in self._jointDofCounts: self._totalDofs += dof self.setSimTime(0) self._useComReward = useComReward self.resetPose()
nrz/ylikuutio
[ 17, 2, 17, 1, 1457044218 ]
def initializePose(self, pose, phys_model, initBase, initializeVelocity=True):
nrz/ylikuutio
[ 17, 2, 17, 1, 1457044218 ]
def calcCycleCount(self, simTime, cycleTime): phases = simTime / cycleTime count = math.floor(phases) loop = True #count = (loop) ? count : cMathUtil::Clamp(count, 0, 1); return count
nrz/ylikuutio
[ 17, 2, 17, 1, 1457044218 ]
def setSimTime(self, t): self._simTime = t #print("SetTimeTime time =",t) keyFrameDuration = self._mocap_data.KeyFrameDuraction() cycleTime = self.getCycleTime() #print("self._motion_data.NumFrames()=",self._mocap_data.NumFrames()) self._cycleCount = self.calcCycleCount(t, cycleTime) #print("cycles=",cycles) frameTime = t - self._cycleCount * cycleTime if (frameTime < 0): frameTime += cycleTime #print("keyFrameDuration=",keyFrameDuration) #print("frameTime=",frameTime) self._frame = int(frameTime / keyFrameDuration) #print("self._frame=",self._frame) self._frameNext = self._frame + 1 if (self._frameNext >= self._mocap_data.NumFrames()): self._frameNext = self._frame self._frameFraction = (frameTime - self._frame * keyFrameDuration) / (keyFrameDuration)
nrz/ylikuutio
[ 17, 2, 17, 1, 1457044218 ]
def computePose(self, frameFraction): frameData = self._mocap_data._motion_data['Frames'][self._frame] frameDataNext = self._mocap_data._motion_data['Frames'][self._frameNext] self._poseInterpolator.Slerp(frameFraction, frameData, frameDataNext, self._pybullet_client) #print("self._poseInterpolator.Slerp(", frameFraction,")=", pose) self.computeCycleOffset() oldPos = self._poseInterpolator._basePos self._poseInterpolator._basePos = [ oldPos[0] + self._cycleCount * self._cycleOffset[0], oldPos[1] + self._cycleCount * self._cycleOffset[1], oldPos[2] + self._cycleCount * self._cycleOffset[2] ] pose = self._poseInterpolator.GetPose() return pose
nrz/ylikuutio
[ 17, 2, 17, 1, 1457044218 ]
def computeAndApplyPDForces(self, desiredPositions, maxForces): dofIndex = 7 scaling = 1 indices = [] forces = [] targetPositions=[] targetVelocities=[] kps = [] kds = []
nrz/ylikuutio
[ 17, 2, 17, 1, 1457044218 ]
def computePDForces(self, desiredPositions, desiredVelocities, maxForces): """Compute torques from the PD controller.""" if desiredVelocities == None: desiredVelocities = [0] * self._totalDofs taus = self._stablePD.computePD(bodyUniqueId=self._sim_model, jointIndices=self._jointIndicesAll, desiredPositions=desiredPositions, desiredVelocities=desiredVelocities, kps=self._kpOrg, kds=self._kdOrg, maxForces=maxForces, timeStep=self._timeStep) return taus
nrz/ylikuutio
[ 17, 2, 17, 1, 1457044218 ]
def setJointMotors(self, desiredPositions, maxForces): controlMode = self._pybullet_client.POSITION_CONTROL startIndex = 7 chest = 1 neck = 2 rightHip = 3 rightKnee = 4 rightAnkle = 5 rightShoulder = 6 rightElbow = 7 leftHip = 9 leftKnee = 10 leftAnkle = 11 leftShoulder = 12 leftElbow = 13 kp = 0.2 forceScale = 1 #self._jointDofCounts=[4,4,4,1,4,4,1,4,1,4,4,1] maxForce = [ forceScale * maxForces[startIndex], forceScale * maxForces[startIndex + 1], forceScale * maxForces[startIndex + 2], forceScale * maxForces[startIndex + 3] ] startIndex += 4 self._pybullet_client.setJointMotorControlMultiDof( self._sim_model, chest, controlMode, targetPosition=self._poseInterpolator._chestRot, positionGain=kp, force=maxForce) maxForce = [ maxForces[startIndex], maxForces[startIndex + 1], maxForces[startIndex + 2], maxForces[startIndex + 3] ] startIndex += 4 self._pybullet_client.setJointMotorControlMultiDof( self._sim_model, neck, controlMode, targetPosition=self._poseInterpolator._neckRot, positionGain=kp, force=maxForce) maxForce = [ maxForces[startIndex], maxForces[startIndex + 1], maxForces[startIndex + 2], maxForces[startIndex + 3] ] startIndex += 4 self._pybullet_client.setJointMotorControlMultiDof( self._sim_model, rightHip, controlMode, targetPosition=self._poseInterpolator._rightHipRot, positionGain=kp, force=maxForce) maxForce = [forceScale * maxForces[startIndex]] startIndex += 1 self._pybullet_client.setJointMotorControlMultiDof( self._sim_model, rightKnee, controlMode, targetPosition=self._poseInterpolator._rightKneeRot, positionGain=kp, force=maxForce) maxForce = [ maxForces[startIndex], maxForces[startIndex + 1], maxForces[startIndex + 2], maxForces[startIndex + 3] ] startIndex += 4 self._pybullet_client.setJointMotorControlMultiDof( self._sim_model, rightAnkle, controlMode, targetPosition=self._poseInterpolator._rightAnkleRot, positionGain=kp, force=maxForce) maxForce = [ forceScale * maxForces[startIndex], forceScale * maxForces[startIndex + 1], forceScale * maxForces[startIndex + 2], forceScale * maxForces[startIndex + 3] ] startIndex += 4 maxForce = [forceScale * maxForces[startIndex]] startIndex += 1 self._pybullet_client.setJointMotorControlMultiDof( self._sim_model, rightElbow, controlMode, targetPosition=self._poseInterpolator._rightElbowRot, positionGain=kp, force=maxForce) maxForce = [ maxForces[startIndex], maxForces[startIndex + 1], maxForces[startIndex + 2], maxForces[startIndex + 3] ] startIndex += 4 self._pybullet_client.setJointMotorControlMultiDof( self._sim_model, leftHip, controlMode, targetPosition=self._poseInterpolator._leftHipRot, positionGain=kp, force=maxForce) maxForce = [forceScale * maxForces[startIndex]] startIndex += 1 self._pybullet_client.setJointMotorControlMultiDof( self._sim_model, leftKnee, controlMode, targetPosition=self._poseInterpolator._leftKneeRot, positionGain=kp, force=maxForce) maxForce = [ maxForces[startIndex], maxForces[startIndex + 1], maxForces[startIndex + 2], maxForces[startIndex + 3] ] startIndex += 4 self._pybullet_client.setJointMotorControlMultiDof( self._sim_model, leftAnkle, controlMode, targetPosition=self._poseInterpolator._leftAnkleRot, positionGain=kp, force=maxForce) maxForce = [ maxForces[startIndex], maxForces[startIndex + 1], maxForces[startIndex + 2], maxForces[startIndex + 3] ] startIndex += 4 self._pybullet_client.setJointMotorControlMultiDof( self._sim_model, leftShoulder, controlMode, targetPosition=self._poseInterpolator._leftShoulderRot, positionGain=kp, force=maxForce) maxForce = [forceScale * maxForces[startIndex]] startIndex += 1 self._pybullet_client.setJointMotorControlMultiDof( self._sim_model, leftElbow, controlMode, targetPosition=self._poseInterpolator._leftElbowRot, positionGain=kp, force=maxForce) #print("startIndex=",startIndex)
nrz/ylikuutio
[ 17, 2, 17, 1, 1457044218 ]
def buildHeadingTrans(self, rootOrn): #align root transform 'forward' with world-space x axis eul = self._pybullet_client.getEulerFromQuaternion(rootOrn) refDir = [1, 0, 0] rotVec = self._pybullet_client.rotateVector(rootOrn, refDir) heading = math.atan2(-rotVec[2], rotVec[0]) heading2 = eul[1] #print("heading=",heading) headingOrn = self._pybullet_client.getQuaternionFromAxisAngle([0, 1, 0], -heading) return headingOrn
nrz/ylikuutio
[ 17, 2, 17, 1, 1457044218 ]
def getState(self): stateVector = [] phase = self.getPhase() #print("phase=",phase) stateVector.append(phase) rootTransPos, rootTransOrn = self.buildOriginTrans() basePos, baseOrn = self._pybullet_client.getBasePositionAndOrientation(self._sim_model) rootPosRel, dummy = self._pybullet_client.multiplyTransforms(rootTransPos, rootTransOrn, basePos, [0, 0, 0, 1]) #print("!!!rootPosRel =",rootPosRel ) #print("rootTransPos=",rootTransPos) #print("basePos=",basePos) localPos, localOrn = self._pybullet_client.multiplyTransforms(rootTransPos, rootTransOrn, basePos, baseOrn) localPos = [ localPos[0] - rootPosRel[0], localPos[1] - rootPosRel[1], localPos[2] - rootPosRel[2] ] #print("localPos=",localPos) stateVector.append(rootPosRel[1]) #self.pb2dmJoints=[0,1,2,9,10,11,3,4,5,12,13,14,6,7,8] self.pb2dmJoints = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] linkIndicesSim = [] for pbJoint in range(self._pybullet_client.getNumJoints(self._sim_model)): linkIndicesSim.append(self.pb2dmJoints[pbJoint])
nrz/ylikuutio
[ 17, 2, 17, 1, 1457044218 ]
def terminates(self): #check if any non-allowed body part hits the ground terminates = False pts = self._pybullet_client.getContactPoints() for p in pts: part = -1 #ignore self-collision if (p[1] == p[2]): continue if (p[1] == self._sim_model): part = p[3] if (p[2] == self._sim_model): part = p[4] if (part >= 0 and part in self._fall_contact_body_parts): #print("terminating part:", part) terminates = True return terminates
nrz/ylikuutio
[ 17, 2, 17, 1, 1457044218 ]
def calcRootAngVelErr(self, vel0, vel1): diff = [vel0[0] - vel1[0], vel0[1] - vel1[1], vel0[2] - vel1[2]] return diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2]
nrz/ylikuutio
[ 17, 2, 17, 1, 1457044218 ]
def getReward(self, pose): """Compute and return the pose-based reward.""" #from DeepMimic double cSceneImitate::CalcRewardImitate #todo: compensate for ground height in some parts, once we move to non-flat terrain # not values from the paper, but from the published code. pose_w = 0.5 vel_w = 0.05 end_eff_w = 0.15 # does not exist in paper root_w = 0.2 if self._useComReward: com_w = 0.1 else: com_w = 0 total_w = pose_w + vel_w + end_eff_w + root_w + com_w pose_w /= total_w vel_w /= total_w end_eff_w /= total_w root_w /= total_w com_w /= total_w pose_scale = 2 vel_scale = 0.1 end_eff_scale = 40 root_scale = 5 com_scale = 10 err_scale = 1 # error scale reward = 0 pose_err = 0 vel_err = 0 end_eff_err = 0 root_err = 0 com_err = 0 heading_err = 0 #create a mimic reward, comparing the dynamics humanoid with a kinematic one #pose = self.InitializePoseFromMotionData() #print("self._kin_model=",self._kin_model) #print("kinematicHumanoid #joints=",self._pybullet_client.getNumJoints(self._kin_model)) #self.ApplyPose(pose, True, True, self._kin_model, self._pybullet_client) #const Eigen::VectorXd& pose0 = sim_char.GetPose(); #const Eigen::VectorXd& vel0 = sim_char.GetVel(); #const Eigen::VectorXd& pose1 = kin_char.GetPose(); #const Eigen::VectorXd& vel1 = kin_char.GetVel(); #tMatrix origin_trans = sim_char.BuildOriginTrans(); #tMatrix kin_origin_trans = kin_char.BuildOriginTrans(); # #tVector com0_world = sim_char.CalcCOM(); if self._useComReward: comSim, comSimVel = self.computeCOMposVel(self._sim_model) comKin, comKinVel = self.computeCOMposVel(self._kin_model) #tVector com_vel0_world = sim_char.CalcCOMVel(); #tVector com1_world; #tVector com_vel1_world; #cRBDUtil::CalcCoM(joint_mat, body_defs, pose1, vel1, com1_world, com_vel1_world); # root_id = 0 #tVector root_pos0 = cKinTree::GetRootPos(joint_mat, pose0); #tVector root_pos1 = cKinTree::GetRootPos(joint_mat, pose1); #tQuaternion root_rot0 = cKinTree::GetRootRot(joint_mat, pose0); #tQuaternion root_rot1 = cKinTree::GetRootRot(joint_mat, pose1); #tVector root_vel0 = cKinTree::GetRootVel(joint_mat, vel0); #tVector root_vel1 = cKinTree::GetRootVel(joint_mat, vel1); #tVector root_ang_vel0 = cKinTree::GetRootAngVel(joint_mat, vel0); #tVector root_ang_vel1 = cKinTree::GetRootAngVel(joint_mat, vel1); mJointWeights = [ 0.20833, 0.10416, 0.0625, 0.10416, 0.0625, 0.041666666666666671, 0.0625, 0.0416, 0.00, 0.10416, 0.0625, 0.0416, 0.0625, 0.0416, 0.0000 ] num_end_effs = 0 num_joints = 15 root_rot_w = mJointWeights[root_id] rootPosSim, rootOrnSim = self._pybullet_client.getBasePositionAndOrientation(self._sim_model) rootPosKin, rootOrnKin = self._pybullet_client.getBasePositionAndOrientation(self._kin_model) linVelSim, angVelSim = self._pybullet_client.getBaseVelocity(self._sim_model) #don't read the velocities from the kinematic model (they are zero), use the pose interpolator velocity #see also issue https://github.com/bulletphysics/bullet3/issues/2401 linVelKin = self._poseInterpolator._baseLinVel angVelKin = self._poseInterpolator._baseAngVel root_rot_err = self.calcRootRotDiff(rootOrnSim, rootOrnKin) pose_err += root_rot_w * root_rot_err root_vel_diff = [ linVelSim[0] - linVelKin[0], linVelSim[1] - linVelKin[1], linVelSim[2] - linVelKin[2] ] root_vel_err = root_vel_diff[0] * root_vel_diff[0] + root_vel_diff[1] * root_vel_diff[ 1] + root_vel_diff[2] * root_vel_diff[2] root_ang_vel_err = self.calcRootAngVelErr(angVelSim, angVelKin) vel_err += root_rot_w * root_ang_vel_err useArray = True
nrz/ylikuutio
[ 17, 2, 17, 1, 1457044218 ]
def __init__(self, parent):
MTG/sms-tools
[ 1480, 707, 1480, 12, 1374853453 ]
def initUI(self): choose_label = "Input file (.wav, mono and 44100 sampling rate):" Label(self.parent, text=choose_label).grid(row=0, column=0, sticky=W, padx=5, pady=(10,2))
MTG/sms-tools
[ 1480, 707, 1480, 12, 1374853453 ]
def browse_file(self):
MTG/sms-tools
[ 1480, 707, 1480, 12, 1374853453 ]
def compute_model(self):
MTG/sms-tools
[ 1480, 707, 1480, 12, 1374853453 ]
def test_uuid_conversion(self): uuid = '089ffb20-5d19-4a8c-bb80-13650627d985' pvm_uuid = uuid_utils.convert_uuid_to_pvm(uuid) self.assertEqual(uuid, pvm_uuid) uuid = '989ffb20-5d19-4a8c-bb80-13650627d985' pvm_uuid = uuid_utils.convert_uuid_to_pvm(uuid) self.assertEqual('1' + uuid[1:], pvm_uuid) uuid = 'c89ffb20-5d19-4a8c-bb80-13650627d985' pvm_uuid = uuid_utils.convert_uuid_to_pvm(uuid) self.assertEqual('4' + uuid[1:], pvm_uuid)
powervm/pypowervm
[ 27, 13, 27, 7, 1421699339 ]
def make_endpoint(endpoint: str) -> str: endpoint = endpoint return endpoint
googleapis/python-aiplatform
[ 306, 205, 306, 52, 1600875819 ]
def upgrade(): """Create DagCode Table.""" from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class SerializedDagModel(Base): __tablename__ = 'serialized_dag' # There are other columns here, but these are the only ones we need for the SELECT/UPDATE we are doing dag_id = sa.Column(sa.String(250), primary_key=True) fileloc = sa.Column(sa.String(2000), nullable=False) fileloc_hash = sa.Column(sa.BigInteger, nullable=False) """Apply add source code table""" op.create_table( 'dag_code', sa.Column('fileloc_hash', sa.BigInteger(), nullable=False, primary_key=True, autoincrement=False), sa.Column('fileloc', sa.String(length=2000), nullable=False), sa.Column('source_code', sa.UnicodeText(), nullable=False), sa.Column('last_updated', sa.TIMESTAMP(timezone=True), nullable=False), ) conn = op.get_bind() if conn.dialect.name != 'sqlite': if conn.dialect.name == "mssql": op.drop_index('idx_fileloc_hash', 'serialized_dag') op.alter_column( table_name='serialized_dag', column_name='fileloc_hash', type_=sa.BigInteger(), nullable=False ) if conn.dialect.name == "mssql": op.create_index('idx_fileloc_hash', 'serialized_dag', ['fileloc_hash']) sessionmaker = sa.orm.sessionmaker() session = sessionmaker(bind=conn) serialized_dags = session.query(SerializedDagModel).all() for dag in serialized_dags: dag.fileloc_hash = DagCode.dag_fileloc_hash(dag.fileloc) session.merge(dag) session.commit()
apache/airflow
[ 29418, 12033, 29418, 869, 1428948298 ]
def __init__(self, stack_state): super(StackTraceModel, self).__init__( text_view=text_views.StackTraceView()) if (stack_state is not None): self['lines'] = [ {'filename': fn, 'line': ln, 'name': nm, 'code': cd} for fn, ln, nm, cd in traceback.extract_stack(stack_state) ] # FIXME(flepied): under Python3 f_exc_type doesn't exist # anymore so we lose information about exceptions if getattr(stack_state, 'f_exc_type', None) is not None: self['root_exception'] = { 'type': stack_state.f_exc_type, 'value': stack_state.f_exc_value} else: self['root_exception'] = None else: self['lines'] = [] self['root_exception'] = None
SylvainA/os-event-catcher
[ 1, 3, 1, 1, 1410295543 ]
def __init__(self, thread_id, stack): super(ThreadModel, self).__init__(text_view=text_views.ThreadView()) self['thread_id'] = thread_id self['stack_trace'] = StackTraceModel(stack)
SylvainA/os-event-catcher
[ 1, 3, 1, 1, 1410295543 ]
def forwards(self, orm): # Adding model 'Accreditation' db.create_table(u'units_accreditation', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('unite', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['units.Unit'])), ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['users.TruffeUser'])), ('role', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['units.Role'])), ('start_date', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), ('end_date', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)), ('validation_date', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), ('display_name', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True)), )) db.send_create_signal(u'units', ['Accreditation'])
ArcaniteSolutions/truffe2
[ 13, 12, 13, 7, 1439638478 ]
def hello(i): print(i)
cr0hn/OMSTD
[ 25, 20, 25, 39, 1415802772 ]
def main(): p = Pool(10) p.map(hello, range(50))
cr0hn/OMSTD
[ 25, 20, 25, 39, 1415802772 ]
def __init__(self, initial_score=10, # the initial score sound_params = {'direction':0.0}, # properties of the score response sound gain_file = 'ding.wav', # sound file per point loss_file = 'xBuzz01.wav', # sound file for losses none_file = 'click.wav', # file to play if no reward ding_interval = 0.2, # interval at which successive gain sounds are played... (if score is > 1) buzz_volume = 0.1, # volume of the buzz (multiplied by the amount of loss) gain_volume = 0.5, # volume of the gain sound ): ConvenienceFunctions.__init__(self) self.score = initial_score self.params = sound_params self.gain_file = gain_file self.loss_file = loss_file self.none_file = none_file self.ding_interval = ding_interval self.buzz_volume = buzz_volume self.gain_volume = gain_volume
sccn/SNAP
[ 26, 14, 26, 2, 1355612553 ]
def play_gain(self,task): self.sound(self.gain_file,volume=self.gain_volume,**self.params) self.marker(1) return task.done
sccn/SNAP
[ 26, 14, 26, 2, 1355612553 ]
def __init__(self, # general properties rewardlogic, # reward handling logic watcher = None, # optional event watcher focused = True, # whether this task is currently focused markerbase = 1, # markers markerbase..markerbase+6 are used event_interval=lambda: random.uniform(45,85), # interval between two successive events # cueing control cueobj = None, # an object that might have .iscued set to true # graphics parameters pic_off='light_off.png', # picture to display for the disabled light pic_on='light_on.png', # picture to display for the enabled light screen_offset=0, # offset to position this icon on one of the three screens pic_params={'pos':[0,0],'scale':0.15}, # parameters for the picture() command snd_params={'volume':0.3,'direction':0.0}, # parameters for the sound() command
sccn/SNAP
[ 26, 14, 26, 2, 1355612553 ]
def run(self): self.pic_params['pos'][0] += self.screen_offset # pre-cache the media files... self.precache_picture(self.pic_on) self.precache_picture(self.pic_off) self.precache_picture(self.pic_tick_on) self.precache_picture(self.pic_tick_off) self.precache_sound(self.snd_wrongcue) self.precache_sound(self.snd_hit) self.accept('control',self.oncontrol,[True]) self.accept('control-up',self.oncontrol,[False])
sccn/SNAP
[ 26, 14, 26, 2, 1355612553 ]
def oncontrol(self,status): self.control = status
sccn/SNAP
[ 26, 14, 26, 2, 1355612553 ]
def false_detection(self): self.marker(self.markerbase+4) self.rewardlogic.score_event(self.false_penalty)
sccn/SNAP
[ 26, 14, 26, 2, 1355612553 ]
def correct(self): if self.focused: if ((self.cueobj is not None) and self.cueobj.iscued): self.marker(self.markerbase+5 if self.control else self.markerbase+6) else: self.marker(self.markerbase+7 if self.control else self.markerbase+8) if self.control == ((self.cueobj is not None) and self.cueobj.iscued): # the user correctly spots the warning event self.sound(self.snd_hit,**self.snd_params) self.rewardlogic.score_event(self.hit_reward) else: # the user spotted it, but didn't get the cue right self.sound(self.snd_wrongcue,**self.snd_params) self.rewardlogic.score_event(self.false_penalty) else: self.marker(self.markerbase+9) # the user spotted it, but was not tasked to do so... self.rewardlogic.score_event(self.false_penalty)
sccn/SNAP
[ 26, 14, 26, 2, 1355612553 ]
def __init__(self, rewardlogic, focused = True, # whether this task is currently focused markerbase = 1, # markers markerbase..markerbase+6 are used event_interval=lambda: random.uniform(45,85), # interval between two successive events pic_off='light_off.png', # picture to display for the disabled light pic_on='light_on.png', # picture to display for the enabled light screen_offset=0, # offset to position this icon on one of the three screens pic_params={'pos':[0,0],'scale':0.15}, # parameters for the picture() command duration = 1.5, # duration for which the cue light stays on ):
sccn/SNAP
[ 26, 14, 26, 2, 1355612553 ]
def run(self): self.pic_params['pos'][0] += self.screen_offset # pre-cache the media files... self.precache_picture(self.pic_on) self.precache_picture(self.pic_off) while True: if not self.focused: self.iscued = False # show the "off" picture for the inter-event interval self.picture(self.pic_off, self.event_interval(), **self.pic_params) # show the "on" picture and cue the other items self.marker(self.markerbase+1) if self.focused: self.iscued = True self.picture(self.pic_on, self.duration, **self.pic_params)
sccn/SNAP
[ 26, 14, 26, 2, 1355612553 ]
def __init__(self, # general properties rewardlogic, # reward handling logic watcher = None, # response event watcher focused = True, # whether this task is currently focused markerbase = 1, # markers markerbase..markerbase+6 are used event_interval=lambda: random.uniform(45,85), # interval between two successive events # cueing control cueobj = None, # an object that might have .iscued set to true # audio parameters screen_offset=0, # offset to position this source on one of the three screens snd_on='xHyprBlip.wav', # sound to play in case of an event snd_params={'volume':0.25,'direction':0.0}, # parameters for the sound() command
sccn/SNAP
[ 26, 14, 26, 2, 1355612553 ]
def run(self): self.snd_params['direction'] += self.screen_offset # pre-cache the media files... self.precache_sound(self.snd_on) self.precache_sound(self.snd_tick_on) self.precache_sound(self.snd_tick_off) self.precache_sound(self.snd_wrongcue) self.precache_sound(self.snd_hit) self.accept('control',self.oncontrol,[True]) self.accept('control-up',self.oncontrol,[False])
sccn/SNAP
[ 26, 14, 26, 2, 1355612553 ]
def oncontrol(self,status): self.control = status
sccn/SNAP
[ 26, 14, 26, 2, 1355612553 ]
def false_detection(self): self.marker(self.markerbase+4) self.rewardlogic.score_event(self.false_penalty)
sccn/SNAP
[ 26, 14, 26, 2, 1355612553 ]
def correct(self): if self.focused: if ((self.cueobj is not None) and self.cueobj.iscued): self.marker(self.markerbase+5 if self.control else self.markerbase+6) else: self.marker(self.markerbase+7 if self.control else self.markerbase+8) if self.control == ((self.cueobj is not None) and self.cueobj.iscued): # the user correctly spots the warning event self.sound(self.snd_hit,**self.snd_params) self.rewardlogic.score_event(self.hit_reward) else: # the user spotted it, but didn't get the cue right self.sound(self.snd_wrongcue,**self.snd_params) self.rewardlogic.score_event(self.false_penalty) else: self.marker(self.markerbase+9) # the user spotted it, but was not tasked to do so... self.rewardlogic.score_event(self.false_penalty)
sccn/SNAP
[ 26, 14, 26, 2, 1355612553 ]
def __init__(self, rewardlogic, focused = True, # whether this task is currently focused markerbase = 1, # markers markerbase..markerbase+6 are used event_interval=lambda: random.uniform(45,85), # interval between two successive events snd_on='xBleep.wav', # picture to display for the enabled light screen_offset=0, # offset to position this icon on one of the three screens snd_params={'volume':0.3,'direction':0.0}, # parameters for the sound() command ):
sccn/SNAP
[ 26, 14, 26, 2, 1355612553 ]
def run(self): self.snd_params['direction'] += self.screen_offset # pre-cache the media files... self.precache_sound(self.snd_on) while True: self.sleep(self.event_interval()) # play the "on" sound and cue the other items self.iscued = self.focused self.sound(self.snd_on, **self.snd_params)
sccn/SNAP
[ 26, 14, 26, 2, 1355612553 ]
def __init__(self, # facilities used by this object rewardhandler=None, # a RewardLogic instance that manages the processing of generated rewards/penalties presenter=None, # the presenter on which to output the math problems presenter_params={'pos':lambda:[random.uniform(-0.5,0.5),random.uniform(-0.5,0)], # parameters of a textpresenter, if no presenter is given 'clearafter':3,'framecolor':[0,0,0,0],'scale':0.1,'align':'center'}, focused = True, # whether this task is currently focused # end conditions end_timeout=None, # end presentation after the timeout has passed end_numproblems=None, # end presentation after this number of problems have been presented
sccn/SNAP
[ 26, 14, 26, 2, 1355612553 ]
def run(self): try: if self.presenter is None: self.presenter = TextPresenter(**self.presenter_params)
sccn/SNAP
[ 26, 14, 26, 2, 1355612553 ]
def on_digit(self,d): self.input += str(d)
sccn/SNAP
[ 26, 14, 26, 2, 1355612553 ]
def __init__(self): LatentModule.__init__(self) self.randseed = 11463 # some initial randseed for the experiment; note that this should be different for each subject (None = random) # block design self.uiblocks = 24 # number of blocks with different UI permutation: should be a multiple of 6 self.focus_per_layout = 8 # number of focus conditions within a UI layout block self.rest_every = 3 # insert a rest period every k UI blocks self.focus_duration = lambda: random.uniform(30,50) # duration of a focus block (was: 30-50) self.initial_rest_time = 10 # initial rest time at the beginning of a new UI layout block self.tasknames = {'sysmonv':'visual system monitoring','sysmona':'auditory system monitoring','comma':'auditory communciations','commv':'text communications','math':'mathematics','satmap':'satellite map','drive':'driving task'} # TODO: make this more complete self.conditions = ['sysmonv-sysmona','commv-comma','math-satmap','math-drive','comma-satmap','comma-drive','comma-sysmona','sysmona-drive','sysmona-satmap','sysmonv','sysmona','commv','comma','satmap','drive','math'] self.bottom_up_probability = 0.5 # probability that the switch stimulus is bottom-up
sccn/SNAP
[ 26, 14, 26, 2, 1355612553 ]
def run(self): try: # init the randseed if self.randseed is not None: print "WARNING: Randomization of the experiment is currently bypassed." random.seed(self.randseed) self.marker(30000+self.randseed)
sccn/SNAP
[ 26, 14, 26, 2, 1355612553 ]
def onspeech(self,phrase,listener): if phrase.lower() == 'roger': self.send_message('comma-roger') self.icon_comma.setScale(self.voice_icon_enlarge_size) self.icon_comma_reset_scale_at = time.time() + self.voice_icon_enlarge_duration taskMgr.doMethodLater(self.voice_icon_enlarge_duration, self.reset_comma, 'reset_comma()')
sccn/SNAP
[ 26, 14, 26, 2, 1355612553 ]
def reset_comma(self,task): if time.time() >= self.icon_comma_reset_scale_at-0.1: self.icon_comma.setScale(0.1) return task.done
sccn/SNAP
[ 26, 14, 26, 2, 1355612553 ]
def clear_objects(self): # remove event watchers self.vismonwatcher.destroy() self.audmonwatcher.destroy() # remove buttons self.icon_sysmona.destroy() self.icon_comma.destroy() self.button_comma.destroy() self.button_commv.destroy() self.button_sysmona.destroy() self.button_sysmonv.destroy() self.button_satmap2.destroy() self.button_drive.destroy() # remove presenters self.mathdisplay.destroy() self.commbox.destroy() self.commsnd.destroy() self.csign.destroy()
sccn/SNAP
[ 26, 14, 26, 2, 1355612553 ]
def sysmona_false_detection(self): self.marker(702) self.rewardlogic.score_event(self.false_response_penalty)
sccn/SNAP
[ 26, 14, 26, 2, 1355612553 ]
def get_args(): parser = ArgumentParser(description='Run health checks of mongo and mtools systems')
ParsePlatform/flashback
[ 216, 72, 216, 7, 1403303564 ]
def create_inactive_user(email, full_name): """ Create inactive user with basic details. Used when moderators invite new users and when a member of the public requests an account. """ User = get_user_model() user = User.objects.create_user(email) user.is_active = False user.full_name = full_name user.set_unusable_password() return user
nlhkabu/connect
[ 47, 25, 47, 18, 1433260168 ]
def get_user(email): """ Retrieve a user based on the supplied email address. Return None if no user has registered this email address. """ User = get_user_model() try: user = User.objects.get(email=email) return user except User.DoesNotExist: return None
nlhkabu/connect
[ 47, 25, 47, 18, 1433260168 ]
def test_objectmapper(self): df = pdml.ModelFrame([]) self.assertIs(df.semi_supervised.LabelPropagation, ss.LabelPropagation) self.assertIs(df.semi_supervised.LabelSpreading, ss.LabelSpreading)
sinhrks/expandas
[ 302, 77, 302, 31, 1424488444 ]
def test_Classifications(self, algo): iris = datasets.load_iris() df = pdml.ModelFrame(iris)
sinhrks/expandas
[ 302, 77, 302, 31, 1424488444 ]
def rollback_env_variables(environ, env_var_subfolders): ''' Generate shell code to reset environment variables by unrolling modifications based on all workspaces in CMAKE_PREFIX_PATH. This does not cover modifications performed by environment hooks. ''' lines = [] unmodified_environ = copy.copy(environ) for key in sorted(env_var_subfolders.keys()): subfolders = env_var_subfolders[key] if not isinstance(subfolders, list): subfolders = [subfolders] for subfolder in subfolders: value = _rollback_env_variable(unmodified_environ, key, subfolder) if value is not None: environ[key] = value lines.append(assignment(key, value)) if lines: lines.insert(0, comment('reset environment variables by unrolling modifications based on all workspaces in CMAKE_PREFIX_PATH')) return lines
jcicolani/Nomad
[ 6, 3, 6, 1, 1446612331 ]
def _get_workspaces(environ, include_fuerte=False, include_non_existing=False): ''' Based on CMAKE_PREFIX_PATH return all catkin workspaces. :param include_fuerte: The flag if paths starting with '/opt/ros/fuerte' should be considered workspaces, ``bool`` ''' # get all cmake prefix paths env_name = 'CMAKE_PREFIX_PATH' value = environ[env_name] if env_name in environ else '' paths = [path for path in value.split(os.pathsep) if path] # remove non-workspace paths workspaces = [path for path in paths if os.path.isfile(os.path.join(path, CATKIN_MARKER_FILE)) or (include_fuerte and path.startswith('/opt/ros/fuerte')) or (include_non_existing and not os.path.exists(path))] return workspaces
jcicolani/Nomad
[ 6, 3, 6, 1, 1446612331 ]
def _prefix_env_variable(environ, name, paths, subfolders): ''' Return the prefix to prepend to the environment variable NAME, adding any path in NEW_PATHS_STR without creating duplicate or empty items. ''' value = environ[name] if name in environ else '' environ_paths = [path for path in value.split(os.pathsep) if path] checked_paths = [] for path in paths: if not isinstance(subfolders, list): subfolders = [subfolders] for subfolder in subfolders: path_tmp = path if subfolder: path_tmp = os.path.join(path_tmp, subfolder) # exclude any path already in env and any path we already added if path_tmp not in environ_paths and path_tmp not in checked_paths: checked_paths.append(path_tmp) prefix_str = os.pathsep.join(checked_paths) if prefix_str != '' and environ_paths: prefix_str += os.pathsep return prefix_str
jcicolani/Nomad
[ 6, 3, 6, 1, 1446612331 ]
def comment(msg): if not IS_WINDOWS: return '# %s' % msg else: return 'REM %s' % msg
jcicolani/Nomad
[ 6, 3, 6, 1, 1446612331 ]
def find_env_hooks(environ, cmake_prefix_path): ''' Generate shell code with found environment hooks for the all workspaces. ''' lines = [] lines.append(comment('found environment hooks in workspaces')) generic_env_hooks = [] generic_env_hooks_workspace = [] specific_env_hooks = [] specific_env_hooks_workspace = [] generic_env_hooks_by_filename = {} specific_env_hooks_by_filename = {} generic_env_hook_ext = 'bat' if IS_WINDOWS else 'sh' specific_env_hook_ext = environ['CATKIN_SHELL'] if not IS_WINDOWS and 'CATKIN_SHELL' in environ and environ['CATKIN_SHELL'] else None # remove non-workspace paths workspaces = [path for path in cmake_prefix_path.split(os.pathsep) if path and os.path.isfile(os.path.join(path, CATKIN_MARKER_FILE))] for workspace in reversed(workspaces): env_hook_dir = os.path.join(workspace, 'etc', 'catkin', 'profile.d') if os.path.isdir(env_hook_dir): for filename in sorted(os.listdir(env_hook_dir)): if filename.endswith('.%s' % generic_env_hook_ext): # remove previous env hook with same name if present if filename in generic_env_hooks_by_filename: i = generic_env_hooks.index(generic_env_hooks_by_filename[filename]) generic_env_hooks.pop(i) generic_env_hooks_workspace.pop(i) # append env hook generic_env_hooks.append(os.path.join(env_hook_dir, filename)) generic_env_hooks_workspace.append(workspace) generic_env_hooks_by_filename[filename] = generic_env_hooks[-1] elif specific_env_hook_ext is not None and filename.endswith('.%s' % specific_env_hook_ext): # remove previous env hook with same name if present if filename in specific_env_hooks_by_filename: i = specific_env_hooks.index(specific_env_hooks_by_filename[filename]) specific_env_hooks.pop(i) specific_env_hooks_workspace.pop(i) # append env hook specific_env_hooks.append(os.path.join(env_hook_dir, filename)) specific_env_hooks_workspace.append(workspace) specific_env_hooks_by_filename[filename] = specific_env_hooks[-1] env_hooks = generic_env_hooks + specific_env_hooks env_hooks_workspace = generic_env_hooks_workspace + specific_env_hooks_workspace count = len(env_hooks) lines.append(assignment('_CATKIN_ENVIRONMENT_HOOKS_COUNT', count)) for i in range(count): lines.append(assignment('_CATKIN_ENVIRONMENT_HOOKS_%d' % i, env_hooks[i])) lines.append(assignment('_CATKIN_ENVIRONMENT_HOOKS_%d_WORKSPACE' % i, env_hooks_workspace[i])) return lines
jcicolani/Nomad
[ 6, 3, 6, 1, 1446612331 ]
def Run(self, options, args): print >> sys.stderr, ('usage: %s <command> [<options>]' % _GetScriptName()) print >> sys.stderr, 'Available commands are:' for command in COMMANDS: print >> sys.stderr, ' %-10s %s' % (command.name, command.description) return 0
ChromiumWebApps/chromium
[ 216, 323, 216, 1, 1392992388 ]
def __init__(self): super(List, self).__init__() self._tests = None
ChromiumWebApps/chromium
[ 216, 323, 216, 1, 1392992388 ]
def ProcessCommandLine(self, parser, options, args): if not args: self._tests = _GetTests() elif len(args) == 1: self._tests = _MatchTestName(args[0]) else: parser.error('Must provide at most one test name.')
ChromiumWebApps/chromium
[ 216, 323, 216, 1, 1392992388 ]