prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>index.d.ts<|end_file_name|><|fim▁begin|>import {ReactFocusEvents, ReactFormEvents, ReactMouseEvents} from '../..'; import * as React from 'react'; export type DropdownPropPointing = 'left' | 'right' | 'top' | 'top left' | 'top right' | 'bottom' | 'bottom left' | 'bottom right'; export type DropdownPropAdditionPosition = 'top' | 'bottom'; export interface DropdownProps extends ReactMouseEvents<HTMLElement>, ReactFocusEvents<HTMLElement>, ReactFormEvents<HTMLElement> { /** Label prefixed to an option added by a user. */ additionLabel?: string; /** Position of the `Add: ...` option in the dropdown list ('top' or 'bottom'). */ additionPosition?: DropdownPropAdditionPosition; /** * Allow user additions to the list of options (boolean). * Requires the use of `selection`, `options` and `search`. */ allowAdditions?: any; /** An element type to render as (string or function). */ as?: any; /** A Dropdown can reduce its complexity */ basic?: boolean; /** Format the Dropdown to appear as a button. */ button?: boolean; /** Primary content. */ children?: React.ReactNode; /** Additional classes. */ className?: string; /** Whether or not the menu should close when the dropdown is blurred. */ closeOnBlur?: boolean; /** A compact dropdown has no minimum width. */ compact?: boolean; /** Initial value of open. */ defaultOpen?: boolean; /** Currently selected label in multi-select. */ defaultSelectedLabel?: any; /** Initial value or value array if multiple. */ defaultValue?: string|number|Array<string>|Array<number>; /** A disabled dropdown menu or item does not allow user interaction. */ disabled?: boolean; /** An errored dropdown can alert a user to a problem. */ error?: boolean; /** A dropdown menu can contain floated content. */ floating?: boolean; /** A dropdown can take the full width of its parent */ fluid?: boolean; /** A dropdown menu can contain a header. */ header?: React.ReactNode; /** Shorthand for Icon. */ icon?: any; /** A dropdown can be formatted as a Menu item. */ item?: boolean; /** A dropdown can be formatted to appear inline in other content. */ inline?: boolean; /** A dropdown can be labeled. */ labeled?: boolean; /** A dropdown can show that it is currently loading data. */ loading?: boolean; /** A selection dropdown can allow multiple selections. */ multiple?: boolean; /** Name of the hidden input which holds the value. */ name?: string; /** Message to display when there are no results. */ noResultsMessage?: string; /** * Called when a user adds a new item. Use this to update the options list. * * @param {SyntheticEvent} event - React's original SyntheticEvent. * @param {object} data - All props and the new item's value. */<|fim▁hole|> * Called on search input change. * * @param {SyntheticEvent} event - React's original SyntheticEvent. * @param {string} value - Current value of search input. */ onSearchChange?: React.FormEventHandler<HTMLSelectElement>; /** Controls whether or not the dropdown menu is displayed. */ open?: boolean; /** Whether or not the menu should open when the dropdown is focused. */ openOnFocus?: boolean; /** Array of Dropdown.Item props e.g. `{ text: '', value: '' }` */ options?: Array<DropdownItemProps>; /** Placeholder text. */ placeholder?: string; /** A dropdown can be formatted so that its menu is pointing. */ pointing?: boolean | DropdownPropPointing; /** * A function that takes (data, index, defaultLabelProps) and returns * shorthand for Label . */ renderLabel?: any; /** A dropdown can have its menu scroll. */ scrolling?: boolean; /** * A selection dropdown can allow a user to search through a large list of choices. * Pass a function here to replace the default search. */ search?: ((filteredOptions: any, searchQuery: any) => void) | boolean; // TODO -add search function; /** Define whether the highlighted item should be selected on blur. */ selectOnBlur?: boolean; /** A dropdown can be used to select between choices in a form. */ selection?: any; /** A simple dropdown can open without Javascript. */ simple?: boolean; /** A dropdown can receive focus. */ tabIndex?: string; /** The text displayed in the dropdown, usually for the active item. */ text?: string|React.ReactNode; /** Custom element to trigger the menu to become visible. Takes place of 'text'. */ trigger?: any; /** Current value or value array if multiple. Creates a controlled component. */ value?: string|number|Array<string>|Array<number>; } interface DropdownClass extends React.ComponentClass<DropdownProps> { Divider: typeof DropdownDivider; Header: typeof DropdownHeader; Item: typeof DropdownItem; Menu: typeof DropdownMenu; } export const Dropdown: DropdownClass; interface DropdownDividerProps { /** An element type to render as (string or function). */ as?: any; /** Additional classes. */ className?: string; } export const DropdownDivider: React.ComponentClass<DropdownDividerProps>; interface DropdownHeaderProps { /** An element type to render as (string or function). */ as?: any; /** Primary content. */ children?: React.ReactNode; /** Additional classes. */ className?: string; /** Shorthand for primary content. */ content?: any; /** Shorthand for Icon. */ icon?: any; } export const DropdownHeader: React.ComponentClass<DropdownHeaderProps>; interface DropdownItemProps extends ReactMouseEvents<HTMLElement>, ReactFocusEvents<HTMLElement>, ReactFormEvents<HTMLElement> { /** Style as the currently chosen item. */ active?: boolean; /** An element type to render as (string or function). */ as?: any; /** Primary content. */ children?: React.ReactNode; /** Additional classes. */ className?: string; /** Additional text with less emphasis. */ description?: any; /** A dropdown item can be disabled. */ disabled?: boolean; /** Shorthand for Flag. */ flag?: any; /** Shorthand for Icon. */ icon?: any; /** Shorthand for Image. */ image?: any; /** Shorthand for Label. */ label?: any; /** * The item currently selected by keyboard shortcut. * This is not the active item. */ selected?: boolean; /** Display text. */ text?: any; /** Stored value */ value?: number|string; } export const DropdownItem: React.ComponentClass<DropdownItemProps>; interface DropdownMenuProps { /** An element type to render as (string or function). */ as?: any; /** Primary content. */ children?: React.ReactNode; /** Additional classes. */ className?: string; /** A dropdown menu can scroll. */ scrolling?: boolean; } export const DropdownMenu: React.ComponentClass<DropdownMenuProps>;<|fim▁end|>
onAddItem?: React.MouseEventHandler<HTMLSelectElement>; /**
<|file_name|>34171-i1181.cpp<|end_file_name|><|fim▁begin|>int main() { if(true) {return 1;}<|fim▁hole|><|fim▁end|>
else if(true) {return 1;} else {return 1;} }
<|file_name|>CountryUtils.java<|end_file_name|><|fim▁begin|>package com.example.android.bluetoothlegatt.ble_service;<|fim▁hole|> * @author Sopheak Tuon * @created on 04-Oct-17 */ import java.util.Locale; public class CountryUtils { public static boolean getMonthAndDayFormate() { Locale locale = Locale.getDefault(); String lang = locale.getLanguage(); String contr = locale.getCountry(); if (lang == null || (!lang.equals("zh") && !lang.equals("ja") && !lang.equals("ko") && (!lang.equals("en") || contr == null || !contr.equals("US")))) { return false; } return true; } public static boolean getLanguageFormate() { String language = Locale.getDefault().getLanguage(); if (language == null || !language.equals("zh")) { return false; } return true; } }<|fim▁end|>
/**
<|file_name|>errors.rs<|end_file_name|><|fim▁begin|>// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use error_code::{self, ErrorCode, ErrorCodeExt}; use openssl::error::ErrorStack as CrypterError; use protobuf::ProtobufError; use std::io::{Error as IoError, ErrorKind}; use std::{error, result}; /// The error type for encryption. #[derive(Debug, Fail)] pub enum Error { #[fail(display = "Other error {}", _0)] Other(Box<dyn error::Error + Sync + Send>), #[fail(display = "RocksDB error {}", _0)] Rocks(String), #[fail(display = "IO error {}", _0)] Io(IoError), #[fail(display = "OpenSSL error {}", _0)] Crypter(CrypterError), #[fail(display = "Protobuf error {}", _0)] Proto(ProtobufError),<|fim▁hole|> WrongMasterKey(Box<dyn error::Error + Sync + Send>), #[fail( display = "Both master key failed, current key {}, previous key {}.", _0, _1 )] BothMasterKeyFail( Box<dyn error::Error + Sync + Send>, Box<dyn error::Error + Sync + Send>, ), } macro_rules! impl_from { ($($inner:ty => $container:ident,)+) => { $( impl From<$inner> for Error { fn from(inr: $inner) -> Error { Error::$container(inr) } } )+ }; } impl_from! { Box<dyn error::Error + Sync + Send> => Other, String => Rocks, IoError => Io, CrypterError => Crypter, ProtobufError => Proto, } impl From<Error> for IoError { fn from(err: Error) -> IoError { match err { Error::Io(e) => e, other => IoError::new(ErrorKind::Other, format!("{}", other)), } } } pub type Result<T> = result::Result<T, Error>; impl ErrorCodeExt for Error { fn error_code(&self) -> ErrorCode { match self { Error::Rocks(_) => error_code::encryption::ROCKS, Error::Io(_) => error_code::encryption::IO, Error::Crypter(_) => error_code::encryption::CRYPTER, Error::Proto(_) => error_code::encryption::PROTO, Error::UnknownEncryption => error_code::encryption::UNKNOWN_ENCRYPTION, Error::WrongMasterKey(_) => error_code::encryption::WRONG_MASTER_KEY, Error::BothMasterKeyFail(_, _) => error_code::encryption::BOTH_MASTER_KEY_FAIL, Error::Other(_) => error_code::UNKNOWN, } } }<|fim▁end|>
#[fail(display = "Unknown encryption error")] UnknownEncryption, #[fail(display = "Wrong master key error {}", _0)]
<|file_name|>test_settings.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ test_settings ~~~~~~~~~~~~~ Test the Settings object. """ import pytest import h2.errors import h2.exceptions import h2.settings from hypothesis import given, assume from hypothesis.strategies import ( integers, booleans, fixed_dictionaries, builds ) class TestSettings(object): """ Test the Settings object behaves as expected. """ def test_settings_defaults_client(self): """ The Settings object begins with the appropriate defaults for clients. """ s = h2.settings.Settings(client=True) assert s[h2.settings.SettingCodes.HEADER_TABLE_SIZE] == 4096 assert s[h2.settings.SettingCodes.ENABLE_PUSH] == 1 assert s[h2.settings.SettingCodes.INITIAL_WINDOW_SIZE] == 65535 assert s[h2.settings.SettingCodes.MAX_FRAME_SIZE] == 16384 assert s[h2.settings.SettingCodes.ENABLE_CONNECT_PROTOCOL] == 0 def test_settings_defaults_server(self): """ The Settings object begins with the appropriate defaults for servers. """ s = h2.settings.Settings(client=False) assert s[h2.settings.SettingCodes.HEADER_TABLE_SIZE] == 4096 assert s[h2.settings.SettingCodes.ENABLE_PUSH] == 0 assert s[h2.settings.SettingCodes.INITIAL_WINDOW_SIZE] == 65535 assert s[h2.settings.SettingCodes.MAX_FRAME_SIZE] == 16384 assert s[h2.settings.SettingCodes.ENABLE_CONNECT_PROTOCOL] == 0 @pytest.mark.parametrize('client', [True, False]) def test_can_set_initial_values(self, client): """ The Settings object can be provided initial values that override the defaults. """ overrides = { h2.settings.SettingCodes.HEADER_TABLE_SIZE: 8080, h2.settings.SettingCodes.MAX_FRAME_SIZE: 16388, h2.settings.SettingCodes.MAX_CONCURRENT_STREAMS: 100, h2.settings.SettingCodes.MAX_HEADER_LIST_SIZE: 2**16, h2.settings.SettingCodes.ENABLE_CONNECT_PROTOCOL: 1, } s = h2.settings.Settings(client=client, initial_values=overrides) assert s[h2.settings.SettingCodes.HEADER_TABLE_SIZE] == 8080 assert s[h2.settings.SettingCodes.ENABLE_PUSH] == bool(client) assert s[h2.settings.SettingCodes.INITIAL_WINDOW_SIZE] == 65535 assert s[h2.settings.SettingCodes.MAX_FRAME_SIZE] == 16388 assert s[h2.settings.SettingCodes.MAX_CONCURRENT_STREAMS] == 100 assert s[h2.settings.SettingCodes.MAX_HEADER_LIST_SIZE] == 2**16 assert s[h2.settings.SettingCodes.ENABLE_CONNECT_PROTOCOL] == 1 @pytest.mark.parametrize( 'setting,value', [ (h2.settings.SettingCodes.ENABLE_PUSH, 2), (h2.settings.SettingCodes.ENABLE_PUSH, -1), (h2.settings.SettingCodes.INITIAL_WINDOW_SIZE, -1), (h2.settings.SettingCodes.INITIAL_WINDOW_SIZE, 2**34), (h2.settings.SettingCodes.MAX_FRAME_SIZE, 1), (h2.settings.SettingCodes.MAX_FRAME_SIZE, 2**30), (h2.settings.SettingCodes.MAX_HEADER_LIST_SIZE, -1), (h2.settings.SettingCodes.ENABLE_CONNECT_PROTOCOL, -1), ] ) def test_cannot_set_invalid_initial_values(self, setting, value): """ The Settings object can be provided initial values that override the defaults. """ overrides = {setting: value} with pytest.raises(h2.exceptions.InvalidSettingsValueError): h2.settings.Settings(initial_values=overrides) def test_applying_value_doesnt_take_effect_immediately(self): """ When a value is applied to the settings object, it doesn't immediately take effect. """ s = h2.settings.Settings(client=True) s[h2.settings.SettingCodes.HEADER_TABLE_SIZE] == 8000 assert s[h2.settings.SettingCodes.HEADER_TABLE_SIZE] == 4096 def test_acknowledging_values(self): """ When we acknowledge settings, the values change. """ s = h2.settings.Settings(client=True) old_settings = dict(s) new_settings = { h2.settings.SettingCodes.HEADER_TABLE_SIZE: 4000, h2.settings.SettingCodes.ENABLE_PUSH: 0, h2.settings.SettingCodes.INITIAL_WINDOW_SIZE: 60, h2.settings.SettingCodes.MAX_FRAME_SIZE: 16385, h2.settings.SettingCodes.ENABLE_CONNECT_PROTOCOL: 1, } s.update(new_settings) assert dict(s) == old_settings s.acknowledge() assert dict(s) == new_settings def test_acknowledging_returns_the_changed_settings(self): """ Acknowledging settings returns the changes. """ s = h2.settings.Settings(client=True) s[h2.settings.SettingCodes.HEADER_TABLE_SIZE] = 8000 s[h2.settings.SettingCodes.ENABLE_PUSH] = 0 changes = s.acknowledge() assert len(changes) == 2 table_size_change = ( changes[h2.settings.SettingCodes.HEADER_TABLE_SIZE] ) push_change = changes[h2.settings.SettingCodes.ENABLE_PUSH] assert table_size_change.setting == ( h2.settings.SettingCodes.HEADER_TABLE_SIZE ) assert table_size_change.original_value == 4096 assert table_size_change.new_value == 8000 assert push_change.setting == h2.settings.SettingCodes.ENABLE_PUSH assert push_change.original_value == 1 assert push_change.new_value == 0 def test_acknowledging_only_returns_changed_settings(self): """ Acknowledging settings does not return unchanged settings. """ s = h2.settings.Settings(client=True) s[h2.settings.SettingCodes.INITIAL_WINDOW_SIZE] = 70 changes = s.acknowledge() assert len(changes) == 1 assert list(changes.keys()) == [ h2.settings.SettingCodes.INITIAL_WINDOW_SIZE ] def test_deleting_values_deletes_all_of_them(self): """ When we delete a key we lose all state about it. """ s = h2.settings.Settings(client=True) s[h2.settings.SettingCodes.HEADER_TABLE_SIZE] == 8000 del s[h2.settings.SettingCodes.HEADER_TABLE_SIZE] with pytest.raises(KeyError): s[h2.settings.SettingCodes.HEADER_TABLE_SIZE] def test_length_correctly_reported(self): """ Length is related only to the number of keys. """ s = h2.settings.Settings(client=True) assert len(s) == 5 s[h2.settings.SettingCodes.HEADER_TABLE_SIZE] == 8000 assert len(s) == 5 s.acknowledge() assert len(s) == 5 del s[h2.settings.SettingCodes.HEADER_TABLE_SIZE] assert len(s) == 4 def test_new_values_work(self): """ New values initially don't appear """ s = h2.settings.Settings(client=True) s[80] = 81 with pytest.raises(KeyError): s[80] def test_new_values_follow_basic_acknowledgement_rules(self): """ A new value properly appears when acknowledged. """ s = h2.settings.Settings(client=True) s[80] = 81 changed_settings = s.acknowledge() assert s[80] == 81 assert len(changed_settings) == 1 changed = changed_settings[80] assert changed.setting == 80 assert changed.original_value is None assert changed.new_value == 81 def test_single_values_arent_affected_by_acknowledgement(self): """ When acknowledged, unchanged settings remain unchanged. """ s = h2.settings.Settings(client=True) assert s[h2.settings.SettingCodes.HEADER_TABLE_SIZE] == 4096 s.acknowledge() assert s[h2.settings.SettingCodes.HEADER_TABLE_SIZE] == 4096 def test_settings_getters(self): """ Getters exist for well-known settings. """ s = h2.settings.Settings(client=True) assert s.header_table_size == ( s[h2.settings.SettingCodes.HEADER_TABLE_SIZE] ) assert s.enable_push == s[h2.settings.SettingCodes.ENABLE_PUSH] assert s.initial_window_size == ( s[h2.settings.SettingCodes.INITIAL_WINDOW_SIZE] ) assert s.max_frame_size == s[h2.settings.SettingCodes.MAX_FRAME_SIZE] assert s.max_concurrent_streams == 2**32 + 1 # A sensible default. assert s.max_header_list_size is None assert s.enable_connect_protocol == s[ h2.settings.SettingCodes.ENABLE_CONNECT_PROTOCOL ] def test_settings_setters(self): """ Setters exist for well-known settings. """ s = h2.settings.Settings(client=True) s.header_table_size = 0 s.enable_push = 1 s.initial_window_size = 2 s.max_frame_size = 16385 s.max_concurrent_streams = 4 s.max_header_list_size = 2**16 s.enable_connect_protocol = 1 s.acknowledge() assert s[h2.settings.SettingCodes.HEADER_TABLE_SIZE] == 0 assert s[h2.settings.SettingCodes.ENABLE_PUSH] == 1 assert s[h2.settings.SettingCodes.INITIAL_WINDOW_SIZE] == 2 assert s[h2.settings.SettingCodes.MAX_FRAME_SIZE] == 16385 assert s[h2.settings.SettingCodes.MAX_CONCURRENT_STREAMS] == 4 assert s[h2.settings.SettingCodes.MAX_HEADER_LIST_SIZE] == 2**16 assert s[h2.settings.SettingCodes.ENABLE_CONNECT_PROTOCOL] == 1 @given(integers()) def test_cannot_set_invalid_values_for_enable_push(self, val): """ SETTINGS_ENABLE_PUSH only allows two values: 0, 1. """ assume(val not in (0, 1)) s = h2.settings.Settings() with pytest.raises(h2.exceptions.InvalidSettingsValueError) as e: s.enable_push = val s.acknowledge() assert e.value.error_code == h2.errors.ErrorCodes.PROTOCOL_ERROR assert s.enable_push == 1 with pytest.raises(h2.exceptions.InvalidSettingsValueError) as e: s[h2.settings.SettingCodes.ENABLE_PUSH] = val s.acknowledge() assert e.value.error_code == h2.errors.ErrorCodes.PROTOCOL_ERROR assert s[h2.settings.SettingCodes.ENABLE_PUSH] == 1 @given(integers()) def test_cannot_set_invalid_vals_for_initial_window_size(self, val): """ SETTINGS_INITIAL_WINDOW_SIZE only allows values between 0 and 2**32 - 1 inclusive. """ s = h2.settings.Settings() if 0 <= val <= 2**31 - 1: s.initial_window_size = val s.acknowledge() assert s.initial_window_size == val else: with pytest.raises(h2.exceptions.InvalidSettingsValueError) as e: s.initial_window_size = val s.acknowledge() assert ( e.value.error_code == h2.errors.ErrorCodes.FLOW_CONTROL_ERROR ) assert s.initial_window_size == 65535 with pytest.raises(h2.exceptions.InvalidSettingsValueError) as e: s[h2.settings.SettingCodes.INITIAL_WINDOW_SIZE] = val s.acknowledge() assert ( e.value.error_code == h2.errors.ErrorCodes.FLOW_CONTROL_ERROR ) assert s[h2.settings.SettingCodes.INITIAL_WINDOW_SIZE] == 65535 @given(integers()) def test_cannot_set_invalid_values_for_max_frame_size(self, val): """ SETTINGS_MAX_FRAME_SIZE only allows values between 2**14 and 2**24 - 1. """ s = h2.settings.Settings() if 2**14 <= val <= 2**24 - 1: s.max_frame_size = val s.acknowledge() assert s.max_frame_size == val else: with pytest.raises(h2.exceptions.InvalidSettingsValueError) as e: s.max_frame_size = val s.acknowledge() assert e.value.error_code == h2.errors.ErrorCodes.PROTOCOL_ERROR assert s.max_frame_size == 16384 with pytest.raises(h2.exceptions.InvalidSettingsValueError) as e: s[h2.settings.SettingCodes.MAX_FRAME_SIZE] = val s.acknowledge() assert e.value.error_code == h2.errors.ErrorCodes.PROTOCOL_ERROR assert s[h2.settings.SettingCodes.MAX_FRAME_SIZE] == 16384<|fim▁hole|> """ SETTINGS_MAX_HEADER_LIST_SIZE only allows non-negative values. """ s = h2.settings.Settings() if val >= 0: s.max_header_list_size = val s.acknowledge() assert s.max_header_list_size == val else: with pytest.raises(h2.exceptions.InvalidSettingsValueError) as e: s.max_header_list_size = val s.acknowledge() assert e.value.error_code == h2.errors.ErrorCodes.PROTOCOL_ERROR assert s.max_header_list_size is None with pytest.raises(h2.exceptions.InvalidSettingsValueError) as e: s[h2.settings.SettingCodes.MAX_HEADER_LIST_SIZE] = val s.acknowledge() assert e.value.error_code == h2.errors.ErrorCodes.PROTOCOL_ERROR with pytest.raises(KeyError): s[h2.settings.SettingCodes.MAX_HEADER_LIST_SIZE] @given(integers()) def test_cannot_set_invalid_values_for_enable_connect_protocol(self, val): """ SETTINGS_ENABLE_CONNECT_PROTOCOL only allows two values: 0, 1. """ assume(val not in (0, 1)) s = h2.settings.Settings() with pytest.raises(h2.exceptions.InvalidSettingsValueError) as e: s.enable_connect_protocol = val s.acknowledge() assert e.value.error_code == h2.errors.ErrorCodes.PROTOCOL_ERROR assert s.enable_connect_protocol == 0 with pytest.raises(h2.exceptions.InvalidSettingsValueError) as e: s[h2.settings.SettingCodes.ENABLE_CONNECT_PROTOCOL] = val s.acknowledge() assert e.value.error_code == h2.errors.ErrorCodes.PROTOCOL_ERROR assert s[h2.settings.SettingCodes.ENABLE_CONNECT_PROTOCOL] == 0 class TestSettingsEquality(object): """ A class defining tests for the standard implementation of == and != . """ SettingsStrategy = builds( h2.settings.Settings, client=booleans(), initial_values=fixed_dictionaries({ h2.settings.SettingCodes.HEADER_TABLE_SIZE: integers(0, 2**32 - 1), h2.settings.SettingCodes.ENABLE_PUSH: integers(0, 1), h2.settings.SettingCodes.INITIAL_WINDOW_SIZE: integers(0, 2**31 - 1), h2.settings.SettingCodes.MAX_FRAME_SIZE: integers(2**14, 2**24 - 1), h2.settings.SettingCodes.MAX_CONCURRENT_STREAMS: integers(0, 2**32 - 1), h2.settings.SettingCodes.MAX_HEADER_LIST_SIZE: integers(0, 2**32 - 1), }) ) @given(settings=SettingsStrategy) def test_equality_reflexive(self, settings): """ An object compares equal to itself using the == operator and the != operator. """ assert (settings == settings) assert not (settings != settings) @given(settings=SettingsStrategy, o_settings=SettingsStrategy) def test_equality_multiple(self, settings, o_settings): """ Two objects compare themselves using the == operator and the != operator. """ if settings == o_settings: assert settings == o_settings assert not (settings != o_settings) else: assert settings != o_settings assert not (settings == o_settings) @given(settings=SettingsStrategy) def test_another_type_equality(self, settings): """ The object does not compare equal to an object of an unrelated type (which does not implement the comparison) using the == operator. """ obj = object() assert (settings != obj) assert not (settings == obj) @given(settings=SettingsStrategy) def test_delegated_eq(self, settings): """ The result of comparison is delegated to the right-hand operand if it is of an unrelated type. """ class Delegate(object): def __eq__(self, other): return [self] def __ne__(self, other): return [self] delg = Delegate() assert (settings == delg) == [delg] assert (settings != delg) == [delg]<|fim▁end|>
@given(integers()) def test_cannot_set_invalid_values_for_max_header_list_size(self, val):
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3 # -*- coding: utf-8 -*- # Copyright © 2014 Martin Ueding <[email protected]> # Licensed under The Lesser GNU Public License Version 2 (or later) <|fim▁hole|>from setuptools import setup, find_packages setup( author="David Pine", description="Least squares linear fit for numpy library of Python", license="LGPL2", name="linfit", packages=find_packages(), install_requires=[ 'numpy', ], url="https://github.com/djpine/linfit", download_url="https://github.com/djpine/linfit", version="2014.9.3", )<|fim▁end|>
<|file_name|>connect_test.go<|end_file_name|><|fim▁begin|>package connect import ( "strings" "testing" ) func TestCatalogCommand_noTabs(t *testing.T) { t.Parallel() if strings.ContainsRune(New().Help(), '\t') { t.Fatal("help has tabs")<|fim▁hole|> } }<|fim▁end|>
<|file_name|>list.js<|end_file_name|><|fim▁begin|>/* ListJS 1.1.1 (www.listjs.com) License (MIT) Copyright (c) 2012 Jonny Strömberg <[email protected]> http://jonnystromberg.com */ ;(function(){ /** * Require the given path. * * @param {String} path * @return {Object} exports * @api public */ function require(path, parent, orig) { var resolved = require.resolve(path); // lookup failed if (null == resolved) { orig = orig || path; parent = parent || 'root'; var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); err.path = orig; err.parent = parent; err.require = true; throw err; } var module = require.modules[resolved]; // perform real require() // by invoking the module's // registered function if (!module._resolving && !module.exports) { var mod = {}; mod.exports = {}; mod.client = mod.component = true; module._resolving = true; module.call(this, mod.exports, require.relative(resolved), mod); delete module._resolving; module.exports = mod.exports; } return module.exports; } /** * Registered modules. */ require.modules = {}; /** * Registered aliases. */ require.aliases = {}; /** * Resolve `path`. * * Lookup: * * - PATH/index.js * - PATH.js * - PATH * * @param {String} path * @return {String} path or null * @api private */ require.resolve = function(path) { if (path.charAt(0) === '/') path = path.slice(1); var paths = [ path, path + '.js', path + '.json', path + '/index.js', path + '/index.json' ]; for (var i = 0; i < paths.length; i++) { var path = paths[i]; if (require.modules.hasOwnProperty(path)) return path; if (require.aliases.hasOwnProperty(path)) return require.aliases[path]; } }; /** * Normalize `path` relative to the current path. * * @param {String} curr * @param {String} path * @return {String} * @api private */ require.normalize = function(curr, path) { var segs = []; if ('.' != path.charAt(0)) return path; curr = curr.split('/'); path = path.split('/'); for (var i = 0; i < path.length; ++i) { if ('..' == path[i]) { curr.pop(); } else if ('.' != path[i] && '' != path[i]) { segs.push(path[i]); } } return curr.concat(segs).join('/'); }; /** * Register module at `path` with callback `definition`. * * @param {String} path * @param {Function} definition * @api private */ require.register = function(path, definition) { require.modules[path] = definition; }; /** * Alias a module definition. * * @param {String} from * @param {String} to * @api private */ require.alias = function(from, to) { if (!require.modules.hasOwnProperty(from)) { throw new Error('Failed to alias "' + from + '", it does not exist'); } require.aliases[to] = from; }; /** * Return a require function relative to the `parent` path. * * @param {String} parent * @return {Function} * @api private */ require.relative = function(parent) { var p = require.normalize(parent, '..'); /** * lastIndexOf helper. */ function lastIndexOf(arr, obj) { var i = arr.length; while (i--) { if (arr[i] === obj) return i; } return -1; } /** * The relative require() itself. */ function localRequire(path) { var resolved = localRequire.resolve(path); return require(resolved, parent, path); } /** * Resolve relative to the parent. */ localRequire.resolve = function(path) { var c = path.charAt(0); if ('/' == c) return path.slice(1); if ('.' == c) return require.normalize(p, path); // resolve deps by returning // the dep in the nearest "deps" // directory var segs = parent.split('/'); var i = lastIndexOf(segs, 'deps') + 1; if (!i) i = 0; path = segs.slice(0, i + 1).join('/') + '/deps/' + path; return path; }; /** * Check if module is defined at `path`. */ localRequire.exists = function(path) { return require.modules.hasOwnProperty(localRequire.resolve(path)); }; return localRequire; }; require.register("component-classes/index.js", function(exports, require, module){ /** * Module dependencies. */ var index = require('indexof'); /** * Whitespace regexp. */ var re = /\s+/; /** * toString reference. */ var toString = Object.prototype.toString; /** * Wrap `el` in a `ClassList`. * * @param {Element} el * @return {ClassList} * @api public */ module.exports = function(el){ return new ClassList(el); }; /** * Initialize a new ClassList for `el`. * * @param {Element} el * @api private */ function ClassList(el) { if (!el) throw new Error('A DOM element reference is required'); this.el = el; this.list = el.classList; } /** * Add class `name` if not already present. * * @param {String} name * @return {ClassList} * @api public */ ClassList.prototype.add = function(name){ // classList if (this.list) { this.list.add(name); return this; } // fallback var arr = this.array(); var i = index(arr, name); if (!~i) arr.push(name); this.el.className = arr.join(' '); return this; }; /** * Remove class `name` when present, or * pass a regular expression to remove * any which match. * * @param {String|RegExp} name * @return {ClassList} * @api public */ ClassList.prototype.remove = function(name){ if ('[object RegExp]' == toString.call(name)) { return this.removeMatching(name); } // classList if (this.list) { this.list.remove(name); return this; } // fallback var arr = this.array(); var i = index(arr, name); if (~i) arr.splice(i, 1); this.el.className = arr.join(' '); return this; }; /** * Remove all classes matching `re`. * * @param {RegExp} re * @return {ClassList} * @api private */ ClassList.prototype.removeMatching = function(re){ var arr = this.array(); for (var i = 0; i < arr.length; i++) { if (re.test(arr[i])) { this.remove(arr[i]); } } return this; }; /** * Toggle class `name`, can force state via `force`. * * For browsers that support classList, but do not support `force` yet, * the mistake will be detected and corrected. * * @param {String} name * @param {Boolean} force * @return {ClassList} * @api public */ ClassList.prototype.toggle = function(name, force){ // classList if (this.list) { if ("undefined" !== typeof force) { if (force !== this.list.toggle(name, force)) { this.list.toggle(name); // toggle again to correct } } else { this.list.toggle(name); } return this; } // fallback if ("undefined" !== typeof force) { if (!force) { this.remove(name); } else { this.add(name); } } else { if (this.has(name)) { this.remove(name); } else { this.add(name); } } return this; }; /** * Return an array of classes. * * @return {Array} * @api public */ ClassList.prototype.array = function(){ var str = this.el.className.replace(/^\s+|\s+$/g, ''); var arr = str.split(re); if ('' === arr[0]) arr.shift(); return arr; }; /** * Check if class `name` is present. * * @param {String} name * @return {ClassList} * @api public */ ClassList.prototype.has = ClassList.prototype.contains = function(name){ return this.list ? this.list.contains(name) : !! ~index(this.array(), name); }; }); require.register("segmentio-extend/index.js", function(exports, require, module){ module.exports = function extend (object) { // Takes an unlimited number of extenders. var args = Array.prototype.slice.call(arguments, 1); // For each extender, copy their properties on our object. for (var i = 0, source; source = args[i]; i++) { if (!source) continue; for (var property in source) { object[property] = source[property]; } } return object; }; }); require.register("component-indexof/index.js", function(exports, require, module){ module.exports = function(arr, obj){ if (arr.indexOf) return arr.indexOf(obj); for (var i = 0; i < arr.length; ++i) { if (arr[i] === obj) return i; } return -1; }; }); require.register("component-event/index.js", function(exports, require, module){ var bind = window.addEventListener ? 'addEventListener' : 'attachEvent', unbind = window.removeEventListener ? 'removeEventListener' : 'detachEvent', prefix = bind !== 'addEventListener' ? 'on' : ''; /** * Bind `el` event `type` to `fn`. * * @param {Element} el * @param {String} type * @param {Function} fn * @param {Boolean} capture * @return {Function} * @api public */ exports.bind = function(el, type, fn, capture){ el[bind](prefix + type, fn, capture || false); return fn; }; /** * Unbind `el` event `type`'s callback `fn`. * * @param {Element} el * @param {String} type * @param {Function} fn * @param {Boolean} capture * @return {Function} * @api public */ exports.unbind = function(el, type, fn, capture){ el[unbind](prefix + type, fn, capture || false); return fn; }; }); require.register("javve-to-array/index.js", function(exports, require, module){ /** * Convert an array-like object into an `Array`. * If `collection` is already an `Array`, then will return a clone of `collection`. * * @param {Array | Mixed} collection An `Array` or array-like object to convert e.g. `arguments` or `NodeList` * @return {Array} Naive conversion of `collection` to a new `Array`. * @api public */ module.exports = function toArray(collection) { if (typeof collection === 'undefined') return [] if (collection === null) return [null] if (collection === window) return [window] if (typeof collection === 'string') return [collection] if (collection instanceof Array) return collection if (typeof collection.length != 'number') return [collection] if (typeof collection === 'function') return [collection] <|fim▁hole|> if (Object.prototype.hasOwnProperty.call(collection, i) || i in collection) { arr.push(collection[i]) } } if (!arr.length) return [] return arr } }); require.register("javve-events/index.js", function(exports, require, module){ var events = require('event'), toArray = require('to-array'); /** * Bind `el` event `type` to `fn`. * * @param {Element} el, NodeList, HTMLCollection or Array * @param {String} type * @param {Function} fn * @param {Boolean} capture * @api public */ exports.bind = function(el, type, fn, capture){ el = toArray(el); for ( var i = 0; i < el.length; i++ ) { events.bind(el[i], type, fn, capture); } }; /** * Unbind `el` event `type`'s callback `fn`. * * @param {Element} el, NodeList, HTMLCollection or Array * @param {String} type * @param {Function} fn * @param {Boolean} capture * @api public */ exports.unbind = function(el, type, fn, capture){ el = toArray(el); for ( var i = 0; i < el.length; i++ ) { events.unbind(el[i], type, fn, capture); } }; }); require.register("javve-get-by-class/index.js", function(exports, require, module){ /** * Find all elements with class `className` inside `container`. * Use `single = true` to increase performance in older browsers * when only one element is needed. * * @param {String} className * @param {Element} container * @param {Boolean} single * @api public */ module.exports = (function() { if (document.getElementsByClassName) { return function(container, className, single) { if (single) { return container.getElementsByClassName(className)[0]; } else { return container.getElementsByClassName(className); } }; } else if (document.querySelector) { return function(container, className, single) { className = '.' + className; if (single) { return container.querySelector(className); } else { return container.querySelectorAll(className); } }; } else { return function(container, className, single) { var classElements = [], tag = '*'; if (container == null) { container = document; } var els = container.getElementsByTagName(tag); var elsLen = els.length; var pattern = new RegExp("(^|\\s)"+className+"(\\s|$)"); for (var i = 0, j = 0; i < elsLen; i++) { if ( pattern.test(els[i].className) ) { if (single) { return els[i]; } else { classElements[j] = els[i]; j++; } } } return classElements; }; } })(); }); require.register("javve-get-attribute/index.js", function(exports, require, module){ /** * Return the value for `attr` at `element`. * * @param {Element} el * @param {String} attr * @api public */ module.exports = function(el, attr) { var result = (el.getAttribute && el.getAttribute(attr)) || null; if( !result ) { var attrs = el.attributes; var length = attrs.length; for(var i = 0; i < length; i++) { if (attr[i] !== undefined) { if(attr[i].nodeName === attr) { result = attr[i].nodeValue; } } } } return result; } }); require.register("javve-natural-sort/index.js", function(exports, require, module){ /* * Natural Sort algorithm for Javascript - Version 0.7 - Released under MIT license * Author: Jim Palmer (based on chunking idea from Dave Koelle) */ module.exports = function(a, b, options) { var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi, sre = /(^[ ]*|[ ]*$)/g, dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/, hre = /^0x[0-9a-f]+$/i, ore = /^0/, options = options || {}, i = function(s) { return options.insensitive && (''+s).toLowerCase() || ''+s }, // convert all to strings strip whitespace x = i(a).replace(sre, '') || '', y = i(b).replace(sre, '') || '', // chunk/tokenize xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'), yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'), // numeric, hex or date detection xD = parseInt(x.match(hre)) || (xN.length != 1 && x.match(dre) && Date.parse(x)), yD = parseInt(y.match(hre)) || xD && y.match(dre) && Date.parse(y) || null, oFxNcL, oFyNcL, mult = options.desc ? -1 : 1; // first try and sort Hex codes or Dates if (yD) if ( xD < yD ) return -1 * mult; else if ( xD > yD ) return 1 * mult; // natural sorting through split numeric strings and default strings for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) { // find floats not starting with '0', string or 0 if not defined (Clint Priest) oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0; oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0; // handle numeric vs string comparison - number < string - (Kyle Adams) if (isNaN(oFxNcL) !== isNaN(oFyNcL)) { return (isNaN(oFxNcL)) ? 1 : -1; } // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2' else if (typeof oFxNcL !== typeof oFyNcL) { oFxNcL += ''; oFyNcL += ''; } if (oFxNcL < oFyNcL) return -1 * mult; if (oFxNcL > oFyNcL) return 1 * mult; } return 0; }; /* var defaultSort = getSortFunction(); module.exports = function(a, b, options) { if (arguments.length == 1) { options = a; return getSortFunction(options); } else { return defaultSort(a,b); } } */ }); require.register("javve-to-string/index.js", function(exports, require, module){ module.exports = function(s) { s = (s === undefined) ? "" : s; s = (s === null) ? "" : s; s = s.toString(); return s; }; }); require.register("component-type/index.js", function(exports, require, module){ /** * toString ref. */ var toString = Object.prototype.toString; /** * Return the type of `val`. * * @param {Mixed} val * @return {String} * @api public */ module.exports = function(val){ switch (toString.call(val)) { case '[object Date]': return 'date'; case '[object RegExp]': return 'regexp'; case '[object Arguments]': return 'arguments'; case '[object Array]': return 'array'; case '[object Error]': return 'error'; } if (val === null) return 'null'; if (val === undefined) return 'undefined'; if (val !== val) return 'nan'; if (val && val.nodeType === 1) return 'element'; return typeof val.valueOf(); }; }); require.register("list.js/index.js", function(exports, require, module){ /* ListJS with beta 1.0.0 By Jonny Strömberg (www.jonnystromberg.com, www.listjs.com) */ (function( window, undefined ) { "use strict"; var document = window.document, getByClass = require('get-by-class'), extend = require('extend'), indexOf = require('indexof'); var List = function(id, options, values) { var self = this, init, Item = require('./src/item')(self), addAsync = require('./src/add-async')(self), parse = require('./src/parse')(self); init = { start: function() { self.listClass = "list"; self.searchClass = "search"; self.sortClass = "sort"; self.page = 200; self.i = 1; self.items = []; self.visibleItems = []; self.matchingItems = []; self.searched = false; self.filtered = false; self.handlers = { 'updated': [] }; self.plugins = {}; self.helpers = { getByClass: getByClass, extend: extend, indexOf: indexOf }; extend(self, options); self.listContainer = (typeof(id) === 'string') ? document.getElementById(id) : id; if (!self.listContainer) { return; } self.list = getByClass(self.listContainer, self.listClass, true); self.templater = require('./src/templater')(self); self.search = require('./src/search')(self); self.filter = require('./src/filter')(self); self.sort = require('./src/sort')(self); this.items(); self.update(); this.plugins(); }, items: function() { parse(self.list); if (values !== undefined) { self.add(values); } }, plugins: function() { for (var i = 0; i < self.plugins.length; i++) { var plugin = self.plugins[i]; self[plugin.name] = plugin; plugin.init(self); } } }; /* * Add object to list */ this.add = function(values, callback) { if (callback) { addAsync(values, callback); return; } var added = [], notCreate = false; if (values[0] === undefined){ values = [values]; } for (var i = 0, il = values.length; i < il; i++) { var item = null; if (values[i] instanceof Item) { item = values[i]; item.reload(); } else { notCreate = (self.items.length > self.page) ? true : false; item = new Item(values[i], undefined, notCreate); } self.items.push(item); added.push(item); } self.update(); return added; }; this.show = function(i, page) { this.i = i; this.page = page; self.update(); return self; }; /* Removes object from list. * Loops through the list and removes objects where * property "valuename" === value */ this.remove = function(valueName, value, options) { var found = 0; for (var i = 0, il = self.items.length; i < il; i++) { if (self.items[i].values()[valueName] == value) { self.templater.remove(self.items[i], options); self.items.splice(i,1); il--; i--; found++; } } self.update(); return found; }; /* Gets the objects in the list which * property "valueName" === value */ this.get = function(valueName, value) { var matchedItems = []; for (var i = 0, il = self.items.length; i < il; i++) { var item = self.items[i]; if (item.values()[valueName] == value) { matchedItems.push(item); } } return matchedItems; }; /* * Get size of the list */ this.size = function() { return self.items.length; }; /* * Removes all items from the list */ this.clear = function() { self.templater.clear(); self.items = []; return self; }; this.on = function(event, callback) { self.handlers[event].push(callback); return self; }; this.off = function(event, callback) { var e = self.handlers[event]; var index = indexOf(e, callback); if (index > -1) { e.splice(index, 1); } return self; }; this.trigger = function(event) { var i = self.handlers[event].length; while(i--) { self.handlers[event][i](self); } return self; }; this.reset = { filter: function() { var is = self.items, il = is.length; while (il--) { is[il].filtered = false; } return self; }, search: function() { var is = self.items, il = is.length; while (il--) { is[il].found = false; } return self; } }; this.update = function() { var is = self.items, il = is.length; self.visibleItems = []; self.matchingItems = []; self.templater.clear(); for (var i = 0; i < il; i++) { if (is[i].matching() && ((self.matchingItems.length+1) >= self.i && self.visibleItems.length < self.page)) { is[i].show(); self.visibleItems.push(is[i]); self.matchingItems.push(is[i]); } else if (is[i].matching()) { self.matchingItems.push(is[i]); is[i].hide(); } else { is[i].hide(); } } self.trigger('updated'); return self; }; init.start(); }; module.exports = List; })(window); }); require.register("list.js/src/search.js", function(exports, require, module){ var events = require('events'), getByClass = require('get-by-class'), toString = require('to-string'); module.exports = function(list) { var item, text, columns, searchString, customSearch; var prepare = { resetList: function() { list.i = 1; list.templater.clear(); customSearch = undefined; }, setOptions: function(args) { if (args.length == 2 && args[1] instanceof Array) { columns = args[1]; } else if (args.length == 2 && typeof(args[1]) == "function") { customSearch = args[1]; } else if (args.length == 3) { columns = args[1]; customSearch = args[2]; } }, setColumns: function() { columns = (columns === undefined) ? prepare.toArray(list.items[0].values()) : columns; }, setSearchString: function(s) { s = toString(s).toLowerCase(); s = s.replace(/[-[\]{}()*+?.,\\^$|#]/g, "\\$&"); // Escape regular expression characters searchString = s; }, toArray: function(values) { var tmpColumn = []; for (var name in values) { tmpColumn.push(name); } return tmpColumn; } }; var search = { list: function() { for (var k = 0, kl = list.items.length; k < kl; k++) { search.item(list.items[k]); } }, item: function(item) { item.found = false; for (var j = 0, jl = columns.length; j < jl; j++) { if (search.values(item.values(), columns[j])) { item.found = true; return; } } }, values: function(values, column) { if (values.hasOwnProperty(column)) { text = toString(values[column]).toLowerCase(); if ((searchString !== "") && (text.search(searchString) > -1)) { return true; } } return false; }, reset: function() { list.reset.search(); list.searched = false; } }; var searchMethod = function(str) { list.trigger('searchStart'); prepare.resetList(); prepare.setSearchString(str); prepare.setOptions(arguments); // str, cols|searchFunction, searchFunction prepare.setColumns(); if (searchString === "" ) { search.reset(); } else { list.searched = true; if (customSearch) { customSearch(searchString, columns); } else { search.list(); } } list.update(); list.trigger('searchComplete'); return list.visibleItems; }; list.handlers.searchStart = list.handlers.searchStart || []; list.handlers.searchComplete = list.handlers.searchComplete || []; events.bind(getByClass(list.listContainer, list.searchClass), 'keyup', function(e) { var target = e.target || e.srcElement; // IE have srcElement searchMethod(target.value); }); list.helpers.toString = toString; return searchMethod; }; }); require.register("list.js/src/sort.js", function(exports, require, module){ var naturalSort = require('natural-sort'), classes = require('classes'), events = require('events'), getByClass = require('get-by-class'), getAttribute = require('get-attribute'); module.exports = function(list) { list.sortFunction = list.sortFunction || function(itemA, itemB, options) { options.desc = options.order == "desc" ? true : false; // Natural sort uses this format return naturalSort(itemA.values()[options.valueName], itemB.values()[options.valueName], options); }; var buttons = { els: undefined, clear: function() { for (var i = 0, il = buttons.els.length; i < il; i++) { classes(buttons.els[i]).remove('asc'); classes(buttons.els[i]).remove('desc'); } }, getOrder: function(btn) { var predefinedOrder = getAttribute(btn, 'data-order'); if (predefinedOrder == "asc" || predefinedOrder == "desc") { return predefinedOrder; } else if (classes(btn).has('desc')) { return "asc"; } else if (classes(btn).has('asc')) { return "desc"; } else { return "asc"; } }, getInSensitive: function(btn, options) { var insensitive = getAttribute(btn, 'data-insensitive'); if (insensitive === "true") { options.insensitive = true; } else { options.insensitive = false; } }, setOrder: function(options) { for (var i = 0, il = buttons.els.length; i < il; i++) { var btn = buttons.els[i]; if (getAttribute(btn, 'data-sort') !== options.valueName) { continue; } var predefinedOrder = getAttribute(btn, 'data-order'); if (predefinedOrder == "asc" || predefinedOrder == "desc") { if (predefinedOrder == options.order) { classes(btn).add(options.order); } } else { classes(btn).add(options.order); } } } }; var sort = function() { list.trigger('sortStart'); options = {}; var target = arguments[0].currentTarget || arguments[0].srcElement || undefined; if (target) { options.valueName = getAttribute(target, 'data-sort'); buttons.getInSensitive(target, options); options.order = buttons.getOrder(target); } else { options = arguments[1] || options; options.valueName = arguments[0]; options.order = options.order || "asc"; options.insensitive = (typeof options.insensitive == "undefined") ? true : options.insensitive; } buttons.clear(); buttons.setOrder(options); options.sortFunction = options.sortFunction || list.sortFunction; list.items.sort(function(a, b) { return options.sortFunction(a, b, options); }); list.update(); list.trigger('sortComplete'); }; // Add handlers list.handlers.sortStart = list.handlers.sortStart || []; list.handlers.sortComplete = list.handlers.sortComplete || []; buttons.els = getByClass(list.listContainer, list.sortClass); events.bind(buttons.els, 'click', sort); list.on('searchStart', buttons.clear); list.on('filterStart', buttons.clear); // Helpers list.helpers.classes = classes; list.helpers.naturalSort = naturalSort; list.helpers.events = events; list.helpers.getAttribute = getAttribute; return sort; }; }); require.register("list.js/src/item.js", function(exports, require, module){ module.exports = function(list) { return function(initValues, element, notCreate) { var item = this; this._values = {}; this.found = false; // Show if list.searched == true and this.found == true this.filtered = false;// Show if list.filtered == true and this.filtered == true var init = function(initValues, element, notCreate) { if (element === undefined) { if (notCreate) { item.values(initValues, notCreate); } else { item.values(initValues); } } else { item.elm = element; var values = list.templater.get(item, initValues); item.values(values); } }; this.values = function(newValues, notCreate) { if (newValues !== undefined) { for(var name in newValues) { item._values[name] = newValues[name]; } if (notCreate !== true) { list.templater.set(item, item.values()); } } else { return item._values; } }; this.show = function() { list.templater.show(item); }; this.hide = function() { list.templater.hide(item); }; this.matching = function() { return ( (list.filtered && list.searched && item.found && item.filtered) || (list.filtered && !list.searched && item.filtered) || (!list.filtered && list.searched && item.found) || (!list.filtered && !list.searched) ); }; this.visible = function() { return (item.elm.parentNode == list.list) ? true : false; }; init(initValues, element, notCreate); }; }; }); require.register("list.js/src/templater.js", function(exports, require, module){ var getByClass = require('get-by-class'); var Templater = function(list) { var itemSource = getItemSource(list.item), templater = this; function getItemSource(item) { if (item === undefined) { var nodes = list.list.childNodes, items = []; for (var i = 0, il = nodes.length; i < il; i++) { // Only textnodes have a data attribute if (nodes[i].data === undefined) { return nodes[i]; } } return null; } else if (item.indexOf("<") !== -1) { // Try create html element of list, do not work for tables!! var div = document.createElement('div'); div.innerHTML = item; return div.firstChild; } else { return document.getElementById(list.item); } } /* Get values from element */ this.get = function(item, valueNames) { templater.create(item); var values = {}; for(var i = 0, il = valueNames.length; i < il; i++) { var elm = getByClass(item.elm, valueNames[i], true); values[valueNames[i]] = elm ? elm.innerHTML : ""; } return values; }; /* Sets values at element */ this.set = function(item, values) { if (!templater.create(item)) { for(var v in values) { if (values.hasOwnProperty(v)) { // TODO speed up if possible var elm = getByClass(item.elm, v, true); if (elm) { /* src attribute for image tag & text for other tags */ if (elm.tagName === "IMG" && values[v] !== "") { elm.src = values[v]; } else { elm.innerHTML = values[v]; } } } } } }; this.create = function(item) { if (item.elm !== undefined) { return false; } /* If item source does not exists, use the first item in list as source for new items */ var newItem = itemSource.cloneNode(true); newItem.removeAttribute('id'); item.elm = newItem; templater.set(item, item.values()); return true; }; this.remove = function(item) { list.list.removeChild(item.elm); }; this.show = function(item) { templater.create(item); list.list.appendChild(item.elm); }; this.hide = function(item) { if (item.elm !== undefined && item.elm.parentNode === list.list) { list.list.removeChild(item.elm); } }; this.clear = function() { /* .innerHTML = ''; fucks up IE */ if (list.list.hasChildNodes()) { while (list.list.childNodes.length >= 1) { list.list.removeChild(list.list.firstChild); } } }; }; module.exports = function(list) { return new Templater(list); }; }); require.register("list.js/src/filter.js", function(exports, require, module){ module.exports = function(list) { // Add handlers list.handlers.filterStart = list.handlers.filterStart || []; list.handlers.filterComplete = list.handlers.filterComplete || []; return function(filterFunction) { list.trigger('filterStart'); list.i = 1; // Reset paging list.reset.filter(); if (filterFunction === undefined) { list.filtered = false; } else { list.filtered = true; var is = list.items; for (var i = 0, il = is.length; i < il; i++) { var item = is[i]; if (filterFunction(item)) { item.filtered = true; } else { item.filtered = false; } } } list.update(); list.trigger('filterComplete'); return list.visibleItems; }; }; }); require.register("list.js/src/add-async.js", function(exports, require, module){ module.exports = function(list) { return function(values, callback, items) { var valuesToAdd = values.splice(0, 100); items = items || []; items = items.concat(list.add(valuesToAdd)); if (values.length > 0) { setTimeout(function() { addAsync(values, callback, items); }, 10); } else { list.update(); callback(items); } }; }; }); require.register("list.js/src/parse.js", function(exports, require, module){ module.exports = function(list) { var Item = require('./item')(list); var getChildren = function(parent) { var nodes = parent.childNodes, items = []; for (var i = 0, il = nodes.length; i < il; i++) { // Only textnodes have a data attribute if (nodes[i].data === undefined) { items.push(nodes[i]); } } return items; }; var parse = function(itemElements, valueNames) { for (var i = 0, il = itemElements.length; i < il; i++) { list.items.push(new Item(valueNames, itemElements[i])); } }; var parseAsync = function(itemElements, valueNames) { var itemsToIndex = itemElements.splice(0, 100); // TODO: If < 100 items, what happens in IE etc? parse(itemsToIndex, valueNames); if (itemElements.length > 0) { setTimeout(function() { init.items.indexAsync(itemElements, valueNames); }, 10); } else { list.update(); // TODO: Add indexed callback } }; return function() { var itemsToIndex = getChildren(list.list), valueNames = list.valueNames; if (list.indexAsync) { parseAsync(itemsToIndex, valueNames); } else { parse(itemsToIndex, valueNames); } }; }; }); require.alias("component-classes/index.js", "list.js/deps/classes/index.js"); require.alias("component-classes/index.js", "classes/index.js"); require.alias("component-indexof/index.js", "component-classes/deps/indexof/index.js"); require.alias("segmentio-extend/index.js", "list.js/deps/extend/index.js"); require.alias("segmentio-extend/index.js", "extend/index.js"); require.alias("component-indexof/index.js", "list.js/deps/indexof/index.js"); require.alias("component-indexof/index.js", "indexof/index.js"); require.alias("javve-events/index.js", "list.js/deps/events/index.js"); require.alias("javve-events/index.js", "events/index.js"); require.alias("component-event/index.js", "javve-events/deps/event/index.js"); require.alias("javve-to-array/index.js", "javve-events/deps/to-array/index.js"); require.alias("javve-get-by-class/index.js", "list.js/deps/get-by-class/index.js"); require.alias("javve-get-by-class/index.js", "get-by-class/index.js"); require.alias("javve-get-attribute/index.js", "list.js/deps/get-attribute/index.js"); require.alias("javve-get-attribute/index.js", "get-attribute/index.js"); require.alias("javve-natural-sort/index.js", "list.js/deps/natural-sort/index.js"); require.alias("javve-natural-sort/index.js", "natural-sort/index.js"); require.alias("javve-to-string/index.js", "list.js/deps/to-string/index.js"); require.alias("javve-to-string/index.js", "list.js/deps/to-string/index.js"); require.alias("javve-to-string/index.js", "to-string/index.js"); require.alias("javve-to-string/index.js", "javve-to-string/index.js"); require.alias("component-type/index.js", "list.js/deps/type/index.js"); require.alias("component-type/index.js", "type/index.js"); if (typeof exports == "object") { module.exports = require("list.js"); } else if (typeof define == "function" && define.amd) { define(function(){ return require("list.js"); }); } else { this["List"] = require("list.js"); }})();<|fim▁end|>
var arr = [] for (var i = 0; i < collection.length; i++) {
<|file_name|>0001_initial.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-08 09:18 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import tinymce.models class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Post', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('comment', tinymce.models.HTMLField(blank=True)), ('created_at', models.DateTimeField(default=django.utils.timezone.now)), ], ), migrations.CreateModel( name='Subject', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)),<|fim▁hole|> ('description', tinymce.models.HTMLField()), ], ), migrations.CreateModel( name='Thread', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('created_at', models.DateTimeField(default=django.utils.timezone.now)), ('Subject', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='threads', to='threads.Subject')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='threads', to=settings.AUTH_USER_MODEL)), ], ), migrations.AddField( model_name='post', name='thread', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='posts', to='threads.Thread'), ), migrations.AddField( model_name='post', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='posts', to=settings.AUTH_USER_MODEL), ), ]<|fim▁end|>
<|file_name|>index.js<|end_file_name|><|fim▁begin|>import React, { PropTypes, } from 'react'; import { StyleSheet, View, Text, } from 'react-native'; const styles = StyleSheet.create({ all: { paddingHorizontal: 10,<|fim▁hole|> paddingVertical: 5, }, text: { fontSize: 12, color: '#666', }, }); function ListItemTitle(props) { return ( <View style={styles.all}> <Text style={styles.text} > {props.text} </Text> </View> ); } ListItemTitle.propTypes = { text: PropTypes.string, }; ListItemTitle.defaultProps = { text: '', }; export default ListItemTitle;<|fim▁end|>
<|file_name|>game.js<|end_file_name|><|fim▁begin|>/* global Cervus */ const material = new Cervus.materials.PhongMaterial({ requires: [ Cervus.components.Render, Cervus.components.Transform ], texture: Cervus.core.image_loader('../textures/4.png'), normal_map: Cervus.core.image_loader('../textures/normal2.jpg') }); const phong_material = new Cervus.materials.PhongMaterial({ requires: [ Cervus.components.Render, Cervus.components.Transform ] }); const game = new Cervus.core.Game({ width: window.innerWidth, height: window.innerHeight, // clear_color: 'f0f' // fps: 1 }); game.camera.get_component(Cervus.components.Move).keyboard_controlled = true; // game.camera.get_component(Cervus.components.Move).mouse_controlled = true; // By default all entities face the user. // Rotate the camera to see the scene. const camera_transform = game.camera.get_component(Cervus.components.Transform); camera_transform.position = [0, 2, 5]; camera_transform.rotate_rl(Math.PI); // game.camera.keyboard_controlled = true; const plane = new Cervus.shapes.Plane(); const plane_transform = plane.get_component(Cervus.components.Transform); const plane_render = plane.get_component(Cervus.components.Render); plane_transform.scale = [100, 1, 100]; plane_render.material = phong_material; plane_render.color = "#eeeeee";<|fim▁hole|> const cube = new Cervus.shapes.Box(); const cube_transform = cube.get_component(Cervus.components.Transform); const cube_render = cube.get_component(Cervus.components.Render); cube_render.material = material; cube_render.color = "#00ff00"; cube_transform.position = [0, 0.5, -1]; const group = new Cervus.core.Entity({ components: [ new Cervus.components.Transform() ] }); game.add(group); group.add(cube); // game.on('tick', () => { // group.get_component(Cervus.components.Transform).rotate_rl(16/1000); game.light.get_component(Cervus.components.Transform).position = game.camera.get_component(Cervus.components.Transform).position; });<|fim▁end|>
game.add(plane);
<|file_name|>helical_joint.rs<|end_file_name|><|fim▁begin|>use na::{self, DVectorSliceMut, Isometry3, RealField, Translation3, Unit, Vector3}; use crate::joint::{Joint, JointMotor, RevoluteJoint, UnitJoint}; use crate::math::{JacobianSliceMut, Velocity}; use crate::object::{BodyPartHandle, Multibody, MultibodyLink}; use crate::solver::{ConstraintSet, GenericNonlinearConstraint, IntegrationParameters}; /// A joint that allows one degree of freedom between two multibody links. /// /// The degree of freedom is the combination of a rotation and a translation along the same axis. /// Both rotational and translational motions are coupled to generate a screw motion. #[derive(Copy, Clone, Debug)] pub struct HelicalJoint<N: RealField> { revo: RevoluteJoint<N>, pitch: N, } impl<N: RealField> HelicalJoint<N> { /// Create an helical joint with the given axis and initial angle. /// /// The `pitch` controls how much translation is generated for how much rotation. /// In particular, the translational displacement along `axis` is given by `angle * pitch`. pub fn new(axis: Unit<Vector3<N>>, pitch: N, angle: N) -> Self { HelicalJoint { revo: RevoluteJoint::new(axis, angle), pitch: pitch, } } /// The translational displacement along the joint axis. pub fn offset(&self) -> N { self.revo.angle() * self.pitch } /// The rotational displacement along the joint axis. pub fn angle(&self) -> N { self.revo.angle() } } impl<N: RealField> Joint<N> for HelicalJoint<N> { #[inline] fn ndofs(&self) -> usize { 1 } fn body_to_parent(&self, parent_shift: &Vector3<N>, body_shift: &Vector3<N>) -> Isometry3<N> { Translation3::from(self.revo.axis().as_ref() * self.revo.angle()) * self.revo.body_to_parent(parent_shift, body_shift) } fn update_jacobians(&mut self, body_shift: &Vector3<N>, vels: &[N]) { self.revo.update_jacobians(body_shift, vels) } fn jacobian(&self, transform: &Isometry3<N>, out: &mut JacobianSliceMut<N>) { let mut jac = *self.revo.local_jacobian(); jac.linear += self.revo.axis().as_ref() * self.pitch; out.copy_from(jac.transformed(transform).as_vector()) } fn jacobian_dot(&self, transform: &Isometry3<N>, out: &mut JacobianSliceMut<N>) { self.revo.jacobian_dot(transform, out) } fn jacobian_dot_veldiff_mul_coordinates( &self, transform: &Isometry3<N>, acc: &[N], out: &mut JacobianSliceMut<N>, ) { self.revo .jacobian_dot_veldiff_mul_coordinates(transform, acc, out) } fn jacobian_mul_coordinates(&self, vels: &[N]) -> Velocity<N> { let mut jac = *self.revo.local_jacobian(); jac.linear += self.revo.axis().as_ref() * self.pitch; jac * vels[0] } fn jacobian_dot_mul_coordinates(&self, vels: &[N]) -> Velocity<N> { self.revo.jacobian_dot_mul_coordinates(vels) } fn default_damping(&self, out: &mut DVectorSliceMut<N>) { out.fill(na::convert(0.1f64)) } fn integrate(&mut self, parameters: &IntegrationParameters<N>, vels: &[N]) { self.revo.integrate(parameters, vels) } fn apply_displacement(&mut self, disp: &[N]) { self.revo.apply_displacement(disp) } #[inline] fn clone(&self) -> Box<dyn Joint<N>> { Box::new(*self) } fn num_velocity_constraints(&self) -> usize { self.revo.num_velocity_constraints() } fn velocity_constraints( &self, parameters: &IntegrationParameters<N>, multibody: &Multibody<N>, link: &MultibodyLink<N>, assembly_id: usize, dof_id: usize, ext_vels: &[N], ground_j_id: &mut usize, jacobians: &mut [N], constraints: &mut ConstraintSet<N, (), (), usize>, ) { // XXX: is this correct even though we don't have the same jacobian? self.revo.velocity_constraints( parameters, multibody, link, assembly_id, dof_id, ext_vels, ground_j_id, jacobians, constraints, ); } fn num_position_constraints(&self) -> usize { // NOTE: we don't test if constraints exist to simplify indexing. 1 } fn position_constraint( &self, _: usize, multibody: &Multibody<N>, link: &MultibodyLink<N>, handle: BodyPartHandle<()>, dof_id: usize, jacobians: &mut [N], ) -> Option<GenericNonlinearConstraint<N, ()>> { // XXX: is this correct even though we don't have the same jacobian? self.revo .position_constraint(0, multibody, link, handle, dof_id, jacobians) } } impl<N: RealField> UnitJoint<N> for HelicalJoint<N> { fn position(&self) -> N { self.revo.angle() } fn motor(&self) -> &JointMotor<N, N> { self.revo.motor() } <|fim▁hole|> } fn max_position(&self) -> Option<N> { self.revo.max_angle() } } revolute_motor_limit_methods!(HelicalJoint, revo);<|fim▁end|>
fn min_position(&self) -> Option<N> { self.revo.min_angle()
<|file_name|>application.js<|end_file_name|><|fim▁begin|>import Ember from "ember"; <|fim▁hole|> } });<|fim▁end|>
export default Ember.Route.extend({ model: function() { return this.store.query('answer', {correct: true});
<|file_name|>purchases.e2e.tests.js<|end_file_name|><|fim▁begin|>'use strict'; describe('Purchases E2E Tests:', function () { describe('Test purchases page', function () { it('Should report missing credentials', function () { browser.get('http://localhost:3000/purchases'); expect(element.all(by.repeater('purchase in purchases')).count()).toEqual(0);<|fim▁hole|><|fim▁end|>
}); }); });
<|file_name|>test_app_extension.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ test ~~~~ Flask-CORS is a simple extension to Flask allowing you to support cross origin resource sharing (CORS) using a simple decorator. :copyright: (c) 2014 by Cory Dolphin. :license: MIT, see LICENSE for more details. """ from tests.base_test import FlaskCorsTestCase, AppConfigTest from tests.test_origins import OriginsTestCase from tests.test_options import OptionsTestCase from flask import Flask, jsonify try: # this is how you would normally import from flask.ext.cors import * except: # support local usage without installed package from flask_cors import * class AppExtensionRegexp(AppConfigTest, OriginsTestCase): def setUp(self): self.app = Flask(__name__) CORS(self.app, resources={ r'/': {}, r'/test_list': {'origins': ["http://foo.com", "http://bar.com"]}, r'/test_string': {'origins': 'http://foo.com'}, r'/test_set': { 'origins': set(["http://foo.com", "http://bar.com"]) }, r'/test_subdomain_regex': { 'origins': r"http?://\w*\.?example\.com:?\d*/?.*" }, r'/test_regex_list': { 'origins': [r".*.example.com", r".*.otherexample.com"] }, r'/test_regex_mixed_list': { 'origins': ["http://example.com", r".*.otherexample.com"] } }) @self.app.route('/') def wildcard(): return 'Welcome!' @self.app.route('/test_list') def test_list(): return 'Welcome!' @self.app.route('/test_string') def test_string(): return 'Welcome!' @self.app.route('/test_set') def test_set(): return 'Welcome!' class AppExtensionList(FlaskCorsTestCase): def setUp(self): self.app = Flask(__name__) CORS(self.app, resources=[r'/test_exposed', r'/test_other_exposed'], origins=['http://foo.com, http://bar.com']) @self.app.route('/test_unexposed') def unexposed(): return 'Not exposed over CORS!' @self.app.route('/test_exposed') def exposed1(): return 'Welcome!' @self.app.route('/test_other_exposed') def exposed2(): return 'Welcome!' def test_exposed(self): for resp in self.iter_responses('/test_exposed'): self.assertEqual(resp.status_code, 200) self.assertEqual(resp.headers.get(ACL_ORIGIN), 'http://foo.com, http://bar.com') def test_other_exposed(self): for resp in self.iter_responses('/test_other_exposed'): self.assertEqual(resp.status_code, 200) self.assertEqual(resp.headers.get(ACL_ORIGIN), 'http://foo.com, http://bar.com') <|fim▁hole|> def test_unexposed(self): for resp in self.iter_responses('/test_unexposed'): self.assertEqual(resp.status_code, 200) self.assertFalse(ACL_ORIGIN in resp.headers) class AppExtensionString(FlaskCorsTestCase): def setUp(self): self.app = Flask(__name__) CORS(self.app, resources=r'/api/*', headers='Content-Type', expose_headers='X-Total-Count') @self.app.route('/api/v1/foo') def exposed1(): return jsonify(success=True) @self.app.route('/api/v1/bar') def exposed2(): return jsonify(success=True) @self.app.route('/api/v1/special') @cross_origin(origins='http://foo.com') def overridden(): return jsonify(special=True) @self.app.route('/') def index(): return 'Welcome' def test_exposed(self): for path in '/api/v1/foo', '/api/v1/bar': for resp in self.iter_responses(path): self.assertEqual(resp.status_code, 200) self.assertEqual(resp.headers.get(ACL_ORIGIN), '*') self.assertEqual(resp.headers.get(ACL_EXPOSE_HEADERS), 'X-Total-Count') def test_unexposed(self): for resp in self.iter_responses('/'): self.assertEqual(resp.status_code, 200) self.assertFalse(ACL_ORIGIN in resp.headers) self.assertFalse(ACL_EXPOSE_HEADERS in resp.headers) def test_override(self): for resp in self.iter_responses('/api/v1/special'): self.assertEqual(resp.status_code, 200) self.assertEqual(resp.headers.get(ACL_ORIGIN), 'http://foo.com') self.assertFalse(ACL_EXPOSE_HEADERS in resp.headers) class AppExtensionError(FlaskCorsTestCase): def test_value_error(self): try: app = Flask(__name__) CORS(app, resources=5) self.assertTrue(False, "Should've raised a value error") except ValueError: pass class AppExtensionDefault(FlaskCorsTestCase): def test_default(self): ''' By default match all. ''' self.app = Flask(__name__) CORS(self.app) @self.app.route('/') def index(): return 'Welcome' for resp in self.iter_responses('/'): self.assertEqual(resp.status_code, 200) self.assertTrue(ACL_ORIGIN in resp.headers) class AppExtensionExampleApp(FlaskCorsTestCase): def setUp(self): self.app = Flask(__name__) CORS(self.app, resources={ r'/api/*': {'origins': ['http://blah.com', 'http://foo.bar']} }) @self.app.route('/') def index(): return '' @self.app.route('/api/foo') def test_wildcard(): return '' @self.app.route('/api/') def test_exact_match(): return '' def test_index(self): ''' If regex does not match, do not set CORS ''' for resp in self.iter_responses('/'): self.assertFalse(ACL_ORIGIN in resp.headers) def test_wildcard(self): ''' Match anything matching the path /api/* with an origin of 'http://blah.com' or 'http://foo.bar' ''' for origin in ['http://foo.bar', 'http://blah.com']: for resp in self.iter_responses('/api/foo', origin=origin): self.assertTrue(ACL_ORIGIN in resp.headers) self.assertEqual(origin, resp.headers.get(ACL_ORIGIN)) def test_exact_match(self): ''' Match anything matching the path /api/* with an origin of 'http://blah.com' or 'http://foo.bar' ''' for origin in ['http://foo.bar', 'http://blah.com']: for resp in self.iter_responses('/api/', origin=origin): self.assertTrue(ACL_ORIGIN in resp.headers) self.assertEqual(origin, resp.headers.get(ACL_ORIGIN)) class AppExtensionCompiledRegexp(FlaskCorsTestCase): def test_compiled_regex(self): ''' Ensure we do not error if the user sepcifies an bad regular expression. ''' import re self.app = Flask(__name__) CORS(self.app, resources=re.compile('/api/.*')) @self.app.route('/') def index(): return 'Welcome' @self.app.route('/api/v1') def example(): return 'Welcome' for resp in self.iter_responses('/'): self.assertFalse(ACL_ORIGIN in resp.headers) for resp in self.iter_responses('/api/v1'): self.assertTrue(ACL_ORIGIN in resp.headers) class AppExtensionBadRegexp(FlaskCorsTestCase): def test_value_error(self): ''' Ensure we do not error if the user sepcifies an bad regular expression. ''' self.app = Flask(__name__) CORS(self.app, resources="[") @self.app.route('/') def index(): return 'Welcome' for resp in self.iter_responses('/'): self.assertEqual(resp.status_code, 200) class AppExtensionOptionsTestCase(OptionsTestCase): def __init__(self, *args, **kwargs): super(AppExtensionOptionsTestCase, self).__init__(*args, **kwargs) def setUp(self): self.app = Flask(__name__) CORS(self.app) def test_defaults(self): @self.app.route('/test_default') def test_default(): return 'Welcome!' super(AppExtensionOptionsTestCase, self).test_defaults() def test_no_options_and_not_auto(self): # This test isn't applicable since we the CORS App extension # Doesn't need to add options handling to view functions, since # it is called after_request, and will simply process the autogenerated # Flask OPTIONS response pass def test_options_and_not_auto(self): self.app.config['CORS_AUTOMATIC_OPTIONS'] = False @self.app.route('/test_options_and_not_auto', methods=['OPTIONS']) def test_options_and_not_auto(): return 'Welcome!' super(AppExtensionOptionsTestCase, self).test_options_and_not_auto() class AppExtensionSortedResourcesTestCase(FlaskCorsTestCase): def setUp(self): from flask_cors import _parse_resources self.resources = _parse_resources({ '/foo': {'origins': 'http://foo.com'}, re.compile(r'/.*'): { 'origins': 'http://some-domain.com' }, re.compile(r'/api/v1/.*'): { 'origins': 'http://specific-domain.com' } }) def test_sorted_order(self): def _get_pattern(p): try: return p.pattern except AttributeError: return p self.assertEqual( [_get_pattern(reg) for reg, opt in self.resources], [r'/api/v1/.*', '/foo', r'/.*'] ) if __name__ == "__main__": unittest.main()<|fim▁end|>
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>// #![deny(warnings)]<|fim▁hole|>extern crate futures; extern crate hyper; extern crate hyper_tls; extern crate tokio_core; #[macro_use] extern crate clap; use clap::{Arg, App}; use std::io::{self, Write}; use futures::{Future, Stream}; use tokio_core::reactor::Core; fn main() { let matches = App::new(crate_name!()) .version(crate_version!()) .author(crate_authors!()) .about(crate_description!()) .arg(Arg::with_name("URL") .help("The URL to reach") .required(true) .index(1)) .arg(Arg::with_name("v") .short("v") .multiple(true) .help("Sets the level of verbosity")) .get_matches(); let mut url = matches.value_of("URL").unwrap().parse::<hyper::Uri>().unwrap(); // TODO: this is really sloppy, need a better way to make uri. should i assume https? if url.scheme() == None { url = ("https://".to_string() + matches.value_of("URL").unwrap()).parse::<hyper::Uri>().unwrap(); } if ! ( url.scheme() == Some("http") || url.scheme() == Some("https") ) { println!("This example only works with 'http' URLs."); return; } let mut core = Core::new().unwrap(); let handle = core.handle(); let client = hyper::Client::configure() .connector(hyper_tls::HttpsConnector::new(4, &handle).unwrap()) .build(&handle); let work = client.get(url).and_then(|res| { if matches.occurrences_of("v") > 0 { // TODO: 1.1 is hard coded for now println!("> HTTP/1.1 {}", res.status()); // TODO: Should consider changing Display for hyper::Headers or using regex println!("> {}", res.headers().to_string().replace("\n", "\n> ")); } res.body().for_each(|chunk| { io::stdout().write_all(&chunk).map_err(From::from) }) }).map(|_| { if matches.occurrences_of("v") > 0 { println!("\n\nDone."); } }); core.run(work).unwrap(); }<|fim▁end|>
<|file_name|>cpu.py<|end_file_name|><|fim▁begin|># (void)walker hardware platform support # Copyright (C) 2012-2013 David Holm <[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. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import abc from ..utils import OrderedDict from ..utils import enum Architecture = enum('Test', 'X86', 'X8664', 'Mips', 'Arm', 'Generic', enum_type='Architecture') class Register(object): _register_fmt = {16: '0x%032lX', 10: '0x%020lX', 8: '0x%016lX', 4: '0x%08lX', 2: '0x%04lX', 1: '0x%02lX'} def __init__(self, name): self._name = name def name(self): return self._name def size(self): raise NotImplementedError def value(self): raise NotImplementedError def str(self): if self.value() is not None: return self._register_fmt[self.size()] % self.value() chars_per_byte = 2 return ''.join(['-' * (self.size() * chars_per_byte)]) def create_static_register(register): class StaticRegister(type(register), object):<|fim▁hole|> self._value = register.value() def size(self): return self._size def value(self): return self._value return StaticRegister(register.name()) class Cpu(object): __metaclass__ = abc.ABCMeta def __init__(self, cpu_factory, registers): self._registers = OrderedDict() for group, register_list in registers.iteritems(): registers = OrderedDict([(x.name(), cpu_factory.create_register(self, x)) for x in register_list]) self._registers[group] = registers @classmethod @abc.abstractmethod def architecture(cls): raise NotImplementedError def register(self, name): for register_dict in self._registers.itervalues(): if name in register_dict: return register_dict[name] return None def registers(self): return self._registers.iteritems() @abc.abstractmethod def stack_pointer(self): raise NotImplementedError @abc.abstractmethod def program_counter(self): raise NotImplementedError class CpuFactory(object): __metaclass__ = abc.ABCMeta def create_cpu(self, architecture): assert architecture in _cpu_map return _cpu_map.get(architecture, None)(self) @abc.abstractmethod def create_register(self, cpu, register): raise NotImplementedError class CpuRepository(object): def __init__(self, cpu_factory): self._cpu_factory = cpu_factory self._cpus = {} def get_cpu(self, architecture): if architecture in self._cpus: return self._cpus[architecture] cpu = self._cpu_factory.create_cpu(architecture) self._cpus[architecture] = cpu return cpu def register_cpu(cls): _cpu_map[cls.architecture()] = cls return cls _cpu_map = {}<|fim▁end|>
def __init__(self, name): super(StaticRegister, self).__init__(name) self._size = register.size()
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>pub mod op; use std::any::Any; use std::fmt; use std::fmt::{Display, Formatter}; use spv::Op; use spv::ExtInst; use spv::ExtInstSet; use spv::raw::MemoryBlock; use spv::raw::MemoryBlockResult; use spv::raw::ReadError; use self::op::*; #[derive(Clone, Debug, PartialEq)] pub enum Inst { Sin(Sin), Cos(Cos), } impl ExtInst for Inst { fn get_op(&self) -> &Op { match *self { Inst::Sin(ref op) => op, Inst::Cos(ref op) => op, } } fn as_any(&self) -> &Any { self } fn eq(&self, other: &ExtInst) -> bool { match other.as_any().downcast_ref::<Inst>() { Some(other_glsl450) => PartialEq::eq(self, other_glsl450), None => false, } } } impl Display for Inst { fn fmt(&self, f: &mut Formatter) -> fmt::Result { use self::Inst::*; match *self { Sin(ref op) => op.fmt(f), Cos(ref op) => op.fmt(f), } } } pub struct InstSet; impl ExtInstSet for InstSet { fn get_name(&self) -> &'static str { "GLSL.std.450" } fn read_instruction<'a, 'b>(&'b self, instruction: u32, block: MemoryBlock<'a>) -> MemoryBlockResult<'a, Box<ExtInst>> { let (block, inst) = try!(match instruction { 13 => read_sin(block), 14 => read_cos(block), _ => return Err(ReadError::UnknownExtInstOp(self.get_name(), instruction)), });<|fim▁hole|> Ok((block, Box::new(inst))) } fn duplicate(&self) -> Box<ExtInstSet> { Box::new(InstSet) } } fn read_sin<'a>(block: MemoryBlock<'a>) -> MemoryBlockResult<'a, Inst> { let (block, x) = try!(block.read_op_id()); Ok((block, Inst::Sin(Sin { x: x }))) } fn read_cos(block: MemoryBlock) -> MemoryBlockResult<Inst> { let (block, x) = try!(block.read_op_id()); Ok((block, Inst::Cos(Cos { x: x }))) }<|fim▁end|>
<|file_name|>AgenteHeuristicoBasico.java<|end_file_name|><|fim▁begin|>package co.edu.unal.sistemasinteligentes.ajedrez.agentes; import co.edu.unal.sistemasinteligentes.ajedrez.base.*; import co.edu.unal.sistemasinteligentes.ajedrez.reversi.Tablero; import co.edu.unal.sistemasinteligentes.ajedrez.reversi.Reversi.EstadoReversi; import java.io.PrintStream; /** * Created by jiacontrerasp on 3/30/15. */<|fim▁hole|> private Jugador jugador; private PrintStream output = null; private int niveles; /** * Constructor de AgenteHeuristico1 * @param niveles: niveles de recursión */ public AgenteHeuristicoBasico(int niveles) { super(); this.niveles = niveles; } public AgenteHeuristicoBasico(int niveles, PrintStream output) { super(); this.niveles = niveles; this.output = output; } @Override public Jugador jugador() { return jugador; } @Override public void comienzo(Jugador jugador, Estado estado) { this.jugador = jugador; } @Override public void fin(Estado estado) { // No hay implementación. } @Override public void movimiento(Movimiento movimiento, Estado estado) { if(output != null){ output.println(String.format("Jugador %s mueve %s.", movimiento.jugador(), movimiento)); printEstado(estado); } } protected void printEstado(Estado estado) { if(output != null){ output.println("\t"+ estado.toString().replace("\n", "\n\t")); } } @Override public String toString() { return String.format("Agente Heuristico Basico " + jugador.toString()); } @Override public double darHeuristica(Estado estado) { char miFicha = (jugador().toString() == "JugadorNegras" ? 'N' :'B'); char fichaContrario = (jugador().toString() == "JugadorNegras" ? 'B' :'N'); Tablero tablero = ((EstadoReversi)(estado)).getTablero(); int misFichas = tablero.cantidadFichas(miFicha); int fichasContrario = tablero.cantidadFichas(fichaContrario); return misFichas - fichasContrario; } @Override public int niveles() { return niveles; } @Override public double maximoValorHeuristica() { return 18; } }<|fim▁end|>
public class AgenteHeuristicoBasico extends _AgenteHeuristico {
<|file_name|>website.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # © 2015 Elico corp (www.elico-corp.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import base64 import random import string from binascii import hexlify, unhexlify from openerp import api, fields, models try: from captcha.image import ImageCaptcha except ImportError: pass try: from simplecrypt import decrypt, encrypt except ImportError: pass class Website(models.Model): _inherit = 'website' captcha = fields.Text('Captcha', compute="_captcha", store=False) captcha_crypt_challenge = fields.Char( 'Crypt', compute="_captcha", store=False) captcha_crypt_password = fields.Char( default=lambda self: self._default_salt(), required=True, help=''' The secret value used as the basis for a key. This should be as long as varied as possible. Try to avoid common words.''') captcha_length = fields.Selection( '_captcha_length', default='4', required=True) captcha_chars = fields.Selection( '_captcha_chars', default='digits', required=True) def is_captcha_valid(self, crypt_challenge, response): challenge = decrypt( self.captcha_crypt_password, unhexlify(crypt_challenge)) if response.upper() == challenge: return True return False @api.depends('captcha_length', 'captcha_chars') @api.one def _captcha(self): captcha = ImageCaptcha() captcha_challenge = self._generate_random_str( self._get_captcha_chars(), int(self.captcha_length)) self.captcha_crypt_challenge = hexlify( encrypt(self.captcha_crypt_password, captcha_challenge)) out = captcha.generate(captcha_challenge).getvalue() self.captcha = base64.b64encode(out) def _generate_random_str(self, chars, size): return ''.join(random.choice(chars) for _ in range(size)) def _default_salt(self): return self._generate_random_str(<|fim▁hole|> def _captcha_length(self): return [(str(i), str(i)) for i in range(1, 11)] def _captcha_chars(self): return [ ('digits', 'Digits only'), ('hexadecimal', 'Hexadecimal'), ('all', 'Letters and Digits')] def _get_captcha_chars(self): chars = string.digits if self.captcha_chars == 'hexadecimal': # do not use the default string.hexdigits because it contains # lowercase chars += 'ABCDEF' elif self.captcha_chars == 'all': chars += string.uppercase return chars<|fim▁end|>
string.digits + string.letters + string.punctuation, 100) # generate a random salt
<|file_name|>processing.py<|end_file_name|><|fim▁begin|>""" file: processing.py author: Bryce Mecum ([email protected]) Processes the scientific metadata documents in ./documents for person and organization information. For each document, the script tries to find the person in an existing list. Matches are currently made off of all information available but future versions should be more loose about this. The document a person/organization was found in are also added to that person/organization so the documents belonging to that person/organization can be attributed to them and used in later graph generation activities. """ import os import re import xml.etree.ElementTree as ET from xml.etree.ElementTree import ParseError from d1lod.metadata import eml from d1lod.metadata import dryad from d1lod.metadata import fgdc def processDirectory(job): filenames = os.listdir("%s" % job.directory) i = 0 for filename in filenames: if i % 1000 == 0: print "%d..." % i try: xmldoc = ET.parse("%s/%s" % (job.directory, filename)) except ParseError: continue processDocument(job, xmldoc, filename) i += 1 print "Processed a total of %d documents" % i def detectMetadataFormat(xmldoc): """ Detect the format of the metadata in `xmldoc`. """ root = xmldoc if re.search("eml$", root.tag): return "eml" elif re.search("Dryad", root.tag): return "dryad" elif re.search("metadata", root.tag): return "fgdc" else: return "unknown" def extractCreators(identifier, doc): """ Detect the format of and extract people/organization creators from a document. Arguments: document: str The document's PID doc: An XML document of the scientific metadata Returns: List of records. """ if doc is None: return []<|fim▁hole|> # Detect the format metadata_format = detectMetadataFormat(doc) # Process the document for people/orgs if metadata_format == "eml": records = eml.process(doc, identifier) elif metadata_format == "dryad": records = dryad.process(doc, identifier) elif metadata_format == "fgdc": records = fgdc.process(doc, identifier) else: print "Unknown format." records = [] return records def processDocument(job, xmldoc, filename): """ Process an individual document.""" document = filename # Strip trailing revision number from filename just_pid = re.match("(autogen.\d+)\.\d", document) if just_pid is not None: document = just_pid.groups(0)[0] # Map the filename to its PID if we have a map to go off of if job.identifier_map is not None: if document in job.identifier_map: document = job.identifier_map[document] # Null out the document PID if it's not public if job.public_pids is not None: if document not in job.public_pids: document = '' records = extractCreators(document, xmldoc) if records is not None: saveRecords(job, records) def saveRecords(job, records): """Saves an array of records to disk, according to their filename""" if records is None: return for record in records: # Skip empty records if 'type' not in record: continue if record['type'] == 'person': job.writePerson(record) # Add their organization too (if applicable) if 'organization' in record and len(record['organization']) > 0: org_record = { 'name': record['organization'], 'format': record['format'], 'source': record['source'], 'document': record['document'] } job.writeOrganization(org_record) elif record['type'] == 'organization': job.writeOrganization(record)<|fim▁end|>
<|file_name|>value_exporter.tsickle.ts<|end_file_name|><|fim▁begin|>/** * @fileoverview added by tsickle<|fim▁hole|>export class Clazz {}<|fim▁end|>
* @suppress {checkTypes} checked by tsc */
<|file_name|>ParameterType.py<|end_file_name|><|fim▁begin|>""" Created on Feb 15, 2014 <|fim▁hole|> from sqlalchemy import Column from sqlalchemy.types import SmallInteger from sqlalchemy.types import Unicode from .meta import Base class ParameterType(Base): """ classdocs """ __tablename__ = 'ParameterTypes' _id = Column(SmallInteger, primary_key=True, autoincrement=True, nullable=False, unique=True) name = Column(Unicode(250), nullable=False, unique=True) unit = Column(Unicode(250), nullable=False) def __init__(self, name, unit): self.name = name self.unit = unit @property def id(self): return self._id @property def serialize(self): """Return data in serializeable (dictionary) format""" ret_dict = { 'id': self.id, 'name': self.name, 'unit': self.unit } return ret_dict def __repr__(self): return str(self.serialize) def init_parameter_types(db_session): db_session.add(ParameterType('Temperature', '°C')) db_session.add(ParameterType('Humidity', '%')) db_session.add(ParameterType('Volume', 'Liter')) db_session.add(ParameterType('pH', 'pH')) db_session.add(ParameterType('Conductivity', 'mS'))<|fim▁end|>
@author: alex """
<|file_name|>minicurl.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import sys import urlparse import os import requests def chunkedFetchUrl(url, local_filename=None, **kwargs): """Adapted from http://stackoverflow.com/q/16694907""" if not local_filename: local_filename = url.split('/')[-1] # NOTE the stream=True parameter r = requests.get(url, stream=True, **kwargs) with open(local_filename, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks f.write(chunk) f.flush() return local_filename url=sys.argv[1] parsed=urlparse.urlparse(url) (h,t) = os.path.split(parsed.path) t = t or 'index.html' bits = parsed.netloc.split('.') if len(bits)==3: d=bits[1] elif len(bits)==2: d=bits[0] else: d=parsed.netloc full=os.path.join(d,h[1:]) try: os.makedirs(full)<|fim▁hole|><|fim▁end|>
except Exception as e: print >> sys.stderr, e chunkedFetchUrl(url, local_filename=os.path.join(full, t))
<|file_name|>viewmixins.py<|end_file_name|><|fim▁begin|>import inspect from django.utils.translation import activate class MenuItemMixin: """ This mixins injects attributes that start with the 'menu_' prefix into the context generated by the view it is applied to. This behavior can be used to highlight an item of a navigation component. """ def get_context_data(self, **kwargs): context = super(MenuItemMixin, self).get_context_data(**kwargs) vattrs = inspect.getmembers(self, lambda a: not (inspect.isroutine(a)))<|fim▁hole|> return context class ActivateLegacyLanguageViewMixin: """ """ def activate_legacy_language(self, *args, **kwargs): if "lang" in kwargs and kwargs["lang"] == "en" or self.request.GET.get("lang") == "en": activate("en") else: activate("fr")<|fim▁end|>
menu_kwargs = dict(a for a in vattrs if a[0].startswith("menu_")) context.update(menu_kwargs)
<|file_name|>url.rs<|end_file_name|><|fim▁begin|>// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. //! Cross-platform open url in default browser #[cfg(windows)] mod shell { extern crate winapi; use self::winapi::*; extern "system" { pub fn ShellExecuteA( hwnd: HWND, lpOperation: LPCSTR, lpFile: LPCSTR, lpParameters: LPCSTR, lpDirectory: LPCSTR, nShowCmd: c_int ) -> HINSTANCE; } pub use self::winapi::SW_SHOWNORMAL as Normal; } #[cfg(windows)] pub fn open(url: &str) { use std::ffi::CString; use std::ptr; unsafe { shell::ShellExecuteA(ptr::null_mut(), CString::new("open").unwrap().as_ptr(), CString::new(url.to_owned().replace("\n", "%0A")).unwrap().as_ptr(), ptr::null(), ptr::null(), shell::Normal); } } #[cfg(any(target_os="macos", target_os="freebsd"))] pub fn open(url: &str) { use std;<|fim▁hole|>#[cfg(target_os="linux")] pub fn open(url: &str) { use std; let _ = std::process::Command::new("xdg-open").arg(url).spawn(); }<|fim▁end|>
let _ = std::process::Command::new("open").arg(url).spawn(); }
<|file_name|>strategy.go<|end_file_name|><|fim▁begin|>/* Copyright 2016 The Kubernetes Authors. 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. */ package role import ( "fmt" "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/validation/field" genericapirequest "k8s.io/apiserver/pkg/endpoints/request" "k8s.io/apiserver/pkg/registry/rest" apistorage "k8s.io/apiserver/pkg/storage" "k8s.io/apiserver/pkg/storage/names" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/apis/rbac" "k8s.io/kubernetes/pkg/apis/rbac/validation" ) // strategy implements behavior for Roles type strategy struct { runtime.ObjectTyper names.NameGenerator } // strategy is the default logic that applies when creating and updating // Role objects. var Strategy = strategy{api.Scheme, names.SimpleNameGenerator} // Strategy should implement rest.RESTCreateStrategy var _ rest.RESTCreateStrategy = Strategy // Strategy should implement rest.RESTUpdateStrategy var _ rest.RESTUpdateStrategy = Strategy // NamespaceScoped is true for Roles. func (strategy) NamespaceScoped() bool { return true } // AllowCreateOnUpdate is true for Roles. func (strategy) AllowCreateOnUpdate() bool { return true } // PrepareForCreate clears fields that are not allowed to be set by end users // on creation. func (strategy) PrepareForCreate(ctx genericapirequest.Context, obj runtime.Object) { _ = obj.(*rbac.Role) } // PrepareForUpdate clears fields that are not allowed to be set by end users on update. func (strategy) PrepareForUpdate(ctx genericapirequest.Context, obj, old runtime.Object) { newRole := obj.(*rbac.Role) oldRole := old.(*rbac.Role) _, _ = newRole, oldRole } // Validate validates a new Role. Validation must check for a correct signature. func (strategy) Validate(ctx genericapirequest.Context, obj runtime.Object) field.ErrorList { role := obj.(*rbac.Role) return validation.ValidateRole(role) } // Canonicalize normalizes the object after validation. func (strategy) Canonicalize(obj runtime.Object) { _ = obj.(*rbac.Role) } // ValidateUpdate is the default update validation for an end user. func (strategy) ValidateUpdate(ctx genericapirequest.Context, obj, old runtime.Object) field.ErrorList { newObj := obj.(*rbac.Role) errorList := validation.ValidateRole(newObj) return append(errorList, validation.ValidateRoleUpdate(newObj, old.(*rbac.Role))...) } // If AllowUnconditionalUpdate() is true and the object specified by // the user does not have a resource version, then generic Update() // populates it with the latest version. Else, it checks that the<|fim▁hole|> return true } func (s strategy) Export(ctx genericapirequest.Context, obj runtime.Object, exact bool) error { return nil } // GetAttrs returns labels and fields of a given object for filtering purposes. func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) { role, ok := obj.(*rbac.Role) if !ok { return nil, nil, fmt.Errorf("not a Role") } return labels.Set(role.Labels), SelectableFields(role), nil } // Matcher returns a generic matcher for a given label and field selector. func Matcher(label labels.Selector, field fields.Selector) apistorage.SelectionPredicate { return apistorage.SelectionPredicate{ Label: label, Field: field, GetAttrs: GetAttrs, } } // SelectableFields returns a field set that can be used for filter selection func SelectableFields(obj *rbac.Role) fields.Set { return nil }<|fim▁end|>
// version specified by the user matches the version of latest etcd // object. func (strategy) AllowUnconditionalUpdate() bool {
<|file_name|>hibernate_state.rs<|end_file_name|><|fim▁begin|>// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use kvproto::metapb::Region; use pd_client::{Feature, FeatureGate}; use serde_derive::{Deserialize, Serialize}; /// Because negotiation protocol can't be recognized by old version of binaries, /// so enabling it directly can cause a lot of connection reset. const NEGOTIATION_HIBERNATE: Feature = Feature::require(5, 0, 0); /// Represents state of the group. #[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)] pub enum GroupState { /// The group is working generally, leader keeps /// replicating data to followers. Ordered, /// The group is out of order. Leadership may not be hold.<|fim▁hole|> /// The group is about to be out of order. It leave some /// safe space to avoid stepping chaos too often. PreChaos, /// The group is hibernated. Idle, } #[derive(PartialEq, Debug)] pub enum LeaderState { Awaken, Poll(Vec<u64>), Hibernated, } #[derive(Debug)] pub struct HibernateState { group: GroupState, leader: LeaderState, } impl HibernateState { pub fn ordered() -> HibernateState { HibernateState { group: GroupState::Ordered, leader: LeaderState::Awaken, } } pub fn group_state(&self) -> GroupState { self.group } pub fn reset(&mut self, group_state: GroupState) { self.group = group_state; if group_state != GroupState::Idle { self.leader = LeaderState::Awaken; } } pub fn count_vote(&mut self, from: u64) { if let LeaderState::Poll(v) = &mut self.leader { if !v.contains(&from) { v.push(from); } } } pub fn should_bcast(&self, gate: &FeatureGate) -> bool { gate.can_enable(NEGOTIATION_HIBERNATE) } pub fn maybe_hibernate(&mut self, my_id: u64, region: &Region) -> bool { let peers = region.get_peers(); let v = match &mut self.leader { LeaderState::Awaken => { self.leader = LeaderState::Poll(Vec::with_capacity(peers.len())); return false; } LeaderState::Poll(v) => v, LeaderState::Hibernated => return true, }; // 1 is for leader itself, which is not counted into votes. if v.len() + 1 < peers.len() { return false; } if peers .iter() .all(|p| p.get_id() == my_id || v.contains(&p.get_id())) { self.leader = LeaderState::Hibernated; true } else { false } } }<|fim▁end|>
Chaos,
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf.urls import patterns, include, url from django.contrib import admin from teacher import * from Views.teacher_view import get_teacher_view, get_overview, get_year_overview, get_class_overview, get_assignment_overview from Views.set_exercise import get_set_exercise_page, send_exercise_to_class, get_view_spec_form from Views.authenticate import authenticate_student, authenticate_teacher, check_user_name_exists from Views.login import student_login, teacher_login from Views.register import register_student, register_teacher from Views.student_view import get_student_view from Views.submit_code import submit_student_code, run_self_test from Views.single_exercise_code_view import single_exercise_view from Views.student_grades import student_grades_view from Views.home import home_page from Views.logout import logout_user from Views.view_spec import view_spec, get_exercise_details from Views.settings import teacher_account_settings, delete_teaching_class, student_account_settings, class_settings, change_password, change_email, get_registered_students_in_course, add_new_class, update_class_name, update_course_students, get_student_submission from Views.add_new_exercise import add_new_exercise, create_exercise from Views.view_submissions import view_student_submissions, view_submissions_teacher, get_student_feedback, submit_student_feedback admin.autodiscover() urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^teacher/$', viewSubmissionMark), url(r'^selectable/', include('selectable.urls')), url(r'^teacher/class-settings/manage-class/$', update_course_students),<|fim▁hole|> url(r'^teacher/get-overview/', get_overview), url(r'^teacher/get-year-overview/', get_year_overview), url(r'^teacher/get-class-overview/', get_class_overview), url(r'^teacher/get-assignment-overview/', get_assignment_overview), url(r'^student/changepassword/$', change_password), url(r'^student/view-submissions/get-feedback/(\d+)/$', get_student_feedback), url(r'^teacher/changepassword/$', change_password), url(r'^teacher/get-students-in-class/$', get_registered_students_in_course), url(r'^teacher/add-new-class/$', add_new_class), url(r'^teacher/get-exercise/$', get_exercise_details), url(r'^teacher/update-class-name/', update_class_name), url(r'^teacher/submit-exercise/', send_exercise_to_class), url(r'^student/changeemail/$', change_email), url(r'^teacher/changeemail/$', change_email), url(r'^teacher/account-settings/', teacher_account_settings), url(r'^student/account-settings/', student_account_settings), url(r'^class-settings/', class_settings), url(r'^teacher-view/$', get_teacher_view), url(r'^set-exercise/$', get_set_exercise_page), url(r'^authenticate_student/$', authenticate_student), url(r'^authenticate_teacher/$', authenticate_teacher), url(r'^student-login/$', student_login), url(r'^teacher-login/$', teacher_login), url(r'^register-student/$', register_student), url(r'^register-teacher/$', register_teacher), url(r'^student-view/$', get_student_view), url(r'^submit-code/(\d+)/$', submit_student_code), url(r'^code-single-exercise/(\d+)/$', single_exercise_view), url(r'^student-grades/$', student_grades_view), url(r'^logout/$', logout_user), url(r'^view-spec/$', view_spec), url(r'^check-username/$', check_user_name_exists), url(r'^student/test/self-defined/$', run_self_test), url(r'^teacher/add-new-exercise/$',add_new_exercise), url(r'^teacher/add-new-exercise/submit-exercise/$',create_exercise), url(r'^student/view-submissions/$', view_student_submissions), url(r'^teacher/view-submissions/$', view_submissions_teacher), url(r'^teacher/view-submissions/send-feedback/$', submit_student_feedback), url(r'^teacher/get-student-submission/$', get_student_submission), url(r'^teacher/set-exercise/view-spec-form/(\d+)/$', get_view_spec_form), url(r'^$', home_page) )<|fim▁end|>
url(r'^teacher/class-settings/delete-class/$', delete_teaching_class),
<|file_name|>dynamic_lib.rs<|end_file_name|><|fim▁begin|>// Copyright 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. /*! Dynamic library facilities. A simple wrapper over the platform's dynamic library facilities */ use c_str::ToCStr; use cast; use path; use ops::*; use option::*; use result::*; pub struct DynamicLibrary { priv handle: *u8} impl Drop for DynamicLibrary { fn drop(&mut self) { match dl::check_for_errors_in(|| { unsafe { dl::close(self.handle) } }) { Ok(()) => {}, Err(str) => fail!("{}", str) } } } impl DynamicLibrary { /// Lazily open a dynamic library. When passed None it gives a /// handle to the calling process pub fn open(filename: Option<&path::Path>) -> Result<DynamicLibrary, ~str> { unsafe { let maybe_library = dl::check_for_errors_in(|| { match filename { Some(name) => dl::open_external(name), None => dl::open_internal() } }); // The dynamic library must not be constructed if there is // an error opening the library so the destructor does not // run. match maybe_library { Err(err) => Err(err), Ok(handle) => Ok(DynamicLibrary { handle: handle }) } } } /// Access the value at the symbol of the dynamic library pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<T, ~str> { // This function should have a lifetime constraint of 'a on // T but that feature is still unimplemented let maybe_symbol_value = dl::check_for_errors_in(|| { symbol.with_c_str(|raw_string| { dl::symbol(self.handle, raw_string) }) }); // The value must not be constructed if there is an error so // the destructor does not run. match maybe_symbol_value { Err(err) => Err(err), Ok(symbol_value) => Ok(cast::transmute(symbol_value)) } } } #[cfg(test)] mod test { use super::*; use prelude::*; use libc; #[test] #[ignore(cfg(windows))] // FIXME #8818 #[ignore(cfg(target_os="android"))] // FIXME(#10379) fn test_loading_cosine() { // The math library does not need to be loaded since it is already // statically linked in let libm = match DynamicLibrary::open(None) { Err(error) => fail!("Could not load self as module: {}", error), Ok(libm) => libm }; let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe { match libm.symbol("cos") { Err(error) => fail!("Could not load function cos: {}", error), Ok(cosine) => cosine } }; let argument = 0.0; let expected_result = 1.0; let result = cosine(argument); if result != expected_result { fail!("cos({:?}) != {:?} but equaled {:?} instead", argument, expected_result, result) } } #[test] #[cfg(target_os = "linux")] #[cfg(target_os = "macos")] #[cfg(target_os = "freebsd")] fn test_errors_do_not_crash() { // Open /dev/null as a library to get an error, and make sure // that only causes an error, and not a crash. let path = GenericPath::new("/dev/null"); match DynamicLibrary::open(Some(&path)) { Err(_) => {} Ok(_) => fail!("Successfully opened the empty library.") } } } #[cfg(target_os = "linux")] #[cfg(target_os = "android")] #[cfg(target_os = "macos")] #[cfg(target_os = "freebsd")] pub mod dl { use c_str::ToCStr; use libc; use path; use ptr; use str; use result::*; pub unsafe fn open_external(filename: &path::Path) -> *u8 { filename.with_c_str(|raw_name| { dlopen(raw_name, Lazy as libc::c_int) as *u8<|fim▁hole|> } pub unsafe fn open_internal() -> *u8 { dlopen(ptr::null(), Lazy as libc::c_int) as *u8 } pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, ~str> { use unstable::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT}; static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT; unsafe { // dlerror isn't thread safe, so we need to lock around this entire // sequence let _guard = lock.lock(); let _old_error = dlerror(); let result = f(); let last_error = dlerror(); let ret = if ptr::null() == last_error { Ok(result) } else { Err(str::raw::from_c_str(last_error)) }; ret } } pub unsafe fn symbol(handle: *u8, symbol: *libc::c_char) -> *u8 { dlsym(handle as *libc::c_void, symbol) as *u8 } pub unsafe fn close(handle: *u8) { dlclose(handle as *libc::c_void); () } pub enum RTLD { Lazy = 1, Now = 2, Global = 256, Local = 0, } #[link_name = "dl"] extern { fn dlopen(filename: *libc::c_char, flag: libc::c_int) -> *libc::c_void; fn dlerror() -> *libc::c_char; fn dlsym(handle: *libc::c_void, symbol: *libc::c_char) -> *libc::c_void; fn dlclose(handle: *libc::c_void) -> libc::c_int; } } #[cfg(target_os = "win32")] pub mod dl { use libc; use os; use path::GenericPath; use path; use ptr; use result::{Ok, Err, Result}; pub unsafe fn open_external(filename: &path::Path) -> *u8 { os::win32::as_utf16_p(filename.as_str().unwrap(), |raw_name| { LoadLibraryW(raw_name as *libc::c_void) as *u8 }) } pub unsafe fn open_internal() -> *u8 { let handle = ptr::null(); GetModuleHandleExW(0 as libc::DWORD, ptr::null(), &handle as **libc::c_void); handle as *u8 } pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, ~str> { unsafe { SetLastError(0); let result = f(); let error = os::errno(); if 0 == error { Ok(result) } else { Err(format!("Error code {}", error)) } } } pub unsafe fn symbol(handle: *u8, symbol: *libc::c_char) -> *u8 { GetProcAddress(handle as *libc::c_void, symbol) as *u8 } pub unsafe fn close(handle: *u8) { FreeLibrary(handle as *libc::c_void); () } #[link_name = "kernel32"] extern "system" { fn SetLastError(error: libc::size_t); fn LoadLibraryW(name: *libc::c_void) -> *libc::c_void; fn GetModuleHandleExW(dwFlags: libc::DWORD, name: *u16, handle: **libc::c_void) -> *libc::c_void; fn GetProcAddress(handle: *libc::c_void, name: *libc::c_char) -> *libc::c_void; fn FreeLibrary(handle: *libc::c_void); } }<|fim▁end|>
})
<|file_name|>database_operations.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ **database_operations.py** **Platform:** Windows, Linux, Mac Os X. **Description:** Defines the :class:`DatabaseOperations` Component Interface class and others helper objects. **Others:** """ from __future__ import unicode_literals import os from PyQt4.QtCore import QString from PyQt4.QtGui import QGridLayout from PyQt4.QtGui import QMessageBox import foundations.common import foundations.data_structures import foundations.exceptions import foundations.verbose import sibl_gui.components.core.database.operations import umbra.engine import umbra.ui.widgets.message_box as message_box from manager.QWidget_component import QWidgetComponentFactory __author__ = "Thomas Mansencal" __copyright__ = "Copyright (C) 2008 - 2014 - Thomas Mansencal" __license__ = "GPL V3.0 - http://www.gnu.org/licenses/" __maintainer__ = "Thomas Mansencal" __email__ = "[email protected]" __status__ = "Production" __all__ = ["LOGGER", "COMPONENT_UI_FILE", "DatabaseType", "DatabaseOperations"] LOGGER = foundations.verbose.install_logger() COMPONENT_UI_FILE = os.path.join(os.path.dirname(__file__), "ui", "Database_Operations.ui") class DatabaseType(foundations.data_structures.Structure): """ | Defines a storage object for manipulation methods associated to a given Database type. | See :mod:`sibl_gui.components.core.database.types` module for more informations about the available Database types. """ def __init__(self, **kwargs): """ Initializes the class. :param kwargs: type, get_method, update_content_method, remove_method, model_container, update_location_method :type kwargs: dict """ LOGGER.debug("> Initializing '{0}()' class.".format(self.__class__.__name__)) foundations.data_structures.Structure.__init__(self, **kwargs) class DatabaseOperations(QWidgetComponentFactory(ui_file=COMPONENT_UI_FILE)): """ | Defines the :mod:`sibl_gui.components.addons.database_operations.database_operations` Component Interface class. | It provides various methods to operate on the Database. """ def __init__(self, parent=None, name=None, *args, **kwargs): """ Initializes the class. :param parent: Object parent. :type parent: QObject :param name: Component name. :type name: unicode :param \*args: Arguments. :type \*args: \* :param \*\*kwargs: Keywords arguments. :type \*\*kwargs: \*\* """ LOGGER.debug("> Initializing '{0}()' class.".format(self.__class__.__name__)) super(DatabaseOperations, self).__init__(parent, name, *args, **kwargs) # --- Setting class attributes. --- self.deactivatable = True self.__engine = None self.__settings = None self.__settings_section = None self.__preferences_manager = None self.__ibl_sets_outliner = None self.__templates_outliner = None self.__types = None @property def engine(self): """ Property for **self.__engine** attribute. :return: self.__engine. :rtype: QObject """ return self.__engine @engine.setter @foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError) def engine(self, value): """ Setter for **self.__engine** attribute. :param value: Attribute value. :type value: QObject """ raise foundations.exceptions.ProgrammingError( "{0} | '{1}' attribute is read only!".format(self.__class__.__name__, "engine")) @engine.deleter<|fim▁hole|> """ Deleter for **self.__engine** attribute. """ raise foundations.exceptions.ProgrammingError( "{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "engine")) @property def settings(self): """ Property for **self.__settings** attribute. :return: self.__settings. :rtype: QSettings """ return self.__settings @settings.setter @foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError) def settings(self, value): """ Setter for **self.__settings** attribute. :param value: Attribute value. :type value: QSettings """ raise foundations.exceptions.ProgrammingError( "{0} | '{1}' attribute is read only!".format(self.__class__.__name__, "settings")) @settings.deleter @foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError) def settings(self): """ Deleter for **self.__settings** attribute. """ raise foundations.exceptions.ProgrammingError( "{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "settings")) @property def settings_section(self): """ Property for **self.__settings_section** attribute. :return: self.__settings_section. :rtype: unicode """ return self.__settings_section @settings_section.setter @foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError) def settings_section(self, value): """ Setter for **self.__settings_section** attribute. :param value: Attribute value. :type value: unicode """ raise foundations.exceptions.ProgrammingError( "{0} | '{1}' attribute is read only!".format(self.__class__.__name__, "settings_section")) @settings_section.deleter @foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError) def settings_section(self): """ Deleter for **self.__settings_section** attribute. """ raise foundations.exceptions.ProgrammingError( "{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "settings_section")) @property def preferences_manager(self): """ Property for **self.__preferences_manager** attribute. :return: self.__preferences_manager. :rtype: QWidget """ return self.__preferences_manager @preferences_manager.setter @foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError) def preferences_manager(self, value): """ Setter for **self.__preferences_manager** attribute. :param value: Attribute value. :type value: QWidget """ raise foundations.exceptions.ProgrammingError( "{0} | '{1}' attribute is read only!".format(self.__class__.__name__, "preferences_manager")) @preferences_manager.deleter @foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError) def preferences_manager(self): """ Deleter for **self.__preferences_manager** attribute. """ raise foundations.exceptions.ProgrammingError( "{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "preferences_manager")) @property def ibl_sets_outliner(self): """ Property for **self.__ibl_sets_outliner** attribute. :return: self.__ibl_sets_outliner. :rtype: QWidget """ return self.__ibl_sets_outliner @ibl_sets_outliner.setter @foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError) def ibl_sets_outliner(self, value): """ Setter for **self.__ibl_sets_outliner** attribute. :param value: Attribute value. :type value: QWidget """ raise foundations.exceptions.ProgrammingError( "{0} | '{1}' attribute is read only!".format(self.__class__.__name__, "ibl_sets_outliner")) @ibl_sets_outliner.deleter @foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError) def ibl_sets_outliner(self): """ Deleter for **self.__ibl_sets_outliner** attribute. """ raise foundations.exceptions.ProgrammingError( "{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "ibl_sets_outliner")) @property def templates_outliner(self): """ Property for **self.__templates_outliner** attribute. :return: self.__templates_outliner. :rtype: QWidget """ return self.__templates_outliner @templates_outliner.setter @foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError) def templates_outliner(self, value): """ Setter for **self.__templates_outliner** attribute. :param value: Attribute value. :type value: QWidget """ raise foundations.exceptions.ProgrammingError( "{0} | '{1}' attribute is read only!".format(self.__class__.__name__, "templates_outliner")) @templates_outliner.deleter @foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError) def templates_outliner(self): """ Deleter for **self.__templates_outliner** attribute. """ raise foundations.exceptions.ProgrammingError( "{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "templates_outliner")) @property def types(self): """ Property for **self.__types** attribute. :return: self.__types. :rtype: tuple """ return self.__types @types.setter @foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError) def types(self, value): """ Setter for **self.__types** attribute. :param value: Attribute value. :type value: tuple """ raise foundations.exceptions.ProgrammingError( "{0} | '{1}' attribute is read only!".format(self.__class__.__name__, "types")) @types.deleter @foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError) def types(self): """ Deleter for **self.__types** attribute. """ raise foundations.exceptions.ProgrammingError( "{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "types")) def activate(self, engine): """ Activates the Component. :param engine: Engine to attach the Component to. :type engine: QObject :return: Method success. :rtype: bool """ LOGGER.debug("> Activating '{0}' Component.".format(self.__class__.__name__)) self.__engine = engine self.__settings = self.__engine.settings self.__settings_section = self.name self.__preferences_manager = self.__engine.components_manager["factory.preferences_manager"] self.__ibl_sets_outliner = self.__engine.components_manager["core.ibl_sets_outliner"] self.__templates_outliner = self.__engine.components_manager["core.templates_outliner"] self.__types = (DatabaseType(type="Ibl Set", get_method=sibl_gui.components.core.database.operations.get_ibl_sets, update_content_method=sibl_gui.components.core.database.operations.update_ibl_set_content, remove_method=sibl_gui.components.core.database.operations.remove_ibl_set, model_container=self.__ibl_sets_outliner, update_location_method=self.__ibl_sets_outliner.update_ibl_set_location_ui), DatabaseType(type="Template", get_method=sibl_gui.components.core.database.operations.get_templates, update_content_method=sibl_gui.components.core.database.operations.update_template_content, remove_method=sibl_gui.components.core.database.operations.remove_template, model_container=self.__templates_outliner, update_location_method=self.__templates_outliner.update_template_location_ui)) self.activated = True return True def deactivate(self): """ Deactivates the Component. :return: Method success. :rtype: bool """ LOGGER.debug("> Deactivating '{0}' Component.".format(self.__class__.__name__)) self.__engine = None self.__settings = None self.__settings_section = None self.__preferences_manager = None self.__ibl_sets_outliner = None self.__templates_outliner = None self.activated = False return True def initialize_ui(self): """ Initializes the Component ui. :return: Method success. :rtype: bool """ LOGGER.debug("> Initializing '{0}' Component ui.".format(self.__class__.__name__)) # Signals / Slots. if not self.__engine.parameters.database_read_only: self.Update_Database_pushButton.clicked.connect(self.__Update_Database_pushButton__clicked) self.Remove_Invalid_Data_pushButton.clicked.connect(self.__Remove_Invalid_Data_pushButton__clicked) else: LOGGER.info( "{0} | Database Operations capabilities deactivated by '{1}' command line parameter value!".format( self.__class__.__name__, "database_read_only")) self.initialized_ui = True return True def uninitialize_ui(self): """ Uninitializes the Component ui. :return: Method success. :rtype: bool """ LOGGER.debug("> Uninitializing '{0}' Component ui.".format(self.__class__.__name__)) # Signals / Slots. if not self.__engine.parameters.database_read_only: self.Update_Database_pushButton.clicked.disconnect(self.__Update_Database_pushButton__clicked) self.Remove_Invalid_Data_pushButton.clicked.disconnect(self.__Remove_Invalid_Data_pushButton__clicked) self.initialized_ui = False return True def add_widget(self): """ Adds the Component Widget to the engine. :return: Method success. :rtype: bool """ LOGGER.debug("> Adding '{0}' Component Widget.".format(self.__class__.__name__)) self.__preferences_manager.Others_Preferences_gridLayout.addWidget(self.Database_Operations_groupBox) return True def remove_widget(self): """ Removes the Component Widget from the engine. :return: Method success. :rtype: bool """ LOGGER.debug("> Removing '{0}' Component Widget.".format(self.__class__.__name__)) self.__preferences_manager.findChild(QGridLayout, "Others_Preferences_gridLayout").removeWidget(self) self.Database_Operations_groupBox.setParent(None) return True def __Update_Database_pushButton__clicked(self, checked): """ Defines the slot triggered by **Update_Database_pushButton** Widget when clicked. :param checked: Checked state. :type checked: bool """ self.update_database() def __Remove_Invalid_Data_pushButton__clicked(self, checked): """ Defines the slot triggered by **Remove_Invalid_Data_pushButton** Widget when clicked. :param checked: Checked state. :type checked: bool """ self.remove_invalid_data() @umbra.engine.show_processing("Updating Database ...") def update_database(self): """ | Updates the Database. | Each type defined by :meth:`DatabaseOperations.sibl_gui.components.core.database.types` attribute will have its instances checked and updated by their associated methods. :return: Method success. :rtype: bool """ for type in self.__types: for item in type.get_method(): if foundations.common.path_exists(item.path): if type.update_content_method(item): LOGGER.info("{0} | '{1}' {2} has been updated!".format(self.__class__.__name__, item.name, type.type)) else: choice = message_box.message_box("Question", "Error", "{0} | '{1}' {2} file is missing, would you like to update it's location?".format( self.__class__.__name__, item.name, type.type), QMessageBox.Critical, QMessageBox.Yes | QMessageBox.No, custom_buttons=((QString("No To All"), QMessageBox.RejectRole),)) if choice == 0: break if choice == QMessageBox.Yes: type.update_location_method(item) self.__engine.process_events() type.model_container.refresh_nodes.emit() self.__engine.stop_processing() self.__engine.notifications_manager.notify("{0} | Database update done!".format(self.__class__.__name__)) return True @umbra.engine.show_processing("Removing Invalid Data ...") def remove_invalid_data(self): """ Removes invalid data from the Database. :return: Method success. :rtype: bool """ if message_box.message_box("Question", "Question", "Are you sure you want to remove invalid data from the Database?", buttons=QMessageBox.Yes | QMessageBox.No) == QMessageBox.Yes: for type in self.__types: for item in type.get_method(): if foundations.common.path_exists(item.path): continue LOGGER.info( "{0} | Removing non existing '{1}' {2} from the Database!".format(self.__class__.__name__, item.name, type.type)) type.remove_method(item.id) self.__engine.process_events() type.model_container.refresh_nodes.emit() self.__engine.stop_processing() self.__engine.notifications_manager.notify( "{0} | Invalid data removed from Database!".format(self.__class__.__name__)) return True<|fim▁end|>
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError) def engine(self):
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-faq-views', version='0.1', packages=['faq'], include_package_data=True, license='BSD License', description='A simple Django app to list frequently asked questions.',<|fim▁hole|> classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], )<|fim▁end|>
long_description=README, #url='http://www.example.com', author='Donny Davis', author_email='[email protected]',
<|file_name|>router.js<|end_file_name|><|fim▁begin|>import React, {Component} from 'react'; import {render} from 'react-dom'; import {Router, Route} from 'react-router'; import createBrowserHistory from 'history/lib/createBrowserHistory' import {App} from './App'; import NoMatch from './pages/NoMatch' <|fim▁hole|> return ( <Router history={createBrowserHistory()}> <Route name="home" path="/" component={App}> </Route> <Route path="*" component={NoMatch}/> </Router> ) }<|fim▁end|>
export default() => {
<|file_name|>Album.py<|end_file_name|><|fim▁begin|>from PIL import Image import os.path,os #import pickle #import sqlite3 import hashlib import time import random import logging import copy import threading import itertools from math import ceil from enum import Enum from copy import deepcopy import itertools from lipyc.utility import recursion_protect from lipyc.Version import Versionned from lipyc.config import * from lipyc.utility import check_ext, make_thumbnail from tkinter import messagebox class Album(Versionned): #subalbums not fully implemented def __init__(self, id, scheduler, name=None, datetime=None): super().__init__() self.scheduler = scheduler self.id = id self.name = name self.datetime = datetime if datetime else time.mktime(time.gmtime()) self.subalbums = set() self.thumbnail = None self.files = set() #order by id self.inner_keys = [] #use for inner albums def __deepcopy__(self, memo): new = Album(self.id, self.scheduler, self.name, self.datetime) new.subalbums = deepcopy(self.subalbums) new.thumbnail = deepcopy(self.thumbnail) new.files = deepcopy(self.files) new.inner_keys = deepcopy(self.inner_keys) return new #for copy_to,add_to,move_to def clone(self, new_id): alb = self.__deepcopy__(None) alb.inner_keys.clear() alb.id = new_id return alb def pseudo_clone(self): new = Album(self.id, self.scheduler, self.name, self.datetime) if self.thumbnail: self.scheduler.duplicate(self.thumbnail) new.subalbums = self.subalbums new.thumbnail = self.thumbnail new.files = self.files return new def sql(self): return (self.id, self.name, self.datetime, '|'.join( [ str(alb.id) for alb in self.subalbums] ), self.thumbnail, '|'.join( [ str(afile.id) for afile in self.files] ), '|'.join(self.inner_keys) ) def rename(self, name): self.name = name def add_file(self, _file): self.files.add(_file) if self.thumbnail == None and _file.thumbnail : self.thumbnail = self.scheduler.duplicate_file( _file.thumbnail ) def remove_file(self, _file): self.files.discard(_file) @recursion_protect() def remove_all(self): for album in list(self.subalbums): album.remove_all() self.subalbums.clear() for _file in list(self.files): self.remove_file(_file) self.files.clear() def add_subalbum(self, album): self.subalbums.add( album ) def remove_subalbum(self, album): if album in self.subalbums: if album.thumbnail : self.scheduler.remove_file( album.thumbnail ) self.subalbums.discard( album ) @recursion_protect() def export_to(self, path): location = os.path.join(path, self.name) if not os.path.isdir(location): os.makedirs( location ) for _file in self.files: _file.export_to(location) for album in self.subalbums: album.export_to( location ) @recursion_protect() def lock_files(self):<|fim▁hole|> album.lock_files() def set_thumbnail(self, location): if self.thumbnail : self.scheduler.remove_file(self.thumbnail) if not isinstance(location, str) or check_ext(location, img_exts): #fichier ouvert self.thumbnail = make_thumbnail(self.scheduler, location ) else: self.thumbnail = self.scheduler.add_file(location_album_default) #size and md5 ought to be combute once for all def deep_files(self): tmp = itertools.chain.from_iterable(map(Album.deep_files, self.subalbums)) return itertools.chain( self.files, tmp) @recursion_protect(0) def __len__(self): #number of file in dir and subdir return len(self.files) + sum( [len(a) for a in self.subalbums ] ) @recursion_protect(0) def all_albums(self): return itertools.chain( [self], *list(map( lambda x:x.all_albums(), self.subalbums )) ) @recursion_protect(0) def all_files(self): return set(itertools.chain( *list(map(lambda x:x.files, self.all_albums())))) @recursion_protect(0) def duplicate(self): if self.thumbnail: self.scheduler.duplicate_file(self.thumbnail) for f in self.files: f.duplicate() for alb in self.subalbums: alb.duplicate()<|fim▁end|>
for _file in self.files: _file.io_lock.acquire() for album in self.subalbums:
<|file_name|>test-mpi.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: ISO-8859-15-*- import sys import os import datetime import time from mpi4py import MPI # MPI related initialisations comm = MPI.COMM_WORLD rank = comm.Get_rank() # number of the processor size = comm.Get_size() # number of all participating processes name = MPI.Get_processor_name() def main(): print "test" #ts = time.time() print "processor #", rank work = None if (rank == 0): work = createWork(size) ################################################### # parallel part ################################################## # send each sublist of the splitted list to on processor workPerNode = comm.scatter(work, root=0) # each processor received a specific number of meta_info_objects # that he has to process print rank, "Received data map with ", len(workPerNode), " elements" workResult = sum(workPerNode) ################################################### # end of parallel part ################################################## workResults = comm.gather(workResult, root=0) if rank == 0: print "outputing results ..." for res in workResults: print "sum: ", res<|fim▁hole|> work = [] for i in range(noOfNodes): work.append(range(100)) return work main()<|fim▁end|>
def createWork(noOfNodes):
<|file_name|>serializers.py<|end_file_name|><|fim▁begin|>"""Defines serializers used by the Team API.""" from copy import deepcopy from django.contrib.auth.models import User from django.db.models import Count from django.conf import settings from django_countries import countries from rest_framework import serializers from openedx.core.lib.api.serializers import CollapsedReferenceSerializer from openedx.core.lib.api.fields import ExpandableField from openedx.core.djangoapps.user_api.accounts.serializers import UserReadOnlySerializer from lms.djangoapps.teams.models import CourseTeam, CourseTeamMembership class CountryField(serializers.Field): """ Field to serialize a country code. """ COUNTRY_CODES = dict(countries).keys() def to_representation(self, obj): """ Represent the country as a 2-character unicode identifier. """ return unicode(obj) def to_internal_value(self, data): """ Check that the code is a valid country code. We leave the data in its original format so that the Django model's CountryField can convert it to the internal representation used by the django-countries library. """ if data and data not in self.COUNTRY_CODES: raise serializers.ValidationError( u"{code} is not a valid country code".format(code=data) ) return data class UserMembershipSerializer(serializers.ModelSerializer): """Serializes CourseTeamMemberships with only user and date_joined Used for listing team members. """ profile_configuration = deepcopy(settings.ACCOUNT_VISIBILITY_CONFIGURATION) profile_configuration['shareable_fields'].append('url') profile_configuration['public_fields'].append('url') user = ExpandableField( collapsed_serializer=CollapsedReferenceSerializer( model_class=User, id_source='username', view_name='accounts_api', read_only=True, ), expanded_serializer=UserReadOnlySerializer(configuration=profile_configuration), ) class Meta(object): model = CourseTeamMembership fields = ("user", "date_joined", "last_activity_at") read_only_fields = ("date_joined", "last_activity_at") class CourseTeamSerializer(serializers.ModelSerializer): """Serializes a CourseTeam with membership information.""" id = serializers.CharField(source='team_id', read_only=True) # pylint: disable=invalid-name membership = UserMembershipSerializer(many=True, read_only=True) country = CountryField() class Meta(object): model = CourseTeam fields = ( "id", "discussion_topic_id", "name", "course_id", "topic_id", "date_created", "description", "country", "language", "last_activity_at", "membership", ) read_only_fields = ("course_id", "date_created", "discussion_topic_id", "last_activity_at") class CourseTeamCreationSerializer(serializers.ModelSerializer): """Deserializes a CourseTeam for creation.""" country = CountryField(required=False) class Meta(object): model = CourseTeam fields = ( "name", "course_id", "description", "topic_id", "country", "language", ) def create(self, validated_data): team = CourseTeam.create( name=validated_data.get("name", ''), course_id=validated_data.get("course_id"), description=validated_data.get("description", ''), topic_id=validated_data.get("topic_id", ''), country=validated_data.get("country", ''), language=validated_data.get("language", ''), ) team.save() return team class CourseTeamSerializerWithoutMembership(CourseTeamSerializer): """The same as the `CourseTeamSerializer`, but elides the membership field. Intended to be used as a sub-serializer for serializing team memberships, since the membership field is redundant in that case. """ def __init__(self, *args, **kwargs): super(CourseTeamSerializerWithoutMembership, self).__init__(*args, **kwargs) del self.fields['membership'] class MembershipSerializer(serializers.ModelSerializer): """Serializes CourseTeamMemberships with information about both teams and users.""" profile_configuration = deepcopy(settings.ACCOUNT_VISIBILITY_CONFIGURATION) profile_configuration['shareable_fields'].append('url') profile_configuration['public_fields'].append('url') user = ExpandableField( collapsed_serializer=CollapsedReferenceSerializer( model_class=User, id_source='username',<|fim▁hole|> ) team = ExpandableField( collapsed_serializer=CollapsedReferenceSerializer( model_class=CourseTeam, id_source='team_id', view_name='teams_detail', read_only=True, ), expanded_serializer=CourseTeamSerializerWithoutMembership(read_only=True), ) class Meta(object): model = CourseTeamMembership fields = ("user", "team", "date_joined", "last_activity_at") read_only_fields = ("date_joined", "last_activity_at") class BaseTopicSerializer(serializers.Serializer): """Serializes a topic without team_count.""" description = serializers.CharField() name = serializers.CharField() id = serializers.CharField() # pylint: disable=invalid-name class TopicSerializer(BaseTopicSerializer): """ Adds team_count to the basic topic serializer, checking if team_count is already present in the topic data, and if not, querying the CourseTeam model to get the count. Requires that `context` is provided with a valid course_id in order to filter teams within the course. """ team_count = serializers.SerializerMethodField() def get_team_count(self, topic): """Get the number of teams associated with this topic""" # If team_count is already present (possible if topic data was pre-processed for sorting), return it. if 'team_count' in topic: return topic['team_count'] else: return CourseTeam.objects.filter(course_id=self.context['course_id'], topic_id=topic['id']).count() class BulkTeamCountTopicListSerializer(serializers.ListSerializer): # pylint: disable=abstract-method """ List serializer for efficiently serializing a set of topics. """ def to_representation(self, obj): """Adds team_count to each topic. """ data = super(BulkTeamCountTopicListSerializer, self).to_representation(obj) add_team_count(data, self.context["course_id"]) return data class BulkTeamCountTopicSerializer(BaseTopicSerializer): # pylint: disable=abstract-method """ Serializes a set of topics, adding the team_count field to each topic as a bulk operation. Requires that `context` is provided with a valid course_id in order to filter teams within the course. """ class Meta(object): list_serializer_class = BulkTeamCountTopicListSerializer def add_team_count(topics, course_id): """ Helper method to add team_count for a list of topics. This allows for a more efficient single query. """ topic_ids = [topic['id'] for topic in topics] teams_per_topic = CourseTeam.objects.filter( course_id=course_id, topic_id__in=topic_ids ).values('topic_id').annotate(team_count=Count('topic_id')) topics_to_team_count = {d['topic_id']: d['team_count'] for d in teams_per_topic} for topic in topics: topic['team_count'] = topics_to_team_count.get(topic['id'], 0)<|fim▁end|>
view_name='accounts_api', read_only=True, ), expanded_serializer=UserReadOnlySerializer(configuration=profile_configuration)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
default_app_config = "gallery.apps.GalleryConfig"
<|file_name|>async.ts<|end_file_name|><|fim▁begin|>import { assert } from 'utils/assert'; type AsyncIterable<T> = Iterable<T | Promise<T>> | Promise<Iterable<T | Promise<T>>>; type AsyncForEachIteratee<T> = ( value: T, index: number, arrayLength: number, ) => unknown | Promise<unknown>; /** * Native port of Bluebird's Promise.prototype.each. Accepts an iterable (or * Promise-wrapped iterable) of any value, and an callback function to be * executed for each value that the iterable yields. * * If a value is a promise, `asyncForEach` will wait for it before iterating * further. */ export async function asyncForEach<T>( iterable: AsyncIterable<T>, iteratee: AsyncForEachIteratee<T>, ): Promise<T[]> { const results: T[] = []; const resolvedList = Array.from(await iterable); const resolvedLength = resolvedList.length; for (let i = 0; i < resolvedList.length; i++) { // eslint-disable-next-line no-await-in-loop const value = await resolvedList[i]; results.push(value); // eslint-disable-next-line no-await-in-loop await iteratee(value, i, resolvedLength); } return results; } type AsyncMapIteratee<T, R> = (value: T, index: number, arrayLength: number) => R | Promise<R>; type AsyncMapOptions = { concurrency?: number }; export async function asyncMap<T, R>( iterable: AsyncIterable<T>, iteratee: AsyncMapIteratee<T, R>, options?: AsyncMapOptions, ): Promise<R[]> { const concurrency = options?.concurrency ?? Infinity; const resolvedList = Array.from(await iterable); const resolvedLength = resolvedList.length; assert(concurrency > 0); return new Promise((resolve, reject) => { const results: R[] = []; let cursor = 0; let pending = 0; function enqueueNextPromises() { // If we have called .then() for all values, and no promises are pending, // resolve with the final array of results. if (cursor === resolvedLength && pending === 0) { resolve(results); } else { // Call .then() in batches for promises moving left->right, only // executing at maximum the value of the configured concurrency. while (pending < Math.min(concurrency, resolvedLength - cursor + 1)) { const index = cursor; const next = resolvedList[index]; cursor++; pending++; Promise.resolve(next) .then((value) => { return iteratee(value, index, resolvedLength); }) .then(<|fim▁hole|> results[index] = value; enqueueNextPromises(); }, ) .catch( // eslint-disable-next-line no-loop-func (err) => { pending--; reject(err); }, ); } } } enqueueNextPromises(); }); } export async function asyncMapSeries<T, R>( iterable: AsyncIterable<T>, iteratee: AsyncMapIteratee<T, R>, ): Promise<R[]> { return asyncMap(iterable, iteratee, { concurrency: 1 }); }<|fim▁end|>
// eslint-disable-next-line no-loop-func (value) => { pending--;
<|file_name|>MongoDataStoreBlobGCTest.java<|end_file_name|><|fim▁begin|>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ package org.apache.jackrabbit.oak.plugins.document.blob.ds; import java.util.Date; import org.apache.jackrabbit.oak.plugins.blob.datastore.DataStoreBlobStore; import org.apache.jackrabbit.oak.plugins.blob.datastore.DataStoreUtils; import org.apache.jackrabbit.oak.plugins.document.DocumentMK; import org.apache.jackrabbit.oak.plugins.document.MongoBlobGCTest; import org.apache.jackrabbit.oak.plugins.document.MongoUtils; import org.junit.After; import org.junit.Assume; import org.junit.Before; import org.junit.BeforeClass; /** * Test for MongoMK GC with {@link DataStoreBlobStore} * */ public class MongoDataStoreBlobGCTest extends MongoBlobGCTest { protected Date startDate; protected DataStoreBlobStore blobStore; @BeforeClass public static void setUpBeforeClass() throws Exception { try { Assume.assumeNotNull(DataStoreUtils.getBlobStore()); } catch (Exception e) { Assume.assumeNoException(e); } } @Override protected DocumentMK.Builder addToBuilder(DocumentMK.Builder mk) { return super.addToBuilder(mk).setBlobStore(blobStore); } @Before<|fim▁hole|> blobStore = DataStoreUtils.getBlobStore(folder.newFolder()); super.setUpConnection(); } }<|fim▁end|>
@Override public void setUpConnection() throws Exception { startDate = new Date();
<|file_name|>unique-send-2.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 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 std::task; fn child(tx: &Sender<Box<uint>>, i: uint) { tx.send(box i); } pub fn main() { let (tx, rx) = channel(); let n = 100u; let mut expected = 0u; for i in range(0u, n) { let tx = tx.clone();<|fim▁hole|> child(&tx, i) }); expected += i; } let mut actual = 0u; for _ in range(0u, n) { let j = rx.recv(); actual += *j; } assert_eq!(expected, actual); }<|fim▁end|>
task::spawn(proc() {
<|file_name|>inlining-issue67557-ice.rs<|end_file_name|><|fim▁begin|>// This used to cause an ICE for an internal index out of range due to simd_shuffle_indices being // passed the wrong Instance, causing issues with inlining. See #67557. // // run-pass // compile-flags: -Zmir-opt-level=4 #![feature(platform_intrinsics, repr_simd)] extern "platform-intrinsic" { fn simd_shuffle2<T, U>(x: T, y: T, idx: [u32; 2]) -> U; } #[repr(simd)] #[derive(Debug, PartialEq)] struct Simd2(u8, u8); fn main() { unsafe { let _: Simd2 = inline_me(); }<|fim▁hole|> const IDX: [u32; 2] = [0, 3]; simd_shuffle2(Simd2(10, 11), Simd2(12, 13), IDX) }<|fim▁end|>
} #[inline(always)] unsafe fn inline_me() -> Simd2 {
<|file_name|>test_BinaryTreeMaximumPathSum.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Authors: Y. Jia <[email protected]> import unittest from common.BinaryTree import BinaryTree from .. import BinaryTreeMaximumPathSum <|fim▁hole|>class test_BinaryTreeMaximumPathSum(unittest.TestCase): solution = BinaryTreeMaximumPathSum.Solution() def test_maxPathSum(self): self.assertEqual(self.solution.maxPathSum(BinaryTree.create_tree([1, 2, 3])[0]), 6) if __name__ == '__main__': unittest.main()<|fim▁end|>
<|file_name|>manifest_disk_repository_test.go<|end_file_name|><|fim▁begin|>package manifest_test import ( "path/filepath" . "github.com/cloudfoundry/cli/cf/manifest" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("ManifestDiskRepository", func() { var repo Repository BeforeEach(func() { repo = NewDiskRepository() }) Describe("given a directory containing a file called 'manifest.yml'", func() { It("reads that file", func() { m, err := repo.ReadManifest("../../fixtures/manifests") Expect(err).NotTo(HaveOccurred()) Expect(m.Path).To(Equal(filepath.Clean("../../fixtures/manifests/manifest.yml"))) applications, err := m.Applications() Expect(err).NotTo(HaveOccurred()) Expect(*applications[0].Name).To(Equal("from-default-manifest")) }) }) Describe("given a directory that doesn't contain a file called 'manifest.y{a}ml'", func() { It("returns an error", func() { m, err := repo.ReadManifest("../../fixtures") Expect(err).To(HaveOccurred()) Expect(m.Path).To(BeEmpty()) }) }) Describe("given a directory that contains a file called 'manifest.yaml'", func() { It("reads that file", func() { m, err := repo.ReadManifest("../../fixtures/manifests/only_yaml") Expect(err).NotTo(HaveOccurred()) Expect(m.Path).To(Equal(filepath.Clean("../../fixtures/manifests/only_yaml/manifest.yaml"))) applications, err := m.Applications() Expect(err).NotTo(HaveOccurred()) Expect(*applications[0].Name).To(Equal("from-default-manifest")) }) }) Describe("given a directory contains files called 'manifest.yml' and 'manifest.yaml'", func() { It("reads the file named 'manifest.yml'", func() { m, err := repo.ReadManifest("../../fixtures/manifests/both_yaml_yml") Expect(err).NotTo(HaveOccurred()) Expect(m.Path).To(Equal(filepath.Clean("../../fixtures/manifests/both_yaml_yml/manifest.yml"))) applications, err := m.Applications() Expect(err).NotTo(HaveOccurred()) Expect(*applications[0].Name).To(Equal("yml-extension")) }) }) Describe("given a path to a file", func() { var ( inputPath string m *Manifest err error ) BeforeEach(func() { inputPath = filepath.Clean("../../fixtures/manifests/different-manifest.yml") m, err = repo.ReadManifest(inputPath) }) It("reads the file at that path", func() { Expect(err).NotTo(HaveOccurred()) Expect(m.Path).To(Equal(inputPath)) applications, err := m.Applications() Expect(err).NotTo(HaveOccurred()) Expect(*applications[0].Name).To(Equal("from-different-manifest")) }) It("passes the base directory to the manifest file", func() { applications, err := m.Applications() Expect(err).NotTo(HaveOccurred()) Expect(len(applications)).To(Equal(1)) Expect(*applications[0].Name).To(Equal("from-different-manifest")) appPath := filepath.Clean("../../fixtures/manifests") Expect(*applications[0].Path).To(Equal(appPath)) }) }) Describe("given a path to a file that doesn't exist", func() { It("returns an error", func() { _, err := repo.ReadManifest("some/path/that/doesnt/exist/manifest.yml") Expect(err).To(HaveOccurred()) }) It("returns empty string for the manifest path", func() { m, _ := repo.ReadManifest("some/path/that/doesnt/exist/manifest.yml") Expect(m.Path).To(Equal("")) }) }) Describe("when the manifest is empty", func() { It("returns an error", func() { _, err := repo.ReadManifest("../../fixtures/manifests/empty-manifest.yml") Expect(err).To(HaveOccurred()) }) It("returns the path to the manifest", func() { inputPath := filepath.Clean("../../fixtures/manifests/empty-manifest.yml") m, _ := repo.ReadManifest(inputPath) Expect(m.Path).To(Equal(inputPath)) }) }) It("converts nested maps to generic maps", func() { m, err := repo.ReadManifest("../../fixtures/manifests/different-manifest.yml") Expect(err).NotTo(HaveOccurred()) applications, err := m.Applications() Expect(err).NotTo(HaveOccurred()) Expect(*applications[0].EnvironmentVars).To(Equal(map[string]interface{}{ "LD_LIBRARY_PATH": "/usr/lib/somewhere", })) }) It("merges manifests with their 'inherited' manifests", func() { m, err := repo.ReadManifest("../../fixtures/manifests/inherited-manifest.yml") Expect(err).NotTo(HaveOccurred()) applications, err := m.Applications() Expect(err).NotTo(HaveOccurred()) Expect(*applications[0].Name).To(Equal("base-app")) Expect(applications[0].ServicesToBind).To(Equal([]string{"base-service"})) Expect(*applications[0].EnvironmentVars).To(Equal(map[string]interface{}{ "foo": "bar", "will-be-overridden": "my-value", })) Expect(*applications[1].Name).To(Equal("my-app")) env := *applications[1].EnvironmentVars Expect(env["will-be-overridden"]).To(Equal("my-value")) Expect(env["foo"]).To(Equal("bar")) services := applications[1].ServicesToBind Expect(services).To(Equal([]string{"base-service", "foo-service"})) }) It("supports yml merges", func() { m, err := repo.ReadManifest("../../fixtures/manifests/merge-manifest.yml") Expect(err).NotTo(HaveOccurred()) applications, err := m.Applications() Expect(err).NotTo(HaveOccurred()) Expect(*applications[0].Name).To(Equal("blue")) Expect(*applications[0].InstanceCount).To(Equal(1)) Expect(*applications[0].Memory).To(Equal(int64(256))) Expect(*applications[1].Name).To(Equal("green")) Expect(*applications[1].InstanceCount).To(Equal(1)) Expect(*applications[1].Memory).To(Equal(int64(256))) Expect(*applications[2].Name).To(Equal("big-blue"))<|fim▁hole|><|fim▁end|>
Expect(*applications[2].InstanceCount).To(Equal(3)) Expect(*applications[2].Memory).To(Equal(int64(256))) }) })
<|file_name|>SimpleImageAnalyser.java<|end_file_name|><|fim▁begin|>package illume.analysis; import java.awt.image.BufferedImage; /* This simple analyser example averages pixel values. */ public class SimpleImageAnalyser<T extends BufferedImage> extends AbstractImageAnalyser<T> {<|fim▁hole|> @Override public double analyse(T input) { int sum_r = 0; int sum_g = 0; int sum_b = 0; for (int y = 0; y < input.getHeight(); y++) { for (int x = 0; x < input.getWidth(); x++) { final int clr = input.getRGB(x, y); sum_r += (clr & 0x00ff0000) >> 16; sum_g += (clr & 0x0000ff00) >> 8; sum_b += clr & 0x000000ff; } } double sum_rgb = ((sum_r + sum_b + sum_g) / 3.0d); double avg = sum_rgb / (input.getHeight() * input.getWidth()); // 8-bit RGB return avg / 255; } }<|fim▁end|>
<|file_name|>MCP320x.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # # MCP320x # # Author: Maurik Holtrop # # This module interfaces with the MCP300x or MCP320x family of chips. These # are 10-bit and 12-bit ADCs respectively. The x number indicates the number # of multiplexed analog inputs: 2 (MCP3202), 4 (MCP3204) or 8 (MCP3208) # Communications with this chip are over the SPI protocol. # See: https://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus # # The version of the code has two SPI interfaces: the builtin hardware # SPI interface on the RPI, or a "bit-banged" GPIO version. # # Bit-Bang GPIO: # We emulate a SPI port in software using the GPIO lines. # This is a bit slower than the hardware interface, but it is far more # clear what is going on, plus the RPi has only one SPI device. # Connections: RPi GPIO to MCP320x # CS_bar_pin = CS/SHDN # CLK_pin = CLK # MOSI_pin = D_in # MISO_pin = D_out # # Hardware SPI: # This uses the builtin hardware on the RPi. You need to enable this with the # raspi-config program first. The data rate can be up to 1MHz. # Connections: RPi pins to MCP320x # CE0 or CE1 = CS/SHDN (chip select) set CS_bar = 0 or 1 # SCK = CLK set CLK_pin = 1000000 (transfer speed) # MOSI = D_in set MOSI_pin = 0 # MISO = D_out set MISO_pin = 0 # The SPI protocol simulated here is MODE=0, CPHA=0, which has a positive polarity clock, # (the clock is 0 at rest, active at 1) and a positive phase (0 to 1 transition) for reading # or writing the data. Thus corresponds to the specifications of the MCP320x chips. # # From MCP3208 datasheet: # Outging data : MCU latches data to A/D converter on rising edges of SCLK # Incoming data: Data is clocked out of A/D converter on falling edges, so should be read on rising edge. try: import RPi.GPIO as GPIO except ImportError as error: pass try: import Adafruit_BBIO as GPIO except ImportError as error: pass try: import spidev except ImportError as error: pass from DevLib.MyValues import MyValues class MCP320x: """This is an class that implements an interface to the MCP320x ADC chips. Standard is the MCP3208, but is will also work wiht the MCP3202, MCP3204, MCP3002, MCP3004 and MCP3008.""" def __init__(self, cs_bar_pin, clk_pin=1000000, mosi_pin=0, miso_pin=0, chip='MCP3208', channel_max=None, bit_length=None, single_ended=True): """Initialize the code and set the GPIO pins. The last argument, ch_max, is 2 for the MCP3202, 4 for the MCP3204 or 8 for the MCS3208.""" self._CLK = clk_pin self._MOSI = mosi_pin self._MISO = miso_pin self._CS_bar = cs_bar_pin chip_dictionary = { "MCP3202": (2, 12), "MCP3204": (4, 12), "MCP3208": (8, 12), "MCP3002": (2, 10), "MCP3004": (4, 10), "MCP3008": (8, 10) } if chip in chip_dictionary: self._ChannelMax = chip_dictionary[chip][0] self._BitLength = chip_dictionary[chip][1] elif chip is None and (channel_max is not None) and (bit_length is not None): self._ChannelMax = channel_max self._BitLength = bit_length else: print("Unknown chip: {} - Please re-initialize.") self._ChannelMax = 0 self._BitLength = 0 return self._SingleEnded = single_ended self._Vref = 3.3 self._values = MyValues(self.read_adc, self._ChannelMax) self._volts = MyValues(self.read_volts, self._ChannelMax) # This is used to speed up the SPIDEV communication. Send out MSB first. # control[0] - bit7-3: upper 5 bits 0, because we can only send 8 bit sequences. # - bit2 : Start bit - starts conversion in ADCs # - bit1 : Select single_ended=1 or differential=0 # - bit0 : D2 high bit of channel select. # control[1] - bit7 : D1 middle bit of channel select. # - bit6 : D0 low bit of channel select. # - bit5-0 : Don't care. if self._SingleEnded: self._control0 = [0b00000110, 0b00100000, 0] # Pre-compute part of the control word. else: self._control0 = [0b00000100, 0b00100000, 0] # Pre-compute part of the control word. if self._MOSI > 0: # Bing Bang mode assert self._MISO != 0 and self._CLK < 32 if GPIO.getmode() != 11: GPIO.setmode(GPIO.BCM) # Use the BCM numbering scheme GPIO.setup(self._CLK, GPIO.OUT) # Setup the ports for in and output GPIO.setup(self._MOSI, GPIO.OUT) GPIO.setup(self._MISO, GPIO.IN) GPIO.setup(self._CS_bar, GPIO.OUT) GPIO.output(self._CLK, 0) # Set the clock low. GPIO.output(self._MOSI, 0) # Set the Master Out low GPIO.output(self._CS_bar, 1) # Set the CS_bar high else: self._dev = spidev.SpiDev(0, self._CS_bar) # Start a SpiDev device self._dev.mode = 0 # Set SPI mode (phase) self._dev.max_speed_hz = self._CLK # Set the data rate self._dev.bits_per_word = 8 # Number of bit per word. ALWAYS 8 def __del__(self): """ Cleanup the GPIO before being destroyed """ if self._MOSI > 0: GPIO.cleanup(self._CS_bar) GPIO.cleanup(self._CLK) GPIO.cleanup(self._MOSI) GPIO.cleanup(self._MISO) def get_channel_max(self): """Return the maximum number of channels""" return self._ChannelMax def get_bit_length(self): """Return the number of bits that will be read""" return self._BitLength def get_value_max(self): """Return the maximum value possible for an ADC read""" return 2 ** self._BitLength - 1 def send_bit(self, bit): """ Send out a single bit, and pulse clock.""" if self._MOSI == 0: return # # The input is read on the rising edge of the clock. # GPIO.output(self._MOSI, bit) # Set the bit. GPIO.output(self._CLK, 1) # Rising edge sends data GPIO.output(self._CLK, 0) # Return clock to zero. def read_bit(self): """ Read a single bit from the ADC and pulse clock.""" if self._MOSI == 0: return 0 # # The output is going out on the falling edge of the clock, # and is to be read on the rising edge of the clock. # Clock should be already low, and data should already be set. GPIO.output(self._CLK, 1) # Set the clock high. Ready to read. bit = GPIO.input(self._MISO) # Read the bit. GPIO.output(self._CLK, 0) # Return clock low, next bit will be set. return bit def read_adc(self, channel): """This reads the actual ADC value, after connecting the analog multiplexer to the desired channel. ADC value is returned at a n-bit integer value, with n=10 or 12 depending on the chip. The value can be converted to a voltage with: volts = data*Vref/(2**n-1)""" if channel < 0 or channel >= self._ChannelMax: print("Error - chip does not have channel = {}".format(channel)) if self._MOSI == 0: # SPIdev Code # This builds up the control word, which selects the channel # and sets single/differential more. control = [self._control0[0] + ((channel & 0b100) >> 2), self._control0[1]+((channel & 0b011) << 6), 0] dat = self._dev.xfer(control) value = (dat[1] << 8)+dat[2] # Unpack the two 8-bit words to a single integer. return value else: # Bit Bang code. # To read out this chip you need to send: # 1 - start bit # 2 - Single ended (1) or differential (0) mode # 3 - Channel select: 1 bit for x=2 or 3 bits for x=4,8 # 4 - MSB first (1) or LSB first (0) # # Start of sequence sets CS_bar low, and sends sequence # GPIO.output(self._CLK, 0) # Make sure clock starts low. GPIO.output(self._MOSI, 0) GPIO.output(self._CS_bar, 0) # Select the chip. self.send_bit(1) # Start bit = 1 self.send_bit(self._SingleEnded) # Select single or differential if self._ChannelMax > 2: self.send_bit(int((channel & 0b100) > 0)) # Send high bit of channel = DS2 self.send_bit(int((channel & 0b010) > 0)) # Send mid bit of channel = DS1 self.send_bit(int((channel & 0b001) > 0)) # Send low bit of channel = DS0 else: self.send_bit(channel) self.send_bit(0) # MSB First (for MCP3x02) or don't care. # The clock is currently low, and the dummy bit = 0 is on the output of the ADC # self.read_bit() # Read the bit. data = 0 for i in range(self._BitLength): # Note you need to shift left first, or else you shift the last bit (bit 0) # to the 1 position. data <<= 1 bit = self.read_bit() data += bit GPIO.output(self._CS_bar, 1) # Unselect the chip. return data def read_volts(self, channel): """Read the ADC value from channel and convert to volts, assuming that Vref is set correctly. """ return self._Vref * self.read_adc(channel) / self.get_value_max() def fast_read_adc0(self): """This reads the actual ADC value of channel 0, with as little overhead as possible. Use with SPIDEV ONLY!!!! returns: The ADC value as an n-bit integer value, with n=10 or 12 depending on the chip.""" dat = self._dev.xfer(self._control0) value = (dat[1] << 8) + dat[2] return value @property def values(self): """ADC values presented as a list.""" return self._values @property def volts(self): """ADC voltages presented as a list""" return self._volts @property def accuracy(self): """The fractional voltage of the least significant bit. """ return self._Vref / float(self.get_value_max()) @property def vref(self): """Reference voltage used by the chip. You need to set this. It defaults to 3.3V""" return self._Vref @vref.setter def vref(self, vr): self._Vref = vr def main(argv): """Test code for the MCP320x driver. This assumes you are using a MCP3208 If no arguments are supplied, then use SPIdev for CE0 and read channel 0""" if len(argv) < 3: print("Args : ", argv) cs_bar = 0 clk_pin = 1000000 mosi_pin = 0<|fim▁hole|> channel = int(argv[1]) elif len(argv) < 6: print("Please supply: cs_bar_pin clk_pin mosi_pin miso_pin channel") sys.exit(1) else: cs_bar = int(argv[1]) clk_pin = int(argv[2]) mosi_pin = int(argv[3]) miso_pin = int(argv[4]) channel = int(argv[5]) adc_chip = MCP320x(cs_bar, clk_pin, mosi_pin, miso_pin) try: while True: value = adc_chip.read_adc(channel) print("{:4d}".format(value)) time.sleep(0.1) except KeyboardInterrupt: sys.exit(0) if __name__ == '__main__': import sys import time main(sys.argv)<|fim▁end|>
miso_pin = 0 if len(argv) < 2: channel = 0 else:
<|file_name|>SmartThingsPublishTest.java<|end_file_name|><|fim▁begin|>package com.unitvectory.shak.jarvis.model; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.junit.Test; import com.unitvectory.shak.jarvis.util.ResourceHelper; /** * Tests the SmartThingsPublish class * * @author Jared Hatfield * */ public class SmartThingsPublishTest { /** * Test the parser being given a null value */ @Test public void testNullStringParse() { JsonPublishRequest myRequest = null; SmartThingsPublish smart = new SmartThingsPublish(myRequest); assertNotNull(smart); assertNull(smart.getPublish()); assertNull(smart.getAuth()); assertNull(smart.getDate()); assertNull(smart.getDescription()); assertNull(smart.getDescriptionText()); assertNull(smart.getDeviceId()); assertNull(smart.getHubId()); assertNull(smart.getId()); assertNull(smart.getLocationId()); assertNull(smart.getName()); assertNull(smart.getSource()); assertNull(smart.getUnit()); assertNull(smart.getValue()); } /** * Test the parser when things go perfectly. */ @Test public void testValidParse() { // Load the test JSON String json = ResourceHelper.load("/messagebody.json"); assertNotNull(json); assertTrue(json.length() > 0); // Create the object JsonPublishRequest request = new JsonPublishRequest(json); assertNotNull(request); assertTrue(request.isValid()); assertNotNull(request.getData()); // Create the SmartThingsPublish SmartThingsPublish smart = new SmartThingsPublish(request); assertNotNull(smart); assertEquals("foobar", smart.getAuth()); assertEquals("2013-12-30T16:03:08.224Z", smart.getDate()); assertEquals( "raw:08EF170A59FF, dni:08EF, battery:17, batteryDivisor:0A, rssi:59, lqi:FF", smart.getDescription()); assertEquals("Sensor was -39 dBm", smart.getDescriptionText()); assertEquals("2fffffff-fffff-ffff-ffff-fffffffffff", smart.getDeviceId()); assertEquals("3fffffff-fffff-ffff-ffff-fffffffffff", smart.getHubId()); assertEquals("1fffffff-fffff-ffff-ffff-fffffffffff", smart.getId()); assertEquals("4fffffff-fffff-ffff-ffff-fffffffffff", smart.getLocationId()); assertEquals("rssi", smart.getName());<|fim▁hole|>}<|fim▁end|>
assertEquals("DEVICE", smart.getSource()); assertEquals("dBm", smart.getUnit()); assertEquals("-39", smart.getValue()); }
<|file_name|>extern-pass-u64.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 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. // Test a call to a function that takes/returns a u64. #[link(name = "rust_test_helpers")] extern {<|fim▁hole|> pub fn main() { unsafe { assert_eq!(22, rust_dbg_extern_identity_u64(22)); } }<|fim▁end|>
pub fn rust_dbg_extern_identity_u64(v: u64) -> u64; }
<|file_name|>server.js<|end_file_name|><|fim▁begin|>// Raymond Ho // 8/22/15 var bodyParser = require('body-parser'), express = require('express'), Datastore = require('nedb'); var db = new Datastore({ filename: __dirname + '/db.json', autoload: true<|fim▁hole|>}); var app = express(); app.use(bodyParser.urlencoded({ extended: false })); // This is to get all tags for a certain video app.get('/bestpart/gettags', function(req, res) { var urlObject = {url: req.query.url}; console.log("Received a GET tags request from:", urlObject.url); db.findOne(urlObject, function(err, docs) { if (docs === null) { var errorString = urlObject.url + " was not found in the database.."; res.send({error: errorString}); } else { console.log('Sending over the docs..', docs); res.send(docs); } }); }); // This is to add or update a new tag app.post('/bestpart/tag', function(req, res) { var tagJSON = req.body; var tag = { tag_created: new Date(), tag_time: tagJSON.time, tag_description: tagJSON.description, tag_score: 0 }; var searchFor = { url: tagJSON.url }; console.log("Received a POST", tagJSON); db.findOne(searchFor, function(err, docs) { if (docs === null) { video = { url: tagJSON.url, tags: [tag], }; db.insert(video); console.log("Added to db."); } else { console.log(docs); db.update(searchFor, { $push: { tags: tag } }, {}, function() {}); console.log("Updated DB"); } }); }); // This is to update the votes a tag has. app.post('/bestpart/votes', function(req, res) { var tagJSON = req.body; var searchFor = { url: tagJSON.url }; var newScore = tagJSON.vote; db.update(searchFor, { $inc: { score: newScore } }, {}, function() {}); }); var server = app.listen(3000, function() { console.log("http://localhost:3000/"); });<|fim▁end|>
<|file_name|>ProgressBarContainer.js<|end_file_name|><|fim▁begin|>import altConnect from 'higher-order-components/altConnect'; import { STATUS_OK } from 'app-constants'; import ItemStore from 'stores/ItemStore'; import ProgressBar from '../components/ProgressBar'; const mapStateToProps = ({ itemState }) => ({ progress: itemState.readingPercentage, hidden: itemState.status !== STATUS_OK, }); mapStateToProps.stores = { ItemStore }; export default altConnect(mapStateToProps)(ProgressBar);<|fim▁hole|>// WEBPACK FOOTER // // ./src/js/app/modules/item/containers/ProgressBarContainer.js<|fim▁end|>
<|file_name|>XMLHandler.js<|end_file_name|><|fim▁begin|><<<<<<< HEAD var xmlDoc; var xmlloaded = false; var _finalUrl; /* * input: none * output: none * gets zipcode from the zipcode text field */ function createURL() { var zip = document.getElementById("zipcode").value;<|fim▁hole|> var _clientId = "&client_id=API KEY"; var _url = "https://api.seatgeek.com/2/recommendations?events.id=1162104&postal_code="; _finalUrl = _url + zip + _clientId + format; // document.getElementById("displayURL").innerHTML = _finalUrl; // debugging } function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { // ready states 1-4 & status 200 = okay // 0: uninitialized // 1: loading // 2: loaded // 3: interactive // 4: complete if (xhttp.readyState == 4 && xhttp.status == 200) { myFunction(xhttp); } }; var zip = document.getElementById("zipcode").value; var format = "&format=xml" var _clientId = "&client_id=API KEY"; var _url = "https://api.seatgeek.com/2/recommendations?events.id=1162104&postal_code="; _finalUrl = _url + zip + _clientId + format; xhttp.open("GET", _finalUrl, true); xhttp.send(); } function myFunction(xml) { var i, buyTickets; var xmlDoc = xml.responseXML; var x = xmlDoc.getElementsByTagName("recommendations"); for (i = 0; i < x.length; i++) { buyTickets = x[i].getElementsByTagName("url")[2].childNodes[0].nodeValue; } document.getElementById("demo").innerHTML = window.open(buyTickets); }<|fim▁end|>
var format = "&format=xml"
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># coding=utf-8 """ Provides crossplatform checking of current power source, battery warning level and battery time remaining estimate. Allows you to add observer for power notifications if platform supports it. Usage: from power import PowerManagement, PowerManagementObserver # Automatically imports platform-specific implementation class Observer(PowerManagementObserver): def on_power_sources_change(self, power_management): print "Power sources did change." def on_time_remaining_change(self, power_management): print "Time remaining did change." # class Observer(object): # ... # PowerManagementObserver.register(Observer) """ __author__ = '[email protected]' __version__ = '1.2' from sys import platform from power.common import * try: if platform.startswith('darwin'): from power.darwin import PowerManagement elif platform.startswith('win32'): from power.win32 import PowerManagement elif platform.startswith('linux'): from power.linux import PowerManagement else: raise RuntimeError("{platform} is not supported.".format(platform=platform)) except RuntimeError as e: import warnings<|fim▁hole|> warnings.warn("Unable to load PowerManagement for {platform}. No-op PowerManagement class is used: {error}".format(error=str(e), platform=platform)) from power.common import PowerManagementNoop as PowerManagement<|fim▁end|>
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib import admin from modeltranslation.admin import TabbedTranslationAdmin from .models import Person, Office, Tag class PersonAdmin(TabbedTranslationAdmin): list_display = ('name', 'surname', 'security_level', 'gender') list_filter = ('security_level', 'tags', 'office', 'name', 'gender') actions = ['copy_100'] def copy_100(self, request, queryset): for item in queryset.all(): item.populate() copy_100.short_description = 'Copy 100 objects with random data' class PersonStackedInline(admin.TabularInline): model = Person extra = 0 class OfficeAdmin(admin.ModelAdmin): inlines = (PersonStackedInline,) list_display = ('office', 'address') <|fim▁hole|> list_display = ('name',) admin.site.register(Person, PersonAdmin) admin.site.register(Office, OfficeAdmin) admin.site.register(Tag, TagAdmin)<|fim▁end|>
class TagAdmin(admin.ModelAdmin):
<|file_name|>CommandBuilder.js<|end_file_name|><|fim▁begin|>'use strict'; import { module } from 'angular'; import _ from 'lodash'; import { AccountService, ExpectedArtifactService } from '@spinnaker/core'; import { KubernetesProviderSettings } from '../../../kubernetes.settings'; export const KUBERNETES_V1_CLUSTER_CONFIGURE_COMMANDBUILDER = 'spinnaker.kubernetes.clusterCommandBuilder.service'; export const name = KUBERNETES_V1_CLUSTER_CONFIGURE_COMMANDBUILDER; // for backwards compatibility module(KUBERNETES_V1_CLUSTER_CONFIGURE_COMMANDBUILDER, []).factory('kubernetesClusterCommandBuilder', function() { function attemptToSetValidAccount(application, defaultAccount, command) { return AccountService.listAccounts('kubernetes', 'v1').then(function(kubernetesAccounts) { const kubernetesAccountNames = _.map(kubernetesAccounts, 'name'); let firstKubernetesAccount = null; if (application.accounts.length) { firstKubernetesAccount = _.find(application.accounts, function(applicationAccount) { return kubernetesAccountNames.includes(applicationAccount); }); } else if (kubernetesAccountNames.length) { firstKubernetesAccount = kubernetesAccountNames[0]; } const defaultAccountIsValid = defaultAccount && kubernetesAccountNames.includes(defaultAccount); command.account = defaultAccountIsValid ? defaultAccount : firstKubernetesAccount ? firstKubernetesAccount : 'my-account-name'; }); } function applyHealthProviders(application, command) { command.interestingHealthProviderNames = ['KubernetesContainer', 'KubernetesPod']; } function buildNewClusterCommand(application, defaults = {}) { const defaultAccount = defaults.account || KubernetesProviderSettings.defaults.account; const command = { account: defaultAccount, application: application.name, strategy: '', targetSize: 1, cloudProvider: 'kubernetes', selectedProvider: 'kubernetes', namespace: 'default', containers: [], initContainers: [], volumeSources: [], buildImageId: buildImageId, groupByRegistry: groupByRegistry, terminationGracePeriodSeconds: 30, viewState: { mode: defaults.mode || 'create', disableStrategySelection: true, useAutoscaler: false, }, capacity: { min: 1, desired: 1, max: 1, }, scalingPolicy: { cpuUtilization: { target: 40, }, }, useSourceCapacity: false, deployment: { enabled: false, minReadySeconds: 0, deploymentStrategy: { type: 'RollingUpdate', rollingUpdate: { maxUnavailable: 1, maxSurge: 1, }, }, }, }; applyHealthProviders(application, command); attemptToSetValidAccount(application, defaultAccount, command); return command; } function buildClusterCommandFromExisting(application, existing, mode) { mode = mode || 'clone'; const command = _.cloneDeep(existing.deployDescription); command.groupByRegistry = groupByRegistry; command.cloudProvider = 'kubernetes'; command.selectedProvider = 'kubernetes'; command.account = existing.account; command.buildImageId = buildImageId; command.strategy = ''; command.containers.forEach(container => { container.imageDescription.imageId = buildImageId(container.imageDescription); }); command.initContainers.forEach(container => { container.imageDescription.imageId = buildImageId(container.imageDescription); }); command.viewState = { mode: mode, useAutoscaler: !!command.scalingPolicy, }; if (!command.capacity) { command.capacity = { min: command.targetSize, max: command.targetSize, desired: command.targetSize, }; } if (!_.has(command, 'scalingPolicy.cpuUtilization.target')) { command.scalingPolicy = { cpuUtilization: { target: 40 } }; } applyHealthProviders(application, command); return command; } function groupByRegistry(container) { if (container.imageDescription) { if (container.imageDescription.fromContext) { return 'Find Image Result(s)'; } else if (container.imageDescription.fromTrigger) { return 'Images from Trigger(s)'; } else if (container.imageDescription.fromArtifact) { return 'Images from Artifact(s)'; } else { return container.imageDescription.registry; } } } function buildImageId(image) { if (image.fromFindImage) { return `${image.cluster} ${image.pattern}`; } else if (image.fromBake) { return `${image.repository} (Baked during execution)`; } else if (image.fromTrigger && !image.tag) { return `${image.registry}/${image.repository} (Tag resolved at runtime)`; } else if (image.fromArtifact) { return `${image.name} (Artifact resolved at runtime)`; } else { if (image.registry) {<|fim▁hole|> return `${image.registry}/${image.repository}:${image.tag}`; } else { return `${image.repository}:${image.tag}`; } } } function reconcileUpstreamImages(containers, upstreamImages) { const getConfig = image => { if (image.fromContext) { return { match: other => other.fromContext && other.stageId === image.stageId, fieldsToCopy: matchImage => { const { cluster, pattern, repository } = matchImage; return { cluster, pattern, repository }; }, }; } else if (image.fromTrigger) { return { match: other => other.fromTrigger && other.registry === image.registry && other.repository === image.repository && other.tag === image.tag, fieldsToCopy: () => ({}), }; } else if (image.fromArtifact) { return { match: other => other.fromArtifact && other.stageId === image.stageId, fieldsToCopy: matchImage => { const { name } = matchImage; return { name }; }, }; } else { return { skipProcessing: true, }; } }; const result = []; containers.forEach(container => { const imageDescription = container.imageDescription; const imageConfig = getConfig(imageDescription); if (imageConfig.skipProcessing) { result.push(container); } else { const matchingImage = upstreamImages.find(imageConfig.match); if (matchingImage) { Object.assign(imageDescription, imageConfig.fieldsToCopy(matchingImage)); result.push(container); } } }); return result; } function findContextImages(current, all, visited = {}) { // This actually indicates a loop in the stage dependencies. if (visited[current.refId]) { return []; } else { visited[current.refId] = true; } let result = []; if (current.type === 'findImage') { result.push({ fromContext: true, fromFindImage: true, cluster: current.cluster, pattern: current.imageNamePattern, repository: current.name, stageId: current.refId, }); } else if (current.type === 'bake') { result.push({ fromContext: true, fromBake: true, repository: current.ami_name, organization: current.organization, stageId: current.refId, }); } current.requisiteStageRefIds.forEach(function(id) { const next = all.find(stage => stage.refId === id); if (next) { result = result.concat(findContextImages(next, all, visited)); } }); return result; } function findTriggerImages(triggers) { return triggers .filter(trigger => { return trigger.type === 'docker'; }) .map(trigger => { return { fromTrigger: true, repository: trigger.repository, account: trigger.account, organization: trigger.organization, registry: trigger.registry, tag: trigger.tag, }; }); } function findArtifactImages(currentStage, pipeline) { const artifactImages = ExpectedArtifactService.getExpectedArtifactsAvailableToStage(currentStage, pipeline) .filter(artifact => artifact.matchArtifact.type === 'docker/image') .map(artifact => ({ fromArtifact: true, artifactId: artifact.id, name: artifact.matchArtifact.name, })); return artifactImages; } function buildNewClusterCommandForPipeline(current, pipeline) { let contextImages = findContextImages(current, pipeline.stages) || []; contextImages = contextImages.concat(findTriggerImages(pipeline.triggers)); contextImages = contextImages.concat(findArtifactImages(current, pipeline)); return { strategy: '', viewState: { contextImages: contextImages, mode: 'editPipeline', submitButtonLabel: 'Done', requiresTemplateSelection: true, useAutoscaler: false, }, }; } function buildClusterCommandFromPipeline(app, originalCommand, current, pipeline) { const command = _.cloneDeep(originalCommand); let contextImages = findContextImages(current, pipeline.stages) || []; contextImages = contextImages.concat(findTriggerImages(pipeline.triggers)); contextImages = contextImages.concat(findArtifactImages(current, pipeline)); command.containers = reconcileUpstreamImages(command.containers, contextImages); command.containers.map(container => { container.imageDescription.imageId = buildImageId(container.imageDescription); }); command.groupByRegistry = groupByRegistry; command.buildImageId = buildImageId; command.strategy = command.strategy || ''; command.selectedProvider = 'kubernetes'; command.viewState = { mode: 'editPipeline', contextImages: contextImages, submitButtonLabel: 'Done', useAutoscaler: !!command.scalingPolicy, }; if (!_.has(command, 'scalingPolicy.cpuUtilization.target')) { command.scalingPolicy = { cpuUtilization: { target: 40 } }; } return command; } return { buildNewClusterCommand: buildNewClusterCommand, buildClusterCommandFromExisting: buildClusterCommandFromExisting, buildNewClusterCommandForPipeline: buildNewClusterCommandForPipeline, buildClusterCommandFromPipeline: buildClusterCommandFromPipeline, groupByRegistry: groupByRegistry, buildImageId: buildImageId, }; });<|fim▁end|>
<|file_name|>pyqt4.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright (C) 2010, 2011, 2012, 2013 Sebastian Wiesner <[email protected]> # This library is free software; you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the<|fim▁hole|># option) any later version. # This library 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 Lesser General Public License # for more details. # You should have received a copy of the GNU Lesser General Public License # along with this library; if not, write to the Free Software Foundation, # Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # pylint: disable=anomalous-backslash-in-string """ pyudev.pyqt4 ============ PyQt4 integration. :class:`MonitorObserver` integrates device monitoring into the PyQt4\_ mainloop by turning device events into Qt signals. :mod:`PyQt4.QtCore` from PyQt4\_ must be available when importing this module. .. _PyQt4: http://riverbankcomputing.co.uk/software/pyqt/intro .. moduleauthor:: Sebastian Wiesner <[email protected]> """ from __future__ import (print_function, division, unicode_literals, absolute_import) from PyQt4.QtCore import QSocketNotifier, QObject, pyqtSignal from pyudev._util import text_type from pyudev.core import Device from pyudev._qt_base import QUDevMonitorObserverMixin, MonitorObserverMixin class MonitorObserver(QObject, MonitorObserverMixin): """An observer for device events integrating into the :mod:`PyQt4` mainloop. This class inherits :class:`~PyQt4.QtCore.QObject` to turn device events into Qt signals: >>> from pyudev import Context, Monitor >>> from pyudev.pyqt4 import MonitorObserver >>> context = Context() >>> monitor = Monitor.from_netlink(context) >>> monitor.filter_by(subsystem='input') >>> observer = MonitorObserver(monitor) >>> def device_event(device): ... print('event {0} on device {1}'.format(device.action, device)) >>> observer.deviceEvent.connect(device_event) >>> monitor.start() This class is a child of :class:`~PyQt4.QtCore.QObject`. """ #: emitted upon arbitrary device events deviceEvent = pyqtSignal(Device) def __init__(self, monitor, parent=None): """ Observe the given ``monitor`` (a :class:`~pyudev.Monitor`): ``parent`` is the parent :class:`~PyQt4.QtCore.QObject` of this object. It is passed unchanged to the inherited constructor of :class:`~PyQt4.QtCore.QObject`. """ QObject.__init__(self, parent) self._setup_notifier(monitor, QSocketNotifier) class QUDevMonitorObserver(QObject, QUDevMonitorObserverMixin): """An observer for device events integrating into the :mod:`PyQt4` mainloop. .. deprecated:: 0.17 Will be removed in 1.0. Use :class:`MonitorObserver` instead. """ #: emitted upon arbitrary device events deviceEvent = pyqtSignal(text_type, Device) #: emitted, if a device was added deviceAdded = pyqtSignal(Device) #: emitted, if a device was removed deviceRemoved = pyqtSignal(Device) #: emitted, if a device was changed deviceChanged = pyqtSignal(Device) #: emitted, if a device was moved deviceMoved = pyqtSignal(Device) def __init__(self, monitor, parent=None): """ Observe the given ``monitor`` (a :class:`~pyudev.Monitor`): ``parent`` is the parent :class:`~PyQt4.QtCore.QObject` of this object. It is passed unchanged to the inherited constructor of :class:`~PyQt4.QtCore.QObject`. """ QObject.__init__(self, parent) self._setup_notifier(monitor, QSocketNotifier)<|fim▁end|>
# Free Software Foundation; either version 2.1 of the License, or (at your
<|file_name|>core.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Core Application - manage multiplexer connected with Analog Discovery 2 | receive voltage from sensors to estimate distance API : wavefroms API Author: Thatchakon Jom-ud """ from ctypes import * from dwfconstants import * import sys import time class Core(): hdwf = c_int() hzSys = c_double() volt = (c_double*1)() dwf = object distance = lambda self, volt: ((0.0325*(volt**3)) - (0.5832*(volt**2)) + (0.0768*volt) + 9.8164) def __init__(self, window): self.gui = window self.set_library() def set_library(self): if sys.platform.startswith("win"): self.dwf = cdll.dwf elif sys.platform.startswith("darwin"): self.dwf = cdll.LoadLibrary("/Library/Frameworks/dwf.framework/dwf") else: self.dwf = cdll.LoadLibrary("libdwf.so") def set_device(self): self.dwf.FDwfDeviceOpen(c_int(-1), byref(self.hdwf)) self.gui.status.emit("AD2: "+self.get_device_status()) if self.get_device_status() != "Not Connect": self.enable_power_supplies(True) self.setup_digital_output() return False def get_device_status(self): return "Connected" if (self.hdwf.value != hdwfNone.value) else "Not Connect" def enable_power_supplies(self, enable): # set up analog IO channel nodes # enable positive supply self.dwf.FDwfAnalogIOChannelNodeSet(self.hdwf, c_int(0), c_int(0), c_double(True)) # set voltage to 5 V self.dwf.FDwfAnalogIOChannelNodeSet(self.hdwf, c_int(0), c_int(1), c_double(5)) # enable negative supply self.dwf.FDwfAnalogIOChannelNodeSet(self.hdwf, c_int(1), c_int(0), c_double(True)) # set voltage to -5 V self.dwf.FDwfAnalogIOChannelNodeSet(self.hdwf, c_int(1), c_int(1), c_double(-5)) self.dwf.FDwfAnalogIOEnableSet(self.hdwf, c_int(enable)) def setup_digital_output(self): self.dwf.FDwfDigitalOutInternalClockInfo(self.hdwf, byref(self.hzSys)) self.dwf.FDwfDigitalOutEnableSet(self.hdwf, c_int(0), c_int(1)) # prescaler to 2kHz self.dwf.FDwfDigitalOutDividerSet(self.hdwf, c_int(0), c_int(int(self.hzSys.value / 2e3))) # 1 tick low, 1 tick high self.dwf.FDwfDigitalOutCounterSet(self.hdwf, c_int(0), c_int(1), c_int(1)) self.dwf.FDwfDigitalOutEnableSet(self.hdwf, c_int(1), c_int(1)) # prescaler to 2kHz self.dwf.FDwfDigitalOutDividerSet(self.hdwf, c_int(1), c_int(int(self.hzSys.value / 2e3)))<|fim▁hole|> self.dwf.FDwfDigitalOutCounterSet(self.hdwf, c_int(1), c_int(2), c_int(2)) self.dwf.FDwfDigitalOutEnableSet(self.hdwf, c_int(2), c_int(1)) # prescaler to 2kHz self.dwf.FDwfDigitalOutDividerSet(self.hdwf, c_int(2), c_int(int(self.hzSys.value / 2e3))) # 4 tick low, 4 tick high self.dwf.FDwfDigitalOutCounterSet(self.hdwf, c_int(2), c_int(4), c_int(4)) self.dwf.FDwfDigitalOutConfigure(self.hdwf, c_int(1)) def get_volt_and_distance(self): sts = c_byte() self.dwf.FDwfAnalogInFrequencySet(self.hdwf, c_double(20000000.0)) self.dwf.FDwfAnalogInBufferSizeSet(self.hdwf, c_int(4000)) self.dwf.FDwfAnalogInChannelEnableSet(self.hdwf, c_int(0), c_bool(True)) self.dwf.FDwfAnalogInConfigure(self.hdwf, c_bool(False), c_bool(True)) while True: self.dwf.FDwfAnalogInStatus(self.hdwf, c_int(1), byref(sts)) if sts.value == DwfStateDone.value: break time.sleep(0.1) self.dwf.FDwfAnalogInStatusData(self.hdwf, c_int(0), self.volt, 1) return self.volt[0], self.distance(self.volt[0]) def disconnect_ad2(self): self.enable_power_supplies(False) self.dwf.FDwfDeviceCloseAll() self.hdwf = c_int() self.gui.status.emit("AD2: Disconnected") return False<|fim▁end|>
# 2 tick low, 2 tick high
<|file_name|>s2_colorpicker.js<|end_file_name|><|fim▁begin|>// version 1.0 - original version jQuery(document).ready(function () { var version = jQuery.fn.jquery.split('.'); if (parseFloat(version[1]) < 7) { // use .live as we are on jQuery prior to 1.7 jQuery('.colorpickerField').live('click', function () { if (jQuery(this).attr('id').search("__i__") === -1) { var picker, field = jQuery(this).attr('id').substr(0, 20); jQuery('.s2_colorpicker').hide(); jQuery('.s2_colorpicker').each(function () { if (jQuery(this).attr('id').search(field) !== -1) { picker = jQuery(this).attr('id'); } }); jQuery.farbtastic('#' + picker).linkTo(this); jQuery('#' + picker).slideDown(); } }); } else { // use .on as we are using jQuery 1.7 and up where .live is deprecated jQuery(document).on('focus', '.colorpickerField', function () { if (jQuery(this).is('.s2_initialised') || this.id.search('__i__') !== -1) { return; // exit early, already initialized or not activated } jQuery(this).addClass('s2_initialised'); var picker, field = jQuery(this).attr('id').substr(0, 20); jQuery('.s2_colorpicker').each(function () { if (jQuery(this).attr('id').search(field) !== -1) { picker = jQuery(this).attr('id'); return false; // stop looping } }); jQuery(this).on('focusin', function (event) { jQuery('.s2_colorpicker').hide(); jQuery.farbtastic('#' + picker).linkTo(this); jQuery('#' + picker).slideDown(); }); jQuery(this).on('focusout', function (event) { jQuery('#' + picker).slideUp(); }); jQuery(this).trigger('focus'); // retrigger focus event for plugin to work });<|fim▁hole|>});<|fim▁end|>
}
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>use std::collections::{HashMap, HashSet}; use std::env; use std::ffi::{OsStr, OsString}; use std::fs; use std::io::{self, Write}; use std::path::{self, PathBuf}; use std::sync::Arc; use rustc_serialize::json; use core::{Package, PackageId, PackageSet, Target, Resolve}; use core::{Profile, Profiles, Workspace}; use core::shell::ColorConfig; use util::{self, CargoResult, ProcessBuilder, ProcessError, human, machine_message}; use util::{Config, internal, ChainError, profile, join_paths, short_hash}; use util::Freshness; use self::job::{Job, Work}; use self::job_queue::JobQueue; use self::output_depinfo::output_depinfo; pub use self::compilation::Compilation; pub use self::context::{Context, Unit}; pub use self::custom_build::{BuildOutput, BuildMap, BuildScripts}; mod compilation; mod context; mod custom_build; mod fingerprint; mod job; mod job_queue; mod layout; mod links; mod output_depinfo; #[derive(PartialEq, Eq, Hash, Debug, Clone, Copy, PartialOrd, Ord)] pub enum Kind { Host, Target } #[derive(Default, Clone)] pub struct BuildConfig { pub host_triple: String, pub host: TargetConfig, pub requested_target: Option<String>, pub target: TargetConfig, pub jobs: u32, pub release: bool, pub test: bool, pub doc_all: bool, pub json_messages: bool, } #[derive(Clone, Default)] pub struct TargetConfig { pub ar: Option<PathBuf>, pub linker: Option<PathBuf>, pub overrides: HashMap<String, BuildOutput>, } pub type PackagesToBuild<'a> = [(&'a Package, Vec<(&'a Target, &'a Profile)>)]; /// A glorified callback for executing calls to rustc. Rather than calling rustc /// directly, we'll use an Executor, giving clients an opportunity to intercept /// the build calls. pub trait Executor: Send + Sync + 'static { fn init(&self, _cx: &Context) {} /// If execution succeeds, the ContinueBuild value indicates whether Cargo /// should continue with the build process for this package. fn exec(&self, cmd: ProcessBuilder, _id: &PackageId) -> Result<(), ProcessError> { cmd.exec()?; Ok(()) } fn exec_json(&self, cmd: ProcessBuilder, _id: &PackageId, handle_stdout: &mut FnMut(&str) -> CargoResult<()>, handle_srderr: &mut FnMut(&str) -> CargoResult<()>) -> Result<(), ProcessError> { cmd.exec_with_streaming(handle_stdout, handle_srderr)?; Ok(()) } } /// A DefaultExecutor calls rustc without doing anything else. It is Cargo's /// default behaviour. #[derive(Copy, Clone)] pub struct DefaultExecutor; impl Executor for DefaultExecutor {} // Returns a mapping of the root package plus its immediate dependencies to // where the compiled libraries are all located. pub fn compile_targets<'a, 'cfg: 'a>(ws: &Workspace<'cfg>, pkg_targets: &'a PackagesToBuild<'a>, packages: &'a PackageSet<'cfg>, resolve: &'a Resolve, config: &'cfg Config, build_config: BuildConfig, profiles: &'a Profiles, exec: Arc<Executor>) -> CargoResult<Compilation<'cfg>> { let units = pkg_targets.iter().flat_map(|&(pkg, ref targets)| { let default_kind = if build_config.requested_target.is_some() { Kind::Target } else { Kind::Host }; targets.iter().map(move |&(target, profile)| { Unit { pkg: pkg, target: target, profile: profile, kind: if target.for_host() {Kind::Host} else {default_kind}, } }) }).collect::<Vec<_>>(); let mut cx = Context::new(ws, resolve, packages, config, build_config, profiles)?; let mut queue = JobQueue::new(&cx); cx.prepare()?; cx.probe_target_info(&units)?; cx.build_used_in_plugin_map(&units)?; custom_build::build_map(&mut cx, &units)?; for unit in units.iter() { // Build up a list of pending jobs, each of which represent // compiling a particular package. No actual work is executed as // part of this, that's all done next as part of the `execute` // function which will run everything in order with proper // parallelism. compile(&mut cx, &mut queue, unit, exec.clone())?; } // Now that we've figured out everything that we're going to do, do it! queue.execute(&mut cx)?; for unit in units.iter() { for (dst, link_dst, _linkable) in cx.target_filenames(unit)? { let bindst = match link_dst { Some(link_dst) => link_dst, None => dst.clone(), }; if unit.profile.test { cx.compilation.tests.push((unit.pkg.clone(), unit.target.name().to_string(), dst)); } else if unit.target.is_bin() || unit.target.is_example() { cx.compilation.binaries.push(bindst); } else if unit.target.is_lib() { let pkgid = unit.pkg.package_id().clone(); cx.compilation.libraries.entry(pkgid).or_insert(Vec::new()) .push((unit.target.clone(), dst)); } if !unit.target.is_lib() { continue } // Include immediate lib deps as well for unit in cx.dep_targets(unit)?.iter() { if unit.profile.run_custom_build { let out_dir = cx.build_script_out_dir(unit).display().to_string(); cx.compilation.extra_env.entry(unit.pkg.package_id().clone()) .or_insert(Vec::new()) .push(("OUT_DIR".to_string(), out_dir)); } let pkgid = unit.pkg.package_id(); if !unit.target.is_lib() { continue } if unit.profile.doc { continue } if cx.compilation.libraries.contains_key(&pkgid) { continue } let v = cx.target_filenames(unit)?; let v = v.into_iter().map(|(f, _, _)| { (unit.target.clone(), f) }).collect::<Vec<_>>(); cx.compilation.libraries.insert(pkgid.clone(), v); } } if let Some(feats) = cx.resolve.features(&unit.pkg.package_id()) { cx.compilation.cfgs.entry(unit.pkg.package_id().clone()) .or_insert(HashSet::new()) .extend(feats.iter().map(|feat| format!("feature=\"{}\"", feat))); } output_depinfo(&mut cx, unit)?; } for (&(ref pkg, _), output) in cx.build_state.outputs.lock().unwrap().iter() { cx.compilation.cfgs.entry(pkg.clone()) .or_insert(HashSet::new()) .extend(output.cfgs.iter().cloned()); for dir in output.library_paths.iter() { cx.compilation.native_dirs.insert(dir.clone()); } } cx.compilation.target = cx.target_triple().to_string(); Ok(cx.compilation) } fn compile<'a, 'cfg: 'a>(cx: &mut Context<'a, 'cfg>, jobs: &mut JobQueue<'a>, unit: &Unit<'a>, exec: Arc<Executor>) -> CargoResult<()> { if !cx.compiled.insert(*unit) { return Ok(()) } // Build up the work to be done to compile this unit, enqueuing it once // we've got everything constructed. let p = profile::start(format!("preparing: {}/{}", unit.pkg, unit.target.name())); fingerprint::prepare_init(cx, unit)?; cx.links.validate(unit)?; let (dirty, fresh, freshness) = if unit.profile.run_custom_build { custom_build::prepare(cx, unit)? } else if unit.profile.doc && unit.profile.test { // we run these targets later, so this is just a noop for now (Work::new(|_| Ok(())), Work::new(|_| Ok(())), Freshness::Fresh) } else { let (freshness, dirty, fresh) = fingerprint::prepare_target(cx, unit)?; let work = if unit.profile.doc { rustdoc(cx, unit)? } else { rustc(cx, unit, exec.clone())? }; let link_work1 = link_targets(cx, unit)?; let link_work2 = link_targets(cx, unit)?; // Need to link targets on both the dirty and fresh let dirty = work.then(link_work1).then(dirty); let fresh = link_work2.then(fresh); (dirty, fresh, freshness) }; jobs.enqueue(cx, unit, Job::new(dirty, fresh), freshness)?; drop(p); // Be sure to compile all dependencies of this target as well. for unit in cx.dep_targets(unit)?.iter() { compile(cx, jobs, unit, exec.clone())?; } Ok(()) } fn rustc(cx: &mut Context, unit: &Unit, exec: Arc<Executor>) -> CargoResult<Work> { let crate_types = unit.target.rustc_crate_types(); let mut rustc = prepare_rustc(cx, crate_types, unit)?; let name = unit.pkg.name().to_string(); if !cx.show_warnings(unit.pkg.package_id()) { if cx.config.rustc()?.cap_lints { rustc.arg("--cap-lints").arg("allow"); } else { rustc.arg("-Awarnings"); } } let filenames = cx.target_filenames(unit)?; let root = cx.out_dir(unit); // Prepare the native lib state (extra -L and -l flags) let build_state = cx.build_state.clone(); let current_id = unit.pkg.package_id().clone(); let build_deps = load_build_deps(cx, unit); // If we are a binary and the package also contains a library, then we // don't pass the `-l` flags. let pass_l_flag = unit.target.is_lib() || !unit.pkg.targets().iter().any(|t| t.is_lib()); let do_rename = unit.target.allows_underscores() && !unit.profile.test; let real_name = unit.target.name().to_string(); let crate_name = unit.target.crate_name(); // XXX(Rely on target_filenames iterator as source of truth rather than rederiving filestem) let rustc_dep_info_loc = if do_rename && cx.target_metadata(unit).is_none() { root.join(&crate_name) } else { root.join(&cx.file_stem(unit)) }.with_extension("d"); let dep_info_loc = fingerprint::dep_info_loc(cx, unit); let cwd = cx.config.cwd().to_path_buf(); rustc.args(&cx.incremental_args(unit)?); rustc.args(&cx.rustflags_args(unit)?); let json_messages = cx.build_config.json_messages; let package_id = unit.pkg.package_id().clone(); let target = unit.target.clone(); let profile = unit.profile.clone(); let features = cx.resolve.features(unit.pkg.package_id()) .into_iter() .flat_map(|i| i) .map(|s| s.to_string()) .collect::<Vec<_>>(); exec.init(cx); let exec = exec.clone(); return Ok(Work::new(move |state| { // Only at runtime have we discovered what the extra -L and -l // arguments are for native libraries, so we process those here. We // also need to be sure to add any -L paths for our plugins to the // dynamic library load path as a plugin's dynamic library may be // located somewhere in there. if let Some(build_deps) = build_deps { let build_state = build_state.outputs.lock().unwrap(); add_native_deps(&mut rustc, &build_state, &build_deps, pass_l_flag, &current_id)?; add_plugin_deps(&mut rustc, &build_state, &build_deps)?; } // FIXME(rust-lang/rust#18913): we probably shouldn't have to do // this manually for &(ref filename, ref _link_dst, _linkable) in filenames.iter() { let mut dsts = vec![root.join(filename)]; // If there is both an rmeta and rlib, rustc will prefer to use the // rlib, even if it is older. Therefore, we must delete the rlib to // force using the new rmeta. if dsts[0].extension() == Some(&OsStr::new("rmeta")) { dsts.push(root.join(filename).with_extension("rlib"));<|fim▁hole|> if fs::metadata(dst).is_ok() { fs::remove_file(dst).chain_error(|| { human(format!("Could not remove file: {}.", dst.display())) })?; } } } state.running(&rustc); if json_messages { exec.exec_json(rustc, &package_id, &mut |line| if !line.is_empty() { Err(internal(&format!("compiler stdout is not empty: `{}`", line))) } else { Ok(()) }, &mut |line| { // stderr from rustc can have a mix of JSON and non-JSON output if line.starts_with("{") { // Handle JSON lines let compiler_message = json::Json::from_str(line).map_err(|_| { internal(&format!("compiler produced invalid json: `{}`", line)) })?; machine_message::emit(machine_message::FromCompiler { package_id: &package_id, target: &target, message: compiler_message, }); } else { // Forward non-JSON to stderr writeln!(io::stderr(), "{}", line)?; } Ok(()) } ).chain_error(|| { human(format!("Could not compile `{}`.", name)) })?; } else { exec.exec(rustc, &package_id).chain_error(|| { human(format!("Could not compile `{}`.", name)) })?; } if do_rename && real_name != crate_name { let dst = &filenames[0].0; let src = dst.with_file_name(dst.file_name().unwrap() .to_str().unwrap() .replace(&real_name, &crate_name)); if src.exists() { fs::rename(&src, &dst).chain_error(|| { internal(format!("could not rename crate {:?}", src)) })?; } } if fs::metadata(&rustc_dep_info_loc).is_ok() { info!("Renaming dep_info {:?} to {:?}", rustc_dep_info_loc, dep_info_loc); fs::rename(&rustc_dep_info_loc, &dep_info_loc).chain_error(|| { internal(format!("could not rename dep info: {:?}", rustc_dep_info_loc)) })?; fingerprint::append_current_dir(&dep_info_loc, &cwd)?; } if json_messages { machine_message::emit(machine_message::Artifact { package_id: &package_id, target: &target, profile: &profile, features: features, filenames: filenames.iter().map(|&(ref src, _, _)| { src.display().to_string() }).collect(), }); } Ok(()) })); // Add all relevant -L and -l flags from dependencies (now calculated and // present in `state`) to the command provided fn add_native_deps(rustc: &mut ProcessBuilder, build_state: &BuildMap, build_scripts: &BuildScripts, pass_l_flag: bool, current_id: &PackageId) -> CargoResult<()> { for key in build_scripts.to_link.iter() { let output = build_state.get(key).chain_error(|| { internal(format!("couldn't find build state for {}/{:?}", key.0, key.1)) })?; for path in output.library_paths.iter() { rustc.arg("-L").arg(path); } if key.0 == *current_id { for cfg in &output.cfgs { rustc.arg("--cfg").arg(cfg); } if pass_l_flag { for name in output.library_links.iter() { rustc.arg("-l").arg(name); } } } } Ok(()) } } /// Link the compiled target (often of form foo-{metadata_hash}) to the /// final target. This must happen during both "Fresh" and "Compile" fn link_targets(cx: &mut Context, unit: &Unit) -> CargoResult<Work> { let filenames = cx.target_filenames(unit)?; Ok(Work::new(move |_| { // If we're a "root crate", e.g. the target of this compilation, then we // hard link our outputs out of the `deps` directory into the directory // above. This means that `cargo build` will produce binaries in // `target/debug` which one probably expects. for (src, link_dst, _linkable) in filenames { // This may have been a `cargo rustc` command which changes the // output, so the source may not actually exist. debug!("Thinking about linking {} to {:?}", src.display(), link_dst); if !src.exists() || link_dst.is_none() { continue } let dst = link_dst.unwrap(); debug!("linking {} to {}", src.display(), dst.display()); if dst.exists() { fs::remove_file(&dst).chain_error(|| { human(format!("failed to remove: {}", dst.display())) })?; } fs::hard_link(&src, &dst) .or_else(|err| { debug!("hard link failed {}. falling back to fs::copy", err); fs::copy(&src, &dst).map(|_| ()) }) .chain_error(|| { human(format!("failed to link or copy `{}` to `{}`", src.display(), dst.display())) })?; } Ok(()) })) } fn load_build_deps(cx: &Context, unit: &Unit) -> Option<Arc<BuildScripts>> { cx.build_scripts.get(unit).cloned() } // For all plugin dependencies, add their -L paths (now calculated and // present in `state`) to the dynamic library load path for the command to // execute. fn add_plugin_deps(rustc: &mut ProcessBuilder, build_state: &BuildMap, build_scripts: &BuildScripts) -> CargoResult<()> { let var = util::dylib_path_envvar(); let search_path = rustc.get_env(var).unwrap_or(OsString::new()); let mut search_path = env::split_paths(&search_path).collect::<Vec<_>>(); for id in build_scripts.plugins.iter() { let key = (id.clone(), Kind::Host); let output = build_state.get(&key).chain_error(|| { internal(format!("couldn't find libs for plugin dep {}", id)) })?; for path in output.library_paths.iter() { search_path.push(path.clone()); } } let search_path = join_paths(&search_path, var)?; rustc.env(var, &search_path); Ok(()) } fn prepare_rustc(cx: &mut Context, crate_types: Vec<&str>, unit: &Unit) -> CargoResult<ProcessBuilder> { let mut base = cx.compilation.rustc_process(unit.pkg)?; build_base_args(cx, &mut base, unit, &crate_types); build_deps_args(&mut base, cx, unit)?; Ok(base) } fn rustdoc(cx: &mut Context, unit: &Unit) -> CargoResult<Work> { let mut rustdoc = cx.compilation.rustdoc_process(unit.pkg)?; rustdoc.arg("--crate-name").arg(&unit.target.crate_name()) .cwd(cx.config.cwd()) .arg(&root_path(cx, unit)); if unit.kind != Kind::Host { if let Some(target) = cx.requested_target() { rustdoc.arg("--target").arg(target); } } let doc_dir = cx.out_dir(unit); // Create the documentation directory ahead of time as rustdoc currently has // a bug where concurrent invocations will race to create this directory if // it doesn't already exist. fs::create_dir_all(&doc_dir)?; rustdoc.arg("-o").arg(doc_dir); if let Some(features) = cx.resolve.features(unit.pkg.package_id()) { for feat in features { rustdoc.arg("--cfg").arg(&format!("feature=\"{}\"", feat)); } } if let Some(ref args) = unit.profile.rustdoc_args { rustdoc.args(args); } build_deps_args(&mut rustdoc, cx, unit)?; rustdoc.args(&cx.rustdocflags_args(unit)?); let name = unit.pkg.name().to_string(); let build_state = cx.build_state.clone(); let key = (unit.pkg.package_id().clone(), unit.kind); Ok(Work::new(move |state| { if let Some(output) = build_state.outputs.lock().unwrap().get(&key) { for cfg in output.cfgs.iter() { rustdoc.arg("--cfg").arg(cfg); } } state.running(&rustdoc); rustdoc.exec().chain_error(|| { human(format!("Could not document `{}`.", name)) }) })) } // The path that we pass to rustc is actually fairly important because it will // show up in error messages and the like. For this reason we take a few moments // to ensure that something shows up pretty reasonably. // // The heuristic here is fairly simple, but the key idea is that the path is // always "relative" to the current directory in order to be found easily. The // path is only actually relative if the current directory is an ancestor if it. // This means that non-path dependencies (git/registry) will likely be shown as // absolute paths instead of relative paths. fn root_path(cx: &Context, unit: &Unit) -> PathBuf { let absolute = unit.pkg.root().join(unit.target.src_path()); let cwd = cx.config.cwd(); if absolute.starts_with(cwd) { util::without_prefix(&absolute, cwd).map(|s| { s.to_path_buf() }).unwrap_or(absolute) } else { absolute } } fn build_base_args(cx: &mut Context, cmd: &mut ProcessBuilder, unit: &Unit, crate_types: &[&str]) { let Profile { ref opt_level, lto, codegen_units, ref rustc_args, debuginfo, debug_assertions, rpath, test, doc: _doc, run_custom_build, ref panic, rustdoc_args: _, check, } = *unit.profile; assert!(!run_custom_build); // Move to cwd so the root_path() passed below is actually correct cmd.cwd(cx.config.cwd()); cmd.arg("--crate-name").arg(&unit.target.crate_name()); cmd.arg(&root_path(cx, unit)); let color_config = cx.config.shell().color_config(); if color_config != ColorConfig::Auto { cmd.arg("--color").arg(&color_config.to_string()); } if cx.build_config.json_messages { cmd.arg("--error-format").arg("json"); } if !test { for crate_type in crate_types.iter() { cmd.arg("--crate-type").arg(crate_type); } } if check { cmd.arg("--emit=dep-info,metadata"); } else { cmd.arg("--emit=dep-info,link"); } let prefer_dynamic = (unit.target.for_host() && !unit.target.is_custom_build()) || (crate_types.contains(&"dylib") && cx.ws.members().find(|&p| p != unit.pkg).is_some()); if prefer_dynamic { cmd.arg("-C").arg("prefer-dynamic"); } if opt_level != "0" { cmd.arg("-C").arg(&format!("opt-level={}", opt_level)); } // If a panic mode was configured *and* we're not ever going to be used in a // plugin, then we can compile with that panic mode. // // If we're used in a plugin then we'll eventually be linked to libsyntax // most likely which isn't compiled with a custom panic mode, so we'll just // get an error if we actually compile with that. This fixes `panic=abort` // crates which have plugin dependencies, but unfortunately means that // dependencies shared between the main application and plugins must be // compiled without `panic=abort`. This isn't so bad, though, as the main // application will still be compiled with `panic=abort`. if let Some(panic) = panic.as_ref() { if !cx.used_in_plugin.contains(unit) { cmd.arg("-C").arg(format!("panic={}", panic)); } } // Disable LTO for host builds as prefer_dynamic and it are mutually // exclusive. if unit.target.can_lto() && lto && !unit.target.for_host() { cmd.args(&["-C", "lto"]); } else { // There are some restrictions with LTO and codegen-units, so we // only add codegen units when LTO is not used. if let Some(n) = codegen_units { cmd.arg("-C").arg(&format!("codegen-units={}", n)); } } if let Some(debuginfo) = debuginfo { cmd.arg("-C").arg(format!("debuginfo={}", debuginfo)); } if let Some(ref args) = *rustc_args { cmd.args(args); } if debug_assertions && opt_level != "0" { cmd.args(&["-C", "debug-assertions=on"]); } else if !debug_assertions && opt_level == "0" { cmd.args(&["-C", "debug-assertions=off"]); } if test && unit.target.harness() { cmd.arg("--test"); } else if test { cmd.arg("--cfg").arg("test"); } if let Some(features) = cx.resolve.features(unit.pkg.package_id()) { for feat in features.iter() { cmd.arg("--cfg").arg(&format!("feature=\"{}\"", feat)); } } match cx.target_metadata(unit) { Some(m) => { cmd.arg("-C").arg(&format!("metadata={}", m)); cmd.arg("-C").arg(&format!("extra-filename=-{}", m)); } None => { cmd.arg("-C").arg(&format!("metadata={}", short_hash(unit.pkg))); } } if rpath { cmd.arg("-C").arg("rpath"); } cmd.arg("--out-dir").arg(&cx.out_dir(unit)); fn opt(cmd: &mut ProcessBuilder, key: &str, prefix: &str, val: Option<&OsStr>) { if let Some(val) = val { let mut joined = OsString::from(prefix); joined.push(val); cmd.arg(key).arg(joined); } } if unit.kind == Kind::Target { opt(cmd, "--target", "", cx.requested_target().map(|s| s.as_ref())); } opt(cmd, "-C", "ar=", cx.ar(unit.kind).map(|s| s.as_ref())); opt(cmd, "-C", "linker=", cx.linker(unit.kind).map(|s| s.as_ref())); } fn build_deps_args(cmd: &mut ProcessBuilder, cx: &mut Context, unit: &Unit) -> CargoResult<()> { cmd.arg("-L").arg(&{ let mut deps = OsString::from("dependency="); deps.push(cx.deps_dir(unit)); deps }); // Be sure that the host path is also listed. This'll ensure that proc-macro // dependencies are correctly found (for reexported macros). if let Kind::Target = unit.kind { cmd.arg("-L").arg(&{ let mut deps = OsString::from("dependency="); deps.push(cx.host_deps()); deps }); } for unit in cx.dep_targets(unit)?.iter() { if unit.profile.run_custom_build { cmd.env("OUT_DIR", &cx.build_script_out_dir(unit)); } if unit.target.linkable() && !unit.profile.doc { link_to(cmd, cx, unit)?; } } return Ok(()); fn link_to(cmd: &mut ProcessBuilder, cx: &mut Context, unit: &Unit) -> CargoResult<()> { for (dst, _link_dst, linkable) in cx.target_filenames(unit)? { if !linkable { continue } let mut v = OsString::new(); v.push(&unit.target.crate_name()); v.push("="); v.push(cx.out_dir(unit)); v.push(&path::MAIN_SEPARATOR.to_string()); v.push(&dst.file_name().unwrap()); cmd.arg("--extern").arg(&v); } Ok(()) } } fn envify(s: &str) -> String { s.chars() .flat_map(|c| c.to_uppercase()) .map(|c| if c == '-' {'_'} else {c}) .collect() } impl Kind { fn for_target(&self, target: &Target) -> Kind { // Once we start compiling for the `Host` kind we continue doing so, but // if we are a `Target` kind and then we start compiling for a target // that needs to be on the host we lift ourselves up to `Host` match *self { Kind::Host => Kind::Host, Kind::Target if target.for_host() => Kind::Host, Kind::Target => Kind::Target, } } }<|fim▁end|>
} for dst in &dsts {
<|file_name|>offlinequeue.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ wakatime.offlinequeue ~~~~~~~~~~~~~~~~~~~~~ Queue for saving heartbeats while offline. :copyright: (c) 2014 Alan Hamlett. :license: BSD, see LICENSE for more details. """ import logging<|fim▁hole|>from time import sleep from .compat import json from .constants import DEFAULT_SYNC_OFFLINE_ACTIVITY, HEARTBEATS_PER_REQUEST from .heartbeat import Heartbeat try: import sqlite3 HAS_SQL = True except ImportError: # pragma: nocover HAS_SQL = False log = logging.getLogger('WakaTime') class Queue(object): db_file = '.wakatime.db' table_name = 'heartbeat_2' args = None configs = None def __init__(self, args, configs): self.args = args self.configs = configs def connect(self): conn = sqlite3.connect(self._get_db_file(), isolation_level=None) c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS {0} ( id text, heartbeat text) '''.format(self.table_name)) return (conn, c) def push(self, heartbeat): if not HAS_SQL: return try: conn, c = self.connect() data = { 'id': heartbeat.get_id(), 'heartbeat': heartbeat.json(), } c.execute('INSERT INTO {0} VALUES (:id,:heartbeat)'.format(self.table_name), data) conn.commit() conn.close() except sqlite3.Error: log.traceback() def pop(self): if not HAS_SQL: return None tries = 3 wait = 0.1 try: conn, c = self.connect() except sqlite3.Error: log.traceback(logging.DEBUG) return None heartbeat = None loop = True while loop and tries > -1: try: c.execute('BEGIN IMMEDIATE') c.execute('SELECT * FROM {0} LIMIT 1'.format(self.table_name)) row = c.fetchone() if row is not None: id = row[0] heartbeat = Heartbeat(json.loads(row[1]), self.args, self.configs, _clone=True) c.execute('DELETE FROM {0} WHERE id=?'.format(self.table_name), [id]) conn.commit() loop = False except sqlite3.Error: log.traceback(logging.DEBUG) sleep(wait) tries -= 1 try: conn.close() except sqlite3.Error: log.traceback(logging.DEBUG) return heartbeat def push_many(self, heartbeats): for heartbeat in heartbeats: self.push(heartbeat) def pop_many(self, limit=None): if limit is None: limit = DEFAULT_SYNC_OFFLINE_ACTIVITY heartbeats = [] count = 0 while count < limit: heartbeat = self.pop() if not heartbeat: break heartbeats.append(heartbeat) count += 1 if count % HEARTBEATS_PER_REQUEST == 0: yield heartbeats heartbeats = [] if heartbeats: yield heartbeats def _get_db_file(self): home = '~' if os.environ.get('WAKATIME_HOME'): home = os.environ.get('WAKATIME_HOME') return os.path.join(os.path.expanduser(home), '.wakatime.db')<|fim▁end|>
import os
<|file_name|>MediatorFlow11CreateCommand.java<|end_file_name|><|fim▁begin|>package org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.commands; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.emf.ecore.EObject; import org.eclipse.gmf.runtime.common.core.command.CommandResult; import org.eclipse.gmf.runtime.common.core.command.ICommand; import org.eclipse.gmf.runtime.emf.type.core.IElementType; import org.eclipse.gmf.runtime.emf.type.core.commands.EditElementCommand; import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest; import org.eclipse.gmf.runtime.emf.type.core.requests.CreateElementRequest; import org.eclipse.gmf.runtime.notation.View; import org.wso2.developerstudio.eclipse.gmf.esb.CloneTargetContainer; import org.wso2.developerstudio.eclipse.gmf.esb.EsbFactory; import org.wso2.developerstudio.eclipse.gmf.esb.MediatorFlow; /** * @generated */ public class MediatorFlow11CreateCommand extends EditElementCommand { /** * @generated */ public MediatorFlow11CreateCommand(CreateElementRequest req) { super(req.getLabel(), null, req); } /** * FIXME: replace with setElementToEdit() * @generated */ protected EObject getElementToEdit() { EObject container = ((CreateElementRequest) getRequest()).getContainer(); if (container instanceof View) { container = ((View) container).getElement(); } return container; } /** * @generated */ public boolean canExecute() { CloneTargetContainer container = (CloneTargetContainer) getElementToEdit(); if (container.getMediatorFlow() != null) { return false; } return true; } /** * @generated<|fim▁hole|> CloneTargetContainer owner = (CloneTargetContainer) getElementToEdit(); owner.setMediatorFlow(newElement); doConfigure(newElement, monitor, info); ((CreateElementRequest) getRequest()).setNewElement(newElement); return CommandResult.newOKCommandResult(newElement); } /** * @generated */ protected void doConfigure(MediatorFlow newElement, IProgressMonitor monitor, IAdaptable info) throws ExecutionException { IElementType elementType = ((CreateElementRequest) getRequest()).getElementType(); ConfigureRequest configureRequest = new ConfigureRequest(getEditingDomain(), newElement, elementType); configureRequest.setClientContext(((CreateElementRequest) getRequest()).getClientContext()); configureRequest.addParameters(getRequest().getParameters()); ICommand configureCommand = elementType.getEditCommand(configureRequest); if (configureCommand != null && configureCommand.canExecute()) { configureCommand.execute(monitor, info); } } }<|fim▁end|>
*/ protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { MediatorFlow newElement = EsbFactory.eINSTANCE.createMediatorFlow();
<|file_name|>system_info_wdg.py<|end_file_name|><|fim▁begin|>########################################################### # # Copyright (c) 2010, Southpaw Technology # All Rights Reserved # # PROPRIETARY INFORMATION. This software is proprietary to # Southpaw Technology, and is not to be reproduced, transmitted, # or disclosed in any way without written permission. # # __all__ = [ 'SystemInfoWdg', 'LinkLoadTestWdg' ,'ClearSideBarCache'] import os, platform, sys from pyasm.common import Environment, Config, Common from pyasm.security import Login from tactic.ui.common import BaseRefreshWdg from pyasm.web import DivWdg, Table, WebContainer, Widget, SpanWdg from pyasm.search import Search from pyasm.biz import Project from pyasm.widget import CheckboxWdg, TextWdg from pyasm.command import Command from tactic.ui.widget import ActionButtonWdg class SystemInfoWdg(BaseRefreshWdg): def get_display(self): top = DivWdg() top.add_color("background", "background") top.add_color("color", "color") top.add_style("min-width: 600px") os_name = os.name top.set_unique_id() top.add_smart_style("spt_info_title", "background", self.top.get_color("background3")) top.add_smart_style("spt_info_title", "padding", "3px") top.add_smart_style("spt_info_title", "font-weight", "bold") # server title_div = DivWdg() top.add(title_div) title_div.add("Server") title_div.add_class("spt_info_title") os_div = DivWdg() top.add(os_div) os_info = platform.uname() try: os_login = os.getlogin() except Exception: os_login = os.environ.get("LOGNAME") table = Table() table.add_color("color", "color") table.add_style("margin: 10px") os_div.add(table) for i, title in enumerate(['OS','Node Name','Release','Version','Machine']): table.add_row() td = table.add_cell("%s: " % title) td.add_style("width: 150px") table.add_cell( os_info[i] ) table.add_row() table.add_cell("CPU Count: ") try : import multiprocessing table.add_cell( multiprocessing.cpu_count() ) except (ImportError, NotImplementedError): table.add_cell( "n/a" ) table.add_row() table.add_cell("Login: ") table.add_cell( os_login ) # python title_div = DivWdg() top.add(title_div) title_div.add("Python") title_div.add_class("spt_info_title") table = Table() table.add_color("color", "color") table.add_style("margin: 10px") top.add(table) table.add_row() td = table.add_cell("Version: ") td.add_style("width: 150px") table.add_cell( sys.version ) # client title_div = DivWdg() top.add(title_div) title_div.add("Client") title_div.add_class("spt_info_title") web = WebContainer.get_web() user_agent = web.get_env("HTTP_USER_AGENT") table = Table() table.add_color("color", "color") table.add_style("margin: 10px") top.add(table) table.add_row() td = table.add_cell("User Agent: ") td.add_style("width: 150px") table.add_cell( user_agent ) table.add_row() td = table.add_cell("TACTIC User: ") table.add_cell( web.get_user_name() ) top.add('<br/>') self.handle_load_balancing(top) # performance test top.add('<br/>') title_div = DivWdg() top.add(title_div) title_div.add("Performance Test") title_div.add_class("spt_info_title") performance_wdg = PerformanceWdg() top.add(performance_wdg) top.add('<br/>') # mail server title_div = DivWdg() top.add(title_div) title_div.add("Mail Server") title_div.add_class("spt_info_title") table = Table(css='email_server') table.add_color("color", "color") table.add_style("margin: 10px") top.add(table) table.add_row() td = table.add_cell("Server: ") td.add_style("width: 150px") mailserver = Config.get_value("services", "mailserver") has_mailserver = True if mailserver: table.add_cell( mailserver ) else: table.add_cell("None configured") has_mailserver = False login = Login.get_by_login('admin') login_email = login.get_value('email') table.add_row() td = table.add_cell("From: ") td.add_style("width: 150px") text = TextWdg('email_from') text.set_attr('size', '40') text.set_value(login_email) text.add_class('email_from') table.add_cell(text) table.add_row() td = table.add_cell("To: ") td.add_style("width: 150px") text = TextWdg('email_to') text.set_attr('size', '40') text.add_class('email_to') text.set_value(login_email) table.add_cell(text) button = ActionButtonWdg(title='Email Send Test') table.add_row_cell('<br/>') table.add_row() table.add_cell(button) button.add_style("float: right") button.add_behavior( { 'type': 'click_up', 'has_mailserver': has_mailserver, 'cbjs_action': ''' if (!bvr.has_mailserver) { spt.alert('You have to fill in mailserver and possibly other mail related options in the TACTIC config file to send email.'); return; } var s = TacticServerStub.get(); try { spt.app_busy.show('Sending email'); var from_txt = bvr.src_el.getParent('.email_server').getElement('.email_from'); var to_txt = bvr.src_el.getParent('.email_server').getElement('.email_to'); var rtn = s.execute_cmd('pyasm.command.EmailTriggerTestCmd', {'sender_email': from_txt.value, 'recipient_emails': to_txt.value.split(','), 'msg': 'Simple Email Test by TACTIC'} ); if (rtn.status == 'OK') { spt.info("Email sent successfully to " + to_txt.value) } } catch(e) { spt.alert(spt.exception.handler(e)); } spt.app_busy.hide(); ''' }) top.add('<br/>') self.handle_directories(top) #table.add_row() #td = table.add_cell("TACTIC User: ") #table.add_cell( web.get_user_name() ) top.add('<br/>') top.add(DivWdg('Link Test', css='spt_info_title')) top.add('<br/>') top.add(LinkLoadTestWdg()) top.add('<br/>') self.handle_python_script_test(top) top.add('<br/>') self.handle_sidebar_clear(top) return top def handle_directories(self, top): # deal with asset directories top.add(DivWdg('Asset Folders', css='spt_info_title')) mailserver = Config.get_value("services", "mailserver") table = Table() table.add_color("color", "color") table.add_style("margin: 10px") top.add(table) table.add_row() td = table.add_cell("asset_base_dir: ") td.add_style("width: 150px") asset_base_dir = Config.get_value("checkin", "asset_base_dir") if asset_base_dir: table.add_cell( asset_base_dir ) tr = table.add_row() tr.add_style('border-bottom: 1px #bbb solid') # check if it is writable is_writable = os.access(asset_base_dir, os.W_OK) span = SpanWdg("writable:") span.add_style('padding-left: 20px') td = table.add_cell(span) td = table.add_cell(str(is_writable)) else: table.add_cell( "None configured") client_os = Environment.get_env_object().get_client_os() if os.name == 'nt': os_name = 'win32' else: os_name = 'linux' if client_os == 'nt':<|fim▁hole|> client_os_name = 'win32' else: client_os_name = 'linux' env = Environment.get() client_handoff_dir = env.get_client_handoff_dir(include_ticket=False, no_exception=True) client_asset_dir = env.get_client_repo_dir() table.add_row() td = table.add_cell("%s_server_handoff_dir: " % os_name) td.add_style("width: 150px") handoff_dir = Config.get_value("checkin", "%s_server_handoff_dir" % os_name) if handoff_dir: table.add_cell( handoff_dir ) table.add_row() # check if it is writable is_writable = os.access(handoff_dir, os.W_OK) span = SpanWdg("writable:") span.add_style('padding-left: 20px') td = table.add_cell(span) td = table.add_cell(str(is_writable)) else: table.add_cell( "None configured") table.add_row() td = table.add_cell("%s hand-off test: " % client_os_name) td.add_style("width: 150px") button = ActionButtonWdg(title='Test') button.add_behavior( { 'type': 'click_up', 'handoff_dir': client_handoff_dir, 'asset_dir': client_asset_dir, 'cbjs_action': ''' var env = spt.Environment.get(); var applet = spt.Applet.get(); var handoff_state = applet.exists(bvr.handoff_dir); var asset_state = applet.exists(bvr.asset_dir); if (asset_state == false) { env.set_transfer_mode("web"); spt.error('client repo directory is not accessible: ' + bvr.asset_dir); } else if (handoff_state == false) { env.set_transfer_mode("web"); spt.error('client handoff directory is not accessible: ' + bvr.handoff_dir); } else { env.set_transfer_mode("copy"); spt.info('<div>client handoff directory: ' + bvr.handoff_dir + '</div><br/><div>client repo directory :' + bvr.asset_dir + '</div><br/><div> can be successfully accessed.</div>', {type:'html'}); } ''' } ) table.add_cell( button ) def handle_python_script_test(self, top): top.add(DivWdg('Python Script Test', css='spt_info_title')) table = Table(css='script') table.add_color("color", "color") table.add_style("margin: 10px") table.add_style("width: 100%") top.add(table) table.add_row() td = table.add_cell("Script Path: ") td.add_style("width: 150px") text = TextWdg('script_path') td = table.add_cell(text) button = ActionButtonWdg(title='Run') table.add_cell(button) button.add_style("float: right") button.add_behavior( { 'type': 'click_up', 'cbjs_action': ''' var s = TacticServerStub.get(); try { var path = bvr.src_el.getParent('.script').getElement('.spt_input').value; if (! path) throw('Please enter a valid script path'); s.execute_cmd('tactic.command.PythonCmd', {script_path: path}); } catch(e) { spt.alert(spt.exception.handler(e)); } ''' }) def handle_load_balancing(self, top): # deal with asset directories top.add(DivWdg('Load Balancing', css='spt_info_title')) table = Table() table.add_class("spt_loadbalance") table.add_color("color", "color") table.add_style("margin: 10px") top.add(table) table.add_row() td = table.add_cell("Load Balancing: ") td.add_style("width: 150px") button = ActionButtonWdg(title='Test') td = table.add_cell(button) message_div = DivWdg() message_div.add_class("spt_loadbalance_message") table.add_cell(message_div) button.add_behavior( { 'type': 'click_up', 'cbjs_action': ''' var server = TacticServerStub.get() var ports = {}; var count = 0; for (var i = 0; i < 50; i++) { var info = server.get_connection_info(); var port = info.port; var num = ports[port]; if (!num) { ports[port] = 1; count += 1; } else { ports[port] += 1; } // if there are 10 requests and still only one, then break if (i == 10 && count == 1) break; } // build the ports string x = []; for (i in ports) { x.push(i); } x.sort(); x = x.join(", "); var loadbalance_el = bvr.src_el.getParent(".spt_loadbalance"); var message_el = loadbalance_el.getElement(".spt_loadbalance_message"); if (count > 1) { var message = "Yes (found " + count + " ports: "+x+")"; } else { var message = "<blink style='background: red; padding: 3px'>Not enabled (found only port " + x + ")</blink>"; } message_el.innerHTML = message ''' } ) def handle_sidebar_clear(self, top): top.add(DivWdg('Clear Side Bar Cache ', css='spt_info_title')) table = Table() table.add_color("color", "color") table.add_style("margin: 10px") top.add(table) table.add_row() td = table.add_cell("Clear the Side Bar Cache for all users") td.add_style("width: 250px") button = ActionButtonWdg(title='Run') table.add_cell(button) button.add_behavior( { 'type': 'click_up', 'cbjs_action': ''' try { var s = TacticServerStub.get(); s.execute_cmd('tactic.ui.app.ClearSideBarCache'); } catch(e) { spt.alert(spt.exception.handler(e)); } spt.info('Side Bar cache cleared.') ''' }) class ClearSideBarCache(Command): def execute(self): tmp_dir = Environment.get_tmp_dir() # remove the sidebar cache sidebar_cache_dir = "%s/cache/side_bar" % tmp_dir if os.path.exists(sidebar_cache_dir): import shutil shutil.rmtree(sidebar_cache_dir) class LinkLoadTestWdg(BaseRefreshWdg): '''Load Pages in popup as part of a testing process''' def get_display(self): config_search_type = "config/widget_config" configs = [] all_element_names = [] from tactic.ui.panel import SideBarBookmarkMenuWdg SideBarBookmarkMenuWdg.add_internal_config(configs, ['definition']) for internal_config in configs: all_element_names = internal_config.get_element_names() search = Search(config_search_type) search.add_filter("search_type", 'SideBarWdg') search.add_filter("view", 'definition') search.add_filter("login", None) config = search.get_sobject() element_names = [] if config: element_names = config.get_element_names() for name in element_names: if 'separator' in name: element_names.remove(name) all_element_names.extend(element_names) all_element_names = [str(name) for name in all_element_names] all_element_names = Common.get_unique_list(all_element_names) widget = DivWdg(css='spt_load_test_top') span = SpanWdg('This loads all the pages defined in the Project views in popups. It will take a few minutes.') widget.add(span) widget.add('<br/>') div = ActionButtonWdg(title='Run') web = WebContainer.get_web() base_url = web.get_base_url().to_string() base_url = '%s/tactic/%s' %(base_url, Project.get_project_code()) div.add_behavior({'type': 'click_up', 'cbjs_action': ''' var element_names = eval(%s); var all_element_names = eval(%s); var top = spt.get_parent(bvr.src_el, '.spt_load_test_top'); var cb = spt.get_element(top, '.spt_input') if (cb.checked) element_list = all_element_names; else element_list = element_names for (var k=0; k < element_list.length; k++) { var name = element_list[k]; //if (k > 3) break; var url = '%s/#/link/' + name; var bvr2 = { title: name, target_id: 'TEST', options: {'link': name, 'title': name, 'path': '/Link Test/' + name }, is_popup: true}; spt.side_bar.display_link_cbk(null, bvr2); } ''' %(element_names, all_element_names, base_url)}) widget.add('<br/>') cb = CheckboxWdg('include_internal', label='include built-in pages') span = SpanWdg(cb, css='med') span.add_color('color','color') widget.add(span) widget.add(div) widget.add('<br/>') widget.add('<br/>') return widget class PerformanceWdg(BaseRefreshWdg): def get_display(self): top = self.top top.add("<br/>") top.add_style("margin-left: 10px") try: import multiprocessing cpu_count = multiprocessing.cpu_count() except (ImportError, NotImplementedError): cpu_count = 'n/a' title = DivWdg() title.add("Click to start performance test: ") title.add_style("float: left") top.add(title) title.add_style("margin-top: 5px") button = ActionButtonWdg(title='Test') top.add(button) button.add_behavior( { 'type': 'click_up', 'cpu_count': cpu_count, 'cbjs_action': ''' var iterations = bvr.cpu_count; if (iterations == 'n/a') iterations = 1; var server = TacticServerStub.get(); var class_name = 'tactic.ui.panel.ViewPanelWdg'; var kwargs = { 'search_type': 'sthpw/login', 'view': 'table' }; var args = { 'args': kwargs, 'cbjs_action': function() { spt.app_busy.show("Asyncronous Test", "Running Test ["+(count+1)+" / "+iterations+"]"); count += 1; var time = new Date().getTime() - start; if (time > async_avg) { async_avg = time; } if (count == iterations) { spt.app_busy.hide(); async_avg = async_avg / iterations; alert("async: "+ async_avg + " ms"); } } }; var sync_avg = 0.0; for (var i = 0; i < iterations; i++) { spt.app_busy.show("Syncronous Requests", "Running Test ["+(i+1)+" / "+iterations+"]"); var start = new Date().getTime(); server.get_widget(class_name, args); var time = new Date().getTime() - start; sync_avg += time; } sync_avg = sync_avg / iterations; spt.app_busy.hide(); alert("sync: " + sync_avg + " ms"); var async_avg = 0.0; var count = 0; spt.app_busy.show("Asyncronous Requests", "Running Test ["+(count+1)+" / "+iterations+"]"); var start = new Date().getTime(); for (var i = 0; i < iterations; i++) { server.async_get_widget(class_name, args); } ''' } ) return top<|fim▁end|>
<|file_name|>bowtie2.py<|end_file_name|><|fim▁begin|>import glob import logging import os import subprocess from plugins import BaseAligner from yapsy.IPlugin import IPlugin from assembly import get_qual_encoding class Bowtie2Aligner(BaseAligner, IPlugin): def run(self): """ Map READS to CONTIGS and return alignment. Set MERGED_PAIR to True if reads[1] is a merged paired end file """ contig_file = self.data.contigfiles[0] reads = self.data.readfiles ## Index contigs prefix = os.path.join(self.outpath, 'bt2') cmd_args = [self.build_bin, '-f', contig_file, prefix] self.arast_popen(cmd_args, overrides=False) ### Align reads bamfiles = [] for i, readset in enumerate(self.data.readsets): samfile = os.path.join(self.outpath, 'align.sam') reads = readset.files cmd_args = [self.executable, '-x', prefix, '-S', samfile, '-p', self.process_threads_allowed] if len(reads) == 2: cmd_args += ['-1', reads[0], '-2', reads[1]] elif len(reads) == 1: cmd_args += ['-U', reads[0]] else: raise Exception('Bowtie plugin error') self.arast_popen(cmd_args, overrides=False) if not os.path.exists(samfile): raise Exception('Unable to complete alignment') ## Convert to BAM bamfile = samfile.replace('.sam', '.bam') cmd_args = ['samtools', 'view', '-bSho', bamfile, samfile] self.arast_popen(cmd_args) bamfiles.append(bamfile) ### Merge samfiles if multiple if len(bamfiles) > 1: bamfile = os.path.join(self.outpath, '{}_{}.bam'.format(os.path.basename(contig_file), i)) self.arast_popen(['samtools', 'merge', bamfile] + bamfiles) if not os.path.exists(bamfile): raise Exception('Unable to complete alignment') else: bamfile = bamfiles[0] if not os.path.exists(bamfile): raise Exception('Unable to complete alignment') ## Convert back to sam samfile = bamfile.replace('.bam', '.sam') self.arast_popen(['samtools', 'view', '-h', '-o', samfile, bamfile])<|fim▁hole|> return {'alignment': samfile, 'alignment_bam': bamfile}<|fim▁end|>
<|file_name|>_bgcolorsrc.py<|end_file_name|><|fim▁begin|><|fim▁hole|> class BgcolorsrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__( self, plotly_name="bgcolorsrc", parent_name="histogram.marker.pattern", **kwargs ): super(BgcolorsrcValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), **kwargs )<|fim▁end|>
import _plotly_utils.basevalidators
<|file_name|>issue-19127.rs<|end_file_name|><|fim▁begin|>// run-pass #![allow(unused_variables)]<|fim▁hole|>// pretty-expanded FIXME #23616 fn foo<T, F: FnOnce(T) -> T>(f: F) {} fn id<'a>(input: &'a u8) -> &'a u8 { input } fn main() { foo(id); }<|fim▁end|>
<|file_name|>_winkeyboard.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This is the Windows backend for keyboard events, and is implemented by invoking the Win32 API through the ctypes module. This is error prone and can introduce very unpythonic failure modes, such as segfaults and low level memory leaks. But it is also dependency-free, very performant well documented on Microsoft's webstie and scattered examples. # TODO: - Keypad numbers still print as numbers even when numlock is off. - No way to specify if user wants a keypad key or not in `map_char`. """ from __future__ import unicode_literals import re import atexit import traceback from threading import Lock from collections import defaultdict from ._keyboard_event import KeyboardEvent, KEY_DOWN, KEY_UP from ._canonical_names import normalize_name try: # Force Python2 to convert to unicode and not to str. chr = unichr except NameError: pass # This part is just declaring Win32 API structures using ctypes. In C # this would be simply #include "windows.h". import ctypes from ctypes import c_short, c_char, c_uint8, c_int32, c_int, c_uint, c_uint32, c_long, Structure, CFUNCTYPE, POINTER from ctypes.wintypes import WORD, DWORD, BOOL, HHOOK, MSG, LPWSTR, WCHAR, WPARAM, LPARAM, LONG, HMODULE, LPCWSTR, HINSTANCE, HWND LPMSG = POINTER(MSG) ULONG_PTR = POINTER(DWORD) kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) GetModuleHandleW = kernel32.GetModuleHandleW GetModuleHandleW.restype = HMODULE GetModuleHandleW.argtypes = [LPCWSTR] #https://github.com/boppreh/mouse/issues/1 #user32 = ctypes.windll.user32 user32 = ctypes.WinDLL('user32', use_last_error = True) VK_PACKET = 0xE7 INPUT_MOUSE = 0 INPUT_KEYBOARD = 1<|fim▁hole|>KEYEVENTF_KEYUP = 0x02 KEYEVENTF_UNICODE = 0x04 class KBDLLHOOKSTRUCT(Structure): _fields_ = [("vk_code", DWORD), ("scan_code", DWORD), ("flags", DWORD), ("time", c_int), ("dwExtraInfo", ULONG_PTR)] # Included for completeness. class MOUSEINPUT(ctypes.Structure): _fields_ = (('dx', LONG), ('dy', LONG), ('mouseData', DWORD), ('dwFlags', DWORD), ('time', DWORD), ('dwExtraInfo', ULONG_PTR)) class KEYBDINPUT(ctypes.Structure): _fields_ = (('wVk', WORD), ('wScan', WORD), ('dwFlags', DWORD), ('time', DWORD), ('dwExtraInfo', ULONG_PTR)) class HARDWAREINPUT(ctypes.Structure): _fields_ = (('uMsg', DWORD), ('wParamL', WORD), ('wParamH', WORD)) class _INPUTunion(ctypes.Union): _fields_ = (('mi', MOUSEINPUT), ('ki', KEYBDINPUT), ('hi', HARDWAREINPUT)) class INPUT(ctypes.Structure): _fields_ = (('type', DWORD), ('union', _INPUTunion)) LowLevelKeyboardProc = CFUNCTYPE(c_int, WPARAM, LPARAM, POINTER(KBDLLHOOKSTRUCT)) SetWindowsHookEx = user32.SetWindowsHookExW SetWindowsHookEx.argtypes = [c_int, LowLevelKeyboardProc, HINSTANCE , DWORD] SetWindowsHookEx.restype = HHOOK CallNextHookEx = user32.CallNextHookEx #CallNextHookEx.argtypes = [c_int , c_int, c_int, POINTER(KBDLLHOOKSTRUCT)] CallNextHookEx.restype = c_int UnhookWindowsHookEx = user32.UnhookWindowsHookEx UnhookWindowsHookEx.argtypes = [HHOOK] UnhookWindowsHookEx.restype = BOOL GetMessage = user32.GetMessageW GetMessage.argtypes = [LPMSG, HWND, c_uint, c_uint] GetMessage.restype = BOOL TranslateMessage = user32.TranslateMessage TranslateMessage.argtypes = [LPMSG] TranslateMessage.restype = BOOL DispatchMessage = user32.DispatchMessageA DispatchMessage.argtypes = [LPMSG] keyboard_state_type = c_uint8 * 256 GetKeyboardState = user32.GetKeyboardState GetKeyboardState.argtypes = [keyboard_state_type] GetKeyboardState.restype = BOOL GetKeyNameText = user32.GetKeyNameTextW GetKeyNameText.argtypes = [c_long, LPWSTR, c_int] GetKeyNameText.restype = c_int MapVirtualKey = user32.MapVirtualKeyW MapVirtualKey.argtypes = [c_uint, c_uint] MapVirtualKey.restype = c_uint ToUnicode = user32.ToUnicode ToUnicode.argtypes = [c_uint, c_uint, keyboard_state_type, LPWSTR, c_int, c_uint] ToUnicode.restype = c_int SendInput = user32.SendInput SendInput.argtypes = [c_uint, POINTER(INPUT), c_int] SendInput.restype = c_uint # https://msdn.microsoft.com/en-us/library/windows/desktop/ms646307(v=vs.85).aspx MAPVK_VK_TO_CHAR = 2 MAPVK_VK_TO_VSC = 0 MAPVK_VSC_TO_VK = 1 MAPVK_VK_TO_VSC_EX = 4 MAPVK_VSC_TO_VK_EX = 3 VkKeyScan = user32.VkKeyScanW VkKeyScan.argtypes = [WCHAR] VkKeyScan.restype = c_short LLKHF_INJECTED = 0x00000010 WM_KEYDOWN = 0x0100 WM_KEYUP = 0x0101 WM_SYSKEYDOWN = 0x104 # Used for ALT key WM_SYSKEYUP = 0x105 # This marks the end of Win32 API declarations. The rest is ours. keyboard_event_types = { WM_KEYDOWN: KEY_DOWN, WM_KEYUP: KEY_UP, WM_SYSKEYDOWN: KEY_DOWN, WM_SYSKEYUP: KEY_UP, } # List taken from the official documentation, but stripped of the OEM-specific keys. # Keys are virtual key codes, values are pairs (name, is_keypad). official_virtual_keys = { 0x03: ('control-break processing', False), 0x08: ('backspace', False), 0x09: ('tab', False), 0x0c: ('clear', False), 0x0d: ('enter', False), 0x10: ('shift', False), 0x11: ('ctrl', False), 0x12: ('alt', False), 0x13: ('pause', False), 0x14: ('caps lock', False), 0x15: ('ime kana mode', False), 0x15: ('ime hanguel mode', False), 0x15: ('ime hangul mode', False), 0x17: ('ime junja mode', False), 0x18: ('ime final mode', False), 0x19: ('ime hanja mode', False), 0x19: ('ime kanji mode', False), 0x1b: ('esc', False), 0x1c: ('ime convert', False), 0x1d: ('ime nonconvert', False), 0x1e: ('ime accept', False), 0x1f: ('ime mode change request', False), 0x20: ('spacebar', False), 0x21: ('page up', False), 0x22: ('page down', False), 0x23: ('end', False), 0x24: ('home', False), 0x25: ('left', False), 0x26: ('up', False), 0x27: ('right', False), 0x28: ('down', False), 0x29: ('select', False), 0x2a: ('print', False), 0x2b: ('execute', False), 0x2c: ('print screen', False), 0x2d: ('insert', False), 0x2e: ('delete', False), 0x2f: ('help', False), 0x30: ('0', False), 0x31: ('1', False), 0x32: ('2', False), 0x33: ('3', False), 0x34: ('4', False), 0x35: ('5', False), 0x36: ('6', False), 0x37: ('7', False), 0x38: ('8', False), 0x39: ('9', False), 0x41: ('a', False), 0x42: ('b', False), 0x43: ('c', False), 0x44: ('d', False), 0x45: ('e', False), 0x46: ('f', False), 0x47: ('g', False), 0x48: ('h', False), 0x49: ('i', False), 0x4a: ('j', False), 0x4b: ('k', False), 0x4c: ('l', False), 0x4d: ('m', False), 0x4e: ('n', False), 0x4f: ('o', False), 0x50: ('p', False), 0x51: ('q', False), 0x52: ('r', False), 0x53: ('s', False), 0x54: ('t', False), 0x55: ('u', False), 0x56: ('v', False), 0x57: ('w', False), 0x58: ('x', False), 0x59: ('y', False), 0x5a: ('z', False), 0x5b: ('left windows', False), 0x5c: ('right windows', False), 0x5d: ('applications', False), 0x5f: ('sleep', False), 0x60: ('0', True), 0x61: ('1', True), 0x62: ('2', True), 0x63: ('3', True), 0x64: ('4', True), 0x65: ('5', True), 0x66: ('6', True), 0x67: ('7', True), 0x68: ('8', True), 0x69: ('9', True), 0x6a: ('*', True), 0x6b: ('+', True), 0x6c: ('separator', True), 0x6d: ('-', True), 0x6e: ('decimal', True), 0x6f: ('/', True), 0x70: ('f1', False), 0x71: ('f2', False), 0x72: ('f3', False), 0x73: ('f4', False), 0x74: ('f5', False), 0x75: ('f6', False), 0x76: ('f7', False), 0x77: ('f8', False), 0x78: ('f9', False), 0x79: ('f10', False), 0x7a: ('f11', False), 0x7b: ('f12', False), 0x7c: ('f13', False), 0x7d: ('f14', False), 0x7e: ('f15', False), 0x7f: ('f16', False), 0x80: ('f17', False), 0x81: ('f18', False), 0x82: ('f19', False), 0x83: ('f20', False), 0x84: ('f21', False), 0x85: ('f22', False), 0x86: ('f23', False), 0x87: ('f24', False), 0x90: ('num lock', False), 0x91: ('scroll lock', False), 0xa0: ('left shift', False), 0xa1: ('right shift', False), 0xa2: ('left ctrl', False), 0xa3: ('right ctrl', False), 0xa4: ('left menu', False), 0xa5: ('right menu', False), 0xa6: ('browser back', False), 0xa7: ('browser forward', False), 0xa8: ('browser refresh', False), 0xa9: ('browser stop', False), 0xaa: ('browser search key', False), 0xab: ('browser favorites', False), 0xac: ('browser start and home', False), 0xad: ('volume mute', False), 0xae: ('volume down', False), 0xaf: ('volume up', False), 0xb0: ('next track', False), 0xb1: ('previous track', False), 0xb2: ('stop media', False), 0xb3: ('play/pause media', False), 0xb4: ('start mail', False), 0xb5: ('select media', False), 0xb6: ('start application 1', False), 0xb7: ('start application 2', False), 0xbb: ('+', False), 0xbc: (',', False), 0xbd: ('-', False), 0xbe: ('.', False), #0xbe:('/', False), # Used for miscellaneous characters; it can vary by keyboard. For the US standard keyboard, the '/?. 0xe5: ('ime process', False), 0xf6: ('attn', False), 0xf7: ('crsel', False), 0xf8: ('exsel', False), 0xf9: ('erase eof', False), 0xfa: ('play', False), 0xfb: ('zoom', False), 0xfc: ('reserved ', False), 0xfd: ('pa1', False), 0xfe: ('clear', False), } tables_lock = Lock() to_name = defaultdict(list) from_name = defaultdict(list) scan_code_to_vk = {} distinct_modifiers = [ (), ('shift',), ('alt gr',), ('num lock',), ('shift', 'num lock'), ('caps lock',), ('shift', 'caps lock'), ('alt gr', 'num lock'), ] name_buffer = ctypes.create_unicode_buffer(32) unicode_buffer = ctypes.create_unicode_buffer(32) keyboard_state = keyboard_state_type() def get_event_names(scan_code, vk, is_extended, modifiers): is_keypad = (scan_code, vk, is_extended) in keypad_keys is_official = vk in official_virtual_keys if is_keypad and is_official: yield official_virtual_keys[vk][0] keyboard_state[0x10] = 0x80 * ('shift' in modifiers) keyboard_state[0x11] = 0x80 * ('alt gr' in modifiers) keyboard_state[0x12] = 0x80 * ('alt gr' in modifiers) keyboard_state[0x14] = 0x01 * ('caps lock' in modifiers) keyboard_state[0x90] = 0x01 * ('num lock' in modifiers) keyboard_state[0x91] = 0x01 * ('scroll lock' in modifiers) unicode_ret = ToUnicode(vk, scan_code, keyboard_state, unicode_buffer, len(unicode_buffer), 0) if unicode_ret and unicode_buffer.value: yield unicode_buffer.value # unicode_ret == -1 -> is dead key # ToUnicode has the side effect of setting global flags for dead keys. # Therefore we need to call it twice to clear those flags. # If your 6 and 7 keys are named "^6" and "^7", this is the reason. ToUnicode(vk, scan_code, keyboard_state, unicode_buffer, len(unicode_buffer), 0) name_ret = GetKeyNameText(scan_code << 16 | is_extended << 24, name_buffer, 1024) if name_ret and name_buffer.value: yield name_buffer.value char = user32.MapVirtualKeyW(vk, MAPVK_VK_TO_CHAR) & 0xFF if char != 0: yield chr(char) if not is_keypad and is_official: yield official_virtual_keys[vk][0] def _setup_name_tables(): """ Ensures the scan code/virtual key code/name translation tables are filled. """ with tables_lock: if to_name: return # Go through every possible scan code, and map them to virtual key codes. # Then vice-versa. all_scan_codes = [(sc, user32.MapVirtualKeyExW(sc, MAPVK_VSC_TO_VK_EX, 0)) for sc in range(0x100)] all_vks = [(user32.MapVirtualKeyExW(vk, MAPVK_VK_TO_VSC_EX, 0), vk) for vk in range(0x100)] for scan_code, vk in all_scan_codes + all_vks: # `to_name` and `from_name` entries will be a tuple (scan_code, vk, extended, shift_state). if (scan_code, vk, 0, 0, 0) in to_name: continue if scan_code not in scan_code_to_vk: scan_code_to_vk[scan_code] = vk # Brute force all combinations to find all possible names. for extended in [0, 1]: for modifiers in distinct_modifiers: entry = (scan_code, vk, extended, modifiers) # Get key names from ToUnicode, GetKeyNameText, MapVirtualKeyW and official virtual keys. names = list(get_event_names(*entry)) if names: # Also map lowercased key names, but only after the properly cased ones. lowercase_names = [name.lower() for name in names] to_name[entry] = names + lowercase_names # Remember the "id" of the name, as the first techniques # have better results and therefore priority. for i, name in enumerate(map(normalize_name, names + lowercase_names)): from_name[name].append((i, entry)) # TODO: single quotes on US INTL is returning the dead key (?), and therefore # not typing properly. # Alt gr is way outside the usual range of keys (0..127) and on my # computer is named as 'ctrl'. Therefore we add it manually and hope # Windows is consistent in its inconsistency. for extended in [0, 1]: for modifiers in distinct_modifiers: to_name[(541, 162, extended, modifiers)] = ['alt gr'] from_name['alt gr'].append((1, (541, 162, extended, modifiers))) modifiers_preference = defaultdict(lambda: 10) modifiers_preference.update({(): 0, ('shift',): 1, ('alt gr',): 2, ('ctrl',): 3, ('alt',): 4}) def order_key(line): i, entry = line scan_code, vk, extended, modifiers = entry return modifiers_preference[modifiers], i, extended, vk, scan_code for name, entries in list(from_name.items()): from_name[name] = sorted(set(entries), key=order_key) # Called by keyboard/__init__.py init = _setup_name_tables # List created manually. keypad_keys = [ # (scan_code, virtual_key_code, is_extended) (126, 194, 0), (126, 194, 0), (28, 13, 1), (28, 13, 1), (53, 111, 1), (53, 111, 1), (55, 106, 0), (55, 106, 0), (69, 144, 1), (69, 144, 1), (71, 103, 0), (71, 36, 0), (72, 104, 0), (72, 38, 0), (73, 105, 0), (73, 33, 0), (74, 109, 0), (74, 109, 0), (75, 100, 0), (75, 37, 0), (76, 101, 0), (76, 12, 0), (77, 102, 0), (77, 39, 0), (78, 107, 0), (78, 107, 0), (79, 35, 0), (79, 97, 0), (80, 40, 0), (80, 98, 0), (81, 34, 0), (81, 99, 0), (82, 45, 0), (82, 96, 0), (83, 110, 0), (83, 46, 0), ] shift_is_pressed = False altgr_is_pressed = False ignore_next_right_alt = False shift_vks = set([0x10, 0xa0, 0xa1]) def prepare_intercept(callback): """ Registers a Windows low level keyboard hook. The provided callback will be invoked for each high-level keyboard event, and is expected to return True if the key event should be passed to the next program, or False if the event is to be blocked. No event is processed until the Windows messages are pumped (see start_intercept). """ _setup_name_tables() def process_key(event_type, vk, scan_code, is_extended): global shift_is_pressed, altgr_is_pressed, ignore_next_right_alt #print(event_type, vk, scan_code, is_extended) # Pressing alt-gr also generates an extra "right alt" event if vk == 0xA5 and ignore_next_right_alt: ignore_next_right_alt = False return True modifiers = ( ('shift',) * shift_is_pressed + ('alt gr',) * altgr_is_pressed + ('num lock',) * (user32.GetKeyState(0x90) & 1) + ('caps lock',) * (user32.GetKeyState(0x14) & 1) + ('scroll lock',) * (user32.GetKeyState(0x91) & 1) ) entry = (scan_code, vk, is_extended, modifiers) if entry not in to_name: to_name[entry] = list(get_event_names(*entry)) names = to_name[entry] name = names[0] if names else None # TODO: inaccurate when holding multiple different shifts. if vk in shift_vks: shift_is_pressed = event_type == KEY_DOWN if scan_code == 541 and vk == 162: ignore_next_right_alt = True altgr_is_pressed = event_type == KEY_DOWN is_keypad = (scan_code, vk, is_extended) in keypad_keys return callback(KeyboardEvent(event_type=event_type, scan_code=scan_code or -vk, name=name, is_keypad=is_keypad)) def low_level_keyboard_handler(nCode, wParam, lParam): try: vk = lParam.contents.vk_code # Ignore the second `alt` DOWN observed in some cases. fake_alt = (LLKHF_INJECTED | 0x20) # Ignore events generated by SendInput with Unicode. if vk != VK_PACKET and lParam.contents.flags & fake_alt != fake_alt: event_type = keyboard_event_types[wParam] is_extended = lParam.contents.flags & 1 scan_code = lParam.contents.scan_code should_continue = process_key(event_type, vk, scan_code, is_extended) if not should_continue: return -1 except Exception as e: print('Error in keyboard hook:') traceback.print_exc() return CallNextHookEx(None, nCode, wParam, lParam) WH_KEYBOARD_LL = c_int(13) keyboard_callback = LowLevelKeyboardProc(low_level_keyboard_handler) handle = GetModuleHandleW(None) thread_id = DWORD(0) keyboard_hook = SetWindowsHookEx(WH_KEYBOARD_LL, keyboard_callback, handle, thread_id) # Register to remove the hook when the interpreter exits. Unfortunately a # try/finally block doesn't seem to work here. atexit.register(UnhookWindowsHookEx, keyboard_callback) def listen(callback): prepare_intercept(callback) msg = LPMSG() while not GetMessage(msg, 0, 0, 0): TranslateMessage(msg) DispatchMessage(msg) def map_name(name): _setup_name_tables() entries = from_name.get(name) if not entries: raise ValueError('Key name {} is not mapped to any known key.'.format(repr(name))) for i, entry in entries: scan_code, vk, is_extended, modifiers = entry yield scan_code or -vk, modifiers def _send_event(code, event_type): if code == 541: # Alt-gr is made of ctrl+alt. Just sending even 541 doesn't do anything. user32.keybd_event(0x11, code, event_type, 0) user32.keybd_event(0x12, code, event_type, 0) elif code > 0: vk = scan_code_to_vk.get(code, 0) user32.keybd_event(vk, code, event_type, 0) else: # Negative scan code is a way to indicate we don't have a scan code, # and the value actually contains the Virtual key code. user32.keybd_event(-code, 0, event_type, 0) def press(code): _send_event(code, 0) def release(code): _send_event(code, 2) def type_unicode(character): # This code and related structures are based on # http://stackoverflow.com/a/11910555/252218 surrogates = bytearray(character.encode('utf-16le')) presses = [] releases = [] for i in range(0, len(surrogates), 2): higher, lower = surrogates[i:i+2] structure = KEYBDINPUT(0, (lower << 8) + higher, KEYEVENTF_UNICODE, 0, None) presses.append(INPUT(INPUT_KEYBOARD, _INPUTunion(ki=structure))) structure = KEYBDINPUT(0, (lower << 8) + higher, KEYEVENTF_UNICODE | KEYEVENTF_KEYUP, 0, None) releases.append(INPUT(INPUT_KEYBOARD, _INPUTunion(ki=structure))) inputs = presses + releases nInputs = len(inputs) LPINPUT = INPUT * nInputs pInputs = LPINPUT(*inputs) cbSize = c_int(ctypes.sizeof(INPUT)) SendInput(nInputs, pInputs, cbSize) if __name__ == '__main__': _setup_name_tables() import pprint pprint.pprint(to_name) pprint.pprint(from_name) #listen(lambda e: print(e.to_json()) or True)<|fim▁end|>
INPUT_HARDWARE = 2
<|file_name|>fan.py<|end_file_name|><|fim▁begin|>""" Support for Wink fans. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/fan.wink/ """ import logging from homeassistant.components.fan import ( SPEED_HIGH, SPEED_LOW, SPEED_MEDIUM, SUPPORT_DIRECTION, SUPPORT_SET_SPEED, FanEntity) from homeassistant.components.wink import DOMAIN, WinkDevice _LOGGER = logging.getLogger(__name__) DEPENDENCIES = ['wink'] SPEED_AUTO = 'auto' SPEED_LOWEST = 'lowest' SUPPORTED_FEATURES = SUPPORT_DIRECTION + SUPPORT_SET_SPEED def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Wink platform.""" import pywink for fan in pywink.get_fans(): if fan.object_id() + fan.name() not in hass.data[DOMAIN]['unique_ids']: add_entities([WinkFanDevice(fan, hass)]) class WinkFanDevice(WinkDevice, FanEntity): """Representation of a Wink fan.""" async def async_added_to_hass(self): """Call when entity is added to hass.""" self.hass.data[DOMAIN]['entities']['fan'].append(self) def set_direction(self, direction: str) -> None: """Set the direction of the fan.""" self.wink.set_fan_direction(direction) def set_speed(self, speed: str) -> None: """Set the speed of the fan.""" self.wink.set_state(True, speed) def turn_on(self, speed: str = None, **kwargs) -> None: """Turn on the fan.""" self.wink.set_state(True, speed) def turn_off(self, **kwargs) -> None: """Turn off the fan.""" self.wink.set_state(False) @property def is_on(self): """Return true if the entity is on.""" return self.wink.state() @property def speed(self) -> str: """Return the current speed.""" current_wink_speed = self.wink.current_fan_speed() if SPEED_AUTO == current_wink_speed: return SPEED_AUTO if SPEED_LOWEST == current_wink_speed: return SPEED_LOWEST if SPEED_LOW == current_wink_speed:<|fim▁hole|> return SPEED_LOW if SPEED_MEDIUM == current_wink_speed: return SPEED_MEDIUM if SPEED_HIGH == current_wink_speed: return SPEED_HIGH return None @property def current_direction(self): """Return direction of the fan [forward, reverse].""" return self.wink.current_fan_direction() @property def speed_list(self) -> list: """Get the list of available speeds.""" wink_supported_speeds = self.wink.fan_speeds() supported_speeds = [] if SPEED_AUTO in wink_supported_speeds: supported_speeds.append(SPEED_AUTO) if SPEED_LOWEST in wink_supported_speeds: supported_speeds.append(SPEED_LOWEST) if SPEED_LOW in wink_supported_speeds: supported_speeds.append(SPEED_LOW) if SPEED_MEDIUM in wink_supported_speeds: supported_speeds.append(SPEED_MEDIUM) if SPEED_HIGH in wink_supported_speeds: supported_speeds.append(SPEED_HIGH) return supported_speeds @property def supported_features(self) -> int: """Flag supported features.""" return SUPPORTED_FEATURES<|fim▁end|>
<|file_name|>stats.py<|end_file_name|><|fim▁begin|># (c) 2012-2014, Michael DeHaan <[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<|fim▁hole|> # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.utils.vars import merge_hash class AggregateStats: ''' holds stats about per-host activity during playbook runs ''' def __init__(self): self.processed = {} self.failures = {} self.ok = {} self.dark = {} self.changed = {} self.skipped = {} # user defined stats, which can be per host or global self.custom = {} def increment(self, what, host): ''' helper function to bump a statistic ''' self.processed[host] = 1 prev = (getattr(self, what)).get(host, 0) getattr(self, what)[host] = prev+1 def summarize(self, host): ''' return information about a particular host ''' return dict( ok = self.ok.get(host, 0), failures = self.failures.get(host, 0), unreachable = self.dark.get(host,0), changed = self.changed.get(host, 0), skipped = self.skipped.get(host, 0) ) def set_custom_stats(self, which, what, host=None): ''' allow setting of a custom stat''' if host is None: host = '_run' if host not in self.custom: self.custom[host] = {which: what} else: self.custom[host][which] = what def update_custom_stats(self, which, what, host=None): ''' allow aggregation of a custom stat''' if host is None: host = '_run' if host not in self.custom or which not in self.custom[host]: return self.set_custom_stats(which, what, host) # mismatching types if type(what) != type(self.custom[host][which]): return None if isinstance(what, dict): self.custom[host][which] = merge_hash(self.custom[host][which], what) else: # let overloaded + take care of other types self.custom[host][which] += what<|fim▁end|>
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
<|file_name|>main.go<|end_file_name|><|fim▁begin|>package main import ( "fmt" "log" "net/http" ) const cookieName = "Site-Cookie1" func main() { http.Handle("/favicon.ico", http.NotFoundHandler()) http.HandleFunc("/", root) http.HandleFunc("/set", set) http.HandleFunc("/read", read) http.HandleFunc("/expire", expire) log.Println("Starting server on 8080") log.Fatalln(http.ListenAndServe(":8080", nil)) } func root(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, `<h1><a href="/set">Set</a></h1>`) } func set(w http.ResponseWriter, _ *http.Request) { http.SetCookie(w, &http.Cookie{ Name: cookieName, Value: "This is a Site Cookie created", }) fmt.Fprint(w, `<h1><a href="/read">Read</a></h1>`) } func read(w http.ResponseWriter, r *http.Request) { coo, err := r.Cookie(cookieName) if err != nil { log.Println(err) http.Redirect(w, r, "/set", http.StatusSeeOther) return } fmt.Fprintf(w, "<h1>Cookie Value: %s</h1>", coo.Value) fmt.Fprint(w, `<h1><a href="/expire">Expire</a></h1>`) } <|fim▁hole|> coo, err := r.Cookie(cookieName) if err != nil { log.Println(err) http.Redirect(w, r, "/set", http.StatusSeeOther) return } coo.MaxAge = -1 // Delete the Cookie http.SetCookie(w, coo) http.Redirect(w, r, "/", http.StatusSeeOther) }<|fim▁end|>
func expire(w http.ResponseWriter, r *http.Request) {
<|file_name|>kendo-test-json.ts<|end_file_name|><|fim▁begin|>/// <reference path="../Scripts/typings/aurelia/aurelia.d.ts"/> /// <reference path="../Scripts/typings/jquery/jquery.d.ts"/> /// <reference path="../Scripts/typings/kendo/kendo.all.d.ts"/> /// <reference path="services/products.ts"/> //import $ = require("jquery"); //import k = require("kendo"); import products = require("./services/products"); export class KendoTest { constructor() { console.log("kendo-test constructed :)"); } attached() {<|fim▁hole|> console.log("kendo-test attached :)"); var dataSource = new kendo.data.DataSource({ type: "json", transport: { read: "./dist/services/products.json" }, pageSize: 21 }); $("#pager").kendoPager({ dataSource: dataSource }); $("#listView").kendoListView({ dataSource: dataSource, template: kendo.template($("#template").html()) }); } } // http://demos.telerik.com/kendo-ui/content/shared/js/products.js<|fim▁end|>
<|file_name|>logger.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright 2014-2018 The PySCF Developers. 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. # # Author: Qiming Sun <[email protected]> # ''' Logging system Log level --------- ======= ====== Level number ------- ------ DEBUG4 9 DEBUG3 8 DEBUG2 7 DEBUG1 6 DEBUG 5 INFO 4 NOTE 3 WARN 2<|fim▁hole|>ERROR 1 QUIET 0 ======= ====== Large value means more noise in the output file. .. note:: Error and warning messages are written to stderr. Each Logger object has its own output destination and verbose level. So multiple Logger objects can be created to manage the message system without affecting each other. The methods provided by Logger class has the direct connection to the log level. E.g. :func:`info` print messages if the verbose level >= 4 (INFO): >>> import sys >>> from pyscf import lib >>> log = lib.logger.Logger(sys.stdout, 4) >>> log.info('info level') info level >>> log.verbose = 3 >>> log.info('info level') >>> log.note('note level') note level timer ----- Logger object provides timer method for timing. Set :attr:`TIMER_LEVEL` to control at which level the timing information should be output. It is 5 (DEBUG) by default. >>> import sys, time >>> from pyscf import lib >>> log = lib.logger.Logger(sys.stdout, 4) >>> t0 = logger.process_clock() >>> log.timer('test', t0) >>> lib.logger.TIMER_LEVEL = 4 >>> log.timer('test', t0) CPU time for test 0.00 sec ''' import sys import time if sys.version_info < (3, 0): process_clock = time.clock perf_counter = time.time else: process_clock = time.process_time perf_counter = time.perf_counter from pyscf.lib import parameters as param import pyscf.__config__ DEBUG4 = param.VERBOSE_DEBUG + 4 DEBUG3 = param.VERBOSE_DEBUG + 3 DEBUG2 = param.VERBOSE_DEBUG + 2 DEBUG1 = param.VERBOSE_DEBUG + 1 DEBUG = param.VERBOSE_DEBUG INFO = param.VERBOSE_INFO NOTE = param.VERBOSE_NOTICE NOTICE = NOTE WARN = param.VERBOSE_WARN WARNING = WARN ERR = param.VERBOSE_ERR ERROR = ERR QUIET = param.VERBOSE_QUIET CRIT = param.VERBOSE_CRIT ALERT = param.VERBOSE_ALERT PANIC = param.VERBOSE_PANIC TIMER_LEVEL = getattr(pyscf.__config__, 'TIMER_LEVEL', DEBUG) sys.verbose = NOTE def flush(rec, msg, *args): rec.stdout.write(msg%args) rec.stdout.write('\n') rec.stdout.flush() def log(rec, msg, *args): if rec.verbose > QUIET: flush(rec, msg, *args) def error(rec, msg, *args): if rec.verbose >= ERROR: flush(rec, '\nERROR: '+msg+'\n', *args) sys.stderr.write('ERROR: ' + (msg%args) + '\n') def warn(rec, msg, *args): if rec.verbose >= WARN: flush(rec, '\nWARN: '+msg+'\n', *args) if rec.stdout is not sys.stdout: sys.stderr.write('WARN: ' + (msg%args) + '\n') def info(rec, msg, *args): if rec.verbose >= INFO: flush(rec, msg, *args) def note(rec, msg, *args): if rec.verbose >= NOTICE: flush(rec, msg, *args) def debug(rec, msg, *args): if rec.verbose >= DEBUG: flush(rec, msg, *args) def debug1(rec, msg, *args): if rec.verbose >= DEBUG1: flush(rec, msg, *args) def debug2(rec, msg, *args): if rec.verbose >= DEBUG2: flush(rec, msg, *args) def debug3(rec, msg, *args): if rec.verbose >= DEBUG3: flush(rec, msg, *args) def debug4(rec, msg, *args): if rec.verbose >= DEBUG4: flush(rec, msg, *args) def stdout(rec, msg, *args): if rec.verbose >= DEBUG: flush(rec, msg, *args) sys.stdout.write('>>> %s\n' % msg) def timer(rec, msg, cpu0=None, wall0=None): if cpu0 is None: cpu0 = rec._t0 if wall0: rec._t0, rec._w0 = process_clock(), perf_counter() if rec.verbose >= TIMER_LEVEL: flush(rec, ' CPU time for %s %9.2f sec, wall time %9.2f sec' % (msg, rec._t0-cpu0, rec._w0-wall0)) return rec._t0, rec._w0 else: rec._t0 = process_clock() if rec.verbose >= TIMER_LEVEL: flush(rec, ' CPU time for %s %9.2f sec' % (msg, rec._t0-cpu0)) return rec._t0 def timer_debug1(rec, msg, cpu0=None, wall0=None): if rec.verbose >= DEBUG1: return timer(rec, msg, cpu0, wall0) elif wall0: rec._t0, rec._w0 = process_clock(), perf_counter() return rec._t0, rec._w0 else: rec._t0 = process_clock() return rec._t0 class Logger(object): ''' Attributes: stdout : file object or sys.stdout The file to dump output message. verbose : int Large value means more noise in the output file. ''' def __init__(self, stdout=sys.stdout, verbose=NOTE): self.stdout = stdout self.verbose = verbose self._t0 = process_clock() self._w0 = perf_counter() log = log error = error warn = warn note = note info = info debug = debug debug1 = debug1 debug2 = debug2 debug3 = debug3 debug4 = debug4 timer = timer timer_debug1 = timer_debug1 def new_logger(rec=None, verbose=None): '''Create and return a :class:`Logger` object Args: rec : An object which carries the attributes stdout and verbose verbose : a Logger object, or integer or None The verbose level. If verbose is a Logger object, the Logger object is returned. If verbose is not specified (None), rec.verbose will be used in the new Logger object. ''' if isinstance(verbose, Logger): log = verbose elif isinstance(verbose, int): if getattr(rec, 'stdout', None): log = Logger(rec.stdout, verbose) else: log = Logger(sys.stdout, verbose) else: log = Logger(rec.stdout, rec.verbose) return log<|fim▁end|>
<|file_name|>css.go<|end_file_name|><|fim▁begin|>package css func checkSubArraySum(nums []int, k int) bool { return bruteForce(nums, k) } // bruteForce time complexity O(n^2) space complexity O(1) func bruteForce(nums []int, k int) bool { n := len(nums) if n < 2 { return false } var sum int for i := range nums { sum = 0 for j := i; j < n; j++ { sum += nums[j] if sum == k || (k != 0 && sum%k == 0) { if j > i { // at least 2 that sum up to k return true } } } } return false } <|fim▁hole|> return false } // key is the sum%k, value is index // based on this math equation // sum1 % k = x ----- eq1 // sum2 % k = x ----- eq2 // then (sum1-sum2) % k = x - x = 0 ------ eq3 hash := make(map[int]int, n) // edge case hash[0] = -1 var sum int for i := range nums { sum += nums[i] if k != 0 { sum %= k } if v, exists := hash[sum]; exists { // found one based on eq3 if i-v > 1 { return true } } else { hash[sum] = i } } return false }<|fim▁end|>
// preSumHash time complexity o(N), space complexity O(N) func preSumHash(nums []int, k int) bool { n := len(nums) if n < 2 {
<|file_name|>checkbox.spec.ts<|end_file_name|><|fim▁begin|>import {dispatchFakeEvent} from '../../cdk/testing/private'; import {ChangeDetectionStrategy, Component, DebugElement, Type} from '@angular/core'; import { ComponentFixture, fakeAsync, flush, flushMicrotasks, TestBed, } from '@angular/core/testing'; import {ThemePalette} from '@angular/material-experimental/mdc-core'; import {FormControl, FormsModule, NgModel, ReactiveFormsModule} from '@angular/forms'; import {By} from '@angular/platform-browser'; import { MatCheckbox, MatCheckboxChange, MatCheckboxModule } from './index'; import {MatCheckboxDefaultOptions, MAT_CHECKBOX_DEFAULT_OPTIONS} from '@angular/material/checkbox'; describe('MDC-based MatCheckbox', () => { let fixture: ComponentFixture<any>; function createComponent<T>(componentType: Type<T>, extraDeclarations: Type<any>[] = []) { TestBed .configureTestingModule({ imports: [MatCheckboxModule, FormsModule, ReactiveFormsModule], declarations: [componentType, ...extraDeclarations], }) .compileComponents(); return TestBed.createComponent<T>(componentType); } describe('basic behaviors', () => { let checkboxDebugElement: DebugElement; let checkboxNativeElement: HTMLElement; let checkboxInstance: MatCheckbox; let testComponent: SingleCheckbox; let inputElement: HTMLInputElement; let labelElement: HTMLLabelElement; let checkboxElement: HTMLElement; beforeEach(() => { fixture = createComponent(SingleCheckbox); fixture.detectChanges(); checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!; checkboxNativeElement = checkboxDebugElement.nativeElement; checkboxInstance = checkboxDebugElement.componentInstance; testComponent = fixture.debugElement.componentInstance; inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input'); labelElement = <HTMLLabelElement>checkboxNativeElement.querySelector('label'); checkboxElement = <HTMLLabelElement>checkboxNativeElement.querySelector('.mdc-checkbox'); }); it('should add and remove the checked state', fakeAsync(() => { expect(checkboxInstance.checked).toBe(false); expect(inputElement.checked).toBe(false); testComponent.isChecked = true; fixture.detectChanges(); expect(checkboxInstance.checked).toBe(true); expect(inputElement.checked).toBe(true); testComponent.isChecked = false; fixture.detectChanges(); expect(checkboxInstance.checked).toBe(false); expect(inputElement.checked).toBe(false); })); it('should expose the ripple instance', () => { expect(checkboxInstance.ripple).toBeTruthy(); }); it('should hide the internal SVG', () => { const svg = checkboxNativeElement.querySelector('svg')!; expect(svg.getAttribute('aria-hidden')).toBe('true'); }); it('should toggle checkbox ripple disabledness correctly', fakeAsync(() => { const rippleSelector = '.mat-ripple-element:not(.mat-checkbox-persistent-ripple)'; testComponent.isDisabled = true; fixture.detectChanges(); dispatchFakeEvent(checkboxElement, 'mousedown'); dispatchFakeEvent(checkboxElement, 'mouseup'); checkboxElement.click(); expect(checkboxNativeElement.querySelectorAll(rippleSelector).length).toBe(0); flush(); testComponent.isDisabled = false; fixture.detectChanges(); dispatchFakeEvent(checkboxElement, 'mousedown'); dispatchFakeEvent(checkboxElement, 'mouseup'); checkboxElement.click(); expect(checkboxNativeElement.querySelectorAll(rippleSelector).length).toBe(1); flush(); })); it('should add and remove indeterminate state', fakeAsync(() => { expect(inputElement.checked).toBe(false); expect(inputElement.indeterminate).toBe(false); expect(inputElement.getAttribute('aria-checked')) .withContext('Expect aria-checked to be false').toBe('false'); testComponent.isIndeterminate = true; fixture.detectChanges(); expect(inputElement.checked).toBe(false); expect(inputElement.indeterminate).toBe(true); expect(inputElement.getAttribute('aria-checked')) .withContext('Expect aria checked to be mixed for indeterminate checkbox').toBe('mixed'); testComponent.isIndeterminate = false; fixture.detectChanges(); expect(inputElement.checked).toBe(false); expect(inputElement.indeterminate).toBe(false); })); it('should set indeterminate to false when input clicked', fakeAsync(() => { testComponent.isIndeterminate = true; fixture.detectChanges(); expect(checkboxInstance.indeterminate).toBe(true); expect(inputElement.indeterminate).toBe(true); expect(testComponent.isIndeterminate).toBe(true); inputElement.click(); fixture.detectChanges(); // Flush the microtasks because the forms module updates the model state asynchronously. flush(); // The checked property has been updated from the model and now the view needs // to reflect the state change. fixture.detectChanges(); expect(checkboxInstance.checked).toBe(true); expect(inputElement.indeterminate).toBe(false); expect(inputElement.checked).toBe(true); expect(testComponent.isIndeterminate).toBe(false); testComponent.isIndeterminate = true; fixture.detectChanges(); expect(checkboxInstance.indeterminate).toBe(true); expect(inputElement.indeterminate).toBe(true); expect(inputElement.checked).toBe(true); expect(testComponent.isIndeterminate).toBe(true); expect(inputElement.getAttribute('aria-checked')) .withContext('Expect aria checked to be true').toBe('true'); inputElement.click(); fixture.detectChanges(); // Flush the microtasks because the forms module updates the model state asynchronously. flush(); // The checked property has been updated from the model and now the view needs // to reflect the state change. fixture.detectChanges(); expect(checkboxInstance.checked).toBe(false); expect(inputElement.indeterminate).toBe(false); expect(inputElement.checked).toBe(false); expect(testComponent.isIndeterminate).toBe(false); })); it('should not set indeterminate to false when checked is set programmatically', fakeAsync(() => { testComponent.isIndeterminate = true; fixture.detectChanges(); expect(checkboxInstance.indeterminate).toBe(true); expect(inputElement.indeterminate).toBe(true); expect(testComponent.isIndeterminate).toBe(true); testComponent.isChecked = true; fixture.detectChanges(); expect(checkboxInstance.checked).toBe(true); expect(inputElement.indeterminate).toBe(true); expect(inputElement.checked).toBe(true); expect(testComponent.isIndeterminate).toBe(true); testComponent.isChecked = false; fixture.detectChanges(); expect(checkboxInstance.checked).toBe(false); expect(inputElement.indeterminate).toBe(true); expect(inputElement.checked).toBe(false); expect(testComponent.isIndeterminate).toBe(true); })); it('should change native element checked when check programmatically', () => { expect(inputElement.checked).toBe(false); checkboxInstance.checked = true; fixture.detectChanges(); expect(inputElement.checked).toBe(true); }); it('should toggle checked state on click', fakeAsync(() => { expect(checkboxInstance.checked).toBe(false); labelElement.click(); fixture.detectChanges(); flush(); expect(checkboxInstance.checked).toBe(true); labelElement.click(); fixture.detectChanges(); flush(); expect(checkboxInstance.checked).toBe(false); })); it('should change from indeterminate to checked on click', fakeAsync(() => { testComponent.isChecked = false; testComponent.isIndeterminate = true; fixture.detectChanges(); expect(checkboxInstance.checked).toBe(false); expect(checkboxInstance.indeterminate).toBe(true); inputElement.click(); fixture.detectChanges(); flush(); expect(checkboxInstance.checked).toBe(true); expect(checkboxInstance.indeterminate).toBe(false); inputElement.click(); fixture.detectChanges(); flush(); expect(checkboxInstance.checked).toBe(false); expect(checkboxInstance.indeterminate).toBe(false); })); it('should add and remove disabled state', fakeAsync(() => { expect(checkboxInstance.disabled).toBe(false); expect(inputElement.tabIndex).toBe(0); expect(inputElement.disabled).toBe(false); testComponent.isDisabled = true; fixture.detectChanges(); expect(checkboxInstance.disabled).toBe(true); expect(inputElement.disabled).toBe(true); testComponent.isDisabled = false; fixture.detectChanges(); expect(checkboxInstance.disabled).toBe(false); expect(inputElement.tabIndex).toBe(0); expect(inputElement.disabled).toBe(false); })); it('should not toggle `checked` state upon interation while disabled', fakeAsync(() => { testComponent.isDisabled = true; fixture.detectChanges(); checkboxNativeElement.click(); expect(checkboxInstance.checked).toBe(false); })); it('should overwrite indeterminate state when clicked', fakeAsync(() => { testComponent.isIndeterminate = true; fixture.detectChanges(); inputElement.click(); fixture.detectChanges(); // Flush the microtasks because the indeterminate state will be updated in the next tick. flush(); expect(checkboxInstance.checked).toBe(true); expect(checkboxInstance.indeterminate).toBe(false); })); it('should preserve the user-provided id', fakeAsync(() => { expect(checkboxNativeElement.id).toBe('simple-check'); expect(inputElement.id).toBe('simple-check-input'); })); it('should generate a unique id for the checkbox input if no id is set', fakeAsync(() => { testComponent.checkboxId = null; fixture.detectChanges(); expect(checkboxInstance.inputId).toMatch(/mat-mdc-checkbox-\d+/); expect(inputElement.id).toBe(checkboxInstance.inputId); })); it('should project the checkbox content into the label element', fakeAsync(() => { let label = <HTMLLabelElement>checkboxNativeElement.querySelector('label'); expect(label.textContent!.trim()).toBe('Simple checkbox'); })); it('should make the host element a tab stop', fakeAsync(() => { expect(inputElement.tabIndex).toBe(0); })); it('should add a css class to position the label before the checkbox', fakeAsync(() => { testComponent.labelPos = 'before'; fixture.detectChanges(); expect(checkboxNativeElement.querySelector('.mdc-form-field')!.classList) .toContain('mdc-form-field--align-end'); })); it('should not trigger the click event multiple times', fakeAsync(() => { // By default, when clicking on a label element, a generated click will be dispatched // on the associated input element. // Since we're using a label element and a visual hidden input, this behavior can led // to an issue, where the click events on the checkbox are getting executed twice. spyOn(testComponent, 'onCheckboxClick'); expect(inputElement.checked).toBe(false); labelElement.click(); fixture.detectChanges(); flush(); expect(inputElement.checked).toBe(true); expect(testComponent.onCheckboxClick).toHaveBeenCalledTimes(1); })); it('should trigger a change event when the native input does', fakeAsync(() => { spyOn(testComponent, 'onCheckboxChange'); expect(inputElement.checked).toBe(false); labelElement.click(); fixture.detectChanges(); flush(); expect(inputElement.checked).toBe(true); expect(testComponent.onCheckboxChange).toHaveBeenCalledTimes(1); })); it('should not trigger the change event by changing the native value', fakeAsync(() => { spyOn(testComponent, 'onCheckboxChange'); expect(inputElement.checked).toBe(false); testComponent.isChecked = true; fixture.detectChanges(); flush(); expect(inputElement.checked).toBe(true); expect(testComponent.onCheckboxChange).not.toHaveBeenCalled(); })); it('should keep the view in sync if the `checked` value changes inside the `change` listener', fakeAsync(() => { spyOn(testComponent, 'onCheckboxChange').and.callFake(() => { checkboxInstance.checked = false; }); labelElement.click(); fixture.detectChanges(); flush(); expect(inputElement.checked).toBe(false); })); it('should forward the required attribute', fakeAsync(() => { testComponent.isRequired = true; fixture.detectChanges(); expect(inputElement.required).toBe(true); testComponent.isRequired = false; fixture.detectChanges(); expect(inputElement.required).toBe(false); })); it('should focus on underlying input element when focus() is called', fakeAsync(() => { expect(document.activeElement).not.toBe(inputElement); checkboxInstance.focus(); fixture.detectChanges(); expect(document.activeElement).toBe(inputElement); })); it('should forward the value to input element', fakeAsync(() => { testComponent.checkboxValue = 'basic_checkbox'; fixture.detectChanges(); expect(inputElement.value).toBe('basic_checkbox'); })); it('should remove the SVG checkmark from the tab order', fakeAsync(() => { expect(checkboxNativeElement.querySelector('svg')!.getAttribute('focusable')) .toBe('false'); })); describe('ripple elements', () => { it('should show ripples on label mousedown', fakeAsync(() => { const rippleSelector = '.mat-ripple-element:not(.mat-checkbox-persistent-ripple)'; expect(checkboxNativeElement.querySelector(rippleSelector)).toBeFalsy(); dispatchFakeEvent(checkboxElement, 'mousedown'); dispatchFakeEvent(checkboxElement, 'mouseup'); checkboxElement.click(); expect(checkboxNativeElement.querySelectorAll(rippleSelector).length).toBe(1); flush(); })); it('should not show ripples when disabled', fakeAsync(() => { const rippleSelector = '.mat-ripple-element:not(.mat-checkbox-persistent-ripple)'; testComponent.isDisabled = true; fixture.detectChanges(); dispatchFakeEvent(checkboxElement, 'mousedown'); dispatchFakeEvent(checkboxElement, 'mouseup'); checkboxElement.click(); expect(checkboxNativeElement.querySelectorAll(rippleSelector).length).toBe(0); flush(); testComponent.isDisabled = false; fixture.detectChanges(); dispatchFakeEvent(checkboxElement, 'mousedown'); dispatchFakeEvent(checkboxElement, 'mouseup'); checkboxElement.click(); expect(checkboxNativeElement.querySelectorAll(rippleSelector).length).toBe(1); flush(); })); it('should remove ripple if matRippleDisabled input is set', fakeAsync(() => { const rippleSelector = '.mat-ripple-element:not(.mat-checkbox-persistent-ripple)'; testComponent.disableRipple = true; fixture.detectChanges(); dispatchFakeEvent(checkboxElement, 'mousedown'); dispatchFakeEvent(checkboxElement, 'mouseup'); checkboxElement.click(); expect(checkboxNativeElement.querySelectorAll(rippleSelector).length).toBe(0); flush(); testComponent.disableRipple = false; fixture.detectChanges(); dispatchFakeEvent(checkboxElement, 'mousedown'); dispatchFakeEvent(checkboxElement, 'mouseup'); checkboxElement.click(); expect(checkboxNativeElement.querySelectorAll(rippleSelector).length).toBe(1); flush(); })); }); describe('color behaviour', () => { it('should apply class based on color attribute', fakeAsync(() => { testComponent.checkboxColor = 'primary'; fixture.detectChanges(); expect(checkboxNativeElement.classList.contains('mat-primary')).toBe(true); testComponent.checkboxColor = 'accent'; fixture.detectChanges(); expect(checkboxNativeElement.classList.contains('mat-accent')).toBe(true); })); it('should not clear previous defined classes', fakeAsync(() => { checkboxNativeElement.classList.add('custom-class'); testComponent.checkboxColor = 'primary'; fixture.detectChanges(); expect(checkboxNativeElement.classList.contains('mat-primary')).toBe(true); expect(checkboxNativeElement.classList.contains('custom-class')).toBe(true); testComponent.checkboxColor = 'accent'; fixture.detectChanges(); expect(checkboxNativeElement.classList.contains('mat-primary')).toBe(false); expect(checkboxNativeElement.classList.contains('mat-accent')).toBe(true); expect(checkboxNativeElement.classList.contains('custom-class')).toBe(true); })); it('should default to accent if no color is passed in', fakeAsync(() => { testComponent.checkboxColor = undefined; fixture.detectChanges(); expect(checkboxNativeElement.classList).toContain('mat-accent'); })); }); describe(`when MAT_CHECKBOX_CLICK_ACTION is 'check'`, () => { beforeEach(() => { TestBed.resetTestingModule(); TestBed.configureTestingModule({ imports: [MatCheckboxModule, FormsModule, ReactiveFormsModule], declarations: [SingleCheckbox], providers: [ {provide: MAT_CHECKBOX_DEFAULT_OPTIONS, useValue: {clickAction: 'check'}}<|fim▁hole|> ] }); fixture = createComponent(SingleCheckbox); fixture.detectChanges(); checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!; checkboxNativeElement = checkboxDebugElement.nativeElement; checkboxInstance = checkboxDebugElement.componentInstance; testComponent = fixture.debugElement.componentInstance; inputElement = checkboxNativeElement.querySelector('input') as HTMLInputElement; labelElement = checkboxNativeElement.querySelector('label') as HTMLLabelElement; }); it('should not set `indeterminate` to false on click if check is set', fakeAsync(() => { testComponent.isIndeterminate = true; inputElement.click(); fixture.detectChanges(); flush(); expect(inputElement.checked).toBe(true); expect(inputElement.indeterminate).toBe(true); })); }); describe(`when MAT_CHECKBOX_CLICK_ACTION is 'noop'`, () => { beforeEach(() => { TestBed.resetTestingModule(); TestBed.configureTestingModule({ imports: [MatCheckboxModule, FormsModule, ReactiveFormsModule], declarations: [SingleCheckbox], providers: [ {provide: MAT_CHECKBOX_DEFAULT_OPTIONS, useValue: {clickAction: 'noop'}} ] }); fixture = createComponent(SingleCheckbox); fixture.detectChanges(); checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!; checkboxNativeElement = checkboxDebugElement.nativeElement; checkboxInstance = checkboxDebugElement.componentInstance; testComponent = fixture.debugElement.componentInstance; inputElement = checkboxNativeElement.querySelector('input') as HTMLInputElement; labelElement = checkboxNativeElement.querySelector('label') as HTMLLabelElement; }); it('should not change `indeterminate` on click if noop is set', fakeAsync(() => { testComponent.isIndeterminate = true; inputElement.click(); fixture.detectChanges(); flush(); expect(inputElement.checked).toBe(false); expect(inputElement.indeterminate).toBe(true); })); it(`should not change 'checked' or 'indeterminate' on click if noop is set`, fakeAsync(() => { testComponent.isChecked = true; testComponent.isIndeterminate = true; inputElement.click(); fixture.detectChanges(); flush(); expect(inputElement.checked).toBe(true); expect(inputElement.indeterminate).toBe(true); testComponent.isChecked = false; inputElement.click(); fixture.detectChanges(); flush(); expect(inputElement.checked).toBe(false); expect(inputElement.indeterminate) .withContext('indeterminate should not change').toBe(true); })); }); it('should have a focus indicator', () => { const checkboxRippleNativeElement = checkboxNativeElement.querySelector('.mat-mdc-checkbox-ripple')!; expect(checkboxRippleNativeElement.classList.contains('mat-mdc-focus-indicator')).toBe(true); }); }); describe('with change event and no initial value', () => { let checkboxDebugElement: DebugElement; let checkboxNativeElement: HTMLElement; let checkboxInstance: MatCheckbox; let testComponent: CheckboxWithChangeEvent; let inputElement: HTMLInputElement; let labelElement: HTMLLabelElement; beforeEach(() => { fixture = createComponent(CheckboxWithChangeEvent); fixture.detectChanges(); checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!; checkboxNativeElement = checkboxDebugElement.nativeElement; checkboxInstance = checkboxDebugElement.componentInstance; testComponent = fixture.debugElement.componentInstance; inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input'); labelElement = <HTMLLabelElement>checkboxNativeElement.querySelector('label'); }); it('should emit the event to the change observable', fakeAsync(() => { let changeSpy = jasmine.createSpy('onChangeObservable'); checkboxInstance.change.subscribe(changeSpy); fixture.detectChanges(); expect(changeSpy).not.toHaveBeenCalled(); // When changing the native `checked` property the checkbox will not fire a change event, // because the element is not focused and it's not the native behavior of the input // element. labelElement.click(); fixture.detectChanges(); flush(); expect(changeSpy).toHaveBeenCalledTimes(1); })); it('should not emit a DOM event to the change output', fakeAsync(() => { fixture.detectChanges(); expect(testComponent.lastEvent).toBeUndefined(); // Trigger the click on the inputElement, because the input will probably // emit a DOM event to the change output. inputElement.click(); fixture.detectChanges(); flush(); // We're checking the arguments type / emitted value to be a boolean, because sometimes the // emitted value can be a DOM Event, which is not valid. // See angular/angular#4059 expect(testComponent.lastEvent.checked).toBe(true); })); }); describe('aria-label', () => { let checkboxDebugElement: DebugElement; let checkboxNativeElement: HTMLElement; let inputElement: HTMLInputElement; it('should use the provided aria-label', fakeAsync(() => { fixture = createComponent(CheckboxWithAriaLabel); checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!; checkboxNativeElement = checkboxDebugElement.nativeElement; inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input'); fixture.detectChanges(); expect(inputElement.getAttribute('aria-label')).toBe('Super effective'); })); it('should not set the aria-label attribute if no value is provided', fakeAsync(() => { fixture = createComponent(SingleCheckbox); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('input').hasAttribute('aria-label')) .toBe(false); })); }); describe('with provided aria-labelledby ', () => { let checkboxDebugElement: DebugElement; let checkboxNativeElement: HTMLElement; let inputElement: HTMLInputElement; it('should use the provided aria-labelledby', fakeAsync(() => { fixture = createComponent(CheckboxWithAriaLabelledby); checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!; checkboxNativeElement = checkboxDebugElement.nativeElement; inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input'); fixture.detectChanges(); expect(inputElement.getAttribute('aria-labelledby')).toBe('some-id'); })); it('should not assign aria-labelledby if none is provided', fakeAsync(() => { fixture = createComponent(SingleCheckbox); checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!; checkboxNativeElement = checkboxDebugElement.nativeElement; inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input'); fixture.detectChanges(); expect(inputElement.getAttribute('aria-labelledby')).toBe(null); })); }); describe('with provided aria-describedby ', () => { let checkboxDebugElement: DebugElement; let checkboxNativeElement: HTMLElement; let inputElement: HTMLInputElement; it('should use the provided aria-describedby', () => { fixture = createComponent(CheckboxWithAriaDescribedby); checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!; checkboxNativeElement = checkboxDebugElement.nativeElement; inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input'); fixture.detectChanges(); expect(inputElement.getAttribute('aria-describedby')).toBe('some-id'); }); it('should not assign aria-describedby if none is provided', () => { fixture = createComponent(SingleCheckbox); checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!; checkboxNativeElement = checkboxDebugElement.nativeElement; inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input'); fixture.detectChanges(); expect(inputElement.getAttribute('aria-describedby')).toBe(null); }); }); describe('with provided tabIndex', () => { let checkboxDebugElement: DebugElement; let checkboxNativeElement: HTMLElement; let testComponent: CheckboxWithTabIndex; let inputElement: HTMLInputElement; beforeEach(() => { fixture = createComponent(CheckboxWithTabIndex); fixture.detectChanges(); testComponent = fixture.debugElement.componentInstance; checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!; checkboxNativeElement = checkboxDebugElement.nativeElement; inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input'); }); it('should preserve any given tabIndex', fakeAsync(() => { expect(inputElement.tabIndex).toBe(7); })); it('should preserve given tabIndex when the checkbox is disabled then enabled', fakeAsync(() => { testComponent.isDisabled = true; fixture.detectChanges(); testComponent.customTabIndex = 13; fixture.detectChanges(); testComponent.isDisabled = false; fixture.detectChanges(); expect(inputElement.tabIndex).toBe(13); })); }); describe('with native tabindex attribute', () => { it('should properly detect native tabindex attribute', fakeAsync(() => { fixture = createComponent(CheckboxWithTabindexAttr); fixture.detectChanges(); const checkbox = fixture.debugElement.query(By.directive(MatCheckbox))! .componentInstance as MatCheckbox; expect(checkbox.tabIndex) .withContext('Expected tabIndex property to have been set based on the native attribute') .toBe(5); })); it('should clear the tabindex attribute from the host element', fakeAsync(() => { fixture = createComponent(CheckboxWithTabindexAttr); fixture.detectChanges(); const checkbox = fixture.debugElement.query(By.directive(MatCheckbox))!.nativeElement; expect(checkbox.getAttribute('tabindex')).toBeFalsy(); })); }); describe('with multiple checkboxes', () => { beforeEach(() => { fixture = createComponent(MultipleCheckboxes); fixture.detectChanges(); }); it('should assign a unique id to each checkbox', fakeAsync(() => { let [firstId, secondId] = fixture.debugElement.queryAll(By.directive(MatCheckbox)) .map(debugElement => debugElement.nativeElement.querySelector('input').id); expect(firstId).toMatch(/mat-mdc-checkbox-\d+-input/); expect(secondId).toMatch(/mat-mdc-checkbox-\d+-input/); expect(firstId).not.toEqual(secondId); })); }); describe('with ngModel', () => { let checkboxDebugElement: DebugElement; let checkboxNativeElement: HTMLElement; let checkboxInstance: MatCheckbox; let inputElement: HTMLInputElement; let ngModel: NgModel; beforeEach(() => { fixture = createComponent(CheckboxWithNgModel); fixture.componentInstance.isRequired = false; fixture.detectChanges(); checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!; checkboxNativeElement = checkboxDebugElement.nativeElement; checkboxInstance = checkboxDebugElement.componentInstance; inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input'); ngModel = checkboxDebugElement.injector.get<NgModel>(NgModel); }); it('should be pristine, untouched, and valid initially', fakeAsync(() => { expect(ngModel.valid).toBe(true); expect(ngModel.pristine).toBe(true); expect(ngModel.touched).toBe(false); })); it('should have correct control states after interaction', fakeAsync(() => { inputElement.click(); fixture.detectChanges(); // Flush the timeout that is being created whenever a `click` event has been fired by // the underlying input. flush(); // After the value change through interaction, the control should be dirty, but remain // untouched as long as the focus is still on the underlying input. expect(ngModel.pristine).toBe(false); expect(ngModel.touched).toBe(false); // If the input element loses focus, the control should remain dirty but should // also turn touched. dispatchFakeEvent(inputElement, 'blur'); fixture.detectChanges(); flushMicrotasks(); expect(ngModel.pristine).toBe(false); expect(ngModel.touched).toBe(true); })); it('should mark the element as touched on blur when inside an OnPush parent', fakeAsync(() => { fixture.destroy(); TestBed.resetTestingModule(); fixture = createComponent(CheckboxWithNgModelAndOnPush); fixture.detectChanges(); checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!; checkboxNativeElement = checkboxDebugElement.nativeElement; checkboxInstance = checkboxDebugElement.componentInstance; inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input'); ngModel = checkboxDebugElement.injector.get<NgModel>(NgModel); inputElement.click(); fixture.detectChanges(); flush(); expect(checkboxNativeElement.classList).not.toContain('ng-touched'); dispatchFakeEvent(inputElement, 'blur'); fixture.detectChanges(); flushMicrotasks(); fixture.detectChanges(); expect(checkboxNativeElement.classList).toContain('ng-touched'); })); it('should not throw an error when disabling while focused', fakeAsync(() => { expect(() => { // Focus the input element because after disabling, the `blur` event should automatically // fire and not result in a changed after checked exception. Related: #12323 inputElement.focus(); fixture.componentInstance.isDisabled = true; fixture.detectChanges(); flushMicrotasks(); }).not.toThrow(); })); it('should toggle checked state on click', fakeAsync(() => { expect(checkboxInstance.checked).toBe(false); inputElement.click(); fixture.detectChanges(); flush(); expect(checkboxInstance.checked).toBe(true); inputElement.click(); fixture.detectChanges(); flush(); expect(checkboxInstance.checked).toBe(false); })); it('should validate with RequiredTrue validator', fakeAsync(() => { fixture.componentInstance.isRequired = true; inputElement.click(); fixture.detectChanges(); flush(); expect(checkboxInstance.checked).toBe(true); expect(ngModel.valid).toBe(true); inputElement.click(); fixture.detectChanges(); flush(); expect(checkboxInstance.checked).toBe(false); expect(ngModel.valid).toBe(false); })); it('should update the ngModel value when using the `toggle` method', fakeAsync(() => { const checkbox = fixture.debugElement.query(By.directive(MatCheckbox)).componentInstance; expect(fixture.componentInstance.isGood).toBe(false); checkbox.toggle(); fixture.detectChanges(); expect(fixture.componentInstance.isGood).toBe(true); })); }); describe('with name attribute', () => { beforeEach(() => { fixture = createComponent(CheckboxWithNameAttribute); fixture.detectChanges(); }); it('should forward name value to input element', fakeAsync(() => { let checkboxElement = fixture.debugElement.query(By.directive(MatCheckbox))!; let inputElement = <HTMLInputElement>checkboxElement.nativeElement.querySelector('input'); expect(inputElement.getAttribute('name')).toBe('test-name'); })); }); describe('with form control', () => { let checkboxDebugElement: DebugElement; let checkboxInstance: MatCheckbox; let testComponent: CheckboxWithFormControl; let inputElement: HTMLInputElement; beforeEach(() => { fixture = createComponent(CheckboxWithFormControl); fixture.detectChanges(); checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!; checkboxInstance = checkboxDebugElement.componentInstance; testComponent = fixture.debugElement.componentInstance; inputElement = <HTMLInputElement>checkboxDebugElement.nativeElement.querySelector('input'); }); it('should toggle the disabled state', fakeAsync(() => { expect(checkboxInstance.disabled).toBe(false); testComponent.formControl.disable(); fixture.detectChanges(); expect(checkboxInstance.disabled).toBe(true); expect(inputElement.disabled).toBe(true); testComponent.formControl.enable(); fixture.detectChanges(); expect(checkboxInstance.disabled).toBe(false); expect(inputElement.disabled).toBe(false); })); }); describe('without label', () => { let checkboxInnerContainer: HTMLElement; beforeEach(() => { fixture = createComponent(CheckboxWithoutLabel); const checkboxDebugEl = fixture.debugElement.query(By.directive(MatCheckbox))!; checkboxInnerContainer = checkboxDebugEl.query(By.css('.mdc-form-field'))!.nativeElement; }); it('should not add the "name" attribute if it is not passed in', fakeAsync(() => { fixture.detectChanges(); expect(checkboxInnerContainer.querySelector('input')!.hasAttribute('name')).toBe(false); })); it('should not add the "value" attribute if it is not passed in', fakeAsync(() => { fixture.detectChanges(); expect(checkboxInnerContainer.querySelector('input')!.hasAttribute('value')).toBe(false); })); }); }); describe('MatCheckboxDefaultOptions', () => { describe('when MAT_CHECKBOX_DEFAULT_OPTIONS overridden', () => { function configure(defaults: MatCheckboxDefaultOptions) { TestBed.configureTestingModule({ imports: [MatCheckboxModule, FormsModule], declarations: [SingleCheckbox, SingleCheckbox], providers: [{provide: MAT_CHECKBOX_DEFAULT_OPTIONS, useValue: defaults}] }); TestBed.compileComponents(); } it('should override default color in component', () => { configure({color: 'primary'}); const fixture: ComponentFixture<SingleCheckbox> = TestBed.createComponent(SingleCheckbox); fixture.detectChanges(); const checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!; expect(checkboxDebugElement.nativeElement.classList).toContain('mat-primary'); }); it('should not override explicit input bindings', () => { configure({color: 'primary'}); const fixture: ComponentFixture<SingleCheckbox> = TestBed.createComponent(SingleCheckbox); fixture.componentInstance.checkboxColor = 'warn'; fixture.detectChanges(); const checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!; expect(checkboxDebugElement.nativeElement.classList).not.toContain('mat-primary'); expect(checkboxDebugElement.nativeElement.classList).toContain('mat-warn'); expect(checkboxDebugElement.nativeElement.classList).toContain('mat-warn'); }); it('should default to accent if config does not specify color', () => { configure({clickAction: 'noop'}); const fixture: ComponentFixture<SingleCheckbox> = TestBed.createComponent(SingleCheckbox); fixture.componentInstance.checkboxColor = undefined; fixture.detectChanges(); const checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!; expect(checkboxDebugElement.nativeElement.classList).toContain('mat-accent'); }); }); }); /** Simple component for testing a single checkbox. */ @Component({ template: ` <div (click)="parentElementClicked = true" (keyup)="parentElementKeyedUp = true"> <mat-checkbox [id]="checkboxId" [required]="isRequired" [labelPosition]="labelPos" [checked]="isChecked" [(indeterminate)]="isIndeterminate" [disabled]="isDisabled" [color]="checkboxColor" [disableRipple]="disableRipple" [value]="checkboxValue" (click)="onCheckboxClick($event)" (change)="onCheckboxChange($event)"> Simple checkbox </mat-checkbox> </div>` }) class SingleCheckbox { labelPos: 'before'|'after' = 'after'; isChecked: boolean = false; isRequired: boolean = false; isIndeterminate: boolean = false; isDisabled: boolean = false; disableRipple: boolean = false; parentElementClicked: boolean = false; parentElementKeyedUp: boolean = false; checkboxId: string|null = 'simple-check'; checkboxColor: ThemePalette = 'primary'; checkboxValue: string = 'single_checkbox'; onCheckboxClick: (event?: Event) => void = () => {}; onCheckboxChange: (event?: MatCheckboxChange) => void = () => {}; } /** Simple component for testing an MatCheckbox with required ngModel. */ @Component({ template: `<mat-checkbox [required]="isRequired" [(ngModel)]="isGood" [disabled]="isDisabled">Be good</mat-checkbox>`, }) class CheckboxWithNgModel { isGood: boolean = false; isRequired: boolean = true; isDisabled: boolean = false; } @Component({ template: `<mat-checkbox [required]="isRequired" [(ngModel)]="isGood">Be good</mat-checkbox>`, changeDetection: ChangeDetectionStrategy.OnPush, }) class CheckboxWithNgModelAndOnPush extends CheckboxWithNgModel { } /** Simple test component with multiple checkboxes. */ @Component(({ template: ` <mat-checkbox>Option 1</mat-checkbox> <mat-checkbox>Option 2</mat-checkbox> ` })) class MultipleCheckboxes { } /** Simple test component with tabIndex */ @Component({ template: ` <mat-checkbox [tabIndex]="customTabIndex" [disabled]="isDisabled"> </mat-checkbox>`, }) class CheckboxWithTabIndex { customTabIndex: number = 7; isDisabled: boolean = false; } /** Simple test component with an aria-label set. */ @Component({template: `<mat-checkbox aria-label="Super effective"></mat-checkbox>`}) class CheckboxWithAriaLabel { } /** Simple test component with an aria-label set. */ @Component({template: `<mat-checkbox aria-labelledby="some-id"></mat-checkbox>`}) class CheckboxWithAriaLabelledby { } /** Simple test component with an aria-describedby set. */ @Component({ template: `<mat-checkbox aria-describedby="some-id"></mat-checkbox>` }) class CheckboxWithAriaDescribedby {} /** Simple test component with name attribute */ @Component({template: `<mat-checkbox name="test-name"></mat-checkbox>`}) class CheckboxWithNameAttribute { } /** Simple test component with change event */ @Component({template: `<mat-checkbox (change)="lastEvent = $event"></mat-checkbox>`}) class CheckboxWithChangeEvent { lastEvent: MatCheckboxChange; } /** Test component with reactive forms */ @Component({template: `<mat-checkbox [formControl]="formControl"></mat-checkbox>`}) class CheckboxWithFormControl { formControl = new FormControl(); } /** Test component without label */ @Component({template: `<mat-checkbox>{{ label }}</mat-checkbox>`}) class CheckboxWithoutLabel { label: string; } /** Test component with the native tabindex attribute. */ @Component({template: `<mat-checkbox tabindex="5"></mat-checkbox>`}) class CheckboxWithTabindexAttr { }<|fim▁end|>
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>//! `simd` offers a basic interface to the SIMD functionality of CPUs. //! //! **Warning** This is an actively developed work-in-progress, and //! may/will break from commit to commit. //! //! # Installation //! //! Via git: //! //! ```toml //! simd = { git = "https://github.com/huonw/simd" } //! ``` //! //! This is **not** currently the `simd` crate on crates.io. #![cfg_attr(feature = "serde", feature(plugin, custom_derive))] #![cfg_attr(feature = "serde", plugin(serde_macros))] #![feature(cfg_target_feature, repr_simd, platform_intrinsics, const_fn)] #![allow(non_camel_case_types)] #[cfg(feature = "serde")] extern crate serde; /// Boolean type for 8-bit integers. #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct bool8i(i8); /// Boolean type for 16-bit integers. #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct bool16i(i16); /// Boolean type for 32-bit integers. #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct bool32i(i32); /// Boolean type for 32-bit floats. #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct bool32f(i32); macro_rules! bool { ($($name: ident, $inner: ty;)*) => { $( impl From<bool> for $name { #[inline] fn from(b: bool) -> $name { $name(-(b as $inner)) } } impl From<$name> for bool { #[inline] fn from(b: $name) -> bool { b.0 != 0 } } )* } } bool! { bool8i, i8; bool16i, i16; bool32i, i32; bool32f, i32; } /// Types that are SIMD vectors. pub unsafe trait Simd { /// The corresponding boolean vector type. type Bool: Simd; /// The element that this vector stores. type Elem; } /// A SIMD vector of 4 `u32`s. #[repr(simd)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Debug, Copy)] pub struct u32x4(u32, u32, u32, u32); /// A SIMD vector of 4 `i32`s. #[repr(simd)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Debug, Copy)] pub struct i32x4(i32, i32, i32, i32); /// A SIMD vector of 4 `f32`s. #[repr(simd)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Debug, Copy)] pub struct f32x4(f32, f32, f32, f32); /// A SIMD boolean vector for length-4 vectors of 32-bit integers. #[repr(simd)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Debug, Copy)] pub struct bool32ix4(i32, i32, i32, i32); /// A SIMD boolean vector for length-4 vectors of 32-bit floats. #[repr(simd)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Debug, Copy)] pub struct bool32fx4(i32, i32, i32, i32); #[allow(dead_code)] #[repr(simd)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Debug, Copy)] struct u32x2(u32, u32); #[allow(dead_code)] #[repr(simd)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Debug, Copy)] struct i32x2(i32, i32); #[allow(dead_code)] #[repr(simd)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Debug, Copy)] struct f32x2(f32, f32); #[allow(dead_code)] #[repr(simd)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Debug, Copy)] struct bool32ix2(i32, i32); #[allow(dead_code)] #[repr(simd)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Debug, Copy)] struct bool32fx2(i32, i32); /// A SIMD vector of 8 `u16`s. #[repr(simd)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Debug, Copy)] pub struct u16x8(u16, u16, u16, u16, u16, u16, u16, u16); /// A SIMD vector of 8 `i16`s. #[repr(simd)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Debug, Copy)] pub struct i16x8(i16, i16, i16, i16, i16, i16, i16, i16); /// A SIMD boolean vector for length-8 vectors of 16-bit integers. #[repr(simd)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Debug, Copy)] pub struct bool16ix8(i16, i16, i16, i16, i16, i16, i16, i16); /// A SIMD vector of 16 `u8`s. #[repr(simd)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Debug, Copy)] pub struct u8x16(u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8); /// A SIMD vector of 16 `i8`s. #[repr(simd)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Debug, Copy)] pub struct i8x16(i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8); /// A SIMD boolean vector for length-16 vectors of 8-bit integers. #[repr(simd)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Debug, Copy)] pub struct bool8ix16(i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8); macro_rules! simd { ($($bool: ty: $($ty: ty = $elem: ty),*;)*) => { $($(unsafe impl Simd for $ty { type Bool = $bool; type Elem = $elem; } impl Clone for $ty { #[inline] fn clone(&self) -> Self { *self } } )*)*} }<|fim▁hole|>simd! { bool8ix16: i8x16 = i8, u8x16 = u8, bool8ix16 = bool8i; bool16ix8: i16x8 = i16, u16x8 = u16, bool16ix8 = bool16i; bool32ix4: i32x4 = i32, u32x4 = u32, bool32ix4 = bool32i; bool32fx4: f32x4 = f32, bool32fx4 = bool32f; bool32ix2: i32x2 = i32, u32x2 = u32, bool32ix2 = bool32i; bool32fx2: f32x2 = f32, bool32fx2 = bool32f; } #[allow(dead_code)] #[inline] fn bitcast<T: Simd, U: Simd>(x: T) -> U { assert_eq!(std::mem::size_of::<T>(), std::mem::size_of::<U>()); unsafe {std::mem::transmute_copy(&x)} } #[allow(dead_code)] extern "platform-intrinsic" { fn simd_eq<T: Simd<Bool = U>, U>(x: T, y: T) -> U; fn simd_ne<T: Simd<Bool = U>, U>(x: T, y: T) -> U; fn simd_lt<T: Simd<Bool = U>, U>(x: T, y: T) -> U; fn simd_le<T: Simd<Bool = U>, U>(x: T, y: T) -> U; fn simd_gt<T: Simd<Bool = U>, U>(x: T, y: T) -> U; fn simd_ge<T: Simd<Bool = U>, U>(x: T, y: T) -> U; fn simd_shuffle2<T: Simd, U: Simd<Elem = T::Elem>>(x: T, y: T, idx: [u32; 2]) -> U; fn simd_shuffle4<T: Simd, U: Simd<Elem = T::Elem>>(x: T, y: T, idx: [u32; 4]) -> U; fn simd_shuffle8<T: Simd, U: Simd<Elem = T::Elem>>(x: T, y: T, idx: [u32; 8]) -> U; fn simd_shuffle16<T: Simd, U: Simd<Elem = T::Elem>>(x: T, y: T, idx: [u32; 16]) -> U; fn simd_insert<T: Simd<Elem = U>, U>(x: T, idx: u32, val: U) -> T; fn simd_extract<T: Simd<Elem = U>, U>(x: T, idx: u32) -> U; fn simd_cast<T: Simd, U: Simd>(x: T) -> U; fn simd_add<T: Simd>(x: T, y: T) -> T; fn simd_sub<T: Simd>(x: T, y: T) -> T; fn simd_mul<T: Simd>(x: T, y: T) -> T; fn simd_div<T: Simd>(x: T, y: T) -> T; fn simd_shl<T: Simd>(x: T, y: T) -> T; fn simd_shr<T: Simd>(x: T, y: T) -> T; fn simd_and<T: Simd>(x: T, y: T) -> T; fn simd_or<T: Simd>(x: T, y: T) -> T; fn simd_xor<T: Simd>(x: T, y: T) -> T; } #[repr(packed)] #[derive(Debug, Copy, Clone)] struct Unalign<T>(T); #[macro_use] mod common; mod sixty_four; mod v256; #[cfg(any(feature = "doc", target_arch = "x86", target_arch = "x86_64"))] pub mod x86; #[cfg(any(feature = "doc", target_arch = "arm"))] pub mod arm; #[cfg(any(feature = "doc", target_arch = "aarch64"))] pub mod aarch64;<|fim▁end|>
<|file_name|>memory.go<|end_file_name|><|fim▁begin|>package collaboration import "sync" func NewMemoryStorage() *memoryStorage { return &memoryStorage{ users: make(map[string]*Option), } } // memoryStorage satisfies Storage interface type memoryStorage struct { users map[string]*Option sync.Mutex } func (m *memoryStorage) Get(username string) (*Option, error) { m.Lock() defer m.Unlock() option, ok := m.users[username] if !ok { return nil, ErrUserNotFound } return option, nil } func (m *memoryStorage) GetAll() (map[string]*Option, error) { m.Lock() defer m.Unlock() return m.users, nil } func (m *memoryStorage) Set(username string, value *Option) error { m.Lock() defer m.Unlock() m.users[username] = value return nil } func (m *memoryStorage) Delete(username string) error {<|fim▁hole|> defer m.Unlock() delete(m.users, username) return nil } func (m *memoryStorage) Close() error { return nil }<|fim▁end|>
m.Lock()
<|file_name|>jobs.py<|end_file_name|><|fim▁begin|>import copy import logging import os import time from datetime import datetime from hashlib import sha1 import newrelic.agent from django.core.exceptions import ObjectDoesNotExist from django.db.utils import IntegrityError from past.builtins import long from treeherder.etl.artifact import (serialize_artifact_json_blobs, store_job_artifacts) from treeherder.etl.common import get_guid_root from treeherder.model.models import (BuildPlatform, FailureClassification, Job, JobGroup, JobLog, JobType, Machine, MachinePlatform, Option, OptionCollection, Product, Push, ReferenceDataSignatures, TaskclusterMetadata) logger = logging.getLogger(__name__) def _get_number(s): try: return long(s) except (ValueError, TypeError): return 0 def _remove_existing_jobs(data): """ Remove jobs from data where we already have them in the same state. 1. split the incoming jobs into pending, running and complete. 2. fetch the ``job_guids`` from the db that are in the same state as they are in ``data``. 3. build a new list of jobs in ``new_data`` that are not already in the db and pass that back. It could end up empty at that point. """ new_data = [] guids = [datum['job']['job_guid'] for datum in data] state_map = { guid: state for (guid, state) in Job.objects.filter( guid__in=guids).values_list('guid', 'state') } for datum in data: job = datum['job'] if not state_map.get(job['job_guid']): new_data.append(datum) else: # should not transition from running to pending, # or completed to any other state current_state = state_map[job['job_guid']] if current_state == 'completed' or ( job['state'] == 'pending' and current_state == 'running'): continue new_data.append(datum) return new_data def _load_job(repository, job_datum, push_id): """ Load a job into the treeherder database If the job is a ``retry`` the ``job_guid`` will have a special suffix on it. But the matching ``pending``/``running`` job will not. So we append the suffixed ``job_guid`` to ``retry_job_guids`` so that we can update the job_id_lookup later with the non-suffixed ``job_guid`` (root ``job_guid``). Then we can find the right ``pending``/``running`` job and update it with this ``retry`` job. """ build_platform, _ = BuildPlatform.objects.get_or_create( os_name=job_datum.get('build_platform', {}).get('os_name', 'unknown'), platform=job_datum.get('build_platform', {}).get('platform', 'unknown'), architecture=job_datum.get('build_platform', {}).get('architecture', 'unknown')) machine_platform, _ = MachinePlatform.objects.get_or_create( os_name=job_datum.get('machine_platform', {}).get('os_name', 'unknown'), platform=job_datum.get('machine_platform', {}).get('platform', 'unknown'), architecture=job_datum.get('machine_platform', {}).get('architecture', 'unknown')) option_names = job_datum.get('option_collection', []) option_collection_hash = OptionCollection.calculate_hash( option_names) if not OptionCollection.objects.filter( option_collection_hash=option_collection_hash).exists(): # in the unlikely event that we haven't seen this set of options # before, add the appropriate database rows options = [] for option_name in option_names: option, _ = Option.objects.get_or_create(name=option_name) options.append(option) for option in options: OptionCollection.objects.create( option_collection_hash=option_collection_hash, option=option) machine, _ = Machine.objects.get_or_create( name=job_datum.get('machine', 'unknown')) job_type, _ = JobType.objects.get_or_create( symbol=job_datum.get('job_symbol') or 'unknown', name=job_datum.get('name') or 'unknown') job_group, _ = JobGroup.objects.get_or_create( name=job_datum.get('group_name') or 'unknown', symbol=job_datum.get('group_symbol') or 'unknown') product_name = job_datum.get('product_name', 'unknown') if not product_name.strip(): product_name = 'unknown' product, _ = Product.objects.get_or_create(name=product_name) job_guid = job_datum['job_guid'] job_guid = job_guid[0:50] who = job_datum.get('who') or 'unknown' who = who[0:50] reason = job_datum.get('reason') or 'unknown' reason = reason[0:125] state = job_datum.get('state') or 'unknown' state = state[0:25] build_system_type = job_datum.get('build_system_type', 'buildbot') reference_data_name = job_datum.get('reference_data_name', None) default_failure_classification = FailureClassification.objects.get( name='not classified') sh = sha1() sh.update(''.join( map(str, [build_system_type, repository.name, build_platform.os_name, build_platform.platform, build_platform.architecture, machine_platform.os_name, machine_platform.platform, machine_platform.architecture, job_group.name, job_group.symbol, job_type.name, job_type.symbol, option_collection_hash, reference_data_name])).encode('utf-8')) signature_hash = sh.hexdigest() # Should be the buildername in the case of buildbot (if not provided # default to using the signature hash) if not reference_data_name: reference_data_name = signature_hash signature, _ = ReferenceDataSignatures.objects.get_or_create( name=reference_data_name, signature=signature_hash, build_system_type=build_system_type, repository=repository.name, defaults={ 'first_submission_timestamp': time.time(), 'build_os_name': build_platform.os_name, 'build_platform': build_platform.platform, 'build_architecture': build_platform.architecture, 'machine_os_name': machine_platform.os_name, 'machine_platform': machine_platform.platform, 'machine_architecture': machine_platform.architecture, 'job_group_name': job_group.name, 'job_group_symbol': job_group.symbol, 'job_type_name': job_type.name, 'job_type_symbol': job_type.symbol, 'option_collection_hash': option_collection_hash }) tier = job_datum.get('tier') or 1 result = job_datum.get('result', 'unknown') submit_time = datetime.fromtimestamp( _get_number(job_datum.get('submit_timestamp'))) start_time = datetime.fromtimestamp( _get_number(job_datum.get('start_timestamp'))) end_time = datetime.fromtimestamp( _get_number(job_datum.get('end_timestamp'))) # first, try to create the job with the given guid (if it doesn't # exist yet) job_guid_root = get_guid_root(job_guid) if not Job.objects.filter(guid__in=[job_guid, job_guid_root]).exists(): # This could theoretically already have been created by another process # that is running updates simultaneously. So just attempt to create # it, but allow it to skip if it's the same guid. The odds are # extremely high that this is a pending and running job that came in # quick succession and are being processed by two different workers. Job.objects.get_or_create( guid=job_guid, defaults={ "repository": repository, "signature": signature, "build_platform": build_platform, "machine_platform": machine_platform, "machine": machine, "option_collection_hash": option_collection_hash, "job_type": job_type, "job_group": job_group, "product": product, "failure_classification": default_failure_classification, "who": who, "reason": reason, "result": result, "state": state, "tier": tier, "submit_time": submit_time, "start_time": start_time, "end_time": end_time, "last_modified": datetime.now(), "push_id": push_id } ) # Can't just use the ``job`` we would get from the ``get_or_create`` # because we need to try the job_guid_root instance first for update, # rather than a possible retry job instance. try: job = Job.objects.get(guid=job_guid_root) except ObjectDoesNotExist: job = Job.objects.get(guid=job_guid) # add taskcluster metadata if applicable if all([k in job_datum for k in ['taskcluster_task_id', 'taskcluster_retry_id']]): try: TaskclusterMetadata.objects.create( job=job, task_id=job_datum['taskcluster_task_id'], retry_id=job_datum['taskcluster_retry_id']) except IntegrityError: pass # Update job with any data that would have changed Job.objects.filter(id=job.id).update( guid=job_guid, signature=signature, build_platform=build_platform, machine_platform=machine_platform, machine=machine, option_collection_hash=option_collection_hash, job_type=job_type, job_group=job_group, product=product, result=result, state=state, tier=tier, submit_time=submit_time, start_time=start_time, end_time=end_time, last_modified=datetime.now(), push_id=push_id) artifacts = job_datum.get('artifacts', []) has_text_log_summary = any(x for x in artifacts if x['name'] == 'text_log_summary') if artifacts: artifacts = serialize_artifact_json_blobs(artifacts) # need to add job guid to artifacts, since they likely weren't # present in the beginning for artifact in artifacts: if not all(k in artifact for k in ("name", "type", "blob")): raise ValueError( "Artifact missing properties: {}".format(artifact)) # Ensure every artifact has a ``job_guid`` value. # It is legal to submit an artifact that doesn't have a # ``job_guid`` value. But, if missing, it should inherit that # value from the job itself. if "job_guid" not in artifact: artifact["job_guid"] = job_guid store_job_artifacts(artifacts) log_refs = job_datum.get('log_references', []) job_logs = [] if log_refs: for log in log_refs:<|fim▁hole|> name = name[0:50] url = log.get('url') or 'unknown' url = url[0:255] # this indicates that a summary artifact was submitted with # this job that corresponds to the buildbot_text log url. # Therefore, the log does not need parsing. So we should # ensure that it's marked as already parsed. if has_text_log_summary and name == 'buildbot_text': parse_status = JobLog.PARSED else: parse_status_map = dict([(k, v) for (v, k) in JobLog.STATUSES]) mapped_status = parse_status_map.get( log.get('parse_status')) if mapped_status: parse_status = mapped_status else: parse_status = JobLog.PENDING jl, _ = JobLog.objects.get_or_create( job=job, name=name, url=url, defaults={ 'status': parse_status }) job_logs.append(jl) _schedule_log_parsing(job, job_logs, result) return job_guid def _schedule_log_parsing(job, job_logs, result): """Kick off the initial task that parses the log data. log_data is a list of job log objects and the result for that job """ # importing here to avoid an import loop from treeherder.log_parser.tasks import parse_logs task_types = { "errorsummary_json", "buildbot_text", "builds-4h" } job_log_ids = [] for job_log in job_logs: # a log can be submitted already parsed. So only schedule # a parsing task if it's ``pending`` # the submitter is then responsible for submitting the # text_log_summary artifact if job_log.status != JobLog.PENDING: continue # if this is not a known type of log, abort parse if job_log.name not in task_types: continue job_log_ids.append(job_log.id) # TODO: Replace the use of different queues for failures vs not with the # RabbitMQ priority feature (since the idea behind separate queues was # only to ensure failures are dealt with first if there is a backlog). if result != 'success': queue = 'log_parser_fail' priority = 'failures' else: queue = 'log_parser' priority = "normal" parse_logs.apply_async(queue=queue, args=[job.id, job_log_ids, priority]) def store_job_data(repository, originalData): """ Store job data instances into jobs db Example: [ { "revision": "24fd64b8251fac5cf60b54a915bffa7e51f636b5", "job": { "job_guid": "d19375ce775f0dc166de01daa5d2e8a73a8e8ebf", "name": "xpcshell", "desc": "foo", "job_symbol": "XP", "group_name": "Shelliness", "group_symbol": "XPC", "product_name": "firefox", "state": "TODO", "result": 0, "reason": "scheduler", "who": "sendchange-unittest", "submit_timestamp": 1365732271, "start_timestamp": "20130411165317", "end_timestamp": "1365733932" "machine": "tst-linux64-ec2-314", "build_platform": { "platform": "Ubuntu VM 12.04", "os_name": "linux", "architecture": "x86_64" }, "machine_platform": { "platform": "Ubuntu VM 12.04", "os_name": "linux", "architecture": "x86_64" }, "option_collection": { "opt": true }, "log_references": [ { "url": "http://ftp.mozilla.org/pub/...", "name": "unittest" } ], artifacts:[{ type:" json | img | ...", name:"", log_urls:[ ] blob:"" }], }, "superseded": [] }, ... ] """ data = copy.deepcopy(originalData) # Ensure that we have job data to process if not data: return # remove any existing jobs that already have the same state data = _remove_existing_jobs(data) if not data: return superseded_job_guid_placeholders = [] # TODO: Refactor this now that store_job_data() is only over called with one job at a time. for datum in data: try: # TODO: this might be a good place to check the datum against # a JSON schema to ensure all the fields are valid. Then # the exception we caught would be much more informative. That # being said, if/when we transition to only using the pulse # job consumer, then the data will always be vetted with a # JSON schema before we get to this point. job = datum['job'] revision = datum['revision'] superseded = datum.get('superseded', []) revision_field = 'revision__startswith' if len(revision) < 40 else 'revision' filter_kwargs = {'repository': repository, revision_field: revision} push_id = Push.objects.values_list('id', flat=True).get(**filter_kwargs) # load job job_guid = _load_job(repository, job, push_id) for superseded_guid in superseded: superseded_job_guid_placeholders.append( # superseded by guid, superseded guid [job_guid, superseded_guid] ) except Exception as e: # Surface the error immediately unless running in production, where we'd # rather report it on New Relic and not block storing the remaining jobs. # TODO: Once buildbot support is removed, remove this as part of # refactoring this method to process just one job at a time. if 'DYNO' not in os.environ: raise logger.exception(e) # make more fields visible in new relic for the job # where we encountered the error datum.update(datum.get("job", {})) newrelic.agent.record_exception(params=datum) # skip any jobs that hit errors in these stages. continue # Update the result/state of any jobs that were superseded by those ingested above. if superseded_job_guid_placeholders: for (job_guid, superseded_by_guid) in superseded_job_guid_placeholders: Job.objects.filter(guid=superseded_by_guid).update( result='superseded', state='completed')<|fim▁end|>
name = log.get('name') or 'unknown'
<|file_name|>parsing_ops.py<|end_file_name|><|fim▁begin|># Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Experimental `dataset` API for parsing example.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.data.ops import dataset_ops from tensorflow.python.data.util import structure from tensorflow.python.framework import dtypes from tensorflow.python.framework import sparse_tensor from tensorflow.python.framework import tensor_spec from tensorflow.python.ops import gen_experimental_dataset_ops from tensorflow.python.ops import parsing_ops from tensorflow.python.ops.ragged import ragged_tensor from tensorflow.python.util.tf_export import tf_export class _ParseExampleDataset(dataset_ops.UnaryDataset): """A `Dataset` that parses `example` dataset into a `dict` dataset.""" def __init__(self, input_dataset, features, num_parallel_calls, deterministic): self._input_dataset = input_dataset if not structure.are_compatible( input_dataset.element_spec, tensor_spec.TensorSpec([None], dtypes.string)): raise TypeError("Input dataset should be a dataset of vectors of strings") self._num_parallel_calls = num_parallel_calls if deterministic is None: self._deterministic = "default" elif deterministic: self._deterministic = "true" else: self._deterministic = "false" # pylint: disable=protected-access self._features = parsing_ops._prepend_none_dimension(features) # TODO(b/112859642): Pass sparse_index and sparse_values for SparseFeature params = parsing_ops._ParseOpParams.from_features(self._features, [ parsing_ops.VarLenFeature, parsing_ops.SparseFeature, parsing_ops.FixedLenFeature, parsing_ops.FixedLenSequenceFeature, parsing_ops.RaggedFeature ]) # pylint: enable=protected-access self._sparse_keys = params.sparse_keys self._sparse_types = params.sparse_types self._ragged_keys = params.ragged_keys self._ragged_value_types = params.ragged_value_types self._ragged_split_types = params.ragged_split_types self._dense_keys = params.dense_keys self._dense_defaults = params.dense_defaults_vec self._dense_shapes = params.dense_shapes_as_proto self._dense_types = params.dense_types input_dataset_shape = dataset_ops.get_legacy_output_shapes( self._input_dataset) self._element_spec = {} for (key, value_type) in zip(params.sparse_keys, params.sparse_types): self._element_spec[key] = sparse_tensor.SparseTensorSpec( input_dataset_shape.concatenate([None]), value_type) for (key, value_type, dense_shape) in zip(params.dense_keys, params.dense_types, params.dense_shapes): self._element_spec[key] = tensor_spec.TensorSpec( input_dataset_shape.concatenate(dense_shape), value_type) for (key, value_type, splits_type) in zip(params.ragged_keys, params.ragged_value_types, params.ragged_split_types): self._element_spec[key] = ragged_tensor.RaggedTensorSpec( input_dataset_shape.concatenate([None]), value_type, 1, splits_type) variant_tensor = ( gen_experimental_dataset_ops.parse_example_dataset_v2( self._input_dataset._variant_tensor, # pylint: disable=protected-access self._num_parallel_calls, self._dense_defaults, self._sparse_keys, self._dense_keys, self._sparse_types, self._dense_shapes, deterministic=self._deterministic, ragged_keys=self._ragged_keys, ragged_value_types=self._ragged_value_types, ragged_split_types=self._ragged_split_types, **self._flat_structure)) super(_ParseExampleDataset, self).__init__(input_dataset, variant_tensor) @property def element_spec(self): return self._element_spec<|fim▁hole|># TODO(b/111553342): add arguments names and example names as well. @tf_export("data.experimental.parse_example_dataset") def parse_example_dataset(features, num_parallel_calls=1, deterministic=None): """A transformation that parses `Example` protos into a `dict` of tensors. Parses a number of serialized `Example` protos given in `serialized`. We refer to `serialized` as a batch with `batch_size` many entries of individual `Example` protos. This op parses serialized examples into a dictionary mapping keys to `Tensor`, `SparseTensor`, and `RaggedTensor` objects. `features` is a dict from keys to `VarLenFeature`, `RaggedFeature`, `SparseFeature`, and `FixedLenFeature` objects. Each `VarLenFeature` and `SparseFeature` is mapped to a `SparseTensor`; each `RaggedFeature` is mapped to a `RaggedTensor`; and each `FixedLenFeature` is mapped to a `Tensor`. See `tf.io.parse_example` for more details about feature dictionaries. Args: features: A `dict` mapping feature keys to `FixedLenFeature`, `VarLenFeature`, `RaggedFeature`, and `SparseFeature` values. num_parallel_calls: (Optional.) A `tf.int32` scalar `tf.Tensor`, representing the number of parsing processes to call in parallel. deterministic: (Optional.) A boolean controlling whether determinism should be traded for performance by allowing elements to be produced out of order if some parsing calls complete faster than others. If `deterministic` is `None`, the `tf.data.Options.experimental_deterministic` dataset option (`True` by default) is used to decide whether to produce elements deterministically. Returns: A dataset transformation function, which can be passed to `tf.data.Dataset.apply`. Raises: ValueError: if features argument is None. """ if features is None: raise ValueError("Missing: features was %s." % features) def _apply_fn(dataset): """Function from `Dataset` to `Dataset` that applies the transformation.""" out_dataset = _ParseExampleDataset(dataset, features, num_parallel_calls, deterministic) if any( isinstance(feature, parsing_ops.SparseFeature) or (isinstance(feature, parsing_ops.RaggedFeature) and feature.partitions) for feature in features.values()): # pylint: disable=protected-access # pylint: disable=g-long-lambda out_dataset = out_dataset.map( lambda x: parsing_ops._construct_tensors_for_composite_features( features, x), num_parallel_calls=num_parallel_calls) return out_dataset return _apply_fn<|fim▁end|>
<|file_name|>static_resource.go<|end_file_name|><|fim▁begin|>package rest import "net/http" type StaticResource struct { ResourceBase result *Result self Link } func NewStaticResource(result *Result, self Link) Resource { return &StaticResource{ result: result, self: self, } } func StaticContent(content []byte, contentType string, selfHref string) Resource { return NewStaticResource( Ok().AddHeader("Content-Type", contentType).WithBody(content), SimpleLink(selfHref), )<|fim▁hole|>} func (r StaticResource) Self() Link { return r.self }<|fim▁end|>
} func (r StaticResource) Get(request *http.Request) (interface{}, error) { return r.result, nil
<|file_name|>mod_file_not_exist.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 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.<|fim▁hole|> mod not_a_real_file; //~ ERROR not_a_real_file.rs fn main() { assert_eq!(mod_file_aux::bar(), 10); }<|fim▁end|>
<|file_name|>t_output.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python2.6 -tt # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. # class Output: 'Output interface' def __init__(self, output): self._on_blank_line = True self._output = output self._flag = False def write(self, lines): 'Writes lines (a string) ' # assume we are not on a blank line self._write(lines) def _write(self, lines): raise NotImplementedError def _write_line_contents(self, line): # if anything was written if self._write_line_contents_impl(line): self._flag = False self._on_blank_line = False def _write_line_contents_impl(self, line): 'Returns whether anything was written or not' raise NotImplementedError def indent(self): pass def unindent(self): pass def force_newline(self): 'Force a newline' print >>self._output self._on_blank_line = True self._flag = False def line_feed(self): '''Enforce that the cursor is placed on an empty line, returns whether a newline was printed or not''' if not self._on_blank_line: self.force_newline() return True return False def double_space(self): '''Unless current position is already on an empty line, insert a blank line before the next statement, as long as it's not the beginning of<|fim▁hole|> def flag_this_line(self, flag=True): '''Mark the current line as flagged. This is used to apply specific logic to certain lines, such as those that represent the start of a scope.''' # TODO(dsanduleac): deprecate this and use a num_lines_printed # abstraction instead. Then modify t_cpp_generator to always print # newlines after statements. Should modify the behaviour of # double_space as well. self._flag = flag @property def on_flagged_line(self): 'Returns whether the line we are currently on has been flagged' return self._flag class IndentedOutput(Output): def __init__(self, output, indent_char=' '): Output.__init__(self, output) self._indent = 0 # configurable values self._indent_char = indent_char def indent(self, amount): assert self._indent + amount >= 0 self._indent += amount def unindent(self, amount): assert self._indent - amount >= 0 self._indent -= amount def _write_line_contents_impl(self, line): # strip trailing characters line = line.rstrip() # handle case where _write is being passed a \n-terminated string if line == '': # don't flag the current line as non-empty, we didn't write # anything return False if self._on_blank_line: # write indent self._output.write(self._indent * self._indent_char) # write content self._output.write(line) return True def _write(self, lines): lines = lines.split('\n') self._write_line_contents(lines[0]) for line in lines[1:]: # ensure newlines between input lines self.force_newline() self._write_line_contents(line) class CompositeOutput(Output): def __init__(self, *outputs): self._outputs = outputs def indent(self): for output in self._outputs: output.indent() def unindent(self): for output in self._outputs: output.unindent() def _write(self, lines): for output in self._outputs: output.write(lines) def _write_line_contents_impl(self, line): # this is never used internally in this output pass def line_feed(self): for output in self._outputs: output.line_feed() def force_newline(self): for output in self._outputs: output.force_newline() # These two don't make sense to be implemented here def flag_this_line(self): raise NotImplementedError def on_flagged_line(self): raise NotImplementedError def double_space(self): for output in self._outputs: output.double_space() class DummyOutput(Output): def __init__(self): pass def _write(self, lines): pass def _write_line_contents_impl(self, line): pass def force_newline(self): pass def line_feed(self): pass def double_space(self): pass def flag_this_line(self, flag=True): pass @property def on_flagged_line(self): return False<|fim▁end|>
a statement''' ofl = self.on_flagged_line if self.line_feed() and not ofl: self.force_newline()
<|file_name|>Flat.java<|end_file_name|><|fim▁begin|>/* * Copyright 2016 peter. * * 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. */ package onl.area51.filesystem.io; import java.io.IOException; import java.nio.file.Path; import java.util.Map; import org.kohsuke.MetaInfServices; /** * A flat FileSystem which locally matches it's structure */ @MetaInfServices(FileSystemIO.class) public class Flat extends LocalFileSystemIO { public Flat( Path basePath,<|fim▁hole|> { super( basePath, env ); } @Override protected String getPath( char[] path ) throws IOException { return String.valueOf( path ); } }<|fim▁end|>
Map<String, ?> env )
<|file_name|>ProductPriceException.java<|end_file_name|><|fim▁begin|>package com.idega.block.trade.stockroom.business; /** * Title: IW Trade * Description: * Copyright: Copyright (c) 2001 * Company: idega.is<|fim▁hole|>public class ProductPriceException extends RuntimeException { public ProductPriceException() { super(); } public ProductPriceException(String explanation){ super(explanation); } }<|fim▁end|>
* @author 2000 - idega team - <br><a href="mailto:[email protected]">Guðmundur Ágúst Sæmundsson</a><br><a href="mailto:[email protected]">Grímur Jónsson</a> * @version 1.0 */
<|file_name|>template.rs<|end_file_name|><|fim▁begin|>use syntax::parse::token; use syntax::parse::parser::Parser; use syntax::ext::base; use parse_utils::block_to_string; use parse_utils::is_tag_start; use parse::rust::parse_rust_tag; use parse::include::parse_include_tag; use parse::print::parse_print_tag; use tags::TEMPLATE; use tags::RUST; use tags::PRINT; use tags::END; use tags::INCLUDE; use tags::template::Template; use tags::template::SubTag; use tags::template::RawHtml; /// /// /// pub fn parse_template_tag( parser: &mut Parser, context: &base::ExtCtxt ) -> Template { let mut template = Template::new(); parse_start_template(&mut template, parser); template.sub_tags = parse_inner_template(parser, context); parse_end_template(parser); return template; } /// /// /// fn parse_start_template(state: &mut Template, parser: &mut Parser) { match ( parser.parse_ident(), parser.parse_fn_decl(true), parser.bump_and_get(), parser.bump_and_get()<|fim▁hole|> ) { ( functioname, ref function_decl, token::BINOP(token::PERCENT), token::GT ) => { state.name = Some(functioname); state.inputs = function_decl.inputs.clone(); println!("found template beginning") }, (one, two, three, four) => { parser.fatal(format!( "Expected `<% template xxx() %>`, found <% template {} {} {}{}", one, two, three, four ).as_slice()); } }; } /// /// /// fn parse_end_template(parser: &mut Parser) { match ( parser.parse_ident().as_str(), parser.bump_and_get(), parser.bump_and_get() ) { ( template, token::BINOP(token::PERCENT), token::GT ) if template == TEMPLATE => { println!("found end template")}, (one, two, three) => { parser.fatal(format!( "Expected `<% end template %>`, found <% end {} {}{}", one, Parser::token_to_string(&two), Parser::token_to_string(&three), ).as_slice()); } }; } /// Parse the content inside a <% template xxx() %> tag /// and return when we've finished to parse the <% end template %> /// if we have parsed all tokens without seeing <% end template %> /// we quit with error fn parse_inner_template ( parser: &mut Parser, context: &base::ExtCtxt ) -> Vec<SubTag> { let mut sub_tags = Vec::new(); // to know when we have a piece of HTML to display as it let mut start_html_block = parser.span.clone(); while parser.token != token::EOF { // TODO handle <%= (%= is interpreted as one token) if !is_tag_start(parser) { parser.bump(); continue; } // the beginning of a tag implies that the current raw html block // is finished let inner_string = block_to_string( context, &start_html_block, &parser.span ); sub_tags.push(RawHtml(inner_string)); //TODO: certainly a better way to do "consume < and %" parser.bump(); parser.bump(); let tag_name = parser.bump_and_get(); println!("{}", Parser::token_to_string(&tag_name)); match Parser::token_to_string(&tag_name).as_slice() { TEMPLATE => parser.fatal("<% template %> can't be nested"), RUST => sub_tags.push(parse_rust_tag(parser, context)), INCLUDE => sub_tags.push(parse_include_tag(parser)), PRINT => sub_tags.push(parse_print_tag(parser)), END => { return sub_tags; }, _ => parser.fatal("unknown tag"), } // we start a new raw html block start_html_block = parser.span.clone(); } parser.fatal("template tag opened but not closed"); }<|fim▁end|>
<|file_name|>glacier_push.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2.7 from boto.glacier.layer1 import Layer1 from boto.glacier.concurrent import ConcurrentUploader import sys import os.path from time import gmtime, strftime access_key_id = "xxx" secret_key = "xxx" target_vault_name = "xxx" inventory = "xxx"<|fim▁hole|> # a description you give to the file fdes = os.path.basename(sys.argv[1]) if not os.path.isfile(fname) : print("Can't find the file to upload") sys.exit(-1); # glacier uploader glacier_layer1 = Layer1(aws_access_key_id=access_key_id, aws_secret_access_key=secret_key, is_secure=True) uploader = ConcurrentUploader(glacier_layer1, target_vault_name, part_size=128*1024*1024, num_threads=1) archive_id = uploader.upload(fname, fdes) # write an inventory file f = open(inventory, 'a+') f.write(archive_id+'\t'+fdes+'\n') f.close() sys.exit(0);<|fim▁end|>
# the file to be uploaded into the vault as an archive fname = sys.argv[1]
<|file_name|>main.py<|end_file_name|><|fim▁begin|>########################################################################### # # Copyright 2021 Google LLC # # 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 # # https://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. # ########################################################################### """ Typically called by Cloud Scheduler with recipe JSON payload. Sample JSON POST payload: { "setup":{ "id":"", #string - Cloud Project ID for billing. "auth":{ "service":{}, #dict - Optional Cloud Service JSON credentials when task uses service. "user":{} #dict - Optional Cloud User JSON credentials when task uses user. } }, "tasks":[ # list of recipe tasks to execute, see StarThinker scripts for examples. { "hello":{ "auth":"user", # not used in demo, for display purposes only. "say":"Hello World" }} ] } <|fim▁hole|>from starthinker.util.configuration import Configuration from starthinker.util.configuration import execute def run(request): recipe = request.get_json(force=True) execute(Configuration(recipe=recipe, verbose=True), recipe.get('tasks', []), force=True) return 'DONE'<|fim▁end|>
Documentation: https://github.com/google/starthinker/blob/master/tutorials/deploy_cloudfunction.md """
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>#![feature(associated_consts)] #[macro_use] extern crate log;<|fim▁hole|>extern crate rand; extern crate readwrite_comp; pub mod node; mod utils { pub use mydht_base::utils::*; } mod keyval { pub use mydht_base::keyval::*; } mod kvstore; pub mod route; pub mod local_transport; pub mod transport; pub mod peer; pub mod shadow; pub mod bytes_wr;<|fim▁end|>
extern crate rustc_serialize; #[macro_use] extern crate mydht_base; extern crate time;
<|file_name|>ec2_ami_copy.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # 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/>. ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: ec2_ami_copy short_description: copies AMI between AWS regions, return new image id description: - Copies AMI from a source region to a destination region. B(Since version 2.3 this module depends on boto3.) version_added: "2.0" options: source_region: description: - The source region the AMI should be copied from. required: true source_image_id: description: - The ID of the AMI in source region that should be copied. required: true name: description: - The name of the new AMI to copy. (As of 2.3 the default is 'default', in prior versions it was 'null'.) required: false default: "default" description: description: - An optional human-readable string describing the contents and purpose of the new AMI. required: false default: null encrypted: description: - Whether or not the destination snapshots of the copied AMI should be encrypted. required: false default: null version_added: "2.2" kms_key_id: description: - KMS key id used to encrypt image. If not specified, uses default EBS Customer Master Key (CMK) for your account.<|fim▁hole|> required: false default: null version_added: "2.2" wait: description: - Wait for the copied AMI to be in state 'available' before returning. required: false default: "no" choices: [ "yes", "no" ] wait_timeout: description: - How long before wait gives up, in seconds. (As of 2.3 this option is deprecated. See boto3 Waiters) required: false default: 1200 tags: description: - A hash/dictionary of tags to add to the new copied AMI; '{"key":"value"}' and '{"key":"value","key":"value"}' required: false default: null author: "Amir Moulavi <[email protected]>, Tim C <[email protected]>" extends_documentation_fragment: - aws - ec2 requirements: - boto3 ''' EXAMPLES = ''' # Basic AMI Copy - ec2_ami_copy: source_region: us-east-1 region: eu-west-1 source_image_id: ami-xxxxxxx # AMI copy wait until available - ec2_ami_copy: source_region: us-east-1 region: eu-west-1 source_image_id: ami-xxxxxxx wait: yes register: image_id # Named AMI copy - ec2_ami_copy: source_region: us-east-1 region: eu-west-1 source_image_id: ami-xxxxxxx name: My-Awesome-AMI description: latest patch # Tagged AMI copy - ec2_ami_copy: source_region: us-east-1 region: eu-west-1 source_image_id: ami-xxxxxxx tags: Name: My-Super-AMI Patch: 1.2.3 # Encrypted AMI copy - ec2_ami_copy: source_region: us-east-1 region: eu-west-1 source_image_id: ami-xxxxxxx encrypted: yes # Encrypted AMI copy with specified key - ec2_ami_copy: source_region: us-east-1 region: eu-west-1 source_image_id: ami-xxxxxxx encrypted: yes kms_key_id: arn:aws:kms:us-east-1:XXXXXXXXXXXX:key/746de6ea-50a4-4bcb-8fbc-e3b29f2d367b ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ec2 import (boto3_conn, ec2_argument_spec, get_aws_connection_info) try: import boto import boto.ec2 HAS_BOTO = True except ImportError: HAS_BOTO = False try: import boto3 from botocore.exceptions import ClientError, NoCredentialsError, NoRegionError, WaiterError HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def copy_image(module, ec2): """ Copies an AMI module : AnsibleModule object ec2: ec2 connection object """ tags = module.params.get('tags') params = {'SourceRegion': module.params.get('source_region'), 'SourceImageId': module.params.get('source_image_id'), 'Name': module.params.get('name'), 'Description': module.params.get('description'), 'Encrypted': module.params.get('encrypted'), } if module.params.get('kms_key_id'): params['KmsKeyId'] = module.params.get('kms_key_id') try: image_id = ec2.copy_image(**params)['ImageId'] if module.params.get('wait'): ec2.get_waiter('image_available').wait(ImageIds=[image_id]) if module.params.get('tags'): ec2.create_tags( Resources=[image_id], Tags=[{'Key' : k, 'Value': v} for k,v in module.params.get('tags').items()] ) module.exit_json(changed=True, image_id=image_id) except WaiterError as we: module.fail_json(msg='An error occured waiting for the image to become available. (%s)' % we.reason) except ClientError as ce: module.fail_json(msg=ce.message) except NoCredentialsError: module.fail_json(msg='Unable to authenticate, AWS credentials are invalid.') except Exception as e: module.fail_json(msg='Unhandled exception. (%s)' % str(e)) def main(): argument_spec = ec2_argument_spec() argument_spec.update(dict( source_region=dict(required=True), source_image_id=dict(required=True), name=dict(default='default'), description=dict(default=''), encrypted=dict(type='bool', default=False, required=False), kms_key_id=dict(type='str', required=False), wait=dict(type='bool', default=False), wait_timeout=dict(default=1200), tags=dict(type='dict'))) module = AnsibleModule(argument_spec=argument_spec) if not HAS_BOTO: module.fail_json(msg='boto required for this module') # TODO: Check botocore version region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=True) if HAS_BOTO3: try: ec2 = boto3_conn(module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_params) except NoRegionError: module.fail_json(msg='AWS Region is required') else: module.fail_json(msg='boto3 required for this module') copy_image(module, ec2) if __name__ == '__main__': main()<|fim▁end|>
<|file_name|>base-repository.ts<|end_file_name|><|fim▁begin|>import { BehaviorSubject, Observable } from 'rxjs'; import { OpenSlidesComponent } from '../../openslides.component'; import { BaseViewModel } from './base-view-model'; import { BaseModel, ModelConstructor } from '../../shared/models/base/base-model'; import { CollectionStringModelMapperService } from '../../core/services/collectionStringModelMapper.service'; import { DataStoreService } from '../../core/services/data-store.service'; import { Identifiable } from '../../shared/models/base/identifiable'; import { auditTime } from 'rxjs/operators'; export abstract class BaseRepository<V extends BaseViewModel, M extends BaseModel> extends OpenSlidesComponent { /** * Stores all the viewModel in an object */ protected viewModelStore: { [modelId: number]: V } = {}; /** * Stores subjects to viewModels in a list */ protected viewModelSubjects: { [modelId: number]: BehaviorSubject<V> } = {}; /** * Observable subject for the whole list */ protected readonly viewModelListSubject: BehaviorSubject<V[]> = new BehaviorSubject<V[]>([]); /** * Construction routine for the base repository * * @param DS: The DataStore * @param collectionStringModelMapperService Mapping strings to their corresponding classes * @param baseModelCtor The model constructor of which this repository is about. * @param depsModelCtors A list of constructors that are used in the view model. * If one of those changes, the view models will be updated. */ public constructor( protected DS: DataStoreService, protected collectionStringModelMapperService: CollectionStringModelMapperService, protected baseModelCtor: ModelConstructor<M>, protected depsModelCtors?: ModelConstructor<BaseModel>[] ) { super(); this.setup(); } protected setup(): void { // Populate the local viewModelStore with ViewModel Objects. this.DS.getAll(this.baseModelCtor).forEach((model: M) => { this.viewModelStore[model.id] = this.createViewModel(model); }); // Update the list and then all models on their own this.updateViewModelListObservable(); this.DS.getAll(this.baseModelCtor).forEach((model: M) => { this.updateViewModelObservable(model.id); }); // Could be raise in error if the root injector is not known this.DS.changeObservable.subscribe(model => { if (model instanceof this.baseModelCtor) { // Add new and updated motions to the viewModelStore this.viewModelStore[model.id] = this.createViewModel(model as M); this.updateAllObservables(model.id); } else if (this.depsModelCtors) { const dependencyChanged: boolean = this.depsModelCtors.some(ctor => { return model instanceof ctor; }); if (dependencyChanged) { // if an domain object we need was added or changed, update viewModelStore this.getViewModelList().forEach(viewModel => { viewModel.updateValues(model); }); this.updateAllObservables(model.id); } } }); // Watch the Observables for deleting this.DS.deletedObservable.subscribe(model => { if (model.collection === this.collectionStringModelMapperService.getCollectionString(this.baseModelCtor)) { delete this.viewModelStore[model.id]; this.updateAllObservables(model.id); } }); } /** * Saves the update to an existing model. So called "update"-function * @param update the update that should be created * @param viewModel the view model that the update is based on */ public abstract async update(update: Partial<M>, viewModel: V): Promise<void>; /** * Deletes a given Model * @param update the update that should be created * @param viewModel the view model that the update is based on */ public abstract async delete(viewModel: V): Promise<void>; /** * Creates a new model * @param update the update that should be created * @param viewModel the view model that the update is based on * TODO: remove the viewModel */ public abstract async create(update: M): Promise<Identifiable>; /** * Creates a view model out of a base model. * * Should read all necessary objects from the datastore * that the viewmodel needs * @param model */ protected abstract createViewModel(model: M): V; /** * helper function to return one viewModel */ public getViewModel(id: number): V { return this.viewModelStore[id]; } /** * helper function to return the viewModel as array */ public getViewModelList(): V[] { return Object.values(this.viewModelStore); } /** * returns the current observable for one viewModel */ public getViewModelObservable(id: number): Observable<V> { if (!this.viewModelSubjects[id]) { this.viewModelSubjects[id] = new BehaviorSubject<V>(this.viewModelStore[id]); } return this.viewModelSubjects[id].asObservable(); } /** * Return the Observable of the whole store. * * All data is piped through an auditTime of 1ms. This is to prevent massive * updates, if e.g. an autoupdate with a lot motions come in. The result is just one * update of the new list instead of many unnecessary updates. */ public getViewModelListObservable(): Observable<V[]> { return this.viewModelListSubject.asObservable().pipe(auditTime(1)); } /** * Updates the ViewModel observable using a ViewModel corresponding to the id */ protected updateViewModelObservable(id: number): void { if (this.viewModelSubjects[id]) { this.viewModelSubjects[id].next(this.viewModelStore[id]); } } /** * update the observable of the list */ protected updateViewModelListObservable(): void {<|fim▁hole|> * Triggers both the observable update routines */ protected updateAllObservables(id: number): void { this.updateViewModelListObservable(); this.updateViewModelObservable(id); } }<|fim▁end|>
this.viewModelListSubject.next(this.getViewModelList()); } /**
<|file_name|>multisample_make_examples.py<|end_file_name|><|fim▁begin|># Copyright 2021 Google LLC. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. 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. # # 3. Neither the name of the copyright holder 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 HOLDER 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. r"""Experimental multi-sample make_examples for DeepVariant. This is a prototype for experimentation with multiple samples in DeepVariant, a proof of concept enabled by a refactoring to join together DeepVariant and DeepTrio, generalizing the functionality of make_examples to work with multiple samples. The output of this script is not compatible with any of DeepVariant's public models, and the DeepVariant team does not intend to provide support for users of this script. Example usage: multisample_make_examples \ --mode calling \ --ref "reference.fa" \ --reads "sample1.bam;sample2.bam;sample3.bam;sample4.bam;sample5.bam" \ --sample_names "sample1;sample2;sample3;sample4;sample5" \ --examples "examples.tfrecord.gz" \ --pileup_image_heights "20;20;20;20;20" \ # optional --downsample_fractions "0.5;0.5;0.5;0.5;0.5" # optional """ import os from absl import app from absl import flags from deepvariant import logging_level from deepvariant import make_examples_core from deepvariant import make_examples_options from deepvariant.protos import deepvariant_pb2 from third_party.nucleus.io.python import hts_verbose from third_party.nucleus.util import errors from third_party.nucleus.util import proto_utils MAIN_SAMPLE_INDEX = 0 # This is the first sample listed in --reads. FLAGS = flags.FLAGS # Adopt more general flags from make_examples_options. flags.adopt_module_key_flags(make_examples_options) # Define flags specific to multi-sample make_examples. flags.DEFINE_string( 'reads', None, 'Required. A list of BAM/CRAM files, with different ' 'samples separated by semi-colons. ' 'At least one aligned, sorted, indexed BAM/CRAM file is required for ' 'each sample. ' 'All must be aligned to the same reference genome compatible with --ref. ' 'Can provide multiple BAMs (comma-separated) for each sample. ' 'Format is, for example: sample1;sample2_BAM1,sample2_BAM2;sample3 ') flags.DEFINE_string( 'sample_names', 'DEFAULT', 'Sample names corresponding to the samples (must match order and length of ' 'samples in --reads). Separate names for each sample with semi-colons, ' 'e.g. "sample1;sample2;sample3". ' 'If not specified, (i.e. "sample1;;sample3" or even ";;") ' 'any sample without a sample name from this flag the will be inferred from ' 'the header information from --reads.') flags.DEFINE_string( 'downsample_fractions', 'DEFAULT', 'If not empty string ("") must be a value between 0.0 and 1.0. ' 'Reads will be kept (randomly) with a probability of downsample_fraction ' 'from the input sample BAMs. This argument makes it easy to create ' 'examples as though the input BAM had less coverage. ' 'Similar to --reads and --sample_name, supply different ' 'values for each sample by separating them with semi-colons, ' 'where the order of samples is the same as in --reads.') flags.DEFINE_string( 'pileup_image_heights', 'DEFAULT', 'Height for the part of the pileup image showing reads from each sample. ' 'By default, use a height of 100 for all samples. ' 'Similar to --reads and --sample_name, supply different ' 'values for each sample by separating them with semi-colons, ' 'where the order of samples is the same as in --reads.') def n_samples_from_flags(add_flags=True, flags_obj=None): """Collects sample-related options into a list of samples.""" n_reads = flags_obj.reads.split(';') num_samples = len(n_reads) flags_organized = {} for flag_name in [ 'reads', 'sample_names', 'downsample_fractions', 'pileup_image_heights' ]: if flags_obj[flag_name].value != 'DEFAULT': flags_organized[flag_name] = flags_obj[flag_name].value.split(';') if len(flags_organized[flag_name]) != num_samples: raise ValueError(f'--{flag_name} has {len(flags_organized[flag_name])} ' f'samples, but it should be matching the number of ' f'samples in --reads, which was {num_samples}.')<|fim▁hole|> else: flags_organized[flag_name] = [''] * num_samples n_sample_options = [] for i in range(num_samples): sample_name = make_examples_core.assign_sample_name( sample_name_flag=flags_organized['sample_names'][i], reads_filenames=flags_organized['reads'][i]) n_sample_options.append( deepvariant_pb2.SampleOptions( role=str(i), name=sample_name, variant_caller_options=make_examples_core.make_vc_options( sample_name=sample_name, flags_obj=flags_obj), order=range(num_samples), pileup_height=100)) if add_flags: for i in range(num_samples): n_sample_options[i].reads_filenames.extend( flags_organized['reads'][i].split(',')) if flags_organized['downsample_fractions'][i]: n_sample_options[i].downsample_fraction = float( flags_organized['downsample_fractions'][i]) if flags_organized['pileup_image_heights'][i]: n_sample_options[i].pileup_height = int( flags_organized['pileup_image_heights'][i]) # Ordering here determines the default order of samples, and when a sample # above has a custom .order, then this is the list those indices refer to. samples_in_order = n_sample_options sample_role_to_train = '0' return samples_in_order, sample_role_to_train def default_options(add_flags=True, flags_obj=None): """Creates a MakeExamplesOptions proto populated with reasonable defaults. Args: add_flags: bool. defaults to True. If True, we will push the value of certain FLAGS into our options. If False, those option fields are left uninitialized. flags_obj: object. If not None, use as the source of flags, else use global FLAGS. Returns: deepvariant_pb2.MakeExamplesOptions protobuf. Raises: ValueError: If we observe invalid flag values. """ if not flags_obj: flags_obj = FLAGS samples_in_order, sample_role_to_train = n_samples_from_flags( add_flags=add_flags, flags_obj=flags_obj) options = make_examples_options.shared_flags_to_options( add_flags=add_flags, flags_obj=flags_obj, samples_in_order=samples_in_order, sample_role_to_train=sample_role_to_train, main_sample_index=MAIN_SAMPLE_INDEX) if add_flags: options.bam_fname = '|'.join( [os.path.basename(x) for x in flags_obj.reads.split(';')]) return options def check_options_are_valid(options): """Checks that all the options chosen make sense together.""" # Check for general flags (shared for DeepVariant and DeepTrio). make_examples_options.check_options_are_valid( options, main_sample_index=MAIN_SAMPLE_INDEX) sample_names = [s.name for s in options.sample_options] if len(sample_names) != len(set(sample_names)): raise ValueError('--sample_names cannot contain duplicate names.') def main(argv=()): with errors.clean_commandline_error_exit(): if len(argv) > 1: errors.log_and_raise( 'Command line parsing failure: make_examples does not accept ' 'positional arguments but some are present on the command line: ' '"{}".'.format(str(argv)), errors.CommandLineError) del argv # Unused. proto_utils.uses_fast_cpp_protos_or_die() logging_level.set_from_flag() hts_verbose.set(hts_verbose.htsLogLevel[FLAGS.hts_logging_level]) # Set up options; may do I/O. options = default_options(add_flags=True, flags_obj=FLAGS) check_options_are_valid(options) # Run! make_examples_core.make_examples_runner(options) if __name__ == '__main__': flags.mark_flags_as_required([ 'examples', 'mode', 'reads', 'ref', ]) app.run(main)<|fim▁end|>
<|file_name|>translation_pl.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.0" language="pl_PL"> <context> <name>EditSiteWidget</name> <message> <location filename="../../ui/edit_site_widget.ui" line="14"/> <source>Dialog</source> <translation>Dialog</translation> </message> <message> <location filename="../../ui/edit_site_widget.ui" line="25"/> <source>Categories:</source> <translation>Kategorie:</translation> </message> <message> <location filename="../../ui/edit_site_widget.ui" line="32"/> <source>Site Name:</source> <translation>Nazwa strony:</translation> </message> <message> <location filename="../../ui/edit_site_widget.ui" line="45"/> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Password Type:&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Typ hasła:&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</translation> </message> <message> <location filename="../../ui/edit_site_widget.ui" line="65"/> <source>Site Counter:&lt;br&gt;(increase to get a &lt;br&gt;new password)</source> <translation>Licznik strony:&lt;br&gt;(zwiększ, by otrzymać&lt;br&gt; nowe hasło)</translation> </message> <message> <location filename="../../ui/edit_site_widget.ui" line="80"/> <source>Sample Password:</source> <translation>Przykładowe hasło:</translation> </message> <message> <location filename="../../ui/edit_site_widget.ui" line="94"/> <source>Password is determined by the User Name, Master Password, Site Name, Type and Counter</source> <translation>Hasło jest zależne od nazwy użytkownika, hasła głównego, nazwy strony, typu i licznika</translation> </message> <message> <location filename="../../ui/edit_site_widget.ui" line="106"/> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;b&gt;Optional&lt;/b&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;b&gt;Opcjonalne&lt;/b&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</translation> </message> <message> <location filename="../../ui/edit_site_widget.ui" line="116"/> <source>Comment:</source> <translation>Komentarz:</translation> </message> <message> <location filename="../../ui/edit_site_widget.ui" line="126"/> <source>Login Name:</source> <translation>Nazwa logowania:</translation> </message> <message> <location filename="../../ui/edit_site_widget.ui" line="142"/> <source>Url:</source> <translation>Adres URL:</translation> </message> <message> <location filename="../../src/edit_site_widget.cpp" line="46"/> <source>Edit Site</source> <translation>Edytuj stronę</translation> </message> <message> <location filename="../../src/edit_site_widget.cpp" line="54"/> <source>New Site</source> <translation>Nowa strona</translation> </message> </context> <context> <name>MainWindow</name> <message> <location filename="../../ui/main_window.ui" line="14"/> <source>qMasterPassword</source> <translation></translation> </message> <message> <location filename="../../ui/main_window.ui" line="82"/> <location filename="../../src/main_window.cpp" line="323"/> <source>Login</source> <translation>Zaloguj</translation> </message> <message> <location filename="../../ui/main_window.ui" line="119"/> <source>Categories</source> <translation>Kategorie</translation> </message> <message> <location filename="../../ui/main_window.ui" line="161"/> <source>Filter:</source> <translation>Filtr</translation> </message> <message> <location filename="../../ui/main_window.ui" line="175"/> <source>Add Site</source> <translation>Dodaj stronę</translation> </message> <message> <location filename="../../ui/main_window.ui" line="185"/> <source>Edit Site</source> <translation>Edytuj stronę</translation> </message> <message> <location filename="../../ui/main_window.ui" line="195"/> <source>Delete Site</source> <translation>Usuń stronę</translation> </message> <message> <location filename="../../ui/main_window.ui" line="252"/> <source>&amp;Edit</source> <translation>&amp;Edycja</translation> </message> <message> <location filename="../../ui/main_window.ui" line="260"/> <source>&amp;Help</source> <translation>&amp;Pomoc</translation> </message> <message> <location filename="../../ui/main_window.ui" line="272"/> <source>&amp;Settings</source> <translation>&amp;Ustawienia</translation> </message> <message> <location filename="../../ui/main_window.ui" line="277"/> <source>&amp;About</source> <translation>&amp;O programie</translation> </message> <message> <location filename="../../ui/main_window.ui" line="282"/> <source>Shortcuts</source> <translation>Skróty</translation> </message> <message> <location filename="../../ui/main_window.ui" line="287"/> <source>Password Generator</source> <translation>Generator haseł</translation> </message> <message> <location filename="../../src/main_window.cpp" line="174"/> <source>&amp;Quit</source> <translation>&amp;Wyjdź</translation> </message> <message> <location filename="../../src/main_window.cpp" line="271"/> <source>Login Failed</source> <translation>Logowanie nie powiodło się</translation> </message> <message> <location filename="../../src/main_window.cpp" line="272"/> <source>Wrong Password</source> <translation>Niepoprawne hasło</translation> </message> <message> <location filename="../../src/main_window.cpp" line="275"/> <location filename="../../src/main_window.cpp" line="982"/> <source>Logout</source> <translation>Wyloguj</translation> </message> <message> <location filename="../../src/main_window.cpp" line="298"/> <source>HMAC SHA256 function failed</source> <translation>Funkcja HMAC SHA256 nie powiodła się</translation> </message> <message> <location filename="../../src/main_window.cpp" line="301"/> <source>scrypt function failed</source> <translation>Funkcja scrypt nie powiodła się</translation> </message> <message> <location filename="../../src/main_window.cpp" line="304"/> <source>not logged in</source> <translation>Niezalogowany</translation> </message> <message> <location filename="../../src/main_window.cpp" line="307"/> <source>Multithreadding exception</source> <translation>Błąd wielowątkowości</translation> </message> <message> <location filename="../../src/main_window.cpp" line="310"/> <source>Random number generation failed</source> <translation>Generowanie losowych liczb nie powiodło się</translation> </message> <message> <location filename="../../src/main_window.cpp" line="313"/> <source>Cryptographic exception</source> <translation>Błąd kryptograficzny</translation> </message> <message> <location filename="../../src/main_window.cpp" line="314"/> <source>Error: %1. Should it happen again, then something is seriously wrong with the program installation.</source> <translation>Błąd: %1. Jeśli błąd pojawi się kolejny raz, istnieje problem z instalacją programu.</translation> </message> <message> <location filename="../../src/main_window.cpp" line="344"/> <source>User exists</source> <translation>Użytkownik istnieje</translation> </message> <message> <location filename="../../src/main_window.cpp" line="345"/> <source>Error: user already exists.</source> <translation>Błąd: użytkownik już istnieje.</translation> </message> <message> <location filename="../../src/main_window.cpp" line="380"/> <source>Delete User</source> <translation>Usuń użytkownika</translation> </message> <message> <location filename="../../src/main_window.cpp" line="381"/> <source>Do you really want to delete the user %1?</source> <translation>Czy na pewno chcesz usunąć użytkownika %1?</translation> </message> <message> <location filename="../../src/main_window.cpp" line="561"/> <source>All</source> <translation>Wszystkie</translation> </message> <message> <location filename="../../src/main_window.cpp" line="736"/> <location filename="../../src/main_window.cpp" line="747"/> <source> for %1 seconds</source> <translation>przez %1 sekund</translation> </message> <message> <location filename="../../src/main_window.cpp" line="737"/> <source>Copied Password to Clipboard</source> <translation>Hasło skopiowane do schowka </translation> </message> <message> <location filename="../../src/main_window.cpp" line="748"/> <source>Copied login name to Clipboard</source> <translation>Skopoiowano nazwę logowania do schowka</translation> </message> <message> <location filename="../../src/main_window.cpp" line="850"/> <source>&amp;Hide</source> <translation>&amp;Ukryj</translation> </message> <message> <location filename="../../src/main_window.cpp" line="852"/> <source>&amp;Show</source> <translation>&amp;Pokaż</translation> </message> <message> <location filename="../../src/main_window.cpp" line="907"/> <source>About %1</source> <translation>O %1</translation> </message> <message> <location filename="../../src/main_window.cpp" line="966"/> <source>Copy password of selected item to clipboard</source> <translation>Skopiuj hasło wybranej pozycji </translation> </message> <message> <location filename="../../src/main_window.cpp" line="968"/> <source>Copy login/user name of selected item to clipboard</source> <translation>Skopiuj login/nazwę logowania wybranej pozycji</translation> </message> <message> <location filename="../../src/main_window.cpp" line="970"/> <source>Auto fill form: select next window and fill in user name (if set) and password</source> <translation>Automatycznie wypełnij pola: wybierz kolejne okno i wypełnij nazwę użytkownika (jeśli ustawiona) oraz hasło</translation> </message> <message> <location filename="../../src/main_window.cpp" line="972"/> <source>Auto fill form (password only)</source> <translation>Autokatycznie wypełnij pole (tylko hasłem)</translation> </message> <message> <location filename="../../src/main_window.cpp" line="974"/> <source>Focus the filter text</source> <translation>Wybierz tekst filtra</translation> </message> <message> <location filename="../../src/main_window.cpp" line="976"/> <source>Select previous item</source> <translation>Wybierz poprzednią pozycję</translation> </message> <message> <location filename="../../src/main_window.cpp" line="978"/> <source>Select next item</source> <translation>Wybierz następną pozycję</translation> </message> <message> <location filename="../../src/main_window.cpp" line="980"/> <source>Open URL of selected item</source> <translation>Otwórz URL wybranej pozycji</translation> </message> </context> <context> <name>PasswordGeneratorWidget</name> <message> <location filename="../../ui/password_generator_widget.ui" line="14"/> <source>Password Generator</source> <translation>Generator haseł</translation> </message> <message> <location filename="../../ui/password_generator_widget.ui" line="22"/><|fim▁hole|> <translation>Metoda:</translation> </message> <message> <location filename="../../ui/password_generator_widget.ui" line="33"/> <source>Characters</source> <translation>Znaki</translation> </message> <message> <location filename="../../ui/password_generator_widget.ui" line="38"/> <source>Templates</source> <translation>Szablony</translation> </message> <message> <location filename="../../ui/password_generator_widget.ui" line="81"/> <source>a-z</source> <translation>a-z</translation> </message> <message> <location filename="../../ui/password_generator_widget.ui" line="91"/> <source>0-9</source> <translation>0-9</translation> </message> <message> <location filename="../../ui/password_generator_widget.ui" line="101"/> <source>A-Z</source> <translation>A-Z</translation> </message> <message> <location filename="../../ui/password_generator_widget.ui" line="114"/> <source>@&amp;&amp;%?,=:+*$#!&apos;^~;/.</source> <translation>@&amp;&amp;%?,=:+*$#!&apos;^~;/.</translation> </message> <message> <location filename="../../ui/password_generator_widget.ui" line="124"/> <source>Select Characters:</source> <translation>Wybierz znaki:</translation> </message> <message> <location filename="../../ui/password_generator_widget.ui" line="131"/> <source>Custom Characters:</source> <translation>Znaki niestandardowe:</translation> </message> <message> <location filename="../../ui/password_generator_widget.ui" line="144"/> <source>()[]{}&lt;&gt;</source> <translation>()[]{}&lt;&gt;</translation> </message> <message> <location filename="../../ui/password_generator_widget.ui" line="151"/> <source>_ (Underline)</source> <translation>_ (Znak podkreślenia)</translation> </message> <message> <location filename="../../ui/password_generator_widget.ui" line="161"/> <source>(Space)</source> <translation>(Spacja)</translation> </message> <message> <location filename="../../ui/password_generator_widget.ui" line="168"/> <source>- (Minus)</source> <translation>- (Minus)</translation> </message> <message> <location filename="../../ui/password_generator_widget.ui" line="188"/> <location filename="../../ui/password_generator_widget.ui" line="233"/> <source>Password Length:</source> <translation>Długość hasła:</translation> </message> <message> <location filename="../../ui/password_generator_widget.ui" line="259"/> <source>Add special Character</source> <translation>Dodaj znak specjalny</translation> </message> <message> <location filename="../../ui/password_generator_widget.ui" line="269"/> <source>Add Number</source> <translation>Dodaj cyfry</translation> </message> <message> <location filename="../../ui/password_generator_widget.ui" line="282"/> <source>Password Strength</source> <translation>Siła hasła</translation> </message> <message> <location filename="../../ui/password_generator_widget.ui" line="319"/> <source>Generate</source> <translation>Wygeneruj</translation> </message> <message> <location filename="../../src/password_generator_widget.cpp" line="80"/> <source> Bits</source> <translation> Bity</translation> </message> <message> <location filename="../../src/password_generator_widget.cpp" line="85"/> <source>Very Weak; might keep out family members</source> <translation>Bardzo słabe; może najwyżej ochronić przed członkami rodziny</translation> </message> <message> <location filename="../../src/password_generator_widget.cpp" line="87"/> <source>Weak; should keep out most people, often good for desktop login passwords</source> <translation>Słabe; powinno chronić przed większością osób, często dobre dla haseł logowania do komputerów</translation> </message> <message> <location filename="../../src/password_generator_widget.cpp" line="89"/> <source>Reasonable; fairly secure passwords for network and company passwords</source> <translation>Rozsądne; dosyć bezpieczne hasło dla haseł do sieci i firm</translation> </message> <message> <location filename="../../src/password_generator_widget.cpp" line="91"/> <source>Strong; can be good for guarding financial information</source> <translation>Silne; może być stosowane do chronienia finansów</translation> </message> <message> <location filename="../../src/password_generator_widget.cpp" line="93"/> <source>Very Strong; often overkill</source> <translation>Bardzo silne; czasami przesada</translation> </message> <message> <location filename="../../src/password_generator_widget.cpp" line="153"/> <source>Error</source> <translation>Błąd</translation> </message> <message> <location filename="../../src/password_generator_widget.cpp" line="153"/> <source>Failed to get random data</source> <translation>Nie udało się otrzymać losowych danych</translation> </message> <message> <location filename="../../src/password_generator_widget.cpp" line="278"/> <source>&lt;p&gt;&lt;b&gt;Method&lt;/b&gt;&lt;br&gt;The character-based method is purely random for the chosen characters and thus harder to guess.&lt;br&gt;The template-based method on the other hand is a bit less random but its passwords are easier to remember.&lt;/p&gt;&lt;p&gt;&lt;b&gt;Password Strength&lt;/b&gt;&lt;br&gt;Shows the entropy bits, where an increase of 1 means twice the amount of brute-force attempts is needed.&lt;br&gt;Note that the statement holds for general passwords. A master password in qMasterPassword is harder to crack (compared to for example web passwords), because the algorithm was specifically designed to be CPU intensive.&lt;/p&gt;</source> <translation>&lt;p&gt;&lt;b&gt;Metoda&lt;/b&gt;&lt;br&gt;Metoda bazowana na znakach jest losowa i dzięki temu hasła są trudniejsze do zgadnięcia.&lt;br&gt;Metoda bazowana na szablonach jest mniej losoba, lecz hasła są łatwiejsze do zapamiętania.&lt;/p&gt;&lt;p&gt;&lt;b&gt;Siła hasła&lt;/b&gt;&lt;br&gt;Pokazuje bity entropii (losowości), gdzie 1 bit więcej to dwukrotnie większa ilość czasu potrzebna na zgadnięcie hasła metodą brute-force.&lt;br&gt;Należy zauważyć, że ta zasada stosowana jest dla &quot;zwykłych&quot; haseł. Hasło główne w qMasterPassword jest skonstruowane tak, by było trudniejsze do złamania metodą brute-force, gdyż algorytm ten jest bardziej wymagający dla procesora.&lt;/p&gt;</translation> </message> </context> <context> <name>QObject</name> <message> <location filename="../../src/main_window.cpp" line="143"/> <source>Site</source> <translation>Strona</translation> </message> <message> <location filename="../../src/main_window.cpp" line="144"/> <source>Login Name</source> <translation>Nazwa logowania</translation> </message> <message> <location filename="../../src/main_window.cpp" line="145"/> <source>Password</source> <translation>Hasło</translation> </message> <message> <location filename="../../src/main_window.cpp" line="148"/> <source>Comment</source> <translation>Komentarz</translation> </message> <message> <location filename="../../src/main_window.cpp" line="149"/> <source>Type</source> <translation>Typ</translation> </message> <message> <location filename="../../src/main_window.cpp" line="150"/> <source>Counter</source> <translation>Licznik</translation> </message> </context> <context> <name>SettingsWidget</name> <message> <location filename="../../ui/settings_widget.ui" line="14"/> <source>Settings</source> <translation>Ustawienia</translation> </message> <message> <location filename="../../ui/settings_widget.ui" line="20"/> <source>General</source> <translation>Ogólne</translation> </message> <message> <location filename="../../ui/settings_widget.ui" line="26"/> <source>Show Passwords after login</source> <translation>Pokazuj hasła po zalogowaniu</translation> </message> <message> <location filename="../../ui/settings_widget.ui" line="33"/> <source>Show System Tray Icon</source> <translation>Pokazuj ikonę w pasku zadań</translation> </message> <message> <location filename="../../ui/settings_widget.ui" line="40"/> <source>Fill Form (Ctrl+V): Hide Window instead of using Alt+Tab</source> <translation>Wypełnianie pól (Ctrl+V): Ukryj okno zamiast używania Alt+Tab</translation> </message> <message> <location filename="../../ui/settings_widget.ui" line="49"/> <source>Auto logout when Window is hidden.</source> <translation>Wyoguj automatycznie gdy okno programu jest ukryte.</translation> </message> <message> <location filename="../../ui/settings_widget.ui" line="56"/> <source>Timeout:</source> <translation>Limit czasu:</translation> </message> <message> <location filename="../../ui/settings_widget.ui" line="70"/> <source>Minutes</source> <translatorcomment>In edge cases the word needs to be conjugated</translatorcomment> <translation>Minut</translation> </message> <message> <location filename="../../ui/settings_widget.ui" line="94"/> <source>Clipboard: Clear password after</source> <translation>Schowek: Wyczyść hasło po</translation> </message> <message> <location filename="../../ui/settings_widget.ui" line="114"/> <source>Seconds</source> <translation>Sekundach</translation> </message> <message> <location filename="../../ui/settings_widget.ui" line="136"/> <source>Show Identicon. Useful to notice typos in the entered master password.</source> <translation>Pokazuj ikonę identyfikacyjną. Użyteczne dla zauważania literówek we wprowadzonym haśle.</translation> </message> <message> <location filename="../../ui/settings_widget.ui" line="146"/> <source>Categories</source> <translation>Kategorie</translation> </message> <message> <location filename="../../ui/settings_widget.ui" line="168"/> <source>Remove</source> <translation>Usuń</translation> </message> <message> <location filename="../../ui/settings_widget.ui" line="178"/> <source>Add</source> <translation>Dodaj</translation> </message> <message> <location filename="../../ui/settings_widget.ui" line="185"/> <source>Restore Defaults</source> <translation>Przywróć domyślne</translation> </message> <message> <location filename="../../ui/settings_widget.ui" line="195"/> <source>Import/Export</source> <translation>Import/Eksport</translation> </message> <message> <location filename="../../ui/settings_widget.ui" line="203"/> <source>User:</source> <translation>Użytkownik:</translation> </message> <message> <location filename="../../ui/settings_widget.ui" line="230"/> <source>Import from JSON</source> <translation>Importuj z JSON</translation> </message> <message> <location filename="../../ui/settings_widget.ui" line="250"/> <source>Export as JSON</source> <translation>Eksportuj jako JSON</translation> </message> <message> <location filename="../../src/settings_widget.cpp" line="113"/> <location filename="../../src/settings_widget.cpp" line="146"/> <source>JSON (*.json)</source> <translation>JSON</translation> </message> <message> <location filename="../../src/settings_widget.cpp" line="127"/> <location filename="../../src/settings_widget.cpp" line="159"/> <source>Error Opening File</source> <translation>Błąd podczas otwierania pliku</translation> </message> <message> <location filename="../../src/settings_widget.cpp" line="128"/> <source>Could not write to file %1</source> <translation>Zapis do pliku %1 nie powiódł się</translation> </message> <message> <location filename="../../src/settings_widget.cpp" line="131"/> <location filename="../../src/settings_widget.cpp" line="163"/> <source>Error</source> <translation>Błąd</translation> </message> <message> <location filename="../../src/settings_widget.cpp" line="132"/> <location filename="../../src/settings_widget.cpp" line="164"/> <source>unknown error (%1) occurred</source> <translation>wystąpił nieznany błąd (%1)</translation> </message> <message> <location filename="../../src/settings_widget.cpp" line="160"/> <source>Could not read from file %1</source> <translation>Odczyt z pliku %1 nie powiódł się</translation> </message> <message> <location filename="../../src/settings_widget.cpp" line="210"/> <source>Personal</source> <translation>Osobiste</translation> </message> <message> <location filename="../../src/settings_widget.cpp" line="211"/> <source>Work</source> <translation>Praca</translation> </message> <message> <location filename="../../src/settings_widget.cpp" line="212"/> <source>eShopping</source> <translation>Zakupy internetowe</translation> </message> <message> <location filename="../../src/settings_widget.cpp" line="213"/> <source>Social Networks</source> <translation>Media społecznościowe</translation> </message> <message> <location filename="../../src/settings_widget.cpp" line="214"/> <source>Bank</source> <translation>Bank</translation> </message> <message> <location filename="../../src/settings_widget.cpp" line="215"/> <source>Forum</source> <translation>Fora</translation> </message> <message> <location filename="../../src/settings_widget.cpp" line="216"/> <source>eMail</source> <translation>eMail</translation> </message> </context> <context> <name>ShortcutsWidget</name> <message> <location filename="../../ui/shortcuts_widget.ui" line="14"/> <source>Keyboard Shortcuts</source> <translation>Skróty klawiszowe</translation> </message> <message> <location filename="../../ui/shortcuts_widget.ui" line="20"/> <source>Keyboard shortcuts when a password entry is selected:</source> <translation>Skróty klawiszowe gdy hasło jest wybrane:</translation> </message> <message> <location filename="../../src/shortcuts_widget.cpp" line="15"/> <source>Shortcut(s)</source> <translation>Skrót(y)</translation> </message> <message> <location filename="../../src/shortcuts_widget.cpp" line="16"/> <source>Description</source> <translation>Opis</translation> </message> </context> <context> <name>UserWidget</name> <message> <location filename="../../ui/user_widget.ui" line="20"/> <source>Add User</source> <translation>Dodaj użytkownika</translation> </message> <message> <location filename="../../ui/user_widget.ui" line="56"/> <source>Master Password:</source> <translation>Hasło główne:</translation> </message> <message> <location filename="../../ui/user_widget.ui" line="66"/> <source>Repeat Password:</source> <translation>Powtórz hasło:</translation> </message> <message> <location filename="../../ui/user_widget.ui" line="76"/> <source>User Name:</source> <translation>Nazwa użytkownika:</translation> </message> <message> <location filename="../../ui/user_widget.ui" line="96"/> <source>Identicon:</source> <translation>Ikona identyfikacyjna:</translation> </message> <message> <location filename="../../ui/user_widget.ui" line="112"/> <source>Generate...</source> <translation>Wygeneruj...</translation> </message> <message> <location filename="../../ui/user_widget.ui" line="121"/> <source>Check Password when logging in. (if enabled, the hash of the password needs to be stored)</source> <translation>Sprawdzaj hasło przy logowaniu. (Gdy włączone, hash hasła musi być zachowany w pliku)</translation> </message> <message> <location filename="../../src/user_widget.cpp" line="38"/> <source>Edit User</source> <translation>Edytuj użytkownika</translation> </message> <message> <location filename="../../src/user_widget.cpp" line="60"/> <source>Cryptographic exception</source> <translation>Błąd kryptograficzny</translation> </message> <message> <location filename="../../src/user_widget.cpp" line="61"/> <source>Failed to generate password hash. password check will be disabled.</source> <translation>Generowanie hashu hasła nie powiodło się. Sprawdzanie hasła zostanie wyłączone.</translation> </message> <message> <location filename="../../src/user_widget.cpp" line="102"/> <source>&lt;p&gt;The identicon is a visual help calculated from the user name and the master password.&lt;/p&gt;&lt;p&gt;Remember it and if it is the same when logging in, you most likely didn&apos;t make a typo.&lt;/p&gt;&lt;p&gt;This avoids the need to explicitly store the hash of the password (password check option below).&lt;/p&gt;&lt;p&gt;It can be disabled under Edit -&gt; Settings.&lt;/p&gt;</source> <translation>&lt;p&gt;Ikona identyfikacyjna jest graficzną pomocą generowaną z nazwy użytkownika i hasła.&lt;/p&gt;&lt;p&gt;Zapamiętaj ją. Jeśli jest taka sama przy logowaniu, najprawdopodobniej hasło zostało wpisane poprawnie.&lt;/p&gt;&lt;p&gt;To daje możliwość uniknięcia przechowywania hashu hasła (opcja sprawdzania hasła poniżej).&lt;/p&gt;&lt;p&gt;Ikona identyfikacyjna może zostać wyłączona w menu Edycja -&gt; Ustawienia.&lt;/p&gt;</translation> </message> </context> </TS><|fim▁end|>
<source>Method:</source>
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.urls import path from tickets import views urlpatterns = [ path('', views.last_event, name='last_event'), path('event/<str:ev>/', views.event, name='event'), <|fim▁hole|> path('event/<str:ev>/<str:space>/<str:session>/register/', views.register, name='register'), path('ticket/<str:order>/payment/', views.payment, name='payment'), path('ticket/<str:order>/thanks/', views.thanks, name='thanks'), path('ticket/confirm/', views.confirm, name='confirm'), path('ticket/confirm/paypal/', views.confirm_paypal, name='confirm_paypal'), path('ticket/<str:order>/confirm/stripe/', views.confirm_stripe, name='confirm_stripe'), path('ticket/template/<int:id>/preview/', views.template_preview, name='template_preview'), path('ticket/email-confirm/<int:id>/preview/', views.email_confirm_preview, name='email_confirm_preview'), path('<str:ev>/', views.multipurchase, name='multipurchase'), path('seats/<int:session>/<int:layout>/', views.ajax_layout, name='ajax_layout'), path('seats/view/<int:map>/', views.seats, name='seats'), path('seats/auto/', views.autoseats, name='autoseats'), path('seats/bystr/', views.seats_by_str, name='seats_by_str'), ]<|fim▁end|>
<|file_name|>healpix.py<|end_file_name|><|fim▁begin|>import numpy as np import exceptions import healpy from file import read def read_map(filename, HDU=0, field=0, nest=False): """Read Healpix map all columns of the specified HDU are read into a compound numpy MASKED array if nest is not None, the map is converted if need to NEST or RING ordering. this function requires healpy""" m, h = read(filename, HDU=HDU, return_header=True) try: m = m[field] except exceptions.KeyError: m = m.values()[field] nside = healpy.npix2nside(m.size) if not nest is None: if h.get('ORDERING', False): if h['ORDERING'] == 'NESTED' and not nest: idx = healpy.ring2nest(nside,np.arange(m.size,dtype=np.int32)) m = m[idx] elif h['ORDERING'] == 'RING' and nest: idx = healpy.nest2ring(nside,np.arange(m.size,dtype=np.int32))<|fim▁hole|> def read_mask(filename, HDU=0, field=0, nest=False): m = read_map(filename, HDU, field, nest) return np.logical_not(m.filled()).astype(np.bool)<|fim▁end|>
m = m[idx] return healpy.ma(m)
<|file_name|>Patch.py<|end_file_name|><|fim▁begin|>import numpy as np <|fim▁hole|>from bokeh.models import ColumnDataSource, DataRange1d, Plot, LinearAxis, Grid from bokeh.models.glyphs import Patch from bokeh.plotting import show N = 30 x1 = np.linspace(-2, 2, N) x2 = x1[::-1] y1 = x1**2 y2 = x2**2 + (x2+2.2) x = np.hstack((x1, x2)) y = np.hstack((y1, y2)) source = ColumnDataSource(dict(x=x, y=y)) xdr = DataRange1d(sources=[source.columns("x")]) ydr = DataRange1d(sources=[source.columns("y")]) plot = Plot( title=None, x_range=xdr, y_range=ydr, plot_width=300, plot_height=300, h_symmetry=False, v_symmetry=False, min_border=0, toolbar_location=None) glyph = Patch(x="x", y="y", fill_color="#a6cee3") plot.add_glyph(source, glyph) xaxis = LinearAxis() plot.add_layout(xaxis, 'below') yaxis = LinearAxis() plot.add_layout(yaxis, 'left') plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker)) plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) doc = Document() doc.add(plot) show(plot)<|fim▁end|>
from bokeh.document import Document
<|file_name|>66. Plus One.py<|end_file_name|><|fim▁begin|>class Solution(object): def plusOne(self, digits):<|fim▁hole|> """ :type digits: List[int] :rtype: List[int] """ return [int(i) for i in str(int(''.join(map(str, digits)))+1)] Solution().plusOne([0])<|fim▁end|>
<|file_name|>graphic_generator.py<|end_file_name|><|fim▁begin|># =============================================================================== # Copyright 2013 Jake Ross # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # =============================================================================== from __future__ import absolute_import from __future__ import print_function from chaco.label import Label from six.moves import map from pychron.core.ui import set_qt set_qt() # ============= enthought library imports ======================= from chaco.abstract_overlay import AbstractOverlay from kiva.fonttools import str_to_font from traits.api import HasTraits, Instance, Float, File, Property, Str, List from traitsui.api import View, Controller, UItem from chaco.api import OverlayPlotContainer from enable.component_editor import ComponentEditor from pyface.api import FileDialog, OK # ============= standard library imports ======================== from lxml.etree import ElementTree, Element from chaco.plot import Plot from chaco.array_plot_data import ArrayPlotData from numpy import linspace, cos, sin, pi import os import csv from chaco.data_label import DataLabel from pychron.paths import paths from chaco.plot_graphics_context import PlotGraphicsContext from traitsui.menu import Action import math from pychron.core.helpers.strtools import to_bool # ============= local library imports ========================== class myDataLabel(DataLabel): show_label_coords = False marker_visible = False label_position = "center" border_visible = False class LabelsOverlay(AbstractOverlay): labels = List def overlay(self, other_component, gc, view_bounds=None, mode="normal"): with gc: gc.set_font(str_to_font(None, None, "7")) for x, y, l in self.labels: ll = Label(x=x, y=y, text=l, font="modern 7") w, h = ll.get_bounding_box(gc) x, y = other_component.map_screen([(x, y)])[0] gc.set_text_position(x - w / 2.0, y + 5) gc.show_text(l) class RotatingContainer(OverlayPlotContainer): rotation = Float(0) def _draw(self, gc, *args, **kw): with gc: w2 = self.width / 2 h2 = self.height / 2 # gc.translate_ctm(w2, h2) # gc.rotate_ctm(math.radians(self.rotation)) # gc.translate_ctm(-w2, -h2) super(RotatingContainer, self)._draw(gc, *args, **kw) class GraphicGeneratorController(Controller): def save(self, info): self.model.save() def traits_view(self): w, h = 750, 750 v = View( UItem("srcpath"), # Item('rotation'), UItem("container", editor=ComponentEditor(), style="custom"), width=w + 2, height=h + 56, resizable=True, buttons=[Action(name="Save", action="save"), "OK", "Cancel"], ) return v class GraphicModel(HasTraits): srcpath = File xmlpath = File container = Instance(OverlayPlotContainer) name = Property _name = Str rotation = Float(enter_set=True, auto_set=False) initialized = False def _get_name(self): return os.path.splitext( self._name if self._name else os.path.basename(self.srcpath) )[0] def save(self, path=None): # print self.container.bounds if path is None: dlg = FileDialog(action="save as", default_directory=paths.data_dir or "") if dlg.open() == OK: path = dlg.path if path is not None: _, tail = os.path.splitext(path) c = self.container if tail == ".pdf": from chaco.pdf_graphics_context import PdfPlotGraphicsContext gc = PdfPlotGraphicsContext(filename=path, pagesize="letter") else: if not tail in (".png", ".jpg", ".tiff"): path = "{}.png".format(path) gc = PlotGraphicsContext((int(c.outer_width), int(c.outer_height))) # c.use_backbuffer = False # for ci in c.components: # try: # ci.x_axis.visible = False # ci.y_axis.visible = False # except Exception: # pass # c.use_backbuffer = False from reportlab.lib.pagesizes import LETTER c.do_layout(size=(LETTER[1], LETTER[1]), force=True) gc.render_component(c) # c.use_backbuffer = True gc.save(path) self._name = os.path.basename(path) def load(self, path): parser = ElementTree(file=open(path, "r")) circles = parser.find("circles") outline = parser.find("outline") bb = outline.find("bounding_box") bs = bb.find("width"), bb.find("height") w, h = [float(b.text) for b in bs] use_label = parser.find("use_label") if use_label is not None: use_label = to_bool(use_label.text.strip()) else: use_label = True data = ArrayPlotData() p = Plot(data=data, padding=10)<|fim▁hole|> p.y_axis.visible = False p.x_axis.title = "X cm" p.y_axis.title = "Y cm" p.index_range.low_setting = -w / 2 p.index_range.high_setting = w / 2 p.value_range.low_setting = -h / 2 p.value_range.high_setting = h / 2 thetas = linspace(0, 2 * pi) radius = circles.find("radius").text radius = float(radius) face_color = circles.find("face_color") if face_color is not None: face_color = face_color.text else: face_color = "white" labels = [] for i, pp in enumerate(circles.findall("point")): x, y, l = pp.find("x").text, pp.find("y").text, pp.find("label").text # print i, pp, x, y # load hole specific attrs r = pp.find("radius") if r is None: r = radius else: r = float(r.text) fc = pp.find("face_color") if fc is None: fc = face_color else: fc = fc.text x, y = list(map(float, (x, y))) xs = x + r * sin(thetas) ys = y + r * cos(thetas) xn, yn = "px{:03d}".format(i), "py{:03d}".format(i) data.set_data(xn, xs) data.set_data(yn, ys) plot = p.plot((xn, yn), face_color=fc, type="polygon")[0] labels.append((x, y, l)) # if use_label: # label = myDataLabel(component=plot, # data_point=(x, y), # label_text=l, # bgcolor='transparent') # plot.overlays.append(label) if use_label: p.overlays.append(LabelsOverlay(component=plot, labels=labels)) self.container.add(p) self.container.invalidate_and_redraw() def _srcpath_changed(self): # default_radius=radius, # default_bounds=bounds, # convert_mm=convert_mm, # use_label=use_label, # make=make, # rotate=rotate) self._reload() def _rotation_changed(self): self._reload() def _reload(self): if self.initialized: self.container = self._container_factory() print(os.path.isfile(self.srcpath), self.srcpath) if os.path.isfile(self.srcpath): p = make_xml( self.srcpath, default_bounds=(2.54, 2.54), default_radius=0.0175 * 2.54, rotate=self.rotation, convert_mm=True, ) self.load(p) def _container_default(self): return self._container_factory() def _container_factory(self): return RotatingContainer(bgcolor="white") def make_xml( path, offset=100, default_bounds=(50, 50), default_radius=3.0, convert_mm=False, make=True, use_label=True, rotate=0, ): """ convert a csv into an xml use blank line as a group marker circle labels are offset by ``offset*group_id`` ie. group 0. 1,2,3 group 1. 101,102,103 """ out = "{}_from_csv.xml".format(os.path.splitext(path)[0]) if not make: return out root = Element("root") ul = Element("use_label") ul.text = "True" if use_label else "False" root.append(ul) outline = Element("outline") bb = Element("bounding_box") width, height = Element("width"), Element("height") width.text, height.text = list(map(str, default_bounds)) bb.append(width) bb.append(height) outline.append(bb) root.append(outline) circles = Element("circles") radius = Element("radius") radius.text = str(default_radius) circles.append(radius) face_color = Element("face_color") face_color.text = "white" circles.append(face_color) root.append(circles) i = 0 off = 0 reader = csv.reader(open(path, "r"), delimiter=",") # writer = open(path + 'angles.txt', 'w') nwriter = None if rotate: nwriter = csv.writer(open(path + "rotated_{}.txt".format(rotate), "w")) header = next(reader) if nwriter: nwriter.writerow(header) theta = math.radians(rotate) for k, row in enumerate(reader): # print k, row row = list(map(str.strip, row)) if row: e = Element("point") x, y, l = Element("x"), Element("y"), Element("label") xx, yy = float(row[1]), float(row[2]) try: r = float(row[4]) rr = Element("radius") if convert_mm: r *= 2.54 rr.text = str(r) e.append(rr) except IndexError: r = None px = math.cos(theta) * xx - math.sin(theta) * yy py = math.sin(theta) * xx + math.cos(theta) * yy xx, yy = px, py if nwriter: data = ["{:0.4f}".format(xx), "{:0.4f}".format(yy)] if r is not None: data.append("{:0.4f}".format(r)) nwriter.writerow(data) if convert_mm: xx = xx * 2.54 yy = yy * 2.54 xx *= 1.1 yy *= 1.1 x.text = str(xx) y.text = str(yy) # a = math.degrees(math.atan2(yy, xx)) # writer.write('{} {}\n'.format(k + 1, a)) l.text = str(i + 1 + off) e.append(l) e.append(x) e.append(y) circles.append(e) i += 1 else: # use blank rows as group markers off += offset i = 0 tree = ElementTree(root) tree.write(out, xml_declaration=True, method="xml", pretty_print=True) return out def open_txt( p, bounds, radius, use_label=True, convert_mm=False, make=True, rotate=None ): gm = GraphicModel(srcpath=p, rotation=rotate or 0) p = make_xml( p, offset=0, default_radius=radius, default_bounds=bounds, convert_mm=convert_mm, use_label=use_label, make=make, rotate=rotate, ) # p = '/Users/ross/Sandbox/graphic_gen_from_csv.xml' gm.load(p) gm.initialized = True gcc = GraphicGeneratorController(model=gm) return gcc, gm if __name__ == "__main__": gm = GraphicModel() # p = '/Users/ross/Sandbox/2mmirrad.txt' # p = '/Users/ross/Sandbox/2mmirrad_ordered.txt' # p = '/Users/ross/Sandbox/1_75mmirrad_ordered.txt' # p = '/Users/ross/Sandbox/1_75mmirrad_ordered.txt' # p = '/Users/ross/Pychrondata_diode/setupfiles/irradiation_tray_maps/0_75mmirrad_ordered1.txt' # p = '/Users/ross/Sandbox/1_75mmirrad.txt' p = "/Users/ross/Pychrondata_dev/setupfiles/irradiation_tray_maps/construction/newtrays/1_75mmirrad_continuous.txt" # p = '/Users/ross/Pychrondata_diode/setupfiles/irradiation_tray_maps/0_75mmirrad.txt' # p = '/Users/ross/Pychrondata_diode/setupfiles/irradiation_tray_maps/0_75mmirrad_continuous.txt' # p = '/Users/ross/Pychrondata_dev/setupfiles/irradiation_tray_maps/newtrays/2mmirrad_continuous.txt' # p = '/Users/ross/Pychrondata_dev/setupfiles/irradiation_tray_maps/newtrays/40_no_spokes.txt' # p = '/Users/ross/Pychrondata_dev/setupfiles/irradiation_tray_maps/newtrays/26_spokes.txt' # p = '/Users/ross/Pychrondata_dev/setupfiles/irradiation_tray_maps/newtrays/26_no_spokes.txt' # p = '/Users/ross/Pychrondata_dev/setupfiles/irradiation_tray_maps/construction/newtrays/40_spokes.txt' # p = '/Users/ross/Desktop/72_spokes' # p = '/Users/ross/Pychrondata_dev/setupfiles/irradiation_tray_maps/construction/newtrays/16_40_ms.txt' # p = '/Users/ross/Pychrondata_dev/setupfiles/irradiation_tray_maps/construction/newtrays/40_spokes_rev2.txt' # p = '/Users/ross/Pychrondata_dev/setupfiles/irradiation_tray_maps/construction/newtrays/40_spokes-5.txt' p = "/Users/ross/Pychrondata_dev/setupfiles/irradiation_tray_maps/construction/newtrays/24_spokes.txt" p = "/Users/ross/PychronDev/data/o2inch.txt" p = "/Users/ross/PychronDev/data/421.txt" gcc, gm = open_txt(p, (51, 51), 0.95, convert_mm=False, make=True, rotate=0) # p2 = '/Users/ross/Pychrondata_diode/setupfiles/irradiation_tray_maps/newtrays/TX_6-Hole.txt' # gcc, gm2 = open_txt(p2, (2.54, 2.54), .1, make=False) # p2 = '/Users/ross/Pychrondata_diode/setupfiles/irradiation_tray_maps/newtrays/TX_20-Hole.txt' # gcc, gm2 = open_txt(p2, (2.54, 2.54), .1, make=False) # gm2.container.bgcolor = 'transparent' # gm2.container.add(gm.container) gcc.configure_traits() # ============= EOF =============================================<|fim▁end|>
p.x_grid.visible = False p.y_grid.visible = False p.x_axis.visible = False
<|file_name|>string.js<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
version https://git-lfs.github.com/spec/v1 oid sha256:e7cf7648766782e7940410a3abb8126a98b94e57bd61bfc7c1523679e8ce7ed6 size 26807
<|file_name|>tree_graph.js<|end_file_name|><|fim▁begin|>function transformPath(decisionPath) { var path = [] for (var i=1; i<decisionPath.length; i++) { var node = { feature: decisionPath[i-1].feature, side: decisionPath[i].side == 'left' ? "<=" : ">", threshold: decisionPath[i-1].threshold.toPrecision(5), featureIdx: decisionPath[i-1].featureIdx, level: i } //copy all properties of decisionPath[i] to node if they won't overide a property for (var attrname in decisionPath[i]) { if (node[attrname] == null) node[attrname] = decisionPath[i][attrname]; } path.push(node) } return path; } var tip_features = { feature: function(d) { return 'Feature: ' + d.feature },<|fim▁hole|>}<|fim▁end|>
count: function(d) { return d.count + ' samples' }, dataPercentage: function(d) { return d.dataPercentage + '% of the data'}, impurity: function(d) { return 'Impurity: ' + d.impurity}
<|file_name|>crx_downloader_factory.cc<|end_file_name|><|fim▁begin|>// Copyright 2020 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 "components/update_client/crx_downloader_factory.h" #include "build/build_config.h" #if defined(OS_WIN) #include "components/update_client/background_downloader_win.h" #endif #include "components/update_client/crx_downloader.h" #include "components/update_client/network.h" #include "components/update_client/url_fetcher_downloader.h" namespace update_client { namespace { class CrxDownloaderFactoryChromium : public CrxDownloaderFactory {<|fim▁hole|> // Overrides for CrxDownloaderFactory. scoped_refptr<CrxDownloader> MakeCrxDownloader( bool background_download_enabled) const override; private: ~CrxDownloaderFactoryChromium() override = default; scoped_refptr<NetworkFetcherFactory> network_fetcher_factory_; }; scoped_refptr<CrxDownloader> CrxDownloaderFactoryChromium::MakeCrxDownloader( bool background_download_enabled) const { scoped_refptr<CrxDownloader> url_fetcher_downloader = base::MakeRefCounted<UrlFetcherDownloader>(nullptr, network_fetcher_factory_); #if defined(OS_WIN) // If background downloads are allowed, then apply the BITS service // background downloader first. if (background_download_enabled) { return base::MakeRefCounted<BackgroundDownloader>(url_fetcher_downloader); } #endif return url_fetcher_downloader; } } // namespace scoped_refptr<CrxDownloaderFactory> MakeCrxDownloaderFactory( scoped_refptr<NetworkFetcherFactory> network_fetcher_factory) { return base::MakeRefCounted<CrxDownloaderFactoryChromium>( network_fetcher_factory); } } // namespace update_client<|fim▁end|>
public: explicit CrxDownloaderFactoryChromium( scoped_refptr<NetworkFetcherFactory> network_fetcher_factory) : network_fetcher_factory_(network_fetcher_factory) {}
<|file_name|>test_basic.py<|end_file_name|><|fim▁begin|># coding: pyxl import unittest2 from pyxl import html from pyxl.base import PyxlException, x_base from pyxl.element import x_element class PyxlTests(unittest2.TestCase): def test_basics(self): self.assertEqual(<div />.to_string(), '<div></div>') self.assertEqual(<img src="blah" />.to_string(), '<img src="blah" />') self.assertEqual(<div class="c"></div>.to_string(), '<div class="c"></div>') self.assertEqual(<div><span></span></div>.to_string(), '<div><span></span></div>') self.assertEqual(<frag><span /><span /></frag>.to_string(), '<span></span><span></span>') def test_escaping(self): self.assertEqual(<div class="&">&{'&'}</div>.to_string(), '<div class="&amp;">&&amp;</div>') self.assertEqual(<div>{html.rawhtml('&')}</div>.to_string(), '<div>&</div>') def test_comments(self): pyxl = ( <div class="blah" # attr comment > # comment1 <!-- comment2 --> text# comment3<|fim▁hole|> def test_cond_comment(self): s = 'blahblah' self.assertEqual( <cond_comment cond="lt IE 8"><div class=">">{s}</div></cond_comment>.to_string(), '<!--[if lt IE 8]><div class="&gt;">blahblah</div><![endif]-->') self.assertEqual( <cond_comment cond="(lt IE 8) & (gt IE 5)"><div>{s}</div></cond_comment>.to_string(), '<!--[if (lt IE 8) & (gt IE 5)]><div>blahblah</div><![endif]-->') def test_decl(self): self.assertEqual( <script><![CDATA[<div><div>]]></script>.to_string(), '<script><![CDATA[<div><div>]]></script>') def test_form_error(self): self.assertEqual( <form_error name="foo" />.to_string(), '<form:error name="foo" />') def test_enum_attrs(self): class x_foo(x_base): __attrs__ = { 'value': ['a', 'b'], } def _to_list(self, l): pass self.assertEqual(<foo />.attr('value'), 'a') self.assertEqual(<foo />.value, 'a') self.assertEqual(<foo value="b" />.attr('value'), 'b') self.assertEqual(<foo value="b" />.value, 'b') with self.assertRaises(PyxlException): <foo value="c" /> class x_bar(x_base): __attrs__ = { 'value': ['a', None, 'b'], } def _to_list(self, l): pass with self.assertRaises(PyxlException): <bar />.attr('value') with self.assertRaises(PyxlException): <bar />.value class x_baz(x_base): __attrs__ = { 'value': [None, 'a', 'b'], } def _to_list(self, l): pass self.assertEqual(<baz />.value, None) def test_render_args_are_added_to_pyxl_attributes(self): class x_foo(x_element): def render(self, value: int): return <span>{value}</span> self.assertEqual(<foo />.value, None) self.assertEqual(<foo value="10" />.value, 10) with self.assertRaises(PyxlException): <foo value="boo" />.value self.assertEqual(<foo value="11" />.to_string(), '<span>11</span>') def test_render_arg_supports_enum(self): class x_foo(x_element): def render(self, value: ['a', 'b']): return <span>{value}</span> self.assertEqual(<foo />.value, 'a') self.assertEqual(<foo value="b" />.value, 'b') with self.assertRaises(PyxlException): <foo value="c" />.value def test_render_arg_without_annotation(self): class x_foo(x_element): def render(self, value): return <span>{value}</span> self.assertEqual(<foo />.to_string(), '<span></span>') self.assertEqual(<foo value="123" />.to_string(), '<span>123</span>') self.assertEqual(<foo value="boo" />.to_string(), '<span>boo</span>') def test_underscore_in_render_arg(self): class x_foo(x_element): def render(self, a_b_c: int): return <span>{a_b_c}</span> self.assertEqual(<foo a_b_c="1" />.to_string(), '<span>1</span>') def test_attr_collision(self): with self.assertRaises(PyxlException): class x_foo(x_element): __attrs__ = { 'laughing': object } def render(self, laughing): pass def test_validate_attrs(self): class x_foo(x_element): __validate_attrs__ = False def render(self): return <span>{self.anything}</span> self.assertEqual(<foo anything="yep" />.to_string(), '<span>yep</span>') class x_bar(x_element): __validate_attrs__ = True def render(self): return <span>{self.anything}</span> with self.assertRaises(PyxlException): <bar anything="nope" /> class x_baz(x_element): def render(self): return <span>{self.anything}</span> with self.assertRaises(PyxlException): <baz anything="nope" /> if __name__ == '__main__': unittest2.main()<|fim▁end|>
# comment4 </div>) self.assertEqual(pyxl.to_string(), '<div class="blah">text</div>')
<|file_name|>s.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import socket<|fim▁hole|> TCP_IP = '127.0.0.1' TCP_PORT = 5005 BUFFER_SIZE = 20 # Normally 1024, but we want fast response s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((TCP_IP, TCP_PORT)) s.listen(1) conn, addr = s.accept() print 'Connection address:', addr while 1: data = conn.recv(BUFFER_SIZE) if not data: break print "received data:", data conn.send(data) # echo conn.close()<|fim▁end|>
<|file_name|>test_xmlutil.py<|end_file_name|><|fim▁begin|># vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack 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. from lxml import etree from xml.dom import minidom from nova.api.openstack import xmlutil from nova import exception from nova import test from nova.tests import utils as tests_utils class SelectorTest(test.TestCase): obj_for_test = { 'test': { 'name': 'test', 'values': [1, 2, 3], 'attrs': { 'foo': 1, 'bar': 2, 'baz': 3, }, }, } def test_empty_selector(self): sel = xmlutil.Selector() self.assertEqual(len(sel.chain), 0) self.assertEqual(sel(self.obj_for_test), self.obj_for_test) def test_dict_selector(self): sel = xmlutil.Selector('test') self.assertEqual(len(sel.chain), 1) self.assertEqual(sel.chain[0], 'test') self.assertEqual(sel(self.obj_for_test), self.obj_for_test['test']) def test_datum_selector(self): sel = xmlutil.Selector('test', 'name') self.assertEqual(len(sel.chain), 2) self.assertEqual(sel.chain[0], 'test') self.assertEqual(sel.chain[1], 'name') self.assertEqual(sel(self.obj_for_test), 'test') def test_list_selector(self): sel = xmlutil.Selector('test', 'values', 0) self.assertEqual(len(sel.chain), 3) self.assertEqual(sel.chain[0], 'test') self.assertEqual(sel.chain[1], 'values') self.assertEqual(sel.chain[2], 0) self.assertEqual(sel(self.obj_for_test), 1) def test_items_selector(self): sel = xmlutil.Selector('test', 'attrs', xmlutil.get_items) self.assertEqual(len(sel.chain), 3) self.assertEqual(sel.chain[2], xmlutil.get_items) for key, val in sel(self.obj_for_test): self.assertEqual(self.obj_for_test['test']['attrs'][key], val) def test_missing_key_selector(self): sel = xmlutil.Selector('test2', 'attrs') self.assertEqual(sel(self.obj_for_test), None) self.assertRaises(KeyError, sel, self.obj_for_test, True) def test_constant_selector(self): sel = xmlutil.ConstantSelector('Foobar') self.assertEqual(sel.value, 'Foobar') self.assertEqual(sel(self.obj_for_test), 'Foobar') class TemplateElementTest(test.TestCase): def test_element_initial_attributes(self): # Create a template element with some attributes elem = xmlutil.TemplateElement('test', attrib=dict(a=1, b=2, c=3), c=4, d=5, e=6) # Verify all the attributes are as expected expected = dict(a=1, b=2, c=4, d=5, e=6) for k, v in expected.items(): self.assertEqual(elem.attrib[k].chain[0], v) def test_element_get_attributes(self): expected = dict(a=1, b=2, c=3) # Create a template element with some attributes elem = xmlutil.TemplateElement('test', attrib=expected) # Verify that get() retrieves the attributes for k, v in expected.items(): self.assertEqual(elem.get(k).chain[0], v) def test_element_set_attributes(self): attrs = dict(a=None, b='foo', c=xmlutil.Selector('foo', 'bar')) # Create a bare template element with no attributes elem = xmlutil.TemplateElement('test') # Set the attribute values for k, v in attrs.items(): elem.set(k, v) # Now verify what got set self.assertEqual(len(elem.attrib['a'].chain), 1) self.assertEqual(elem.attrib['a'].chain[0], 'a') self.assertEqual(len(elem.attrib['b'].chain), 1) self.assertEqual(elem.attrib['b'].chain[0], 'foo') self.assertEqual(elem.attrib['c'], attrs['c']) def test_element_attribute_keys(self): attrs = dict(a=1, b=2, c=3, d=4) expected = set(attrs.keys()) # Create a template element with some attributes elem = xmlutil.TemplateElement('test', attrib=attrs) # Now verify keys self.assertEqual(set(elem.keys()), expected) def test_element_attribute_items(self): expected = dict(a=xmlutil.Selector(1), b=xmlutil.Selector(2), c=xmlutil.Selector(3)) keys = set(expected.keys()) # Create a template element with some attributes elem = xmlutil.TemplateElement('test', attrib=expected) # Now verify items for k, v in elem.items(): self.assertEqual(expected[k], v) keys.remove(k) # Did we visit all keys? self.assertEqual(len(keys), 0) def test_element_selector_none(self): # Create a template element with no selector elem = xmlutil.TemplateElement('test') self.assertEqual(len(elem.selector.chain), 0) def test_element_selector_string(self): # Create a template element with a string selector elem = xmlutil.TemplateElement('test', selector='test') self.assertEqual(len(elem.selector.chain), 1) self.assertEqual(elem.selector.chain[0], 'test') def test_element_selector(self): sel = xmlutil.Selector('a', 'b') # Create a template element with an explicit selector elem = xmlutil.TemplateElement('test', selector=sel) self.assertEqual(elem.selector, sel) def test_element_subselector_none(self): # Create a template element with no subselector elem = xmlutil.TemplateElement('test') self.assertEqual(elem.subselector, None) def test_element_subselector_string(self): # Create a template element with a string subselector elem = xmlutil.TemplateElement('test', subselector='test') self.assertEqual(len(elem.subselector.chain), 1) self.assertEqual(elem.subselector.chain[0], 'test') def test_element_subselector(self): sel = xmlutil.Selector('a', 'b') # Create a template element with an explicit subselector elem = xmlutil.TemplateElement('test', subselector=sel) self.assertEqual(elem.subselector, sel) def test_element_append_child(self): # Create an element elem = xmlutil.TemplateElement('test') # Make sure the element starts off empty self.assertEqual(len(elem), 0) # Create a child element child = xmlutil.TemplateElement('child') # Append the child to the parent elem.append(child) # Verify that the child was added self.assertEqual(len(elem), 1) self.assertEqual(elem[0], child) self.assertEqual('child' in elem, True) self.assertEqual(elem['child'], child) # Ensure that multiple children of the same name are rejected child2 = xmlutil.TemplateElement('child') self.assertRaises(KeyError, elem.append, child2) def test_element_extend_children(self): # Create an element elem = xmlutil.TemplateElement('test') # Make sure the element starts off empty self.assertEqual(len(elem), 0) # Create a few children children = [ xmlutil.TemplateElement('child1'), xmlutil.TemplateElement('child2'), xmlutil.TemplateElement('child3'), ] # Extend the parent by those children elem.extend(children) # Verify that the children were added self.assertEqual(len(elem), 3) for idx in range(len(elem)): self.assertEqual(children[idx], elem[idx]) self.assertEqual(children[idx].tag in elem, True) self.assertEqual(elem[children[idx].tag], children[idx]) # Ensure that multiple children of the same name are rejected children2 = [ xmlutil.TemplateElement('child4'), xmlutil.TemplateElement('child1'), ] self.assertRaises(KeyError, elem.extend, children2) # Also ensure that child4 was not added self.assertEqual(len(elem), 3) self.assertEqual(elem[-1].tag, 'child3') def test_element_insert_child(self): # Create an element elem = xmlutil.TemplateElement('test') # Make sure the element starts off empty self.assertEqual(len(elem), 0) # Create a few children children = [ xmlutil.TemplateElement('child1'), xmlutil.TemplateElement('child2'), xmlutil.TemplateElement('child3'), ] # Extend the parent by those children elem.extend(children) # Create a child to insert child = xmlutil.TemplateElement('child4') # Insert it elem.insert(1, child) # Ensure the child was inserted in the right place self.assertEqual(len(elem), 4) children.insert(1, child) for idx in range(len(elem)): self.assertEqual(children[idx], elem[idx]) self.assertEqual(children[idx].tag in elem, True) self.assertEqual(elem[children[idx].tag], children[idx]) # Ensure that multiple children of the same name are rejected child2 = xmlutil.TemplateElement('child2') self.assertRaises(KeyError, elem.insert, 2, child2) def test_element_remove_child(self): # Create an element elem = xmlutil.TemplateElement('test') # Make sure the element starts off empty self.assertEqual(len(elem), 0) # Create a few children children = [ xmlutil.TemplateElement('child1'), xmlutil.TemplateElement('child2'), xmlutil.TemplateElement('child3'), ] # Extend the parent by those children elem.extend(children) # Create a test child to remove child = xmlutil.TemplateElement('child2') # Try to remove it self.assertRaises(ValueError, elem.remove, child) # Ensure that no child was removed self.assertEqual(len(elem), 3) # Now remove a legitimate child elem.remove(children[1])<|fim▁hole|> # Ensure that the child was removed self.assertEqual(len(elem), 2) self.assertEqual(elem[0], children[0]) self.assertEqual(elem[1], children[2]) self.assertEqual('child2' in elem, False) # Ensure the child cannot be retrieved by name def get_key(elem, key): return elem[key] self.assertRaises(KeyError, get_key, elem, 'child2') def test_element_text(self): # Create an element elem = xmlutil.TemplateElement('test') # Ensure that it has no text self.assertEqual(elem.text, None) # Try setting it to a string and ensure it becomes a selector elem.text = 'test' self.assertEqual(hasattr(elem.text, 'chain'), True) self.assertEqual(len(elem.text.chain), 1) self.assertEqual(elem.text.chain[0], 'test') # Try resetting the text to None elem.text = None self.assertEqual(elem.text, None) # Now make up a selector and try setting the text to that sel = xmlutil.Selector() elem.text = sel self.assertEqual(elem.text, sel) # Finally, try deleting the text and see what happens del elem.text self.assertEqual(elem.text, None) def test_apply_attrs(self): # Create a template element attrs = dict(attr1=xmlutil.ConstantSelector(1), attr2=xmlutil.ConstantSelector(2)) tmpl_elem = xmlutil.TemplateElement('test', attrib=attrs) # Create an etree element elem = etree.Element('test') # Apply the template to the element tmpl_elem.apply(elem, None) # Now, verify the correct attributes were set for k, v in elem.items(): self.assertEqual(str(attrs[k].value), v) def test_apply_text(self): # Create a template element tmpl_elem = xmlutil.TemplateElement('test') tmpl_elem.text = xmlutil.ConstantSelector(1) # Create an etree element elem = etree.Element('test') # Apply the template to the element tmpl_elem.apply(elem, None) # Now, verify the text was set self.assertEqual(str(tmpl_elem.text.value), elem.text) def test__render(self): attrs = dict(attr1=xmlutil.ConstantSelector(1), attr2=xmlutil.ConstantSelector(2), attr3=xmlutil.ConstantSelector(3)) # Create a master template element master_elem = xmlutil.TemplateElement('test', attr1=attrs['attr1']) # Create a couple of slave template element slave_elems = [ xmlutil.TemplateElement('test', attr2=attrs['attr2']), xmlutil.TemplateElement('test', attr3=attrs['attr3']), ] # Try the render elem = master_elem._render(None, None, slave_elems, None) # Verify the particulars of the render self.assertEqual(elem.tag, 'test') self.assertEqual(len(elem.nsmap), 0) for k, v in elem.items(): self.assertEqual(str(attrs[k].value), v) # Create a parent for the element to be rendered parent = etree.Element('parent') # Try the render again... elem = master_elem._render(parent, None, slave_elems, dict(a='foo')) # Verify the particulars of the render self.assertEqual(len(parent), 1) self.assertEqual(parent[0], elem) self.assertEqual(len(elem.nsmap), 1) self.assertEqual(elem.nsmap['a'], 'foo') def test_render(self): # Create a template element tmpl_elem = xmlutil.TemplateElement('test') tmpl_elem.text = xmlutil.Selector() # Create the object we're going to render obj = ['elem1', 'elem2', 'elem3', 'elem4'] # Try a render with no object elems = tmpl_elem.render(None, None) self.assertEqual(len(elems), 0) # Try a render with one object elems = tmpl_elem.render(None, 'foo') self.assertEqual(len(elems), 1) self.assertEqual(elems[0][0].text, 'foo') self.assertEqual(elems[0][1], 'foo') # Now, try rendering an object with multiple entries parent = etree.Element('parent') elems = tmpl_elem.render(parent, obj) self.assertEqual(len(elems), 4) # Check the results for idx in range(len(obj)): self.assertEqual(elems[idx][0].text, obj[idx]) self.assertEqual(elems[idx][1], obj[idx]) def test_subelement(self): # Try the SubTemplateElement constructor parent = xmlutil.SubTemplateElement(None, 'parent') self.assertEqual(parent.tag, 'parent') self.assertEqual(len(parent), 0) # Now try it with a parent element child = xmlutil.SubTemplateElement(parent, 'child') self.assertEqual(child.tag, 'child') self.assertEqual(len(parent), 1) self.assertEqual(parent[0], child) def test_wrap(self): # These are strange methods, but they make things easier elem = xmlutil.TemplateElement('test') self.assertEqual(elem.unwrap(), elem) self.assertEqual(elem.wrap().root, elem) def test_dyntag(self): obj = ['a', 'b', 'c'] # Create a template element with a dynamic tag tmpl_elem = xmlutil.TemplateElement(xmlutil.Selector()) # Try the render parent = etree.Element('parent') elems = tmpl_elem.render(parent, obj) # Verify the particulars of the render self.assertEqual(len(elems), len(obj)) for idx in range(len(obj)): self.assertEqual(elems[idx][0].tag, obj[idx]) class TemplateTest(test.TestCase): def test_wrap(self): # These are strange methods, but they make things easier elem = xmlutil.TemplateElement('test') tmpl = xmlutil.Template(elem) self.assertEqual(tmpl.unwrap(), elem) self.assertEqual(tmpl.wrap(), tmpl) def test__siblings(self): # Set up a basic template elem = xmlutil.TemplateElement('test') tmpl = xmlutil.Template(elem) # Check that we get the right siblings siblings = tmpl._siblings() self.assertEqual(len(siblings), 1) self.assertEqual(siblings[0], elem) def test__nsmap(self): # Set up a basic template elem = xmlutil.TemplateElement('test') tmpl = xmlutil.Template(elem, nsmap=dict(a="foo")) # Check out that we get the right namespace dictionary nsmap = tmpl._nsmap() self.assertNotEqual(id(nsmap), id(tmpl.nsmap)) self.assertEqual(len(nsmap), 1) self.assertEqual(nsmap['a'], 'foo') def test_master_attach(self): # Set up a master template elem = xmlutil.TemplateElement('test') tmpl = xmlutil.MasterTemplate(elem, 1) # Make sure it has a root but no slaves self.assertEqual(tmpl.root, elem) self.assertEqual(len(tmpl.slaves), 0) # Try to attach an invalid slave bad_elem = xmlutil.TemplateElement('test2') self.assertRaises(ValueError, tmpl.attach, bad_elem) self.assertEqual(len(tmpl.slaves), 0) # Try to attach an invalid and a valid slave good_elem = xmlutil.TemplateElement('test') self.assertRaises(ValueError, tmpl.attach, good_elem, bad_elem) self.assertEqual(len(tmpl.slaves), 0) # Try to attach an inapplicable template class InapplicableTemplate(xmlutil.Template): def apply(self, master): return False inapp_tmpl = InapplicableTemplate(good_elem) tmpl.attach(inapp_tmpl) self.assertEqual(len(tmpl.slaves), 0) # Now try attaching an applicable template tmpl.attach(good_elem) self.assertEqual(len(tmpl.slaves), 1) self.assertEqual(tmpl.slaves[0].root, good_elem) def test_master_copy(self): # Construct a master template elem = xmlutil.TemplateElement('test') tmpl = xmlutil.MasterTemplate(elem, 1, nsmap=dict(a='foo')) # Give it a slave slave = xmlutil.TemplateElement('test') tmpl.attach(slave) # Construct a copy copy = tmpl.copy() # Check to see if we actually managed a copy self.assertNotEqual(tmpl, copy) self.assertEqual(tmpl.root, copy.root) self.assertEqual(tmpl.version, copy.version) self.assertEqual(id(tmpl.nsmap), id(copy.nsmap)) self.assertNotEqual(id(tmpl.slaves), id(copy.slaves)) self.assertEqual(len(tmpl.slaves), len(copy.slaves)) self.assertEqual(tmpl.slaves[0], copy.slaves[0]) def test_slave_apply(self): # Construct a master template elem = xmlutil.TemplateElement('test') master = xmlutil.MasterTemplate(elem, 3) # Construct a slave template with applicable minimum version slave = xmlutil.SlaveTemplate(elem, 2) self.assertEqual(slave.apply(master), True) # Construct a slave template with equal minimum version slave = xmlutil.SlaveTemplate(elem, 3) self.assertEqual(slave.apply(master), True) # Construct a slave template with inapplicable minimum version slave = xmlutil.SlaveTemplate(elem, 4) self.assertEqual(slave.apply(master), False) # Construct a slave template with applicable version range slave = xmlutil.SlaveTemplate(elem, 2, 4) self.assertEqual(slave.apply(master), True) # Construct a slave template with low version range slave = xmlutil.SlaveTemplate(elem, 1, 2) self.assertEqual(slave.apply(master), False) # Construct a slave template with high version range slave = xmlutil.SlaveTemplate(elem, 4, 5) self.assertEqual(slave.apply(master), False) # Construct a slave template with matching version range slave = xmlutil.SlaveTemplate(elem, 3, 3) self.assertEqual(slave.apply(master), True) def test__serialize(self): # Our test object to serialize obj = { 'test': { 'name': 'foobar', 'values': [1, 2, 3, 4], 'attrs': { 'a': 1, 'b': 2, 'c': 3, 'd': 4, }, 'image': { 'name': 'image_foobar', 'id': 42, }, }, } # Set up our master template root = xmlutil.TemplateElement('test', selector='test', name='name') value = xmlutil.SubTemplateElement(root, 'value', selector='values') value.text = xmlutil.Selector() attrs = xmlutil.SubTemplateElement(root, 'attrs', selector='attrs') xmlutil.SubTemplateElement(attrs, 'attr', selector=xmlutil.get_items, key=0, value=1) master = xmlutil.MasterTemplate(root, 1, nsmap=dict(f='foo')) # Set up our slave template root_slave = xmlutil.TemplateElement('test', selector='test') image = xmlutil.SubTemplateElement(root_slave, 'image', selector='image', id='id') image.text = xmlutil.Selector('name') slave = xmlutil.SlaveTemplate(root_slave, 1, nsmap=dict(b='bar')) # Attach the slave to the master... master.attach(slave) # Try serializing our object siblings = master._siblings() nsmap = master._nsmap() result = master._serialize(None, obj, siblings, nsmap) # Now we get to manually walk the element tree... self.assertEqual(result.tag, 'test') self.assertEqual(len(result.nsmap), 2) self.assertEqual(result.nsmap['f'], 'foo') self.assertEqual(result.nsmap['b'], 'bar') self.assertEqual(result.get('name'), obj['test']['name']) for idx, val in enumerate(obj['test']['values']): self.assertEqual(result[idx].tag, 'value') self.assertEqual(result[idx].text, str(val)) idx += 1 self.assertEqual(result[idx].tag, 'attrs') for attr in result[idx]: self.assertEqual(attr.tag, 'attr') self.assertEqual(attr.get('value'), str(obj['test']['attrs'][attr.get('key')])) idx += 1 self.assertEqual(result[idx].tag, 'image') self.assertEqual(result[idx].get('id'), str(obj['test']['image']['id'])) self.assertEqual(result[idx].text, obj['test']['image']['name']) class MasterTemplateBuilder(xmlutil.TemplateBuilder): def construct(self): elem = xmlutil.TemplateElement('test') return xmlutil.MasterTemplate(elem, 1) class SlaveTemplateBuilder(xmlutil.TemplateBuilder): def construct(self): elem = xmlutil.TemplateElement('test') return xmlutil.SlaveTemplate(elem, 1) class TemplateBuilderTest(test.TestCase): def test_master_template_builder(self): # Make sure the template hasn't been built yet self.assertEqual(MasterTemplateBuilder._tmpl, None) # Now, construct the template tmpl1 = MasterTemplateBuilder() # Make sure that there is a template cached... self.assertNotEqual(MasterTemplateBuilder._tmpl, None) # Make sure it wasn't what was returned... self.assertNotEqual(MasterTemplateBuilder._tmpl, tmpl1) # Make sure it doesn't get rebuilt cached = MasterTemplateBuilder._tmpl tmpl2 = MasterTemplateBuilder() self.assertEqual(MasterTemplateBuilder._tmpl, cached) # Make sure we're always getting fresh copies self.assertNotEqual(tmpl1, tmpl2) # Make sure we can override the copying behavior tmpl3 = MasterTemplateBuilder(False) self.assertEqual(MasterTemplateBuilder._tmpl, tmpl3) def test_slave_template_builder(self): # Make sure the template hasn't been built yet self.assertEqual(SlaveTemplateBuilder._tmpl, None) # Now, construct the template tmpl1 = SlaveTemplateBuilder() # Make sure there is a template cached... self.assertNotEqual(SlaveTemplateBuilder._tmpl, None) # Make sure it was what was returned... self.assertEqual(SlaveTemplateBuilder._tmpl, tmpl1) # Make sure it doesn't get rebuilt tmpl2 = SlaveTemplateBuilder() self.assertEqual(SlaveTemplateBuilder._tmpl, tmpl1) # Make sure we're always getting the cached copy self.assertEqual(tmpl1, tmpl2) class MiscellaneousXMLUtilTests(test.TestCase): def test_make_flat_dict(self): expected_xml = ("<?xml version='1.0' encoding='UTF-8'?>\n" '<wrapper><a>foo</a><b>bar</b></wrapper>') root = xmlutil.make_flat_dict('wrapper') tmpl = xmlutil.MasterTemplate(root, 1) result = tmpl.serialize(dict(wrapper=dict(a='foo', b='bar'))) self.assertEqual(result, expected_xml) def test_safe_parse_xml(self): normal_body = (""" <?xml version="1.0" ?><foo> <bar> <v1>hey</v1> <v2>there</v2> </bar> </foo>""").strip() dom = xmlutil.safe_minidom_parse_string(normal_body) self.assertEqual(normal_body, str(dom.toxml())) self.assertRaises(exception.MalformedRequestBody, xmlutil.safe_minidom_parse_string, tests_utils.killer_xml_body()) class SafeParserTestCase(test.TestCase): def test_external_dtd(self): xml_string = ("""<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head/> <body>html with dtd</body> </html>""") parser = xmlutil.ProtectedExpatParser(forbid_dtd=False, forbid_entities=True) self.assertRaises(ValueError, minidom.parseString, xml_string, parser) def test_external_file(self): xml_string = """<!DOCTYPE external [ <!ENTITY ee SYSTEM "file:///PATH/TO/root.xml"> ]> <root>&ee;</root>""" parser = xmlutil.ProtectedExpatParser(forbid_dtd=False, forbid_entities=True) self.assertRaises(ValueError, minidom.parseString, xml_string, parser) def test_notation(self): xml_string = """<?xml version="1.0" standalone="no"?> <!-- comment data --> <!DOCTYPE x [ <!NOTATION notation SYSTEM "notation.jpeg"> ]> <root attr1="value1"> </root>""" parser = xmlutil.ProtectedExpatParser(forbid_dtd=False, forbid_entities=True) self.assertRaises(ValueError, minidom.parseString, xml_string, parser)<|fim▁end|>
<|file_name|>eGauge.py<|end_file_name|><|fim▁begin|># Copyright (c) 2013 eGauge Systems LLC # 4730 Walnut St, Suite 110 # Boulder, CO 80301 # voice: 720-545-9767 # email: [email protected] # # All rights reserved. # # MIT License # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # import sys, urllib2 from lxml import etree class error (Exception): pass class PushData: _tdesc = { "P": { "doc" : "Power", "units" : ["W", "Ws"], "scale" : 1, }, "S": { "doc" : "Apparent power", "units" : ["VA", "VAs"], "scale" : 1, }, "V": { "doc" : "Voltage", "units" : ["V", "Vs"], "scale" : 1e-3, }, "I": { "doc" : "Current", "units" : ["A", "As"], "scale" : 1e-3, }, "F": { "doc" : "Frequency", "units" : ["Hz", "Hzs"], "scale" : 1e-3, }, "THD": { "doc" : "Total Harmonic Distortion", "units" : ["%", "%s"], "scale" : 1e-3, }, "T": { "doc" : "Temperature", "units" : ["C", "Cs"], "scale" : 1e-3, }, "Q": { "doc" : "Mass flow-rate", "units" : ["g/s", "g"], "scale" : 1e-3, }, "v": { "doc" : "Speed", "units" : ["m/s", "m"], "scale" : 1e-3, }, "R": { "doc" : "Resistance", "units" : ["Ohm", "Ohm*s"], "scale" : 1, }, "Ee": { "doc" : "Irradiance", "units" : ["W/m^2", "W/m^2*s"], "scale" : 1, }, "PQ": { "doc" : "Reactive power", "units" : ["VAr", "VArh"], "scale" : 1, }, "$": { "doc" : "Money", "units" : ["$", "$s"], "scale" : 1, }, "a": { "doc" : "Angle", "units" : ["DEG", "DEGs"], "scale" : 1, }, "h": { "doc" : "Humidity", "units" : ["%", "%s"], "scale" : 1e-1, }, "Qv": { "doc" : "Volumetric flow-rate", "units" : ["m^3/s", "m^3"], "scale" : 1e-9, }, "Pa": { "doc" : "Pressure", "units" : ["Pa", "Pa*s"], "scale" : 1, } } <|fim▁hole|> def __init__ (self, xml_string): self.config_serial_number = None self.num_registers = 0 self.regname = [] self.regtype = [] self.ts = [] self.row = [] xml = etree.fromstring (xml_string) if xml.tag != 'group': raise error, ('Expected <group> as the top element') self.config_serial_number = int (xml.attrib['serial'], 0) for data in xml: ts = None delta = None if data.tag != 'data': raise error, ('Expected <data> elements within <group>') if 'columns' in data.attrib: self.num_registers = int (data.attrib['columns']) if 'time_stamp' in data.attrib: ts = long (data.attrib['time_stamp'], 0) if 'time_delta' in data.attrib: delta = long (data.attrib['time_delta'], 0) if 'epoch' in data.attrib: self.epoch = int (data.attrib['epoch'], 0) if ts == None: raise error, ('<data> element is missing time_stamp attribute') if delta == None: raise error, ('<data> element is missing time_delta attribute') for el in data: if el.tag == 'r': row = [] for c in el: row.append (long (c.text)) self.ts.append (ts) self.row.append (row) ts -= delta elif el.tag == 'cname': t = "P" if 't' in el.attrib: t = el.attrib['t'] self.regname.append (el.text) self.regtype.append (t) return def __str__ (self): ret = "" ret += "serial # = %d, " % self.config_serial_number ret += "names = %s, " % self.regname ret += "types = %s, rows=[" % self.regtype for i in range (len (self.ts)): if i > 0: ret += ", " ret += "0x%08x, " % self.ts[i] ret += "%s" % self.row[i] ret += "]" return ret<|fim▁end|>