_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q34300
SawyerStack.staged_rewards
train
def staged_rewards(self): """ Helper function to return staged rewards based on current physical states. Returns: r_reach (float): reward for reaching and grasping r_lift (float): reward for lifting and aligning r_stack (float): reward for stacking ""...
python
{ "resource": "" }
q34301
NutAssemblyTask.merge_objects
train
def merge_objects(self, mujoco_objects): """Adds physical objects to the MJCF model.""" self.mujoco_objects = mujoco_objects self.objects = {} # xml manifestation self.max_horizontal_radius = 0 for obj_name, obj_mjcf in mujoco_objects.items(): self.merge_asset(obj_mj...
python
{ "resource": "" }
q34302
Gripper.hide_visualization
train
def hide_visualization(self): """ Hides all visualization geoms and sites. This should be called before rendering to agents """ for site_name in self.visualization_sites: site = self.worldbody.find(".//site[@name='{}']".format(site_name)) site.set("rgba", ...
python
{ "resource": "" }
q34303
BaxterLift._load_model
train
def _load_model(self): """ Loads the arena and pot object. """ super()._load_model() self.mujoco_robot.set_base_xpos([0, 0, 0]) # load model for table top workspace self.mujoco_arena = TableArena( table_full_size=self.table_full_size, table_friction=s...
python
{ "resource": "" }
q34304
BaxterLift._pot_quat
train
def _pot_quat(self): """Returns the orientation of the pot.""" return T.convert_quat(self.sim.data.body_xquat[self.cube_body_id], to="xyzw")
python
{ "resource": "" }
q34305
BaxterLift._check_success
train
def _check_success(self): """ Returns True if task is successfully completed """ # cube is higher than the table top above a margin cube_height = self.sim.data.body_xpos[self.cube_body_id][2] table_height = self.table_full_size[2] return cube_height > table_height...
python
{ "resource": "" }
q34306
DataCollectionWrapper._start_new_episode
train
def _start_new_episode(self): """ Bookkeeping to do at the start of each new episode. """ # flush any data left over from the previous episode if any interactions have happened if self.has_interaction: self._flush() # timesteps in current episode sel...
python
{ "resource": "" }
q34307
DataCollectionWrapper._flush
train
def _flush(self): """ Method to flush internal state to disk. """ t1, t2 = str(time.time()).split(".") state_path = os.path.join(self.ep_directory, "state_{}_{}.npz".format(t1, t2)) if hasattr(self.env, "unwrapped"): env_name = self.env.unwrapped.__class__.__n...
python
{ "resource": "" }
q34308
MujocoXML.resolve_asset_dependency
train
def resolve_asset_dependency(self): """ Converts every file dependency into absolute path so when we merge we don't break things. """ for node in self.asset.findall("./*[@file]"): file = node.get("file") abs_path = os.path.abspath(self.folder) abs_pat...
python
{ "resource": "" }
q34309
MujocoXML.create_default_element
train
def create_default_element(self, name): """ Creates a <@name/> tag under root if there is none. """ found = self.root.find(name) if found is not None: return found ele = ET.Element(name) self.root.append(ele) return ele
python
{ "resource": "" }
q34310
MujocoXML.merge
train
def merge(self, other, merge_body=True): """ Default merge method. Args: other: another MujocoXML instance raises XML error if @other is not a MujocoXML instance. merges <worldbody/>, <actuator/> and <asset/> of @other into @self merge_bod...
python
{ "resource": "" }
q34311
MujocoXML.get_model
train
def get_model(self, mode="mujoco_py"): """ Returns a MjModel instance from the current xml tree. """ available_modes = ["mujoco_py"] with io.StringIO() as string: string.write(ET.tostring(self.root, encoding="unicode")) if mode == "mujoco_py": ...
python
{ "resource": "" }
q34312
MujocoXML.get_xml
train
def get_xml(self): """ Returns a string of the MJCF XML file. """ with io.StringIO() as string: string.write(ET.tostring(self.root, encoding="unicode")) return string.getvalue()
python
{ "resource": "" }
q34313
MujocoXML.save_model
train
def save_model(self, fname, pretty=False): """ Saves the xml to file. Args: fname: output file location pretty: attempts!! to pretty print the output """ with open(fname, "w") as f: xml_str = ET.tostring(self.root, encoding="unicode") ...
python
{ "resource": "" }
q34314
MujocoXML.merge_asset
train
def merge_asset(self, other): """ Useful for merging other files in a custom logic. """ for asset in other.asset: asset_name = asset.get("name") asset_type = asset.tag # Avoids duplication pattern = "./{}[@name='{}']".format(asset_type, ass...
python
{ "resource": "" }
q34315
GymWrapper._flatten_obs
train
def _flatten_obs(self, obs_dict, verbose=False): """ Filters keys of interest out and concatenate the information. Args: obs_dict: ordered dictionary of observations """ ob_lst = [] for key in obs_dict: if key in self.keys: if verb...
python
{ "resource": "" }
q34316
PickPlaceTask.merge_visual
train
def merge_visual(self, mujoco_objects): """Adds visual objects to the MJCF model.""" self.visual_obj_mjcf = [] for obj_name, obj_mjcf in mujoco_objects.items(): self.merge_asset(obj_mjcf) # Load object obj = obj_mjcf.get_visual(name=obj_name, site=False) ...
python
{ "resource": "" }
q34317
PickPlaceTask.place_visual
train
def place_visual(self): """Places visual objects randomly until no collisions or max iterations hit.""" index = 0 bin_pos = string_to_array(self.bin2_body.get("pos")) bin_size = self.bin_size for _, obj_mjcf in self.visual_objects: bin_x_low = bin_pos[0] ...
python
{ "resource": "" }
q34318
SawyerLift._load_model
train
def _load_model(self): """ Loads an xml model, puts it in self.model """ super()._load_model() self.mujoco_robot.set_base_xpos([0, 0, 0]) # load model for table top workspace self.mujoco_arena = TableArena( table_full_size=self.table_full_size, table_...
python
{ "resource": "" }
q34319
MujocoPyRenderer.set_camera
train
def set_camera(self, camera_id): """ Set the camera view to the specified camera ID. """ self.viewer.cam.fixedcamid = camera_id self.viewer.cam.type = const.CAMERA_FIXED
python
{ "resource": "" }
q34320
MujocoPyRenderer.add_keypress_callback
train
def add_keypress_callback(self, key, fn): """ Allows for custom callback functions for the viewer. Called on key down. Parameter 'any' will ensure that the callback is called on any key down, and block default mujoco viewer callbacks from executing, except for the ESC callback to...
python
{ "resource": "" }
q34321
MujocoPyRenderer.add_keyup_callback
train
def add_keyup_callback(self, key, fn): """ Allows for custom callback functions for the viewer. Called on key up. Parameter 'any' will ensure that the callback is called on any key up, and block default mujoco viewer callbacks from executing, except for the ESC callback to close...
python
{ "resource": "" }
q34322
MujocoPyRenderer.add_keyrepeat_callback
train
def add_keyrepeat_callback(self, key, fn): """ Allows for custom callback functions for the viewer. Called on key repeat. Parameter 'any' will ensure that the callback is called on any key repeat, and block default mujoco viewer callbacks from executing, except for the ESC callb...
python
{ "resource": "" }
q34323
DemoSamplerWrapper.reset
train
def reset(self): """ Logic for sampling a state from the demonstration and resetting the simulation to that state. """ state = self.sample() if state is None: # None indicates that a normal env reset should occur return self.env.reset() el...
python
{ "resource": "" }
q34324
DemoSamplerWrapper.sample
train
def sample(self): """ This is the core sampling method. Samples a state from a demonstration, in accordance with the configuration. """ # chooses a sampling scheme randomly based on the mixing ratios seed = random.uniform(0, 1) ratio = np.cumsum(self.scheme_ratio...
python
{ "resource": "" }
q34325
DemoSamplerWrapper._xml_for_episode_index
train
def _xml_for_episode_index(self, ep_ind): """ Helper method to retrieve the corresponding model xml string for the passed episode index. """ # read the model xml, using the metadata stored in the attribute for this episode model_file = self.demo_file["data/{}".format(ep_...
python
{ "resource": "" }
q34326
to_int16
train
def to_int16(y1, y2): """Convert two 8 bit bytes to a signed 16 bit integer.""" x = (y1) | (y2 << 8) if x >= 32768: x = -(65536 - x) return x
python
{ "resource": "" }
q34327
scale_to_control
train
def scale_to_control(x, axis_scale=350., min_v=-1.0, max_v=1.0): """Normalize raw HID readings to target range.""" x = x / axis_scale x = min(max(x, min_v), max_v) return x
python
{ "resource": "" }
q34328
SpaceMouse.get_controller_state
train
def get_controller_state(self): """Returns the current state of the 3d mouse, a dictionary of pos, orn, grasp, and reset.""" dpos = self.control[:3] * 0.005 roll, pitch, yaw = self.control[3:] * 0.005 self.grasp = self.control_gripper # convert RPY to an absolute orientation ...
python
{ "resource": "" }
q34329
SpaceMouse.run
train
def run(self): """Listener method that keeps pulling new messages.""" t_last_click = -1 while True: d = self.device.read(13) if d is not None and self._enabled: if d[0] == 1: ## readings from 6-DoF sensor self.y = convert(d[1], d[2]...
python
{ "resource": "" }
q34330
Robot.add_gripper
train
def add_gripper(self, arm_name, gripper): """ Mounts gripper to arm. Throws error if robot already has a gripper or gripper type is incorrect. Args: arm_name (str): name of arm mount gripper (MujocoGripper instance): gripper MJCF model """ if arm...
python
{ "resource": "" }
q34331
Arena.set_origin
train
def set_origin(self, offset): """Applies a constant offset to all objects.""" offset = np.array(offset) for node in self.worldbody.findall("./*[@pos]"): cur_pos = string_to_array(node.get("pos")) new_pos = cur_pos + offset node.set("pos", array_to_string(new_p...
python
{ "resource": "" }
q34332
Arena.add_pos_indicator
train
def add_pos_indicator(self): """Adds a new position indicator.""" body = new_body(name="pos_indicator") body.append( new_geom( "sphere", [0.03], rgba=[1, 0, 0, 0.5], group=1, contype="0", ...
python
{ "resource": "" }
q34333
TableArena.table_top_abs
train
def table_top_abs(self): """Returns the absolute position of table top""" table_height = np.array([0, 0, self.table_full_size[2]]) return string_to_array(self.floor.get("pos")) + table_height
python
{ "resource": "" }
q34334
BaxterEnv._reset_internal
train
def _reset_internal(self): """Resets the pose of the arm and grippers.""" super()._reset_internal() self.sim.data.qpos[self._ref_joint_pos_indexes] = self.mujoco_robot.init_qpos if self.has_gripper_right: self.sim.data.qpos[ self._ref_joint_gripper_right_actu...
python
{ "resource": "" }
q34335
BaxterEnv._get_reference
train
def _get_reference(self): """Sets up references for robots, grippers, and objects.""" super()._get_reference() # indices for joints in qpos, qvel self.robot_joints = list(self.mujoco_robot.joints) self._ref_joint_pos_indexes = [ self.sim.model.get_joint_qpos_addr(x) ...
python
{ "resource": "" }
q34336
BaxterEnv.move_indicator
train
def move_indicator(self, pos): """Moves the position of the indicator object to @pos.""" if self.use_indicator_object: self.sim.data.qpos[ self._ref_indicator_pos_low : self._ref_indicator_pos_low + 3 ] = pos
python
{ "resource": "" }
q34337
BaxterEnv._post_action
train
def _post_action(self, action): """Optionally performs gripper visualization after the actions.""" ret = super()._post_action(action) self._gripper_visualization() return ret
python
{ "resource": "" }
q34338
BaxterEnv.set_robot_joint_positions
train
def set_robot_joint_positions(self, jpos): """ Helper method to force robot joint positions to the passed values. """ self.sim.data.qpos[self._ref_joint_pos_indexes] = jpos self.sim.forward()
python
{ "resource": "" }
q34339
Baxter.set_base_xpos
train
def set_base_xpos(self, pos): """Places the robot on position @pos.""" node = self.worldbody.find("./body[@name='base']") node.set("pos", array_to_string(pos - self.bottom_offset))
python
{ "resource": "" }
q34340
_get_size
train
def _get_size(size, size_max, size_min, default_max, default_min): """ Helper method for providing a size, or a range to randomize from """ if len(default_max) != len(default_min): raise ValueError('default_max = {} and default_...
python
{ "resource": "" }
q34341
_get_randomized_range
train
def _get_randomized_range(val, provided_range, default_range): """ Helper to initialize by either value or a range Returns a range to randomize from """ if val is None: if provided_range is None: return default_range ...
python
{ "resource": "" }
q34342
gripper_factory
train
def gripper_factory(name): """ Genreator for grippers Creates a Gripper instance with the provided name. Args: name: the name of the gripper class Returns: gripper: Gripper instance Raises: XMLError: [description] """ if name == "TwoFingerGripper": ret...
python
{ "resource": "" }
q34343
Keyboard._display_controls
train
def _display_controls(self): """ Method to pretty print controls. """ def print_command(char, info): char += " " * (10 - len(char)) print("{}\t{}".format(char, info)) print("") print_command("Keys", "Command") print_command("q", "reset si...
python
{ "resource": "" }
q34344
Keyboard._reset_internal_state
train
def _reset_internal_state(self): """ Resets internal state of controller, except for the reset signal. """ self.rotation = np.array([[-1., 0., 0.], [0., 1., 0.], [0., 0., -1.]]) self.pos = np.zeros(3) # (x, y, z) self.last_pos = np.zeros(3) self.grasp = False
python
{ "resource": "" }
q34345
Keyboard.get_controller_state
train
def get_controller_state(self): """Returns the current state of the keyboard, a dictionary of pos, orn, grasp, and reset.""" dpos = self.pos - self.last_pos self.last_pos = np.array(self.pos) return dict( dpos=dpos, rotation=self.rotation, grasp=int(se...
python
{ "resource": "" }
q34346
Keyboard.on_press
train
def on_press(self, window, key, scancode, action, mods): """ Key handler for key presses. """ # controls for moving position if key == glfw.KEY_W: self.pos[0] -= self._pos_step # dec x elif key == glfw.KEY_S: self.pos[0] += self._pos_step # inc ...
python
{ "resource": "" }
q34347
Keyboard.on_release
train
def on_release(self, window, key, scancode, action, mods): """ Key handler for key releases. """ # controls for grasping if key == glfw.KEY_SPACE: self.grasp = not self.grasp # toggle gripper # user-commanded reset elif key == glfw.KEY_Q: ...
python
{ "resource": "" }
q34348
xml_path_completion
train
def xml_path_completion(xml_path): """ Takes in a local xml path and returns a full path. if @xml_path is absolute, do nothing if @xml_path is not absolute, load xml that is shipped by the package """ if xml_path.startswith("/"): full_path = xml_path else: full_path =...
python
{ "resource": "" }
q34349
postprocess_model_xml
train
def postprocess_model_xml(xml_str): """ This function postprocesses the model.xml collected from a MuJoCo demonstration in order to make sure that the STL files can be found. """ path = os.path.split(robosuite.__file__)[0] path_split = path.split("/") # replace mesh and texture file paths ...
python
{ "resource": "" }
q34350
BaxterIKController.sync_ik_robot
train
def sync_ik_robot(self, joint_positions, simulate=False, sync_last=True): """ Force the internal robot model to match the provided joint angles. Args: joint_positions (list): a list or flat numpy array of joint positions. simulate (bool): If True, actually use physics si...
python
{ "resource": "" }
q34351
BaxterIKController.bullet_base_pose_to_world_pose
train
def bullet_base_pose_to_world_pose(self, pose_in_base): """ Convert a pose in the base frame to a pose in the world frame. Args: pose_in_base: a (pos, orn) tuple. Returns: pose_in world: a (pos, orn) tuple. """ pose_in_base = T.pose2mat(pose_in_b...
python
{ "resource": "" }
q34352
BaxterIKController.clip_joint_velocities
train
def clip_joint_velocities(self, velocities): """ Clips joint velocities into a valid range. """ for i in range(len(velocities)): if velocities[i] >= 1.0: velocities[i] = 1.0 elif velocities[i] <= -1.0: velocities[i] = -1.0 r...
python
{ "resource": "" }
q34353
BaxterPegInHole._load_model
train
def _load_model(self): """ Loads the peg and the hole models. """ super()._load_model() self.mujoco_robot.set_base_xpos([0, 0, 0]) # Add arena and robot self.model = MujocoWorldBase() self.arena = EmptyArena() if self.use_indicator_object: ...
python
{ "resource": "" }
q34354
BaxterPegInHole._compute_orientation
train
def _compute_orientation(self): """ Helper function to return the relative positions between the hole and the peg. In particular, the intersection of the line defined by the peg and the plane defined by the hole is computed; the parallel distance, perpendicular distance, and angl...
python
{ "resource": "" }
q34355
BaxterPegInHole._check_success
train
def _check_success(self): """ Returns True if task is successfully completed. """ t, d, cos = self._compute_orientation() return d < 0.06 and t >= -0.12 and t <= 0.14 and cos > 0.95
python
{ "resource": "" }
q34356
mat2euler
train
def mat2euler(rmat, axes="sxyz"): """ Converts given rotation matrix to euler angles in radian. Args: rmat: 3x3 rotation matrix axes: One of 24 axis sequences as string or encoded tuple Returns: converted euler angles in radian vec3 float """ try: firstaxis, par...
python
{ "resource": "" }
q34357
pose2mat
train
def pose2mat(pose): """ Converts pose to homogeneous matrix. Args: pose: a (pos, orn) tuple where pos is vec3 float cartesian, and orn is vec4 float quaternion. Returns: 4x4 homogeneous matrix """ homo_pose_mat = np.zeros((4, 4), dtype=np.float32) homo_pose_mat[...
python
{ "resource": "" }
q34358
pose_inv
train
def pose_inv(pose): """ Computes the inverse of a homogenous matrix corresponding to the pose of some frame B in frame A. The inverse is the pose of frame A in frame B. Args: pose: numpy array of shape (4,4) for the pose to inverse Returns: numpy array of shape (4,4) for the invers...
python
{ "resource": "" }
q34359
_skew_symmetric_translation
train
def _skew_symmetric_translation(pos_A_in_B): """ Helper function to get a skew symmetric translation matrix for converting quantities between frames. """ return np.array( [ 0., -pos_A_in_B[2], pos_A_in_B[1], pos_A_in_B[2], 0., ...
python
{ "resource": "" }
q34360
vel_in_A_to_vel_in_B
train
def vel_in_A_to_vel_in_B(vel_A, ang_vel_A, pose_A_in_B): """ Converts linear and angular velocity of a point in frame A to the equivalent in frame B. Args: vel_A: 3-dim iterable for linear velocity in A ang_vel_A: 3-dim iterable for angular velocity in A pose_A_in_B: numpy array of ...
python
{ "resource": "" }
q34361
force_in_A_to_force_in_B
train
def force_in_A_to_force_in_B(force_A, torque_A, pose_A_in_B): """ Converts linear and rotational force at a point in frame A to the equivalent in frame B. Args: force_A: 3-dim iterable for linear force in A torque_A: 3-dim iterable for rotational force (moment) in A pose_A_in_B: num...
python
{ "resource": "" }
q34362
rotation_matrix
train
def rotation_matrix(angle, direction, point=None): """ Returns matrix to rotate about axis defined by point and direction. Examples: >>> angle = (random.random() - 0.5) * (2*math.pi) >>> direc = numpy.random.random(3) - 0.5 >>> point = numpy.random.random(3) - 0.5 >>> R0 = ...
python
{ "resource": "" }
q34363
make_pose
train
def make_pose(translation, rotation): """ Makes a homogenous pose matrix from a translation vector and a rotation matrix. Args: translation: a 3-dim iterable rotation: a 3x3 matrix Returns: pose: a 4x4 homogenous matrix """ pose = np.zeros((4, 4)) pose[:3, :3] = rot...
python
{ "resource": "" }
q34364
get_pose_error
train
def get_pose_error(target_pose, current_pose): """ Computes the error corresponding to target pose - current pose as a 6-dim vector. The first 3 components correspond to translational error while the last 3 components correspond to the rotational error. Args: target_pose: a 4x4 homogenous m...
python
{ "resource": "" }
q34365
make
train
def make(env_name, *args, **kwargs): """Try to get the equivalent functionality of gym.make in a sloppy way.""" if env_name not in REGISTERED_ENVS: raise Exception( "Environment {} not found. Make sure it is a registered environment among: {}".format( env_name, ", ".join(REGI...
python
{ "resource": "" }
q34366
MujocoEnv.initialize_time
train
def initialize_time(self, control_freq): """ Initializes the time constants used for simulation. """ self.cur_time = 0 self.model_timestep = self.sim.model.opt.timestep if self.model_timestep <= 0: raise XMLError("xml model defined non-positive time step") ...
python
{ "resource": "" }
q34367
MujocoEnv.reset
train
def reset(self): """Resets simulation.""" # TODO(yukez): investigate black screen of death # if there is an active viewer window, destroy it self._destroy_viewer() self._reset_internal() self.sim.forward() return self._get_observation()
python
{ "resource": "" }
q34368
MujocoEnv.step
train
def step(self, action): """Takes a step in simulation with control command @action.""" if self.done: raise ValueError("executing action in terminated episode") self.timestep += 1 self._pre_action(action) end_time = self.cur_time + self.control_timestep while ...
python
{ "resource": "" }
q34369
MujocoEnv._post_action
train
def _post_action(self, action): """Do any housekeeping after taking an action.""" reward = self.reward(action) # done if number of elapsed timesteps is greater than horizon self.done = (self.timestep >= self.horizon) and not self.ignore_done return reward, self.done, {}
python
{ "resource": "" }
q34370
MujocoEnv.reset_from_xml_string
train
def reset_from_xml_string(self, xml_string): """Reloads the environment from an XML description of the environment.""" # if there is an active viewer window, destroy it self.close() # load model from xml self.mjpy_model = load_model_from_xml(xml_string) self.sim = MjSi...
python
{ "resource": "" }
q34371
MujocoEnv.find_contacts
train
def find_contacts(self, geoms_1, geoms_2): """ Finds contact between two geom groups. Args: geoms_1: a list of geom names (string) geoms_2: another list of geom names (string) Returns: iterator of all contacts between @geoms_1 and @geoms_2 ""...
python
{ "resource": "" }
q34372
SawyerEnv._reset_internal
train
def _reset_internal(self): """ Sets initial pose of arm and grippers. """ super()._reset_internal() self.sim.data.qpos[self._ref_joint_pos_indexes] = self.mujoco_robot.init_qpos if self.has_gripper: self.sim.data.qpos[ self._ref_joint_gripper_...
python
{ "resource": "" }
q34373
SawyerEnv._get_reference
train
def _get_reference(self): """ Sets up necessary reference for robots, grippers, and objects. """ super()._get_reference() # indices for joints in qpos, qvel self.robot_joints = list(self.mujoco_robot.joints) self._ref_joint_pos_indexes = [ self.sim.mo...
python
{ "resource": "" }
q34374
SawyerEnv._pre_action
train
def _pre_action(self, action): """ Overrides the superclass method to actuate the robot with the passed joint velocities and gripper control. Args: action (numpy array): The control to apply to the robot. The first @self.mujoco_robot.dof dimensions should be...
python
{ "resource": "" }
q34375
collect_random_trajectory
train
def collect_random_trajectory(env, timesteps=1000): """Run a random policy to collect trajectories. The rollout trajectory is saved to files in npz format. Modify the DataCollectionWrapper wrapper to add new fields or change data formats. """ obs = env.reset() dof = env.dof for t in range...
python
{ "resource": "" }
q34376
playback_trajectory
train
def playback_trajectory(env, ep_dir): """Playback data from an episode. Args: ep_dir: The path to the directory containing data for an episode. """ # first reload the model from the xml xml_path = os.path.join(ep_dir, "model.xml") with open(xml_path, "r") as f: env.reset_from_x...
python
{ "resource": "" }
q34377
IKWrapper.set_robot_joint_positions
train
def set_robot_joint_positions(self, positions): """ Overrides the function to set the joint positions directly, since we need to notify the IK controller of the change. """ self.env.set_robot_joint_positions(positions) self.controller.sync_state()
python
{ "resource": "" }
q34378
IKWrapper._make_input
train
def _make_input(self, action, old_quat): """ Helper function that returns a dictionary with keys dpos, rotation from a raw input array. The first three elements are taken to be displacement in position, and a quaternion indicating the change in rotation with respect to @old_quat. ...
python
{ "resource": "" }
q34379
RedisPublisher.fetch_message
train
def fetch_message(self, request, facility, audience='any'): """ Fetch the first message available for the given ``facility`` and ``audience``, if it has been persisted in the Redis datastore. The current HTTP ``request`` is used to determine to whom the message belongs. A unique ...
python
{ "resource": "" }
q34380
RedisSubscriber.set_pubsub_channels
train
def set_pubsub_channels(self, request, channels): """ Initialize the channels used for publishing and subscribing messages through the message queue. """ facility = request.path_info.replace(settings.WEBSOCKET_URL, '', 1) # initialize publishers audience = { ...
python
{ "resource": "" }
q34381
RedisSubscriber.send_persisted_messages
train
def send_persisted_messages(self, websocket): """ This method is called immediately after a websocket is openend by the client, so that persisted messages can be sent back to the client upon connection. """ for channel in self._subscription.channels: message = self._c...
python
{ "resource": "" }
q34382
RedisSubscriber.get_file_descriptor
train
def get_file_descriptor(self): """ Returns the file descriptor used for passing to the select call when listening on the message queue. """ return self._subscription.connection and self._subscription.connection._sock.fileno()
python
{ "resource": "" }
q34383
RedisSubscriber.release
train
def release(self): """ New implementation to free up Redis subscriptions when websockets close. This prevents memory sap when Redis Output Buffer and Output Lists build when websockets are abandoned. """ if self._subscription and self._subscription.subscribed: self._s...
python
{ "resource": "" }
q34384
default
train
def default(request): """ Adds additional context variables to the default context. """ protocol = request.is_secure() and 'wss://' or 'ws://' heartbeat_msg = settings.WS4REDIS_HEARTBEAT and '"{0}"'.format(settings.WS4REDIS_HEARTBEAT) or 'null' context = { 'WEBSOCKET_URI': protocol + req...
python
{ "resource": "" }
q34385
WebSocket._decode_bytes
train
def _decode_bytes(self, bytestring): """ Internal method used to convert the utf-8 encoded bytestring into unicode. If the conversion fails, the socket will be closed. """ if not bytestring: return u'' try: return bytestring.decode('utf-8') ...
python
{ "resource": "" }
q34386
WebSocket.handle_close
train
def handle_close(self, header, payload): """ Called when a close frame has been decoded from the stream. :param header: The decoded `Header`. :param payload: The bytestring payload associated with the close frame. """ if not payload: self.close(1000, None) ...
python
{ "resource": "" }
q34387
WebSocket.read_frame
train
def read_frame(self): """ Block until a full frame has been read from the socket. This is an internal method as calling this will not cleanup correctly if an exception is called. Use `receive` instead. :return: The header and payload as a tuple. """ header = Hea...
python
{ "resource": "" }
q34388
WebSocket.read_message
train
def read_message(self): """ Return the next text or binary message from the socket. This is an internal method as calling this will not cleanup correctly if an exception is called. Use `receive` instead. """ opcode = None message = None while True: ...
python
{ "resource": "" }
q34389
WebSocket.close
train
def close(self, code=1000, message=''): """ Close the websocket and connection, sending the specified code and message. The underlying socket object is _not_ closed, that is the responsibility of the initiator. """ try: message = self._encode_bytes(message) ...
python
{ "resource": "" }
q34390
Header.decode_header
train
def decode_header(cls, stream): """ Decode a WebSocket header. :param stream: A file like object that can be 'read' from. :returns: A `Header` instance. """ read = stream.read data = read(2) if len(data) != 2: raise WebSocketError("Unexpected ...
python
{ "resource": "" }
q34391
Header.encode_header
train
def encode_header(cls, fin, opcode, mask, length, flags): """ Encodes a WebSocket header. :param fin: Whether this is the final frame for this opcode. :param opcode: The opcode of the payload, see `OPCODE_*` :param mask: Whether the payload is masked. :param length: The ...
python
{ "resource": "" }
q34392
store_groups_in_session
train
def store_groups_in_session(sender, user, request, **kwargs): """ When a user logs in, fetch its groups and store them in the users session. This is required by ws4redis, since fetching groups accesses the database, which is a blocking operation and thus not allowed from within the websocket loop. "...
python
{ "resource": "" }
q34393
RedisStore.publish_message
train
def publish_message(self, message, expire=None): """ Publish a ``message`` on the subscribed channel on the Redis datastore. ``expire`` sets the time in seconds, on how long the message shall additionally of being published, also be persisted in the Redis datastore. If unset, it defaults...
python
{ "resource": "" }
q34394
uWSGIWebsocket.get_file_descriptor
train
def get_file_descriptor(self): """Return the file descriptor for the given websocket""" try: return uwsgi.connection_fd() except IOError as e: self.close() raise WebSocketError(e)
python
{ "resource": "" }
q34395
StereoPair.get_frames_singleimage
train
def get_frames_singleimage(self): """ Get current left and right frames from a single image, by splitting the image in half. """ frame = self.captures[0].read()[1] height, width, colors = frame.shape left_frame = frame[:, :width/2, :] right_frame = frame[:...
python
{ "resource": "" }
q34396
StereoPair.show_frames
train
def show_frames(self, wait=0): """ Show current frames from cameras. ``wait`` is the wait interval in milliseconds before the window closes. """ for window, frame in zip(self.windows, self.get_frames()): cv2.imshow(window, frame) cv2.waitKey(wait)
python
{ "resource": "" }
q34397
ChessboardFinder.get_chessboard
train
def get_chessboard(self, columns, rows, show=False): """ Take a picture with a chessboard visible in both captures. ``columns`` and ``rows`` should be the number of inside corners in the chessboard's columns and rows. ``show`` determines whether the frames are shown while the ca...
python
{ "resource": "" }
q34398
CalibratedPair.get_frames
train
def get_frames(self): """Rectify and return current frames from cameras.""" frames = super(CalibratedPair, self).get_frames() return self.calibration.rectify(frames)
python
{ "resource": "" }
q34399
CalibratedPair.get_point_cloud
train
def get_point_cloud(self, pair): """Get 3D point cloud from image pair.""" disparity = self.block_matcher.get_disparity(pair) points = self.block_matcher.get_3d(disparity, self.calibration.disp_to_depth_mat) colors = cv2.cvtColor(pair[0], cv2.CO...
python
{ "resource": "" }