prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>simple.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import from itertools import cycle import logging import random import six from six.moves import xrange from .base import Producer log = logging.getLogger(__name__) class SimpleProducer(Producer): """A simple, round-robin producer. See Producer class for Base Arguments Additional Arguments: random_start (bool, optional): randomize the initial partition which the first message block will be published to, otherwise if false, the first message block will always publish to partition 0 before cycling through each partition, defaults to True.<|fim▁hole|> """ def __init__(self, *args, **kwargs): self.partition_cycles = {} self.random_start = kwargs.pop('random_start', True) super(SimpleProducer, self).__init__(*args, **kwargs) def _next_partition(self, topic): if topic not in self.partition_cycles: if not self.client.has_metadata_for_topic(topic): self.client.load_metadata_for_topics(topic) self.partition_cycles[topic] = cycle(self.client.get_partition_ids_for_topic(topic)) # Randomize the initial partition that is returned if self.random_start: num_partitions = len(self.client.get_partition_ids_for_topic(topic)) for _ in xrange(random.randint(0, num_partitions-1)): next(self.partition_cycles[topic]) return next(self.partition_cycles[topic]) def send_messages(self, topic, *msg): if not isinstance(topic, six.binary_type): topic = topic.encode('utf-8') partition = self._next_partition(topic) return super(SimpleProducer, self).send_messages( topic, partition, *msg ) def __repr__(self): return '<SimpleProducer batch=%s>' % self.async<|fim▁end|>
<|file_name|>border.mako.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% from data import to_rust_ident, ALL_SIDES, PHYSICAL_SIDES, maybe_moz_logical_alias %> ${helpers.four_sides_shorthand("border-color", "border-%s-color", "specified::Color::parse", spec="https://drafts.csswg.org/css-backgrounds/#border-color", allow_quirks=True)} ${helpers.four_sides_shorthand("border-style", "border-%s-style", "specified::BorderStyle::parse", spec="https://drafts.csswg.org/css-backgrounds/#border-style")} <%helpers:shorthand name="border-width" sub_properties="${ ' '.join('border-%s-width' % side for side in PHYSICAL_SIDES)}" spec="https://drafts.csswg.org/css-backgrounds/#border-width"> use values::generics::rect::Rect; use values::specified::{AllowQuirks, BorderSideWidth}; pub fn parse_value<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Longhands, ParseError<'i>> { let rect = Rect::parse_with(context, input, |_, i| { BorderSideWidth::parse_quirky(context, i, AllowQuirks::Yes) })?; Ok(expanded! { border_top_width: rect.0, border_right_width: rect.1, border_bottom_width: rect.2, border_left_width: rect.3, }) } impl<'a> ToCss for LonghandsToSerialize<'a> { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { % for side in PHYSICAL_SIDES: let ${side} = &self.border_${side}_width; % endfor Rect::new(top, right, bottom, left).to_css(dest) } } </%helpers:shorthand> pub fn parse_border<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<(specified::Color, specified::BorderStyle, specified::BorderSideWidth), ParseError<'i>> { use values::specified::{Color, BorderStyle, BorderSideWidth}; let _unused = context; let mut color = None; let mut style = None; let mut width = None; let mut any = false; loop { if color.is_none() { if let Ok(value) = input.try(|i| Color::parse(context, i)) { color = Some(value); any = true; continue } } if style.is_none() { if let Ok(value) = input.try(|i| BorderStyle::parse(context, i)) { style = Some(value); any = true; continue } } if width.is_none() { if let Ok(value) = input.try(|i| BorderSideWidth::parse(context, i)) { width = Some(value); any = true; continue } } break } if any { Ok((color.unwrap_or_else(|| Color::currentcolor()), style.unwrap_or(BorderStyle::None),<|fim▁hole|> width.unwrap_or(BorderSideWidth::Medium))) } else { Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)) } } % for side, logical in ALL_SIDES: <% spec = "https://drafts.csswg.org/css-backgrounds/#border-%s" % side if logical: spec = "https://drafts.csswg.org/css-logical-props/#propdef-border-%s" % side %> <%helpers:shorthand name="border-${side}" sub_properties="${' '.join( 'border-%s-%s' % (side, prop) for prop in ['color', 'style', 'width'] )}" alias="${maybe_moz_logical_alias(product, (side, logical), '-moz-border-%s')}" spec="${spec}"> pub fn parse_value<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Longhands, ParseError<'i>> { let (color, style, width) = super::parse_border(context, input)?; Ok(expanded! { border_${to_rust_ident(side)}_color: color, border_${to_rust_ident(side)}_style: style, border_${to_rust_ident(side)}_width: width }) } impl<'a> ToCss for LonghandsToSerialize<'a> { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { super::serialize_directional_border( dest, self.border_${to_rust_ident(side)}_width, self.border_${to_rust_ident(side)}_style, self.border_${to_rust_ident(side)}_color ) } } </%helpers:shorthand> % endfor <%helpers:shorthand name="border" sub_properties="${' '.join('border-%s-%s' % (side, prop) for side in PHYSICAL_SIDES for prop in ['color', 'style', 'width'])} ${' '.join('border-image-%s' % name for name in ['outset', 'repeat', 'slice', 'source', 'width'])}" spec="https://drafts.csswg.org/css-backgrounds/#border"> pub fn parse_value<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Longhands, ParseError<'i>> { use properties::longhands::{border_image_outset, border_image_repeat, border_image_slice}; use properties::longhands::{border_image_source, border_image_width}; let (color, style, width) = super::parse_border(context, input)?; Ok(expanded! { % for side in PHYSICAL_SIDES: border_${side}_color: color.clone(), border_${side}_style: style, border_${side}_width: width.clone(), % endfor // The ‘border’ shorthand resets ‘border-image’ to its initial value. // See https://drafts.csswg.org/css-backgrounds-3/#the-border-shorthands % for name in "outset repeat slice source width".split(): border_image_${name}: border_image_${name}::get_initial_specified_value(), % endfor }) } impl<'a> ToCss for LonghandsToSerialize<'a> { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let all_equal = { % for side in PHYSICAL_SIDES: let border_${side}_width = self.border_${side}_width; let border_${side}_style = self.border_${side}_style; let border_${side}_color = self.border_${side}_color; % endfor border_top_width == border_right_width && border_right_width == border_bottom_width && border_bottom_width == border_left_width && border_top_style == border_right_style && border_right_style == border_bottom_style && border_bottom_style == border_left_style && border_top_color == border_right_color && border_right_color == border_bottom_color && border_bottom_color == border_left_color }; // If all longhands are all present, then all sides should be the same, // so we can just one set of color/style/width if all_equal { super::serialize_directional_border( dest, self.border_${side}_width, self.border_${side}_style, self.border_${side}_color ) } else { Ok(()) } } } </%helpers:shorthand> <%helpers:shorthand name="border-radius" sub_properties="${' '.join( 'border-%s-radius' % (corner) for corner in ['top-left', 'top-right', 'bottom-right', 'bottom-left'] )}" extra_prefixes="webkit" spec="https://drafts.csswg.org/css-backgrounds/#border-radius"> use values::generics::rect::Rect; use values::generics::border::BorderCornerRadius; use values::specified::border::BorderRadius; use parser::Parse; pub fn parse_value<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Longhands, ParseError<'i>> { let radii = BorderRadius::parse(context, input)?; Ok(expanded! { border_top_left_radius: radii.top_left, border_top_right_radius: radii.top_right, border_bottom_right_radius: radii.bottom_right, border_bottom_left_radius: radii.bottom_left, }) } impl<'a> ToCss for LonghandsToSerialize<'a> { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let LonghandsToSerialize { border_top_left_radius: &BorderCornerRadius(ref tl), border_top_right_radius: &BorderCornerRadius(ref tr), border_bottom_right_radius: &BorderCornerRadius(ref br), border_bottom_left_radius: &BorderCornerRadius(ref bl), } = *self; let widths = Rect::new(tl.width(), tr.width(), br.width(), bl.width()); let heights = Rect::new(tl.height(), tr.height(), br.height(), bl.height()); BorderRadius::serialize_rects(widths, heights, dest) } } </%helpers:shorthand> <%helpers:shorthand name="border-image" sub_properties="border-image-outset border-image-repeat border-image-slice border-image-source border-image-width" extra_prefixes="moz webkit" spec="https://drafts.csswg.org/css-backgrounds-3/#border-image"> use properties::longhands::{border_image_outset, border_image_repeat, border_image_slice}; use properties::longhands::{border_image_source, border_image_width}; pub fn parse_value<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Longhands, ParseError<'i>> { % for name in "outset repeat slice source width".split(): let mut border_image_${name} = border_image_${name}::get_initial_specified_value(); % endfor let result: Result<_, ParseError> = input.try(|input| { % for name in "outset repeat slice source width".split(): let mut ${name} = None; % endfor loop { if slice.is_none() { if let Ok(value) = input.try(|input| border_image_slice::parse(context, input)) { slice = Some(value); // Parse border image width and outset, if applicable. let maybe_width_outset: Result<_, ParseError> = input.try(|input| { input.expect_delim('/')?; // Parse border image width, if applicable. let w = input.try(|input| border_image_width::parse(context, input)).ok(); // Parse border image outset if applicable. let o = input.try(|input| { input.expect_delim('/')?; border_image_outset::parse(context, input) }).ok(); if w.is_none() && o.is_none() { Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)) } else { Ok((w, o)) } }); if let Ok((w, o)) = maybe_width_outset { width = w; outset = o; } continue } } % for name in "source repeat".split(): if ${name}.is_none() { if let Ok(value) = input.try(|input| border_image_${name}::parse(context, input)) { ${name} = Some(value); continue } } % endfor break } let mut any = false; % for name in "outset repeat slice source width".split(): any = any || ${name}.is_some(); % endfor if any { % for name in "outset repeat slice source width".split(): if let Some(b_${name}) = ${name} { border_image_${name} = b_${name}; } % endfor Ok(()) } else { Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)) } }); result?; Ok(expanded! { % for name in "outset repeat slice source width".split(): border_image_${name}: border_image_${name}, % endfor }) } impl<'a> ToCss for LonghandsToSerialize<'a> { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { self.border_image_source.to_css(dest)?; dest.write_str(" ")?; self.border_image_slice.to_css(dest)?; dest.write_str(" / ")?; self.border_image_width.to_css(dest)?; dest.write_str(" / ")?; self.border_image_outset.to_css(dest)?; dest.write_str(" ")?; self.border_image_repeat.to_css(dest) } } </%helpers:shorthand><|fim▁end|>
<|file_name|>dstr-let-obj-ptrn-id-init-unresolvable.js<|end_file_name|><|fim▁begin|>// This file was procedurally generated from the following sources: // - src/dstr-binding/obj-ptrn-id-init-unresolvable.case // - src/dstr-binding/error/for-of-let.template /*--- description: Destructuring initializer is an unresolvable reference (for-of statement) esid: sec-for-in-and-for-of-statements-runtime-semantics-labelledevaluation es6id: 13.7.5.11 features: [destructuring-binding] flags: [generated] info: | IterationStatement : for ( ForDeclaration of AssignmentExpression ) Statement [...] 3. Return ForIn/OfBodyEvaluation(ForDeclaration, Statement, keyResult, lexicalBinding, labelSet). 13.7.5.13 Runtime Semantics: ForIn/OfBodyEvaluation [...]<|fim▁hole|> [...] 5. Repeat [...] h. If destructuring is false, then [...] i. Else i. If lhsKind is assignment, then [...] ii. Else if lhsKind is varBinding, then [...] iii. Else, 1. Assert: lhsKind is lexicalBinding. 2. Assert: lhs is a ForDeclaration. 3. Let status be the result of performing BindingInitialization for lhs passing nextValue and iterationEnv as arguments. [...] 13.3.3.7 Runtime Semantics: KeyedBindingInitialization SingleNameBinding : BindingIdentifier Initializeropt [...] 6. If Initializer is present and v is undefined, then a. Let defaultValue be the result of evaluating Initializer. b. Let v be GetValue(defaultValue). c. ReturnIfAbrupt(v). 6.2.3.1 GetValue (V) 1. ReturnIfAbrupt(V). 2. If Type(V) is not Reference, return V. 3. Let base be GetBase(V). 4. If IsUnresolvableReference(V), throw a ReferenceError exception. ---*/ assert.throws(ReferenceError, function() { for (let { x = unresolvableReference } of [{}]) { return; } });<|fim▁end|>
3. Let destructuring be IsDestructuring of lhs.
<|file_name|>cnn.py<|end_file_name|><|fim▁begin|>import numpy as np import torch from torch import nn as nn from rlkit.policies.base import Policy from rlkit.pythonplusplus import identity from rlkit.torch.core import PyTorchModule, eval_np from rlkit.torch.data_management.normalizer import TorchFixedNormalizer from rlkit.torch.pytorch_util import activation_from_string class CNN(PyTorchModule): # TODO: remove the FC parts of this code def __init__( self, input_width, input_height, input_channels, output_size, kernel_sizes, n_channels, strides, paddings, hidden_sizes=None, added_fc_input_size=0, conv_normalization_type='none', fc_normalization_type='none', init_w=1e-4, hidden_init=nn.init.xavier_uniform_, hidden_activation=nn.ReLU(), output_activation=identity, output_conv_channels=False, pool_type='none', pool_sizes=None, pool_strides=None, pool_paddings=None, ): if hidden_sizes is None: hidden_sizes = [] assert len(kernel_sizes) == \ len(n_channels) == \ len(strides) == \ len(paddings) assert conv_normalization_type in {'none', 'batch', 'layer'} assert fc_normalization_type in {'none', 'batch', 'layer'} assert pool_type in {'none', 'max2d'} if pool_type == 'max2d': assert len(pool_sizes) == len(pool_strides) == len(pool_paddings) super().__init__() self.hidden_sizes = hidden_sizes self.input_width = input_width self.input_height = input_height self.input_channels = input_channels self.output_size = output_size self.output_activation = output_activation self.hidden_activation = hidden_activation self.conv_normalization_type = conv_normalization_type self.fc_normalization_type = fc_normalization_type self.added_fc_input_size = added_fc_input_size self.conv_input_length = self.input_width * self.input_height * self.input_channels self.output_conv_channels = output_conv_channels self.pool_type = pool_type self.conv_layers = nn.ModuleList() self.conv_norm_layers = nn.ModuleList() self.pool_layers = nn.ModuleList()<|fim▁hole|> self.fc_norm_layers = nn.ModuleList() for i, (out_channels, kernel_size, stride, padding) in enumerate( zip(n_channels, kernel_sizes, strides, paddings) ): conv = nn.Conv2d(input_channels, out_channels, kernel_size, stride=stride, padding=padding) hidden_init(conv.weight) conv.bias.data.fill_(0) conv_layer = conv self.conv_layers.append(conv_layer) input_channels = out_channels if pool_type == 'max2d': self.pool_layers.append( nn.MaxPool2d( kernel_size=pool_sizes[i], stride=pool_strides[i], padding=pool_paddings[i], ) ) # use torch rather than ptu because initially the model is on CPU test_mat = torch.zeros( 1, self.input_channels, self.input_width, self.input_height, ) # find output dim of conv_layers by trial and add norm conv layers for i, conv_layer in enumerate(self.conv_layers): test_mat = conv_layer(test_mat) if self.conv_normalization_type == 'batch': self.conv_norm_layers.append(nn.BatchNorm2d(test_mat.shape[1])) if self.conv_normalization_type == 'layer': self.conv_norm_layers.append(nn.LayerNorm(test_mat.shape[1:])) if self.pool_type != 'none': test_mat = self.pool_layers[i](test_mat) self.conv_output_flat_size = int(np.prod(test_mat.shape)) if self.output_conv_channels: self.last_fc = None else: fc_input_size = self.conv_output_flat_size # used only for injecting input directly into fc layers fc_input_size += added_fc_input_size for idx, hidden_size in enumerate(hidden_sizes): fc_layer = nn.Linear(fc_input_size, hidden_size) fc_input_size = hidden_size fc_layer.weight.data.uniform_(-init_w, init_w) fc_layer.bias.data.uniform_(-init_w, init_w) self.fc_layers.append(fc_layer) if self.fc_normalization_type == 'batch': self.fc_norm_layers.append(nn.BatchNorm1d(hidden_size)) if self.fc_normalization_type == 'layer': self.fc_norm_layers.append(nn.LayerNorm(hidden_size)) self.last_fc = nn.Linear(fc_input_size, output_size) self.last_fc.weight.data.uniform_(-init_w, init_w) self.last_fc.bias.data.uniform_(-init_w, init_w) def forward(self, input, return_last_activations=False): conv_input = input.narrow(start=0, length=self.conv_input_length, dim=1).contiguous() # reshape from batch of flattened images into (channels, w, h) h = conv_input.view(conv_input.shape[0], self.input_channels, self.input_height, self.input_width) h = self.apply_forward_conv(h) if self.output_conv_channels: return h # flatten channels for fc layers h = h.view(h.size(0), -1) if self.added_fc_input_size != 0: extra_fc_input = input.narrow( start=self.conv_input_length, length=self.added_fc_input_size, dim=1, ) h = torch.cat((h, extra_fc_input), dim=1) h = self.apply_forward_fc(h) if return_last_activations: return h return self.output_activation(self.last_fc(h)) def apply_forward_conv(self, h): for i, layer in enumerate(self.conv_layers): h = layer(h) if self.conv_normalization_type != 'none': h = self.conv_norm_layers[i](h) if self.pool_type != 'none': h = self.pool_layers[i](h) h = self.hidden_activation(h) return h def apply_forward_fc(self, h): for i, layer in enumerate(self.fc_layers): h = layer(h) if self.fc_normalization_type != 'none': h = self.fc_norm_layers[i](h) h = self.hidden_activation(h) return h class ConcatCNN(CNN): """ Concatenate inputs along dimension and then pass through MLP. """ def __init__(self, *args, dim=1, **kwargs): super().__init__(*args, **kwargs) self.dim = dim def forward(self, *inputs, **kwargs): flat_inputs = torch.cat(inputs, dim=self.dim) return super().forward(flat_inputs, **kwargs) class MergedCNN(CNN): ''' CNN that supports input directly into fully connected layers ''' def __init__(self, added_fc_input_size, **kwargs ): super().__init__(added_fc_input_size=added_fc_input_size, **kwargs) def forward(self, conv_input, fc_input): h = torch.cat((conv_input, fc_input), dim=1) output = super().forward(h) return output class CNNPolicy(CNN, Policy): """ A simpler interface for creating policies. """ def __init__( self, *args, obs_normalizer: TorchFixedNormalizer = None, **kwargs ): super().__init__(*args, **kwargs) self.obs_normalizer = obs_normalizer def forward(self, obs, **kwargs): if self.obs_normalizer: obs = self.obs_normalizer.normalize(obs) return super().forward(obs, **kwargs) def get_action(self, obs_np): actions = self.get_actions(obs_np[None]) return actions[0, :], {} def get_actions(self, obs): return eval_np(self, obs) class BasicCNN(PyTorchModule): # TODO: clean up CNN using this basic CNN def __init__( self, input_width, input_height, input_channels, kernel_sizes, n_channels, strides, paddings, normalization_type='none', hidden_init=None, hidden_activation='relu', output_activation=identity, pool_type='none', pool_sizes=None, pool_strides=None, pool_paddings=None, ): assert len(kernel_sizes) == \ len(n_channels) == \ len(strides) == \ len(paddings) assert normalization_type in {'none', 'batch', 'layer'} assert pool_type in {'none', 'max2d'} if pool_type == 'max2d': assert len(pool_sizes) == len(pool_strides) == len(pool_paddings) super().__init__() self.input_width = input_width self.input_height = input_height self.input_channels = input_channels self.output_activation = output_activation if isinstance(hidden_activation, str): hidden_activation = activation_from_string(hidden_activation) self.hidden_activation = hidden_activation self.normalization_type = normalization_type self.conv_input_length = self.input_width * self.input_height * self.input_channels self.pool_type = pool_type self.conv_layers = nn.ModuleList() self.conv_norm_layers = nn.ModuleList() self.pool_layers = nn.ModuleList() for i, (out_channels, kernel_size, stride, padding) in enumerate( zip(n_channels, kernel_sizes, strides, paddings) ): conv = nn.Conv2d(input_channels, out_channels, kernel_size, stride=stride, padding=padding) if hidden_init: hidden_init(conv.weight) conv_layer = conv self.conv_layers.append(conv_layer) input_channels = out_channels if pool_type == 'max2d': if pool_sizes[i] > 1: self.pool_layers.append( nn.MaxPool2d( kernel_size=pool_sizes[i], stride=pool_strides[i], padding=pool_paddings[i], ) ) else: self.pool_layers.append(None) # use torch rather than ptu because initially the model is on CPU test_mat = torch.zeros( 1, self.input_channels, self.input_height, self.input_width, ) # find output dim of conv_layers by trial and add norm conv layers for i, conv_layer in enumerate(self.conv_layers): test_mat = conv_layer(test_mat) if self.normalization_type == 'batch': self.conv_norm_layers.append(nn.BatchNorm2d(test_mat.shape[1])) if self.normalization_type == 'layer': self.conv_norm_layers.append(nn.LayerNorm(test_mat.shape[1:])) if self.pool_type != 'none': if self.pool_layers[i]: test_mat = self.pool_layers[i](test_mat) self.output_shape = test_mat.shape[1:] # ignore batch dim def forward(self, conv_input): return self.apply_forward_conv(conv_input) def apply_forward_conv(self, h): for i, layer in enumerate(self.conv_layers): h = layer(h) if self.normalization_type != 'none': h = self.conv_norm_layers[i](h) if self.pool_type != 'none': if self.pool_layers[i]: h = self.pool_layers[i](h) h = self.hidden_activation(h) return h<|fim▁end|>
self.fc_layers = nn.ModuleList()
<|file_name|>observation_verifier_test.py<|end_file_name|><|fim▁begin|># Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # pylint: disable=missing-docstring # pylint: disable=invalid-name import unittest from citest.base import ( ExecutionContext, JsonSnapshotHelper) import citest.json_contract as jc import citest.json_predicate as jp _called_verifiers = [] _TEST_FOUND_ERROR_COMMENT='Found error.' <|fim▁hole|>class TestObsoleteObservationFailureVerifier(jc.ObservationFailureVerifier): def __init__(self, title, expect): super(TestObsoleteObservationFailureVerifier, self).__init__(title) self.__expect = expect def _error_comment_or_none(self, error): if error.args[0] == self.__expect: return _TEST_FOUND_ERROR_COMMENT return None def _makeObservationVerifyResult( valid, observation=None, good_results=None, bad_results=None, failed_constraints=None): default_result = jp.PredicateResult(valid=valid) good_results = good_results or ([default_result] if valid else []) bad_results = bad_results or ([] if valid else [default_result]) failed_constraints = failed_constraints or [] observation = observation or jc.Observation() good_attempt_results = [jp.ObjectResultMapAttempt(observation, result) for result in good_results] bad_attempt_results = [jp.ObjectResultMapAttempt(observation, result) for result in bad_results] return jc.ObservationVerifyResult( valid=valid, observation=observation, good_results=good_attempt_results, bad_results=bad_attempt_results, failed_constraints=failed_constraints) class FakeObservationVerifier(jc.ObservationVerifier): def __init__(self, title, dnf_verifier, result): super(FakeObservationVerifier, self).__init__( title=title, dnf_verifiers=dnf_verifier) self.__result = result def __call__(self, context, observation): _called_verifiers.append(self) return self.__result class ObservationVerifierTest(unittest.TestCase): def assertEqual(self, expect, have, msg=''): if not msg: msg = 'EXPECTED\n{0!r}\nGOT\n{1!r}'.format(expect, have) JsonSnapshotHelper.AssertExpectedValue(expect, have, msg) def test_result_builder_add_good_result(self): context = ExecutionContext() observation = jc.Observation() observation.add_object('A') pred = jp.PathPredicate(None, jp.STR_EQ('A')) builder = jc.ObservationVerifyResultBuilder(observation) map_pred = jp.MapPredicate(pred) map_result = map_pred(context, observation.objects) builder.add_map_result(map_result) verify_results = builder.build(True) self.assertTrue(verify_results) self.assertEqual(observation, verify_results.observation) self.assertEqual([], verify_results.bad_results) self.assertEqual([], verify_results.failed_constraints) self.assertEqual(map_result.good_object_result_mappings, verify_results.good_results) def test_result_builder_add_bad_result(self): context = ExecutionContext() observation = jc.Observation() observation.add_object('A') pred = jp.PathPredicate(None, jp.STR_EQ('B')) builder = jc.ObservationVerifyResultBuilder(observation) map_pred = jp.MapPredicate(pred) map_result = map_pred(context, observation.objects) builder.add_map_result(map_result) verify_results = builder.build(False) self.assertFalse(verify_results) self.assertEqual(observation, verify_results.observation) self.assertEqual([], verify_results.good_results) self.assertEqual([pred], verify_results.failed_constraints) self.assertEqual(map_result.bad_object_result_mappings, verify_results.bad_results) def test_result_builder_add_mixed_results(self): context = ExecutionContext() observation = jc.Observation() observation.add_object('GOOD') observation.add_object('BAD') pred = jp.PathPredicate(None, jp.STR_EQ('GOOD')) builder = jc.ObservationVerifyResultBuilder(observation) map_pred = jp.MapPredicate(pred) map_result = map_pred(context, observation.objects) builder.add_map_result(map_result) verify_results = builder.build(False) self.assertFalse(verify_results) self.assertEqual(observation, verify_results.observation) self.assertEqual(map_result.good_object_result_mappings, verify_results.good_results) self.assertEqual([], verify_results.failed_constraints) self.assertEqual(map_result.bad_object_result_mappings, verify_results.bad_results) def test_result_observation_verifier_conjunction_ok(self): context = ExecutionContext() builder = jc.ObservationVerifierBuilder(title='Test') verifiers = [] pred_results = [] for i in range(3): this_result = jp.PredicateResult(True, comment='Pred {0}'.format(i)) pred_results.append(this_result) result = _makeObservationVerifyResult( valid=True, good_results=[this_result]) fake_verifier = FakeObservationVerifier( title=i, dnf_verifier=[], result=result) verifiers.append(fake_verifier) builder.AND(fake_verifier) # verify build can work multiple times self.assertEqual(builder.build(), builder.build()) verifier = builder.build() self.assertEqual([verifiers], verifier.dnf_verifiers) expect = _makeObservationVerifyResult(True, good_results=pred_results) global _called_verifiers _called_verifiers = [] got = verifier(context, jc.Observation()) self.assertEqual(expect, got) self.assertEqual(verifiers, _called_verifiers) def test_result_observation_verifier_conjunction_failure_aborts_early(self): context = ExecutionContext() builder = jc.ObservationVerifierBuilder(title='Test') verifiers = [] results = [] pred_results = [jp.PredicateResult(False, comment='Result %d' % i) for i in range(3)] for i in range(3): result = _makeObservationVerifyResult( valid=False, bad_results=[pred_results[i]]) fake_verifier = FakeObservationVerifier( title=i, dnf_verifier=[], result=result) verifiers.append(fake_verifier) results.append(result) builder.AND(fake_verifier) # verify build can work multiple times self.assertEqual(builder.build(), builder.build()) verifier = builder.build() self.assertEqual([verifiers], verifier.dnf_verifiers) expect = _makeObservationVerifyResult( False, bad_results=[pred_results[0]]) global _called_verifiers _called_verifiers = [] got = verifier(context, jc.Observation()) self.assertEqual(expect, got) self.assertEqual(verifiers[:1], _called_verifiers) def test_result_observation_verifier_disjunction_success_aborts_early(self): context = ExecutionContext() builder = jc.ObservationVerifierBuilder(title='Test') verifiers = [] results = [] pred_results = [jp.PredicateResult(False, comment='Result %d' % i) for i in range(2)] for i in range(2): result = _makeObservationVerifyResult( valid=True, good_results=[pred_results[i]]) fake_verifier = FakeObservationVerifier( title=i, dnf_verifier=[], result=result) verifiers.append(fake_verifier) results.append(result) builder.OR(fake_verifier) verifier = builder.build() self.assertEqual([verifiers[0:1], verifiers[1:2]], verifier.dnf_verifiers) expect = _makeObservationVerifyResult(True, good_results=[pred_results[0]]) global _called_verifiers _called_verifiers = [] got = verifier(context, jc.Observation()) self.assertEqual(expect, got) self.assertEqual(verifiers[:1], _called_verifiers) def test_result_observation_verifier_disjunction_failure(self): context = ExecutionContext() observation = jc.Observation() builder = jc.ObservationVerifierBuilder(title='Test') verifiers = [] results = [] pred_results = [jp.PredicateResult(False, comment='Result %d' % i) for i in range(2)] for i in range(2): result = _makeObservationVerifyResult(observation=observation, valid=False, bad_results=[pred_results[i]]) fake_verifier = FakeObservationVerifier( title=i, dnf_verifier=[], result=result) verifiers.append(fake_verifier) results.append(result) builder.OR(fake_verifier) verifier = builder.build() self.assertEqual([verifiers[0:1], verifiers[1:2]], verifier.dnf_verifiers) expect = _makeObservationVerifyResult( False, observation=observation, bad_results=pred_results) global _called_verifiers _called_verifiers = [] got = verifier(context, observation) self.assertEqual(expect, got) self.assertEqual(verifiers, _called_verifiers) def test_obsolete_observation_failure_ok(self): error_text = 'the error' context = ExecutionContext() observation = jc.Observation() error = ValueError(error_text) observation.add_error(error) failure_verifier = TestObsoleteObservationFailureVerifier( 'Test', error_text) failure_pred_result = jc.ObservationFailedError([error], valid=True) expect_failure = jc.ObservationVerifyResult( valid=True, observation=observation, good_results=[jp.ObjectResultMapAttempt(observation, failure_pred_result)], bad_results=[], failed_constraints=[], comment=_TEST_FOUND_ERROR_COMMENT) got = failure_verifier(context, observation) self.assertEqual(expect_failure, got) builder = jc.ObservationVerifierBuilder(title='Test') builder.EXPECT(failure_verifier) verifier = builder.build() expect = jc.ObservationVerifyResult( valid=True, observation=observation, good_results=expect_failure.good_results, bad_results=[], failed_constraints=[]) got = verifier(context, observation) self.assertEqual(expect, got) def test_observation_failure_ok(self): error_text = 'the error' context = ExecutionContext() observation = jc.Observation() error = ValueError(error_text) observation.add_error(error) exception_pred = jp.ExceptionMatchesPredicate( ValueError, regex=error_text) builder = jc.ObservationVerifierBuilder(title='Test') builder.EXPECT(jc.ObservationErrorPredicate(jp.LIST_MATCHES([exception_pred]))) failure_verifier = builder.build() observation_predicate_result = jc.ObservationPredicateResult( True, observation, jp.LIST_MATCHES([exception_pred]), jp.LIST_MATCHES([exception_pred])(context, [error])) expect_failure = jc.ObservationVerifyResult( True, observation, good_results=[observation_predicate_result], bad_results=[], failed_constraints=[]) got = failure_verifier(context, observation) self.assertEqual(expect_failure, got) def test_obsolete_observation_failure_not_ok(self): error_text = 'the error' context = ExecutionContext() observation = jc.Observation() error = ValueError('not the error') observation.add_error(error) failure_verifier = TestObsoleteObservationFailureVerifier( 'Test', error_text) comment = failure_verifier._error_not_found_comment(observation) failure_pred_result = jp.PredicateResult(valid=False, comment=comment) expect_failure = jc.ObservationVerifyResult( valid=False, observation=observation, bad_results=[jp.ObjectResultMapAttempt(observation, failure_pred_result)], good_results=[], failed_constraints=[], comment=comment) self.assertEqual(expect_failure, failure_verifier(context, observation)) builder = jc.ObservationVerifierBuilder(title='Test Verifier') builder.EXPECT(failure_verifier) verifier = builder.build() expect = jc.ObservationVerifyResult( valid=False, observation=observation, bad_results=expect_failure.bad_results, good_results=[], failed_constraints=[]) got = verifier(context, observation) self.assertEqual(expect, got) def test_obsolete_observation_failure_or_found(self): context = ExecutionContext() observation = jc.Observation() observation.add_error(ValueError('not the error')) failure_verifier = TestObsoleteObservationFailureVerifier( 'Verify', 'NotFound') comment = failure_verifier._error_not_found_comment(observation) failure_result = jp.PredicateResult(valid=False, comment=comment) # We've already established this result is what we expect bad_observation_result = failure_verifier(context, observation) success_pred_result = jp.PredicateResult(valid=True) good_observation_result = _makeObservationVerifyResult( valid=True, good_results=[success_pred_result], observation=observation) success_verifier = FakeObservationVerifier( 'Found', dnf_verifier=[], result=good_observation_result) builder = jc.ObservationVerifierBuilder(title='Observation Verifier') builder.EXPECT(failure_verifier).OR(success_verifier) verifier = builder.build() expect = jc.ObservationVerifyResult( valid=True, observation=observation, bad_results=bad_observation_result.bad_results, good_results=good_observation_result.good_results, failed_constraints=[]) got = verifier(context, observation) self.assertEqual(expect, got) if __name__ == '__main__': unittest.main()<|fim▁end|>
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>""" Tests for users API """ import datetime import ddt import pytz from django.conf import settings from django.template import defaultfilters from django.test import RequestFactory, override_settings from django.utils import timezone from milestones.tests.utils import MilestonesTestCaseMixin from mock import patch from lms.djangoapps.certificates.api import generate_user_certificates from lms.djangoapps.certificates.models import CertificateStatuses from lms.djangoapps.certificates.tests.factories import GeneratedCertificateFactory from course_modes.models import CourseMode from courseware.access_response import MilestoneAccessError, StartDateError, VisibilityError from lms.djangoapps.grades.tests.utils import mock_passing_grade from mobile_api.testutils import ( MobileAPITestCase, MobileAuthTestMixin, MobileAuthUserTestMixin, MobileCourseAccessTestMixin ) from openedx.core.lib.courses import course_image_url from openedx.core.lib.tests import attr from student.models import CourseEnrollment from util.milestones_helpers import set_prerequisite_courses from util.testing import UrlResetMixin from xmodule.course_module import DEFAULT_START_DATE from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory from .. import errors from .serializers import CourseEnrollmentSerializer @attr(shard=9) class TestUserDetailApi(MobileAPITestCase, MobileAuthUserTestMixin): """ Tests for /api/mobile/v0.5/users/<user_name>... """ REVERSE_INFO = {'name': 'user-detail', 'params': ['username']} def test_success(self): self.login() response = self.api_response() self.assertEqual(response.data['username'], self.user.username) self.assertEqual(response.data['email'], self.user.email) @attr(shard=9) class TestUserInfoApi(MobileAPITestCase, MobileAuthTestMixin): """ Tests for /api/mobile/v0.5/my_user_info """ def reverse_url(self, reverse_args=None, **kwargs): return '/api/mobile/v0.5/my_user_info' def test_success(self): """Verify the endpoint redirects to the user detail endpoint""" self.login() response = self.api_response(expected_response_code=302) self.assertIn(self.username, response['location']) @attr(shard=9) @ddt.ddt @override_settings(MKTG_URLS={'ROOT': 'dummy-root'}) class TestUserEnrollmentApi(UrlResetMixin, MobileAPITestCase, MobileAuthUserTestMixin, MobileCourseAccessTestMixin, MilestonesTestCaseMixin): """ Tests for /api/mobile/v0.5/users/<user_name>/course_enrollments/ """ REVERSE_INFO = {'name': 'courseenrollment-detail', 'params': ['username']} ALLOW_ACCESS_TO_UNRELEASED_COURSE = True ALLOW_ACCESS_TO_MILESTONE_COURSE = True ALLOW_ACCESS_TO_NON_VISIBLE_COURSE = True NEXT_WEEK = datetime.datetime.now(pytz.UTC) + datetime.timedelta(days=7) LAST_WEEK = datetime.datetime.now(pytz.UTC) - datetime.timedelta(days=7) ADVERTISED_START = "Spring 2016" ENABLED_SIGNALS = ['course_published'] DATES = { 'next_week': NEXT_WEEK, 'last_week': LAST_WEEK, 'default_start_date': DEFAULT_START_DATE, } @patch.dict(settings.FEATURES, {"ENABLE_DISCUSSION_SERVICE": True}) def setUp(self): super(TestUserEnrollmentApi, self).setUp() def verify_success(self, response): """ Verifies user course enrollment response for success """ super(TestUserEnrollmentApi, self).verify_success(response) courses = response.data self.assertEqual(len(courses), 1) found_course = courses[0]['course'] self.assertIn('courses/{}/about'.format(self.course.id), found_course['course_about']) self.assertIn('course_info/{}/updates'.format(self.course.id), found_course['course_updates']) self.assertIn('course_info/{}/handouts'.format(self.course.id), found_course['course_handouts']) self.assertIn('video_outlines/courses/{}'.format(self.course.id), found_course['video_outline']) self.assertEqual(found_course['id'], unicode(self.course.id)) self.assertEqual(courses[0]['mode'], CourseMode.DEFAULT_MODE_SLUG) self.assertEqual(courses[0]['course']['subscription_id'], self.course.clean_id(padding_char='_')) expected_course_image_url = course_image_url(self.course) self.assertIsNotNone(expected_course_image_url) self.assertIn(expected_course_image_url, found_course['course_image']) self.assertIn(expected_course_image_url, found_course['media']['course_image']['uri']) def verify_failure(self, response, error_type=None): self.assertEqual(response.status_code, 200) courses = response.data self.assertEqual(len(courses), 0) @patch.dict(settings.FEATURES, {'ENABLE_MKTG_SITE': True}) def test_sort_order(self): self.login() num_courses = 3 courses = [] for course_index in range(num_courses): courses.append(CourseFactory.create(mobile_available=True)) self.enroll(courses[course_index].id) # verify courses are returned in the order of enrollment, with most recently enrolled first. response = self.api_response() for course_index in range(num_courses): self.assertEqual( response.data[course_index]['course']['id'], unicode(courses[num_courses - course_index - 1].id) ) @patch.dict(settings.FEATURES, { 'ENABLE_PREREQUISITE_COURSES': True, 'DISABLE_START_DATES': False, 'ENABLE_MKTG_SITE': True, }) def test_courseware_access(self): self.login() course_with_prereq = CourseFactory.create(start=self.LAST_WEEK, mobile_available=True) prerequisite_course = CourseFactory.create() set_prerequisite_courses(course_with_prereq.id, [unicode(prerequisite_course.id)]) # Create list of courses with various expected courseware_access responses and corresponding expected codes courses = [ course_with_prereq, CourseFactory.create(start=self.NEXT_WEEK, mobile_available=True), CourseFactory.create(visible_to_staff_only=True, mobile_available=True), CourseFactory.create(start=self.LAST_WEEK, mobile_available=True, visible_to_staff_only=False), ] expected_error_codes = [<|fim▁hole|> StartDateError(self.NEXT_WEEK).error_code, # 'course_not_started' VisibilityError().error_code, # 'not_visible_to_user' None, ] # Enroll in all the courses for course in courses: self.enroll(course.id) # Verify courses have the correct response through error code. Last enrolled course is first course in response response = self.api_response() for course_index in range(len(courses)): result = response.data[course_index]['course']['courseware_access'] self.assertEqual(result['error_code'], expected_error_codes[::-1][course_index]) if result['error_code'] is not None: self.assertFalse(result['has_access']) @ddt.data( ('next_week', ADVERTISED_START, ADVERTISED_START, "string"), ('next_week', None, defaultfilters.date(NEXT_WEEK, "DATE_FORMAT"), "timestamp"), ('next_week', '', defaultfilters.date(NEXT_WEEK, "DATE_FORMAT"), "timestamp"), ('default_start_date', ADVERTISED_START, ADVERTISED_START, "string"), ('default_start_date', '', None, "empty"), ('default_start_date', None, None, "empty"), ) @ddt.unpack @patch.dict(settings.FEATURES, {'DISABLE_START_DATES': False, 'ENABLE_MKTG_SITE': True}) def test_start_type_and_display(self, start, advertised_start, expected_display, expected_type): """ Tests that the correct start_type and start_display are returned in the case the course has not started """ self.login() course = CourseFactory.create(start=self.DATES[start], advertised_start=advertised_start, mobile_available=True) self.enroll(course.id) response = self.api_response() self.assertEqual(response.data[0]['course']['start_type'], expected_type) self.assertEqual(response.data[0]['course']['start_display'], expected_display) @patch.dict(settings.FEATURES, {"ENABLE_DISCUSSION_SERVICE": True, 'ENABLE_MKTG_SITE': True}) def test_discussion_url(self): self.login_and_enroll() response = self.api_response() response_discussion_url = response.data[0]['course']['discussion_url'] self.assertIn('/api/discussion/v1/courses/{}'.format(self.course.id), response_discussion_url) def test_org_query(self): self.login() # Create list of courses with various organizations courses = [ CourseFactory.create(org='edX', mobile_available=True), CourseFactory.create(org='edX', mobile_available=True), CourseFactory.create(org='edX', mobile_available=True, visible_to_staff_only=True), CourseFactory.create(org='Proversity.org', mobile_available=True), CourseFactory.create(org='MITx', mobile_available=True), CourseFactory.create(org='HarvardX', mobile_available=True), ] # Enroll in all the courses for course in courses: self.enroll(course.id) response = self.api_response(data={'org': 'edX'}) # Test for 3 expected courses self.assertEqual(len(response.data), 3) # Verify only edX courses are returned for entry in response.data: self.assertEqual(entry['course']['org'], 'edX') @attr(shard=9) @override_settings(MKTG_URLS={'ROOT': 'dummy-root'}) class TestUserEnrollmentCertificates(UrlResetMixin, MobileAPITestCase, MilestonesTestCaseMixin): """ Tests for /api/mobile/v0.5/users/<user_name>/course_enrollments/ """ REVERSE_INFO = {'name': 'courseenrollment-detail', 'params': ['username']} ENABLED_SIGNALS = ['course_published'] def verify_pdf_certificate(self): """ Verifies the correct URL is returned in the response for PDF certificates. """ self.login_and_enroll() certificate_url = "http://test_certificate_url" GeneratedCertificateFactory.create( user=self.user, course_id=self.course.id, status=CertificateStatuses.downloadable, mode='verified', download_url=certificate_url, ) response = self.api_response() certificate_data = response.data[0]['certificate'] self.assertEquals(certificate_data['url'], certificate_url) @patch.dict(settings.FEATURES, {'ENABLE_MKTG_SITE': True}) def test_no_certificate(self): self.login_and_enroll() response = self.api_response() certificate_data = response.data[0]['certificate'] self.assertDictEqual(certificate_data, {}) @patch.dict(settings.FEATURES, {'CERTIFICATES_HTML_VIEW': False, 'ENABLE_MKTG_SITE': True}) def test_pdf_certificate_with_html_cert_disabled(self): """ Tests PDF certificates with CERTIFICATES_HTML_VIEW set to True. """ self.verify_pdf_certificate() @patch.dict(settings.FEATURES, {'CERTIFICATES_HTML_VIEW': True, 'ENABLE_MKTG_SITE': True}) def test_pdf_certificate_with_html_cert_enabled(self): """ Tests PDF certificates with CERTIFICATES_HTML_VIEW set to True. """ self.verify_pdf_certificate() @patch.dict(settings.FEATURES, {'CERTIFICATES_HTML_VIEW': True, 'ENABLE_MKTG_SITE': True}) def test_web_certificate(self): CourseMode.objects.create( course_id=self.course.id, mode_display_name="Honor", mode_slug=CourseMode.HONOR, ) self.login_and_enroll() self.course.cert_html_view_enabled = True self.store.update_item(self.course, self.user.id) with mock_passing_grade(): generate_user_certificates(self.user, self.course.id) response = self.api_response() certificate_data = response.data[0]['certificate'] self.assertRegexpMatches( certificate_data['url'], r'http.*/certificates/user/{user_id}/course/{course_id}'.format( user_id=self.user.id, course_id=self.course.id, ) ) @attr(shard=9) class CourseStatusAPITestCase(MobileAPITestCase): """ Base test class for /api/mobile/v0.5/users/<user_name>/course_status_info/{course_id} """ REVERSE_INFO = {'name': 'user-course-status', 'params': ['username', 'course_id']} def setUp(self): """ Creates a basic course structure for our course """ super(CourseStatusAPITestCase, self).setUp() self.section = ItemFactory.create( parent=self.course, category='chapter', ) self.sub_section = ItemFactory.create( parent=self.section, category='sequential', ) self.unit = ItemFactory.create( parent=self.sub_section, category='vertical', ) self.other_sub_section = ItemFactory.create( parent=self.section, category='sequential', ) self.other_unit = ItemFactory.create( parent=self.other_sub_section, category='vertical', ) @attr(shard=9) class TestCourseStatusGET(CourseStatusAPITestCase, MobileAuthUserTestMixin, MobileCourseAccessTestMixin, MilestonesTestCaseMixin): """ Tests for GET of /api/mobile/v0.5/users/<user_name>/course_status_info/{course_id} """ def test_success(self): self.login_and_enroll() response = self.api_response() self.assertEqual( response.data["last_visited_module_id"], unicode(self.sub_section.location) ) self.assertEqual( response.data["last_visited_module_path"], [unicode(module.location) for module in [self.sub_section, self.section, self.course]] ) @attr(shard=9) class TestCourseStatusPATCH(CourseStatusAPITestCase, MobileAuthUserTestMixin, MobileCourseAccessTestMixin, MilestonesTestCaseMixin): """ Tests for PATCH of /api/mobile/v0.5/users/<user_name>/course_status_info/{course_id} """ def url_method(self, url, **kwargs): # override implementation to use PATCH method. return self.client.patch(url, data=kwargs.get('data', None)) def test_success(self): self.login_and_enroll() response = self.api_response(data={"last_visited_module_id": unicode(self.other_unit.location)}) self.assertEqual( response.data["last_visited_module_id"], unicode(self.other_sub_section.location) ) def test_invalid_module(self): self.login_and_enroll() response = self.api_response(data={"last_visited_module_id": "abc"}, expected_response_code=400) self.assertEqual( response.data, errors.ERROR_INVALID_MODULE_ID ) def test_nonexistent_module(self): self.login_and_enroll() non_existent_key = self.course.id.make_usage_key('video', 'non-existent') response = self.api_response(data={"last_visited_module_id": non_existent_key}, expected_response_code=400) self.assertEqual( response.data, errors.ERROR_INVALID_MODULE_ID ) def test_no_timezone(self): self.login_and_enroll() past_date = datetime.datetime.now() response = self.api_response( data={ "last_visited_module_id": unicode(self.other_unit.location), "modification_date": past_date.isoformat() }, expected_response_code=400 ) self.assertEqual( response.data, errors.ERROR_INVALID_MODIFICATION_DATE ) def _date_sync(self, date, initial_unit, update_unit, expected_subsection): """ Helper for test cases that use a modification to decide whether to update the course status """ self.login_and_enroll() # save something so we have an initial date self.api_response(data={"last_visited_module_id": unicode(initial_unit.location)}) # now actually update it response = self.api_response( data={ "last_visited_module_id": unicode(update_unit.location), "modification_date": date.isoformat() } ) self.assertEqual( response.data["last_visited_module_id"], unicode(expected_subsection.location) ) def test_old_date(self): self.login_and_enroll() date = timezone.now() + datetime.timedelta(days=-100) self._date_sync(date, self.unit, self.other_unit, self.sub_section) def test_new_date(self): self.login_and_enroll() date = timezone.now() + datetime.timedelta(days=100) self._date_sync(date, self.unit, self.other_unit, self.other_sub_section) def test_no_initial_date(self): self.login_and_enroll() response = self.api_response( data={ "last_visited_module_id": unicode(self.other_unit.location), "modification_date": timezone.now().isoformat() } ) self.assertEqual( response.data["last_visited_module_id"], unicode(self.other_sub_section.location) ) def test_invalid_date(self): self.login_and_enroll() response = self.api_response(data={"modification_date": "abc"}, expected_response_code=400) self.assertEqual( response.data, errors.ERROR_INVALID_MODIFICATION_DATE ) @attr(shard=9) @patch.dict(settings.FEATURES, {'ENABLE_MKTG_SITE': True}) @override_settings(MKTG_URLS={'ROOT': 'dummy-root'}) class TestCourseEnrollmentSerializer(MobileAPITestCase, MilestonesTestCaseMixin): """ Test the course enrollment serializer """ ENABLED_SIGNALS = ['course_published'] def setUp(self): super(TestCourseEnrollmentSerializer, self).setUp() self.login_and_enroll() self.request = RequestFactory().get('/') self.request.user = self.user def test_success(self): serialized = CourseEnrollmentSerializer( CourseEnrollment.enrollments_for_user(self.user)[0], context={'request': self.request}, ).data self.assertEqual(serialized['course']['name'], self.course.display_name) self.assertEqual(serialized['course']['number'], self.course.id.course) self.assertEqual(serialized['course']['org'], self.course.id.org) # Assert utm parameters expected_utm_parameters = { 'twitter': 'utm_campaign=social-sharing-db&utm_medium=social&utm_source=twitter', 'facebook': 'utm_campaign=social-sharing-db&utm_medium=social&utm_source=facebook' } self.assertEqual(serialized['course']['course_sharing_utm_parameters'], expected_utm_parameters) def test_with_display_overrides(self): self.course.display_coursenumber = "overridden_number" self.course.display_organization = "overridden_org" self.store.update_item(self.course, self.user.id) serialized = CourseEnrollmentSerializer( CourseEnrollment.enrollments_for_user(self.user)[0], context={'request': self.request}, ).data self.assertEqual(serialized['course']['number'], self.course.display_coursenumber) self.assertEqual(serialized['course']['org'], self.course.display_organization)<|fim▁end|>
MilestoneAccessError().error_code, # 'unfulfilled_milestones'
<|file_name|>conf.py<|end_file_name|><|fim▁begin|># DO THIS FIRST to set project name !!! <|fim▁hole|> from askapdev.sphinx.conf import * version = 'current' release = 'current'<|fim▁end|>
import askapdev.sphinx # CAN NOT contain spaces! askapdev.sphinx.project = u'askap.parset'
<|file_name|>regex_iterator_example.cpp<|end_file_name|><|fim▁begin|>/* * * Copyright (c) 2003 * John Maddock * * Use, modification and distribution are subject to the * Boost Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)<|fim▁hole|> * */ /* * LOCATION: see http://www.boost.org for most recent version. * FILE regex_iterator_example_2.cpp * VERSION see <boost/version.hpp> * DESCRIPTION: regex_iterator example 2: searches a cpp file for class definitions, * using global data. */ #include <string> #include <map> #include <fstream> #include <iostream> #include <boost/regex.hpp> using namespace std; // purpose: // takes the contents of a file in the form of a string // and searches for all the C++ class definitions, storing // their locations in a map of strings/int's typedef std::map<std::string, std::string::difference_type, std::less<std::string> > map_type; const char* re = // possibly leading whitespace: "^[[:space:]]*" // possible template declaration: "(template[[:space:]]*<[^;:{]+>[[:space:]]*)?" // class or struct: "(class|struct)[[:space:]]*" // leading declspec macros etc: "(" "\\<\\w+\\>" "(" "[[:blank:]]*\\([^)]*\\)" ")?" "[[:space:]]*" ")*" // the class name "(\\<\\w*\\>)[[:space:]]*" // template specialisation parameters "(<[^;:{]+>)?[[:space:]]*" // terminate in { or : "(\\{|:[^;\\{()]*\\{)"; boost::regex expression(re); map_type class_index; bool regex_callback(const boost::match_results<std::string::const_iterator>& what) { // what[0] contains the whole string // what[5] contains the class name. // what[6] contains the template specialisation if any. // add class name and position to map: class_index[what[5].str() + what[6].str()] = what.position(5); return true; } void load_file(std::string& s, std::istream& is) { s.erase(); if(is.bad()) return; s.reserve(is.rdbuf()->in_avail()); char c; while(is.get(c)) { if(s.capacity() == s.size()) s.reserve(s.capacity() * 3); s.append(1, c); } } int main(int argc, const char** argv) { std::string text; for(int i = 1; i < argc; ++i) { cout << "Processing file " << argv[i] << endl; std::ifstream fs(argv[i]); load_file(text, fs); fs.close(); // construct our iterators: boost::sregex_iterator m1(text.begin(), text.end(), expression); boost::sregex_iterator m2; std::for_each(m1, m2, &regex_callback); // copy results: cout << class_index.size() << " matches found" << endl; map_type::iterator c, d; c = class_index.begin(); d = class_index.end(); while(c != d) { cout << "class \"" << (*c).first << "\" found at index: " << (*c).second << endl; ++c; } class_index.erase(class_index.begin(), class_index.end()); } return 0; }<|fim▁end|>
<|file_name|>harmonicfolder.hpp<|end_file_name|><|fim▁begin|>#pragma once #include <data_types/fourierseries.hpp> #include <kernels/kernels.h> #include <kernels/defaults.h> #include <iostream> #include <utils/nvtx.hpp> class HarmonicFolder { private: unsigned int max_blocks; unsigned int max_threads; float** h_data_ptrs; float** d_data_ptrs; HarmonicSums<float>& sums; public: HarmonicFolder(HarmonicSums<float>& sums, unsigned int max_blocks=MAX_BLOCKS, unsigned int max_threads=MAX_THREADS) :sums(sums),max_blocks(max_blocks),max_threads(max_threads) { Utils::device_malloc<float*>(&d_data_ptrs,sums.size()); Utils::host_malloc<float*>(&h_data_ptrs,sums.size()); } void fold(DevicePowerSpectrum<float>& fold0) { PUSH_NVTX_RANGE("Harmonic summing",2) for (int ii=0;ii<sums.size();ii++) { h_data_ptrs[ii] = sums[ii]->get_data(); } Utils::h2dcpy<float*>(d_data_ptrs,h_data_ptrs,sums.size()); device_harmonic_sum(fold0.get_data(),d_data_ptrs, fold0.get_nbins(),sums.size(), max_blocks,max_threads);<|fim▁hole|> ~HarmonicFolder() { Utils::device_free(d_data_ptrs); Utils::host_free(h_data_ptrs); } };<|fim▁end|>
POP_NVTX_RANGE }
<|file_name|>matching.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! High-level interface to CSS selector matching. #![allow(unsafe_code)] #![deny(missing_docs)] use applicable_declarations::ApplicableDeclarationList; use cascade_info::CascadeInfo; use context::{SelectorFlagsMap, SharedStyleContext, StyleContext}; use data::{ComputedStyle, ElementData, RestyleData}; use dom::{TElement, TNode}; use font_metrics::FontMetricsProvider; use invalidation::element::restyle_hints::{RESTYLE_CSS_ANIMATIONS, RESTYLE_CSS_TRANSITIONS}; use invalidation::element::restyle_hints::{RESTYLE_SMIL, RESTYLE_STYLE_ATTRIBUTE}; use invalidation::element::restyle_hints::RestyleHint; use log::LogLevel::Trace; use properties::{ALLOW_SET_ROOT_FONT_SIZE, PROHIBIT_DISPLAY_CONTENTS, SKIP_ROOT_AND_ITEM_BASED_DISPLAY_FIXUP}; use properties::{AnimationRules, CascadeFlags, ComputedValues}; use properties::{VISITED_DEPENDENT_ONLY, cascade}; use properties::longhands::display::computed_value as display; use rule_tree::{CascadeLevel, StrongRuleNode}; use selector_parser::{PseudoElement, RestyleDamage, SelectorImpl}; use selectors::matching::{ElementSelectorFlags, MatchingContext, MatchingMode, StyleRelations}; use selectors::matching::{VisitedHandlingMode, AFFECTED_BY_PSEUDO_ELEMENTS}; use sharing::StyleSharingBehavior; use stylearc::Arc; use stylist::RuleInclusion; /// Whether we are cascading for an eager pseudo-element or something else. /// /// Controls where we inherit styles from, and whether display:contents is /// prohibited. #[derive(PartialEq, Copy, Clone)] enum CascadeTarget { /// Inherit from the parent element, as normal CSS dictates, _or_ from the /// closest non-Native Anonymous element in case this is Native Anonymous /// Content. display:contents is allowed. Normal, /// Inherit from the primary style, this is used while computing eager /// pseudos, like ::before and ::after when we're traversing the parent. /// Also prohibits display:contents from having an effect. /// /// TODO(emilio) display:contents really should apply to ::before/::after. /// https://github.com/w3c/csswg-drafts/issues/1345 EagerPseudo, } /// Represents the result of comparing an element's old and new style. pub struct StyleDifference { /// The resulting damage. pub damage: RestyleDamage, /// Whether any styles changed. pub change: StyleChange, } impl StyleDifference { /// Creates a new `StyleDifference`. pub fn new(damage: RestyleDamage, change: StyleChange) -> Self { StyleDifference { change: change, damage: damage, } } } /// Represents whether or not the style of an element has changed. #[derive(Copy, Clone)] pub enum StyleChange { /// The style hasn't changed. Unchanged, /// The style has changed. Changed, } /// Whether or not newly computed values for an element need to be cascade /// to children. pub enum ChildCascadeRequirement { /// Old and new computed values were the same, or we otherwise know that /// we won't bother recomputing style for children, so we can skip cascading /// the new values into child elements. CanSkipCascade, /// Old and new computed values were different, so we must cascade the /// new values to children. /// /// FIXME(heycam) Although this is "must" cascade, in the future we should /// track whether child elements rely specifically on inheriting particular /// property values. When we do that, we can treat `MustCascadeChildren` as /// "must cascade unless we know that changes to these properties can be /// ignored". MustCascadeChildren, /// The same as `MustCascadeChildren`, but for the entire subtree. This is /// used to handle root font-size updates needing to recascade the whole /// document. MustCascadeDescendants, } impl From<StyleChange> for ChildCascadeRequirement { fn from(change: StyleChange) -> ChildCascadeRequirement { match change { StyleChange::Unchanged => ChildCascadeRequirement::CanSkipCascade, StyleChange::Changed => ChildCascadeRequirement::MustCascadeChildren, } } } bitflags! { /// Flags that represent the result of replace_rules. pub flags RulesChanged: u8 { /// Normal rules are changed. const NORMAL_RULES_CHANGED = 0x01, /// Important rules are changed. const IMPORTANT_RULES_CHANGED = 0x02, } } impl RulesChanged { /// Return true if there are any normal rules changed. #[inline] pub fn normal_rules_changed(&self) -> bool { self.contains(NORMAL_RULES_CHANGED) } /// Return true if there are any important rules changed. #[inline] pub fn important_rules_changed(&self) -> bool { self.contains(IMPORTANT_RULES_CHANGED) } } /// Determines which styles are being cascaded currently. #[derive(PartialEq, Eq, Copy, Clone, Debug)] pub enum CascadeVisitedMode { /// Cascade the regular, unvisited styles. Unvisited, /// Cascade the styles used when an element's relevant link is visited. A /// "relevant link" is the element being matched if it is a link or the /// nearest ancestor link. Visited, } /// Various helper methods to ease navigating the style storage locations /// depending on the current cascade mode. impl CascadeVisitedMode { /// Returns whether there is a rule node based on the cascade mode. fn has_rules(&self, style: &ComputedStyle) -> bool { match *self { CascadeVisitedMode::Unvisited => true, CascadeVisitedMode::Visited => style.has_visited_rules(), } } /// Returns the rule node based on the cascade mode. fn rules<'a>(&self, style: &'a ComputedStyle) -> &'a StrongRuleNode { match *self { CascadeVisitedMode::Unvisited => &style.rules, CascadeVisitedMode::Visited => style.visited_rules(), } } /// Returns a mutable rules node based on the cascade mode, if any. fn get_rules_mut<'a>(&self, style: &'a mut ComputedStyle) -> Option<&'a mut StrongRuleNode> { match *self { CascadeVisitedMode::Unvisited => Some(&mut style.rules), CascadeVisitedMode::Visited => style.get_visited_rules_mut(), } } /// Returns the computed values based on the cascade mode. In visited mode, /// visited values are only returned if they already exist. If they don't, /// we fallback to the regular, unvisited styles. fn values<'a>(&self, style: &'a ComputedStyle) -> &'a Arc<ComputedValues> { let mut values = style.values(); if *self == CascadeVisitedMode::Visited && values.get_visited_style().is_some() { values = values.visited_style(); } values } /// Set the computed values based on the cascade mode. fn set_values(&self, style: &mut ComputedStyle, values: Arc<ComputedValues>) { match *self { CascadeVisitedMode::Unvisited => style.values = Some(values), CascadeVisitedMode::Visited => style.set_visited_values(values), } } /// Take the computed values based on the cascade mode. fn take_values(&self, style: &mut ComputedStyle) -> Option<Arc<ComputedValues>> { match *self { CascadeVisitedMode::Unvisited => style.values.take(), CascadeVisitedMode::Visited => style.take_visited_values(), } } /// Returns whether there might be visited values that should be inserted /// within the regular computed values based on the cascade mode. fn visited_values_for_insertion(&self) -> bool { *self == CascadeVisitedMode::Unvisited } /// Returns whether animations should be processed based on the cascade /// mode. At the moment, it appears we don't need to support animating /// visited styles. fn should_process_animations(&self) -> bool { *self == CascadeVisitedMode::Unvisited } /// Returns whether we should accumulate restyle damage based on the cascade /// mode. At the moment, it appears we don't need to do so for visited /// styles. TODO: Verify this is correct as part of /// https://bugzilla.mozilla.org/show_bug.cgi?id=1364484. fn should_accumulate_damage(&self) -> bool { *self == CascadeVisitedMode::Unvisited } /// Returns whether the cascade should filter to only visited dependent /// properties based on the cascade mode. fn visited_dependent_only(&self) -> bool { *self == CascadeVisitedMode::Visited } } trait PrivateMatchMethods: TElement { /// Returns the closest parent element that doesn't have a display: contents /// style (and thus generates a box). /// /// This is needed to correctly handle blockification of flex and grid /// items. /// /// Returns itself if the element has no parent. In practice this doesn't /// happen because the root element is blockified per spec, but it could /// happen if we decide to not blockify for roots of disconnected subtrees, /// which is a kind of dubious beahavior. fn layout_parent(&self) -> Self { let mut current = self.clone(); loop { current = match current.traversal_parent() { Some(el) => el, None => return current, }; let is_display_contents = current.borrow_data().unwrap().styles().primary.values().is_display_contents(); if !is_display_contents { return current; } } } fn cascade_with_rules(&self, shared_context: &SharedStyleContext, font_metrics_provider: &FontMetricsProvider, rule_node: &StrongRuleNode, primary_style: &ComputedStyle, cascade_target: CascadeTarget, cascade_visited: CascadeVisitedMode, visited_values_to_insert: Option<Arc<ComputedValues>>) -> Arc<ComputedValues> { let mut cascade_info = CascadeInfo::new(); let mut cascade_flags = CascadeFlags::empty(); if self.skip_root_and_item_based_display_fixup() { cascade_flags.insert(SKIP_ROOT_AND_ITEM_BASED_DISPLAY_FIXUP) } if cascade_visited.visited_dependent_only() { cascade_flags.insert(VISITED_DEPENDENT_ONLY); } if self.is_native_anonymous() || cascade_target == CascadeTarget::EagerPseudo { cascade_flags.insert(PROHIBIT_DISPLAY_CONTENTS); } else { cascade_flags.insert(ALLOW_SET_ROOT_FONT_SIZE); } // Grab the inherited values. let parent_el; let parent_data; let style_to_inherit_from = match cascade_target { CascadeTarget::Normal => { parent_el = self.inheritance_parent(); parent_data = parent_el.as_ref().and_then(|e| e.borrow_data()); let parent_style = parent_data.as_ref().map(|d| { // Sometimes Gecko eagerly styles things without processing // pending restyles first. In general we'd like to avoid this, // but there can be good reasons (for example, needing to // construct a frame for some small piece of newly-added // content in order to do something specific with that frame, // but not wanting to flush all of layout). debug_assert!(cfg!(feature = "gecko") || parent_el.unwrap().has_current_styles(d)); &d.styles().primary }); parent_style.map(|s| cascade_visited.values(s)) } CascadeTarget::EagerPseudo => { parent_el = Some(self.clone()); Some(cascade_visited.values(primary_style)) } }; let mut layout_parent_el = parent_el.clone(); let layout_parent_data; let mut layout_parent_style = style_to_inherit_from; if style_to_inherit_from.map_or(false, |s| s.is_display_contents()) { layout_parent_el = Some(layout_parent_el.unwrap().layout_parent()); layout_parent_data = layout_parent_el.as_ref().unwrap().borrow_data().unwrap(); layout_parent_style = Some(cascade_visited.values(&layout_parent_data.styles().primary)); } let style_to_inherit_from = style_to_inherit_from.map(|x| &**x); let layout_parent_style = layout_parent_style.map(|x| &**x); // Propagate the "can be fragmented" bit. It would be nice to // encapsulate this better. // // Note that this is technically not needed for pseudos since we already // do that when we resolve the non-pseudo style, but it doesn't hurt // anyway. // // TODO(emilio): This is servo-only, move somewhere else? if let Some(ref p) = layout_parent_style { let can_be_fragmented = p.is_multicol() || layout_parent_el.as_ref().unwrap().as_node().can_be_fragmented(); unsafe { self.as_node().set_can_be_fragmented(can_be_fragmented); } } // Invoke the cascade algorithm. let values = Arc::new(cascade(shared_context.stylist.device(), rule_node, &shared_context.guards, style_to_inherit_from, layout_parent_style, visited_values_to_insert, Some(&mut cascade_info), &*shared_context.error_reporter, font_metrics_provider, cascade_flags, shared_context.quirks_mode)); cascade_info.finish(&self.as_node()); values } fn cascade_internal(&self, context: &StyleContext<Self>, primary_style: &ComputedStyle, eager_pseudo_style: Option<&ComputedStyle>, cascade_visited: CascadeVisitedMode) -> Arc<ComputedValues> { if let Some(pseudo) = self.implemented_pseudo_element() { debug_assert!(eager_pseudo_style.is_none()); // This is an element-backed pseudo, just grab the styles from the // parent if it's eager, and recascade otherwise. // // We also recascade if the eager pseudo-style has any animation // rules, because we don't cascade those during the eager traversal. // // We could make that a bit better if the complexity cost is not too // big, but given further restyles are posted directly to // pseudo-elements, it doesn't seem worth the effort at a glance. // // For the same reason as described in match_primary, if we are // computing default styles, we aren't guaranteed the parent // will have eagerly computed our styles, so we just handled it // below like a lazy pseudo. let only_default_rules = context.shared.traversal_flags.for_default_styles(); if pseudo.is_eager() && !only_default_rules { debug_assert!(pseudo.is_before_or_after()); let parent = self.parent_element().unwrap(); if !parent.may_have_animations() || primary_style.rules.get_animation_rules().is_empty() { let parent_data = parent.borrow_data().unwrap(); let pseudo_style = parent_data.styles().pseudos.get(&pseudo).unwrap(); let values = cascade_visited.values(pseudo_style); return values.clone() } } } // Find possible visited computed styles to insert within the regular // computed values we are about to create. let visited_values_to_insert = if cascade_visited.visited_values_for_insertion() { match eager_pseudo_style { Some(ref s) => s.clone_visited_values(), None => primary_style.clone_visited_values(), } } else { None }; // Grab the rule node. let style = eager_pseudo_style.unwrap_or(primary_style); let rule_node = cascade_visited.rules(style); let cascade_target = if eager_pseudo_style.is_some() { CascadeTarget::EagerPseudo } else { CascadeTarget::Normal }; self.cascade_with_rules(context.shared, &context.thread_local.font_metrics_provider, rule_node, primary_style, cascade_target, cascade_visited, visited_values_to_insert) } /// Computes values and damage for the primary style of an element, setting /// them on the ElementData. fn cascade_primary(&self, context: &mut StyleContext<Self>, data: &mut ElementData, important_rules_changed: bool, cascade_visited: CascadeVisitedMode) -> ChildCascadeRequirement { debug!("Cascade primary for {:?}, visited: {:?}", self, cascade_visited); // Collect some values. let (mut styles, restyle) = data.styles_and_restyle_mut(); let mut primary_style = &mut styles.primary; // If there was no relevant link, we won't have any visited rules, so // there may not be anything do for the visited case. This early return // is especially important for the `cascade_primary_and_pseudos` path // since we rely on the state of some previous matching run. if !cascade_visited.has_rules(primary_style) { return ChildCascadeRequirement::CanSkipCascade } let mut old_values = cascade_visited.take_values(primary_style); // Compute the new values. let mut new_values = self.cascade_internal(context, primary_style, None, cascade_visited); // NB: Animations for pseudo-elements in Gecko are handled while // traversing the pseudo-elements themselves. if !context.shared.traversal_flags.for_animation_only() && cascade_visited.should_process_animations() { self.process_animations(context, &mut old_values, &mut new_values, primary_style, important_rules_changed); } let mut child_cascade_requirement = ChildCascadeRequirement::CanSkipCascade; if cascade_visited.should_accumulate_damage() { child_cascade_requirement = self.accumulate_damage(&context.shared, restyle, old_values.as_ref().map(|v| v.as_ref()), &new_values, None); // Handle root font-size changes. if self.is_root() && !self.is_native_anonymous() { // The new root font-size has already been updated on the Device // in properties::apply_declarations. let device = context.shared.stylist.device(); let new_font_size = new_values.get_font().clone_font_size(); // If the root font-size changed since last time, and something // in the document did use rem units, ensure we recascade the // entire tree. if old_values.map_or(false, |v| v.get_font().clone_font_size() != new_font_size) && device.used_root_font_size() { child_cascade_requirement = ChildCascadeRequirement::MustCascadeDescendants; } } } // Set the new computed values. cascade_visited.set_values(primary_style, new_values); // Return whether the damage indicates we must cascade new inherited // values into children. child_cascade_requirement } /// Computes values and damage for the eager pseudo-element styles of an /// element, setting them on the ElementData. fn cascade_eager_pseudo(&self, context: &mut StyleContext<Self>, data: &mut ElementData, pseudo: &PseudoElement, cascade_visited: CascadeVisitedMode) { debug_assert!(pseudo.is_eager()); let (mut styles, restyle) = data.styles_and_restyle_mut(); let mut pseudo_style = styles.pseudos.get_mut(pseudo).unwrap(); // If there was no relevant link, we won't have any visited rules, so // there may not be anything do for the visited case. This early return // is especially important for the `cascade_primary_and_pseudos` path // since we rely on the state of some previous matching run. if !cascade_visited.has_rules(pseudo_style) { return } let old_values = cascade_visited.take_values(pseudo_style); let new_values = self.cascade_internal(context, &styles.primary, Some(pseudo_style), cascade_visited); if cascade_visited.should_accumulate_damage() { self.accumulate_damage(&context.shared, restyle,<|fim▁hole|> &new_values, Some(pseudo)); } cascade_visited.set_values(pseudo_style, new_values); } /// get_after_change_style removes the transition rules from the ComputedValues. /// If there is no transition rule in the ComputedValues, it returns None. #[cfg(feature = "gecko")] fn get_after_change_style(&self, context: &mut StyleContext<Self>, primary_style: &ComputedStyle) -> Option<Arc<ComputedValues>> { let rule_node = &primary_style.rules; let without_transition_rules = context.shared.stylist.rule_tree().remove_transition_rule_if_applicable(rule_node); if without_transition_rules == *rule_node { // We don't have transition rule in this case, so return None to let the caller // use the original ComputedValues. return None; } // This currently ignores visited styles, which seems acceptable, // as existing browsers don't appear to transition visited styles. Some(self.cascade_with_rules(context.shared, &context.thread_local.font_metrics_provider, &without_transition_rules, primary_style, CascadeTarget::Normal, CascadeVisitedMode::Unvisited, None)) } #[cfg(feature = "gecko")] fn needs_animations_update(&self, context: &mut StyleContext<Self>, old_values: Option<&Arc<ComputedValues>>, new_values: &ComputedValues) -> bool { let new_box_style = new_values.get_box(); let has_new_animation_style = new_box_style.animation_name_count() >= 1 && new_box_style.animation_name_at(0).0.is_some(); let has_animations = self.has_css_animations(); old_values.map_or(has_new_animation_style, |old| { let old_box_style = old.get_box(); let old_display_style = old_box_style.clone_display(); let new_display_style = new_box_style.clone_display(); // If the traverse is triggered by CSS rule changes, // we need to try to update all CSS animations. context.shared.traversal_flags.for_css_rule_changes() || !old_box_style.animations_equals(&new_box_style) || (old_display_style == display::T::none && new_display_style != display::T::none && has_new_animation_style) || (old_display_style != display::T::none && new_display_style == display::T::none && has_animations) }) } #[cfg(feature = "gecko")] fn process_animations(&self, context: &mut StyleContext<Self>, old_values: &mut Option<Arc<ComputedValues>>, new_values: &mut Arc<ComputedValues>, primary_style: &ComputedStyle, important_rules_changed: bool) { use context::{CASCADE_RESULTS, CSS_ANIMATIONS, CSS_TRANSITIONS, EFFECT_PROPERTIES}; use context::UpdateAnimationsTasks; let mut tasks = UpdateAnimationsTasks::empty(); if self.needs_animations_update(context, old_values.as_ref(), new_values) { tasks.insert(CSS_ANIMATIONS); } let before_change_style = if self.might_need_transitions_update(old_values.as_ref().map(|s| &**s), new_values) { let after_change_style = if self.has_css_transitions() { self.get_after_change_style(context, primary_style) } else { None }; // In order to avoid creating a SequentialTask for transitions which // may not be updated, we check it per property to make sure Gecko // side will really update transition. let needs_transitions_update = { // We borrow new_values here, so need to add a scope to make // sure we release it before assigning a new value to it. let after_change_style_ref = after_change_style.as_ref().unwrap_or(&new_values); self.needs_transitions_update(old_values.as_ref().unwrap(), after_change_style_ref) }; if needs_transitions_update { if let Some(values_without_transitions) = after_change_style { *new_values = values_without_transitions; } tasks.insert(CSS_TRANSITIONS); // We need to clone old_values into SequentialTask, so we can use it later. old_values.clone() } else { None } } else { None }; if self.has_animations() { tasks.insert(EFFECT_PROPERTIES); if important_rules_changed { tasks.insert(CASCADE_RESULTS); } } if !tasks.is_empty() { let task = ::context::SequentialTask::update_animations(*self, before_change_style, tasks); context.thread_local.tasks.push(task); } } #[cfg(feature = "servo")] fn process_animations(&self, context: &mut StyleContext<Self>, old_values: &mut Option<Arc<ComputedValues>>, new_values: &mut Arc<ComputedValues>, _primary_style: &ComputedStyle, _important_rules_changed: bool) { use animation; let possibly_expired_animations = &mut context.thread_local.current_element_info.as_mut().unwrap() .possibly_expired_animations; let shared_context = context.shared; if let Some(ref mut old) = *old_values { self.update_animations_for_cascade(shared_context, old, possibly_expired_animations, &context.thread_local.font_metrics_provider); } let new_animations_sender = &context.thread_local.new_animations_sender; let this_opaque = self.as_node().opaque(); // Trigger any present animations if necessary. animation::maybe_start_animations(&shared_context, new_animations_sender, this_opaque, &new_values); // Trigger transitions if necessary. This will reset `new_values` back // to its old value if it did trigger a transition. if let Some(ref values) = *old_values { animation::start_transitions_if_applicable( new_animations_sender, this_opaque, &**values, new_values, &shared_context.timer, &possibly_expired_animations); } } /// Computes and applies non-redundant damage. #[cfg(feature = "gecko")] fn accumulate_damage_for(&self, shared_context: &SharedStyleContext, restyle: &mut RestyleData, old_values: &ComputedValues, new_values: &Arc<ComputedValues>, pseudo: Option<&PseudoElement>) -> ChildCascadeRequirement { // Don't accumulate damage if we're in a restyle for reconstruction. if shared_context.traversal_flags.for_reconstruct() { return ChildCascadeRequirement::MustCascadeChildren; } // If an ancestor is already getting reconstructed by Gecko's top-down // frame constructor, no need to apply damage. Similarly if we already // have an explicitly stored ReconstructFrame hint. // // See https://bugzilla.mozilla.org/show_bug.cgi?id=1301258#c12 // for followup work to make the optimization here more optimal by considering // each bit individually. let skip_applying_damage = restyle.reconstructed_self_or_ancestor(); let difference = self.compute_style_difference(&old_values, &new_values, pseudo); if !skip_applying_damage { restyle.damage |= difference.damage; } difference.change.into() } /// Computes and applies restyle damage unless we've already maxed it out. #[cfg(feature = "servo")] fn accumulate_damage_for(&self, _shared_context: &SharedStyleContext, restyle: &mut RestyleData, old_values: &ComputedValues, new_values: &Arc<ComputedValues>, pseudo: Option<&PseudoElement>) -> ChildCascadeRequirement { let difference = self.compute_style_difference(&old_values, &new_values, pseudo); restyle.damage |= difference.damage; difference.change.into() } #[cfg(feature = "servo")] fn update_animations_for_cascade(&self, context: &SharedStyleContext, style: &mut Arc<ComputedValues>, possibly_expired_animations: &mut Vec<::animation::PropertyAnimation>, font_metrics: &FontMetricsProvider) { use animation::{self, Animation}; // Finish any expired transitions. let this_opaque = self.as_node().opaque(); animation::complete_expired_transitions(this_opaque, style, context); // Merge any running transitions into the current style, and cancel them. let had_running_animations = context.running_animations .read() .get(&this_opaque) .is_some(); if had_running_animations { let mut all_running_animations = context.running_animations.write(); for running_animation in all_running_animations.get_mut(&this_opaque).unwrap() { // This shouldn't happen frequently, but under some // circumstances mainly huge load or debug builds, the // constellation might be delayed in sending the // `TickAllAnimations` message to layout. // // Thus, we can't assume all the animations have been already // updated by layout, because other restyle due to script might // be triggered by layout before the animation tick. // // See #12171 and the associated PR for an example where this // happened while debugging other release panic. if !running_animation.is_expired() { animation::update_style_for_animation(context, running_animation, style, font_metrics); if let Animation::Transition(_, _, ref frame, _) = *running_animation { possibly_expired_animations.push(frame.property_animation.clone()) } } } } } } impl<E: TElement> PrivateMatchMethods for E {} /// Collects the outputs of the primary matching process, including the rule /// node and other associated data. #[derive(Debug)] pub struct MatchingResults { /// Whether the rules changed. rules_changed: bool, /// Whether there are any changes of important rules overriding animations. important_rules_overriding_animation_changed: bool, /// Records certains relations between elements noticed during matching (and /// also extended after matching). relations: StyleRelations, /// Whether we encountered a "relevant link" while matching _any_ selector /// for this element. (This differs from `RelevantLinkStatus` which tracks /// the status for the _current_ selector only.) relevant_link_found: bool, } impl MatchingResults { /// Create `MatchingResults` with only the basic required outputs. fn new(rules_changed: bool, important_rules: bool) -> Self { Self { rules_changed: rules_changed, important_rules_overriding_animation_changed: important_rules, relations: StyleRelations::default(), relevant_link_found: false, } } /// Create `MatchingResults` from the output fields of `MatchingContext`. fn new_from_context(rules_changed: bool, important_rules: bool, context: MatchingContext) -> Self { Self { rules_changed: rules_changed, important_rules_overriding_animation_changed: important_rules, relations: context.relations, relevant_link_found: context.relevant_link_found, } } } /// The public API that elements expose for selector matching. pub trait MatchMethods : TElement { /// Performs selector matching and property cascading on an element and its /// eager pseudos. fn match_and_cascade(&self, context: &mut StyleContext<Self>, data: &mut ElementData, sharing: StyleSharingBehavior) -> ChildCascadeRequirement { debug!("Match and cascade for {:?}", self); // Perform selector matching for the primary style. let mut primary_results = self.match_primary(context, data, VisitedHandlingMode::AllLinksUnvisited); let important_rules_changed = primary_results.important_rules_overriding_animation_changed; // If there's a relevant link involved, match and cascade primary styles // as if the link is visited as well. This is done before the regular // cascade because the visited ComputedValues are placed within the // regular ComputedValues, which is immutable after the cascade. let relevant_link_found = primary_results.relevant_link_found; if relevant_link_found { self.match_primary(context, data, VisitedHandlingMode::RelevantLinkVisited); self.cascade_primary(context, data, important_rules_changed, CascadeVisitedMode::Visited); } // Cascade properties and compute primary values. let child_cascade_requirement = self.cascade_primary(context, data, important_rules_changed, CascadeVisitedMode::Unvisited); // Match and cascade eager pseudo-elements. if !data.styles().is_display_none() { self.match_pseudos(context, data, VisitedHandlingMode::AllLinksUnvisited); // If there's a relevant link involved, match and cascade eager // pseudo-element styles as if the link is visited as well. // This runs after matching for regular styles because matching adds // each pseudo as needed to the PseudoMap, and this runs before // cascade for regular styles because the visited ComputedValues // are placed within the regular ComputedValues, which is immutable // after the cascade. if relevant_link_found { self.match_pseudos(context, data, VisitedHandlingMode::RelevantLinkVisited); self.cascade_pseudos(context, data, CascadeVisitedMode::Visited); } self.cascade_pseudos(context, data, CascadeVisitedMode::Unvisited); } // If we have any pseudo elements, indicate so in the primary StyleRelations. if !data.styles().pseudos.is_empty() { primary_results.relations |= AFFECTED_BY_PSEUDO_ELEMENTS; } // If the style is shareable, add it to the LRU cache. if sharing == StyleSharingBehavior::Allow { // If we previously tried to match this element against the cache, // the revalidation match results will already be cached. Otherwise // we'll have None, and compute them later on-demand. // // If we do have the results, grab them here to satisfy the borrow // checker. let validation_data = context.thread_local .current_element_info .as_mut().unwrap() .validation_data .take(); let dom_depth = context.thread_local.bloom_filter.matching_depth(); context.thread_local .style_sharing_candidate_cache .insert_if_possible(self, data.styles().primary.values(), primary_results.relations, validation_data, dom_depth); } child_cascade_requirement } /// Performs the cascade, without matching. fn cascade_primary_and_pseudos(&self, context: &mut StyleContext<Self>, mut data: &mut ElementData, important_rules_changed: bool) -> ChildCascadeRequirement { // If there's a relevant link involved, cascade styles as if the link is // visited as well. This is done before the regular cascade because the // visited ComputedValues are placed within the regular ComputedValues, // which is immutable after the cascade. If there aren't any visited // rules, these calls will return without cascading. self.cascade_primary(context, &mut data, important_rules_changed, CascadeVisitedMode::Visited); let child_cascade_requirement = self.cascade_primary(context, &mut data, important_rules_changed, CascadeVisitedMode::Unvisited); self.cascade_pseudos(context, &mut data, CascadeVisitedMode::Visited); self.cascade_pseudos(context, &mut data, CascadeVisitedMode::Unvisited); child_cascade_requirement } /// Runs selector matching to (re)compute the primary rule node for this /// element. /// /// Returns `MatchingResults` with the new rules and other associated data /// from the matching process. fn match_primary(&self, context: &mut StyleContext<Self>, data: &mut ElementData, visited_handling: VisitedHandlingMode) -> MatchingResults { debug!("Match primary for {:?}, visited: {:?}", self, visited_handling); let only_default_rules = context.shared.traversal_flags.for_default_styles(); let implemented_pseudo = self.implemented_pseudo_element(); if let Some(ref pseudo) = implemented_pseudo { // We don't expect to match against a non-canonical pseudo-element. debug_assert_eq!(*pseudo, pseudo.canonical()); if pseudo.is_eager() && !only_default_rules { // If it's an eager element-backed pseudo, we can generally just // grab the matched rules from the parent, and then update // animations. // // However, if we're computing default styles, then we might // have traversed to this pseudo-implementing element without // any pseudo styles stored on the parent. For example, if // document-level style sheets cause the element to exist, due // to ::before rules, then those rules won't be found when // computing default styles on the parent, so we won't have // bothered to store pseudo styles there. In this case, we just // treat it like a lazily computed pseudo. let parent = self.parent_element().unwrap(); let parent_data = parent.borrow_data().unwrap(); let pseudo_style = parent_data.styles().pseudos.get(&pseudo).unwrap(); let mut rules = pseudo_style.rules.clone(); if parent.may_have_animations() { let animation_rules = data.get_animation_rules(); // Handle animations here. if let Some(animation_rule) = animation_rules.0 { let animation_rule_node = context.shared.stylist.rule_tree() .update_rule_at_level(CascadeLevel::Animations, Some(&animation_rule), &mut rules, &context.shared.guards); if let Some(node) = animation_rule_node { rules = node; } } if let Some(animation_rule) = animation_rules.1 { let animation_rule_node = context.shared.stylist.rule_tree() .update_rule_at_level(CascadeLevel::Transitions, Some(&animation_rule), &mut rules, &context.shared.guards); if let Some(node) = animation_rule_node { rules = node; } } } let important_rules_changed = self.has_animations() && data.has_styles() && data.important_rules_are_different(&rules, &context.shared.guards); let rules_changed = match visited_handling { VisitedHandlingMode::AllLinksVisitedAndUnvisited => { unreachable!("We should never try to selector match with \ AllLinksVisitedAndUnvisited"); }, VisitedHandlingMode::AllLinksUnvisited => { data.set_primary_rules(rules) }, VisitedHandlingMode::RelevantLinkVisited => { data.styles_mut().primary.set_visited_rules(rules) }, }; return MatchingResults::new(rules_changed, important_rules_changed) } } let mut applicable_declarations = ApplicableDeclarationList::new(); let stylist = &context.shared.stylist; let style_attribute = self.style_attribute(); let map = &mut context.thread_local.selector_flags; let mut set_selector_flags = |element: &Self, flags: ElementSelectorFlags| { self.apply_selector_flags(map, element, flags); }; let rule_inclusion = if only_default_rules { RuleInclusion::DefaultOnly } else { RuleInclusion::All }; let bloom_filter = context.thread_local.bloom_filter.filter(); let mut matching_context = MatchingContext::new_for_visited(MatchingMode::Normal, Some(bloom_filter), visited_handling, context.shared.quirks_mode); { let smil_override = data.get_smil_override(); let animation_rules = if self.may_have_animations() { data.get_animation_rules() } else { AnimationRules(None, None) }; // Compute the primary rule node. stylist.push_applicable_declarations(self, implemented_pseudo.as_ref(), style_attribute, smil_override, animation_rules, rule_inclusion, &mut applicable_declarations, &mut matching_context, &mut set_selector_flags); } self.unset_dirty_style_attribute(); let primary_rule_node = stylist.rule_tree().compute_rule_node( &mut applicable_declarations, &context.shared.guards ); if log_enabled!(Trace) { trace!("Matched rules:"); for rn in primary_rule_node.self_and_ancestors() { if let Some(source) = rn.style_source() { trace!(" > {:?}", source); } } } let important_rules_changed = self.has_animations() && data.has_styles() && data.important_rules_are_different( &primary_rule_node, &context.shared.guards ); let rules_changed = match visited_handling { VisitedHandlingMode::AllLinksVisitedAndUnvisited => { unreachable!("We should never try to selector match with \ AllLinksVisitedAndUnvisited"); }, VisitedHandlingMode::AllLinksUnvisited => { data.set_primary_rules(primary_rule_node) }, VisitedHandlingMode::RelevantLinkVisited => { data.styles_mut().primary.set_visited_rules(primary_rule_node) }, }; MatchingResults::new_from_context(rules_changed, important_rules_changed, matching_context) } /// Runs selector matching to (re)compute eager pseudo-element rule nodes /// for this element. fn match_pseudos(&self, context: &mut StyleContext<Self>, data: &mut ElementData, visited_handling: VisitedHandlingMode) { debug!("Match pseudos for {:?}, visited: {:?}", self, visited_handling); if self.implemented_pseudo_element().is_some() { // Element pseudos can't have any other pseudo. return; } let mut applicable_declarations = ApplicableDeclarationList::new(); let map = &mut context.thread_local.selector_flags; let mut set_selector_flags = |element: &Self, flags: ElementSelectorFlags| { self.apply_selector_flags(map, element, flags); }; // Borrow the stuff we need here so the borrow checker doesn't get mad // at us later in the closure. let stylist = &context.shared.stylist; let guards = &context.shared.guards; let rule_inclusion = if context.shared.traversal_flags.for_default_styles() { RuleInclusion::DefaultOnly } else { RuleInclusion::All }; let bloom_filter = context.thread_local.bloom_filter.filter(); let mut matching_context = MatchingContext::new_for_visited(MatchingMode::ForStatelessPseudoElement, Some(bloom_filter), visited_handling, context.shared.quirks_mode); // Compute rule nodes for eagerly-cascaded pseudo-elements. let mut matches_different_pseudos = false; SelectorImpl::each_eagerly_cascaded_pseudo_element(|pseudo| { // For pseudo-elements, we only try to match visited rules if there // are also unvisited rules. (This matches Gecko's behavior.) if visited_handling == VisitedHandlingMode::RelevantLinkVisited && !data.styles().pseudos.has(&pseudo) { return } if !self.may_generate_pseudo(&pseudo, data.styles().primary.values()) { return; } debug_assert!(applicable_declarations.is_empty()); // NB: We handle animation rules for ::before and ::after when // traversing them. stylist.push_applicable_declarations(self, Some(&pseudo), None, None, AnimationRules(None, None), rule_inclusion, &mut applicable_declarations, &mut matching_context, &mut set_selector_flags); let pseudos = &mut data.styles_mut().pseudos; if !applicable_declarations.is_empty() { let rules = stylist.rule_tree().compute_rule_node( &mut applicable_declarations, &guards ); matches_different_pseudos |= pseudos.add_rules( &pseudo, visited_handling, rules ); } else { matches_different_pseudos |= pseudos.remove_rules( &pseudo, visited_handling ); } }); if matches_different_pseudos && data.restyle.is_restyle() { // Any changes to the matched pseudo-elements trigger // reconstruction. data.restyle.damage |= RestyleDamage::reconstruct(); } } /// Applies selector flags to an element, deferring mutations of the parent /// until after the traversal. /// /// TODO(emilio): This is somewhat inefficient, because of a variety of /// reasons: /// /// * It doesn't coalesce flags. /// * It doesn't look at flags already sent in a task for the main /// thread to process. /// * It doesn't take advantage of us knowing that the traversal is /// sequential. /// /// I suspect (need to measure!) that we don't use to set flags on /// a lot of different elements, but we could end up posting the same /// flag over and over with this approach. /// /// If the number of elements is low, perhaps a small cache with the /// flags already sent would be appropriate. /// /// The sequential task business for this is kind of sad :(. /// /// Anyway, let's do the obvious thing for now. fn apply_selector_flags(&self, map: &mut SelectorFlagsMap<Self>, element: &Self, flags: ElementSelectorFlags) { // Handle flags that apply to the element. let self_flags = flags.for_self(); if !self_flags.is_empty() { if element == self { // If this is the element we're styling, we have exclusive // access to the element, and thus it's fine inserting them, // even from the worker. unsafe { element.set_selector_flags(self_flags); } } else { // Otherwise, this element is an ancestor of the current element // we're styling, and thus multiple children could write to it // if we did from here. // // Instead, we can read them, and post them if necessary as a // sequential task in order for them to be processed later. if !element.has_selector_flags(self_flags) { map.insert_flags(*element, self_flags); } } } // Handle flags that apply to the parent. let parent_flags = flags.for_parent(); if !parent_flags.is_empty() { if let Some(p) = element.parent_element() { if !p.has_selector_flags(parent_flags) { map.insert_flags(p, parent_flags); } } } } /// Computes and applies restyle damage. fn accumulate_damage(&self, shared_context: &SharedStyleContext, restyle: &mut RestyleData, old_values: Option<&ComputedValues>, new_values: &Arc<ComputedValues>, pseudo: Option<&PseudoElement>) -> ChildCascadeRequirement { let old_values = match old_values { Some(v) => v, None => return ChildCascadeRequirement::MustCascadeChildren, }; // ::before and ::after are element-backed in Gecko, so they do the // damage calculation for themselves, when there's an actual pseudo. let is_existing_before_or_after = cfg!(feature = "gecko") && pseudo.map_or(false, |p| p.is_before_or_after()) && self.existing_style_for_restyle_damage(old_values, pseudo) .is_some(); if is_existing_before_or_after { return ChildCascadeRequirement::CanSkipCascade; } self.accumulate_damage_for(shared_context, restyle, old_values, new_values, pseudo) } /// Updates the rule nodes without re-running selector matching, using just /// the rule tree. /// /// Returns true if an !important rule was replaced. fn replace_rules( &self, replacements: RestyleHint, context: &StyleContext<Self>, data: &mut ElementData ) -> bool { let mut result = false; result |= self.replace_rules_internal(replacements, context, data, CascadeVisitedMode::Unvisited); if !context.shared.traversal_flags.for_animation_only() { result |= self.replace_rules_internal(replacements, context, data, CascadeVisitedMode::Visited); } result } /// Updates the rule nodes without re-running selector matching, using just /// the rule tree, for a specific visited mode. /// /// Returns true if an !important rule was replaced. fn replace_rules_internal( &self, replacements: RestyleHint, context: &StyleContext<Self>, data: &mut ElementData, cascade_visited: CascadeVisitedMode ) -> bool { use properties::PropertyDeclarationBlock; use shared_lock::Locked; debug_assert!(replacements.intersects(RestyleHint::replacements()) && (replacements & !RestyleHint::replacements()).is_empty()); let element_styles = &mut data.styles_mut(); let primary_rules = match cascade_visited.get_rules_mut(&mut element_styles.primary) { Some(r) => r, None => return false, }; let replace_rule_node = |level: CascadeLevel, pdb: Option<&Arc<Locked<PropertyDeclarationBlock>>>, path: &mut StrongRuleNode| -> bool { let new_node = context.shared.stylist.rule_tree() .update_rule_at_level(level, pdb, path, &context.shared.guards); match new_node { Some(n) => { *path = n; level.is_important() }, None => false, } }; if !context.shared.traversal_flags.for_animation_only() { let mut result = false; if replacements.contains(RESTYLE_STYLE_ATTRIBUTE) { let style_attribute = self.style_attribute(); result |= replace_rule_node(CascadeLevel::StyleAttributeNormal, style_attribute, primary_rules); result |= replace_rule_node(CascadeLevel::StyleAttributeImportant, style_attribute, primary_rules); self.unset_dirty_style_attribute(); } return result; } // Animation restyle hints are processed prior to other restyle // hints in the animation-only traversal. // // Non-animation restyle hints will be processed in a subsequent // normal traversal. if replacements.intersects(RestyleHint::for_animations()) { debug_assert!(context.shared.traversal_flags.for_animation_only()); if replacements.contains(RESTYLE_SMIL) { replace_rule_node(CascadeLevel::SMILOverride, self.get_smil_override(), primary_rules); } let replace_rule_node_for_animation = |level: CascadeLevel, primary_rules: &mut StrongRuleNode| { let animation_rule = self.get_animation_rule_by_cascade(level); replace_rule_node(level, animation_rule.as_ref(), primary_rules); }; // Apply Transition rules and Animation rules if the corresponding restyle hint // is contained. if replacements.contains(RESTYLE_CSS_TRANSITIONS) { replace_rule_node_for_animation(CascadeLevel::Transitions, primary_rules); } if replacements.contains(RESTYLE_CSS_ANIMATIONS) { replace_rule_node_for_animation(CascadeLevel::Animations, primary_rules); } } false } /// Given the old and new style of this element, and whether it's a /// pseudo-element, compute the restyle damage used to determine which /// kind of layout or painting operations we'll need. fn compute_style_difference(&self, old_values: &ComputedValues, new_values: &Arc<ComputedValues>, pseudo: Option<&PseudoElement>) -> StyleDifference { if let Some(source) = self.existing_style_for_restyle_damage(old_values, pseudo) { return RestyleDamage::compute_style_difference(source, new_values) } let new_style_is_display_none = new_values.get_box().clone_display() == display::T::none; let old_style_is_display_none = old_values.get_box().clone_display() == display::T::none; // If there's no style source, that likely means that Gecko couldn't // find a style context. // // This happens with display:none elements, and not-yet-existing // pseudo-elements. if new_style_is_display_none && old_style_is_display_none { // The style remains display:none. No need for damage. return StyleDifference::new(RestyleDamage::empty(), StyleChange::Unchanged) } if pseudo.map_or(false, |p| p.is_before_or_after()) { if (old_style_is_display_none || old_values.ineffective_content_property()) && (new_style_is_display_none || new_values.ineffective_content_property()) { // The pseudo-element will remain undisplayed, so just avoid // triggering any change. return StyleDifference::new(RestyleDamage::empty(), StyleChange::Unchanged) } return StyleDifference::new(RestyleDamage::reconstruct(), StyleChange::Changed) } // Something else. Be conservative for now. warn!("Reframing due to lack of old style source: {:?}, pseudo: {:?}", self, pseudo); // Something else. Be conservative for now. StyleDifference::new(RestyleDamage::reconstruct(), StyleChange::Changed) } /// Performs the cascade for the element's eager pseudos. fn cascade_pseudos(&self, context: &mut StyleContext<Self>, mut data: &mut ElementData, cascade_visited: CascadeVisitedMode) { debug!("Cascade pseudos for {:?}, visited: {:?}", self, cascade_visited); // Note that we've already set up the map of matching pseudo-elements // in match_pseudos (and handled the damage implications of changing // which pseudos match), so now we can just iterate what we have. This // does mean collecting owned pseudos, so that the borrow checker will // let us pass the mutable |data| to the cascade function. let matched_pseudos = data.styles().pseudos.keys(); for pseudo in matched_pseudos { self.cascade_eager_pseudo(context, data, &pseudo, cascade_visited); } } /// Returns computed values without animation and transition rules. fn get_base_style(&self, shared_context: &SharedStyleContext, font_metrics_provider: &FontMetricsProvider, primary_style: &ComputedStyle, pseudo_style: Option<&ComputedStyle>) -> Arc<ComputedValues> { let relevant_style = pseudo_style.unwrap_or(primary_style); let rule_node = &relevant_style.rules; let without_animation_rules = shared_context.stylist.rule_tree().remove_animation_rules(rule_node); if without_animation_rules == *rule_node { // Note that unwrapping here is fine, because the style is // only incomplete during the styling process. return relevant_style.values.as_ref().unwrap().clone(); } // This currently ignores visited styles, which seems acceptable, // as existing browsers don't appear to animate visited styles. self.cascade_with_rules(shared_context, font_metrics_provider, &without_animation_rules, primary_style, CascadeTarget::Normal, CascadeVisitedMode::Unvisited, None) } } impl<E: TElement> MatchMethods for E {}<|fim▁end|>
old_values.as_ref().map(|v| &**v),
<|file_name|>heuristics.py<|end_file_name|><|fim▁begin|>import polyglot import yaml class Heuristics (object): """ The Heuristics class receives a path to the file that is trying to be identified and an array of possible languages for that file. The disambiguate method will find the array with unambiguous strings of syntax for each language and check the file in question for those strings. If a match occurrs then the file is unquestionably written in the language that the string belongs to. If no match is found then None is returned and the file wasn't determined to be of a particular language.""" def __init__(self, path, possibleLanguages): self.syntaxFile = polyglot.Polyglot.tryOpenFile ('syntax.yml') # {language1: [bits_of_syntax1, bits_of_syntax2], language2: [bits_of_syntax3, bits_of_syntax4]} self.syntaxBits = yaml.safe_load (self.syntaxFile) self.disambiguate(path, possibleLanguages) def disambiguate(self, path, possibleLanguages): #checks the syntax strings of every possible language until it finds a match with open (path) as sourceCode: for lang in possibleLanguages: if lang not in self.syntaxBits.keys(): continue #there are no stored syntax strings for that language else: for string in self.syntaxBits [lang]: if string in sourceCode.read(): return lang<|fim▁hole|> sourceCode.seek (0) #re-reads from the beginning of the file return None<|fim▁end|>
<|file_name|>EntitySystemTest.java<|end_file_name|><|fim▁begin|>package com.artemis; import static org.junit.Assert.assertEquals; import java.util.NoSuchElementException; import com.artemis.systems.EntityProcessingSystem; import com.artemis.utils.IntBag; import org.junit.Test; import com.artemis.utils.ImmutableBag; /** * Created by obartley on 6/9/14. */ public class EntitySystemTest { @SuppressWarnings("static-method") @Test(expected = NoSuchElementException.class) public void test_process_one_inactive() { World w = new World(new WorldConfiguration() .setSystem(new IteratorTestSystem(0))); Entity e = w.createEntity(); e.edit().add(new C()); e.disable(); w.process(); } <|fim▁hole|> .setSystem(new IteratorTestSystem(1))); Entity e = w.createEntity(); e.edit().add(new C()); w.process(); } @Test public void aspect_exclude_only() { ExcludingSystem es1 = new ExcludingSystem(); EmptySystem es2 = new EmptySystem(); World w = new World(new WorldConfiguration() .setSystem(es1) .setSystem(es2)); Entity e = w.createEntity(); w.process(); assertEquals(1, es1.getActives().size()); assertEquals(1, es2.getActives().size()); } public static class C extends Component {} public static class C2 extends Component {} public static class IteratorTestSystem extends EntitySystem { public int expectedSize; @SuppressWarnings("unchecked") public IteratorTestSystem(int expectedSize) { super(Aspect.all(C.class)); this.expectedSize = expectedSize; } @Override protected void processSystem() { assertEquals(expectedSize, subscription.getEntities().size()); getActives().iterator().next(); } @Override protected boolean checkProcessing() { return true; } } public static class ExcludingSystem extends EntityProcessingSystem { public ExcludingSystem() { super(Aspect.exclude(C.class)); } @Override protected void process(Entity e) {} } public static class EmptySystem extends EntityProcessingSystem { public EmptySystem() { super(Aspect.all()); } @Override protected void process(Entity e) {} } }<|fim▁end|>
@SuppressWarnings("static-method") @Test public void test_process_one_active() { World w = new World(new WorldConfiguration()
<|file_name|>managers.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # This technical data was produced for the U. S. Government under Contract No. W15P7T-13-C-F600, and # is subject to the Rights in Technical Data-Noncommercial Items clause at DFARS 252.227-7013 (FEB 2012) from django.contrib.gis.db import models class AOIManager(models.GeoManager): def add_filters(self, **kwargs): """ Returns the queryset with new filters """ return super(AOIManager, self).get_query_set().filter(**kwargs) def unassigned(self): """ Returns unassigned AOIs. """ return self.add_filters(status='Unassigned') def assigned(self): """ Returns assigned AOIs. """ return self.add_filters(status='Assigned') def in_work(self): """ Returns AOIs in work. """ return self.add_filters(status='In Work') def submitted(self): """ Returns submitted AOIs. """ return self.add_filters(status='Submitted') def completed(self): """ Returns completed AOIs. """<|fim▁hole|><|fim▁end|>
return self.add_filters(status='Completed')
<|file_name|>error.rs<|end_file_name|><|fim▁begin|>extern crate clap; use std; use super::grammar; pub type Result<T> = std::result::Result<T, Error>; #[derive(Debug)] pub enum Error { AddrParse(std::net::AddrParseError), CLI(clap::Error), Env(std::env::VarError), IO(std::io::Error), Parse(grammar::ParseError), StringConversion(std::string::FromUtf8Error), InvalidArgument(String), ErrorResponse(String), BadResponse, Exec(i32, String), UnsupportedAction, AgentExists(String), UndeliverableMessage(String), Timeout, } impl From<clap::Error> for Error { fn from(err: clap::Error) -> Error { Error::CLI(err) } } impl From<std::io::Error> for Error { fn from(err: std::io::Error) -> Error { Error::IO(err) } } impl From<std::net::AddrParseError> for Error { fn from(err: std::net::AddrParseError) -> Error { Error::AddrParse(err) } } impl From<std::env::VarError> for Error { fn from(err: std::env::VarError) -> Error { Error::Env(err) } } impl From<grammar::ParseError> for Error { fn from(err: grammar::ParseError) -> Error { Error::Parse(err) } } impl From<std::string::FromUtf8Error> for Error { fn from(err: std::string::FromUtf8Error) -> Error { Error::StringConversion(err) } } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match *self {<|fim▁hole|> Error::Parse(ref err) => err.fmt(f), Error::StringConversion(ref err) => err.fmt(f), Error::InvalidArgument(ref msg) => write!(f, "invalid argument: {}", msg), Error::BadResponse => write!(f, "bad response"), Error::ErrorResponse(ref msg) => write!(f, "{}", msg), Error::Exec(code, ref stderr) => write!(f, "script exit code {}: {}", code, stderr), Error::UnsupportedAction => write!(f, "unsupported action"), Error::AgentExists(ref name) => write!(f, "agent {} already added", name), Error::UndeliverableMessage(ref dst) => write!(f, "undeliverable message: {}", dst), Error::Timeout => write!(f, "timeout"), } } } impl std::error::Error for Error { fn description(&self) -> &str { match *self { Error::AddrParse(ref err) => err.description(), Error::CLI(ref err) => err.description(), Error::Env(ref err) => err.description(), Error::IO(ref err) => err.description(), Error::Parse(ref err) => err.description(), Error::StringConversion(ref err) => err.description(), Error::InvalidArgument(ref msg) => msg, Error::BadResponse => "bad response", Error::ErrorResponse(ref msg) => msg, Error::Exec(_, ref stderr) => stderr, Error::UnsupportedAction => "unsupported action", Error::AgentExists(ref name) => name, Error::UndeliverableMessage(ref dst) => dst, Error::Timeout => "timeout", } } fn cause(&self) -> Option<&std::error::Error> { match *self { Error::AddrParse(ref err) => Some(err), Error::CLI(ref err) => Some(err), Error::Env(ref err) => Some(err), Error::IO(ref err) => Some(err), Error::Parse(ref err) => Some(err), Error::StringConversion(ref err) => Some(err), _ => None, } } } pub fn to_ioerror<E: std::error::Error>(e: E) -> std::io::Error { std::io::Error::new(std::io::ErrorKind::Other, e.description()) }<|fim▁end|>
Error::AddrParse(ref err) => err.fmt(f), Error::CLI(ref err) => err.fmt(f), Error::Env(ref err) => err.fmt(f), Error::IO(ref err) => err.fmt(f),
<|file_name|>gulpfile.js<|end_file_name|><|fim▁begin|>'use strict' var gulp = require('gulp') var $ = require('gulp-load-plugins')() gulp.task('default', function() { gulp.src('./src/**/*.js') .pipe($.wrap('!function(a,b){"function"==typeof define&&define.amd?define(b):"object"==typeof exports?module.exports=b(require,exports,module):a.audioWave=b()}(this,function(){<%= contents %>});'))<|fim▁hole|> .pipe($.uglify({ "mangle": true })) .pipe($.rename({ suffix: ".min" })) .pipe(gulp.dest('./dist')) .pipe(gulp.dest('./demo/js')) }) gulp.task('demo', $.serve('demo'))<|fim▁end|>
.pipe($.jsbeautifier({ config: '.jsbeautifyrc' })) .pipe(gulp.dest('./dist'))
<|file_name|>enums.go<|end_file_name|><|fim▁begin|>package features // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. // ChangeType enumerates the values for change type. type ChangeType string const ( // Create The resource does not exist in the current state but is present in the desired state. The // resource will be created when the deployment is executed. Create ChangeType = "Create" // Delete The resource exists in the current state and is missing from the desired state. The resource will // be deleted when the deployment is executed. Delete ChangeType = "Delete" // Deploy The resource exists in the current state and the desired state and will be redeployed when the // deployment is executed. The properties of the resource may or may not change. Deploy ChangeType = "Deploy" // Ignore The resource exists in the current state and is missing from the desired state. The resource will // not be deployed or modified when the deployment is executed. Ignore ChangeType = "Ignore" // Modify The resource exists in the current state and the desired state and will be redeployed when the // deployment is executed. The properties of the resource will change. Modify ChangeType = "Modify" // NoChange The resource exists in the current state and the desired state and will be redeployed when the<|fim▁hole|>) // PossibleChangeTypeValues returns an array of possible values for the ChangeType const type. func PossibleChangeTypeValues() []ChangeType { return []ChangeType{Create, Delete, Deploy, Ignore, Modify, NoChange} } // DeploymentMode enumerates the values for deployment mode. type DeploymentMode string const ( // Complete ... Complete DeploymentMode = "Complete" // Incremental ... Incremental DeploymentMode = "Incremental" ) // PossibleDeploymentModeValues returns an array of possible values for the DeploymentMode const type. func PossibleDeploymentModeValues() []DeploymentMode { return []DeploymentMode{Complete, Incremental} } // OnErrorDeploymentType enumerates the values for on error deployment type. type OnErrorDeploymentType string const ( // LastSuccessful ... LastSuccessful OnErrorDeploymentType = "LastSuccessful" // SpecificDeployment ... SpecificDeployment OnErrorDeploymentType = "SpecificDeployment" ) // PossibleOnErrorDeploymentTypeValues returns an array of possible values for the OnErrorDeploymentType const type. func PossibleOnErrorDeploymentTypeValues() []OnErrorDeploymentType { return []OnErrorDeploymentType{LastSuccessful, SpecificDeployment} } // PropertyChangeType enumerates the values for property change type. type PropertyChangeType string const ( // PropertyChangeTypeArray The property is an array and contains nested changes. PropertyChangeTypeArray PropertyChangeType = "Array" // PropertyChangeTypeCreate The property does not exist in the current state but is present in the desired // state. The property will be created when the deployment is executed. PropertyChangeTypeCreate PropertyChangeType = "Create" // PropertyChangeTypeDelete The property exists in the current state and is missing from the desired state. // It will be deleted when the deployment is executed. PropertyChangeTypeDelete PropertyChangeType = "Delete" // PropertyChangeTypeModify The property exists in both current and desired state and is different. The // value of the property will change when the deployment is executed. PropertyChangeTypeModify PropertyChangeType = "Modify" ) // PossiblePropertyChangeTypeValues returns an array of possible values for the PropertyChangeType const type. func PossiblePropertyChangeTypeValues() []PropertyChangeType { return []PropertyChangeType{PropertyChangeTypeArray, PropertyChangeTypeCreate, PropertyChangeTypeDelete, PropertyChangeTypeModify} } // ResourceIdentityType enumerates the values for resource identity type. type ResourceIdentityType string const ( // None ... None ResourceIdentityType = "None" // SystemAssigned ... SystemAssigned ResourceIdentityType = "SystemAssigned" // SystemAssignedUserAssigned ... SystemAssignedUserAssigned ResourceIdentityType = "SystemAssigned, UserAssigned" // UserAssigned ... UserAssigned ResourceIdentityType = "UserAssigned" ) // PossibleResourceIdentityTypeValues returns an array of possible values for the ResourceIdentityType const type. func PossibleResourceIdentityTypeValues() []ResourceIdentityType { return []ResourceIdentityType{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned} } // WhatIfResultFormat enumerates the values for what if result format. type WhatIfResultFormat string const ( // FullResourcePayloads ... FullResourcePayloads WhatIfResultFormat = "FullResourcePayloads" // ResourceIDOnly ... ResourceIDOnly WhatIfResultFormat = "ResourceIdOnly" ) // PossibleWhatIfResultFormatValues returns an array of possible values for the WhatIfResultFormat const type. func PossibleWhatIfResultFormatValues() []WhatIfResultFormat { return []WhatIfResultFormat{FullResourcePayloads, ResourceIDOnly} }<|fim▁end|>
// deployment is executed. The properties of the resource will not change. NoChange ChangeType = "NoChange"
<|file_name|>login_backend.py<|end_file_name|><|fim▁begin|>from .models import EmailUser class EmailOrPhoneModelBackend: def authenticate(self, username=None, password=None): if '@' in username: kwargs = {'email__iexact': username} else: kwargs = {'phone': username} try: user = EmailUser.objects.get(**kwargs) if user.check_password(password): return user except EmailUser.DoesNotExist: return None def get_user(self, user_id): try:<|fim▁hole|> except EmailUser.DoesNotExist: return None<|fim▁end|>
return EmailUser.objects.get(pk=user_id)
<|file_name|>__openerp__.py<|end_file_name|><|fim▁begin|>############################################################################### # # Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################### { 'name': 'Order BOM explode report', 'version': '0.1', 'category': 'Report', 'description': ''' Manage report for order product ''', 'author': 'Micronaet S.r.l. - Nicola Riolini', 'website': 'http://www.micronaet.it', 'license': 'AGPL-3', 'depends': [ 'base', 'product', 'sale', 'purchase', 'mrp', 'report_aeroo', 'order_bom', 'bom_category', 'inventory_field', # for inventory field 'bom_order_utility', # Utility for filter 'bom_dynamic_structured', # for filter type category 'textilene_status', # TODO remove when moved company parameters 'production_accounting_external', 'production_forecast_order', # for forecast check 'no_parcels_count', # exclude no parcels product 'product_last_supplier', # last purchase supplier data (for filter) ], 'init_xml': [], 'demo': [], 'data': [ #'security/xml_groups.xml',<|fim▁hole|> #'security/ir.model.access.csv', 'bom_explode_view.xml', 'report/explode_report.xml', 'wizard/report_component_status.xml', #'scheduler.xml', ], 'active': False, 'installable': True, 'auto_install': False, }<|fim▁end|>
<|file_name|>vue-form.js<|end_file_name|><|fim▁begin|>import Vue from 'vue'; import VueForm from 'vue-form'; Vue.use(VueForm, { validators: { 'step': function(value, stepValue) { return stepValue === `any` || Number(value) % Number(stepValue) === 0; }, 'data-exclusive-minimum': function(value, exclusiveMinimum) { return Number(value) > Number(exclusiveMinimum); }, 'data-exclusive-maximum': function(value, exclusiveMaximum) { return Number(value) < Number(exclusiveMaximum); }, 'complete-range': function(range) { return range === null || (range[0] !== null && range[1] !== null); }, 'valid-range': function(range) { if (range === null) { // allowed range return true; } if (range[0] === null || range[1] === null) { // let complete-range validator handle this return true; } if (Number.isNaN(range[0]) || Number.isNaN(range[1])) { // let number validator handle this return true; } return range[0] <= range[1]; }, 'categories-not-empty': function(categories) { return categories.length > 0; }, 'complete-dimensions': function(dimensions) { return dimensions === null || (dimensions[0] !== null && dimensions[1] !== null && dimensions[2] !== null); }, 'start-with-uppercase-or-number': function(value) { return /^[\dA-Z]/.test(value); }, 'no-mode-name': function(value) { return !/\bmode\b/i.test(value);<|fim▁hole|> if (/\bfine\b|\d+[\s_-]*bit/i.test(value)) { return false; } return !/\bLSB\b|\bMSB\b/.test(value); }, 'entity-complete': function(value, attributeValue, vnode) { const component = vnode.componentInstance; if (component.hasNumber) { return component.selectedNumber !== `` && component.selectedNumber !== null; } return true; }, 'entities-have-same-units': function(value, attributeValue, vnode) { return vnode.componentInstance.hasSameUnit; }, 'valid-color-hex-list': function(value) { return /^\s*#[\da-f]{6}(?:\s*,\s*#[\da-f]{6})*\s*$/i.test(value); }, 'max-file-size': function(file, attributeValue) { if (typeof file === `object`) { let maxSize = Number.parseInt(attributeValue, 10); if (attributeValue.includes(`M`)) { maxSize *= 1000 * 1000; } else if (attributeValue.includes(`k`)) { maxSize *= 1000; } return file.size <= maxSize; } return true; }, }, });<|fim▁end|>
}, 'no-fine-channel-name': function(value) {
<|file_name|>RedirectUtil.java<|end_file_name|><|fim▁begin|>/* * oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2014, Gluu */ package org.gluu.oxauth.util;<|fim▁hole|> import org.gluu.oxauth.model.common.ResponseMode; import org.jboss.resteasy.specimpl.ResponseBuilderImpl; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import java.net.MalformedURLException; import java.net.URI; import static org.gluu.oxauth.client.AuthorizationRequest.NO_REDIRECT_HEADER; /** * @version October 7, 2019 */ public class RedirectUtil { private final static Logger log = LoggerFactory.getLogger(RedirectUtil.class); static String JSON_REDIRECT_PROPNAME = "redirect"; static int HTTP_REDIRECT = 302; public static ResponseBuilder getRedirectResponseBuilder(RedirectUri redirectUriResponse, HttpServletRequest httpRequest) { ResponseBuilder builder; if (httpRequest != null && httpRequest.getHeader(NO_REDIRECT_HEADER) != null) { try { URI redirectURI = URI.create(redirectUriResponse.toString()); JSONObject jsonObject = new JSONObject(); jsonObject.put(JSON_REDIRECT_PROPNAME, redirectURI.toURL()); String jsonResp = jsonObject.toString(); jsonResp = jsonResp.replace("\\/", "/"); builder = Response.ok( new GenericEntity<String>(jsonResp, String.class), MediaType.APPLICATION_JSON_TYPE ); } catch (MalformedURLException e) { builder = Response.serverError(); log.debug(e.getMessage(), e); } catch (JSONException e) { builder = Response.serverError(); log.debug(e.getMessage(), e); } } else if (redirectUriResponse.getResponseMode() != ResponseMode.FORM_POST) { URI redirectURI = URI.create(redirectUriResponse.toString()); builder = new ResponseBuilderImpl(); builder = Response.status(HTTP_REDIRECT); builder.location(redirectURI); } else { builder = new ResponseBuilderImpl(); builder.status(Response.Status.OK); builder.type(MediaType.TEXT_HTML_TYPE); builder.cacheControl(CacheControl.valueOf("no-cache, no-store")); builder.header("Pragma", "no-cache"); builder.entity(redirectUriResponse.toString()); } return builder; } }<|fim▁end|>
<|file_name|>html_elems.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ /*************************************************************************** Name : DB Manager<|fim▁hole|>Date : May 23, 2011 copyright : (C) 2011 by Giuseppe Sucameli email : [email protected] ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ """ from builtins import str from builtins import object class HtmlContent(object): def __init__(self, data): self.data = data if not isinstance(data, HtmlContent) else data.data def toHtml(self): if isinstance(self.data, list) or isinstance(self.data, tuple): html = u'' for item in self.data: html += HtmlContent(item).toHtml() return html if hasattr(self.data, 'toHtml'): return self.data.toHtml() html = str(self.data).replace("\n", "<br>") return html def hasContents(self): if isinstance(self.data, list) or isinstance(self.data, tuple): empty = True for item in self.data: if item.hasContents(): empty = False break return not empty if hasattr(self.data, 'hasContents'): return self.data.hasContents() return len(self.data) > 0 class HtmlElem(object): def __init__(self, tag, data, attrs=None): self.tag = tag self.data = data if isinstance(data, HtmlContent) else HtmlContent(data) self.attrs = attrs if attrs is not None else dict() if 'tag' in self.attrs: self.setTag(self.attrs['tag']) del self.attrs['tag'] def setTag(self, tag): self.tag = tag def getOriginalData(self): return self.data.data def setAttr(self, name, value): self.attrs[name] = value def getAttrsHtml(self): html = u'' for k, v in self.attrs.items(): html += u' %s="%s"' % (k, v) return html def openTagHtml(self): return u"<%s%s>" % (self.tag, self.getAttrsHtml()) def closeTagHtml(self): return u"</%s>" % self.tag def toHtml(self): return u"%s%s%s" % (self.openTagHtml(), self.data.toHtml(), self.closeTagHtml()) def hasContents(self): return self.data.toHtml() != "" class HtmlParagraph(HtmlElem): def __init__(self, data, attrs=None): HtmlElem.__init__(self, 'p', data, attrs) class HtmlListItem(HtmlElem): def __init__(self, data, attrs=None): HtmlElem.__init__(self, 'li', data, attrs) class HtmlList(HtmlElem): def __init__(self, items, attrs=None): # make sure to have HtmlListItem items items = list(items) for i, item in enumerate(items): if not isinstance(item, HtmlListItem): items[i] = HtmlListItem(item) HtmlElem.__init__(self, 'ul', items, attrs) class HtmlTableCol(HtmlElem): def __init__(self, data, attrs=None): HtmlElem.__init__(self, 'td', data, attrs) def closeTagHtml(self): # FIX INVALID BEHAVIOR: an empty cell as last table's cell break margins return u"&nbsp;%s" % HtmlElem.closeTagHtml(self) class HtmlTableRow(HtmlElem): def __init__(self, cols, attrs=None): # make sure to have HtmlTableCol items cols = list(cols) for i, c in enumerate(cols): if not isinstance(c, HtmlTableCol): cols[i] = HtmlTableCol(c) HtmlElem.__init__(self, 'tr', cols, attrs) class HtmlTableHeader(HtmlTableRow): def __init__(self, cols, attrs=None): HtmlTableRow.__init__(self, cols, attrs) for c in self.getOriginalData(): c.setTag('th') class HtmlTable(HtmlElem): def __init__(self, rows, attrs=None): # make sure to have HtmlTableRow items rows = list(rows) for i, r in enumerate(rows): if not isinstance(r, HtmlTableRow): rows[i] = HtmlTableRow(r) HtmlElem.__init__(self, 'table', rows, attrs) class HtmlWarning(HtmlContent): def __init__(self, data): data = ['<img src=":/icons/warning-20px.png">&nbsp;&nbsp; ', data] HtmlContent.__init__(self, data) class HtmlSection(HtmlContent): def __init__(self, title, content=None): data = ['<div class="section"><h2>', title, '</h2>'] if content is not None: data.extend(['<div>', content, '</div>']) data.append('</div>') HtmlContent.__init__(self, data)<|fim▁end|>
Description : Database manager plugin for QGIS
<|file_name|>applications_health_evaluation.py<|end_file_name|><|fim▁begin|># coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- <|fim▁hole|> class ApplicationsHealthEvaluation(HealthEvaluation): """Represents health evaluation for applications, containing health evaluations for each unhealthy application that impacted current aggregated health state. :param aggregated_health_state: Possible values include: 'Invalid', 'Ok', 'Warning', 'Error', 'Unknown' :type aggregated_health_state: str or :class:`enum <azure.servicefabric.models.enum>` :param description: Description of the health evaluation, which represents a summary of the evaluation process. :type description: str :param kind: Polymorphic Discriminator :type kind: str :param max_percent_unhealthy_applications: Maximum allowed percentage of unhealthy applications from the ClusterHealthPolicy. :type max_percent_unhealthy_applications: int :param total_count: Total number of applications from the health store. :type total_count: long :param unhealthy_evaluations: :type unhealthy_evaluations: list of :class:`HealthEvaluationWrapper <azure.servicefabric.models.HealthEvaluationWrapper>` """ _validation = { 'kind': {'required': True}, } _attribute_map = { 'aggregated_health_state': {'key': 'AggregatedHealthState', 'type': 'str'}, 'description': {'key': 'Description', 'type': 'str'}, 'kind': {'key': 'Kind', 'type': 'str'}, 'max_percent_unhealthy_applications': {'key': 'MaxPercentUnhealthyApplications', 'type': 'int'}, 'total_count': {'key': 'TotalCount', 'type': 'long'}, 'unhealthy_evaluations': {'key': 'UnhealthyEvaluations', 'type': '[HealthEvaluationWrapper]'}, } def __init__(self, aggregated_health_state=None, description=None, max_percent_unhealthy_applications=None, total_count=None, unhealthy_evaluations=None): super(ApplicationsHealthEvaluation, self).__init__(aggregated_health_state=aggregated_health_state, description=description) self.max_percent_unhealthy_applications = max_percent_unhealthy_applications self.total_count = total_count self.unhealthy_evaluations = unhealthy_evaluations self.kind = 'Applications'<|fim▁end|>
from .health_evaluation import HealthEvaluation
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.shortcuts import render<|fim▁hole|> def index(request): context = {} return render(request, 'waterfall_wall/index.html', context) class ImageViewSet(viewsets.ModelViewSet): """ API endpoint that allows images to be viewed. """ queryset = Image.objects.all() serializer_class = ImageSerializer<|fim▁end|>
from rest_framework import viewsets from waterfall_wall.serializers import ImageSerializer from waterfall_wall.models import Image
<|file_name|>test_tile.py<|end_file_name|><|fim▁begin|>from core_tests_base import CoreTestsBase, FakeTessagon, FakeTileSubClass class TestTile(CoreTestsBase): # Note: these tests are highly dependent on the behavior of # FakeTessagon and FakeAdaptor def test_add_vert(self): tessagon = FakeTessagon() tile = FakeTileSubClass(tessagon, u_range=[0.5, 1.0], v_range=[2.5, 3.0]) tile.add_vert(['top', 'left'], 0.25, 0.75) assert tile.blend(0.25, 0.75) == [0.625, 2.875] # One vert added assert tile.verts['top']['left'] == tile.f(0.625, 2.875) assert tile.verts['top']['right'] is None assert tile.verts['bottom']['left'] is None assert tile.verts['bottom']['right'] is None def test_add_vert_u_symmetric(self): tessagon = FakeTessagon() tile = FakeTileSubClass(tessagon, u_range=[0.5, 1.0], v_range=[2.5, 3.0], u_symmetric=True) tile.add_vert(['top', 'left'], 0.25, 0.75)<|fim▁hole|> # [0.75, 0.75] is reflection of [0.25, 0.75] in U direction assert tile.blend(0.75, 0.75) == [0.875, 2.875] # Two verts added assert tile.verts['top']['left'] == tile.f(0.625, 2.875) assert tile.verts['top']['right'] == tile.f(0.875, 2.875) assert tile.verts['bottom']['left'] is None assert tile.verts['bottom']['right'] is None def test_add_vert_v_symmetric(self): tessagon = FakeTessagon() tile = FakeTileSubClass(tessagon, u_range=[0.5, 1.0], v_range=[2.5, 3.0], v_symmetric=True) tile.add_vert(['top', 'left'], 0.25, 0.75) # [0.25, 0.25] is reflection of [0.25, 0.75] in V direction assert tile.blend(0.25, 0.25) == [0.625, 2.625] # Two verts added assert tile.verts['top']['left'] == tile.f(0.625, 2.875) assert tile.verts['top']['right'] is None assert tile.verts['bottom']['left'] == tile.f(0.625, 2.625) assert tile.verts['bottom']['right'] is None def test_add_vert_u_v_symmetric(self): tessagon = FakeTessagon() tile = FakeTileSubClass(tessagon, u_range=[0.5, 1.0], v_range=[2.5, 3.0], u_symmetric=True, v_symmetric=True) tile.add_vert(['top', 'left'], 0.25, 0.75) # [0.75, 0.25] is reflection of [0.25, 0.75] in U and V directions assert tile.blend(0.75, 0.25) == [0.875, 2.625] # Four verts added assert tile.verts['top']['left'] == tile.f(0.625, 2.875) assert tile.verts['top']['right'] == tile.f(0.875, 2.875) assert tile.verts['bottom']['left'] == tile.f(0.625, 2.625) assert tile.verts['bottom']['right'] == tile.f(0.875, 2.625)<|fim▁end|>
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># coding: utf-8 from collections import namedtuple from pandas.io.msgpack.exceptions import * # noqa from pandas.io.msgpack._version import version # noqa class ExtType(namedtuple("ExtType", "code data")): """ExtType represents ext type in msgpack.""" def __new__(cls, code, data): if not isinstance(code, int): raise TypeError("code must be int") if not isinstance(data, bytes): raise TypeError("data must be bytes")<|fim▁hole|> return super().__new__(cls, code, data) import os # noqa from pandas.io.msgpack._packer import Packer # noqa from pandas.io.msgpack._unpacker import unpack, unpackb, Unpacker # noqa def pack(o, stream, **kwargs): """ Pack object `o` and write it to `stream` See :class:`Packer` for options. """ packer = Packer(**kwargs) stream.write(packer.pack(o)) def packb(o, **kwargs): """ Pack object `o` and return packed bytes See :class:`Packer` for options. """ return Packer(**kwargs).pack(o) # alias for compatibility to simplejson/marshal/pickle. load = unpack loads = unpackb dump = pack dumps = packb<|fim▁end|>
if not 0 <= code <= 127: raise ValueError("code must be 0~127")
<|file_name|>FastMixerState.cpp<|end_file_name|><|fim▁begin|>/* * Copyright (C) 2012 The Android Open Source Project *<|fim▁hole|> * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "FastMixerState.h" namespace android { FastTrack::FastTrack() : mBufferProvider(NULL), mVolumeProvider(NULL), mSampleRate(0), mChannelMask(AUDIO_CHANNEL_OUT_STEREO), mGeneration(0) { } FastTrack::~FastTrack() { } FastMixerState::FastMixerState() : mFastTracksGen(0), mTrackMask(0), mOutputSink(NULL), mOutputSinkGen(0), mFrameCount(0), mCommand(INITIAL), mColdFutexAddr(NULL), mColdGen(0), mDumpState(NULL), mTeeSink(NULL) { } FastMixerState::~FastMixerState() { } } // namespace android<|fim▁end|>
* Licensed under the Apache License, Version 2.0 (the "License");
<|file_name|>ssh.py<|end_file_name|><|fim▁begin|># (c) 2012, Michael DeHaan <[email protected]> # Copyright 2015 Abhijit Menon-Sen <[email protected]> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # from __future__ import (absolute_import, division, print_function) __metaclass__ = type import errno import fcntl import os import pipes import pty import select import subprocess import time from ansible import constants as C from ansible.compat.six import PY3, text_type, binary_type from ansible.errors import AnsibleError, AnsibleConnectionFailure, AnsibleFileNotFound from ansible.errors import AnsibleOptionsError from ansible.module_utils.basic import BOOLEANS from ansible.module_utils._text import to_bytes, to_native, to_text from ansible.plugins.connection import ConnectionBase from ansible.utils.boolean import boolean from ansible.utils.path import unfrackpath, makedirs_safe try: from __main__ import display except ImportError: from ansible.utils.display import Display display = Display() SSHPASS_AVAILABLE = None class Connection(ConnectionBase): ''' ssh based connections ''' transport = 'ssh' has_pipelining = True become_methods = frozenset(C.BECOME_METHODS).difference(['runas']) def __init__(self, *args, **kwargs): super(Connection, self).__init__(*args, **kwargs) self.host = self._play_context.remote_addr # The connection is created by running ssh/scp/sftp from the exec_command, # put_file, and fetch_file methods, so we don't need to do any connection # management here. def _connect(self): return self @staticmethod def _sshpass_available(): global SSHPASS_AVAILABLE # We test once if sshpass is available, and remember the result. It # would be nice to use distutils.spawn.find_executable for this, but # distutils isn't always available; shutils.which() is Python3-only. if SSHPASS_AVAILABLE is None: try: p = subprocess.Popen(["sshpass"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.communicate() SSHPASS_AVAILABLE = True except OSError: SSHPASS_AVAILABLE = False return SSHPASS_AVAILABLE @staticmethod def _persistence_controls(b_command): ''' Takes a command array and scans it for ControlPersist and ControlPath settings and returns two booleans indicating whether either was found. This could be smarter, e.g. returning false if ControlPersist is 'no', but for now we do it simple way. ''' controlpersist = False controlpath = False for b_arg in (a.lower() for a in b_command): if b'controlpersist' in b_arg: controlpersist = True elif b'controlpath' in b_arg: controlpath = True return controlpersist, controlpath def _add_args(self, b_command, b_args, explanation): """ Adds arguments to the ssh command and displays a caller-supplied explanation of why. <|fim▁hole|> StringIO would not) :arg explanation: A text string containing explaining why the arguments were added. It will be displayed with a high enough verbosity. .. note:: This function does its work via side-effect. The b_command list has the new arguments appended. """ display.vvvvv(u'SSH: %s: (%s)' % (explanation, ')('.join(to_text(a) for a in b_args)), host=self._play_context.remote_addr) b_command += b_args def _build_command(self, binary, *other_args): ''' Takes a binary (ssh, scp, sftp) and optional extra arguments and returns a command line as an array that can be passed to subprocess.Popen. ''' b_command = [] # # First, the command to invoke # # If we want to use password authentication, we have to set up a pipe to # write the password to sshpass. if self._play_context.password: if not self._sshpass_available(): raise AnsibleError("to use the 'ssh' connection type with passwords, you must install the sshpass program") self.sshpass_pipe = os.pipe() b_command += [b'sshpass', b'-d' + to_bytes(self.sshpass_pipe[0], nonstring='simplerepr', errors='surrogate_or_strict')] b_command += [to_bytes(binary, errors='surrogate_or_strict')] # # Next, additional arguments based on the configuration. # # sftp batch mode allows us to correctly catch failed transfers, but can # be disabled if the client side doesn't support the option. However, # sftp batch mode does not prompt for passwords so it must be disabled # if not using controlpersist and using sshpass if binary == 'sftp' and C.DEFAULT_SFTP_BATCH_MODE: if self._play_context.password: b_args = [b'-o', b'BatchMode=no'] self._add_args(b_command, b_args, u'disable batch mode for sshpass') b_command += [b'-b', b'-'] if self._play_context.verbosity > 3: b_command.append(b'-vvv') # # Next, we add [ssh_connection]ssh_args from ansible.cfg. # if self._play_context.ssh_args: b_args = [to_bytes(a, errors='surrogate_or_strict') for a in self._split_ssh_args(self._play_context.ssh_args)] self._add_args(b_command, b_args, u"ansible.cfg set ssh_args") # Now we add various arguments controlled by configuration file settings # (e.g. host_key_checking) or inventory variables (ansible_ssh_port) or # a combination thereof. if not C.HOST_KEY_CHECKING: b_args = (b"-o", b"StrictHostKeyChecking=no") self._add_args(b_command, b_args, u"ANSIBLE_HOST_KEY_CHECKING/host_key_checking disabled") if self._play_context.port is not None: b_args = (b"-o", b"Port=" + to_bytes(self._play_context.port, nonstring='simplerepr', errors='surrogate_or_strict')) self._add_args(b_command, b_args, u"ANSIBLE_REMOTE_PORT/remote_port/ansible_port set") key = self._play_context.private_key_file if key: b_args = (b"-o", b'IdentityFile="' + to_bytes(os.path.expanduser(key), errors='surrogate_or_strict') + b'"') self._add_args(b_command, b_args, u"ANSIBLE_PRIVATE_KEY_FILE/private_key_file/ansible_ssh_private_key_file set") if not self._play_context.password: self._add_args( b_command, ( b"-o", b"KbdInteractiveAuthentication=no", b"-o", b"PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey", b"-o", b"PasswordAuthentication=no" ), u"ansible_password/ansible_ssh_pass not set" ) user = self._play_context.remote_user if user: self._add_args(b_command, (b"-o", b"User=" + to_bytes(self._play_context.remote_user, errors='surrogate_or_strict')), u"ANSIBLE_REMOTE_USER/remote_user/ansible_user/user/-u set" ) self._add_args(b_command, (b"-o", b"ConnectTimeout=" + to_bytes(self._play_context.timeout, errors='surrogate_or_strict', nonstring='simplerepr')), u"ANSIBLE_TIMEOUT/timeout set" ) # Add in any common or binary-specific arguments from the PlayContext # (i.e. inventory or task settings or overrides on the command line). for opt in (u'ssh_common_args', u'{0}_extra_args'.format(binary)): attr = getattr(self._play_context, opt, None) if attr is not None: b_args = [to_bytes(a, errors='surrogate_or_strict') for a in self._split_ssh_args(attr)] self._add_args(b_command, b_args, u"PlayContext set %s" % opt) # Check if ControlPersist is enabled and add a ControlPath if one hasn't # already been set. controlpersist, controlpath = self._persistence_controls(b_command) if controlpersist: self._persistent = True if not controlpath: cpdir = unfrackpath(C.ANSIBLE_SSH_CONTROL_PATH_DIR) b_cpdir = to_bytes(cpdir, errors='surrogate_or_strict') # The directory must exist and be writable. makedirs_safe(b_cpdir, 0o700) if not os.access(b_cpdir, os.W_OK): raise AnsibleError("Cannot write to ControlPath %s" % to_native(cpdir)) b_args = (b"-o", b"ControlPath=" + to_bytes(C.ANSIBLE_SSH_CONTROL_PATH % dict(directory=cpdir), errors='surrogate_or_strict')) self._add_args(b_command, b_args, u"found only ControlPersist; added ControlPath") # Finally, we add any caller-supplied extras. if other_args: b_command += [to_bytes(a) for a in other_args] return b_command def _send_initial_data(self, fh, in_data): ''' Writes initial data to the stdin filehandle of the subprocess and closes it. (The handle must be closed; otherwise, for example, "sftp -b -" will just hang forever waiting for more commands.) ''' display.debug('Sending initial data') try: fh.write(to_bytes(in_data)) fh.close() except (OSError, IOError): raise AnsibleConnectionFailure('SSH Error: data could not be sent to the remote host. Make sure this host can be reached over ssh') display.debug('Sent initial data (%d bytes)' % len(in_data)) # Used by _run() to kill processes on failures @staticmethod def _terminate_process(p): """ Terminate a process, ignoring errors """ try: p.terminate() except (OSError, IOError): pass # This is separate from _run() because we need to do the same thing for stdout # and stderr. def _examine_output(self, source, state, b_chunk, sudoable): ''' Takes a string, extracts complete lines from it, tests to see if they are a prompt, error message, etc., and sets appropriate flags in self. Prompt and success lines are removed. Returns the processed (i.e. possibly-edited) output and the unprocessed remainder (to be processed with the next chunk) as strings. ''' output = [] for b_line in b_chunk.splitlines(True): display_line = to_text(b_line).rstrip('\r\n') suppress_output = False #display.debug("Examining line (source=%s, state=%s): '%s'" % (source, state, display_line)) if self._play_context.prompt and self.check_password_prompt(b_line): display.debug("become_prompt: (source=%s, state=%s): '%s'" % (source, state, display_line)) self._flags['become_prompt'] = True suppress_output = True elif self._play_context.success_key and self.check_become_success(b_line): display.debug("become_success: (source=%s, state=%s): '%s'" % (source, state, display_line)) self._flags['become_success'] = True suppress_output = True elif sudoable and self.check_incorrect_password(b_line): display.debug("become_error: (source=%s, state=%s): '%s'" % (source, state, display_line)) self._flags['become_error'] = True elif sudoable and self.check_missing_password(b_line): display.debug("become_nopasswd_error: (source=%s, state=%s): '%s'" % (source, state, display_line)) self._flags['become_nopasswd_error'] = True if not suppress_output: output.append(b_line) # The chunk we read was most likely a series of complete lines, but just # in case the last line was incomplete (and not a prompt, which we would # have removed from the output), we retain it to be processed with the # next chunk. remainder = b'' if output and not output[-1].endswith(b'\n'): remainder = output[-1] output = output[:-1] return b''.join(output), remainder def _run(self, cmd, in_data, sudoable=True, checkrc=True): ''' Starts the command and communicates with it until it ends. ''' display_cmd = list(map(pipes.quote, map(to_text, cmd))) display.vvv(u'SSH: EXEC {0}'.format(u' '.join(display_cmd)), host=self.host) # Start the given command. If we don't need to pipeline data, we can try # to use a pseudo-tty (ssh will have been invoked with -tt). If we are # pipelining data, or can't create a pty, we fall back to using plain # old pipes. p = None if isinstance(cmd, (text_type, binary_type)): cmd = to_bytes(cmd) else: cmd = list(map(to_bytes, cmd)) if not in_data: try: # Make sure stdin is a proper pty to avoid tcgetattr errors master, slave = pty.openpty() if PY3 and self._play_context.password: p = subprocess.Popen(cmd, stdin=slave, stdout=subprocess.PIPE, stderr=subprocess.PIPE, pass_fds=self.sshpass_pipe) else: p = subprocess.Popen(cmd, stdin=slave, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdin = os.fdopen(master, 'wb', 0) os.close(slave) except (OSError, IOError): p = None if not p: if PY3 and self._play_context.password: p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, pass_fds=self.sshpass_pipe) else: p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdin = p.stdin # If we are using SSH password authentication, write the password into # the pipe we opened in _build_command. if self._play_context.password: os.close(self.sshpass_pipe[0]) try: os.write(self.sshpass_pipe[1], to_bytes(self._play_context.password) + b'\n') except OSError as e: # Ignore broken pipe errors if the sshpass process has exited. if e.errno != errno.EPIPE or p.poll() is None: raise os.close(self.sshpass_pipe[1]) # # SSH state machine # # Now we read and accumulate output from the running process until it # exits. Depending on the circumstances, we may also need to write an # escalation password and/or pipelined input to the process. states = [ 'awaiting_prompt', 'awaiting_escalation', 'ready_to_send', 'awaiting_exit' ] # Are we requesting privilege escalation? Right now, we may be invoked # to execute sftp/scp with sudoable=True, but we can request escalation # only when using ssh. Otherwise we can send initial data straightaway. state = states.index('ready_to_send') if b'ssh' in cmd: if self._play_context.prompt: # We're requesting escalation with a password, so we have to # wait for a password prompt. state = states.index('awaiting_prompt') display.debug(u'Initial state: %s: %s' % (states[state], self._play_context.prompt)) elif self._play_context.become and self._play_context.success_key: # We're requesting escalation without a password, so we have to # detect success/failure before sending any initial data. state = states.index('awaiting_escalation') display.debug(u'Initial state: %s: %s' % (states[state], self._play_context.success_key)) # We store accumulated stdout and stderr output from the process here, # but strip any privilege escalation prompt/confirmation lines first. # Output is accumulated into tmp_*, complete lines are extracted into # an array, then checked and removed or copied to stdout or stderr. We # set any flags based on examining the output in self._flags. b_stdout = b_stderr = b'' b_tmp_stdout = b_tmp_stderr = b'' self._flags = dict( become_prompt=False, become_success=False, become_error=False, become_nopasswd_error=False ) # select timeout should be longer than the connect timeout, otherwise # they will race each other when we can't connect, and the connect # timeout usually fails timeout = 2 + self._play_context.timeout rpipes = [p.stdout, p.stderr] for fd in rpipes: fcntl.fcntl(fd, fcntl.F_SETFL, fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK) # If we can send initial data without waiting for anything, we do so # before we call select. if states[state] == 'ready_to_send' and in_data: self._send_initial_data(stdin, in_data) state += 1 while True: rfd, wfd, efd = select.select(rpipes, [], [], timeout) # We pay attention to timeouts only while negotiating a prompt. if not rfd: if state <= states.index('awaiting_escalation'): # If the process has already exited, then it's not really a # timeout; we'll let the normal error handling deal with it. if p.poll() is not None: break self._terminate_process(p) raise AnsibleError('Timeout (%ds) waiting for privilege escalation prompt: %s' % (timeout, to_native(b_stdout))) # Read whatever output is available on stdout and stderr, and stop # listening to the pipe if it's been closed. if p.stdout in rfd: b_chunk = p.stdout.read() if b_chunk == b'': rpipes.remove(p.stdout) # When ssh has ControlMaster (+ControlPath/Persist) enabled, the # first connection goes into the background and we never see EOF # on stderr. If we see EOF on stdout, lower the select timeout # to reduce the time wasted selecting on stderr if we observe # that the process has not yet existed after this EOF. Otherwise # we may spend a long timeout period waiting for an EOF that is # not going to arrive until the persisted connection closes. timeout = 1 b_tmp_stdout += b_chunk display.debug("stdout chunk (state=%s):\n>>>%s<<<\n" % (state, to_text(b_chunk))) if p.stderr in rfd: b_chunk = p.stderr.read() if b_chunk == b'': rpipes.remove(p.stderr) b_tmp_stderr += b_chunk display.debug("stderr chunk (state=%s):\n>>>%s<<<\n" % (state, to_text(b_chunk))) # We examine the output line-by-line until we have negotiated any # privilege escalation prompt and subsequent success/error message. # Afterwards, we can accumulate output without looking at it. if state < states.index('ready_to_send'): if b_tmp_stdout: b_output, b_unprocessed = self._examine_output('stdout', states[state], b_tmp_stdout, sudoable) b_stdout += b_output b_tmp_stdout = b_unprocessed if b_tmp_stderr: b_output, b_unprocessed = self._examine_output('stderr', states[state], b_tmp_stderr, sudoable) b_stderr += b_output b_tmp_stderr = b_unprocessed else: b_stdout += b_tmp_stdout b_stderr += b_tmp_stderr b_tmp_stdout = b_tmp_stderr = b'' # If we see a privilege escalation prompt, we send the password. # (If we're expecting a prompt but the escalation succeeds, we # didn't need the password and can carry on regardless.) if states[state] == 'awaiting_prompt': if self._flags['become_prompt']: display.debug('Sending become_pass in response to prompt') stdin.write(to_bytes(self._play_context.become_pass) + b'\n') self._flags['become_prompt'] = False state += 1 elif self._flags['become_success']: state += 1 # We've requested escalation (with or without a password), now we # wait for an error message or a successful escalation. if states[state] == 'awaiting_escalation': if self._flags['become_success']: display.debug('Escalation succeeded') self._flags['become_success'] = False state += 1 elif self._flags['become_error']: display.debug('Escalation failed') self._terminate_process(p) self._flags['become_error'] = False raise AnsibleError('Incorrect %s password' % self._play_context.become_method) elif self._flags['become_nopasswd_error']: display.debug('Escalation requires password') self._terminate_process(p) self._flags['become_nopasswd_error'] = False raise AnsibleError('Missing %s password' % self._play_context.become_method) elif self._flags['become_prompt']: # This shouldn't happen, because we should see the "Sorry, # try again" message first. display.debug('Escalation prompt repeated') self._terminate_process(p) self._flags['become_prompt'] = False raise AnsibleError('Incorrect %s password' % self._play_context.become_method) # Once we're sure that the privilege escalation prompt, if any, has # been dealt with, we can send any initial data and start waiting # for output. if states[state] == 'ready_to_send': if in_data: self._send_initial_data(stdin, in_data) state += 1 # Now we're awaiting_exit: has the child process exited? If it has, # and we've read all available output from it, we're done. if p.poll() is not None: if not rpipes or not rfd: break # We should not see further writes to the stdout/stderr file # descriptors after the process has closed, set the select # timeout to gather any last writes we may have missed. timeout = 0 continue # If the process has not yet exited, but we've already read EOF from # its stdout and stderr (and thus removed both from rpipes), we can # just wait for it to exit. elif not rpipes: p.wait() break # Otherwise there may still be outstanding data to read. # close stdin after process is terminated and stdout/stderr are read # completely (see also issue #848) stdin.close() if C.HOST_KEY_CHECKING: if cmd[0] == b"sshpass" and p.returncode == 6: raise AnsibleError('Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this. Please add this host\'s fingerprint to your known_hosts file to manage this host.') controlpersisterror = b'Bad configuration option: ControlPersist' in b_stderr or b'unknown configuration option: ControlPersist' in b_stderr if p.returncode != 0 and controlpersisterror: raise AnsibleError('using -c ssh on certain older ssh versions may not support ControlPersist, set ANSIBLE_SSH_ARGS="" (or ssh_args in [ssh_connection] section of the config file) before running again') if p.returncode == 255 and in_data and checkrc: raise AnsibleConnectionFailure('SSH Error: data could not be sent to the remote host. Make sure this host can be reached over ssh') return (p.returncode, b_stdout, b_stderr) def _exec_command(self, cmd, in_data=None, sudoable=True): ''' run a command on the remote host ''' super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable) display.vvv(u"ESTABLISH SSH CONNECTION FOR USER: {0}".format(self._play_context.remote_user), host=self._play_context.remote_addr) # we can only use tty when we are not pipelining the modules. piping # data into /usr/bin/python inside a tty automatically invokes the # python interactive-mode but the modules are not compatible with the # interactive-mode ("unexpected indent" mainly because of empty lines) ssh_executable = self._play_context.ssh_executable if not in_data and sudoable: args = (ssh_executable, '-tt', self.host, cmd) else: args = (ssh_executable, self.host, cmd) cmd = self._build_command(*args) (returncode, stdout, stderr) = self._run(cmd, in_data, sudoable=sudoable) return (returncode, stdout, stderr) def _file_transport_command(self, in_path, out_path, sftp_action): # scp and sftp require square brackets for IPv6 addresses, but # accept them for hostnames and IPv4 addresses too. host = '[%s]' % self.host # since this can be a non-bool now, we need to handle it correctly scp_if_ssh = C.DEFAULT_SCP_IF_SSH if not isinstance(scp_if_ssh, bool): scp_if_ssh = scp_if_ssh.lower() if scp_if_ssh in BOOLEANS: scp_if_ssh = boolean(scp_if_ssh) elif scp_if_ssh != 'smart': raise AnsibleOptionsError('scp_if_ssh needs to be one of [smart|True|False]') # create a list of commands to use based on config options methods = ['sftp'] if scp_if_ssh == 'smart': methods.append('scp') elif scp_if_ssh: methods = ['scp'] success = False res = None for method in methods: if method == 'sftp': cmd = self._build_command('sftp', to_bytes(host)) in_data = u"{0} {1} {2}\n".format(sftp_action, pipes.quote(in_path), pipes.quote(out_path)) elif method == 'scp': cmd = self._build_command('scp', in_path, u'{0}:{1}'.format(host, pipes.quote(out_path))) in_data = None in_data = to_bytes(in_data, nonstring='passthru') (returncode, stdout, stderr) = self._run(cmd, in_data, checkrc=False) # Check the return code and rollover to next method if failed if returncode == 0: success = True break else: # If not in smart mode, the data will be printed by the raise below if scp_if_ssh == 'smart': display.warning(msg='%s transfer mechanism failed on %s. Use ANSIBLE_DEBUG=1 to see detailed information' % (method, host)) display.debug(msg='%s' % to_native(stdout)) display.debug(msg='%s' % to_native(stderr)) res = (returncode, stdout, stderr) if not success: raise AnsibleError("failed to transfer file to {0}:\n{1}\n{2}"\ .format(to_native(out_path), to_native(res[1]), to_native(res[2]))) # # Main public methods # def exec_command(self, *args, **kwargs): """ Wrapper around _exec_command to retry in the case of an ssh failure Will retry if: * an exception is caught * ssh returns 255 Will not retry if * remaining_tries is <2 * retries limit reached """ remaining_tries = int(C.ANSIBLE_SSH_RETRIES) + 1 cmd_summary = "%s..." % args[0] for attempt in range(remaining_tries): try: return_tuple = self._exec_command(*args, **kwargs) # 0 = success # 1-254 = remote command return code # 255 = failure from the ssh command itself if return_tuple[0] != 255: break else: raise AnsibleConnectionFailure("Failed to connect to the host via ssh: %s" % to_native(return_tuple[2])) except (AnsibleConnectionFailure, Exception) as e: if attempt == remaining_tries - 1: raise else: pause = 2 ** attempt - 1 if pause > 30: pause = 30 if isinstance(e, AnsibleConnectionFailure): msg = "ssh_retry: attempt: %d, ssh return code is 255. cmd (%s), pausing for %d seconds" % (attempt, cmd_summary, pause) else: msg = "ssh_retry: attempt: %d, caught exception(%s) from cmd (%s), pausing for %d seconds" % (attempt, e, cmd_summary, pause) display.vv(msg, host=self.host) time.sleep(pause) continue return return_tuple def put_file(self, in_path, out_path): ''' transfer a file from local to remote ''' super(Connection, self).put_file(in_path, out_path) display.vvv(u"PUT {0} TO {1}".format(in_path, out_path), host=self.host) if not os.path.exists(to_bytes(in_path, errors='surrogate_or_strict')): raise AnsibleFileNotFound("file or module does not exist: {0}".format(to_native(in_path))) self._file_transport_command(in_path, out_path, 'put') def fetch_file(self, in_path, out_path): ''' fetch a file from remote to local ''' super(Connection, self).fetch_file(in_path, out_path) display.vvv(u"FETCH {0} TO {1}".format(in_path, out_path), host=self.host) self._file_transport_command(in_path, out_path, 'get') def close(self): # If we have a persistent ssh connection (ControlPersist), we can ask it # to stop listening. Otherwise, there's nothing to do here. # TODO: reenable once winrm issues are fixed # temporarily disabled as we are forced to currently close connections after every task because of winrm # if self._connected and self._persistent: # ssh_executable = self._play_context.ssh_executable # cmd = self._build_command(ssh_executable, '-O', 'stop', self.host) # # cmd = map(to_bytes, cmd) # p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # stdout, stderr = p.communicate() self._connected = False<|fim▁end|>
:arg b_command: A list containing the command to add the new arguments to. This list will be modified by this method. :arg b_args: An iterable of new arguments to add. This iterable is used more than once so it must be persistent (ie: a list is okay but a
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>#![allow(unused_variables, unused_imports, dead_code)] use m3u8_rs::*; use nom::AsBytes; use std::collections::HashMap; use std::fs; use std::fs::File; use std::io::Read; use std::path; fn all_sample_m3u_playlists() -> Vec<path::PathBuf> { let path: std::path::PathBuf = ["sample-playlists"].iter().collect(); fs::read_dir(path.to_str().unwrap()) .unwrap() .filter_map(Result::ok) .map(|dir| dir.path()) .filter(|path| path.extension().map_or(false, |ext| ext == "m3u8")) .collect() } fn getm3u(path: &str) -> String { let mut buf = String::new(); let mut file = fs::File::open(path).unwrap_or_else(|_| panic!("Can't find m3u8: {}", path)); let u = file.read_to_string(&mut buf).expect("Can't read file"); buf } fn get_sample_playlist(name: &str) -> String { let path: std::path::PathBuf = ["sample-playlists", name].iter().collect(); getm3u(path.to_str().unwrap()) } // ----------------------------------------------------------------------------------------------- // Playlist fn print_parse_playlist_test(playlist_name: &str) -> bool { let input: String = get_sample_playlist(playlist_name); println!("Parsing playlist file: {:?}", playlist_name); let parsed = parse_playlist(input.as_bytes()); if let Result::Ok((i, o)) = parsed { println!("{:?}", o); true } else { println!("Parsing failed:\n {:?}", parsed); false } } #[test] fn playlist_master_with_alternatives() { assert!(print_parse_playlist_test("master-with-alternatives.m3u8")); } #[test] fn playlist_master_with_alternatives_2_3() { assert!(print_parse_playlist_test("master-with-alternatives-2.m3u8")); } #[test] fn playlist_master_with_i_frame_stream_inf() { assert!(print_parse_playlist_test( "master-with-i-frame-stream-inf.m3u8" )); } #[test] fn playlist_master_with_multiple_codecs() { assert!(print_parse_playlist_test( "master-with-multiple-codecs.m3u8" )); } // -- Media playlists #[test] fn playlist_media_standard() { assert!(print_parse_playlist_test("mediaplaylist.m3u8")); } #[test] fn playlist_media_without_segments() { assert!(print_parse_playlist_test( "media-playlist-without-segments.m3u8" )); } #[test] fn playlist_media_with_cues() { assert!(print_parse_playlist_test("media-playlist-with-cues.m3u8")); } #[test] fn playlist_media_with_cues1() { assert!(print_parse_playlist_test("media-playlist-with-cues-1.m3u8")); } #[test] fn playlist_media_with_scte35() { assert!(print_parse_playlist_test("media-playlist-with-scte35.m3u8")); } #[test] fn playlist_media_with_scte35_1() { assert!(print_parse_playlist_test( "media-playlist-with-scte35-1.m3u8" )); } // ----------------------------------------------------------------------------------------------- // Playlist with no newline end #[test] fn playlist_not_ending_in_newline_master() { assert!(print_parse_playlist_test( "master-not-ending-in-newline.m3u8" )); } #[test] fn playlist_not_ending_in_newline_master1() { assert!(print_parse_playlist_test( "master-not-ending-in-newline-1.m3u8" )); } #[test] fn playlist_not_ending_in_newline_media() { assert!(print_parse_playlist_test( "media-not-ending-in-newline.m3u8" )); } <|fim▁hole|> #[test] fn playlist_type_is_master() { let input = get_sample_playlist("master.m3u8"); let result = is_master_playlist(input.as_bytes()); assert!(result); } // #[test] // fn playlist_type_with_unknown_tag() { // let input = get_sample_playlist("!!"); // let result = is_master_playlist(input.as_bytes()); // println!("Playlist_type_with_unknown_tag is master playlist: {:?}", result); // assert_eq!(true, result); // } #[test] fn playlist_types() { for path_buf in all_sample_m3u_playlists() { let path = path_buf.to_str().unwrap(); let input = getm3u(path); let is_master = is_master_playlist(input.as_bytes()); println!("{:?} = {:?}", path, is_master); assert!(path.to_lowercase().contains("master") == is_master); } } // ----------------------------------------------------------------------------------------------- // Creating playlists fn print_create_and_parse_playlist(playlist_original: &mut Playlist) -> Playlist { let mut utf8: Vec<u8> = Vec::new(); playlist_original.write_to(&mut utf8).unwrap(); let m3u8_str: &str = std::str::from_utf8(&utf8).unwrap(); let playlist_parsed = match *playlist_original { Playlist::MasterPlaylist(_) => { Playlist::MasterPlaylist(parse_master_playlist_res(m3u8_str.as_bytes()).unwrap()) } Playlist::MediaPlaylist(_) => { Playlist::MediaPlaylist(parse_media_playlist_res(m3u8_str.as_bytes()).unwrap()) } }; print!("\n\n---- utf8 result\n\n{}", m3u8_str); print!("\n---- Original\n\n{:?}", playlist_original); print!("\n\n---- Parsed\n\n{:?}\n\n", playlist_parsed); playlist_parsed } #[test] fn create_and_parse_master_playlist_empty() { let mut playlist_original = Playlist::MasterPlaylist(MasterPlaylist { ..Default::default() }); let playlist_parsed = print_create_and_parse_playlist(&mut playlist_original); assert_eq!(playlist_original, playlist_parsed); } #[test] fn create_and_parse_master_playlist_full() { let mut playlist_original = Playlist::MasterPlaylist(MasterPlaylist { version: 6, alternatives: vec![AlternativeMedia { media_type: AlternativeMediaType::Audio, uri: Some("alt-media-uri".into()), group_id: "group-id".into(), language: Some("language".into()), assoc_language: Some("assoc-language".into()), name: "Xmedia".into(), default: true, // Its absence indicates an implicit value of NO autoselect: true, // Its absence indicates an implicit value of NO forced: true, // Its absence indicates an implicit value of NO instream_id: Some("instream_id".into()), characteristics: Some("characteristics".into()), channels: Some("channels".into()), }], variants: vec![VariantStream { is_i_frame: false, uri: "masterplaylist-uri".into(), bandwidth: "10010010".into(), average_bandwidth: Some("10010010".into()), codecs: Some("TheCODEC".into()), resolution: Some("1000x3000".into()), frame_rate: Some("60".into()), hdcp_level: Some("NONE".into()), audio: Some("audio".into()), video: Some("video".into()), subtitles: Some("subtitles".into()), closed_captions: Some("closed_captions".into()), }], session_data: vec![SessionData { data_id: "****".into(), field: SessionDataField::Value("%%%%".to_string()), language: Some("SessionDataLanguage".into()), }], session_key: vec![SessionKey(Key { method: "AES-128".into(), uri: Some("https://secure.domain.com".into()), iv: Some("0xb059217aa2649ce170b734".into()), keyformat: Some("xXkeyformatXx".into()), keyformatversions: Some("xXFormatVers".into()), })], start: Some(Start { time_offset: "123123123".into(), precise: Some("YES".into()), }), independent_segments: true, unknown_tags: vec![], }); let playlist_parsed = print_create_and_parse_playlist(&mut playlist_original); assert_eq!(playlist_original, playlist_parsed); } #[test] fn create_and_parse_media_playlist_empty() { let mut playlist_original = Playlist::MediaPlaylist(MediaPlaylist { ..Default::default() }); let playlist_parsed = print_create_and_parse_playlist(&mut playlist_original); assert_eq!(playlist_original, playlist_parsed); } #[test] fn create_and_parse_media_playlist_single_segment() { let mut playlist_original = Playlist::MediaPlaylist(MediaPlaylist { segments: vec![MediaSegment { uri: "20140311T113819-01-338559live.ts".into(), duration: 2.002, title: Some("hey".into()), ..Default::default() }], ..Default::default() }); let playlist_parsed = print_create_and_parse_playlist(&mut playlist_original); assert_eq!(playlist_original, playlist_parsed); } #[test] fn create_and_parse_media_playlist_full() { let mut playlist_original = Playlist::MediaPlaylist(MediaPlaylist { version: 4, target_duration: 3.0, media_sequence: 338559, discontinuity_sequence: 1234, end_list: true, playlist_type: Some(MediaPlaylistType::Vod), i_frames_only: true, start: Some(Start { time_offset: "9999".into(), precise: Some("YES".into()), }), independent_segments: true, segments: vec![MediaSegment { uri: "20140311T113819-01-338559live.ts".into(), duration: 2.002, title: Some("338559".into()), byte_range: Some(ByteRange { length: 137116, offset: Some(4559), }), discontinuity: true, key: Some(Key { method: "AES-128".into(), uri: Some("https://secure.domain.com".into()), iv: Some("0xb059217aa2649ce170b734".into()), keyformat: Some("xXkeyformatXx".into()), keyformatversions: Some("xXFormatVers".into()), }), map: Some(Map { uri: "www.map-uri.com".into(), byte_range: Some(ByteRange { length: 137116, offset: Some(4559), }), }), program_date_time: Some("broodlordinfestorgg".into()), daterange: None, unknown_tags: vec![ExtTag { tag: "X-CUE-OUT".into(), rest: Some("DURATION=2.002".into()), }], }], }); let playlist_parsed = print_create_and_parse_playlist(&mut playlist_original); assert_eq!(playlist_original, playlist_parsed); } // // Roundtrip #[test] fn parsing_write_to_should_produce_the_same_structure() { for playlist in all_sample_m3u_playlists() { let input = getm3u(playlist.to_str().unwrap()); let expected = parse_playlist_res(input.as_bytes()).unwrap(); let mut written: Vec<u8> = Vec::new(); expected.write_to(&mut written).unwrap(); let actual = parse_playlist_res(&written).unwrap(); assert_eq!( expected, actual, "\n\nFailed parser input:\n\n{}\n\nOriginal input:\n\n{}", std::str::from_utf8(&written).unwrap(), input ); } } // Failure on arbitrary text files that don't start with #EXTM3U8 #[test] fn parsing_text_file_should_fail() { let s = " Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. "; let res = parse_master_playlist_res(s.as_bytes()); assert!(res.is_err()); } #[test] fn parsing_binary_data_should_fail_cleanly() { let data = (0..1024).map(|i| (i % 255) as u8).collect::<Vec<u8>>(); let res = parse_master_playlist_res(&data); assert!(res.is_err()); }<|fim▁end|>
// ----------------------------------------------------------------------------------------------- // Playlist type detection tests
<|file_name|>UpdateAttr.java<|end_file_name|><|fim▁begin|>/* * Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.truffle.r.nodes.builtin.base; import static com.oracle.truffle.r.nodes.builtin.CastBuilder.Predef.stringValue; import static com.oracle.truffle.r.runtime.RError.Message.MUST_BE_NONNULL_STRING; import static com.oracle.truffle.r.runtime.builtins.RBehavior.PURE; import static com.oracle.truffle.r.runtime.builtins.RBuiltinKind.PRIMITIVE; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; import com.oracle.truffle.api.dsl.Cached; import com.oracle.truffle.api.dsl.Fallback; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.Node; import com.oracle.truffle.r.nodes.attributes.RemoveAttributeNode; import com.oracle.truffle.r.nodes.attributes.SetAttributeNode; import com.oracle.truffle.r.nodes.attributes.SpecialAttributesFunctions.SetClassAttributeNode; import com.oracle.truffle.r.nodes.attributes.SpecialAttributesFunctions.SetDimAttributeNode; import com.oracle.truffle.r.nodes.attributes.SpecialAttributesFunctions.SetRowNamesAttributeNode; import com.oracle.truffle.r.nodes.builtin.RBuiltinNode; import com.oracle.truffle.r.nodes.builtin.base.UpdateAttrNodeGen.InternStringNodeGen; import com.oracle.truffle.r.nodes.unary.CastIntegerNode; import com.oracle.truffle.r.nodes.unary.CastIntegerNodeGen; import com.oracle.truffle.r.nodes.unary.CastListNode; import com.oracle.truffle.r.nodes.unary.CastToVectorNode; import com.oracle.truffle.r.nodes.unary.CastToVectorNodeGen; import com.oracle.truffle.r.nodes.unary.GetNonSharedNode; import com.oracle.truffle.r.runtime.RError; import com.oracle.truffle.r.runtime.RError.Message; import com.oracle.truffle.r.runtime.RRuntime; import com.oracle.truffle.r.runtime.Utils; import com.oracle.truffle.r.runtime.builtins.RBuiltin; import com.oracle.truffle.r.runtime.data.RAttributable; import com.oracle.truffle.r.runtime.data.RDataFactory; import com.oracle.truffle.r.runtime.data.RNull; import com.oracle.truffle.r.runtime.data.RShareable; import com.oracle.truffle.r.runtime.data.RStringVector; import com.oracle.truffle.r.runtime.data.model.RAbstractContainer; import com.oracle.truffle.r.runtime.data.model.RAbstractIntVector; import com.oracle.truffle.r.runtime.data.model.RAbstractVector; @RBuiltin(name = "attr<-", kind = PRIMITIVE, parameterNames = {"x", "which", "value"}, behavior = PURE) public abstract class UpdateAttr extends RBuiltinNode.Arg3 { @Child private UpdateNames updateNames; @Child private UpdateDimNames updateDimNames; @Child private CastIntegerNode castInteger; @Child private CastToVectorNode castVector; @Child private CastListNode castList; @Child private SetClassAttributeNode setClassAttrNode; @Child private SetRowNamesAttributeNode setRowNamesAttrNode; @Child private SetAttributeNode setGenAttrNode; @Child private SetDimAttributeNode setDimNode; @Child private InternStringNode intern = InternStringNodeGen.create(); public abstract static class InternStringNode extends Node { public abstract String execute(String value); @Specialization(limit = "3", guards = "value == cachedValue") protected static String internCached(@SuppressWarnings("unused") String value, @SuppressWarnings("unused") @Cached("value") String cachedValue, @Cached("intern(value)") String interned) { return interned; } @Specialization(replaces = "internCached") protected static String intern(String value) { return Utils.intern(value); } } static { Casts casts = new Casts(UpdateAttr.class); // Note: cannot check 'attributability' easily because atomic values, e.g int, are not // RAttributable.<|fim▁hole|> private RAbstractContainer updateNames(RAbstractContainer container, Object o) { if (updateNames == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); updateNames = insert(UpdateNamesNodeGen.create()); } return (RAbstractContainer) updateNames.executeStringVector(container, o); } private RAbstractContainer updateDimNames(RAbstractContainer container, Object o) { if (updateDimNames == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); updateDimNames = insert(UpdateDimNamesNodeGen.create()); } return updateDimNames.executeRAbstractContainer(container, o); } private RAbstractIntVector castInteger(RAbstractVector vector) { if (castInteger == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); castInteger = insert(CastIntegerNodeGen.create(true, false, false)); } return (RAbstractIntVector) castInteger.doCast(vector); } private RAbstractVector castVector(Object value) { if (castVector == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); castVector = insert(CastToVectorNodeGen.create(false)); } return (RAbstractVector) castVector.doCast(value); } @Specialization protected RNull updateAttr(@SuppressWarnings("unused") RNull nullTarget, @SuppressWarnings("unused") String attrName, @SuppressWarnings("unused") RNull nullAttrVal) { return RNull.instance; } @Specialization protected RAbstractContainer updateAttr(RAbstractContainer container, String name, RNull value, @Cached("create()") RemoveAttributeNode removeAttrNode, @Cached("create()") GetNonSharedNode nonShared) { String internedName = intern.execute(name); RAbstractContainer result = ((RAbstractContainer) nonShared.execute(container)).materialize(); // the name is interned, so identity comparison is sufficient if (internedName == RRuntime.DIM_ATTR_KEY) { if (setDimNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); setDimNode = insert(SetDimAttributeNode.create()); } setDimNode.setDimensions(result, null); } else if (internedName == RRuntime.NAMES_ATTR_KEY) { return updateNames(result, value); } else if (internedName == RRuntime.DIMNAMES_ATTR_KEY) { return updateDimNames(result, value); } else if (internedName == RRuntime.CLASS_ATTR_KEY) { if (setClassAttrNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); setClassAttrNode = insert(SetClassAttributeNode.create()); } setClassAttrNode.reset(result); return result; } else if (internedName == RRuntime.ROWNAMES_ATTR_KEY) { if (setRowNamesAttrNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); setRowNamesAttrNode = insert(SetRowNamesAttributeNode.create()); } setRowNamesAttrNode.setRowNames(result, null); } else if (result.getAttributes() != null) { removeAttrNode.execute(result, internedName); } return result; } @TruffleBoundary protected static RStringVector convertClassAttrFromObject(Object value) { if (value instanceof RStringVector) { return (RStringVector) value; } else if (value instanceof String) { return RDataFactory.createStringVector((String) value); } else { throw RError.error(RError.SHOW_CALLER, RError.Message.SET_INVALID_CLASS_ATTR); } } @Specialization(guards = "!isRNull(value)") protected RAbstractContainer updateAttr(RAbstractContainer container, String name, Object value, @Cached("create()") GetNonSharedNode nonShared) { String internedName = intern.execute(name); RAbstractContainer result = ((RAbstractContainer) nonShared.execute(container)).materialize(); // the name is interned, so identity comparison is sufficient if (internedName == RRuntime.DIM_ATTR_KEY) { RAbstractIntVector dimsVector = castInteger(castVector(value)); if (dimsVector.getLength() == 0) { throw error(RError.Message.LENGTH_ZERO_DIM_INVALID); } if (setDimNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); setDimNode = insert(SetDimAttributeNode.create()); } setDimNode.setDimensions(result, dimsVector.materialize().getDataCopy()); } else if (internedName == RRuntime.NAMES_ATTR_KEY) { return updateNames(result, value); } else if (internedName == RRuntime.DIMNAMES_ATTR_KEY) { return updateDimNames(result, value); } else if (internedName == RRuntime.CLASS_ATTR_KEY) { if (setClassAttrNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); setClassAttrNode = insert(SetClassAttributeNode.create()); } setClassAttrNode.execute(result, convertClassAttrFromObject(value)); return result; } else if (internedName == RRuntime.ROWNAMES_ATTR_KEY) { if (setRowNamesAttrNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); setRowNamesAttrNode = insert(SetRowNamesAttributeNode.create()); } setRowNamesAttrNode.setRowNames(result, castVector(value)); } else { // generic attribute if (setGenAttrNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); setGenAttrNode = insert(SetAttributeNode.create()); } setGenAttrNode.execute(result, internedName, value); } return result; } /** * All other, non-performance centric, {@link RAttributable} types. */ @Fallback @TruffleBoundary protected Object updateAttr(Object obj, Object name, Object value) { assert name instanceof String : "casts should not pass anything but String"; Object object = obj; if (object instanceof RShareable) { object = ((RShareable) object).getNonShared(); } String internedName = intern.execute((String) name); if (object instanceof RAttributable) { RAttributable attributable = (RAttributable) object; if (value == RNull.instance) { attributable.removeAttr(internedName); } else { attributable.setAttr(internedName, value); } return object; } else if (RRuntime.isForeignObject(obj)) { throw RError.error(this, Message.OBJ_CANNOT_BE_ATTRIBUTED); } else if (obj == RNull.instance) { throw RError.error(this, Message.SET_ATTRIBUTES_ON_NULL); } else { throw RError.nyi(this, "object cannot be attributed: "); } } }<|fim▁end|>
casts.arg("x"); casts.arg("which").defaultError(MUST_BE_NONNULL_STRING, "name").mustBe(stringValue()).asStringVector().findFirst(); }
<|file_name|>test_repetition_unit.py<|end_file_name|><|fim▁begin|># This file is part of wger Workout Manager. # # wger Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # wger Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Workout Manager. If not, see <http://www.gnu.org/licenses/>. # wger from wger.core.models import RepetitionUnit from wger.core.tests import api_base_test from wger.core.tests.base_testcase import ( WorkoutManagerAccessTestCase, WorkoutManagerAddTestCase, WorkoutManagerDeleteTestCase, WorkoutManagerEditTestCase, WorkoutManagerTestCase ) class RepresentationTestCase(WorkoutManagerTestCase): ''' Test the representation of a model ''' def test_representation(self): ''' Test that the representation of an object is correct ''' self.assertEqual("{0}".format(RepetitionUnit.objects.get(pk=1)), 'Repetitions') class OverviewTest(WorkoutManagerAccessTestCase): ''' Tests the settings unit overview page ''' url = 'core:repetition-unit:list' anonymous_fail = True class AddTestCase(WorkoutManagerAddTestCase): ''' Tests adding a new unit ''' object_class = RepetitionUnit url = 'core:repetition-unit:add' data = {'name': 'Furlongs'} user_success = 'admin', user_fail = ('general_manager1', 'general_manager2', 'member1', 'member2', 'trainer2', 'trainer3', 'trainer4', 'manager3') class DeleteTestCase(WorkoutManagerDeleteTestCase): ''' Tests deleting a unit ''' pk = 1 object_class = RepetitionUnit url = 'core:repetition-unit:delete' user_success = 'admin', user_fail = ('general_manager1', 'general_manager2', 'member1', 'member2', 'trainer2',<|fim▁hole|> 'trainer4', 'manager3') class EditTestCase(WorkoutManagerEditTestCase): ''' Tests editing a unit ''' pk = 1 object_class = RepetitionUnit url = 'core:repetition-unit:edit' data = {'name': 'Furlongs'} user_success = 'admin', user_fail = ('general_manager1', 'general_manager2', 'member1', 'member2', 'trainer2', 'trainer3', 'trainer4', 'manager3') class ApiTestCase(api_base_test.ApiBaseResourceTestCase): ''' Tests the unit resource ''' pk = 1 resource = RepetitionUnit private_resource = False def get_resource_name(self): return 'setting-repetitionunit'<|fim▁end|>
'trainer3',
<|file_name|>wings.py<|end_file_name|><|fim▁begin|>"""Fake Wings component""" from threading import Thread import time # Use fake GPIO import GPIOSim.RPi.in_mem as GPIO from tuxeatpi.components.wings import Wings from tuxeatpi.fake_components.base import push_switch class FakeWings(Wings): """Fake wings class""" def __init__(self, pins, event_queue, logger): self.move_wings_thread = FakeWingsMover(pins.get('position')) Wings.__init__(self, pins, event_queue, logger)<|fim▁hole|> def move_start(self): """Override move_start function for fake one""" self.move_wings_thread = FakeWingsMover(self.pins.get('position')) self.move_wings_thread.start() try: super(FakeWings, self).move_start() except Exception: # pylint: disable=W0703 pass def move_stop(self): """Override move_stop function for fake one""" self.move_wings_thread.stop() super(FakeWings, self).move_stop() def push_wing(self, side): """Simulation push switch function""" push_switch(GPIO.GPIO_TO_PIN[self.pins[side + '_switch']]) class FakeWingsMover(Thread): """Thread which simulate wings movement""" # TODO make it stoppable in hug with Ctrl-C signal def __init__(self, position_pin): Thread.__init__(self) self.position_pin = position_pin def stop(self): """Stop moving wings""" self.running = False def run(self): """Start moving wings""" # Get pin_id from self.pins pin_id = GPIO.GPIO_TO_PIN[self.position_pin] self.running = True while self.running: if self.running: GPIO.set_pin_value(pin_id, 1) time.sleep(0.1) if self.running: GPIO.set_pin_value(pin_id, 0) time.sleep(0.1) if self.running: GPIO.set_pin_value(pin_id, 1) time.sleep(0.1) if self.running: GPIO.set_pin_value(pin_id, 0) time.sleep(0.25)<|fim▁end|>
<|file_name|>Item.py<|end_file_name|><|fim▁begin|><|fim▁hole|> self.path = path self.name = name<|fim▁end|>
class Item(object): def __init__(self, path, name):
<|file_name|>service.ts<|end_file_name|><|fim▁begin|>// TODO debug only? import {assert} from './assert'; import {makeDecorator, getAnnotations, mergeAnnotations} from './reflection'; import {setIfInterface, isFunction} from './utils'; /** * Options available when decorating a class as a service */ export interface ServiceOptions { /** * The name the service will be made available for injection */ name: string; /** * An optional provider object or provider factory */ provider?: ng.IServiceProvider|ng.IServiceProviderFactory; /** * An optional service factory */ factory?: Function; } /** * @internal */ export class ServiceAnnotation { name: string = void 0; provider: ng.IServiceProvider|ng.IServiceProviderFactory = void 0;<|fim▁hole|> // TODO debug only? assert.notNull(options, 'options must not be null'); assert.notEmpty(options.name, 'name cannot be null or empty'); setIfInterface(this, options); } } /** * Interface services may implement */ export interface Service { } /** * @internal */ export interface ServiceConstructor extends Function { new (...args: any[]): Service; prototype: Service; } type DecoratorSignature = (options: ServiceOptions) => ClassDecorator; /** * A decorator to annotate a class as being a service */ export var Service = <DecoratorSignature> makeDecorator(ServiceAnnotation); /** * @internal */ export function publishService(serviceClass: ServiceConstructor, ngModule: ng.IModule, name?: string): ng.IModule { // Reflect.decorate apply decorators reversely, so we need to reverse // the extracted annotations before merging them // var aux = getAnnotations(serviceClass, ServiceAnnotation).reverse(); var aux = getAnnotations(serviceClass, ServiceAnnotation); // TODO debug only? assert.notEmpty(aux, 'Did you decorate it with @Service?'); var annotation = <ServiceAnnotation> {/*no defalts*/}; mergeAnnotations(annotation, ...aux); var name = name != null ? name : annotation.name; if (annotation.provider) { ngModule.provider(name, <any> annotation.provider); } else if (annotation.factory) { ngModule.factory(name, annotation.factory); } else { ngModule.service(name, serviceClass); } return ngModule; }<|fim▁end|>
factory: Function = void 0; constructor(options: ServiceOptions) {
<|file_name|>spawn.rs<|end_file_name|><|fim▁begin|>//extern crate scoped_threadpool; extern crate threadpool; extern crate thread_local; extern crate hwloc; use matrix::{Scalar,Mat}; use core::marker::{PhantomData}; use thread_comm::{ThreadComm,ThreadInfo}; use composables::{GemmNode,AlgorithmStep}; use std::sync::{Arc,Mutex}; use std::cell::{RefCell}; use self::threadpool::ThreadPool; use self::thread_local::ThreadLocal; use self::hwloc::{Topology, ObjectType, CPUBIND_THREAD, CpuSet}; use libc; fn cpuset_for_core(topology: &Topology, idx: usize) -> CpuSet { let cores = (*topology).objects_with_type(&ObjectType::Core).unwrap(); match cores.get(idx) { Some(val) => val.cpuset().unwrap(), None => panic!("No Core found with id {}", idx) } } pub struct SpawnThreads<T: Scalar, At: Mat<T>, Bt: Mat<T>, Ct: Mat<T>, S: GemmNode<T, At, Bt, Ct>> where S: Send, T: 'static, S: 'static, At: 'static, Bt: 'static, Ct: 'static { n_threads: usize, pool: ThreadPool,<|fim▁hole|> cntl_cache: Arc<ThreadLocal<RefCell<S>>>, _t: PhantomData<T>, _at: PhantomData<At>, _bt: PhantomData<Bt>, _ct: PhantomData<Ct>, } impl<T: Scalar,At: Mat<T>, Bt: Mat<T>, Ct: Mat<T>, S: GemmNode<T, At, Bt, Ct>> SpawnThreads <T,At,Bt,Ct,S> where S: Send { pub fn set_n_threads(&mut self, n_threads: usize){ //Create new thread pool self.n_threads = n_threads; if n_threads > 1 { self.pool = ThreadPool::new(n_threads-1); } else { self.pool = ThreadPool::new(1); } //Clear the control tree cache Arc::get_mut(&mut self.cntl_cache).expect("").clear(); //Bind threads to cores self.bind_threads(); } fn bind_threads(&mut self) { //Get topology let topo = Arc::new(Mutex::new(Topology::new())); let comm : Arc<ThreadComm<T>> = Arc::new(ThreadComm::new(self.n_threads)); //Bind workers to cores. for id in 1..self.n_threads { let my_topo = topo.clone(); let my_comm = comm.clone(); self.pool.execute(move || { let tid = unsafe { libc::pthread_self() }; { let mut locked_topo = my_topo.lock().unwrap(); //let before = locked_topo.get_cpubind_for_thread(tid, CPUBIND_THREAD); let bind_to = cpuset_for_core(&*locked_topo, id); let _ = locked_topo.set_cpubind_for_thread(tid, bind_to, CPUBIND_THREAD); //let after = locked_topo.get_cpubind_for_thread(tid, CPUBIND_THREAD); } //Barrier to make sure therad binding is done. let thr = ThreadInfo::new(id, my_comm); thr.barrier() }); } //Bind parent to a core. let tid = unsafe { libc::pthread_self() }; { let mut locked_topo = topo.lock().unwrap(); let bind_to = cpuset_for_core(&*locked_topo, 0); let _ = locked_topo.set_cpubind_for_thread(tid, bind_to, CPUBIND_THREAD); } let thr = ThreadInfo::new(0, comm); thr.barrier(); } } impl<T: Scalar, At: Mat<T>, Bt: Mat<T>, Ct: Mat<T>, S: GemmNode<T, At, Bt, Ct>> GemmNode<T, At, Bt, Ct> for SpawnThreads<T, At, Bt, Ct, S> where S: Send { #[inline(always)] unsafe fn run(&mut self, a: &mut At, b: &mut Bt, c:&mut Ct, _thr: &ThreadInfo<T>) -> () { //Create global thread communicator let comm : Arc<ThreadComm<T>> = Arc::new(ThreadComm::new(self.n_threads)); //Make some shallow copies here to pass into the scoped, //because self.pool borrows self as mutable //let cache = self.cntl_cache.clone(); //Spawn n-1 workers since head thread will do work too. for id in 1..self.n_threads { //Make some shallow copies because of borrow rules let mut my_a = a.make_alias(); let mut my_b = b.make_alias(); let mut my_c = c.make_alias(); let my_comm = comm.clone(); let my_cache = self.cntl_cache.clone(); self.pool.execute(move || { //Make this thread's communicator holder let thr = ThreadInfo::new(id, my_comm); //Read this thread's cached control tree let cntl_tree_cell = my_cache.get_or(|| Box::new(RefCell::new(S::new()))); //Run subproblem cntl_tree_cell.borrow_mut().run(&mut my_a, &mut my_b, &mut my_c, &thr); thr.barrier(); }); } //Do parent thread's work let thr = ThreadInfo::new(0, comm); let cntl_tree_cell = self.cntl_cache.get_or(|| Box::new(RefCell::new(S::new()))); cntl_tree_cell.borrow_mut().run(a, b, c, &thr); thr.barrier(); } fn new() -> Self { SpawnThreads{ n_threads : 1, pool: ThreadPool::new(1), cntl_cache: Arc::new(ThreadLocal::new()), _t: PhantomData, _at:PhantomData, _bt: PhantomData, _ct: PhantomData } } fn hierarchy_description() -> Vec<AlgorithmStep> { S::hierarchy_description() } }<|fim▁end|>
<|file_name|>kexidatetimeformatter.cpp<|end_file_name|><|fim▁begin|>/* This file is part of the KDE project Copyright (C) 2006-2011 Jarosław Staniek <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "kexidatetimeformatter.h" #include <kdebug.h> #include <klocale.h> #include <kglobal.h> #include <kdatepicker.h> #include <kdatetable.h> #include <klineedit.h> #include <kmenu.h> #include <kdatewidget.h> class KexiDateFormatter::Private { public: Private() {} //! Input mask generated using the formatter settings. Can be used in QLineEdit::setInputMask(). QString inputMask; //! Order of date sections Order order; //! 4 or 2 digits bool longYear; bool monthWithLeadingZero, dayWithLeadingZero; //! Date format used in toString() QString qtFormat; //! Used in fromString(const QString&) to convert string back to QDate int yearpos, monthpos, daypos; QString separator; }; class KexiTimeFormatter::Private { public: Private() : hmsRegExp(new QRegExp( QLatin1String("(\\d*):(\\d*):(\\d*).*( am| pm){,1}"), Qt::CaseInsensitive)) , hmRegExp(new QRegExp( QLatin1String("(\\d*):(\\d*).*( am| pm){,1}"), Qt::CaseInsensitive)) { } ~Private() { delete hmsRegExp; delete hmRegExp; } //! Input mask generated using the formatter settings. Can be used in QLineEdit::setInputMask(). QString inputMask; // //! Order of date sections // QDateEdit::Order order; //! 12 or 12h bool is24h; bool hoursWithLeadingZero; //! Time format used in toString(). Notation from KLocale::setTimeFormat() is used. QString outputFormat; //! Used in fromString(const QString&) to convert string back to QTime int hourpos, minpos, secpos, ampmpos; QRegExp *hmsRegExp, *hmRegExp; }; KexiDateFormatter::KexiDateFormatter() : d(new Private) { // use "short date" format system settings //! @todo allow to override the format using column property and/or global app settings QString df(KGlobal::locale()->dateFormatShort()); if (df.length() > 2) d->separator = df.mid(2, 1); else d->separator = "-"; const int separatorLen = d->separator.length(); QString yearMask("9999"); QString yearDateFormat("yyyy"); QString monthDateFormat("MM"); QString dayDateFormat("dd"); //for setting up d->dateFormat bool ok = df.length() >= 8; int yearpos, monthpos, daypos; //result of df.find() if (ok) {//look at % variables //! @todo more variables are possible here, see void KLocale::setDateFormatShort() docs //! http://developer.kde.org/documentation/library/3.5-api/kdelibs-apidocs/kdecore/html/classKLocale.html#a59 yearpos = df.indexOf("%y", 0, Qt::CaseInsensitive); //&y or %y d->longYear = !(yearpos >= 0 && df.mid(yearpos + 1, 1) == "y"); if (!d->longYear) { yearMask = "99"; yearDateFormat = "yy"; } monthpos = df.indexOf("%m", 0, Qt::CaseSensitive); //%m or %n d->monthWithLeadingZero = true; if (monthpos < 0) { monthpos = df.indexOf("%n", 0, Qt::CaseInsensitive); d->monthWithLeadingZero = false; monthDateFormat = "M"; } daypos = df.indexOf("%d", 0, Qt::CaseSensitive);//%d or %e d->dayWithLeadingZero = true; if (daypos < 0) { daypos = df.indexOf("%e", 0, Qt::CaseInsensitive); d->dayWithLeadingZero = false; dayDateFormat = "d"; } ok = (yearpos >= 0 && monthpos >= 0 && daypos >= 0); } d->order = YMD; //default if (ok) { if (yearpos < monthpos && monthpos < daypos) { //will be set in "default: YMD" } else if (yearpos < daypos && daypos < monthpos) { d->order = YDM; //! @todo use QRegExp (to replace %Y by %1, etc.) instead of hardcoded "%1%299%399" //! because df may contain also other characters d->inputMask = yearMask + d->separator + QLatin1String("99") + d->separator + QLatin1String("99"); d->qtFormat = yearDateFormat + d->separator + dayDateFormat + d->separator + monthDateFormat; d->yearpos = 0; d->daypos = yearMask.length() + separatorLen; d->monthpos = d->daypos + 2 + separatorLen; } else if (daypos < monthpos && monthpos < yearpos) { d->order = DMY; d->inputMask = QLatin1String("99") + d->separator + QLatin1String("99") + d->separator + yearMask; d->qtFormat = dayDateFormat + d->separator + monthDateFormat + d->separator + yearDateFormat; d->daypos = 0; d->monthpos = 2 + separatorLen; d->yearpos = d->monthpos + 2 + separatorLen; } else if (monthpos < daypos && daypos < yearpos) { d->order = MDY; d->inputMask = QLatin1String("99") + d->separator + QLatin1String("99") + d->separator + yearMask; d->qtFormat = monthDateFormat + d->separator + dayDateFormat + d->separator + yearDateFormat; d->monthpos = 0; d->daypos = 2 + separatorLen; d->yearpos = d->daypos + 2 + separatorLen; } else ok = false; } if (!ok || d->order == YMD) {//default: YMD d->inputMask = yearMask + d->separator + QLatin1String("99") + d->separator + QLatin1String("99"); d->qtFormat = yearDateFormat + d->separator + monthDateFormat + d->separator + dayDateFormat; d->yearpos = 0; d->monthpos = yearMask.length() + separatorLen; d->daypos = d->monthpos + 2 + separatorLen; } d->inputMask += ";_"; } KexiDateFormatter::~KexiDateFormatter() { delete d; } QDate KexiDateFormatter::fromString(const QString& str) const { bool ok = true; int year = str.mid(d->yearpos, d->longYear ? 4 : 2).toInt(&ok); if (!ok) return QDate(); if (year < 30) {//2000..2029 year = 2000 + year; } else if (year < 100) {//1930..1999 year = 1900 + year; } int month = str.mid(d->monthpos, 2).toInt(&ok); if (!ok) return QDate(); int day = str.mid(d->daypos, 2).toInt(&ok); if (!ok) return QDate(); QDate date(year, month, day); if (!date.isValid()) return QDate(); return date; } QVariant KexiDateFormatter::stringToVariant(const QString& str) const { if (isEmpty(str)) return QVariant(); const QDate date(fromString(str)); if (date.isValid()) return date; return QVariant(); } bool KexiDateFormatter::isEmpty(const QString& str) const { QString s(str); return s.remove(d->separator).trimmed().isEmpty(); } QString KexiDateFormatter::inputMask() const { return d->inputMask; } QString KexiDateFormatter::separator() const { return d->separator; } QString KexiDateFormatter::toString(const QDate& date) const { return date.toString(d->qtFormat); } //------------------------------------------------ KexiTimeFormatter::KexiTimeFormatter() : d(new Private) { QString tf(KGlobal::locale()->timeFormat()); //d->hourpos, d->minpos, d->secpos; are result of tf.indexOf() QString hourVariable, minVariable, secVariable; //detect position of HOUR section: find %H or %k or %I or %l d->is24h = true; d->hoursWithLeadingZero = true; d->hourpos = tf.indexOf("%H", 0, Qt::CaseSensitive); if (d->hourpos >= 0) { d->is24h = true; d->hoursWithLeadingZero = true; } else { d->hourpos = tf.indexOf("%k", 0, Qt::CaseSensitive); if (d->hourpos >= 0) { d->is24h = true; d->hoursWithLeadingZero = false; } else { d->hourpos = tf.indexOf("%I", 0, Qt::CaseSensitive); if (d->hourpos >= 0) { d->is24h = false; d->hoursWithLeadingZero = true; } else { d->hourpos = tf.indexOf("%l", 0, Qt::CaseSensitive); if (d->hourpos >= 0) { d->is24h = false; d->hoursWithLeadingZero = false; } } } } d->minpos = tf.indexOf("%M", 0, Qt::CaseSensitive); d->secpos = tf.indexOf("%S", 0, Qt::CaseSensitive); //can be -1 d->ampmpos = tf.indexOf("%p", 0, Qt::CaseSensitive); //can be -1 if (d->hourpos < 0 || d->minpos < 0) { //set default: hr and min are needed, sec are optional tf = "%H:%M:%S"; d->is24h = true; d->hoursWithLeadingZero = false; d->hourpos = 0; d->minpos = 3; d->secpos = d->minpos + 3; d->ampmpos = -1; } hourVariable = tf.mid(d->hourpos, 2); d->inputMask = tf; // d->inputMask.replace( hourVariable, "00" ); // d->inputMask.replace( "%M", "00" ); // d->inputMask.replace( "%S", "00" ); //optional d->inputMask.replace(hourVariable, "99"); d->inputMask.replace("%M", "99"); d->inputMask.replace("%S", "00"); //optional d->inputMask.replace("%p", "AA"); //am or pm d->inputMask += ";_"; d->outputFormat = tf; } KexiTimeFormatter::~KexiTimeFormatter() { delete d; } QTime KexiTimeFormatter::fromString(const QString& str) const { int hour, min, sec; bool pm = false; bool tryWithoutSeconds = true; if (d->secpos >= 0) { if (-1 != d->hmsRegExp->indexIn(str)) { hour = d->hmsRegExp->cap(1).toInt(); min = d->hmsRegExp->cap(2).toInt(); sec = d->hmsRegExp->cap(3).toInt(); if (d->ampmpos >= 0 && d->hmsRegExp->numCaptures() > 3) pm = d->hmsRegExp->cap(4).trimmed().toLower() == "pm"; tryWithoutSeconds = false; } } if (tryWithoutSeconds) { if (-1 == d->hmRegExp->indexIn(str)) return QTime(99, 0, 0); hour = d->hmRegExp->cap(1).toInt(); min = d->hmRegExp->cap(2).toInt(); sec = 0; if (d->ampmpos >= 0 && d->hmRegExp->numCaptures() > 2) pm = d->hmsRegExp->cap(4).toLower() == "pm"; } if (pm && hour < 12) hour += 12; //PM return QTime(hour, min, sec); } QVariant KexiTimeFormatter::stringToVariant(const QString& str) { if (isEmpty(str)) return QVariant(); const QTime time(fromString(str)); if (time.isValid()) return time; return QVariant(); } bool KexiTimeFormatter::isEmpty(const QString& str) const { QString s(str); return s.remove(':').trimmed().isEmpty(); } QString KexiTimeFormatter::toString(const QTime& time) const { if (!time.isValid()) return QString(); QString s(d->outputFormat); if (d->is24h) { if (d->hoursWithLeadingZero) s.replace("%H", QString::fromLatin1(time.hour() < 10 ? "0" : "") + QString::number(time.hour())); else s.replace("%k", QString::number(time.hour())); } else { int time12 = (time.hour() > 12) ? (time.hour() - 12) : time.hour(); if (d->hoursWithLeadingZero) s.replace("%I", QString::fromLatin1(time12 < 10 ? "0" : "") + QString::number(time12)); else s.replace("%l", QString::number(time12)); } s.replace("%M", QString::fromLatin1(time.minute() < 10 ? "0" : "") + QString::number(time.minute())); if (d->secpos >= 0) s.replace("%S", QString::fromLatin1(time.second() < 10 ? "0" : "") + QString::number(time.second())); if (d->ampmpos >= 0) s.replace("%p", ki18n( time.hour() >= 12 ? "pm" : "am" ).toString( KGlobal::locale() )); return s; } QString KexiTimeFormatter::inputMask() const { return d->inputMask; } //------------------------------------------------ QString KexiDateTimeFormatter::inputMask(const KexiDateFormatter& dateFormatter, const KexiTimeFormatter& timeFormatter) { QString mask(dateFormatter.inputMask()); mask.truncate(dateFormatter.inputMask().length() - 2); return mask + " " + timeFormatter.inputMask(); } QDateTime KexiDateTimeFormatter::fromString( const KexiDateFormatter& dateFormatter, const KexiTimeFormatter& timeFormatter, const QString& str) { QString s(str.trimmed()); const int timepos = s.indexOf(' '); const bool emptyTime = timepos >= 0 && timeFormatter.isEmpty(s.mid(timepos + 1)); //.remove(':').trimmed().isEmpty(); if (emptyTime) s = s.left(timepos); if (timepos > 0 && !emptyTime) { return QDateTime( dateFormatter.fromString(s.left(timepos)), timeFormatter.fromString(s.mid(timepos + 1)) ); } else { return QDateTime( dateFormatter.fromString(s), QTime(0, 0, 0) ); } } QString KexiDateTimeFormatter::toString(const KexiDateFormatter &dateFormatter, const KexiTimeFormatter &timeFormatter, const QDateTime &value) { if (value.isValid()) return dateFormatter.toString(value.date()) + ' ' + timeFormatter.toString(value.time()); return QString(); } bool KexiDateTimeFormatter::isEmpty(const KexiDateFormatter& dateFormatter, const KexiTimeFormatter& timeFormatter, const QString& str) { int timepos = str.indexOf(' '); const bool emptyTime = timepos >= 0 && timeFormatter.isEmpty(str.mid(timepos + 1)); //s.mid(timepos+1).remove(':').trimmed().isEmpty(); return (timepos >= 0 && dateFormatter.isEmpty(str.left(timepos)) //s.left(timepos).remove(d->dateFormatter.separator()).trimmed().isEmpty() && emptyTime); } bool KexiDateTimeFormatter::isValid(const KexiDateFormatter& dateFormatter, const KexiTimeFormatter& timeFormatter, const QString& str)<|fim▁hole|>{ int timepos = str.indexOf(' '); const bool emptyTime = timepos >= 0 && timeFormatter.isEmpty(str.mid(timepos + 1)); //s.mid(timepos+1).remove(':').trimmed().isEmpty(); if (timepos >= 0 && dateFormatter.isEmpty(str.left(timepos)) // s.left(timepos).remove(d->dateFormatter.separator()).trimmed().isEmpty() && emptyTime) //empty date/time is valid return true; return timepos >= 0 && dateFormatter.fromString(str.left(timepos)).isValid() && (emptyTime /*date without time is also valid*/ || timeFormatter.fromString(str.mid(timepos + 1)).isValid()); }<|fim▁end|>
<|file_name|>navtreeindex3.js<|end_file_name|><|fim▁begin|>var NAVTREEINDEX3 = { "d4/db5/array_8hpp.html":[3,0,1,11], "d4/db5/array_8hpp.html#a0048463a9200ce90a34092d719fe9922":[3,0,1,11,1], "d4/db5/array_8hpp.html#a311d0610601290b2bb98f1808fc56d24":[3,0,1,11,3], "d4/db5/array_8hpp.html#a44c20174c4360e3d4ec9373839c493e2":[3,0,1,11,2], "d4/db5/array_8hpp.html#a66c2e9bfacf2a266d988285089c50705":[3,0,1,11,5], "d4/db5/array_8hpp.html#ae74917955a3fa69cd29c43493f75fef3":[3,0,1,11,4], "d4/de8/classstd_1_1basic__string.html":[2,0,0,16], "d4/de8/classstd_1_1basic__string.html#a048145b966ec41fbaa4714140308167a":[2,0,0,16,28], "d4/de8/classstd_1_1basic__string.html#a11da29d044d50af12ad86730e077c349":[2,0,0,16,37], "d4/de8/classstd_1_1basic__string.html#a155d2fa939e5c2c45b68db675a5fa86a":[2,0,0,16,6], "d4/de8/classstd_1_1basic__string.html#a19700f17170ad1f72867c379b2d0d75e":[2,0,0,16,44], "d4/de8/classstd_1_1basic__string.html#a1f4ccdd026fe166b90dd52cb7be634c9":[2,0,0,16,8], "d4/de8/classstd_1_1basic__string.html#a26f9a2e19f6933f947bee0132e3aae81":[2,0,0,16,27], "d4/de8/classstd_1_1basic__string.html#a366ac2380d95d352498c88278a7a9d8b":[2,0,0,16,24], "d4/de8/classstd_1_1basic__string.html#a37d7594eca3b2c47b5f0bc2447a982c9":[2,0,0,16,34], "d4/de8/classstd_1_1basic__string.html#a42961d0cef0f670eb1a2462a2b8f08c8":[2,0,0,16,15], "d4/de8/classstd_1_1basic__string.html#a43bb85d9b8916f484babb7b92d10cb42":[2,0,0,16,42], "d4/de8/classstd_1_1basic__string.html#a44aa7597b00eed7606f7952989ac6ed1":[2,0,0,16,21], "d4/de8/classstd_1_1basic__string.html#a4a618a1d6343243652cc9123e6d26593":[2,0,0,16,4], "d4/de8/classstd_1_1basic__string.html#a52b9d0b393063fdb59585f80ac803191":[2,0,0,16,5], "d4/de8/classstd_1_1basic__string.html#a5339b8e4151978ad8f67fb23a1da93a7":[2,0,0,16,0], "d4/de8/classstd_1_1basic__string.html#a55b6e4d56823c8de8ab5fbf9e33dfce5":[2,0,0,16,18], "d4/de8/classstd_1_1basic__string.html#a56c4648661953fc5e9269b4a89ed7441":[2,0,0,16,33], "d4/de8/classstd_1_1basic__string.html#a59f4cc8315d514e52ecdc743e0451e27":[2,0,0,16,41], "d4/de8/classstd_1_1basic__string.html#a5f93368f7fb6a2874bf8da801aa526d1":[2,0,0,16,43], "d4/de8/classstd_1_1basic__string.html#a617bd833ddf33273bb8049b83fc4b254":[2,0,0,16,1], "d4/de8/classstd_1_1basic__string.html#a6d31b891369dbaa90962ecf4cddf078a":[2,0,0,16,40], "d4/de8/classstd_1_1basic__string.html#a7ec81f393c688621e7857ace949111eb":[2,0,0,16,9], "d4/de8/classstd_1_1basic__string.html#a8493d62f43e0ef6a8c18adc283618ee9":[2,0,0,16,36], "d4/de8/classstd_1_1basic__string.html#a8db97eff295c3b6a6bf4631d6ec5dfdf":[2,0,0,16,23], "d4/de8/classstd_1_1basic__string.html#a8e26341ef4a38db673b8a986d881824b":[2,0,0,16,31], "d4/de8/classstd_1_1basic__string.html#a91a0362fdb3c542e2aa27c88d74370e3":[2,0,0,16,10], "d4/de8/classstd_1_1basic__string.html#a9ae54e7e4d3f24e11e92bf28ab4e7555":[2,0,0,16,38], "d4/de8/classstd_1_1basic__string.html#a9e4d69675aff6909e70935e4368ca859":[2,0,0,16,39], "d4/de8/classstd_1_1basic__string.html#a9e89f6285c48714f17596dc9b5183def":[2,0,0,16,29], "d4/de8/classstd_1_1basic__string.html#aa25030581cb9824576b8bee02eaba540":[2,0,0,16,17], "d4/de8/classstd_1_1basic__string.html#aa40b7059ca42243c7bbb557bea09336c":[2,0,0,16,2], "d4/de8/classstd_1_1basic__string.html#aa4b716dd9157b8dba708c56c89be5dc4":[2,0,0,16,26], "d4/de8/classstd_1_1basic__string.html#aa5f40b761e880a93fd8c6c3db5c0df72":[2,0,0,16,35], "d4/de8/classstd_1_1basic__string.html#aa97a7b633573d24a9944a57986800d71":[2,0,0,16,16], "d4/de8/classstd_1_1basic__string.html#ab1b0a7a408203f0126955b874de27352":[2,0,0,16,7], "d4/de8/classstd_1_1basic__string.html#ab2c981bafcfc423d2dd847c0e5fc35fd":[2,0,0,16,19], "d4/de8/classstd_1_1basic__string.html#ab66e0321e01c4483cfbef4f845f0d35c":[2,0,0,16,32], "d4/de8/classstd_1_1basic__string.html#ab8a99058684557be228b91b498e8a3e9":[2,0,0,16,12], "d4/de8/classstd_1_1basic__string.html#ac04ce8c34135d3576f1f639c8917d138":[2,0,0,16,30], "d4/de8/classstd_1_1basic__string.html#ac08e1b13601baa3477b970ebd35ebf99":[2,0,0,16,3], "d4/de8/classstd_1_1basic__string.html#ac74c043d5388cc66d0f922526f4cd395":[2,0,0,16,22], "d4/de8/classstd_1_1basic__string.html#ad0e792c2a8a518722c3e6fef0000e68f":[2,0,0,16,14], "d4/de8/classstd_1_1basic__string.html#ad9e4f9545f7d760a0975a6c3c0a75a20":[2,0,0,16,13], "d4/de8/classstd_1_1basic__string.html#ada7d4480f4f216b45818c2952042b3bd":[2,0,0,16,25], "d4/de8/classstd_1_1basic__string.html#aebc27f736e76a55864f508077c3f56d8":[2,0,0,16,20], "d4/de8/classstd_1_1basic__string.html#afec7916221582f548d4ed0656f871806":[2,0,0,16,11], "d4/de8/classstd_1_1map.html":[2,0,0,111], "d4/de8/classstd_1_1map.html#a2340c924a5187f1a63cfdf0687216763":[2,0,0,111,18], "d4/de8/classstd_1_1map.html#a2c6eaa30025b6bbcbb0cfc5963ee237c":[2,0,0,111,8], "d4/de8/classstd_1_1map.html#a3b6a55862b5d793f47b0023f53eab748":[2,0,0,111,6], "d4/de8/classstd_1_1map.html#a4b6b2b79140050d718dc72d1f1c9f0ad":[2,0,0,111,5], "d4/de8/classstd_1_1map.html#a58706f0166408a04c60bdba751d1a98d":[2,0,0,111,4], "d4/de8/classstd_1_1map.html#a73ea071e7772e050444541652f732083":[2,0,0,111,1], "d4/de8/classstd_1_1map.html#a873685a9110c9219265f1e3201282581":[2,0,0,111,3], "d4/de8/classstd_1_1map.html#a8c523966f8bbd00039d0f2b5cc3c77e5":[2,0,0,111,19], "d4/de8/classstd_1_1map.html#a8f93152ce41f03543187d01c98c034ff":[2,0,0,111,17], "d4/de8/classstd_1_1map.html#a97bf18d62e8afe85c3739cbc62abbbc6":[2,0,0,111,14], "d4/de8/classstd_1_1map.html#a9bcac17c36254c93e37f06d966d32773":[2,0,0,111,21], "d4/de8/classstd_1_1map.html#aa77322ea3800895f483a5a863a2f9356":[2,0,0,111,10], "d4/de8/classstd_1_1map.html#aa9af2db3e9feccee588c59852c389319":[2,0,0,111,0], "d4/de8/classstd_1_1map.html#ab85e6b3f71a6cd66e4c7920f6b141423":[2,0,0,111,7], "d4/de8/classstd_1_1map.html#ab8c8abbc1c9afb13828d3a04a46d9b4c":[2,0,0,111,11], "d4/de8/classstd_1_1map.html#ac8005e666248dfa867980a0d2a7d433d":[2,0,0,111,12], "d4/de8/classstd_1_1map.html#ac9e60107a51138e82a8a66d2c3bca0bf":[2,0,0,111,2], "d4/de8/classstd_1_1map.html#ad4354abcb3f30dae394e199f1230d681":[2,0,0,111,16], "d4/de8/classstd_1_1map.html#adf709df841b651865a6aa361ad6a9763":[2,0,0,111,15], "d4/de8/classstd_1_1map.html#ae02b3d1d336a42ab76f5e187ae9ef5d4":[2,0,0,111,20], "d4/de8/classstd_1_1map.html#ae82d0b4bd0fec70cc51778722e2d760a":[2,0,0,111,9], "d4/de8/classstd_1_1map.html#ae9dcf18d95d45bef7b48ddf28503c60f":[2,0,0,111,13], "d4/dfa/classstd_1_1fixed__sorted__vector.html":[2,0,0,40], "d4/dfa/classstd_1_1fixed__sorted__vector.html#a2ce3d1d05f733abbbf1bf5b42707f51a":[2,0,0,40,4], "d4/dfa/classstd_1_1fixed__sorted__vector.html#a3554132678255108808abcfb93cd9a6b":[2,0,0,40,14], "d4/dfa/classstd_1_1fixed__sorted__vector.html#a3d1973321125b85937c51627cecf7526":[2,0,0,40,15], "d4/dfa/classstd_1_1fixed__sorted__vector.html#a481527c0df696268826e6932ebce476e":[2,0,0,40,0], "d4/dfa/classstd_1_1fixed__sorted__vector.html#a4d7c31d322d6b796ef3bc3a150d9e4b6":[2,0,0,40,3], "d4/dfa/classstd_1_1fixed__sorted__vector.html#a5340ed31349b4ad6bc2010cece895c61":[2,0,0,40,8], "d4/dfa/classstd_1_1fixed__sorted__vector.html#a5a3d349013a3a8b429c8c17d01fc3a73":[2,0,0,40,13], "d4/dfa/classstd_1_1fixed__sorted__vector.html#a616d38b84b146a28959b47d3d3c457ca":[2,0,0,40,1], "d4/dfa/classstd_1_1fixed__sorted__vector.html#a6a5879b6815b4d99155138bb46333a88":[2,0,0,40,6], "d4/dfa/classstd_1_1fixed__sorted__vector.html#a71c9a896bf7d257a85c24d65789efa7d":[2,0,0,40,17], "d4/dfa/classstd_1_1fixed__sorted__vector.html#a7827372b61d7a779057d11a2f2fc7287":[2,0,0,40,10], "d4/dfa/classstd_1_1fixed__sorted__vector.html#a80357d89e033ef0e8213b3b14e675b61":[2,0,0,40,11], "d4/dfa/classstd_1_1fixed__sorted__vector.html#a819e554776546c42857db0bb4fbc474c":[2,0,0,40,16], "d4/dfa/classstd_1_1fixed__sorted__vector.html#a8dd3ad604c8a45f3a514cedf70ed0c1d":[2,0,0,40,2], "d4/dfa/classstd_1_1fixed__sorted__vector.html#abab718a13944985143bc2a882aeea657":[2,0,0,40,7], "d4/dfa/classstd_1_1fixed__sorted__vector.html#ad3a09470b09ced0d1e9b2dfe4999dcb4":[2,0,0,40,9], "d4/dfa/classstd_1_1fixed__sorted__vector.html#ad55e670afba8c3b8a947c2007188ebe8":[2,0,0,40,12], "d4/dfa/classstd_1_1fixed__sorted__vector.html#ad8536b6a839c0f97ed486f1e87871179":[2,0,0,40,5], "d4/dff/classstd_1_1list.html":[2,0,0,106], "d4/dff/classstd_1_1list.html#a012d703d9498bb5379aefab4cbd793fc":[2,0,0,106,10], "d4/dff/classstd_1_1list.html#a068c5ba29eb4c5784417063041db9876":[2,0,0,106,26], "d4/dff/classstd_1_1list.html#a11c4f88fd223f0d6f69e9812409148ac":[2,0,0,106,3], "d4/dff/classstd_1_1list.html#a1b5cf608d0dfc92d253ad2b2c61ffe92":[2,0,0,106,4], "d4/dff/classstd_1_1list.html#a25f54f28c1f8d88247acb96bdcea6816":[2,0,0,106,7], "d4/dff/classstd_1_1list.html#a3131c7319678df9ca4a822a04cf7fb6c":[2,0,0,106,29], "d4/dff/classstd_1_1list.html#a39dd6f17e8be7b52b109f62295528b5c":[2,0,0,106,2], "d4/dff/classstd_1_1list.html#a3a37b706d3d0b2f13b2428e3ca1c699c":[2,0,0,106,1], "d4/dff/classstd_1_1list.html#a3e9ec15c28ddebc1953662e58ec510ca":[2,0,0,106,19], "d4/dff/classstd_1_1list.html#a3f6fac6aa256c5db949f84a0cd2efcac":[2,0,0,106,0], "d4/dff/classstd_1_1list.html#a40e6feb7cf0b64094287e5827597da81":[2,0,0,106,8], "d4/dff/classstd_1_1list.html#a41a418c3113d8c12fe012f774be80597":[2,0,0,106,24], "d4/dff/classstd_1_1list.html#a4354c4728b382544e06fce4fc9bcc312":[2,0,0,106,20], "d4/dff/classstd_1_1list.html#a551b830dafee1df29c1140d6f313a18b":[2,0,0,106,22], "d4/dff/classstd_1_1list.html#a5ae1a58a6b82d43f7cd07e9109333d57":[2,0,0,106,14], "d4/dff/classstd_1_1list.html#a5b9334ad92fc00e1e85ea89b0897abf1":[2,0,0,106,17], "d4/dff/classstd_1_1list.html#a6ce0ffc7ab23dbf139a9cad3847cca65":[2,0,0,106,25], "d4/dff/classstd_1_1list.html#a79d4760b4b044e86ccc18f418c2dfbd5":[2,0,0,106,18], "d4/dff/classstd_1_1list.html#a7ea2991023c95d6082a982639d589122":[2,0,0,106,16], "d4/dff/classstd_1_1list.html#a8309c19812be5d7699bae2cb74b23498":[2,0,0,106,6], "d4/dff/classstd_1_1list.html#a845d0da013d055fa9d8a5fba3c83451f":[2,0,0,106,12], "d4/dff/classstd_1_1list.html#a9016e842ec79a98cfbe4af8253025cda":[2,0,0,106,21], "d4/dff/classstd_1_1list.html#a9e4100a74107d8bfdf64836fd395c428":[2,0,0,106,23], "d4/dff/classstd_1_1list.html#aa2a48b9d9d42da5c02daeecaa24f1f6b":[2,0,0,106,11], "d4/dff/classstd_1_1list.html#acad7862b982e5d322e4f43256e64094c":[2,0,0,106,27], "d4/dff/classstd_1_1list.html#adce674f11895530210a08dd9feb8221f":[2,0,0,106,9], "d4/dff/classstd_1_1list.html#adf28a3cd2d000c2e9dbb2f31d140189b":[2,0,0,106,28], "d4/dff/classstd_1_1list.html#ae9e3042311db99b0ed187cf26bcedb09":[2,0,0,106,30], "d4/dff/classstd_1_1list.html#aec0f8c316d3702cf37f24968429eec63":[2,0,0,106,15], "d4/dff/classstd_1_1list.html#af24365dafd4b435765afc393959c72da":[2,0,0,106,5], "d4/dff/classstd_1_1list.html#afd9bdd4dc99526ea4f79c9bf5cb9c006":[2,0,0,106,13], "d5/d05/classstd_1_1ramakrishna.html":[2,0,0,127], "d5/d05/classstd_1_1ramakrishna.html#a6441f28b4ef0e44eb62726b5c61ba8e0":[2,0,0,127,1], "d5/d05/classstd_1_1ramakrishna.html#aa74c6cbb95ea33a3f5343a91f34004cb":[2,0,0,127,0], "d5/d27/applications__events_8hpp.html":[3,0,1,9], "d5/d2c/smath_8hpp.html":[3,0,1,62], "d5/d38/classstd_1_1independent__bits__engine.html":[2,0,0,59], "d5/d38/classstd_1_1independent__bits__engine.html#a1daa4f3fdd1c4a805931b678d3fae5fe":[2,0,0,59,3], "d5/d38/classstd_1_1independent__bits__engine.html#a32f151de85e10db3c7818333e543d1cb":[2,0,0,59,5], "d5/d38/classstd_1_1independent__bits__engine.html#a3f7b409af91a4364b2adca735cb6f34a":[2,0,0,59,4], "d5/d38/classstd_1_1independent__bits__engine.html#a43d68292f4b0693e304146b9a32ddcb3":[2,0,0,59,2], "d5/d38/classstd_1_1independent__bits__engine.html#a569ea2356722f0905ea3abb74bb2cd6b":[2,0,0,59,1], "d5/d38/classstd_1_1independent__bits__engine.html#a5bf120f126dd5ca1964d01a4ce8d5bef":[2,0,0,59,6], "d5/d38/classstd_1_1independent__bits__engine.html#a5d7b0d9168fd124a290e25ea93541c96":[2,0,0,59,8], "d5/d38/classstd_1_1independent__bits__engine.html#a60306c9881c5ce4dc0d055d32571ac03":[2,0,0,59,9], "d5/d38/classstd_1_1independent__bits__engine.html#a7ec88d4d053d1852f3fe16f5f8610365":[2,0,0,59,0], "d5/d38/classstd_1_1independent__bits__engine.html#af31e73ded39f92a9a9c714092f6a6556":[2,0,0,59,7], "d5/d40/structstd_1_1internal_1_1slist__base__node.html":[2,0,0,1,7], "d5/d40/structstd_1_1internal_1_1slist__base__node.html#a0e1fe1f53aeebb7d860d8630a02d71ec":[2,0,0,1,7,0], "d5/d40/structstd_1_1internal_1_1slist__base__node.html#a3ad27932e24383eba50bf6e8ddefb9d9":[2,0,0,1,7,4], "d5/d40/structstd_1_1internal_1_1slist__base__node.html#a5059f904e47e8ee44777fd9f8026efb8":[2,0,0,1,7,2], "d5/d40/structstd_1_1internal_1_1slist__base__node.html#a9c43ac315223c45502b3e85c040d4a12":[2,0,0,1,7,1], "d5/d40/structstd_1_1internal_1_1slist__base__node.html#aad3c6a04ad23efc497a7a5a1b576b103":[2,0,0,1,7,3], "d5/d40/structstd_1_1internal_1_1slist__base__node.html#ab51c452c73a63bded6db92d617ac441e":[2,0,0,1,7,5], "d5/d46/classstd_1_1event.html":[2,0,0,31], "d5/d46/classstd_1_1event.html#a2555ea55a19f7438c11b448a4da310be":[2,0,0,31,0], "d5/d46/classstd_1_1event.html#a3127439e3b1ae53ff82ffbd6eb1cdb74":[2,0,0,31,1], "d5/d46/classstd_1_1event.html#a60162e40f032fd335c8f63923b4ef002":[2,0,0,31,2], "d5/d46/classstd_1_1event.html#a650674261758e63ccde58cd585caef81":[2,0,0,31,4], "d5/d46/classstd_1_1event.html#ae5bc638a246c98040e8ecfa64836f029":[2,0,0,31,5], "d5/d46/classstd_1_1event.html#ae9459294918a688d5b389ed80b54cd58":[2,0,0,31,3], "d5/d4b/classstd_1_1property.html":[2,0,0,125], "d5/d4b/classstd_1_1property.html#a098f2afe0df9c5ce4506b335611ef53e":[2,0,0,125,3], "d5/d4b/classstd_1_1property.html#a2b7254e0060ade9f44e65f3a4d71dd54":[2,0,0,125,1], "d5/d4b/classstd_1_1property.html#a556273c46a8a9cbd32b5a05375c844cd":[2,0,0,125,0], "d5/d4b/classstd_1_1property.html#aa2728918617e3d879fb41e58d7e53c24":[2,0,0,125,4], "d5/d4b/classstd_1_1property.html#ae5ddf88013535b71302ec90518934549":[2,0,0,125,5], "d5/d4b/classstd_1_1property.html#af5962d92265befccc38f8a426d11d58a":[2,0,0,125,2], "d5/d51/buffer__allocator_8hpp.html":[3,0,1,15], "d5/d61/allocator_8hpp.html":[3,0,1,7], "d5/d61/allocator_8hpp.html#a3b4c7dfb17db51bb2753517543ccd37c":[3,0,1,7,2], "d5/d61/allocator_8hpp.html#a9a2e8249bedcfb932780df5723e4ad9e":[3,0,1,7,1], "d5/d64/classstd_1_1slist.html":[2,0,0,141], "d5/d64/classstd_1_1slist.html#a04a69afc6847311533818dddfcdee97e":[2,0,0,141,4], "d5/d64/classstd_1_1slist.html#a0b6782d4bcd7dc6971e8fbb42a6ad5ce":[2,0,0,141,12], "d5/d64/classstd_1_1slist.html#a111d34dd3475c3d5b9247a70a85a30b2":[2,0,0,141,22], "d5/d64/classstd_1_1slist.html#a140815ea1f9e91fe058f933f1ae8ed55":[2,0,0,141,6], "d5/d64/classstd_1_1slist.html#a14776d9cb4de5a6ab72e848ecd996a67":[2,0,0,141,10], "d5/d64/classstd_1_1slist.html#a24c00ed63a3cd52377a77de14fe82652":[2,0,0,141,0], "d5/d64/classstd_1_1slist.html#a2977308e228e97004773dee54c91b8b5":[2,0,0,141,13], "d5/d64/classstd_1_1slist.html#a2bdb4b58fb7bdd268323735f0b33bbe6":[2,0,0,141,11], "d5/d64/classstd_1_1slist.html#a3660e14a008464ecc897c731968ecd81":[2,0,0,141,19], "d5/d64/classstd_1_1slist.html#a47166c64c1ddb6b559610a6c5f739c35":[2,0,0,141,17], "d5/d64/classstd_1_1slist.html#a495f2218b4c1e39bda6258ee9dcb9db1":[2,0,0,141,20], "d5/d64/classstd_1_1slist.html#a55470629e45e49d744d6eeab82331138":[2,0,0,141,7], "d5/d64/classstd_1_1slist.html#a5fa39130f5ef432af64b224e50d99e72":[2,0,0,141,16], "d5/d64/classstd_1_1slist.html#a61f6570d0e7572ac7d68e6e8967dd098":[2,0,0,141,5], "d5/d64/classstd_1_1slist.html#a6ae4ca7dfc3e0bd5080033904ae10c71":[2,0,0,141,9], "d5/d64/classstd_1_1slist.html#a7f3ce2758b964158f7b413bbe0e2c699":[2,0,0,141,21], "d5/d64/classstd_1_1slist.html#a8f3d02d796e1b94127a8f9ec622e7f3a":[2,0,0,141,14], "d5/d64/classstd_1_1slist.html#a9dc76627cfe746336df1102798406f04":[2,0,0,141,3], "d5/d64/classstd_1_1slist.html#aae0f045e80a1691a8dc0daa4a64d7c53":[2,0,0,141,8], "d5/d64/classstd_1_1slist.html#ab6b6cc8d2f6529076150d4b9d25421c1":[2,0,0,141,15], "d5/d64/classstd_1_1slist.html#aca19a21368914a9c7d6ba9bfd2ca7e6e":[2,0,0,141,2], "d5/d64/classstd_1_1slist.html#ace6af22ddd9ca105272f3a7e6c8dd90c":[2,0,0,141,18], "d5/d64/classstd_1_1slist.html#af578a53dfee381d366b7a881720a07d4":[2,0,0,141,1], "d5/d68/structstd_1_1is__polymorphic.html":[2,0,0,91], "d5/d6c/atomic_8hpp.html":[3,0,1,12], "d5/d6c/atomic_8hpp.html#a6257cbad5715428cc0b01d30efe1fc3f":[3,0,1,12,1], "d5/d6c/atomic_8hpp.html#a6257cbad5715428cc0b01d30efe1fc3fa1b67b1f58b6dfe544dc067460fc47332":[3,0,1,12,1,5], "d5/d6c/atomic_8hpp.html#a6257cbad5715428cc0b01d30efe1fc3fa713961552f49e86e76c18d31568396d8":[3,0,1,12,1,1], "d5/d6c/atomic_8hpp.html#a6257cbad5715428cc0b01d30efe1fc3fa71556f1ad3429c75eb63c783a8c4390e":[3,0,1,12,1,0], "d5/d6c/atomic_8hpp.html#a6257cbad5715428cc0b01d30efe1fc3fa8b17a31dea30fef995ad75d19e1d85ee":[3,0,1,12,1,3],<|fim▁hole|>"d5/d6c/atomic_8hpp.html#a6257cbad5715428cc0b01d30efe1fc3fad4338b1beb516c55566a43f41ad98560":[3,0,1,12,1,4], "d5/d6c/atomic_8hpp.html#a6257cbad5715428cc0b01d30efe1fc3faf4ba3803d19d0df46da5f0ae092ec08d":[3,0,1,12,1,2], "d5/d78/structstd_1_1has__trivial__assign.html":[2,0,0,50], "d5/d7a/classstd_1_1spinlock.html":[2,0,0,143], "d5/d7a/classstd_1_1spinlock.html#a01429c40f6b8a27bc844f2e7073b5262":[2,0,0,143,0], "d5/d7a/classstd_1_1spinlock.html#a1c0cb294f8af28dee9a63807a982b0ed":[2,0,0,143,6], "d5/d7a/classstd_1_1spinlock.html#a48029fe3844ce4614875c893d20a970e":[2,0,0,143,8], "d5/d7a/classstd_1_1spinlock.html#a6d010c79795532eac8503d24b5c14312":[2,0,0,143,1], "d5/d7a/classstd_1_1spinlock.html#aa4caf15c25859ff4c23fcf4d978023d2":[2,0,0,143,3], "d5/d7a/classstd_1_1spinlock.html#aa7b292b211c18e54849550385c9686cd":[2,0,0,143,2], "d5/d7a/classstd_1_1spinlock.html#abb56d76aad9b5ab8d865d2a1691ebf03":[2,0,0,143,4], "d5/d7a/classstd_1_1spinlock.html#aca18d2985a115a9f01ecd5aab1d6e12f":[2,0,0,143,7], "d5/d7a/classstd_1_1spinlock.html#ae958fb96bc80bb084032600a3834bee4":[2,0,0,143,5], "d5/d7e/structstd_1_1_sys_1_1mutex__struct.html":[2,0,0,151,0], "d5/d88/structstd_1_1string__rep.html":[2,0,0,149], "d5/d88/structstd_1_1string__rep.html#a2b07a0e88e164ee6406b2d1b9c6112c5":[2,0,0,149,0], "d5/d88/structstd_1_1string__rep.html#a811ba699f524a07fca87451ec9b7bd9a":[2,0,0,149,5], "d5/d88/structstd_1_1string__rep.html#a8c75d5341c4689f99f5357e4c7686edd":[2,0,0,149,6], "d5/d88/structstd_1_1string__rep.html#a9703e294128a2ee943237571af5bedf0":[2,0,0,149,3], "d5/d88/structstd_1_1string__rep.html#a976c3e095976d5098eafa69b61abc016":[2,0,0,149,1], "d5/d88/structstd_1_1string__rep.html#abf1f5949512a20b084a87b276f65307c":[2,0,0,149,4], "d5/d88/structstd_1_1string__rep.html#ad9d46356d507f4750b7f66b84d741bd2":[2,0,0,149,2], "d5/da8/classstd_1_1lock__base.html":[2,0,0,107], "d5/da8/classstd_1_1lock__base.html#a11a6fcfe95e53fcf7fa9ea1899795399":[2,0,0,107,2], "d5/da8/classstd_1_1lock__base.html#a40542bbcdbabc587b03363ba1e6291c6":[2,0,0,107,0], "d5/da8/classstd_1_1lock__base.html#a493cd8e3d4e08f82d1d64014153a032b":[2,0,0,107,3], "d5/da8/classstd_1_1lock__base.html#ad2292c7877a72b49f0b59e08a7392c61":[2,0,0,107,1], "d5/da8/classstd_1_1lock__base.html#ad5ab453523394a1c4b083b82766f555e":[2,0,0,107,4], "d5/da8/ext_8hpp.html":[3,0,1,2,3], "d5/da8/ext_8hpp.html#a75ea34a9c5a358814dc101008e25da63":[3,0,1,2,3,3], "d5/da8/ext_8hpp.html#af2e3a1605007b6c1c31a698b0036a4af":[3,0,1,2,3,1], "d5/da8/ext_8hpp.html#af627b3eb00e62d3b51160e17590d7cf8":[3,0,1,2,3,0], "d5/da8/ext_8hpp.html#afedf386ab72c194c06eaeb3d5c7c650a":[3,0,1,2,3,2], "d5/db6/structstd_1_1random__access__iterator__tag.html":[2,0,0,128], "d5/dcf/classstd_1_1net_1_1socket.html":[2,0,0,3,8], "d5/dcf/classstd_1_1net_1_1socket.html#a037eb0329c110f9978e504a2e9c6b850":[2,0,0,3,8,1], "d5/dcf/classstd_1_1net_1_1socket.html#a057063eaf2e2ae7e3e2a68d36aea64fe":[2,0,0,3,8,18], "d5/dcf/classstd_1_1net_1_1socket.html#a1145bdb7d5e964fd525f0635dcfd043f":[2,0,0,3,8,2], "d5/dcf/classstd_1_1net_1_1socket.html#a2adbebe226bb20438587b8cd802a74a8":[2,0,0,3,8,7], "d5/dcf/classstd_1_1net_1_1socket.html#a2c9643d14e3b5ff465bbc77391ae2bef":[2,0,0,3,8,3], "d5/dcf/classstd_1_1net_1_1socket.html#a2e846460d29b2e9e9c15201245cf0ddb":[2,0,0,3,8,25], "d5/dcf/classstd_1_1net_1_1socket.html#a3ce264c4d03e7d066e68ca59cd173baf":[2,0,0,3,8,17], "d5/dcf/classstd_1_1net_1_1socket.html#a45060a1f5a96f3fc0b579b6a12e59686":[2,0,0,3,8,5], "d5/dcf/classstd_1_1net_1_1socket.html#a49263efe677b0ed0b0db906d9b300835":[2,0,0,3,8,24], "d5/dcf/classstd_1_1net_1_1socket.html#a4dee92e90c25b542d7a5dfd2777565c1":[2,0,0,3,8,16], "d5/dcf/classstd_1_1net_1_1socket.html#a5138f6fa3c53e3b9c7acfd668fbe8080":[2,0,0,3,8,27], "d5/dcf/classstd_1_1net_1_1socket.html#a514b503b24b99d2d281ca8ea6f062c35":[2,0,0,3,8,35], "d5/dcf/classstd_1_1net_1_1socket.html#a545a96e10df6b5750fd7c5c525bc42ac":[2,0,0,3,8,21], "d5/dcf/classstd_1_1net_1_1socket.html#a5a951a5a6482ed9ebff2b61092a045ff":[2,0,0,3,8,10], "d5/dcf/classstd_1_1net_1_1socket.html#a6bb39f226ba79d033a9881ed2ab64fea":[2,0,0,3,8,36], "d5/dcf/classstd_1_1net_1_1socket.html#a6fd737591a798c982ab10d1171863b11":[2,0,0,3,8,26], "d5/dcf/classstd_1_1net_1_1socket.html#a799f9d5c22e3f0b1b9e9142b71dc548b":[2,0,0,3,8,22] };<|fim▁end|>
<|file_name|>instr.cpp<|end_file_name|><|fim▁begin|>/* file "ia64/instr.cpp" */ /* Copyright (c) 2002 The President and Fellows of Harvard College All rights reserved. This software is provided under the terms described in the "machine/copyright.h" include file. */ #include <machine/copyright.h> #ifdef USE_PRAGMA_INTERFACE #pragma implementation "ia64/instr.h" #endif #include <machine/machine.h> #include <ia64/opcodes.h> #include <ia64/reg_info.h> #include <ia64/instr.h> #ifdef USE_DMALLOC #include <dmalloc.h> #define new D_NEW #endif using namespace ia64; /* ---------------- is_* helper routines ------------------- */ bool is_ldc_ia64(Instr *mi) { int o = get_opcode(mi); int s = get_stem(o); return ((s == MOV_IMM) || (s == MOVL)); } /* * Unconditional register-to-register copy within a single register file. */ bool is_move_ia64(Instr *mi) { int o = get_opcode(mi); int s = get_stem(o); if (((s == MOV_GR) || (s == MOV_FR)) && !is_predicated(mi)) return true; else return false; } bool is_cmove_ia64(Instr *mi) { int o = get_opcode(mi); int s = get_stem(o); if ((s >= MOV_AR) && (s <= MOVL) && is_predicated(mi)) return true; else return false; } bool has_qpred(Instr *mi) { if (srcs_size(mi) < 1) return false; int loc = srcs_size(mi) - 1; Opnd predOpnd = get_src(mi, loc); if (is_preg(predOpnd)) return true; else return false; } /* * Set qualifying predicate * This routine adds a qualifying predicate to the instruction * i.e. (qp) mov dst = src */ void set_qpred(Instr *mi, Opnd qp) { claim(is_preg(qp), "Attempting to add qp that isn't a preg"); if (has_qpred(mi)) set_src(mi, (srcs_size(mi)-1), qp); else append_src(mi, qp); } /* * Returns the qualifying predicate of the instruction or an error */ Opnd get_qpred(Instr *mi) { Opnd predOpnd; if (has_qpred(mi)) predOpnd = get_src(mi, (srcs_size(mi)-1)); else claim(false, "Oops, no predicate set on instruction!"); return predOpnd; } bool is_predicated_ia64(Instr *mi) { if (!has_qpred(mi)) return false; Opnd predOpnd = get_qpred(mi); if (predOpnd != opnd_pr_const1) return true; else return false; } bool is_line_ia64(Instr *mi) { int o = get_opcode(mi); int s = get_stem(o); return (s == LN); } bool is_ubr_ia64(Instr *mi) { int o = get_opcode(mi); int s = get_stem(o); return (((s == BR) || (s == BRL)) && !is_predicated(mi) && !is_call_ia64(mi) && !is_return_ia64(mi) && !is_mbr(mi)); } bool is_cbr_ia64(Instr *mi) { int o = get_opcode(mi); int s = get_stem(o); return (((s == BR) || (s == BRL)) && is_predicated(mi) && !is_call_ia64(mi) && !is_return_ia64(mi) && !is_mbr(mi)); } bool is_call_ia64(Instr *mi) { int o = get_opcode(mi); int s = get_stem(o); if ((s == BR) || (s == BRL)) { if (get_br_ext(o, 1) == BTYPE_CALL) return true; } return false; } bool is_return_ia64(Instr *mi) { int o = get_opcode(mi); int s = get_stem(o); if ((s == BR) || (s == BRL)) { if (get_br_ext(o, 1) == BTYPE_RET) return true; } else if (s == RFI) return true; return false; } bool is_triary_exp_ia64(Instr *mi) { int o = get_opcode(mi); int s = get_stem(o); switch (s) { case FMA: case FMS: case FNMA: case FPMA: case FPMS: case FPNMA: case FSELECT: case PSHLADD: case PSHRADD: case SHLADD: case SHLADDP4: case SHRP: case XMA: return true; default: return false; } } bool is_binary_exp_ia64(Instr *mi) { int o = get_opcode(mi); int s = get_stem(o); switch (s) { case ADD: case ADDP4: case AND: case ANDCM: case CMP: case CMP4: case CMPXCHG: case FADD: case FAMAX: case FAMIN: case FAND: case FANDCM: case FCMP: case FMAX: case FMERGE: case FMIN: case FMIX: case FMPY: case FNMPY: case FOR: case FPACK: case FPAMAX: case FPAMIN: case FPCMP: case FPMAX: case FPMERGE: case FPMIN: case FPMPY: case FPNMPY: case FPRCPA: case FRCPA: case FSUB: case FSWAP: case FSXT: case FXOR: case MIX: case OR: case PACK: case PADD: case PAVG: case PAVGSUB: case PCMP: case PMAX: case PMIN: case PMPY: case PROBE: case PSAD: case PSHL: case PSHR: case PSUB: case SHL: case SHR: case SUB: case TBIT: case UNPACK: case XMPY: case XOR: return true; default: return false; } } bool is_unary_exp_ia64(Instr *mi) { int o = get_opcode(mi);<|fim▁hole|> case CZX: case FABS: case FCVT_FX: case FCVT_XF: case FCVT_XUF: case FNEG: case FNEGABS: case FNORM: case FPCVT_FX: case FPNEG: case FPNEGABS: case FPRSQRTA: case FRSQRTA: case GETF: case POPCNT: case SETF: case SXT: case TAK: case THASH: case TNAT: case TPA: case TTAG: case ZXT: return true; default: return false; } } bool is_commutative_ia64(Instr *mi) { int opc = get_opcode(mi); int st = get_stem(opc); switch (st) { case ADD: case ADDP4: case AND: case OR: /* The above have an immediate form that cannot be reversed */ return !is_immed(get_src(mi, 1)); case CMP: case CMP4: /* The next set have relational operators that can only be reversed if they are set to "EQUAL" */ return (get_ext(opc, 1) == CREL_EQ); case FCMP: case FPCMP: return (get_ext(opc, 1) == FREL_EQ); case PCMP: return (get_ext(opc, 1) == PREL_EQ); case FADD: case FAMAX: case FAMIN: case FAND: case FMAX: case FMIN: case FMPY: case FNMPY: case FOR: case FPAMAX: case FPAMIN: case FPMAX: case FPMIN: case FPMPY: case FPNMPY: case FXOR: case PADD: case PAVG: case PMAX: case PMIN: case PMPY: case PSAD: case XMPY: case XOR: return true; default: return false; } } bool is_two_opnd_ia64(Instr *instr) { return false; } bool reads_memory_ia64(Instr *instr) { int o = get_opcode(instr); int s = get_stem(o); switch (s) { case CMPXCHG: case FETCHADD: case LD: case LDF: case LDFP: case LFETCH: case XCHG: return true; default: return false; } } bool writes_memory_ia64(Instr *instr) { int o = get_opcode(instr); int s = get_stem(o); switch (s) { case ST: case STF: return true; default: return false; } }<|fim▁end|>
int s = get_stem(o); switch (s) {
<|file_name|>test_prettyprint.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # This file is part of Gtfslib-python. # # Gtfslib-python is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Gtfslib-python is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details.<|fim▁hole|>@author: Laurent GRÉGOIRE <[email protected]> """ import math import sys import unittest import six from gtfsplugins.prettycsv import PrettyCsv class TestPrettyPrinter(unittest.TestCase): def test_prettyprinter(self): # Capture standard output saved_stdout = sys.stdout try: out = six.StringIO() sys.stdout = out with PrettyCsv(None, fieldnames=[ 'col1', 'col2' ], maxwidth=5) as csv: csv.writerow({ 'col1': 1, 'col2': 2 }) csv.writerow({ 'col2': 'foobarbaz', 'col1': 11 }) csv.writerow([ 42, 'baz', 'extrawide' ]) output1 = out.getvalue().strip() out = six.StringIO() sys.stdout = out with PrettyCsv(None, maxwidth=5) as csv: csv.writerow([ 1, 2 ]) csv.writerow([ 11, 'foobarbaz', 'extrawide' ]) output2 = out.getvalue().strip() out = six.StringIO() sys.stdout = out with PrettyCsv(None, fieldnames=[ 'col1', 'col2' ], maxwidth=5) as csv: csv.writerow([ 1 ]) csv.writerow([ None, 1.42 ]) csv.writerow([ None, 1./3., math.pi ]) output3 = out.getvalue().strip() finally: sys.stdout = saved_stdout self.assertEqual("+------+-------+-------+\n"+ "| col1 | col2 | |\n"+ "+------+-------+-------+\n"+ "| 1 | 2 | |\n"+ "| 11 | fooba | |\n"+ "| 42 | baz | extra |\n"+ "+------+-------+-------+", output1) self.assertEqual("+----+-------+-------+\n"+ "| 1 | 2 | |\n"+ "| 11 | fooba | extra |\n"+ "+----+-------+-------+", output2) self.assertEqual("+------+-------+-------+\n"+ "| col1 | col2 | |\n"+ "+------+-------+-------+\n"+ "| 1 | | |\n"+ "| | 1.42 | |\n"+ "| | 0.333 | 3.141 |\n"+ "+------+-------+-------+", output3) if __name__ == '__main__': unittest.main()<|fim▁end|>
# # You should have received a copy of the GNU General Public License # along with gtfslib-python. If not, see <http://www.gnu.org/licenses/>. """
<|file_name|>streaming.pass.cpp<|end_file_name|><|fim▁begin|>//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++03, c++11, c++14, c++17 // XFAIL: * <|fim▁hole|>// <chrono> // class year_month_day; // template<class charT, class traits> // basic_ostream<charT, traits>& // operator<<(basic_ostream<charT, traits>& os, const year_month_day& ym); // // Returns: os << ym.year() << '/' << ym.month(). // // // template<class charT, class traits> // basic_ostream<charT, traits>& // to_stream(basic_ostream<charT, traits>& os, const charT* fmt, const year_month_day& ym); // // Effects: Streams ym into os using the format specified by the NTCTS fmt. fmt encoding follows the rules specified in 25.11. // // template<class charT, class traits, class Alloc = allocator<charT>> // basic_istream<charT, traits>& // from_stream(basic_istream<charT, traits>& is, const charT* fmt, // year_month_day& ym, basic_string<charT, traits, Alloc>* abbrev = nullptr, // minutes* offset = nullptr); // // Effects: Attempts to parse the input stream is into the year_month_day ym using the format // flags given in the NTCTS fmt as specified in 25.12. If the parse fails to decode // a valid year_month_day, is.setstate(ios_- base::failbit) shall be called and ym shall // not be modified. If %Z is used and successfully parsed, that value will be assigned // to *abbrev if abbrev is non-null. If %z (or a modified variant) is used and // successfully parsed, that value will be assigned to *offset if offset is non-null. #include <chrono> #include <type_traits> #include <cassert> #include <iostream> #include "test_macros.h" int main(int, char**) { using year_month_day = std::chrono::year_month_day; using year = std::chrono::year; using month = std::chrono::month; using day = std::chrono::day; std::cout << year_month_day{year{2018}, month{3}, day{12}}; return 0; }<|fim▁end|>
<|file_name|>YWeather.py<|end_file_name|><|fim▁begin|># YWeather by 2boom 2013 v.0.6 # xml from http://weather.yahooapis.com/forecastrss from Components.Converter.Converter import Converter from Components.Element import cached from Tools.Directories import fileExists from Poll import Poll import time import os class YWeather(Poll, Converter, object): weather_city = '711665' time_update = 20 time_update_ms = 30000 city = 0 country = 1 direction = 2 speed = 3 humidity = 4 visibility = 5 pressure = 6 pressurenm = 7 wtext = 8 temp = 9 picon = 10 wtext2 = 11 templow2 = 12 temphigh2 = 13 picon2 = 14 day2 = 15 date2 = 16 wtext3 = 17 templow3 = 18 temphigh3 = 19 picon3 = 20<|fim▁hole|> templow4 = 24 temphigh4 = 25 picon4 = 26 day4 = 27 date4 = 28 wtext5 = 29 templow5 = 30 temphigh5 = 31 picon5 = 32 day5 = 33 date5 = 34 def __init__(self, type): Converter.__init__(self, type) Poll.__init__(self) if type == "city": self.type = self.city elif type == "country": self.type = self.country elif type == "direction": self.type = self.direction elif type == "speed": self.type = self.speed elif type == "humidity": self.type = self.humidity elif type == "visibility": self.type = self.visibility elif type == "pressure": self.type = self.pressure elif type == "pressurenm": self.type = self.pressurenm elif type == "text": self.type = self.wtext elif type == "temp": self.type = self.temp elif type == "picon": self.type = self.picon elif type == "text2": self.type = self.wtext2 elif type == "templow2": self.type = self.templow2 elif type == "temphigh2": self.type = self.temphigh2 elif type == "day2": self.type = self.day2 elif type == "date2": self.type = self.date2 elif type == "picon2": self.type = self.picon2 elif type == "text3": self.type = self.wtext3 elif type == "templow3": self.type = self.templow3 elif type == "temphigh3": self.type = self.temphigh3 elif type == "day3": self.type = self.day3 elif type == "date3": self.type = self.date3 elif type == "picon3": self.type = self.picon3 elif type == "text4": self.type = self.wtext4 elif type == "templow4": self.type = self.templow4 elif type == "temphigh4": self.type = self.temphigh4 elif type == "day4": self.type = self.day4 elif type == "date4": self.type = self.date4 elif type == "picon4": self.type = self.picon4 elif type == "text5": self.type = self.wtext5 elif type == "templow5": self.type = self.templow5 elif type == "temphigh5": self.type = self.temphigh5 elif type == "day5": self.type = self.day5 elif type == "date5": self.type = self.date5 elif type == "picon5": self.type = self.picon5 self.poll_interval = self.time_update_ms self.poll_enabled = True @cached def getText(self): xweather = {'ycity':"N/A", 'ycountry':"N/A", 'ydirection':"N/A", 'yspeed':"N/A", 'yhumidity':"N/A", 'yvisibility':"N/A", 'ypressure':"N/A", 'ytext':"N/A", 'ytemp':"N/A", 'ypicon':"3200", 'yday2':"N/A", 'yday3':"N/A", 'yday4':"N/A", 'yday5':"N/A", 'ypiconday2':"3200", 'ypiconday3':"3200", 'ypiconday4':"3200", 'ypiconday5':"3200", 'ydate2':"N/A", 'ydate3':"N/A", 'ydate4':"N/A", 'ydate5':"N/A", 'ytextday2':"N/A", 'ytextday3':"N/A", 'ytextday4':"N/A", 'ytextday5':"N/A", 'ytemphighday2':"N/A", 'ytemphighday3':"N/A", 'ytemphighday4':"N/A", 'ytemphighday5':"N/A", 'ytemplowday2':"N/A", 'ytemplowday3':"N/A", 'ytemplowday4':"N/A", 'ytemplowday5':"N/A"} direct = 0 info = "" if fileExists("/usr/lib/enigma2/python/Plugins/Extensions/iSkin/Weather/Config/Location_id"): self.weather_city = open("/usr/lib/enigma2/python/Plugins/Extensions/iSkin/Weather/Config/Location_id").read() elif fileExists("/usr/lib/enigma2/python/Plugins/Extensions/YahooWeather/Config/Location_id"): self.weather_city = open("/usr/lib/enigma2/python/Plugins/Extensions/YahooWeather/Config/Location_id").read() if fileExists("/tmp/yweather.xml"): if int((time.time() - os.stat("/tmp/yweather.xml").st_mtime)/60) >= self.time_update: os.system("rm /tmp/yweather.xml") os.system("wget -P /tmp -T2 'https://query.yahooapis.com/v1/public/yql?q=select%20%2A%20from%20weather.forecast%20where%20woeid=%s%20AND%20u=%22c%22' -O /tmp/yweather.xml" % self.weather_city) else: os.system("wget -P /tmp -T2 'https://query.yahooapis.com/v1/public/yql?q=select%20%2A%20from%20weather.forecast%20where%20woeid=%s%20AND%20u=%22c%22' -O /tmp/yweather.xml" % self.weather_city) if not fileExists("/tmp/yweather.xml"): os.system("echo -e 'None' >> /tmp/yweather.xml") return 'N/A' if not fileExists("/tmp/yweather.xml"): os.system("echo -e 'None' >> /tmp/yweather.xml") return 'N/A' wday = 1 for line in open("/tmp/yweather.xml"): if line.find("<yweather:location") > -1: xweather['ycity'] = line.split('city')[1].split('"')[1] xweather['ycountry'] = line.split('country')[1].split('"')[1] elif line.find("<yweather:wind") > -1: xweather['ydirection'] = line.split('direction')[1].split('"')[1] xweather['yspeed'] = line.split('speed')[1].split('"')[1] elif line.find("<yweather:atmosphere") > -1: xweather['yhumidity'] = line.split('humidity')[1].split('"')[1] xweather['yvisibility'] = line.split('visibility')[1].split('"')[1] xweather['ypressure'] = line.split('pressure')[1].split('"')[1] elif line.find("<yweather:condition") > -1: xweather['ytext'] = line.split('text')[1].split('"')[1] xweather['ypicon'] = line.split('code')[1].split('"')[1] xweather['ytemp'] = line.split('temp')[1].split('"')[1] elif line.find('yweather:forecast') > -1: if wday == 2: xweather['yday2'] = line.split('day')[1].split('"')[1] xweather['ydate2'] = line.split('date')[1].split('"')[1] xweather['ytextday2'] = line.split('text')[1].split('"')[1] xweather['ypiconday2'] = line.split('code')[1].split('"')[1] xweather['ytemphighday2'] = line.split('high')[1].split('"')[1] xweather['ytemplowday2'] = line.split('low')[1].split('"')[1] elif wday == 3: xweather['yday3'] = line.split('day')[1].split('"')[1] xweather['ydate3'] = line.split('date')[1].split('"')[1] xweather['ytextday3'] = line.split('text')[1].split('"')[1] xweather['ypiconday3'] = line.split('code')[1].split('"')[1] xweather['ytemphighday3'] = line.split('high')[1].split('"')[1] xweather['ytemplowday3'] = line.split('low')[1].split('"')[1] elif wday == 4: xweather['yday4'] = line.split('day')[1].split('"')[1] xweather['ydate4'] = line.split('date')[1].split('"')[1] xweather['ytextday4'] = line.split('text')[1].split('"')[1] xweather['ypiconday4'] = line.split('code')[1].split('"')[1] xweather['ytemphighday4'] = line.split('high')[1].split('"')[1] xweather['ytemplowday4'] = line.split('low')[1].split('"')[1] elif wday == 5: xweather['yday5'] = line.split('day')[1].split('"')[1] xweather['ydate5'] = line.split('date')[1].split('"')[1] xweather['ytextday5'] = line.split('text')[1].split('"')[1] xweather['ypiconday5'] = line.split('code')[1].split('"')[1] xweather['ytemphighday5'] = line.split('high')[1].split('"')[1] xweather['ytemplowday5'] = line.split('low')[1].split('"')[1] wday = wday + 1 if self.type == self.city: info = xweather['ycity'] elif self.type == self.country: info = xweather['ycountry'] elif self.type == self.direction: if xweather['ydirection'] != "N/A": direct = int(xweather['ydirection']) if direct >= 0 and direct <= 20: info = _('N') elif direct >= 21 and direct <= 35: info = _('nne') elif direct >= 36 and direct <= 55: info = _('ne') elif direct >= 56 and direct <= 70: info = _('ene') elif direct >= 71 and direct <= 110: info = _('E') elif direct >= 111 and direct <= 125: info = _('ese') elif direct >= 126 and direct <= 145: info = _('se') elif direct >= 146 and direct <= 160: info = _('sse') elif direct >= 161 and direct <= 200: info = _('S') elif direct >= 201 and direct <= 215: info = _('ssw') elif direct >= 216 and direct <= 235: info = _('sw') elif direct >= 236 and direct <= 250: info = _('wsw') elif direct >= 251 and direct <= 290: info = _('W') elif direct >= 291 and direct <= 305: info = _('wnw') elif direct >= 306 and direct <= 325: info = _('nw') elif direct >= 326 and direct <= 340: info = _('nnw') elif direct >= 341 and direct <= 360: info = _('N') else: info = "N/A" elif self.type == self.speed: info = xweather['yspeed'] + ' km/h' elif self.type == self.humidity: info = xweather['yhumidity'] + ' mb' elif self.type == self.visibility: info = xweather['yvisibility'] + ' km' elif self.type == self.pressure: info = xweather['ypressure'] + ' mb' elif self.type == self.pressurenm: if xweather['ypressure'] != "N/A": info = "%d mmHg" % round(float(xweather['ypressure']) * 0.75) else: info = "N/A" elif self.type == self.wtext: info = xweather['ytext'] elif self.type == self.temp: if info != "N/A": info = xweather['ytemp'] + '%s' % unichr(176).encode("latin-1") else: info = xweather['ytemp'] elif self.type == self.picon: info = xweather['ypicon'] elif self.type == self.wtext2: info = xweather['ytextday2'] elif self.type == self.templow2: if info != "N/A": info = xweather['ytemplowday2'] + '%s' % unichr(176).encode("latin-1") else: info = xweather['ytemplowday2'] elif self.type == self.temphigh2: if info != "N/A": info = xweather['ytemphighday2'] + '%s' % unichr(176).encode("latin-1") else: info = xweather['ytemphighday2'] elif self.type == self.picon2: info = xweather['ypiconday2'] elif self.type == self.day2: if xweather['yday2'] != "N/A": day = xweather['yday2'] if day == 'Mon': info = _('Mon') elif day == 'Tue': info = _('Tue') elif day == 'Wed': info = _('Wed') elif day == 'Thu': info = _('Thu') elif day == 'Fri': info = _('Fri') elif day == 'Sat': info = _('Sat') elif day == 'Sun': info = _('Sun') else: info = "N/A" elif self.type == self.date2: info = xweather['ydate2'] elif self.type == self.wtext3: info = xweather['ytextday3'] elif self.type == self.templow3: if info != "N/A": info = xweather['ytemplowday3'] + '%s' % unichr(176).encode("latin-1") else: info = xweather['ytemplowday3'] elif self.type == self.temphigh3: if info != "N/A": info = xweather['ytemphighday3'] + '%s' % unichr(176).encode("latin-1") else: info = xweather['ytemphighday3'] elif self.type == self.picon3: info = xweather['ypiconday3'] elif self.type == self.day3: if xweather['yday3'] != "N/A": day = xweather['yday3'] if day == 'Mon': info = _('Mon') elif day == 'Tue': info = _('Tue') elif day == 'Wed': info = _('Wed') elif day == 'Thu': info = _('Thu') elif day == 'Fri': info = _('Fri') elif day == 'Sat': info = _('Sat') elif day == 'Sun': info = _('Sun') else: info = "N/A" elif self.type == self.date3: info = xweather['ydate3'] elif self.type == self.wtext4: info = xweather['ytextday4'] elif self.type == self.templow4: if info != "N/A": info = xweather['ytemplowday4'] + '%s' % unichr(176).encode("latin-1") else: info = xweather['ytemplowday4'] elif self.type == self.temphigh4: if info != "N/A": info = xweather['ytemphighday4'] + '%s' % unichr(176).encode("latin-1") else: info = xweather['ytemphighday4'] elif self.type == self.picon4: info = xweather['ypiconday4'] elif self.type == self.day4: if xweather['yday4'] != "N/A": day = xweather['yday4'] if day == 'Mon': info = _('Mon') elif day == 'Tue': info = _('Tue') elif day == 'Wed': info = _('Wed') elif day == 'Thu': info = _('Thu') elif day == 'Fri': info = _('Fri') elif day == 'Sat': info = _('Sat') elif day == 'Sun': info = _('Sun') else: info = "N/A" elif self.type == self.date4: info = xweather['ydate4'] elif self.type == self.wtext5: info = xweather['ytextday5'] elif self.type == self.templow5: if info != "N/A": info = xweather['ytemplowday5'] + '%s' % unichr(176).encode("latin-1") else: info = xweather['ytemplowday5'] elif self.type == self.temphigh5: if info != "N/A": info = xweather['ytemphighday5'] + '%s' % unichr(176).encode("latin-1") else: info = xweather['ytemphighday5'] elif self.type == self.picon5: info = xweather['ypiconday5'] elif self.type == self.day5: if xweather['yday5'] != "N/A": day = xweather['yday5'] if day == 'Mon': info = _('Mon') elif day == 'Tue': info = _('Tue') elif day == 'Wed': info = _('Wed') elif day == 'Thu': info = _('Thu') elif day == 'Fri': info = _('Fri') elif day == 'Sat': info = _('Sat') elif day == 'Sun': info = _('Sun') else: info = "N/A" elif self.type == self.date5: info = xweather['ydate5'] return info text = property(getText) def changed(self, what): Converter.changed(self, (self.CHANGED_POLL,))<|fim▁end|>
day3 = 21 date3 = 22 wtext4 = 23
<|file_name|>huffman2.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- encoding: utf-8 -*- import os import marshal import cPickle import array class HuffmanNode(object): recurPrint = False def __init__(self, ch=None, fq=None, lnode=None, rnode=None, parent=None): self.L = lnode self.R = rnode self.p = parent self.c = ch self.fq = fq def __repr__(self): if HuffmanNode.recurPrint: lnode = self.L if self.L else '#' rnode = self.R if self.R else '#' return ''.join( ('(%s:%d)'%(self.c, self.fq), str(lnode), str(rnode) ) ) else: return '(%s:%d)'%(self.c, self.fq) def __cmp__(self, other): if not isinstance(other, HuffmanNode): return super(HuffmanNode, self).__cmp__(other) return cmp(self.fq, other.fq) def _pop_first_two_nodes(nodes): if len(nodes)>1: first=nodes.pop(0) second=nodes.pop(0) return first, second else: #print "[popFirstTwoNodes] nodes's length <= 1" return nodes[0], None def _build_tree(nodes): nodes.sort() while(True): first, second = _pop_first_two_nodes(nodes) if not second: return first parent = HuffmanNode(lnode=first, rnode=second, fq=first.fq+second.fq) first.p = parent second.p = parent nodes.insert(0, parent) nodes.sort() def _gen_huffman_code(node, dict_codes, buffer_stack=[]): if not node.L and not node.R: dict_codes[node.c] = ''.join(buffer_stack) return buffer_stack.append('0') _gen_huffman_code(node.L, dict_codes, buffer_stack) buffer_stack.pop() buffer_stack.append('1') _gen_huffman_code(node.R, dict_codes, buffer_stack) buffer_stack.pop() def _cal_freq(long_str): from collections import defaultdict d = defaultdict(int) for c in long_str: d[c] += 1 return d MAX_BITS = 8 class Encoder(object): def __init__(self, filename_or_long_str=None): if filename_or_long_str: if os.path.exists(filename_or_long_str): self.encode(filename_or_long_str) else: #print '[Encoder] take \'%s\' as a string to be encoded.'\ # % filename_or_long_str self.long_str = filename_or_long_str def __get_long_str(self): return self._long_str def __set_long_str(self, s): self._long_str = s if s: self.root = self._get_tree_root() self.code_map = self._get_code_map() self.array_codes, self.code_length = self._encode() long_str = property(__get_long_str, __set_long_str) def _get_tree_root(self): d = _cal_freq(self.long_str) return _build_tree( [HuffmanNode(ch=ch, fq=int(fq)) for ch, fq in d.iteritems()] ) def _get_code_map(self): a_dict={} _gen_huffman_code(self.root, a_dict) return a_dict def _encode(self): array_codes = array.array('B') code_length = 0 buff, length = 0, 0 for ch in self.long_str: code = self.code_map[ch] for bit in list(code): if bit=='1': buff = (buff << 1) | 0x01 else: # bit == '0' buff = (buff << 1) length += 1 if length == MAX_BITS: array_codes.extend([buff]) buff, length = 0, 0 code_length += len(code) if length != 0: array_codes.extend([buff << (MAX_BITS-length)]) return array_codes, code_length def encode(self, filename):<|fim▁hole|> self.long_str = fp.read() fp.close() def write(self, filename): if self._long_str: fcompressed = open(filename, 'wb') marshal.dump( (cPickle.dumps(self.root), self.code_length, self.array_codes), fcompressed) fcompressed.close() else: print "You haven't set 'long_str' attribute." class Decoder(object): def __init__(self, filename_or_raw_str=None): if filename_or_raw_str: if os.path.exists(filename_or_raw_str): filename = filename_or_raw_str self.read(filename) else: print '[Decoder] take \'%s\' as raw string' % filename_or_raw_str raw_string = filename_or_raw_str unpickled_root, length, array_codes = marshal.loads(raw_string) self.root = cPickle.loads(unpickled_root) self.code_length = length self.array_codes = array.array('B', array_codes) def _decode(self): string_buf = [] total_length = 0 node = self.root for code in self.array_codes: buf_length = 0 while (buf_length < MAX_BITS and total_length != self.code_length): buf_length += 1 total_length += 1 if code >> (MAX_BITS - buf_length) & 1: node = node.R if node.c: string_buf.append(node.c) node = self.root else: node = node.L if node.c: string_buf.append(node.c) node = self.root return ''.join(string_buf) def read(self, filename): fp = open(filename, 'rb') unpickled_root, length, array_codes = marshal.load(fp) self.root = cPickle.loads(unpickled_root) self.code_length = length self.array_codes = array.array('B', array_codes) fp.close() def decode_as(self, filename): decoded = self._decode() fout = open(filename, 'wb') fout.write(decoded) fout.close() if __name__=='__main__': original_file = 'filename.txt' compressed_file = 'compressed.scw' decompressed_file = 'filename2.txt' # first way to use Encoder/Decoder enc = Encoder(original_file) enc.write(compressed_file) dec = Decoder(compressed_file) dec.decode_as(decompressed_file) # second way #enc = Encoder() #enc.encode(original_file) #enc.write(compressed_file) #dec = Decoder() #dec.read(compressed_file) #dec.decode_as(decompressed_file)<|fim▁end|>
fp = open(filename, 'rb')
<|file_name|>cef_stream.rs<|end_file_name|><|fim▁begin|>// Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the name Chromium Embedded // Framework nor the names of its contributors may be used to endorse // or promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // --------------------------------------------------------------------------- // // This file was generated by the CEF translator tool and should not be edited // by hand. See the translator.README.txt file in the tools directory for // more information. // #![allow(non_snake_case, unused_imports)] use eutil; use interfaces; use types; use wrappers::CefWrap; use libc; use std::collections::HashMap; use std::ptr; // // Structure the client can implement to provide a custom stream reader. The // functions of this structure may be called on any thread. // #[repr(C)] pub struct _cef_read_handler_t { // // Base structure. // pub base: types::cef_base_t, // // Read raw binary data. // pub read: Option<extern "C" fn(this: *mut cef_read_handler_t, ptr: *mut (), size: libc::size_t, n: libc::size_t) -> libc::size_t>, // // Seek to the specified offset position. |whence| may be any one of SEEK_CUR, // SEEK_END or SEEK_SET. Return zero on success and non-zero on failure. // pub seek: Option<extern "C" fn(this: *mut cef_read_handler_t, offset: i64, whence: libc::c_int) -> libc::c_int>, // // Return the current offset position. // pub tell: Option<extern "C" fn(this: *mut cef_read_handler_t) -> i64>, // // Return non-zero if at end of file. // pub eof: Option<extern "C" fn(this: *mut cef_read_handler_t) -> libc::c_int>, // // Return true (1) if this handler performs work like accessing the file // system which may block. Used as a hint for determining the thread to access // the handler from. // pub may_block: Option<extern "C" fn( this: *mut cef_read_handler_t) -> libc::c_int>, // // The reference count. This will only be present for Rust instances! // pub ref_count: usize, // // Extra data. This will only be present for Rust instances! // pub extra: u8, } pub type cef_read_handler_t = _cef_read_handler_t; // // Structure the client can implement to provide a custom stream reader. The // functions of this structure may be called on any thread. // pub struct CefReadHandler { c_object: *mut cef_read_handler_t, } impl Clone for CefReadHandler { fn clone(&self) -> CefReadHandler{ unsafe { if !self.c_object.is_null() { ((*self.c_object).base.add_ref.unwrap())(&mut (*self.c_object).base); } CefReadHandler { c_object: self.c_object, } } } } impl Drop for CefReadHandler { fn drop(&mut self) { unsafe { if !self.c_object.is_null() { ((*self.c_object).base.release.unwrap())(&mut (*self.c_object).base); } } } } impl CefReadHandler { pub unsafe fn from_c_object(c_object: *mut cef_read_handler_t) -> CefReadHandler { CefReadHandler { c_object: c_object, } } pub unsafe fn from_c_object_addref(c_object: *mut cef_read_handler_t) -> CefReadHandler { if !c_object.is_null() { ((*c_object).base.add_ref.unwrap())(&mut (*c_object).base); } CefReadHandler { c_object: c_object, } } pub fn c_object(&self) -> *mut cef_read_handler_t { self.c_object } pub fn c_object_addrefed(&self) -> *mut cef_read_handler_t { unsafe { if !self.c_object.is_null() { eutil::add_ref(self.c_object as *mut types::cef_base_t); } self.c_object } } pub fn is_null_cef_object(&self) -> bool { self.c_object.is_null() } pub fn is_not_null_cef_object(&self) -> bool { !self.c_object.is_null() } // // Read raw binary data. // pub fn read(&self, ptr: &mut (), size: libc::size_t, n: libc::size_t) -> libc::size_t { if self.c_object.is_null() { panic!("called a CEF method on a null object") } unsafe { CefWrap::to_rust( ((*self.c_object).read.unwrap())( self.c_object, CefWrap::to_c(ptr), CefWrap::to_c(size), CefWrap::to_c(n))) } } // // Seek to the specified offset position. |whence| may be any one of SEEK_CUR, // SEEK_END or SEEK_SET. Return zero on success and non-zero on failure. // pub fn seek(&self, offset: i64, whence: libc::c_int) -> libc::c_int { if self.c_object.is_null() { panic!("called a CEF method on a null object") } unsafe { CefWrap::to_rust( ((*self.c_object).seek.unwrap())( self.c_object, CefWrap::to_c(offset), CefWrap::to_c(whence))) } } // // Return the current offset position. // pub fn tell(&self) -> i64 { if self.c_object.is_null() { panic!("called a CEF method on a null object") } unsafe { CefWrap::to_rust( ((*self.c_object).tell.unwrap())( self.c_object)) } } // // Return non-zero if at end of file. // pub fn eof(&self) -> libc::c_int { if self.c_object.is_null() { panic!("called a CEF method on a null object") } unsafe { CefWrap::to_rust( ((*self.c_object).eof.unwrap())( self.c_object)) } } // // Return true (1) if this handler performs work like accessing the file // system which may block. Used as a hint for determining the thread to access // the handler from. // pub fn may_block(&self) -> libc::c_int { if self.c_object.is_null() { panic!("called a CEF method on a null object") } unsafe { CefWrap::to_rust( ((*self.c_object).may_block.unwrap())( self.c_object)) } } } impl CefWrap<*mut cef_read_handler_t> for CefReadHandler { fn to_c(rust_object: CefReadHandler) -> *mut cef_read_handler_t { rust_object.c_object_addrefed() } unsafe fn to_rust(c_object: *mut cef_read_handler_t) -> CefReadHandler { CefReadHandler::from_c_object_addref(c_object) } } impl CefWrap<*mut cef_read_handler_t> for Option<CefReadHandler> { fn to_c(rust_object: Option<CefReadHandler>) -> *mut cef_read_handler_t { match rust_object { None => ptr::null_mut(), Some(rust_object) => rust_object.c_object_addrefed(), } } unsafe fn to_rust(c_object: *mut cef_read_handler_t) -> Option<CefReadHandler> { if c_object.is_null() { None } else { Some(CefReadHandler::from_c_object_addref(c_object)) } } } // // Structure used to read data from a stream. The functions of this structure // may be called on any thread. // #[repr(C)] pub struct _cef_stream_reader_t { // // Base structure. // pub base: types::cef_base_t, // // Read raw binary data. // pub read: Option<extern "C" fn(this: *mut cef_stream_reader_t, ptr: *mut (), size: libc::size_t, n: libc::size_t) -> libc::size_t>, // // Seek to the specified offset position. |whence| may be any one of SEEK_CUR, // SEEK_END or SEEK_SET. Returns zero on success and non-zero on failure. // pub seek: Option<extern "C" fn(this: *mut cef_stream_reader_t, offset: i64, whence: libc::c_int) -> libc::c_int>, // // Return the current offset position. // pub tell: Option<extern "C" fn(this: *mut cef_stream_reader_t) -> i64>, // // Return non-zero if at end of file. // pub eof: Option<extern "C" fn(this: *mut cef_stream_reader_t) -> libc::c_int>, // // Returns true (1) if this reader performs work like accessing the file // system which may block. Used as a hint for determining the thread to access // the reader from. // pub may_block: Option<extern "C" fn( this: *mut cef_stream_reader_t) -> libc::c_int>, // // The reference count. This will only be present for Rust instances! // pub ref_count: usize, // // Extra data. This will only be present for Rust instances! // pub extra: u8, } pub type cef_stream_reader_t = _cef_stream_reader_t; // // Structure used to read data from a stream. The functions of this structure // may be called on any thread. // pub struct CefStreamReader { c_object: *mut cef_stream_reader_t, } impl Clone for CefStreamReader { fn clone(&self) -> CefStreamReader{ unsafe { if !self.c_object.is_null() { ((*self.c_object).base.add_ref.unwrap())(&mut (*self.c_object).base); } CefStreamReader { c_object: self.c_object, } } } } impl Drop for CefStreamReader { fn drop(&mut self) { unsafe { if !self.c_object.is_null() { ((*self.c_object).base.release.unwrap())(&mut (*self.c_object).base); } } } } impl CefStreamReader { pub unsafe fn from_c_object(c_object: *mut cef_stream_reader_t) -> CefStreamReader { CefStreamReader { c_object: c_object, } } pub unsafe fn from_c_object_addref(c_object: *mut cef_stream_reader_t) -> CefStreamReader { if !c_object.is_null() { ((*c_object).base.add_ref.unwrap())(&mut (*c_object).base); } CefStreamReader { c_object: c_object, } } pub fn c_object(&self) -> *mut cef_stream_reader_t { self.c_object } pub fn c_object_addrefed(&self) -> *mut cef_stream_reader_t { unsafe { if !self.c_object.is_null() { eutil::add_ref(self.c_object as *mut types::cef_base_t); } self.c_object } } pub fn is_null_cef_object(&self) -> bool { self.c_object.is_null() } pub fn is_not_null_cef_object(&self) -> bool { !self.c_object.is_null() } // // Read raw binary data. // pub fn read(&self, ptr: &mut (), size: libc::size_t, n: libc::size_t) -> libc::size_t { if self.c_object.is_null() { panic!("called a CEF method on a null object") } unsafe { CefWrap::to_rust( ((*self.c_object).read.unwrap())( self.c_object, CefWrap::to_c(ptr), CefWrap::to_c(size), CefWrap::to_c(n))) } } // // Seek to the specified offset position. |whence| may be any one of SEEK_CUR, // SEEK_END or SEEK_SET. Returns zero on success and non-zero on failure. // pub fn seek(&self, offset: i64, whence: libc::c_int) -> libc::c_int { if self.c_object.is_null() { panic!("called a CEF method on a null object") } unsafe { CefWrap::to_rust( ((*self.c_object).seek.unwrap())( self.c_object, CefWrap::to_c(offset), CefWrap::to_c(whence))) } } // // Return the current offset position. // pub fn tell(&self) -> i64 { if self.c_object.is_null() { panic!("called a CEF method on a null object") } unsafe { CefWrap::to_rust( ((*self.c_object).tell.unwrap())( self.c_object)) } } // // Return non-zero if at end of file. // pub fn eof(&self) -> libc::c_int { if self.c_object.is_null() { panic!("called a CEF method on a null object") } unsafe { CefWrap::to_rust( ((*self.c_object).eof.unwrap())( self.c_object)) } } // // Returns true (1) if this reader performs work like accessing the file // system which may block. Used as a hint for determining the thread to access // the reader from. // pub fn may_block(&self) -> libc::c_int { if self.c_object.is_null() { panic!("called a CEF method on a null object") } unsafe { CefWrap::to_rust( ((*self.c_object).may_block.unwrap())( self.c_object)) } } // // Create a new cef_stream_reader_t object from a file. // pub fn create_for_file(fileName: &[u16]) -> interfaces::CefStreamReader { unsafe { CefWrap::to_rust( ::stream::cef_stream_reader_create_for_file( CefWrap::to_c(fileName))) } } // // Create a new cef_stream_reader_t object from data. // pub fn create_for_data(data: &mut (), size: libc::size_t) -> interfaces::CefStreamReader { unsafe { CefWrap::to_rust( ::stream::cef_stream_reader_create_for_data( CefWrap::to_c(data), CefWrap::to_c(size))) } } // // Create a new cef_stream_reader_t object from a custom handler. // pub fn create_for_handler( handler: interfaces::CefReadHandler) -> interfaces::CefStreamReader { unsafe { CefWrap::to_rust( ::stream::cef_stream_reader_create_for_handler( CefWrap::to_c(handler))) } } } impl CefWrap<*mut cef_stream_reader_t> for CefStreamReader { fn to_c(rust_object: CefStreamReader) -> *mut cef_stream_reader_t { rust_object.c_object_addrefed() } unsafe fn to_rust(c_object: *mut cef_stream_reader_t) -> CefStreamReader { CefStreamReader::from_c_object_addref(c_object) } } impl CefWrap<*mut cef_stream_reader_t> for Option<CefStreamReader> { fn to_c(rust_object: Option<CefStreamReader>) -> *mut cef_stream_reader_t { match rust_object { None => ptr::null_mut(), Some(rust_object) => rust_object.c_object_addrefed(), } } unsafe fn to_rust(c_object: *mut cef_stream_reader_t) -> Option<CefStreamReader> { if c_object.is_null() { None } else { Some(CefStreamReader::from_c_object_addref(c_object)) } } } // // Structure the client can implement to provide a custom stream writer. The // functions of this structure may be called on any thread. // #[repr(C)] pub struct _cef_write_handler_t { // // Base structure. // pub base: types::cef_base_t, // // Write raw binary data. // pub write: Option<extern "C" fn(this: *mut cef_write_handler_t, ptr: *const ( ), size: libc::size_t, n: libc::size_t) -> libc::size_t>, // // Seek to the specified offset position. |whence| may be any one of SEEK_CUR, // SEEK_END or SEEK_SET. Return zero on success and non-zero on failure. // pub seek: Option<extern "C" fn(this: *mut cef_write_handler_t, offset: i64, whence: libc::c_int) -> libc::c_int>, // // Return the current offset position. // pub tell: Option<extern "C" fn(this: *mut cef_write_handler_t) -> i64>, // // Flush the stream. // pub flush: Option<extern "C" fn( this: *mut cef_write_handler_t) -> libc::c_int>, // // Return true (1) if this handler performs work like accessing the file // system which may block. Used as a hint for determining the thread to access // the handler from. // pub may_block: Option<extern "C" fn( this: *mut cef_write_handler_t) -> libc::c_int>, // // The reference count. This will only be present for Rust instances! // pub ref_count: usize, // // Extra data. This will only be present for Rust instances! // pub extra: u8, } pub type cef_write_handler_t = _cef_write_handler_t; // // Structure the client can implement to provide a custom stream writer. The // functions of this structure may be called on any thread. // pub struct CefWriteHandler { c_object: *mut cef_write_handler_t, } impl Clone for CefWriteHandler { fn clone(&self) -> CefWriteHandler{ unsafe { if !self.c_object.is_null() { ((*self.c_object).base.add_ref.unwrap())(&mut (*self.c_object).base); } CefWriteHandler { c_object: self.c_object, } } } } impl Drop for CefWriteHandler { fn drop(&mut self) { unsafe { if !self.c_object.is_null() { ((*self.c_object).base.release.unwrap())(&mut (*self.c_object).base); } } } } impl CefWriteHandler { pub unsafe fn from_c_object(c_object: *mut cef_write_handler_t) -> CefWriteHandler { CefWriteHandler { c_object: c_object, } } pub unsafe fn from_c_object_addref(c_object: *mut cef_write_handler_t) -> CefWriteHandler { if !c_object.is_null() { ((*c_object).base.add_ref.unwrap())(&mut (*c_object).base); } CefWriteHandler { c_object: c_object, } } pub fn c_object(&self) -> *mut cef_write_handler_t { self.c_object } pub fn c_object_addrefed(&self) -> *mut cef_write_handler_t { unsafe { if !self.c_object.is_null() { eutil::add_ref(self.c_object as *mut types::cef_base_t); } self.c_object } } pub fn is_null_cef_object(&self) -> bool { self.c_object.is_null() } pub fn is_not_null_cef_object(&self) -> bool { !self.c_object.is_null() } // // Write raw binary data. // pub fn write(&self, ptr: &(), size: libc::size_t, n: libc::size_t) -> libc::size_t { if self.c_object.is_null() { panic!("called a CEF method on a null object") } unsafe { CefWrap::to_rust( ((*self.c_object).write.unwrap())( self.c_object, CefWrap::to_c(ptr), CefWrap::to_c(size), CefWrap::to_c(n))) } } // // Seek to the specified offset position. |whence| may be any one of SEEK_CUR, // SEEK_END or SEEK_SET. Return zero on success and non-zero on failure. // pub fn seek(&self, offset: i64, whence: libc::c_int) -> libc::c_int { if self.c_object.is_null() { panic!("called a CEF method on a null object") } unsafe { CefWrap::to_rust( ((*self.c_object).seek.unwrap())( self.c_object, CefWrap::to_c(offset), CefWrap::to_c(whence))) } } // // Return the current offset position. // pub fn tell(&self) -> i64 { if self.c_object.is_null() { panic!("called a CEF method on a null object") } unsafe { CefWrap::to_rust( ((*self.c_object).tell.unwrap())( self.c_object)) } } // // Flush the stream. // pub fn flush(&self) -> libc::c_int { if self.c_object.is_null() { panic!("called a CEF method on a null object") } unsafe { CefWrap::to_rust( ((*self.c_object).flush.unwrap())( self.c_object)) } } // // Return true (1) if this handler performs work like accessing the file // system which may block. Used as a hint for determining the thread to access // the handler from. // pub fn may_block(&self) -> libc::c_int { if self.c_object.is_null() { panic!("called a CEF method on a null object") } unsafe { CefWrap::to_rust( ((*self.c_object).may_block.unwrap())( self.c_object)) } } } impl CefWrap<*mut cef_write_handler_t> for CefWriteHandler { fn to_c(rust_object: CefWriteHandler) -> *mut cef_write_handler_t { rust_object.c_object_addrefed() } unsafe fn to_rust(c_object: *mut cef_write_handler_t) -> CefWriteHandler { CefWriteHandler::from_c_object_addref(c_object) } } impl CefWrap<*mut cef_write_handler_t> for Option<CefWriteHandler> { fn to_c(rust_object: Option<CefWriteHandler>) -> *mut cef_write_handler_t { match rust_object { None => ptr::null_mut(), Some(rust_object) => rust_object.c_object_addrefed(), } } unsafe fn to_rust(c_object: *mut cef_write_handler_t) -> Option<CefWriteHandler> { if c_object.is_null() { None } else { Some(CefWriteHandler::from_c_object_addref(c_object)) } } } // // Structure used to write data to a stream. The functions of this structure may // be called on any thread. // #[repr(C)] pub struct _cef_stream_writer_t { // // Base structure. // pub base: types::cef_base_t, // // Write raw binary data. // pub write: Option<extern "C" fn(this: *mut cef_stream_writer_t, ptr: *const ( ), size: libc::size_t, n: libc::size_t) -> libc::size_t>, // // Seek to the specified offset position. |whence| may be any one of SEEK_CUR, // SEEK_END or SEEK_SET. Returns zero on success and non-zero on failure. // pub seek: Option<extern "C" fn(this: *mut cef_stream_writer_t, offset: i64, whence: libc::c_int) -> libc::c_int>, // // Return the current offset position. // pub tell: Option<extern "C" fn(this: *mut cef_stream_writer_t) -> i64>, // // Flush the stream. // pub flush: Option<extern "C" fn( this: *mut cef_stream_writer_t) -> libc::c_int>, // // Returns true (1) if this writer performs work like accessing the file // system which may block. Used as a hint for determining the thread to access // the writer from. // pub may_block: Option<extern "C" fn( this: *mut cef_stream_writer_t) -> libc::c_int>, // // The reference count. This will only be present for Rust instances! // pub ref_count: usize, <|fim▁hole|> // pub extra: u8, } pub type cef_stream_writer_t = _cef_stream_writer_t; // // Structure used to write data to a stream. The functions of this structure may // be called on any thread. // pub struct CefStreamWriter { c_object: *mut cef_stream_writer_t, } impl Clone for CefStreamWriter { fn clone(&self) -> CefStreamWriter{ unsafe { if !self.c_object.is_null() { ((*self.c_object).base.add_ref.unwrap())(&mut (*self.c_object).base); } CefStreamWriter { c_object: self.c_object, } } } } impl Drop for CefStreamWriter { fn drop(&mut self) { unsafe { if !self.c_object.is_null() { ((*self.c_object).base.release.unwrap())(&mut (*self.c_object).base); } } } } impl CefStreamWriter { pub unsafe fn from_c_object(c_object: *mut cef_stream_writer_t) -> CefStreamWriter { CefStreamWriter { c_object: c_object, } } pub unsafe fn from_c_object_addref(c_object: *mut cef_stream_writer_t) -> CefStreamWriter { if !c_object.is_null() { ((*c_object).base.add_ref.unwrap())(&mut (*c_object).base); } CefStreamWriter { c_object: c_object, } } pub fn c_object(&self) -> *mut cef_stream_writer_t { self.c_object } pub fn c_object_addrefed(&self) -> *mut cef_stream_writer_t { unsafe { if !self.c_object.is_null() { eutil::add_ref(self.c_object as *mut types::cef_base_t); } self.c_object } } pub fn is_null_cef_object(&self) -> bool { self.c_object.is_null() } pub fn is_not_null_cef_object(&self) -> bool { !self.c_object.is_null() } // // Write raw binary data. // pub fn write(&self, ptr: &(), size: libc::size_t, n: libc::size_t) -> libc::size_t { if self.c_object.is_null() { panic!("called a CEF method on a null object") } unsafe { CefWrap::to_rust( ((*self.c_object).write.unwrap())( self.c_object, CefWrap::to_c(ptr), CefWrap::to_c(size), CefWrap::to_c(n))) } } // // Seek to the specified offset position. |whence| may be any one of SEEK_CUR, // SEEK_END or SEEK_SET. Returns zero on success and non-zero on failure. // pub fn seek(&self, offset: i64, whence: libc::c_int) -> libc::c_int { if self.c_object.is_null() { panic!("called a CEF method on a null object") } unsafe { CefWrap::to_rust( ((*self.c_object).seek.unwrap())( self.c_object, CefWrap::to_c(offset), CefWrap::to_c(whence))) } } // // Return the current offset position. // pub fn tell(&self) -> i64 { if self.c_object.is_null() { panic!("called a CEF method on a null object") } unsafe { CefWrap::to_rust( ((*self.c_object).tell.unwrap())( self.c_object)) } } // // Flush the stream. // pub fn flush(&self) -> libc::c_int { if self.c_object.is_null() { panic!("called a CEF method on a null object") } unsafe { CefWrap::to_rust( ((*self.c_object).flush.unwrap())( self.c_object)) } } // // Returns true (1) if this writer performs work like accessing the file // system which may block. Used as a hint for determining the thread to access // the writer from. // pub fn may_block(&self) -> libc::c_int { if self.c_object.is_null() { panic!("called a CEF method on a null object") } unsafe { CefWrap::to_rust( ((*self.c_object).may_block.unwrap())( self.c_object)) } } // // Create a new cef_stream_writer_t object for a file. // pub fn create_for_file(fileName: &[u16]) -> interfaces::CefStreamWriter { unsafe { CefWrap::to_rust( ::stream::cef_stream_writer_create_for_file( CefWrap::to_c(fileName))) } } // // Create a new cef_stream_writer_t object for a custom handler. // pub fn create_for_handler( handler: interfaces::CefWriteHandler) -> interfaces::CefStreamWriter { unsafe { CefWrap::to_rust( ::stream::cef_stream_writer_create_for_handler( CefWrap::to_c(handler))) } } } impl CefWrap<*mut cef_stream_writer_t> for CefStreamWriter { fn to_c(rust_object: CefStreamWriter) -> *mut cef_stream_writer_t { rust_object.c_object_addrefed() } unsafe fn to_rust(c_object: *mut cef_stream_writer_t) -> CefStreamWriter { CefStreamWriter::from_c_object_addref(c_object) } } impl CefWrap<*mut cef_stream_writer_t> for Option<CefStreamWriter> { fn to_c(rust_object: Option<CefStreamWriter>) -> *mut cef_stream_writer_t { match rust_object { None => ptr::null_mut(), Some(rust_object) => rust_object.c_object_addrefed(), } } unsafe fn to_rust(c_object: *mut cef_stream_writer_t) -> Option<CefStreamWriter> { if c_object.is_null() { None } else { Some(CefStreamWriter::from_c_object_addref(c_object)) } } }<|fim▁end|>
// // Extra data. This will only be present for Rust instances!
<|file_name|>CreateApplicationListReportRuleProvider.java<|end_file_name|><|fim▁begin|>package org.jboss.windup.reporting.rules; import java.util.HashMap; import java.util.Map; import javax.inject.Inject; import org.jboss.forge.furnace.Furnace; import org.jboss.windup.config.AbstractRuleProvider; import org.jboss.windup.config.GraphRewrite; import org.jboss.windup.config.metadata.RuleMetadata; import org.jboss.windup.config.operation.GraphOperation; import org.jboss.windup.config.phase.PostReportGenerationPhase; import org.jboss.windup.graph.GraphContext; import org.jboss.windup.graph.model.WindupVertexFrame; import org.jboss.windup.graph.service.GraphService; import org.jboss.windup.reporting.model.ApplicationReportModel; import org.jboss.windup.reporting.model.TemplateType; import org.jboss.windup.reporting.model.WindupVertexListModel; import org.jboss.windup.reporting.rules.AttachApplicationReportsToIndexRuleProvider; import org.jboss.windup.reporting.service.ApplicationReportService; import org.ocpsoft.rewrite.config.Configuration; import org.ocpsoft.rewrite.config.ConfigurationBuilder; import org.ocpsoft.rewrite.context.EvaluationContext; /** * This renders an application index page listing all applications analyzed by the current execution of windup. * * @author <a href="mailto:[email protected]">Jesse Sightler</a> */ @RuleMetadata(phase = PostReportGenerationPhase.class, before = AttachApplicationReportsToIndexRuleProvider.class) public class CreateApplicationListReportRuleProvider extends AbstractRuleProvider<|fim▁hole|> @Inject private Furnace furnace; // @formatter:off @Override public Configuration getConfiguration(GraphContext context) { return ConfigurationBuilder.begin() .addRule() .perform(new GraphOperation() { @Override public void perform(GraphRewrite event, EvaluationContext context) { createIndexReport(event.getGraphContext()); } }); } // @formatter:on private void createIndexReport(GraphContext context) { ApplicationReportService applicationReportService = new ApplicationReportService(context); ApplicationReportModel report = applicationReportService.create(); report.setReportPriority(1); report.setReportIconClass("glyphicon glyphicon-home"); report.setReportName(APPLICATION_LIST_REPORT); report.setTemplatePath(TEMPLATE_PATH); report.setTemplateType(TemplateType.FREEMARKER); report.setDisplayInApplicationReportIndex(false); report.setReportFilename(OUTPUT_FILENAME); GraphService<WindupVertexListModel> listService = new GraphService<>(context, WindupVertexListModel.class); WindupVertexListModel<ApplicationReportModel> applications = listService.create(); for (ApplicationReportModel applicationReportModel : applicationReportService.findAll()) { if (applicationReportModel.isMainApplicationReport() != null && applicationReportModel.isMainApplicationReport()) applications.addItem(applicationReportModel); } Map<String, WindupVertexFrame> relatedData = new HashMap<>(); relatedData.put("applications", applications); report.setRelatedResource(relatedData); } }<|fim▁end|>
{ public static final String APPLICATION_LIST_REPORT = "Application List"; private static final String OUTPUT_FILENAME = "../index.html"; public static final String TEMPLATE_PATH = "/reports/templates/application_list.ftl";
<|file_name|>INoise.d.ts<|end_file_name|><|fim▁begin|>import type { INoiseFactor } from "./INoiseFactor"; import type { IOptionLoader } from "../../IOptionLoader";<|fim▁hole|>export interface INoise extends IOptionLoader<INoise> { delay: INoiseDelay; enable: boolean; factor: INoiseFactor; }<|fim▁end|>
import type { INoiseDelay } from "./INoiseDelay";
<|file_name|>hub.js<|end_file_name|><|fim▁begin|>var debug = require('debug')('harmonyhubjs:client:login:hub') var Client = require('node-xmpp-client') var Q = require('q') var util = require('../util') /** PrivateFunction: getIdentity * Logs in to a Harmony hub as a guest and uses the userAuthToken from logitech's * web service to retrieve an identity token. * * Parameters: * (String) hubhost - Hostname/IP of the Harmony hub to connect. * (int) hubport - Optional. Port of the Harmony hub to connect. By default, * this is set to 5222. * * Returns: * (Q.promise) - The resolved promise passes the retrieved identity token. */ function getIdentity (hubhost, hubport) { debug('retrieve identity by logging in as guest') <|fim▁hole|> // [email protected] / guest // [email protected]/gatorade var deferred = Q.defer() var iqId var xmppClient = new Client({ jid: '[email protected]/gatorade', password: 'guest', host: hubhost, port: hubport, disallowTLS: true, reconnect: true }) xmppClient.on('online', function () { debug('XMPP client connected') var body = 'method=pair:name=harmonyjs#iOS6.0.1#iPhone' var iq = util.buildIqStanza( 'get', 'connect.logitech.com', 'vnd.logitech.connect/vnd.logitech.pair', body, 'guest') iqId = iq.attr('id') xmppClient.send(iq) }) xmppClient.on('error', function (e) { debug('XMPP client error', e) xmppClient.end() deferred.reject(e) }) xmppClient.on('stanza', function (stanza) { debug('received XMPP stanza: ' + stanza) if (stanza.attrs.id === iqId.toString()) { var body = stanza.getChildText('oa') var response = util.decodeColonSeparatedResponse(body) if (response.identity && response.identity !== undefined) { debug('received identity token: ' + response.identity) xmppClient.end() deferred.resolve(response.identity) } else { debug('could not find identity token') xmppClient.end() deferred.reject(new Error('Did not retrieve identity.')) } } }) return deferred.promise } /** PrivateFunction: loginWithIdentity * After fetching an identity from the Harmony hub, this function creates an * XMPP client using that identity. It returns a promise which, when resolved, * passes that XMPP client. * * Parameters: * (String) identity - Identity token to login to the Harmony hub. * (String) hubhost - Hostname/IP of the Harmony hub to connect. * (int) hubport - Optional. Port of the Harmony hub to connect. By default, * this is set to 5222. * * Returns: * (Q.promise) - When resolved, passes the logged in XMPP client, ready to * communicate with the Harmony hub. */ function loginWithIdentity (identity, hubhost, hubport) { debug('create xmpp client using retrieved identity token: ' + identity) var deferred = Q.defer() var jid = identity + '@connect.logitech.com/gatorade' var password = identity var xmppClient = new Client({ jid: jid, password: password, host: hubhost, port: hubport, disallowTLS: true }) xmppClient.on('error', function (e) { debug('XMPP login error', e) xmppClient.end() deferred.reject(e) }) xmppClient.once('online', function () { debug('XMPP client connected using identity token') deferred.resolve(xmppClient) }) return deferred.promise } /** Function: loginToHub * Uses a userAuthToken to login to a Harmony hub. * * Parameters: * (String) userAuthToken - A authentication token, retrieved from logitechs * web service. * (String) hubhost - Hostname/IP of the Harmony hub to connect. * (int) hubport - Optional. Port of the Harmony hub to connect. By default, * this is set to 5222. * * Returns: * (Q.promise) - The final resolved promise will pass a fully authenticated * XMPP client which can be used to communicate with the * Harmony hub. */ function loginToHub (hubhost, hubport) { debug('perform hub login') hubport = hubport || 5222 return getIdentity(hubhost, hubport) .then(function (identity) { return loginWithIdentity(identity, hubhost, hubport) }) } module.exports = loginToHub<|fim▁end|>
<|file_name|>atomic_nand_acq.rs<|end_file_name|><|fim▁begin|>#![feature(core, core_intrinsics)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::atomic_nand_acq; use core::cell::UnsafeCell; use std::sync::Arc; use std::thread; // pub fn atomic_nand_acq<T>(dst: *mut T, src: T) -> T; struct A<T> { v: UnsafeCell<T> } unsafe impl Sync for A<T> {} impl<T> A<T> { fn new(v: T) -> A<T> { A { v: UnsafeCell::<T>::new(v) } } } type T = usize; macro_rules! atomic_nand_acq_test { ($init:expr, $value:expr, $result:expr) => ({ let value: T = $init; let a: A<T> = A::<T>::new(value); let data: Arc<A<T>> = Arc::<A<T>>::new(a); let clone: Arc<A<T>> = data.clone();<|fim▁hole|> thread::spawn(move || { let dst: *mut T = clone.v.get(); let src: T = $value; let old: T = unsafe { atomic_nand_acq::<T>(dst, src) }; assert_eq!(old, $init); }); thread::sleep_ms(10); let ptr: *mut T = data.v.get(); assert_eq!(unsafe { *ptr }, $result); }) } #[test] fn atomic_nand_acq_test1() { atomic_nand_acq_test!( 0xff00, 0x0a0a, !0x0a00 ); } }<|fim▁end|>
<|file_name|>strava-creds.d.ts<|end_file_name|><|fim▁begin|>import { EpochSeconds, Seconds } from './util'; export declare type StravaCredsData = { token_type: string; expires_at: EpochSeconds; expires_in: EpochSeconds; refresh_token: string; access_token: string;<|fim▁hole|> id?: string; username?: string; [key: string]: any; }; }; export declare class StravaCreds { data: StravaCredsData; path: string; constructor(tokenFile: string); readonly expiresAt: EpochSeconds; readonly refreshToken: string; readonly accessToken: string; areValid(t?: Seconds): boolean; static validCredData(val: any): val is StravaCredsData; read(): Promise<void>; write(data: any): Promise<void>; }<|fim▁end|>
athlete: {
<|file_name|>test_sql.py<|end_file_name|><|fim▁begin|># # GeoCoon - GIS data analysis library based on Pandas and Shapely # # Copyright (C) 2014 by Artur Wroblewski <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. #<|fim▁hole|># from shapely.geometry import Point from geocoon.sql import read_sql from geocoon.core import GeoDataFrame, PointSeries import unittest from unittest import mock class SQLTestCase(unittest.TestCase): """ Test SQL GeoCoon SQL routines. """ @mock.patch('pandas.io.sql.read_sql') def test_read_sql(self, f_sql): """ Test SQL data frame read """ points = Point(1, 1), Point(2, 2), Point(3, 3) data = { 'a': PointSeries([p.wkb for p in points]), 'b': list(range(3)), } data = GeoDataFrame(data) data = data[['a', 'b']] f_sql.return_value = data result = read_sql('query', 'con', geom_col='a') self.assertEqual(PointSeries, type(result.a)) self.assertEqual(Point, type(result.a[0])) self.assertEqual(3, len(result.index)) self.assertTrue(all([1, 2, 3] == result.a.x)) self.assertTrue(all([1, 2, 3] == result.a.y)) # vim: sw=4:et:ai<|fim▁end|>
# You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>.
<|file_name|>dazeus.rs<|end_file_name|><|fim▁begin|>use super::error::{Error, ReceiveError}; use super::event::{Event, EventType}; use super::handler::{Handler, Message}; use super::listener::{Listener, ListenerHandle}; use super::request::{ConfigGroup, Request}; use super::response::Response; use super::scope::Scope; use std::cell::RefCell; use std::io::{Read, Write}; struct ResponseQueue { pub responses: Vec<Response>, pub expecting: u64, } /// The base DaZeus struct. /// /// See the [crate documentation](./index.html) for a more detailed instruction on how to get /// started with these DaZeus bindings. pub struct DaZeus<'a, T> { handler: RefCell<Handler<T>>, listeners: Vec<Listener<'a>>, current_handle: u64, queue: RefCell<ResponseQueue>, } impl<'a, T> DaZeus<'a, T> where T: Read + Write, { /// Create a new instance of DaZeus from the given connection. pub fn new(conn: T) -> DaZeus<'a, T> { DaZeus { handler: RefCell::new(Handler::new(conn)), listeners: Vec::new(), current_handle: 1, queue: RefCell::new(ResponseQueue { responses: Vec::new(), expecting: 0, }), } } /// Loop wait for messages to receive in a blocking way. pub fn listen(&self) -> Result<(), Error> { loop { self.try_next_event()?; } } fn next_response(&self) -> Result<Response, Error> { { self.queue.borrow_mut().expecting += 1; } loop { { let mut queue = self.queue.borrow_mut(); if !queue.responses.is_empty() && queue.expecting == 0 { return Ok(queue.responses.pop().unwrap()); } } let msg = { self.handler.borrow_mut().read() }; match msg? { Message::Event(e) => self.handle_event(e), Message::Response(r) => { let mut queue = self.queue.borrow_mut(); queue.expecting -= 1; if queue.expecting == 0 { return Ok(r); } else { queue.responses.push(r); } } } } } fn try_next_event(&self) -> Result<Event, Error> { let msg = { self.handler.borrow_mut().read() }; match msg? { Message::Event(e) => { self.handle_event(e.clone()); Ok(e) } Message::Response(_) => Err(Error::ReceiveError(ReceiveError::new())), } } fn next_event(&self) -> Event { match self.try_next_event() { Ok(evt) => evt, Err(e) => panic!("{}", e), } } /// Handle an event received by calling all event listeners listening for that event type. fn handle_event(&self, event: Event) { for listener in self.listeners.iter() { if listener.event == event.event { listener.call(event.clone(), self); } } } /// Subscribe to an event type and call the callback function every time such an event occurs. pub fn subscribe<F>(&mut self, event: EventType, callback: F) -> (ListenerHandle, Response) where F: FnMut(Event, &dyn DaZeusClient) + 'a, { let request = match event { EventType::Command(ref cmd) => Request::SubscribeCommand(cmd.clone(), None), _ => Request::Subscribe(event.clone()), }; let handle = self.current_handle; self.current_handle += 1; let listener = Listener::new(handle, event, callback); self.listeners.push(listener); (handle, self.send(request)) } /// Subscribe to a command and call the callback function every time such a command occurs. pub fn subscribe_command<F>(&mut self, command: &str, callback: F) -> (ListenerHandle, Response) where F: FnMut(Event, &dyn DaZeusClient) + 'a, { self.subscribe(EventType::Command(command.to_string()), callback) } } /// Methods for interaction with the DaZeus server. pub trait DaZeusClient<'a> { /// Try to send a request to DaZeus fn try_send(&self, request: Request) -> Result<Response, Error>; /// Send a request to DaZeus and retrieve a Future in which the response will be contained. fn send(&self, request: Request) -> Response; /// Unsubscribe a listener for some event. fn unsubscribe(&mut self, handle: ListenerHandle) -> Response; /// Remove all subscriptions for a specific event type. fn unsubscribe_all(&mut self, event: EventType) -> Response; /// Check if there is any active listener for the given event type. fn has_any_subscription(&self, event: EventType) -> bool; /// Retrieve the networks the bot is connected to. fn networks(&self) -> Response; /// Retrieve the channels the bot is in for a given network. fn channels(&self, network: &str) -> Response; /// Send a message to a specific channel using the PRIVMSG method. fn message(&self, network: &str, channel: &str, message: &str) -> Response; /// Send a CTCP NOTICE to a specific channel. fn notice(&self, network: &str, channel: &str, message: &str) -> Response; /// Send a CTCP REQUEST to a specific channel. fn ctcp(&self, network: &str, channel: &str, message: &str) -> Response; /// Send a CTCP REPLY to a specific channel. fn ctcp_reply(&self, network: &str, channel: &str, message: &str) -> Response; /// Send a CTCP ACTION to a specific channel fn action(&self, network: &str, channel: &str, message: &str) -> Response; /// Send a request for the list of nicks in a channel. /// /// Note that the response will not contain the names data, instead listen for a names event. /// The Response will only indicate whether or not the request has been submitted successfully. /// The server may respond with an `EventType::Names` event any time after this request has /// been submitted. fn send_names(&self, network: &str, channel: &str) -> Response; /// Send a request for a whois of a specific nick on some network. /// /// Note that the response will not contain the whois data, instead listen for a whois event. /// The Response will only indicate whether or not the request has been submitted successfully. /// The server may respond with an `EventType::Whois` event any time after this request has /// been submitted. fn send_whois(&self, network: &str, nick: &str) -> Response; /// Try to join a channel on some network. fn join(&self, network: &str, channel: &str) -> Response; /// Try to leave a channel on some network. fn part(&self, network: &str, channel: &str) -> Response; /// Retrieve the nickname of the bot on the given network. fn nick(&self, network: &str) -> Option<String>; /// Send a handshake to the DaZeus core. fn handshake(&self, name: &str, version: &str, config: Option<&str>) -> Response; /// Retrieve a config value from the DaZeus config. fn get_config(&self, name: &str, group: ConfigGroup) -> Response; /// Retrieve the character that is used by the bot for highlighting. fn get_highlight_char(&self) -> Option<String>; /// Retrieve a property stored in the bot database. fn get_property(&self, name: &str, scope: Scope) -> Response; /// Set a property to be stored in the bot database. fn set_property(&self, name: &str, value: &str, scope: Scope) -> Response; <|fim▁hole|> /// Retrieve a list of keys starting with the common prefix with the given scope. fn get_property_keys(&self, prefix: &str, scope: Scope) -> Response; /// Set a permission to either allow or deny for a specific scope. fn set_permission(&self, permission: &str, allow: bool, scope: Scope) -> Response; /// Retrieve whether for some scope the given permission was set. /// /// Will return the default if it was not. fn has_permission(&self, permission: &str, default: bool, scope: Scope) -> Response; /// Remove a set permission from the bot. fn unset_permission(&self, permission: &str, scope: Scope) -> Response; /// Send a whois request and wait for an event that answers this request (blocking). /// /// Note that the IRC server may not respond to the whois request (if it has been configured /// this way), in which case this request will block forever. fn whois(&mut self, network: &str, nick: &str) -> Event; /// Send a names request and wait for an event that answers this request (blocking). /// /// Note that the IRC server may not respond to the names request (if it has been configured /// this way), in which case this request will block forever. fn names(&mut self, network: &str, channel: &str) -> Event; /// Send a reply in response to some event. /// /// Note that not all types of events can be responded to. Mostly message type events /// concerning some IRC user can be responded to. Join events can also be responded to. fn reply(&self, event: &Event, message: &str, highlight: bool) -> Response; /// Send a reply (as a notice) in response to some event. /// /// Note that not all types of events can be responded to. Mostly message type events /// concerning some IRC user can be responded to. Join events can also be responded to. fn reply_with_notice(&self, event: &Event, message: &str) -> Response; /// Send a reply (as a ctcp action) in response to some event. /// /// Note that not all types of events can be responded to. Mostly message type events /// concerning some IRC user can be responded to. Join events can also be responded to. fn reply_with_action(&self, event: &Event, message: &str) -> Response; } impl<'a, T> DaZeusClient<'a> for DaZeus<'a, T> where T: Read + Write, { /// Try to send a request to DaZeus fn try_send(&self, request: Request) -> Result<Response, Error> { self.handler.borrow_mut().write(request)?; self.next_response() } /// Send a request to DaZeus and retrieve a Future in which the response will be contained. fn send(&self, request: Request) -> Response { match self.try_send(request) { Ok(response) => response, Err(e) => panic!("{}", e), } } /// Unsubscribe a listener for some event. fn unsubscribe(&mut self, handle: ListenerHandle) -> Response { // first find the event type let event = { match self.listeners.iter().find(|l| l.has_handle(handle)) { Some(listener) => Some(listener.event.clone()), None => None, } }; self.listeners.retain(|l| !l.has_handle(handle)); match event { // we can't unsubscribe commands Some(EventType::Command(_)) => Response::for_success(), // unsubscribe if there are no more listeners for the event Some(evt) => { if self.listeners.iter().any(|l| l.event == evt) { Response::for_success() } else { self.send(Request::Unsubscribe(evt)) } } None => Response::for_fail("Could not find listener with given handle"), } } /// Remove all subscriptions for a specific event type. fn unsubscribe_all(&mut self, event: EventType) -> Response { self.listeners.retain(|l| l.event != event); match event { EventType::Command(_) => Response::for_success(), _ => self.send(Request::Unsubscribe(event)), } } /// Check if there is any active listener for the given event type. fn has_any_subscription(&self, event: EventType) -> bool { self.listeners.iter().any(|l| l.event == event) } /// Retrieve the networks the bot is connected to. fn networks(&self) -> Response { self.send(Request::Networks) } /// Retrieve the channels the bot is in for a given network. fn channels(&self, network: &str) -> Response { self.send(Request::Channels(network.to_string())) } /// Send a message to a specific channel using the PRIVMSG method. fn message(&self, network: &str, channel: &str, message: &str) -> Response { self.send(Request::Message( network.to_string(), channel.to_string(), message.to_string(), )) } /// Send a CTCP NOTICE to a specific channel. fn notice(&self, network: &str, channel: &str, message: &str) -> Response { self.send(Request::Notice( network.to_string(), channel.to_string(), message.to_string(), )) } /// Send a CTCP REQUEST to a specific channel. fn ctcp(&self, network: &str, channel: &str, message: &str) -> Response { self.send(Request::Ctcp( network.to_string(), channel.to_string(), message.to_string(), )) } /// Send a CTCP REPLY to a specific channel. fn ctcp_reply(&self, network: &str, channel: &str, message: &str) -> Response { self.send(Request::CtcpReply( network.to_string(), channel.to_string(), message.to_string(), )) } /// Send a CTCP ACTION to a specific channel fn action(&self, network: &str, channel: &str, message: &str) -> Response { self.send(Request::Action( network.to_string(), channel.to_string(), message.to_string(), )) } /// Send a request for the list of nicks in a channel. /// /// Note that the response will not contain the names data, instead listen for a names event. /// The Response will only indicate whether or not the request has been submitted successfully. /// The server may respond with an `EventType::Names` event any time after this request has /// been submitted. fn send_names(&self, network: &str, channel: &str) -> Response { self.send(Request::Names(network.to_string(), channel.to_string())) } /// Send a request for a whois of a specific nick on some network. /// /// Note that the response will not contain the whois data, instead listen for a whois event. /// The Response will only indicate whether or not the request has been submitted successfully. /// The server may respond with an `EventType::Whois` event any time after this request has /// been submitted. fn send_whois(&self, network: &str, nick: &str) -> Response { self.send(Request::Whois(network.to_string(), nick.to_string())) } /// Try to join a channel on some network. fn join(&self, network: &str, channel: &str) -> Response { self.send(Request::Join(network.to_string(), channel.to_string())) } /// Try to leave a channel on some network. fn part(&self, network: &str, channel: &str) -> Response { self.send(Request::Part(network.to_string(), channel.to_string())) } /// Retrieve the nickname of the bot on the given network. fn nick(&self, network: &str) -> Option<String> { let resp = self.send(Request::Nick(network.to_string())); match resp.get_str("nick") { Some(s) => Some(s.to_string()), None => None, } } /// Send a handshake to the DaZeus core. fn handshake(&self, name: &str, version: &str, config: Option<&str>) -> Response { let n = name.to_string(); let v = version.to_string(); let req = match config { Some(config_name) => Request::Handshake(n, v, Some(config_name.to_string())), None => Request::Handshake(n, v, None), }; self.send(req) } /// Retrieve a config value from the DaZeus config. fn get_config(&self, name: &str, group: ConfigGroup) -> Response { self.send(Request::Config(name.to_string(), group)) } /// Retrieve the character that is used by the bot for highlighting. fn get_highlight_char(&self) -> Option<String> { let resp = self.get_config("highlight", ConfigGroup::Core); match resp.get_str("value") { Some(s) => Some(s.to_string()), None => None, } } /// Retrieve a property stored in the bot database. fn get_property(&self, name: &str, scope: Scope) -> Response { self.send(Request::GetProperty(name.to_string(), scope)) } /// Set a property to be stored in the bot database. fn set_property(&self, name: &str, value: &str, scope: Scope) -> Response { self.send(Request::SetProperty( name.to_string(), value.to_string(), scope, )) } /// Remove a property stored in the bot database. fn unset_property(&self, name: &str, scope: Scope) -> Response { self.send(Request::UnsetProperty(name.to_string(), scope)) } /// Retrieve a list of keys starting with the common prefix with the given scope. fn get_property_keys(&self, prefix: &str, scope: Scope) -> Response { self.send(Request::PropertyKeys(prefix.to_string(), scope)) } /// Set a permission to either allow or deny for a specific scope. fn set_permission(&self, permission: &str, allow: bool, scope: Scope) -> Response { self.send(Request::SetPermission(permission.to_string(), allow, scope)) } /// Retrieve whether for some scope the given permission was set. /// /// Will return the default if it was not. fn has_permission(&self, permission: &str, default: bool, scope: Scope) -> Response { self.send(Request::HasPermission( permission.to_string(), default, scope, )) } /// Remove a set permission from the bot. fn unset_permission(&self, permission: &str, scope: Scope) -> Response { self.send(Request::UnsetPermission(permission.to_string(), scope)) } /// Send a whois request and wait for an event that answers this request (blocking). /// /// Note that the IRC server may not respond to the whois request (if it has been configured /// this way), in which case this request will block forever. fn whois(&mut self, network: &str, nick: &str) -> Event { if !self.has_any_subscription(EventType::Whois) { self.send(Request::Subscribe(EventType::Whois)); } self.send_whois(network, nick); loop { let evt = self.next_event(); match evt.event { EventType::Whois if &evt[0] == network && &evt[2] == nick => { if !self.has_any_subscription(EventType::Whois) { self.send(Request::Unsubscribe(EventType::Whois)); } return evt; } _ => (), } } } /// Send a names request and wait for an event that answers this request (blocking). /// /// Note that the IRC server may not respond to the names request (if it has been configured /// this way), in which case this request will block forever. fn names(&mut self, network: &str, channel: &str) -> Event { if !self.has_any_subscription(EventType::Names) { self.send(Request::Subscribe(EventType::Names)); } self.send_names(network, channel); loop { let evt = self.next_event(); match evt.event { EventType::Names if &evt[0] == network && &evt[2] == channel => { if !self.has_any_subscription(EventType::Names) { self.send(Request::Unsubscribe(EventType::Names)); } return evt; } _ => (), } } } /// Send a reply in response to some event. /// /// Note that not all types of events can be responded to. Mostly message type events /// concerning some IRC user can be responded to. Join events can also be responded to. fn reply(&self, event: &Event, message: &str, highlight: bool) -> Response { if let Some((network, channel, user)) = targets_for_event(event) { let nick = self.nick(network).unwrap_or_else(|| "".to_string()); if channel == nick { self.message(network, user, message) } else if highlight { let msg = format!("{}: {}", user, message); self.message(network, channel, &msg[..]) } else { self.message(network, channel, message) } } else { Response::for_fail("Not an event to reply to") } } /// Send a reply (as a notice) in response to some event. /// /// Note that not all types of events can be responded to. Mostly message type events /// concerning some IRC user can be responded to. Join events can also be responded to. fn reply_with_notice(&self, event: &Event, message: &str) -> Response { if let Some((network, channel, user)) = targets_for_event(event) { let nick = self.nick(network).unwrap_or_else(|| "".to_string()); if channel == nick { self.notice(network, user, message) } else { self.notice(network, channel, message) } } else { Response::for_fail("Not an event to reply to") } } /// Send a reply (as a CTCP action) in response to some event. /// /// Note that not all types of events can be responded to. Mostly message type events /// concerning some IRC user can be responded to. Join events can also be responded to. fn reply_with_action(&self, event: &Event, message: &str) -> Response { if let Some((network, channel, user)) = targets_for_event(event) { let nick = self.nick(network).unwrap_or_else(|| "".to_string()); if channel == nick { self.action(network, user, message) } else { self.action(network, channel, message) } } else { Response::for_fail("Not an event to reply to") } } } fn targets_for_event(event: &Event) -> Option<(&str, &str, &str)> { let params = &event.params; match event.event { EventType::Join | EventType::PrivMsg | EventType::Notice | EventType::Ctcp | EventType::Command(_) | EventType::Action => Some((&params[0][..], &params[2][..], &params[1][..])), _ => None, } }<|fim▁end|>
/// Remove a property stored in the bot database. fn unset_property(&self, name: &str, scope: Scope) -> Response;
<|file_name|>starting_hand.rs<|end_file_name|><|fim▁begin|>use crate::core::{Card, Hand, Suit, Value}; /// Enum to represent how the suits of a hand correspond to each other. /// `Suitedness::Suited` will mean that all cards have the same suit /// `Suitedness::OffSuit` will mean that all cards have the different suit /// `Suitedness::Any` makes no promises. #[derive(Debug, Eq, PartialEq, PartialOrd, Ord, Clone, Copy)] pub enum Suitedness { /// All of the cards are the same suit Suited, /// None of the cards are the same suit OffSuit, /// No promises about suit. Any, } /// `HoldemStartingHand` represents the two card starting hand of texas holdem. /// It can generate all the possible actual starting hands. /// /// Give two values and if you only want suited variants. #[derive(Debug, Eq, PartialEq, PartialOrd, Ord, Clone)] pub struct Default { /// The first value. value_one: Value, /// The second value. value_two: Value, /// should we only consider possible starting hands of the same suit? suited: Suitedness, } impl Default { /// Is this starting hand a pocket pair? fn is_pair(&self) -> bool { self.value_one == self.value_two } /// Create a new vector of all suited hands. fn create_suited(&self) -> Vec<Hand> { // Can't have a suited pair. Not unless you're cheating. if self.is_pair() { return vec![]; } Suit::suits() .iter() .map(|s| { Hand::new_with_cards(vec![ Card { value: self.value_one, suit: *s, }, Card { value: self.value_two, suit: *s, }, ]) }) .collect() } /// Create a new vector of all the off suit hands. fn create_offsuit(&self) -> Vec<Hand> { // Since the values are the same there is no reason to swap the suits. let expected_hands = if self.is_pair() { 6 } else { 12 }; self.append_offsuit(Vec::with_capacity(expected_hands)) } /// Append all the off suit hands to the passed in vec and /// then return it. /// /// @returns the passed in vector with offsuit hands appended. fn append_offsuit(&self, mut hands: Vec<Hand>) -> Vec<Hand> { let suits = Suit::suits(); for (i, suit_one) in suits.iter().enumerate() { for suit_two in &suits[i + 1..] { // Push the hands in. hands.push(Hand::new_with_cards(vec![ Card { value: self.value_one, suit: *suit_one, }, Card { value: self.value_two, suit: *suit_two, }, ])); // If this isn't a pair then the flipped suits is needed. if self.value_one != self.value_two { hands.push(Hand::new_with_cards(vec![ Card { value: self.value_one, suit: *suit_two, }, Card { value: self.value_two, suit: *suit_one, }, ])); } } } hands } /// Get all the possible starting hands represented by the /// two values of this starting hand. fn possible_hands(&self) -> Vec<Hand> { match self.suited { Suitedness::Suited => self.create_suited(), Suitedness::OffSuit => self.create_offsuit(), Suitedness::Any => self.append_offsuit(self.create_suited()), } } }<|fim▁hole|>/// static card and a range for the other. #[derive(Debug, PartialEq, Eq, PartialOrd)] pub struct SingleCardRange { /// First value; this one will not change. value_one: Value, /// Inclusive start range start: Value, /// Inclusive end range end: Value, /// What Suits can this have. suited: Suitedness, } impl SingleCardRange { /// Generate all the possible hands for this starting hand type. fn possible_hands(&self) -> Vec<Hand> { let mut cur_value = self.start; let mut hands = vec![]; // TODO: Make a better iterator for values. while cur_value <= self.end { let mut new_hands = Default { value_one: self.value_one, value_two: cur_value, suited: self.suited, } .possible_hands(); hands.append(&mut new_hands); cur_value = Value::from_u8(cur_value as u8 + 1); } hands } } /// Enum to represent all the possible ways to specify a starting hand. #[derive(Debug, PartialEq, Eq, PartialOrd)] pub enum StartingHand { /// Default starting hand type. This means that we /// specify two cards and their suitedness. Def(Default), /// A starting hand where the second card is a range. SingleCardRange(SingleCardRange), } impl StartingHand { /// Create a default starting hand with two `Value`'s and a `Suitedness`. pub fn default(value_one: Value, value_two: Value, suited: Suitedness) -> Self { Self::Def(Default { value_one, value_two, suited, }) } /// Create a new StartingHand with the second card being a range. pub fn single_range(value_one: Value, start: Value, end: Value, suited: Suitedness) -> Self { Self::SingleCardRange(SingleCardRange { value_one, start, end, suited, }) } /// Create every possible unique StartingHand. pub fn all() -> Vec<Self> { let mut hands = Vec::with_capacity(169); let values = Value::values(); for (i, value_one) in values.iter().enumerate() { for value_two in &values[i..] { hands.push(Self::Def(Default { value_one: *value_one, value_two: *value_two, suited: Suitedness::OffSuit, })); if value_one != value_two { hands.push(Self::Def(Default { value_one: *value_one, value_two: *value_two, suited: Suitedness::Suited, })); } } } hands } /// From a `StartingHand` specify all the hands this could represent. pub fn possible_hands(&self) -> Vec<Hand> { match *self { Self::Def(ref h) => h.possible_hands(), Self::SingleCardRange(ref h) => h.possible_hands(), } } } #[cfg(test)] mod tests { use super::*; use crate::core::Value; #[test] fn test_aces() { let sh = Default { value_one: Value::Ace, value_two: Value::Ace, suited: Suitedness::OffSuit, }; assert!(6 == sh.possible_hands().len()); } #[test] fn test_suited_connector() { let sh = Default { value_one: Value::Ace, value_two: Value::King, suited: Suitedness::Suited, }; assert!(4 == sh.possible_hands().len()); } #[test] fn test_unsuited_connector() { let sh = Default { value_one: Value::Ace, value_two: Value::King, suited: Suitedness::OffSuit, }; assert!(12 == sh.possible_hands().len()); } #[test] fn test_starting_hand_count() { let num_to_test: usize = StartingHand::all() .iter() .map(|h| h.possible_hands().len()) .sum(); assert!(1326 == num_to_test); } }<|fim▁end|>
/// Starting hand struct to represent where it's one
<|file_name|>filesize.rs<|end_file_name|><|fim▁begin|>use std::fmt; #[derive(Debug)] enum FileSize { B, KB, MB, GB, TB, } impl fmt::Display for FileSize { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self) } } impl FileSize { fn value(&self) -> u64 { match *self { FileSize::B => 1, FileSize::KB => 1_024, FileSize::MB => 1_048_576, FileSize::GB => 1_073_741_824,<|fim▁hole|> pub fn format_filesize(size: u64) -> String { let (file_size, unit) = match size { 0...999 => (size as f64, FileSize::B), 1_000...999_999 => (size as f64 / FileSize::KB.value() as f64, FileSize::KB), 1_000_000...999_999_999 => (size as f64 / FileSize::MB.value() as f64, FileSize::MB), 1_000_000_000...999_999_999_999 => { (size as f64 / FileSize::GB.value() as f64, FileSize::GB) } _ => (size as f64 / FileSize::TB.value() as f64, FileSize::TB), }; format!("{:.2} {}", file_size, unit) }<|fim▁end|>
FileSize::TB => 1_099_511_627_776, } } }
<|file_name|>18.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -8- """ By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. 3 7 4 2 4 6 8 5 9 3 That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom of the triangle below: """ triangle = """ 75 95 64 17 47 82 18 35 87 10<|fim▁hole|> 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 38 17 14 91 43 58 50 27 29 48 63 66 04 68 89 53 67 30 73 16 69 87 40 31 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23 """ def largest_triangle_sum(values, row=0, column=0, sums={}): if (row, column) in sums: return sums[row, column] s = values[row][column] if row + 1 < len(values): left = largest_triangle_sum(values, row + 1, column, sums) right = largest_triangle_sum(values, row + 1, column + 1, sums) s += max([left, right]) sums[row, column] = s return s def main(): values = [[int(j) for j in i.split()] for i in triangle.split('\n') if i] print(largest_triangle_sum(values)) if __name__ == '__main__': main()<|fim▁end|>
20 04 82 47 65
<|file_name|>cover.py<|end_file_name|><|fim▁begin|>"""Support for ZHA covers.""" from __future__ import annotations import asyncio import functools import logging from zigpy.zcl.foundation import Status from homeassistant.components.cover import ( ATTR_CURRENT_POSITION, ATTR_POSITION, DEVICE_CLASS_DAMPER, DEVICE_CLASS_SHADE, DOMAIN, CoverEntity, ) from homeassistant.const import STATE_CLOSED, STATE_CLOSING, STATE_OPEN, STATE_OPENING from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from .core import discovery from .core.const import ( CHANNEL_COVER, CHANNEL_LEVEL, CHANNEL_ON_OFF, CHANNEL_SHADE, DATA_ZHA, DATA_ZHA_DISPATCHERS, SIGNAL_ADD_ENTITIES, SIGNAL_ATTR_UPDATED, SIGNAL_SET_LEVEL, ) from .core.registries import ZHA_ENTITIES from .core.typing import ChannelType, ZhaDeviceType from .entity import ZhaEntity _LOGGER = logging.getLogger(__name__) STRICT_MATCH = functools.partial(ZHA_ENTITIES.strict_match, DOMAIN) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Zigbee Home Automation cover from config entry.""" entities_to_create = hass.data[DATA_ZHA][DOMAIN] unsub = async_dispatcher_connect( hass, SIGNAL_ADD_ENTITIES, functools.partial( discovery.async_add_entities, async_add_entities, entities_to_create ), ) hass.data[DATA_ZHA][DATA_ZHA_DISPATCHERS].append(unsub) @STRICT_MATCH(channel_names=CHANNEL_COVER) class ZhaCover(ZhaEntity, CoverEntity): """Representation of a ZHA cover.""" def __init__(self, unique_id, zha_device, channels, **kwargs): """Init this sensor.""" super().__init__(unique_id, zha_device, channels, **kwargs) self._cover_channel = self.cluster_channels.get(CHANNEL_COVER) self._current_position = None async def async_added_to_hass(self): """Run when about to be added to hass.""" await super().async_added_to_hass() self.async_accept_signal( self._cover_channel, SIGNAL_ATTR_UPDATED, self.async_set_position ) @callback<|fim▁hole|> self._state = last_state.state if "current_position" in last_state.attributes: self._current_position = last_state.attributes["current_position"] @property def is_closed(self): """Return if the cover is closed.""" if self.current_cover_position is None: return None return self.current_cover_position == 0 @property def is_opening(self): """Return if the cover is opening or not.""" return self._state == STATE_OPENING @property def is_closing(self): """Return if the cover is closing or not.""" return self._state == STATE_CLOSING @property def current_cover_position(self): """Return the current position of ZHA cover. None is unknown, 0 is closed, 100 is fully open. """ return self._current_position @callback def async_set_position(self, attr_id, attr_name, value): """Handle position update from channel.""" _LOGGER.debug("setting position: %s", value) self._current_position = 100 - value if self._current_position == 0: self._state = STATE_CLOSED elif self._current_position == 100: self._state = STATE_OPEN self.async_write_ha_state() @callback def async_update_state(self, state): """Handle state update from channel.""" _LOGGER.debug("state=%s", state) self._state = state self.async_write_ha_state() async def async_open_cover(self, **kwargs): """Open the window cover.""" res = await self._cover_channel.up_open() if isinstance(res, list) and res[1] is Status.SUCCESS: self.async_update_state(STATE_OPENING) async def async_close_cover(self, **kwargs): """Close the window cover.""" res = await self._cover_channel.down_close() if isinstance(res, list) and res[1] is Status.SUCCESS: self.async_update_state(STATE_CLOSING) async def async_set_cover_position(self, **kwargs): """Move the roller shutter to a specific position.""" new_pos = kwargs[ATTR_POSITION] res = await self._cover_channel.go_to_lift_percentage(100 - new_pos) if isinstance(res, list) and res[1] is Status.SUCCESS: self.async_update_state( STATE_CLOSING if new_pos < self._current_position else STATE_OPENING ) async def async_stop_cover(self, **kwargs): """Stop the window cover.""" res = await self._cover_channel.stop() if isinstance(res, list) and res[1] is Status.SUCCESS: self._state = STATE_OPEN if self._current_position > 0 else STATE_CLOSED self.async_write_ha_state() async def async_update(self): """Attempt to retrieve the open/close state of the cover.""" await super().async_update() await self.async_get_state() async def async_get_state(self, from_cache=True): """Fetch the current state.""" _LOGGER.debug("polling current state") if self._cover_channel: pos = await self._cover_channel.get_attribute_value( "current_position_lift_percentage", from_cache=from_cache ) _LOGGER.debug("read pos=%s", pos) if pos is not None: self._current_position = 100 - pos self._state = ( STATE_OPEN if self.current_cover_position > 0 else STATE_CLOSED ) else: self._current_position = None self._state = None @STRICT_MATCH(channel_names={CHANNEL_LEVEL, CHANNEL_ON_OFF, CHANNEL_SHADE}) class Shade(ZhaEntity, CoverEntity): """ZHA Shade.""" _attr_device_class = DEVICE_CLASS_SHADE def __init__( self, unique_id: str, zha_device: ZhaDeviceType, channels: list[ChannelType], **kwargs, ) -> None: """Initialize the ZHA light.""" super().__init__(unique_id, zha_device, channels, **kwargs) self._on_off_channel = self.cluster_channels[CHANNEL_ON_OFF] self._level_channel = self.cluster_channels[CHANNEL_LEVEL] self._position = None self._is_open = None @property def current_cover_position(self): """Return current position of cover. None is unknown, 0 is closed, 100 is fully open. """ return self._position @property def is_closed(self) -> bool | None: """Return True if shade is closed.""" if self._is_open is None: return None return not self._is_open async def async_added_to_hass(self): """Run when about to be added to hass.""" await super().async_added_to_hass() self.async_accept_signal( self._on_off_channel, SIGNAL_ATTR_UPDATED, self.async_set_open_closed ) self.async_accept_signal( self._level_channel, SIGNAL_SET_LEVEL, self.async_set_level ) @callback def async_restore_last_state(self, last_state): """Restore previous state.""" self._is_open = last_state.state == STATE_OPEN if ATTR_CURRENT_POSITION in last_state.attributes: self._position = last_state.attributes[ATTR_CURRENT_POSITION] @callback def async_set_open_closed(self, attr_id: int, attr_name: str, value: bool) -> None: """Set open/closed state.""" self._is_open = bool(value) self.async_write_ha_state() @callback def async_set_level(self, value: int) -> None: """Set the reported position.""" value = max(0, min(255, value)) self._position = int(value * 100 / 255) self.async_write_ha_state() async def async_open_cover(self, **kwargs): """Open the window cover.""" res = await self._on_off_channel.on() if not isinstance(res, list) or res[1] != Status.SUCCESS: self.debug("couldn't open cover: %s", res) return self._is_open = True self.async_write_ha_state() async def async_close_cover(self, **kwargs): """Close the window cover.""" res = await self._on_off_channel.off() if not isinstance(res, list) or res[1] != Status.SUCCESS: self.debug("couldn't open cover: %s", res) return self._is_open = False self.async_write_ha_state() async def async_set_cover_position(self, **kwargs): """Move the roller shutter to a specific position.""" new_pos = kwargs[ATTR_POSITION] res = await self._level_channel.move_to_level_with_on_off( new_pos * 255 / 100, 1 ) if not isinstance(res, list) or res[1] != Status.SUCCESS: self.debug("couldn't set cover's position: %s", res) return self._position = new_pos self.async_write_ha_state() async def async_stop_cover(self, **kwargs) -> None: """Stop the cover.""" res = await self._level_channel.stop() if not isinstance(res, list) or res[1] != Status.SUCCESS: self.debug("couldn't stop cover: %s", res) return @STRICT_MATCH( channel_names={CHANNEL_LEVEL, CHANNEL_ON_OFF}, manufacturers="Keen Home Inc" ) class KeenVent(Shade): """Keen vent cover.""" _attr_device_class = DEVICE_CLASS_DAMPER async def async_open_cover(self, **kwargs): """Open the cover.""" position = self._position or 100 tasks = [ self._level_channel.move_to_level_with_on_off(position * 255 / 100, 1), self._on_off_channel.on(), ] results = await asyncio.gather(*tasks, return_exceptions=True) if any(isinstance(result, Exception) for result in results): self.debug("couldn't open cover") return self._is_open = True self._position = position self.async_write_ha_state()<|fim▁end|>
def async_restore_last_state(self, last_state): """Restore previous state."""
<|file_name|>dwellClick.js<|end_file_name|><|fim▁begin|>/* exported DwellClickIndicator */ const { Clutter, Gio, GLib, GObject, St } = imports.gi; const PanelMenu = imports.ui.panelMenu; const MOUSE_A11Y_SCHEMA = 'org.gnome.desktop.a11y.mouse'; const KEY_DWELL_CLICK_ENABLED = 'dwell-click-enabled'; const KEY_DWELL_MODE = 'dwell-mode'; const DWELL_MODE_WINDOW = 'window'; const DWELL_CLICK_MODES = { primary: { name: _("Single Click"), icon: 'pointer-primary-click-symbolic', type: Clutter.PointerA11yDwellClickType.PRIMARY, }, double: { name: _("Double Click"), icon: 'pointer-double-click-symbolic', type: Clutter.PointerA11yDwellClickType.DOUBLE, }, drag: { name: _("Drag"), icon: 'pointer-drag-symbolic', type: Clutter.PointerA11yDwellClickType.DRAG, }, secondary: { name: _("Secondary Click"), icon: 'pointer-secondary-click-symbolic', type: Clutter.PointerA11yDwellClickType.SECONDARY, }, }; var DwellClickIndicator = GObject.registerClass( class DwellClickIndicator extends PanelMenu.Button { _init() { super._init(0.5, _("Dwell Click")); this._icon = new St.Icon({ style_class: 'system-status-icon', icon_name: 'pointer-primary-click-symbolic' }); this.add_child(this._icon); this._a11ySettings = new Gio.Settings({ schema_id: MOUSE_A11Y_SCHEMA }); this._a11ySettings.connect('changed::%s'.format(KEY_DWELL_CLICK_ENABLED), this._syncMenuVisibility.bind(this)); this._a11ySettings.connect('changed::%s'.format(KEY_DWELL_MODE), this._syncMenuVisibility.bind(this)); this._seat = Clutter.get_default_backend().get_default_seat(); this._seat.connect('ptr-a11y-dwell-click-type-changed', this._updateClickType.bind(this)); this._addDwellAction(DWELL_CLICK_MODES.primary); this._addDwellAction(DWELL_CLICK_MODES.double); this._addDwellAction(DWELL_CLICK_MODES.drag); this._addDwellAction(DWELL_CLICK_MODES.secondary); this._setClickType(DWELL_CLICK_MODES.primary); this._syncMenuVisibility(); } _syncMenuVisibility() { this.visible = this._a11ySettings.get_boolean(KEY_DWELL_CLICK_ENABLED) && this._a11ySettings.get_string(KEY_DWELL_MODE) == DWELL_MODE_WINDOW; return GLib.SOURCE_REMOVE; } _addDwellAction(mode) {<|fim▁hole|> } _updateClickType(manager, clickType) { for (let mode in DWELL_CLICK_MODES) { if (DWELL_CLICK_MODES[mode].type == clickType) this._icon.icon_name = DWELL_CLICK_MODES[mode].icon; } } _setClickType(mode) { this._seat.set_pointer_a11y_dwell_click_type(mode.type); this._icon.icon_name = mode.icon; } });<|fim▁end|>
this.menu.addAction(mode.name, this._setClickType.bind(this, mode), mode.icon);
<|file_name|>form-password.min.js<|end_file_name|><|fim▁begin|>version https://git-lfs.github.com/spec/v1<|fim▁hole|><|fim▁end|>
oid sha256:5df6faea233808c6556f6ab7b79d7e126b054faf6651af82437fe36f225404cf size 1193
<|file_name|>dialect.go<|end_file_name|><|fim▁begin|>// Copyright 2015 CoreOS, Inc. All rights reserved. // Use of this source code is governed by the BSD 3-Clause license, // which can be found in the LICENSE file. package sqlbuilder type Dialect interface { EscapeCharacter() rune InsertReturningClause() string Kind() string Name() *string } type genericDialect struct { escapeChar rune returningClause string kind string name *string } func (db *genericDialect) EscapeCharacter() rune { return db.escapeChar } func (db *genericDialect) InsertReturningClause() string { return db.returningClause } func (db *genericDialect) Kind() string { return db.kind } func (db *genericDialect) Name() *string { return db.name } func NewMySQLDialect(dbName *string) Dialect { return &genericDialect{ escapeChar: '`', kind: "mysql", name: dbName, } } func NewPostgresDialect(dbName *string) Dialect { return &genericDialect{ escapeChar: '"', returningClause: " RETURNING *", kind: "postgres", name: dbName, } } func NewSQLiteDialect() Dialect { defaultName := "main" return &genericDialect{<|fim▁hole|>}<|fim▁end|>
escapeChar: '"', kind: "sqlite", name: &defaultName, }
<|file_name|>Books.cpp<|end_file_name|><|fim▁begin|>/* * Books.cpp * Author: suyashd95 */<|fim▁hole|> #include "Books.h" #include <iostream> #include <cstring> using namespace std; Books::Books() { stock = new int[size]; price = new float[size]; author = new const char*[size]; publisher = new const char*[size]; title = new const char*[size]; populateData(); } void Books::populateData() { for(int i = 0; i < size; i++) { switch(i) { case 0: stock[i] = 10; price[i] = 500.00; author[i] = "JK Rowling"; publisher[i] = "Bloomsbury"; title[i] = "Harry Potter"; break; case 1: stock[i] = 0; price[i] = 200.00; author[i] = "Jeffrey Archer"; publisher[i] = "Penguin"; title[i] = "A Quiver Full Of Arrows"; break; case 2: stock[i] = 3; price[i] = 1000.00; author[i] = "JKR Tolkien"; publisher[i] = "Penguin"; title[i] = "The Lord Of The Rings"; break; case 3: stock[i] = 0; price[i] = 80.00; author[i] = "Danielle Steele"; publisher[i] = "Penguin"; title[i] = "A Perfect Stranger"; break; case 4: stock[i] = 7; price[i] = 300.00; author[i] = "Jane Austen"; publisher[i] = "Bloomsbury"; title[i] = "Pride & Prejudice"; break; } } } void Books::bookPurchase() { string author, title; cout << "Enter the author of the book: " << flush; getline(cin, author, '\n'); cout << "Enter the title of the book: " << flush; getline(cin, title, '\n'); char found = 'n'; for(int i = 0; i < size; i++) { int condition1 = strcmp(this->author[i], author.c_str()); int condition2 = strcmp(this->title[i], title.c_str()); if(condition1 == 0 && condition2 == 0) { found = 'y'; cout << endl; cout << "Search Successful..." << endl; cout << "Details of the Book:\n" << endl; cout << " Author: " << this->author[i] << endl; cout << " Title: " << this->title[i] << endl; cout << "Publisher: " << this->publisher[i] << endl; cout << " Price: " << this->price[i] << endl; unsigned int requiredCopies; cout << "Please enter the number of copies required for purchase: " << flush; cin >> requiredCopies; cout << endl; if(requiredCopies <= this->stock[i]) cout << "Total Cost: " << this->price[i] * requiredCopies << endl; else cout << "Required copies not in stock." << endl; break; } } if(found == 'n') cout << "\nSearch Unsuccessful...\nBook is not available." << endl; } Books::~Books() { delete [] stock; delete [] price; delete [] author; delete [] publisher; delete [] title; }<|fim▁end|>
<|file_name|>app.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python from flask import Flask, render_template, request, jsonify, session, redirect, escape, url_for import MySQLdb import bcrypt from esipy import App from esipy import EsiClient from esipy import EsiSecurity from esipy.exceptions import APIException import time import json import requests import datetime import math app = Flask(__name__) class ServerError(Exception):pass class DB: conn = None def connect(self): config = {} execfile("config.conf",config) self.conn = MySQLdb.connect( host=config['dbHost'], user=config['dbUser'], passwd=config['dbPass'], db=config['dbBase'] ) self.conn.autocommit(True) self.conn.set_character_set('utf8') def query(self, sql, args=None): try: cursor = self.conn.cursor() cursor.execute(sql,args) except (AttributeError, MySQLdb.OperationalError): self.connect() cursor = self.conn.cursor() cursor.execute(sql,args) return cursor if __name__ == '__main__': config = {} execfile("config.conf",config) serverIP = config['serverIP'] serverPort = config['serverPort'] rounds = 10 debug = config['debug'] cer = config['ssl_cer'] key = config['ssl_key'] context = (cer,key) app.secret_key = config['appKey'] esi_app = App.create('https://esi.tech.ccp.is/latest/swagger.json?datasource=tranquility') security = EsiSecurity( app=esi_app, redirect_uri=config['callbackURL'], client_id=config['clientID'], secret_key=config['secretKey'] ) client = EsiClient(security=security) scopes = ['esi-location.read_location.v1','esi-skills.read_skillqueue.v1','esi-skills.read_skills.v1','esi-clones.read_clones.v1'] db = DB() def profit(): extractorID = "40519" injectorID = "40520" plexID = "44992" priceList = [] url = "http://api.eve-central.com/api/marketstat/json?regionlimit=10000002&typeid=" try: prices = requests.get(url+extractorID).json()[0] extractorPrice = prices['buy']['fivePercent'] extractorPricen= prices['sell']['fivePercent'] prices = requests.get(url+injectorID).json()[0] injectorPrice = prices['sell']['fivePercent'] injectorPricen= prices['buy']['fivePercent'] prices = requests.get(url+plexID).json()[0] plexPrice = prices['buy']['fivePercent'] plexPricen= prices['sell']['fivePercent'] injectorsMonth = 3.888 profit = round(((injectorsMonth * (injectorPrice - extractorPrice)) - (plexPrice * 500))/1000000,2) nonoptimal = round(((injectorsMonth * (injectorPricen - extractorPricen)) - (plexPricen * 500))/1000000,2) return "<a href='https://market.madpilot.nl/static/graph/farm-month.png'>Projected profits: (min)"+str(nonoptimal)+"mil - (max)"+str(profit)+"mil </a>" except: return "<a href='https://market.madpilot.nl/static/graph/farm-month.png'>Projected profits: (min)"+str(0)+"mil - (max)"+str(0)+"mil </a>" def isk(extractors): extractorID = "40519" injectorID = "40520" plexID = "44992" priceList = [] url = "http://api.eve-central.com/api/marketstat/json?regionlimit=10000002&typeid=" try: prices = requests.get(url+extractorID).json()[0] extractorPrice = prices['buy']['fivePercent'] extractorPricen= prices['sell']['fivePercent'] prices = requests.get(url+injectorID).json()[0] injectorPrice = prices['sell']['fivePercent'] injectorPricen= prices['buy']['fivePercent'] prices = requests.get(url+plexID).json()[0] plexPrice = prices['buy']['fivePercent'] plexPricen= prices['sell']['fivePercent'] maxProfit = round(((injectorPrice - extractorPrice) * extractors)/1000000,2) minProfit = round(((injectorPricen - extractorPricen) * extractors)/1000000,2) except: maxProfit = 0 minProfit = 0 return [maxProfit, minProfit] def isReady(char_id): checkDelay = 1800 cur = db.query("SELECT UNIX_TIMESTAMP(updated) FROM cache_table WHERE character_id = %s",[char_id]) lastChecked = cur.fetchone() curTime = int(time.time()) if lastChecked: lastCheckedEpoch = lastChecked[0] if (curTime - lastCheckedEpoch) < checkDelay: print("Checktime is less than "+str(checkDelay)+" Seconds (current: "+str(curTime - lastCheckedEpoch)+"). Skipping") return False return True return True @app.route('/') def index(): error = None if 'username' not in session: error = "Not logged in" return redirect(url_for('login', error=error)) secure = security.get_auth_uri(scopes=scopes) cur = db.query("SELECT id FROM users WHERE user = %s;", [session['username']]) for row in cur.fetchall(): userID = row[0] characters = [] cur = db.query("SELECT character_id, access_token, refresh_token, expires, expires_in, added, updated FROM characters WHERE owner_id = %s;", [userID]) allSP = 0 extractableSP = 0 numExtract = 0 for row in cur.fetchall(): epoch = round(time.time()) expires = row[3] - row[4] - epoch if expires < 0: expires = 0 refresh = {u'access_token': row[1], u'refresh_token': row[2], u'expires_in': expires} security.update_token(refresh) ready = isReady(row[0]) if not ready: cur = db.query("SELECT * FROM cache_table WHERE character_id=%s",[row[0]]) cache = cur.fetchall()[0] #Get character name charName = esi_app.op['get_characters_names'](character_ids=[row[0]]) result = client.request(charName) charName = json.loads(result.raw)[0].get('character_name') print "Character "+charName #Get character location if ready: charLocation = esi_app.op['get_characters_character_id_location'](character_id=row[0]) result = client.request(charLocation) location = json.loads(result.raw) sol = esi_app.op['get_universe_systems_system_id'](system_id=location.get('solar_system_id')) sol = json.loads(client.request(sol).raw).get('name') cur = db.query("INSERT INTO cache_table (character_id,char_location) VALUES (%s,%s) ON DUPLICATE KEY UPDATE char_location=%s",[row[0],result.raw,result.raw]) else: location = json.loads(cache[3]) sol = esi_app.op['get_universe_systems_system_id'](system_id=location.get('solar_system_id')) sol = json.loads(client.request(sol).raw).get('name') #Get current training skill + queue if ready: charTrain = esi_app.op['get_characters_character_id_skillqueue'](character_id=row[0]) result = client.request(charTrain) training = json.loads(result.raw) cur = db.query("INSERT INTO cache_table (character_id,char_queue) VALUES (%s,%s) ON DUPLICATE KEY UPDATE char_queue=%s",[row[0],result.raw,result.raw]) else: training = json.loads(cache[4]) currentlyTrainingStart = training[0].get('start_date') currentlyTrainingEnd = training[0].get('finish_date') startTrainEpoch = int(time.mktime(time.strptime(currentlyTrainingStart, "%Y-%m-%dT%H:%M:%SZ"))) endTrainEpoch = int(time.mktime(time.strptime(currentlyTrainingEnd, "%Y-%m-%dT%H:%M:%SZ"))) if endTrainEpoch < epoch: while endTrainEpoch < epoch and len(training)>1: del training[0] currentlyTrainingStart = training[0].get('start_date') currentlyTrainingEnd = training[0].get('finish_date') startTrainEpoch = int(time.mktime(time.strptime(currentlyTrainingStart, "%Y-%m-%dT%H:%M:%SZ"))) endTrainEpoch = int(time.mktime(time.strptime(currentlyTrainingEnd, "%Y-%m-%dT%H:%M:%SZ"))) trainedSpCur = training[0].get('training_start_sp') - training[0].get('level_start_sp') endQueue = training[-1].get('finish_date') currentlyTraining = training[0].get('skill_id') currentlyTrainingLevel = training[0].get('finished_level') curSkillStartSP = training[0].get('level_start_sp') curSkillEndSP = training[0].get('level_end_sp') curSkillSP = curSkillEndSP - curSkillStartSP #Get currently training name skillName = esi_app.op['get_universe_types_type_id'](type_id=currentlyTraining) result = client.request(skillName) skillName = json.loads(result.raw).get('name') #Get character total sp if ready: charSkill = esi_app.op['get_characters_character_id_skills'](character_id=row[0]) result = client.request(charSkill) sp = json.loads(result.raw) totalSp = sp.get('total_sp') cur = db.query("INSERT INTO cache_table (character_id,char_skills) VALUES (%s,%s) ON DUPLICATE KEY UPDATE char_skills=%s",[row[0],result.raw,result.raw]) else: sp = json.loads(cache[5]) totalSp = sp.get('total_sp') #Get current training skill rank skillRank = esi_app.op['universe_types_type_id'](type_id=currentlyTraining) result = client.request(skillRank) skillDogma = json.loads(result.raw).get('dogma_attributes') print skillDogma skillRank = 5 # for skill in skillDogma: # if skill.get('attribute_id') == 275: # skillRank = skill.get('value') # break; startTrainEpoch = int(time.mktime(time.strptime(currentlyTrainingStart, "%Y-%m-%dT%H:%M:%SZ"))) endTrainEpoch = int(time.mktime(time.strptime(currentlyTrainingEnd, "%Y-%m-%dT%H:%M:%SZ"))) totalTrainTime = endTrainEpoch - startTrainEpoch trainedTime = epoch - startTrainEpoch<|fim▁hole|> # skillEndSP = (250 * math.pow(5.65685,currentlyTrainingLevel)) spPerSec = float(curSkillSP) / float(totalTrainTime) trainedSP = int(spPerSec * trainedTime) totalSp += trainedSP allSP += totalSp #Prettify dates timeLeftCurrent = datetime.datetime.strptime(currentlyTrainingEnd, "%Y-%m-%dT%H:%M:%SZ").replace(microsecond=0) - datetime.datetime.now().replace(microsecond=0) endQueueLeft = datetime.datetime.strptime(endQueue, "%Y-%m-%dT%H:%M:%SZ").replace(microsecond=0) - datetime.datetime.now().replace(microsecond=0) currentlyTrainingEnd = time.strftime("%Y-%m-%d %H:%M",time.gmtime(int(time.mktime(time.strptime(currentlyTrainingEnd, "%Y-%m-%dT%H:%M:%SZ"))))) endQueue = time.strftime("%Y-%m-%d %H:%M",time.gmtime(int(time.mktime(time.strptime(endQueue, "%Y-%m-%dT%H:%M:%SZ"))))) #Get Cybernetics skill for skill in sp.get('skills'): if skill.get('skill_id') == 3411: cyberLevel = skill.get('current_skill_level') break; #Get character attributes #Assume 2700(max) for now, until attributes are added to ESI startTime = time.mktime(time.strptime(currentlyTrainingStart, "%Y-%m-%dT%H:%M:%SZ")) timeDone = epoch - startTime spAdded = int(timeDone / 60 / 60 * 2700) if totalSp > 5500000: exSP = totalSp - 5000000 extractableSP += exSP exSP = int(exSP / 500000) numExtract += exSP totalSp = format(totalSp, "8,d") queueStatus = None if endTrainEpoch < epoch: queueStatus = "Queue empty!" characters.append( { "characterName": charName, "characterID": row[0], "characterImage": "https://image.eveonline.com/Character/"+str(row[0])+"_64.jpg", "totalSP": totalSp, "characterLocation": sol, "currentEnd":currentlyTrainingEnd, "queueEnd": endQueue, "currentlyTraining": currentlyTraining, "timeLeftCurrent": timeLeftCurrent, "endQueueLeft": endQueueLeft, "currentlyTrainingLevel": currentlyTrainingLevel, "currentlyTrainingName": skillName, "cyberneticsLevel": cyberLevel, "queueStatus": queueStatus }) print "----------" allSP = format(allSP, "8,d") extractableSP = format(extractableSP, "8,d") stats = [{ "allSP": allSP, "exSP": extractableSP, "numEx": numExtract }] profits = isk(numExtract) return render_template('index.html',secUrl=secure, characters=characters, stats=stats, profit=profit(), profits=profits) @app.route('/login', methods=['GET', 'POST']) def login(): error = None error = request.args['error'] if 'username' in session: return redirect(url_for('index')) try: if request.method == 'POST': username = request.form['username'] cur = db.query("SELECT COUNT(1) FROM users WHERE user = %s", [username]) if not cur.fetchone()[0]: raise ServerError('Incorrect username / password') password = request.form['password'] cur = db.query("SELECT pass FROM users WHERE user = %s;", [username]) for row in cur.fetchall(): if bcrypt.hashpw(password.encode('utf-8'), row[0]) == row[0]: session['username'] = request.form['username'] return redirect(url_for('index')) raise ServerError('Incorrect username / password') except ServerError as e: error = str(e) return render_template('login.html', error=error) @app.route('/logout') def logout(): session.pop('username', None) return redirect(url_for('index')) @app.route('/register', methods=['GET', 'POST']) def register(): error = None if 'username' not in session: try: if request.method == 'POST': username = request.form['username'] password = request.form['password'] email = request.form['email'] if not username or not password or not email: raise ServerError('Fill in all fields please') password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(rounds)) cur = db.query("INSERT INTO users (`user`, `pass`, `email`) VALUES (%s,%s,%s)", [username, password, email]) except ServerError as e: error = str(e) return render_template('register.html', error=error) if config['registerEnabled']: return render_template('register.html') error = "Registration is disabled by the admin" return redirect(url_for('login', error=error)) if session['username'] == 'admin': return render_template('register.html') error = "Only available to admins" return redirect(url_for('login', error=error)) @app.route('/userPage', methods=['GET','POST']) def userPage(): return "User! :-)" @app.route('/oauth') def oauth(): code = request.args.get('code') if not code: return redirect(url_for('index')) token = security.auth(code) access_token = token['access_token'] refresh_token = token['refresh_token'] expires_in = token['expires_in'] cur = db.query("SELECT id FROM users WHERE user = %s;", [session['username']]) for row in cur.fetchall(): userID = row[0] verify = security.verify() charID = verify.get('CharacterID') print userID print charID print token print token['access_token'] print token['refresh_token'] print token['expires_in'] epoch = round(time.time()) expires = epoch + int(expires_in) cur = db.query("INSERT INTO characters (owner_id, character_id, access_token, refresh_token, expires, expires_in) VALUES (%s,%s,%s,%s,%s,%s) ON DUPLICATE KEY UPDATE access_token=%s, refresh_token=%s, expires=%s, expires_in=%s",[userID,charID,access_token,refresh_token,expires,int(expires_in),access_token,refresh_token,expires,int(expires_in)]) return redirect(url_for('index')) if __name__ == '__main__': if config['ssl']: app.run( host=serverIP, port=serverPort, ssl_context=context, debug=debug ) else: app.run( host=serverIP, port=serverPort, debug=debug )<|fim▁end|>
# skillStartSP = (250 * math.pow(5.65685,currentlyTrainingLevel-1))
<|file_name|>parserSkippedTokens19.ts<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
\ declare var v;
<|file_name|>G_Timer.cpp<|end_file_name|><|fim▁begin|>// leave this line at the top for all g_xxxx.cpp files... #include "g_headers.h" #include "G_Local.h" typedef map < string, int > timer_m; timer_m g_timers[ MAX_GENTITIES ]; /* ------------------------- TIMER_Clear ------------------------- */ void TIMER_Clear( void ) { for ( int i = 0; i < MAX_GENTITIES; i++ ) { g_timers[i].clear(); } } /* ------------------------- TIMER_Clear ------------------------- */ void TIMER_Clear( gentity_t *ent ) { // rudimentary safety checks, might be other things to check? if ( ent && ent->s.number > 0 && ent->s.number < MAX_GENTITIES ) { g_timers[ent->s.number].clear(); } } /* ------------------------- TIMER_Save ------------------------- */ void TIMER_Save( void ) { int j; gentity_t *ent; for ( j = 0, ent = &g_entities[0]; j < MAX_GENTITIES; j++, ent++ ) { int numTimers = g_timers[ent->s.number].size(); int i; //Write out the timer information gi.AppendToSaveGame('TIME', (void *)&numTimers, sizeof(numTimers)); timer_m::iterator ti; for ( i = 0, ti = g_timers[ j ].begin(); i < numTimers; i++, ti++ ) { const char *id = ((*ti).first).c_str(); int length = strlen( id ); //Write out the string size and data gi.AppendToSaveGame('TSLN', (void *) &length, sizeof(length) ); gi.AppendToSaveGame('TSNM', (void *) id, length ); //Write out the timer data gi.AppendToSaveGame('TDTA', (void *) &(*ti).second, sizeof( (*ti).second ) ); } } } /* ------------------------- TIMER_Load ------------------------- */ void TIMER_Load( void ) { int j; gentity_t *ent; for ( j = 0, ent = &g_entities[0]; j < MAX_GENTITIES; j++, ent++ ) { int numTimers; gi.ReadFromSaveGame( 'TIME', (void *)&numTimers, sizeof(numTimers) ); //Make sure there's something to read if ( numTimers == 0 ) continue; //Read back all entries for ( int i = 0; i < numTimers; i++ ) { int length, time; char tempBuffer[1024]; //FIXME: Blech! gi.ReadFromSaveGame( 'TSLN', (void *) &length, sizeof( length ) ); //Validity check, though this will never happen (unless of course you pass in gibberish) if ( length >= 1024 ) { assert(0); continue; } //Read the id and time gi.ReadFromSaveGame( 'TSNM', (char *) tempBuffer, length ); gi.ReadFromSaveGame( 'TDTA', (void *) &time, sizeof( time ) ); //Restore it g_timers[ j ][(const char *) tempBuffer ] = time; } } } /* ------------------------- TIMER_Set ------------------------- */ void TIMER_Set( gentity_t *ent, const char *identifier, int duration ) { g_timers[ent->s.number][identifier] = level.time + duration; } /* ------------------------- TIMER_Get ------------------------- */ int TIMER_Get( gentity_t *ent, const char *identifier ) { timer_m::iterator ti; ti = g_timers[ent->s.number].find( identifier ); if ( ti == g_timers[ent->s.number].end() ) { //assert(0); return -1; } return (*ti).second; } /* ------------------------- TIMER_Done ------------------------- */ qboolean TIMER_Done( gentity_t *ent, const char *identifier ) { timer_m::iterator ti; ti = g_timers[ent->s.number].find( identifier ); if ( ti == g_timers[ent->s.number].end() ) return true; return ( (*ti).second < level.time ); } /* ------------------------- TIMER_Done2 Returns false if timer has been started but is not done...or if timer was never started ------------------------- */ qboolean TIMER_Done2( gentity_t *ent, const char *identifier, qboolean remove ) { timer_m::iterator ti; ti = g_timers[ent->s.number].find( identifier ); if ( ti == g_timers[ent->s.number].end() ) { return qfalse; } qboolean res =((*ti).second < level.time );<|fim▁hole|> if ( res && remove ) { // Timer is done and it was requested that it should be removed. g_timers[ent->s.number].erase( ti ); } return res; } /* ------------------------- TIMER_Exists ------------------------- */ qboolean TIMER_Exists( gentity_t *ent, const char *identifier ) { timer_m::iterator ti; ti = g_timers[ent->s.number].find( identifier ); if ( ti == g_timers[ent->s.number].end( )) { return qfalse; } return qtrue; } /* ------------------------- TIMER_Remove Utility to get rid of any timer ------------------------- */ void TIMER_Remove( gentity_t *ent, const char *identifier ) { timer_m::iterator ti; ti = g_timers[ent->s.number].find( identifier ); if ( ti != g_timers[ent->s.number].end() ) { g_timers[ent->s.number].erase( ti ); } } /* ------------------------- TIMER_Start ------------------------- */ qboolean TIMER_Start( gentity_t *self, const char *identifier, int duration ) { if ( TIMER_Done( self, identifier ) ) { TIMER_Set( self, identifier, duration ); return qtrue; } return qfalse; }<|fim▁end|>
<|file_name|>loader.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import logging, os, sys l = logging.getLogger(__name__) from django.conf import settings import json from django_lean.experiments.models import Experiment class ExperimentLoader(object): """ Loads the experiments from a file containing a list of experiment It will add new experiments, but not touch existing experiments """ NAME_ATTRIBUTE="name" ALLOWED_ATTRIBUTES=[NAME_ATTRIBUTE] APPLICATION_RELATIVE_EXPERIMENT_FILE = "%sexperiments.json" % os.sep __loaded = False @classmethod def load_all_experiments(cls, apps=settings.INSTALLED_APPS): """ Loads experiments for all applications in settings.INSTALLED_APPS """ if not cls.__loaded: cls.__loaded = True for app_name in apps: application_path = os.path.dirname(sys.modules[app_name].__file__) application_experiment_file_path = (<|fim▁hole|> application_path + ExperimentLoader.APPLICATION_RELATIVE_EXPERIMENT_FILE) if os.access(application_experiment_file_path, os.F_OK): ExperimentLoader.load_experiments(application_experiment_file_path) @staticmethod def load_experiments(filename): """ Will load the data from the filename, expected data format to be JSON : [{ name : "name" }] """ fp = open(filename) experiment_names = None try: experiment_names = json.load(fp) except Exception as e: l.error("Unable to parse experiment file %s: %s" % (filename, e)) raise e finally: fp.close() for entry in experiment_names: for key in entry.keys(): if key not in ExperimentLoader.ALLOWED_ATTRIBUTES: l.warning("Ignoring unrecognized key %s on experiment " "definition %s in filename %s" % (key, entry, filename)) if ExperimentLoader.NAME_ATTRIBUTE in entry: Experiment.objects.get_or_create( name=entry.get(ExperimentLoader.NAME_ATTRIBUTE)) else: l.warning("Invalid entry in experiment file %s : %s" % (filename, entry))<|fim▁end|>
<|file_name|>MainActivity.java<|end_file_name|><|fim▁begin|>package com.smbc.droid; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.android.volley.toolbox.NetworkImageView; public class MainActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final ComicPagerAdapter adapter = new ComicPagerAdapter( getSupportFragmentManager()); final ViewPager viewPager = (ViewPager) findViewById(R.id.pager); viewPager.setAdapter(adapter); // findViewById(R.id.btn_next).setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // viewPager.setCurrentItem(viewPager.getCurrentItem()+1, true); // } // }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. // getMenuInflater().inflate(R.menu.menu_main, menu); return true; }<|fim▁hole|> // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }<|fim▁end|>
@Override public boolean onOptionsItemSelected(MenuItem item) {
<|file_name|>ubinascii_unhexlify.py<|end_file_name|><|fim▁begin|>try: try: import ubinascii as binascii except ImportError: import binascii except ImportError: print("SKIP") raise SystemExit print(binascii.unhexlify(b'0001020304050607')) print(binascii.unhexlify(b'08090a0b0c0d0e0f')) print(binascii.unhexlify(b'7f80ff')) print(binascii.unhexlify(b'313233344142434461626364')) try:<|fim▁hole|> a = binascii.unhexlify(b'0') # odd buffer length except ValueError: print('ValueError') try: a = binascii.unhexlify(b'gg') # digit not hex except ValueError: print('ValueError')<|fim▁end|>
<|file_name|>build.rs<|end_file_name|><|fim▁begin|><|fim▁hole|>// Copyright © 2015, Peter Atashian // Licensed under the MIT License <LICENSE.md> fn main() { println!("cargo:rustc-flags=-l wmip"); }<|fim▁end|>
<|file_name|>http.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals import base64 import calendar import datetime import re import sys import unicodedata from binascii import Error as BinasciiError from email.utils import formatdate from django.utils import six from django.utils.datastructures import MultiValueDict from django.utils.encoding import force_bytes, force_str, force_text from django.utils.functional import allow_lazy from django.utils.six.moves.urllib.parse import ( quote, quote_plus, unquote, unquote_plus, urlencode as original_urlencode, urlparse, ) ETAG_MATCH = re.compile(r'(?:W/)?"((?:\\.|[^"])*)"') MONTHS = 'jan feb mar apr may jun jul aug sep oct nov dec'.split() __D = r'(?P<day>\d{2})' __D2 = r'(?P<day>[ \d]\d)' __M = r'(?P<mon>\w{3})' __Y = r'(?P<year>\d{4})' __Y2 = r'(?P<year>\d{2})' __T = r'(?P<hour>\d{2}):(?P<min>\d{2}):(?P<sec>\d{2})' RFC1123_DATE = re.compile(r'^\w{3}, %s %s %s %s GMT$' % (__D, __M, __Y, __T)) RFC850_DATE = re.compile(r'^\w{6,9}, %s-%s-%s %s GMT$' % (__D, __M, __Y2, __T)) ASCTIME_DATE = re.compile(r'^\w{3} %s %s %s %s$' % (__M, __D2, __T, __Y)) RFC3986_GENDELIMS = str(":/?#[]@") RFC3986_SUBDELIMS = str("!$&'()*+,;=") PROTOCOL_TO_PORT = { 'http': 80, 'https': 443, } def urlquote(url, safe='/'): """ A version of Python's urllib.quote() function that can operate on unicode strings. The url is first UTF-8 encoded before quoting. The returned string can safely be used as part of an argument to a subsequent iri_to_uri() call without double-quoting occurring. """ return force_text(quote(force_str(url), force_str(safe))) urlquote = allow_lazy(urlquote, six.text_type) def urlquote_plus(url, safe=''): """ A version of Python's urllib.quote_plus() function that can operate on unicode strings. The url is first UTF-8 encoded before quoting. The returned string can safely be used as part of an argument to a subsequent iri_to_uri() call without double-quoting occurring. """ return force_text(quote_plus(force_str(url), force_str(safe))) urlquote_plus = allow_lazy(urlquote_plus, six.text_type) def urlunquote(quoted_url): """ A wrapper for Python's urllib.unquote() function that can operate on the result of django.utils.http.urlquote(). """ return force_text(unquote(force_str(quoted_url))) urlunquote = allow_lazy(urlunquote, six.text_type) def urlunquote_plus(quoted_url): """ A wrapper for Python's urllib.unquote_plus() function that can operate on the result of django.utils.http.urlquote_plus(). """ return force_text(unquote_plus(force_str(quoted_url))) urlunquote_plus = allow_lazy(urlunquote_plus, six.text_type) def urlencode(query, doseq=0): """ A version of Python's urllib.urlencode() function that can operate on unicode strings. The parameters are first cast to UTF-8 encoded strings and then encoded as per normal. """ if isinstance(query, MultiValueDict): query = query.lists() elif hasattr(query, 'items'): query = query.items() return original_urlencode( [(force_str(k), [force_str(i) for i in v] if isinstance(v, (list, tuple)) else force_str(v)) for k, v in query], doseq) def cookie_date(epoch_seconds=None): """ Formats the time to ensure compatibility with Netscape's cookie standard. Accepts a floating point number expressed in seconds since the epoch, in UTC - such as that outputted by time.time(). If set to None, defaults to the current time. Outputs a string in the format 'Wdy, DD-Mon-YYYY HH:MM:SS GMT'. """ rfcdate = formatdate(epoch_seconds) return '%s-%s-%s GMT' % (rfcdate[:7], rfcdate[8:11], rfcdate[12:25]) def http_date(epoch_seconds=None): """ Formats the time to match the RFC1123 date format as specified by HTTP RFC2616 section 3.3.1. Accepts a floating point number expressed in seconds since the epoch, in UTC - such as that outputted by time.time(). If set to None, defaults to the current time. Outputs a string in the format 'Wdy, DD Mon YYYY HH:MM:SS GMT'. """ return formatdate(epoch_seconds, usegmt=True) def parse_http_date(date): """ Parses a date format as specified by HTTP RFC2616 section 3.3.1. The three formats allowed by the RFC are accepted, even if only the first one is still in widespread use. Returns an integer expressed in seconds since the epoch, in UTC. """ # emails.Util.parsedate does the job for RFC1123 dates; unfortunately # RFC2616 makes it mandatory to support RFC850 dates too. So we roll # our own RFC-compliant parsing. for regex in RFC1123_DATE, RFC850_DATE, ASCTIME_DATE: m = regex.match(date) if m is not None: break else: raise ValueError("%r is not in a valid HTTP date format" % date) try: year = int(m.group('year')) if year < 100: if year < 70: year += 2000 else: year += 1900 month = MONTHS.index(m.group('mon').lower()) + 1 day = int(m.group('day')) hour = int(m.group('hour')) min = int(m.group('min')) sec = int(m.group('sec')) result = datetime.datetime(year, month, day, hour, min, sec) return calendar.timegm(result.utctimetuple()) except Exception: six.reraise(ValueError, ValueError("%r is not a valid date" % date), sys.exc_info()[2]) def parse_http_date_safe(date): """ Same as parse_http_date, but returns None if the input is invalid. """ try: return parse_http_date(date) except Exception: pass # Base 36 functions: useful for generating compact URLs def base36_to_int(s): """ Converts a base 36 string to an ``int``. Raises ``ValueError` if the input won't fit into an int. """ # To prevent overconsumption of server resources, reject any # base36 string that is long than 13 base36 digits (13 digits # is sufficient to base36-encode any 64-bit integer) if len(s) > 13: raise ValueError("Base36 input too large") value = int(s, 36) # ... then do a final check that the value will fit into an int to avoid # returning a long (#15067). The long type was removed in Python 3. if six.PY2 and value > sys.maxint: raise ValueError("Base36 input too large") return value def int_to_base36(i): """ Converts an integer to a base36 string """ char_set = '0123456789abcdefghijklmnopqrstuvwxyz' if i < 0: raise ValueError("Negative base36 conversion input.") if six.PY2: if not isinstance(i, six.integer_types): raise TypeError("Non-integer base36 conversion input.") if i > sys.maxint: raise ValueError("Base36 conversion input too large.") if i < 36: return char_set[i] b36 = '' while i != 0: i, n = divmod(i, 36) b36 = char_set[n] + b36 return b36 def urlsafe_base64_encode(s): """ Encodes a bytestring in base64 for use in URLs, stripping any trailing equal signs. """ return base64.urlsafe_b64encode(s).rstrip(b'\n=') def urlsafe_base64_decode(s): """ Decodes a base64 encoded string, adding back any trailing equal signs that might have been stripped. """ s = force_bytes(s) try: return base64.urlsafe_b64decode(s.ljust(len(s) + len(s) % 4, b'=')) except (LookupError, BinasciiError) as e: raise ValueError(e) def parse_etags(etag_str): """ Parses a string with one or several etags passed in If-None-Match and If-Match headers by the rules in RFC 2616. Returns a list of etags without surrounding double quotes (") and unescaped from \<CHAR>. """ etags = ETAG_MATCH.findall(etag_str) if not etags: # etag_str has wrong format, treat it as an opaque string then return [etag_str] etags = [e.encode('ascii').decode('unicode_escape') for e in etags] return etags def quote_etag(etag): """ Wraps a string in double quotes escaping contents as necessary. """ return '"%s"' % etag.replace('\\', '\\\\').replace('"', '\\"') def same_origin(url1, url2): """ Checks if two URLs are 'same-origin' """ p1, p2 = urlparse(url1), urlparse(url2) try: o1 = (p1.scheme, p1.hostname, p1.port or PROTOCOL_TO_PORT[p1.scheme]) o2 = (p2.scheme, p2.hostname, p2.port or PROTOCOL_TO_PORT[p2.scheme]) return o1 == o2 except (ValueError, KeyError): return False def is_safe_url(url, host=None): """ Return ``True`` if the url is a safe redirection (i.e. it doesn't point to a different host and uses a safe scheme). Always returns ``False`` on an empty url. """ if url is not None: url = url.strip() if not url: return False if six.PY2: try: url = force_text(url) except UnicodeDecodeError: return False # Chrome treats \ completely as / in paths but it could be part of some # basic auth credentials so we need to check both URLs. return _is_safe_url(url, host) and _is_safe_url(url.replace('\\', '/'), host) def _is_safe_url(url, host): # Chrome considers any URL with more than two slashes to be absolute, but # urlparse is not so flexible. Treat any url with three slashes as unsafe. if url.startswith('///'): return False url_info = urlparse(url) # Forbid URLs like http:///example.com - with a scheme, but without a hostname. # In that URL, example.com is not the hostname but, a path component. However, # Chrome will still consider example.com to be the hostname, so we must not<|fim▁hole|> # allow this syntax. if not url_info.netloc and url_info.scheme: return False # Forbid URLs that start with control characters. Some browsers (like # Chrome) ignore quite a few control characters at the start of a # URL and might consider the URL as scheme relative. if unicodedata.category(url[0])[0] == 'C': return False return ((not url_info.netloc or url_info.netloc == host) and (not url_info.scheme or url_info.scheme in ['http', 'https']))<|fim▁end|>
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>use std::str::FromStr; fn group_by_sum(packages: &[usize], target: usize) -> Vec<Vec<usize>> { let mut results = Vec::new(); struct Iter<'a> { f: &'a Fn(&mut Iter, usize, usize, Vec<usize>) -> (), results: &'a mut Vec<Vec<usize>> } { let mut iter = Iter {results: &mut results, f: &|iter, index, so_far, current|{ if so_far == target { iter.results.push(current.clone());<|fim▁hole|> current.push(index); (iter.f)(iter, index + 1, so_far + packages[index], current); } (iter.f)(iter, index + 1, so_far, current); } }}; (iter.f)(&mut iter, 0, 0, Vec::new()); } results } fn intersects(a: &Vec<usize>, b: &Vec<usize>) -> bool { a.iter().any(|x| b.contains(x)) } fn quantum_entanglement(xs: &Vec<usize>) -> usize { xs.iter().fold(1, |acc, x| acc * x) } fn split_into_groups(packages: &Vec<usize>, target_weight: usize) -> Vec<Vec<usize>> { let mut grouped_by_sum: Vec<Vec<usize>> = group_by_sum(&packages, target_weight) .iter() // assuming that values are unique. .map(|combination| combination.iter().map(|i| packages[*i]).collect()) .collect(); grouped_by_sum.sort_by(|a, b| (a.len(), quantum_entanglement(a)).cmp(&(b.len(), quantum_entanglement(b)))); grouped_by_sum } fn main() { let input = include_str!("../input.txt"); let packages: Vec<_> = input.lines().map(|i|usize::from_str(i).unwrap()).rev().collect(); let sum = packages.iter().fold(0, |acc, x| acc + x); let target = sum / 3; let grouped_by_sum = split_into_groups(&packages, target); for group in grouped_by_sum.iter() { if grouped_by_sum.iter().any(|another| intersects(group, another)){ println!("Part 1. Min quantum entanglement: {}", quantum_entanglement(&group)); break; } } let target = sum / 4; let grouped_by_sum = split_into_groups(&packages, target); 'outer: for first in grouped_by_sum.iter() { for second in grouped_by_sum.iter() { for third in grouped_by_sum.iter() { if !intersects(first, second) && !intersects(second, third) && !intersects(third, first) { println!("Part 2. Min quantum entanglement: {}", quantum_entanglement(&first)); break 'outer; } } } } }<|fim▁end|>
} else if index < packages.len() { if packages[index] <= target - so_far { let mut current = current.clone();
<|file_name|>plotaw.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """ plot magnetic lattice """ import matplotlib.pylab as plt import numpy as np <|fim▁hole|> plt.plot(data12[:,0], data12[:,1], 'r-', data12[:,0], data12[:,2], 'b-', linewidth=2) plt.xlim([110,240]) plt.ylim([1.5,1.53]) plt.legend([r'$a_u$',r'$a_d$'],1) plt.xlabel(r'$z\,\mathrm{[m]}$',fontsize=18) plt.ylabel(r'undulator parameter',fontsize=18) plt.show()<|fim▁end|>
f12 = 'AWDall.lat' data12 = np.loadtxt(f12)
<|file_name|>PromiseRejected.java<|end_file_name|><|fim▁begin|>/* * Aphelion * Copyright (c) 2013 Joris van der Wel * * This file is part of Aphelion * * Aphelion is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, version 3 of the License. * * Aphelion is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Aphelion. If not, see <http://www.gnu.org/licenses/>. * * In addition, the following supplemental terms apply, based on section 7 of * the GNU Affero General Public License (version 3): * a) Preservation of all legal notices and author attributions * b) Prohibition of misrepresentation of the origin of this material, and * modified versions are required to be marked in reasonable ways as * different from the original version (for example by appending a copyright notice). * * Linking this library statically or dynamically with other modules is making a * combined work based on this library. Thus, the terms and conditions of the * GNU Affero General Public License cover the whole combination. * * As a special exception, the copyright holders of this library give you * permission to link this library with independent modules to produce an * executable, regardless of the license terms of these independent modules, * and to copy and distribute the resulting executable under terms of your * choice, provided that you also meet, for each linked independent module, * the terms and conditions of the license of that module. An independent * module is a module which is not derived from or based on this library. */ package aphelion.shared.event.promise;<|fim▁hole|> /** * * @author Joris */ public interface PromiseRejected { void rejected(PromiseException error); }<|fim▁end|>
<|file_name|>simplify.go<|end_file_name|><|fim▁begin|>package simplify import "container/heap" func Simplify(input *Mesh, factor float64) *Mesh { // find distinct vertices vectorVertex := make(map[Vector]*Vertex) for _, t := range input.Triangles { vectorVertex[t.V1] = NewVertex(t.V1) vectorVertex[t.V2] = NewVertex(t.V2) vectorVertex[t.V3] = NewVertex(t.V3) } // accumlate quadric matrices for each vertex based on its faces for _, t := range input.Triangles { q := t.Quadric() v1 := vectorVertex[t.V1] v2 := vectorVertex[t.V2] v3 := vectorVertex[t.V3] v1.Quadric = v1.Quadric.Add(q) v2.Quadric = v2.Quadric.Add(q) v3.Quadric = v3.Quadric.Add(q) } // create faces and map vertex => faces<|fim▁hole|> v2 := vectorVertex[t.V2] v3 := vectorVertex[t.V3] f := NewFace(v1, v2, v3) vertexFaces[v1] = append(vertexFaces[v1], f) vertexFaces[v2] = append(vertexFaces[v2], f) vertexFaces[v3] = append(vertexFaces[v3], f) } // find distinct pairs // TODO: pair vertices within a threshold distance of each other pairs := make(map[PairKey]*Pair) for _, t := range input.Triangles { v1 := vectorVertex[t.V1] v2 := vectorVertex[t.V2] v3 := vectorVertex[t.V3] pairs[MakePairKey(v1, v2)] = NewPair(v1, v2) pairs[MakePairKey(v2, v3)] = NewPair(v2, v3) pairs[MakePairKey(v3, v1)] = NewPair(v3, v1) } // enqueue pairs and map vertex => pairs var queue PriorityQueue vertexPairs := make(map[*Vertex][]*Pair) for _, p := range pairs { heap.Push(&queue, p) vertexPairs[p.A] = append(vertexPairs[p.A], p) vertexPairs[p.B] = append(vertexPairs[p.B], p) } // simplify numFaces := len(input.Triangles) target := int(float64(numFaces) * factor) for numFaces > target { // pop best pair p := heap.Pop(&queue).(*Pair) if p.Removed { continue } p.Removed = true // get related faces distinctFaces := make(map[*Face]bool) for _, f := range vertexFaces[p.A] { if !f.Removed { distinctFaces[f] = true } } for _, f := range vertexFaces[p.B] { if !f.Removed { distinctFaces[f] = true } } // get related pairs distinctPairs := make(map[*Pair]bool) for _, q := range vertexPairs[p.A] { if !q.Removed { distinctPairs[q] = true } } for _, q := range vertexPairs[p.B] { if !q.Removed { distinctPairs[q] = true } } // create the new vertex v := &Vertex{p.Vector(), p.Quadric()} // update faces newFaces := make([]*Face, 0, len(distinctFaces)) valid := true for f := range distinctFaces { v1, v2, v3 := f.V1, f.V2, f.V3 if v1 == p.A || v1 == p.B { v1 = v } if v2 == p.A || v2 == p.B { v2 = v } if v3 == p.A || v3 == p.B { v3 = v } face := NewFace(v1, v2, v3) if face.Degenerate() { continue } if face.Normal().Dot(f.Normal()) < 1e-3 { valid = false break } newFaces = append(newFaces, face) } if !valid { continue } delete(vertexFaces, p.A) delete(vertexFaces, p.B) for f := range distinctFaces { f.Removed = true numFaces-- } for _, f := range newFaces { numFaces++ vertexFaces[f.V1] = append(vertexFaces[f.V1], f) vertexFaces[f.V2] = append(vertexFaces[f.V2], f) vertexFaces[f.V3] = append(vertexFaces[f.V3], f) } // update pairs and prune current pair delete(vertexPairs, p.A) delete(vertexPairs, p.B) seen := make(map[Vector]bool) for q := range distinctPairs { q.Removed = true heap.Remove(&queue, q.Index) a, b := q.A, q.B if a == p.A || a == p.B { a = v } if b == p.A || b == p.B { b = v } if b == v { // swap so that a == v a, b = b, a } if _, ok := seen[b.Vector]; ok { // only want distinct neighbors continue } seen[b.Vector] = true q = NewPair(a, b) heap.Push(&queue, q) vertexPairs[a] = append(vertexPairs[a], q) vertexPairs[b] = append(vertexPairs[b], q) } } // find distinct faces distinctFaces := make(map[*Face]bool) for _, faces := range vertexFaces { for _, f := range faces { if !f.Removed { distinctFaces[f] = true } } } // construct resulting mesh triangles := make([]*Triangle, len(distinctFaces)) i := 0 for f := range distinctFaces { triangles[i] = NewTriangle(f.V1.Vector, f.V2.Vector, f.V3.Vector) i++ } return NewMesh(triangles) }<|fim▁end|>
vertexFaces := make(map[*Vertex][]*Face) for _, t := range input.Triangles { v1 := vectorVertex[t.V1]
<|file_name|>util.py<|end_file_name|><|fim▁begin|>#__author__ = 'hello' # -*- coding: cp936 -*- import re import os import random import json import string import ctypes from myexception import * PATH = './img/' dm2 = ctypes.WinDLL('./CrackCaptchaAPI.dll') if not os.path.exists('./img'): os.mkdir('./img') def str_tr(content): instr = "0123456789" outstr ="QAEDTGUJOL" trantab = string.maketrans(instr,outstr) return content.translate(trantab) def getHid(): import wmi m = wmi.WMI() a = '' b = '' for cpu in m.Win32_Processor(): a = cpu.Processorid.strip() for bd in m.Win32_BIOS(): b= bd.SerialNumber.strip() return a+b def getEightRandomString(): return ''.join(random.sample(string.ascii_letters,8)) def getCToken(content): s = '' pattern = re.compile('securityCToken = "([+-]?\d*)"') match = pattern.search(content) if match: s = match.group(1) return s def GetCaptcha(content): global PATH filename = ''.join(random.sample(string.ascii_letters,8)) filename += '.jpg' filename = PATH+filename img = None try: img = open(filename,'wb') img.write(content) except IOError: raise FileCanNotCreate('open file error') finally: if img: img.close() dm2.D2File.argtypes=[ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_short, ctypes.c_int, ctypes.c_char_p] dm2.D2File.restype = ctypes.c_int key = ctypes.c_char_p('fa6fd217145f273b59d7e72c1b63386e') id = ctypes.c_long(54) user = ctypes.c_char_p('test') pas = ctypes.c_char_p('test') timeout = ctypes.c_short(30) result = ctypes.create_string_buffer('/0'*100) ret = -1 ret = dm2.D2File(key,user, pas, filename,timeout,id,(result)) if ret > 0: return result.value elif ret == -101: raise D2FILE(u'Óà¶î²»×ã,ÐèÒª³äÖµ') elif ret > -199: raise D2FILE('user info error') elif ret == -208: raise D2FILE('software can not user') elif ret == -210: raise D2FILE('invalid user') elif ret == -301: raise D2FILE('can not find dll') else: raise D2FILE(u'ʶ±ð¿â³ö´í') def GetTimeSlot(content,num): try: timeslot = json.loads(content) slotLen = len(timeslot['timeSlots']) if num < slotLen: return timeslot['timeSlots'][num]['startTime'],timeslot['timeSlots]'[num]['timeslotID']] elif slotLen > 0: return timeslot['timeSlots'][slotLen-1]['startTime'],timeslot['timeSlots]'[slotLen-1]['timeslotID']] except ValueError,e: raise NoJsonData('') def sendEmail(count): import smtplib from email.mime.text import MIMEText from email.header import Header smtpserver = 'smtp.163.com' sender = '[email protected]' receiver = '[email protected]' subject = u'Ô¤¶©¸öÊý' user = 'sghcarbon' pas = 'carbon216'<|fim▁hole|> msg['From'] = sender msg['To'] = receiver try: send_smtp = smtplib.SMTP() send_smtp.connect(smtpserver) send_smtp.login(user,pas) send_smtp.sendmail(sender,receiver,msg.as_string()) send_smtp.close() print 'ok' except: print 'error'<|fim▁end|>
content = getHid()+u'Ô¤¶©¸öÊý:'+str(count) msg = MIMEText(content,'plain','utf-8') msg['Subject'] = Header(subject,'utf-8')
<|file_name|>registers.rs<|end_file_name|><|fim▁begin|>#[derive(Debug, PartialEq, Clone, Copy)] pub enum Register {<|fim▁hole|> RC, RD, RE, RF, } impl From<String> for Register { fn from(string: String) -> Register { match string.as_ref() { "ra" => Register::RA, "rb" => Register::RB, "rc" => Register::RC, "rd" => Register::RD, "re" => Register::RE, "rf" => Register::RF, _ => unreachable!(), } } }<|fim▁end|>
RA, RB,
<|file_name|>mime_classifier.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::borrow::ToOwned; use std::cmp::max; pub struct MIMEClassifier {<|fim▁hole|> image_classifier: GroupedClassifier, audio_video_classifer: GroupedClassifier, scriptable_classifier: GroupedClassifier, plaintext_classifier: GroupedClassifier, archive_classifer: GroupedClassifier, binary_or_plaintext: BinaryOrPlaintextClassifier, feeds_classifier: FeedsClassifier } impl MIMEClassifier { //Performs MIME Type Sniffing Algorithm (section 7) pub fn classify(&self, no_sniff: bool, check_for_apache_bug: bool, supplied_type: &Option<(String, String)>, data: &[u8]) -> Option<(String, String)> { match *supplied_type { None => { return self.sniff_unknown_type(!no_sniff, data); } Some((ref media_type, ref media_subtype)) => { match (&**media_type, &**media_subtype) { ("unknown", "unknown") | ("application", "unknown") | ("*", "*") => { return self.sniff_unknown_type(!no_sniff, data); } _ => { if no_sniff { return supplied_type.clone(); } if check_for_apache_bug { return self.sniff_text_or_data(data); } if MIMEClassifier::is_xml(media_type, media_subtype) { return supplied_type.clone(); } //Inplied in section 7.3, but flow is not clear if MIMEClassifier::is_html(media_type, media_subtype) { return self.feeds_classifier .classify(data) .or(supplied_type.clone()); } if &**media_type == "image" { if let Some(tp) = self.image_classifier.classify(data) { return Some(tp); } } match (&**media_type, &**media_subtype) { ("audio", _) | ("video", _) | ("application", "ogg") => { if let Some(tp) = self.audio_video_classifer.classify(data) { return Some(tp); } } _ => {} } } } } } return supplied_type.clone(); } pub fn new() -> MIMEClassifier { MIMEClassifier { image_classifier: GroupedClassifier::image_classifer(), audio_video_classifer: GroupedClassifier::audio_video_classifer(), scriptable_classifier: GroupedClassifier::scriptable_classifier(), plaintext_classifier: GroupedClassifier::plaintext_classifier(), archive_classifer: GroupedClassifier::archive_classifier(), binary_or_plaintext: BinaryOrPlaintextClassifier, feeds_classifier: FeedsClassifier } } //some sort of iterator over the classifiers might be better? fn sniff_unknown_type(&self, sniff_scriptable: bool, data: &[u8]) -> Option<(String, String)> { if sniff_scriptable { self.scriptable_classifier.classify(data) } else { None }.or_else(|| self.plaintext_classifier.classify(data)) .or_else(|| self.image_classifier.classify(data)) .or_else(|| self.audio_video_classifer.classify(data)) .or_else(|| self.archive_classifer.classify(data)) .or_else(|| self.binary_or_plaintext.classify(data)) } fn sniff_text_or_data(&self, data: &[u8]) -> Option<(String, String)> { self.binary_or_plaintext.classify(data) } fn is_xml(tp: &str, sub_tp: &str) -> bool { let suffix = &sub_tp[(max(sub_tp.len() as isize - "+xml".len() as isize, 0) as usize)..]; match (tp, sub_tp, suffix) { (_, _, "+xml") | ("application", "xml",_) | ("text", "xml",_) => {true} _ => {false} } } fn is_html(tp: &str, sub_tp: &str) -> bool { tp == "text" && sub_tp == "html" } } pub fn as_string_option(tup: Option<(&'static str, &'static str)>) -> Option<(String, String)> { tup.map(|(a, b)| (a.to_owned(), b.to_owned())) } //Interface used for composite types trait MIMEChecker { fn classify(&self, data: &[u8]) -> Option<(String, String)>; } trait Matches { fn matches(&mut self, matches: &[u8]) -> bool; } impl <'a, T: Iterator<Item=&'a u8> + Clone> Matches for T { // Matching function that works on an iterator. // see if the next matches.len() bytes in data_iterator equal matches // move iterator and return true or just return false // // Params // self: an iterator // matches: a vector of bytes to match // // Return // true if the next n elements of self match n elements of matches // false otherwise // // Side effects // moves the iterator when match is found fn matches(&mut self, matches: &[u8]) -> bool { for (byte_a, byte_b) in self.clone().take(matches.len()).zip(matches) { if byte_a != byte_b { return false; } } self.nth(matches.len()); true } } struct ByteMatcher { pattern: &'static [u8], mask: &'static [u8], leading_ignore: &'static [u8], content_type: (&'static str,&'static str) } impl ByteMatcher { fn matches(&self, data: &[u8]) -> Option<usize> { if data.len() < self.pattern.len() { return None; } //TODO replace with iterators if I ever figure them out... let mut i: usize = 0; let max_i = data.len()-self.pattern.len(); loop { if !self.leading_ignore.iter().any(|x| *x == data[i]) { break; } i = i + 1; if i > max_i { return None; } } for j in 0..self.pattern.len() { if (data[i] & self.mask[j]) != (self.pattern[j] & self.mask[j]) { return None; } i = i + 1; } Some(i) } } impl MIMEChecker for ByteMatcher { fn classify(&self, data: &[u8]) -> Option<(String, String)> { self.matches(data).map(|_| { (self.content_type.0.to_owned(), self.content_type.1.to_owned()) }) } } struct TagTerminatedByteMatcher { matcher: ByteMatcher } impl MIMEChecker for TagTerminatedByteMatcher { fn classify(&self, data: &[u8]) -> Option<(String, String)> { let pattern = self.matcher.matches(data); let pattern_matches = pattern.map(|j| j < data.len() && (data[j] == b' ' || data[j] == b'>')); if pattern_matches.unwrap_or(false) { Some((self.matcher.content_type.0.to_owned(), self.matcher.content_type.1.to_owned())) } else { None } } } pub struct Mp4Matcher; impl Mp4Matcher { pub fn matches(&self, data: &[u8]) -> bool { if data.len() < 12 { return false; } let box_size = ((data[0] as u32) << 3 | (data[1] as u32) << 2 | (data[2] as u32) << 1 | (data[3] as u32)) as usize; if (data.len() < box_size) || (box_size % 4 != 0) { return false; } //TODO replace with iterators let ftyp = [0x66, 0x74, 0x79, 0x70]; let mp4 = [0x6D, 0x70, 0x34]; for i in 4..8 { if data[i] != ftyp[i - 4] { return false; } } let mut all_match = true; for i in 8..11 { if data[i] != mp4[i - 8] { all_match = false; break; } } if all_match { return true; } let mut bytes_read: usize = 16; while bytes_read < box_size { all_match = true; for i in 0..3 { if mp4[i] != data[i + bytes_read] { all_match = false; break; } } if all_match { return true; } bytes_read = bytes_read + 4; } false } } impl MIMEChecker for Mp4Matcher { fn classify(&self, data: &[u8]) -> Option<(String, String)> { if self.matches(data) { Some(("video".to_owned(), "mp4".to_owned())) } else { None } } } struct BinaryOrPlaintextClassifier; impl BinaryOrPlaintextClassifier { fn classify_impl(&self, data: &[u8]) -> (&'static str, &'static str) { if (data.len() >= 2 && ((data[0] == 0xFFu8 && data[1] == 0xFEu8) || (data[0] == 0xFEu8 && data[1] == 0xFFu8))) || (data.len() >= 3 && data[0] == 0xEFu8 && data[1] == 0xBBu8 && data[2] == 0xBFu8) { ("text", "plain") } else if data.len() >= 1 && data.iter().any(|&x| x <= 0x08u8 || x == 0x0Bu8 || (x >= 0x0Eu8 && x <= 0x1Au8) || (x >= 0x1Cu8 && x <= 0x1Fu8)) { ("application", "octet-stream") } else { ("text", "plain") } } } impl MIMEChecker for BinaryOrPlaintextClassifier { fn classify(&self, data: &[u8]) -> Option<(String, String)> { return as_string_option(Some(self.classify_impl(data))); } } struct GroupedClassifier { byte_matchers: Vec<Box<MIMEChecker + Send + Sync>>, } impl GroupedClassifier { fn image_classifer() -> GroupedClassifier { GroupedClassifier { byte_matchers: vec![ box ByteMatcher::image_x_icon(), box ByteMatcher::image_x_icon_cursor(), box ByteMatcher::image_bmp(), box ByteMatcher::image_gif89a(), box ByteMatcher::image_gif87a(), box ByteMatcher::image_webp(), box ByteMatcher::image_png(), box ByteMatcher::image_jpeg(), ] } } fn audio_video_classifer() -> GroupedClassifier { GroupedClassifier { byte_matchers: vec![ box ByteMatcher::video_webm(), box ByteMatcher::audio_basic(), box ByteMatcher::audio_aiff(), box ByteMatcher::audio_mpeg(), box ByteMatcher::application_ogg(), box ByteMatcher::audio_midi(), box ByteMatcher::video_avi(), box ByteMatcher::audio_wave(), box Mp4Matcher ] } } fn scriptable_classifier() -> GroupedClassifier { GroupedClassifier { byte_matchers: vec![ box ByteMatcher::text_html_doctype(), box ByteMatcher::text_html_page(), box ByteMatcher::text_html_head(), box ByteMatcher::text_html_script(), box ByteMatcher::text_html_iframe(), box ByteMatcher::text_html_h1(), box ByteMatcher::text_html_div(), box ByteMatcher::text_html_font(), box ByteMatcher::text_html_table(), box ByteMatcher::text_html_a(), box ByteMatcher::text_html_style(), box ByteMatcher::text_html_title(), box ByteMatcher::text_html_b(), box ByteMatcher::text_html_body(), box ByteMatcher::text_html_br(), box ByteMatcher::text_html_p(), box ByteMatcher::text_html_comment(), box ByteMatcher::text_xml(), box ByteMatcher::application_pdf() ] } } fn plaintext_classifier() -> GroupedClassifier { GroupedClassifier { byte_matchers: vec![ box ByteMatcher::text_plain_utf_8_bom(), box ByteMatcher::text_plain_utf_16le_bom(), box ByteMatcher::text_plain_utf_16be_bom(), box ByteMatcher::application_postscript() ] } } fn archive_classifier() -> GroupedClassifier { GroupedClassifier { byte_matchers: vec![ box ByteMatcher::application_x_gzip(), box ByteMatcher::application_zip(), box ByteMatcher::application_x_rar_compressed() ] } } // TODO: Use this in font context classifier #[allow(dead_code)] fn font_classifier() -> GroupedClassifier { GroupedClassifier { byte_matchers: vec![ box ByteMatcher::application_font_woff(), box ByteMatcher::true_type_collection(), box ByteMatcher::open_type(), box ByteMatcher::true_type(), box ByteMatcher::application_vnd_ms_font_object(), ] } } } impl MIMEChecker for GroupedClassifier { fn classify(&self, data: &[u8]) -> Option<(String, String)> { self.byte_matchers .iter() .filter_map(|matcher| matcher.classify(data)) .next() } } struct FeedsClassifier; impl FeedsClassifier { fn classify_impl(&self, data: &[u8]) -> Option<(&'static str, &'static str)> { let length = data.len(); let mut data_iterator = data.iter(); // acceptable byte sequences let utf8_bom = &[0xEFu8, 0xBBu8, 0xBFu8]; // can not be feed unless length is > 3 if length < 3 { return None; } // eat the first three bytes if they are equal to UTF-8 BOM data_iterator.matches(utf8_bom); // continuously search for next "<" until end of data_iterator // TODO: need max_bytes to prevent inadvertently examining html document // eg. an html page with a feed example while !data_iterator.find(|&data_iterator| *data_iterator == b'<').is_none() { if data_iterator.matches(b"?") { // eat until ?> while !data_iterator.matches(b"?>") { if data_iterator.next().is_none() { return None; } } } else if data_iterator.matches(b"!--") { // eat until --> while !data_iterator.matches(b"-->") { if data_iterator.next().is_none() { return None; } } } else if data_iterator.matches(b"!") { data_iterator.find(|&data_iterator| *data_iterator == b'>'); } else if data_iterator.matches(b"rss") { return Some(("application", "rss+xml")); } else if data_iterator.matches(b"feed") { return Some(("application", "atom+xml")); } else if data_iterator.matches(b"rdf: RDF") { while !data_iterator.next().is_none() { if data_iterator.matches(b"http: //purl.org/rss/1.0/") { while !data_iterator.next().is_none() { if data_iterator.matches(b"http: //www.w3.org/1999/02/22-rdf-syntax-ns#") { return Some(("application", "rss+xml")); } } } else if data_iterator.matches(b"http: //www.w3.org/1999/02/22-rdf-syntax-ns#") { while !data_iterator.next().is_none() { if data_iterator.matches(b"http: //purl.org/rss/1.0/") { return Some(("application", "rss+xml")); } } } } } } None } } impl MIMEChecker for FeedsClassifier { fn classify(&self, data: &[u8]) -> Option<(String, String)> { as_string_option(self.classify_impl(data)) } } //Contains hard coded byte matchers //TODO: These should be configured and not hard coded impl ByteMatcher { //A Windows Icon signature fn image_x_icon() -> ByteMatcher { ByteMatcher { pattern: b"\x00\x00\x01\x00", mask: b"\xFF\xFF\xFF\xFF", content_type: ("image", "x-icon"), leading_ignore: &[] } } //A Windows Cursor signature. fn image_x_icon_cursor() -> ByteMatcher { ByteMatcher { pattern: b"\x00\x00\x02\x00", mask: b"\xFF\xFF\xFF\xFF", content_type: ("image", "x-icon"), leading_ignore: &[] } } //The string "BM", a BMP signature. fn image_bmp() -> ByteMatcher { ByteMatcher { pattern: b"BM", mask: b"\xFF\xFF", content_type: ("image", "bmp"), leading_ignore: &[] } } //The string "GIF89a", a GIF signature. fn image_gif89a() -> ByteMatcher { ByteMatcher { pattern: b"GIF89a", mask: b"\xFF\xFF\xFF\xFF\xFF\xFF", content_type: ("image", "gif"), leading_ignore: &[] } } //The string "GIF87a", a GIF signature. fn image_gif87a() -> ByteMatcher { ByteMatcher { pattern: b"GIF87a", mask: b"\xFF\xFF\xFF\xFF\xFF\xFF", content_type: ("image", "gif"), leading_ignore: &[] } } //The string "RIFF" followed by four bytes followed by the string "WEBPVP". fn image_webp() -> ByteMatcher { ByteMatcher { pattern: b"RIFF\x00\x00\x00\x00WEBPVP", mask: b"\xFF\xFF\xFF\xFF\x00\x00\x00\x00,\xFF\xFF\xFF\xFF\xFF\xFF", content_type: ("image", "webp"), leading_ignore: &[] } } //An error-checking byte followed by the string "PNG" followed by CR LF SUB LF, the PNG //signature. fn image_png() -> ByteMatcher { ByteMatcher { pattern: b"\x89PNG\r\n\x1A\n", mask: b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", content_type: ("image", "png"), leading_ignore: &[] } } // The JPEG Start of Image marker followed by the indicator byte of another marker. fn image_jpeg() -> ByteMatcher { ByteMatcher { pattern: b"\xFF\xD8\xFF", mask: b"\xFF\xFF\xFF", content_type: ("image", "jpeg"), leading_ignore: &[] } } //The WebM signature. [TODO: Use more bytes?] fn video_webm() -> ByteMatcher { ByteMatcher { pattern: b"\x1A\x45\xDF\xA3", mask: b"\xFF\xFF\xFF\xFF", content_type: ("video", "webm"), leading_ignore: &[] } } //The string ".snd", the basic audio signature. fn audio_basic() -> ByteMatcher { ByteMatcher { pattern: b".snd", mask: b"\xFF\xFF\xFF\xFF", content_type: ("audio", "basic"), leading_ignore: &[] } } //The string "FORM" followed by four bytes followed by the string "AIFF", the AIFF signature. fn audio_aiff() -> ByteMatcher { ByteMatcher { pattern: b"FORM\x00\x00\x00\x00AIFF", mask: b"\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF", content_type: ("audio", "aiff"), leading_ignore: &[] } } //The string "ID3", the ID3v2-tagged MP3 signature. fn audio_mpeg() -> ByteMatcher { ByteMatcher { pattern: b"ID3", mask: b"\xFF\xFF\xFF", content_type: ("audio", "mpeg"), leading_ignore: &[] } } //The string "OggS" followed by NUL, the Ogg container signature. fn application_ogg() -> ByteMatcher { ByteMatcher { pattern: b"OggS", mask: b"\xFF\xFF\xFF\xFF\xFF", content_type: ("application", "ogg"), leading_ignore: &[] } } //The string "MThd" followed by four bytes representing the number 6 in 32 bits (big-endian), //the MIDI signature. fn audio_midi() -> ByteMatcher { ByteMatcher { pattern: b"MThd\x00\x00\x00\x06", mask: b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", content_type: ("audio", "midi"), leading_ignore: &[] } } //The string "RIFF" followed by four bytes followed by the string "AVI ", the AVI signature. fn video_avi() -> ByteMatcher { ByteMatcher { pattern: b"RIFF\x00\x00\x00\x00AVI ", mask: b"\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF", content_type: ("video", "avi"), leading_ignore: &[] } } // The string "RIFF" followed by four bytes followed by the string "WAVE", the WAVE signature. fn audio_wave() -> ByteMatcher { ByteMatcher { pattern: b"RIFF\x00\x00\x00\x00WAVE", mask: b"\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF", content_type: ("audio", "wave"), leading_ignore: &[] } } // doctype terminated with Tag terminating (TT) Byte fn text_html_doctype() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { matcher: ByteMatcher { pattern: b"<!DOCTYPE HTML", mask: b"\xFF\xFF\xDF\xDF\xDF\xDF\xDF\xDF\xDF\xFF\xDF\xDF\xDF\xDF", content_type: ("text", "html"), leading_ignore: b"\t\n\x0C\r " } } } // HTML terminated with Tag terminating (TT) Byte: 0x20 (SP) fn text_html_page() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { matcher: ByteMatcher { pattern: b"<HTML", mask: b"\xFF\xDF\xDF\xDF\xDF\xFF", content_type: ("text", "html"), leading_ignore: b"\t\n\x0C\r " } } } // head terminated with Tag Terminating (TT) Byte fn text_html_head() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { matcher: ByteMatcher { pattern: b"<HEAD", mask: b"\xFF\xDF\xDF\xDF\xDF", content_type: ("text", "html"), leading_ignore: b"\t\n\x0C\r " } } } // script terminated with Tag Terminating (TT) Byte fn text_html_script() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { matcher: ByteMatcher { pattern: b"<SCRIPT", mask: b"\xFF\xDF\xDF\xDF\xDF\xDF\xDF", content_type: ("text", "html"), leading_ignore: b"\t\n\x0C\r " } } } // iframe terminated with Tag Terminating (TT) Byte fn text_html_iframe() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { matcher: ByteMatcher { pattern: b"<IFRAME", mask: b"\xFF\xDF\xDF\xDF\xDF\xDF\xDF", content_type: ("text", "html"), leading_ignore: b"\t\n\x0C\r " } } } // h1 terminated with Tag Terminating (TT) Byte fn text_html_h1() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { matcher: ByteMatcher { pattern: b"<H1", mask: b"\xFF\xDF\xFF", content_type: ("text", "html"), leading_ignore: b"\t\n\x0C\r " } } } // div terminated with Tag Terminating (TT) Byte fn text_html_div() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { matcher: ByteMatcher { pattern: b"<DIV", mask: b"\xFF\xDF\xDF\xDF", content_type: ("text", "html"), leading_ignore: b"\t\n\x0C\r " } } } // font terminated with Tag Terminating (TT) Byte fn text_html_font() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { matcher: ByteMatcher { pattern: b"<FONT", mask: b"\xFF\xDF\xDF\xDF\xDF", content_type: ("text", "html"), leading_ignore: b"\t\n\x0C\r " } } } // table terminated with Tag Terminating (TT) Byte fn text_html_table() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { matcher: ByteMatcher { pattern: b"<TABLE", mask: b"\xFF\xDF\xDF\xDF\xDF\xDF", content_type: ("text", "html"), leading_ignore: b"\t\n\x0C\r " } } } // a terminated with Tag Terminating (TT) Byte fn text_html_a() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { matcher: ByteMatcher { pattern: b"<A", mask: b"\xFF\xDF", content_type: ("text", "html"), leading_ignore: b"\t\n\x0C\r " } } } // style terminated with Tag Terminating (TT) Byte fn text_html_style() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { matcher: ByteMatcher { pattern: b"<STYLE", mask: b"\xFF\xDF\xDF\xDF\xDF\xDF", content_type: ("text", "html"), leading_ignore: b"\t\n\x0C\r " } } } // title terminated with Tag Terminating (TT) Byte fn text_html_title() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { matcher: ByteMatcher { pattern: b"<TITLE", mask: b"\xFF\xDF\xDF\xDF\xDF\xDF", content_type: ("text", "html"), leading_ignore: b"\t\n\x0C\r " } } } // b terminated with Tag Terminating (TT) Byte fn text_html_b() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { matcher: ByteMatcher { pattern: b"<B", mask: b"\xFF\xDF", content_type: ("text", "html"), leading_ignore: b"\t\n\x0C\r " } } } // body terminated with Tag Terminating (TT) Byte fn text_html_body() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { matcher: ByteMatcher { pattern: b"<BODY", mask: b"\xFF\xDF\xDF\xDF\xDF", content_type: ("text", "html"), leading_ignore: b"\t\n\x0C\r " } } } // br terminated with Tag Terminating (TT) Byte fn text_html_br() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { matcher: ByteMatcher { pattern: b"<BR", mask: b"\xFF\xDF\xDF", content_type: ("text", "html"), leading_ignore: b"\t\n\x0C\r " } } } // p terminated with Tag Terminating (TT) Byte fn text_html_p() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { matcher: ByteMatcher { pattern: b"<P", mask: b"\xFF\xDF", content_type: ("text", "html"), leading_ignore: b"\t\n\x0C\r " } } } // comment terminated with Tag Terminating (TT) Byte fn text_html_comment() -> TagTerminatedByteMatcher { TagTerminatedByteMatcher { matcher: ByteMatcher { pattern: b"<!--", mask: b"\xFF\xFF\xFF\xFF", content_type: ("text", "html"), leading_ignore: b"\t\n\x0C\r " } } } //The string "<?xml". fn text_xml() -> ByteMatcher { ByteMatcher { pattern: b"<?xml", mask: b"\xFF\xFF\xFF\xFF\xFF", content_type: ("text", "xml"), leading_ignore: b"\t\n\x0C\r " } } //The string "%PDF-", the PDF signature. fn application_pdf() -> ByteMatcher { ByteMatcher { pattern: b"%PDF", mask: b"\xFF\xFF\xFF\xFF\xFF", content_type: ("application", "pdf"), leading_ignore: &[] } } //34 bytes followed by the string "LP", the Embedded OpenType signature. // TODO: Use this in font context classifier #[allow(dead_code)] fn application_vnd_ms_font_object() -> ByteMatcher { ByteMatcher { pattern: b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00LP", mask: b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\xFF\xFF", content_type: ("application", "vnd.ms-fontobject"), leading_ignore: &[] } } //4 bytes representing the version number 1.0, a TrueType signature. // TODO: Use this in font context classifier #[allow(dead_code)] fn true_type() -> ByteMatcher { ByteMatcher { pattern: b"\x00\x01\x00\x00", mask: b"\xFF\xFF\xFF\xFF", content_type: ("(TrueType)", ""), leading_ignore: &[] } } //The string "OTTO", the OpenType signature. // TODO: Use this in font context classifier #[allow(dead_code)] fn open_type() -> ByteMatcher { ByteMatcher { pattern: b"OTTO", mask: b"\xFF\xFF\xFF\xFF", content_type: ("(OpenType)", ""), leading_ignore: &[] } } // The string "ttcf", the TrueType Collection signature. // TODO: Use this in font context classifier #[allow(dead_code)] fn true_type_collection() -> ByteMatcher { ByteMatcher { pattern: b"ttcf", mask: b"\xFF\xFF\xFF\xFF", content_type: ("(TrueType Collection)", ""), leading_ignore: &[] } } // The string "wOFF", the Web Open Font Format signature. // TODO: Use this in font context classifier #[allow(dead_code)] fn application_font_woff() -> ByteMatcher { ByteMatcher { pattern: b"wOFF", mask: b"\xFF\xFF\xFF\xFF", content_type: ("application", "font-woff"), leading_ignore: &[] } } //The GZIP archive signature. fn application_x_gzip() -> ByteMatcher { ByteMatcher { pattern: b"\x1F\x8B\x08", mask: b"\xFF\xFF\xFF", content_type: ("application", "x-gzip"), leading_ignore: &[] } } //The string "PK" followed by ETX EOT, the ZIP archive signature. fn application_zip() -> ByteMatcher { ByteMatcher { pattern: b"PK\x03\x04", mask: b"\xFF\xFF\xFF\xFF", content_type: ("application", "zip"), leading_ignore: &[] } } //The string "Rar " followed by SUB BEL NUL, the RAR archive signature. fn application_x_rar_compressed() -> ByteMatcher { ByteMatcher { pattern: b"Rar \x1A\x07\x00", mask: b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF", content_type: ("application", "x-rar-compressed"), leading_ignore: &[] } } // The string "%!PS-Adobe-", the PostScript signature. fn application_postscript() -> ByteMatcher { ByteMatcher { pattern: b"%!PS-Adobe-", mask: b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", content_type: ("application", "postscript"), leading_ignore: &[] } } // UTF-16BE BOM fn text_plain_utf_16be_bom() -> ByteMatcher { ByteMatcher { pattern: b"\xFE\xFF\x00\x00", mask: b"\xFF\xFF\x00\x00", content_type: ("text", "plain"), leading_ignore: &[] } } //UTF-16LE BOM fn text_plain_utf_16le_bom() -> ByteMatcher { ByteMatcher { pattern: b"\xFF\xFE\x00\x00", mask: b"\xFF\xFF\x00\x00", content_type: ("text", "plain"), leading_ignore: &[] } } //UTF-8 BOM fn text_plain_utf_8_bom() -> ByteMatcher { ByteMatcher { pattern: b"\xEF\xBB\xBF\x00", mask: b"\xFF\xFF\xFF\x00", content_type: ("text", "plain"), leading_ignore: &[] } } }<|fim▁end|>
<|file_name|>catalog_test.go<|end_file_name|><|fim▁begin|>package servicebroker import ( "reflect" "testing" schema "github.com/lestrrat/go-jsschema" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/openshift/origin/pkg/openservicebroker/api" templateapi "github.com/openshift/origin/pkg/template/api" ) func TestServiceFromTemplate(t *testing.T) { template := &templateapi.Template{ ObjectMeta: metav1.ObjectMeta{ Name: "name", UID: "ee33151d-a34d-442d-a0ca-6353b73a58fd", Annotations: map[string]string{ "description": "description", "tags": "tag1,tag2", "openshift.io/display-name": "displayName", "iconClass": "iconClass", "template.openshift.io/long-description": "longDescription", "template.openshift.io/provider-display-name": "providerDisplayName", "template.openshift.io/documentation-url": "documentationURL", "template.openshift.io/support-url": "supportURL", }, }, Parameters: []templateapi.Parameter{ { Name: "param1", Required: true, }, { Name: "param2", }, }, } expectedService := &api.Service{ Name: "name", ID: "ee33151d-a34d-442d-a0ca-6353b73a58fd", Description: "description", Tags: []string{"tag1", "tag2"}, Bindable: true, Metadata: map[string]interface{}{ "providerDisplayName": "providerDisplayName", "documentationUrl": "documentationURL", "supportUrl": "supportURL", "displayName": "displayName", "console.openshift.io/iconClass": "iconClass", "longDescription": "longDescription", }, Plans: []api.Plan{ { ID: "ee33151d-a34d-442d-a0ca-6353b73a58fd", Name: "default", Description: "Default plan", Free: true, Bindable: true, Schemas: api.Schema{ ServiceInstances: api.ServiceInstances{ Create: map[string]*schema.Schema{ "parameters": { Type: schema.PrimitiveTypes{schema.ObjectType}, SchemaRef: "http://json-schema.org/draft-04/schema", Required: []string{ "template.openshift.io/namespace", "template.openshift.io/requester-username", "param1", }, Properties: map[string]*schema.Schema{ "template.openshift.io/namespace": { Title: "Template service broker: namespace", Description: "OpenShift namespace in which to provision service", Type: schema.PrimitiveTypes{schema.StringType}, }, "template.openshift.io/requester-username": { Title: "Template service broker: requester username", Description: "OpenShift user requesting provision/bind", Type: schema.PrimitiveTypes{schema.StringType}, }, "param1": { Default: "", Type: schema.PrimitiveTypes{schema.StringType}, }, "param2": { Default: "", Type: schema.PrimitiveTypes{schema.StringType}, }, }, }, }, }, ServiceBindings: api.ServiceBindings{ Create: map[string]*schema.Schema{ "parameters": { Type: schema.PrimitiveTypes{schema.ObjectType}, SchemaRef: "http://json-schema.org/draft-04/schema", Required: []string{"template.openshift.io/requester-username"}, Properties: map[string]*schema.Schema{ "template.openshift.io/requester-username": {<|fim▁hole|> }, }, }, }, }, }, }, } service := serviceFromTemplate(template) if !reflect.DeepEqual(service, expectedService) { t.Error("service did not match expectedService") } }<|fim▁end|>
Title: "Template service broker: requester username", Description: "OpenShift user requesting provision/bind", Type: schema.PrimitiveTypes{schema.StringType}, },
<|file_name|>plot_sparse_coding.py<|end_file_name|><|fim▁begin|>""" =========================================== Sparse coding with a precomputed dictionary =========================================== Transform a signal as a sparse combination of Ricker wavelets. This example visually compares different sparse coding methods using the :class:`sklearn.decomposition.SparseCoder` estimator. The Ricker (also known as mexican hat or the second derivative of a gaussian) is not a particularily good kernel to represent piecewise constant signals like this one. It can therefore be seen how much adding different widths of atoms matters and it therefore motivates learning the dictionary to best fit your type of signals. The richer dictionary on the right is not larger in size, heavier subsampling is performed in order to stay on the same order of magnitude. """ print __doc__ import numpy as np import matplotlib.pylab as pl from sklearn.decomposition import SparseCoder def ricker_function(resolution, center, width): """Discrete sub-sampled Ricker (mexican hat) wavelet""" x = np.linspace(0, resolution - 1, resolution) x = (2 / ((np.sqrt(3 * width) * np.pi ** 1 / 4))) * ( 1 - ((x - center) ** 2 / width ** 2)) * np.exp( (-(x - center) ** 2) / (2 * width ** 2)) return x def ricker_matrix(width, resolution, n_atoms): """Dictionary of Ricker (mexican hat) wavelets""" centers = np.linspace(0, resolution - 1, n_atoms) D = np.empty((n_atoms, resolution)) for i, center in enumerate(centers): D[i] = ricker_function(resolution, center, width) D /= np.sqrt(np.sum(D ** 2, axis=1))[:, np.newaxis] return D resolution = 1024 subsampling = 3 # subsampling factor width = 100 n_atoms = resolution / subsampling # Compute a wavelet dictionary D_fixed = ricker_matrix(width=width, resolution=resolution, n_atoms=n_atoms) D_multi = np.r_[tuple(ricker_matrix(width=w, resolution=resolution, n_atoms=np.floor(n_atoms / 5)) for w in (10, 50, 100, 500, 1000))] # Generate a signal y = np.linspace(0, resolution - 1, resolution) first_quarter = y < resolution / 4 y[first_quarter] = 3. y[np.logical_not(first_quarter)] = -1. # List the different sparse coding methods in the following format:<|fim▁hole|> pl.figure(figsize=(13, 6)) for subplot, (D, title) in enumerate(zip((D_fixed, D_multi), ('fixed width', 'multiple widths'))): pl.subplot(1, 2, subplot + 1) pl.title('Sparse coding against %s dictionary' % title) pl.plot(y, ls='dotted', label='Original signal') # Do a wavelet approximation for title, algo, alpha, n_nonzero in estimators: coder = SparseCoder(dictionary=D, transform_n_nonzero_coefs=n_nonzero, transform_alpha=alpha, transform_algorithm=algo) x = coder.transform(y) density = len(np.flatnonzero(x)) x = np.ravel(np.dot(x, D)) squared_error = np.sum((y - x) ** 2) pl.plot(x, label='%s: %s nonzero coefs,\n%.2f error' % (title, density, squared_error)) # Soft thresholding debiasing coder = SparseCoder(dictionary=D, transform_algorithm='threshold', transform_alpha=20) x = coder.transform(y) _, idx = np.where(x != 0) x[0, idx], _, _, _ = np.linalg.lstsq(D[idx, :].T, y) x = np.ravel(np.dot(x, D)) squared_error = np.sum((y - x) ** 2) pl.plot(x, label='Thresholding w/ debiasing:\n%d nonzero coefs, %.2f error' % (len(idx), squared_error)) pl.axis('tight') pl.legend() pl.subplots_adjust(.04, .07, .97, .90, .09, .2) pl.show()<|fim▁end|>
# (title, transform_algorithm, transform_alpha, transform_n_nozero_coefs) estimators = [('OMP', 'omp', None, 15), ('Lasso', 'lasso_cd', 2, None), ]
<|file_name|>stripe.d.ts<|end_file_name|><|fim▁begin|>export interface StripeCardTokenParams { /** * Card number */ number: string; /** * Expiry month */ expMonth: number; /** * Expiry year */ <|fim▁hole|> expYear: number; /** * CVC / CVV */ cvc?: string; /** * Cardholder name */ name?: string; /** * Address line 1 */ address_line1?: string; /** * Address line 2 */ address_line2?: string; /** * City */ address_city?: string; /** * State / Province */ address_state?: string; /** * Country */ address_country?: string; /** * Postal code / ZIP Code */ postal_code?: string; /** * 3-letter ISO code for currency */ currency?: string; } /** * @beta * @name Stripe * @description * A plugin that allows you to use Stripe's Native SDKs for Android and iOS. * * @usage * ``` * import { Stripe } from 'ionic-native'; * * Stripe.setPublishableKey('my_publishable_key'); * * let card = { * number: '4242424242424242', * expMonth: 12, * expYear: 2020, * cvc: 220 * }; * * Stripe.createToken(card) * .then(token => console.log(token)) * .catch(error => console.error(error)); * * ``` * * @interfaces * StripeCardTokenParams */ export declare class Stripe { /** * Set publishable key * @param publishableKey {string} Publishable key * @return {Promise<void>} */ static setPublishableKey(publishableKey: string): Promise<void>; /** * Create Credit Card Token * @param params {StripeCardTokenParams} Credit card information * @return {Promise<string>} returns a promise that resolves with the token, or reject with an error */ static createCardToken(params: StripeCardTokenParams): Promise<string>; }<|fim▁end|>
<|file_name|>service.py<|end_file_name|><|fim▁begin|># Copyright (c) 2013 eBay Software Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import json import os import stat import subprocess import tempfile from oslo_log import log as logging from oslo_utils import netutils import pexpect import six from trove.common import cfg from trove.common.db import models from trove.common import exception from trove.common.i18n import _ from trove.common import instance as rd_instance from trove.common import utils as utils from trove.guestagent.common import operating_system from trove.guestagent.datastore.experimental.couchbase import system from trove.guestagent.datastore import service from trove.guestagent import pkg LOG = logging.getLogger(__name__) CONF = cfg.CONF packager = pkg.Package() class CouchbaseApp(object): """ Handles installation and configuration of couchbase on a trove instance. """ def __init__(self, status, state_change_wait_time=None): """ Sets default status and state_change_wait_time """ if state_change_wait_time: self.state_change_wait_time = state_change_wait_time else: self.state_change_wait_time = CONF.state_change_wait_time self.status = status def install_if_needed(self, packages): """ Install couchbase if needed, do nothing if it is already installed. """ LOG.info(_('Preparing Guest as Couchbase Server.')) if not packager.pkg_is_installed(packages): LOG.debug('Installing Couchbase.') self._install_couchbase(packages) def initial_setup(self): self.ip_address = netutils.get_my_ipv4() mount_point = CONF.couchbase.mount_point try: LOG.info(_('Couchbase Server change data dir path.')) operating_system.chown(mount_point, 'couchbase', 'couchbase', as_root=True) pwd = CouchbaseRootAccess.get_password() utils.execute_with_timeout( (system.cmd_node_init % {'data_path': mount_point, 'IP': self.ip_address, 'PWD': pwd}), shell=True) operating_system.remove(system.INSTANCE_DATA_DIR, force=True, as_root=True) LOG.debug('Couchbase Server initialize cluster.') utils.execute_with_timeout( (system.cmd_cluster_init % {'IP': self.ip_address, 'PWD': pwd}), shell=True) utils.execute_with_timeout(system.cmd_set_swappiness, shell=True) utils.execute_with_timeout(system.cmd_update_sysctl_conf, shell=True) LOG.info(_('Couchbase Server initial setup finished.')) except exception.ProcessExecutionError: LOG.exception(_('Error performing initial Couchbase setup.')) raise RuntimeError(_("Couchbase Server initial setup failed")) def _install_couchbase(self, packages): """ Install the Couchbase Server. """ LOG.debug('Installing Couchbase Server. Creating %s' % system.COUCHBASE_CONF_DIR) operating_system.create_directory(system.COUCHBASE_CONF_DIR, as_root=True) pkg_opts = {} packager.pkg_install(packages, pkg_opts, system.TIME_OUT) self.start_db() LOG.debug('Finished installing Couchbase Server.') def stop_db(self, update_db=False, do_not_start_on_reboot=False): self.status.stop_db_service( system.SERVICE_CANDIDATES, self.state_change_wait_time, disable_on_boot=do_not_start_on_reboot, update_db=update_db) def restart(self): self.status.restart_db_service( system.SERVICE_CANDIDATES, self.state_change_wait_time) def start_db(self, update_db=False): self.status.start_db_service( system.SERVICE_CANDIDATES, self.state_change_wait_time, enable_on_boot=True, update_db=update_db) def enable_root(self, root_password=None): return CouchbaseRootAccess.enable_root(root_password) def start_db_with_conf_changes(self, config_contents): LOG.info(_("Starting Couchbase with configuration changes.\n" "Configuration contents:\n %s.") % config_contents) if self.status.is_running: LOG.error(_("Cannot start Couchbase with configuration changes. " "Couchbase state == %s.") % self.status) raise RuntimeError(_("Couchbase is not stopped.")) self._write_config(config_contents) self.start_db(True) def reset_configuration(self, configuration): config_contents = configuration['config_contents'] LOG.debug("Resetting configuration.") self._write_config(config_contents) def _write_config(self, config_contents): """ Update contents of Couchbase configuration file """ return class CouchbaseAppStatus(service.BaseDbStatus): """ Handles all of the status updating for the couchbase guest agent. """ def _get_actual_db_status(self): self.ip_address = netutils.get_my_ipv4() pwd = None try: pwd = CouchbaseRootAccess.get_password() return self._get_status_from_couchbase(pwd) except exception.ProcessExecutionError: # log the exception, but continue with native config approach LOG.exception(_("Error getting the Couchbase status.")) try: out, err = utils.execute_with_timeout( system.cmd_get_password_from_config, shell=True) except exception.ProcessExecutionError: LOG.exception(_("Error getting the root password from the " "native Couchbase config file.")) return rd_instance.ServiceStatuses.SHUTDOWN config_pwd = out.strip() if out is not None else None if not config_pwd or config_pwd == pwd: LOG.debug("The root password from the native Couchbase config " "file is either empty or already matches the " "stored value.") return rd_instance.ServiceStatuses.SHUTDOWN try:<|fim▁hole|> "config file.")) return rd_instance.ServiceStatuses.SHUTDOWN # if the parsed root password worked, update the stored value to # avoid having to consult/parse the couchbase config file again. LOG.debug("Updating the stored value for the Couchbase " "root password.") CouchbaseRootAccess().write_password_to_file(config_pwd) return status def _get_status_from_couchbase(self, pwd): out, err = utils.execute_with_timeout( (system.cmd_couchbase_status % {'IP': self.ip_address, 'PWD': pwd}), shell=True) server_stats = json.loads(out) if not err and server_stats["clusterMembership"] == "active": return rd_instance.ServiceStatuses.RUNNING else: return rd_instance.ServiceStatuses.SHUTDOWN def cleanup_stalled_db_services(self): utils.execute_with_timeout(system.cmd_kill) class CouchbaseRootAccess(object): @classmethod def enable_root(cls, root_password=None): user = models.DatastoreUser.root(password=root_password) if root_password: CouchbaseRootAccess().write_password_to_file(root_password) else: CouchbaseRootAccess().set_password(user.password) return user.serialize() def set_password(self, root_password): self.ip_address = netutils.get_my_ipv4() child = pexpect.spawn(system.cmd_reset_pwd % {'IP': self.ip_address}) try: child.expect('.*password.*') child.sendline(root_password) child.expect('.*(yes/no).*') child.sendline('yes') child.expect('.*successfully.*') except pexpect.TIMEOUT: child.delayafterclose = 1 child.delayafterterminate = 1 try: child.close(force=True) except pexpect.ExceptionPexpect: # Close fails to terminate a sudo process on some OSes. subprocess.call(['sudo', 'kill', str(child.pid)]) self.write_password_to_file(root_password) def write_password_to_file(self, root_password): operating_system.create_directory(system.COUCHBASE_CONF_DIR, as_root=True) try: tempfd, tempname = tempfile.mkstemp() os.fchmod(tempfd, stat.S_IRUSR | stat.S_IWUSR) if isinstance(root_password, six.text_type): root_password = root_password.encode('utf-8') os.write(tempfd, root_password) os.fchmod(tempfd, stat.S_IRUSR) os.close(tempfd) except OSError as err: message = _("An error occurred in saving password " "(%(errno)s). %(strerror)s.") % { "errno": err.errno, "strerror": err.strerror} LOG.exception(message) raise RuntimeError(message) operating_system.move(tempname, system.pwd_file, as_root=True) @staticmethod def get_password(): pwd = "password" if os.path.exists(system.pwd_file): with open(system.pwd_file) as file: pwd = file.readline().strip() return pwd<|fim▁end|>
status = self._get_status_from_couchbase(config_pwd) except exception.ProcessExecutionError: LOG.exception(_("Error getting Couchbase status using the " "password parsed from the native Couchbase "
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#-*- coding: utf-8 -*- # Author: Matt Earnshaw <[email protected]> from __future__ import absolute_import import os import sys import sunpy from PyQt4.QtGui import QApplication from sunpy.gui.mainwindow import MainWindow from sunpy.io import UnrecognizedFileTypeError class Plotman(object): """ Wraps a MainWindow so PlotMan instances can be created via the CLI. Examples<|fim▁hole|> from sunpy.gui import Plotman plots = Plotman("data/examples") plots.show() """ def __init__(self, *paths): """ *paths: directories containing FITS paths or FITS paths to be opened in PlotMan """ self.app = QApplication(sys.argv) self.main = MainWindow() self.open_files(paths) def open_files(self, inputs): VALID_EXTENSIONS = [".jp2", ".fits", ".fts"] to_open = [] # Determine files to process for input_ in inputs: if os.path.isfile(input_): to_open.append(input_) elif os.path.isdir(input_): for file_ in os.listdir(input_): to_open.append(file_) else: raise IOError("Path " + input_ + " does not exist.") # Load files for filepath in to_open: name, ext = os.path.splitext(filepath) #pylint: disable=W0612 if ext.lower() in VALID_EXTENSIONS: try: self.main.add_tab(filepath, os.path.basename(filepath)) except UnrecognizedFileTypeError: pass def show(self): self.main.show() self.app.exec_() if __name__=="__main__": from sunpy.gui import Plotman plots = Plotman(sunpy.AIA_171_IMAGE) plots.show()<|fim▁end|>
--------
<|file_name|>index.d.ts<|end_file_name|><|fim▁begin|><|fim▁hole|> export = differenceInMinutes }<|fim▁end|>
declare module 'date-fns/difference_in_minutes' { import {differenceInMinutes} from 'date-fns'
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.conf import settings from django.db import models<|fim▁hole|> from django_dropimages import settings as di_settings # if no custom image models is present I load my own if not di_settings.CONFIG['DROPIMAGEGALLERY_MODEL']: class DropimagesGallery(models.Model): gallery_identifier = models.CharField(max_length=36) creation_timestamp = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True) # if no custom image models is present I load my own if not di_settings.CONFIG['DROPIMAGE_MODEL']: class DropimagesImage(models.Model): dropimages_gallery = models.ForeignKey('django_dropimages.DropimagesGallery', related_name='images') dropimages_original_filename = models.CharField(max_length=256) image = models.ImageField(upload_to='%y/%m/%d')<|fim▁end|>
<|file_name|>guestbook.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # # Copyright 2015 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import jinja2 import os import webapp2 import logging from google.appengine.api import memcache jinja_environment = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), extensions=['jinja2.ext.autoescape'], autoescape=True) class MainPage(webapp2.RequestHandler): def get(self): greetings = memcache.get('entries') if greetings is None: greetings = [] template = jinja_environment.get_template('index.html') self.response.out.write(template.render(entries=greetings)) def post(self): greeting = self.request.get('entry') greetings = memcache.get('entries') if greetings is not None: greetings.append(greeting) if not memcache.replace('entries', greetings): logging.error('Memcache replace failed.') else: greetings = [greeting] if not memcache.set('entries', greetings): logging.error('Memcache set failed.') self.redirect('/') class Clear(webapp2.RequestHandler): def post(self): if not memcache.delete('entries'): logging.error("Memcache failed to delete entries") self.redirect('/') <|fim▁hole|> ('/', MainPage), ('/clear', Clear) ], debug=True)<|fim▁end|>
application = webapp2.WSGIApplication([
<|file_name|>non_sym_m0n.py<|end_file_name|><|fim▁begin|>from __future__ import division import conformal_blocks.cbbundle as cbd import cProfile, time, random #First test #---------- # def experiment(): """ Computes the rank and divisor of conformal block bundles with random weights. :return: Null """<|fim▁hole|> liealg = cbd.TypeALieAlgebra(rank, store_fusion=True, exact=False) A_l = liealg.get_weights(level) print("Weight", "Rank", "Divisor") for i in range(tries): weights = [random.choice(A_l) for i in range(num_points)] if sum([sum(liealg._convert_funds_to_epsilons(wt)) for wt in weights]) % (rank+1) != 0: continue cbb = cbd.ConformalBlocksBundle(liealg, weights, level) if cbb.get_rank() > 0: divisor = cbb.get_symmetrized_divisor() print(weights, cbb.get_rank(), divisor) else: print(weights, cbb.get_rank(), 0) if __name__ == '__main__': t0 = time.clock() experiment() print(time.clock() -t0) #cProfile.run('experiment()', sort='cumtime')<|fim▁end|>
rank = 5 level = 3 num_points = 10 tries = 100
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>default_app_config = 'providers.edu.iowaresearch.apps.AppConfig' """ Example Record <record> <header> <identifier>oai:ir.uiowa.edu:iwp_archive-1227</identifier> <datestamp>2016-07-05T19:23:14Z</datestamp> <setSpec>publication:iwp</setSpec> <setSpec>publication:grad</setSpec> <setSpec>publication:iwp_archive</setSpec> <setSpec>publication:harvest</setSpec> <setSpec>publication:fullharvest</setSpec> </header> <metadata> <oai_dc:dc xmlns:oai_dc="http://www.openarchives.org/OAI/2.0/oai_dc/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd"> <dc:title>Writing Sample</dc:title> <dc:creator>Gamerro, Carlos</dc:creator><|fim▁hole|> <dc:date>2008-10-01T07:00:00Z</dc:date> <dc:type>text</dc:type> <dc:format>application/pdf</dc:format> <dc:identifier>http://ir.uiowa.edu/iwp_archive/228</dc:identifier> <dc:identifier> http://ir.uiowa.edu/cgi/viewcontent.cgi?article=1227&amp;context=iwp_archive </dc:identifier> <dc:rights>Copyright © 2008 Carlos Gamerro</dc:rights> <dc:source> International Writing Program Archive of Residents' Work </dc:source> <dc:language>eng</dc:language> <dc:publisher>Iowa Research Online</dc:publisher> </oai_dc:dc> </metadata> </record> """<|fim▁end|>
<dc:description> Excerpts from The Adventure of the Busts of Eva Perón and The Islands. </dc:description>
<|file_name|>index.d.ts<|end_file_name|><|fim▁begin|>export * from "./logic" export * from "./strategies" export * from "./defaults"<|fim▁hole|><|fim▁end|>
export * from "./dragndrop"
<|file_name|>product_supplierinfo.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # © 2014 Serv. Tecnol. Avanzados (http://www.serviciosbaeza.com) # Pedro M. Baeza <[email protected]> # © 2016 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from openerp import models, fields, api import openerp.addons.decimal_precision as dp class ProductSupplierInfo(models.Model): _inherit = 'product.supplierinfo' discount = fields.Float( string='Discount (%)', digits_compute=dp.get_precision('Discount'))<|fim▁hole|> def onchange_name(self): for supplierinfo in self.filtered('name'): supplierinfo.discount =\ supplierinfo.name.default_supplierinfo_discount<|fim▁end|>
@api.onchange('name') @api.multi
<|file_name|>test03.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python from ming import * import sys srcdir=sys.argv[1] m = SWFMovie(); font = SWFFont(srcdir + "/../Media/test.ttf")<|fim▁hole|> w = font.getStringWidth("The quick brown fox jumps over the lazy dog. 1234567890") text.setFont(font) text.setColor(0,0,0,255) text.setHeight(20) text.moveTo(w,0) text.addString("|") m.add(text) m.nextFrame() m.save("test03.swf")<|fim▁end|>
text = SWFText(1)
<|file_name|>tcp.rs<|end_file_name|><|fim▁begin|>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use prelude::v1::*; use io::prelude::*; use io; use net::{ToSocketAddrs, SocketAddr, Shutdown}; use sys_common::net2 as net_imp; use sys_common::AsInner; /// A structure which represents a TCP stream between a local socket and a /// remote socket. /// /// The socket will be closed when the value is dropped. /// /// # Example /// /// ```no_run /// use std::io::prelude::*; /// use std::net::TcpStream; /// /// { /// let mut stream = TcpStream::connect("127.0.0.1:34254").unwrap(); /// /// // ignore the Result /// let _ = stream.write(&[1]); /// let _ = stream.read(&mut [0; 128]); // ignore here too /// } // the stream is closed here /// ``` pub struct TcpStream(net_imp::TcpStream); /// A structure representing a socket server. /// /// # Examples /// /// ```no_run /// use std::net::{TcpListener, TcpStream}; /// use std::thread::Thread; /// /// let listener = TcpListener::bind("127.0.0.1:80").unwrap(); /// /// fn handle_client(stream: TcpStream) { /// // ... /// } /// /// // accept connections and process them, spawning a new thread for each one /// for stream in listener.incoming() { /// match stream { /// Ok(stream) => { /// Thread::spawn(move|| { /// // connection succeeded /// handle_client(stream) /// }); /// } /// Err(e) => { /* connection failed */ } /// } /// } /// /// // close the socket server /// drop(listener); /// ``` pub struct TcpListener(net_imp::TcpListener); /// An infinite iterator over the connections from a `TcpListener`. /// /// This iterator will infinitely yield `Some` of the accepted connections. It /// is equivalent to calling `accept` in a loop. pub struct Incoming<'a> { listener: &'a TcpListener } impl TcpStream { /// Open a TCP connection to a remote host. /// /// `addr` is an address of the remote host. Anything which implements /// `ToSocketAddrs` trait can be supplied for the address; see this trait /// documentation for concrete examples. pub fn connect<A: ToSocketAddrs + ?Sized>(addr: &A) -> io::Result<TcpStream> { super::each_addr(addr, net_imp::TcpStream::connect).map(TcpStream) } /// Returns the socket address of the remote peer of this TCP connection. pub fn peer_addr(&self) -> io::Result<SocketAddr> { self.0.peer_addr() } /// Returns the socket address of the local half of this TCP connection. pub fn socket_addr(&self) -> io::Result<SocketAddr> { self.0.socket_addr() } /// Shut down the read, write, or both halves of this connection. /// /// This function will cause all pending and future I/O on the specified /// portions to return immediately with an appropriate value (see the /// documentation of `Shutdown`). pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { self.0.shutdown(how) } /// Create a new independently owned handle to the underlying socket. /// /// The returned `TcpStream` is a reference to the same stream that this /// object references. Both handles will read and write the same stream of /// data, and options set on one stream will be propagated to the other /// stream. pub fn try_clone(&self) -> io::Result<TcpStream> { self.0.duplicate().map(TcpStream) } /// Sets the nodelay flag on this connection to the boolean specified pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> { self.0.set_nodelay(nodelay) } /// Sets the keepalive timeout to the timeout specified. /// /// If the value specified is `None`, then the keepalive flag is cleared on /// this connection. Otherwise, the keepalive timeout will be set to the /// specified time, in seconds. pub fn set_keepalive(&self, seconds: Option<u32>) -> io::Result<()> { self.0.set_keepalive(seconds) } } impl Read for TcpStream { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } } impl Write for TcpStream { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } impl<'a> Read for &'a TcpStream { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } } impl<'a> Write for &'a TcpStream { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }<|fim▁hole|> fn flush(&mut self) -> io::Result<()> { Ok(()) } } impl AsInner<net_imp::TcpStream> for TcpStream { fn as_inner(&self) -> &net_imp::TcpStream { &self.0 } } impl TcpListener { /// Creates a new `TcpListener` which will be bound to the specified /// address. /// /// The returned listener is ready for accepting connections. /// /// Binding with a port number of 0 will request that the OS assigns a port /// to this listener. The port allocated can be queried via the /// `socket_addr` function. /// /// The address type can be any implementer of `ToSocketAddrs` trait. See /// its documentation for concrete examples. pub fn bind<A: ToSocketAddrs + ?Sized>(addr: &A) -> io::Result<TcpListener> { super::each_addr(addr, net_imp::TcpListener::bind).map(TcpListener) } /// Returns the local socket address of this listener. pub fn socket_addr(&self) -> io::Result<SocketAddr> { self.0.socket_addr() } /// Create a new independently owned handle to the underlying socket. /// /// The returned `TcpListener` is a reference to the same socket that this /// object references. Both handles can be used to accept incoming /// connections and options set on one listener will affect the other. pub fn try_clone(&self) -> io::Result<TcpListener> { self.0.duplicate().map(TcpListener) } /// Accept a new incoming connection from this listener. /// /// This function will block the calling thread until a new TCP connection /// is established. When established, the corresponding `TcpStream` and the /// remote peer's address will be returned. pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> { self.0.accept().map(|(a, b)| (TcpStream(a), b)) } /// Returns an iterator over the connections being received on this /// listener. /// /// The returned iterator will never returned `None` and will also not yield /// the peer's `SocketAddr` structure. pub fn incoming(&self) -> Incoming { Incoming { listener: self } } } impl<'a> Iterator for Incoming<'a> { type Item = io::Result<TcpStream>; fn next(&mut self) -> Option<io::Result<TcpStream>> { Some(self.listener.accept().map(|p| p.0)) } } impl AsInner<net_imp::TcpListener> for TcpListener { fn as_inner(&self) -> &net_imp::TcpListener { &self.0 } } #[cfg(test)] mod tests { use prelude::v1::*; use io::ErrorKind; use io::prelude::*; use net::*; use net::test::{next_test_ip4, next_test_ip6}; use sync::mpsc::channel; use thread::Thread; fn each_ip(f: &mut FnMut(SocketAddr)) { f(next_test_ip4()); f(next_test_ip6()); } macro_rules! t { ($e:expr) => { match $e { Ok(t) => t, Err(e) => panic!("received error for `{}`: {}", stringify!($e), e), } } } // FIXME #11530 this fails on android because tests are run as root #[cfg_attr(any(windows, target_os = "android"), ignore)] #[test] fn bind_error() { match TcpListener::bind("0.0.0.0:1") { Ok(..) => panic!(), Err(e) => assert_eq!(e.kind(), ErrorKind::PermissionDenied), } } #[test] fn connect_error() { match TcpStream::connect("0.0.0.0:1") { Ok(..) => panic!(), Err(e) => assert_eq!(e.kind(), ErrorKind::ConnectionRefused), } } #[test] fn listen_localhost() { let socket_addr = next_test_ip4(); let listener = t!(TcpListener::bind(&socket_addr)); let _t = Thread::scoped(move || { let mut stream = t!(TcpStream::connect(&("localhost", socket_addr.port()))); t!(stream.write(&[144])); }); let mut stream = t!(listener.accept()).0; let mut buf = [0]; t!(stream.read(&mut buf)); assert!(buf[0] == 144); } #[test] fn connect_ip4_loopback() { let addr = next_test_ip4(); let acceptor = t!(TcpListener::bind(&addr)); let _t = Thread::scoped(move|| { let mut stream = t!(TcpStream::connect(&("127.0.0.1", addr.port()))); t!(stream.write(&[44])); }); let mut stream = t!(acceptor.accept()).0; let mut buf = [0]; t!(stream.read(&mut buf)); assert!(buf[0] == 44); } #[test] fn connect_ip6_loopback() { let addr = next_test_ip6(); let acceptor = t!(TcpListener::bind(&addr)); let _t = Thread::scoped(move|| { let mut stream = t!(TcpStream::connect(&("::1", addr.port()))); t!(stream.write(&[66])); }); let mut stream = t!(acceptor.accept()).0; let mut buf = [0]; t!(stream.read(&mut buf)); assert!(buf[0] == 66); } #[test] fn smoke_test_ip6() { each_ip(&mut |addr| { let acceptor = t!(TcpListener::bind(&addr)); let (tx, rx) = channel(); let _t = Thread::scoped(move|| { let mut stream = t!(TcpStream::connect(&addr)); t!(stream.write(&[99])); tx.send(t!(stream.socket_addr())).unwrap(); }); let (mut stream, addr) = t!(acceptor.accept()); let mut buf = [0]; t!(stream.read(&mut buf)); assert!(buf[0] == 99); assert_eq!(addr, t!(rx.recv())); }) } #[test] fn read_eof_ip4() { each_ip(&mut |addr| { let acceptor = t!(TcpListener::bind(&addr)); let _t = Thread::scoped(move|| { let _stream = t!(TcpStream::connect(&addr)); // Close }); let mut stream = t!(acceptor.accept()).0; let mut buf = [0]; let nread = t!(stream.read(&mut buf)); assert_eq!(nread, 0); let nread = t!(stream.read(&mut buf)); assert_eq!(nread, 0); }) } #[test] fn write_close() { each_ip(&mut |addr| { let acceptor = t!(TcpListener::bind(&addr)); let (tx, rx) = channel(); let _t = Thread::scoped(move|| { drop(t!(TcpStream::connect(&addr))); tx.send(()).unwrap(); }); let mut stream = t!(acceptor.accept()).0; rx.recv().unwrap(); let buf = [0]; match stream.write(&buf) { Ok(..) => {} Err(e) => { assert!(e.kind() == ErrorKind::ConnectionReset || e.kind() == ErrorKind::BrokenPipe || e.kind() == ErrorKind::ConnectionAborted, "unknown error: {}", e); } } }) } #[test] fn multiple_connect_serial_ip4() { each_ip(&mut |addr| { let max = 10; let acceptor = t!(TcpListener::bind(&addr)); let _t = Thread::scoped(move|| { for _ in 0..max { let mut stream = t!(TcpStream::connect(&addr)); t!(stream.write(&[99])); } }); for stream in acceptor.incoming().take(max) { let mut stream = t!(stream); let mut buf = [0]; t!(stream.read(&mut buf)); assert_eq!(buf[0], 99); } }) } #[test] fn multiple_connect_interleaved_greedy_schedule() { static MAX: usize = 10; each_ip(&mut |addr| { let acceptor = t!(TcpListener::bind(&addr)); let _t = Thread::scoped(move|| { let acceptor = acceptor; for (i, stream) in acceptor.incoming().enumerate().take(MAX) { // Start another task to handle the connection let _t = Thread::scoped(move|| { let mut stream = t!(stream); let mut buf = [0]; t!(stream.read(&mut buf)); assert!(buf[0] == i as u8); }); } }); connect(0, addr); }); fn connect(i: usize, addr: SocketAddr) { if i == MAX { return } let t = Thread::scoped(move|| { let mut stream = t!(TcpStream::connect(&addr)); // Connect again before writing connect(i + 1, addr); t!(stream.write(&[i as u8])); }); t.join().ok().unwrap(); } } #[test] fn multiple_connect_interleaved_lazy_schedule_ip4() { static MAX: usize = 10; each_ip(&mut |addr| { let acceptor = t!(TcpListener::bind(&addr)); let _t = Thread::scoped(move|| { for stream in acceptor.incoming().take(MAX) { // Start another task to handle the connection let _t = Thread::scoped(move|| { let mut stream = t!(stream); let mut buf = [0]; t!(stream.read(&mut buf)); assert!(buf[0] == 99); }); } }); connect(0, addr); }); fn connect(i: usize, addr: SocketAddr) { if i == MAX { return } let t = Thread::scoped(move|| { let mut stream = t!(TcpStream::connect(&addr)); connect(i + 1, addr); t!(stream.write(&[99])); }); t.join().ok().unwrap(); } } pub fn socket_name(addr: SocketAddr) { } pub fn peer_name(addr: SocketAddr) { } #[test] fn socket_and_peer_name_ip4() { each_ip(&mut |addr| { let listener = t!(TcpListener::bind(&addr)); let so_name = t!(listener.socket_addr()); assert_eq!(addr, so_name); let _t = Thread::scoped(move|| { t!(listener.accept()); }); let stream = t!(TcpStream::connect(&addr)); assert_eq!(addr, t!(stream.peer_addr())); }) } #[test] fn partial_read() { each_ip(&mut |addr| { let (tx, rx) = channel(); let srv = t!(TcpListener::bind(&addr)); let _t = Thread::scoped(move|| { let mut cl = t!(srv.accept()).0; cl.write(&[10]).unwrap(); let mut b = [0]; t!(cl.read(&mut b)); tx.send(()).unwrap(); }); let mut c = t!(TcpStream::connect(&addr)); let mut b = [0; 10]; assert_eq!(c.read(&mut b), Ok(1)); t!(c.write(&[1])); rx.recv().unwrap(); }) } #[test] fn double_bind() { each_ip(&mut |addr| { let _listener = t!(TcpListener::bind(&addr)); match TcpListener::bind(&addr) { Ok(..) => panic!(), Err(e) => { assert!(e.kind() == ErrorKind::ConnectionRefused || e.kind() == ErrorKind::Other, "unknown error: {} {:?}", e, e.kind()); } } }) } #[test] fn fast_rebind() { each_ip(&mut |addr| { let acceptor = t!(TcpListener::bind(&addr)); let _t = Thread::scoped(move|| { t!(TcpStream::connect(&addr)); }); t!(acceptor.accept()); drop(acceptor); t!(TcpListener::bind(&addr)); }); } #[test] fn tcp_clone_smoke() { each_ip(&mut |addr| { let acceptor = t!(TcpListener::bind(&addr)); let _t = Thread::scoped(move|| { let mut s = t!(TcpStream::connect(&addr)); let mut buf = [0, 0]; assert_eq!(s.read(&mut buf), Ok(1)); assert_eq!(buf[0], 1); t!(s.write(&[2])); }); let mut s1 = t!(acceptor.accept()).0; let s2 = t!(s1.try_clone()); let (tx1, rx1) = channel(); let (tx2, rx2) = channel(); let _t = Thread::scoped(move|| { let mut s2 = s2; rx1.recv().unwrap(); t!(s2.write(&[1])); tx2.send(()).unwrap(); }); tx1.send(()).unwrap(); let mut buf = [0, 0]; assert_eq!(s1.read(&mut buf), Ok(1)); rx2.recv().unwrap(); }) } #[test] fn tcp_clone_two_read() { each_ip(&mut |addr| { let acceptor = t!(TcpListener::bind(&addr)); let (tx1, rx) = channel(); let tx2 = tx1.clone(); let _t = Thread::scoped(move|| { let mut s = t!(TcpStream::connect(&addr)); t!(s.write(&[1])); rx.recv().unwrap(); t!(s.write(&[2])); rx.recv().unwrap(); }); let mut s1 = t!(acceptor.accept()).0; let s2 = t!(s1.try_clone()); let (done, rx) = channel(); let _t = Thread::scoped(move|| { let mut s2 = s2; let mut buf = [0, 0]; t!(s2.read(&mut buf)); tx2.send(()).unwrap(); done.send(()).unwrap(); }); let mut buf = [0, 0]; t!(s1.read(&mut buf)); tx1.send(()).unwrap(); rx.recv().unwrap(); }) } #[test] fn tcp_clone_two_write() { each_ip(&mut |addr| { let acceptor = t!(TcpListener::bind(&addr)); let _t = Thread::scoped(move|| { let mut s = t!(TcpStream::connect(&addr)); let mut buf = [0, 1]; t!(s.read(&mut buf)); t!(s.read(&mut buf)); }); let mut s1 = t!(acceptor.accept()).0; let s2 = t!(s1.try_clone()); let (done, rx) = channel(); let _t = Thread::scoped(move|| { let mut s2 = s2; t!(s2.write(&[1])); done.send(()).unwrap(); }); t!(s1.write(&[2])); rx.recv().unwrap(); }) } #[test] fn shutdown_smoke() { each_ip(&mut |addr| { let a = t!(TcpListener::bind(&addr)); let _t = Thread::scoped(move|| { let mut c = t!(a.accept()).0; let mut b = [0]; assert_eq!(c.read(&mut b), Ok(0)); t!(c.write(&[1])); }); let mut s = t!(TcpStream::connect(&addr)); t!(s.shutdown(Shutdown::Write)); assert!(s.write(&[1]).is_err()); let mut b = [0, 0]; assert_eq!(t!(s.read(&mut b)), 1); assert_eq!(b[0], 1); }) } #[test] fn close_readwrite_smoke() { each_ip(&mut |addr| { let a = t!(TcpListener::bind(&addr)); let (tx, rx) = channel::<()>(); let _t = Thread::scoped(move|| { let _s = t!(a.accept()); let _ = rx.recv(); }); let mut b = [0]; let mut s = t!(TcpStream::connect(&addr)); let mut s2 = t!(s.try_clone()); // closing should prevent reads/writes t!(s.shutdown(Shutdown::Write)); assert!(s.write(&[0]).is_err()); t!(s.shutdown(Shutdown::Read)); assert_eq!(s.read(&mut b), Ok(0)); // closing should affect previous handles assert!(s2.write(&[0]).is_err()); assert_eq!(s2.read(&mut b), Ok(0)); // closing should affect new handles let mut s3 = t!(s.try_clone()); assert!(s3.write(&[0]).is_err()); assert_eq!(s3.read(&mut b), Ok(0)); // make sure these don't die let _ = s2.shutdown(Shutdown::Read); let _ = s2.shutdown(Shutdown::Write); let _ = s3.shutdown(Shutdown::Read); let _ = s3.shutdown(Shutdown::Write); drop(tx); }) } #[test] fn close_read_wakes_up() { each_ip(&mut |addr| { let a = t!(TcpListener::bind(&addr)); let (tx1, rx) = channel::<()>(); let _t = Thread::scoped(move|| { let _s = t!(a.accept()); let _ = rx.recv(); }); let s = t!(TcpStream::connect(&addr)); let s2 = t!(s.try_clone()); let (tx, rx) = channel(); let _t = Thread::scoped(move|| { let mut s2 = s2; assert_eq!(t!(s2.read(&mut [0])), 0); tx.send(()).unwrap(); }); // this should wake up the child task t!(s.shutdown(Shutdown::Read)); // this test will never finish if the child doesn't wake up rx.recv().unwrap(); drop(tx1); }) } #[test] fn clone_while_reading() { each_ip(&mut |addr| { let accept = t!(TcpListener::bind(&addr)); // Enqueue a task to write to a socket let (tx, rx) = channel(); let (txdone, rxdone) = channel(); let txdone2 = txdone.clone(); let _t = Thread::scoped(move|| { let mut tcp = t!(TcpStream::connect(&addr)); rx.recv().unwrap(); t!(tcp.write(&[0])); txdone2.send(()).unwrap(); }); // Spawn off a reading clone let tcp = t!(accept.accept()).0; let tcp2 = t!(tcp.try_clone()); let txdone3 = txdone.clone(); let _t = Thread::scoped(move|| { let mut tcp2 = tcp2; t!(tcp2.read(&mut [0])); txdone3.send(()).unwrap(); }); // Try to ensure that the reading clone is indeed reading for _ in 0..50 { Thread::yield_now(); } // clone the handle again while it's reading, then let it finish the // read. let _ = t!(tcp.try_clone()); tx.send(()).unwrap(); rxdone.recv().unwrap(); rxdone.recv().unwrap(); }) } #[test] fn clone_accept_smoke() { each_ip(&mut |addr| { let a = t!(TcpListener::bind(&addr)); let a2 = t!(a.try_clone()); let _t = Thread::scoped(move|| { let _ = TcpStream::connect(&addr); }); let _t = Thread::scoped(move|| { let _ = TcpStream::connect(&addr); }); t!(a.accept()); t!(a2.accept()); }) } #[test] fn clone_accept_concurrent() { each_ip(&mut |addr| { let a = t!(TcpListener::bind(&addr)); let a2 = t!(a.try_clone()); let (tx, rx) = channel(); let tx2 = tx.clone(); let _t = Thread::scoped(move|| { tx.send(t!(a.accept())).unwrap(); }); let _t = Thread::scoped(move|| { tx2.send(t!(a2.accept())).unwrap(); }); let _t = Thread::scoped(move|| { let _ = TcpStream::connect(&addr); }); let _t = Thread::scoped(move|| { let _ = TcpStream::connect(&addr); }); rx.recv().unwrap(); rx.recv().unwrap(); }) } }<|fim▁end|>
<|file_name|>test_import.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- #----------------------------------------------------------------------------- # Copyright (c) 2005-2016, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License with exception # for distributing bootloader. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- import os import pytest import glob import ctypes, ctypes.util from PyInstaller.compat import is_darwin from PyInstaller.utils.tests import skipif, importorskip, \ skipif_notwin, xfail, is_py2 # :todo: find a way to get this from `conftest` or such # Directory with testing modules used in some tests. _MODULES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'modules') def test_nameclash(pyi_builder): # test-case for issue #964: Nameclashes in module information gathering # All pyinstaller specific module attributes should be prefixed, # to avoid nameclashes. pyi_builder.test_source( """ import pyi_testmod_nameclash.nameclash """) def test_relative_import(pyi_builder): pyi_builder.test_source( """ import pyi_testmod_relimp.B.C from pyi_testmod_relimp.F import H import pyi_testmod_relimp.relimp1 assert pyi_testmod_relimp.relimp1.name == 'pyi_testmod_relimp.relimp1' assert pyi_testmod_relimp.B.C.name == 'pyi_testmod_relimp.B.C' assert pyi_testmod_relimp.F.H.name == 'pyi_testmod_relimp.F.H' """ ) def test_relative_import2(pyi_builder): pyi_builder.test_source( """ import pyi_testmod_relimp2.bar import pyi_testmod_relimp2.bar.bar2 pyi_testmod_relimp2.bar.say_hello_please() pyi_testmod_relimp2.bar.bar2.say_hello_please() """ ) def test_relative_import3(pyi_builder): pyi_builder.test_source( """ from pyi_testmod_relimp3a.aa import a1 print(a1.getString()) """ ) def test_module_with_coding_utf8(pyi_builder): # Module ``utf8_encoded_module`` simply has an ``coding`` header # and uses same German umlauts. pyi_builder.test_source("import module_with_coding_utf8") def test_hiddenimport(pyi_builder): # The script simply does nothing, not even print out a line. pyi_builder.test_source('pass', ['--hidden-import=a_hidden_import']) def test_error_during_import(pyi_builder): # See ticket #27: historically, PyInstaller was catching all # errors during imports... pyi_builder.test_source( """ try: import error_during_import2 except KeyError: print("OK") else: raise RuntimeError("failure!") """) # :todo: Use some package which is already installed for some other # reason instead of `simplejson` which is only used here. @importorskip('simplejson') def test_c_extension(pyi_builder): pyi_builder.test_script('pyi_c_extension.py') # Verify that __path__ is respected for imports from the filesystem: # # * pyi_testmod_path/ # # * __init__.py -- inserts a/ into __path__, then imports b, which now refers # to a/b.py, not ./b.py. # * b.py - raises an exception. **Should not be imported.** # * a/ -- contains no __init__.py. # # * b.py - Empty. Should be imported. @xfail(reason='__path__ not respected for filesystem modules.') def test_import_respects_path(pyi_builder, script_dir): pyi_builder.test_source('import pyi_testmod_path', ['--additional-hooks-dir='+script_dir.join('pyi_hooks').strpath]) def test_import_pyqt5_uic_port(monkeypatch, pyi_builder): extra_path = os.path.join(_MODULES_DIR, 'pyi_import_pyqt_uic_port') pyi_builder.test_script('pyi_import_pyqt5_uic_port.py', pyi_args=['--path', extra_path]) #--- ctypes ---- def test_ctypes_CDLL_c(pyi_builder): # Make sure we are able to load the MSVCRXX.DLL resp. libc.so we are # currently bound. This is some of a no-brainer since the resp. dll/so # is collected anyway. pyi_builder.test_source( """ import ctypes, ctypes.util lib = ctypes.CDLL(ctypes.util.find_library('c')) assert lib is not None """) import PyInstaller.depend.utils __orig_resolveCtypesImports = PyInstaller.depend.utils._resolveCtypesImports def __monkeypatch_resolveCtypesImports(monkeypatch, compiled_dylib): def mocked_resolveCtypesImports(*args, **kwargs): from PyInstaller.config import CONF old_pathex = CONF['pathex'] CONF['pathex'].append(str(compiled_dylib)) res = __orig_resolveCtypesImports(*args, **kwargs) CONF['pathex'] = old_pathex return res # Add the path to ctypes_dylib to pathex, only for # _resolveCtypesImports. We can not monkeypath CONF['pathex'] # here, as it will be overwritten when pyi_builder is starting up. # So be monkeypatch _resolveCtypesImports by a wrapper. monkeypatch.setattr(PyInstaller.depend.utils, "_resolveCtypesImports", mocked_resolveCtypesImports) def skip_if_lib_missing(libname, text=None): """ pytest decorator to evaluate the required shared lib. :param libname: Name of the required library. :param text: Text to put into the reason message (defaults to 'lib%s.so' % libname) :return: pytest decorator with a reason. """ soname = ctypes.util.find_library(libname) if not text: text = "lib%s.so" % libname # Return pytest decorator. return skipif(not (soname and ctypes.CDLL(soname)), reason="required %s missing" % text) _template_ctypes_CDLL_find_library = """ import ctypes, ctypes.util, sys, os lib = ctypes.CDLL(ctypes.util.find_library(%(libname)r)) print(lib) assert lib is not None and lib._name is not None if getattr(sys, 'frozen', False): soname = ctypes.util.find_library(%(libname)r) print(soname) libfile = os.path.join(sys._MEIPASS, soname) print(libfile) assert os.path.isfile(libfile), '%%s is missing' %% soname print('>>> file found') """ # Ghostscript's libgs.so should be available in may Unix/Linux systems # # At least on Linux, we can not use our own `ctypes_dylib` because # `find_library` does not consult LD_LIBRARY_PATH and hence does not # find our lib. Anyway, this test tests the path of the loaded lib and # thus checks if libgs.so is included into the frozen exe. # TODO: Check how this behaves on other platforms. @skip_if_lib_missing('gs', 'libgs.so (Ghostscript)') def test_ctypes_CDLL_find_library__gs(pyi_builder): libname = 'gs' pyi_builder.test_source(_template_ctypes_CDLL_find_library % locals()) #-- Generate test-cases for the different types of ctypes objects. _template_ctypes_test = """ print(lib) assert lib is not None and lib._name is not None import sys, os if getattr(sys, 'frozen', False): libfile = os.path.join(sys._MEIPASS, %(soname)r) print(libfile) assert os.path.isfile(libfile), '%(soname)s is missing' print('>>> file found') """ parameters = [] ids = [] for prefix in ('', 'ctypes.'): for funcname in ('CDLL', 'PyDLL', 'WinDLL', 'OleDLL', 'cdll.LoadLibrary'): ids.append(prefix+funcname) params = (prefix+funcname, ids[-1]) if funcname in ("WinDLL", "OleDLL"): # WinDLL, OleDLL only work on windows. params = skipif_notwin(params) parameters.append(params) @pytest.mark.parametrize("funcname,test_id", parameters, ids=ids) def test_ctypes_gen(pyi_builder, monkeypatch, funcname, compiled_dylib, test_id): # evaluate the soname here, so the test-code contains a constant. # We want the name of the dynamically-loaded library only, not its path. # See discussion in https://github.com/pyinstaller/pyinstaller/pull/1478#issuecomment-139622994. soname = compiled_dylib.basename source = """ import ctypes ; from ctypes import * lib = %s(%%(soname)r)<|fim▁hole|> __monkeypatch_resolveCtypesImports(monkeypatch, compiled_dylib.dirname) pyi_builder.test_source(source % locals(), test_id=test_id) @pytest.mark.parametrize("funcname,test_id", parameters, ids=ids) def test_ctypes_in_func_gen(pyi_builder, monkeypatch, funcname, compiled_dylib, test_id): """ This is much like test_ctypes_gen except that the ctypes calls are in a function. See issue #1620. """ soname = compiled_dylib.basename source = (""" import ctypes ; from ctypes import * def f(): def g(): lib = %s(%%(soname)r) """ % funcname + _template_ctypes_test + """ g() f() """) __monkeypatch_resolveCtypesImports(monkeypatch, compiled_dylib.dirname) pyi_builder.test_source(source % locals(), test_id=test_id) # TODO: Add test-cases for the prefabricated library loaders supporting # attribute accesses on windows. Example:: # # cdll.kernel32.GetModuleHandleA(None) # # Of course we need to use dlls which is not are commony available on # windows but mot excluded in PyInstaller.depend.dylib def test_egg_unzipped(pyi_builder): pathex = os.path.join(_MODULES_DIR, 'pyi_egg_unzipped.egg') pyi_builder.test_source( """ # This code is part of the package for testing eggs in `PyInstaller`. import os import pkg_resources # Test ability to load resource. expected_data = 'This is data file for `unzipped`.'.encode('ascii') t = pkg_resources.resource_string('unzipped_egg', 'data/datafile.txt') print('Resource: %s' % t) t_filename = pkg_resources.resource_filename('unzipped_egg', 'data/datafile.txt') print('Resource filename: %s' % t_filename) assert t.rstrip() == expected_data # Test ability that module from .egg is able to load resource. import unzipped_egg assert unzipped_egg.data == expected_data print('Okay.') """, pyi_args=['--paths', pathex], ) def test_egg_zipped(pyi_builder): pathex = os.path.join(_MODULES_DIR, 'pyi_egg_zipped.egg') pyi_builder.test_source( """ # This code is part of the package for testing eggs in `PyInstaller`. import os import pkg_resources # Test ability to load resource. expected_data = 'This is data file for `zipped`.'.encode('ascii') t = pkg_resources.resource_string('zipped_egg', 'data/datafile.txt') print('Resource: %s' % t) t_filename = pkg_resources.resource_filename('zipped_egg', 'data/datafile.txt') print('Resource filename: %s' % t_filename) assert t.rstrip() == expected_data # Test ability that module from .egg is able to load resource. import zipped_egg assert zipped_egg.data == expected_data print('Okay.') """, pyi_args=['--paths', pathex], ) #--- namespaces --- def test_nspkg1(pyi_builder): # Test inclusion of namespace packages implemented using # pkg_resources.declare_namespace pathex = glob.glob(os.path.join(_MODULES_DIR, 'nspkg1-pkg', '*.egg')) pyi_builder.test_source( """ import nspkg1.aaa import nspkg1.bbb.zzz import nspkg1.ccc """, pyi_args=['--paths', os.pathsep.join(pathex)], ) def test_nspkg1_empty(pyi_builder): # Test inclusion of a namespace-only packages in an zipped egg. # This package only defines the namespace, nothing is contained there. pathex = glob.glob(os.path.join(_MODULES_DIR, 'nspkg1-pkg', '*.egg')) pyi_builder.test_source( """ import nspkg1 print (nspkg1) """, pyi_args=['--paths', os.pathsep.join(pathex)], ) def test_nspkg1_bbb_zzz(pyi_builder): # Test inclusion of a namespace packages in an zipped egg pathex = glob.glob(os.path.join(_MODULES_DIR, 'nspkg1-pkg', '*.egg')) pyi_builder.test_source( """ import nspkg1.bbb.zzz """, pyi_args=['--paths', os.pathsep.join(pathex)], ) def test_nspkg2(pyi_builder): # Test inclusion of namespace packages implemented as nspkg.pth-files pathex = glob.glob(os.path.join(_MODULES_DIR, 'nspkg2-pkg')) pyi_builder.test_source( """ import nspkg2.aaa import nspkg2.bbb.zzz import nspkg2.ccc """, pyi_args=['--paths', os.pathsep.join(pathex)], ) @xfail(reason="modulegraph implements `pkgutil.extend_path` wrong") def test_nspkg3(pyi_builder): pathex = glob.glob(os.path.join(_MODULES_DIR, 'nspkg3-pkg', '*.egg')) pyi_builder.test_source( """ import nspkg3.aaa try: # pkgutil ignores items of sys.path that are not strings # referring to existing directories. So this zipped egg # *must* be ignored. import nspkg3.bbb.zzz except ImportError: pass else: raise SystemExit('nspkg3.bbb.zzz found but should not') try: import nspkg3.a except ImportError: pass else: raise SystemExit('nspkg3.a found but should not') import nspkg3.ccc """, pyi_args=['--paths', os.pathsep.join(pathex)], ) def test_nspkg3_empty(pyi_builder): # Test inclusion of a namespace-only package in a zipped egg # using pkgutil.extend_path. # This package only defines namespace, nothing is contained there. pathex = glob.glob(os.path.join(_MODULES_DIR, 'nspkg3-pkg', '*_empty.egg')) pyi_builder.test_source( """ import nspkg3 print (nspkg3) """, pyi_args=['--paths', os.pathsep.join(pathex)], ) def test_nspkg3_aaa(pyi_builder): # Test inclusion of a namespace package in an directory using # pkgutil.extend_path pathex = glob.glob(os.path.join(_MODULES_DIR, 'nspkg3-pkg', '*.egg')) pyi_builder.test_source( """ import nspkg3.aaa """, pyi_args=['--paths', os.pathsep.join(pathex)], ) def test_nspkg3_bbb_zzz(pyi_builder): # Test inclusion of a namespace package in an zipped egg using # pkgutil.extend_path pathex = glob.glob(os.path.join(_MODULES_DIR, 'nspkg3-pkg', '*.egg')) pyi_builder.test_source( """ import nspkg3.bbb.zzz """, pyi_args=['--paths', os.pathsep.join(pathex)], ) @skipif(is_py2, reason="requires Python 3.3") def test_nspkg_pep420(pyi_builder): # Test inclusion of PEP 420 namespace packages. pathex = glob.glob(os.path.join(_MODULES_DIR, 'nspkg-pep420', 'path*')) pyi_builder.test_source( """ import package.sub1 import package.sub2 import package.subpackage.sub import package.nspkg.mod """, pyi_args=['--paths', os.pathsep.join(pathex)], ) #--- hooks related stuff --- def test_pkg_without_hook_for_pkg(pyi_builder, script_dir): # The package `pkg_without_hook_for_pkg` does not have a hook, but # `pkg_without_hook_for_pkg.sub1` has one. And this hook includes # the "hidden" import `pkg_without_hook_for_pkg.sub1.sub11` pyi_builder.test_source( 'import pkg_without_hook_for_pkg.sub1', ['--additional-hooks-dir=%s' % script_dir.join('pyi_hooks')]) @xfail(is_darwin, reason='Issue #1895.') def test_app_with_plugin(pyi_builder, data_dir, monkeypatch): from PyInstaller.building.build_main import Analysis class MyAnalysis(Analysis): def __init__(self, *args, **kwargs): kwargs['datas'] = datas # Setting back is required to make `super()` within # Analysis access the correct class. Do not use # `monkeypatch.undo()` as this will undo *all* # monkeypathes. monkeypatch.setattr('PyInstaller.building.build_main.Analysis', Analysis) super(MyAnalysis, self).__init__(*args, **kwargs) monkeypatch.setattr('PyInstaller.building.build_main.Analysis', MyAnalysis) # :fixme: When PyInstaller supports setting datas via the # command-line, us this here instead of monkeypatching Analysis. datas = [('data/*/static_plugin.py', '.')] pyi_builder.test_script('pyi_app_with_plugin.py')<|fim▁end|>
""" % funcname + _template_ctypes_test
<|file_name|>text_buffer.rs<|end_file_name|><|fim▁begin|>// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::c_char; use ffi; use cast::GTK_TEXT_BUFFER; pub trait TextBufferTrait: ::WidgetTrait { fn set_text(&self, text: &str) { unsafe { // Don't need a null-terminated string here ffi::gtk_text_buffer_set_text( GTK_TEXT_BUFFER(self.unwrap_widget()), text.as_ptr() as *const c_char, text.len() as i32) } } <|fim▁hole|><|fim▁end|>
}
<|file_name|>handlebars-require-express.js<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
var exphbs = require('express-handlebars');
<|file_name|>host_content_settings_map_unittest.cc<|end_file_name|><|fim▁begin|>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/auto_reset.h" #include "base/command_line.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/message_loop/message_loop.h" #include "chrome/browser/content_settings/content_settings_mock_observer.h" #include "chrome/browser/content_settings/cookie_settings_factory.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/content_settings/mock_settings_observer.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/testing_profile.h" #include "components/content_settings/core/browser/content_settings_details.h" #include "components/content_settings/core/browser/cookie_settings.h" #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/content_settings/core/browser/website_settings_info.h" #include "components/content_settings/core/browser/website_settings_registry.h" #include "components/content_settings/core/common/pref_names.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/syncable_prefs/testing_pref_service_syncable.h" #include "content/public/test/test_browser_thread.h" #include "net/base/static_cookie_policy.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" using content::BrowserThread; using ::testing::_; class HostContentSettingsMapTest : public testing::Test { public: HostContentSettingsMapTest() : ui_thread_(BrowserThread::UI, &message_loop_) { } protected: const std::string& GetPrefName(ContentSettingsType type) { return content_settings::WebsiteSettingsRegistry::GetInstance() ->Get(type) ->pref_name(); } base::MessageLoop message_loop_; content::TestBrowserThread ui_thread_; }; TEST_F(HostContentSettingsMapTest, DefaultValues) { TestingProfile profile; HostContentSettingsMap* host_content_settings_map = HostContentSettingsMapFactory::GetForProfile(&profile); // Check setting defaults. EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_JAVASCRIPT, NULL)); host_content_settings_map->SetDefaultContentSetting( CONTENT_SETTINGS_TYPE_IMAGES, CONTENT_SETTING_BLOCK); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_IMAGES, NULL)); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetContentSetting( GURL(chrome::kChromeUINewTabURL), GURL(chrome::kChromeUINewTabURL), CONTENT_SETTINGS_TYPE_IMAGES, std::string())); #if defined(ENABLE_PLUGINS) host_content_settings_map->SetDefaultContentSetting( CONTENT_SETTINGS_TYPE_PLUGINS, CONTENT_SETTING_ALLOW); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_PLUGINS, NULL)); host_content_settings_map->SetDefaultContentSetting( CONTENT_SETTINGS_TYPE_PLUGINS, CONTENT_SETTING_BLOCK); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_PLUGINS, NULL)); host_content_settings_map->SetDefaultContentSetting( CONTENT_SETTINGS_TYPE_PLUGINS, CONTENT_SETTING_DETECT_IMPORTANT_CONTENT); EXPECT_EQ(CONTENT_SETTING_DETECT_IMPORTANT_CONTENT, host_content_settings_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_PLUGINS, NULL)); #endif host_content_settings_map->SetDefaultContentSetting( CONTENT_SETTINGS_TYPE_POPUPS, CONTENT_SETTING_ALLOW); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_POPUPS, NULL)); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_KEYGEN, NULL)); } TEST_F(HostContentSettingsMapTest, IndividualSettings) { TestingProfile profile; HostContentSettingsMap* host_content_settings_map = HostContentSettingsMapFactory::GetForProfile(&profile); // Check returning individual settings. GURL host("http://example.com/"); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); host_content_settings_map->SetContentSettingDefaultScope( host, GURL(), CONTENT_SETTINGS_TYPE_IMAGES, std::string(), CONTENT_SETTING_DEFAULT); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); host_content_settings_map->SetContentSettingDefaultScope( host, GURL(), CONTENT_SETTINGS_TYPE_IMAGES, std::string(), CONTENT_SETTING_BLOCK); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); #if defined(ENABLE_PLUGINS) EXPECT_EQ(CONTENT_SETTING_DETECT_IMPORTANT_CONTENT, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_PLUGINS, std::string())); #endif // Check returning all settings for a host. host_content_settings_map->SetContentSettingDefaultScope( host, GURL(), CONTENT_SETTINGS_TYPE_IMAGES, std::string(), CONTENT_SETTING_DEFAULT); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); host_content_settings_map->SetContentSettingDefaultScope( host, GURL(), CONTENT_SETTINGS_TYPE_JAVASCRIPT, std::string(), CONTENT_SETTING_BLOCK); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_JAVASCRIPT, std::string())); #if defined(ENABLE_PLUGINS) host_content_settings_map->SetContentSettingDefaultScope( host, GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, std::string(), CONTENT_SETTING_ALLOW); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_PLUGINS, std::string())); #endif EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_POPUPS, std::string())); EXPECT_EQ(CONTENT_SETTING_ASK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_GEOLOCATION, std::string())); EXPECT_EQ( CONTENT_SETTING_ASK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string())); EXPECT_EQ(CONTENT_SETTING_ASK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_FULLSCREEN, std::string())); EXPECT_EQ(CONTENT_SETTING_ASK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_MOUSELOCK, std::string())); host_content_settings_map->SetContentSettingDefaultScope( host, GURL(), CONTENT_SETTINGS_TYPE_KEYGEN, std::string(), CONTENT_SETTING_ALLOW); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_KEYGEN, std::string())); // Check returning all hosts for a setting. GURL host2("http://example.org/"); host_content_settings_map->SetContentSettingDefaultScope( host2, GURL(), CONTENT_SETTINGS_TYPE_IMAGES, std::string(), CONTENT_SETTING_BLOCK); #if defined(ENABLE_PLUGINS) host_content_settings_map->SetContentSettingDefaultScope( host2, GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, std::string(), CONTENT_SETTING_BLOCK); #endif ContentSettingsForOneType host_settings; host_content_settings_map->GetSettingsForOneType( CONTENT_SETTINGS_TYPE_IMAGES, std::string(), &host_settings); // |host_settings| contains the default setting and an exception. EXPECT_EQ(2U, host_settings.size()); #if defined(ENABLE_PLUGINS) host_content_settings_map->GetSettingsForOneType( CONTENT_SETTINGS_TYPE_PLUGINS, std::string(), &host_settings); // |host_settings| contains the default setting and 2 exceptions. EXPECT_EQ(3U, host_settings.size()); #endif host_content_settings_map->GetSettingsForOneType( CONTENT_SETTINGS_TYPE_POPUPS, std::string(), &host_settings); // |host_settings| contains only the default setting. EXPECT_EQ(1U, host_settings.size()); } TEST_F(HostContentSettingsMapTest, Clear) { TestingProfile profile; HostContentSettingsMap* host_content_settings_map = HostContentSettingsMapFactory::GetForProfile(&profile); // Check clearing one type. GURL host("http://example.org/"); GURL host2("http://example.net/"); host_content_settings_map->SetContentSettingDefaultScope( host2, GURL(), CONTENT_SETTINGS_TYPE_IMAGES, std::string(), CONTENT_SETTING_BLOCK); host_content_settings_map->SetContentSettingDefaultScope( host, GURL(), CONTENT_SETTINGS_TYPE_IMAGES, std::string(), CONTENT_SETTING_BLOCK); #if defined(ENABLE_PLUGINS) host_content_settings_map->SetContentSettingDefaultScope( host, GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, std::string(), CONTENT_SETTING_BLOCK); #endif host_content_settings_map->SetContentSettingDefaultScope( host2, GURL(), CONTENT_SETTINGS_TYPE_IMAGES, std::string(), CONTENT_SETTING_BLOCK); host_content_settings_map->ClearSettingsForOneType( CONTENT_SETTINGS_TYPE_IMAGES); ContentSettingsForOneType host_settings; host_content_settings_map->GetSettingsForOneType( CONTENT_SETTINGS_TYPE_IMAGES, std::string(), &host_settings); // |host_settings| contains only the default setting. EXPECT_EQ(1U, host_settings.size()); #if defined(ENABLE_PLUGINS) host_content_settings_map->GetSettingsForOneType( CONTENT_SETTINGS_TYPE_PLUGINS, std::string(), &host_settings); // |host_settings| contains the default setting and an exception. EXPECT_EQ(2U, host_settings.size()); #endif } TEST_F(HostContentSettingsMapTest, Patterns) { TestingProfile profile; HostContentSettingsMap* host_content_settings_map = HostContentSettingsMapFactory::GetForProfile(&profile); GURL host1("http://example.com/"); GURL host2("http://www.example.com/"); GURL host3("http://example.org/"); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetContentSetting( host1, host1, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); host_content_settings_map->SetContentSettingDefaultScope( host1, GURL(), CONTENT_SETTINGS_TYPE_IMAGES, std::string(), CONTENT_SETTING_BLOCK); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting( host1, host1, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting( host2, host2, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetContentSetting( host3, host3, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); host_content_settings_map->SetContentSettingDefaultScope( host3, GURL(), CONTENT_SETTINGS_TYPE_IMAGES, std::string(), CONTENT_SETTING_BLOCK); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting( host3, host3, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); } TEST_F(HostContentSettingsMapTest, Observer) { TestingProfile profile; HostContentSettingsMap* host_content_settings_map = HostContentSettingsMapFactory::GetForProfile(&profile); MockSettingsObserver observer(host_content_settings_map); GURL host("http://example.com/"); ContentSettingsPattern primary_pattern = ContentSettingsPattern::FromString("[*.]example.com"); ContentSettingsPattern secondary_pattern = ContentSettingsPattern::Wildcard(); EXPECT_CALL(observer, OnContentSettingsChanged(host_content_settings_map, CONTENT_SETTINGS_TYPE_IMAGES, false, primary_pattern, secondary_pattern, false)); host_content_settings_map->SetContentSettingDefaultScope( host, GURL(), CONTENT_SETTINGS_TYPE_IMAGES, std::string(), CONTENT_SETTING_ALLOW); ::testing::Mock::VerifyAndClearExpectations(&observer); EXPECT_CALL(observer, OnContentSettingsChanged(host_content_settings_map, CONTENT_SETTINGS_TYPE_IMAGES, false, _, _, true)); host_content_settings_map->ClearSettingsForOneType( CONTENT_SETTINGS_TYPE_IMAGES); ::testing::Mock::VerifyAndClearExpectations(&observer); EXPECT_CALL(observer, OnContentSettingsChanged(host_content_settings_map, CONTENT_SETTINGS_TYPE_IMAGES, false, _, _, true)); host_content_settings_map->SetDefaultContentSetting( CONTENT_SETTINGS_TYPE_IMAGES, CONTENT_SETTING_BLOCK); } TEST_F(HostContentSettingsMapTest, ObserveDefaultPref) { TestingProfile profile; HostContentSettingsMap* host_content_settings_map = HostContentSettingsMapFactory::GetForProfile(&profile); PrefService* prefs = profile.GetPrefs(); GURL host("http://example.com"); host_content_settings_map->SetDefaultContentSetting( CONTENT_SETTINGS_TYPE_IMAGES, CONTENT_SETTING_BLOCK); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); const content_settings::WebsiteSettingsInfo* info = content_settings::WebsiteSettingsRegistry::GetInstance()->Get( CONTENT_SETTINGS_TYPE_IMAGES); // Clearing the backing pref should also clear the internal cache. prefs->ClearPref(info->default_value_pref_name()); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); // Reseting the pref to its previous value should update the cache. prefs->SetInteger(info->default_value_pref_name(), CONTENT_SETTING_BLOCK); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); } TEST_F(HostContentSettingsMapTest, ObserveExceptionPref) { TestingProfile profile; HostContentSettingsMap* host_content_settings_map = HostContentSettingsMapFactory::GetForProfile(&profile); PrefService* prefs = profile.GetPrefs(); // Make a copy of the default pref value so we can reset it later. scoped_ptr<base::Value> default_value( prefs->FindPreference(GetPrefName(CONTENT_SETTINGS_TYPE_IMAGES)) ->GetValue() ->DeepCopy()); GURL host("http://example.com"); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); host_content_settings_map->SetContentSettingDefaultScope( host, GURL(), CONTENT_SETTINGS_TYPE_IMAGES, std::string(), CONTENT_SETTING_BLOCK); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); // Make a copy of the pref's new value so we can reset it later. scoped_ptr<base::Value> new_value( prefs->FindPreference(GetPrefName(CONTENT_SETTINGS_TYPE_IMAGES)) ->GetValue() ->DeepCopy()); // Clearing the backing pref should also clear the internal cache. prefs->Set(GetPrefName(CONTENT_SETTINGS_TYPE_IMAGES), *default_value); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetContentSetting(<|fim▁hole|> EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); } TEST_F(HostContentSettingsMapTest, HostTrimEndingDotCheck) { TestingProfile profile; HostContentSettingsMap* host_content_settings_map = HostContentSettingsMapFactory::GetForProfile(&profile); content_settings::CookieSettings* cookie_settings = CookieSettingsFactory::GetForProfile(&profile).get(); GURL host_ending_with_dot("http://example.com./"); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetContentSetting( host_ending_with_dot, host_ending_with_dot, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); host_content_settings_map->SetContentSettingDefaultScope( host_ending_with_dot, GURL(), CONTENT_SETTINGS_TYPE_IMAGES, std::string(), CONTENT_SETTING_DEFAULT); EXPECT_EQ( CONTENT_SETTING_ALLOW, host_content_settings_map->GetContentSetting(host_ending_with_dot, host_ending_with_dot, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); host_content_settings_map->SetContentSettingDefaultScope( host_ending_with_dot, GURL(), CONTENT_SETTINGS_TYPE_IMAGES, std::string(), CONTENT_SETTING_BLOCK); EXPECT_EQ( CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting(host_ending_with_dot, host_ending_with_dot, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); EXPECT_TRUE(cookie_settings->IsSettingCookieAllowed( host_ending_with_dot, host_ending_with_dot)); host_content_settings_map->SetContentSettingDefaultScope( host_ending_with_dot, GURL(), CONTENT_SETTINGS_TYPE_COOKIES, std::string(), CONTENT_SETTING_DEFAULT); EXPECT_TRUE(cookie_settings->IsSettingCookieAllowed( host_ending_with_dot, host_ending_with_dot)); host_content_settings_map->SetContentSettingDefaultScope( host_ending_with_dot, GURL(), CONTENT_SETTINGS_TYPE_COOKIES, std::string(), CONTENT_SETTING_BLOCK); EXPECT_FALSE(cookie_settings->IsSettingCookieAllowed( host_ending_with_dot, host_ending_with_dot)); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetContentSetting( host_ending_with_dot, host_ending_with_dot, CONTENT_SETTINGS_TYPE_JAVASCRIPT, std::string())); host_content_settings_map->SetContentSettingDefaultScope( host_ending_with_dot, GURL(), CONTENT_SETTINGS_TYPE_JAVASCRIPT, std::string(), CONTENT_SETTING_DEFAULT); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetContentSetting( host_ending_with_dot, host_ending_with_dot, CONTENT_SETTINGS_TYPE_JAVASCRIPT, std::string())); host_content_settings_map->SetContentSettingDefaultScope( host_ending_with_dot, GURL(), CONTENT_SETTINGS_TYPE_JAVASCRIPT, std::string(), CONTENT_SETTING_BLOCK); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting( host_ending_with_dot, host_ending_with_dot, CONTENT_SETTINGS_TYPE_JAVASCRIPT, std::string())); #if defined(ENABLE_PLUGINS) EXPECT_EQ(CONTENT_SETTING_DETECT_IMPORTANT_CONTENT, host_content_settings_map->GetContentSetting( host_ending_with_dot, host_ending_with_dot, CONTENT_SETTINGS_TYPE_PLUGINS, std::string())); host_content_settings_map->SetContentSettingDefaultScope( host_ending_with_dot, GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, std::string(), CONTENT_SETTING_DEFAULT); EXPECT_EQ(CONTENT_SETTING_DETECT_IMPORTANT_CONTENT, host_content_settings_map->GetContentSetting( host_ending_with_dot, host_ending_with_dot, CONTENT_SETTINGS_TYPE_PLUGINS, std::string())); host_content_settings_map->SetContentSettingDefaultScope( host_ending_with_dot, GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, std::string(), CONTENT_SETTING_BLOCK); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting( host_ending_with_dot, host_ending_with_dot, CONTENT_SETTINGS_TYPE_PLUGINS, std::string())); #endif EXPECT_EQ( CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting(host_ending_with_dot, host_ending_with_dot, CONTENT_SETTINGS_TYPE_POPUPS, std::string())); host_content_settings_map->SetContentSettingDefaultScope( host_ending_with_dot, GURL(), CONTENT_SETTINGS_TYPE_POPUPS, std::string(), CONTENT_SETTING_DEFAULT); EXPECT_EQ( CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting(host_ending_with_dot, host_ending_with_dot, CONTENT_SETTINGS_TYPE_POPUPS, std::string())); host_content_settings_map->SetContentSettingDefaultScope( host_ending_with_dot, GURL(), CONTENT_SETTINGS_TYPE_POPUPS, std::string(), CONTENT_SETTING_ALLOW); EXPECT_EQ( CONTENT_SETTING_ALLOW, host_content_settings_map->GetContentSetting(host_ending_with_dot, host_ending_with_dot, CONTENT_SETTINGS_TYPE_POPUPS, std::string())); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting( host_ending_with_dot, host_ending_with_dot, CONTENT_SETTINGS_TYPE_KEYGEN, std::string())); host_content_settings_map->SetContentSettingDefaultScope( host_ending_with_dot, GURL(), CONTENT_SETTINGS_TYPE_KEYGEN, std::string(), CONTENT_SETTING_ALLOW); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetContentSetting( host_ending_with_dot, host_ending_with_dot, CONTENT_SETTINGS_TYPE_KEYGEN, std::string())); host_content_settings_map->SetContentSettingDefaultScope( host_ending_with_dot, GURL(), CONTENT_SETTINGS_TYPE_KEYGEN, std::string(), CONTENT_SETTING_DEFAULT); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting( host_ending_with_dot, host_ending_with_dot, CONTENT_SETTINGS_TYPE_KEYGEN, std::string())); } TEST_F(HostContentSettingsMapTest, NestedSettings) { TestingProfile profile; HostContentSettingsMap* host_content_settings_map = HostContentSettingsMapFactory::GetForProfile(&profile); GURL host("http://a.b.example.com/"); GURL host1("http://example.com/"); GURL host2("http://b.example.com/"); host_content_settings_map->SetContentSettingDefaultScope( host1, GURL(), CONTENT_SETTINGS_TYPE_IMAGES, std::string(), CONTENT_SETTING_BLOCK); host_content_settings_map->SetContentSettingDefaultScope( host2, GURL(), CONTENT_SETTINGS_TYPE_COOKIES, std::string(), CONTENT_SETTING_BLOCK); host_content_settings_map->SetContentSettingDefaultScope( host, GURL(), CONTENT_SETTINGS_TYPE_PLUGINS, std::string(), CONTENT_SETTING_BLOCK); host_content_settings_map->SetDefaultContentSetting( CONTENT_SETTINGS_TYPE_JAVASCRIPT, CONTENT_SETTING_BLOCK); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_COOKIES, std::string())); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_JAVASCRIPT, std::string())); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_PLUGINS, std::string())); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_POPUPS, std::string())); EXPECT_EQ(CONTENT_SETTING_ASK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_GEOLOCATION, std::string())); EXPECT_EQ( CONTENT_SETTING_ASK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string())); EXPECT_EQ(CONTENT_SETTING_ASK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_FULLSCREEN, std::string())); EXPECT_EQ(CONTENT_SETTING_ASK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_MOUSELOCK, std::string())); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_KEYGEN, std::string())); } TEST_F(HostContentSettingsMapTest, OffTheRecord) { TestingProfile profile; Profile* otr_profile = profile.GetOffTheRecordProfile(); HostContentSettingsMap* host_content_settings_map = HostContentSettingsMapFactory::GetForProfile(&profile); HostContentSettingsMap* otr_map = HostContentSettingsMapFactory::GetForProfile(otr_profile); GURL host("http://example.com/"); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); EXPECT_EQ(CONTENT_SETTING_ALLOW, otr_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); // Changing content settings on the main map should also affect the // incognito map. host_content_settings_map->SetContentSettingDefaultScope( host, GURL(), CONTENT_SETTINGS_TYPE_IMAGES, std::string(), CONTENT_SETTING_BLOCK); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); EXPECT_EQ(CONTENT_SETTING_BLOCK, otr_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); // Changing content settings on the incognito map should NOT affect the // main map. otr_map->SetContentSettingDefaultScope(host, GURL(), CONTENT_SETTINGS_TYPE_IMAGES, std::string(), CONTENT_SETTING_ALLOW); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); EXPECT_EQ(CONTENT_SETTING_ALLOW, otr_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); } TEST_F(HostContentSettingsMapTest, OffTheRecordPartialInheritPref) { // Permissions marked INHERIT_IN_INCOGNITO_EXCEPT_ALLOW in // ContentSettingsRegistry (e.g. push & notifications) only inherit BLOCK // settings from regular to incognito. TestingProfile profile; Profile* otr_profile = profile.GetOffTheRecordProfile(); HostContentSettingsMap* host_content_settings_map = HostContentSettingsMapFactory::GetForProfile(&profile); HostContentSettingsMap* otr_map = HostContentSettingsMapFactory::GetForProfile(otr_profile); GURL host("http://example.com/"); EXPECT_EQ( CONTENT_SETTING_ASK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string())); EXPECT_EQ( CONTENT_SETTING_ASK, otr_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string())); // BLOCK should be inherited from the main map to the incognito map. host_content_settings_map->SetContentSettingDefaultScope( host, GURL(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string(), CONTENT_SETTING_BLOCK); EXPECT_EQ( CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string())); EXPECT_EQ( CONTENT_SETTING_BLOCK, otr_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string())); // ALLOW should not be inherited from the main map to the incognito map (but // it still overwrites the BLOCK, hence incognito reverts to ASK). host_content_settings_map->SetContentSettingDefaultScope( host, GURL(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string(), CONTENT_SETTING_ALLOW); EXPECT_EQ( CONTENT_SETTING_ALLOW, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string())); EXPECT_EQ( CONTENT_SETTING_ASK, otr_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string())); } TEST_F(HostContentSettingsMapTest, OffTheRecordPartialInheritDefault) { // Permissions marked INHERIT_IN_INCOGNITO_EXCEPT_ALLOW in // ContentSettingsRegistry (e.g. push & notifications) only inherit BLOCK // default settings from regular to incognito. TestingProfile profile; Profile* otr_profile = profile.GetOffTheRecordProfile(); HostContentSettingsMap* host_content_settings_map = HostContentSettingsMapFactory::GetForProfile(&profile); HostContentSettingsMap* otr_map = HostContentSettingsMapFactory::GetForProfile(otr_profile); GURL host("http://example.com/"); EXPECT_EQ(CONTENT_SETTING_ASK, host_content_settings_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_NOTIFICATIONS, NULL)); EXPECT_EQ( CONTENT_SETTING_ASK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string())); EXPECT_EQ(CONTENT_SETTING_ASK, otr_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_NOTIFICATIONS, NULL)); EXPECT_EQ( CONTENT_SETTING_ASK, otr_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string())); // BLOCK should be inherited from the main map to the incognito map. host_content_settings_map->SetDefaultContentSetting( CONTENT_SETTINGS_TYPE_NOTIFICATIONS, CONTENT_SETTING_BLOCK); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_NOTIFICATIONS, NULL)); EXPECT_EQ( CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string())); EXPECT_EQ(CONTENT_SETTING_BLOCK, otr_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_NOTIFICATIONS, NULL)); EXPECT_EQ( CONTENT_SETTING_BLOCK, otr_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string())); // ALLOW should not be inherited from the main map to the incognito map (but // it still overwrites the BLOCK, hence incognito reverts to ASK). host_content_settings_map->SetDefaultContentSetting( CONTENT_SETTINGS_TYPE_NOTIFICATIONS, CONTENT_SETTING_ALLOW); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_NOTIFICATIONS, NULL)); EXPECT_EQ( CONTENT_SETTING_ALLOW, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string())); EXPECT_EQ(CONTENT_SETTING_ASK, otr_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_NOTIFICATIONS, NULL)); EXPECT_EQ( CONTENT_SETTING_ASK, otr_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string())); } TEST_F(HostContentSettingsMapTest, OffTheRecordDontInheritSetting) { // Website settings marked DONT_INHERIT_IN_INCOGNITO in // WebsiteSettingsRegistry (e.g. usb chooser data) don't inherit any values // from from regular to incognito. TestingProfile profile; Profile* otr_profile = profile.GetOffTheRecordProfile(); HostContentSettingsMap* host_content_settings_map = HostContentSettingsMapFactory::GetForProfile(&profile); HostContentSettingsMap* otr_map = HostContentSettingsMapFactory::GetForProfile(otr_profile); GURL host("http://example.com/"); // USB chooser data defaults to |nullptr|. EXPECT_EQ(nullptr, host_content_settings_map->GetWebsiteSetting( host, host, CONTENT_SETTINGS_TYPE_USB_CHOOSER_DATA, std::string(), nullptr)); EXPECT_EQ(nullptr, otr_map->GetWebsiteSetting( host, host, CONTENT_SETTINGS_TYPE_USB_CHOOSER_DATA, std::string(), nullptr)); base::DictionaryValue test_value; test_value.SetString("test", "value"); host_content_settings_map->SetWebsiteSettingDefaultScope( host, host, CONTENT_SETTINGS_TYPE_USB_CHOOSER_DATA, std::string(), test_value.DeepCopy()); // The setting is not inherted by |otr_map|. scoped_ptr<base::Value> stored_value = host_content_settings_map->GetWebsiteSetting( host, host, CONTENT_SETTINGS_TYPE_USB_CHOOSER_DATA, std::string(), nullptr); EXPECT_TRUE(stored_value && stored_value->Equals(&test_value)); EXPECT_EQ(nullptr, otr_map->GetWebsiteSetting( host, host, CONTENT_SETTINGS_TYPE_USB_CHOOSER_DATA, std::string(), nullptr)); } // For a single Unicode encoded pattern, check if it gets converted to punycode // and old pattern gets deleted. TEST_F(HostContentSettingsMapTest, CanonicalizeExceptionsUnicodeOnly) { TestingProfile profile; PrefService* prefs = profile.GetPrefs(); // Set utf-8 data. { DictionaryPrefUpdate update(prefs, GetPrefName(CONTENT_SETTINGS_TYPE_PLUGINS)); base::DictionaryValue* all_settings_dictionary = update.Get(); ASSERT_TRUE(NULL != all_settings_dictionary); base::DictionaryValue* dummy_payload = new base::DictionaryValue; dummy_payload->SetInteger("setting", CONTENT_SETTING_ALLOW); all_settings_dictionary->SetWithoutPathExpansion("[*.]\xC4\x87ira.com,*", dummy_payload); } HostContentSettingsMapFactory::GetForProfile(&profile); const base::DictionaryValue* all_settings_dictionary = prefs->GetDictionary(GetPrefName(CONTENT_SETTINGS_TYPE_PLUGINS)); const base::DictionaryValue* result = NULL; EXPECT_FALSE(all_settings_dictionary->GetDictionaryWithoutPathExpansion( "[*.]\xC4\x87ira.com,*", &result)); EXPECT_TRUE(all_settings_dictionary->GetDictionaryWithoutPathExpansion( "[*.]xn--ira-ppa.com,*", &result)); } // If both Unicode and its punycode pattern exist, make sure we don't touch the // settings for the punycode, and that Unicode pattern gets deleted. TEST_F(HostContentSettingsMapTest, CanonicalizeExceptionsUnicodeAndPunycode) { TestingProfile profile; scoped_ptr<base::Value> value = base::JSONReader::Read("{\"[*.]\\xC4\\x87ira.com,*\":{\"setting\":1}}"); profile.GetPrefs()->Set(GetPrefName(CONTENT_SETTINGS_TYPE_COOKIES), *value); // Set punycode equivalent, with different setting. scoped_ptr<base::Value> puny_value = base::JSONReader::Read("{\"[*.]xn--ira-ppa.com,*\":{\"setting\":2}}"); profile.GetPrefs()->Set(GetPrefName(CONTENT_SETTINGS_TYPE_COOKIES), *puny_value); // Initialize the content map. HostContentSettingsMapFactory::GetForProfile(&profile); const base::DictionaryValue& content_setting_prefs = *profile.GetPrefs()->GetDictionary( GetPrefName(CONTENT_SETTINGS_TYPE_COOKIES)); std::string prefs_as_json; base::JSONWriter::Write(content_setting_prefs, &prefs_as_json); EXPECT_STREQ("{\"[*.]xn--ira-ppa.com,*\":{\"setting\":2}}", prefs_as_json.c_str()); } // If a default-content-setting is managed, the managed value should be used // instead of the default value. TEST_F(HostContentSettingsMapTest, ManagedDefaultContentSetting) { TestingProfile profile; HostContentSettingsMap* host_content_settings_map = HostContentSettingsMapFactory::GetForProfile(&profile); syncable_prefs::TestingPrefServiceSyncable* prefs = profile.GetTestingPrefService(); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_JAVASCRIPT, NULL)); // Set managed-default-content-setting through the coresponding preferences. prefs->SetManagedPref(prefs::kManagedDefaultJavaScriptSetting, new base::FundamentalValue(CONTENT_SETTING_BLOCK)); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_JAVASCRIPT, NULL)); // Remove managed-default-content-settings-preferences. prefs->RemoveManagedPref(prefs::kManagedDefaultJavaScriptSetting); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_JAVASCRIPT, NULL)); // Set preference to manage the default-content-setting for Plugins. prefs->SetManagedPref(prefs::kManagedDefaultPluginsSetting, new base::FundamentalValue(CONTENT_SETTING_BLOCK)); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_PLUGINS, NULL)); #if defined(ENABLE_PLUGINS) // Remove the preference to manage the default-content-setting for Plugins. prefs->RemoveManagedPref(prefs::kManagedDefaultPluginsSetting); EXPECT_EQ(CONTENT_SETTING_DETECT_IMPORTANT_CONTENT, host_content_settings_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_PLUGINS, NULL)); #endif EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_KEYGEN, NULL)); // Set managed-default content setting through the coresponding preferences. prefs->SetManagedPref(prefs::kManagedDefaultKeygenSetting, new base::FundamentalValue(CONTENT_SETTING_ALLOW)); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_KEYGEN, NULL)); // Remove managed-default content settings preferences. prefs->RemoveManagedPref(prefs::kManagedDefaultKeygenSetting); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_KEYGEN, NULL)); } TEST_F(HostContentSettingsMapTest, GetNonDefaultContentSettingsIfTypeManaged) { TestingProfile profile; HostContentSettingsMap* host_content_settings_map = HostContentSettingsMapFactory::GetForProfile(&profile); syncable_prefs::TestingPrefServiceSyncable* prefs = profile.GetTestingPrefService(); // Set url for JavaScript setting. GURL host("http://example.com/"); host_content_settings_map->SetContentSettingDefaultScope( host, GURL(), CONTENT_SETTINGS_TYPE_JAVASCRIPT, std::string(), CONTENT_SETTING_BLOCK); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_JAVASCRIPT, NULL)); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_JAVASCRIPT, std::string())); // Set managed-default-content-setting for content-settings-type JavaScript. prefs->SetManagedPref(prefs::kManagedDefaultJavaScriptSetting, new base::FundamentalValue(CONTENT_SETTING_ALLOW)); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_JAVASCRIPT, std::string())); } // Managed default content setting should have higher priority // than user defined patterns. TEST_F(HostContentSettingsMapTest, ManagedDefaultContentSettingIgnoreUserPattern) { TestingProfile profile; HostContentSettingsMap* host_content_settings_map = HostContentSettingsMapFactory::GetForProfile(&profile); syncable_prefs::TestingPrefServiceSyncable* prefs = profile.GetTestingPrefService(); // Block all JavaScript. host_content_settings_map->SetDefaultContentSetting( CONTENT_SETTINGS_TYPE_JAVASCRIPT, CONTENT_SETTING_BLOCK); // Set an exception to allow "[*.]example.com" GURL host("http://example.com/"); host_content_settings_map->SetContentSettingDefaultScope( host, GURL(), CONTENT_SETTINGS_TYPE_JAVASCRIPT, std::string(), CONTENT_SETTING_ALLOW); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_JAVASCRIPT, NULL)); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_JAVASCRIPT, std::string())); // Set managed-default-content-settings-preferences. prefs->SetManagedPref(prefs::kManagedDefaultJavaScriptSetting, new base::FundamentalValue(CONTENT_SETTING_BLOCK)); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_JAVASCRIPT, std::string())); // Remove managed-default-content-settings-preferences. prefs->RemoveManagedPref(prefs::kManagedDefaultJavaScriptSetting); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_JAVASCRIPT, std::string())); } // If a default-content-setting is set to managed setting, the user defined // setting should be preserved. TEST_F(HostContentSettingsMapTest, OverwrittenDefaultContentSetting) { TestingProfile profile; HostContentSettingsMap* host_content_settings_map = HostContentSettingsMapFactory::GetForProfile(&profile); syncable_prefs::TestingPrefServiceSyncable* prefs = profile.GetTestingPrefService(); // Set user defined default-content-setting for Cookies. host_content_settings_map->SetDefaultContentSetting( CONTENT_SETTINGS_TYPE_COOKIES, CONTENT_SETTING_BLOCK); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_COOKIES, NULL)); // Set preference to manage the default-content-setting for Cookies. prefs->SetManagedPref(prefs::kManagedDefaultCookiesSetting, new base::FundamentalValue(CONTENT_SETTING_ALLOW)); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_COOKIES, NULL)); // Remove the preference to manage the default-content-setting for Cookies. prefs->RemoveManagedPref(prefs::kManagedDefaultCookiesSetting); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_COOKIES, NULL)); } // If a setting for a default-content-setting-type is set while the type is // managed, then the new setting should be preserved and used after the // default-content-setting-type is not managed anymore. TEST_F(HostContentSettingsMapTest, SettingDefaultContentSettingsWhenManaged) { TestingProfile profile; HostContentSettingsMap* host_content_settings_map = HostContentSettingsMapFactory::GetForProfile(&profile); syncable_prefs::TestingPrefServiceSyncable* prefs = profile.GetTestingPrefService(); prefs->SetManagedPref(prefs::kManagedDefaultPluginsSetting, new base::FundamentalValue(CONTENT_SETTING_ALLOW)); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_PLUGINS, NULL)); host_content_settings_map->SetDefaultContentSetting( CONTENT_SETTINGS_TYPE_PLUGINS, CONTENT_SETTING_BLOCK); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_PLUGINS, NULL)); prefs->RemoveManagedPref(prefs::kManagedDefaultPluginsSetting); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetDefaultContentSetting( CONTENT_SETTINGS_TYPE_PLUGINS, NULL)); } TEST_F(HostContentSettingsMapTest, GetContentSetting) { TestingProfile profile; HostContentSettingsMap* host_content_settings_map = HostContentSettingsMapFactory::GetForProfile(&profile); GURL host("http://example.com/"); GURL embedder("chrome://foo"); host_content_settings_map->SetContentSettingDefaultScope( host, GURL(), CONTENT_SETTINGS_TYPE_IMAGES, std::string(), CONTENT_SETTING_BLOCK); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetContentSetting( embedder, host, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); } TEST_F(HostContentSettingsMapTest, IsDefaultSettingAllowedForType) { EXPECT_FALSE(HostContentSettingsMap::IsDefaultSettingAllowedForType( CONTENT_SETTING_ALLOW, CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC)); EXPECT_FALSE(HostContentSettingsMap::IsDefaultSettingAllowedForType( CONTENT_SETTING_ALLOW, CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA)); } TEST_F(HostContentSettingsMapTest, AddContentSettingsObserver) { TestingProfile profile; HostContentSettingsMap* host_content_settings_map = HostContentSettingsMapFactory::GetForProfile(&profile); content_settings::MockObserver mock_observer; GURL host("http://example.com/"); ContentSettingsPattern pattern = ContentSettingsPattern::FromString("[*.]example.com"); EXPECT_CALL(mock_observer, OnContentSettingChanged(pattern, ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_IMAGES, "")); host_content_settings_map->AddObserver(&mock_observer); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); host_content_settings_map->SetContentSettingDefaultScope( host, GURL(), CONTENT_SETTINGS_TYPE_IMAGES, std::string(), CONTENT_SETTING_DEFAULT); } TEST_F(HostContentSettingsMapTest, GuestProfile) { TestingProfile profile; profile.SetGuestSession(true); HostContentSettingsMap* host_content_settings_map = HostContentSettingsMapFactory::GetForProfile(&profile); GURL host("http://example.com/"); ContentSettingsPattern pattern = ContentSettingsPattern::FromString("[*.]example.com"); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); // Changing content settings should not result in any prefs being stored // however the value should be set in memory. host_content_settings_map->SetContentSettingDefaultScope( host, GURL(), CONTENT_SETTINGS_TYPE_IMAGES, std::string(), CONTENT_SETTING_BLOCK); EXPECT_EQ(CONTENT_SETTING_BLOCK, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); const base::DictionaryValue* all_settings_dictionary = profile.GetPrefs()->GetDictionary( GetPrefName(CONTENT_SETTINGS_TYPE_IMAGES)); EXPECT_TRUE(all_settings_dictionary->empty()); } // Default settings should not be modifiable for the guest profile (there is no // UI to do this). TEST_F(HostContentSettingsMapTest, GuestProfileDefaultSetting) { TestingProfile profile; profile.SetGuestSession(true); HostContentSettingsMap* host_content_settings_map = HostContentSettingsMapFactory::GetForProfile(&profile); GURL host("http://example.com/"); // There are no custom rules, so this should be the default. EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); host_content_settings_map->SetDefaultContentSetting( CONTENT_SETTINGS_TYPE_IMAGES, CONTENT_SETTING_BLOCK); EXPECT_EQ(CONTENT_SETTING_ALLOW, host_content_settings_map->GetContentSetting( host, host, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); } // We used to incorrectly store content settings in prefs for the guest profile. // We need to ensure these get deleted appropriately. TEST_F(HostContentSettingsMapTest, GuestProfileMigration) { TestingProfile profile; profile.SetGuestSession(true); // Set a pref manually in the guest profile. scoped_ptr<base::Value> value = base::JSONReader::Read("{\"[*.]\\xC4\\x87ira.com,*\":{\"setting\":1}}"); profile.GetPrefs()->Set(GetPrefName(CONTENT_SETTINGS_TYPE_IMAGES), *value); // Test that during construction all the prefs get cleared. HostContentSettingsMapFactory::GetForProfile(&profile); const base::DictionaryValue* all_settings_dictionary = profile.GetPrefs()->GetDictionary( GetPrefName(CONTENT_SETTINGS_TYPE_IMAGES)); EXPECT_TRUE(all_settings_dictionary->empty()); }<|fim▁end|>
host, host, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); // Reseting the pref to its previous value should update the cache. prefs->Set(GetPrefName(CONTENT_SETTINGS_TYPE_IMAGES), *new_value);
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""Hypertext Transfer Protocol (HTTP) These objects provide support for :rfc:`HTTP <2616>`. .. seealso:: :mod:`HTTP authentication <bedframe.auth.http>` """ <|fim▁hole|> from ._exc import * from ._services import *<|fim▁end|>
__copyright__ = "Copyright (C) 2014 Ivan D Vasin" __docformat__ = "restructuredtext"
<|file_name|>rusti.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! * rusti - A REPL using the JIT backend * * Rusti works by serializing state between lines of input. This means that each * line can be run in a separate task, and the only limiting factor is that all * local bound variables are encodable. * * This is accomplished by feeding in generated input to rustc for execution in * the JIT compiler. Currently input actually gets fed in three times to get * information about the program. * * - Pass #1 * In this pass, the input is simply thrown at the parser and the input comes * back. This validates the structure of the program, and at this stage the * global items (fns, structs, impls, traits, etc.) are filtered from the * input into the "global namespace". These declarations shadow all previous * declarations of an item by the same name. * * - Pass #2 * After items have been stripped, the remaining input is passed to rustc * along with all local variables declared (initialized to nothing). This pass * runs up to typechecking. From this, we can learn about the types of each * bound variable, what variables are bound, and also ensure that all the * types are encodable (the input can actually be run). * * - Pass #3 * Finally, a program is generated to deserialize the local variable state, * run the code input, and then reserialize all bindings back into a local * hash map. Once this code runs, the input has fully been run and the REPL * waits for new input. * * Encoding/decoding is done with EBML, and there is simply a map of ~str -> * ~[u8] maintaining the values of each local binding (by name). */ #[link(name = "rusti", vers = "0.8-pre", uuid = "7fb5bf52-7d45-4fee-8325-5ad3311149fc", url = "https://github.com/mozilla/rust/tree/master/src/rusti")]; #[license = "MIT/ASL2"]; #[crate_type = "lib"]; extern mod extra; extern mod rustc; extern mod syntax; use std::{libc, io, os, task}; use std::cell::Cell; use extra::rl; use rustc::driver::{driver, session}; use syntax::{ast, diagnostic}; use syntax::ast_util::*; use syntax::parse::token; use syntax::print::pprust; use program::Program; use utils::*; mod program; pub mod utils; /** * A structure shared across REPL instances for storing history * such as statements and view items. I wish the AST was sendable. */ pub struct Repl { prompt: ~str, binary: ~str, running: bool, lib_search_paths: ~[~str], program: Program, } // Action to do after reading a :command enum CmdAction { action_none, action_run_line(~str), } /// Run an input string in a Repl, returning the new Repl. fn run(mut repl: Repl, input: ~str) -> Repl { // Build some necessary rustc boilerplate for compiling things let binary = repl.binary.to_managed(); let options = @session::options { crate_type: session::unknown_crate, binary: binary, addl_lib_search_paths: @mut repl.lib_search_paths.map(|p| Path(*p)), jit: true, .. copy *session::basic_options() }; // Because we assume that everything is encodable (and assert so), add some // extra helpful information if the error crops up. Otherwise people are // bound to be very confused when they find out code is running that they // never typed in... let sess = driver::build_session(options, |cm, msg, lvl| { diagnostic::emit(cm, msg, lvl); if msg.contains("failed to find an implementation of trait") && msg.contains("extra::serialize::Encodable") { diagnostic::emit(cm, "Currrently rusti serializes bound locals between \ different lines of input. This means that all \ values of local variables need to be encodable, \ and this type isn't encodable", diagnostic::note); } }); let intr = token::get_ident_interner(); // // Stage 1: parse the input and filter it into the program (as necessary) // debug!("parsing: %s", input); let crate = parse_input(sess, binary, input); let mut to_run = ~[]; // statements to run (emitted back into code) let new_locals = @mut ~[]; // new locals being defined let mut result = None; // resultant expression (to print via pp) do find_main(crate, sess) |blk| { // Fish out all the view items, be sure to record 'extern mod' items // differently beause they must appear before all 'use' statements for blk.node.view_items.iter().advance |vi| { let s = do with_pp(intr) |pp, _| { pprust::print_view_item(pp, vi); }; match vi.node { ast::view_item_extern_mod(*) => { repl.program.record_extern(s); } ast::view_item_use(*) => { repl.program.record_view_item(s); } } } // Iterate through all of the block's statements, inserting them into // the correct portions of the program for blk.node.stmts.iter().advance |stmt| { let s = do with_pp(intr) |pp, _| { pprust::print_stmt(pp, *stmt); }; match stmt.node { ast::stmt_decl(d, _) => { match d.node { ast::decl_item(it) => { let name = sess.str_of(it.ident); match it.node { // Structs are treated specially because to make // them at all usable they need to be decorated // with #[deriving(Encoable, Decodable)] ast::item_struct(*) => { repl.program.record_struct(name, s); } // Item declarations are hoisted out of main() _ => { repl.program.record_item(name, s); } } } // Local declarations must be specially dealt with, // record all local declarations for use later on ast::decl_local(l) => { let mutbl = l.node.is_mutbl; do each_binding(l) |path, _| { let s = do with_pp(intr) |pp, _| { pprust::print_path(pp, path, false); }; new_locals.push((s, mutbl)); } to_run.push(s); } } } // run statements with expressions (they have effects) ast::stmt_mac(*) | ast::stmt_semi(*) | ast::stmt_expr(*) => { to_run.push(s); } } } result = do blk.node.expr.map_consume |e| { do with_pp(intr) |pp, _| { pprust::print_expr(pp, e); } }; } // return fast for empty inputs if to_run.len() == 0 && result.is_none() { return repl; } // // Stage 2: run everything up to typeck to learn the types of the new // variables introduced into the program // info!("Learning about the new types in the program"); repl.program.set_cache(); // before register_new_vars (which changes them) let input = to_run.connect("\n"); let test = repl.program.test_code(input, &result, *new_locals); debug!("testing with ^^^^^^ %?", (||{ println(test) })()); let dinput = driver::str_input(test.to_managed()); let cfg = driver::build_configuration(sess, binary, &dinput); let outputs = driver::build_output_filenames(&dinput, &None, &None, [], sess); let (crate, tcx) = driver::compile_upto(sess, copy cfg, &dinput, driver::cu_typeck, Some(outputs)); // Once we're typechecked, record the types of all local variables defined // in this input do find_main(crate.expect("crate after cu_typeck"), sess) |blk| { repl.program.register_new_vars(blk, tcx.expect("tcx after cu_typeck")); } // // Stage 3: Actually run the code in the JIT // info!("actually running code"); let code = repl.program.code(input, &result); debug!("actually running ^^^^^^ %?", (||{ println(code) })()); let input = driver::str_input(code.to_managed()); let cfg = driver::build_configuration(sess, binary, &input); let outputs = driver::build_output_filenames(&input, &None, &None, [], sess); let sess = driver::build_session(options, diagnostic::emit); driver::compile_upto(sess, cfg, &input, driver::cu_everything, Some(outputs)); // // Stage 4: Inform the program that computation is done so it can update all // local variable bindings. // info!("cleaning up after code"); repl.program.consume_cache(); return repl; fn parse_input(sess: session::Session, binary: @str, input: &str) -> @ast::crate { let code = fmt!("fn main() {\n %s \n}", input); let input = driver::str_input(code.to_managed()); let cfg = driver::build_configuration(sess, binary, &input); let outputs = driver::build_output_filenames(&input, &None, &None, [], sess); let (crate, _) = driver::compile_upto(sess, cfg, &input, driver::cu_parse, Some(outputs)); crate.expect("parsing should return a crate") } fn find_main(crate: @ast::crate, sess: session::Session, f: &fn(&ast::blk)) { for crate.node.module.items.iter().advance |item| { match item.node { ast::item_fn(_, _, _, _, ref blk) => { if item.ident == sess.ident_of("main") { return f(blk); } } _ => {} } } fail!("main function was expected somewhere..."); } } // Compiles a crate given by the filename as a library if the compiled // version doesn't exist or is older than the source file. Binary is // the name of the compiling executable. Returns Some(true) if it // successfully compiled, Some(false) if the crate wasn't compiled // because it already exists and is newer than the source file, or // None if there were compile errors. fn compile_crate(src_filename: ~str, binary: ~str) -> Option<bool> { match do task::try { let src_path = Path(src_filename); let binary = binary.to_managed(); let options = @session::options { binary: binary, addl_lib_search_paths: @mut ~[os::getcwd()], .. copy *session::basic_options() }; let input = driver::file_input(copy src_path); let sess = driver::build_session(options, diagnostic::emit); *sess.building_library = true; let cfg = driver::build_configuration(sess, binary, &input); let outputs = driver::build_output_filenames( &input, &None, &None, [], sess); // If the library already exists and is newer than the source // file, skip compilation and return None. let mut should_compile = true; let dir = os::list_dir_path(&Path(outputs.out_filename.dirname())); let maybe_lib_path = do dir.iter().find_ |file| { // The actual file's name has a hash value and version // number in it which is unknown at this time, so looking // for a file that matches out_filename won't work, // instead we guess which file is the library by matching // the prefix and suffix of out_filename to files in the // directory. let file_str = file.filename().get(); file_str.starts_with(outputs.out_filename.filestem().get()) && file_str.ends_with(outputs.out_filename.filetype().get()) }; match maybe_lib_path { Some(lib_path) => { let (src_mtime, _) = src_path.get_mtime().get(); let (lib_mtime, _) = lib_path.get_mtime().get(); if lib_mtime >= src_mtime { should_compile = false; } }, None => { }, } if (should_compile) { println(fmt!("compiling %s...", src_filename)); driver::compile_upto(sess, cfg, &input, driver::cu_everything, Some(outputs)); true } else { false } } { Ok(true) => Some(true), Ok(false) => Some(false), Err(_) => None, } } /// Tries to get a line from rl after outputting a prompt. Returns /// None if no input was read (e.g. EOF was reached). fn get_line(use_rl: bool, prompt: &str) -> Option<~str> { if use_rl { let result = unsafe { rl::read(prompt) }; match result { None => None, Some(line) => { unsafe { rl::add_history(line) }; Some(line) } } } else { if io::stdin().eof() { None } else { Some(io::stdin().read_line()) } } } /// Run a command, e.g. :clear, :exit, etc. fn run_cmd(repl: &mut Repl, _in: @io::Reader, _out: @io::Writer, cmd: ~str, args: ~[~str], use_rl: bool) -> CmdAction { let mut action = action_none; match cmd { ~"exit" => repl.running = false, ~"clear" => { repl.program.clear(); // XXX: Win32 version of linenoise can't do this //rl::clear(); } ~"help" => { println( ":{\\n ..lines.. \\n:}\\n - execute multiline command\n\ :load <crate> ... - loads given crates as dynamic libraries\n\ :clear - clear the bindings\n\ :exit - exit from the repl\n\ :help - show this message"); } ~"load" => { let mut loaded_crates: ~[~str] = ~[]; for args.iter().advance |arg| { let (crate, filename) = if arg.ends_with(".rs") || arg.ends_with(".rc") { (arg.slice_to(arg.len() - 3).to_owned(), copy *arg) } else { (copy *arg, *arg + ".rs") }; match compile_crate(filename, copy repl.binary) { Some(_) => loaded_crates.push(crate), None => { } } } for loaded_crates.iter().advance |crate| { let crate_path = Path(*crate); let crate_dir = crate_path.dirname(); repl.program.record_extern(fmt!("extern mod %s;", *crate)); if !repl.lib_search_paths.iter().any(|x| x == &crate_dir) { repl.lib_search_paths.push(crate_dir); } } if loaded_crates.is_empty() { println("no crates loaded"); } else { println(fmt!("crates loaded: %s", loaded_crates.connect(", "))); } } ~"{" => { let mut multiline_cmd = ~""; let mut end_multiline = false; while (!end_multiline) { match get_line(use_rl, "rusti| ") { None => fail!("unterminated multiline command :{ .. :}"), Some(line) => { if line.trim() == ":}" { end_multiline = true; } else { multiline_cmd.push_str(line); multiline_cmd.push_char('\n'); } } } } action = action_run_line(multiline_cmd); } _ => println(~"unknown cmd: " + cmd) } return action; } /// Executes a line of input, which may either be rust code or a /// :command. Returns a new Repl if it has changed. pub fn run_line(repl: &mut Repl, in: @io::Reader, out: @io::Writer, line: ~str, use_rl: bool) -> Option<Repl> { if line.starts_with(":") { // drop the : and the \n (one byte each) let full = line.slice(1, line.len()); let split: ~[~str] = full.word_iter().transform(|s| s.to_owned()).collect(); let len = split.len(); if len > 0 { let cmd = copy split[0]; if !cmd.is_empty() { let args = if len > 1 { split.slice(1, len).to_owned() } else { ~[] }; match run_cmd(repl, in, out, cmd, args, use_rl) { action_none => { } action_run_line(multiline_cmd) => { if !multiline_cmd.is_empty() { return run_line(repl, in, out, multiline_cmd, use_rl); } } } return None; } } } let line = Cell::new(line); let r = Cell::new(copy *repl); let result = do task::try { run(r.take(), line.take()) }; if result.is_ok() { return Some(result.get()); } return None; } pub fn main() { let args = os::args(); let in = io::stdin(); let out = io::stdout(); let mut repl = Repl { prompt: ~"rusti> ", binary: copy args[0], running: true, lib_search_paths: ~[], program: Program::new(), }; let istty = unsafe { libc::isatty(libc::STDIN_FILENO as i32) } != 0; // only print this stuff if the user is actually typing into rusti if istty { println("WARNING: The Rust REPL is experimental and may be"); println("unstable. If you encounter problems, please use the"); println("compiler instead. Type :help for help."); unsafe { do rl::complete |line, suggest| { if line.starts_with(":") { suggest(~":clear"); suggest(~":exit"); suggest(~":help"); suggest(~":load"); } } } } while repl.running { match get_line(istty, repl.prompt) { None => break, Some(line) => { if line.is_empty() { if istty { println("()"); } loop; } match run_line(&mut repl, in, out, line, istty) { Some(new_repl) => repl = new_repl, None => { } } } } } } #[cfg(test)] mod tests { use std::io; use std::iterator::IteratorUtil; use program::Program; use super::*; fn repl() -> Repl { Repl { prompt: ~"rusti> ", binary: ~"rusti", running: true, lib_search_paths: ~[], program: Program::new(), } } // FIXME: #7220 rusti on 32bit mac doesn't work. // FIXME: #7641 rusti on 32bit linux cross compile doesn't work // FIXME: #7115 re-enable once LLVM has been upgraded #[cfg(thiswillneverbeacfgflag)] fn run_program(prog: &str) { let mut r = repl(); for prog.split_iter('\n').advance |cmd| { let result = run_line(&mut r, io::stdin(), io::stdout(), cmd.to_owned(), false); r = result.expect(fmt!("the command '%s' failed", cmd)); } } fn run_program(_: &str) {} #[test] fn super_basic() { run_program(""); } #[test] fn regression_5937() { run_program("use std::hashmap;"); } #[test] fn regression_5784() { run_program("let a = 3;"); } #[test] #[ignore] fn new_tasks() { // XXX: can't spawn new tasks because the JIT code is cleaned up // after the main function is done. run_program(" spawn( || println(\"Please don't segfault\") ); do spawn { println(\"Please?\"); } "); } #[test] fn inferred_integers_usable() { run_program("let a = 2;\n()\n"); run_program(" let a = 3; let b = 4u; assert!((a as uint) + b == 7) "); } #[test] fn local_variables_allow_shadowing() { run_program(" let a = 3; let a = 5; assert!(a == 5) "); } #[test] fn string_usable() { run_program(" let a = ~\"\"; let b = \"\"; let c = @\"\"; let d = a + b + c; assert!(d.len() == 0); "); } #[test] fn vectors_usable() { run_program(" let a = ~[1, 2, 3]; let b = &[1, 2, 3]; let c = @[1, 2, 3]; let d = a + b + c; assert!(d.len() == 9); let e: &[int] = []; "); } #[test] fn structs_usable() { run_program(" struct A{ a: int } let b = A{ a: 3 }; assert!(b.a == 3) "); } #[test] fn mutable_variables_work() { run_program(" let mut a = 3; a = 5; let mut b = std::hashmap::HashSet::new::<int>(); b.insert(a); assert!(b.contains(&5)) assert!(b.len() == 1) "); } #[test] fn functions_saved() { run_program(" fn fib(x: int) -> int { if x < 2 {x} else { fib(x - 1) + fib(x - 2) } } let a = fib(3); let a = a + fib(4); assert!(a == 5) "); } #[test] fn modules_saved() { run_program(" mod b { pub fn foo() -> uint { 3 } } assert!(b::foo() == 3) "); } #[test] fn multiple_functions() { run_program(" fn f() {} fn f() {} f() "); } #[test] fn multiple_items_same_name() { run_program(" fn f() {} mod f {} struct f; enum f {} fn f() {} f() "); } #[test] fn simultaneous_definition_and_expression() { run_program(" let a = 3; a as u8 "); } #[test] fn exit_quits() { let mut r = repl(); assert!(r.running); let result = run_line(&mut r, io::stdin(), io::stdout(), ~":exit", false); assert!(result.is_none()); assert!(!r.running);<|fim▁hole|>}<|fim▁end|>
}
<|file_name|>test_shared_group_details.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import, print_function from sentry.testutils import APITestCase class SharedGroupDetailsTest(APITestCase): def test_simple(self): self.login_as(user=self.user) group = self.create_group() event = self.create_event(group=group) url = '/api/0/shared/issues/{}/'.format(group.get_share_id()) response = self.client.get(url, format='json') assert response.status_code == 200, response.content assert response.data['id'] == str(group.id) assert response.data['latestEvent']['id'] == str(event.id) assert response.data['project']['slug'] == group.project.slug assert response.data['project']['organization']['slug'] == group.organization.slug def test_feature_disabled(self): self.login_as(user=self.user) group = self.create_group()<|fim▁hole|> org.save() url = '/api/0/shared/issues/{}/'.format(group.get_share_id()) response = self.client.get(url, format='json') assert response.status_code == 404<|fim▁end|>
org = group.organization org.flags.disable_shared_issues = True
<|file_name|>Blog_LinearRegression.py<|end_file_name|><|fim▁begin|># coding: utf-8 # In[2]: # Import and read the datset import numpy as np from sklearn import linear_model import matplotlib.pyplot as plt import pandas as pd dataset = pd.read_csv("C://Users//Koyel//Desktop/MieRobotAdvert.csv") dataset.head() # In[3]: dataset.describe() # In[4]: dataset.columns # In[5]: import seaborn as sns get_ipython().magic('matplotlib inline') sns.pairplot(dataset) # In[6]: sns.heatmap(dataset.corr()) # In[7]: dataset.columns # In[8]: X = dataset[['Facebook', 'Twitter', 'Google']] y = dataset['Hits'] # In[9]: from sklearn.model_selection import train_test_split # In[10]: X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=101) # In[11]: from sklearn.linear_model import LinearRegression # In[12]: lm = LinearRegression() # In[13]: lm.fit(X_train,y_train) # In[14]: print(lm.intercept_) # In[15]: coeff_df = pd.DataFrame(lm.coef_,X.columns,columns=['Calculated Coefficient']) coeff_df # In[17]: predictions = lm.predict(X_test) # In[26]: plt.ylabel("likes predicted") plt.title("Likes predicated for MieRobot.com blogs",color='r') plt.scatter(y_test,predictions) # In[23]: print (lm.score) # In[19]: sns.distplot((y_test-predictions),bins=50); # In[20]: from sklearn import metrics print('MAE:', metrics.mean_absolute_error(y_test, predictions)) print('MSE:', metrics.mean_squared_error(y_test, predictions))<|fim▁hole|> # In[ ]:<|fim▁end|>
print('RMSE:', np.sqrt(metrics.mean_squared_error(y_test, predictions)))
<|file_name|>test_mnl.py<|end_file_name|><|fim▁begin|># ActivitySim # Copyright (C) 2014-2015 Synthicity, LLC # See full license in LICENSE.txt. import os.path import numpy as np import pandas as pd import pandas.util.testing as pdt import pytest from ..activitysim import eval_variables from .. import mnl # this is lifted straight from urbansim's test_mnl.py @pytest.fixture(scope='module', params=[ ('fish.csv', 'fish_choosers.csv', pd.DataFrame( [[-0.02047652], [0.95309824]], index=['price', 'catch'], columns=['Alt']), pd.DataFrame([ [0.2849598, 0.2742482, 0.1605457, 0.2802463], [0.1498991, 0.4542377, 0.2600969, 0.1357664]], columns=['beach', 'boat', 'charter', 'pier']))]) def test_data(request): data, choosers, spec, probabilities = request.param return { 'data': data, 'choosers': choosers, 'spec': spec, 'probabilities': probabilities }<|fim▁hole|> @pytest.fixture def choosers(test_data): filen = os.path.join( os.path.dirname(__file__), 'data', test_data['choosers']) return pd.read_csv(filen) @pytest.fixture def spec(test_data): return test_data['spec'] @pytest.fixture def choosers_dm(choosers, spec): return eval_variables(spec.index, choosers) @pytest.fixture def utilities(choosers_dm, spec, test_data): utils = choosers_dm.dot(spec).astype('float') return pd.DataFrame( utils.as_matrix().reshape(test_data['probabilities'].shape), columns=test_data['probabilities'].columns) def test_utils_to_probs(utilities, test_data): probs = mnl.utils_to_probs(utilities) pdt.assert_frame_equal(probs, test_data['probabilities']) def test_utils_to_probs_raises(): with pytest.raises(RuntimeError): mnl.utils_to_probs( pd.DataFrame([[1, 2, np.inf, 3]])) def test_make_choices_only_one(): probs = pd.DataFrame( [[1, 0, 0], [0, 1, 0]], columns=['a', 'b', 'c'], index=['x', 'y']) choices = mnl.make_choices(probs) pdt.assert_series_equal( choices, pd.Series([0, 1], index=['x', 'y'])) def test_make_choices_real_probs(random_seed, utilities): probs = mnl.utils_to_probs(utilities) choices = mnl.make_choices(probs) pdt.assert_series_equal( choices, pd.Series([1, 2], index=[0, 1])) @pytest.fixture(scope='module') def interaction_choosers(): return pd.DataFrame({ 'attr': ['a', 'b', 'c', 'b']}, index=['w', 'x', 'y', 'z']) @pytest.fixture(scope='module') def interaction_alts(): return pd.DataFrame({ 'prop': [10, 20, 30, 40]}, index=[1, 2, 3, 4]) def test_interaction_dataset_no_sample(interaction_choosers, interaction_alts): expected = pd.DataFrame({ 'attr': ['a'] * 4 + ['b'] * 4 + ['c'] * 4 + ['b'] * 4, 'prop': [10, 20, 30, 40] * 4, 'chooser_idx': ['w'] * 4 + ['x'] * 4 + ['y'] * 4 + ['z'] * 4}, index=[1, 2, 3, 4] * 4) interacted = mnl.interaction_dataset( interaction_choosers, interaction_alts) interacted, expected = interacted.align(expected, axis=1) pdt.assert_frame_equal(interacted, expected) def test_interaction_dataset_sampled( interaction_choosers, interaction_alts, random_seed): expected = pd.DataFrame({ 'attr': ['a'] * 2 + ['b'] * 2 + ['c'] * 2 + ['b'] * 2, 'prop': [30, 40, 10, 30, 40, 10, 20, 10], 'chooser_idx': ['w'] * 2 + ['x'] * 2 + ['y'] * 2 + ['z'] * 2}, index=[3, 4, 1, 3, 4, 1, 2, 1]) interacted = mnl.interaction_dataset( interaction_choosers, interaction_alts, sample_size=2) interacted, expected = interacted.align(expected, axis=1) pdt.assert_frame_equal(interacted, expected)<|fim▁end|>
<|file_name|>packet.py<|end_file_name|><|fim▁begin|><|fim▁hole|> ''' Copyright (c) 2013 Potential Ventures Ltd Copyright (c) 2013 SolarFlare Communications Inc All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Potential Ventures Ltd, SolarFlare Communications Inc nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL POTENTIAL VENTURES LTD BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ''' """ Collection of Ethernet Packet generators to use for testdata generation Most generators take the keyword argument "payload" which can be used to control the payload contents if required. Defaults to random data. """ import random from scapy.all import Ether, IP, UDP # Supress SCAPY warning messages import logging logging.getLogger("scapy").setLevel(logging.ERROR) from cocotb.decorators import public from cocotb.generators.byte import get_bytes, random_data _default_payload = random_data # UDP packet generators @public def udp_all_sizes(max_size=1500, payload=_default_payload()): """UDP packets of every supported size""" header = Ether() / IP() / UDP() for size in range(0, max_size - len(header)): yield header / get_bytes(size, payload) @public def udp_random_sizes(npackets=100, payload=_default_payload()): """UDP packets with random sizes""" header = Ether() / IP() / UDP() max_size = 1500 - len(header) for pkt in range(npackets): yield header / get_bytes(random.randint(0, max_size), payload) # IPV4 generator @public def ipv4_small_packets(npackets=100, payload=_default_payload()): """Small (<100bytes payload) IPV4 packets""" for pkt in range(npackets): yield Ether() / IP() / get_bytes(random.randint(0, 100), payload)<|fim▁end|>
#!/usr/bin/env python
<|file_name|>Macro.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3 #JMP:xkozub03 import sys import re import Config from Config import exit_err macro_list = {}; def init_list(redef_opt): def_macro = Macro("@def"); set_macro = Macro("@set"); let_macro = Macro("@let"); null_macro = Macro("@null"); _def_macro = Macro("@__def__"); _set_macro = Macro("@__set__"); _let_macro = Macro("@__let__"); def_macro.is_def = True; set_macro.is_set = True; let_macro.is_let = True; null_macro.is_null = True; _def_macro.is_def = True; _set_macro.is_set = True; _let_macro.is_let = True; def_macro.set_redef(redef_opt); _def_macro.set_redef(redef_opt); def_macro.add_arg("$frst");<|fim▁hole|> set_macro.add_arg("$frst"); let_macro.add_arg("$frst"); let_macro.add_arg("$scnd"); _def_macro.add_arg("$frst"); _def_macro.add_arg("$scnd"); _def_macro.add_arg("$thrd"); _set_macro.add_arg("$frst"); _let_macro.add_arg("$frst"); _let_macro.add_arg("$scnd"); macro_list["@def"] = def_macro; macro_list["@set"] = set_macro; macro_list["@let"] = let_macro; macro_list["@null"] = null_macro; macro_list["@__def__"] = _def_macro; macro_list["@__set__"] = _set_macro; macro_list["@__let__"] = _let_macro; class Macro: name = ""; body = ""; args = {}; args_ord_name = []; args_cnt = 0; args_order = 0; is_def = False; is_set = False; is_let = False; is_null = False; redef = True; def __init__(self, name): self.name = name; self.body = ""; self.args = {}; self.args_ord_name = []; self.args_cnt = 0; self.args_order = 0; self.is_def = False; self.is_set = False; self.is_let = False; self.is_null = False; self.redef = True; return; def set_redef(self, redef): self.redef = redef; def get_name(self): return self.name; def get_num_of_args(self): return self.args_cnt; def add_arg(self, name): if name in self.args.keys(): #redefinice argumentu; exit_err("Semantic error (argument redefinition - '" + name + "')", 56); self.args[name] = ''; self.args_ord_name.append(name); self.args_cnt += 1; def set_next_arg(self, value): if self.args_order == self.args_cnt: #prilis mnoho parametru sys.stderr.write("Syntax error\n"); sys.exit(56); if self.is_def and self.args_order == 0 and value[0] != '@': exit_err("Macro name expected ('" + value + "' given)", 57); self.args[self.args_ord_name[self.args_order]] = value; self.args_order += 1; def set_body(self, body): self.body = body; def expand(self): return _expand(self); def expand_def(self): return _expand_def(self); def expand_set(self): return _expand_set(self); def expand_let(self): return _expand_let(self); def expand_null(self): return _expand_null(self); def _expand(self): if self.args_order != self.args_cnt: sys.stderr.write("Syntax error\n"); exit(56); self.args_order = 0; if self.is_def: return self.expand_def(); if self.is_set: return self.expand_set(); if self.is_null: return self.expand_null(); if self.is_let: return self.expand_let(); exp_body = self.body; m = re.findall("((^|[^\$]*?)(\$[a-zA-Z_][a-zA-Z_0-9]*)(\s|\$|$|[^a-zA-Z_0-9]))", exp_body); for rex in m: if rex[2] in self.args.keys(): exp_body = exp_body.replace(rex[0], rex[1] + self.args[rex[2]] + rex[3]); return exp_body; def _expand_def(self): name = self.args[self.args_ord_name[0]]; arg_list = self.args[self.args_ord_name[1]]; def_body = self.args[self.args_ord_name[2]]; new_macro = Macro(name); if name == "@__def__" or name == "@__let__" or name == "@__set__": exit_err("Redef __macro__ error", 57); if name == "@null": return ""; if self.redef and name in macro_list: exit_err("Redef -r macro error", 57); m = re.findall("\$[a-zA-Z_][a-zA-Z_0-9]*", arg_list); for rex in m: new_macro.add_arg(rex); new_macro.set_body(def_body); macro_list[name] = new_macro; return ""; def _expand_set(self): self.body = ""; set = self.args[self.args_ord_name[0]]; global ignore_white; if set == "-INPUT_SPACES": Config.ignore_white = True; elif set == "+INPUT_SPACES": Config.ignore_white = False; else: sys.stderr.write("Set error!\n"); sys.exit(56); return self.body; def _expand_let(self): self.body = ""; first = self.args[self.args_ord_name[0]]; second = self.args[self.args_ord_name[1]]; if first[0] != '@' or second[0] != '@': exit_err("let macro requires macro names as both arguments", 57); if first == "@null": return self.body; if first == "@__def__" or first == "@__let__" or first == "@__set__": exit_err("Redef __macro__ error", 57); if second == "@null": if first in macro_list: del macro_list[first]; return self.body; macro_list[first] = macro_list[second]; return self.body; def _expand_null(self): return "";<|fim▁end|>
def_macro.add_arg("$scnd"); def_macro.add_arg("$thrd");
<|file_name|>vfpclasssd.rs<|end_file_name|><|fim▁begin|>use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*;<|fim▁hole|>use ::Reg::*; use ::RegScale::*; fn vfpclasssd_1() { run_test(&Instruction { mnemonic: Mnemonic::VFPCLASSSD, operand1: Some(Direct(K2)), operand2: Some(Direct(XMM4)), operand3: Some(Literal8(5)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K3), broadcast: None }, &[98, 243, 253, 11, 103, 212, 5], OperandSize::Dword) } fn vfpclasssd_2() { run_test(&Instruction { mnemonic: Mnemonic::VFPCLASSSD, operand1: Some(Direct(K7)), operand2: Some(IndirectScaledDisplaced(EDX, Eight, 153484929, Some(OperandSize::Qword), None)), operand3: Some(Literal8(47)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K3), broadcast: None }, &[98, 243, 253, 11, 103, 60, 213, 129, 254, 37, 9, 47], OperandSize::Dword) } fn vfpclasssd_3() { run_test(&Instruction { mnemonic: Mnemonic::VFPCLASSSD, operand1: Some(Direct(K2)), operand2: Some(Direct(XMM16)), operand3: Some(Literal8(38)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K2), broadcast: None }, &[98, 179, 253, 10, 103, 208, 38], OperandSize::Qword) } fn vfpclasssd_4() { run_test(&Instruction { mnemonic: Mnemonic::VFPCLASSSD, operand1: Some(Direct(K2)), operand2: Some(IndirectScaledIndexed(RSI, RDX, Eight, Some(OperandSize::Qword), None)), operand3: Some(Literal8(3)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: Some(MaskReg::K1), broadcast: None }, &[98, 243, 253, 9, 103, 20, 214, 3], OperandSize::Qword) }<|fim▁end|>
<|file_name|>GhostMailer.test.js<|end_file_name|><|fim▁begin|>const should = require('should'); const sinon = require('sinon'); const Promise = require('bluebird'); const mail = require('../../../../../core/server/services/mail'); const settingsCache = require('../../../../../core/shared/settings-cache'); const configUtils = require('../../../../utils/configUtils'); const urlUtils = require('../../../../../core/shared/url-utils'); let mailer; // Mock SMTP config const SMTP = { transport: 'SMTP', options: { service: 'Gmail', auth: { user: 'nil', pass: '123' } } }; // test data const mailDataNoDomain = { to: '[email protected]', subject: 'testemail', html: '<p>This</p>' }; const mailDataNoServer = { to: '[email protected]', subject: 'testemail', html: '<p>This</p>' }; const mailDataIncomplete = { subject: 'testemail', html: '<p>This</p>'<|fim▁hole|>}; const sandbox = sinon.createSandbox(); describe('Mail: Ghostmailer', function () { afterEach(function () { mailer = null; configUtils.restore(); sandbox.restore(); }); it('should attach mail provider to ghost instance', function () { mailer = new mail.GhostMailer(); should.exist(mailer); mailer.should.have.property('send').and.be.a.Function(); }); it('should setup SMTP transport on initialization', function () { configUtils.set({mail: SMTP}); mailer = new mail.GhostMailer(); mailer.should.have.property('transport'); mailer.transport.transporter.name.should.eql('SMTP'); mailer.transport.sendMail.should.be.a.Function(); }); it('should fallback to direct if config is empty', function () { configUtils.set({mail: {}}); mailer = new mail.GhostMailer(); mailer.should.have.property('transport'); mailer.transport.transporter.name.should.eql('SMTP (direct)'); }); it('sends valid message successfully ', function (done) { configUtils.set({mail: {transport: 'stub'}}); mailer = new mail.GhostMailer(); mailer.transport.transporter.name.should.eql('Stub'); mailer.send(mailDataNoServer).then(function (response) { should.exist(response.response); should.exist(response.envelope); response.envelope.to.should.containEql('[email protected]'); done(); }).catch(done); }); it('handles failure', function (done) { configUtils.set({mail: {transport: 'stub', options: {error: 'Stub made a boo boo :('}}}); mailer = new mail.GhostMailer(); mailer.transport.transporter.name.should.eql('Stub'); mailer.send(mailDataNoServer).then(function () { done(new Error('Stub did not error')); }).catch(function (error) { error.message.should.containEql('Stub made a boo boo :('); done(); }).catch(done); }); it('should fail to send messages when given insufficient data', async function () { mailer = new mail.GhostMailer(); await mailer.send().should.be.rejectedWith('Incomplete message data.'); await mailer.send({subject: '123'}).should.be.rejectedWith('Incomplete message data.'); await mailer.send({subject: '', html: '123'}).should.be.rejectedWith('Incomplete message data.'); }); describe('Direct', function () { beforeEach(function () { configUtils.set({mail: {}}); mailer = new mail.GhostMailer(); }); afterEach(function () { mailer = null; }); it('return correct failure message for domain doesn\'t exist', function (done) { mailer.transport.transporter.name.should.eql('SMTP (direct)'); mailer.send(mailDataNoDomain).then(function () { done(new Error('Error message not shown.')); }, function (error) { error.message.should.startWith('Failed to send email.'); done(); }).catch(done); }); it('return correct failure message for no mail server at this address', function (done) { mailer.transport.transporter.name.should.eql('SMTP (direct)'); mailer.send(mailDataNoServer).then(function () { done(new Error('Error message not shown.')); }, function (error) { error.message.should.startWith('Failed to send email.'); done(); }).catch(done); }); it('return correct failure message for incomplete data', function (done) { mailer.transport.transporter.name.should.eql('SMTP (direct)'); mailer.send(mailDataIncomplete).then(function () { done(new Error('Error message not shown.')); }, function (error) { error.message.should.eql('Incomplete message data.'); done(); }).catch(done); }); }); describe('From address', function () { it('should use the config', async function () { configUtils.set({ mail: { from: '"Blog Title" <[email protected]>' } }); mailer = new mail.GhostMailer(); sandbox.stub(mailer, 'sendMail').resolves(); mailer.transport.transporter.name = 'NOT DIRECT'; await mailer.send({ to: '[email protected]', subject: 'subject', html: 'content' }); mailer.sendMail.firstCall.args[0].from.should.equal('"Blog Title" <[email protected]>'); }); describe('should fall back to [blog.title] <noreply@[blog.url]>', function () { beforeEach(async function () { mailer = new mail.GhostMailer(); sandbox.stub(mailer, 'sendMail').resolves(); mailer.transport.transporter.name = 'NOT DIRECT'; sandbox.stub(settingsCache, 'get').returns('Test'); }); it('standard domain', async function () { sandbox.stub(urlUtils, 'urlFor').returns('http://default.com'); configUtils.set({mail: {from: null}}); await mailer.send({ to: '[email protected]', subject: 'subject', html: 'content' }); mailer.sendMail.firstCall.args[0].from.should.equal('"Test" <[email protected]>'); }); it('trailing slash', async function () { sandbox.stub(urlUtils, 'urlFor').returns('http://default.com/'); configUtils.set({mail: {from: null}}); await mailer.send({ to: '[email protected]', subject: 'subject', html: 'content' }); mailer.sendMail.firstCall.args[0].from.should.equal('"Test" <[email protected]>'); }); it('strip port', async function () { sandbox.stub(urlUtils, 'urlFor').returns('http://default.com:2368/'); configUtils.set({mail: {from: null}}); await mailer.send({ to: '[email protected]', subject: 'subject', html: 'content' }); mailer.sendMail.firstCall.args[0].from.should.equal('"Test" <[email protected]>'); }); it('Escape title', async function () { settingsCache.get.restore(); sandbox.stub(settingsCache, 'get').returns('Test"'); sandbox.stub(urlUtils, 'urlFor').returns('http://default.com:2368/'); configUtils.set({mail: {from: null}}); await mailer.send({ to: '[email protected]', subject: 'subject', html: 'content' }); mailer.sendMail.firstCall.args[0].from.should.equal('"Test\\"" <[email protected]>'); }); }); it('should use mail.from', async function () { // Standard domain configUtils.set({mail: {from: '"bar" <[email protected]>'}}); mailer = new mail.GhostMailer(); sandbox.stub(mailer, 'sendMail').resolves(); mailer.transport.transporter.name = 'NOT DIRECT'; await mailer.send({ to: '[email protected]', subject: 'subject', html: 'content' }); mailer.sendMail.firstCall.args[0].from.should.equal('"bar" <[email protected]>'); }); it('should attach blog title', async function () { sandbox.stub(settingsCache, 'get').returns('Test'); configUtils.set({mail: {from: '[email protected]'}}); mailer = new mail.GhostMailer(); sandbox.stub(mailer, 'sendMail').resolves(); mailer.transport.transporter.name = 'NOT DIRECT'; await mailer.send({ to: '[email protected]', subject: 'subject', html: 'content' }); mailer.sendMail.firstCall.args[0].from.should.equal('"Test" <[email protected]>'); // only from set configUtils.set({mail: {from: '[email protected]'}}); await mailer.send({ to: '[email protected]', subject: 'subject', html: 'content' }); mailer.sendMail.firstCall.args[0].from.should.equal('"Test" <[email protected]>'); }); it('should ignore theme title if from address is Title <[email protected]> format', async function () { configUtils.set({mail: {from: '"R2D2" <[email protected]>'}}); mailer = new mail.GhostMailer(); sandbox.stub(mailer, 'sendMail').resolves(); mailer.transport.transporter.name = 'NOT DIRECT'; await mailer.send({ to: '[email protected]', subject: 'subject', html: 'content' }); mailer.sendMail.firstCall.args[0].from.should.equal('"R2D2" <[email protected]>'); // only from set configUtils.set({mail: {from: '"R2D2" <[email protected]>'}}); await mailer.send({ to: '[email protected]', subject: 'subject', html: 'content' }); mailer.sendMail.firstCall.args[0].from.should.equal('"R2D2" <[email protected]>'); }); it('should use default title if not theme title is provided', async function () { configUtils.set({mail: {from: null}}); sandbox.stub(urlUtils, 'urlFor').returns('http://default.com:2368/'); mailer = new mail.GhostMailer(); sandbox.stub(mailer, 'sendMail').resolves(); mailer.transport.transporter.name = 'NOT DIRECT'; await mailer.send({ to: '[email protected]', subject: 'subject', html: 'content' }); mailer.sendMail.firstCall.args[0].from.should.equal('"Ghost at default.com" <[email protected]>'); }); }); });<|fim▁end|>
<|file_name|>statistics.py<|end_file_name|><|fim▁begin|># log moments (mean, variance, skewness, kurtosis) and quantiles # why am I spending time creating a complex quantile and histogram # estimator when I only need average, so far from math import sqrt from bisect import bisect_left import scipy.stats as st maxlong = 9223372036854775807 class RunningStat(object): '''Gather single-pass statistical data from an iterable''' __slots__ = ('count', 'moments', 'min', 'max') def __init__(object, moments=1, buckets=1, sorted=False): self.count = 0 self.moments = [0] * moments # statistical moments #self.buckets = [0] * buckets # count of items in each bucket #self.percentiles = [0] * (buckets + 1) # border values between buckets #self.vk = 0 self.min = None self.max = None def __call__(self, iterable, quantifier=float): '''Wrap an iterable''' item = next(iterable) self.count += 1 num = quantifier(item) if num < self.min: self.min = num else if num > self.max: self.max = num #index = bisect_left(self.percentiles, num) #self.bucket[index] += 1 yield item def add_to_moments(self, num): oldmean = self.moments[0] try: newmean = oldmean + (num - oldmean) / self.count except ZeroDivisionError: newmean = num vk = vk + (num - oldmean)(num - newmean) self.moments[0] = newmean def __len__(self): return self.count def __iadd__(self, other): if type(other) is str: _addstr(self, other) return for string in other: _addstr(self, string) #def __enter__(self): pass def __exit__(self): self._mean = float(self._mean / self.count) def _addstr(self, string): words = string.split() self.count = len(words) for w in words: self._mean += len(w) def _mean_(self): if type(self._mean) is int: __exit__(self) return self._mean def append(self, other): self.count += 1 self.accumulated += len(other) @property def mean(self): return self.moments[0] @property def variance(self): return self.moments[1] @property def kurtosis(self): return self.moments[2] class Gen(object): __slots__ = ('inner') def __init__(self, inner): self.inner = inner def __iter__(self): return Iter(self, self.inner) def __len__(self): return len(self.inner) class Iter(object): __slots__ = ('generator', 'count', 'inner') def __new__(cls, gen, iterable, action=None): if isinstance(iterable, cls): return iterable return super().__new__(cls, gen, iterable) def __init__(self, gen, iterable, action=None): self.generator = gen self.count = 0 self.actions = [] if action is None else [action] self.inner = iterable \ if hasattr(iterable, '__next__') \ else iterable.__iter__()<|fim▁hole|> r = self.inner.__next__() for a in self.actions: r = a(r) self.count += 1 return r def __len__(self): return self.generator.__len__() - self.count z_score = st.norm.ppf((1+.95)/2) z_sqr = z_score*z_score def wilson_score(positive, n): '''returns lower bound of Wilson score confidence interval for a Bernoulli parameter resource: http://www.evanmiller.org/how-not-to-sort-by-average-rating.html''' assert positive <= n if n is 0: return float('NaN') p = positive / n zz÷n = z_sqr / n return (p + zz÷n/2 - z * sqrt((p * (1 - p) + zz÷n/4) / n)) \ / (1 + zz÷n) # trying using closure instead def stats(gen, moments=2, readers=[]): def generator():<|fim▁end|>
def __iter__(self): return self def __next__(self):