code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class HbvGeoLocationRepository(GeoLocationRepository): <NEW_LINE> <INDENT> def __init__(self, geo_location_dict, epsg_id): <NEW_LINE> <INDENT> if not isinstance(geo_location_dict,dict): <NEW_LINE> <INDENT> raise HbvGeoLocationError("geo_location_dict must be a dict(), of type dict(int,[x,y,z])") <NEW_LINE> <DEDENT> if epsg_id is None: <NEW_LINE> <INDENT> raise HbvGeoLocationError("epsg_id must be specified as a valid epsg_id, like 32633") <NEW_LINE> <DEDENT> self._geo_location_dict = geo_location_dict <NEW_LINE> self._epsg_id = epsg_id <NEW_LINE> <DEDENT> def get_locations(self, location_id_list, epsg_id=32633): <NEW_LINE> <INDENT> if epsg_id != self._epsg_id: <NEW_LINE> <INDENT> raise HbvGeoLocationError("HbvGeoLocationRepository does not yet implement epsg-coordindate transforms, wanted epsg_id={0}, available = {1}".format(epsg_id,self._epsg_id)) <NEW_LINE> <DEDENT> locations = {} <NEW_LINE> for location_id in location_id_list: <NEW_LINE> <INDENT> if self._geo_location_dict.get(location_id) is not None: <NEW_LINE> <INDENT> locations[location_id] = tuple(self._geo_location_dict[location_id]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise HbvGeoLocationError("Could not get location of geo point-id!") <NEW_LINE> <DEDENT> <DEDENT> return locations
Provide a yaml-based key-location map for gis-identites not available(yet)
6259906b0a50d4780f7069c0
class TestAnonymousSurvey(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> question = "What language did you first learn to speak?" <NEW_LINE> self.my_survey = AnonymousSurvey(question) <NEW_LINE> self.responses = ['English', 'Spanish', 'Mandarin'] <NEW_LINE> <DEDENT> def test_store_single_response(self): <NEW_LINE> <INDENT> self.my_survey.store_response(self.responses[0]) <NEW_LINE> self.assertIn(self.responses[0], self.my_survey.responses) <NEW_LINE> <DEDENT> def test_store_responses(self): <NEW_LINE> <INDENT> for response in self.responses: <NEW_LINE> <INDENT> self.my_survey.store_response(response) <NEW_LINE> <DEDENT> for response in self.responses: <NEW_LINE> <INDENT> self.assertIn(response, self.my_survey.responses)
Tests for the class AnonymousSurvey
6259906b32920d7e50bc7846
class BaseWasmException(Exception): <NEW_LINE> <INDENT> pass
Base exception class for this library.
6259906b442bda511e95d958
class VerticalProgressBar(HorizontalProgressBar): <NEW_LINE> <INDENT> def _get_sizes_min_max(self) -> Tuple[int, int]: <NEW_LINE> <INDENT> return 0, self.fill_height() <NEW_LINE> <DEDENT> def _get_value_sizes(self, _old_ratio: float, _new_ratio: float) -> Tuple[int, int]: <NEW_LINE> <INDENT> return int(_old_ratio * self.fill_height()), int( _new_ratio * self.fill_height() ) <NEW_LINE> <DEDENT> def _get_horizontal_fill( self, _start: int, _end: int, _incr: int ) -> Tuple[int, int, int]: <NEW_LINE> <INDENT> return ProgressBarBase._get_horizontal_fill(self, _start, _end, _incr) <NEW_LINE> <DEDENT> def _get_vertical_fill( self, _start: int, _end: int, _incr: int ) -> Tuple[int, int, int]: <NEW_LINE> <INDENT> if not self._invert_fill_direction(): <NEW_LINE> <INDENT> return _start, _end, _incr <NEW_LINE> <DEDENT> base_offset = self.fill_height() - 1 <NEW_LINE> return base_offset - _start, base_offset - _end, _incr * -1 <NEW_LINE> <DEDENT> def _invert_fill_direction(self) -> bool: <NEW_LINE> <INDENT> return self._direction == VerticalFillDirection.BOTTOM_TO_TOP
A dynamic progress bar widget. The anchor position is the position where the control would start if it were being read visually or on paper, where the (0, 0) position is the lower-left corner for ascending progress bars (fills from the bottom to to the top in vertical bars, or from the left to the right in horizontal progress bars), upper-left corner for descending progress bars (fills from the top to the bottom). Using the diagrams below, the bar will fill in the following directions:: -------------------------------- | Bottom-to-top | 3-4 to 1-2 | -------------------------------- | Top-to-bottom | 1-2 to 3-4 | -------------------------------- 1--2 | | | | | | | | 3--4 :param position: The coordinates of the top-left corner of progress bar. :type position: Tuple[int, int] :param size: The size in (width, height) of the progress bar, in pixels :type size: Tuple[int, int] :param min_value: The lowest value which can be displayed by the progress bar. When the "value" property is set to the same value, no bar is displayed. :type min_value: int, float :param max_value: This highest value which can be displayed by the progress bar. When the "value" property is set to the same value, the bar shows as full. :type max_value: int, float :param value: The starting value to be displayed. Must be between the values of min_value and max_value, inclusively. :type value: int, float :param bar_color: The color of the value portion of the progress bar. Can be a hex value for color (i.e. 0x225588). :type bar_color: int, Tuple[byte, byte, byte] :param outline_color: The colour for the outline of the progress bar. Can be a hex value for color (i.e. 0x225588). :type outline_color: int, Tuple[byte, byte, byte] :param fill_color: The colour for the background within the progress bar. Can be a hex value for color (i.e. 0x225588). :type fill_color: int, Tuple[byte, byte, byte] :param border_thickness: The thickness of the outer border of the widget. If it is 1 or larger, will be displayed with the color of the "outline_color" parameter. :type border_thickness: int :param margin_size: The thickness (in pixels) of the margin between the border and the bar. If it is 1 or larger, will be filled in by the color of the "fill_color" parameter. :type margin_size: int :param direction: The direction of the fill :type direction: VerticalFillDirection
6259906b92d797404e38975b
class FSEntryParamsOrganize(FSEntryParamsExt): <NEW_LINE> <INDENT> def __init__(self, args = {}): <NEW_LINE> <INDENT> super().__init__(args)
Organize Entry attributes
6259906baad79263cf42ffb6
class ESPBlock(nn.Layer): <NEW_LINE> <INDENT> def __init__(self, in_channels, out_channels, strides, dilations, data_format="channels_last", **kwargs): <NEW_LINE> <INDENT> super(ESPBlock, self).__init__(**kwargs) <NEW_LINE> num_branches = len(dilations) <NEW_LINE> assert (out_channels % num_branches == 0) <NEW_LINE> self.downsample = (strides != 1) <NEW_LINE> mid_channels = out_channels // num_branches <NEW_LINE> self.reduce_conv = conv1x1_block( in_channels=in_channels, out_channels=mid_channels, groups=num_branches, activation=(lambda: PReLU2(in_channels=mid_channels, name="activ")), data_format=data_format, name="reduce_conv") <NEW_LINE> self.branches = HierarchicalConcurrent( data_format=data_format, name="branches") <NEW_LINE> for i in range(num_branches): <NEW_LINE> <INDENT> self.branches.add(conv3x3( in_channels=mid_channels, out_channels=mid_channels, strides=strides, padding=dilations[i], dilation=dilations[i], groups=mid_channels, data_format=data_format, name="branch{}".format(i + 1))) <NEW_LINE> <DEDENT> self.merge_conv = conv1x1_block( in_channels=out_channels, out_channels=out_channels, groups=num_branches, activation=None, data_format=data_format, name="merge_conv") <NEW_LINE> self.preactiv = PreActivation( in_channels=out_channels, data_format=data_format, name="preactiv") <NEW_LINE> if not self.downsample: <NEW_LINE> <INDENT> self.activ = PReLU2(in_channels=out_channels, name="activ") <NEW_LINE> <DEDENT> <DEDENT> def call(self, x, x0, training=None): <NEW_LINE> <INDENT> y = self.reduce_conv(x, training=training) <NEW_LINE> y = self.branches(y, training=training) <NEW_LINE> y = self.preactiv(y, training=training) <NEW_LINE> y = self.merge_conv(y, training=training) <NEW_LINE> if not self.downsample: <NEW_LINE> <INDENT> y = y + x <NEW_LINE> y = self.activ(y) <NEW_LINE> <DEDENT> return y, x0
ESPNetv2 block (so-called EESP block). Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. strides : int or tuple/list of 2 int Strides of the branch convolution layers. dilations : list of int Dilation values for branches. data_format : str, default 'channels_last' The ordering of the dimensions in tensors.
6259906b4527f215b58eb5a0
class SubmitGrade(forms.Form): <NEW_LINE> <INDENT> override = forms.BooleanField(widget=forms.CheckboxInput(), required=False,label="Submit without reviewing all rubric items") <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.valid = kwargs.pop('valid') <NEW_LINE> super(SubmitGrade, self).__init__(*args, **kwargs) <NEW_LINE> if self.valid: <NEW_LINE> <INDENT> self.fields['override'].widget = forms.HiddenInput() <NEW_LINE> <DEDENT> <DEDENT> def clean(self): <NEW_LINE> <INDENT> super().clean() <NEW_LINE> if not (self.valid or self.cleaned_data['override']): <NEW_LINE> <INDENT> raise forms.ValidationError("Not all rubric items have been graded.")
Form to submit rubric
6259906b4f6381625f19a0a7
@PIPELINES.register_module() <NEW_LINE> class LoadAnnotations(object): <NEW_LINE> <INDENT> def __init__(self, reduce_zero_label=False, file_client_args=dict(backend='disk'), imdecode_backend='pillow'): <NEW_LINE> <INDENT> self.reduce_zero_label = reduce_zero_label <NEW_LINE> self.file_client_args = file_client_args.copy() <NEW_LINE> self.file_client = None <NEW_LINE> self.imdecode_backend = imdecode_backend <NEW_LINE> <DEDENT> def __call__(self, results): <NEW_LINE> <INDENT> if self.file_client is None: <NEW_LINE> <INDENT> self.file_client = mmcv.FileClient(**self.file_client_args) <NEW_LINE> <DEDENT> if results.get('seg_prefix', None) is not None: <NEW_LINE> <INDENT> filename = osp.join(results['seg_prefix'], results['ann_info']['seg_map']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> filename = results['ann_info']['seg_map'] <NEW_LINE> <DEDENT> img_bytes = self.file_client.get(filename) <NEW_LINE> gt_semantic_seg = mmcv.imfrombytes( img_bytes, flag='unchanged', backend=self.imdecode_backend).squeeze().astype(np.uint8) <NEW_LINE> if results.get('label_map', None) is not None: <NEW_LINE> <INDENT> for old_id, new_id in results['label_map'].items(): <NEW_LINE> <INDENT> gt_semantic_seg[gt_semantic_seg == old_id] = new_id <NEW_LINE> <DEDENT> <DEDENT> if self.reduce_zero_label: <NEW_LINE> <INDENT> gt_semantic_seg[gt_semantic_seg == 0] = 255 <NEW_LINE> gt_semantic_seg = gt_semantic_seg - 1 <NEW_LINE> gt_semantic_seg[gt_semantic_seg == 254] = 255 <NEW_LINE> <DEDENT> results['gt_semantic_seg'] = gt_semantic_seg <NEW_LINE> results['seg_fields'].append('gt_semantic_seg') <NEW_LINE> return results <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> repr_str = self.__class__.__name__ <NEW_LINE> repr_str += f'(reduce_zero_label={self.reduce_zero_label},' <NEW_LINE> repr_str += f"imdecode_backend='{self.imdecode_backend}')" <NEW_LINE> return repr_str
Load annotations for semantic segmentation. Args: reduct_zero_label (bool): Whether reduce all label value by 1. Usually used for datasets where 0 is background label. Default: False. file_client_args (dict): Arguments to instantiate a FileClient. See :class:`mmcv.fileio.FileClient` for details. Defaults to ``dict(backend='disk')``. imdecode_backend (str): Backend for :func:`mmcv.imdecode`. Default: 'pillow'
6259906bdd821e528d6da581
class DilatedResBlock(nn.Module): <NEW_LINE> <INDENT> def __init__(self, in_ch, out_ch, dilation=1, shortcut=None): <NEW_LINE> <INDENT> super(DilatedResBlock, self).__init__() <NEW_LINE> self.left = nn.Sequential( BuildingBlock(in_ch, out_ch, dilation), nn.Conv2d(out_ch, out_ch, 3, padding=1, dilation=dilation), nn.BatchNorm2d(out_ch), ) <NEW_LINE> self.right = shortcut <NEW_LINE> <DEDENT> def forward(self, input): <NEW_LINE> <INDENT> out = self.left(input) <NEW_LINE> residual = input if self.right is None else self.right(input) <NEW_LINE> out += residual <NEW_LINE> return F.relu(out)
input -> building_block -> building_block -> + -> output ↘ -----------(shortcut)------------- ↗
6259906b4c3428357761bab4
class Agent(): <NEW_LINE> <INDENT> def __init__(self, state_size, action_size, random_seed): <NEW_LINE> <INDENT> self.state_size = state_size <NEW_LINE> self.action_size = action_size <NEW_LINE> self.seed = random.seed(random_seed) <NEW_LINE> self.actor_local = Actor(state_size, action_size, random_seed).to(device) <NEW_LINE> self.actor_target = Actor(state_size, action_size, random_seed).to(device) <NEW_LINE> self.actor_optimizer = optim.Adam(self.actor_local.parameters(), lr=LR_ACTOR) <NEW_LINE> self.critic_local = Critic(state_size, action_size, random_seed).to(device) <NEW_LINE> self.critic_target = Critic(state_size, action_size, random_seed).to(device) <NEW_LINE> self.critic_optimizer = optim.Adam(self.critic_local.parameters(), lr=LR_CRITIC, weight_decay=WEIGHT_DECAY) <NEW_LINE> self.noise = OUNoise(action_size, random_seed) <NEW_LINE> self.memory = ReplayBuffer(action_size, BUFFER_SIZE, BATCH_SIZE, random_seed) <NEW_LINE> <DEDENT> def step(self, num_update=1): <NEW_LINE> <INDENT> if len(self.memory) > BATCH_SIZE: <NEW_LINE> <INDENT> for i in range(num_update): <NEW_LINE> <INDENT> experiences = self.memory.sample() <NEW_LINE> self.learn(experiences, GAMMA) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def act(self, state, add_noise=True): <NEW_LINE> <INDENT> state = torch.from_numpy(state).float().to(device) <NEW_LINE> self.actor_local.eval() <NEW_LINE> with torch.no_grad(): <NEW_LINE> <INDENT> action = self.actor_local(state).cpu().data.numpy() <NEW_LINE> <DEDENT> self.actor_local.train() <NEW_LINE> if add_noise: <NEW_LINE> <INDENT> action += self.noise.sample() <NEW_LINE> <DEDENT> return np.clip(action, -1, 1) <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.noise.reset() <NEW_LINE> <DEDENT> def learn(self, experiences, gamma): <NEW_LINE> <INDENT> states, actions, rewards, next_states, dones = experiences <NEW_LINE> actions_next = self.actor_target(next_states) <NEW_LINE> Q_targets_next = self.critic_target(next_states, actions_next) <NEW_LINE> Q_targets = rewards + (gamma * Q_targets_next * (1 - dones)) <NEW_LINE> Q_expected = self.critic_local(states, actions) <NEW_LINE> critic_loss = F.mse_loss(Q_expected, Q_targets) <NEW_LINE> self.critic_optimizer.zero_grad() <NEW_LINE> critic_loss.backward() <NEW_LINE> torch.nn.utils.clip_grad_norm_(self.critic_local.parameters(), 1) <NEW_LINE> self.critic_optimizer.step() <NEW_LINE> actions_pred = self.actor_local(states) <NEW_LINE> actor_loss = -self.critic_local(states, actions_pred).mean() <NEW_LINE> self.actor_optimizer.zero_grad() <NEW_LINE> actor_loss.backward() <NEW_LINE> self.actor_optimizer.step() <NEW_LINE> self.soft_update(self.critic_local, self.critic_target, TAU) <NEW_LINE> self.soft_update(self.actor_local, self.actor_target, TAU) <NEW_LINE> <DEDENT> def soft_update(self, local_model, target_model, tau): <NEW_LINE> <INDENT> for target_param, local_param in zip(target_model.parameters(), local_model.parameters()): <NEW_LINE> <INDENT> target_param.data.copy_(tau*local_param.data + (1.0-tau)*target_param.data)
Interacts with and learns from the environment.
6259906b3539df3088ecda9f
class DependencyNode(object): <NEW_LINE> <INDENT> __slots__ = ["_label", "_element", "_line_nb", "_modifier", "_step", "_nostep_repr", "_hash"] <NEW_LINE> def __init__(self, label, element, line_nb, step, modifier=False): <NEW_LINE> <INDENT> self._label = label <NEW_LINE> self._element = element <NEW_LINE> self._line_nb = line_nb <NEW_LINE> self._modifier = modifier <NEW_LINE> self._step = step <NEW_LINE> self._nostep_repr = (self._label, self._line_nb, self._element) <NEW_LINE> self._hash = hash( (self._label, self._element, self._line_nb, self._step)) <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return self._hash <NEW_LINE> <DEDENT> def __eq__(self, depnode): <NEW_LINE> <INDENT> if not isinstance(depnode, self.__class__): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return (self.label == depnode.label and self.element == depnode.element and self.line_nb == depnode.line_nb and self.step == depnode.step) <NEW_LINE> <DEDENT> def __cmp__(self, node): <NEW_LINE> <INDENT> if not isinstance(node, self.__class__): <NEW_LINE> <INDENT> raise ValueError("Compare error between %s, %s" % (self.__class__, node.__class__)) <NEW_LINE> <DEDENT> return cmp((self.label, self.element, self.line_nb), (node.label, node.element, node.line_nb)) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "<%s %s %s %s M:%s S:%s>" % (self.__class__.__name__, self.label.name, self.element, self.line_nb, self.modifier, self.step) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__str__() <NEW_LINE> <DEDENT> @property <NEW_LINE> def nostep_repr(self): <NEW_LINE> <INDENT> return self._nostep_repr <NEW_LINE> <DEDENT> @property <NEW_LINE> def label(self): <NEW_LINE> <INDENT> return self._label <NEW_LINE> <DEDENT> @property <NEW_LINE> def element(self): <NEW_LINE> <INDENT> return self._element <NEW_LINE> <DEDENT> @property <NEW_LINE> def line_nb(self): <NEW_LINE> <INDENT> return self._line_nb <NEW_LINE> <DEDENT> @property <NEW_LINE> def step(self): <NEW_LINE> <INDENT> return self._step <NEW_LINE> <DEDENT> @property <NEW_LINE> def modifier(self): <NEW_LINE> <INDENT> return self._modifier <NEW_LINE> <DEDENT> @modifier.setter <NEW_LINE> def modifier(self, value): <NEW_LINE> <INDENT> self._modifier = value
Node elements of a DependencyGraph A dependency node stands for the dependency on the @element at line number @line_nb in the IRblock named @label, *before* the evaluation of this line.
6259906bd6c5a102081e392a
class MaskAttrib: <NEW_LINE> <INDENT> def set_mask(self, mask): <NEW_LINE> <INDENT> self._attributes['mask'] = mask <NEW_LINE> <DEDENT> def get_mask(self): <NEW_LINE> <INDENT> return self._attributes.get('mask')
The MaskAttrib class defines the Mask.attrib attribute set.
6259906b3d592f4c4edbc6e1
class SignalConnectionManager(gui.Widget): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(SignalConnectionManager, self).__init__(**kwargs) <NEW_LINE> self.label = gui.Label('Signal connections', width='100%') <NEW_LINE> self.label.add_class("DialogTitle") <NEW_LINE> self.append(self.label) <NEW_LINE> self.container = gui.VBox(width='100%', height='90%') <NEW_LINE> self.container.style['justify-content'] = 'flex-start' <NEW_LINE> self.container.style['overflow-y'] = 'scroll' <NEW_LINE> self.listeners_list = [] <NEW_LINE> <DEDENT> def build_widget_list_from_tree(self, node): <NEW_LINE> <INDENT> if not hasattr(node, 'attributes'): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not 'editor_varname' in node.attributes.keys(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.listeners_list.append(node) <NEW_LINE> for child in node.children.values(): <NEW_LINE> <INDENT> self.build_widget_list_from_tree(child) <NEW_LINE> <DEDENT> <DEDENT> def update(self, widget, widget_tree): <NEW_LINE> <INDENT> self.listeners_list = [] <NEW_LINE> self.build_widget_list_from_tree(widget_tree) <NEW_LINE> self.label.set_text('Signal connections: ' + widget.attributes['editor_varname']) <NEW_LINE> self.container = gui.VBox(width='100%', height='90%') <NEW_LINE> self.container.style['justify-content'] = 'flex-start' <NEW_LINE> self.container.style['overflow-y'] = 'scroll' <NEW_LINE> self.append(self.container, 'container') <NEW_LINE> for (setOnEventListenerFuncname,setOnEventListenerFunc) in inspect.getmembers(widget): <NEW_LINE> <INDENT> if hasattr(setOnEventListenerFunc, '_event_info'): <NEW_LINE> <INDENT> self.container.append( SignalConnection(widget, self.listeners_list, setOnEventListenerFuncname, setOnEventListenerFunc, width='100%') )
This class allows to interconnect event signals
6259906b71ff763f4b5e8fa7
class Project: <NEW_LINE> <INDENT> def __init__(self, pid: str, p_owner: str, p_owner_name: str, name: str, description: str, created: datetime, updated_on: datetime, flags: str = '', features: [Feature] = None): <NEW_LINE> <INDENT> self.project_id = pid <NEW_LINE> self.project_owner_id = p_owner <NEW_LINE> self.project_owner_name = p_owner_name <NEW_LINE> self.name = name <NEW_LINE> self.description = description <NEW_LINE> self.created = created <NEW_LINE> self.updated_on = updated_on <NEW_LINE> self.flags = flags <NEW_LINE> self.features = features <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> features = '' <NEW_LINE> if self.features: <NEW_LINE> <INDENT> for feature in self.features: <NEW_LINE> <INDENT> features += f' › {feature.name} ({feature.feature_id})\n' <NEW_LINE> <DEDENT> <DEDENT> poid = self.project_owner_id <NEW_LINE> poname = self.project_owner_name <NEW_LINE> return (f'Project ”{self.name}”: \n' f' - id ”{self.project_id}”\n' f' - product owner ”{poname} ({poid})”\n' f' - description ”{self.description}”\n' f' - created ”{self.created}”\n' f' - updated on ”{self.updated_on}”\n' f' - flags ”{self.flags}”\n' f' - features:\n{features}') <NEW_LINE> <DEDENT> def __eq__(self, o: object) -> bool: <NEW_LINE> <INDENT> for field, value in self.__dict__.items(): <NEW_LINE> <INDENT> if field not in o.__dict__.keys(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if value != o.__dict__[field]: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True
Class Project resembles project from the database as a object
6259906b23849d37ff8528b7
class CharacterSheet(View): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(CharacterSheet, self).__init__(**kwargs) <NEW_LINE> self.actor = None <NEW_LINE> self.text = [] <NEW_LINE> <DEDENT> def ready(self): <NEW_LINE> <INDENT> self.scroller = self.spawn(Scroller()) <NEW_LINE> self.sidescroller = self.spawn(SideScroller()) <NEW_LINE> <DEDENT> def keyin(self, c): <NEW_LINE> <INDENT> if c == ord(' '): <NEW_LINE> <INDENT> self.suicide() <NEW_LINE> <DEDENT> else: return True <NEW_LINE> return False <NEW_LINE> <DEDENT> def draw(self, display): <NEW_LINE> <INDENT> sibling = self.get_first_parental_sibling(MainPane) <NEW_LINE> cursor = sibling.get_first_descendent(Cursor) <NEW_LINE> if not cursor: <NEW_LINE> <INDENT> self.suicide() <NEW_LINE> return True <NEW_LINE> <DEDENT> self.window.clear() <NEW_LINE> self.border("#") <NEW_LINE> cell = self.map.cell(cursor.coords) <NEW_LINE> actors = cell.actors if cell else None <NEW_LINE> if not actors: <NEW_LINE> <INDENT> display.cline(self, "There's nothing interesting here.") <NEW_LINE> return True <NEW_LINE> <DEDENT> self.actor = actors[cursor.selector.index] <NEW_LINE> if len(actors) > 1: <NEW_LINE> <INDENT> scroller = "<green-black>" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> scroller = "<red-black>" <NEW_LINE> <DEDENT> display.cline(self, '%s(+-)</> %s' % (scroller, self.actor.appearance())) <NEW_LINE> display.cline(self, "-"*self.width) <NEW_LINE> self.text = text.wrap_string(self.actor.get_view_data(self), self.width) <NEW_LINE> self.scroller.resize(len(self.text)-self.height + 2) <NEW_LINE> offset = 0 <NEW_LINE> if self.scroller.index > 0: <NEW_LINE> <INDENT> display.cline(self, '[...]') <NEW_LINE> offset += 1 <NEW_LINE> <DEDENT> maxlines = self.height - self.y_acc <NEW_LINE> for x in range(maxlines): <NEW_LINE> <INDENT> if self.y_acc+1 == self.height and self.scroller.index < self.scroller.max: <NEW_LINE> <INDENT> display.cline(self, '[...]') <NEW_LINE> break; <NEW_LINE> <DEDENT> index = self.scroller.index + x + offset <NEW_LINE> line = self.text[index] <NEW_LINE> display.cline(self, line)
Display information about an inspected Actor.
6259906b627d3e7fe0e08689
class M2j_module(object): <NEW_LINE> <INDENT> def __init__(self, spi_rack, module, remote=False): <NEW_LINE> <INDENT> self.module = module <NEW_LINE> self.spi_rack = spi_rack <NEW_LINE> self.enable_remote(remote) <NEW_LINE> self.spi_rack.write_data(self.module, 5, 0, 6, bytearray([0xFF])) <NEW_LINE> s_data = bytearray([0b01110001, 0, 0]) <NEW_LINE> self.spi_rack.write_data(self.module, 0, MAX5702_MODE, MAX5702_SPEED, s_data) <NEW_LINE> <DEDENT> def get_level(self): <NEW_LINE> <INDENT> s_data = bytearray([0, 0]) <NEW_LINE> r_data = self.spi_rack.read_data(self.module, 1, MCP320x_MODE, MCP320x_SPEED, s_data) <NEW_LINE> return (r_data[0]&0x0F)<<8 | r_data[1] <NEW_LINE> <DEDENT> def set_gain(self, level): <NEW_LINE> <INDENT> s_data = bytearray([0b10000010, (level&0xFF0)>>4, (level&0x0F)<<4]) <NEW_LINE> self.spi_rack.write_data(self.module, 0, MAX5702_MODE, MAX5702_SPEED, s_data) <NEW_LINE> <DEDENT> def enable_remote(self, enable): <NEW_LINE> <INDENT> self.remote = enable <NEW_LINE> self.spi_rack.write_data(self.module, 5, 0, BICPINS_SPEED, bytearray([self.remote<<5 | 16])) <NEW_LINE> <DEDENT> def clear_rf_clip(self): <NEW_LINE> <INDENT> self.spi_rack.write_data(self.module, 5, 0, BICPINS_SPEED, bytearray([self.remote<<4])) <NEW_LINE> self.spi_rack.write_data(self.module, 5, 0, BICPINS_SPEED, bytearray([self.remote<<4 | 8])) <NEW_LINE> <DEDENT> def rf_clipped(self): <NEW_LINE> <INDENT> data = self.spi_rack.read_data(self.module, 6, 0, BICPINS_SPEED, bytearray([0])) <NEW_LINE> return bool(data[0]&0x08)
M2j module interface class This class does the low level interfacing with the M2j amplifier module. It requires a SPI Rack object and module number at initializationself. Allows the user to get the RF level before the last amplifier and see if the amplifiers are clipping. The user can also set the amplification of the module by changing a variable attenuator inside the unit. Attributes: module: the module number set by the user (must coincide with hardware) remote: true if remote control is enabled
6259906b63d6d428bbee3e8a
@dataclass <NEW_LINE> class DataCollatorCTCWithPadding: <NEW_LINE> <INDENT> processor: CustomWav2Vec2Processor <NEW_LINE> padding: Union[bool, str] = True <NEW_LINE> max_length: Optional[int] = 160000 <NEW_LINE> max_length_labels: Optional[int] = None <NEW_LINE> pad_to_multiple_of: Optional[int] = 160000 <NEW_LINE> pad_to_multiple_of_labels: Optional[int] = None <NEW_LINE> number_of_labels: Optional[int] = 5 <NEW_LINE> def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]: <NEW_LINE> <INDENT> input_features = [{"input_values": feature["input_values"]} for feature in features] <NEW_LINE> def onehot(lbl): <NEW_LINE> <INDENT> onehot = [0] * self.number_of_labels <NEW_LINE> onehot[int(lbl)] = 1 <NEW_LINE> return onehot <NEW_LINE> <DEDENT> output_features = [onehot(feature["labels"]) for feature in features] <NEW_LINE> batch = self.processor.pad( input_features, padding=True, max_length=self.max_length, pad_to_multiple_of=self.pad_to_multiple_of, return_tensors="pt", ) <NEW_LINE> batch["labels"] = torch.tensor(output_features) <NEW_LINE> return batch
Data collator that will dynamically pad the inputs received. Args: processor (:class:`~transformers.Wav2Vec2Processor`) The processor used for proccessing the data. padding (:obj:`bool`, :obj:`str` or :class:`~transformers.tokenization_utils_base.PaddingStrategy`, `optional`, defaults to :obj:`True`): Select a strategy to pad the returned sequences (according to the model's padding side and padding index) among: * :obj:`True` or :obj:`'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). * :obj:`'max_length'`: Pad to a maximum length specified with the argument :obj:`max_length` or to the maximum acceptable input length for the model if that argument is not provided. * :obj:`False` or :obj:`'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different lengths). max_length (:obj:`int`, `optional`): Maximum length of the ``input_values`` of the returned list and optionally padding length (see above). max_length_labels (:obj:`int`, `optional`): Maximum length of the ``labels`` returned list and optionally padding length (see above). pad_to_multiple_of (:obj:`int`, `optional`): If set will pad the sequence to a multiple of the provided value. This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >= 7.5 (Volta).
6259906b76e4537e8c3f0d84
class Commit(namedtuple('Foo', 'name revision create_at expire_at')): <NEW_LINE> <INDENT> pass
Commit result
6259906b8e7ae83300eea890
class RcMalformedCompareKoji(TestCompareKoji): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> TestCompareKoji.setUp(self) <NEW_LINE> self.before_rpm.add_installed_file( "/usr/share/data/invalid_rc.sh", rpmfluff.SourceFile("invalid_rc.sh", invalid_rc), ) <NEW_LINE> self.after_rpm.add_installed_file( "/usr/share/data/invalid_rc.sh", rpmfluff.SourceFile("invalid_rc.sh", invalid_rc), ) <NEW_LINE> self.inspection = "shellsyntax" <NEW_LINE> self.result = "BAD" <NEW_LINE> self.waiver_auth = "Anyone"
Invalid /bin/rc script is BAD for comparing Koji builds
6259906b5fcc89381b266d57
class Run(command_line.OptparseCommand): <NEW_LINE> <INDENT> usage = 'benchmark_name [page_set] [<options>]' <NEW_LINE> @classmethod <NEW_LINE> def CreateParser(cls): <NEW_LINE> <INDENT> options = browser_options.BrowserFinderOptions() <NEW_LINE> parser = options.CreateParser('%%prog %s %s' % (cls.Name(), cls.usage)) <NEW_LINE> return parser <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def AddCommandLineArgs(cls, parser, environment): <NEW_LINE> <INDENT> benchmark.AddCommandLineArgs(parser) <NEW_LINE> matching_benchmarks = [] <NEW_LINE> for arg in sys.argv[1:]: <NEW_LINE> <INDENT> matching_benchmarks += _MatchBenchmarkName(arg, environment) <NEW_LINE> <DEDENT> if matching_benchmarks: <NEW_LINE> <INDENT> matching_benchmark = matching_benchmarks.pop() <NEW_LINE> matching_benchmark.AddCommandLineArgs(parser) <NEW_LINE> matching_benchmark.SetArgumentDefaults(parser) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def ProcessCommandLineArgs(cls, parser, args, environment): <NEW_LINE> <INDENT> all_benchmarks = _Benchmarks(environment) <NEW_LINE> if not args.positional_args: <NEW_LINE> <INDENT> possible_browser = ( browser_finder.FindBrowser(args) if args.browser_type else None) <NEW_LINE> PrintBenchmarkList(all_benchmarks, possible_browser) <NEW_LINE> sys.exit(-1) <NEW_LINE> <DEDENT> input_benchmark_name = args.positional_args[0] <NEW_LINE> matching_benchmarks = _MatchBenchmarkName(input_benchmark_name, environment) <NEW_LINE> if not matching_benchmarks: <NEW_LINE> <INDENT> print >> sys.stderr, 'No benchmark named "%s".' % input_benchmark_name <NEW_LINE> print >> sys.stderr <NEW_LINE> most_likely_matched_benchmarks = GetMostLikelyMatchedBenchmarks( all_benchmarks, input_benchmark_name) <NEW_LINE> if most_likely_matched_benchmarks: <NEW_LINE> <INDENT> print >> sys.stderr, 'Do you mean any of those benchmarks below?' <NEW_LINE> PrintBenchmarkList(most_likely_matched_benchmarks, None, sys.stderr) <NEW_LINE> <DEDENT> sys.exit(-1) <NEW_LINE> <DEDENT> if len(matching_benchmarks) > 1: <NEW_LINE> <INDENT> print >> sys.stderr, ('Multiple benchmarks named "%s".' % input_benchmark_name) <NEW_LINE> print >> sys.stderr, 'Did you mean one of these?' <NEW_LINE> print >> sys.stderr <NEW_LINE> PrintBenchmarkList(matching_benchmarks, None, sys.stderr) <NEW_LINE> sys.exit(-1) <NEW_LINE> <DEDENT> benchmark_class = matching_benchmarks.pop() <NEW_LINE> if len(args.positional_args) > 1: <NEW_LINE> <INDENT> parser.error('Too many arguments.') <NEW_LINE> <DEDENT> assert issubclass(benchmark_class, benchmark.Benchmark), ( 'Trying to run a non-Benchmark?!') <NEW_LINE> benchmark.ProcessCommandLineArgs(parser, args) <NEW_LINE> benchmark_class.ProcessCommandLineArgs(parser, args) <NEW_LINE> cls._benchmark = benchmark_class <NEW_LINE> <DEDENT> def Run(self, args): <NEW_LINE> <INDENT> return min(255, self._benchmark().Run(args))
Run one or more benchmarks (default)
6259906b3317a56b869bf144
class SearchFeaturesRunner(FeatureFormatterMixin, AbstractSearchRunner): <NEW_LINE> <INDENT> def __init__(self, args): <NEW_LINE> <INDENT> super(SearchFeaturesRunner, self).__init__(args) <NEW_LINE> self._referenceName = args.referenceName <NEW_LINE> self._featureSetId = args.featureSetId <NEW_LINE> self._parentId = args.parentId <NEW_LINE> self._start = args.start <NEW_LINE> self._end = args.end <NEW_LINE> if args.featureTypes == "": <NEW_LINE> <INDENT> self._featureTypes = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._featureTypes = args.featureTypes.split(",") <NEW_LINE> <DEDENT> <DEDENT> def _run(self, featureSetId): <NEW_LINE> <INDENT> iterator = self._client.search_features( start=self._start, end=self._end, reference_name=self._referenceName, feature_set_id=featureSetId, parent_id=self._parentId, feature_types=self._featureTypes) <NEW_LINE> self._output(iterator) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> if self._featureSetId is None and not self._parentId: <NEW_LINE> <INDENT> for featureSet in self.getAllFeatureSets(): <NEW_LINE> <INDENT> self._run(featureSet) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self._run(self._featureSetId)
Runner class for the features/search method.
6259906b4428ac0f6e659d35
class crm_ais(crm_lha): <NEW_LINE> <INDENT> def __init__(self, Environment, randseed=None, name=None): <NEW_LINE> <INDENT> if not name: name="crm-ais" <NEW_LINE> crm_lha.__init__(self, Environment, randseed=randseed, name=name) <NEW_LINE> self.fullcomplist = {} <NEW_LINE> self.templates = PatternSelector(self.name) <NEW_LINE> <DEDENT> def NodeUUID(self, node): <NEW_LINE> <INDENT> return node <NEW_LINE> <DEDENT> def ais_components(self, extra={}): <NEW_LINE> <INDENT> complist = [] <NEW_LINE> if not len(self.fullcomplist.keys()): <NEW_LINE> <INDENT> for c in ["cib", "lrmd", "crmd", "attrd" ]: <NEW_LINE> <INDENT> self.fullcomplist[c] = Process( self, c, pats = self.templates.get_component(self.name, c), badnews_ignore = self.templates.get_component(self.name, "%s-ignore" % c), common_ignore = self.templates.get_component(self.name, "common-ignore")) <NEW_LINE> <DEDENT> self.fullcomplist["pengine"] = Process( self, "pengine", dc_pats = self.templates.get_component(self.name, "pengine"), badnews_ignore = self.templates.get_component(self.name, "pengine-ignore"), common_ignore = self.templates.get_component(self.name, "common-ignore")) <NEW_LINE> self.fullcomplist["stonith-ng"] = Process( self, "stonith-ng", process="stonithd", pats = self.templates.get_component(self.name, "stonith"), badnews_ignore = self.templates.get_component(self.name, "stonith-ignore"), common_ignore = self.templates.get_component(self.name, "common-ignore")) <NEW_LINE> self.fullcomplist.update(extra) <NEW_LINE> <DEDENT> vgrind = self.Env["valgrind-procs"].split() <NEW_LINE> for key in list(self.fullcomplist.keys()): <NEW_LINE> <INDENT> if self.Env["valgrind-tests"]: <NEW_LINE> <INDENT> if key in vgrind: <NEW_LINE> <INDENT> self.log("Filtering %s from the component list as it is being profiled by valgrind" % key) <NEW_LINE> continue <NEW_LINE> <DEDENT> <DEDENT> if key == "stonith-ng" and not self.Env["DoFencing"]: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> complist.append(self.fullcomplist[key]) <NEW_LINE> <DEDENT> return complist
The crm version 3 cluster manager class. It implements the things we need to talk to and manipulate crm clusters running on top of openais
6259906be1aae11d1e7cf40e
class PartycommunicationTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> trytond.tests.test_tryton.install_module('party_communication') <NEW_LINE> <DEDENT> def test0005views(self): <NEW_LINE> <INDENT> test_view('party_communication') <NEW_LINE> <DEDENT> def test0006depends(self): <NEW_LINE> <INDENT> test_depends()
Test Party Communication module
6259906b097d151d1a2c2871
class DokuWikiXMLRPCError(DokuWikiError): <NEW_LINE> <INDENT> def __init__(self, obj): <NEW_LINE> <INDENT> DokuWikiError.__init__(self) <NEW_LINE> if isinstance(obj, xmlrpclib.Fault): <NEW_LINE> <INDENT> self.page_id = obj.faultCode <NEW_LINE> self.message = obj.faultString <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.page_id = 0 <NEW_LINE> self.message = obj <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '<%s %s: \'%s\'>' % (self.__class__.__name__, self.page_id, self.message)
Triggered on XMLRPC faults.
6259906b4a966d76dd5f06f1
class EB_Inspector(IntelBase): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(EB_Inspector, self).__init__(*args, **kwargs) <NEW_LINE> self.subdir = '' <NEW_LINE> loosever = LooseVersion(self.version) <NEW_LINE> if loosever >= LooseVersion('2013_update7') and loosever < LooseVersion('2017'): <NEW_LINE> <INDENT> self.subdir = 'inspector_xe' <NEW_LINE> <DEDENT> elif loosever >= LooseVersion('2017') and loosever < LooseVersion('2021'): <NEW_LINE> <INDENT> self.subdir = 'inspector' <NEW_LINE> <DEDENT> elif loosever >= LooseVersion('2021'): <NEW_LINE> <INDENT> self.subdir = os.path.join('inspector', 'latest') <NEW_LINE> <DEDENT> <DEDENT> def make_installdir(self): <NEW_LINE> <INDENT> super(EB_Inspector, self).make_installdir(dontcreate=True) <NEW_LINE> <DEDENT> def install_step(self): <NEW_LINE> <INDENT> silent_cfg_names_map = None <NEW_LINE> if LooseVersion(self.version) <= LooseVersion('2013_update6'): <NEW_LINE> <INDENT> silent_cfg_names_map = { 'activation_name': ACTIVATION_NAME_2012, 'license_file_name': LICENSE_FILE_NAME_2012, } <NEW_LINE> <DEDENT> super(EB_Inspector, self).install_step(silent_cfg_names_map=silent_cfg_names_map) <NEW_LINE> <DEDENT> def make_module_req_guess(self): <NEW_LINE> <INDENT> return self.get_guesses_tools() <NEW_LINE> <DEDENT> def sanity_check_step(self): <NEW_LINE> <INDENT> binaries = ['inspxe-cl', 'inspxe-feedback', 'inspxe-gui', 'inspxe-runmc', 'inspxe-runtc'] <NEW_LINE> custom_paths = self.get_custom_paths_tools(binaries) <NEW_LINE> super(EB_Inspector, self).sanity_check_step(custom_paths=custom_paths)
Support for installing Intel Inspector
6259906b2ae34c7f260ac8eb
class LossComputeBase(nn.Module): <NEW_LINE> <INDENT> def __init__(self, generator, tgt_vocab): <NEW_LINE> <INDENT> super(LossComputeBase, self).__init__() <NEW_LINE> self.generator = generator <NEW_LINE> self.tgt_vocab = tgt_vocab <NEW_LINE> self.padding_idx = tgt_vocab.stoi[onmt.io.PAD_WORD] <NEW_LINE> <DEDENT> def _make_shard_state(self, batch, output, range_, attns=None): <NEW_LINE> <INDENT> return NotImplementedError <NEW_LINE> <DEDENT> def _compute_loss(self, batch, output, target, **kwargs): <NEW_LINE> <INDENT> return NotImplementedError <NEW_LINE> <DEDENT> def monolithic_compute_loss(self, batch, output, attns): <NEW_LINE> <INDENT> range_ = (0, batch.tgt.size(0)) <NEW_LINE> shard_state = self._make_shard_state(batch, output, range_, attns) <NEW_LINE> _, batch_stats = self._compute_loss(batch, **shard_state) <NEW_LINE> return batch_stats <NEW_LINE> <DEDENT> def sharded_compute_loss(self, batch, output, attns, cur_trunc, trunc_size, shard_size, normalization): <NEW_LINE> <INDENT> batch_stats = onmt.Statistics() <NEW_LINE> range_ = (cur_trunc, cur_trunc + trunc_size) <NEW_LINE> shard_state = self._make_shard_state(batch, output, range_, attns) <NEW_LINE> for shard in shards(shard_state, shard_size): <NEW_LINE> <INDENT> loss, stats = self._compute_loss(batch, **shard) <NEW_LINE> loss.div(normalization).backward(retain_graph=True) <NEW_LINE> batch_stats.update(stats) <NEW_LINE> <DEDENT> return batch_stats <NEW_LINE> <DEDENT> def _stats(self, loss, scores, target): <NEW_LINE> <INDENT> pred = scores.max(1)[1] <NEW_LINE> non_padding = target.ne(self.padding_idx) <NEW_LINE> num_correct = pred.eq(target) .masked_select(non_padding) .sum() <NEW_LINE> return onmt.Statistics(loss.item(), non_padding.sum().item(), num_correct.item()) <NEW_LINE> <DEDENT> def _bottle(self, v): <NEW_LINE> <INDENT> return v.view(-1, v.size(2)) <NEW_LINE> <DEDENT> def _unbottle(self, v, batch_size): <NEW_LINE> <INDENT> return v.view(-1, batch_size, v.size(1))
Class for managing efficient loss computation. Handles sharding next step predictions and accumulating mutiple loss computations Users can implement their own loss computation strategy by making subclass of this one. Users need to implement the _compute_loss() and make_shard_state() methods. Args: generator (:obj:`nn.Module`) : module that maps the output of the decoder to a distribution over the target vocabulary. tgt_vocab (:obj:`Vocab`) : torchtext vocab object representing the target output normalzation (str): normalize by "sents" or "tokens"
6259906b01c39578d7f14336
class Battery(): <NEW_LINE> <INDENT> def __init__(self,battery_size=70): <NEW_LINE> <INDENT> self.battery_size = battery_size <NEW_LINE> <DEDENT> def describe_battery(self): <NEW_LINE> <INDENT> print( "This car has a " + str(self.battery_size) + "-kWh battery." ) <NEW_LINE> <DEDENT> def get_range(self): <NEW_LINE> <INDENT> if self.battery_size == 70: <NEW_LINE> <INDENT> range = 240 <NEW_LINE> <DEDENT> elif self.battery_size == 85: <NEW_LINE> <INDENT> range =270 <NEW_LINE> <DEDENT> message = "This car can go approximately " + str(range) <NEW_LINE> message += "miles on a full charge" <NEW_LINE> print(message) <NEW_LINE> <DEDENT> def upgrade_battery(self): <NEW_LINE> <INDENT> if self.battery_size != 85: <NEW_LINE> <INDENT> self.battery_size = 85
一次模拟电动汽车电瓶的简单尝试
6259906b4527f215b58eb5a1
class Stopwatch: <NEW_LINE> <INDENT> __slots__ = '_time_func', 'start_time', '_time', 'running' <NEW_LINE> def __init__(self, time_func=time.time): <NEW_LINE> <INDENT> self._time_func = time_func <NEW_LINE> self.reset() <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self.start() <NEW_LINE> <DEDENT> def __exit__(self, *args): <NEW_LINE> <INDENT> self.stop() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f"Stopwatch(time={self.time})" <NEW_LINE> <DEDENT> @property <NEW_LINE> def time(self): <NEW_LINE> <INDENT> return self._time + self._time_func() - self.start_time if self.running else self._time <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self._time = 0. <NEW_LINE> self.start_time = None <NEW_LINE> self.running = False <NEW_LINE> return self <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> if self.running: <NEW_LINE> <INDENT> raise RuntimeError("Stopwatch is already running.") <NEW_LINE> <DEDENT> self.start_time = self._time_func() <NEW_LINE> self.running = True <NEW_LINE> return self <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> if self.running: <NEW_LINE> <INDENT> self._time = self.time <NEW_LINE> self.running = False <NEW_LINE> <DEDENT> return self._time
A stopwatch that can be used as a context manager. Example: with Stopwatch as sw: sleep(1) assert sw.running and sw.time >= 1. assert not sw.running and sw.time >= 1. Example: sw = Stopwatch().start() sleep(1) assert sw.running and sw.time >= 1. sw.stop() assert not sw.running and sw.time >= 1. sw.reset() assert not sw.running and sw.time == sw.start_time == 0
6259906b26068e7796d4e13c
class Human_quantum_player(Player): <NEW_LINE> <INDENT> def __init__(self, game): <NEW_LINE> <INDENT> self.game = game <NEW_LINE> <DEDENT> def play(self, opp_move): <NEW_LINE> <INDENT> if opp_move is not None: <NEW_LINE> <INDENT> self.game.do_move(opp_move) <NEW_LINE> <DEDENT> while True: <NEW_LINE> <INDENT> m = re.findall('\d+', input("Your Move (format 'from_i to_i' or 'from_r from_c to_r to_c') -> ") ) <NEW_LINE> if len(m)==4: <NEW_LINE> <INDENT> from_i = self.game.rc2i(int(m[0]), int(m[1])) <NEW_LINE> to_i = self.game.rc2i(int(m[2]), int(m[3])) <NEW_LINE> m = [from_i, to_i] <NEW_LINE> <DEDENT> if len(m)==2: <NEW_LINE> <INDENT> m[0] , m[1] = int(m[0]), int(m[1]) <NEW_LINE> <DEDENT> m = tuple(m) <NEW_LINE> if m not in self.game.legal_moves(): <NEW_LINE> <INDENT> print ("Error: illegal move ", m) <NEW_LINE> continue <NEW_LINE> <DEDENT> break <NEW_LINE> <DEDENT> self.game.do_move(m) <NEW_LINE> return m
Allow a user player to play a game at the console in format 'from_i to_i' or 'from_r from_c to_r to_c'
6259906bdd821e528d6da582
class ArticleImage(models.Model): <NEW_LINE> <INDENT> article = models.ForeignKey('ArticleItem') <NEW_LINE> image = models.ImageField(upload_to="upload")
article item image
6259906b5166f23b2e244bd5
class Viewport(object): <NEW_LINE> <INDENT> _viewport = None <NEW_LINE> def __new__(cls): <NEW_LINE> <INDENT> if Viewport._viewport is not None: <NEW_LINE> <INDENT> return Viewport._viewport <NEW_LINE> <DEDENT> Viewport._viewport = super(Viewport, cls).__new__(cls) <NEW_LINE> return Viewport._viewport <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> self.environment = get_environment() <NEW_LINE> <DEDENT> @property <NEW_LINE> def resolution(self): <NEW_LINE> <INDENT> return self.environment.get_viewport_size() <NEW_LINE> <DEDENT> @property <NEW_LINE> def fps(self): <NEW_LINE> <INDENT> if not self.environment.video_info_supported: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.environment.get_fps() <NEW_LINE> <DEDENT> @property <NEW_LINE> def lines(self): <NEW_LINE> <INDENT> return Line.parse_lines(self.environment.get_syllables()) <NEW_LINE> <DEDENT> def write(self, line): <NEW_LINE> <INDENT> self.environment.write_line(line) <NEW_LINE> <DEDENT> @property <NEW_LINE> def styles(self): <NEW_LINE> <INDENT> return StyleManager.resolve().get_styles() <NEW_LINE> <DEDENT> @property <NEW_LINE> def style_manager(self): <NEW_LINE> <INDENT> return StyleManager.resolve()
Viewports.
6259906b63d6d428bbee3e8b
class Jobs(object): <NEW_LINE> <INDENT> def __init__(self, name, client): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.client = client <NEW_LINE> <DEDENT> def running(self, offset=0, count=25): <NEW_LINE> <INDENT> return self.client('jobs', 'running', self.name, offset, count) <NEW_LINE> <DEDENT> def stalled(self, offset=0, count=25): <NEW_LINE> <INDENT> return self.client('jobs', 'stalled', self.name, offset, count) <NEW_LINE> <DEDENT> def scheduled(self, offset=0, count=25): <NEW_LINE> <INDENT> return self.client('jobs', 'scheduled', self.name, offset, count) <NEW_LINE> <DEDENT> def depends(self, offset=0, count=25): <NEW_LINE> <INDENT> return self.client('jobs', 'depends', self.name, offset, count) <NEW_LINE> <DEDENT> def recurring(self, offset=0, count=25): <NEW_LINE> <INDENT> return self.client('jobs', 'recurring', self.name, offset, count)
A proxy object for queue-specific job information
6259906b796e427e5384ff7b
class GfalCommand(Command): <NEW_LINE> <INDENT> def __init__(self, *, action, recursive = False, dry_run = False, **kwargs): <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> self.base_command = "gfal-" <NEW_LINE> self.action = action <NEW_LINE> self.recursive = recursive <NEW_LINE> self.dry_run = dry_run <NEW_LINE> self.start_site_prefix = self.get_site_prefix(self.start_site) if self.start_site is not None else "" <NEW_LINE> self.end_site_prefix = self.get_site_prefix(self.end_site) if self.end_site is not None else "" <NEW_LINE> self.build_command() <NEW_LINE> <DEDENT> def get_site_prefix(self, site): <NEW_LINE> <INDENT> if site.alias == 'local': <NEW_LINE> <INDENT> return "file:////" <NEW_LINE> <DEDENT> elif GetSiteInfo.EndpointType.GSIFTP in site.endpoints: <NEW_LINE> <INDENT> return max(site.endpoints[GetSiteInfo.EndpointType.GSIFTP], key=len) + "/store/user/" + site.username + "/" <NEW_LINE> <DEDENT> elif GetSiteInfo.EndpointType.XROOTD in site.endpoints: <NEW_LINE> <INDENT> return max(site.endpoints[GetSiteInfo.EndpointType.XROOTD], key=len) + "/store/user/" + site.username + "/" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(site) <NEW_LINE> raise RuntimeError(f"The site {site.alias} must be 'local' or have either a gsiftp or xrootd endpoint.") <NEW_LINE> <DEDENT> <DEDENT> def build_command(self): <NEW_LINE> <INDENT> self.command_pieces = [self.base_command + self.action] <NEW_LINE> if self.verbose: <NEW_LINE> <INDENT> self.command_pieces.append("-vvv") <NEW_LINE> <DEDENT> if self.recursive: <NEW_LINE> <INDENT> self.command_pieces.append("-r") <NEW_LINE> <DEDENT> if self.dry_run: <NEW_LINE> <INDENT> self.command_pieces.append("--dry-run") <NEW_LINE> <DEDENT> if self.additional_arguments != "": <NEW_LINE> <INDENT> self.command_pieces.append(self.additional_arguments) <NEW_LINE> <DEDENT> self.command_pieces.append((self.start_site_prefix + (self.override_path if self.override_path != "" else self.start_site.path) + "") if self.start_site is not None else "") <NEW_LINE> self.command_pieces.append((self.end_site_prefix + (self.override_path if self.override_path != "" else self.end_site.path) + "") if self.end_site is not None else "")
Creates and stores a GFAL based command
6259906b4e4d562566373c0a
class ConnectionFailure(ProviderFailure): <NEW_LINE> <INDENT> pass
Provider is considered off-line
6259906b32920d7e50bc784a
class CatalogBaseTable(object): <NEW_LINE> <INDENT> def __init__(self, j_catalog_base_table): <NEW_LINE> <INDENT> self._j_catalog_base_table = j_catalog_base_table <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def create_table( schema: TableSchema, partition_keys: List[str] = [], properties: Dict[str, str] = {}, comment: str = None ) -> "CatalogBaseTable": <NEW_LINE> <INDENT> assert schema is not None <NEW_LINE> assert partition_keys is not None <NEW_LINE> assert properties is not None <NEW_LINE> gateway = get_gateway() <NEW_LINE> return CatalogBaseTable( gateway.jvm.org.apache.flink.table.catalog.CatalogTableImpl( schema._j_table_schema, partition_keys, properties, comment)) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def create_view( original_query: str, expanded_query: str, schema: TableSchema, properties: Dict[str, str], comment: str = None ) -> "CatalogBaseTable": <NEW_LINE> <INDENT> assert original_query is not None <NEW_LINE> assert expanded_query is not None <NEW_LINE> assert schema is not None <NEW_LINE> assert properties is not None <NEW_LINE> gateway = get_gateway() <NEW_LINE> return CatalogBaseTable( gateway.jvm.org.apache.flink.table.catalog.CatalogViewImpl( original_query, expanded_query, schema._j_table_schema, properties, comment)) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _get(j_catalog_base_table): <NEW_LINE> <INDENT> return CatalogBaseTable(j_catalog_base_table) <NEW_LINE> <DEDENT> def get_options(self): <NEW_LINE> <INDENT> return dict(self._j_catalog_base_table.getOptions()) <NEW_LINE> <DEDENT> def get_properties(self): <NEW_LINE> <INDENT> warnings.warn("Deprecated in 1.11. Use CatalogBaseTable#get_options instead.", DeprecationWarning) <NEW_LINE> return dict(self._j_catalog_base_table.getProperties()) <NEW_LINE> <DEDENT> def get_schema(self): <NEW_LINE> <INDENT> return TableSchema(j_table_schema=self._j_catalog_base_table.getSchema()) <NEW_LINE> <DEDENT> def get_comment(self): <NEW_LINE> <INDENT> return self._j_catalog_base_table.getComment() <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> return CatalogBaseTable(self._j_catalog_base_table.copy()) <NEW_LINE> <DEDENT> def get_description(self): <NEW_LINE> <INDENT> description = self._j_catalog_base_table.getDescription() <NEW_LINE> if description.isPresent(): <NEW_LINE> <INDENT> return description.get() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def get_detailed_description(self): <NEW_LINE> <INDENT> detailed_description = self._j_catalog_base_table.getDetailedDescription() <NEW_LINE> if detailed_description.isPresent(): <NEW_LINE> <INDENT> return detailed_description.get() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None
CatalogBaseTable is the common parent of table and view. It has a map of key-value pairs defining the properties of the table.
6259906b67a9b606de5476a4
class PackageServicesRequestInputSet(InputSet): <NEW_LINE> <INDENT> def set_Response(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Response', value) <NEW_LINE> <DEDENT> def set_DestinationZip(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'DestinationZip', value) <NEW_LINE> <DEDENT> def set_Endpoint(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Endpoint', value) <NEW_LINE> <DEDENT> def set_OriginZip(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'OriginZip', value) <NEW_LINE> <DEDENT> def set_Password(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Password', value) <NEW_LINE> <DEDENT> def set_UserId(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'UserId', value)
An InputSet with methods appropriate for specifying the inputs to the PackageServicesRequest Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
6259906b2ae34c7f260ac8ed
class Client: <NEW_LINE> <INDENT> def __init__(self, client_socket, ip_address, connection_time, login): <NEW_LINE> <INDENT> self._is_connected = True <NEW_LINE> self._safe_quit = False <NEW_LINE> self._ip_address = ip_address <NEW_LINE> self._connection_time = connection_time <NEW_LINE> self._login = login <NEW_LINE> self._handler = ClientHandler(self, client_socket, 0.05) <NEW_LINE> self._handler.start() <NEW_LINE> <DEDENT> def is_connected(self): <NEW_LINE> <INDENT> return self._is_connected <NEW_LINE> <DEDENT> def set_connection_state(self, new_state): <NEW_LINE> <INDENT> self._is_connected = new_state <NEW_LINE> <DEDENT> def get_socket(self): <NEW_LINE> <INDENT> return self._handler.get_socket() <NEW_LINE> <DEDENT> def get_ip(self): <NEW_LINE> <INDENT> return self._ip_address <NEW_LINE> <DEDENT> def get_login(self): <NEW_LINE> <INDENT> return self._login <NEW_LINE> <DEDENT> def set_login(self, login): <NEW_LINE> <INDENT> self._login = login <NEW_LINE> <DEDENT> def is_safe_quit(self): <NEW_LINE> <INDENT> return self._safe_quit <NEW_LINE> <DEDENT> def set_quit_safety(self, new_state): <NEW_LINE> <INDENT> self._safe_quit = new_state
Данный класс хранит всю информацию о конкретном клиенте, которая необходима серверу для поддержки соединения. Для каждого сокета клиента создаётся отдельный обработчик.
6259906be76e3b2f99fda205
class _BraidConstructorIndex: <NEW_LINE> <INDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return lambda obj=None, p=None, * args, **kwargs: Braid(obj, *args, n=key, p=p, **kwargs)
>>> Braid([-3], 5) == B[5]([-3]) True
6259906b01c39578d7f14337
class SnubaDiscoverEventStorage(EventStorage): <NEW_LINE> <INDENT> def get_events(self, *args, **kwargs): <NEW_LINE> <INDENT> return SnubaEventStorage().get_events(*args, **kwargs) <NEW_LINE> <DEDENT> def get_event_by_id(self, *args, **kwargs): <NEW_LINE> <INDENT> return SnubaEventStorage().get_event_by_id(*args, **kwargs) <NEW_LINE> <DEDENT> def get_earliest_event_id(self, event, filter): <NEW_LINE> <INDENT> filter = deepcopy(filter) <NEW_LINE> filter.conditions = filter.conditions or [] <NEW_LINE> filter.conditions.extend(get_before_event_condition(event)) <NEW_LINE> filter.end = event.datetime <NEW_LINE> return self.__get_event_id_from_filter(filter=filter, orderby=ASC_ORDERING) <NEW_LINE> <DEDENT> def get_latest_event_id(self, event, filter): <NEW_LINE> <INDENT> filter = deepcopy(filter) <NEW_LINE> filter.conditions = filter.conditions or [] <NEW_LINE> filter.conditions.extend(get_after_event_condition(event)) <NEW_LINE> filter.start = event.datetime <NEW_LINE> return self.__get_event_id_from_filter(filter=filter, orderby=DESC_ORDERING) <NEW_LINE> <DEDENT> def get_next_event_id(self, event, filter): <NEW_LINE> <INDENT> assert filter, "You must provide a filter" <NEW_LINE> if not event: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> filter = deepcopy(filter) <NEW_LINE> filter.conditions = filter.conditions or [] <NEW_LINE> filter.conditions.extend(get_after_event_condition(event)) <NEW_LINE> filter.start = event.datetime <NEW_LINE> return self.__get_event_id_from_filter(filter=filter, orderby=ASC_ORDERING) <NEW_LINE> <DEDENT> def get_prev_event_id(self, event, filter): <NEW_LINE> <INDENT> assert filter, "You must provide a filter" <NEW_LINE> if not event: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> filter = deepcopy(filter) <NEW_LINE> filter.conditions = filter.conditions or [] <NEW_LINE> filter.conditions.extend(get_before_event_condition(event)) <NEW_LINE> filter.end = event.datetime <NEW_LINE> return self.__get_event_id_from_filter(filter=filter, orderby=DESC_ORDERING) <NEW_LINE> <DEDENT> def __get_event_id_from_filter(self, filter=None, orderby=None): <NEW_LINE> <INDENT> columns = [EVENT_ID, PROJECT_ID] <NEW_LINE> try: <NEW_LINE> <INDENT> result = snuba.dataset_query( selected_columns=columns, conditions=filter.conditions, filter_keys=filter.filter_keys, start=filter.start, end=filter.end, limit=1, referrer="eventstore.discover_dataset.get_next_or_prev_event_id", orderby=orderby, dataset=Dataset.Discover, ) <NEW_LINE> <DEDENT> except (snuba.QueryOutsideRetentionError, snuba.QueryOutsideGroupActivityError): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if "error" in result or len(result["data"]) == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> row = result["data"][0] <NEW_LINE> return (six.text_type(row["project_id"]), six.text_type(row["event_id"]))
Experimental backend that uses the Snuba Discover dataset instead of Events or Transactions directly.
6259906bbe8e80087fbc0890
class IssoParser(ConfigParser): <NEW_LINE> <INDENT> def getint(self, section, key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> delta = timedelta(self.get(section, key)) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return super(IssoParser, self).getint(section, key) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return int(delta.total_seconds()) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return int(delta.total_seconds()) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def getlist(self, section, key): <NEW_LINE> <INDENT> return list(map(str.strip, self.get(section, key).split(','))) <NEW_LINE> <DEDENT> def getiter(self, section, key): <NEW_LINE> <INDENT> for item in map(str.strip, self.get(section, key).split('\n')): <NEW_LINE> <INDENT> if item: <NEW_LINE> <INDENT> yield item <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def section(self, section): <NEW_LINE> <INDENT> return Section(self, section)
Parse INI-style configuration with some modifications for Isso. * parse human-readable timedelta such as "15m" as "15 minutes" * handle indented lines as "lists"
6259906b3539df3088ecdaa3
class BRZipCodeField(CharField): <NEW_LINE> <INDENT> default_error_messages = { 'invalid': _('Enter a zip code in the format XXXXX-XXX.'), } <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(BRZipCodeField, self).__init__(*args, **kwargs) <NEW_LINE> self.validators.append(BRPostalCodeValidator())
A form field that validates input as a Brazilian zip code, with the format XXXXX-XXX. .. versionchanged:: 2.2 Use BRPostalCodeValidator to centralize validation logic and share with equivalent model field. More details at: https://github.com/django/django-localflavor/issues/334
6259906b32920d7e50bc784b
class Trace(DeclarativeBase): <NEW_LINE> <INDENT> __tablename__ = 'traces' <NEW_LINE> id = Column(Integer, autoincrement=True, primary_key=True) <NEW_LINE> flight_id = Column(Integer, ForeignKey('flights.id', ondelete='CASCADE'), nullable=False) <NEW_LINE> flight = relation('Flight', primaryjoin=(flight_id == Flight.id), backref=backref('traces', cascade="all")) <NEW_LINE> contest_type = Column(String, nullable=False) <NEW_LINE> trace_type = Column(String, nullable=False) <NEW_LINE> distance = Column(Integer) <NEW_LINE> duration = Column(Interval) <NEW_LINE> times = Column(postgresql.ARRAY(DateTime), nullable=False) <NEW_LINE> _locations = GeometryColumn('locations', LineString(2, wkt_internal=True), nullable=False, comparator=PGComparator) <NEW_LINE> @property <NEW_LINE> def speed(self): <NEW_LINE> <INDENT> if self.distance is None or self.duration is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return float(self.distance) / self.duration.total_seconds() <NEW_LINE> <DEDENT> @property <NEW_LINE> def locations(self): <NEW_LINE> <INDENT> return [Location(longitude=location[0], latitude=location[1]) for location in self._locations.coords(DBSession)] <NEW_LINE> <DEDENT> @locations.setter <NEW_LINE> def locations(self, locations): <NEW_LINE> <INDENT> points = ['{} {}'.format(location.longitude, location.latitude) for location in locations] <NEW_LINE> wkt = "LINESTRING({})".format(','.join(points)) <NEW_LINE> self._locations = WKTSpatialElement(wkt)
This table saves the locations and visiting times of the turnpoints of an optimized Flight.
6259906bd268445f2663a75f
class SemiParametricRegressor(Regressor): <NEW_LINE> <INDENT> def __init__(self, regressor, features, transform, update='composition'): <NEW_LINE> <INDENT> super(SemiParametricRegressor, self).__init__( regressor, features) <NEW_LINE> self.transform = transform <NEW_LINE> self._update = self._select_update(update) <NEW_LINE> <DEDENT> @property <NEW_LINE> def algorithm(self): <NEW_LINE> <INDENT> return "Semi-Parametric" <NEW_LINE> <DEDENT> def _create_fitting_result(self, image, parameters, gt_shape=None): <NEW_LINE> <INDENT> self.transform.from_vector_inplace(parameters) <NEW_LINE> return SemiParametricFittingResult( image, self, parameters=[self.transform.as_vector()], gt_shape=gt_shape) <NEW_LINE> <DEDENT> def fit(self, image, initial_parameters, gt_shape=None, **kwargs): <NEW_LINE> <INDENT> self.transform.from_vector_inplace(initial_parameters) <NEW_LINE> return Fitter.fit(self, image, initial_parameters, gt_shape=gt_shape, **kwargs) <NEW_LINE> <DEDENT> def _select_update(self, update): <NEW_LINE> <INDENT> if update == 'additive': <NEW_LINE> <INDENT> return self._additive <NEW_LINE> <DEDENT> elif update == 'compositional': <NEW_LINE> <INDENT> return self._compositional <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Unknown update string selected. Valid' 'options are: additive, compositional') <NEW_LINE> <DEDENT> <DEDENT> def _additive(self, delta_p): <NEW_LINE> <INDENT> parameters = self.transform.as_vector() + delta_p <NEW_LINE> self.transform.from_vector_inplace(parameters) <NEW_LINE> <DEDENT> def _compositional(self, delta_p): <NEW_LINE> <INDENT> self.transform.compose_after_from_vector_inplace(delta_p) <NEW_LINE> <DEDENT> def update(self, delta_p, initial_shape): <NEW_LINE> <INDENT> self._update(delta_p) <NEW_LINE> return self.transform.target, self.transform.as_vector() <NEW_LINE> <DEDENT> def get_parameters(self, shape): <NEW_LINE> <INDENT> self.transform.set_target(shape) <NEW_LINE> return self.transform.as_vector()
Fitter of Semi-Parametric Regressor. Parameters ---------- regressor : callable The regressor to be used from `menpo.fit.regression.regressioncallables`. features : function The feature function used to regress.
6259906b6e29344779b01e59
class EVAR(Fingerprint): <NEW_LINE> <INDENT> API = 'PyFunge v2' <NEW_LINE> ID = 0x45564152 <NEW_LINE> @Fingerprint.register('G') <NEW_LINE> def command71(self, ip): <NEW_LINE> <INDENT> name = ip.pop_string() <NEW_LINE> try: <NEW_LINE> <INDENT> ip.push_string(self.platform.environ[name]) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> ip.push(0) <NEW_LINE> <DEDENT> <DEDENT> @Fingerprint.register('N') <NEW_LINE> def command78(self, ip): <NEW_LINE> <INDENT> ip.push(len(self.platform.environ)) <NEW_LINE> <DEDENT> @Fingerprint.register('P') <NEW_LINE> def command80(self, ip): <NEW_LINE> <INDENT> namevalue = ip.pop_string() <NEW_LINE> if '=' not in namevalue: <NEW_LINE> <INDENT> self.reflect(ip) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> name, value = namevalue.split('=', 1) <NEW_LINE> self.platform.environ[name] = value <NEW_LINE> <DEDENT> <DEDENT> @Fingerprint.register('V') <NEW_LINE> def command86(self, ip): <NEW_LINE> <INDENT> environ = self.platform.environ <NEW_LINE> n = ip.pop() <NEW_LINE> if 0 <= n < len(environ): <NEW_LINE> <INDENT> name = sorted(environ.keys())[n] <NEW_LINE> ip.push_string('%s=%s' % (name, environ[name])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.reflect(ip)
Environment variables extension
6259906b5166f23b2e244bd7
class EnrollmentDailyMysqlTask(OverwriteHiveAndMysqlDownstreamMixin, CourseEnrollmentDownstreamMixin, MysqlInsertTask): <NEW_LINE> <INDENT> overwrite = None <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(EnrollmentDailyMysqlTask, self).__init__(*args, **kwargs) <NEW_LINE> self.overwrite = self.overwrite_mysql <NEW_LINE> <DEDENT> @property <NEW_LINE> def table(self): <NEW_LINE> <INDENT> return 'course_enrollment_daily' <NEW_LINE> <DEDENT> @property <NEW_LINE> def insert_source_task(self): <NEW_LINE> <INDENT> return EnrollmentDailyDataTask( mapreduce_engine=self.mapreduce_engine, n_reduce_tasks=self.n_reduce_tasks, source=self.source, interval=self.interval, pattern=self.pattern, warehouse_path=self.warehouse_path, overwrite_n_days=self.overwrite_n_days, overwrite=self.overwrite_hive, ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def columns(self): <NEW_LINE> <INDENT> return EnrollmentDailyRecord.get_sql_schema() <NEW_LINE> <DEDENT> @property <NEW_LINE> def indexes(self): <NEW_LINE> <INDENT> return [ ('course_id',), ('course_id', 'date'), ]
A history of the number of students enrolled in each course at the end of each day. During operations: The object at insert_source_task is opened and each row is treated as a row to be inserted. At the end of this task data has been written to MySQL. Overwrite functionality is complex and configured through the OverwriteHiveAndMysqlDownstreamMixin, so we default the standard overwrite parameter to None.
6259906b1b99ca4002290138
class BadType(Invalid): <NEW_LINE> <INDENT> pass
The JWT has an unexpected "typ" value.
6259906b99cbb53fe68326ec
class MAVLink_gcs_radio_message(MAVLink_message): <NEW_LINE> <INDENT> def __init__(self, rssi, remrssi, txbuf, noise, remnoise, rxerrors, fixed): <NEW_LINE> <INDENT> MAVLink_message.__init__(self, MAVLINK_MSG_ID_GCS_RADIO, 'GCS_RADIO') <NEW_LINE> self._fieldnames = ['rssi', 'remrssi', 'txbuf', 'noise', 'remnoise', 'rxerrors', 'fixed'] <NEW_LINE> self.rssi = rssi <NEW_LINE> self.remrssi = remrssi <NEW_LINE> self.txbuf = txbuf <NEW_LINE> self.noise = noise <NEW_LINE> self.remnoise = remnoise <NEW_LINE> self.rxerrors = rxerrors <NEW_LINE> self.fixed = fixed <NEW_LINE> <DEDENT> def pack(self, mav): <NEW_LINE> <INDENT> return MAVLink_message.pack(self, mav, 108, struct.pack('<HHBBBBB', self.rxerrors, self.fixed, self.rssi, self.remrssi, self.txbuf, self.noise, self.remnoise))
Status of radio system on ground
6259906b63d6d428bbee3e8c
class ColorAnimation(ColorAnimationBase,ISealable,IAnimatable,IResource): <NEW_LINE> <INDENT> def AllocateClock(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def Clone(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def CloneCore(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def CloneCurrentValueCore(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def CreateInstance(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def CreateInstanceCore(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def FreezeCore(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def GetAsFrozenCore(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def GetCurrentValueAsFrozenCore(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def GetCurrentValueCore(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def GetNaturalDuration(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def GetNaturalDurationCore(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def OnChanged(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def OnFreezablePropertyChanged(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def OnPropertyChanged(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def ReadPreamble(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def ShouldSerializeProperty(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def WritePostscript(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def WritePreamble(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __new__(self,*__args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> By=property(lambda self: object(),lambda self,v: None,lambda self: None) <NEW_LINE> EasingFunction=property(lambda self: object(),lambda self,v: None,lambda self: None) <NEW_LINE> From=property(lambda self: object(),lambda self,v: None,lambda self: None) <NEW_LINE> IsAdditive=property(lambda self: object(),lambda self,v: None,lambda self: None) <NEW_LINE> IsCumulative=property(lambda self: object(),lambda self,v: None,lambda self: None) <NEW_LINE> To=property(lambda self: object(),lambda self,v: None,lambda self: None) <NEW_LINE> ByProperty=None <NEW_LINE> EasingFunctionProperty=None <NEW_LINE> FromProperty=None <NEW_LINE> ToProperty=None
Animates the value of a System.Windows.Media.Color property between two target values using linear interpolation over a specified System.Windows.Media.Animation.Timeline.Duration. ColorAnimation() ColorAnimation(toValue: Color,duration: Duration) ColorAnimation(toValue: Color,duration: Duration,fillBehavior: FillBehavior) ColorAnimation(fromValue: Color,toValue: Color,duration: Duration) ColorAnimation(fromValue: Color,toValue: Color,duration: Duration,fillBehavior: FillBehavior)
6259906b44b2445a339b7562
class BadWalkabout(Exception): <NEW_LINE> <INDENT> def __init__(self, failed_name): <NEW_LINE> <INDENT> super(BadWalkabout, self).__init__(failed_name) <NEW_LINE> self.failed_name = failed_name
Walkabout Resource specified does not contain any GIF files (AnimatedSprite) for creating a Walkabout sprite. Used in Walkabout when no files match "*.gif" in the provided Resource. Attributes: failed_name (str): The supplied archive was appended to the resources' walkabout direction. This is the value of the attempted which resulted in KeyError. See Also: * Walkabout.__init__() * resources.Resource
6259906bf548e778e596cd92
class AuditBaseTestCase(BaseModelTestCase): <NEW_LINE> <INDENT> ...
This is the base `TestCase` for all the `AuditBase` models in the project.
6259906bfff4ab517ebcf021
class SegmentTerminatorNotFoundError(Exception): <NEW_LINE> <INDENT> def __init__(self, msg): <NEW_LINE> <INDENT> self.msg = msg
Exception raised for errors in the Interchange Header. Attributes: msg -- explanation of the error
6259906b7d43ff2487428014
class OwnerListView(ListView): <NEW_LINE> <INDENT> permission = None <NEW_LINE> related= None <NEW_LINE> defer = None <NEW_LINE> owner_field = 'owner' <NEW_LINE> def sort_filter(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def get_queryset(self): <NEW_LINE> <INDENT> vars = self.request.GET <NEW_LINE> sort = vars.get('sort', None) <NEW_LINE> if sort: <NEW_LINE> <INDENT> if sort not in self.model._meta.get_all_field_names(): <NEW_LINE> <INDENT> raise Http404("%s is not a valid sorting field"%sort) <NEW_LINE> <DEDENT> <DEDENT> self.owner = get_object_or_404(User, username=self.kwargs.get("owner")) <NEW_LINE> owner_lookup = dict([(self.owner_field, self.owner)]) <NEW_LINE> list = self.model.objects.filter(**owner_lookup) <NEW_LINE> if self.permission: <NEW_LINE> <INDENT> list = list.filter(PermissionsRegistry.get_filter(self.permission, self.request.user)) <NEW_LINE> <DEDENT> if self.related: <NEW_LINE> <INDENT> list = list.select_related(*self.related) <NEW_LINE> <DEDENT> if self.defer: <NEW_LINE> <INDENT> list = list.defer(*self.defer) <NEW_LINE> <DEDENT> if sort: <NEW_LINE> <INDENT> dir = vars.get('dir', "desc") <NEW_LINE> order_by = (dir=="desc" and "-" or "") + sort <NEW_LINE> list = list.order_by(order_by) <NEW_LINE> <DEDENT> return list <NEW_LINE> <DEDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> kwargs = super(OwnerListView, self).get_context_data(**kwargs) <NEW_LINE> kwargs["owner"] = self.owner <NEW_LINE> kwargs["user"] = self.request.user <NEW_LINE> return kwargs
A base view for filtering based on the 'owner' of a particular object. For now, 'owner' is expected to be a username that maps to a Django User.
6259906b0a50d4780f7069c3
class __handler(TestStatus): <NEW_LINE> <INDENT> def __init__(self, verbose=False, alert=False): <NEW_LINE> <INDENT> super(self.__class__, self).__init__(verbose, alert) <NEW_LINE> self._alert = False
Default handler for tests, when a real one isn't specified. This only prints to stdout, and will never set (or remove) an alert.
6259906b3346ee7daa338261
class Alien(Sprite): <NEW_LINE> <INDENT> def __init__(self, ai_settings, screen): <NEW_LINE> <INDENT> super(Alien, self).__init__() <NEW_LINE> self.screen = screen <NEW_LINE> self.ai_settings = ai_settings <NEW_LINE> self.image = pygame.image.load('images/ufo.png') <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.x = self.rect.width <NEW_LINE> self.rect.y = self.rect.height <NEW_LINE> self.x = float(self.rect.x) <NEW_LINE> <DEDENT> def blitme(self): <NEW_LINE> <INDENT> self.screen.blit(self.image, self.rect) <NEW_LINE> <DEDENT> def check_edges(self): <NEW_LINE> <INDENT> screen_rect = self.screen.get_rect() <NEW_LINE> if self.rect.right >= screen_rect.right: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif self.rect.left <= 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.x += (self.ai_settings.alien_speed_factor * self.ai_settings.fleet_direction) <NEW_LINE> self.rect.x = self.x
Класс, представляющий одного пришельца.
6259906b01c39578d7f14338
class TestYoutubeSubsBase(SharedModuleStoreTestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> super().setUpClass() <NEW_LINE> cls.course = CourseFactory.create( org=cls.org, number=cls.number, display_name=cls.display_name)
Base class for tests of Youtube subs. Using override_settings and a setUpClass() override in a test class which is inherited by another test class doesn't work well with pytest-django.
6259906b5fc7496912d48e6b
class Equippable: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> require_attributes(self, ['equipped']) <NEW_LINE> <DEDENT> def add_bonuses(self, equippable): <NEW_LINE> <INDENT> for bonus in equippable.bonuses: <NEW_LINE> <INDENT> old = getattr(self, bonus) <NEW_LINE> new = old + equippable.bonuses[bonus] <NEW_LINE> print(f'adding {equippable.name} - {bonus}: {old} => {new}') <NEW_LINE> setattr(self, bonus, getattr(self, bonus) + equippable.bonuses[bonus]) <NEW_LINE> <DEDENT> <DEDENT> def remove_bonuses(self, equippable): <NEW_LINE> <INDENT> for bonus in equippable.bonuses: <NEW_LINE> <INDENT> old = getattr(self, bonus) <NEW_LINE> new = old - equippable.bonuses[bonus] <NEW_LINE> print(f'removing {equippable.name} - {bonus}: {old} => {new}') <NEW_LINE> setattr(self, bonus, getattr(self, bonus) - equippable.bonuses[bonus]) <NEW_LINE> <DEDENT> <DEDENT> def sum_bonuses(self): <NEW_LINE> <INDENT> bonuses = defaultdict(float) <NEW_LINE> for slot, equip in self.equipped.items(): <NEW_LINE> <INDENT> if equip: <NEW_LINE> <INDENT> if isinstance(equip, list): <NEW_LINE> <INDENT> for item in equip: <NEW_LINE> <INDENT> for bonus in item.bonuses: <NEW_LINE> <INDENT> bonuses[bonus] += item.bonuses[bonus] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for bonus in equip.bonuses: <NEW_LINE> <INDENT> bonuses[bonus] += equip.bonuses[bonus] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return bonuses <NEW_LINE> <DEDENT> def equip(self, slot, equippable): <NEW_LINE> <INDENT> print('equipping', equippable) <NEW_LINE> current = self.equipped[slot] <NEW_LINE> equippable.owner = self <NEW_LINE> if isinstance(current, list): <NEW_LINE> <INDENT> current.append(equippable) <NEW_LINE> self.add_bonuses(equippable) <NEW_LINE> <DEDENT> elif self.equipped[slot]: <NEW_LINE> <INDENT> self.equipped[slot] = equippable <NEW_LINE> self.add_bonuses(equippable) <NEW_LINE> self.remove_bonuses(current) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.equipped[slot] = equippable <NEW_LINE> self.add_bonuses(equippable) <NEW_LINE> <DEDENT> if isinstance(equippable, Skill): <NEW_LINE> <INDENT> equippable.set_focus_options() <NEW_LINE> <DEDENT> <DEDENT> def unequip_all(self): <NEW_LINE> <INDENT> for slot, equip in self.equipped.items(): <NEW_LINE> <INDENT> if equip: <NEW_LINE> <INDENT> if isinstance(equip, list): <NEW_LINE> <INDENT> for item in equip: <NEW_LINE> <INDENT> item.owner = None <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> equip.owner = None <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.equipped = { 'armor': None, 'weapon': None, 'active_skill': None, 'passives': [] }
Mixin that allows for wearing items and passive skills
6259906b4428ac0f6e659d39
class position_dodge(position): <NEW_LINE> <INDENT> REQUIRED_AES = {'x'} <NEW_LINE> def __init__(self, width=None, preserve='total'): <NEW_LINE> <INDENT> self.params = {'width': width, 'preserve': preserve} <NEW_LINE> <DEDENT> def setup_params(self, data): <NEW_LINE> <INDENT> if (('xmin' not in data) and ('xmax' not in data) and (self.params['width'] is None)): <NEW_LINE> <INDENT> msg = ("Width not defined. " "Set with `position_dodge(width = ?)`") <NEW_LINE> raise PlotnineError(msg) <NEW_LINE> <DEDENT> params = copy(self.params) <NEW_LINE> if params['preserve'] == 'total': <NEW_LINE> <INDENT> params['n'] = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> params['n'] = data['xmin'].value_counts().max() <NEW_LINE> <DEDENT> return params <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def compute_panel(cls, data, scales, params): <NEW_LINE> <INDENT> return cls.collide(data, params=params) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def strategy(data, params): <NEW_LINE> <INDENT> width = params['width'] <NEW_LINE> with suppress(TypeError): <NEW_LINE> <INDENT> iter(width) <NEW_LINE> width = np.asarray(width) <NEW_LINE> width = width[data.index] <NEW_LINE> <DEDENT> udata_group = data['group'].drop_duplicates() <NEW_LINE> n = params.get('n', None) <NEW_LINE> if n is None: <NEW_LINE> <INDENT> n = len(udata_group) <NEW_LINE> <DEDENT> if n == 1: <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> if not all([col in data.columns for col in ['xmin', 'xmax']]): <NEW_LINE> <INDENT> data['xmin'] = data['x'] <NEW_LINE> data['xmax'] = data['x'] <NEW_LINE> <DEDENT> d_width = np.max(data['xmax'] - data['xmin']) <NEW_LINE> udata_group = udata_group.sort_values() <NEW_LINE> groupidx = match(data['group'], udata_group) <NEW_LINE> groupidx = np.asarray(groupidx) + 1 <NEW_LINE> data['x'] = data['x'] + width * ((groupidx - 0.5) / n - 0.5) <NEW_LINE> data['xmin'] = data['x'] - (d_width / n) / 2 <NEW_LINE> data['xmax'] = data['x'] + (d_width / n) / 2 <NEW_LINE> return data
Dodge overlaps and place objects side-by-side Parameters ---------- width: float Dodging width, when different to the width of the individual elements. This is useful when you want to align narrow geoms with wider geoms preserve: str in ``['total', 'single']`` Should dodging preserve the total width of all elements at a position, or the width of a single element?
6259906be1aae11d1e7cf410
class BackupJob(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser( prog=piserver.constants.PROGRAM, description=piserver.constants.DESCRIPTION) <NEW_LINE> parser.add_argument('jobname', type=str, help='Job configuration file name (the local name)') <NEW_LINE> parser.add_argument( '-v', '--version', action='version', version='%(prog)s ' + piserver.constants.__version__) <NEW_LINE> parser.add_argument('--dryrun', dest='dryrun', action='store_const', const=True, default=False, help='Sets the dry run flag to true (no data is actually copied)') <NEW_LINE> args = parser.parse_args(sys.argv[1:]) <NEW_LINE> self.job_config = piserver.config.JobConfig( args.jobname, dryrun=args.dryrun) <NEW_LINE> self.src = self.job_config.gen_rsync_source() <NEW_LINE> self.dst = self.job_config.gen_rsync_target() <NEW_LINE> self.jobid = piserver.jobrecords.create_new_record(self.job_config) <NEW_LINE> self.completed = False <NEW_LINE> atexit.register(self._failure_catch) <NEW_LINE> self._run_backup() <NEW_LINE> <DEDENT> def _failure_catch(self): <NEW_LINE> <INDENT> if self.completed: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> piserver.desktop_notify.notify_failure(self.jobid, self.job_config, '?') <NEW_LINE> piserver.jobrecords.record_failure(self.jobid, self.job_config) <NEW_LINE> piserver.jobrecords.record_entry('failure was caught by _failure_catch') <NEW_LINE> <DEDENT> def _run_backup(self): <NEW_LINE> <INDENT> rsync_cmd = ['rsync', '-a'] <NEW_LINE> if self.job_config.is_dry_run(): <NEW_LINE> <INDENT> rsync_cmd.append('-n') <NEW_LINE> <DEDENT> if self.job_config.rsync_delete: <NEW_LINE> <INDENT> rsync_cmd.append('--delete') <NEW_LINE> <DEDENT> if self.job_config.rsync_verbose: <NEW_LINE> <INDENT> rsync_cmd.append('-v') <NEW_LINE> <DEDENT> for ignore in self.job_config.ignore_files: <NEW_LINE> <INDENT> rsync_cmd.append('--exclude='+ignore) <NEW_LINE> <DEDENT> rsync_cmd.append(self.src) <NEW_LINE> rsync_cmd.append(self.dst) <NEW_LINE> piserver.jobrecords.record_started(self.jobid, self.job_config) <NEW_LINE> piserver.jobrecords.record_call_stack(self.jobid, rsync_cmd) <NEW_LINE> piserver.desktop_notify.notify_start(self.jobid, self.job_config) <NEW_LINE> code = subprocess.call(rsync_cmd) <NEW_LINE> if code == 0: <NEW_LINE> <INDENT> piserver.jobrecords.record_success(self.jobid, self.job_config) <NEW_LINE> piserver.desktop_notify.notify_success(self.jobid, self.job_config) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> piserver.jobrecords.record_failure(self.jobid, self.job_config) <NEW_LINE> piserver.desktop_notify.notify_failure(self.jobid, self.job_config, code) <NEW_LINE> piserver.jobrecords.record_entry( self.jobid, 'subprocess failed with code %d' % code) <NEW_LINE> <DEDENT> self.completed = 1
Class representing a single backup job.
6259906b4e4d562566373c0d
class ModelSetting(Setting): <NEW_LINE> <INDENT> def __init__(self, config=None, name='ModelSetting'): <NEW_LINE> <INDENT> super(ModelSetting, self).__init__(name, config) <NEW_LINE> <DEDENT> def _initialize_attrib(self): <NEW_LINE> <INDENT> self.classname = '' <NEW_LINE> <DEDENT> def _load(self, _content): <NEW_LINE> <INDENT> self.classname = _content.get('classname')
Settings for model class selection.
6259906b3539df3088ecdaa6
class Age(atom.AtomBase): <NEW_LINE> <INDENT> _tag = 'age' <NEW_LINE> _namespace = YOUTUBE_NAMESPACE
The YouTube Age element
6259906b1f5feb6acb1643f5
class RegRefTransform: <NEW_LINE> <INDENT> def __init__(self, expr): <NEW_LINE> <INDENT> regref_symbols = list(expr.free_symbols) <NEW_LINE> self.expr = expr <NEW_LINE> self.func = sym.lambdify(regref_symbols, expr) <NEW_LINE> self.regrefs = [int(str(i)[1:]) for i in regref_symbols] <NEW_LINE> self.func_str = str(expr) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.func_str <NEW_LINE> <DEDENT> __repr__ = __str__
Class to represent a classical register transform. Args: expr (sympy.Expr): a SymPy expression representing the RegRef transform
6259906b0c0af96317c57962
class direction(object): <NEW_LINE> <INDENT> compass_dirs = { "N": 0.0, "NNE": 22.5, "NE": 45.0, "ENE": 67.5, "E": 90.0, "ESE":112.5, "SE":135.0, "SSE":157.5, "S":180.0, "SSW":202.5, "SW":225.0, "WSW":247.5, "W":270.0, "WNW":292.5, "NW":315.0, "NNW":337.5 } <NEW_LINE> def __init__( self, d ): <NEW_LINE> <INDENT> if d in direction.compass_dirs: <NEW_LINE> <INDENT> self._compass = d <NEW_LINE> self._degrees = direction.compass_dirs[d] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._compass = None <NEW_LINE> value = float(d) <NEW_LINE> if value < 0.0 or value > 360.0: <NEW_LINE> <INDENT> raise ValueError("direction must be 0..360: '"+str(value)+"'") <NEW_LINE> <DEDENT> self._degrees = value <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.string() <NEW_LINE> <DEDENT> def value( self ): <NEW_LINE> <INDENT> return self._degrees <NEW_LINE> <DEDENT> def string( self ): <NEW_LINE> <INDENT> return "%.0f degrees" % self._degrees <NEW_LINE> <DEDENT> def compass( self ): <NEW_LINE> <INDENT> if not self._compass: <NEW_LINE> <INDENT> degrees = 22.5 * round(self._degrees/22.5) <NEW_LINE> if degrees == 360.0: <NEW_LINE> <INDENT> self._compass = "N" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for name, d in list(direction.compass_dirs.items()): <NEW_LINE> <INDENT> if d == degrees: <NEW_LINE> <INDENT> self._compass = name <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return self._compass
A class representing a compass direction.
6259906bf548e778e596cd93
class ReturnSlaveMessageCountRequest(DiagnosticStatusSimpleRequest): <NEW_LINE> <INDENT> sub_function_code = 0x000E <NEW_LINE> def execute(self): <NEW_LINE> <INDENT> count = _MCB.Counter.SlaveMessage <NEW_LINE> return ReturnSlaveMessageCountResponse(count)
The response data field returns the quantity of messages addressed to the remote device, or broadcast, that the remote device has processed since its last restart, clear counters operation, or power-up
6259906b1f037a2d8b9e546e
class DescribeAllDevicesRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Offset = None <NEW_LINE> self.Limit = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Offset = params.get("Offset") <NEW_LINE> self.Limit = params.get("Limit") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set))
DescribeAllDevices请求参数结构体
6259906b4c3428357761baba
class CoreConfig(AppConfig): <NEW_LINE> <INDENT> name = 'core'
Default CoreConfig Class
6259906b56ac1b37e63038e6
class UpdateOwnProfile(permissions.BasePermission): <NEW_LINE> <INDENT> def has_object_permission(self, request, view, obj): <NEW_LINE> <INDENT> if request.method in permissions.SAFE_METHODS: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return obj.id == request.user.id
Allow user to edit their own profile
6259906b4428ac0f6e659d3a
class MaxUnpool1d(_MaxUnpoolNd): <NEW_LINE> <INDENT> def __init__(self, kernel_size, stride=None, padding=0): <NEW_LINE> <INDENT> super(MaxUnpool1d, self).__init__() <NEW_LINE> self.kernel_size = _single(kernel_size) <NEW_LINE> self.stride = _single(stride or kernel_size) <NEW_LINE> self.padding = _single(padding) <NEW_LINE> <DEDENT> def forward(self, input, indices, output_size=None): <NEW_LINE> <INDENT> return F.max_unpool1d(input, indices, self.kernel_size, self.stride, self.padding, output_size)
Computes a partial inverse of :class:`MaxPool1d`. :class:`MaxPool1d` is not fully invertible, since the non-maximal values are lost. :class:`MaxUnpool1d` takes in as input the output of :class:`MaxPool1d` including the indices of the maximal values and computes a partial inverse in which all non-maximal values are set to zero. .. note:: `MaxPool1d` can map several input sizes to the same output sizes. Hence, the inversion process can get ambiguous. To accommodate this, you can provide the needed output size as an additional argument `output_size` in the forward call. See the Inputs and Example below. Args: kernel_size (int or tuple): Size of the max pooling window. stride (int or tuple): Stride of the max pooling window. It is set to ``kernel_size`` by default. padding (int or tuple): Padding that was added to the input Inputs: - `input`: the input Tensor to invert - `indices`: the indices given out by `MaxPool1d` - `output_size` (optional) : a `torch.Size` that specifies the targeted output size Shape: - Input: :math:`(N, C, H_{in})` - Output: :math:`(N, C, H_{out})` where .. math:: H_{out} = (H_{in} - 1) * \text{stride}[0] - 2 * \text{padding}[0] + \text{kernel_size}[0] or as given by :attr:`output_size` in the call operator Example:: >>> pool = nn.MaxPool1d(2, stride=2, return_indices=True) >>> unpool = nn.MaxUnpool1d(2, stride=2) >>> input = torch.tensor([[[1., 2, 3, 4, 5, 6, 7, 8]]]) >>> output, indices = pool(input) >>> unpool(output, indices) tensor([[[ 0., 2., 0., 4., 0., 6., 0., 8.]]]) >>> # Example showcasing the use of output_size >>> input = torch.tensor([[[1., 2, 3, 4, 5, 6, 7, 8, 9]]]) >>> output, indices = pool(input) >>> unpool(output, indices, output_size=input.size()) tensor([[[ 0., 2., 0., 4., 0., 6., 0., 8., 0.]]]) >>> unpool(output, indices) tensor([[[ 0., 2., 0., 4., 0., 6., 0., 8.]]])
6259906b7d43ff2487428015
class RecipeBookRecipeRelation(models.Model): <NEW_LINE> <INDENT> recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) <NEW_LINE> recipeBook = models.ForeignKey(RecipeBook, on_delete=models.CASCADE) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return u'%s - %s' % (self.recipeBook.name, self.recipe.name) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '%s - %s' % (self.recipeBook.name, self.recipe.name)
class of a RecipeBookRecipeRelation
6259906b2ae34c7f260ac8f0
class MCP3201(MCP32xx): <NEW_LINE> <INDENT> def __init__(self, **spi_args): <NEW_LINE> <INDENT> super(MCP3201, self).__init__(0, differential=True, **spi_args) <NEW_LINE> <DEDENT> def _read(self): <NEW_LINE> <INDENT> return self._words_to_int(self._spi.read(2), 13) >> 1
The `MCP3201`_ is a 12-bit analog to digital converter with 1 channel. Please note that the MCP3201 always operates in differential mode, measuring the value of IN+ relative to IN-. .. _MCP3201: http://www.farnell.com/datasheets/1669366.pdf
6259906be76e3b2f99fda209
class ChangeLayout(zeit.content.cp.browser.blocks.teaser.ChangeLayout): <NEW_LINE> <INDENT> def reload(self): <NEW_LINE> <INDENT> super(ChangeLayout, self).reload(self.context.__parent__)
Always reload surrounding area when changing layout.
6259906bbaa26c4b54d50ab0
class CustomFieldSerializer: <NEW_LINE> <INDENT> superType = Object() <NEW_LINE> def __init__(self, instanceType): <NEW_LINE> <INDENT> self.instanceType = instanceType <NEW_LINE> <DEDENT> def getTypeName(self): <NEW_LINE> <INDENT> return self.className <NEW_LINE> <DEDENT> def getSignature(self, crc): <NEW_LINE> <INDENT> crc = crc32(self.getTypeName(), crc) <NEW_LINE> if self.superType is not None: <NEW_LINE> <INDENT> crc = self.superType.getSignature(crc) <NEW_LINE> <DEDENT> return crc
Base functionality for the custom field serializers.
6259906be1aae11d1e7cf411
class PersonForm(forms.Form): <NEW_LINE> <INDENT> first_name = forms.CharField(max_length=20, label=_(u"First Name")) <NEW_LINE> last_name = forms.CharField(max_length=30, label=_(u"Last Name")) <NEW_LINE> username = forms.CharField(max_length=15, label=_(u"Username")) <NEW_LINE> email = forms.EmailField() <NEW_LINE> phone = forms.CharField(max_length=20, label=_(u"Phone")) <NEW_LINE> password1 = forms.CharField(widget=forms.PasswordInput(), label=_(u"Password")) <NEW_LINE> password2 = forms.CharField(widget=forms.PasswordInput(), label=_(u"Confirmation")) <NEW_LINE> gender = forms.ChoiceField(choices = GENDER_CHOICES, label=_(u"Gender")) <NEW_LINE> def clean_username(self): <NEW_LINE> <INDENT> username = self.cleaned_data.get("username") <NEW_LINE> if User.objects.filter(username=username).exists(): <NEW_LINE> <INDENT> raise forms.ValidationError(_(u"username %s is in use, please specify another one") % username) <NEW_LINE> <DEDENT> return self.cleaned_data.get("username") <NEW_LINE> <DEDENT> def clean(self): <NEW_LINE> <INDENT> cleaned_data = self.cleaned_data <NEW_LINE> password1 = cleaned_data.get("password1") <NEW_LINE> password2 = cleaned_data.get("password2") <NEW_LINE> if not password1 or len(password1) < 4: <NEW_LINE> <INDENT> self._errors['password1'] = self.error_class( [_(u"please specify a password at least four characters")]) <NEW_LINE> if password1: del cleaned_data["password1"] <NEW_LINE> if password2: del cleaned_data["password2"] <NEW_LINE> <DEDENT> elif password1 != password2: <NEW_LINE> <INDENT> self._errors['password1'] = self.error_class( [_(u"password and confirmation does not match")]) <NEW_LINE> del cleaned_data["password1"] <NEW_LINE> if password2: del cleaned_data["password2"] <NEW_LINE> <DEDENT> return cleaned_data
Person registration form
6259906b4428ac0f6e659d3b
class RepeatedKFold(_RepeatedSplits): <NEW_LINE> <INDENT> def __init__(self, n_splits=5, n_repeats=10, random_state=None): <NEW_LINE> <INDENT> super(RepeatedKFold, self).__init__( KFold, n_repeats, random_state, n_splits=n_splits)
Repeated K-Fold cross validator. Repeats K-Fold n times with different randomization in each repetition. Read more in the :ref:`User Guide <cross_validation>`. Parameters ---------- n_splits : int, default=5 Number of folds. Must be at least 2. n_repeats : int, default=10 Number of times cross-validator needs to be repeated. random_state : int, RandomState instance or None, optional, default=None If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. Examples -------- >>> import numpy as np >>> from sklearn.model_selection import RepeatedKFold >>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]]) >>> y = np.array([0, 0, 1, 1]) >>> rkf = RepeatedKFold(n_splits=2, n_repeats=2, random_state=2652124) >>> for train_index, test_index in rkf.split(X): ... print("TRAIN:", train_index, "TEST:", test_index) ... X_train, X_test = X[train_index], X[test_index] ... y_train, y_test = y[train_index], y[test_index] ... TRAIN: [0 1] TEST: [2 3] TRAIN: [2 3] TEST: [0 1] TRAIN: [1 2] TEST: [0 3] TRAIN: [0 3] TEST: [1 2] Notes ----- Randomized CV splitters may return different results for each call of split. You can make the results identical by setting ``random_state`` to an integer. See also -------- RepeatedStratifiedKFold: Repeats Stratified K-Fold n times.
6259906b4e4d562566373c0f
class PartFont(Part): <NEW_LINE> <INDENT> def __init__(self, children): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.fontname = children[0].text <NEW_LINE> <DEDENT> except (AttributeError, IndexError): <NEW_LINE> <INDENT> self.fontname = '' <NEW_LINE> <DEDENT> self.children = children[1:] <NEW_LINE> <DEDENT> def render(self, state): <NEW_LINE> <INDENT> font = state.font <NEW_LINE> oldfamily = font.family() <NEW_LINE> font.setFamily(self.fontname) <NEW_LINE> state.painter.setFont(font) <NEW_LINE> Part.render(self, state) <NEW_LINE> font.setFamily(oldfamily) <NEW_LINE> state.painter.setFont(font)
Change font name in part.
6259906b91f36d47f2231a93
class _NodeSetupMixin(object): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super().setUp() <NEW_LINE> self.bp1 = models.Blueprint( id='bp1', creator=self.user, tenant=self.tenant, ) <NEW_LINE> self.dep1 = self._deployment('d1') <NEW_LINE> <DEDENT> def _deployment(self, deployment_id, **kwargs): <NEW_LINE> <INDENT> deployment_params = { 'id': deployment_id, 'blueprint': self.bp1, 'scaling_groups': {}, 'creator': self.user, 'tenant': self.tenant, } <NEW_LINE> deployment_params.update(kwargs) <NEW_LINE> return models.Deployment(**deployment_params) <NEW_LINE> <DEDENT> def _node(self, node_id, **kwargs): <NEW_LINE> <INDENT> node_params = { 'id': node_id, 'type': 'type1', 'number_of_instances': 0, 'deploy_number_of_instances': 0, 'max_number_of_instances': 0, 'min_number_of_instances': 0, 'planned_number_of_instances': 0, 'deployment': self.dep1, 'creator': self.user, 'tenant': self.tenant, } <NEW_LINE> node_params.update(kwargs) <NEW_LINE> return models.Node(**node_params) <NEW_LINE> <DEDENT> def _instance(self, instance_id, **kwargs): <NEW_LINE> <INDENT> instance_params = { 'id': instance_id, 'state': '', 'creator': self.user, 'tenant': self.tenant, } <NEW_LINE> instance_params.update(kwargs) <NEW_LINE> if 'node' not in instance_params: <NEW_LINE> <INDENT> instance_params['node'] = self._node('node1') <NEW_LINE> <DEDENT> return models.NodeInstance(**instance_params)
A mixin useful in these tests, that exposes utils for creating nodes Creating nodes otherwise is a pain because of how many arguments they require
6259906bd6c5a102081e3932
class BluetoothConnection(object): <NEW_LINE> <INDENT> def __init__(self, acl_connect_event): <NEW_LINE> <INDENT> if len(acl_connect_event.key_field_values) < 2: <NEW_LINE> <INDENT> raise (BluetoothConnectionError( 'Invalid ACL connection event, cannot create connection.')) <NEW_LINE> <DEDENT> conn_handle = _convert_handle_to_int(acl_connect_event.key_field_values[0]) <NEW_LINE> if conn_handle is None: <NEW_LINE> <INDENT> raise(BluetoothConnectionError( 'Invalid ACL connection handle, cannot create connection.')) <NEW_LINE> <DEDENT> self.acl_connect_event = acl_connect_event <NEW_LINE> self._connection_handle = conn_handle <NEW_LINE> self._bt_addr = acl_connect_event.key_field_values[1] <NEW_LINE> self.event_lists = {} <NEW_LINE> for evt_type in BT_EVENTS: <NEW_LINE> <INDENT> if 'acl ' not in evt_type: <NEW_LINE> <INDENT> self.event_lists[evt_type] = [BluetoothEventFactory.create_event( evt_type)] <NEW_LINE> <DEDENT> <DEDENT> self.acl_disconnect_event = BluetoothEventFactory.create_event( 'acl disconnect') <NEW_LINE> <DEDENT> def update(self, packet): <NEW_LINE> <INDENT> if self.is_disconnected: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> handle = get_connection_handle(packet) <NEW_LINE> bd_addr = get_bd_addr(packet) <NEW_LINE> if ((handle is None or handle != self._connection_handle) and (bd_addr is None or bd_addr != self._bt_addr)): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for evt_type in self.event_lists: <NEW_LINE> <INDENT> evt = self.event_lists[evt_type][-1] <NEW_LINE> evt.update(packet) <NEW_LINE> if evt.is_finished: <NEW_LINE> <INDENT> self.event_lists[evt_type].append( BluetoothEventFactory.create_event(evt_type)) <NEW_LINE> <DEDENT> <DEDENT> self.acl_disconnect_event.update(packet) <NEW_LINE> if self.acl_disconnect_event.is_finished: <NEW_LINE> <INDENT> print('Disconnected! handle = %s' % hex(handle)) <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def get_events(self): <NEW_LINE> <INDENT> all_events = [] <NEW_LINE> for evt_type in self.event_lists: <NEW_LINE> <INDENT> all_events.extend(self.event_lists[evt_type][:-1]) <NEW_LINE> <DEDENT> all_events = sorted(all_events, key=lambda event: event.start_time) <NEW_LINE> all_events = [self.acl_connect_event] + all_events <NEW_LINE> if self.acl_disconnect_event.is_finished: <NEW_LINE> <INDENT> all_events += [self.acl_disconnect_event] <NEW_LINE> <DEDENT> return all_events <NEW_LINE> <DEDENT> @property <NEW_LINE> def bt_addr(self): <NEW_LINE> <INDENT> return self._bt_addr <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_disconnected(self): <NEW_LINE> <INDENT> if self.acl_disconnect_event: <NEW_LINE> <INDENT> return self.acl_disconnect_event.is_finished <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def print_summary(self): <NEW_LINE> <INDENT> print('Connection handle {}, BT addr {},{} disconnected.'.format( hex(self._connection_handle), self._bt_addr, '' if self.is_disconnected else ' not'))
Represents a Bluetooth connection. This class maintains a list of events that happened during the connection.
6259906b8da39b475be049f4
class QEnterEvent(__PyQt5_QtCore.QEvent): <NEW_LINE> <INDENT> def globalPos(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def globalX(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def globalY(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def localPos(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def pos(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def screenPos(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def windowPos(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def x(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def y(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def __init__(self, *__args): <NEW_LINE> <INDENT> pass
QEnterEvent(Union[QPointF, QPoint], Union[QPointF, QPoint], Union[QPointF, QPoint]) QEnterEvent(QEnterEvent)
6259906b2ae34c7f260ac8f1
class EmailTemplate(models.Model): <NEW_LINE> <INDENT> subject = models.CharField(_('subject'),max_length=1024) <NEW_LINE> body = models.TextField(_('body'),max_length=8192) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.subject <NEW_LINE> <DEDENT> def send(self, recipients, **kw): <NEW_LINE> <INDENT> if hasattr(recipients, 'all'): <NEW_LINE> <INDENT> recipients=recipients.all() <NEW_LINE> <DEDENT> if not hasattr(recipients, '__iter__'): <NEW_LINE> <INDENT> recipients = [recipients] <NEW_LINE> <DEDENT> from djangomail import Mailer <NEW_LINE> for recipient in recipients: <NEW_LINE> <INDENT> Mailer.send_template_mail(self.subject, recipient, self.body, **kw) <NEW_LINE> <DEDENT> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = _('email templates') <NEW_LINE> verbose_name = _('email template')
Email template. Used for sending emails after e.g. issue updates.
6259906b5fdd1c0f98e5f78e
class StreamProtocolHandler(object): <NEW_LINE> <INDENT> def __init__(self, message_schema, packet_callback): <NEW_LINE> <INDENT> self.message_schema = message_schema <NEW_LINE> self.packet_callback = packet_callback <NEW_LINE> self._available_bytes = b"" <NEW_LINE> self._packet_generator = self._create_packet_generator() <NEW_LINE> <DEDENT> def _create_packet_generator(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> curmsg = self.message_schema() <NEW_LINE> for i, (_name, field) in enumerate(curmsg): <NEW_LINE> <INDENT> bytes_required = field.bytes_required <NEW_LINE> if i == 0 and isinstance(field, Magic): <NEW_LINE> <INDENT> magic_seq = field.getval() <NEW_LINE> while True: <NEW_LINE> <INDENT> if len(self._available_bytes) < bytes_required: <NEW_LINE> <INDENT> yield None <NEW_LINE> continue <NEW_LINE> <DEDENT> idx = self._available_bytes.find(magic_seq) <NEW_LINE> if idx == -1: <NEW_LINE> <INDENT> self._available_bytes = self._available_bytes[-(bytes_required - 1):] <NEW_LINE> yield None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._available_bytes = self._available_bytes[idx:] <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> while True: <NEW_LINE> <INDENT> bytes_available = len(self._available_bytes) <NEW_LINE> if bytes_required <= bytes_available: <NEW_LINE> <INDENT> field_bytes = self._available_bytes[:bytes_required] <NEW_LINE> new_bytes = self._available_bytes[bytes_required:] <NEW_LINE> self._available_bytes = new_bytes <NEW_LINE> field.unpack(field_bytes) <NEW_LINE> break <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> yield None <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> yield curmsg <NEW_LINE> <DEDENT> <DEDENT> def feed(self, new_bytes): <NEW_LINE> <INDENT> self._available_bytes += new_bytes <NEW_LINE> callbacks = [] <NEW_LINE> try: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> packet = six.next(self._packet_generator) <NEW_LINE> if packet is None: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> callbacks.append(partial(self.packet_callback, packet)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> self.reset() <NEW_LINE> <DEDENT> for callback in callbacks: <NEW_LINE> <INDENT> callback() <NEW_LINE> <DEDENT> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self._packet_generator = self._create_packet_generator() <NEW_LINE> self._available_bytes = b""
Protocol handler that deals fluidly with a stream of bytes The protocol handler is agnostic to the data source or methodology being used to collect the data (blocking reads on a socket to async IO on a serial port). Here's an example of what one usage might look like (very simple approach for parsing a simple TCP protocol:: from suitcase.protocol import StreamProtocolHandler from suitcase.fields import LengthField, UBInt16, VariableRawPayload from suitcase.structure import Structure import socket class SimpleFramedMessage(Structure): length = LengthField(UBInt16()) payload = VariableRawPayload(length) def packet_received(packet): print(packet) def run_forever(host, port): protocol_handler = StreamProtocolHandler(SimpleFramedMessage, packet_received) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(host, port) sock.setblocking(1) while True: bytes = sock.recv(1024) if len(bytes) == 0: print("Socket closed... exiting") return else: protocol_handler.feed(bytes) :param message_schema: The top-level message schema that defines the packets for the protocol to be used. :param packet_callback: A callback to be executed with the form ``callback(packet)`` when a fully-formed packet is detected.
6259906b32920d7e50bc784f
class DescribeOperationResultRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.TaskId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.TaskId = params.get("TaskId")
DescribeOperationResult请求参数结构体
6259906bd486a94d0ba2d7c8
class VIEW3D_OT_pospath_button(Operator, ImportHelper): <NEW_LINE> <INDENT> bl_idname = "atomblend.import_pospath" <NEW_LINE> bl_label = "Select .pos file" <NEW_LINE> filename_ext = ".pos" <NEW_LINE> filter_glob = StringProperty( default="*.pos", options={'HIDDEN'}, ) <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> props = context.scene.pos_panel_props <NEW_LINE> props.pos_filename = self.filepath <NEW_LINE> return {'FINISHED'}
Select POS file from dialogue
6259906b435de62698e9d613
class Node: <NEW_LINE> <INDENT> def __init__(self,data): <NEW_LINE> <INDENT> self.data = data <NEW_LINE> self.parent = None <NEW_LINE> self.children = [] <NEW_LINE> <DEDENT> def addChild(self,data): <NEW_LINE> <INDENT> node = Tree.Node(data) <NEW_LINE> node.parent = self <NEW_LINE> self.children.append(node) <NEW_LINE> <DEDENT> def getChild(self,data): <NEW_LINE> <INDENT> for child in self.children: <NEW_LINE> <INDENT> if child.data == data: <NEW_LINE> <INDENT> return child <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def removeChild(self,node): <NEW_LINE> <INDENT> for child in self.children: <NEW_LINE> <INDENT> if child.data == str(node): <NEW_LINE> <INDENT> self.children.remove(child) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.data
Node class should not be used outside the context of a tree, so it is nested within the Tree class.
6259906b7d847024c075dbe4
class PassThroughEnc2Dec(Seq2SeqEnc2Dec): <NEW_LINE> <INDENT> def hybrid_forward( self, F, encoder_output_static: Tensor, encoder_output_dynamic: Tensor, future_features_dynamic: Tensor, ) -> Tuple[Tensor, Tensor]: <NEW_LINE> <INDENT> return encoder_output_static, encoder_output_dynamic
Simplest class for passing encoder tensors do decoder. Passes through tensors, except that future_features_dynamic is dropped.
6259906bac7a0e7691f73cf0
class EmptyPasswordStoreError(PasswordStoreError): <NEW_LINE> <INDENT> pass
Raised when the password store is empty.
6259906ba8370b77170f1bcf
class comRNA(CommandLineApplication): <NEW_LINE> <INDENT> _parameters = { '-L':ValuedParameter(Prefix='',Name='L',Value=None,Delimiter=' '), '-E':ValuedParameter(Prefix='',Name='E',Value=None,Delimiter=' '), '-S':ValuedParameter(Prefix='',Name='S',Value=None,Delimiter=' '), '-Sh':ValuedParameter(Prefix='',Name='Sh',Value=None,Delimiter=' '), '-Sl':ValuedParameter(Prefix='',Name='Sl',Value=None,Delimiter=' '), '-P':ValuedParameter(Prefix='',Name='P',Value=None,Delimiter=' '), '-n':ValuedParameter(Prefix='',Name='n',Value=None,Delimiter=' '), '-x':ValuedParameter(Prefix='',Name='x',Value=None,Delimiter=' '), '-m':ValuedParameter(Prefix='',Name='m',Value=None,Delimiter=' '), '-tp':ValuedParameter(Prefix='',Name='tp',Value=None,Delimiter=' '), '-ts':ValuedParameter(Prefix='',Name='ts',Value=None,Delimiter=' '), '-a':ValuedParameter(Prefix='',Name='a',Value=None,Delimiter=' '), '-o':ValuedParameter(Prefix='',Name='o',Value=None,Delimiter=' '), '-c':ValuedParameter(Prefix='',Name='c',Value=None,Delimiter=' '), '-j':ValuedParameter(Prefix='',Name='j',Value=None,Delimiter=' '), '-r':ValuedParameter(Prefix='',Name='r',Value=None,Delimiter=' '), '-f':ValuedParameter(Prefix='',Name='f',Value=None,Delimiter=' '), '-v':ValuedParameter(Prefix='',Name='v',Value=None,Delimiter=' '), '-g':ValuedParameter(Prefix='',Name='g',Value=None,Delimiter=' '), '-d':ValuedParameter(Prefix='',Name='d',Value=None,Delimiter=' '), '-wa':ValuedParameter(Prefix='',Name='wa',Value=None,Delimiter=' '), '-wb':ValuedParameter(Prefix='',Name='wb',Value=None,Delimiter=' '), '-wc':ValuedParameter(Prefix='',Name='wc',Value=None,Delimiter=' '), '-wd':ValuedParameter(Prefix='',Name='wd',Value=None,Delimiter=' '), '-we':ValuedParameter(Prefix='',Name='we',Value=None,Delimiter=' '), '-pk':ValuedParameter(Prefix='',Name='pk',Value=None,Delimiter=' '), '-pg':ValuedParameter(Prefix='',Name='pg',Value=None,Delimiter=' '), '-pd':ValuedParameter(Prefix='',Name='pd',Value=None,Delimiter=' '), '-ps':ValuedParameter(Prefix='',Name='ps',Value=None,Delimiter=' '), '-pc':ValuedParameter(Prefix='',Name='pc',Value=None,Delimiter=' ')} <NEW_LINE> _command = 'comRNA' <NEW_LINE> _input_handler = '_input_as_string'
Application controller comRNA v1.80 for comRNA options type comRNA at the promt
6259906bf548e778e596cd96
class Reset(Cmd): <NEW_LINE> <INDENT> cmd = "reset" <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> Cmd.__init__(self) <NEW_LINE> self.parser.add_argument("-v", "--verbose", action="store_true", help="enable verbose output") <NEW_LINE> <DEDENT> def __call__(self, args): <NEW_LINE> <INDENT> if args.verbose: <NEW_LINE> <INDENT> enable_verbose_logs() <NEW_LINE> <DEDENT> delete_cache()
Reset cache
6259906bf7d966606f7494c0
class ToNumpy(ForceHandleMixin, BaseTransformer): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> BaseTransformer.__init__(self) <NEW_LINE> ForceHandleMixin.__init__(self) <NEW_LINE> <DEDENT> def _will_process(self, data_container: DataContainer, context: ExecutionContext) -> ( DataContainer, ExecutionContext): <NEW_LINE> <INDENT> return data_container.to_numpy(), context
Convert data inputs, and expected outputs to a numpy array.
6259906b21bff66bcd724470
class TempFile: <NEW_LINE> <INDENT> def __init__(self, mode): <NEW_LINE> <INDENT> import tempfile <NEW_LINE> fd, self.Name = tempfile.mkstemp(prefix='hg-p4-') <NEW_LINE> if mode: <NEW_LINE> <INDENT> self.File = os.fdopen(fd, mode) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> os.close(fd) <NEW_LINE> self.File = None <NEW_LINE> <DEDENT> <DEDENT> def close(self): <NEW_LINE> <INDENT> if self.File: <NEW_LINE> <INDENT> self.File.close() <NEW_LINE> self.File=None <NEW_LINE> <DEDENT> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> self.close() <NEW_LINE> try: <NEW_LINE> <INDENT> os.unlink(self.Name) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass
Temporary file
6259906b99fddb7c1ca639d5
class BaseCallback(object): <NEW_LINE> <INDENT> def __init__(self, epochs=None, manual_update=False, external_metric_labels=None, **kwargs): <NEW_LINE> <INDENT> self.params = None <NEW_LINE> self.model = None <NEW_LINE> self.manual_update = manual_update <NEW_LINE> self.epochs = epochs <NEW_LINE> self.epoch = 0 <NEW_LINE> if external_metric_labels is None: <NEW_LINE> <INDENT> external_metric_labels = collections.OrderedDict() <NEW_LINE> <DEDENT> self.external_metric_labels = external_metric_labels <NEW_LINE> self.external_metric = collections.OrderedDict() <NEW_LINE> self.keras_metrics = [ 'binary_accuracy', 'categorical_accuracy', 'sparse_categorical_accuracy', 'top_k_categorical_accuracy' ] <NEW_LINE> <DEDENT> @property <NEW_LINE> def logger(self): <NEW_LINE> <INDENT> logger = logging.getLogger(__name__) <NEW_LINE> if not logger.handlers: <NEW_LINE> <INDENT> setup_logging() <NEW_LINE> <DEDENT> return logger <NEW_LINE> <DEDENT> def set_model(self, model): <NEW_LINE> <INDENT> self.model = model <NEW_LINE> <DEDENT> def set_params(self, params): <NEW_LINE> <INDENT> self.params = params <NEW_LINE> <DEDENT> def on_train_begin(self, logs=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_train_end(self, logs=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_epoch_begin(self, epoch, logs=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_epoch_end(self, epoch, logs=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_test_begin(self, logs=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_test_end(self, logs=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_predict_begin(self, logs=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_predict_end(self, logs=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_train_batch_begin(self, batch, logs=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_train_batch_end(self, batch, logs=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_test_batch_begin(self, batch, logs=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_test_batch_end(self, batch, logs=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_predict_batch_begin(self, batch, logs=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_predict_batch_end(self, batch, logs=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def add_external_metric(self, metric_label): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def set_external_metric_value(self, metric_label, metric_value): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_operator(self, metric): <NEW_LINE> <INDENT> metric = metric.lower() <NEW_LINE> if metric.endswith('error_rate') or metric.endswith('er'): <NEW_LINE> <INDENT> return numpy.less <NEW_LINE> <DEDENT> elif (metric.endswith('f_measure') or metric.endswith('fmeasure') or metric.endswith('fscore') or metric.endswith('f-score')): <NEW_LINE> <INDENT> return numpy.greater <NEW_LINE> <DEDENT> elif metric.endswith('accuracy') or metric.endswith('acc'): <NEW_LINE> <INDENT> return numpy.greater <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return numpy.less <NEW_LINE> <DEDENT> <DEDENT> def _implements_train_batch_hooks(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def _implements_test_batch_hooks(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def _implements_predict_batch_hooks(self): <NEW_LINE> <INDENT> return False
Base class for Callbacks
6259906b3346ee7daa338263
class TestDataInputsTinyResponse(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def make_instance(self, include_optional): <NEW_LINE> <INDENT> if include_optional : <NEW_LINE> <INDENT> return DataInputsTinyResponse( data = [ samsara.models.data_input_tiny_response.DataInputTinyResponse( asset_id = '74771078-5edb-4733-88f2-7242f520d1f1', data_group = 'Flow', id = '0', name = 'Pump Flow', units = 'Gallons Per Minute', ) ], pagination = samsara.models.pagination_response.paginationResponse( end_cursor = 'MjkY', has_next_page = True, ) ) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return DataInputsTinyResponse( ) <NEW_LINE> <DEDENT> <DEDENT> def testDataInputsTinyResponse(self): <NEW_LINE> <INDENT> inst_req_only = self.make_instance(include_optional=False) <NEW_LINE> inst_req_and_optional = self.make_instance(include_optional=True)
DataInputsTinyResponse unit test stubs
6259906b4f6381625f19a0ac
class Preprocessing(luigi.Task): <NEW_LINE> <INDENT> def requires(self): <NEW_LINE> <INDENT> return [CreateTransactionTable(), ExportMySQLToHive(source_table='products', destination='/input/products/products', schema="DROP TABLE IF EXISTS products; " "CREATE EXTERNAL TABLE products " "(id INT, name STRING, category STRING, price DOUBLE) " "ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t' " "LOCATION '/input/products';")] <NEW_LINE> <DEDENT> def complete(self): <NEW_LINE> <INDENT> return custom_table_exists('products') and custom_table_exists('transactions')
Defines all preprocessing dependencies of the data flow.
6259906b2ae34c7f260ac8f2
class TaskLayout(HasStrictTraits): <NEW_LINE> <INDENT> left_panes = NestedListStr <NEW_LINE> right_panes = NestedListStr <NEW_LINE> bottom_panes = NestedListStr <NEW_LINE> top_panes = NestedListStr <NEW_LINE> toolkit_state = Any
A picklable object that describes the layout of a Task's dock panes.
6259906baad79263cf42ffc0
class FileDetailed(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.swagger_types = { 'detail_type': 'str', 'store_name': 'str', 'uid': 'int', 'name': 'str', 'link': 'str', 'store_data': 'object' } <NEW_LINE> self.attribute_map = { 'detail_type': 'detail_type', 'store_name': 'store_name', 'uid': 'uid', 'name': 'name', 'link': 'link', 'store_data': 'store_data' } <NEW_LINE> self._detail_type = None <NEW_LINE> self._store_name = None <NEW_LINE> self._uid = None <NEW_LINE> self._name = None <NEW_LINE> self._link = None <NEW_LINE> self._store_data = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def detail_type(self): <NEW_LINE> <INDENT> return self._detail_type <NEW_LINE> <DEDENT> @detail_type.setter <NEW_LINE> def detail_type(self, detail_type): <NEW_LINE> <INDENT> self._detail_type = detail_type <NEW_LINE> <DEDENT> @property <NEW_LINE> def store_name(self): <NEW_LINE> <INDENT> return self._store_name <NEW_LINE> <DEDENT> @store_name.setter <NEW_LINE> def store_name(self, store_name): <NEW_LINE> <INDENT> self._store_name = store_name <NEW_LINE> <DEDENT> @property <NEW_LINE> def uid(self): <NEW_LINE> <INDENT> return self._uid <NEW_LINE> <DEDENT> @uid.setter <NEW_LINE> def uid(self, uid): <NEW_LINE> <INDENT> self._uid = uid <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> @property <NEW_LINE> def link(self): <NEW_LINE> <INDENT> return self._link <NEW_LINE> <DEDENT> @link.setter <NEW_LINE> def link(self, link): <NEW_LINE> <INDENT> self._link = link <NEW_LINE> <DEDENT> @property <NEW_LINE> def store_data(self): <NEW_LINE> <INDENT> return self._store_data <NEW_LINE> <DEDENT> @store_data.setter <NEW_LINE> def store_data(self, store_data): <NEW_LINE> <INDENT> self._store_data = store_data <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
6259906ba8370b77170f1bd0
class ErrorSet: <NEW_LINE> <INDENT> def __init__(self, error_set, after=True): <NEW_LINE> <INDENT> self.data = np.array(list(error_set)) <NEW_LINE> if after: <NEW_LINE> <INDENT> self.error_func = self.error_func_after <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.error_func = self.error_func_before <NEW_LINE> <DEDENT> <DEDENT> def error_func_after(self, after, before, replace, location, error_params): <NEW_LINE> <INDENT> after.update(np.random.choice(self.data), {location}, emptyappend=True) <NEW_LINE> <DEDENT> def error_func_before(self, after, before, replace, location, error_params): <NEW_LINE> <INDENT> before.update(np.random.choice(self.data), {location}, emptyappend=True)
Class used to create a callable that returns an element from the error_set with uniform distribution.
6259906b8e71fb1e983bd2d2
class ParamMixin(object): <NEW_LINE> <INDENT> def build_param_gui(self, container): <NEW_LINE> <INDENT> captions = (('Load Param', 'button', 'Save Param', 'button'), ) <NEW_LINE> w, b = Widgets.build_info(captions, orientation=self.orientation) <NEW_LINE> self.w.update(b) <NEW_LINE> b.load_param.set_tooltip('Load previously saved parameters') <NEW_LINE> b.load_param.add_callback( 'activated', lambda w: self.load_params_cb()) <NEW_LINE> b.save_param.set_tooltip(f'Save {str(self)} parameters') <NEW_LINE> b.save_param.add_callback( 'activated', lambda w: self.save_params()) <NEW_LINE> container.add_widget(w, stretch=0) <NEW_LINE> self.filesel = FileSelection(self.fv.w.root.get_widget()) <NEW_LINE> <DEDENT> def params_dict(self): <NEW_LINE> <INDENT> raise NotImplementedError('To be implemented by Ginga local plugin') <NEW_LINE> <DEDENT> def save_params(self): <NEW_LINE> <INDENT> pardict = self.params_dict() <NEW_LINE> fname = Widgets.SaveDialog( title='Save parameters', selectedfilter='*.json').get_path() <NEW_LINE> if fname is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if os.path.exists(fname): <NEW_LINE> <INDENT> self.logger.warn(f'{fname} will be overwritten') <NEW_LINE> <DEDENT> with open(fname, 'w') as fout: <NEW_LINE> <INDENT> json.dump(pardict, fout, indent=4, sort_keys=True, cls=JsonCustomEncoder) <NEW_LINE> <DEDENT> self.logger.info(f'Parameters saved as {fname}') <NEW_LINE> <DEDENT> def load_params_cb(self): <NEW_LINE> <INDENT> self.filesel.popup('Load JSON file', self.load_params, initialdir='.', filename='JSON files (*.json)') <NEW_LINE> <DEDENT> def load_params(self, filename): <NEW_LINE> <INDENT> if not os.path.isfile(filename): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> with open(filename) as fin: <NEW_LINE> <INDENT> self.logger.info(f'{str(self)} parameters loaded from {filename}') <NEW_LINE> pardict = json.load(fin) <NEW_LINE> <DEDENT> self.ingest_params(pardict) <NEW_LINE> <DEDENT> def ingest_params(self, pardict): <NEW_LINE> <INDENT> raise NotImplementedError('To be implemented by Ginga local plugin')
Mixin class for Ginga local plugin that enables the feature to save/load parameters.
6259906bd6c5a102081e3934
class NasPathBlock(HybridBlock): <NEW_LINE> <INDENT> def __init__(self, in_channels, out_channels, **kwargs): <NEW_LINE> <INDENT> super(NasPathBlock, self).__init__(**kwargs) <NEW_LINE> mid_channels = out_channels // 2 <NEW_LINE> with self.name_scope(): <NEW_LINE> <INDENT> self.activ = nn.Activation('relu') <NEW_LINE> self.path1 = NasPathBranch( in_channels=in_channels, out_channels=mid_channels) <NEW_LINE> self.path2 = NasPathBranch( in_channels=in_channels, out_channels=mid_channels, specific=True) <NEW_LINE> self.bn = nasnet_batch_norm(channels=out_channels) <NEW_LINE> <DEDENT> <DEDENT> def hybrid_forward(self, F, x): <NEW_LINE> <INDENT> x = self.activ(x) <NEW_LINE> x1 = self.path1(x) <NEW_LINE> x2 = self.path2(x) <NEW_LINE> x = F.concat(x1, x2, dim=1) <NEW_LINE> x = self.bn(x) <NEW_LINE> return x
NASNet specific `path` block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels.
6259906b8da39b475be049f6
class ConnectToMongoDbTaskProperties(ProjectTaskProperties): <NEW_LINE> <INDENT> _validation = { 'task_type': {'required': True}, 'errors': {'readonly': True}, 'state': {'readonly': True}, 'commands': {'readonly': True}, 'output': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'task_type': {'key': 'taskType', 'type': 'str'}, 'errors': {'key': 'errors', 'type': '[ODataError]'}, 'state': {'key': 'state', 'type': 'str'}, 'commands': {'key': 'commands', 'type': '[CommandProperties]'}, 'client_data': {'key': 'clientData', 'type': '{str}'}, 'input': {'key': 'input', 'type': 'MongoDbConnectionInfo'}, 'output': {'key': 'output', 'type': '[MongoDbClusterInfo]'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(ConnectToMongoDbTaskProperties, self).__init__(**kwargs) <NEW_LINE> self.task_type = 'Connect.MongoDb' <NEW_LINE> self.input = kwargs.get('input', None) <NEW_LINE> self.output = None
Properties for the task that validates the connection to and provides information about a MongoDB server. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param task_type: Required. Task type.Constant filled by server. :type task_type: str :ivar errors: Array of errors. This is ignored if submitted. :vartype errors: list[~azure.mgmt.datamigration.models.ODataError] :ivar state: The state of the task. This is ignored if submitted. Possible values include: "Unknown", "Queued", "Running", "Canceled", "Succeeded", "Failed", "FailedInputValidation", "Faulted". :vartype state: str or ~azure.mgmt.datamigration.models.TaskState :ivar commands: Array of command properties. :vartype commands: list[~azure.mgmt.datamigration.models.CommandProperties] :param client_data: Key value pairs of client data to attach meta data information to task. :type client_data: dict[str, str] :param input: Describes a connection to a MongoDB data source. :type input: ~azure.mgmt.datamigration.models.MongoDbConnectionInfo :ivar output: An array containing a single MongoDbClusterInfo object. :vartype output: list[~azure.mgmt.datamigration.models.MongoDbClusterInfo]
6259906b2ae34c7f260ac8f3
class ActivatedMixin(models.Model): <NEW_LINE> <INDENT> objects = GenericManager() <NEW_LINE> actives = GenericActiveManager() <NEW_LINE> activated = models.BooleanField(_('Activated'), default=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> <DEDENT> def delete(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> super(ActivatedMixin, self).delete() <NEW_LINE> <DEDENT> except models.deletion.ProtectedError: <NEW_LINE> <INDENT> self.activated = False <NEW_LINE> self.save()
Mixin class providing activated fields to any model
6259906b379a373c97d9a82a
class RuntimeException(Exception): <NEW_LINE> <INDENT> pass
Base class for all exceptions used by the device runtime. Those exceptions are defined in ``artiq.coredevice.runtime_exceptions``.
6259906bd486a94d0ba2d7ca
class SLSPQdriverTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.top = set_as_top(Assembly()) <NEW_LINE> self.top.add('driver', SLSQPdriver()) <NEW_LINE> self.top.add('comp', OptRosenSuzukiComponent()) <NEW_LINE> self.top.driver.workflow.add('comp') <NEW_LINE> self.top.driver.iprint = 0 <NEW_LINE> self.top.driver.differentiator = FiniteDifference() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.top = None <NEW_LINE> <DEDENT> def test_opt1(self): <NEW_LINE> <INDENT> self.top.driver.add_objective('comp.result') <NEW_LINE> map(self.top.driver.add_parameter, ['comp.x[0]', 'comp.x[1]','comp.x[2]', 'comp.x[3]']) <NEW_LINE> map(self.top.driver.add_constraint,[ 'comp.x[0]**2+comp.x[0]+comp.x[1]**2-comp.x[1]+comp.x[2]**2+comp.x[2]+comp.x[3]**2-comp.x[3] < 8', 'comp.x[0]**2-comp.x[0]+2*comp.x[1]**2+comp.x[2]**2+2*comp.x[3]**2-comp.x[3] < 10', '2*comp.x[0]**2+2*comp.x[0]+comp.x[1]**2-comp.x[1]+comp.x[2]**2-comp.x[3] < 5']) <NEW_LINE> self.top.driver.recorders = [ListCaseRecorder()] <NEW_LINE> self.top.driver.printvars = ['comp.opt_objective'] <NEW_LINE> self.top.run() <NEW_LINE> self.assertAlmostEqual(self.top.comp.opt_objective, self.top.driver.eval_objective(), places=2) <NEW_LINE> self.assertAlmostEqual(self.top.comp.opt_design_vars[0], self.top.comp.x[0], places=1) <NEW_LINE> self.assertAlmostEqual(self.top.comp.opt_design_vars[1], self.top.comp.x[1], places=2) <NEW_LINE> self.assertAlmostEqual(self.top.comp.opt_design_vars[2], self.top.comp.x[2], places=2) <NEW_LINE> self.assertAlmostEqual(self.top.comp.opt_design_vars[3], self.top.comp.x[3], places=1) <NEW_LINE> cases = self.top.driver.recorders[0].get_iterator() <NEW_LINE> end_case = cases[-1] <NEW_LINE> self.assertEqual(self.top.comp.x[1], end_case.get_input('comp.x[1]')) <NEW_LINE> self.assertEqual(self.top.comp.opt_objective, end_case.get_output('comp.opt_objective')) <NEW_LINE> <DEDENT> def test_max_iter(self): <NEW_LINE> <INDENT> self.top.driver.add_objective('comp.result') <NEW_LINE> map(self.top.driver.add_parameter, ['comp.x[0]', 'comp.x[1]','comp.x[2]', 'comp.x[3]']) <NEW_LINE> self.top.driver.maxiter = 2 <NEW_LINE> self.top.run() <NEW_LINE> self.assertEqual(self.top.driver.error_code, 9)
test SLSQP optimizer component
6259906bdd821e528d6da586